prefix
stringlengths
82
32.6k
middle
stringlengths
5
470
suffix
stringlengths
0
81.2k
file_path
stringlengths
6
168
repo_name
stringlengths
16
77
context
listlengths
5
5
lang
stringclasses
4 values
ground_truth
stringlengths
5
470
import debug from "debug"; import EventEmitter from "eventemitter3"; import { NDKCacheAdapter } from "./cache/index.js"; import dedupEvent from "./events/dedup.js"; import NDKEvent from "./events/index.js"; import type { NDKRelay } from "./relay/index.js"; import { NDKPool } from "./relay/pool/index.js"; import { calculateRelaySetFromEvent } from "./relay/sets/calculate.js"; import { NDKRelaySet } from "./relay/sets/index.js"; import { correctRelaySet } from "./relay/sets/utils.js"; import type { NDKSigner } from "./signers/index.js"; import { NDKFilter, NDKSubscription, NDKSubscriptionOptions, filterFromId, relaysFromBech32, } from "./subscription/index.js"; import NDKUser, { NDKUserParams } from "./user/index.js"; import { NDKUserProfile } from "./user/profile.js"; export { NDKEvent, NDKUser, NDKFilter, NDKUserProfile, NDKCacheAdapter }; export * from "./events/index.js"; export * from "./events/kinds/index.js"; export * from "./events/kinds/article.js"; export * from "./events/kinds/dvm/index.js"; export * from "./events/kinds/lists/index.js"; export * from "./events/kinds/repost.js"; export * from "./relay/index.js"; export * from "./relay/sets/index.js"; export * from "./signers/index.js"; export * from "./signers/nip07/index.js"; export * from "./signers/nip46/backend/index.js"; export * from "./signers/nip46/rpc.js"; export * from "./signers/nip46/index.js"; export * from "./signers/private-key/index.js"; export * from "./subscription/index.js"; export * from "./user/profile.js"; export { NDKZapInvoice, zapInvoiceFromEvent } from "./zap/invoice.js"; export interface NDKConstructorParams { explicitRelayUrls?: string[]; devWriteRelayUrls?: string[]; signer?: NDKSigner; cacheAdapter?: NDKCacheAdapter; debug?: debug.Debugger; } export interface GetUserParams extends NDKUserParams { npub?: string; hexpubkey?: string; } export default class NDK extends EventEmitter { public pool: NDKPool; public signer?: NDKSigner; public cacheAdapter?: NDKCacheAdapter; public debug: debug.Debugger; public devWriteRelaySet?: NDKRelaySet; public delayedSubscriptions: Map<string, NDKSubscription[]>; public constructor(opts: NDKConstructorParams = {}) { super(); this.debug = opts.debug || debug("ndk"); this.pool = new NDKPool(opts.explicitRelayUrls || [], this); this.signer = opts.signer; this.cacheAdapter = opts.cacheAdapter; this.delayedSubscriptions = new Map(); if (opts.devWriteRelayUrls) { this.devWriteRelaySet = NDKRelaySet.fromRelayUrls( opts.devWriteRelayUrls, this ); } } public toJSON(): string { return { relayCount: this.pool.relays.size }.toString(); } /** * Connect to relays with optional timeout. * If the timeout is reached, the connection will be continued to be established in the background. */ public async connect(timeoutMs?: number): Promise<void> { this.debug("Connecting to relays", { timeoutMs }); return this.pool.connect(timeoutMs); } /** * Get a NDKUser object * * @param opts * @returns */ public getUser(opts: GetUserParams): NDKUser { const user = new NDKUser(opts); user.ndk = this; return user; } /** * Create a new subscription. Subscriptions automatically start and finish when all relays * on the set send back an EOSE. (set `opts.closeOnEose` to `false` in order avoid this) * * @param filters * @param opts * @param relaySet explicit relay set to use * @param autoStart automatically start the subscription * @returns NDKSubscription */ public subscribe( filters: NDKFilter | NDKFilter[], opts?: NDKSubscriptionOptions, relaySet?: NDKRelaySet, autoStart = true ): NDKSubscription { const subscription = new NDKSubscription(this, filters, opts, relaySet); // Signal to the relays that they are explicitly being used if (relaySet) { for (const relay of relaySet.relays) { this.pool.useTemporaryRelay(relay); } } if (autoStart) subscription.start(); return subscription; } /** * Publish an event to a relay * @param event event to publish * @param relaySet explicit relay set to use * @param timeoutMs timeout in milliseconds to wait for the event to be published * @returns The relays the event was published to * * @deprecated Use `event.publish()` instead */ public async publish( event: NDKEvent, relaySet?: NDKRelaySet, timeoutMs?: number ): Promise<Set<NDKRelay>> { this.debug("Deprecated: Use `event.publish()` instead"); if (!relaySet) { // If we have a devWriteRelaySet, use it to publish all events relaySet = this.devWriteRelaySet || calculateRelaySetFromEvent(this, event); } return relaySet.publish(event, timeoutMs); } /** * Fetch a single event. * * @param idOrFilter event id in bech32 format or filter * @param opts subscription options * @param relaySet explicit relay set to use */ public async fetchEvent( idOrFilter: string | NDKFilter, opts?: NDKSubscriptionOptions, relaySet?: NDKRelaySet ): Promise<NDKEvent | null> { let filter: NDKFilter; // if no relayset has been provided, try to get one from the event id if (!relaySet && typeof idOrFilter === "string") { const relays = relaysFromBech32(idOrFilter); if (relays.length > 0) { relaySet = new NDKRelaySet(new Set<NDKRelay>(relays), this); // Make sure we have connected relays in this set relaySet = correctRelaySet(relaySet, this.pool); } } if (typeof idOrFilter === "string") { filter = filterFromId(idOrFilter); } else { filter = idOrFilter; } if (!filter) { throw new Error(`Invalid filter: ${JSON.stringify(idOrFilter)}`); } return new Promise((resolve) => { const s = this.subscribe( filter, { ...(opts || {}), closeOnEose: true }, relaySet, false ); s.on("event", (event) => { event.ndk = this; resolve(event); }); s.on("eose", () => { resolve(null); }); s.start(); }); } /** * Fetch events */ public async fetchEvents( filters: NDKFilter | NDKFilter[], opts?: NDKSubscriptionOptions, relaySet?: NDKRelaySet ): Promise<Set<NDKEvent>> { return new Promise((resolve) => { const events: Map<string, NDKEvent> = new Map(); const relaySetSubscription = this.subscribe( filters, { ...(opts || {}), closeOnEose: true }, relaySet, false ); const onEvent = (event: NDKEvent) => { const dedupKey = event.deduplicationKey(); const existingEvent = events.get(dedupKey); if (existingEvent) {
event = dedupEvent(existingEvent, event);
} event.ndk = this; events.set(dedupKey, event); }; // We want to inspect duplicated events // so we can dedup them relaySetSubscription.on("event", onEvent); relaySetSubscription.on("event:dup", onEvent); relaySetSubscription.on("eose", () => { resolve(new Set(events.values())); }); relaySetSubscription.start(); }); } /** * Ensures that a signer is available to sign an event. */ public async assertSigner() { if (!this.signer) { this.emit("signerRequired"); throw new Error("Signer required"); } } }
src/index.ts
nostr-dev-kit-ndk-ece64e1
[ { "filename": "src/subscription/index.ts", "retrieved_chunk": " event: NDKEvent,\n relay: NDKRelay | undefined,\n fromCache = false\n ) {\n if (relay) event.relay = relay;\n if (!relay) relay = event.relay;\n if (!fromCache && relay) {\n // track the event per relay\n let events = this.eventsPerRelay.get(relay);\n if (!events) {", "score": 0.8789246082305908 }, { "filename": "src/subscription/index.ts", "retrieved_chunk": " this.emit(\"event\", event, relay, this);\n }\n // EOSE handling\n private eoseTimeout: ReturnType<typeof setTimeout> | undefined;\n public eoseReceived(relay: NDKRelay): void {\n if (this.opts?.closeOnEose) {\n this.relaySubscriptions.get(relay)?.unsub();\n this.relaySubscriptions.delete(relay);\n // if this was the last relay that needed to EOSE, emit that this subscription is closed\n if (this.relaySubscriptions.size === 0) {", "score": 0.8705860376358032 }, { "filename": "src/subscription/index.ts", "retrieved_chunk": " for (const subscription of this.subscriptions) {\n if (!this.isEventForSubscription(event, subscription)) {\n continue;\n }\n subscription.emit(\"event\", event, relay, subscription);\n }\n }\n private forwardEventDup(\n event: NDKEvent,\n relay: NDKRelay,", "score": 0.8687666058540344 }, { "filename": "src/user/index.test.ts", "retrieved_chunk": " }),\n });\n ndk.subscribe = jest.fn((filter, opts?): NDKSubscription => {\n const sub = new NDKSubscription(ndk, filter, opts);\n setTimeout(() => {\n sub.emit(\"event\", newEvent);\n sub.emit(\"event\", oldEvent);\n sub.emit(\"eose\");\n }, 100);\n return sub;", "score": 0.8672059774398804 }, { "filename": "src/user/index.ts", "retrieved_chunk": " closeOnEose: true,\n groupable: false,\n }\n );\n opts = {\n cacheUsage: NDKSubscriptionCacheUsage.ONLY_RELAY,\n closeOnEose: true,\n };\n }\n if (!setMetadataEvents || setMetadataEvents.size === 0) {", "score": 0.864457368850708 } ]
typescript
event = dedupEvent(existingEvent, event);
import debug from "debug"; import EventEmitter from "eventemitter3"; import { NDKCacheAdapter } from "./cache/index.js"; import dedupEvent from "./events/dedup.js"; import NDKEvent from "./events/index.js"; import type { NDKRelay } from "./relay/index.js"; import { NDKPool } from "./relay/pool/index.js"; import { calculateRelaySetFromEvent } from "./relay/sets/calculate.js"; import { NDKRelaySet } from "./relay/sets/index.js"; import { correctRelaySet } from "./relay/sets/utils.js"; import type { NDKSigner } from "./signers/index.js"; import { NDKFilter, NDKSubscription, NDKSubscriptionOptions, filterFromId, relaysFromBech32, } from "./subscription/index.js"; import NDKUser, { NDKUserParams } from "./user/index.js"; import { NDKUserProfile } from "./user/profile.js"; export { NDKEvent, NDKUser, NDKFilter, NDKUserProfile, NDKCacheAdapter }; export * from "./events/index.js"; export * from "./events/kinds/index.js"; export * from "./events/kinds/article.js"; export * from "./events/kinds/dvm/index.js"; export * from "./events/kinds/lists/index.js"; export * from "./events/kinds/repost.js"; export * from "./relay/index.js"; export * from "./relay/sets/index.js"; export * from "./signers/index.js"; export * from "./signers/nip07/index.js"; export * from "./signers/nip46/backend/index.js"; export * from "./signers/nip46/rpc.js"; export * from "./signers/nip46/index.js"; export * from "./signers/private-key/index.js"; export * from "./subscription/index.js"; export * from "./user/profile.js"; export { NDKZapInvoice, zapInvoiceFromEvent } from "./zap/invoice.js"; export interface NDKConstructorParams { explicitRelayUrls?: string[]; devWriteRelayUrls?: string[]; signer?: NDKSigner; cacheAdapter?: NDKCacheAdapter; debug?: debug.Debugger; } export interface GetUserParams extends NDKUserParams { npub?: string; hexpubkey?: string; } export default class NDK extends EventEmitter { public pool: NDKPool; public signer?: NDKSigner; public cacheAdapter?: NDKCacheAdapter; public debug: debug.Debugger; public devWriteRelaySet?: NDKRelaySet; public delayedSubscriptions: Map<string, NDKSubscription[]>; public constructor(opts: NDKConstructorParams = {}) { super(); this.debug = opts.debug || debug("ndk"); this.pool = new NDKPool(opts.explicitRelayUrls || [], this); this.signer = opts.signer; this.cacheAdapter = opts.cacheAdapter; this.delayedSubscriptions = new Map(); if (opts.devWriteRelayUrls) { this.devWriteRelaySet = NDKRelaySet.fromRelayUrls( opts.devWriteRelayUrls, this ); } } public toJSON(): string { return { relayCount: this.pool.relays.size }.toString(); } /** * Connect to relays with optional timeout. * If the timeout is reached, the connection will be continued to be established in the background. */ public async connect(timeoutMs?: number): Promise<void> { this.debug("Connecting to relays", { timeoutMs }); return this.pool.connect(timeoutMs); } /** * Get a NDKUser object * * @param opts * @returns */ public getUser(opts: GetUserParams): NDKUser { const user = new NDKUser(opts); user.ndk = this; return user; } /** * Create a new subscription. Subscriptions automatically start and finish when all relays * on the set send back an EOSE. (set `opts.closeOnEose` to `false` in order avoid this) * * @param filters * @param opts * @param relaySet explicit relay set to use * @param autoStart automatically start the subscription * @returns NDKSubscription */ public subscribe( filters: NDKFilter | NDKFilter[], opts?: NDKSubscriptionOptions, relaySet?: NDKRelaySet, autoStart = true ): NDKSubscription { const subscription = new NDKSubscription(this, filters, opts, relaySet); // Signal to the relays that they are explicitly being used if (relaySet) { for (const relay of relaySet.relays) { this.pool.useTemporaryRelay(relay); } } if (autoStart) subscription.start(); return subscription; } /** * Publish an event to a relay * @param event event to publish * @param relaySet explicit relay set to use * @param timeoutMs timeout in milliseconds to wait for the event to be published * @returns The relays the event was published to * * @deprecated Use `event.publish()` instead */ public async publish( event: NDKEvent, relaySet?: NDKRelaySet, timeoutMs?: number ): Promise<Set<NDKRelay>> { this.debug("Deprecated: Use `event.publish()` instead"); if (!relaySet) { // If we have a devWriteRelaySet, use it to publish all events relaySet = this.devWriteRelaySet || calculateRelaySetFromEvent(this, event); } return relaySet.publish(event, timeoutMs); } /** * Fetch a single event. * * @param idOrFilter event id in bech32 format or filter * @param opts subscription options * @param relaySet explicit relay set to use */ public async fetchEvent( idOrFilter: string | NDKFilter, opts?: NDKSubscriptionOptions, relaySet?: NDKRelaySet ): Promise<NDKEvent | null> { let filter: NDKFilter; // if no relayset has been provided, try to get one from the event id if (!relaySet && typeof idOrFilter === "string") { const relays = relaysFromBech32(idOrFilter); if (relays.length > 0) { relaySet = new NDKRelaySet(new Set<NDKRelay>(relays), this); // Make sure we have connected relays in this set
relaySet = correctRelaySet(relaySet, this.pool);
} } if (typeof idOrFilter === "string") { filter = filterFromId(idOrFilter); } else { filter = idOrFilter; } if (!filter) { throw new Error(`Invalid filter: ${JSON.stringify(idOrFilter)}`); } return new Promise((resolve) => { const s = this.subscribe( filter, { ...(opts || {}), closeOnEose: true }, relaySet, false ); s.on("event", (event) => { event.ndk = this; resolve(event); }); s.on("eose", () => { resolve(null); }); s.start(); }); } /** * Fetch events */ public async fetchEvents( filters: NDKFilter | NDKFilter[], opts?: NDKSubscriptionOptions, relaySet?: NDKRelaySet ): Promise<Set<NDKEvent>> { return new Promise((resolve) => { const events: Map<string, NDKEvent> = new Map(); const relaySetSubscription = this.subscribe( filters, { ...(opts || {}), closeOnEose: true }, relaySet, false ); const onEvent = (event: NDKEvent) => { const dedupKey = event.deduplicationKey(); const existingEvent = events.get(dedupKey); if (existingEvent) { event = dedupEvent(existingEvent, event); } event.ndk = this; events.set(dedupKey, event); }; // We want to inspect duplicated events // so we can dedup them relaySetSubscription.on("event", onEvent); relaySetSubscription.on("event:dup", onEvent); relaySetSubscription.on("eose", () => { resolve(new Set(events.values())); }); relaySetSubscription.start(); }); } /** * Ensures that a signer is available to sign an event. */ public async assertSigner() { if (!this.signer) { this.emit("signerRequired"); throw new Error("Signer required"); } } }
src/index.ts
nostr-dev-kit-ndk-ece64e1
[ { "filename": "src/relay/sets/calculate.ts", "retrieved_chunk": " * @param event {Event}\n * @returns Promise<NDKRelaySet>\n */\nexport function calculateRelaySetFromEvent(\n ndk: NDK,\n event: Event\n): NDKRelaySet {\n const relays: Set<NDKRelay> = new Set();\n ndk.pool?.relays.forEach((relay) => relays.add(relay));\n return new NDKRelaySet(relays, ndk);", "score": 0.8704754710197449 }, { "filename": "src/relay/sets/calculate.ts", "retrieved_chunk": "): NDKRelaySet {\n const relays: Set<NDKRelay> = new Set();\n ndk.pool?.relays.forEach((relay) => {\n if (!relay.complaining) {\n relays.add(relay);\n } else {\n ndk.debug(`Relay ${relay.url} is complaining, not adding to set`);\n }\n });\n return new NDKRelaySet(relays, ndk);", "score": 0.8591210842132568 }, { "filename": "src/user/index.ts", "retrieved_chunk": " if (!this.ndk) throw new Error(\"NDK not set\");\n const relayListEvents = await this.ndk.fetchEvents({\n kinds: [10002],\n authors: [this.hexpubkey()],\n });\n if (relayListEvents) {\n return relayListEvents;\n }\n return new Set<NDKEvent>();\n }", "score": 0.8574327230453491 }, { "filename": "src/subscription/index.ts", "retrieved_chunk": " event: NDKEvent,\n relay: NDKRelay | undefined,\n fromCache = false\n ) {\n if (relay) event.relay = relay;\n if (!relay) relay = event.relay;\n if (!fromCache && relay) {\n // track the event per relay\n let events = this.eventsPerRelay.get(relay);\n if (!events) {", "score": 0.8526729345321655 }, { "filename": "src/events/index.ts", "retrieved_chunk": " * The relay that this event was first received from.\n */\n public relay: NDKRelay | undefined;\n constructor(ndk?: NDK, event?: NostrEvent) {\n super();\n this.ndk = ndk;\n this.created_at = event?.created_at;\n this.content = event?.content || \"\";\n this.tags = event?.tags || [];\n this.id = event?.id || \"\";", "score": 0.8495131731033325 } ]
typescript
relaySet = correctRelaySet(relaySet, this.pool);
import debug from "debug"; import EventEmitter from "eventemitter3"; import { Relay, relayInit, Sub } from "nostr-tools"; import "websocket-polyfill"; import NDKEvent, { NDKTag, NostrEvent } from "../events/index.js"; import { NDKSubscription } from "../subscription/index.js"; import User from "../user/index.js"; import { NDKRelayScore } from "./score.js"; export enum NDKRelayStatus { CONNECTING, CONNECTED, DISCONNECTING, DISCONNECTED, RECONNECTING, FLAPPING, } export interface NDKRelayConnectionStats { /** * The number of times a connection has been attempted. */ attempts: number; /** * The number of times a connection has been successfully established. */ success: number; /** * The durations of the last 100 connections in milliseconds. */ durations: number[]; /** * The time the current connection was established in milliseconds. */ connectedAt?: number; } /** * The NDKRelay class represents a connection to a relay. * * @emits NDKRelay#connect * @emits NDKRelay#disconnect * @emits NDKRelay#notice * @emits NDKRelay#event * @emits NDKRelay#published when an event is published to the relay * @emits NDKRelay#publish:failed when an event fails to publish to the relay * @emits NDKRelay#eose */ export class NDKRelay extends EventEmitter { readonly url: string; readonly scores: Map<User, NDKRelayScore>; private relay: Relay; private _status: NDKRelayStatus; private connectedAt?: number; private _connectionStats: NDKRelayConnectionStats = { attempts: 0, success: 0, durations: [], }; public complaining = false; private debug: debug.Debugger; /** * Active subscriptions this relay is connected to */ public activeSubscriptions = new Set<NDKSubscription>(); public constructor(url: string) { super(); this.url = url; this.relay = relayInit(url); this.scores = new Map<User, NDKRelayScore>(); this._status = NDKRelayStatus.DISCONNECTED; this.debug = debug(`ndk:relay:${url}`); this.relay.on("connect", () => { this.updateConnectionStats.connected(); this._status = NDKRelayStatus.CONNECTED; this.emit("connect"); }); this.relay.on("disconnect", () => { this.updateConnectionStats.disconnected(); if (this._status === NDKRelayStatus.CONNECTED) { this._status = NDKRelayStatus.DISCONNECTED; this.handleReconnection(); } this.emit("disconnect"); }); this.relay.on("notice", (notice: string) => this.handleNotice(notice)); } /** * Evaluates the connection stats to determine if the relay is flapping. */ private isFlapping(): boolean { const durations = this._connectionStats.durations; if (durations.length < 10) return false; const sum = durations.reduce((a, b) => a + b, 0); const avg = sum / durations.length; const variance = durations .map((x) => Math.pow(x - avg, 2)) .reduce((a, b) => a + b, 0) / durations.length; const stdDev = Math.sqrt(variance); const isFlapping = stdDev < 1000; return isFlapping; } /** * Called when the relay is unexpectedly disconnected. */ private handleReconnection() { if (this.isFlapping()) { this.emit("flapping", this, this._connectionStats); this._status = NDKRelayStatus.FLAPPING; } if (this.connectedAt && Date.now() - this.connectedAt < 5000) { setTimeout(() => this.connect(), 60000); } else { this.connect(); } } get status(): NDKRelayStatus { return this._status; } /** * Connects to the relay. */ public async connect(): Promise<void> { try { this.updateConnectionStats.attempt(); this._status = NDKRelayStatus.CONNECTING; await this.relay.connect(); } catch (e) { this.debug("Failed to connect", e); this._status = NDKRelayStatus.DISCONNECTED; throw e; } } /** * Disconnects from the relay. */ public disconnect(): void { this._status = NDKRelayStatus.DISCONNECTING; this.relay.close(); } async handleNotice(notice: string) { // This is a prototype; if the relay seems to be complaining // remove it from relay set selection for a minute. if (notice.includes("oo many") || notice.includes("aximum")) { this.disconnect(); // fixme setTimeout(() => this.connect(), 2000); this.debug(this.relay.url, "Relay complaining?", notice); // this.complaining = true; // setTimeout(() => { // this.complaining = false; // console.log(this.relay.url, 'Reactivate relay'); // }, 60000); } this.emit("notice", this, notice); } /** * Subscribes to a subscription. */ public subscribe(subscription: NDKSubscription): Sub { const { filters } = subscription; const sub = this.relay.sub(filters, { id: subscription.subId, }); this.debug(`Subscribed to ${JSON.stringify(filters)}`); sub.on("event", (event: NostrEvent) => { const e = new NDKEvent(undefined, event); e.relay = this; subscription.eventReceived(e, this); }); sub.on("eose", () => { subscription.eoseReceived(this); }); const unsub = sub.unsub; sub.unsub = () => { this.debug(`Unsubscribing from ${JSON.stringify(filters)}`); this.activeSubscriptions.delete(subscription); unsub(); }; this.activeSubscriptions.add(subscription); subscription.on("close", () => { this.activeSubscriptions.delete(subscription); }); return sub; } /** * Publishes an event to the relay with an optional timeout. * * If the relay is not connected, the event will be published when the relay connects, * unless the timeout is reached before the relay connects. * * @param event The event to publish * @param timeoutMs The timeout for the publish operation in milliseconds * @returns A promise that resolves when the event has been published or rejects if the operation times out */
public async publish(event: NDKEvent, timeoutMs = 2500): Promise<boolean> {
if (this.status === NDKRelayStatus.CONNECTED) { return this.publishEvent(event, timeoutMs); } else { this.once("connect", () => { this.publishEvent(event, timeoutMs); }); return true; } } private async publishEvent( event: NDKEvent, timeoutMs?: number ): Promise<boolean> { const nostrEvent = await event.toNostrEvent(); const publish = this.relay.publish(nostrEvent as any); let publishTimeout: NodeJS.Timeout | number; const publishPromise = new Promise<boolean>((resolve, reject) => { publish .then(() => { clearTimeout(publishTimeout as unknown as NodeJS.Timeout); this.emit("published", event); resolve(true); }) .catch((err) => { clearTimeout(publishTimeout as NodeJS.Timeout); this.debug("Publish failed", err, event.id); this.emit("publish:failed", event, err); reject(err); }); }); // If no timeout is specified, just return the publish promise if (!timeoutMs) { return publishPromise; } // Create a promise that rejects after timeoutMs milliseconds const timeoutPromise = new Promise<boolean>((_, reject) => { publishTimeout = setTimeout(() => { this.debug("Publish timed out", event.rawEvent()); this.emit("publish:failed", event, "Timeout"); reject(new Error("Publish operation timed out")); }, timeoutMs); }); // wait for either the publish operation to complete or the timeout to occur return Promise.race([publishPromise, timeoutPromise]); } /** * Called when this relay has responded with an event but * wasn't the fastest one. * @param timeDiffInMs The time difference in ms between the fastest and this relay in milliseconds */ // eslint-disable-next-line @typescript-eslint/no-unused-vars public scoreSlowerEvent(timeDiffInMs: number): void { // TODO } /** * Utility functions to update the connection stats. */ private updateConnectionStats = { connected: () => { this._connectionStats.success++; this._connectionStats.connectedAt = Date.now(); }, disconnected: () => { if (this._connectionStats.connectedAt) { this._connectionStats.durations.push( Date.now() - this._connectionStats.connectedAt ); if (this._connectionStats.durations.length > 100) { this._connectionStats.durations.shift(); } } this._connectionStats.connectedAt = undefined; }, attempt: () => { this._connectionStats.attempts++; }, }; /** * Returns the connection stats. */ get connectionStats(): NDKRelayConnectionStats { return this._connectionStats; } public tagReference(marker?: string): NDKTag { const tag = ["r", this.relay.url]; if (marker) { tag.push(marker); } return tag; } }
src/relay/index.ts
nostr-dev-kit-ndk-ece64e1
[ { "filename": "src/index.ts", "retrieved_chunk": " * @param event event to publish\n * @param relaySet explicit relay set to use\n * @param timeoutMs timeout in milliseconds to wait for the event to be published\n * @returns The relays the event was published to\n *\n * @deprecated Use `event.publish()` instead\n */\n public async publish(\n event: NDKEvent,\n relaySet?: NDKRelaySet,", "score": 0.8942681550979614 }, { "filename": "src/relay/sets/index.ts", "retrieved_chunk": " public async publish(\n event: NDKEvent,\n timeoutMs?: number\n ): Promise<Set<NDKRelay>> {\n const publishedToRelays: Set<NDKRelay> = new Set();\n // go through each relay and publish the event\n const promises: Promise<void>[] = Array.from(this.relays).map(\n (relay: NDKRelay) => {\n return new Promise<void>((resolve) => {\n relay", "score": 0.8889706134796143 }, { "filename": "src/index.ts", "retrieved_chunk": " timeoutMs?: number\n ): Promise<Set<NDKRelay>> {\n this.debug(\"Deprecated: Use `event.publish()` instead\");\n if (!relaySet) {\n // If we have a devWriteRelaySet, use it to publish all events\n relaySet =\n this.devWriteRelaySet ||\n calculateRelaySetFromEvent(this, event);\n }\n return relaySet.publish(event, timeoutMs);", "score": 0.8869776725769043 }, { "filename": "src/events/index.ts", "retrieved_chunk": " * @param relaySet {NDKRelaySet} The relaySet to publish the even to.\n * @returns A promise that resolves to the relays the event was published to.\n */\n public async publish(\n relaySet?: NDKRelaySet,\n timeoutMs?: number\n ): Promise<Set<NDKRelay>> {\n if (!this.sig) await this.sign();\n if (!this.ndk)\n throw new Error(", "score": 0.8712061047554016 }, { "filename": "src/relay/sets/index.ts", "retrieved_chunk": " .publish(event, timeoutMs)\n .then(() => {\n publishedToRelays.add(relay);\n resolve();\n })\n .catch((err) => {\n this.debug(\"error publishing to relay\", {\n relay: relay.url,\n err,\n });", "score": 0.8558652400970459 } ]
typescript
public async publish(event: NDKEvent, timeoutMs = 2500): Promise<boolean> {
#!/usr/bin/env node import { blue, bold, cyan, dim, red, yellow } from 'kolorist'; import cac from 'cac'; import { version } from '../package.json'; import { generate } from './generate'; import { hasTagOnGitHub, sendRelease } from './github'; import { isRepoShallow } from './git'; import type { ChangelogOptions } from './types'; const cli = cac('githublogen'); cli .version(version) .option('-t, --token <path>', 'GitHub Token') .option('--from <ref>', 'From tag') .option('--to <ref>', 'To tag') .option('--github <path>', 'GitHub Repository, e.g. soybeanjs/githublogen') .option('--name <name>', 'Name of the release') .option('--contributors', 'Show contributors section') .option('--prerelease', 'Mark release as prerelease') .option('-d, --draft', 'Mark release as draft') .option('--output <path>', 'Output to file instead of sending to GitHub') .option('--capitalize', 'Should capitalize for each comment message') .option('--emoji', 'Use emojis in section titles', { default: true }) .option('--group', 'Nest commit messages under their scopes') .option('--dry', 'Dry run') .help(); cli.command('').action(async (args: any) => { try { console.log(); console.log(dim(`${bold('github')}logen `) + dim(`v${version}`)); const cwd = process.cwd(); const { config, md, commits } = await generate(cwd, args as unknown as ChangelogOptions); const markdown = md.replace(/&nbsp;/g, ''); console.log(cyan(config.from) + dim(' -> ') + blue(config.to) + dim(` (${commits.length} commits)`)); console.log(dim('--------------')); console.log(); console.log(markdown); console.log(); console.log(dim('--------------')); if (config.dry) { console.log(yellow('Dry run. Release skipped.')); return; } if (!(await hasTagOnGitHub(config.to, config))) { console.error(yellow(`Current ref "${bold(config.to)}" is not available as tags on GitHub. Release skipped.`)); process.exitCode = 1; return; } if (!commits.length && (await isRepoShallow())) { console.error( yellow( 'The repo seems to be clone shallowly, which make changelog failed to generate. You might want to specify `fetch-depth: 0` in your CI config.' ) ); process.exitCode = 1; return; } await
sendRelease(config, md);
} catch (e: any) { console.error(red(String(e))); if (e?.stack) { console.error(dim(e.stack?.split('\n').slice(1).join('\n'))); } process.exit(1); } }); cli.parse();
src/cli.ts
soybeanjs-githublogen-0932953
[ { "filename": "src/github.ts", "retrieved_chunk": "import { $fetch } from 'ohmyfetch';\nimport { cyan, green, red, yellow } from 'kolorist';\nimport { notNullish } from './shared';\nimport type { AuthorInfo, ChangelogOptions, Commit } from './types';\nexport async function sendRelease(options: ChangelogOptions, content: string) {\n const headers = getHeaders(options);\n const github = options.repo.repo!;\n let url = `https://api.github.com/repos/${github}/releases`;\n let method = 'POST';\n try {", "score": 0.8495469093322754 }, { "filename": "src/github.ts", "retrieved_chunk": " try {\n console.log(cyan(method === 'POST' ? 'Creating release notes...' : 'Updating release notes...'));\n const res = await $fetch(url, {\n method,\n body: JSON.stringify(body),\n headers\n });\n console.log(green(`Released on ${res.html_url}`));\n } catch (e) {\n console.log();", "score": 0.8467612266540527 }, { "filename": "src/generate.ts", "retrieved_chunk": "import { getGitDiff } from './git';\nimport { generateMarkdown } from './markdown';\nimport { resolveAuthors } from './github';\nimport { resolveConfig } from './config';\nimport { parseCommits } from './parse';\nimport type { ChangelogOptions } from './types';\nexport async function generate(cwd: string, options: ChangelogOptions) {\n const resolved = await resolveConfig(cwd, options);\n const rawCommits = await getGitDiff(resolved.from, resolved.to);\n const commits = parseCommits(rawCommits, resolved);", "score": 0.8285314440727234 }, { "filename": "src/generate.ts", "retrieved_chunk": " if (resolved.contributors) {\n await resolveAuthors(commits, resolved);\n }\n const md = generateMarkdown(commits, resolved);\n return { config: resolved, md, commits };\n}", "score": 0.8238433003425598 }, { "filename": "src/github.ts", "retrieved_chunk": " console.error(red('Failed to create the release. Using the following link to create it manually:'));\n console.error(yellow(webUrl));\n console.log();\n throw e;\n }\n}\nfunction getHeaders(options: ChangelogOptions) {\n return {\n accept: 'application/vnd.github.v3+json',\n authorization: `token ${options.tokens.github}`", "score": 0.8213365077972412 } ]
typescript
sendRelease(config, md);
#!/usr/bin/env node import { blue, bold, cyan, dim, red, yellow } from 'kolorist'; import cac from 'cac'; import { version } from '../package.json'; import { generate } from './generate'; import { hasTagOnGitHub, sendRelease } from './github'; import { isRepoShallow } from './git'; import type { ChangelogOptions } from './types'; const cli = cac('githublogen'); cli .version(version) .option('-t, --token <path>', 'GitHub Token') .option('--from <ref>', 'From tag') .option('--to <ref>', 'To tag') .option('--github <path>', 'GitHub Repository, e.g. soybeanjs/githublogen') .option('--name <name>', 'Name of the release') .option('--contributors', 'Show contributors section') .option('--prerelease', 'Mark release as prerelease') .option('-d, --draft', 'Mark release as draft') .option('--output <path>', 'Output to file instead of sending to GitHub') .option('--capitalize', 'Should capitalize for each comment message') .option('--emoji', 'Use emojis in section titles', { default: true }) .option('--group', 'Nest commit messages under their scopes') .option('--dry', 'Dry run') .help(); cli.command('').action(async (args: any) => { try { console.log(); console.log(dim(`${bold('github')}logen `) + dim(`v${version}`)); const cwd = process.cwd(); const { config, md, commits } = await generate(cwd, args as unknown as ChangelogOptions); const markdown = md.replace(/&nbsp;/g, ''); console.log(cyan(config.from) + dim(' -> ') + blue(config.to) + dim(` (${commits.length} commits)`)); console.log(dim('--------------')); console.log(); console.log(markdown); console.log(); console.log(dim('--------------')); if (config.dry) { console.log(yellow('Dry run. Release skipped.')); return; } if (!(await
hasTagOnGitHub(config.to, config))) {
console.error(yellow(`Current ref "${bold(config.to)}" is not available as tags on GitHub. Release skipped.`)); process.exitCode = 1; return; } if (!commits.length && (await isRepoShallow())) { console.error( yellow( 'The repo seems to be clone shallowly, which make changelog failed to generate. You might want to specify `fetch-depth: 0` in your CI config.' ) ); process.exitCode = 1; return; } await sendRelease(config, md); } catch (e: any) { console.error(red(String(e))); if (e?.stack) { console.error(dim(e.stack?.split('\n').slice(1).join('\n'))); } process.exit(1); } }); cli.parse();
src/cli.ts
soybeanjs-githublogen-0932953
[ { "filename": "src/github.ts", "retrieved_chunk": " try {\n console.log(cyan(method === 'POST' ? 'Creating release notes...' : 'Updating release notes...'));\n const res = await $fetch(url, {\n method,\n body: JSON.stringify(body),\n headers\n });\n console.log(green(`Released on ${res.html_url}`));\n } catch (e) {\n console.log();", "score": 0.8411981463432312 }, { "filename": "src/github.ts", "retrieved_chunk": "import { $fetch } from 'ohmyfetch';\nimport { cyan, green, red, yellow } from 'kolorist';\nimport { notNullish } from './shared';\nimport type { AuthorInfo, ChangelogOptions, Commit } from './types';\nexport async function sendRelease(options: ChangelogOptions, content: string) {\n const headers = getHeaders(options);\n const github = options.repo.repo!;\n let url = `https://api.github.com/repos/${github}/releases`;\n let method = 'POST';\n try {", "score": 0.8159428834915161 }, { "filename": "src/github.ts", "retrieved_chunk": " draft: options.draft || false,\n name: options.name || options.to,\n prerelease: options.prerelease,\n tag_name: options.to\n };\n const webUrl = `https://github.com/${github}/releases/new?title=${encodeURIComponent(\n String(body.name)\n )}&body=${encodeURIComponent(String(body.body))}&tag=${encodeURIComponent(String(options.to))}&prerelease=${\n options.prerelease\n }`;", "score": 0.8102402687072754 }, { "filename": "src/github.ts", "retrieved_chunk": " const exists = await $fetch(`https://api.github.com/repos/${github}/releases/tags/${options.to}`, {\n headers\n });\n if (exists.url) {\n url = exists.url;\n method = 'PATCH';\n }\n } catch (e) {}\n const body = {\n body: content,", "score": 0.8077231645584106 }, { "filename": "src/github.ts", "retrieved_chunk": " console.error(red('Failed to create the release. Using the following link to create it manually:'));\n console.error(yellow(webUrl));\n console.log();\n throw e;\n }\n}\nfunction getHeaders(options: ChangelogOptions) {\n return {\n accept: 'application/vnd.github.v3+json',\n authorization: `token ${options.tokens.github}`", "score": 0.80706787109375 } ]
typescript
hasTagOnGitHub(config.to, config))) {
import debug from "debug"; import EventEmitter from "eventemitter3"; import { Relay, relayInit, Sub } from "nostr-tools"; import "websocket-polyfill"; import NDKEvent, { NDKTag, NostrEvent } from "../events/index.js"; import { NDKSubscription } from "../subscription/index.js"; import User from "../user/index.js"; import { NDKRelayScore } from "./score.js"; export enum NDKRelayStatus { CONNECTING, CONNECTED, DISCONNECTING, DISCONNECTED, RECONNECTING, FLAPPING, } export interface NDKRelayConnectionStats { /** * The number of times a connection has been attempted. */ attempts: number; /** * The number of times a connection has been successfully established. */ success: number; /** * The durations of the last 100 connections in milliseconds. */ durations: number[]; /** * The time the current connection was established in milliseconds. */ connectedAt?: number; } /** * The NDKRelay class represents a connection to a relay. * * @emits NDKRelay#connect * @emits NDKRelay#disconnect * @emits NDKRelay#notice * @emits NDKRelay#event * @emits NDKRelay#published when an event is published to the relay * @emits NDKRelay#publish:failed when an event fails to publish to the relay * @emits NDKRelay#eose */ export class NDKRelay extends EventEmitter { readonly url: string; readonly scores: Map<User, NDKRelayScore>; private relay: Relay; private _status: NDKRelayStatus; private connectedAt?: number; private _connectionStats: NDKRelayConnectionStats = { attempts: 0, success: 0, durations: [], }; public complaining = false; private debug: debug.Debugger; /** * Active subscriptions this relay is connected to */ public activeSubscriptions = new Set<NDKSubscription>(); public constructor(url: string) { super(); this.url = url; this.relay = relayInit(url); this.scores = new Map<User, NDKRelayScore>(); this._status = NDKRelayStatus.DISCONNECTED; this.debug = debug(`ndk:relay:${url}`); this.relay.on("connect", () => { this.updateConnectionStats.connected(); this._status = NDKRelayStatus.CONNECTED; this.emit("connect"); }); this.relay.on("disconnect", () => { this.updateConnectionStats.disconnected(); if (this._status === NDKRelayStatus.CONNECTED) { this._status = NDKRelayStatus.DISCONNECTED; this.handleReconnection(); } this.emit("disconnect"); }); this.relay.on("notice", (notice: string) => this.handleNotice(notice)); } /** * Evaluates the connection stats to determine if the relay is flapping. */ private isFlapping(): boolean { const durations = this._connectionStats.durations; if (durations.length < 10) return false; const sum = durations.reduce((a, b) => a + b, 0); const avg = sum / durations.length; const variance = durations .map((x) => Math.pow(x - avg, 2)) .reduce((a, b) => a + b, 0) / durations.length; const stdDev = Math.sqrt(variance); const isFlapping = stdDev < 1000; return isFlapping; } /** * Called when the relay is unexpectedly disconnected. */ private handleReconnection() { if (this.isFlapping()) { this.emit("flapping", this, this._connectionStats); this._status = NDKRelayStatus.FLAPPING; } if (this.connectedAt && Date.now() - this.connectedAt < 5000) { setTimeout(() => this.connect(), 60000); } else { this.connect(); } } get status(): NDKRelayStatus { return this._status; } /** * Connects to the relay. */ public async connect(): Promise<void> { try { this.updateConnectionStats.attempt(); this._status = NDKRelayStatus.CONNECTING; await this.relay.connect(); } catch (e) { this.debug("Failed to connect", e); this._status = NDKRelayStatus.DISCONNECTED; throw e; } } /** * Disconnects from the relay. */ public disconnect(): void { this._status = NDKRelayStatus.DISCONNECTING; this.relay.close(); } async handleNotice(notice: string) { // This is a prototype; if the relay seems to be complaining // remove it from relay set selection for a minute. if (notice.includes("oo many") || notice.includes("aximum")) { this.disconnect(); // fixme setTimeout(() => this.connect(), 2000); this.debug(this.relay.url, "Relay complaining?", notice); // this.complaining = true; // setTimeout(() => { // this.complaining = false; // console.log(this.relay.url, 'Reactivate relay'); // }, 60000); } this.emit("notice", this, notice); } /** * Subscribes to a subscription. */ public subscribe(subscription: NDKSubscription): Sub { const { filters } = subscription; const sub = this.relay.sub(filters, { id: subscription.subId, }); this.debug(`Subscribed to ${JSON.stringify(filters)}`); sub.on("event", (event: NostrEvent) => { const e = new NDKEvent(undefined, event); e.relay = this; subscription.eventReceived(e, this); }); sub.on("eose", () => { subscription.eoseReceived(this); }); const unsub = sub.unsub; sub.unsub = () => { this.debug(`Unsubscribing from ${JSON.stringify(filters)}`); this.activeSubscriptions.delete(subscription); unsub(); }; this.activeSubscriptions.add(subscription); subscription.on("close", () => { this.activeSubscriptions.delete(subscription); }); return sub; } /** * Publishes an event to the relay with an optional timeout. * * If the relay is not connected, the event will be published when the relay connects, * unless the timeout is reached before the relay connects. * * @param event The event to publish * @param timeoutMs The timeout for the publish operation in milliseconds * @returns A promise that resolves when the event has been published or rejects if the operation times out */ public async publish(event: NDKEvent, timeoutMs = 2500): Promise<boolean> { if (this.status === NDKRelayStatus.CONNECTED) { return this.publishEvent(event, timeoutMs); } else { this.once("connect", () => { this.publishEvent(event, timeoutMs); }); return true; } } private async publishEvent( event: NDKEvent, timeoutMs?: number ): Promise<boolean> { const nostrEvent = await event.toNostrEvent(); const publish = this.relay.publish(nostrEvent as any); let publishTimeout: NodeJS.Timeout | number; const publishPromise = new Promise<boolean>((resolve, reject) => { publish .then(() => { clearTimeout(publishTimeout as unknown as NodeJS.Timeout); this.emit("published", event); resolve(true); }) .catch((err) => { clearTimeout(publishTimeout as NodeJS.Timeout); this.debug("Publish failed", err, event.id); this.emit("publish:failed", event, err); reject(err); }); }); // If no timeout is specified, just return the publish promise if (!timeoutMs) { return publishPromise; } // Create a promise that rejects after timeoutMs milliseconds const timeoutPromise = new Promise<boolean>((_, reject) => { publishTimeout = setTimeout(() => { this.debug("Publish timed out", event.rawEvent()); this.emit("publish:failed", event, "Timeout"); reject(new Error("Publish operation timed out")); }, timeoutMs); }); // wait for either the publish operation to complete or the timeout to occur return Promise.race([publishPromise, timeoutPromise]); } /** * Called when this relay has responded with an event but * wasn't the fastest one. * @param timeDiffInMs The time difference in ms between the fastest and this relay in milliseconds */ // eslint-disable-next-line @typescript-eslint/no-unused-vars public scoreSlowerEvent(timeDiffInMs: number): void { // TODO } /** * Utility functions to update the connection stats. */ private updateConnectionStats = { connected: () => { this._connectionStats.success++; this._connectionStats.connectedAt = Date.now(); }, disconnected: () => { if (this._connectionStats.connectedAt) { this._connectionStats.durations.push( Date.now() - this._connectionStats.connectedAt ); if (this._connectionStats.durations.length > 100) { this._connectionStats.durations.shift(); } } this._connectionStats.connectedAt = undefined; }, attempt: () => { this._connectionStats.attempts++; }, }; /** * Returns the connection stats. */ get connectionStats(): NDKRelayConnectionStats { return this._connectionStats; } public tagReference
(marker?: string): NDKTag {
const tag = ["r", this.relay.url]; if (marker) { tag.push(marker); } return tag; } }
src/relay/index.ts
nostr-dev-kit-ndk-ece64e1
[ { "filename": "src/relay/pool/index.ts", "retrieved_chunk": "import debug from \"debug\";\nimport EventEmitter from \"eventemitter3\";\nimport NDK from \"../../index.js\";\nimport { NDKRelay, NDKRelayStatus } from \"../index.js\";\nexport type NDKPoolStats = {\n total: number;\n connected: number;\n disconnected: number;\n connecting: number;\n};", "score": 0.8479775190353394 }, { "filename": "src/relay/pool/index.ts", "retrieved_chunk": " total: 0,\n connected: 0,\n disconnected: 0,\n connecting: 0,\n };\n for (const relay of this.relays.values()) {\n stats.total++;\n if (relay.status === NDKRelayStatus.CONNECTED) {\n stats.connected++;\n } else if (relay.status === NDKRelayStatus.DISCONNECTED) {", "score": 0.842004656791687 }, { "filename": "src/relay/pool/index.ts", "retrieved_chunk": " }\n public size(): number {\n return this.relays.size;\n }\n /**\n * Returns the status of each relay in the pool.\n * @returns {NDKPoolStats} An object containing the number of relays in each status.\n */\n public stats(): NDKPoolStats {\n const stats: NDKPoolStats = {", "score": 0.8355406522750854 }, { "filename": "src/relay/pool/index.ts", "retrieved_chunk": " stats.disconnected++;\n } else if (relay.status === NDKRelayStatus.CONNECTING) {\n stats.connecting++;\n }\n }\n return stats;\n }\n public connectedRelays(): NDKRelay[] {\n return Array.from(this.relays.values()).filter(\n (relay) => relay.status === NDKRelayStatus.CONNECTED", "score": 0.828481912612915 }, { "filename": "src/events/index.ts", "retrieved_chunk": " * event = new NDKEvent(ndk, { kind: 30000, pubkey: 'pubkey', tags: [ [\"d\", \"d-code\"] ] });\n * event.tagReference(); // [\"a\", \"30000:pubkey:d-code\"]\n *\n * event = new NDKEvent(ndk, { kind: 1, pubkey: 'pubkey', id: \"eventid\" });\n * event.tagReference(); // [\"e\", \"eventid\"]\n * @returns {NDKTag} The NDKTag object referencing this event\n */\n tagReference(): NDKTag {\n // NIP-33\n if (this.isParamReplaceable()) {", "score": 0.8160786032676697 } ]
typescript
(marker?: string): NDKTag {
import { $fetch } from 'ohmyfetch'; import { cyan, green, red, yellow } from 'kolorist'; import { notNullish } from './shared'; import type { AuthorInfo, ChangelogOptions, Commit } from './types'; export async function sendRelease(options: ChangelogOptions, content: string) { const headers = getHeaders(options); const github = options.repo.repo!; let url = `https://api.github.com/repos/${github}/releases`; let method = 'POST'; try { const exists = await $fetch(`https://api.github.com/repos/${github}/releases/tags/${options.to}`, { headers }); if (exists.url) { url = exists.url; method = 'PATCH'; } } catch (e) {} const body = { body: content, draft: options.draft || false, name: options.name || options.to, prerelease: options.prerelease, tag_name: options.to }; const webUrl = `https://github.com/${github}/releases/new?title=${encodeURIComponent( String(body.name) )}&body=${encodeURIComponent(String(body.body))}&tag=${encodeURIComponent(String(options.to))}&prerelease=${ options.prerelease }`; try { console.log(cyan(method === 'POST' ? 'Creating release notes...' : 'Updating release notes...')); const res = await $fetch(url, { method, body: JSON.stringify(body), headers }); console.log(green(`Released on ${res.html_url}`)); } catch (e) { console.log(); console.error(red('Failed to create the release. Using the following link to create it manually:')); console.error(yellow(webUrl)); console.log(); throw e; } } function getHeaders(options: ChangelogOptions) { return { accept: 'application/vnd.github.v3+json', authorization: `token ${options.tokens.github}` }; } export async function resolveAuthorInfo(options: ChangelogOptions, info: AuthorInfo) { if (info.login) return info; // token not provided, skip github resolving if (!options.tokens.github) return info; try { const data = await $fetch(`https://api.github.com/search/users?q=${encodeURIComponent(info.email)}`, { headers: getHeaders(options) }); info.login = data.items[0].login; } catch {} if (info.login) return info; if (info.commits.length) { try { const data = await $fetch(`https://api.github.com/repos/${options.repo.repo}/commits/${info.commits[0]}`, { headers: getHeaders(options) }); info.login = data.author.login; } catch (e) {} } return info; }
export async function resolveAuthors(commits: Commit[], options: ChangelogOptions) {
const map = new Map<string, AuthorInfo>(); commits.forEach(commit => { commit.resolvedAuthors = commit.authors .map((a, idx) => { if (!a.email || !a.name) { return null; } if (!map.has(a.email)) { map.set(a.email, { commits: [], name: a.name, email: a.email }); } const info = map.get(a.email)!; // record commits only for the first author if (idx === 0) { info.commits.push(commit.shortHash); } return info; }) .filter(notNullish); }); const authors = Array.from(map.values()); const resolved = await Promise.all(authors.map(info => resolveAuthorInfo(options, info))); const loginSet = new Set<string>(); const nameSet = new Set<string>(); return resolved .sort((a, b) => (a.login || a.name).localeCompare(b.login || b.name)) .filter(i => { if (i.login && loginSet.has(i.login)) { return false; } if (i.login) { loginSet.add(i.login); } else { if (nameSet.has(i.name)) { return false; } nameSet.add(i.name); } return true; }); } export async function hasTagOnGitHub(tag: string, options: ChangelogOptions) { try { await $fetch(`https://api.github.com/repos/${options.repo.repo}/git/ref/tags/${tag}`, { headers: getHeaders(options) }); return true; } catch (e) { return false; } }
src/github.ts
soybeanjs-githublogen-0932953
[ { "filename": "src/generate.ts", "retrieved_chunk": " if (resolved.contributors) {\n await resolveAuthors(commits, resolved);\n }\n const md = generateMarkdown(commits, resolved);\n return { config: resolved, md, commits };\n}", "score": 0.8581615686416626 }, { "filename": "src/types.ts", "retrieved_chunk": "export interface Commit extends GitCommit {\n resolvedAuthors?: AuthorInfo[];\n}\nexport interface ChangelogOptions extends ChangelogConfig {\n /**\n * Dry run. Skip releasing to GitHub.\n */\n dry?: boolean;\n /**\n * Whether to include contributors in release notes.", "score": 0.8405910730361938 }, { "filename": "src/types.ts", "retrieved_chunk": " references: Reference[];\n authors: GitCommitAuthor[];\n isBreaking: boolean;\n}\nexport interface AuthorInfo {\n commits: string[];\n login?: string;\n email: string;\n name: string;\n}", "score": 0.8379142880439758 }, { "filename": "src/generate.ts", "retrieved_chunk": "import { getGitDiff } from './git';\nimport { generateMarkdown } from './markdown';\nimport { resolveAuthors } from './github';\nimport { resolveConfig } from './config';\nimport { parseCommits } from './parse';\nimport type { ChangelogOptions } from './types';\nexport async function generate(cwd: string, options: ChangelogOptions) {\n const resolved = await resolveConfig(cwd, options);\n const rawCommits = await getGitDiff(resolved.from, resolved.to);\n const commits = parseCommits(rawCommits, resolved);", "score": 0.8349169492721558 }, { "filename": "src/markdown.ts", "retrieved_chunk": " const hashRefs = formatReferences(commit.references, options.repo.repo || '', 'hash');\n let authors = join([\n ...new Set(commit.resolvedAuthors?.map(i => (i.login ? `@${i.login}` : `**${i.name}**`)))\n ])?.trim();\n if (authors) {\n authors = `by ${authors}`;\n }\n let refs = [authors, prRefs, hashRefs].filter(i => i?.trim()).join(' ');\n if (refs) {\n refs = `&nbsp;-&nbsp; ${refs}`;", "score": 0.8229159116744995 } ]
typescript
export async function resolveAuthors(commits: Commit[], options: ChangelogOptions) {
#!/usr/bin/env node import { blue, bold, cyan, dim, red, yellow } from 'kolorist'; import cac from 'cac'; import { version } from '../package.json'; import { generate } from './generate'; import { hasTagOnGitHub, sendRelease } from './github'; import { isRepoShallow } from './git'; import type { ChangelogOptions } from './types'; const cli = cac('githublogen'); cli .version(version) .option('-t, --token <path>', 'GitHub Token') .option('--from <ref>', 'From tag') .option('--to <ref>', 'To tag') .option('--github <path>', 'GitHub Repository, e.g. soybeanjs/githublogen') .option('--name <name>', 'Name of the release') .option('--contributors', 'Show contributors section') .option('--prerelease', 'Mark release as prerelease') .option('-d, --draft', 'Mark release as draft') .option('--output <path>', 'Output to file instead of sending to GitHub') .option('--capitalize', 'Should capitalize for each comment message') .option('--emoji', 'Use emojis in section titles', { default: true }) .option('--group', 'Nest commit messages under their scopes') .option('--dry', 'Dry run') .help(); cli.command('').action(async (args: any) => { try { console.log(); console.log(dim(`${bold('github')}logen `) + dim(`v${version}`)); const cwd = process.cwd(); const { config, md, commits } = await generate(cwd, args as unknown as ChangelogOptions); const markdown = md.replace(/&nbsp;/g, ''); console.log(cyan(config.from) + dim(' -> ') + blue(config.to) + dim(` (${commits.length} commits)`)); console.log(dim('--------------')); console.log(); console.log(markdown); console.log(); console.log(dim('--------------')); if (config.dry) { console.log(yellow('Dry run. Release skipped.')); return; } if (!(await hasTagOnGitHub(config.to, config))) { console.error(yellow(`Current ref "${bold(config.to)}" is not available as tags on GitHub. Release skipped.`)); process.exitCode = 1; return; }
if (!commits.length && (await isRepoShallow())) {
console.error( yellow( 'The repo seems to be clone shallowly, which make changelog failed to generate. You might want to specify `fetch-depth: 0` in your CI config.' ) ); process.exitCode = 1; return; } await sendRelease(config, md); } catch (e: any) { console.error(red(String(e))); if (e?.stack) { console.error(dim(e.stack?.split('\n').slice(1).join('\n'))); } process.exit(1); } }); cli.parse();
src/cli.ts
soybeanjs-githublogen-0932953
[ { "filename": "src/github.ts", "retrieved_chunk": " try {\n console.log(cyan(method === 'POST' ? 'Creating release notes...' : 'Updating release notes...'));\n const res = await $fetch(url, {\n method,\n body: JSON.stringify(body),\n headers\n });\n console.log(green(`Released on ${res.html_url}`));\n } catch (e) {\n console.log();", "score": 0.8353222012519836 }, { "filename": "src/github.ts", "retrieved_chunk": "import { $fetch } from 'ohmyfetch';\nimport { cyan, green, red, yellow } from 'kolorist';\nimport { notNullish } from './shared';\nimport type { AuthorInfo, ChangelogOptions, Commit } from './types';\nexport async function sendRelease(options: ChangelogOptions, content: string) {\n const headers = getHeaders(options);\n const github = options.repo.repo!;\n let url = `https://api.github.com/repos/${github}/releases`;\n let method = 'POST';\n try {", "score": 0.8249064087867737 }, { "filename": "src/generate.ts", "retrieved_chunk": "import { getGitDiff } from './git';\nimport { generateMarkdown } from './markdown';\nimport { resolveAuthors } from './github';\nimport { resolveConfig } from './config';\nimport { parseCommits } from './parse';\nimport type { ChangelogOptions } from './types';\nexport async function generate(cwd: string, options: ChangelogOptions) {\n const resolved = await resolveConfig(cwd, options);\n const rawCommits = await getGitDiff(resolved.from, resolved.to);\n const commits = parseCommits(rawCommits, resolved);", "score": 0.8104537725448608 }, { "filename": "src/config.ts", "retrieved_chunk": " overrides: options\n }).then(r => r.config || defaultConfig);\n config.from = config.from || (await getLastGitTag());\n config.to = config.to || (await getCurrentGitBranch());\n config.repo = await resolveRepoConfig(cwd);\n config.prerelease = config.prerelease ?? isPrerelease(config.to);\n if (config.to === config.from) {\n config.from = (await getLastGitTag(-1)) || (await getFirstGitCommit());\n }\n return config as ResolvedChangelogOptions;", "score": 0.8095943927764893 }, { "filename": "src/github.ts", "retrieved_chunk": " draft: options.draft || false,\n name: options.name || options.to,\n prerelease: options.prerelease,\n tag_name: options.to\n };\n const webUrl = `https://github.com/${github}/releases/new?title=${encodeURIComponent(\n String(body.name)\n )}&body=${encodeURIComponent(String(body.body))}&tag=${encodeURIComponent(String(options.to))}&prerelease=${\n options.prerelease\n }`;", "score": 0.8094333410263062 } ]
typescript
if (!commits.length && (await isRepoShallow())) {
import type { RawGitCommit, RepoConfig } from './types'; export async function getGitHubRepo() { const url = await execCommand('git', ['config', '--get', 'remote.origin.url']); const match = url.match(/github\.com[\/:]([\w\d._-]+?)\/([\w\d._-]+?)(\.git)?$/i); if (!match) { throw new Error(`Can not parse GitHub repo from url ${url}`); } return `${match[1]}/${match[2]}`; } export async function getGitMainBranchName() { const main = await execCommand('git', ['rev-parse', '--abbrev-ref', 'HEAD']); return main; } export async function getCurrentGitBranch() { const result1 = await execCommand('git', ['tag', '--points-at', 'HEAD']); const main = getGitMainBranchName(); return result1 || main; } export async function isRepoShallow() { return (await execCommand('git', ['rev-parse', '--is-shallow-repository'])).trim() === 'true'; } export async function getLastGitTag(delta = 0) { const tags = await execCommand('git', ['--no-pager', 'tag', '-l', '--sort=creatordate']).then(r => r.split('\n')); return tags[tags.length + delta - 1]; } export async function isRefGitTag(to: string) { const { execa } = await import('execa'); try { await execa('git', ['show-ref', '--verify', `refs/tags/${to}`], { reject: true }); return true; } catch { return false; } } export function getFirstGitCommit() { return execCommand('git', ['rev-list', '--max-parents=0', 'HEAD']); } export function isPrerelease(version: string) { return !/^[^.]*[\d.]+$/.test(version); } async function execCommand(cmd: string, args: string[]) { const { execa } = await import('execa'); const res = await execa(cmd, args); return res.stdout.trim(); } export async function getGitDiff(from
: string | undefined, to = 'HEAD'): Promise<RawGitCommit[]> {
// https://git-scm.com/docs/pretty-formats const r = await execCommand('git', [ '--no-pager', 'log', `${from ? `${from}...` : ''}${to}`, '--pretty="----%n%s|%h|%an|%ae%n%b"', '--name-status' ]); return r .split('----\n') .splice(1) .map(line => { const [firstLine, ..._body] = line.split('\n'); const [message, shortHash, authorName, authorEmail] = firstLine.split('|'); const $r: RawGitCommit = { message, shortHash, author: { name: authorName, email: authorEmail }, body: _body.join('\n') }; return $r; }); } export function getGitRemoteURL(cwd: string, remote = 'origin') { return execCommand('git', [`--work-tree=${cwd}`, 'remote', 'get-url', remote]); } export function getGitPushUrl(config: RepoConfig, token?: string) { if (!token) return null; return `https://${token}@${config.domain}/${config.repo}`; }
src/git.ts
soybeanjs-githublogen-0932953
[ { "filename": "src/generate.ts", "retrieved_chunk": "import { getGitDiff } from './git';\nimport { generateMarkdown } from './markdown';\nimport { resolveAuthors } from './github';\nimport { resolveConfig } from './config';\nimport { parseCommits } from './parse';\nimport type { ChangelogOptions } from './types';\nexport async function generate(cwd: string, options: ChangelogOptions) {\n const resolved = await resolveConfig(cwd, options);\n const rawCommits = await getGitDiff(resolved.from, resolved.to);\n const commits = parseCommits(rawCommits, resolved);", "score": 0.8411450386047363 }, { "filename": "src/cli.ts", "retrieved_chunk": " const { config, md, commits } = await generate(cwd, args as unknown as ChangelogOptions);\n const markdown = md.replace(/&nbsp;/g, '');\n console.log(cyan(config.from) + dim(' -> ') + blue(config.to) + dim(` (${commits.length} commits)`));\n console.log(dim('--------------'));\n console.log();\n console.log(markdown);\n console.log();\n console.log(dim('--------------'));\n if (config.dry) {\n console.log(yellow('Dry run. Release skipped.'));", "score": 0.8247113227844238 }, { "filename": "src/config.ts", "retrieved_chunk": "import { getCurrentGitBranch, getFirstGitCommit, getLastGitTag, isPrerelease } from './git';\nimport { resolveRepoConfig } from './repo';\nimport type { ChangelogOptions, ResolvedChangelogOptions } from './types';\nconst defaultConfig: ChangelogOptions = {\n cwd: process.cwd(),\n from: '',\n to: '',\n gitMainBranch: 'main',\n scopeMap: {},\n repo: {},", "score": 0.8129093647003174 }, { "filename": "src/config.ts", "retrieved_chunk": " overrides: options\n }).then(r => r.config || defaultConfig);\n config.from = config.from || (await getLastGitTag());\n config.to = config.to || (await getCurrentGitBranch());\n config.repo = await resolveRepoConfig(cwd);\n config.prerelease = config.prerelease ?? isPrerelease(config.to);\n if (config.to === config.from) {\n config.from = (await getLastGitTag(-1)) || (await getFirstGitCommit());\n }\n return config as ResolvedChangelogOptions;", "score": 0.7994899153709412 }, { "filename": "src/parse.ts", "retrieved_chunk": " };\n}\nexport function parseCommits(commits: RawGitCommit[], config: ChangelogConfig): GitCommit[] {\n return commits.map(commit => parseGitCommit(commit, config)).filter(notNullish);\n}", "score": 0.7902969121932983 } ]
typescript
: string | undefined, to = 'HEAD'): Promise<RawGitCommit[]> {
import { $fetch } from 'ohmyfetch'; import { cyan, green, red, yellow } from 'kolorist'; import { notNullish } from './shared'; import type { AuthorInfo, ChangelogOptions, Commit } from './types'; export async function sendRelease(options: ChangelogOptions, content: string) { const headers = getHeaders(options); const github = options.repo.repo!; let url = `https://api.github.com/repos/${github}/releases`; let method = 'POST'; try { const exists = await $fetch(`https://api.github.com/repos/${github}/releases/tags/${options.to}`, { headers }); if (exists.url) { url = exists.url; method = 'PATCH'; } } catch (e) {} const body = { body: content, draft: options.draft || false, name: options.name || options.to, prerelease: options.prerelease, tag_name: options.to }; const webUrl = `https://github.com/${github}/releases/new?title=${encodeURIComponent( String(body.name) )}&body=${encodeURIComponent(String(body.body))}&tag=${encodeURIComponent(String(options.to))}&prerelease=${ options.prerelease }`; try { console.log(cyan(method === 'POST' ? 'Creating release notes...' : 'Updating release notes...')); const res = await $fetch(url, { method, body: JSON.stringify(body), headers }); console.log(green(`Released on ${res.html_url}`)); } catch (e) { console.log(); console.error(red('Failed to create the release. Using the following link to create it manually:')); console.error(yellow(webUrl)); console.log(); throw e; } } function getHeaders(options: ChangelogOptions) { return { accept: 'application/vnd.github.v3+json', authorization: `token ${options.tokens.github}` }; } export async function resolveAuthorInfo(options: ChangelogOptions, info: AuthorInfo) { if (info.login) return info; // token not provided, skip github resolving if (!options.tokens.github) return info; try { const data = await $fetch(`https://api.github.com/search/users?q=${encodeURIComponent(info.email)}`, { headers: getHeaders(options) }); info.login = data.items[0].login; } catch {} if (info.login) return info; if (info.commits.length) { try { const data = await $fetch(`https://api.github.com/repos/${options.repo.repo}/commits/${info.commits[0]}`, { headers: getHeaders(options) }); info.login = data.author.login; } catch (e) {} } return info; } export async function resolveAuthors(commits: Commit[], options: ChangelogOptions) { const map = new Map<string, AuthorInfo>(); commits.forEach(commit => { commit.resolvedAuthors = commit.authors .
map((a, idx) => {
if (!a.email || !a.name) { return null; } if (!map.has(a.email)) { map.set(a.email, { commits: [], name: a.name, email: a.email }); } const info = map.get(a.email)!; // record commits only for the first author if (idx === 0) { info.commits.push(commit.shortHash); } return info; }) .filter(notNullish); }); const authors = Array.from(map.values()); const resolved = await Promise.all(authors.map(info => resolveAuthorInfo(options, info))); const loginSet = new Set<string>(); const nameSet = new Set<string>(); return resolved .sort((a, b) => (a.login || a.name).localeCompare(b.login || b.name)) .filter(i => { if (i.login && loginSet.has(i.login)) { return false; } if (i.login) { loginSet.add(i.login); } else { if (nameSet.has(i.name)) { return false; } nameSet.add(i.name); } return true; }); } export async function hasTagOnGitHub(tag: string, options: ChangelogOptions) { try { await $fetch(`https://api.github.com/repos/${options.repo.repo}/git/ref/tags/${tag}`, { headers: getHeaders(options) }); return true; } catch (e) { return false; } }
src/github.ts
soybeanjs-githublogen-0932953
[ { "filename": "src/generate.ts", "retrieved_chunk": " if (resolved.contributors) {\n await resolveAuthors(commits, resolved);\n }\n const md = generateMarkdown(commits, resolved);\n return { config: resolved, md, commits };\n}", "score": 0.8706455230712891 }, { "filename": "src/types.ts", "retrieved_chunk": " references: Reference[];\n authors: GitCommitAuthor[];\n isBreaking: boolean;\n}\nexport interface AuthorInfo {\n commits: string[];\n login?: string;\n email: string;\n name: string;\n}", "score": 0.8420423865318298 }, { "filename": "src/types.ts", "retrieved_chunk": "export interface Commit extends GitCommit {\n resolvedAuthors?: AuthorInfo[];\n}\nexport interface ChangelogOptions extends ChangelogConfig {\n /**\n * Dry run. Skip releasing to GitHub.\n */\n dry?: boolean;\n /**\n * Whether to include contributors in release notes.", "score": 0.8409703373908997 }, { "filename": "src/markdown.ts", "retrieved_chunk": " const hashRefs = formatReferences(commit.references, options.repo.repo || '', 'hash');\n let authors = join([\n ...new Set(commit.resolvedAuthors?.map(i => (i.login ? `@${i.login}` : `**${i.name}**`)))\n ])?.trim();\n if (authors) {\n authors = `by ${authors}`;\n }\n let refs = [authors, prRefs, hashRefs].filter(i => i?.trim()).join(' ');\n if (refs) {\n refs = `&nbsp;-&nbsp; ${refs}`;", "score": 0.8338280916213989 }, { "filename": "src/markdown.ts", "retrieved_chunk": " padding = ' ';\n } else if (scope) {\n prefix = `${scopeText}: `;\n }\n lines.push(...scopes[scope].reverse().map(commit => `${padding}- ${prefix}${formatLine(commit, options)}`));\n });\n return lines;\n}\nexport function generateMarkdown(commits: Commit[], options: ResolvedChangelogOptions) {\n const lines: string[] = [];", "score": 0.8262922167778015 } ]
typescript
map((a, idx) => {
import type { RawGitCommit, RepoConfig } from './types'; export async function getGitHubRepo() { const url = await execCommand('git', ['config', '--get', 'remote.origin.url']); const match = url.match(/github\.com[\/:]([\w\d._-]+?)\/([\w\d._-]+?)(\.git)?$/i); if (!match) { throw new Error(`Can not parse GitHub repo from url ${url}`); } return `${match[1]}/${match[2]}`; } export async function getGitMainBranchName() { const main = await execCommand('git', ['rev-parse', '--abbrev-ref', 'HEAD']); return main; } export async function getCurrentGitBranch() { const result1 = await execCommand('git', ['tag', '--points-at', 'HEAD']); const main = getGitMainBranchName(); return result1 || main; } export async function isRepoShallow() { return (await execCommand('git', ['rev-parse', '--is-shallow-repository'])).trim() === 'true'; } export async function getLastGitTag(delta = 0) { const tags = await execCommand('git', ['--no-pager', 'tag', '-l', '--sort=creatordate']).then(r => r.split('\n')); return tags[tags.length + delta - 1]; } export async function isRefGitTag(to: string) { const { execa } = await import('execa'); try { await execa('git', ['show-ref', '--verify', `refs/tags/${to}`], { reject: true }); return true; } catch { return false; } } export function getFirstGitCommit() { return execCommand('git', ['rev-list', '--max-parents=0', 'HEAD']); } export function isPrerelease(version: string) { return !/^[^.]*[\d.]+$/.test(version); } async function execCommand(cmd: string, args: string[]) { const { execa } = await import('execa'); const res = await execa(cmd, args); return res.stdout.trim(); } export async function getGitDiff(from: string | undefined, to = 'HEAD'): Promise<RawGitCommit[]> { // https://git-scm.com/docs/pretty-formats const r = await execCommand('git', [ '--no-pager', 'log', `${from ? `${from}...` : ''}${to}`, '--pretty="----%n%s|%h|%an|%ae%n%b"', '--name-status' ]); return r .split('----\n') .splice(1) .map(line => { const [firstLine, ..._body] = line.split('\n'); const [message, shortHash, authorName, authorEmail] = firstLine.split('|'); const $r: RawGitCommit = { message, shortHash, author: { name: authorName, email: authorEmail }, body: _body.join('\n') }; return $r; }); } export function getGitRemoteURL(cwd: string, remote = 'origin') { return execCommand('git', [`--work-tree=${cwd}`, 'remote', 'get-url', remote]); } export
function getGitPushUrl(config: RepoConfig, token?: string) {
if (!token) return null; return `https://${token}@${config.domain}/${config.repo}`; }
src/git.ts
soybeanjs-githublogen-0932953
[ { "filename": "src/repo.ts", "retrieved_chunk": " const pkg = await readPackageJSON(cwd).catch(() => {});\n if (pkg && pkg.repository) {\n const url = typeof pkg.repository === 'string' ? pkg.repository : pkg.repository.url;\n return getRepoConfig(url);\n }\n const gitRemote = await getGitRemoteURL(cwd).catch(() => {});\n if (gitRemote) {\n return getRepoConfig(gitRemote);\n }\n return {};", "score": 0.8342102766036987 }, { "filename": "src/repo.ts", "retrieved_chunk": " }\n const refSpec = providerToRefSpec[repo.provider];\n return `[${ref.value}](${baseUrl(repo)}/${refSpec[ref.type]}/${ref.value.replace(/^#/, '')})`;\n}\nexport function formatCompareChanges(v: string, config: ChangelogConfig) {\n const part = config.repo?.provider === 'bitbucket' ? 'branches/compare' : 'compare';\n return `[compare changes](${baseUrl(config.repo)}/${part}/${config.from}...${v || config.to})`;\n}\nexport async function resolveRepoConfig(cwd: string) {\n // Try closest package.json", "score": 0.812516450881958 }, { "filename": "src/repo.ts", "retrieved_chunk": "}\nexport function getRepoConfig(repoUrl = ''): RepoConfig {\n let provider: RepoProvider | undefined;\n let repo: string | undefined;\n let domain: string | undefined;\n let url: URL | undefined;\n try {\n url = new URL(repoUrl);\n } catch {}\n const m = repoUrl.match(providerURLRegex)?.groups ?? {};", "score": 0.8073937296867371 }, { "filename": "src/config.ts", "retrieved_chunk": "import { getCurrentGitBranch, getFirstGitCommit, getLastGitTag, isPrerelease } from './git';\nimport { resolveRepoConfig } from './repo';\nimport type { ChangelogOptions, ResolvedChangelogOptions } from './types';\nconst defaultConfig: ChangelogOptions = {\n cwd: process.cwd(),\n from: '',\n to: '',\n gitMainBranch: 'main',\n scopeMap: {},\n repo: {},", "score": 0.7994242906570435 }, { "filename": "src/repo.ts", "retrieved_chunk": "import { readPackageJSON } from 'pkg-types';\nimport type { Reference, ChangelogConfig, RepoProvider, RepoConfig } from './types';\nimport { getGitRemoteURL } from './git';\nconst providerToRefSpec: Record<RepoProvider, Record<Reference['type'], string>> = {\n github: { 'pull-request': 'pull', hash: 'commit', issue: 'issues' },\n gitlab: { 'pull-request': 'merge_requests', hash: 'commit', issue: 'issues' },\n bitbucket: {\n 'pull-request': 'pull-requests',\n hash: 'commit',\n issue: 'issues'", "score": 0.7967836856842041 } ]
typescript
function getGitPushUrl(config: RepoConfig, token?: string) {
import { $fetch } from 'ohmyfetch'; import { cyan, green, red, yellow } from 'kolorist'; import { notNullish } from './shared'; import type { AuthorInfo, ChangelogOptions, Commit } from './types'; export async function sendRelease(options: ChangelogOptions, content: string) { const headers = getHeaders(options); const github = options.repo.repo!; let url = `https://api.github.com/repos/${github}/releases`; let method = 'POST'; try { const exists = await $fetch(`https://api.github.com/repos/${github}/releases/tags/${options.to}`, { headers }); if (exists.url) { url = exists.url; method = 'PATCH'; } } catch (e) {} const body = { body: content, draft: options.draft || false, name: options.name || options.to, prerelease: options.prerelease, tag_name: options.to }; const webUrl = `https://github.com/${github}/releases/new?title=${encodeURIComponent( String(body.name) )}&body=${encodeURIComponent(String(body.body))}&tag=${encodeURIComponent(String(options.to))}&prerelease=${ options.prerelease }`; try { console.log(cyan(method === 'POST' ? 'Creating release notes...' : 'Updating release notes...')); const res = await $fetch(url, { method, body: JSON.stringify(body), headers }); console.log(green(`Released on ${res.html_url}`)); } catch (e) { console.log(); console.error(red('Failed to create the release. Using the following link to create it manually:')); console.error(yellow(webUrl)); console.log(); throw e; } } function getHeaders(options: ChangelogOptions) { return { accept: 'application/vnd.github.v3+json', authorization: `token ${options.tokens.github}` }; } export async function resolveAuthorInfo(options: ChangelogOptions
, info: AuthorInfo) {
if (info.login) return info; // token not provided, skip github resolving if (!options.tokens.github) return info; try { const data = await $fetch(`https://api.github.com/search/users?q=${encodeURIComponent(info.email)}`, { headers: getHeaders(options) }); info.login = data.items[0].login; } catch {} if (info.login) return info; if (info.commits.length) { try { const data = await $fetch(`https://api.github.com/repos/${options.repo.repo}/commits/${info.commits[0]}`, { headers: getHeaders(options) }); info.login = data.author.login; } catch (e) {} } return info; } export async function resolveAuthors(commits: Commit[], options: ChangelogOptions) { const map = new Map<string, AuthorInfo>(); commits.forEach(commit => { commit.resolvedAuthors = commit.authors .map((a, idx) => { if (!a.email || !a.name) { return null; } if (!map.has(a.email)) { map.set(a.email, { commits: [], name: a.name, email: a.email }); } const info = map.get(a.email)!; // record commits only for the first author if (idx === 0) { info.commits.push(commit.shortHash); } return info; }) .filter(notNullish); }); const authors = Array.from(map.values()); const resolved = await Promise.all(authors.map(info => resolveAuthorInfo(options, info))); const loginSet = new Set<string>(); const nameSet = new Set<string>(); return resolved .sort((a, b) => (a.login || a.name).localeCompare(b.login || b.name)) .filter(i => { if (i.login && loginSet.has(i.login)) { return false; } if (i.login) { loginSet.add(i.login); } else { if (nameSet.has(i.name)) { return false; } nameSet.add(i.name); } return true; }); } export async function hasTagOnGitHub(tag: string, options: ChangelogOptions) { try { await $fetch(`https://api.github.com/repos/${options.repo.repo}/git/ref/tags/${tag}`, { headers: getHeaders(options) }); return true; } catch (e) { return false; } }
src/github.ts
soybeanjs-githublogen-0932953
[ { "filename": "src/types.ts", "retrieved_chunk": " references: Reference[];\n authors: GitCommitAuthor[];\n isBreaking: boolean;\n}\nexport interface AuthorInfo {\n commits: string[];\n login?: string;\n email: string;\n name: string;\n}", "score": 0.8209218978881836 }, { "filename": "src/types.ts", "retrieved_chunk": "export interface Commit extends GitCommit {\n resolvedAuthors?: AuthorInfo[];\n}\nexport interface ChangelogOptions extends ChangelogConfig {\n /**\n * Dry run. Skip releasing to GitHub.\n */\n dry?: boolean;\n /**\n * Whether to include contributors in release notes.", "score": 0.8166723847389221 }, { "filename": "src/config.ts", "retrieved_chunk": " output: 'CHANGELOG.md',\n contributors: true,\n capitalize: true,\n group: true\n};\nexport async function resolveConfig(cwd: string, options: ChangelogOptions) {\n const { loadConfig } = await import('c12');\n const config = await loadConfig<ChangelogOptions>({\n name: 'githublogen',\n defaults: defaultConfig,", "score": 0.8125249147415161 }, { "filename": "src/generate.ts", "retrieved_chunk": "import { getGitDiff } from './git';\nimport { generateMarkdown } from './markdown';\nimport { resolveAuthors } from './github';\nimport { resolveConfig } from './config';\nimport { parseCommits } from './parse';\nimport type { ChangelogOptions } from './types';\nexport async function generate(cwd: string, options: ChangelogOptions) {\n const resolved = await resolveConfig(cwd, options);\n const rawCommits = await getGitDiff(resolved.from, resolved.to);\n const commits = parseCommits(rawCommits, resolved);", "score": 0.8020879626274109 }, { "filename": "src/markdown.ts", "retrieved_chunk": " }\n const description = options.capitalize ? capitalize(commit.description) : commit.description;\n return [description, refs].filter(i => i?.trim()).join(' ');\n}\nfunction formatTitle(name: string, options: ResolvedChangelogOptions) {\n let $name = name.trim();\n if (!options.emoji) {\n $name = name.replace(emojisRE, '').trim();\n }\n return `### &nbsp;&nbsp;&nbsp;${$name}`;", "score": 0.7992806434631348 } ]
typescript
, info: AuthorInfo) {
import debug from "debug"; import EventEmitter from "eventemitter3"; import { Relay, relayInit, Sub } from "nostr-tools"; import "websocket-polyfill"; import NDKEvent, { NDKTag, NostrEvent } from "../events/index.js"; import { NDKSubscription } from "../subscription/index.js"; import User from "../user/index.js"; import { NDKRelayScore } from "./score.js"; export enum NDKRelayStatus { CONNECTING, CONNECTED, DISCONNECTING, DISCONNECTED, RECONNECTING, FLAPPING, } export interface NDKRelayConnectionStats { /** * The number of times a connection has been attempted. */ attempts: number; /** * The number of times a connection has been successfully established. */ success: number; /** * The durations of the last 100 connections in milliseconds. */ durations: number[]; /** * The time the current connection was established in milliseconds. */ connectedAt?: number; } /** * The NDKRelay class represents a connection to a relay. * * @emits NDKRelay#connect * @emits NDKRelay#disconnect * @emits NDKRelay#notice * @emits NDKRelay#event * @emits NDKRelay#published when an event is published to the relay * @emits NDKRelay#publish:failed when an event fails to publish to the relay * @emits NDKRelay#eose */ export class NDKRelay extends EventEmitter { readonly url: string; readonly scores: Map<User, NDKRelayScore>; private relay: Relay; private _status: NDKRelayStatus; private connectedAt?: number; private _connectionStats: NDKRelayConnectionStats = { attempts: 0, success: 0, durations: [], }; public complaining = false; private debug: debug.Debugger; /** * Active subscriptions this relay is connected to */ public
activeSubscriptions = new Set<NDKSubscription>();
public constructor(url: string) { super(); this.url = url; this.relay = relayInit(url); this.scores = new Map<User, NDKRelayScore>(); this._status = NDKRelayStatus.DISCONNECTED; this.debug = debug(`ndk:relay:${url}`); this.relay.on("connect", () => { this.updateConnectionStats.connected(); this._status = NDKRelayStatus.CONNECTED; this.emit("connect"); }); this.relay.on("disconnect", () => { this.updateConnectionStats.disconnected(); if (this._status === NDKRelayStatus.CONNECTED) { this._status = NDKRelayStatus.DISCONNECTED; this.handleReconnection(); } this.emit("disconnect"); }); this.relay.on("notice", (notice: string) => this.handleNotice(notice)); } /** * Evaluates the connection stats to determine if the relay is flapping. */ private isFlapping(): boolean { const durations = this._connectionStats.durations; if (durations.length < 10) return false; const sum = durations.reduce((a, b) => a + b, 0); const avg = sum / durations.length; const variance = durations .map((x) => Math.pow(x - avg, 2)) .reduce((a, b) => a + b, 0) / durations.length; const stdDev = Math.sqrt(variance); const isFlapping = stdDev < 1000; return isFlapping; } /** * Called when the relay is unexpectedly disconnected. */ private handleReconnection() { if (this.isFlapping()) { this.emit("flapping", this, this._connectionStats); this._status = NDKRelayStatus.FLAPPING; } if (this.connectedAt && Date.now() - this.connectedAt < 5000) { setTimeout(() => this.connect(), 60000); } else { this.connect(); } } get status(): NDKRelayStatus { return this._status; } /** * Connects to the relay. */ public async connect(): Promise<void> { try { this.updateConnectionStats.attempt(); this._status = NDKRelayStatus.CONNECTING; await this.relay.connect(); } catch (e) { this.debug("Failed to connect", e); this._status = NDKRelayStatus.DISCONNECTED; throw e; } } /** * Disconnects from the relay. */ public disconnect(): void { this._status = NDKRelayStatus.DISCONNECTING; this.relay.close(); } async handleNotice(notice: string) { // This is a prototype; if the relay seems to be complaining // remove it from relay set selection for a minute. if (notice.includes("oo many") || notice.includes("aximum")) { this.disconnect(); // fixme setTimeout(() => this.connect(), 2000); this.debug(this.relay.url, "Relay complaining?", notice); // this.complaining = true; // setTimeout(() => { // this.complaining = false; // console.log(this.relay.url, 'Reactivate relay'); // }, 60000); } this.emit("notice", this, notice); } /** * Subscribes to a subscription. */ public subscribe(subscription: NDKSubscription): Sub { const { filters } = subscription; const sub = this.relay.sub(filters, { id: subscription.subId, }); this.debug(`Subscribed to ${JSON.stringify(filters)}`); sub.on("event", (event: NostrEvent) => { const e = new NDKEvent(undefined, event); e.relay = this; subscription.eventReceived(e, this); }); sub.on("eose", () => { subscription.eoseReceived(this); }); const unsub = sub.unsub; sub.unsub = () => { this.debug(`Unsubscribing from ${JSON.stringify(filters)}`); this.activeSubscriptions.delete(subscription); unsub(); }; this.activeSubscriptions.add(subscription); subscription.on("close", () => { this.activeSubscriptions.delete(subscription); }); return sub; } /** * Publishes an event to the relay with an optional timeout. * * If the relay is not connected, the event will be published when the relay connects, * unless the timeout is reached before the relay connects. * * @param event The event to publish * @param timeoutMs The timeout for the publish operation in milliseconds * @returns A promise that resolves when the event has been published or rejects if the operation times out */ public async publish(event: NDKEvent, timeoutMs = 2500): Promise<boolean> { if (this.status === NDKRelayStatus.CONNECTED) { return this.publishEvent(event, timeoutMs); } else { this.once("connect", () => { this.publishEvent(event, timeoutMs); }); return true; } } private async publishEvent( event: NDKEvent, timeoutMs?: number ): Promise<boolean> { const nostrEvent = await event.toNostrEvent(); const publish = this.relay.publish(nostrEvent as any); let publishTimeout: NodeJS.Timeout | number; const publishPromise = new Promise<boolean>((resolve, reject) => { publish .then(() => { clearTimeout(publishTimeout as unknown as NodeJS.Timeout); this.emit("published", event); resolve(true); }) .catch((err) => { clearTimeout(publishTimeout as NodeJS.Timeout); this.debug("Publish failed", err, event.id); this.emit("publish:failed", event, err); reject(err); }); }); // If no timeout is specified, just return the publish promise if (!timeoutMs) { return publishPromise; } // Create a promise that rejects after timeoutMs milliseconds const timeoutPromise = new Promise<boolean>((_, reject) => { publishTimeout = setTimeout(() => { this.debug("Publish timed out", event.rawEvent()); this.emit("publish:failed", event, "Timeout"); reject(new Error("Publish operation timed out")); }, timeoutMs); }); // wait for either the publish operation to complete or the timeout to occur return Promise.race([publishPromise, timeoutPromise]); } /** * Called when this relay has responded with an event but * wasn't the fastest one. * @param timeDiffInMs The time difference in ms between the fastest and this relay in milliseconds */ // eslint-disable-next-line @typescript-eslint/no-unused-vars public scoreSlowerEvent(timeDiffInMs: number): void { // TODO } /** * Utility functions to update the connection stats. */ private updateConnectionStats = { connected: () => { this._connectionStats.success++; this._connectionStats.connectedAt = Date.now(); }, disconnected: () => { if (this._connectionStats.connectedAt) { this._connectionStats.durations.push( Date.now() - this._connectionStats.connectedAt ); if (this._connectionStats.durations.length > 100) { this._connectionStats.durations.shift(); } } this._connectionStats.connectedAt = undefined; }, attempt: () => { this._connectionStats.attempts++; }, }; /** * Returns the connection stats. */ get connectionStats(): NDKRelayConnectionStats { return this._connectionStats; } public tagReference(marker?: string): NDKTag { const tag = ["r", this.relay.url]; if (marker) { tag.push(marker); } return tag; } }
src/relay/index.ts
nostr-dev-kit-ndk-ece64e1
[ { "filename": "src/subscription/index.ts", "retrieved_chunk": " readonly subId: string;\n readonly filters: NDKFilter[];\n readonly opts: NDKSubscriptionOptions;\n public relaySet?: NDKRelaySet;\n public ndk: NDK;\n public relaySubscriptions: Map<NDKRelay, Sub>;\n private debug: debug.Debugger;\n /**\n * Events that have been seen by the subscription, with the time they were first seen.\n */", "score": 0.8813307881355286 }, { "filename": "src/index.ts", "retrieved_chunk": " public pool: NDKPool;\n public signer?: NDKSigner;\n public cacheAdapter?: NDKCacheAdapter;\n public debug: debug.Debugger;\n public devWriteRelaySet?: NDKRelaySet;\n public delayedSubscriptions: Map<string, NDKSubscription[]>;\n public constructor(opts: NDKConstructorParams = {}) {\n super();\n this.debug = opts.debug || debug(\"ndk\");\n this.pool = new NDKPool(opts.explicitRelayUrls || [], this);", "score": 0.857776403427124 }, { "filename": "src/subscription/index.ts", "retrieved_chunk": " this.subId = subId || opts?.subId || generateFilterId(this.filters[0]);\n this.relaySet = relaySet;\n this.relaySubscriptions = new Map<NDKRelay, Sub>();\n this.debug = ndk.debug.extend(`subscription:${this.subId}`);\n // validate that the caller is not expecting a persistent\n // subscription while using an option that will only hit the cache\n if (\n this.opts.cacheUsage === NDKSubscriptionCacheUsage.ONLY_CACHE &&\n !this.opts.closeOnEose\n ) {", "score": 0.8577371835708618 }, { "filename": "src/relay/pool/index.ts", "retrieved_chunk": "import debug from \"debug\";\nimport EventEmitter from \"eventemitter3\";\nimport NDK from \"../../index.js\";\nimport { NDKRelay, NDKRelayStatus } from \"../index.js\";\nexport type NDKPoolStats = {\n total: number;\n connected: number;\n disconnected: number;\n connecting: number;\n};", "score": 0.8532836437225342 }, { "filename": "src/relay/pool/index.ts", "retrieved_chunk": " public relays = new Map<string, NDKRelay>();\n private debug: debug.Debugger;\n private temporaryRelayTimers = new Map<string, NodeJS.Timeout>();\n public constructor(relayUrls: string[] = [], ndk: NDK) {\n super();\n this.debug = ndk.debug.extend(\"pool\");\n for (const relayUrl of relayUrls) {\n const relay = new NDKRelay(relayUrl);\n this.addRelay(relay, false);\n }", "score": 0.8523696064949036 } ]
typescript
activeSubscriptions = new Set<NDKSubscription>();
import { $fetch } from 'ohmyfetch'; import { cyan, green, red, yellow } from 'kolorist'; import { notNullish } from './shared'; import type { AuthorInfo, ChangelogOptions, Commit } from './types'; export async function sendRelease(options: ChangelogOptions, content: string) { const headers = getHeaders(options); const github = options.repo.repo!; let url = `https://api.github.com/repos/${github}/releases`; let method = 'POST'; try { const exists = await $fetch(`https://api.github.com/repos/${github}/releases/tags/${options.to}`, { headers }); if (exists.url) { url = exists.url; method = 'PATCH'; } } catch (e) {} const body = { body: content, draft: options.draft || false, name: options.name || options.to, prerelease: options.prerelease, tag_name: options.to }; const webUrl = `https://github.com/${github}/releases/new?title=${encodeURIComponent( String(body.name) )}&body=${encodeURIComponent(String(body.body))}&tag=${encodeURIComponent(String(options.to))}&prerelease=${ options.prerelease }`; try { console.log(cyan(method === 'POST' ? 'Creating release notes...' : 'Updating release notes...')); const res = await $fetch(url, { method, body: JSON.stringify(body), headers }); console.log(green(`Released on ${res.html_url}`)); } catch (e) { console.log(); console.error(red('Failed to create the release. Using the following link to create it manually:')); console.error(yellow(webUrl)); console.log(); throw e; } } function getHeaders(options: ChangelogOptions) { return { accept: 'application/vnd.github.v3+json', authorization: `token ${options.tokens.github}` }; } export async function resolveAuthorInfo(options: ChangelogOptions, info: AuthorInfo) { if (info.login) return info; // token not provided, skip github resolving if (!options.tokens.github) return info; try { const data = await $fetch(`https://api.github.com/search/users?q=${encodeURIComponent(info.email)}`, { headers: getHeaders(options) }); info.login = data.items[0].login; } catch {} if (info.login) return info; if (info.commits.length) { try { const data = await $fetch(`https://api.github.com/repos/${options.repo.repo}/commits/${info.commits[0]}`, { headers: getHeaders(options) }); info.login = data.author.login; } catch (e) {} } return info; } export async function resolveAuthors(commits: Commit[], options: ChangelogOptions) { const map = new Map<string, AuthorInfo>(); commits.forEach(commit => { commit.resolvedAuthors = commit.authors .map((a
, idx) => {
if (!a.email || !a.name) { return null; } if (!map.has(a.email)) { map.set(a.email, { commits: [], name: a.name, email: a.email }); } const info = map.get(a.email)!; // record commits only for the first author if (idx === 0) { info.commits.push(commit.shortHash); } return info; }) .filter(notNullish); }); const authors = Array.from(map.values()); const resolved = await Promise.all(authors.map(info => resolveAuthorInfo(options, info))); const loginSet = new Set<string>(); const nameSet = new Set<string>(); return resolved .sort((a, b) => (a.login || a.name).localeCompare(b.login || b.name)) .filter(i => { if (i.login && loginSet.has(i.login)) { return false; } if (i.login) { loginSet.add(i.login); } else { if (nameSet.has(i.name)) { return false; } nameSet.add(i.name); } return true; }); } export async function hasTagOnGitHub(tag: string, options: ChangelogOptions) { try { await $fetch(`https://api.github.com/repos/${options.repo.repo}/git/ref/tags/${tag}`, { headers: getHeaders(options) }); return true; } catch (e) { return false; } }
src/github.ts
soybeanjs-githublogen-0932953
[ { "filename": "src/generate.ts", "retrieved_chunk": " if (resolved.contributors) {\n await resolveAuthors(commits, resolved);\n }\n const md = generateMarkdown(commits, resolved);\n return { config: resolved, md, commits };\n}", "score": 0.8699584007263184 }, { "filename": "src/types.ts", "retrieved_chunk": " references: Reference[];\n authors: GitCommitAuthor[];\n isBreaking: boolean;\n}\nexport interface AuthorInfo {\n commits: string[];\n login?: string;\n email: string;\n name: string;\n}", "score": 0.8421273231506348 }, { "filename": "src/types.ts", "retrieved_chunk": "export interface Commit extends GitCommit {\n resolvedAuthors?: AuthorInfo[];\n}\nexport interface ChangelogOptions extends ChangelogConfig {\n /**\n * Dry run. Skip releasing to GitHub.\n */\n dry?: boolean;\n /**\n * Whether to include contributors in release notes.", "score": 0.8388952016830444 }, { "filename": "src/markdown.ts", "retrieved_chunk": " const hashRefs = formatReferences(commit.references, options.repo.repo || '', 'hash');\n let authors = join([\n ...new Set(commit.resolvedAuthors?.map(i => (i.login ? `@${i.login}` : `**${i.name}**`)))\n ])?.trim();\n if (authors) {\n authors = `by ${authors}`;\n }\n let refs = [authors, prRefs, hashRefs].filter(i => i?.trim()).join(' ');\n if (refs) {\n refs = `&nbsp;-&nbsp; ${refs}`;", "score": 0.8335499167442322 }, { "filename": "src/parse.ts", "retrieved_chunk": " description = description.replace(PullRequestRE, '').trim();\n // Find all authors\n const authors: GitCommitAuthor[] = [commit.author];\n const matchs = commit.body.matchAll(CoAuthoredByRegex);\n for (const $match of matchs) {\n const { name = '', email = '' } = $match.groups || {};\n const author: GitCommitAuthor = {\n name: name.trim(),\n email: email.trim()\n };", "score": 0.8243674635887146 } ]
typescript
, idx) => {
import { convert } from 'convert-gitmoji'; import { partition, groupBy, capitalize, join } from './shared'; import type { Reference, Commit, ResolvedChangelogOptions } from './types'; const emojisRE = /([\u2700-\u27BF]|[\uE000-\uF8FF]|\uD83C[\uDC00-\uDFFF]|\uD83D[\uDC00-\uDFFF]|[\u2011-\u26FF]|\uD83E[\uDD10-\uDDFF])/g; function formatReferences(references: Reference[], github: string, type: 'issues' | 'hash'): string { const refs = references .filter(i => { if (type === 'issues') { return i.type === 'issue' || i.type === 'pull-request'; } return i.type === 'hash'; }) .map(ref => { if (!github) { return ref.value; } if (ref.type === 'pull-request' || ref.type === 'issue') { return `https://github.com/${github}/issues/${ref.value.slice(1)}`; } return `[<samp>(${ref.value.slice(0, 5)})</samp>](https://github.com/${github}/commit/${ref.value})`; }); const referencesString = join(refs).trim(); if (type === 'issues') { return referencesString && `in ${referencesString}`; } return referencesString; } function formatLine(commit: Commit, options: ResolvedChangelogOptions) { const prRefs = formatReferences(commit.references, options.repo.repo || '', 'issues'); const hashRefs = formatReferences(commit.references, options.repo.repo || '', 'hash'); let authors = join([ ...new Set(commit.resolvedAuthors?.map(i => (i.login ? `@${i.login}` : `**${i.name}**`))) ])?.trim(); if (authors) { authors = `by ${authors}`; } let refs = [authors, prRefs, hashRefs].filter(i => i?.trim()).join(' '); if (refs) { refs = `&nbsp;-&nbsp; ${refs}`; }
const description = options.capitalize ? capitalize(commit.description) : commit.description;
return [description, refs].filter(i => i?.trim()).join(' '); } function formatTitle(name: string, options: ResolvedChangelogOptions) { let $name = name.trim(); if (!options.emoji) { $name = name.replace(emojisRE, '').trim(); } return `### &nbsp;&nbsp;&nbsp;${$name}`; } function formatSection(commits: Commit[], sectionName: string, options: ResolvedChangelogOptions) { if (!commits.length) { return []; } const lines: string[] = ['', formatTitle(sectionName, options), '']; const scopes = groupBy(commits, 'scope'); let useScopeGroup = options.group; // group scopes only when one of the scope have multiple commits if (!Object.entries(scopes).some(([k, v]) => k && v.length > 1)) { useScopeGroup = false; } Object.keys(scopes) .sort() .forEach(scope => { let padding = ''; let prefix = ''; const scopeText = `**${options.scopeMap[scope] || scope}**`; if (scope && (useScopeGroup === true || (useScopeGroup === 'multiple' && scopes[scope].length > 1))) { lines.push(`- ${scopeText}:`); padding = ' '; } else if (scope) { prefix = `${scopeText}: `; } lines.push(...scopes[scope].reverse().map(commit => `${padding}- ${prefix}${formatLine(commit, options)}`)); }); return lines; } export function generateMarkdown(commits: Commit[], options: ResolvedChangelogOptions) { const lines: string[] = []; const [breaking, changes] = partition(commits, c => c.isBreaking); const group = groupBy(changes, 'type'); lines.push(...formatSection(breaking, options.titles.breakingChanges!, options)); for (const type of Object.keys(options.types)) { const items = group[type] || []; lines.push(...formatSection(items, options.types[type].title, options)); } if (!lines.length) { lines.push('*No significant changes*'); } const url = `https://github.com/${options.repo.repo!}/compare/${options.from}...${options.to}`; lines.push('', `##### &nbsp;&nbsp;&nbsp;&nbsp;[View changes on GitHub](${url})`); return convert(lines.join('\n').trim(), true); }
src/markdown.ts
soybeanjs-githublogen-0932953
[ { "filename": "src/parse.ts", "retrieved_chunk": " description = description.replace(PullRequestRE, '').trim();\n // Find all authors\n const authors: GitCommitAuthor[] = [commit.author];\n const matchs = commit.body.matchAll(CoAuthoredByRegex);\n for (const $match of matchs) {\n const { name = '', email = '' } = $match.groups || {};\n const author: GitCommitAuthor = {\n name: name.trim(),\n email: email.trim()\n };", "score": 0.8730148077011108 }, { "filename": "src/github.ts", "retrieved_chunk": " }\n return info;\n}\nexport async function resolveAuthors(commits: Commit[], options: ChangelogOptions) {\n const map = new Map<string, AuthorInfo>();\n commits.forEach(commit => {\n commit.resolvedAuthors = commit.authors\n .map((a, idx) => {\n if (!a.email || !a.name) {\n return null;", "score": 0.8580512404441833 }, { "filename": "src/github.ts", "retrieved_chunk": " if (idx === 0) {\n info.commits.push(commit.shortHash);\n }\n return info;\n })\n .filter(notNullish);\n });\n const authors = Array.from(map.values());\n const resolved = await Promise.all(authors.map(info => resolveAuthorInfo(options, info)));\n const loginSet = new Set<string>();", "score": 0.8567467927932739 }, { "filename": "src/parse.ts", "retrieved_chunk": " authors.push(author);\n }\n return {\n ...commit,\n authors,\n description,\n type,\n scope,\n references,\n isBreaking", "score": 0.8515020608901978 }, { "filename": "src/generate.ts", "retrieved_chunk": " if (resolved.contributors) {\n await resolveAuthors(commits, resolved);\n }\n const md = generateMarkdown(commits, resolved);\n return { config: resolved, md, commits };\n}", "score": 0.8486231565475464 } ]
typescript
const description = options.capitalize ? capitalize(commit.description) : commit.description;
import { convert } from 'convert-gitmoji'; import { partition, groupBy, capitalize, join } from './shared'; import type { Reference, Commit, ResolvedChangelogOptions } from './types'; const emojisRE = /([\u2700-\u27BF]|[\uE000-\uF8FF]|\uD83C[\uDC00-\uDFFF]|\uD83D[\uDC00-\uDFFF]|[\u2011-\u26FF]|\uD83E[\uDD10-\uDDFF])/g; function formatReferences(references: Reference[], github: string, type: 'issues' | 'hash'): string { const refs = references .filter(i => { if (type === 'issues') { return i.type === 'issue' || i.type === 'pull-request'; } return i.type === 'hash'; }) .map(ref => { if (!github) { return ref.value; } if (ref.type === 'pull-request' || ref.type === 'issue') { return `https://github.com/${github}/issues/${ref.value.slice(1)}`; } return `[<samp>(${ref.value.slice(0, 5)})</samp>](https://github.com/${github}/commit/${ref.value})`; }); const referencesString = join(refs).trim(); if (type === 'issues') { return referencesString && `in ${referencesString}`; } return referencesString; } function formatLine(commit: Commit, options: ResolvedChangelogOptions) { const prRefs = formatReferences(commit.references, options.repo.repo || '', 'issues'); const hashRefs = formatReferences(commit.references, options.repo.repo || '', 'hash'); let authors = join([ ...new Set(commit.resolvedAuthors?.map(i => (i.login ? `@${i.login}` : `**${i.name}**`))) ])?.trim(); if (authors) { authors = `by ${authors}`; } let refs = [authors, prRefs, hashRefs].filter(i => i?.trim()).join(' '); if (refs) { refs = `&nbsp;-&nbsp; ${refs}`; } const description = options.capitalize ? capitalize(commit.description) : commit.description; return [description, refs].filter(i => i?.trim()).join(' '); } function formatTitle(name: string, options: ResolvedChangelogOptions) { let $name = name.trim(); if (!options.emoji) { $name = name.replace(emojisRE, '').trim(); } return `### &nbsp;&nbsp;&nbsp;${$name}`; } function formatSection(commits: Commit[], sectionName: string, options: ResolvedChangelogOptions) { if (!commits.length) { return []; } const lines: string[] = ['', formatTitle(sectionName, options), ''];
const scopes = groupBy(commits, 'scope');
let useScopeGroup = options.group; // group scopes only when one of the scope have multiple commits if (!Object.entries(scopes).some(([k, v]) => k && v.length > 1)) { useScopeGroup = false; } Object.keys(scopes) .sort() .forEach(scope => { let padding = ''; let prefix = ''; const scopeText = `**${options.scopeMap[scope] || scope}**`; if (scope && (useScopeGroup === true || (useScopeGroup === 'multiple' && scopes[scope].length > 1))) { lines.push(`- ${scopeText}:`); padding = ' '; } else if (scope) { prefix = `${scopeText}: `; } lines.push(...scopes[scope].reverse().map(commit => `${padding}- ${prefix}${formatLine(commit, options)}`)); }); return lines; } export function generateMarkdown(commits: Commit[], options: ResolvedChangelogOptions) { const lines: string[] = []; const [breaking, changes] = partition(commits, c => c.isBreaking); const group = groupBy(changes, 'type'); lines.push(...formatSection(breaking, options.titles.breakingChanges!, options)); for (const type of Object.keys(options.types)) { const items = group[type] || []; lines.push(...formatSection(items, options.types[type].title, options)); } if (!lines.length) { lines.push('*No significant changes*'); } const url = `https://github.com/${options.repo.repo!}/compare/${options.from}...${options.to}`; lines.push('', `##### &nbsp;&nbsp;&nbsp;&nbsp;[View changes on GitHub](${url})`); return convert(lines.join('\n').trim(), true); }
src/markdown.ts
soybeanjs-githublogen-0932953
[ { "filename": "src/github.ts", "retrieved_chunk": " }\n return info;\n}\nexport async function resolveAuthors(commits: Commit[], options: ChangelogOptions) {\n const map = new Map<string, AuthorInfo>();\n commits.forEach(commit => {\n commit.resolvedAuthors = commit.authors\n .map((a, idx) => {\n if (!a.email || !a.name) {\n return null;", "score": 0.8237574100494385 }, { "filename": "src/generate.ts", "retrieved_chunk": " if (resolved.contributors) {\n await resolveAuthors(commits, resolved);\n }\n const md = generateMarkdown(commits, resolved);\n return { config: resolved, md, commits };\n}", "score": 0.8147087693214417 }, { "filename": "src/parse.ts", "retrieved_chunk": " };\n}\nexport function parseCommits(commits: RawGitCommit[], config: ChangelogConfig): GitCommit[] {\n return commits.map(commit => parseGitCommit(commit, config)).filter(notNullish);\n}", "score": 0.8136288523674011 }, { "filename": "src/generate.ts", "retrieved_chunk": "import { getGitDiff } from './git';\nimport { generateMarkdown } from './markdown';\nimport { resolveAuthors } from './github';\nimport { resolveConfig } from './config';\nimport { parseCommits } from './parse';\nimport type { ChangelogOptions } from './types';\nexport async function generate(cwd: string, options: ChangelogOptions) {\n const resolved = await resolveConfig(cwd, options);\n const rawCommits = await getGitDiff(resolved.from, resolved.to);\n const commits = parseCommits(rawCommits, resolved);", "score": 0.8087588548660278 }, { "filename": "src/cli.ts", "retrieved_chunk": " const { config, md, commits } = await generate(cwd, args as unknown as ChangelogOptions);\n const markdown = md.replace(/&nbsp;/g, '');\n console.log(cyan(config.from) + dim(' -> ') + blue(config.to) + dim(` (${commits.length} commits)`));\n console.log(dim('--------------'));\n console.log();\n console.log(markdown);\n console.log();\n console.log(dim('--------------'));\n if (config.dry) {\n console.log(yellow('Dry run. Release skipped.'));", "score": 0.8068277835845947 } ]
typescript
const scopes = groupBy(commits, 'scope');
import debug from "debug"; import EventEmitter from "eventemitter3"; import NDK from "../../index.js"; import { NDKRelay, NDKRelayStatus } from "../index.js"; export type NDKPoolStats = { total: number; connected: number; disconnected: number; connecting: number; }; /** * Handles connections to all relays. A single pool should be used per NDK instance. * * @emit connect - Emitted when all relays in the pool are connected, or when the specified timeout has elapsed, and some relays are connected. * @emit notice - Emitted when a relay in the pool sends a notice. * @emit flapping - Emitted when a relay in the pool is flapping. * @emit relay:connect - Emitted when a relay in the pool connects. * @emit relay:disconnect - Emitted when a relay in the pool disconnects. */ export class NDKPool extends EventEmitter { public relays = new Map<string, NDKRelay>(); private debug: debug.Debugger; private temporaryRelayTimers = new Map<string, NodeJS.Timeout>(); public constructor(relayUrls: string[] = [], ndk: NDK) { super(); this.debug = ndk.debug.extend("pool"); for (const relayUrl of relayUrls) { const relay = new NDKRelay(relayUrl); this.addRelay(relay, false); } } /** * Adds a relay to the pool, and sets a timer to remove it if it is not used within the specified time. * @param relay - The relay to add to the pool. * @param removeIfUnusedAfter - The time in milliseconds to wait before removing the relay from the pool after it is no longer used. */
public useTemporaryRelay(relay: NDKRelay, removeIfUnusedAfter = 600000) {
const relayAlreadyInPool = this.relays.has(relay.url); // check if the relay is already in the pool if (!relayAlreadyInPool) { this.addRelay(relay); } // check if the relay already has a disconnecting timer const existingTimer = this.temporaryRelayTimers.get(relay.url); if (existingTimer) { clearTimeout(existingTimer); } // add a disconnecting timer only if the relay was not already in the pool // or if it had an existing timer // this prevents explicit relays from being removed from the pool if (!relayAlreadyInPool || existingTimer) { // set a timer to remove the relay from the pool if it is not used within the specified time const timer = setTimeout(() => { this.removeRelay(relay.url); }, removeIfUnusedAfter) as unknown as NodeJS.Timeout; this.temporaryRelayTimers.set(relay.url, timer); } } /** * Adds a relay to the pool. * * @param relay - The relay to add to the pool. * @param connect - Whether or not to connect to the relay. */ public addRelay(relay: NDKRelay, connect = true) { const relayUrl = relay.url; relay.on("notice", (relay, notice) => this.emit("notice", relay, notice) ); relay.on("connect", () => this.handleRelayConnect(relayUrl)); relay.on("disconnect", () => this.emit("relay:disconnect", relay)); relay.on("flapping", () => this.handleFlapping(relay)); this.relays.set(relayUrl, relay); if (connect) { relay.connect(); } } /** * Removes a relay from the pool. * @param relayUrl - The URL of the relay to remove. * @returns {boolean} True if the relay was removed, false if it was not found. */ public removeRelay(relayUrl: string): boolean { const relay = this.relays.get(relayUrl); if (relay) { relay.disconnect(); this.relays.delete(relayUrl); this.emit("relay:disconnect", relay); return true; } // remove the relay from the temporary relay timers const existingTimer = this.temporaryRelayTimers.get(relayUrl); if (existingTimer) { clearTimeout(existingTimer); this.temporaryRelayTimers.delete(relayUrl); } return false; } private handleRelayConnect(relayUrl: string) { this.debug(`Relay ${relayUrl} connected`); this.emit("relay:connect", this.relays.get(relayUrl)); if (this.stats().connected === this.relays.size) { this.emit("connect"); } } /** * Attempts to establish a connection to each relay in the pool. * * @async * @param {number} [timeoutMs] - Optional timeout in milliseconds for each connection attempt. * @returns {Promise<void>} A promise that resolves when all connection attempts have completed. * @throws {Error} If any of the connection attempts result in an error or timeout. */ public async connect(timeoutMs?: number): Promise<void> { const promises: Promise<void>[] = []; this.debug( `Connecting to ${this.relays.size} relays${ timeoutMs ? `, timeout ${timeoutMs}...` : "" }` ); for (const relay of this.relays.values()) { if (timeoutMs) { const timeoutPromise = new Promise<void>((_, reject) => { setTimeout( () => reject(`Timed out after ${timeoutMs}ms`), timeoutMs ); }); promises.push( Promise.race([relay.connect(), timeoutPromise]).catch( (e) => { this.debug( `Failed to connect to relay ${relay.url}: ${e}` ); } ) ); } else { promises.push(relay.connect()); } } // If we are running with a timeout, check if we need to emit a `connect` event // in case some, but not all, relays were connected if (timeoutMs) { setTimeout(() => { const allConnected = this.stats().connected === this.relays.size; const someConnected = this.stats().connected > 0; if (!allConnected && someConnected) { this.emit("connect"); } }, timeoutMs); } await Promise.all(promises); } private handleFlapping(relay: NDKRelay) { this.debug(`Relay ${relay.url} is flapping`); // TODO: Be smarter about this. this.relays.delete(relay.url); this.emit("flapping", relay); } public size(): number { return this.relays.size; } /** * Returns the status of each relay in the pool. * @returns {NDKPoolStats} An object containing the number of relays in each status. */ public stats(): NDKPoolStats { const stats: NDKPoolStats = { total: 0, connected: 0, disconnected: 0, connecting: 0, }; for (const relay of this.relays.values()) { stats.total++; if (relay.status === NDKRelayStatus.CONNECTED) { stats.connected++; } else if (relay.status === NDKRelayStatus.DISCONNECTED) { stats.disconnected++; } else if (relay.status === NDKRelayStatus.CONNECTING) { stats.connecting++; } } return stats; } public connectedRelays(): NDKRelay[] { return Array.from(this.relays.values()).filter( (relay) => relay.status === NDKRelayStatus.CONNECTED ); } /** * Get a list of all relay urls in the pool. */ public urls(): string[] { return Array.from(this.relays.keys()); } }
src/relay/pool/index.ts
nostr-dev-kit-ndk-ece64e1
[ { "filename": "src/relay/sets/index.ts", "retrieved_chunk": " public constructor(relays: Set<NDKRelay>, ndk: NDK) {\n this.relays = relays;\n this.ndk = ndk;\n this.debug = ndk.debug.extend(\"relayset\");\n }\n /**\n * Adds a relay to this set.\n */\n public addRelay(relay: NDKRelay) {\n this.relays.add(relay);", "score": 0.8206048607826233 }, { "filename": "src/relay/sets/calculate.ts", "retrieved_chunk": "): NDKRelaySet {\n const relays: Set<NDKRelay> = new Set();\n ndk.pool?.relays.forEach((relay) => {\n if (!relay.complaining) {\n relays.add(relay);\n } else {\n ndk.debug(`Relay ${relay.url} is complaining, not adding to set`);\n }\n });\n return new NDKRelaySet(relays, ndk);", "score": 0.8074918985366821 }, { "filename": "src/relay/sets/index.ts", "retrieved_chunk": " */\n static fromRelayUrls(relayUrls: string[], ndk: NDK): NDKRelaySet {\n const relays = new Set<NDKRelay>();\n for (const url of relayUrls) {\n const relay = ndk.pool.relays.get(url);\n if (relay) {\n relays.add(relay);\n }\n }\n return new NDKRelaySet(new Set(relays), ndk);", "score": 0.8052201271057129 }, { "filename": "src/relay/sets/index.ts", "retrieved_chunk": " if (relay.status === NDKRelayStatus.CONNECTED) {\n // If the relay is already connected, subscribe immediately\n this.subscribeOnRelay(relay, subscription);\n } else {\n // If the relay is not connected, add a one-time listener to wait for the 'connected' event\n const connectedListener = () => {\n this.debug(\n \"new relay coming online for active subscription\",\n {\n relay: relay.url,", "score": 0.8040329217910767 }, { "filename": "src/index.ts", "retrieved_chunk": " if (relaySet) {\n for (const relay of relaySet.relays) {\n this.pool.useTemporaryRelay(relay);\n }\n }\n if (autoStart) subscription.start();\n return subscription;\n }\n /**\n * Publish an event to a relay", "score": 0.797478199005127 } ]
typescript
public useTemporaryRelay(relay: NDKRelay, removeIfUnusedAfter = 600000) {
import { convert } from 'convert-gitmoji'; import { partition, groupBy, capitalize, join } from './shared'; import type { Reference, Commit, ResolvedChangelogOptions } from './types'; const emojisRE = /([\u2700-\u27BF]|[\uE000-\uF8FF]|\uD83C[\uDC00-\uDFFF]|\uD83D[\uDC00-\uDFFF]|[\u2011-\u26FF]|\uD83E[\uDD10-\uDDFF])/g; function formatReferences(references: Reference[], github: string, type: 'issues' | 'hash'): string { const refs = references .filter(i => { if (type === 'issues') { return i.type === 'issue' || i.type === 'pull-request'; } return i.type === 'hash'; }) .map(ref => { if (!github) { return ref.value; } if (ref.type === 'pull-request' || ref.type === 'issue') { return `https://github.com/${github}/issues/${ref.value.slice(1)}`; } return `[<samp>(${ref.value.slice(0, 5)})</samp>](https://github.com/${github}/commit/${ref.value})`; }); const referencesString = join(refs).trim(); if (type === 'issues') { return referencesString && `in ${referencesString}`; } return referencesString; } function formatLine(commit: Commit, options: ResolvedChangelogOptions) { const prRefs = formatReferences(commit.references, options.repo.repo || '', 'issues'); const hashRefs = formatReferences(commit.references, options.repo.repo || '', 'hash'); let authors = join([ ...new Set(commit.resolvedAuthors?.map(i => (i.login ? `@${i.login}` : `**${i.name}**`))) ])?.trim(); if (authors) { authors = `by ${authors}`; } let refs = [authors, prRefs, hashRefs].filter(i => i?.trim()).join(' '); if (refs) { refs = `&nbsp;-&nbsp; ${refs}`; } const description = options.capitalize ? capitalize(commit.description) : commit.description; return [description, refs].filter(i => i?.trim()).join(' '); } function formatTitle(name: string, options: ResolvedChangelogOptions) { let $name = name.trim(); if (!options.emoji) { $name = name.replace(emojisRE, '').trim(); } return `### &nbsp;&nbsp;&nbsp;${$name}`; } function formatSection(commits: Commit[], sectionName: string, options: ResolvedChangelogOptions) { if (!commits.length) { return []; } const lines: string[] = ['', formatTitle(sectionName, options), '']; const scopes = groupBy(commits, 'scope'); let useScopeGroup = options.group; // group scopes only when one of the scope have multiple commits
if (!Object.entries(scopes).some(([k, v]) => k && v.length > 1)) {
useScopeGroup = false; } Object.keys(scopes) .sort() .forEach(scope => { let padding = ''; let prefix = ''; const scopeText = `**${options.scopeMap[scope] || scope}**`; if (scope && (useScopeGroup === true || (useScopeGroup === 'multiple' && scopes[scope].length > 1))) { lines.push(`- ${scopeText}:`); padding = ' '; } else if (scope) { prefix = `${scopeText}: `; } lines.push(...scopes[scope].reverse().map(commit => `${padding}- ${prefix}${formatLine(commit, options)}`)); }); return lines; } export function generateMarkdown(commits: Commit[], options: ResolvedChangelogOptions) { const lines: string[] = []; const [breaking, changes] = partition(commits, c => c.isBreaking); const group = groupBy(changes, 'type'); lines.push(...formatSection(breaking, options.titles.breakingChanges!, options)); for (const type of Object.keys(options.types)) { const items = group[type] || []; lines.push(...formatSection(items, options.types[type].title, options)); } if (!lines.length) { lines.push('*No significant changes*'); } const url = `https://github.com/${options.repo.repo!}/compare/${options.from}...${options.to}`; lines.push('', `##### &nbsp;&nbsp;&nbsp;&nbsp;[View changes on GitHub](${url})`); return convert(lines.join('\n').trim(), true); }
src/markdown.ts
soybeanjs-githublogen-0932953
[ { "filename": "src/parse.ts", "retrieved_chunk": " };\n}\nexport function parseCommits(commits: RawGitCommit[], config: ChangelogConfig): GitCommit[] {\n return commits.map(commit => parseGitCommit(commit, config)).filter(notNullish);\n}", "score": 0.825957179069519 }, { "filename": "src/github.ts", "retrieved_chunk": " }\n return info;\n}\nexport async function resolveAuthors(commits: Commit[], options: ChangelogOptions) {\n const map = new Map<string, AuthorInfo>();\n commits.forEach(commit => {\n commit.resolvedAuthors = commit.authors\n .map((a, idx) => {\n if (!a.email || !a.name) {\n return null;", "score": 0.823650062084198 }, { "filename": "src/generate.ts", "retrieved_chunk": "import { getGitDiff } from './git';\nimport { generateMarkdown } from './markdown';\nimport { resolveAuthors } from './github';\nimport { resolveConfig } from './config';\nimport { parseCommits } from './parse';\nimport type { ChangelogOptions } from './types';\nexport async function generate(cwd: string, options: ChangelogOptions) {\n const resolved = await resolveConfig(cwd, options);\n const rawCommits = await getGitDiff(resolved.from, resolved.to);\n const commits = parseCommits(rawCommits, resolved);", "score": 0.8145978450775146 }, { "filename": "src/generate.ts", "retrieved_chunk": " if (resolved.contributors) {\n await resolveAuthors(commits, resolved);\n }\n const md = generateMarkdown(commits, resolved);\n return { config: resolved, md, commits };\n}", "score": 0.8057663440704346 }, { "filename": "src/github.ts", "retrieved_chunk": " if (idx === 0) {\n info.commits.push(commit.shortHash);\n }\n return info;\n })\n .filter(notNullish);\n });\n const authors = Array.from(map.values());\n const resolved = await Promise.all(authors.map(info => resolveAuthorInfo(options, info)));\n const loginSet = new Set<string>();", "score": 0.802323043346405 } ]
typescript
if (!Object.entries(scopes).some(([k, v]) => k && v.length > 1)) {
import debug from "debug"; import EventEmitter from "eventemitter3"; import NDK from "../../index.js"; import { NDKRelay, NDKRelayStatus } from "../index.js"; export type NDKPoolStats = { total: number; connected: number; disconnected: number; connecting: number; }; /** * Handles connections to all relays. A single pool should be used per NDK instance. * * @emit connect - Emitted when all relays in the pool are connected, or when the specified timeout has elapsed, and some relays are connected. * @emit notice - Emitted when a relay in the pool sends a notice. * @emit flapping - Emitted when a relay in the pool is flapping. * @emit relay:connect - Emitted when a relay in the pool connects. * @emit relay:disconnect - Emitted when a relay in the pool disconnects. */ export class NDKPool extends EventEmitter { public relays = new Map<string, NDKRelay>(); private debug: debug.Debugger; private temporaryRelayTimers = new Map<string, NodeJS.Timeout>(); public constructor(relayUrls: string[] = [], ndk: NDK) { super(); this.debug = ndk.debug.extend("pool"); for (const relayUrl of relayUrls) { const relay = new NDKRelay(relayUrl); this.addRelay(relay, false); } } /** * Adds a relay to the pool, and sets a timer to remove it if it is not used within the specified time. * @param relay - The relay to add to the pool. * @param removeIfUnusedAfter - The time in milliseconds to wait before removing the relay from the pool after it is no longer used. */ public useTemporaryRelay(relay: NDKRelay, removeIfUnusedAfter = 600000) { const relayAlreadyInPool = this.relays.has(relay.url); // check if the relay is already in the pool if (!relayAlreadyInPool) { this.addRelay(relay); } // check if the relay already has a disconnecting timer const existingTimer = this.temporaryRelayTimers.get(relay.url); if (existingTimer) { clearTimeout(existingTimer); } // add a disconnecting timer only if the relay was not already in the pool // or if it had an existing timer // this prevents explicit relays from being removed from the pool if (!relayAlreadyInPool || existingTimer) { // set a timer to remove the relay from the pool if it is not used within the specified time const timer = setTimeout(() => { this.removeRelay(relay.url); }, removeIfUnusedAfter) as unknown as NodeJS.Timeout; this.temporaryRelayTimers.set(relay.url, timer); } } /** * Adds a relay to the pool. * * @param relay - The relay to add to the pool. * @param connect - Whether or not to connect to the relay. */ public addRelay(relay: NDKRelay, connect = true) { const relayUrl = relay.url;
relay.on("notice", (relay, notice) => this.emit("notice", relay, notice) );
relay.on("connect", () => this.handleRelayConnect(relayUrl)); relay.on("disconnect", () => this.emit("relay:disconnect", relay)); relay.on("flapping", () => this.handleFlapping(relay)); this.relays.set(relayUrl, relay); if (connect) { relay.connect(); } } /** * Removes a relay from the pool. * @param relayUrl - The URL of the relay to remove. * @returns {boolean} True if the relay was removed, false if it was not found. */ public removeRelay(relayUrl: string): boolean { const relay = this.relays.get(relayUrl); if (relay) { relay.disconnect(); this.relays.delete(relayUrl); this.emit("relay:disconnect", relay); return true; } // remove the relay from the temporary relay timers const existingTimer = this.temporaryRelayTimers.get(relayUrl); if (existingTimer) { clearTimeout(existingTimer); this.temporaryRelayTimers.delete(relayUrl); } return false; } private handleRelayConnect(relayUrl: string) { this.debug(`Relay ${relayUrl} connected`); this.emit("relay:connect", this.relays.get(relayUrl)); if (this.stats().connected === this.relays.size) { this.emit("connect"); } } /** * Attempts to establish a connection to each relay in the pool. * * @async * @param {number} [timeoutMs] - Optional timeout in milliseconds for each connection attempt. * @returns {Promise<void>} A promise that resolves when all connection attempts have completed. * @throws {Error} If any of the connection attempts result in an error or timeout. */ public async connect(timeoutMs?: number): Promise<void> { const promises: Promise<void>[] = []; this.debug( `Connecting to ${this.relays.size} relays${ timeoutMs ? `, timeout ${timeoutMs}...` : "" }` ); for (const relay of this.relays.values()) { if (timeoutMs) { const timeoutPromise = new Promise<void>((_, reject) => { setTimeout( () => reject(`Timed out after ${timeoutMs}ms`), timeoutMs ); }); promises.push( Promise.race([relay.connect(), timeoutPromise]).catch( (e) => { this.debug( `Failed to connect to relay ${relay.url}: ${e}` ); } ) ); } else { promises.push(relay.connect()); } } // If we are running with a timeout, check if we need to emit a `connect` event // in case some, but not all, relays were connected if (timeoutMs) { setTimeout(() => { const allConnected = this.stats().connected === this.relays.size; const someConnected = this.stats().connected > 0; if (!allConnected && someConnected) { this.emit("connect"); } }, timeoutMs); } await Promise.all(promises); } private handleFlapping(relay: NDKRelay) { this.debug(`Relay ${relay.url} is flapping`); // TODO: Be smarter about this. this.relays.delete(relay.url); this.emit("flapping", relay); } public size(): number { return this.relays.size; } /** * Returns the status of each relay in the pool. * @returns {NDKPoolStats} An object containing the number of relays in each status. */ public stats(): NDKPoolStats { const stats: NDKPoolStats = { total: 0, connected: 0, disconnected: 0, connecting: 0, }; for (const relay of this.relays.values()) { stats.total++; if (relay.status === NDKRelayStatus.CONNECTED) { stats.connected++; } else if (relay.status === NDKRelayStatus.DISCONNECTED) { stats.disconnected++; } else if (relay.status === NDKRelayStatus.CONNECTING) { stats.connecting++; } } return stats; } public connectedRelays(): NDKRelay[] { return Array.from(this.relays.values()).filter( (relay) => relay.status === NDKRelayStatus.CONNECTED ); } /** * Get a list of all relay urls in the pool. */ public urls(): string[] { return Array.from(this.relays.keys()); } }
src/relay/pool/index.ts
nostr-dev-kit-ndk-ece64e1
[ { "filename": "src/relay/sets/index.ts", "retrieved_chunk": " public constructor(relays: Set<NDKRelay>, ndk: NDK) {\n this.relays = relays;\n this.ndk = ndk;\n this.debug = ndk.debug.extend(\"relayset\");\n }\n /**\n * Adds a relay to this set.\n */\n public addRelay(relay: NDKRelay) {\n this.relays.add(relay);", "score": 0.8654800057411194 }, { "filename": "src/relay/sets/index.ts", "retrieved_chunk": " if (relay.status === NDKRelayStatus.CONNECTED) {\n // If the relay is already connected, subscribe immediately\n this.subscribeOnRelay(relay, subscription);\n } else {\n // If the relay is not connected, add a one-time listener to wait for the 'connected' event\n const connectedListener = () => {\n this.debug(\n \"new relay coming online for active subscription\",\n {\n relay: relay.url,", "score": 0.8538866639137268 }, { "filename": "src/relay/index.ts", "retrieved_chunk": " } else {\n this.connect();\n }\n }\n get status(): NDKRelayStatus {\n return this._status;\n }\n /**\n * Connects to the relay.\n */", "score": 0.846250057220459 }, { "filename": "src/relay/index.ts", "retrieved_chunk": " this.updateConnectionStats.connected();\n this._status = NDKRelayStatus.CONNECTED;\n this.emit(\"connect\");\n });\n this.relay.on(\"disconnect\", () => {\n this.updateConnectionStats.disconnected();\n if (this._status === NDKRelayStatus.CONNECTED) {\n this._status = NDKRelayStatus.DISCONNECTED;\n this.handleReconnection();\n }", "score": 0.8456366062164307 }, { "filename": "src/relay/sets/calculate.ts", "retrieved_chunk": "): NDKRelaySet {\n const relays: Set<NDKRelay> = new Set();\n ndk.pool?.relays.forEach((relay) => {\n if (!relay.complaining) {\n relays.add(relay);\n } else {\n ndk.debug(`Relay ${relay.url} is complaining, not adding to set`);\n }\n });\n return new NDKRelaySet(relays, ndk);", "score": 0.8430570363998413 } ]
typescript
relay.on("notice", (relay, notice) => this.emit("notice", relay, notice) );
import { convert } from 'convert-gitmoji'; import { partition, groupBy, capitalize, join } from './shared'; import type { Reference, Commit, ResolvedChangelogOptions } from './types'; const emojisRE = /([\u2700-\u27BF]|[\uE000-\uF8FF]|\uD83C[\uDC00-\uDFFF]|\uD83D[\uDC00-\uDFFF]|[\u2011-\u26FF]|\uD83E[\uDD10-\uDDFF])/g; function formatReferences(references: Reference[], github: string, type: 'issues' | 'hash'): string { const refs = references .filter(i => { if (type === 'issues') { return i.type === 'issue' || i.type === 'pull-request'; } return i.type === 'hash'; }) .map(ref => { if (!github) { return ref.value; } if (ref.type === 'pull-request' || ref.type === 'issue') { return `https://github.com/${github}/issues/${ref.value.slice(1)}`; } return `[<samp>(${ref.value.slice(0, 5)})</samp>](https://github.com/${github}/commit/${ref.value})`; }); const referencesString = join(refs).trim(); if (type === 'issues') { return referencesString && `in ${referencesString}`; } return referencesString; } function formatLine(commit: Commit, options: ResolvedChangelogOptions) { const prRefs = formatReferences(commit.references, options.repo.repo || '', 'issues'); const hashRefs = formatReferences(commit.references, options.repo.repo || '', 'hash'); let authors = join([ ...new Set(commit.resolvedAuthors?.map(i => (i.login ? `@${i.login}` : `**${i.name}**`))) ])?.trim(); if (authors) { authors = `by ${authors}`; } let refs = [authors, prRefs, hashRefs].filter(i => i?.trim()).join(' '); if (refs) { refs = `&nbsp;-&nbsp; ${refs}`; } const description = options.capitalize ? capitalize(commit.description) : commit.description; return [description, refs].filter(i => i?.trim()).join(' '); } function formatTitle(name: string, options: ResolvedChangelogOptions) { let $name = name.trim(); if (!options.emoji) { $name = name.replace(emojisRE, '').trim(); } return `### &nbsp;&nbsp;&nbsp;${$name}`; } function formatSection(commits: Commit[], sectionName: string, options: ResolvedChangelogOptions) { if (!commits.length) { return []; } const lines: string[] = ['', formatTitle(sectionName, options), '']; const scopes = groupBy(commits, 'scope'); let useScopeGroup = options.group; // group scopes only when one of the scope have multiple commits if (!Object.entries(scopes).some(([k, v]) => k && v.length > 1)) { useScopeGroup = false; } Object.keys(scopes) .sort() .forEach(scope => { let padding = ''; let prefix = ''; const scopeText = `**${options.scopeMap[scope] || scope}**`; if (scope && (useScopeGroup === true || (useScopeGroup === 'multiple' && scopes[scope].length > 1))) { lines.push(`- ${scopeText}:`); padding = ' '; } else if (scope) { prefix = `${scopeText}: `; } lines.push(...scopes[scope].reverse
().map(commit => `${padding}- ${prefix}${formatLine(commit, options)}`));
}); return lines; } export function generateMarkdown(commits: Commit[], options: ResolvedChangelogOptions) { const lines: string[] = []; const [breaking, changes] = partition(commits, c => c.isBreaking); const group = groupBy(changes, 'type'); lines.push(...formatSection(breaking, options.titles.breakingChanges!, options)); for (const type of Object.keys(options.types)) { const items = group[type] || []; lines.push(...formatSection(items, options.types[type].title, options)); } if (!lines.length) { lines.push('*No significant changes*'); } const url = `https://github.com/${options.repo.repo!}/compare/${options.from}...${options.to}`; lines.push('', `##### &nbsp;&nbsp;&nbsp;&nbsp;[View changes on GitHub](${url})`); return convert(lines.join('\n').trim(), true); }
src/markdown.ts
soybeanjs-githublogen-0932953
[ { "filename": "src/git.ts", "retrieved_chunk": " `${from ? `${from}...` : ''}${to}`,\n '--pretty=\"----%n%s|%h|%an|%ae%n%b\"',\n '--name-status'\n ]);\n return r\n .split('----\\n')\n .splice(1)\n .map(line => {\n const [firstLine, ..._body] = line.split('\\n');\n const [message, shortHash, authorName, authorEmail] = firstLine.split('|');", "score": 0.792209267616272 }, { "filename": "src/generate.ts", "retrieved_chunk": " if (resolved.contributors) {\n await resolveAuthors(commits, resolved);\n }\n const md = generateMarkdown(commits, resolved);\n return { config: resolved, md, commits };\n}", "score": 0.790418267250061 }, { "filename": "src/cli.ts", "retrieved_chunk": " const { config, md, commits } = await generate(cwd, args as unknown as ChangelogOptions);\n const markdown = md.replace(/&nbsp;/g, '');\n console.log(cyan(config.from) + dim(' -> ') + blue(config.to) + dim(` (${commits.length} commits)`));\n console.log(dim('--------------'));\n console.log();\n console.log(markdown);\n console.log();\n console.log(dim('--------------'));\n if (config.dry) {\n console.log(yellow('Dry run. Release skipped.'));", "score": 0.790313720703125 }, { "filename": "src/github.ts", "retrieved_chunk": " if (idx === 0) {\n info.commits.push(commit.shortHash);\n }\n return info;\n })\n .filter(notNullish);\n });\n const authors = Array.from(map.values());\n const resolved = await Promise.all(authors.map(info => resolveAuthorInfo(options, info)));\n const loginSet = new Set<string>();", "score": 0.7862780690193176 }, { "filename": "src/github.ts", "retrieved_chunk": " }\n return info;\n}\nexport async function resolveAuthors(commits: Commit[], options: ChangelogOptions) {\n const map = new Map<string, AuthorInfo>();\n commits.forEach(commit => {\n commit.resolvedAuthors = commit.authors\n .map((a, idx) => {\n if (!a.email || !a.name) {\n return null;", "score": 0.7816011309623718 } ]
typescript
().map(commit => `${padding}- ${prefix}${formatLine(commit, options)}`));
import { notNullish } from './shared'; import type { GitCommit, RawGitCommit, GitCommitAuthor, ChangelogConfig, Reference } from './types'; // https://www.conventionalcommits.org/en/v1.0.0/ // https://regex101.com/r/FSfNvA/1 const ConventionalCommitRegex = /(?<type>[a-z]+)(\((?<scope>.+)\))?(?<breaking>!)?: (?<description>.+)/i; const CoAuthoredByRegex = /co-authored-by:\s*(?<name>.+)(<(?<email>.+)>)/gim; const PullRequestRE = /\([a-z]*(#\d+)\s*\)/gm; const IssueRE = /(#\d+)/gm; export function parseGitCommit(commit: RawGitCommit, config: ChangelogConfig): GitCommit | null { const match = commit.message.match(ConventionalCommitRegex); if (!match?.groups) { return null; } const type = match.groups.type; let scope = match.groups.scope || ''; scope = config.scopeMap[scope] || scope; const isBreaking = Boolean(match.groups.breaking); let description = match.groups.description; // Extract references from message const references: Reference[] = []; for (const m of description.matchAll(PullRequestRE)) { references.push({ type: 'pull-request', value: m[1] }); } for (const m of description.matchAll(IssueRE)) { if (!references.some(i => i.value === m[1])) { references.push({ type: 'issue', value: m[1] }); } } references.push({ value: commit.shortHash, type: 'hash' }); // Remove references and normalize description = description.replace(PullRequestRE, '').trim(); // Find all authors
const authors: GitCommitAuthor[] = [commit.author];
const matchs = commit.body.matchAll(CoAuthoredByRegex); for (const $match of matchs) { const { name = '', email = '' } = $match.groups || {}; const author: GitCommitAuthor = { name: name.trim(), email: email.trim() }; authors.push(author); } return { ...commit, authors, description, type, scope, references, isBreaking }; } export function parseCommits(commits: RawGitCommit[], config: ChangelogConfig): GitCommit[] { return commits.map(commit => parseGitCommit(commit, config)).filter(notNullish); }
src/parse.ts
soybeanjs-githublogen-0932953
[ { "filename": "src/markdown.ts", "retrieved_chunk": " const hashRefs = formatReferences(commit.references, options.repo.repo || '', 'hash');\n let authors = join([\n ...new Set(commit.resolvedAuthors?.map(i => (i.login ? `@${i.login}` : `**${i.name}**`)))\n ])?.trim();\n if (authors) {\n authors = `by ${authors}`;\n }\n let refs = [authors, prRefs, hashRefs].filter(i => i?.trim()).join(' ');\n if (refs) {\n refs = `&nbsp;-&nbsp; ${refs}`;", "score": 0.8596552014350891 }, { "filename": "src/markdown.ts", "retrieved_chunk": "import { convert } from 'convert-gitmoji';\nimport { partition, groupBy, capitalize, join } from './shared';\nimport type { Reference, Commit, ResolvedChangelogOptions } from './types';\nconst emojisRE =\n /([\\u2700-\\u27BF]|[\\uE000-\\uF8FF]|\\uD83C[\\uDC00-\\uDFFF]|\\uD83D[\\uDC00-\\uDFFF]|[\\u2011-\\u26FF]|\\uD83E[\\uDD10-\\uDDFF])/g;\nfunction formatReferences(references: Reference[], github: string, type: 'issues' | 'hash'): string {\n const refs = references\n .filter(i => {\n if (type === 'issues') {\n return i.type === 'issue' || i.type === 'pull-request';", "score": 0.8393716216087341 }, { "filename": "src/github.ts", "retrieved_chunk": " if (idx === 0) {\n info.commits.push(commit.shortHash);\n }\n return info;\n })\n .filter(notNullish);\n });\n const authors = Array.from(map.values());\n const resolved = await Promise.all(authors.map(info => resolveAuthorInfo(options, info)));\n const loginSet = new Set<string>();", "score": 0.8306057453155518 }, { "filename": "src/github.ts", "retrieved_chunk": " }\n return info;\n}\nexport async function resolveAuthors(commits: Commit[], options: ChangelogOptions) {\n const map = new Map<string, AuthorInfo>();\n commits.forEach(commit => {\n commit.resolvedAuthors = commit.authors\n .map((a, idx) => {\n if (!a.email || !a.name) {\n return null;", "score": 0.8223334550857544 }, { "filename": "src/markdown.ts", "retrieved_chunk": " return `[<samp>(${ref.value.slice(0, 5)})</samp>](https://github.com/${github}/commit/${ref.value})`;\n });\n const referencesString = join(refs).trim();\n if (type === 'issues') {\n return referencesString && `in ${referencesString}`;\n }\n return referencesString;\n}\nfunction formatLine(commit: Commit, options: ResolvedChangelogOptions) {\n const prRefs = formatReferences(commit.references, options.repo.repo || '', 'issues');", "score": 0.8206360936164856 } ]
typescript
const authors: GitCommitAuthor[] = [commit.author];
import { convert } from 'convert-gitmoji'; import { partition, groupBy, capitalize, join } from './shared'; import type { Reference, Commit, ResolvedChangelogOptions } from './types'; const emojisRE = /([\u2700-\u27BF]|[\uE000-\uF8FF]|\uD83C[\uDC00-\uDFFF]|\uD83D[\uDC00-\uDFFF]|[\u2011-\u26FF]|\uD83E[\uDD10-\uDDFF])/g; function formatReferences(references: Reference[], github: string, type: 'issues' | 'hash'): string { const refs = references .filter(i => { if (type === 'issues') { return i.type === 'issue' || i.type === 'pull-request'; } return i.type === 'hash'; }) .map(ref => { if (!github) { return ref.value; } if (ref.type === 'pull-request' || ref.type === 'issue') { return `https://github.com/${github}/issues/${ref.value.slice(1)}`; } return `[<samp>(${ref.value.slice(0, 5)})</samp>](https://github.com/${github}/commit/${ref.value})`; }); const referencesString = join(refs).trim(); if (type === 'issues') { return referencesString && `in ${referencesString}`; } return referencesString; } function formatLine(commit: Commit, options: ResolvedChangelogOptions) { const prRefs = formatReferences(commit.references, options.repo.repo || '', 'issues'); const hashRefs = formatReferences(commit.references, options.repo.repo || '', 'hash'); let authors = join([ ...new Set(commit.resolvedAuthors?.map(i => (i.login ? `@${i.login}` : `**${i.name}**`))) ])?.trim(); if (authors) { authors = `by ${authors}`; } let refs = [authors, prRefs, hashRefs].filter(i => i?.trim()).join(' '); if (refs) { refs = `&nbsp;-&nbsp; ${refs}`; } const description = options.capitalize ? capitalize(commit.description) : commit.description; return [description, refs].filter(i => i?.trim()).join(' '); } function formatTitle(name: string, options: ResolvedChangelogOptions) { let $name = name.trim(); if (!options.emoji) { $name = name.replace(emojisRE, '').trim(); } return `### &nbsp;&nbsp;&nbsp;${$name}`; } function formatSection(commits: Commit[], sectionName: string, options: ResolvedChangelogOptions) { if (!commits.length) { return []; } const lines: string[] = ['', formatTitle(sectionName, options), '']; const scopes = groupBy(commits, 'scope'); let useScopeGroup = options.group; // group scopes only when one of the scope have multiple commits if (!Object.entries(scopes).some(([k, v]) => k && v.length > 1)) { useScopeGroup = false; } Object.keys(scopes) .sort() .forEach(scope => { let padding = ''; let prefix = ''; const scopeText = `**${options.scopeMap[scope] || scope}**`; if (scope && (useScopeGroup === true || (useScopeGroup === 'multiple' && scopes[scope].length > 1))) { lines.push(`- ${scopeText}:`); padding = ' '; } else if (scope) { prefix = `${scopeText}: `; } lines.push(...scopes[scope].reverse().map(commit => `${padding}- ${prefix}${formatLine(commit, options)}`)); }); return lines; } export function generateMarkdown(commits: Commit[], options: ResolvedChangelogOptions) { const lines: string[] = []; const [breaking, changes] = partition(commits
, c => c.isBreaking);
const group = groupBy(changes, 'type'); lines.push(...formatSection(breaking, options.titles.breakingChanges!, options)); for (const type of Object.keys(options.types)) { const items = group[type] || []; lines.push(...formatSection(items, options.types[type].title, options)); } if (!lines.length) { lines.push('*No significant changes*'); } const url = `https://github.com/${options.repo.repo!}/compare/${options.from}...${options.to}`; lines.push('', `##### &nbsp;&nbsp;&nbsp;&nbsp;[View changes on GitHub](${url})`); return convert(lines.join('\n').trim(), true); }
src/markdown.ts
soybeanjs-githublogen-0932953
[ { "filename": "src/generate.ts", "retrieved_chunk": "import { getGitDiff } from './git';\nimport { generateMarkdown } from './markdown';\nimport { resolveAuthors } from './github';\nimport { resolveConfig } from './config';\nimport { parseCommits } from './parse';\nimport type { ChangelogOptions } from './types';\nexport async function generate(cwd: string, options: ChangelogOptions) {\n const resolved = await resolveConfig(cwd, options);\n const rawCommits = await getGitDiff(resolved.from, resolved.to);\n const commits = parseCommits(rawCommits, resolved);", "score": 0.8512902855873108 }, { "filename": "src/generate.ts", "retrieved_chunk": " if (resolved.contributors) {\n await resolveAuthors(commits, resolved);\n }\n const md = generateMarkdown(commits, resolved);\n return { config: resolved, md, commits };\n}", "score": 0.8372663259506226 }, { "filename": "src/cli.ts", "retrieved_chunk": " const { config, md, commits } = await generate(cwd, args as unknown as ChangelogOptions);\n const markdown = md.replace(/&nbsp;/g, '');\n console.log(cyan(config.from) + dim(' -> ') + blue(config.to) + dim(` (${commits.length} commits)`));\n console.log(dim('--------------'));\n console.log();\n console.log(markdown);\n console.log();\n console.log(dim('--------------'));\n if (config.dry) {\n console.log(yellow('Dry run. Release skipped.'));", "score": 0.8352389335632324 }, { "filename": "src/parse.ts", "retrieved_chunk": " };\n}\nexport function parseCommits(commits: RawGitCommit[], config: ChangelogConfig): GitCommit[] {\n return commits.map(commit => parseGitCommit(commit, config)).filter(notNullish);\n}", "score": 0.8340779542922974 }, { "filename": "src/github.ts", "retrieved_chunk": " }\n return info;\n}\nexport async function resolveAuthors(commits: Commit[], options: ChangelogOptions) {\n const map = new Map<string, AuthorInfo>();\n commits.forEach(commit => {\n commit.resolvedAuthors = commit.authors\n .map((a, idx) => {\n if (!a.email || !a.name) {\n return null;", "score": 0.8157557845115662 } ]
typescript
, c => c.isBreaking);
import { readPackageJSON } from 'pkg-types'; import type { Reference, ChangelogConfig, RepoProvider, RepoConfig } from './types'; import { getGitRemoteURL } from './git'; const providerToRefSpec: Record<RepoProvider, Record<Reference['type'], string>> = { github: { 'pull-request': 'pull', hash: 'commit', issue: 'issues' }, gitlab: { 'pull-request': 'merge_requests', hash: 'commit', issue: 'issues' }, bitbucket: { 'pull-request': 'pull-requests', hash: 'commit', issue: 'issues' } }; const providerToDomain: Record<RepoProvider, string> = { github: 'github.com', gitlab: 'gitlab.com', bitbucket: 'bitbucket.org' }; const domainToProvider: Record<string, RepoProvider> = { 'github.com': 'github', 'gitlab.com': 'gitlab', 'bitbucket.org': 'bitbucket' }; // https://regex101.com/r/NA4Io6/1 const providerURLRegex = /^(?:(?<user>\w+)@)?(?:(?<provider>[^/:]+):)?(?<repo>\w+\/\w+)(?:\.git)?$/; function baseUrl(config: RepoConfig) { return `https://${config.domain}/${config.repo}`; } export function formatReference(ref: Reference, repo?: RepoConfig) { if (!repo?.provider || !(repo.provider in providerToRefSpec)) { return ref.value; } const refSpec = providerToRefSpec[repo.provider]; return `[${ref.value}](${baseUrl(repo)}/${refSpec[ref.type]}/${ref.value.replace(/^#/, '')})`; }
export function formatCompareChanges(v: string, config: ChangelogConfig) {
const part = config.repo?.provider === 'bitbucket' ? 'branches/compare' : 'compare'; return `[compare changes](${baseUrl(config.repo)}/${part}/${config.from}...${v || config.to})`; } export async function resolveRepoConfig(cwd: string) { // Try closest package.json const pkg = await readPackageJSON(cwd).catch(() => {}); if (pkg && pkg.repository) { const url = typeof pkg.repository === 'string' ? pkg.repository : pkg.repository.url; return getRepoConfig(url); } const gitRemote = await getGitRemoteURL(cwd).catch(() => {}); if (gitRemote) { return getRepoConfig(gitRemote); } return {}; } export function getRepoConfig(repoUrl = ''): RepoConfig { let provider: RepoProvider | undefined; let repo: string | undefined; let domain: string | undefined; let url: URL | undefined; try { url = new URL(repoUrl); } catch {} const m = repoUrl.match(providerURLRegex)?.groups ?? {}; if (m.repo && m.provider) { repo = m.repo; provider = m.provider in domainToProvider ? domainToProvider[m.provider] : (m.provider as RepoProvider); domain = provider in providerToDomain ? providerToDomain[provider] : provider; } else if (url) { domain = url.hostname; repo = url.pathname .split('/') .slice(1, 3) .join('/') .replace(/\.git$/, ''); provider = domainToProvider[domain]; } else if (m.repo) { repo = m.repo; provider = 'github'; domain = providerToDomain[provider]; } return { provider, repo, domain }; }
src/repo.ts
soybeanjs-githublogen-0932953
[ { "filename": "src/markdown.ts", "retrieved_chunk": " return `[<samp>(${ref.value.slice(0, 5)})</samp>](https://github.com/${github}/commit/${ref.value})`;\n });\n const referencesString = join(refs).trim();\n if (type === 'issues') {\n return referencesString && `in ${referencesString}`;\n }\n return referencesString;\n}\nfunction formatLine(commit: Commit, options: ResolvedChangelogOptions) {\n const prRefs = formatReferences(commit.references, options.repo.repo || '', 'issues');", "score": 0.8441781997680664 }, { "filename": "src/markdown.ts", "retrieved_chunk": " }\n return i.type === 'hash';\n })\n .map(ref => {\n if (!github) {\n return ref.value;\n }\n if (ref.type === 'pull-request' || ref.type === 'issue') {\n return `https://github.com/${github}/issues/${ref.value.slice(1)}`;\n }", "score": 0.8249846696853638 }, { "filename": "src/markdown.ts", "retrieved_chunk": " const url = `https://github.com/${options.repo.repo!}/compare/${options.from}...${options.to}`;\n lines.push('', `##### &nbsp;&nbsp;&nbsp;&nbsp;[View changes on GitHub](${url})`);\n return convert(lines.join('\\n').trim(), true);\n}", "score": 0.8149353861808777 }, { "filename": "src/markdown.ts", "retrieved_chunk": " const hashRefs = formatReferences(commit.references, options.repo.repo || '', 'hash');\n let authors = join([\n ...new Set(commit.resolvedAuthors?.map(i => (i.login ? `@${i.login}` : `**${i.name}**`)))\n ])?.trim();\n if (authors) {\n authors = `by ${authors}`;\n }\n let refs = [authors, prRefs, hashRefs].filter(i => i?.trim()).join(' ');\n if (refs) {\n refs = `&nbsp;-&nbsp; ${refs}`;", "score": 0.8145809173583984 }, { "filename": "src/git.ts", "retrieved_chunk": " return execCommand('git', [`--work-tree=${cwd}`, 'remote', 'get-url', remote]);\n}\nexport function getGitPushUrl(config: RepoConfig, token?: string) {\n if (!token) return null;\n return `https://${token}@${config.domain}/${config.repo}`;\n}", "score": 0.8085442185401917 } ]
typescript
export function formatCompareChanges(v: string, config: ChangelogConfig) {
import { notNullish } from './shared'; import type { GitCommit, RawGitCommit, GitCommitAuthor, ChangelogConfig, Reference } from './types'; // https://www.conventionalcommits.org/en/v1.0.0/ // https://regex101.com/r/FSfNvA/1 const ConventionalCommitRegex = /(?<type>[a-z]+)(\((?<scope>.+)\))?(?<breaking>!)?: (?<description>.+)/i; const CoAuthoredByRegex = /co-authored-by:\s*(?<name>.+)(<(?<email>.+)>)/gim; const PullRequestRE = /\([a-z]*(#\d+)\s*\)/gm; const IssueRE = /(#\d+)/gm; export function parseGitCommit(commit: RawGitCommit, config: ChangelogConfig): GitCommit | null { const match = commit.message.match(ConventionalCommitRegex); if (!match?.groups) { return null; } const type = match.groups.type; let scope = match.groups.scope || ''; scope = config.scopeMap[scope] || scope; const isBreaking = Boolean(match.groups.breaking); let description = match.groups.description; // Extract references from message const references: Reference[] = []; for (const m of description.matchAll(PullRequestRE)) { references.push({ type: 'pull-request', value: m[1] }); } for (const m of description.matchAll(IssueRE)) { if (!references.some(i => i.value === m[1])) { references.push({ type: 'issue', value: m[1] }); } } references.push({ value: commit.shortHash, type: 'hash' }); // Remove references and normalize description = description.replace(PullRequestRE, '').trim(); // Find all authors const authors: GitCommitAuthor[] = [commit.author]; const matchs = commit.body.matchAll(CoAuthoredByRegex); for (const $match of matchs) { const { name = '', email = '' } = $match.groups || {}; const author: GitCommitAuthor = { name: name.trim(), email: email.trim() }; authors.push(author); } return { ...commit, authors, description, type, scope, references, isBreaking }; } export function parseCommits(commits: RawGitCommit[], config: ChangelogConfig): GitCommit[] { return commits
.map(commit => parseGitCommit(commit, config)).filter(notNullish);
}
src/parse.ts
soybeanjs-githublogen-0932953
[ { "filename": "src/markdown.ts", "retrieved_chunk": " padding = ' ';\n } else if (scope) {\n prefix = `${scopeText}: `;\n }\n lines.push(...scopes[scope].reverse().map(commit => `${padding}- ${prefix}${formatLine(commit, options)}`));\n });\n return lines;\n}\nexport function generateMarkdown(commits: Commit[], options: ResolvedChangelogOptions) {\n const lines: string[] = [];", "score": 0.8291512131690979 }, { "filename": "src/github.ts", "retrieved_chunk": " }\n return info;\n}\nexport async function resolveAuthors(commits: Commit[], options: ChangelogOptions) {\n const map = new Map<string, AuthorInfo>();\n commits.forEach(commit => {\n commit.resolvedAuthors = commit.authors\n .map((a, idx) => {\n if (!a.email || !a.name) {\n return null;", "score": 0.8249005079269409 }, { "filename": "src/markdown.ts", "retrieved_chunk": "}\nfunction formatSection(commits: Commit[], sectionName: string, options: ResolvedChangelogOptions) {\n if (!commits.length) {\n return [];\n }\n const lines: string[] = ['', formatTitle(sectionName, options), ''];\n const scopes = groupBy(commits, 'scope');\n let useScopeGroup = options.group;\n // group scopes only when one of the scope have multiple commits\n if (!Object.entries(scopes).some(([k, v]) => k && v.length > 1)) {", "score": 0.8230552673339844 }, { "filename": "src/generate.ts", "retrieved_chunk": " if (resolved.contributors) {\n await resolveAuthors(commits, resolved);\n }\n const md = generateMarkdown(commits, resolved);\n return { config: resolved, md, commits };\n}", "score": 0.8212543725967407 }, { "filename": "src/types.ts", "retrieved_chunk": " tag_name: string;\n name?: string;\n body?: string;\n draft?: boolean;\n prerelease?: boolean;\n}\nexport interface GitCommit extends RawGitCommit {\n description: string;\n type: string;\n scope: string;", "score": 0.820581316947937 } ]
typescript
.map(commit => parseGitCommit(commit, config)).filter(notNullish);
import type { RawGitCommit, RepoConfig } from './types'; export async function getGitHubRepo() { const url = await execCommand('git', ['config', '--get', 'remote.origin.url']); const match = url.match(/github\.com[\/:]([\w\d._-]+?)\/([\w\d._-]+?)(\.git)?$/i); if (!match) { throw new Error(`Can not parse GitHub repo from url ${url}`); } return `${match[1]}/${match[2]}`; } export async function getGitMainBranchName() { const main = await execCommand('git', ['rev-parse', '--abbrev-ref', 'HEAD']); return main; } export async function getCurrentGitBranch() { const result1 = await execCommand('git', ['tag', '--points-at', 'HEAD']); const main = getGitMainBranchName(); return result1 || main; } export async function isRepoShallow() { return (await execCommand('git', ['rev-parse', '--is-shallow-repository'])).trim() === 'true'; } export async function getLastGitTag(delta = 0) { const tags = await execCommand('git', ['--no-pager', 'tag', '-l', '--sort=creatordate']).then(r => r.split('\n')); return tags[tags.length + delta - 1]; } export async function isRefGitTag(to: string) { const { execa } = await import('execa'); try { await execa('git', ['show-ref', '--verify', `refs/tags/${to}`], { reject: true }); return true; } catch { return false; } } export function getFirstGitCommit() { return execCommand('git', ['rev-list', '--max-parents=0', 'HEAD']); } export function isPrerelease(version: string) { return !/^[^.]*[\d.]+$/.test(version); } async function execCommand(cmd: string, args: string[]) { const { execa } = await import('execa'); const res = await execa(cmd, args); return res.stdout.trim(); } export async function getGitDiff(from: string | undefined, to = 'HEAD'): Promise<RawGitCommit[]> { // https://git-scm.com/docs/pretty-formats const r = await execCommand('git', [ '--no-pager', 'log', `${from ? `${from}...` : ''}${to}`, '--pretty="----%n%s|%h|%an|%ae%n%b"', '--name-status' ]); return r .split('----\n') .splice(1) .map(line => { const [firstLine, ..._body] = line.split('\n'); const [message, shortHash, authorName, authorEmail] = firstLine.split('|'); const $r: RawGitCommit = { message, shortHash, author: { name: authorName, email: authorEmail }, body: _body.join('\n') }; return $r; }); } export function getGitRemoteURL(cwd: string, remote = 'origin') { return execCommand('git', [`--work-tree=${cwd}`, 'remote', 'get-url', remote]); }
export function getGitPushUrl(config: RepoConfig, token?: string) {
if (!token) return null; return `https://${token}@${config.domain}/${config.repo}`; }
src/git.ts
soybeanjs-githublogen-0932953
[ { "filename": "src/repo.ts", "retrieved_chunk": " const pkg = await readPackageJSON(cwd).catch(() => {});\n if (pkg && pkg.repository) {\n const url = typeof pkg.repository === 'string' ? pkg.repository : pkg.repository.url;\n return getRepoConfig(url);\n }\n const gitRemote = await getGitRemoteURL(cwd).catch(() => {});\n if (gitRemote) {\n return getRepoConfig(gitRemote);\n }\n return {};", "score": 0.8432960510253906 }, { "filename": "src/repo.ts", "retrieved_chunk": "}\nexport function getRepoConfig(repoUrl = ''): RepoConfig {\n let provider: RepoProvider | undefined;\n let repo: string | undefined;\n let domain: string | undefined;\n let url: URL | undefined;\n try {\n url = new URL(repoUrl);\n } catch {}\n const m = repoUrl.match(providerURLRegex)?.groups ?? {};", "score": 0.8210341930389404 }, { "filename": "src/repo.ts", "retrieved_chunk": "import { readPackageJSON } from 'pkg-types';\nimport type { Reference, ChangelogConfig, RepoProvider, RepoConfig } from './types';\nimport { getGitRemoteURL } from './git';\nconst providerToRefSpec: Record<RepoProvider, Record<Reference['type'], string>> = {\n github: { 'pull-request': 'pull', hash: 'commit', issue: 'issues' },\n gitlab: { 'pull-request': 'merge_requests', hash: 'commit', issue: 'issues' },\n bitbucket: {\n 'pull-request': 'pull-requests',\n hash: 'commit',\n issue: 'issues'", "score": 0.8141562938690186 }, { "filename": "src/repo.ts", "retrieved_chunk": " }\n const refSpec = providerToRefSpec[repo.provider];\n return `[${ref.value}](${baseUrl(repo)}/${refSpec[ref.type]}/${ref.value.replace(/^#/, '')})`;\n}\nexport function formatCompareChanges(v: string, config: ChangelogConfig) {\n const part = config.repo?.provider === 'bitbucket' ? 'branches/compare' : 'compare';\n return `[compare changes](${baseUrl(config.repo)}/${part}/${config.from}...${v || config.to})`;\n}\nexport async function resolveRepoConfig(cwd: string) {\n // Try closest package.json", "score": 0.8128013610839844 }, { "filename": "src/config.ts", "retrieved_chunk": "import { getCurrentGitBranch, getFirstGitCommit, getLastGitTag, isPrerelease } from './git';\nimport { resolveRepoConfig } from './repo';\nimport type { ChangelogOptions, ResolvedChangelogOptions } from './types';\nconst defaultConfig: ChangelogOptions = {\n cwd: process.cwd(),\n from: '',\n to: '',\n gitMainBranch: 'main',\n scopeMap: {},\n repo: {},", "score": 0.8094640970230103 } ]
typescript
export function getGitPushUrl(config: RepoConfig, token?: string) {
#!/usr/bin/env node import { blue, bold, cyan, dim, red, yellow } from 'kolorist'; import cac from 'cac'; import { version } from '../package.json'; import { generate } from './generate'; import { hasTagOnGitHub, sendRelease } from './github'; import { isRepoShallow } from './git'; import type { ChangelogOptions } from './types'; const cli = cac('githublogen'); cli .version(version) .option('-t, --token <path>', 'GitHub Token') .option('--from <ref>', 'From tag') .option('--to <ref>', 'To tag') .option('--github <path>', 'GitHub Repository, e.g. soybeanjs/githublogen') .option('--name <name>', 'Name of the release') .option('--contributors', 'Show contributors section') .option('--prerelease', 'Mark release as prerelease') .option('-d, --draft', 'Mark release as draft') .option('--output <path>', 'Output to file instead of sending to GitHub') .option('--capitalize', 'Should capitalize for each comment message') .option('--emoji', 'Use emojis in section titles', { default: true }) .option('--group', 'Nest commit messages under their scopes') .option('--dry', 'Dry run') .help(); cli.command('').action(async (args: any) => { try { console.log(); console.log(dim(`${bold('github')}logen `) + dim(`v${version}`)); const cwd = process.cwd(); const { config, md, commits } = await generate(cwd, args as unknown as ChangelogOptions); const markdown = md.replace(/&nbsp;/g, ''); console.log(cyan(config.from) + dim(' -> ') + blue(config.to) + dim(` (${commits.length} commits)`)); console.log(dim('--------------')); console.log(); console.log(markdown); console.log(); console.log(dim('--------------')); if (config.dry) { console.log(yellow('Dry run. Release skipped.')); return; } if (!(await hasTagOnGitHub(config.to, config))) { console.error(yellow(`Current ref "${bold(config.to)}" is not available as tags on GitHub. Release skipped.`)); process.exitCode = 1; return; } if (!
commits.length && (await isRepoShallow())) {
console.error( yellow( 'The repo seems to be clone shallowly, which make changelog failed to generate. You might want to specify `fetch-depth: 0` in your CI config.' ) ); process.exitCode = 1; return; } await sendRelease(config, md); } catch (e: any) { console.error(red(String(e))); if (e?.stack) { console.error(dim(e.stack?.split('\n').slice(1).join('\n'))); } process.exit(1); } }); cli.parse();
src/cli.ts
soybeanjs-githublogen-0932953
[ { "filename": "src/github.ts", "retrieved_chunk": " try {\n console.log(cyan(method === 'POST' ? 'Creating release notes...' : 'Updating release notes...'));\n const res = await $fetch(url, {\n method,\n body: JSON.stringify(body),\n headers\n });\n console.log(green(`Released on ${res.html_url}`));\n } catch (e) {\n console.log();", "score": 0.8362492918968201 }, { "filename": "src/github.ts", "retrieved_chunk": "import { $fetch } from 'ohmyfetch';\nimport { cyan, green, red, yellow } from 'kolorist';\nimport { notNullish } from './shared';\nimport type { AuthorInfo, ChangelogOptions, Commit } from './types';\nexport async function sendRelease(options: ChangelogOptions, content: string) {\n const headers = getHeaders(options);\n const github = options.repo.repo!;\n let url = `https://api.github.com/repos/${github}/releases`;\n let method = 'POST';\n try {", "score": 0.8264251351356506 }, { "filename": "src/config.ts", "retrieved_chunk": " overrides: options\n }).then(r => r.config || defaultConfig);\n config.from = config.from || (await getLastGitTag());\n config.to = config.to || (await getCurrentGitBranch());\n config.repo = await resolveRepoConfig(cwd);\n config.prerelease = config.prerelease ?? isPrerelease(config.to);\n if (config.to === config.from) {\n config.from = (await getLastGitTag(-1)) || (await getFirstGitCommit());\n }\n return config as ResolvedChangelogOptions;", "score": 0.8141474723815918 }, { "filename": "src/git.ts", "retrieved_chunk": " const main = await execCommand('git', ['rev-parse', '--abbrev-ref', 'HEAD']);\n return main;\n}\nexport async function getCurrentGitBranch() {\n const result1 = await execCommand('git', ['tag', '--points-at', 'HEAD']);\n const main = getGitMainBranchName();\n return result1 || main;\n}\nexport async function isRepoShallow() {\n return (await execCommand('git', ['rev-parse', '--is-shallow-repository'])).trim() === 'true';", "score": 0.8129023909568787 }, { "filename": "src/github.ts", "retrieved_chunk": " draft: options.draft || false,\n name: options.name || options.to,\n prerelease: options.prerelease,\n tag_name: options.to\n };\n const webUrl = `https://github.com/${github}/releases/new?title=${encodeURIComponent(\n String(body.name)\n )}&body=${encodeURIComponent(String(body.body))}&tag=${encodeURIComponent(String(options.to))}&prerelease=${\n options.prerelease\n }`;", "score": 0.8099390268325806 } ]
typescript
commits.length && (await isRepoShallow())) {
import { readPackageJSON } from 'pkg-types'; import type { Reference, ChangelogConfig, RepoProvider, RepoConfig } from './types'; import { getGitRemoteURL } from './git'; const providerToRefSpec: Record<RepoProvider, Record<Reference['type'], string>> = { github: { 'pull-request': 'pull', hash: 'commit', issue: 'issues' }, gitlab: { 'pull-request': 'merge_requests', hash: 'commit', issue: 'issues' }, bitbucket: { 'pull-request': 'pull-requests', hash: 'commit', issue: 'issues' } }; const providerToDomain: Record<RepoProvider, string> = { github: 'github.com', gitlab: 'gitlab.com', bitbucket: 'bitbucket.org' }; const domainToProvider: Record<string, RepoProvider> = { 'github.com': 'github', 'gitlab.com': 'gitlab', 'bitbucket.org': 'bitbucket' }; // https://regex101.com/r/NA4Io6/1 const providerURLRegex = /^(?:(?<user>\w+)@)?(?:(?<provider>[^/:]+):)?(?<repo>\w+\/\w+)(?:\.git)?$/; function baseUrl(config: RepoConfig) { return `https://${config.domain}/${config.repo}`; } export function formatReference(ref: Reference, repo?: RepoConfig) { if (!repo?.provider || !(repo.provider in providerToRefSpec)) { return ref.value; } const refSpec = providerToRefSpec[repo.provider]; return `[${ref.value}](${baseUrl(repo)}/${refSpec[ref.type]}/${ref.value.replace(/^#/, '')})`; } export function formatCompareChanges(v: string, config: ChangelogConfig) { const part = config.repo?.provider === 'bitbucket' ? 'branches/compare' : 'compare'; return `[compare changes](${baseUrl(config.repo)}/${part}/${config.from}...${v || config.to})`; } export async function resolveRepoConfig(cwd: string) { // Try closest package.json const pkg = await readPackageJSON(cwd).catch(() => {}); if (pkg && pkg.repository) { const url = typeof pkg.repository === 'string' ? pkg.repository : pkg.repository.url; return getRepoConfig(url); }
const gitRemote = await getGitRemoteURL(cwd).catch(() => {});
if (gitRemote) { return getRepoConfig(gitRemote); } return {}; } export function getRepoConfig(repoUrl = ''): RepoConfig { let provider: RepoProvider | undefined; let repo: string | undefined; let domain: string | undefined; let url: URL | undefined; try { url = new URL(repoUrl); } catch {} const m = repoUrl.match(providerURLRegex)?.groups ?? {}; if (m.repo && m.provider) { repo = m.repo; provider = m.provider in domainToProvider ? domainToProvider[m.provider] : (m.provider as RepoProvider); domain = provider in providerToDomain ? providerToDomain[provider] : provider; } else if (url) { domain = url.hostname; repo = url.pathname .split('/') .slice(1, 3) .join('/') .replace(/\.git$/, ''); provider = domainToProvider[domain]; } else if (m.repo) { repo = m.repo; provider = 'github'; domain = providerToDomain[provider]; } return { provider, repo, domain }; }
src/repo.ts
soybeanjs-githublogen-0932953
[ { "filename": "src/git.ts", "retrieved_chunk": " return execCommand('git', [`--work-tree=${cwd}`, 'remote', 'get-url', remote]);\n}\nexport function getGitPushUrl(config: RepoConfig, token?: string) {\n if (!token) return null;\n return `https://${token}@${config.domain}/${config.repo}`;\n}", "score": 0.8634121417999268 }, { "filename": "src/config.ts", "retrieved_chunk": "import { getCurrentGitBranch, getFirstGitCommit, getLastGitTag, isPrerelease } from './git';\nimport { resolveRepoConfig } from './repo';\nimport type { ChangelogOptions, ResolvedChangelogOptions } from './types';\nconst defaultConfig: ChangelogOptions = {\n cwd: process.cwd(),\n from: '',\n to: '',\n gitMainBranch: 'main',\n scopeMap: {},\n repo: {},", "score": 0.858902096748352 }, { "filename": "src/config.ts", "retrieved_chunk": " overrides: options\n }).then(r => r.config || defaultConfig);\n config.from = config.from || (await getLastGitTag());\n config.to = config.to || (await getCurrentGitBranch());\n config.repo = await resolveRepoConfig(cwd);\n config.prerelease = config.prerelease ?? isPrerelease(config.to);\n if (config.to === config.from) {\n config.from = (await getLastGitTag(-1)) || (await getFirstGitCommit());\n }\n return config as ResolvedChangelogOptions;", "score": 0.8544005155563354 }, { "filename": "src/git.ts", "retrieved_chunk": "import type { RawGitCommit, RepoConfig } from './types';\nexport async function getGitHubRepo() {\n const url = await execCommand('git', ['config', '--get', 'remote.origin.url']);\n const match = url.match(/github\\.com[\\/:]([\\w\\d._-]+?)\\/([\\w\\d._-]+?)(\\.git)?$/i);\n if (!match) {\n throw new Error(`Can not parse GitHub repo from url ${url}`);\n }\n return `${match[1]}/${match[2]}`;\n}\nexport async function getGitMainBranchName() {", "score": 0.850438117980957 }, { "filename": "src/config.ts", "retrieved_chunk": " output: 'CHANGELOG.md',\n contributors: true,\n capitalize: true,\n group: true\n};\nexport async function resolveConfig(cwd: string, options: ChangelogOptions) {\n const { loadConfig } = await import('c12');\n const config = await loadConfig<ChangelogOptions>({\n name: 'githublogen',\n defaults: defaultConfig,", "score": 0.838422954082489 } ]
typescript
const gitRemote = await getGitRemoteURL(cwd).catch(() => {});
import { convert } from 'convert-gitmoji'; import { partition, groupBy, capitalize, join } from './shared'; import type { Reference, Commit, ResolvedChangelogOptions } from './types'; const emojisRE = /([\u2700-\u27BF]|[\uE000-\uF8FF]|\uD83C[\uDC00-\uDFFF]|\uD83D[\uDC00-\uDFFF]|[\u2011-\u26FF]|\uD83E[\uDD10-\uDDFF])/g; function formatReferences(references: Reference[], github: string, type: 'issues' | 'hash'): string { const refs = references .filter(i => { if (type === 'issues') { return i.type === 'issue' || i.type === 'pull-request'; } return i.type === 'hash'; }) .map(ref => { if (!github) { return ref.value; } if (ref.type === 'pull-request' || ref.type === 'issue') { return `https://github.com/${github}/issues/${ref.value.slice(1)}`; } return `[<samp>(${ref.value.slice(0, 5)})</samp>](https://github.com/${github}/commit/${ref.value})`; }); const referencesString = join(refs).trim(); if (type === 'issues') { return referencesString && `in ${referencesString}`; } return referencesString; } function formatLine(commit: Commit, options: ResolvedChangelogOptions) { const prRefs = formatReferences(commit.references, options.repo.repo || '', 'issues'); const hashRefs = formatReferences(commit.references, options.repo.repo || '', 'hash'); let authors = join([ ...new Set(commit.resolvedAuthors?.map(i => (i.login ? `@${i.login}` : `**${i.name}**`))) ])?.trim(); if (authors) { authors = `by ${authors}`; } let refs = [authors, prRefs, hashRefs].filter(i => i?.trim()).join(' '); if (refs) { refs = `&nbsp;-&nbsp; ${refs}`; } const description = options.capitalize ? capitalize(commit.description) : commit.description; return [description, refs].filter(i => i?.trim()).join(' '); } function formatTitle(name: string, options: ResolvedChangelogOptions) { let $name = name.trim(); if (!options.emoji) { $name = name.replace(emojisRE, '').trim(); } return `### &nbsp;&nbsp;&nbsp;${$name}`; } function formatSection(commits: Commit[], sectionName: string, options: ResolvedChangelogOptions) { if (!commits.length) { return []; } const lines: string[] = ['', formatTitle(sectionName, options), '']; const scopes = groupBy(commits, 'scope'); let useScopeGroup = options.group; // group scopes only when one of the scope have multiple commits if (!Object.entries(scopes).some(([k, v]) => k && v.length > 1)) { useScopeGroup = false; } Object.keys(scopes) .sort() .forEach(scope => { let padding = ''; let prefix = ''; const scopeText = `**${options.scopeMap[scope] || scope}**`; if (scope && (useScopeGroup === true || (useScopeGroup === 'multiple' && scopes[scope].length > 1))) { lines.push(`- ${scopeText}:`); padding = ' '; } else if (scope) { prefix = `${scopeText}: `; } lines.push(...scopes[scope].reverse().map(commit => `${padding}- ${prefix}${formatLine(commit, options)}`)); }); return lines; } export function generateMarkdown(commits: Commit[], options: ResolvedChangelogOptions) { const lines: string[] = [];
const [breaking, changes] = partition(commits, c => c.isBreaking);
const group = groupBy(changes, 'type'); lines.push(...formatSection(breaking, options.titles.breakingChanges!, options)); for (const type of Object.keys(options.types)) { const items = group[type] || []; lines.push(...formatSection(items, options.types[type].title, options)); } if (!lines.length) { lines.push('*No significant changes*'); } const url = `https://github.com/${options.repo.repo!}/compare/${options.from}...${options.to}`; lines.push('', `##### &nbsp;&nbsp;&nbsp;&nbsp;[View changes on GitHub](${url})`); return convert(lines.join('\n').trim(), true); }
src/markdown.ts
soybeanjs-githublogen-0932953
[ { "filename": "src/generate.ts", "retrieved_chunk": "import { getGitDiff } from './git';\nimport { generateMarkdown } from './markdown';\nimport { resolveAuthors } from './github';\nimport { resolveConfig } from './config';\nimport { parseCommits } from './parse';\nimport type { ChangelogOptions } from './types';\nexport async function generate(cwd: string, options: ChangelogOptions) {\n const resolved = await resolveConfig(cwd, options);\n const rawCommits = await getGitDiff(resolved.from, resolved.to);\n const commits = parseCommits(rawCommits, resolved);", "score": 0.8495588302612305 }, { "filename": "src/generate.ts", "retrieved_chunk": " if (resolved.contributors) {\n await resolveAuthors(commits, resolved);\n }\n const md = generateMarkdown(commits, resolved);\n return { config: resolved, md, commits };\n}", "score": 0.8370269536972046 }, { "filename": "src/cli.ts", "retrieved_chunk": " const { config, md, commits } = await generate(cwd, args as unknown as ChangelogOptions);\n const markdown = md.replace(/&nbsp;/g, '');\n console.log(cyan(config.from) + dim(' -> ') + blue(config.to) + dim(` (${commits.length} commits)`));\n console.log(dim('--------------'));\n console.log();\n console.log(markdown);\n console.log();\n console.log(dim('--------------'));\n if (config.dry) {\n console.log(yellow('Dry run. Release skipped.'));", "score": 0.8352852463722229 }, { "filename": "src/parse.ts", "retrieved_chunk": " };\n}\nexport function parseCommits(commits: RawGitCommit[], config: ChangelogConfig): GitCommit[] {\n return commits.map(commit => parseGitCommit(commit, config)).filter(notNullish);\n}", "score": 0.8292813897132874 }, { "filename": "src/github.ts", "retrieved_chunk": " }\n return info;\n}\nexport async function resolveAuthors(commits: Commit[], options: ChangelogOptions) {\n const map = new Map<string, AuthorInfo>();\n commits.forEach(commit => {\n commit.resolvedAuthors = commit.authors\n .map((a, idx) => {\n if (!a.email || !a.name) {\n return null;", "score": 0.8163810968399048 } ]
typescript
const [breaking, changes] = partition(commits, c => c.isBreaking);
#!/usr/bin/env node import { blue, bold, cyan, dim, red, yellow } from 'kolorist'; import cac from 'cac'; import { version } from '../package.json'; import { generate } from './generate'; import { hasTagOnGitHub, sendRelease } from './github'; import { isRepoShallow } from './git'; import type { ChangelogOptions } from './types'; const cli = cac('githublogen'); cli .version(version) .option('-t, --token <path>', 'GitHub Token') .option('--from <ref>', 'From tag') .option('--to <ref>', 'To tag') .option('--github <path>', 'GitHub Repository, e.g. soybeanjs/githublogen') .option('--name <name>', 'Name of the release') .option('--contributors', 'Show contributors section') .option('--prerelease', 'Mark release as prerelease') .option('-d, --draft', 'Mark release as draft') .option('--output <path>', 'Output to file instead of sending to GitHub') .option('--capitalize', 'Should capitalize for each comment message') .option('--emoji', 'Use emojis in section titles', { default: true }) .option('--group', 'Nest commit messages under their scopes') .option('--dry', 'Dry run') .help(); cli.command('').action(async (args: any) => { try { console.log(); console.log(dim(`${bold('github')}logen `) + dim(`v${version}`)); const cwd = process.cwd(); const { config, md, commits } = await generate(cwd, args as unknown as ChangelogOptions); const markdown = md.replace(/&nbsp;/g, ''); console.log(cyan(config.from) + dim(' -> ') + blue(config.to) + dim(` (${commits.length} commits)`)); console.log(dim('--------------')); console.log(); console.log(markdown); console.log(); console.log(dim('--------------')); if (config.dry) { console.log(yellow('Dry run. Release skipped.')); return; }
if (!(await hasTagOnGitHub(config.to, config))) {
console.error(yellow(`Current ref "${bold(config.to)}" is not available as tags on GitHub. Release skipped.`)); process.exitCode = 1; return; } if (!commits.length && (await isRepoShallow())) { console.error( yellow( 'The repo seems to be clone shallowly, which make changelog failed to generate. You might want to specify `fetch-depth: 0` in your CI config.' ) ); process.exitCode = 1; return; } await sendRelease(config, md); } catch (e: any) { console.error(red(String(e))); if (e?.stack) { console.error(dim(e.stack?.split('\n').slice(1).join('\n'))); } process.exit(1); } }); cli.parse();
src/cli.ts
soybeanjs-githublogen-0932953
[ { "filename": "src/github.ts", "retrieved_chunk": " try {\n console.log(cyan(method === 'POST' ? 'Creating release notes...' : 'Updating release notes...'));\n const res = await $fetch(url, {\n method,\n body: JSON.stringify(body),\n headers\n });\n console.log(green(`Released on ${res.html_url}`));\n } catch (e) {\n console.log();", "score": 0.8352502584457397 }, { "filename": "src/github.ts", "retrieved_chunk": "import { $fetch } from 'ohmyfetch';\nimport { cyan, green, red, yellow } from 'kolorist';\nimport { notNullish } from './shared';\nimport type { AuthorInfo, ChangelogOptions, Commit } from './types';\nexport async function sendRelease(options: ChangelogOptions, content: string) {\n const headers = getHeaders(options);\n const github = options.repo.repo!;\n let url = `https://api.github.com/repos/${github}/releases`;\n let method = 'POST';\n try {", "score": 0.8200556635856628 }, { "filename": "src/github.ts", "retrieved_chunk": " draft: options.draft || false,\n name: options.name || options.to,\n prerelease: options.prerelease,\n tag_name: options.to\n };\n const webUrl = `https://github.com/${github}/releases/new?title=${encodeURIComponent(\n String(body.name)\n )}&body=${encodeURIComponent(String(body.body))}&tag=${encodeURIComponent(String(options.to))}&prerelease=${\n options.prerelease\n }`;", "score": 0.8118880987167358 }, { "filename": "src/generate.ts", "retrieved_chunk": "import { getGitDiff } from './git';\nimport { generateMarkdown } from './markdown';\nimport { resolveAuthors } from './github';\nimport { resolveConfig } from './config';\nimport { parseCommits } from './parse';\nimport type { ChangelogOptions } from './types';\nexport async function generate(cwd: string, options: ChangelogOptions) {\n const resolved = await resolveConfig(cwd, options);\n const rawCommits = await getGitDiff(resolved.from, resolved.to);\n const commits = parseCommits(rawCommits, resolved);", "score": 0.811686635017395 }, { "filename": "src/github.ts", "retrieved_chunk": " console.error(red('Failed to create the release. Using the following link to create it manually:'));\n console.error(yellow(webUrl));\n console.log();\n throw e;\n }\n}\nfunction getHeaders(options: ChangelogOptions) {\n return {\n accept: 'application/vnd.github.v3+json',\n authorization: `token ${options.tokens.github}`", "score": 0.8086383938789368 } ]
typescript
if (!(await hasTagOnGitHub(config.to, config))) {
import { $fetch } from 'ohmyfetch'; import { cyan, green, red, yellow } from 'kolorist'; import { notNullish } from './shared'; import type { AuthorInfo, ChangelogOptions, Commit } from './types'; export async function sendRelease(options: ChangelogOptions, content: string) { const headers = getHeaders(options); const github = options.repo.repo!; let url = `https://api.github.com/repos/${github}/releases`; let method = 'POST'; try { const exists = await $fetch(`https://api.github.com/repos/${github}/releases/tags/${options.to}`, { headers }); if (exists.url) { url = exists.url; method = 'PATCH'; } } catch (e) {} const body = { body: content, draft: options.draft || false, name: options.name || options.to, prerelease: options.prerelease, tag_name: options.to }; const webUrl = `https://github.com/${github}/releases/new?title=${encodeURIComponent( String(body.name) )}&body=${encodeURIComponent(String(body.body))}&tag=${encodeURIComponent(String(options.to))}&prerelease=${ options.prerelease }`; try { console.log(cyan(method === 'POST' ? 'Creating release notes...' : 'Updating release notes...')); const res = await $fetch(url, { method, body: JSON.stringify(body), headers }); console.log(green(`Released on ${res.html_url}`)); } catch (e) { console.log(); console.error(red('Failed to create the release. Using the following link to create it manually:')); console.error(yellow(webUrl)); console.log(); throw e; } } function getHeaders(options: ChangelogOptions) { return { accept: 'application/vnd.github.v3+json', authorization: `token ${options.tokens.github}` }; } export async function resolveAuthorInfo(options: ChangelogOptions, info: AuthorInfo) { if (info.login) return info; // token not provided, skip github resolving if (!options.tokens.github) return info; try {
const data = await $fetch(`https://api.github.com/search/users?q=${encodeURIComponent(info.email)}`, {
headers: getHeaders(options) }); info.login = data.items[0].login; } catch {} if (info.login) return info; if (info.commits.length) { try { const data = await $fetch(`https://api.github.com/repos/${options.repo.repo}/commits/${info.commits[0]}`, { headers: getHeaders(options) }); info.login = data.author.login; } catch (e) {} } return info; } export async function resolveAuthors(commits: Commit[], options: ChangelogOptions) { const map = new Map<string, AuthorInfo>(); commits.forEach(commit => { commit.resolvedAuthors = commit.authors .map((a, idx) => { if (!a.email || !a.name) { return null; } if (!map.has(a.email)) { map.set(a.email, { commits: [], name: a.name, email: a.email }); } const info = map.get(a.email)!; // record commits only for the first author if (idx === 0) { info.commits.push(commit.shortHash); } return info; }) .filter(notNullish); }); const authors = Array.from(map.values()); const resolved = await Promise.all(authors.map(info => resolveAuthorInfo(options, info))); const loginSet = new Set<string>(); const nameSet = new Set<string>(); return resolved .sort((a, b) => (a.login || a.name).localeCompare(b.login || b.name)) .filter(i => { if (i.login && loginSet.has(i.login)) { return false; } if (i.login) { loginSet.add(i.login); } else { if (nameSet.has(i.name)) { return false; } nameSet.add(i.name); } return true; }); } export async function hasTagOnGitHub(tag: string, options: ChangelogOptions) { try { await $fetch(`https://api.github.com/repos/${options.repo.repo}/git/ref/tags/${tag}`, { headers: getHeaders(options) }); return true; } catch (e) { return false; } }
src/github.ts
soybeanjs-githublogen-0932953
[ { "filename": "src/types.ts", "retrieved_chunk": " references: Reference[];\n authors: GitCommitAuthor[];\n isBreaking: boolean;\n}\nexport interface AuthorInfo {\n commits: string[];\n login?: string;\n email: string;\n name: string;\n}", "score": 0.8263300657272339 }, { "filename": "src/types.ts", "retrieved_chunk": "export interface Commit extends GitCommit {\n resolvedAuthors?: AuthorInfo[];\n}\nexport interface ChangelogOptions extends ChangelogConfig {\n /**\n * Dry run. Skip releasing to GitHub.\n */\n dry?: boolean;\n /**\n * Whether to include contributors in release notes.", "score": 0.8032661080360413 }, { "filename": "src/generate.ts", "retrieved_chunk": " if (resolved.contributors) {\n await resolveAuthors(commits, resolved);\n }\n const md = generateMarkdown(commits, resolved);\n return { config: resolved, md, commits };\n}", "score": 0.8032490015029907 }, { "filename": "src/parse.ts", "retrieved_chunk": " description = description.replace(PullRequestRE, '').trim();\n // Find all authors\n const authors: GitCommitAuthor[] = [commit.author];\n const matchs = commit.body.matchAll(CoAuthoredByRegex);\n for (const $match of matchs) {\n const { name = '', email = '' } = $match.groups || {};\n const author: GitCommitAuthor = {\n name: name.trim(),\n email: email.trim()\n };", "score": 0.8031086921691895 }, { "filename": "src/config.ts", "retrieved_chunk": " output: 'CHANGELOG.md',\n contributors: true,\n capitalize: true,\n group: true\n};\nexport async function resolveConfig(cwd: string, options: ChangelogOptions) {\n const { loadConfig } = await import('c12');\n const config = await loadConfig<ChangelogOptions>({\n name: 'githublogen',\n defaults: defaultConfig,", "score": 0.798736035823822 } ]
typescript
const data = await $fetch(`https://api.github.com/search/users?q=${encodeURIComponent(info.email)}`, {
import { $fetch } from 'ohmyfetch'; import { cyan, green, red, yellow } from 'kolorist'; import { notNullish } from './shared'; import type { AuthorInfo, ChangelogOptions, Commit } from './types'; export async function sendRelease(options: ChangelogOptions, content: string) { const headers = getHeaders(options); const github = options.repo.repo!; let url = `https://api.github.com/repos/${github}/releases`; let method = 'POST'; try { const exists = await $fetch(`https://api.github.com/repos/${github}/releases/tags/${options.to}`, { headers }); if (exists.url) { url = exists.url; method = 'PATCH'; } } catch (e) {} const body = { body: content, draft: options.draft || false, name: options.name || options.to, prerelease: options.prerelease, tag_name: options.to }; const webUrl = `https://github.com/${github}/releases/new?title=${encodeURIComponent( String(body.name) )}&body=${encodeURIComponent(String(body.body))}&tag=${encodeURIComponent(String(options.to))}&prerelease=${ options.prerelease }`; try { console.log(cyan(method === 'POST' ? 'Creating release notes...' : 'Updating release notes...')); const res = await $fetch(url, { method, body: JSON.stringify(body), headers }); console.log(green(`Released on ${res.html_url}`)); } catch (e) { console.log(); console.error(red('Failed to create the release. Using the following link to create it manually:')); console.error(yellow(webUrl)); console.log(); throw e; } } function getHeaders(options: ChangelogOptions) { return { accept: 'application/vnd.github.v3+json', authorization: `token ${options.tokens.github}` }; } export async function resolveAuthorInfo(options: ChangelogOptions, info: AuthorInfo) {
if (info.login) return info;
// token not provided, skip github resolving if (!options.tokens.github) return info; try { const data = await $fetch(`https://api.github.com/search/users?q=${encodeURIComponent(info.email)}`, { headers: getHeaders(options) }); info.login = data.items[0].login; } catch {} if (info.login) return info; if (info.commits.length) { try { const data = await $fetch(`https://api.github.com/repos/${options.repo.repo}/commits/${info.commits[0]}`, { headers: getHeaders(options) }); info.login = data.author.login; } catch (e) {} } return info; } export async function resolveAuthors(commits: Commit[], options: ChangelogOptions) { const map = new Map<string, AuthorInfo>(); commits.forEach(commit => { commit.resolvedAuthors = commit.authors .map((a, idx) => { if (!a.email || !a.name) { return null; } if (!map.has(a.email)) { map.set(a.email, { commits: [], name: a.name, email: a.email }); } const info = map.get(a.email)!; // record commits only for the first author if (idx === 0) { info.commits.push(commit.shortHash); } return info; }) .filter(notNullish); }); const authors = Array.from(map.values()); const resolved = await Promise.all(authors.map(info => resolveAuthorInfo(options, info))); const loginSet = new Set<string>(); const nameSet = new Set<string>(); return resolved .sort((a, b) => (a.login || a.name).localeCompare(b.login || b.name)) .filter(i => { if (i.login && loginSet.has(i.login)) { return false; } if (i.login) { loginSet.add(i.login); } else { if (nameSet.has(i.name)) { return false; } nameSet.add(i.name); } return true; }); } export async function hasTagOnGitHub(tag: string, options: ChangelogOptions) { try { await $fetch(`https://api.github.com/repos/${options.repo.repo}/git/ref/tags/${tag}`, { headers: getHeaders(options) }); return true; } catch (e) { return false; } }
src/github.ts
soybeanjs-githublogen-0932953
[ { "filename": "src/types.ts", "retrieved_chunk": " references: Reference[];\n authors: GitCommitAuthor[];\n isBreaking: boolean;\n}\nexport interface AuthorInfo {\n commits: string[];\n login?: string;\n email: string;\n name: string;\n}", "score": 0.8317433595657349 }, { "filename": "src/types.ts", "retrieved_chunk": "export interface Commit extends GitCommit {\n resolvedAuthors?: AuthorInfo[];\n}\nexport interface ChangelogOptions extends ChangelogConfig {\n /**\n * Dry run. Skip releasing to GitHub.\n */\n dry?: boolean;\n /**\n * Whether to include contributors in release notes.", "score": 0.8240211009979248 }, { "filename": "src/generate.ts", "retrieved_chunk": " if (resolved.contributors) {\n await resolveAuthors(commits, resolved);\n }\n const md = generateMarkdown(commits, resolved);\n return { config: resolved, md, commits };\n}", "score": 0.8155814409255981 }, { "filename": "src/config.ts", "retrieved_chunk": " output: 'CHANGELOG.md',\n contributors: true,\n capitalize: true,\n group: true\n};\nexport async function resolveConfig(cwd: string, options: ChangelogOptions) {\n const { loadConfig } = await import('c12');\n const config = await loadConfig<ChangelogOptions>({\n name: 'githublogen',\n defaults: defaultConfig,", "score": 0.8131582736968994 }, { "filename": "src/markdown.ts", "retrieved_chunk": " }\n const description = options.capitalize ? capitalize(commit.description) : commit.description;\n return [description, refs].filter(i => i?.trim()).join(' ');\n}\nfunction formatTitle(name: string, options: ResolvedChangelogOptions) {\n let $name = name.trim();\n if (!options.emoji) {\n $name = name.replace(emojisRE, '').trim();\n }\n return `### &nbsp;&nbsp;&nbsp;${$name}`;", "score": 0.8090435266494751 } ]
typescript
if (info.login) return info;
import debug from "debug"; import EventEmitter from "eventemitter3"; import NDK from "../../index.js"; import { NDKRelay, NDKRelayStatus } from "../index.js"; export type NDKPoolStats = { total: number; connected: number; disconnected: number; connecting: number; }; /** * Handles connections to all relays. A single pool should be used per NDK instance. * * @emit connect - Emitted when all relays in the pool are connected, or when the specified timeout has elapsed, and some relays are connected. * @emit notice - Emitted when a relay in the pool sends a notice. * @emit flapping - Emitted when a relay in the pool is flapping. * @emit relay:connect - Emitted when a relay in the pool connects. * @emit relay:disconnect - Emitted when a relay in the pool disconnects. */ export class NDKPool extends EventEmitter { public relays = new Map<string, NDKRelay>(); private debug: debug.Debugger; private temporaryRelayTimers = new Map<string, NodeJS.Timeout>(); public constructor(relayUrls: string[] = [], ndk: NDK) { super(); this.debug = ndk.debug.extend("pool"); for (const relayUrl of relayUrls) { const relay = new NDKRelay(relayUrl); this.addRelay(relay, false); } } /** * Adds a relay to the pool, and sets a timer to remove it if it is not used within the specified time. * @param relay - The relay to add to the pool. * @param removeIfUnusedAfter - The time in milliseconds to wait before removing the relay from the pool after it is no longer used. */ public useTemporaryRelay(relay: NDKRelay, removeIfUnusedAfter = 600000) { const relayAlreadyInPool = this.relays.has(relay.url); // check if the relay is already in the pool if (!relayAlreadyInPool) { this.addRelay(relay); } // check if the relay already has a disconnecting timer const existingTimer = this.temporaryRelayTimers.get(relay.url); if (existingTimer) { clearTimeout(existingTimer); } // add a disconnecting timer only if the relay was not already in the pool // or if it had an existing timer // this prevents explicit relays from being removed from the pool if (!relayAlreadyInPool || existingTimer) { // set a timer to remove the relay from the pool if it is not used within the specified time const timer = setTimeout(() => { this.removeRelay(relay.url); }, removeIfUnusedAfter) as unknown as NodeJS.Timeout; this.temporaryRelayTimers.set(relay.url, timer); } } /** * Adds a relay to the pool. * * @param relay - The relay to add to the pool. * @param connect - Whether or not to connect to the relay. */ public addRelay(relay: NDKRelay, connect = true) { const relayUrl = relay.url; relay.on(
"notice", (relay, notice) => this.emit("notice", relay, notice) );
relay.on("connect", () => this.handleRelayConnect(relayUrl)); relay.on("disconnect", () => this.emit("relay:disconnect", relay)); relay.on("flapping", () => this.handleFlapping(relay)); this.relays.set(relayUrl, relay); if (connect) { relay.connect(); } } /** * Removes a relay from the pool. * @param relayUrl - The URL of the relay to remove. * @returns {boolean} True if the relay was removed, false if it was not found. */ public removeRelay(relayUrl: string): boolean { const relay = this.relays.get(relayUrl); if (relay) { relay.disconnect(); this.relays.delete(relayUrl); this.emit("relay:disconnect", relay); return true; } // remove the relay from the temporary relay timers const existingTimer = this.temporaryRelayTimers.get(relayUrl); if (existingTimer) { clearTimeout(existingTimer); this.temporaryRelayTimers.delete(relayUrl); } return false; } private handleRelayConnect(relayUrl: string) { this.debug(`Relay ${relayUrl} connected`); this.emit("relay:connect", this.relays.get(relayUrl)); if (this.stats().connected === this.relays.size) { this.emit("connect"); } } /** * Attempts to establish a connection to each relay in the pool. * * @async * @param {number} [timeoutMs] - Optional timeout in milliseconds for each connection attempt. * @returns {Promise<void>} A promise that resolves when all connection attempts have completed. * @throws {Error} If any of the connection attempts result in an error or timeout. */ public async connect(timeoutMs?: number): Promise<void> { const promises: Promise<void>[] = []; this.debug( `Connecting to ${this.relays.size} relays${ timeoutMs ? `, timeout ${timeoutMs}...` : "" }` ); for (const relay of this.relays.values()) { if (timeoutMs) { const timeoutPromise = new Promise<void>((_, reject) => { setTimeout( () => reject(`Timed out after ${timeoutMs}ms`), timeoutMs ); }); promises.push( Promise.race([relay.connect(), timeoutPromise]).catch( (e) => { this.debug( `Failed to connect to relay ${relay.url}: ${e}` ); } ) ); } else { promises.push(relay.connect()); } } // If we are running with a timeout, check if we need to emit a `connect` event // in case some, but not all, relays were connected if (timeoutMs) { setTimeout(() => { const allConnected = this.stats().connected === this.relays.size; const someConnected = this.stats().connected > 0; if (!allConnected && someConnected) { this.emit("connect"); } }, timeoutMs); } await Promise.all(promises); } private handleFlapping(relay: NDKRelay) { this.debug(`Relay ${relay.url} is flapping`); // TODO: Be smarter about this. this.relays.delete(relay.url); this.emit("flapping", relay); } public size(): number { return this.relays.size; } /** * Returns the status of each relay in the pool. * @returns {NDKPoolStats} An object containing the number of relays in each status. */ public stats(): NDKPoolStats { const stats: NDKPoolStats = { total: 0, connected: 0, disconnected: 0, connecting: 0, }; for (const relay of this.relays.values()) { stats.total++; if (relay.status === NDKRelayStatus.CONNECTED) { stats.connected++; } else if (relay.status === NDKRelayStatus.DISCONNECTED) { stats.disconnected++; } else if (relay.status === NDKRelayStatus.CONNECTING) { stats.connecting++; } } return stats; } public connectedRelays(): NDKRelay[] { return Array.from(this.relays.values()).filter( (relay) => relay.status === NDKRelayStatus.CONNECTED ); } /** * Get a list of all relay urls in the pool. */ public urls(): string[] { return Array.from(this.relays.keys()); } }
src/relay/pool/index.ts
nostr-dev-kit-ndk-ece64e1
[ { "filename": "src/relay/sets/index.ts", "retrieved_chunk": " public constructor(relays: Set<NDKRelay>, ndk: NDK) {\n this.relays = relays;\n this.ndk = ndk;\n this.debug = ndk.debug.extend(\"relayset\");\n }\n /**\n * Adds a relay to this set.\n */\n public addRelay(relay: NDKRelay) {\n this.relays.add(relay);", "score": 0.8706082701683044 }, { "filename": "src/relay/sets/index.ts", "retrieved_chunk": " if (relay.status === NDKRelayStatus.CONNECTED) {\n // If the relay is already connected, subscribe immediately\n this.subscribeOnRelay(relay, subscription);\n } else {\n // If the relay is not connected, add a one-time listener to wait for the 'connected' event\n const connectedListener = () => {\n this.debug(\n \"new relay coming online for active subscription\",\n {\n relay: relay.url,", "score": 0.8676877021789551 }, { "filename": "src/relay/index.ts", "retrieved_chunk": " this.updateConnectionStats.connected();\n this._status = NDKRelayStatus.CONNECTED;\n this.emit(\"connect\");\n });\n this.relay.on(\"disconnect\", () => {\n this.updateConnectionStats.disconnected();\n if (this._status === NDKRelayStatus.CONNECTED) {\n this._status = NDKRelayStatus.DISCONNECTED;\n this.handleReconnection();\n }", "score": 0.8618875741958618 }, { "filename": "src/relay/index.ts", "retrieved_chunk": " } else {\n this.connect();\n }\n }\n get status(): NDKRelayStatus {\n return this._status;\n }\n /**\n * Connects to the relay.\n */", "score": 0.8525810241699219 }, { "filename": "src/relay/index.ts", "retrieved_chunk": " public async connect(): Promise<void> {\n try {\n this.updateConnectionStats.attempt();\n this._status = NDKRelayStatus.CONNECTING;\n await this.relay.connect();\n } catch (e) {\n this.debug(\"Failed to connect\", e);\n this._status = NDKRelayStatus.DISCONNECTED;\n throw e;\n }", "score": 0.8495949506759644 } ]
typescript
"notice", (relay, notice) => this.emit("notice", relay, notice) );
import { $fetch } from 'ohmyfetch'; import { cyan, green, red, yellow } from 'kolorist'; import { notNullish } from './shared'; import type { AuthorInfo, ChangelogOptions, Commit } from './types'; export async function sendRelease(options: ChangelogOptions, content: string) { const headers = getHeaders(options); const github = options.repo.repo!; let url = `https://api.github.com/repos/${github}/releases`; let method = 'POST'; try { const exists = await $fetch(`https://api.github.com/repos/${github}/releases/tags/${options.to}`, { headers }); if (exists.url) { url = exists.url; method = 'PATCH'; } } catch (e) {} const body = { body: content, draft: options.draft || false, name: options.name || options.to, prerelease: options.prerelease, tag_name: options.to }; const webUrl = `https://github.com/${github}/releases/new?title=${encodeURIComponent( String(body.name) )}&body=${encodeURIComponent(String(body.body))}&tag=${encodeURIComponent(String(options.to))}&prerelease=${ options.prerelease }`; try { console.log(cyan(method === 'POST' ? 'Creating release notes...' : 'Updating release notes...')); const res = await $fetch(url, { method, body: JSON.stringify(body), headers }); console.log(green(`Released on ${res.html_url}`)); } catch (e) { console.log(); console.error(red('Failed to create the release. Using the following link to create it manually:')); console.error(yellow(webUrl)); console.log(); throw e; } } function getHeaders(options: ChangelogOptions) { return { accept: 'application/vnd.github.v3+json', authorization: `token ${options.tokens.github}` }; } export async function resolveAuthorInfo(options: ChangelogOptions, info: AuthorInfo) { if (info.login) return info; // token not provided, skip github resolving if (!options.tokens.github) return info; try { const data = await $fetch(`https://api.github.com/search/users?q=${encodeURIComponent(info.email)}`, { headers: getHeaders(options) }); info.login = data.items[0].login; } catch {} if (info.login) return info; if (info.commits.length) { try { const data = await $fetch(`https://api.github.com/repos/${options.repo.repo}/commits/${info.commits[0]}`, { headers: getHeaders(options) }); info.login = data.author.login; } catch (e) {} } return info; } export async function resolveAuthors(commits: Commit[], options: ChangelogOptions) { const map = new Map<string, AuthorInfo>(); commits.forEach(commit => { commit.resolvedAuthors = commit.authors
.map((a, idx) => {
if (!a.email || !a.name) { return null; } if (!map.has(a.email)) { map.set(a.email, { commits: [], name: a.name, email: a.email }); } const info = map.get(a.email)!; // record commits only for the first author if (idx === 0) { info.commits.push(commit.shortHash); } return info; }) .filter(notNullish); }); const authors = Array.from(map.values()); const resolved = await Promise.all(authors.map(info => resolveAuthorInfo(options, info))); const loginSet = new Set<string>(); const nameSet = new Set<string>(); return resolved .sort((a, b) => (a.login || a.name).localeCompare(b.login || b.name)) .filter(i => { if (i.login && loginSet.has(i.login)) { return false; } if (i.login) { loginSet.add(i.login); } else { if (nameSet.has(i.name)) { return false; } nameSet.add(i.name); } return true; }); } export async function hasTagOnGitHub(tag: string, options: ChangelogOptions) { try { await $fetch(`https://api.github.com/repos/${options.repo.repo}/git/ref/tags/${tag}`, { headers: getHeaders(options) }); return true; } catch (e) { return false; } }
src/github.ts
soybeanjs-githublogen-0932953
[ { "filename": "src/generate.ts", "retrieved_chunk": " if (resolved.contributors) {\n await resolveAuthors(commits, resolved);\n }\n const md = generateMarkdown(commits, resolved);\n return { config: resolved, md, commits };\n}", "score": 0.8546706438064575 }, { "filename": "src/types.ts", "retrieved_chunk": " references: Reference[];\n authors: GitCommitAuthor[];\n isBreaking: boolean;\n}\nexport interface AuthorInfo {\n commits: string[];\n login?: string;\n email: string;\n name: string;\n}", "score": 0.846977174282074 }, { "filename": "src/types.ts", "retrieved_chunk": "export interface Commit extends GitCommit {\n resolvedAuthors?: AuthorInfo[];\n}\nexport interface ChangelogOptions extends ChangelogConfig {\n /**\n * Dry run. Skip releasing to GitHub.\n */\n dry?: boolean;\n /**\n * Whether to include contributors in release notes.", "score": 0.8299256563186646 }, { "filename": "src/parse.ts", "retrieved_chunk": " authors.push(author);\n }\n return {\n ...commit,\n authors,\n description,\n type,\n scope,\n references,\n isBreaking", "score": 0.8273835182189941 }, { "filename": "src/markdown.ts", "retrieved_chunk": " const hashRefs = formatReferences(commit.references, options.repo.repo || '', 'hash');\n let authors = join([\n ...new Set(commit.resolvedAuthors?.map(i => (i.login ? `@${i.login}` : `**${i.name}**`)))\n ])?.trim();\n if (authors) {\n authors = `by ${authors}`;\n }\n let refs = [authors, prRefs, hashRefs].filter(i => i?.trim()).join(' ');\n if (refs) {\n refs = `&nbsp;-&nbsp; ${refs}`;", "score": 0.8264355659484863 } ]
typescript
.map((a, idx) => {
import { $fetch } from 'ohmyfetch'; import { cyan, green, red, yellow } from 'kolorist'; import { notNullish } from './shared'; import type { AuthorInfo, ChangelogOptions, Commit } from './types'; export async function sendRelease(options: ChangelogOptions, content: string) { const headers = getHeaders(options); const github = options.repo.repo!; let url = `https://api.github.com/repos/${github}/releases`; let method = 'POST'; try { const exists = await $fetch(`https://api.github.com/repos/${github}/releases/tags/${options.to}`, { headers }); if (exists.url) { url = exists.url; method = 'PATCH'; } } catch (e) {} const body = { body: content, draft: options.draft || false, name: options.name || options.to, prerelease: options.prerelease, tag_name: options.to }; const webUrl = `https://github.com/${github}/releases/new?title=${encodeURIComponent( String(body.name) )}&body=${encodeURIComponent(String(body.body))}&tag=${encodeURIComponent(String(options.to))}&prerelease=${ options.prerelease }`; try { console.log(cyan(method === 'POST' ? 'Creating release notes...' : 'Updating release notes...')); const res = await $fetch(url, { method, body: JSON.stringify(body), headers }); console.log(green(`Released on ${res.html_url}`)); } catch (e) { console.log(); console.error(red('Failed to create the release. Using the following link to create it manually:')); console.error(yellow(webUrl)); console.log(); throw e; } } function getHeaders(options: ChangelogOptions) { return { accept: 'application/vnd.github.v3+json', authorization: `token ${options.tokens.github}` }; } export async function resolveAuthorInfo(options: ChangelogOptions, info: AuthorInfo) { if (info.login) return info; // token not provided, skip github resolving if (!options.tokens.github) return info; try { const data = await $fetch(`https://api.github.com/search/users?q=${encodeURIComponent(info.email)}`, { headers: getHeaders(options) }); info.login = data.items[0].login; } catch {} if (info.login) return info;
if (info.commits.length) {
try { const data = await $fetch(`https://api.github.com/repos/${options.repo.repo}/commits/${info.commits[0]}`, { headers: getHeaders(options) }); info.login = data.author.login; } catch (e) {} } return info; } export async function resolveAuthors(commits: Commit[], options: ChangelogOptions) { const map = new Map<string, AuthorInfo>(); commits.forEach(commit => { commit.resolvedAuthors = commit.authors .map((a, idx) => { if (!a.email || !a.name) { return null; } if (!map.has(a.email)) { map.set(a.email, { commits: [], name: a.name, email: a.email }); } const info = map.get(a.email)!; // record commits only for the first author if (idx === 0) { info.commits.push(commit.shortHash); } return info; }) .filter(notNullish); }); const authors = Array.from(map.values()); const resolved = await Promise.all(authors.map(info => resolveAuthorInfo(options, info))); const loginSet = new Set<string>(); const nameSet = new Set<string>(); return resolved .sort((a, b) => (a.login || a.name).localeCompare(b.login || b.name)) .filter(i => { if (i.login && loginSet.has(i.login)) { return false; } if (i.login) { loginSet.add(i.login); } else { if (nameSet.has(i.name)) { return false; } nameSet.add(i.name); } return true; }); } export async function hasTagOnGitHub(tag: string, options: ChangelogOptions) { try { await $fetch(`https://api.github.com/repos/${options.repo.repo}/git/ref/tags/${tag}`, { headers: getHeaders(options) }); return true; } catch (e) { return false; } }
src/github.ts
soybeanjs-githublogen-0932953
[ { "filename": "src/parse.ts", "retrieved_chunk": " description = description.replace(PullRequestRE, '').trim();\n // Find all authors\n const authors: GitCommitAuthor[] = [commit.author];\n const matchs = commit.body.matchAll(CoAuthoredByRegex);\n for (const $match of matchs) {\n const { name = '', email = '' } = $match.groups || {};\n const author: GitCommitAuthor = {\n name: name.trim(),\n email: email.trim()\n };", "score": 0.8211544752120972 }, { "filename": "src/markdown.ts", "retrieved_chunk": " const hashRefs = formatReferences(commit.references, options.repo.repo || '', 'hash');\n let authors = join([\n ...new Set(commit.resolvedAuthors?.map(i => (i.login ? `@${i.login}` : `**${i.name}**`)))\n ])?.trim();\n if (authors) {\n authors = `by ${authors}`;\n }\n let refs = [authors, prRefs, hashRefs].filter(i => i?.trim()).join(' ');\n if (refs) {\n refs = `&nbsp;-&nbsp; ${refs}`;", "score": 0.8153601288795471 }, { "filename": "src/types.ts", "retrieved_chunk": " references: Reference[];\n authors: GitCommitAuthor[];\n isBreaking: boolean;\n}\nexport interface AuthorInfo {\n commits: string[];\n login?: string;\n email: string;\n name: string;\n}", "score": 0.8126600980758667 }, { "filename": "src/generate.ts", "retrieved_chunk": " if (resolved.contributors) {\n await resolveAuthors(commits, resolved);\n }\n const md = generateMarkdown(commits, resolved);\n return { config: resolved, md, commits };\n}", "score": 0.8087860941886902 }, { "filename": "src/markdown.ts", "retrieved_chunk": " }\n return i.type === 'hash';\n })\n .map(ref => {\n if (!github) {\n return ref.value;\n }\n if (ref.type === 'pull-request' || ref.type === 'issue') {\n return `https://github.com/${github}/issues/${ref.value.slice(1)}`;\n }", "score": 0.8002922534942627 } ]
typescript
if (info.commits.length) {
import { convert } from 'convert-gitmoji'; import { partition, groupBy, capitalize, join } from './shared'; import type { Reference, Commit, ResolvedChangelogOptions } from './types'; const emojisRE = /([\u2700-\u27BF]|[\uE000-\uF8FF]|\uD83C[\uDC00-\uDFFF]|\uD83D[\uDC00-\uDFFF]|[\u2011-\u26FF]|\uD83E[\uDD10-\uDDFF])/g; function formatReferences(references: Reference[], github: string, type: 'issues' | 'hash'): string { const refs = references .filter(i => { if (type === 'issues') { return i.type === 'issue' || i.type === 'pull-request'; } return i.type === 'hash'; }) .map(ref => { if (!github) { return ref.value; } if (ref.type === 'pull-request' || ref.type === 'issue') { return `https://github.com/${github}/issues/${ref.value.slice(1)}`; } return `[<samp>(${ref.value.slice(0, 5)})</samp>](https://github.com/${github}/commit/${ref.value})`; }); const referencesString = join(refs).trim(); if (type === 'issues') { return referencesString && `in ${referencesString}`; } return referencesString; } function formatLine(commit: Commit, options: ResolvedChangelogOptions) { const prRefs = formatReferences(commit.references, options.repo.repo || '', 'issues'); const hashRefs = formatReferences(commit.references, options.repo.repo || '', 'hash'); let authors = join([ ...new Set(commit.resolvedAuthors?.map(i => (i.login ? `@${i.login}` : `**${i.name}**`))) ])?.trim(); if (authors) { authors = `by ${authors}`; } let refs = [authors, prRefs, hashRefs].filter(i => i?.trim()).join(' '); if (refs) { refs = `&nbsp;-&nbsp; ${refs}`; } const description = options.capitalize ? capitalize(commit.description) : commit.description; return [description, refs].filter(i => i?.trim()).join(' '); } function formatTitle(name: string, options: ResolvedChangelogOptions) { let $name = name.trim(); if (!options.emoji) { $name = name.replace(emojisRE, '').trim(); } return `### &nbsp;&nbsp;&nbsp;${$name}`; } function formatSection(commits: Commit[], sectionName: string, options: ResolvedChangelogOptions) { if (!commits.length) { return []; } const lines: string[] = ['', formatTitle(sectionName, options), '']; const scopes = groupBy(commits, 'scope'); let useScopeGroup = options.group; // group scopes only when one of the scope have multiple commits if (!Object.entries(scopes).some(([k, v]) => k && v.length > 1)) { useScopeGroup = false; } Object.keys(scopes) .sort() .forEach(scope => { let padding = ''; let prefix = ''; const scopeText = `**${options.scopeMap[scope] || scope}**`; if (scope && (useScopeGroup === true || (useScopeGroup === 'multiple' && scopes[scope].length > 1))) { lines.push(`- ${scopeText}:`); padding = ' '; } else if (scope) { prefix = `${scopeText}: `; } lines.push(...scopes[scope].reverse().map(commit => `${padding}- ${prefix}${formatLine(commit, options)}`)); }); return lines; } export function generateMarkdown(commits: Commit[], options: ResolvedChangelogOptions) { const lines: string[] = []; const
[breaking, changes] = partition(commits, c => c.isBreaking);
const group = groupBy(changes, 'type'); lines.push(...formatSection(breaking, options.titles.breakingChanges!, options)); for (const type of Object.keys(options.types)) { const items = group[type] || []; lines.push(...formatSection(items, options.types[type].title, options)); } if (!lines.length) { lines.push('*No significant changes*'); } const url = `https://github.com/${options.repo.repo!}/compare/${options.from}...${options.to}`; lines.push('', `##### &nbsp;&nbsp;&nbsp;&nbsp;[View changes on GitHub](${url})`); return convert(lines.join('\n').trim(), true); }
src/markdown.ts
soybeanjs-githublogen-0932953
[ { "filename": "src/generate.ts", "retrieved_chunk": "import { getGitDiff } from './git';\nimport { generateMarkdown } from './markdown';\nimport { resolveAuthors } from './github';\nimport { resolveConfig } from './config';\nimport { parseCommits } from './parse';\nimport type { ChangelogOptions } from './types';\nexport async function generate(cwd: string, options: ChangelogOptions) {\n const resolved = await resolveConfig(cwd, options);\n const rawCommits = await getGitDiff(resolved.from, resolved.to);\n const commits = parseCommits(rawCommits, resolved);", "score": 0.8521717190742493 }, { "filename": "src/generate.ts", "retrieved_chunk": " if (resolved.contributors) {\n await resolveAuthors(commits, resolved);\n }\n const md = generateMarkdown(commits, resolved);\n return { config: resolved, md, commits };\n}", "score": 0.8371661901473999 }, { "filename": "src/cli.ts", "retrieved_chunk": " const { config, md, commits } = await generate(cwd, args as unknown as ChangelogOptions);\n const markdown = md.replace(/&nbsp;/g, '');\n console.log(cyan(config.from) + dim(' -> ') + blue(config.to) + dim(` (${commits.length} commits)`));\n console.log(dim('--------------'));\n console.log();\n console.log(markdown);\n console.log();\n console.log(dim('--------------'));\n if (config.dry) {\n console.log(yellow('Dry run. Release skipped.'));", "score": 0.8357716202735901 }, { "filename": "src/parse.ts", "retrieved_chunk": " };\n}\nexport function parseCommits(commits: RawGitCommit[], config: ChangelogConfig): GitCommit[] {\n return commits.map(commit => parseGitCommit(commit, config)).filter(notNullish);\n}", "score": 0.8353089094161987 }, { "filename": "src/github.ts", "retrieved_chunk": " }\n return info;\n}\nexport async function resolveAuthors(commits: Commit[], options: ChangelogOptions) {\n const map = new Map<string, AuthorInfo>();\n commits.forEach(commit => {\n commit.resolvedAuthors = commit.authors\n .map((a, idx) => {\n if (!a.email || !a.name) {\n return null;", "score": 0.8186213970184326 } ]
typescript
[breaking, changes] = partition(commits, c => c.isBreaking);
import debug from "debug"; import EventEmitter from "eventemitter3"; import NDK from "../../index.js"; import { NDKRelay, NDKRelayStatus } from "../index.js"; export type NDKPoolStats = { total: number; connected: number; disconnected: number; connecting: number; }; /** * Handles connections to all relays. A single pool should be used per NDK instance. * * @emit connect - Emitted when all relays in the pool are connected, or when the specified timeout has elapsed, and some relays are connected. * @emit notice - Emitted when a relay in the pool sends a notice. * @emit flapping - Emitted when a relay in the pool is flapping. * @emit relay:connect - Emitted when a relay in the pool connects. * @emit relay:disconnect - Emitted when a relay in the pool disconnects. */ export class NDKPool extends EventEmitter { public relays = new Map<string, NDKRelay>(); private debug: debug.Debugger; private temporaryRelayTimers = new Map<string, NodeJS.Timeout>(); public constructor(relayUrls: string[] = [], ndk: NDK) { super(); this.debug = ndk.debug.extend("pool"); for (const relayUrl of relayUrls) { const relay = new NDKRelay(relayUrl); this.addRelay(relay, false); } } /** * Adds a relay to the pool, and sets a timer to remove it if it is not used within the specified time. * @param relay - The relay to add to the pool. * @param removeIfUnusedAfter - The time in milliseconds to wait before removing the relay from the pool after it is no longer used. */ public useTemporaryRelay(relay: NDKRelay, removeIfUnusedAfter = 600000) { const relayAlreadyInPool = this.relays.has(relay.url); // check if the relay is already in the pool if (!relayAlreadyInPool) { this.addRelay(relay); } // check if the relay already has a disconnecting timer const existingTimer = this.temporaryRelayTimers.get(relay.url); if (existingTimer) { clearTimeout(existingTimer); } // add a disconnecting timer only if the relay was not already in the pool // or if it had an existing timer // this prevents explicit relays from being removed from the pool if (!relayAlreadyInPool || existingTimer) { // set a timer to remove the relay from the pool if it is not used within the specified time const timer = setTimeout(() => { this.removeRelay(relay.url); }, removeIfUnusedAfter) as unknown as NodeJS.Timeout; this.temporaryRelayTimers.set(relay.url, timer); } } /** * Adds a relay to the pool. * * @param relay - The relay to add to the pool. * @param connect - Whether or not to connect to the relay. */ public addRelay(relay: NDKRelay, connect = true) { const relayUrl = relay.url; relay.on("notice", (relay, notice) => this.emit("notice", relay, notice) ); relay.on("connect", () => this.handleRelayConnect(relayUrl)); relay.on("disconnect", () => this.emit("relay:disconnect", relay)); relay.on("flapping", () => this.handleFlapping(relay)); this.relays.set(relayUrl, relay); if (connect) { relay.connect(); } } /** * Removes a relay from the pool. * @param relayUrl - The URL of the relay to remove. * @returns {boolean} True if the relay was removed, false if it was not found. */ public removeRelay(relayUrl: string): boolean { const relay = this.relays.get(relayUrl); if (relay) { relay.disconnect(); this.relays.delete(relayUrl); this.emit("relay:disconnect", relay); return true; } // remove the relay from the temporary relay timers const existingTimer = this.temporaryRelayTimers.get(relayUrl); if (existingTimer) { clearTimeout(existingTimer); this.temporaryRelayTimers.delete(relayUrl); } return false; } private handleRelayConnect(relayUrl: string) { this.debug(`Relay ${relayUrl} connected`); this.emit("relay:connect", this.relays.get(relayUrl)); if (this.stats().connected === this.relays.size) { this.emit("connect"); } } /** * Attempts to establish a connection to each relay in the pool. * * @async * @param {number} [timeoutMs] - Optional timeout in milliseconds for each connection attempt. * @returns {Promise<void>} A promise that resolves when all connection attempts have completed. * @throws {Error} If any of the connection attempts result in an error or timeout. */ public async connect(timeoutMs?: number): Promise<void> { const promises: Promise<void>[] = []; this.debug( `Connecting to ${this.relays.size} relays${ timeoutMs ? `, timeout ${timeoutMs}...` : "" }` ); for (const relay of this.relays.values()) { if (timeoutMs) { const timeoutPromise = new Promise<void>((_, reject) => { setTimeout( () => reject(`Timed out after ${timeoutMs}ms`), timeoutMs ); }); promises.push( Promise.race([relay.connect(), timeoutPromise]).catch( (e) => { this.debug( `Failed to connect to relay ${relay.url}: ${e}` ); } ) ); } else { promises.push(relay.connect()); } } // If we are running with a timeout, check if we need to emit a `connect` event // in case some, but not all, relays were connected if (timeoutMs) { setTimeout(() => { const allConnected = this.stats().connected === this.relays.size; const someConnected = this.stats().connected > 0; if (!allConnected && someConnected) { this.emit("connect"); } }, timeoutMs); } await Promise.all(promises); } private handleFlapping(relay: NDKRelay) { this.debug(`Relay ${relay.url} is flapping`); // TODO: Be smarter about this. this.relays.delete(relay.url); this.emit("flapping", relay); } public size(): number { return this.relays.size; } /** * Returns the status of each relay in the pool. * @returns {NDKPoolStats} An object containing the number of relays in each status. */ public stats(): NDKPoolStats { const stats: NDKPoolStats = { total: 0, connected: 0, disconnected: 0, connecting: 0, }; for (const relay of this.relays.values()) { stats.total++; if (relay.status === NDKRelayStatus.CONNECTED) { stats.connected++; } else if (relay.status === NDKRelayStatus.DISCONNECTED) { stats.disconnected++; } else if (relay.status === NDKRelayStatus.CONNECTING) { stats.connecting++; } } return stats; }
public connectedRelays(): NDKRelay[] {
return Array.from(this.relays.values()).filter( (relay) => relay.status === NDKRelayStatus.CONNECTED ); } /** * Get a list of all relay urls in the pool. */ public urls(): string[] { return Array.from(this.relays.keys()); } }
src/relay/pool/index.ts
nostr-dev-kit-ndk-ece64e1
[ { "filename": "src/relay/index.ts", "retrieved_chunk": " this.updateConnectionStats.connected();\n this._status = NDKRelayStatus.CONNECTED;\n this.emit(\"connect\");\n });\n this.relay.on(\"disconnect\", () => {\n this.updateConnectionStats.disconnected();\n if (this._status === NDKRelayStatus.CONNECTED) {\n this._status = NDKRelayStatus.DISCONNECTED;\n this.handleReconnection();\n }", "score": 0.898417055606842 }, { "filename": "src/relay/index.ts", "retrieved_chunk": " private connectedAt?: number;\n private _connectionStats: NDKRelayConnectionStats = {\n attempts: 0,\n success: 0,\n durations: [],\n };\n public complaining = false;\n private debug: debug.Debugger;\n /**\n * Active subscriptions this relay is connected to", "score": 0.877851665019989 }, { "filename": "src/relay/index.ts", "retrieved_chunk": " };\n /**\n * Returns the connection stats.\n */\n get connectionStats(): NDKRelayConnectionStats {\n return this._connectionStats;\n }\n public tagReference(marker?: string): NDKTag {\n const tag = [\"r\", this.relay.url];\n if (marker) {", "score": 0.8670903444290161 }, { "filename": "src/relay/index.ts", "retrieved_chunk": " public async connect(): Promise<void> {\n try {\n this.updateConnectionStats.attempt();\n this._status = NDKRelayStatus.CONNECTING;\n await this.relay.connect();\n } catch (e) {\n this.debug(\"Failed to connect\", e);\n this._status = NDKRelayStatus.DISCONNECTED;\n throw e;\n }", "score": 0.8610512614250183 }, { "filename": "src/relay/index.ts", "retrieved_chunk": " CONNECTED,\n DISCONNECTING,\n DISCONNECTED,\n RECONNECTING,\n FLAPPING,\n}\nexport interface NDKRelayConnectionStats {\n /**\n * The number of times a connection has been attempted.\n */", "score": 0.8591160774230957 } ]
typescript
public connectedRelays(): NDKRelay[] {
import { $fetch } from 'ohmyfetch'; import { cyan, green, red, yellow } from 'kolorist'; import { notNullish } from './shared'; import type { AuthorInfo, ChangelogOptions, Commit } from './types'; export async function sendRelease(options: ChangelogOptions, content: string) { const headers = getHeaders(options); const github = options.repo.repo!; let url = `https://api.github.com/repos/${github}/releases`; let method = 'POST'; try { const exists = await $fetch(`https://api.github.com/repos/${github}/releases/tags/${options.to}`, { headers }); if (exists.url) { url = exists.url; method = 'PATCH'; } } catch (e) {} const body = { body: content, draft: options.draft || false, name: options.name || options.to, prerelease: options.prerelease, tag_name: options.to }; const webUrl = `https://github.com/${github}/releases/new?title=${encodeURIComponent( String(body.name) )}&body=${encodeURIComponent(String(body.body))}&tag=${encodeURIComponent(String(options.to))}&prerelease=${ options.prerelease }`; try { console.log(cyan(method === 'POST' ? 'Creating release notes...' : 'Updating release notes...')); const res = await $fetch(url, { method, body: JSON.stringify(body), headers }); console.log(green(`Released on ${res.html_url}`)); } catch (e) { console.log(); console.error(red('Failed to create the release. Using the following link to create it manually:')); console.error(yellow(webUrl)); console.log(); throw e; } } function getHeaders(options: ChangelogOptions) { return { accept: 'application/vnd.github.v3+json', authorization: `token ${options.tokens.github}` }; } export async function resolveAuthorInfo(options: ChangelogOptions, info: AuthorInfo) { if (info.login) return info; // token not provided, skip github resolving if (!options.tokens.github) return info; try { const data = await $fetch(`https://api.github.com/search/users?q=${encodeURIComponent(info.email)}`, { headers: getHeaders(options) }); info.login = data.items[0].login; } catch {} if (info.login) return info; if (info.commits.length) { try { const data = await $fetch(`https://api.github.com/repos/${options.repo.repo}/commits/${info.commits[0]}`, { headers: getHeaders(options) }); info.login = data.author.login; } catch (e) {} } return info; } export async function resolveAuthors(commits: Commit[], options: ChangelogOptions) { const map = new Map<string, AuthorInfo>(); commits.forEach(commit => { commit.resolvedAuthors = commit.authors .map
((a, idx) => {
if (!a.email || !a.name) { return null; } if (!map.has(a.email)) { map.set(a.email, { commits: [], name: a.name, email: a.email }); } const info = map.get(a.email)!; // record commits only for the first author if (idx === 0) { info.commits.push(commit.shortHash); } return info; }) .filter(notNullish); }); const authors = Array.from(map.values()); const resolved = await Promise.all(authors.map(info => resolveAuthorInfo(options, info))); const loginSet = new Set<string>(); const nameSet = new Set<string>(); return resolved .sort((a, b) => (a.login || a.name).localeCompare(b.login || b.name)) .filter(i => { if (i.login && loginSet.has(i.login)) { return false; } if (i.login) { loginSet.add(i.login); } else { if (nameSet.has(i.name)) { return false; } nameSet.add(i.name); } return true; }); } export async function hasTagOnGitHub(tag: string, options: ChangelogOptions) { try { await $fetch(`https://api.github.com/repos/${options.repo.repo}/git/ref/tags/${tag}`, { headers: getHeaders(options) }); return true; } catch (e) { return false; } }
src/github.ts
soybeanjs-githublogen-0932953
[ { "filename": "src/generate.ts", "retrieved_chunk": " if (resolved.contributors) {\n await resolveAuthors(commits, resolved);\n }\n const md = generateMarkdown(commits, resolved);\n return { config: resolved, md, commits };\n}", "score": 0.868720293045044 }, { "filename": "src/types.ts", "retrieved_chunk": " references: Reference[];\n authors: GitCommitAuthor[];\n isBreaking: boolean;\n}\nexport interface AuthorInfo {\n commits: string[];\n login?: string;\n email: string;\n name: string;\n}", "score": 0.8409985303878784 }, { "filename": "src/types.ts", "retrieved_chunk": "export interface Commit extends GitCommit {\n resolvedAuthors?: AuthorInfo[];\n}\nexport interface ChangelogOptions extends ChangelogConfig {\n /**\n * Dry run. Skip releasing to GitHub.\n */\n dry?: boolean;\n /**\n * Whether to include contributors in release notes.", "score": 0.8384127020835876 }, { "filename": "src/markdown.ts", "retrieved_chunk": " const hashRefs = formatReferences(commit.references, options.repo.repo || '', 'hash');\n let authors = join([\n ...new Set(commit.resolvedAuthors?.map(i => (i.login ? `@${i.login}` : `**${i.name}**`)))\n ])?.trim();\n if (authors) {\n authors = `by ${authors}`;\n }\n let refs = [authors, prRefs, hashRefs].filter(i => i?.trim()).join(' ');\n if (refs) {\n refs = `&nbsp;-&nbsp; ${refs}`;", "score": 0.8322365283966064 }, { "filename": "src/markdown.ts", "retrieved_chunk": " padding = ' ';\n } else if (scope) {\n prefix = `${scopeText}: `;\n }\n lines.push(...scopes[scope].reverse().map(commit => `${padding}- ${prefix}${formatLine(commit, options)}`));\n });\n return lines;\n}\nexport function generateMarkdown(commits: Commit[], options: ResolvedChangelogOptions) {\n const lines: string[] = [];", "score": 0.8238750100135803 } ]
typescript
((a, idx) => {
import { $fetch } from 'ohmyfetch'; import { cyan, green, red, yellow } from 'kolorist'; import { notNullish } from './shared'; import type { AuthorInfo, ChangelogOptions, Commit } from './types'; export async function sendRelease(options: ChangelogOptions, content: string) { const headers = getHeaders(options); const github = options.repo.repo!; let url = `https://api.github.com/repos/${github}/releases`; let method = 'POST'; try { const exists = await $fetch(`https://api.github.com/repos/${github}/releases/tags/${options.to}`, { headers }); if (exists.url) { url = exists.url; method = 'PATCH'; } } catch (e) {} const body = { body: content, draft: options.draft || false, name: options.name || options.to, prerelease: options.prerelease, tag_name: options.to }; const webUrl = `https://github.com/${github}/releases/new?title=${encodeURIComponent( String(body.name) )}&body=${encodeURIComponent(String(body.body))}&tag=${encodeURIComponent(String(options.to))}&prerelease=${ options.prerelease }`; try { console.log(cyan(method === 'POST' ? 'Creating release notes...' : 'Updating release notes...')); const res = await $fetch(url, { method, body: JSON.stringify(body), headers }); console.log(green(`Released on ${res.html_url}`)); } catch (e) { console.log(); console.error(red('Failed to create the release. Using the following link to create it manually:')); console.error(yellow(webUrl)); console.log(); throw e; } } function getHeaders(options: ChangelogOptions) { return { accept: 'application/vnd.github.v3+json', authorization: `token ${options.tokens.github}` }; } export async function resolveAuthorInfo(options: ChangelogOptions, info: AuthorInfo) { if (info.login) return info; // token not provided, skip github resolving if (!options.tokens.github) return info; try { const data = await $fetch(`https://api.github.com/search/users?q=${encodeURIComponent(info.email)}`, { headers: getHeaders(options) }); info.login = data.items[0].login; } catch {} if (info.login) return info; if (info.commits.length) { try { const data = await $fetch(`https://api.github.com/repos/${options.repo.repo}/commits/${info.commits[0]}`, { headers: getHeaders(options) }); info.login = data.author.login; } catch (e) {} } return info; } export async function resolveAuthors(commits: Commit[], options: ChangelogOptions) { const map = new Map<string, AuthorInfo>(); commits.forEach(commit => { commit.resolvedAuthors = commit.authors .map((a, idx) => { if (!a.email || !a.name) { return null; } if (!map.has(a.email)) { map.set(a.email, { commits: [], name: a.name, email: a.email }); } const info = map.get(a.email)!; // record commits only for the first author if (idx === 0) { info.commits.push(commit.shortHash); } return info; }) .filter(notNullish); }); const authors = Array.from(map.values()); const resolved = await Promise.all(authors.map(info => resolveAuthorInfo(options, info))); const loginSet = new Set<string>(); const nameSet = new Set<string>(); return resolved .sort((a, b)
=> (a.login || a.name).localeCompare(b.login || b.name)) .filter(i => {
if (i.login && loginSet.has(i.login)) { return false; } if (i.login) { loginSet.add(i.login); } else { if (nameSet.has(i.name)) { return false; } nameSet.add(i.name); } return true; }); } export async function hasTagOnGitHub(tag: string, options: ChangelogOptions) { try { await $fetch(`https://api.github.com/repos/${options.repo.repo}/git/ref/tags/${tag}`, { headers: getHeaders(options) }); return true; } catch (e) { return false; } }
src/github.ts
soybeanjs-githublogen-0932953
[ { "filename": "src/generate.ts", "retrieved_chunk": " if (resolved.contributors) {\n await resolveAuthors(commits, resolved);\n }\n const md = generateMarkdown(commits, resolved);\n return { config: resolved, md, commits };\n}", "score": 0.8222649097442627 }, { "filename": "src/markdown.ts", "retrieved_chunk": " const hashRefs = formatReferences(commit.references, options.repo.repo || '', 'hash');\n let authors = join([\n ...new Set(commit.resolvedAuthors?.map(i => (i.login ? `@${i.login}` : `**${i.name}**`)))\n ])?.trim();\n if (authors) {\n authors = `by ${authors}`;\n }\n let refs = [authors, prRefs, hashRefs].filter(i => i?.trim()).join(' ');\n if (refs) {\n refs = `&nbsp;-&nbsp; ${refs}`;", "score": 0.8101352453231812 }, { "filename": "src/types.ts", "retrieved_chunk": " references: Reference[];\n authors: GitCommitAuthor[];\n isBreaking: boolean;\n}\nexport interface AuthorInfo {\n commits: string[];\n login?: string;\n email: string;\n name: string;\n}", "score": 0.799920916557312 }, { "filename": "src/parse.ts", "retrieved_chunk": " description = description.replace(PullRequestRE, '').trim();\n // Find all authors\n const authors: GitCommitAuthor[] = [commit.author];\n const matchs = commit.body.matchAll(CoAuthoredByRegex);\n for (const $match of matchs) {\n const { name = '', email = '' } = $match.groups || {};\n const author: GitCommitAuthor = {\n name: name.trim(),\n email: email.trim()\n };", "score": 0.7918698787689209 }, { "filename": "src/parse.ts", "retrieved_chunk": " authors.push(author);\n }\n return {\n ...commit,\n authors,\n description,\n type,\n scope,\n references,\n isBreaking", "score": 0.7901608943939209 } ]
typescript
=> (a.login || a.name).localeCompare(b.login || b.name)) .filter(i => {
import { readPackageJSON } from 'pkg-types'; import type { Reference, ChangelogConfig, RepoProvider, RepoConfig } from './types'; import { getGitRemoteURL } from './git'; const providerToRefSpec: Record<RepoProvider, Record<Reference['type'], string>> = { github: { 'pull-request': 'pull', hash: 'commit', issue: 'issues' }, gitlab: { 'pull-request': 'merge_requests', hash: 'commit', issue: 'issues' }, bitbucket: { 'pull-request': 'pull-requests', hash: 'commit', issue: 'issues' } }; const providerToDomain: Record<RepoProvider, string> = { github: 'github.com', gitlab: 'gitlab.com', bitbucket: 'bitbucket.org' }; const domainToProvider: Record<string, RepoProvider> = { 'github.com': 'github', 'gitlab.com': 'gitlab', 'bitbucket.org': 'bitbucket' }; // https://regex101.com/r/NA4Io6/1 const providerURLRegex = /^(?:(?<user>\w+)@)?(?:(?<provider>[^/:]+):)?(?<repo>\w+\/\w+)(?:\.git)?$/; function baseUrl(config: RepoConfig) { return `https://${config.domain}/${config.repo}`; } export function formatReference(ref: Reference, repo?: RepoConfig) { if (!repo?.provider || !(repo.provider in providerToRefSpec)) { return ref.value; } const refSpec = providerToRefSpec[repo.provider]; return `[${ref.value}](${baseUrl(repo)}/${refSpec[ref.type]}/${ref.value.replace(/^#/, '')})`; } export function formatCompareChanges(v: string, config: ChangelogConfig) {
const part = config.repo?.provider === 'bitbucket' ? 'branches/compare' : 'compare';
return `[compare changes](${baseUrl(config.repo)}/${part}/${config.from}...${v || config.to})`; } export async function resolveRepoConfig(cwd: string) { // Try closest package.json const pkg = await readPackageJSON(cwd).catch(() => {}); if (pkg && pkg.repository) { const url = typeof pkg.repository === 'string' ? pkg.repository : pkg.repository.url; return getRepoConfig(url); } const gitRemote = await getGitRemoteURL(cwd).catch(() => {}); if (gitRemote) { return getRepoConfig(gitRemote); } return {}; } export function getRepoConfig(repoUrl = ''): RepoConfig { let provider: RepoProvider | undefined; let repo: string | undefined; let domain: string | undefined; let url: URL | undefined; try { url = new URL(repoUrl); } catch {} const m = repoUrl.match(providerURLRegex)?.groups ?? {}; if (m.repo && m.provider) { repo = m.repo; provider = m.provider in domainToProvider ? domainToProvider[m.provider] : (m.provider as RepoProvider); domain = provider in providerToDomain ? providerToDomain[provider] : provider; } else if (url) { domain = url.hostname; repo = url.pathname .split('/') .slice(1, 3) .join('/') .replace(/\.git$/, ''); provider = domainToProvider[domain]; } else if (m.repo) { repo = m.repo; provider = 'github'; domain = providerToDomain[provider]; } return { provider, repo, domain }; }
src/repo.ts
soybeanjs-githublogen-0932953
[ { "filename": "src/markdown.ts", "retrieved_chunk": " return `[<samp>(${ref.value.slice(0, 5)})</samp>](https://github.com/${github}/commit/${ref.value})`;\n });\n const referencesString = join(refs).trim();\n if (type === 'issues') {\n return referencesString && `in ${referencesString}`;\n }\n return referencesString;\n}\nfunction formatLine(commit: Commit, options: ResolvedChangelogOptions) {\n const prRefs = formatReferences(commit.references, options.repo.repo || '', 'issues');", "score": 0.8575742244720459 }, { "filename": "src/markdown.ts", "retrieved_chunk": " }\n return i.type === 'hash';\n })\n .map(ref => {\n if (!github) {\n return ref.value;\n }\n if (ref.type === 'pull-request' || ref.type === 'issue') {\n return `https://github.com/${github}/issues/${ref.value.slice(1)}`;\n }", "score": 0.8372993469238281 }, { "filename": "src/markdown.ts", "retrieved_chunk": " const hashRefs = formatReferences(commit.references, options.repo.repo || '', 'hash');\n let authors = join([\n ...new Set(commit.resolvedAuthors?.map(i => (i.login ? `@${i.login}` : `**${i.name}**`)))\n ])?.trim();\n if (authors) {\n authors = `by ${authors}`;\n }\n let refs = [authors, prRefs, hashRefs].filter(i => i?.trim()).join(' ');\n if (refs) {\n refs = `&nbsp;-&nbsp; ${refs}`;", "score": 0.8269410729408264 }, { "filename": "src/markdown.ts", "retrieved_chunk": "import { convert } from 'convert-gitmoji';\nimport { partition, groupBy, capitalize, join } from './shared';\nimport type { Reference, Commit, ResolvedChangelogOptions } from './types';\nconst emojisRE =\n /([\\u2700-\\u27BF]|[\\uE000-\\uF8FF]|\\uD83C[\\uDC00-\\uDFFF]|\\uD83D[\\uDC00-\\uDFFF]|[\\u2011-\\u26FF]|\\uD83E[\\uDD10-\\uDDFF])/g;\nfunction formatReferences(references: Reference[], github: string, type: 'issues' | 'hash'): string {\n const refs = references\n .filter(i => {\n if (type === 'issues') {\n return i.type === 'issue' || i.type === 'pull-request';", "score": 0.8212571144104004 }, { "filename": "src/markdown.ts", "retrieved_chunk": " const url = `https://github.com/${options.repo.repo!}/compare/${options.from}...${options.to}`;\n lines.push('', `##### &nbsp;&nbsp;&nbsp;&nbsp;[View changes on GitHub](${url})`);\n return convert(lines.join('\\n').trim(), true);\n}", "score": 0.814010739326477 } ]
typescript
const part = config.repo?.provider === 'bitbucket' ? 'branches/compare' : 'compare';
import { notNullish } from './shared'; import type { GitCommit, RawGitCommit, GitCommitAuthor, ChangelogConfig, Reference } from './types'; // https://www.conventionalcommits.org/en/v1.0.0/ // https://regex101.com/r/FSfNvA/1 const ConventionalCommitRegex = /(?<type>[a-z]+)(\((?<scope>.+)\))?(?<breaking>!)?: (?<description>.+)/i; const CoAuthoredByRegex = /co-authored-by:\s*(?<name>.+)(<(?<email>.+)>)/gim; const PullRequestRE = /\([a-z]*(#\d+)\s*\)/gm; const IssueRE = /(#\d+)/gm; export function parseGitCommit(commit: RawGitCommit, config: ChangelogConfig): GitCommit | null { const match = commit.message.match(ConventionalCommitRegex); if (!match?.groups) { return null; } const type = match.groups.type; let scope = match.groups.scope || ''; scope = config.scopeMap[scope] || scope; const isBreaking = Boolean(match.groups.breaking); let description = match.groups.description; // Extract references from message const references: Reference[] = []; for (const m of description.matchAll(PullRequestRE)) { references.push({ type: 'pull-request', value: m[1] }); } for (const m of description.matchAll(IssueRE)) { if (!references.some(i => i.value === m[1])) { references.push({ type: 'issue', value: m[1] }); } } references.push({ value: commit.shortHash, type: 'hash' }); // Remove references and normalize description = description.replace(PullRequestRE, '').trim(); // Find all authors const authors: GitCommitAuthor[] = [commit.author]; const matchs = commit.body.matchAll(CoAuthoredByRegex); for (const $match of matchs) { const { name = '', email = '' } = $match.groups || {}; const author: GitCommitAuthor = { name: name.trim(), email: email.trim() }; authors.push(author); } return { ...commit, authors, description, type, scope, references, isBreaking }; } export function parseCommits(commits: RawGitCommit[], config: ChangelogConfig): GitCommit[] {
return commits.map(commit => parseGitCommit(commit, config)).filter(notNullish);
}
src/parse.ts
soybeanjs-githublogen-0932953
[ { "filename": "src/github.ts", "retrieved_chunk": " }\n return info;\n}\nexport async function resolveAuthors(commits: Commit[], options: ChangelogOptions) {\n const map = new Map<string, AuthorInfo>();\n commits.forEach(commit => {\n commit.resolvedAuthors = commit.authors\n .map((a, idx) => {\n if (!a.email || !a.name) {\n return null;", "score": 0.8419777750968933 }, { "filename": "src/generate.ts", "retrieved_chunk": " if (resolved.contributors) {\n await resolveAuthors(commits, resolved);\n }\n const md = generateMarkdown(commits, resolved);\n return { config: resolved, md, commits };\n}", "score": 0.8394665718078613 }, { "filename": "src/markdown.ts", "retrieved_chunk": " padding = ' ';\n } else if (scope) {\n prefix = `${scopeText}: `;\n }\n lines.push(...scopes[scope].reverse().map(commit => `${padding}- ${prefix}${formatLine(commit, options)}`));\n });\n return lines;\n}\nexport function generateMarkdown(commits: Commit[], options: ResolvedChangelogOptions) {\n const lines: string[] = [];", "score": 0.8289453983306885 }, { "filename": "src/types.ts", "retrieved_chunk": "export interface Commit extends GitCommit {\n resolvedAuthors?: AuthorInfo[];\n}\nexport interface ChangelogOptions extends ChangelogConfig {\n /**\n * Dry run. Skip releasing to GitHub.\n */\n dry?: boolean;\n /**\n * Whether to include contributors in release notes.", "score": 0.826010525226593 }, { "filename": "src/generate.ts", "retrieved_chunk": "import { getGitDiff } from './git';\nimport { generateMarkdown } from './markdown';\nimport { resolveAuthors } from './github';\nimport { resolveConfig } from './config';\nimport { parseCommits } from './parse';\nimport type { ChangelogOptions } from './types';\nexport async function generate(cwd: string, options: ChangelogOptions) {\n const resolved = await resolveConfig(cwd, options);\n const rawCommits = await getGitDiff(resolved.from, resolved.to);\n const commits = parseCommits(rawCommits, resolved);", "score": 0.8242596387863159 } ]
typescript
return commits.map(commit => parseGitCommit(commit, config)).filter(notNullish);
import { readPackageJSON } from 'pkg-types'; import type { Reference, ChangelogConfig, RepoProvider, RepoConfig } from './types'; import { getGitRemoteURL } from './git'; const providerToRefSpec: Record<RepoProvider, Record<Reference['type'], string>> = { github: { 'pull-request': 'pull', hash: 'commit', issue: 'issues' }, gitlab: { 'pull-request': 'merge_requests', hash: 'commit', issue: 'issues' }, bitbucket: { 'pull-request': 'pull-requests', hash: 'commit', issue: 'issues' } }; const providerToDomain: Record<RepoProvider, string> = { github: 'github.com', gitlab: 'gitlab.com', bitbucket: 'bitbucket.org' }; const domainToProvider: Record<string, RepoProvider> = { 'github.com': 'github', 'gitlab.com': 'gitlab', 'bitbucket.org': 'bitbucket' }; // https://regex101.com/r/NA4Io6/1 const providerURLRegex = /^(?:(?<user>\w+)@)?(?:(?<provider>[^/:]+):)?(?<repo>\w+\/\w+)(?:\.git)?$/; function baseUrl(config: RepoConfig) { return `https://${config.domain}/${config.repo}`; } export function formatReference(ref: Reference, repo?: RepoConfig) { if (!repo?.provider || !(repo.provider in providerToRefSpec)) { return ref.value; } const refSpec = providerToRefSpec[repo.provider]; return `[${ref.value}](${baseUrl(repo)}/${refSpec[ref.type]}/${ref.value.replace(/^#/, '')})`; } export function formatCompareChanges(v: string, config: ChangelogConfig) { const part = config.repo?.provider === 'bitbucket' ? 'branches/compare' : 'compare';
return `[compare changes](${baseUrl(config.repo)}/${part}/${config.from}...${v || config.to})`;
} export async function resolveRepoConfig(cwd: string) { // Try closest package.json const pkg = await readPackageJSON(cwd).catch(() => {}); if (pkg && pkg.repository) { const url = typeof pkg.repository === 'string' ? pkg.repository : pkg.repository.url; return getRepoConfig(url); } const gitRemote = await getGitRemoteURL(cwd).catch(() => {}); if (gitRemote) { return getRepoConfig(gitRemote); } return {}; } export function getRepoConfig(repoUrl = ''): RepoConfig { let provider: RepoProvider | undefined; let repo: string | undefined; let domain: string | undefined; let url: URL | undefined; try { url = new URL(repoUrl); } catch {} const m = repoUrl.match(providerURLRegex)?.groups ?? {}; if (m.repo && m.provider) { repo = m.repo; provider = m.provider in domainToProvider ? domainToProvider[m.provider] : (m.provider as RepoProvider); domain = provider in providerToDomain ? providerToDomain[provider] : provider; } else if (url) { domain = url.hostname; repo = url.pathname .split('/') .slice(1, 3) .join('/') .replace(/\.git$/, ''); provider = domainToProvider[domain]; } else if (m.repo) { repo = m.repo; provider = 'github'; domain = providerToDomain[provider]; } return { provider, repo, domain }; }
src/repo.ts
soybeanjs-githublogen-0932953
[ { "filename": "src/markdown.ts", "retrieved_chunk": " return `[<samp>(${ref.value.slice(0, 5)})</samp>](https://github.com/${github}/commit/${ref.value})`;\n });\n const referencesString = join(refs).trim();\n if (type === 'issues') {\n return referencesString && `in ${referencesString}`;\n }\n return referencesString;\n}\nfunction formatLine(commit: Commit, options: ResolvedChangelogOptions) {\n const prRefs = formatReferences(commit.references, options.repo.repo || '', 'issues');", "score": 0.8649319410324097 }, { "filename": "src/markdown.ts", "retrieved_chunk": " }\n return i.type === 'hash';\n })\n .map(ref => {\n if (!github) {\n return ref.value;\n }\n if (ref.type === 'pull-request' || ref.type === 'issue') {\n return `https://github.com/${github}/issues/${ref.value.slice(1)}`;\n }", "score": 0.8393077850341797 }, { "filename": "src/markdown.ts", "retrieved_chunk": " const hashRefs = formatReferences(commit.references, options.repo.repo || '', 'hash');\n let authors = join([\n ...new Set(commit.resolvedAuthors?.map(i => (i.login ? `@${i.login}` : `**${i.name}**`)))\n ])?.trim();\n if (authors) {\n authors = `by ${authors}`;\n }\n let refs = [authors, prRefs, hashRefs].filter(i => i?.trim()).join(' ');\n if (refs) {\n refs = `&nbsp;-&nbsp; ${refs}`;", "score": 0.8380303382873535 }, { "filename": "src/markdown.ts", "retrieved_chunk": " const url = `https://github.com/${options.repo.repo!}/compare/${options.from}...${options.to}`;\n lines.push('', `##### &nbsp;&nbsp;&nbsp;&nbsp;[View changes on GitHub](${url})`);\n return convert(lines.join('\\n').trim(), true);\n}", "score": 0.8290004134178162 }, { "filename": "src/markdown.ts", "retrieved_chunk": "import { convert } from 'convert-gitmoji';\nimport { partition, groupBy, capitalize, join } from './shared';\nimport type { Reference, Commit, ResolvedChangelogOptions } from './types';\nconst emojisRE =\n /([\\u2700-\\u27BF]|[\\uE000-\\uF8FF]|\\uD83C[\\uDC00-\\uDFFF]|\\uD83D[\\uDC00-\\uDFFF]|[\\u2011-\\u26FF]|\\uD83E[\\uDD10-\\uDDFF])/g;\nfunction formatReferences(references: Reference[], github: string, type: 'issues' | 'hash'): string {\n const refs = references\n .filter(i => {\n if (type === 'issues') {\n return i.type === 'issue' || i.type === 'pull-request';", "score": 0.8251307606697083 } ]
typescript
return `[compare changes](${baseUrl(config.repo)}/${part}/${config.from}...${v || config.to})`;
import { notNullish } from './shared'; import type { GitCommit, RawGitCommit, GitCommitAuthor, ChangelogConfig, Reference } from './types'; // https://www.conventionalcommits.org/en/v1.0.0/ // https://regex101.com/r/FSfNvA/1 const ConventionalCommitRegex = /(?<type>[a-z]+)(\((?<scope>.+)\))?(?<breaking>!)?: (?<description>.+)/i; const CoAuthoredByRegex = /co-authored-by:\s*(?<name>.+)(<(?<email>.+)>)/gim; const PullRequestRE = /\([a-z]*(#\d+)\s*\)/gm; const IssueRE = /(#\d+)/gm; export function parseGitCommit(commit: RawGitCommit, config: ChangelogConfig): GitCommit | null { const match = commit.message.match(ConventionalCommitRegex); if (!match?.groups) { return null; } const type = match.groups.type; let scope = match.groups.scope || ''; scope = config.scopeMap[scope] || scope; const isBreaking = Boolean(match.groups.breaking); let description = match.groups.description; // Extract references from message const references: Reference[] = []; for (const m of description.matchAll(PullRequestRE)) { references.push({ type: 'pull-request', value: m[1] }); } for (const m of description.matchAll(IssueRE)) { if (!references.some(i => i.value === m[1])) { references.push({ type: 'issue', value: m[1] }); } } references.push({ value: commit.shortHash, type: 'hash' }); // Remove references and normalize description = description.replace(PullRequestRE, '').trim(); // Find all authors const authors:
GitCommitAuthor[] = [commit.author];
const matchs = commit.body.matchAll(CoAuthoredByRegex); for (const $match of matchs) { const { name = '', email = '' } = $match.groups || {}; const author: GitCommitAuthor = { name: name.trim(), email: email.trim() }; authors.push(author); } return { ...commit, authors, description, type, scope, references, isBreaking }; } export function parseCommits(commits: RawGitCommit[], config: ChangelogConfig): GitCommit[] { return commits.map(commit => parseGitCommit(commit, config)).filter(notNullish); }
src/parse.ts
soybeanjs-githublogen-0932953
[ { "filename": "src/markdown.ts", "retrieved_chunk": " const hashRefs = formatReferences(commit.references, options.repo.repo || '', 'hash');\n let authors = join([\n ...new Set(commit.resolvedAuthors?.map(i => (i.login ? `@${i.login}` : `**${i.name}**`)))\n ])?.trim();\n if (authors) {\n authors = `by ${authors}`;\n }\n let refs = [authors, prRefs, hashRefs].filter(i => i?.trim()).join(' ');\n if (refs) {\n refs = `&nbsp;-&nbsp; ${refs}`;", "score": 0.8717930912971497 }, { "filename": "src/github.ts", "retrieved_chunk": " if (idx === 0) {\n info.commits.push(commit.shortHash);\n }\n return info;\n })\n .filter(notNullish);\n });\n const authors = Array.from(map.values());\n const resolved = await Promise.all(authors.map(info => resolveAuthorInfo(options, info)));\n const loginSet = new Set<string>();", "score": 0.84018474817276 }, { "filename": "src/markdown.ts", "retrieved_chunk": "import { convert } from 'convert-gitmoji';\nimport { partition, groupBy, capitalize, join } from './shared';\nimport type { Reference, Commit, ResolvedChangelogOptions } from './types';\nconst emojisRE =\n /([\\u2700-\\u27BF]|[\\uE000-\\uF8FF]|\\uD83C[\\uDC00-\\uDFFF]|\\uD83D[\\uDC00-\\uDFFF]|[\\u2011-\\u26FF]|\\uD83E[\\uDD10-\\uDDFF])/g;\nfunction formatReferences(references: Reference[], github: string, type: 'issues' | 'hash'): string {\n const refs = references\n .filter(i => {\n if (type === 'issues') {\n return i.type === 'issue' || i.type === 'pull-request';", "score": 0.838707685470581 }, { "filename": "src/markdown.ts", "retrieved_chunk": " return `[<samp>(${ref.value.slice(0, 5)})</samp>](https://github.com/${github}/commit/${ref.value})`;\n });\n const referencesString = join(refs).trim();\n if (type === 'issues') {\n return referencesString && `in ${referencesString}`;\n }\n return referencesString;\n}\nfunction formatLine(commit: Commit, options: ResolvedChangelogOptions) {\n const prRefs = formatReferences(commit.references, options.repo.repo || '', 'issues');", "score": 0.8313915729522705 }, { "filename": "src/github.ts", "retrieved_chunk": " }\n return info;\n}\nexport async function resolveAuthors(commits: Commit[], options: ChangelogOptions) {\n const map = new Map<string, AuthorInfo>();\n commits.forEach(commit => {\n commit.resolvedAuthors = commit.authors\n .map((a, idx) => {\n if (!a.email || !a.name) {\n return null;", "score": 0.8287469744682312 } ]
typescript
GitCommitAuthor[] = [commit.author];
import Event from "../../events/index.js"; import NDK from "../../index.js"; import { NDKFilter } from "../../subscription/index.js"; import { NDKRelay } from "../index.js"; import { NDKRelaySet } from "./index.js"; /** * Creates a NDKRelaySet for the specified event. * TODO: account for relays where tagged pubkeys or hashtags * tend to write to. * @param ndk {NDK} * @param event {Event} * @returns Promise<NDKRelaySet> */ export function calculateRelaySetFromEvent( ndk: NDK, event: Event ): NDKRelaySet { const relays: Set<NDKRelay> = new Set(); ndk.pool?.relays.forEach((relay) => relays.add(relay)); return new NDKRelaySet(relays, ndk); } /** * Creates a NDKRelaySet for the specified filter * @param ndk * @param filter * @returns Promise<NDKRelaySet> */ export function calculateRelaySetFromFilter( ndk: NDK, filter: NDKFilter ): NDKRelaySet { const relays: Set<NDKRelay> = new Set(); ndk.pool?.relays.forEach((relay) => { if (!relay.complaining) { relays.add(relay); } else { ndk.debug(`Relay ${relay.url} is complaining, not adding to set`); } }); return new NDKRelaySet(relays, ndk); } /** * Calculates a number of RelaySets for each filter. * @param ndk * @param filters */ export function calculateRelaySetsFromFilters( ndk: NDK, filters:
NDKFilter[] ): Map<NDKFilter, NDKRelaySet> {
const sets: Map<NDKFilter, NDKRelaySet> = new Map(); filters.forEach((filter) => { const set = calculateRelaySetFromFilter(ndk, filter); sets.set(filter, set); }); return sets; }
src/relay/sets/calculate.ts
nostr-dev-kit-ndk-ece64e1
[ { "filename": "src/relay/sets/index.ts", "retrieved_chunk": " */\n static fromRelayUrls(relayUrls: string[], ndk: NDK): NDKRelaySet {\n const relays = new Set<NDKRelay>();\n for (const url of relayUrls) {\n const relay = ndk.pool.relays.get(url);\n if (relay) {\n relays.add(relay);\n }\n }\n return new NDKRelaySet(new Set(relays), ndk);", "score": 0.8353937864303589 }, { "filename": "src/subscription/index.ts", "retrieved_chunk": "export function mergeFilters(filters: NDKFilter[]): NDKFilter {\n const result: any = {};\n filters.forEach((filter) => {\n Object.entries(filter).forEach(([key, value]) => {\n if (Array.isArray(value)) {\n if (result[key] === undefined) {\n result[key] = [...value];\n } else {\n result[key] = Array.from(\n new Set([...result[key], ...value])", "score": 0.8318208456039429 }, { "filename": "src/relay/sets/index.ts", "retrieved_chunk": " public constructor(relays: Set<NDKRelay>, ndk: NDK) {\n this.relays = relays;\n this.ndk = ndk;\n this.debug = ndk.debug.extend(\"relayset\");\n }\n /**\n * Adds a relay to this set.\n */\n public addRelay(relay: NDKRelay) {\n this.relays.add(relay);", "score": 0.8084904551506042 }, { "filename": "src/relay/pool/index.ts", "retrieved_chunk": " public relays = new Map<string, NDKRelay>();\n private debug: debug.Debugger;\n private temporaryRelayTimers = new Map<string, NodeJS.Timeout>();\n public constructor(relayUrls: string[] = [], ndk: NDK) {\n super();\n this.debug = ndk.debug.extend(\"pool\");\n for (const relayUrl of relayUrls) {\n const relay = new NDKRelay(relayUrl);\n this.addRelay(relay, false);\n }", "score": 0.8049031496047974 }, { "filename": "src/subscription/index.ts", "retrieved_chunk": " }\n private startWithRelaySet(): void {\n if (!this.relaySet) {\n this.relaySet = calculateRelaySetFromFilter(\n this.ndk,\n this.filters[0]\n );\n }\n if (this.relaySet) {\n this.relaySet.subscribe(this);", "score": 0.8044642210006714 } ]
typescript
NDKFilter[] ): Map<NDKFilter, NDKRelaySet> {
import Event from "../../events/index.js"; import NDK from "../../index.js"; import { NDKFilter } from "../../subscription/index.js"; import { NDKRelay } from "../index.js"; import { NDKRelaySet } from "./index.js"; /** * Creates a NDKRelaySet for the specified event. * TODO: account for relays where tagged pubkeys or hashtags * tend to write to. * @param ndk {NDK} * @param event {Event} * @returns Promise<NDKRelaySet> */ export function calculateRelaySetFromEvent( ndk: NDK, event: Event ): NDKRelaySet { const relays: Set<NDKRelay> = new Set(); ndk.pool?.relays.forEach((relay) => relays.add(relay)); return new NDKRelaySet(relays, ndk); } /** * Creates a NDKRelaySet for the specified filter * @param ndk * @param filter * @returns Promise<NDKRelaySet> */ export function calculateRelaySetFromFilter( ndk: NDK, filter: NDKFilter ): NDKRelaySet { const relays: Set<NDKRelay> = new Set(); ndk.pool?.relays.forEach((relay) => { if (!relay.complaining) { relays.add(relay); } else { ndk.debug(`Relay ${relay.url} is complaining, not adding to set`); } }); return new NDKRelaySet(relays, ndk); } /** * Calculates a number of RelaySets for each filter. * @param ndk * @param filters */ export function calculateRelaySetsFromFilters( ndk: NDK, filters: NDKFilter[]
): Map<NDKFilter, NDKRelaySet> {
const sets: Map<NDKFilter, NDKRelaySet> = new Map(); filters.forEach((filter) => { const set = calculateRelaySetFromFilter(ndk, filter); sets.set(filter, set); }); return sets; }
src/relay/sets/calculate.ts
nostr-dev-kit-ndk-ece64e1
[ { "filename": "src/relay/sets/index.ts", "retrieved_chunk": " */\n static fromRelayUrls(relayUrls: string[], ndk: NDK): NDKRelaySet {\n const relays = new Set<NDKRelay>();\n for (const url of relayUrls) {\n const relay = ndk.pool.relays.get(url);\n if (relay) {\n relays.add(relay);\n }\n }\n return new NDKRelaySet(new Set(relays), ndk);", "score": 0.8409936428070068 }, { "filename": "src/subscription/index.ts", "retrieved_chunk": "export function mergeFilters(filters: NDKFilter[]): NDKFilter {\n const result: any = {};\n filters.forEach((filter) => {\n Object.entries(filter).forEach(([key, value]) => {\n if (Array.isArray(value)) {\n if (result[key] === undefined) {\n result[key] = [...value];\n } else {\n result[key] = Array.from(\n new Set([...result[key], ...value])", "score": 0.8377320766448975 }, { "filename": "src/relay/sets/index.ts", "retrieved_chunk": " public constructor(relays: Set<NDKRelay>, ndk: NDK) {\n this.relays = relays;\n this.ndk = ndk;\n this.debug = ndk.debug.extend(\"relayset\");\n }\n /**\n * Adds a relay to this set.\n */\n public addRelay(relay: NDKRelay) {\n this.relays.add(relay);", "score": 0.815650463104248 }, { "filename": "src/relay/pool/index.ts", "retrieved_chunk": " public relays = new Map<string, NDKRelay>();\n private debug: debug.Debugger;\n private temporaryRelayTimers = new Map<string, NodeJS.Timeout>();\n public constructor(relayUrls: string[] = [], ndk: NDK) {\n super();\n this.debug = ndk.debug.extend(\"pool\");\n for (const relayUrl of relayUrls) {\n const relay = new NDKRelay(relayUrl);\n this.addRelay(relay, false);\n }", "score": 0.8123220205307007 }, { "filename": "src/subscription/index.ts", "retrieved_chunk": " }\n private startWithRelaySet(): void {\n if (!this.relaySet) {\n this.relaySet = calculateRelaySetFromFilter(\n this.ndk,\n this.filters[0]\n );\n }\n if (this.relaySet) {\n this.relaySet.subscribe(this);", "score": 0.8111081123352051 } ]
typescript
): Map<NDKFilter, NDKRelaySet> {
import { verifySignature, Event } from "nostr-tools"; import NDK, { NDKEvent, NDKPrivateKeySigner, NDKUser } from "../../../index.js"; import { NDKNostrRpc } from "../rpc.js"; import ConnectEventHandlingStrategy from "./connect.js"; import DescribeEventHandlingStrategy from "./describe.js"; import GetPublicKeyHandlingStrategy from "./get-public-key.js"; import Nip04DecryptHandlingStrategy from "./nip04-decrypt.js"; import Nip04EncryptHandlingStrategy from "./nip04-encrypt.js"; import SignEventHandlingStrategy from "./sign-event.js"; export type Nip46PermitCallback = ( pubkey: string, method: string, params?: any ) => Promise<boolean>; export type Nip46ApplyTokenCallback = ( pubkey: string, token: string ) => Promise<void>; export interface IEventHandlingStrategy { handle( backend: NDKNip46Backend, remotePubkey: string, params: string[] ): Promise<string | undefined>; } /** * This class implements a NIP-46 backend, meaning that it will hold a private key * of the npub that wants to be published as. * * This backend is meant to be used by an NDKNip46Signer, which is the class that * should run client-side, where the user wants to sign events from. */ export class NDKNip46Backend { readonly ndk: NDK; readonly signer: NDKPrivateKeySigner; public localUser?: NDKUser; readonly debug: debug.Debugger; private rpc: NDKNostrRpc; private permitCallback: Nip46PermitCallback; /** * @param ndk The NDK instance to use * @param privateKey The private key of the npub that wants to be published as */ public constructor( ndk: NDK, privateKey: string, permitCallback: Nip46PermitCallback ) { this.ndk = ndk; this.signer = new NDKPrivateKeySigner(privateKey); this.debug = ndk.debug.extend("nip46:backend"); this.rpc = new NDKNostrRpc(ndk, this.signer, this.debug); this.permitCallback = permitCallback; } /** * This method starts the backend, which will start listening for incoming * requests. */ public async start() { this.localUser = await this.signer.user(); const sub = this.ndk.subscribe( { kinds: [24133 as number], "#p": [this.localUser.hexpubkey()], }, { closeOnEose: false } ); sub.on("event", (e) => this.handleIncomingEvent(e)); } public handlers: { [method: string]: IEventHandlingStrategy } = { connect: new ConnectEventHandlingStrategy(), sign_event: new SignEventHandlingStrategy(), nip04_encrypt: new Nip04EncryptHandlingStrategy(),
nip04_decrypt: new Nip04DecryptHandlingStrategy(), get_public_key: new GetPublicKeyHandlingStrategy(), describe: new DescribeEventHandlingStrategy(), };
/** * Enables the user to set a custom strategy for handling incoming events. * @param method - The method to set the strategy for * @param strategy - The strategy to set */ public setStrategy(method: string, strategy: IEventHandlingStrategy) { this.handlers[method] = strategy; } /** * Overload this method to apply tokens, which can * wrap permission sets to be applied to a pubkey. * @param pubkey public key to apply token to * @param token token to apply */ async applyToken(pubkey: string, token: string): Promise<void> { throw new Error("connection token not supported"); } protected async handleIncomingEvent(event: NDKEvent) { const { id, method, params } = (await this.rpc.parseEvent( event )) as any; const remotePubkey = event.pubkey; let response: string | undefined; this.debug("incoming event", { id, method, params }); // validate signature explicitly if (!verifySignature(event.rawEvent() as Event<any>)) { this.debug("invalid signature", event.rawEvent()); return; } const strategy = this.handlers[method]; if (strategy) { try { response = await strategy.handle(this, remotePubkey, params); } catch (e: any) { this.debug("error handling event", e, { id, method, params }); this.rpc.sendResponse( id, remotePubkey, "error", undefined, e.message ); } } else { this.debug("unsupported method", { method, params }); } if (response) { this.debug(`sending response to ${remotePubkey}`, response); this.rpc.sendResponse(id, remotePubkey, response); } else { this.rpc.sendResponse( id, remotePubkey, "error", undefined, "Not authorized" ); } } public async decrypt( remotePubkey: string, senderUser: NDKUser, payload: string ) { if (!(await this.pubkeyAllowed(remotePubkey, "decrypt", payload))) { this.debug(`decrypt request from ${remotePubkey} rejected`); return undefined; } return await this.signer.decrypt(senderUser, payload); } public async encrypt( remotePubkey: string, recipientUser: NDKUser, payload: string ) { if (!(await this.pubkeyAllowed(remotePubkey, "encrypt", payload))) { this.debug(`encrypt request from ${remotePubkey} rejected`); return undefined; } return await this.signer.encrypt(recipientUser, payload); } public async signEvent( remotePubkey: string, params: string[] ): Promise<NDKEvent | undefined> { const [eventString] = params; this.debug(`sign event request from ${remotePubkey}`); const event = new NDKEvent(this.ndk, JSON.parse(eventString)); this.debug("event to sign", event.rawEvent()); if (!(await this.pubkeyAllowed(remotePubkey, "sign_event", event))) { this.debug(`sign event request from ${remotePubkey} rejected`); return undefined; } this.debug(`sign event request from ${remotePubkey} allowed`); await event.sign(this.signer); return event; } /** * This method should be overriden by the user to allow or reject incoming * connections. */ public async pubkeyAllowed( pubkey: string, method: string, params?: any ): Promise<boolean> { return this.permitCallback(pubkey, method, params); } }
src/signers/nip46/backend/index.ts
nostr-dev-kit-ndk-ece64e1
[ { "filename": "src/subscription/index.ts", "retrieved_chunk": " this.on(\"event:dup\", this.forwardEventDup);\n this.on(\"eose\", this.forwardEose);\n this.on(\"close\", this.forwardClose);\n }\n private isEventForSubscription(\n event: NDKEvent,\n subscription: NDKSubscription\n ): boolean {\n const { filters } = subscription;\n if (!filters) return false;", "score": 0.8423566818237305 }, { "filename": "src/relay/index.ts", "retrieved_chunk": " id: subscription.subId,\n });\n this.debug(`Subscribed to ${JSON.stringify(filters)}`);\n sub.on(\"event\", (event: NostrEvent) => {\n const e = new NDKEvent(undefined, event);\n e.relay = this;\n subscription.eventReceived(e, this);\n });\n sub.on(\"eose\", () => {\n subscription.eoseReceived(this);", "score": 0.8366457223892212 }, { "filename": "src/signers/nip46/rpc.ts", "retrieved_chunk": " this.emit(\"request\", parsedEvent);\n } else {\n this.emit(`response-${parsedEvent.id}`, parsedEvent);\n }\n } catch (e) {\n this.debug(\"error parsing event\", e, event);\n }\n });\n return new Promise((resolve, reject) => {\n sub.on(\"eose\", () => resolve(sub));", "score": 0.83497154712677 }, { "filename": "src/signers/nip46/backend/connect.ts", "retrieved_chunk": "import { IEventHandlingStrategy, NDKNip46Backend } from \"./index.js\";\nexport default class ConnectEventHandlingStrategy\n implements IEventHandlingStrategy\n{\n async handle(\n backend: NDKNip46Backend,\n remotePubkey: string,\n params: string[]\n ): Promise<string | undefined> {\n const [pubkey, token] = params;", "score": 0.823696494102478 }, { "filename": "src/signers/nip46/backend/sign-event.ts", "retrieved_chunk": "import { IEventHandlingStrategy, NDKNip46Backend } from \"./index.js\";\nexport default class SignEventHandlingStrategy\n implements IEventHandlingStrategy\n{\n async handle(\n backend: NDKNip46Backend,\n remotePubkey: string,\n params: string[]\n ): Promise<string | undefined> {\n const event = await backend.signEvent(remotePubkey, params);", "score": 0.8224643468856812 } ]
typescript
nip04_decrypt: new Nip04DecryptHandlingStrategy(), get_public_key: new GetPublicKeyHandlingStrategy(), describe: new DescribeEventHandlingStrategy(), };
import { verifySignature, Event } from "nostr-tools"; import NDK, { NDKEvent, NDKPrivateKeySigner, NDKUser } from "../../../index.js"; import { NDKNostrRpc } from "../rpc.js"; import ConnectEventHandlingStrategy from "./connect.js"; import DescribeEventHandlingStrategy from "./describe.js"; import GetPublicKeyHandlingStrategy from "./get-public-key.js"; import Nip04DecryptHandlingStrategy from "./nip04-decrypt.js"; import Nip04EncryptHandlingStrategy from "./nip04-encrypt.js"; import SignEventHandlingStrategy from "./sign-event.js"; export type Nip46PermitCallback = ( pubkey: string, method: string, params?: any ) => Promise<boolean>; export type Nip46ApplyTokenCallback = ( pubkey: string, token: string ) => Promise<void>; export interface IEventHandlingStrategy { handle( backend: NDKNip46Backend, remotePubkey: string, params: string[] ): Promise<string | undefined>; } /** * This class implements a NIP-46 backend, meaning that it will hold a private key * of the npub that wants to be published as. * * This backend is meant to be used by an NDKNip46Signer, which is the class that * should run client-side, where the user wants to sign events from. */ export class NDKNip46Backend { readonly ndk: NDK; readonly signer: NDKPrivateKeySigner; public localUser?: NDKUser; readonly debug: debug.Debugger; private rpc: NDKNostrRpc; private permitCallback: Nip46PermitCallback; /** * @param ndk The NDK instance to use * @param privateKey The private key of the npub that wants to be published as */ public constructor( ndk: NDK, privateKey: string, permitCallback: Nip46PermitCallback ) { this.ndk = ndk; this.signer = new NDKPrivateKeySigner(privateKey); this.debug = ndk.debug.extend("nip46:backend"); this.rpc = new NDKNostrRpc(ndk, this.signer, this.debug); this.permitCallback = permitCallback; } /** * This method starts the backend, which will start listening for incoming * requests. */ public async start() { this.localUser = await this.signer.user(); const sub = this.ndk.subscribe( { kinds: [24133 as number], "#p": [this.localUser.hexpubkey()], }, { closeOnEose: false } ); sub.
on("event", (e) => this.handleIncomingEvent(e));
} public handlers: { [method: string]: IEventHandlingStrategy } = { connect: new ConnectEventHandlingStrategy(), sign_event: new SignEventHandlingStrategy(), nip04_encrypt: new Nip04EncryptHandlingStrategy(), nip04_decrypt: new Nip04DecryptHandlingStrategy(), get_public_key: new GetPublicKeyHandlingStrategy(), describe: new DescribeEventHandlingStrategy(), }; /** * Enables the user to set a custom strategy for handling incoming events. * @param method - The method to set the strategy for * @param strategy - The strategy to set */ public setStrategy(method: string, strategy: IEventHandlingStrategy) { this.handlers[method] = strategy; } /** * Overload this method to apply tokens, which can * wrap permission sets to be applied to a pubkey. * @param pubkey public key to apply token to * @param token token to apply */ async applyToken(pubkey: string, token: string): Promise<void> { throw new Error("connection token not supported"); } protected async handleIncomingEvent(event: NDKEvent) { const { id, method, params } = (await this.rpc.parseEvent( event )) as any; const remotePubkey = event.pubkey; let response: string | undefined; this.debug("incoming event", { id, method, params }); // validate signature explicitly if (!verifySignature(event.rawEvent() as Event<any>)) { this.debug("invalid signature", event.rawEvent()); return; } const strategy = this.handlers[method]; if (strategy) { try { response = await strategy.handle(this, remotePubkey, params); } catch (e: any) { this.debug("error handling event", e, { id, method, params }); this.rpc.sendResponse( id, remotePubkey, "error", undefined, e.message ); } } else { this.debug("unsupported method", { method, params }); } if (response) { this.debug(`sending response to ${remotePubkey}`, response); this.rpc.sendResponse(id, remotePubkey, response); } else { this.rpc.sendResponse( id, remotePubkey, "error", undefined, "Not authorized" ); } } public async decrypt( remotePubkey: string, senderUser: NDKUser, payload: string ) { if (!(await this.pubkeyAllowed(remotePubkey, "decrypt", payload))) { this.debug(`decrypt request from ${remotePubkey} rejected`); return undefined; } return await this.signer.decrypt(senderUser, payload); } public async encrypt( remotePubkey: string, recipientUser: NDKUser, payload: string ) { if (!(await this.pubkeyAllowed(remotePubkey, "encrypt", payload))) { this.debug(`encrypt request from ${remotePubkey} rejected`); return undefined; } return await this.signer.encrypt(recipientUser, payload); } public async signEvent( remotePubkey: string, params: string[] ): Promise<NDKEvent | undefined> { const [eventString] = params; this.debug(`sign event request from ${remotePubkey}`); const event = new NDKEvent(this.ndk, JSON.parse(eventString)); this.debug("event to sign", event.rawEvent()); if (!(await this.pubkeyAllowed(remotePubkey, "sign_event", event))) { this.debug(`sign event request from ${remotePubkey} rejected`); return undefined; } this.debug(`sign event request from ${remotePubkey} allowed`); await event.sign(this.signer); return event; } /** * This method should be overriden by the user to allow or reject incoming * connections. */ public async pubkeyAllowed( pubkey: string, method: string, params?: any ): Promise<boolean> { return this.permitCallback(pubkey, method, params); } }
src/signers/nip46/backend/index.ts
nostr-dev-kit-ndk-ece64e1
[ { "filename": "src/signers/nip46/index.ts", "retrieved_chunk": " const user = this.ndk.getUser({ npub: localUser.npub });\n // Generates subscription, single subscription for the lifetime of our connection\n await this.rpc.subscribe({\n kinds: [24133 as number],\n \"#p\": [localUser.hexpubkey()],\n });\n return new Promise((resolve, reject) => {\n // There is a race condition between the subscription and sending the request;\n // introducing a small delay here to give a clear priority to the subscription\n // to happen first", "score": 0.9045444130897522 }, { "filename": "src/signers/nip46/rpc.ts", "retrieved_chunk": " event.content = await this.signer.encrypt(remoteUser, event.content);\n await event.sign(this.signer);\n this.debug(\"sending request to\", remotePubkey);\n await this.ndk.publish(event);\n return promise;\n }\n}", "score": 0.8816788792610168 }, { "filename": "src/signers/nip46/rpc.ts", "retrieved_chunk": " const localUser = await this.signer.user();\n const remoteUser = this.ndk.getUser({ hexpubkey: remotePubkey });\n const event = new NDKEvent(this.ndk, {\n kind,\n content: JSON.stringify(res),\n tags: [[\"p\", remotePubkey]],\n pubkey: localUser.hexpubkey(),\n } as NostrEvent);\n event.content = await this.signer.encrypt(remoteUser, event.content);\n await event.sign(this.signer);", "score": 0.8796818256378174 }, { "filename": "src/events/repost.ts", "retrieved_chunk": " if (!signer) {\n throw new Error(\"No signer available\");\n }\n const user = await signer.user();\n const e = new NDKEvent(this.ndk, {\n kind: getKind(this),\n content: \"\",\n pubkey: user.hexpubkey(),\n } as NostrEvent);\n e.tag(this);", "score": 0.8771969676017761 }, { "filename": "src/signers/nip46/index.ts", "retrieved_chunk": " this.rpc = new NDKNostrRpc(ndk, this.localSigner, this.debug);\n }\n /**\n * Get the user that is being published as\n */\n public async user(): Promise<NDKUser> {\n return this.remoteUser;\n }\n public async blockUntilReady(): Promise<NDKUser> {\n const localUser = await this.localSigner.user();", "score": 0.8735676407814026 } ]
typescript
on("event", (e) => this.handleIncomingEvent(e));
import { sha256 } from "@noble/hashes/sha256"; import { bytesToHex } from "@noble/hashes/utils"; import NDKEvent from "../../events/index.js"; import type NDK from "../../index.js"; import { NDKSubscription, NDKSubscriptionGroup, } from "../../subscription/index.js"; import { NDKRelay, NDKRelayStatus } from "../index.js"; /** * A relay set is a group of relays. This grouping can be short-living, for a single * REQ or can be long-lasting, for example for the explicit relay list the user * has specified. * * Requests to relays should be sent through this interface. */ export class NDKRelaySet { readonly relays: Set<NDKRelay>; private debug: debug.Debugger; private ndk: NDK; public constructor(relays: Set<NDKRelay>, ndk: NDK) { this.relays = relays; this.ndk = ndk; this.debug = ndk.debug.extend("relayset"); } /** * Adds a relay to this set. */ public addRelay(relay: NDKRelay) { this.relays.add(relay); } /** * Creates a relay set from a list of relay URLs. * * This is useful for testing in development to pass a local relay * to publish methods. * * @param relayUrls - list of relay URLs to include in this set * @param ndk * @returns NDKRelaySet */ static fromRelayUrls(relayUrls: string[], ndk: NDK): NDKRelaySet { const relays = new Set<NDKRelay>(); for (const url of relayUrls) { const relay = ndk.pool.relays.get(url); if (relay) { relays.add(relay); } } return new NDKRelaySet(new Set(relays), ndk); } private subscribeOnRelay(relay: NDKRelay, subscription: NDKSubscription) { const sub = relay.subscribe(subscription); subscription.relaySubscriptions.set(relay, sub); } /** * Calculates an ID of this specific combination of relays. */ public getId() { const urls = Array.from(this.relays).map((r) => r.url); const urlString = urls.sort().join(","); return bytesToHex(sha256(urlString)); } /** * Add a subscription to this relay set */ public subscribe(subscription: NDKSubscription): NDKSubscription { const subGroupableId = subscription.groupableId(); const groupableId = `${this.getId()}:${subGroupableId}`; if (!subGroupableId) { this.executeSubscription(subscription); return subscription; } const delayedSubscription = this.ndk.delayedSubscriptions.get(groupableId); if (delayedSubscription) { delayedSubscription.push(subscription); } else { setTimeout(() => { this.executeDelayedSubscription(groupableId); }, subscription.opts.groupableDelay); this.ndk.delayedSubscriptions.set(groupableId, [subscription]); } return subscription; } private executeDelayedSubscription(groupableId: string) { const subscriptions = this.ndk.delayedSubscriptions.get(groupableId); this.ndk.delayedSubscriptions.delete(groupableId); if (subscriptions) { if (subscriptions.length > 1) { this.executeSubscriptions(subscriptions); } else { this.executeSubscription(subscriptions[0]); } } } /** * This function takes a similar group of subscriptions, merges the filters * and sends a single subscription to the relay. */ private executeSubscriptions(subscriptions: NDKSubscription[]) { const ndk = subscriptions[0].ndk; const subGroup = new NDKSubscriptionGroup(ndk, subscriptions); this.executeSubscription(subGroup); } private executeSubscription( subscription: NDKSubscription ): NDKSubscription { this.debug("subscribing", { filters: subscription.filters }); for (const relay of this.relays) { if (relay.status === NDKRelayStatus.CONNECTED) { // If the relay is already connected, subscribe immediately this.subscribeOnRelay(relay, subscription); } else { // If the relay is not connected, add a one-time listener to wait for the 'connected' event const connectedListener = () => { this.debug( "new relay coming online for active subscription", { relay: relay.url, filters: subscription.filters, } ); this.subscribeOnRelay(relay, subscription); }; relay.once("connect", connectedListener); // Add a one-time listener to remove the connectedListener when the subscription stops subscription.once("close", () => { relay.removeListener("connect", connectedListener); }); } } return subscription; } /** * Publish an event to all relays in this set. Returns the number of relays that have received the event. * @param event * @param timeoutMs - timeout in milliseconds for each publish operation and connection operation * @returns A set where the event was successfully published to */ public async publish( event
: NDKEvent, timeoutMs?: number ): Promise<Set<NDKRelay>> {
const publishedToRelays: Set<NDKRelay> = new Set(); // go through each relay and publish the event const promises: Promise<void>[] = Array.from(this.relays).map( (relay: NDKRelay) => { return new Promise<void>((resolve) => { relay .publish(event, timeoutMs) .then(() => { publishedToRelays.add(relay); resolve(); }) .catch((err) => { this.debug("error publishing to relay", { relay: relay.url, err, }); resolve(); }); }); } ); await Promise.all(promises); if (publishedToRelays.size === 0) { throw new Error("No relay was able to receive the event"); } return publishedToRelays; } public size(): number { return this.relays.size; } }
src/relay/sets/index.ts
nostr-dev-kit-ndk-ece64e1
[ { "filename": "src/index.ts", "retrieved_chunk": " * @param event event to publish\n * @param relaySet explicit relay set to use\n * @param timeoutMs timeout in milliseconds to wait for the event to be published\n * @returns The relays the event was published to\n *\n * @deprecated Use `event.publish()` instead\n */\n public async publish(\n event: NDKEvent,\n relaySet?: NDKRelaySet,", "score": 0.9321928024291992 }, { "filename": "src/index.ts", "retrieved_chunk": " timeoutMs?: number\n ): Promise<Set<NDKRelay>> {\n this.debug(\"Deprecated: Use `event.publish()` instead\");\n if (!relaySet) {\n // If we have a devWriteRelaySet, use it to publish all events\n relaySet =\n this.devWriteRelaySet ||\n calculateRelaySetFromEvent(this, event);\n }\n return relaySet.publish(event, timeoutMs);", "score": 0.9153062105178833 }, { "filename": "src/relay/index.ts", "retrieved_chunk": " * @param timeoutMs The timeout for the publish operation in milliseconds\n * @returns A promise that resolves when the event has been published or rejects if the operation times out\n */\n public async publish(event: NDKEvent, timeoutMs = 2500): Promise<boolean> {\n if (this.status === NDKRelayStatus.CONNECTED) {\n return this.publishEvent(event, timeoutMs);\n } else {\n this.once(\"connect\", () => {\n this.publishEvent(event, timeoutMs);\n });", "score": 0.9115073084831238 }, { "filename": "src/relay/index.ts", "retrieved_chunk": " return true;\n }\n }\n private async publishEvent(\n event: NDKEvent,\n timeoutMs?: number\n ): Promise<boolean> {\n const nostrEvent = await event.toNostrEvent();\n const publish = this.relay.publish(nostrEvent as any);\n let publishTimeout: NodeJS.Timeout | number;", "score": 0.8884018063545227 }, { "filename": "src/events/index.ts", "retrieved_chunk": " * @param relaySet {NDKRelaySet} The relaySet to publish the even to.\n * @returns A promise that resolves to the relays the event was published to.\n */\n public async publish(\n relaySet?: NDKRelaySet,\n timeoutMs?: number\n ): Promise<Set<NDKRelay>> {\n if (!this.sig) await this.sign();\n if (!this.ndk)\n throw new Error(", "score": 0.8815478682518005 } ]
typescript
: NDKEvent, timeoutMs?: number ): Promise<Set<NDKRelay>> {
import { verifySignature, Event } from "nostr-tools"; import NDK, { NDKEvent, NDKPrivateKeySigner, NDKUser } from "../../../index.js"; import { NDKNostrRpc } from "../rpc.js"; import ConnectEventHandlingStrategy from "./connect.js"; import DescribeEventHandlingStrategy from "./describe.js"; import GetPublicKeyHandlingStrategy from "./get-public-key.js"; import Nip04DecryptHandlingStrategy from "./nip04-decrypt.js"; import Nip04EncryptHandlingStrategy from "./nip04-encrypt.js"; import SignEventHandlingStrategy from "./sign-event.js"; export type Nip46PermitCallback = ( pubkey: string, method: string, params?: any ) => Promise<boolean>; export type Nip46ApplyTokenCallback = ( pubkey: string, token: string ) => Promise<void>; export interface IEventHandlingStrategy { handle( backend: NDKNip46Backend, remotePubkey: string, params: string[] ): Promise<string | undefined>; } /** * This class implements a NIP-46 backend, meaning that it will hold a private key * of the npub that wants to be published as. * * This backend is meant to be used by an NDKNip46Signer, which is the class that * should run client-side, where the user wants to sign events from. */ export class NDKNip46Backend { readonly ndk: NDK; readonly signer: NDKPrivateKeySigner; public localUser?: NDKUser; readonly debug: debug.Debugger; private rpc: NDKNostrRpc; private permitCallback: Nip46PermitCallback; /** * @param ndk The NDK instance to use * @param privateKey The private key of the npub that wants to be published as */ public constructor( ndk: NDK, privateKey: string, permitCallback: Nip46PermitCallback ) { this.ndk = ndk; this.signer = new NDKPrivateKeySigner(privateKey); this.debug = ndk.debug.extend("nip46:backend"); this.rpc = new NDKNostrRpc(ndk, this.signer, this.debug); this.permitCallback = permitCallback; } /** * This method starts the backend, which will start listening for incoming * requests. */ public async start() { this.localUser = await this.signer.user(); const sub = this.ndk.subscribe( { kinds: [24133 as number], "#p": [this.localUser.hexpubkey()], }, { closeOnEose: false } ); sub.on("event", (e) => this.handleIncomingEvent(e)); } public handlers: { [method: string]: IEventHandlingStrategy } = { connect: new ConnectEventHandlingStrategy(), sign_event: new SignEventHandlingStrategy(), nip04_encrypt: new Nip04EncryptHandlingStrategy(), nip04_decrypt: new Nip04DecryptHandlingStrategy(), get_public_key: new GetPublicKeyHandlingStrategy(), describe: new DescribeEventHandlingStrategy(), }; /** * Enables the user to set a custom strategy for handling incoming events. * @param method - The method to set the strategy for * @param strategy - The strategy to set */ public setStrategy(method: string, strategy: IEventHandlingStrategy) { this.handlers[method] = strategy; } /** * Overload this method to apply tokens, which can * wrap permission sets to be applied to a pubkey. * @param pubkey public key to apply token to * @param token token to apply */ async applyToken(pubkey: string, token: string): Promise<void> { throw new Error("connection token not supported"); } protected async handleIncomingEvent(event: NDKEvent) { const { id, method, params } = (await this.rpc.parseEvent( event )) as any; const remotePubkey = event.pubkey; let response: string | undefined; this.debug("incoming event", { id, method, params }); // validate signature explicitly if (!verifySignature(event.rawEvent() as Event<any>)) { this.debug("invalid signature", event.rawEvent()); return; } const strategy = this.handlers[method]; if (strategy) { try { response = await strategy.handle(this, remotePubkey, params); } catch (e: any) { this.debug("error handling event", e, { id, method, params }); this.rpc.sendResponse( id, remotePubkey, "error", undefined, e.message ); } } else { this.debug("unsupported method", { method, params }); } if (response) { this.debug(`sending response to ${remotePubkey}`, response); this.rpc.sendResponse(id, remotePubkey, response); } else { this.rpc.sendResponse( id, remotePubkey, "error", undefined, "Not authorized" ); } } public async decrypt( remotePubkey: string,
senderUser: NDKUser, payload: string ) {
if (!(await this.pubkeyAllowed(remotePubkey, "decrypt", payload))) { this.debug(`decrypt request from ${remotePubkey} rejected`); return undefined; } return await this.signer.decrypt(senderUser, payload); } public async encrypt( remotePubkey: string, recipientUser: NDKUser, payload: string ) { if (!(await this.pubkeyAllowed(remotePubkey, "encrypt", payload))) { this.debug(`encrypt request from ${remotePubkey} rejected`); return undefined; } return await this.signer.encrypt(recipientUser, payload); } public async signEvent( remotePubkey: string, params: string[] ): Promise<NDKEvent | undefined> { const [eventString] = params; this.debug(`sign event request from ${remotePubkey}`); const event = new NDKEvent(this.ndk, JSON.parse(eventString)); this.debug("event to sign", event.rawEvent()); if (!(await this.pubkeyAllowed(remotePubkey, "sign_event", event))) { this.debug(`sign event request from ${remotePubkey} rejected`); return undefined; } this.debug(`sign event request from ${remotePubkey} allowed`); await event.sign(this.signer); return event; } /** * This method should be overriden by the user to allow or reject incoming * connections. */ public async pubkeyAllowed( pubkey: string, method: string, params?: any ): Promise<boolean> { return this.permitCallback(pubkey, method, params); } }
src/signers/nip46/backend/index.ts
nostr-dev-kit-ndk-ece64e1
[ { "filename": "src/signers/nip46/backend/nip04-decrypt.ts", "retrieved_chunk": " const [senderPubkey, payload] = params;\n const senderUser = new NDKUser({ hexpubkey: senderPubkey });\n const decryptedPayload = await backend.decrypt(\n remotePubkey,\n senderUser,\n payload\n );\n return JSON.stringify([decryptedPayload]);\n }\n}", "score": 0.8744996786117554 }, { "filename": "src/signers/nip46/index.ts", "retrieved_chunk": " public async decrypt(sender: NDKUser, value: string): Promise<string> {\n this.debug(\"asking for decryption\");\n const promise = new Promise<string>((resolve, reject) => {\n this.rpc.sendRequest(\n this.remotePubkey,\n \"nip04_decrypt\",\n [sender.hexpubkey(), value],\n 24133,\n (response: NDKRpcResponse) => {\n if (!response.error) {", "score": 0.872126579284668 }, { "filename": "src/signers/nip46/backend/nip04-encrypt.ts", "retrieved_chunk": " const [recipientPubkey, payload] = params;\n const recipientUser = new NDKUser({ hexpubkey: recipientPubkey });\n const decryptedPayload = await backend.encrypt(\n remotePubkey,\n recipientUser,\n payload\n );\n return decryptedPayload;\n }\n}", "score": 0.8688933849334717 }, { "filename": "src/signers/index.ts", "retrieved_chunk": " * @param value\n */\n decrypt(sender: NDKUser, value: string): Promise<string>;\n}", "score": 0.8687533736228943 }, { "filename": "src/events/nip04.ts", "retrieved_chunk": " );\n }\n recipient = new NDKUser({ hexpubkey: pTags[0][1] });\n recipient.ndk = this.ndk;\n }\n this.content = await signer.encrypt(recipient, this.content);\n}\nexport async function decrypt(\n this: NDKEvent,\n sender?: NDKUser,", "score": 0.8659965395927429 } ]
typescript
senderUser: NDKUser, payload: string ) {
import { verifySignature, Event } from "nostr-tools"; import NDK, { NDKEvent, NDKPrivateKeySigner, NDKUser } from "../../../index.js"; import { NDKNostrRpc } from "../rpc.js"; import ConnectEventHandlingStrategy from "./connect.js"; import DescribeEventHandlingStrategy from "./describe.js"; import GetPublicKeyHandlingStrategy from "./get-public-key.js"; import Nip04DecryptHandlingStrategy from "./nip04-decrypt.js"; import Nip04EncryptHandlingStrategy from "./nip04-encrypt.js"; import SignEventHandlingStrategy from "./sign-event.js"; export type Nip46PermitCallback = ( pubkey: string, method: string, params?: any ) => Promise<boolean>; export type Nip46ApplyTokenCallback = ( pubkey: string, token: string ) => Promise<void>; export interface IEventHandlingStrategy { handle( backend: NDKNip46Backend, remotePubkey: string, params: string[] ): Promise<string | undefined>; } /** * This class implements a NIP-46 backend, meaning that it will hold a private key * of the npub that wants to be published as. * * This backend is meant to be used by an NDKNip46Signer, which is the class that * should run client-side, where the user wants to sign events from. */ export class NDKNip46Backend { readonly ndk: NDK; readonly signer: NDKPrivateKeySigner; public localUser?: NDKUser; readonly debug: debug.Debugger; private rpc: NDKNostrRpc; private permitCallback: Nip46PermitCallback; /** * @param ndk The NDK instance to use * @param privateKey The private key of the npub that wants to be published as */ public constructor( ndk: NDK, privateKey: string, permitCallback: Nip46PermitCallback ) { this.ndk = ndk; this.signer = new NDKPrivateKeySigner(privateKey); this.debug = ndk.debug.extend("nip46:backend"); this.rpc = new NDKNostrRpc(ndk, this.signer, this.debug); this.permitCallback = permitCallback; } /** * This method starts the backend, which will start listening for incoming * requests. */ public async start() { this.localUser = await this.signer.user(); const sub = this.ndk.subscribe( { kinds: [24133 as number], "#p": [this.localUser.hexpubkey()], }, { closeOnEose: false } ); sub.on("event", (e) => this.handleIncomingEvent(e)); } public handlers: { [method: string]: IEventHandlingStrategy } = { connect: new ConnectEventHandlingStrategy(), sign_event: new SignEventHandlingStrategy(), nip04_encrypt: new Nip04EncryptHandlingStrategy(), nip04_decrypt: new Nip04DecryptHandlingStrategy(), get_public_key
: new GetPublicKeyHandlingStrategy(), describe: new DescribeEventHandlingStrategy(), };
/** * Enables the user to set a custom strategy for handling incoming events. * @param method - The method to set the strategy for * @param strategy - The strategy to set */ public setStrategy(method: string, strategy: IEventHandlingStrategy) { this.handlers[method] = strategy; } /** * Overload this method to apply tokens, which can * wrap permission sets to be applied to a pubkey. * @param pubkey public key to apply token to * @param token token to apply */ async applyToken(pubkey: string, token: string): Promise<void> { throw new Error("connection token not supported"); } protected async handleIncomingEvent(event: NDKEvent) { const { id, method, params } = (await this.rpc.parseEvent( event )) as any; const remotePubkey = event.pubkey; let response: string | undefined; this.debug("incoming event", { id, method, params }); // validate signature explicitly if (!verifySignature(event.rawEvent() as Event<any>)) { this.debug("invalid signature", event.rawEvent()); return; } const strategy = this.handlers[method]; if (strategy) { try { response = await strategy.handle(this, remotePubkey, params); } catch (e: any) { this.debug("error handling event", e, { id, method, params }); this.rpc.sendResponse( id, remotePubkey, "error", undefined, e.message ); } } else { this.debug("unsupported method", { method, params }); } if (response) { this.debug(`sending response to ${remotePubkey}`, response); this.rpc.sendResponse(id, remotePubkey, response); } else { this.rpc.sendResponse( id, remotePubkey, "error", undefined, "Not authorized" ); } } public async decrypt( remotePubkey: string, senderUser: NDKUser, payload: string ) { if (!(await this.pubkeyAllowed(remotePubkey, "decrypt", payload))) { this.debug(`decrypt request from ${remotePubkey} rejected`); return undefined; } return await this.signer.decrypt(senderUser, payload); } public async encrypt( remotePubkey: string, recipientUser: NDKUser, payload: string ) { if (!(await this.pubkeyAllowed(remotePubkey, "encrypt", payload))) { this.debug(`encrypt request from ${remotePubkey} rejected`); return undefined; } return await this.signer.encrypt(recipientUser, payload); } public async signEvent( remotePubkey: string, params: string[] ): Promise<NDKEvent | undefined> { const [eventString] = params; this.debug(`sign event request from ${remotePubkey}`); const event = new NDKEvent(this.ndk, JSON.parse(eventString)); this.debug("event to sign", event.rawEvent()); if (!(await this.pubkeyAllowed(remotePubkey, "sign_event", event))) { this.debug(`sign event request from ${remotePubkey} rejected`); return undefined; } this.debug(`sign event request from ${remotePubkey} allowed`); await event.sign(this.signer); return event; } /** * This method should be overriden by the user to allow or reject incoming * connections. */ public async pubkeyAllowed( pubkey: string, method: string, params?: any ): Promise<boolean> { return this.permitCallback(pubkey, method, params); } }
src/signers/nip46/backend/index.ts
nostr-dev-kit-ndk-ece64e1
[ { "filename": "src/signers/nip46/backend/describe.ts", "retrieved_chunk": "import { IEventHandlingStrategy, NDKNip46Backend } from \"./index.js\";\nexport default class DescribeHandlingStrategy\n implements IEventHandlingStrategy\n{\n async handle(\n backend: NDKNip46Backend,\n remotePubkey: string,\n params: string[]\n ): Promise<string | undefined> {\n const keys = Object.keys(backend.handlers);", "score": 0.8443061709403992 }, { "filename": "src/signers/nip46/backend/sign-event.ts", "retrieved_chunk": "import { IEventHandlingStrategy, NDKNip46Backend } from \"./index.js\";\nexport default class SignEventHandlingStrategy\n implements IEventHandlingStrategy\n{\n async handle(\n backend: NDKNip46Backend,\n remotePubkey: string,\n params: string[]\n ): Promise<string | undefined> {\n const event = await backend.signEvent(remotePubkey, params);", "score": 0.8395335674285889 }, { "filename": "src/signers/nip46/backend/connect.ts", "retrieved_chunk": "import { IEventHandlingStrategy, NDKNip46Backend } from \"./index.js\";\nexport default class ConnectEventHandlingStrategy\n implements IEventHandlingStrategy\n{\n async handle(\n backend: NDKNip46Backend,\n remotePubkey: string,\n params: string[]\n ): Promise<string | undefined> {\n const [pubkey, token] = params;", "score": 0.8278505802154541 }, { "filename": "src/signers/nip46/backend/get-public-key.ts", "retrieved_chunk": "import { IEventHandlingStrategy, NDKNip46Backend } from \"./index.js\";\nexport default class GetPublicKeyHandlingStrategy\n implements IEventHandlingStrategy\n{\n async handle(\n backend: NDKNip46Backend,\n remotePubkey: string,\n params: string[]\n ): Promise<string | undefined> {\n return backend.localUser?.hexpubkey();", "score": 0.807172417640686 }, { "filename": "src/signers/nip46/backend/nip04-encrypt.ts", "retrieved_chunk": "import NDKUser from \"../../../user/index.js\";\nimport { IEventHandlingStrategy, NDKNip46Backend } from \"./index.js\";\nexport default class Nip04EncryptHandlingStrategy\n implements IEventHandlingStrategy\n{\n async handle(\n backend: NDKNip46Backend,\n remotePubkey: string,\n params: string[]\n ): Promise<string | undefined> {", "score": 0.8055802583694458 } ]
typescript
: new GetPublicKeyHandlingStrategy(), describe: new DescribeEventHandlingStrategy(), };
import { verifySignature, Event } from "nostr-tools"; import NDK, { NDKEvent, NDKPrivateKeySigner, NDKUser } from "../../../index.js"; import { NDKNostrRpc } from "../rpc.js"; import ConnectEventHandlingStrategy from "./connect.js"; import DescribeEventHandlingStrategy from "./describe.js"; import GetPublicKeyHandlingStrategy from "./get-public-key.js"; import Nip04DecryptHandlingStrategy from "./nip04-decrypt.js"; import Nip04EncryptHandlingStrategy from "./nip04-encrypt.js"; import SignEventHandlingStrategy from "./sign-event.js"; export type Nip46PermitCallback = ( pubkey: string, method: string, params?: any ) => Promise<boolean>; export type Nip46ApplyTokenCallback = ( pubkey: string, token: string ) => Promise<void>; export interface IEventHandlingStrategy { handle( backend: NDKNip46Backend, remotePubkey: string, params: string[] ): Promise<string | undefined>; } /** * This class implements a NIP-46 backend, meaning that it will hold a private key * of the npub that wants to be published as. * * This backend is meant to be used by an NDKNip46Signer, which is the class that * should run client-side, where the user wants to sign events from. */ export class NDKNip46Backend { readonly ndk: NDK; readonly signer: NDKPrivateKeySigner; public localUser?: NDKUser; readonly debug: debug.Debugger; private rpc: NDKNostrRpc; private permitCallback: Nip46PermitCallback; /** * @param ndk The NDK instance to use * @param privateKey The private key of the npub that wants to be published as */ public constructor( ndk: NDK, privateKey: string, permitCallback: Nip46PermitCallback ) { this.ndk = ndk; this.signer = new NDKPrivateKeySigner(privateKey); this.debug = ndk.debug.extend("nip46:backend"); this.rpc = new NDKNostrRpc(ndk, this.signer, this.debug); this.permitCallback = permitCallback; } /** * This method starts the backend, which will start listening for incoming * requests. */ public async start() { this.localUser = await this.signer.user(); const sub = this.ndk.subscribe( { kinds: [24133 as number], "#p": [this.localUser.hexpubkey()], }, { closeOnEose: false } ); sub.on("event", (e) => this.handleIncomingEvent(e)); } public handlers: { [method: string]: IEventHandlingStrategy } = { connect: new ConnectEventHandlingStrategy(), sign_event: new SignEventHandlingStrategy(),
nip04_encrypt: new Nip04EncryptHandlingStrategy(), nip04_decrypt: new Nip04DecryptHandlingStrategy(), get_public_key: new GetPublicKeyHandlingStrategy(), describe: new DescribeEventHandlingStrategy(), };
/** * Enables the user to set a custom strategy for handling incoming events. * @param method - The method to set the strategy for * @param strategy - The strategy to set */ public setStrategy(method: string, strategy: IEventHandlingStrategy) { this.handlers[method] = strategy; } /** * Overload this method to apply tokens, which can * wrap permission sets to be applied to a pubkey. * @param pubkey public key to apply token to * @param token token to apply */ async applyToken(pubkey: string, token: string): Promise<void> { throw new Error("connection token not supported"); } protected async handleIncomingEvent(event: NDKEvent) { const { id, method, params } = (await this.rpc.parseEvent( event )) as any; const remotePubkey = event.pubkey; let response: string | undefined; this.debug("incoming event", { id, method, params }); // validate signature explicitly if (!verifySignature(event.rawEvent() as Event<any>)) { this.debug("invalid signature", event.rawEvent()); return; } const strategy = this.handlers[method]; if (strategy) { try { response = await strategy.handle(this, remotePubkey, params); } catch (e: any) { this.debug("error handling event", e, { id, method, params }); this.rpc.sendResponse( id, remotePubkey, "error", undefined, e.message ); } } else { this.debug("unsupported method", { method, params }); } if (response) { this.debug(`sending response to ${remotePubkey}`, response); this.rpc.sendResponse(id, remotePubkey, response); } else { this.rpc.sendResponse( id, remotePubkey, "error", undefined, "Not authorized" ); } } public async decrypt( remotePubkey: string, senderUser: NDKUser, payload: string ) { if (!(await this.pubkeyAllowed(remotePubkey, "decrypt", payload))) { this.debug(`decrypt request from ${remotePubkey} rejected`); return undefined; } return await this.signer.decrypt(senderUser, payload); } public async encrypt( remotePubkey: string, recipientUser: NDKUser, payload: string ) { if (!(await this.pubkeyAllowed(remotePubkey, "encrypt", payload))) { this.debug(`encrypt request from ${remotePubkey} rejected`); return undefined; } return await this.signer.encrypt(recipientUser, payload); } public async signEvent( remotePubkey: string, params: string[] ): Promise<NDKEvent | undefined> { const [eventString] = params; this.debug(`sign event request from ${remotePubkey}`); const event = new NDKEvent(this.ndk, JSON.parse(eventString)); this.debug("event to sign", event.rawEvent()); if (!(await this.pubkeyAllowed(remotePubkey, "sign_event", event))) { this.debug(`sign event request from ${remotePubkey} rejected`); return undefined; } this.debug(`sign event request from ${remotePubkey} allowed`); await event.sign(this.signer); return event; } /** * This method should be overriden by the user to allow or reject incoming * connections. */ public async pubkeyAllowed( pubkey: string, method: string, params?: any ): Promise<boolean> { return this.permitCallback(pubkey, method, params); } }
src/signers/nip46/backend/index.ts
nostr-dev-kit-ndk-ece64e1
[ { "filename": "src/subscription/index.ts", "retrieved_chunk": " this.on(\"event:dup\", this.forwardEventDup);\n this.on(\"eose\", this.forwardEose);\n this.on(\"close\", this.forwardClose);\n }\n private isEventForSubscription(\n event: NDKEvent,\n subscription: NDKSubscription\n ): boolean {\n const { filters } = subscription;\n if (!filters) return false;", "score": 0.8423566818237305 }, { "filename": "src/relay/index.ts", "retrieved_chunk": " id: subscription.subId,\n });\n this.debug(`Subscribed to ${JSON.stringify(filters)}`);\n sub.on(\"event\", (event: NostrEvent) => {\n const e = new NDKEvent(undefined, event);\n e.relay = this;\n subscription.eventReceived(e, this);\n });\n sub.on(\"eose\", () => {\n subscription.eoseReceived(this);", "score": 0.8366457223892212 }, { "filename": "src/signers/nip46/rpc.ts", "retrieved_chunk": " this.emit(\"request\", parsedEvent);\n } else {\n this.emit(`response-${parsedEvent.id}`, parsedEvent);\n }\n } catch (e) {\n this.debug(\"error parsing event\", e, event);\n }\n });\n return new Promise((resolve, reject) => {\n sub.on(\"eose\", () => resolve(sub));", "score": 0.83497154712677 }, { "filename": "src/signers/nip46/backend/connect.ts", "retrieved_chunk": "import { IEventHandlingStrategy, NDKNip46Backend } from \"./index.js\";\nexport default class ConnectEventHandlingStrategy\n implements IEventHandlingStrategy\n{\n async handle(\n backend: NDKNip46Backend,\n remotePubkey: string,\n params: string[]\n ): Promise<string | undefined> {\n const [pubkey, token] = params;", "score": 0.823696494102478 }, { "filename": "src/signers/nip46/backend/sign-event.ts", "retrieved_chunk": "import { IEventHandlingStrategy, NDKNip46Backend } from \"./index.js\";\nexport default class SignEventHandlingStrategy\n implements IEventHandlingStrategy\n{\n async handle(\n backend: NDKNip46Backend,\n remotePubkey: string,\n params: string[]\n ): Promise<string | undefined> {\n const event = await backend.signEvent(remotePubkey, params);", "score": 0.8224643468856812 } ]
typescript
nip04_encrypt: new Nip04EncryptHandlingStrategy(), nip04_decrypt: new Nip04DecryptHandlingStrategy(), get_public_key: new GetPublicKeyHandlingStrategy(), describe: new DescribeEventHandlingStrategy(), };
import { verifySignature, Event } from "nostr-tools"; import NDK, { NDKEvent, NDKPrivateKeySigner, NDKUser } from "../../../index.js"; import { NDKNostrRpc } from "../rpc.js"; import ConnectEventHandlingStrategy from "./connect.js"; import DescribeEventHandlingStrategy from "./describe.js"; import GetPublicKeyHandlingStrategy from "./get-public-key.js"; import Nip04DecryptHandlingStrategy from "./nip04-decrypt.js"; import Nip04EncryptHandlingStrategy from "./nip04-encrypt.js"; import SignEventHandlingStrategy from "./sign-event.js"; export type Nip46PermitCallback = ( pubkey: string, method: string, params?: any ) => Promise<boolean>; export type Nip46ApplyTokenCallback = ( pubkey: string, token: string ) => Promise<void>; export interface IEventHandlingStrategy { handle( backend: NDKNip46Backend, remotePubkey: string, params: string[] ): Promise<string | undefined>; } /** * This class implements a NIP-46 backend, meaning that it will hold a private key * of the npub that wants to be published as. * * This backend is meant to be used by an NDKNip46Signer, which is the class that * should run client-side, where the user wants to sign events from. */ export class NDKNip46Backend { readonly ndk: NDK; readonly signer: NDKPrivateKeySigner; public localUser?: NDKUser; readonly debug: debug.Debugger; private rpc: NDKNostrRpc; private permitCallback: Nip46PermitCallback; /** * @param ndk The NDK instance to use * @param privateKey The private key of the npub that wants to be published as */ public constructor( ndk: NDK, privateKey: string, permitCallback: Nip46PermitCallback ) { this.ndk = ndk; this.signer = new NDKPrivateKeySigner(privateKey); this.debug = ndk.debug.extend("nip46:backend"); this.rpc = new NDKNostrRpc(ndk, this.signer, this.debug); this.permitCallback = permitCallback; } /** * This method starts the backend, which will start listening for incoming * requests. */ public async start() { this.localUser = await this.signer.user(); const sub = this.ndk.subscribe( { kinds: [24133 as number], "#p": [this.localUser.hexpubkey()], }, { closeOnEose: false } ); sub.on("event", (e) => this.handleIncomingEvent(e)); } public handlers: { [method: string]: IEventHandlingStrategy } = { connect: new ConnectEventHandlingStrategy(), sign_event: new SignEventHandlingStrategy(), nip04_encrypt: new Nip04EncryptHandlingStrategy(), nip04_decrypt: new Nip04DecryptHandlingStrategy(), get_public_key: new GetPublicKeyHandlingStrategy(),
describe: new DescribeEventHandlingStrategy(), };
/** * Enables the user to set a custom strategy for handling incoming events. * @param method - The method to set the strategy for * @param strategy - The strategy to set */ public setStrategy(method: string, strategy: IEventHandlingStrategy) { this.handlers[method] = strategy; } /** * Overload this method to apply tokens, which can * wrap permission sets to be applied to a pubkey. * @param pubkey public key to apply token to * @param token token to apply */ async applyToken(pubkey: string, token: string): Promise<void> { throw new Error("connection token not supported"); } protected async handleIncomingEvent(event: NDKEvent) { const { id, method, params } = (await this.rpc.parseEvent( event )) as any; const remotePubkey = event.pubkey; let response: string | undefined; this.debug("incoming event", { id, method, params }); // validate signature explicitly if (!verifySignature(event.rawEvent() as Event<any>)) { this.debug("invalid signature", event.rawEvent()); return; } const strategy = this.handlers[method]; if (strategy) { try { response = await strategy.handle(this, remotePubkey, params); } catch (e: any) { this.debug("error handling event", e, { id, method, params }); this.rpc.sendResponse( id, remotePubkey, "error", undefined, e.message ); } } else { this.debug("unsupported method", { method, params }); } if (response) { this.debug(`sending response to ${remotePubkey}`, response); this.rpc.sendResponse(id, remotePubkey, response); } else { this.rpc.sendResponse( id, remotePubkey, "error", undefined, "Not authorized" ); } } public async decrypt( remotePubkey: string, senderUser: NDKUser, payload: string ) { if (!(await this.pubkeyAllowed(remotePubkey, "decrypt", payload))) { this.debug(`decrypt request from ${remotePubkey} rejected`); return undefined; } return await this.signer.decrypt(senderUser, payload); } public async encrypt( remotePubkey: string, recipientUser: NDKUser, payload: string ) { if (!(await this.pubkeyAllowed(remotePubkey, "encrypt", payload))) { this.debug(`encrypt request from ${remotePubkey} rejected`); return undefined; } return await this.signer.encrypt(recipientUser, payload); } public async signEvent( remotePubkey: string, params: string[] ): Promise<NDKEvent | undefined> { const [eventString] = params; this.debug(`sign event request from ${remotePubkey}`); const event = new NDKEvent(this.ndk, JSON.parse(eventString)); this.debug("event to sign", event.rawEvent()); if (!(await this.pubkeyAllowed(remotePubkey, "sign_event", event))) { this.debug(`sign event request from ${remotePubkey} rejected`); return undefined; } this.debug(`sign event request from ${remotePubkey} allowed`); await event.sign(this.signer); return event; } /** * This method should be overriden by the user to allow or reject incoming * connections. */ public async pubkeyAllowed( pubkey: string, method: string, params?: any ): Promise<boolean> { return this.permitCallback(pubkey, method, params); } }
src/signers/nip46/backend/index.ts
nostr-dev-kit-ndk-ece64e1
[ { "filename": "src/subscription/index.ts", "retrieved_chunk": " this.on(\"event:dup\", this.forwardEventDup);\n this.on(\"eose\", this.forwardEose);\n this.on(\"close\", this.forwardClose);\n }\n private isEventForSubscription(\n event: NDKEvent,\n subscription: NDKSubscription\n ): boolean {\n const { filters } = subscription;\n if (!filters) return false;", "score": 0.8423566818237305 }, { "filename": "src/relay/index.ts", "retrieved_chunk": " id: subscription.subId,\n });\n this.debug(`Subscribed to ${JSON.stringify(filters)}`);\n sub.on(\"event\", (event: NostrEvent) => {\n const e = new NDKEvent(undefined, event);\n e.relay = this;\n subscription.eventReceived(e, this);\n });\n sub.on(\"eose\", () => {\n subscription.eoseReceived(this);", "score": 0.8366457223892212 }, { "filename": "src/signers/nip46/rpc.ts", "retrieved_chunk": " this.emit(\"request\", parsedEvent);\n } else {\n this.emit(`response-${parsedEvent.id}`, parsedEvent);\n }\n } catch (e) {\n this.debug(\"error parsing event\", e, event);\n }\n });\n return new Promise((resolve, reject) => {\n sub.on(\"eose\", () => resolve(sub));", "score": 0.83497154712677 }, { "filename": "src/signers/nip46/backend/connect.ts", "retrieved_chunk": "import { IEventHandlingStrategy, NDKNip46Backend } from \"./index.js\";\nexport default class ConnectEventHandlingStrategy\n implements IEventHandlingStrategy\n{\n async handle(\n backend: NDKNip46Backend,\n remotePubkey: string,\n params: string[]\n ): Promise<string | undefined> {\n const [pubkey, token] = params;", "score": 0.823696494102478 }, { "filename": "src/signers/nip46/backend/sign-event.ts", "retrieved_chunk": "import { IEventHandlingStrategy, NDKNip46Backend } from \"./index.js\";\nexport default class SignEventHandlingStrategy\n implements IEventHandlingStrategy\n{\n async handle(\n backend: NDKNip46Backend,\n remotePubkey: string,\n params: string[]\n ): Promise<string | undefined> {\n const event = await backend.signEvent(remotePubkey, params);", "score": 0.8224643468856812 } ]
typescript
describe: new DescribeEventHandlingStrategy(), };
import { sha256 } from "@noble/hashes/sha256"; import { bytesToHex } from "@noble/hashes/utils"; import NDKEvent from "../../events/index.js"; import type NDK from "../../index.js"; import { NDKSubscription, NDKSubscriptionGroup, } from "../../subscription/index.js"; import { NDKRelay, NDKRelayStatus } from "../index.js"; /** * A relay set is a group of relays. This grouping can be short-living, for a single * REQ or can be long-lasting, for example for the explicit relay list the user * has specified. * * Requests to relays should be sent through this interface. */ export class NDKRelaySet { readonly relays: Set<NDKRelay>; private debug: debug.Debugger; private ndk: NDK; public constructor(relays: Set<NDKRelay>, ndk: NDK) { this.relays = relays; this.ndk = ndk; this.debug = ndk.debug.extend("relayset"); } /** * Adds a relay to this set. */ public addRelay(relay: NDKRelay) { this.relays.add(relay); } /** * Creates a relay set from a list of relay URLs. * * This is useful for testing in development to pass a local relay * to publish methods. * * @param relayUrls - list of relay URLs to include in this set * @param ndk * @returns NDKRelaySet */ static fromRelayUrls(relayUrls: string[], ndk: NDK): NDKRelaySet { const relays = new Set<NDKRelay>(); for (const url of relayUrls) { const relay = ndk.pool.relays.get(url); if (relay) { relays.add(relay); } } return new NDKRelaySet(new Set(relays), ndk); } private subscribeOnRelay(relay: NDKRelay, subscription: NDKSubscription) { const sub = relay.subscribe(subscription); subscription.relaySubscriptions.set(relay, sub); } /** * Calculates an ID of this specific combination of relays. */ public getId() { const urls = Array.from(this.relays).map((r) => r.url); const urlString = urls.sort().join(","); return bytesToHex(sha256(urlString)); } /** * Add a subscription to this relay set */ public subscribe(subscription: NDKSubscription): NDKSubscription { const subGroupableId = subscription.groupableId(); const groupableId = `${this.getId()}:${subGroupableId}`; if (!subGroupableId) { this.executeSubscription(subscription); return subscription; } const delayedSubscription = this.ndk.delayedSubscriptions.get(groupableId); if (delayedSubscription) { delayedSubscription.push(subscription); } else { setTimeout(() => { this.executeDelayedSubscription(groupableId); }, subscription.opts.groupableDelay); this.ndk.delayedSubscriptions.set(groupableId, [subscription]); } return subscription; } private executeDelayedSubscription(groupableId: string) { const subscriptions = this.ndk.delayedSubscriptions.get(groupableId); this.ndk.delayedSubscriptions.delete(groupableId); if (subscriptions) { if (subscriptions.length > 1) { this.executeSubscriptions(subscriptions); } else { this.executeSubscription(subscriptions[0]); } } } /** * This function takes a similar group of subscriptions, merges the filters * and sends a single subscription to the relay. */ private executeSubscriptions(subscriptions: NDKSubscription[]) { const ndk = subscriptions[0].ndk; const subGroup = new NDKSubscriptionGroup(ndk, subscriptions); this.executeSubscription(subGroup); } private executeSubscription( subscription: NDKSubscription ): NDKSubscription { this.debug("subscribing", { filters: subscription.filters }); for (const relay of this.relays) { if (relay.status === NDKRelayStatus.CONNECTED) { // If the relay is already connected, subscribe immediately this.subscribeOnRelay(relay, subscription); } else { // If the relay is not connected, add a one-time listener to wait for the 'connected' event const connectedListener = () => { this.debug( "new relay coming online for active subscription", { relay: relay.url, filters: subscription.filters, } ); this.subscribeOnRelay(relay, subscription); }; relay.once("connect", connectedListener); // Add a one-time listener to remove the connectedListener when the subscription stops subscription.once("close", () => { relay.removeListener("connect", connectedListener); }); } } return subscription; } /** * Publish an event to all relays in this set. Returns the number of relays that have received the event. * @param event * @param timeoutMs - timeout in milliseconds for each publish operation and connection operation * @returns A set where the event was successfully published to */ public async publish( event:
NDKEvent, timeoutMs?: number ): Promise<Set<NDKRelay>> {
const publishedToRelays: Set<NDKRelay> = new Set(); // go through each relay and publish the event const promises: Promise<void>[] = Array.from(this.relays).map( (relay: NDKRelay) => { return new Promise<void>((resolve) => { relay .publish(event, timeoutMs) .then(() => { publishedToRelays.add(relay); resolve(); }) .catch((err) => { this.debug("error publishing to relay", { relay: relay.url, err, }); resolve(); }); }); } ); await Promise.all(promises); if (publishedToRelays.size === 0) { throw new Error("No relay was able to receive the event"); } return publishedToRelays; } public size(): number { return this.relays.size; } }
src/relay/sets/index.ts
nostr-dev-kit-ndk-ece64e1
[ { "filename": "src/index.ts", "retrieved_chunk": " * @param event event to publish\n * @param relaySet explicit relay set to use\n * @param timeoutMs timeout in milliseconds to wait for the event to be published\n * @returns The relays the event was published to\n *\n * @deprecated Use `event.publish()` instead\n */\n public async publish(\n event: NDKEvent,\n relaySet?: NDKRelaySet,", "score": 0.9323080778121948 }, { "filename": "src/index.ts", "retrieved_chunk": " timeoutMs?: number\n ): Promise<Set<NDKRelay>> {\n this.debug(\"Deprecated: Use `event.publish()` instead\");\n if (!relaySet) {\n // If we have a devWriteRelaySet, use it to publish all events\n relaySet =\n this.devWriteRelaySet ||\n calculateRelaySetFromEvent(this, event);\n }\n return relaySet.publish(event, timeoutMs);", "score": 0.9129652380943298 }, { "filename": "src/relay/index.ts", "retrieved_chunk": " * @param timeoutMs The timeout for the publish operation in milliseconds\n * @returns A promise that resolves when the event has been published or rejects if the operation times out\n */\n public async publish(event: NDKEvent, timeoutMs = 2500): Promise<boolean> {\n if (this.status === NDKRelayStatus.CONNECTED) {\n return this.publishEvent(event, timeoutMs);\n } else {\n this.once(\"connect\", () => {\n this.publishEvent(event, timeoutMs);\n });", "score": 0.9090929627418518 }, { "filename": "src/relay/index.ts", "retrieved_chunk": " return true;\n }\n }\n private async publishEvent(\n event: NDKEvent,\n timeoutMs?: number\n ): Promise<boolean> {\n const nostrEvent = await event.toNostrEvent();\n const publish = this.relay.publish(nostrEvent as any);\n let publishTimeout: NodeJS.Timeout | number;", "score": 0.8852417469024658 }, { "filename": "src/events/index.ts", "retrieved_chunk": " * @param relaySet {NDKRelaySet} The relaySet to publish the even to.\n * @returns A promise that resolves to the relays the event was published to.\n */\n public async publish(\n relaySet?: NDKRelaySet,\n timeoutMs?: number\n ): Promise<Set<NDKRelay>> {\n if (!this.sig) await this.sign();\n if (!this.ndk)\n throw new Error(", "score": 0.8800364136695862 } ]
typescript
NDKEvent, timeoutMs?: number ): Promise<Set<NDKRelay>> {
import debug from "debug"; import type { NostrEvent } from "../../events/index.js"; import NDKUser from "../../user/index.js"; import { NDKSigner } from "../index.js"; type Nip04QueueItem = { type: "encrypt" | "decrypt"; counterpartyHexpubkey: string; value: string; resolve: (value: string) => void; reject: (reason?: Error) => void; }; /** * NDKNip07Signer implements the NDKSigner interface for signing Nostr events * with a NIP-07 browser extension (e.g., getalby, nos2x). */ export class NDKNip07Signer implements NDKSigner { private _userPromise: Promise<NDKUser> | undefined; public nip04Queue: Nip04QueueItem[] = []; private nip04Processing = false; private debug: debug.Debugger; public constructor() { if (!window.nostr) { throw new Error("NIP-07 extension not available"); } this.debug = debug("ndk:nip07"); } public async blockUntilReady(): Promise<NDKUser> { const pubkey = await window.nostr?.getPublicKey(); // If the user rejects granting access, error out if (!pubkey) { throw new Error("User rejected access"); } return new NDKUser({ hexpubkey: pubkey }); } /** * Getter for the user property. * @returns The NDKUser instance. */ public async user(): Promise<NDKUser> { if (!this._userPromise) { this._userPromise = this.blockUntilReady(); } return this._userPromise; } /** * Signs the given Nostr event. * @param event - The Nostr event to be signed. * @returns The signature of the signed event. * @throws Error if the NIP-07 is not available on the window object. */ public async sign(event: NostrEvent): Promise<string> { if (!window.nostr) { throw new Error("NIP-07 extension not available"); } const signedEvent = await window.nostr.signEvent(event); return signedEvent.sig; } public async encrypt(recipient: NDKUser, value: string): Promise<string> { if (!window.nostr) { throw new Error("NIP-07 extension not available"); } const recipientHexPubKey = recipient.hexpubkey(); return this.queueNip04("encrypt", recipientHexPubKey, value); } public async decrypt(sender: NDKUser, value: string): Promise<string> { if (!window.nostr) { throw new Error("NIP-07 extension not available"); } const senderHexPubKey = sender.hexpubkey(); return this.queueNip04("decrypt", senderHexPubKey, value); } private async queueNip04( type: "encrypt" | "decrypt", counterpartyHexpubkey: string, value: string ): Promise<string> { return new Promise((resolve, reject) => { this.nip04Queue.push({ type, counterpartyHexpubkey, value, resolve, reject, }); if (!this.nip04Processing) { this.processNip04Queue(); } }); } private async processNip04Queue( item?: Nip04QueueItem, retries = 0 ): Promise<void> { if (!item && this.nip04Queue.length === 0) { this.nip04Processing = false; return; } this.nip04Processing = true; const { type, counterpartyHexpubkey, value, resolve, reject } = item || this.nip04Queue.shift()!; this.debug("Processing encryption queue item", { type, counterpartyHexpubkey, value, }); try { let result; if (type === "encrypt") { result = await window.nostr!.nip04.encrypt( counterpartyHexpubkey, value ); } else { result = await window.nostr!.nip04.decrypt( counterpartyHexpubkey, value ); } resolve(result); } catch (error: any) { // retry a few times if the call is already executing if ( error.message && error.message.includes("call already executing") ) { if (retries < 5) { this.debug("Retrying encryption queue item", { type, counterpartyHexpubkey, value, retries, }); setTimeout(() => { this.processNip04Queue(item, retries + 1); }, 50 * retries); return; } } reject(error); } this.processNip04Queue(); } } declare global { interface Window { nostr?: { getPublicKey(): Promise<string>;
signEvent(event: NostrEvent): Promise<{ sig: string }>;
nip04: { encrypt( recipientHexPubKey: string, value: string ): Promise<string>; decrypt( senderHexPubKey: string, value: string ): Promise<string>; }; }; } }
src/signers/nip07/index.ts
nostr-dev-kit-ndk-ece64e1
[ { "filename": "src/signers/private-key/index.ts", "retrieved_chunk": "import type { UnsignedEvent } from \"nostr-tools\";\nimport {\n generatePrivateKey,\n getPublicKey,\n nip04,\n getSignature,\n} from \"nostr-tools\";\nimport type { NostrEvent } from \"../../events/index.js\";\nimport NDKUser from \"../../user\";\nimport { NDKSigner } from \"../index.js\";", "score": 0.8684321045875549 }, { "filename": "src/signers/nip46/index.ts", "retrieved_chunk": " public async sign(event: NostrEvent): Promise<string> {\n this.debug(\"asking for a signature\");\n const promise = new Promise<string>((resolve, reject) => {\n this.rpc.sendRequest(\n this.remotePubkey,\n \"sign_event\",\n [JSON.stringify(event)],\n 24133,\n (response: NDKRpcResponse) => {\n this.debug(\"got a response\", response);", "score": 0.8527652025222778 }, { "filename": "src/events/index.ts", "retrieved_chunk": " */\n async toNostrEvent(pubkey?: string): Promise<NostrEvent> {\n if (!pubkey && this.pubkey === \"\") {\n const user = await this.ndk?.signer?.user();\n this.pubkey = user?.hexpubkey() || \"\";\n }\n if (!this.created_at) this.created_at = Math.floor(Date.now() / 1000);\n const nostrEvent = this.rawEvent();\n const { content, tags } = this.generateTags();\n nostrEvent.content = content || \"\";", "score": 0.8523586988449097 }, { "filename": "src/signers/private-key/index.ts", "retrieved_chunk": " }\n public async user(): Promise<NDKUser> {\n await this.blockUntilReady();\n return this._user as NDKUser;\n }\n public async sign(event: NostrEvent): Promise<string> {\n if (!this.privateKey) {\n throw Error(\"Attempted to sign without a private key\");\n }\n return getSignature(event as UnsignedEvent, this.privateKey);", "score": 0.8499025702476501 }, { "filename": "src/signers/nip46/backend/index.ts", "retrieved_chunk": "import { verifySignature, Event } from \"nostr-tools\";\nimport NDK, { NDKEvent, NDKPrivateKeySigner, NDKUser } from \"../../../index.js\";\nimport { NDKNostrRpc } from \"../rpc.js\";\nimport ConnectEventHandlingStrategy from \"./connect.js\";\nimport DescribeEventHandlingStrategy from \"./describe.js\";\nimport GetPublicKeyHandlingStrategy from \"./get-public-key.js\";\nimport Nip04DecryptHandlingStrategy from \"./nip04-decrypt.js\";\nimport Nip04EncryptHandlingStrategy from \"./nip04-encrypt.js\";\nimport SignEventHandlingStrategy from \"./sign-event.js\";\nexport type Nip46PermitCallback = (", "score": 0.8481394052505493 } ]
typescript
signEvent(event: NostrEvent): Promise<{ sig: string }>;
import { verifySignature, Event } from "nostr-tools"; import NDK, { NDKEvent, NDKPrivateKeySigner, NDKUser } from "../../../index.js"; import { NDKNostrRpc } from "../rpc.js"; import ConnectEventHandlingStrategy from "./connect.js"; import DescribeEventHandlingStrategy from "./describe.js"; import GetPublicKeyHandlingStrategy from "./get-public-key.js"; import Nip04DecryptHandlingStrategy from "./nip04-decrypt.js"; import Nip04EncryptHandlingStrategy from "./nip04-encrypt.js"; import SignEventHandlingStrategy from "./sign-event.js"; export type Nip46PermitCallback = ( pubkey: string, method: string, params?: any ) => Promise<boolean>; export type Nip46ApplyTokenCallback = ( pubkey: string, token: string ) => Promise<void>; export interface IEventHandlingStrategy { handle( backend: NDKNip46Backend, remotePubkey: string, params: string[] ): Promise<string | undefined>; } /** * This class implements a NIP-46 backend, meaning that it will hold a private key * of the npub that wants to be published as. * * This backend is meant to be used by an NDKNip46Signer, which is the class that * should run client-side, where the user wants to sign events from. */ export class NDKNip46Backend { readonly ndk: NDK; readonly signer: NDKPrivateKeySigner; public localUser?: NDKUser; readonly debug: debug.Debugger; private rpc: NDKNostrRpc; private permitCallback: Nip46PermitCallback; /** * @param ndk The NDK instance to use * @param privateKey The private key of the npub that wants to be published as */ public constructor( ndk: NDK, privateKey: string, permitCallback: Nip46PermitCallback ) { this.ndk = ndk; this.signer = new NDKPrivateKeySigner(privateKey); this.debug = ndk.debug.extend("nip46:backend"); this.rpc = new NDKNostrRpc(ndk, this.signer, this.debug); this.permitCallback = permitCallback; } /** * This method starts the backend, which will start listening for incoming * requests. */ public async start() { this.localUser = await this.signer.user(); const sub = this.ndk.subscribe( { kinds: [24133 as number], "#p": [this.localUser.hexpubkey()], }, { closeOnEose: false } ); sub.on("event", (e) => this.handleIncomingEvent(e)); } public handlers: { [method: string]: IEventHandlingStrategy } = { connect: new ConnectEventHandlingStrategy(), sign_event: new SignEventHandlingStrategy(), nip04_encrypt: new Nip04EncryptHandlingStrategy(), nip04_decrypt: new Nip04DecryptHandlingStrategy(), get_public_key: new GetPublicKeyHandlingStrategy(), describe: new DescribeEventHandlingStrategy(), }; /** * Enables the user to set a custom strategy for handling incoming events. * @param method - The method to set the strategy for * @param strategy - The strategy to set */ public setStrategy(method: string, strategy: IEventHandlingStrategy) { this.handlers[method] = strategy; } /** * Overload this method to apply tokens, which can * wrap permission sets to be applied to a pubkey. * @param pubkey public key to apply token to * @param token token to apply */ async applyToken(pubkey: string, token: string): Promise<void> { throw new Error("connection token not supported"); }
protected async handleIncomingEvent(event: NDKEvent) {
const { id, method, params } = (await this.rpc.parseEvent( event )) as any; const remotePubkey = event.pubkey; let response: string | undefined; this.debug("incoming event", { id, method, params }); // validate signature explicitly if (!verifySignature(event.rawEvent() as Event<any>)) { this.debug("invalid signature", event.rawEvent()); return; } const strategy = this.handlers[method]; if (strategy) { try { response = await strategy.handle(this, remotePubkey, params); } catch (e: any) { this.debug("error handling event", e, { id, method, params }); this.rpc.sendResponse( id, remotePubkey, "error", undefined, e.message ); } } else { this.debug("unsupported method", { method, params }); } if (response) { this.debug(`sending response to ${remotePubkey}`, response); this.rpc.sendResponse(id, remotePubkey, response); } else { this.rpc.sendResponse( id, remotePubkey, "error", undefined, "Not authorized" ); } } public async decrypt( remotePubkey: string, senderUser: NDKUser, payload: string ) { if (!(await this.pubkeyAllowed(remotePubkey, "decrypt", payload))) { this.debug(`decrypt request from ${remotePubkey} rejected`); return undefined; } return await this.signer.decrypt(senderUser, payload); } public async encrypt( remotePubkey: string, recipientUser: NDKUser, payload: string ) { if (!(await this.pubkeyAllowed(remotePubkey, "encrypt", payload))) { this.debug(`encrypt request from ${remotePubkey} rejected`); return undefined; } return await this.signer.encrypt(recipientUser, payload); } public async signEvent( remotePubkey: string, params: string[] ): Promise<NDKEvent | undefined> { const [eventString] = params; this.debug(`sign event request from ${remotePubkey}`); const event = new NDKEvent(this.ndk, JSON.parse(eventString)); this.debug("event to sign", event.rawEvent()); if (!(await this.pubkeyAllowed(remotePubkey, "sign_event", event))) { this.debug(`sign event request from ${remotePubkey} rejected`); return undefined; } this.debug(`sign event request from ${remotePubkey} allowed`); await event.sign(this.signer); return event; } /** * This method should be overriden by the user to allow or reject incoming * connections. */ public async pubkeyAllowed( pubkey: string, method: string, params?: any ): Promise<boolean> { return this.permitCallback(pubkey, method, params); } }
src/signers/nip46/backend/index.ts
nostr-dev-kit-ndk-ece64e1
[ { "filename": "src/signers/nip46/backend/connect.ts", "retrieved_chunk": "import { IEventHandlingStrategy, NDKNip46Backend } from \"./index.js\";\nexport default class ConnectEventHandlingStrategy\n implements IEventHandlingStrategy\n{\n async handle(\n backend: NDKNip46Backend,\n remotePubkey: string,\n params: string[]\n ): Promise<string | undefined> {\n const [pubkey, token] = params;", "score": 0.8505143523216248 }, { "filename": "src/signers/nip46/backend/connect.ts", "retrieved_chunk": " const debug = backend.debug.extend(\"connect\");\n debug(`connection request from ${pubkey}`);\n if (token && backend.applyToken) {\n debug(`applying token`);\n await backend.applyToken(pubkey, token);\n }\n if (await backend.pubkeyAllowed(pubkey, \"connect\", token)) {\n debug(`connection request from ${pubkey} allowed`);\n return \"ack\";\n } else {", "score": 0.8299839496612549 }, { "filename": "src/signers/nip46/rpc.ts", "retrieved_chunk": " });\n }\n public async parseEvent(\n event: NDKEvent\n ): Promise<NDKRpcRequest | NDKRpcResponse> {\n const remoteUser = this.ndk.getUser({ hexpubkey: event.pubkey });\n remoteUser.ndk = this.ndk;\n const decryptedContent = await this.signer.decrypt(\n remoteUser,\n event.content", "score": 0.8196946382522583 }, { "filename": "src/signers/nip46/backend/nip04-encrypt.ts", "retrieved_chunk": "import NDKUser from \"../../../user/index.js\";\nimport { IEventHandlingStrategy, NDKNip46Backend } from \"./index.js\";\nexport default class Nip04EncryptHandlingStrategy\n implements IEventHandlingStrategy\n{\n async handle(\n backend: NDKNip46Backend,\n remotePubkey: string,\n params: string[]\n ): Promise<string | undefined> {", "score": 0.8121176362037659 }, { "filename": "src/signers/nip46/rpc.ts", "retrieved_chunk": " event.content = await this.signer.encrypt(remoteUser, event.content);\n await event.sign(this.signer);\n this.debug(\"sending request to\", remotePubkey);\n await this.ndk.publish(event);\n return promise;\n }\n}", "score": 0.8099609613418579 } ]
typescript
protected async handleIncomingEvent(event: NDKEvent) {
import { verifySignature, Event } from "nostr-tools"; import NDK, { NDKEvent, NDKPrivateKeySigner, NDKUser } from "../../../index.js"; import { NDKNostrRpc } from "../rpc.js"; import ConnectEventHandlingStrategy from "./connect.js"; import DescribeEventHandlingStrategy from "./describe.js"; import GetPublicKeyHandlingStrategy from "./get-public-key.js"; import Nip04DecryptHandlingStrategy from "./nip04-decrypt.js"; import Nip04EncryptHandlingStrategy from "./nip04-encrypt.js"; import SignEventHandlingStrategy from "./sign-event.js"; export type Nip46PermitCallback = ( pubkey: string, method: string, params?: any ) => Promise<boolean>; export type Nip46ApplyTokenCallback = ( pubkey: string, token: string ) => Promise<void>; export interface IEventHandlingStrategy { handle( backend: NDKNip46Backend, remotePubkey: string, params: string[] ): Promise<string | undefined>; } /** * This class implements a NIP-46 backend, meaning that it will hold a private key * of the npub that wants to be published as. * * This backend is meant to be used by an NDKNip46Signer, which is the class that * should run client-side, where the user wants to sign events from. */ export class NDKNip46Backend { readonly ndk: NDK; readonly signer: NDKPrivateKeySigner; public localUser?: NDKUser; readonly debug: debug.Debugger; private rpc: NDKNostrRpc; private permitCallback: Nip46PermitCallback; /** * @param ndk The NDK instance to use * @param privateKey The private key of the npub that wants to be published as */ public constructor( ndk:
NDK, privateKey: string, permitCallback: Nip46PermitCallback ) {
this.ndk = ndk; this.signer = new NDKPrivateKeySigner(privateKey); this.debug = ndk.debug.extend("nip46:backend"); this.rpc = new NDKNostrRpc(ndk, this.signer, this.debug); this.permitCallback = permitCallback; } /** * This method starts the backend, which will start listening for incoming * requests. */ public async start() { this.localUser = await this.signer.user(); const sub = this.ndk.subscribe( { kinds: [24133 as number], "#p": [this.localUser.hexpubkey()], }, { closeOnEose: false } ); sub.on("event", (e) => this.handleIncomingEvent(e)); } public handlers: { [method: string]: IEventHandlingStrategy } = { connect: new ConnectEventHandlingStrategy(), sign_event: new SignEventHandlingStrategy(), nip04_encrypt: new Nip04EncryptHandlingStrategy(), nip04_decrypt: new Nip04DecryptHandlingStrategy(), get_public_key: new GetPublicKeyHandlingStrategy(), describe: new DescribeEventHandlingStrategy(), }; /** * Enables the user to set a custom strategy for handling incoming events. * @param method - The method to set the strategy for * @param strategy - The strategy to set */ public setStrategy(method: string, strategy: IEventHandlingStrategy) { this.handlers[method] = strategy; } /** * Overload this method to apply tokens, which can * wrap permission sets to be applied to a pubkey. * @param pubkey public key to apply token to * @param token token to apply */ async applyToken(pubkey: string, token: string): Promise<void> { throw new Error("connection token not supported"); } protected async handleIncomingEvent(event: NDKEvent) { const { id, method, params } = (await this.rpc.parseEvent( event )) as any; const remotePubkey = event.pubkey; let response: string | undefined; this.debug("incoming event", { id, method, params }); // validate signature explicitly if (!verifySignature(event.rawEvent() as Event<any>)) { this.debug("invalid signature", event.rawEvent()); return; } const strategy = this.handlers[method]; if (strategy) { try { response = await strategy.handle(this, remotePubkey, params); } catch (e: any) { this.debug("error handling event", e, { id, method, params }); this.rpc.sendResponse( id, remotePubkey, "error", undefined, e.message ); } } else { this.debug("unsupported method", { method, params }); } if (response) { this.debug(`sending response to ${remotePubkey}`, response); this.rpc.sendResponse(id, remotePubkey, response); } else { this.rpc.sendResponse( id, remotePubkey, "error", undefined, "Not authorized" ); } } public async decrypt( remotePubkey: string, senderUser: NDKUser, payload: string ) { if (!(await this.pubkeyAllowed(remotePubkey, "decrypt", payload))) { this.debug(`decrypt request from ${remotePubkey} rejected`); return undefined; } return await this.signer.decrypt(senderUser, payload); } public async encrypt( remotePubkey: string, recipientUser: NDKUser, payload: string ) { if (!(await this.pubkeyAllowed(remotePubkey, "encrypt", payload))) { this.debug(`encrypt request from ${remotePubkey} rejected`); return undefined; } return await this.signer.encrypt(recipientUser, payload); } public async signEvent( remotePubkey: string, params: string[] ): Promise<NDKEvent | undefined> { const [eventString] = params; this.debug(`sign event request from ${remotePubkey}`); const event = new NDKEvent(this.ndk, JSON.parse(eventString)); this.debug("event to sign", event.rawEvent()); if (!(await this.pubkeyAllowed(remotePubkey, "sign_event", event))) { this.debug(`sign event request from ${remotePubkey} rejected`); return undefined; } this.debug(`sign event request from ${remotePubkey} allowed`); await event.sign(this.signer); return event; } /** * This method should be overriden by the user to allow or reject incoming * connections. */ public async pubkeyAllowed( pubkey: string, method: string, params?: any ): Promise<boolean> { return this.permitCallback(pubkey, method, params); } }
src/signers/nip46/backend/index.ts
nostr-dev-kit-ndk-ece64e1
[ { "filename": "src/signers/nip46/index.ts", "retrieved_chunk": " * @param ndk - The NDK instance to use\n * @param token - connection token, in the form \"npub#otp\"\n * @param localSigner - The signer that will be used to request events to be signed\n */\n public constructor(ndk: NDK, token: string, localSigner?: NDKSigner);\n /**\n * @param ndk - The NDK instance to use\n * @param remoteNpub - The npub that wants to be published as\n * @param localSigner - The signer that will be used to request events to be signed\n */", "score": 0.8631967306137085 }, { "filename": "src/signers/nip46/index.ts", "retrieved_chunk": " public constructor(ndk: NDK, remoteNpub: string, localSigner?: NDKSigner);\n /**\n * @param ndk - The NDK instance to use\n * @param remotePubkey - The public key of the npub that wants to be published as\n * @param localSigner - The signer that will be used to request events to be signed\n */\n public constructor(ndk: NDK, remotePubkey: string, localSigner?: NDKSigner);\n /**\n * @param ndk - The NDK instance to use\n * @param tokenOrRemotePubkey - The public key, or a connection token, of the npub that wants to be published as", "score": 0.8480406403541565 }, { "filename": "src/signers/nip46/index.ts", "retrieved_chunk": " this.ndk = ndk;\n this.remotePubkey = remotePubkey;\n this.token = token;\n this.debug = ndk.debug.extend(\"nip46:signer\");\n this.remoteUser = new NDKUser({ hexpubkey: remotePubkey });\n if (!localSigner) {\n this.localSigner = NDKPrivateKeySigner.generate();\n } else {\n this.localSigner = localSigner;\n }", "score": 0.8303530812263489 }, { "filename": "src/signers/private-key/index.ts", "retrieved_chunk": "export class NDKPrivateKeySigner implements NDKSigner {\n private _user: NDKUser | undefined;\n privateKey?: string;\n public constructor(privateKey?: string) {\n if (privateKey) {\n this.privateKey = privateKey;\n this._user = new NDKUser({\n hexpubkey: getPublicKey(this.privateKey),\n });\n }", "score": 0.8289415836334229 }, { "filename": "src/subscription/index.ts", "retrieved_chunk": " ndk: NDK,\n filters: NDKFilter | NDKFilter[],\n opts?: NDKSubscriptionOptions,\n relaySet?: NDKRelaySet,\n subId?: string\n ) {\n super();\n this.ndk = ndk;\n this.opts = { ...defaultOpts, ...(opts || {}) };\n this.filters = filters instanceof Array ? filters : [filters];", "score": 0.8223806023597717 } ]
typescript
NDK, privateKey: string, permitCallback: Nip46PermitCallback ) {
import { verifySignature, Event } from "nostr-tools"; import NDK, { NDKEvent, NDKPrivateKeySigner, NDKUser } from "../../../index.js"; import { NDKNostrRpc } from "../rpc.js"; import ConnectEventHandlingStrategy from "./connect.js"; import DescribeEventHandlingStrategy from "./describe.js"; import GetPublicKeyHandlingStrategy from "./get-public-key.js"; import Nip04DecryptHandlingStrategy from "./nip04-decrypt.js"; import Nip04EncryptHandlingStrategy from "./nip04-encrypt.js"; import SignEventHandlingStrategy from "./sign-event.js"; export type Nip46PermitCallback = ( pubkey: string, method: string, params?: any ) => Promise<boolean>; export type Nip46ApplyTokenCallback = ( pubkey: string, token: string ) => Promise<void>; export interface IEventHandlingStrategy { handle( backend: NDKNip46Backend, remotePubkey: string, params: string[] ): Promise<string | undefined>; } /** * This class implements a NIP-46 backend, meaning that it will hold a private key * of the npub that wants to be published as. * * This backend is meant to be used by an NDKNip46Signer, which is the class that * should run client-side, where the user wants to sign events from. */ export class NDKNip46Backend { readonly ndk: NDK; readonly signer: NDKPrivateKeySigner; public localUser?: NDKUser; readonly debug: debug.Debugger; private rpc: NDKNostrRpc; private permitCallback: Nip46PermitCallback; /** * @param ndk The NDK instance to use * @param privateKey The private key of the npub that wants to be published as */ public constructor( ndk: NDK, privateKey: string, permitCallback: Nip46PermitCallback ) { this.ndk = ndk; this.signer = new NDKPrivateKeySigner(privateKey); this.debug = ndk.debug.extend("nip46:backend"); this.rpc = new NDKNostrRpc(ndk, this.signer, this.debug); this.permitCallback = permitCallback; } /** * This method starts the backend, which will start listening for incoming * requests. */ public async start() { this.localUser = await this.signer.user(); const sub = this.ndk.subscribe( { kinds: [24133 as number], "#p": [this.localUser.hexpubkey()], }, { closeOnEose: false } ); sub.on("event", (e) => this.handleIncomingEvent(e)); } public handlers: { [method: string]: IEventHandlingStrategy } = { connect: new ConnectEventHandlingStrategy(), sign_event: new SignEventHandlingStrategy(), nip04_encrypt: new Nip04EncryptHandlingStrategy(), nip04_decrypt: new Nip04DecryptHandlingStrategy(), get_public_key: new GetPublicKeyHandlingStrategy(), describe: new DescribeEventHandlingStrategy(), }; /** * Enables the user to set a custom strategy for handling incoming events. * @param method - The method to set the strategy for * @param strategy - The strategy to set */ public setStrategy(method: string, strategy: IEventHandlingStrategy) { this.handlers[method] = strategy; } /** * Overload this method to apply tokens, which can * wrap permission sets to be applied to a pubkey. * @param pubkey public key to apply token to * @param token token to apply */ async applyToken(pubkey: string, token: string): Promise<void> { throw new Error("connection token not supported"); } protected async handleIncomingEvent(event: NDKEvent) { const { id, method, params } = (await this.rpc.parseEvent( event )) as any; const remotePubkey = event.pubkey; let response: string | undefined; this.debug("incoming event", { id, method, params }); // validate signature explicitly if (!verifySignature(event.rawEvent() as Event<any>)) { this.debug("invalid signature", event.rawEvent()); return; } const strategy = this.handlers[method]; if (strategy) { try { response = await strategy.handle(this, remotePubkey, params); } catch (e: any) { this.debug("error handling event", e, { id, method, params }); this.rpc.sendResponse( id, remotePubkey, "error", undefined, e.message ); } } else { this.debug("unsupported method", { method, params }); } if (response) { this.debug(`sending response to ${remotePubkey}`, response); this.rpc.sendResponse(id, remotePubkey, response); } else { this.rpc.sendResponse( id, remotePubkey, "error", undefined, "Not authorized" ); } } public async decrypt( remotePubkey: string, senderUser: NDKUser, payload: string ) { if (!(await this.pubkeyAllowed(remotePubkey, "decrypt", payload))) { this.debug(`decrypt request from ${remotePubkey} rejected`); return undefined; } return await this.signer.decrypt(senderUser, payload); } public async encrypt( remotePubkey: string,
recipientUser: NDKUser, payload: string ) {
if (!(await this.pubkeyAllowed(remotePubkey, "encrypt", payload))) { this.debug(`encrypt request from ${remotePubkey} rejected`); return undefined; } return await this.signer.encrypt(recipientUser, payload); } public async signEvent( remotePubkey: string, params: string[] ): Promise<NDKEvent | undefined> { const [eventString] = params; this.debug(`sign event request from ${remotePubkey}`); const event = new NDKEvent(this.ndk, JSON.parse(eventString)); this.debug("event to sign", event.rawEvent()); if (!(await this.pubkeyAllowed(remotePubkey, "sign_event", event))) { this.debug(`sign event request from ${remotePubkey} rejected`); return undefined; } this.debug(`sign event request from ${remotePubkey} allowed`); await event.sign(this.signer); return event; } /** * This method should be overriden by the user to allow or reject incoming * connections. */ public async pubkeyAllowed( pubkey: string, method: string, params?: any ): Promise<boolean> { return this.permitCallback(pubkey, method, params); } }
src/signers/nip46/backend/index.ts
nostr-dev-kit-ndk-ece64e1
[ { "filename": "src/events/nip04.ts", "retrieved_chunk": " );\n }\n recipient = new NDKUser({ hexpubkey: pTags[0][1] });\n recipient.ndk = this.ndk;\n }\n this.content = await signer.encrypt(recipient, this.content);\n}\nexport async function decrypt(\n this: NDKEvent,\n sender?: NDKUser,", "score": 0.8960354328155518 }, { "filename": "src/signers/nip46/backend/nip04-encrypt.ts", "retrieved_chunk": " const [recipientPubkey, payload] = params;\n const recipientUser = new NDKUser({ hexpubkey: recipientPubkey });\n const decryptedPayload = await backend.encrypt(\n remotePubkey,\n recipientUser,\n payload\n );\n return decryptedPayload;\n }\n}", "score": 0.8940677642822266 }, { "filename": "src/signers/nip46/index.ts", "retrieved_chunk": " }\n public async encrypt(recipient: NDKUser, value: string): Promise<string> {\n this.debug(\"asking for encryption\");\n const promise = new Promise<string>((resolve, reject) => {\n this.rpc.sendRequest(\n this.remotePubkey,\n \"nip04_encrypt\",\n [recipient.hexpubkey(), value],\n 24133,\n (response: NDKRpcResponse) => {", "score": 0.8935602307319641 }, { "filename": "src/signers/private-key/index.ts", "retrieved_chunk": " }\n public async encrypt(recipient: NDKUser, value: string): Promise<string> {\n if (!this.privateKey) {\n throw Error(\"Attempted to encrypt without a private key\");\n }\n const recipientHexPubKey = recipient.hexpubkey();\n return await nip04.encrypt(this.privateKey, recipientHexPubKey, value);\n }\n public async decrypt(sender: NDKUser, value: string): Promise<string> {\n if (!this.privateKey) {", "score": 0.8923397064208984 }, { "filename": "src/signers/nip46/rpc.ts", "retrieved_chunk": " event.content = await this.signer.encrypt(remoteUser, event.content);\n await event.sign(this.signer);\n this.debug(\"sending request to\", remotePubkey);\n await this.ndk.publish(event);\n return promise;\n }\n}", "score": 0.8871111273765564 } ]
typescript
recipientUser: NDKUser, payload: string ) {
import NDK, { NDKPrivateKeySigner, NDKSigner, NDKUser, NostrEvent, } from "../../index.js"; import { NDKNostrRpc, NDKRpcResponse } from "./rpc.js"; /** * This NDKSigner implements NIP-46, which allows remote signing of events. * This class is meant to be used client-side, paired with the NDKNip46Backend or a NIP-46 backend (like Nostr-Connect) */ export class NDKNip46Signer implements NDKSigner { private ndk: NDK; public remoteUser: NDKUser; public remotePubkey: string; public token: string | undefined; public localSigner: NDKSigner; private rpc: NDKNostrRpc; private debug: debug.Debugger; /** * @param ndk - The NDK instance to use * @param token - connection token, in the form "npub#otp" * @param localSigner - The signer that will be used to request events to be signed */ public constructor(ndk: NDK, token: string, localSigner?: NDKSigner); /** * @param ndk - The NDK instance to use * @param remoteNpub - The npub that wants to be published as * @param localSigner - The signer that will be used to request events to be signed */ public constructor(ndk: NDK, remoteNpub: string, localSigner?: NDKSigner); /** * @param ndk - The NDK instance to use * @param remotePubkey - The public key of the npub that wants to be published as * @param localSigner - The signer that will be used to request events to be signed */ public constructor(ndk: NDK, remotePubkey: string, localSigner?: NDKSigner); /** * @param ndk - The NDK instance to use * @param tokenOrRemotePubkey - The public key, or a connection token, of the npub that wants to be published as * @param localSigner - The signer that will be used to request events to be signed */ public constructor( ndk: NDK, tokenOrRemotePubkey: string, localSigner?: NDKSigner ) { let remotePubkey: string; let token: string | undefined; if (tokenOrRemotePubkey.includes("#")) { const parts = tokenOrRemotePubkey.split("#"); remotePubkey = new NDKUser({ npub: parts[0] }).hexpubkey(); token = parts[1]; } else if (tokenOrRemotePubkey.startsWith("npub")) { remotePubkey = new NDKUser({ npub: tokenOrRemotePubkey, }).hexpubkey(); } else { remotePubkey = tokenOrRemotePubkey; } this.ndk = ndk; this.remotePubkey = remotePubkey; this.token = token; this.debug = ndk.debug.extend("nip46:signer"); this.remoteUser = new NDKUser({ hexpubkey: remotePubkey }); if (!localSigner) { this.localSigner = NDKPrivateKeySigner.generate(); } else { this.localSigner = localSigner; } this.rpc = new NDKNostrRpc(ndk, this.localSigner, this.debug); } /** * Get the user that is being published as */ public async user(): Promise<NDKUser> { return this.remoteUser; } public async blockUntilReady(): Promise<NDKUser> { const localUser = await this.localSigner.user(); const user = this.ndk.getUser({ npub: localUser.npub }); // Generates subscription, single subscription for the lifetime of our connection await this.rpc.subscribe({ kinds: [24133 as number], "#p": [localUser.hexpubkey()], }); return new Promise((resolve, reject) => { // There is a race condition between the subscription and sending the request; // introducing a small delay here to give a clear priority to the subscription // to happen first setTimeout(() => { const connectParams = [localUser.hexpubkey()]; if (this.token) { connectParams.push(this.token); } this.rpc.sendRequest( this.remotePubkey, "connect", connectParams, 24133,
(response: NDKRpcResponse) => {
if (response.result === "ack") { resolve(user); } else { reject(response.error); } } ); }, 100); }); } public async encrypt(recipient: NDKUser, value: string): Promise<string> { this.debug("asking for encryption"); const promise = new Promise<string>((resolve, reject) => { this.rpc.sendRequest( this.remotePubkey, "nip04_encrypt", [recipient.hexpubkey(), value], 24133, (response: NDKRpcResponse) => { if (!response.error) { resolve(response.result); } else { reject(response.error); } } ); }); return promise; } public async decrypt(sender: NDKUser, value: string): Promise<string> { this.debug("asking for decryption"); const promise = new Promise<string>((resolve, reject) => { this.rpc.sendRequest( this.remotePubkey, "nip04_decrypt", [sender.hexpubkey(), value], 24133, (response: NDKRpcResponse) => { if (!response.error) { const value = JSON.parse(response.result); resolve(value[0]); } else { reject(response.error); } } ); }); return promise; } public async sign(event: NostrEvent): Promise<string> { this.debug("asking for a signature"); const promise = new Promise<string>((resolve, reject) => { this.rpc.sendRequest( this.remotePubkey, "sign_event", [JSON.stringify(event)], 24133, (response: NDKRpcResponse) => { this.debug("got a response", response); if (!response.error) { const json = JSON.parse(response.result); resolve(json.sig); } else { reject(response.error); } } ); }); return promise; } }
src/signers/nip46/index.ts
nostr-dev-kit-ndk-ece64e1
[ { "filename": "src/signers/nip46/rpc.ts", "retrieved_chunk": " public async sendRequest(\n remotePubkey: string,\n method: string,\n params: string[] = [],\n kind = 24133,\n cb?: (res: NDKRpcResponse) => void\n ) {\n const id = Math.random().toString(36).substring(7);\n const localUser = await this.signer.user();\n const remoteUser = this.ndk.getUser({ hexpubkey: remotePubkey });", "score": 0.8935929536819458 }, { "filename": "src/signers/nip46/rpc.ts", "retrieved_chunk": " const request = { id, method, params };\n const promise = new Promise<NDKRpcResponse>((resolve) => {\n if (cb) this.once(`response-${id}`, cb);\n });\n const event = new NDKEvent(this.ndk, {\n kind,\n content: JSON.stringify(request),\n tags: [[\"p\", remotePubkey]],\n pubkey: localUser.hexpubkey(),\n } as NostrEvent);", "score": 0.8632616400718689 }, { "filename": "src/signers/nip46/backend/nip04-decrypt.ts", "retrieved_chunk": " const [senderPubkey, payload] = params;\n const senderUser = new NDKUser({ hexpubkey: senderPubkey });\n const decryptedPayload = await backend.decrypt(\n remotePubkey,\n senderUser,\n payload\n );\n return JSON.stringify([decryptedPayload]);\n }\n}", "score": 0.8458696603775024 }, { "filename": "src/signers/nip46/backend/connect.ts", "retrieved_chunk": " const debug = backend.debug.extend(\"connect\");\n debug(`connection request from ${pubkey}`);\n if (token && backend.applyToken) {\n debug(`applying token`);\n await backend.applyToken(pubkey, token);\n }\n if (await backend.pubkeyAllowed(pubkey, \"connect\", token)) {\n debug(`connection request from ${pubkey} allowed`);\n return \"ack\";\n } else {", "score": 0.841751217842102 }, { "filename": "src/signers/nip46/backend/index.ts", "retrieved_chunk": " */\n async applyToken(pubkey: string, token: string): Promise<void> {\n throw new Error(\"connection token not supported\");\n }\n protected async handleIncomingEvent(event: NDKEvent) {\n const { id, method, params } = (await this.rpc.parseEvent(\n event\n )) as any;\n const remotePubkey = event.pubkey;\n let response: string | undefined;", "score": 0.8412049412727356 } ]
typescript
(response: NDKRpcResponse) => {
import { verifySignature, Event } from "nostr-tools"; import NDK, { NDKEvent, NDKPrivateKeySigner, NDKUser } from "../../../index.js"; import { NDKNostrRpc } from "../rpc.js"; import ConnectEventHandlingStrategy from "./connect.js"; import DescribeEventHandlingStrategy from "./describe.js"; import GetPublicKeyHandlingStrategy from "./get-public-key.js"; import Nip04DecryptHandlingStrategy from "./nip04-decrypt.js"; import Nip04EncryptHandlingStrategy from "./nip04-encrypt.js"; import SignEventHandlingStrategy from "./sign-event.js"; export type Nip46PermitCallback = ( pubkey: string, method: string, params?: any ) => Promise<boolean>; export type Nip46ApplyTokenCallback = ( pubkey: string, token: string ) => Promise<void>; export interface IEventHandlingStrategy { handle( backend: NDKNip46Backend, remotePubkey: string, params: string[] ): Promise<string | undefined>; } /** * This class implements a NIP-46 backend, meaning that it will hold a private key * of the npub that wants to be published as. * * This backend is meant to be used by an NDKNip46Signer, which is the class that * should run client-side, where the user wants to sign events from. */ export class NDKNip46Backend { readonly ndk: NDK; readonly signer: NDKPrivateKeySigner; public localUser?: NDKUser; readonly debug: debug.Debugger; private rpc: NDKNostrRpc; private permitCallback: Nip46PermitCallback; /** * @param ndk The NDK instance to use * @param privateKey The private key of the npub that wants to be published as */ public constructor( ndk: NDK, privateKey: string, permitCallback: Nip46PermitCallback ) { this.ndk = ndk; this.signer = new NDKPrivateKeySigner(privateKey); this.debug = ndk.debug.extend("nip46:backend"); this.rpc = new NDKNostrRpc(ndk, this.signer, this.debug); this.permitCallback = permitCallback; } /** * This method starts the backend, which will start listening for incoming * requests. */ public async start() { this.localUser = await this.signer.user(); const sub = this.ndk.subscribe( { kinds: [24133 as number], "#p": [this.localUser.hexpubkey()], }, { closeOnEose: false } ); sub.on("event", (e) => this.handleIncomingEvent(e)); } public handlers: { [method: string]: IEventHandlingStrategy } = { connect: new ConnectEventHandlingStrategy(), sign_event: new SignEventHandlingStrategy(), nip04_encrypt: new Nip04EncryptHandlingStrategy(), nip04_decrypt: new Nip04DecryptHandlingStrategy(), get_public_key: new GetPublicKeyHandlingStrategy(), describe: new DescribeEventHandlingStrategy(), }; /** * Enables the user to set a custom strategy for handling incoming events. * @param method - The method to set the strategy for * @param strategy - The strategy to set */ public setStrategy(method: string, strategy: IEventHandlingStrategy) { this.handlers[method] = strategy; } /** * Overload this method to apply tokens, which can * wrap permission sets to be applied to a pubkey. * @param pubkey public key to apply token to * @param token token to apply */ async applyToken(pubkey: string, token: string): Promise<void> { throw new Error("connection token not supported"); } protected async handleIncomingEvent(event: NDKEvent) { const { id, method, params } = (await this.rpc.parseEvent( event )) as any; const remotePubkey = event.pubkey; let response: string | undefined; this.debug("incoming event", { id, method, params }); // validate signature explicitly if (!verifySignature(event.rawEvent() as Event<any>)) { this.debug("invalid signature", event.rawEvent()); return; } const strategy = this.handlers[method]; if (strategy) { try { response = await strategy.handle(this, remotePubkey, params); } catch (e: any) { this.debug("error handling event", e, { id, method, params }); this.rpc.sendResponse( id, remotePubkey, "error", undefined, e.message ); } } else { this.debug("unsupported method", { method, params }); } if (response) { this.debug(`sending response to ${remotePubkey}`, response); this.rpc.sendResponse(id, remotePubkey, response); } else { this.rpc.sendResponse( id, remotePubkey, "error", undefined, "Not authorized" ); } } public async decrypt( remotePubkey: string, senderUser: NDKUser, payload: string ) { if (!(await this.pubkeyAllowed(remotePubkey, "decrypt", payload))) { this.debug(`decrypt request from ${remotePubkey} rejected`); return undefined; } return await this.signer.decrypt(senderUser, payload); } public async encrypt( remotePubkey: string, recipientUser: NDKUser, payload: string ) { if (!(await this.pubkeyAllowed(remotePubkey, "encrypt", payload))) { this.debug(`encrypt request from ${remotePubkey} rejected`); return undefined; } return await this.signer.encrypt(recipientUser, payload); } public async signEvent( remotePubkey: string, params: string[] ): Promise
<NDKEvent | undefined> {
const [eventString] = params; this.debug(`sign event request from ${remotePubkey}`); const event = new NDKEvent(this.ndk, JSON.parse(eventString)); this.debug("event to sign", event.rawEvent()); if (!(await this.pubkeyAllowed(remotePubkey, "sign_event", event))) { this.debug(`sign event request from ${remotePubkey} rejected`); return undefined; } this.debug(`sign event request from ${remotePubkey} allowed`); await event.sign(this.signer); return event; } /** * This method should be overriden by the user to allow or reject incoming * connections. */ public async pubkeyAllowed( pubkey: string, method: string, params?: any ): Promise<boolean> { return this.permitCallback(pubkey, method, params); } }
src/signers/nip46/backend/index.ts
nostr-dev-kit-ndk-ece64e1
[ { "filename": "src/signers/nip46/rpc.ts", "retrieved_chunk": " event.content = await this.signer.encrypt(remoteUser, event.content);\n await event.sign(this.signer);\n this.debug(\"sending request to\", remotePubkey);\n await this.ndk.publish(event);\n return promise;\n }\n}", "score": 0.8932561874389648 }, { "filename": "src/signers/nip46/backend/nip04-encrypt.ts", "retrieved_chunk": " const [recipientPubkey, payload] = params;\n const recipientUser = new NDKUser({ hexpubkey: recipientPubkey });\n const decryptedPayload = await backend.encrypt(\n remotePubkey,\n recipientUser,\n payload\n );\n return decryptedPayload;\n }\n}", "score": 0.8893058896064758 }, { "filename": "src/signers/nip46/backend/nip04-encrypt.ts", "retrieved_chunk": "import NDKUser from \"../../../user/index.js\";\nimport { IEventHandlingStrategy, NDKNip46Backend } from \"./index.js\";\nexport default class Nip04EncryptHandlingStrategy\n implements IEventHandlingStrategy\n{\n async handle(\n backend: NDKNip46Backend,\n remotePubkey: string,\n params: string[]\n ): Promise<string | undefined> {", "score": 0.8882243633270264 }, { "filename": "src/signers/nip46/backend/sign-event.ts", "retrieved_chunk": "import { IEventHandlingStrategy, NDKNip46Backend } from \"./index.js\";\nexport default class SignEventHandlingStrategy\n implements IEventHandlingStrategy\n{\n async handle(\n backend: NDKNip46Backend,\n remotePubkey: string,\n params: string[]\n ): Promise<string | undefined> {\n const event = await backend.signEvent(remotePubkey, params);", "score": 0.8827065229415894 }, { "filename": "src/signers/nip46/backend/nip04-decrypt.ts", "retrieved_chunk": "import NDKUser from \"../../../user/index.js\";\nimport { IEventHandlingStrategy, NDKNip46Backend } from \"./index.js\";\nexport default class Nip04DecryptHandlingStrategy\n implements IEventHandlingStrategy\n{\n async handle(\n backend: NDKNip46Backend,\n remotePubkey: string,\n params: string[]\n ): Promise<string | undefined> {", "score": 0.8818005919456482 } ]
typescript
<NDKEvent | undefined> {
import EventEmitter from "eventemitter3"; import { Filter as NostrFilter, matchFilter, Sub, nip19 } from "nostr-tools"; import { EventPointer } from "nostr-tools/lib/nip19"; import NDKEvent, { NDKEventId } from "../events/index.js"; import NDK from "../index.js"; import { NDKRelay } from "../relay"; import { calculateRelaySetFromFilter } from "../relay/sets/calculate"; import { NDKRelaySet } from "../relay/sets/index.js"; import { queryFullyFilled } from "./utils.js"; export type NDKFilter = NostrFilter; export enum NDKSubscriptionCacheUsage { // Only use cache, don't subscribe to relays ONLY_CACHE = "ONLY_CACHE", // Use cache, if no matches, use relays CACHE_FIRST = "CACHE_FIRST", // Use cache in addition to relays PARALLEL = "PARALLEL", // Skip cache, don't query it ONLY_RELAY = "ONLY_RELAY", } export interface NDKSubscriptionOptions { closeOnEose: boolean; cacheUsage?: NDKSubscriptionCacheUsage; /** * Groupable subscriptions are created with a slight time * delayed to allow similar filters to be grouped together. */ groupable?: boolean; /** * The delay to use when grouping subscriptions, specified in milliseconds. * @default 100 */ groupableDelay?: number; /** * The subscription ID to use for the subscription. */ subId?: string; } /** * Default subscription options. */ export const defaultOpts: NDKSubscriptionOptions = { closeOnEose: true, cacheUsage: NDKSubscriptionCacheUsage.CACHE_FIRST, groupable: true, groupableDelay: 100, }; /** * Represents a subscription to an NDK event stream. * * @event NDKSubscription#event * Emitted when an event is received by the subscription. * @param {NDKEvent} event - The event received by the subscription. * @param {NDKRelay} relay - The relay that received the event. * @param {NDKSubscription} subscription - The subscription that received the event. * * @event NDKSubscription#event:dup * Emitted when a duplicate event is received by the subscription. * @param {NDKEvent} event - The duplicate event received by the subscription. * @param {NDKRelay} relay - The relay that received the event. * @param {number} timeSinceFirstSeen - The time elapsed since the first time the event was seen. * @param {NDKSubscription} subscription - The subscription that received the event. * * @event NDKSubscription#eose - Emitted when all relays have reached the end of the event stream. * @param {NDKSubscription} subscription - The subscription that received EOSE. * * @event NDKSubscription#close - Emitted when the subscription is closed. * @param {NDKSubscription} subscription - The subscription that was closed. */ export class NDKSubscription extends EventEmitter { readonly subId: string; readonly filters: NDKFilter[]; readonly opts: NDKSubscriptionOptions; public relaySet?: NDKRelaySet; public ndk: NDK; public relaySubscriptions
: Map<NDKRelay, Sub>;
private debug: debug.Debugger; /** * Events that have been seen by the subscription, with the time they were first seen. */ public eventFirstSeen = new Map<NDKEventId, number>(); /** * Relays that have sent an EOSE. */ public eosesSeen = new Set<NDKRelay>(); /** * Events that have been seen by the subscription per relay. */ public eventsPerRelay: Map<NDKRelay, Set<NDKEventId>> = new Map(); public constructor( ndk: NDK, filters: NDKFilter | NDKFilter[], opts?: NDKSubscriptionOptions, relaySet?: NDKRelaySet, subId?: string ) { super(); this.ndk = ndk; this.opts = { ...defaultOpts, ...(opts || {}) }; this.filters = filters instanceof Array ? filters : [filters]; this.subId = subId || opts?.subId || generateFilterId(this.filters[0]); this.relaySet = relaySet; this.relaySubscriptions = new Map<NDKRelay, Sub>(); this.debug = ndk.debug.extend(`subscription:${this.subId}`); // validate that the caller is not expecting a persistent // subscription while using an option that will only hit the cache if ( this.opts.cacheUsage === NDKSubscriptionCacheUsage.ONLY_CACHE && !this.opts.closeOnEose ) { throw new Error( "Cannot use cache-only options with a persistent subscription" ); } } /** * Provides access to the first filter of the subscription for * backwards compatibility. */ get filter(): NDKFilter { return this.filters[0]; } /** * Calculates the groupable ID for this subscription. * * @returns The groupable ID, or null if the subscription is not groupable. */ public groupableId(): string | null { if (!this.opts?.groupable || this.filters.length > 1) { return null; } const filter = this.filters[0]; // Check if there is a kind and no time-based filters const noTimeConstraints = !filter.since && !filter.until; const noLimit = !filter.limit; if (noTimeConstraints && noLimit) { let id = filter.kinds ? filter.kinds.join(",") : ""; const keys = Object.keys(filter || {}) .sort() .join("-"); id += `-${keys}`; return id; } return null; } private shouldQueryCache(): boolean { return this.opts?.cacheUsage !== NDKSubscriptionCacheUsage.ONLY_RELAY; } private shouldQueryRelays(): boolean { return this.opts?.cacheUsage !== NDKSubscriptionCacheUsage.ONLY_CACHE; } private shouldWaitForCache(): boolean { return ( // Must want to close on EOSE; subscriptions // that want to receive further updates must // always hit the relay this.opts.closeOnEose && // Cache adapter must claim to be fast !!this.ndk.cacheAdapter?.locking && // If explicitly told to run in parallel, then // we should not wait for the cache this.opts.cacheUsage !== NDKSubscriptionCacheUsage.PARALLEL ); } /** * Start the subscription. This is the main method that should be called * after creating a subscription. */ public async start(): Promise<void> { let cachePromise; if (this.shouldQueryCache()) { cachePromise = this.startWithCache(); if (this.shouldWaitForCache()) { await cachePromise; // if the cache has a hit, return early if (queryFullyFilled(this)) { this.emit("eose", this); return; } } } if (this.shouldQueryRelays()) { this.startWithRelaySet(); } else { this.emit("eose", this); } return; } public stop(): void { this.relaySubscriptions.forEach((sub) => sub.unsub()); this.relaySubscriptions.clear(); this.emit("close", this); } private async startWithCache(): Promise<void> { if (this.ndk.cacheAdapter?.query) { const promise = this.ndk.cacheAdapter.query(this); if (this.ndk.cacheAdapter.locking) { await promise; } } } private startWithRelaySet(): void { if (!this.relaySet) { this.relaySet = calculateRelaySetFromFilter( this.ndk, this.filters[0] ); } if (this.relaySet) { this.relaySet.subscribe(this); } } // EVENT handling /** * Called when an event is received from a relay or the cache * @param event * @param relay * @param fromCache Whether the event was received from the cache */ public eventReceived( event: NDKEvent, relay: NDKRelay | undefined, fromCache = false ) { if (relay) event.relay = relay; if (!relay) relay = event.relay; if (!fromCache && relay) { // track the event per relay let events = this.eventsPerRelay.get(relay); if (!events) { events = new Set(); this.eventsPerRelay.set(relay, events); } events.add(event.id); // mark the event as seen const eventAlreadySeen = this.eventFirstSeen.has(event.id); if (eventAlreadySeen) { const timeSinceFirstSeen = Date.now() - (this.eventFirstSeen.get(event.id) || 0); relay.scoreSlowerEvent(timeSinceFirstSeen); this.emit("event:dup", event, relay, timeSinceFirstSeen, this); return; } if (this.ndk.cacheAdapter) { this.ndk.cacheAdapter.setEvent(event, this.filters[0], relay); } this.eventFirstSeen.set(`${event.id}`, Date.now()); } else { this.eventFirstSeen.set(`${event.id}`, 0); } this.emit("event", event, relay, this); } // EOSE handling private eoseTimeout: ReturnType<typeof setTimeout> | undefined; public eoseReceived(relay: NDKRelay): void { if (this.opts?.closeOnEose) { this.relaySubscriptions.get(relay)?.unsub(); this.relaySubscriptions.delete(relay); // if this was the last relay that needed to EOSE, emit that this subscription is closed if (this.relaySubscriptions.size === 0) { this.emit("close", this); } } this.eosesSeen.add(relay); const hasSeenAllEoses = this.eosesSeen.size === this.relaySet?.size(); if (hasSeenAllEoses) { this.emit("eose"); } else { if (this.eoseTimeout) { clearTimeout(this.eoseTimeout); } this.eoseTimeout = setTimeout(() => { this.emit("eose"); }, 500); } } } /** * Represents a group of subscriptions. * * Events emitted from the group will be emitted from each subscription. */ export class NDKSubscriptionGroup extends NDKSubscription { private subscriptions: NDKSubscription[]; constructor(ndk: NDK, subscriptions: NDKSubscription[]) { const debug = ndk.debug.extend("subscription-group"); const filters = mergeFilters(subscriptions.map((s) => s.filters[0])); super( ndk, filters, subscriptions[0].opts, // TODO: This should be merged subscriptions[0].relaySet // TODO: This should be merged ); this.subscriptions = subscriptions; debug("merged filters", { count: subscriptions.length, mergedFilters: this.filters[0], }); // forward events to the matching subscriptions this.on("event", this.forwardEvent); this.on("event:dup", this.forwardEventDup); this.on("eose", this.forwardEose); this.on("close", this.forwardClose); } private isEventForSubscription( event: NDKEvent, subscription: NDKSubscription ): boolean { const { filters } = subscription; if (!filters) return false; return matchFilter(filters[0], event.rawEvent() as any); // check if there is a filter whose key begins with '#'; if there is, check if the event has a tag with the same key on the first position // of the tags array of arrays and the same value in the second position // for (const key in filter) { // if (key === 'kinds' && filter.kinds!.includes(event.kind!)) return false; // else if (key === 'authors' && filter.authors!.includes(event.pubkey)) return false; // else if (key.startsWith('#')) { // const tagKey = key.slice(1); // const tagValue = filter[key]; // if (event.tags) { // for (const tag of event.tags) { // if (tag[0] === tagKey && tag[1] === tagValue) { // return false; // } // } // } // } // return true; } private forwardEvent(event: NDKEvent, relay: NDKRelay) { for (const subscription of this.subscriptions) { if (!this.isEventForSubscription(event, subscription)) { continue; } subscription.emit("event", event, relay, subscription); } } private forwardEventDup( event: NDKEvent, relay: NDKRelay, timeSinceFirstSeen: number ) { for (const subscription of this.subscriptions) { if (!this.isEventForSubscription(event, subscription)) { continue; } subscription.emit( "event:dup", event, relay, timeSinceFirstSeen, subscription ); } } private forwardEose() { for (const subscription of this.subscriptions) { subscription.emit("eose", subscription); } } private forwardClose() { for (const subscription of this.subscriptions) { subscription.emit("close", subscription); } } } /** * Go through all the passed filters, which should be * relatively similar, and merge them. */ export function mergeFilters(filters: NDKFilter[]): NDKFilter { const result: any = {}; filters.forEach((filter) => { Object.entries(filter).forEach(([key, value]) => { if (Array.isArray(value)) { if (result[key] === undefined) { result[key] = [...value]; } else { result[key] = Array.from( new Set([...result[key], ...value]) ); } } else { result[key] = value; } }); }); return result as NDKFilter; } /** * Creates a valid nostr filter from an event id or a NIP-19 bech32. */ export function filterFromId(id: string): NDKFilter { let decoded; try { decoded = nip19.decode(id); switch (decoded.type) { case "nevent": return { ids: [decoded.data.id] }; case "note": return { ids: [decoded.data] }; case "naddr": return { authors: [decoded.data.pubkey], "#d": [decoded.data.identifier], kinds: [decoded.data.kind], }; } } catch (e) {} return { ids: [id] }; } /** * Returns the specified relays from a NIP-19 bech32. * * @param bech32 The NIP-19 bech32. */ export function relaysFromBech32(bech32: string): NDKRelay[] { try { const decoded = nip19.decode(bech32); if (["naddr", "nevent"].includes(decoded?.type)) { const data = decoded.data as unknown as EventPointer; if (data?.relays) { return data.relays.map((r: string) => new NDKRelay(r)); } } } catch (e) { /* empty */ } return []; } /** * Generates a random filter id, based on the filter keys. */ function generateFilterId(filter: NDKFilter) { const keys = Object.keys(filter) || []; const subId = []; for (const key of keys) { if (key === "kinds") { const v = [key, filter.kinds!.join(",")]; subId.push(v.join(":")); } else { subId.push(key); } } subId.push(Math.floor(Math.random() * 999999999).toString()); return subId.join("-"); }
src/subscription/index.ts
nostr-dev-kit-ndk-ece64e1
[ { "filename": "src/relay/index.ts", "retrieved_chunk": " id: subscription.subId,\n });\n this.debug(`Subscribed to ${JSON.stringify(filters)}`);\n sub.on(\"event\", (event: NostrEvent) => {\n const e = new NDKEvent(undefined, event);\n e.relay = this;\n subscription.eventReceived(e, this);\n });\n sub.on(\"eose\", () => {\n subscription.eoseReceived(this);", "score": 0.8764982223510742 }, { "filename": "src/cache/index.ts", "retrieved_chunk": " query(subscription: NDKSubscription): Promise<void>;\n setEvent(\n event: NDKEvent,\n filter: NDKFilter,\n relay?: NDKRelay\n ): Promise<void>;\n}", "score": 0.8649452328681946 }, { "filename": "src/relay/index.ts", "retrieved_chunk": " // }, 60000);\n }\n this.emit(\"notice\", this, notice);\n }\n /**\n * Subscribes to a subscription.\n */\n public subscribe(subscription: NDKSubscription): Sub {\n const { filters } = subscription;\n const sub = this.relay.sub(filters, {", "score": 0.8645857572555542 }, { "filename": "src/index.ts", "retrieved_chunk": " * @returns NDKSubscription\n */\n public subscribe(\n filters: NDKFilter | NDKFilter[],\n opts?: NDKSubscriptionOptions,\n relaySet?: NDKRelaySet,\n autoStart = true\n ): NDKSubscription {\n const subscription = new NDKSubscription(this, filters, opts, relaySet);\n // Signal to the relays that they are explicitly being used", "score": 0.8645522594451904 }, { "filename": "src/relay/sets/index.ts", "retrieved_chunk": " private executeSubscriptions(subscriptions: NDKSubscription[]) {\n const ndk = subscriptions[0].ndk;\n const subGroup = new NDKSubscriptionGroup(ndk, subscriptions);\n this.executeSubscription(subGroup);\n }\n private executeSubscription(\n subscription: NDKSubscription\n ): NDKSubscription {\n this.debug(\"subscribing\", { filters: subscription.filters });\n for (const relay of this.relays) {", "score": 0.8538408875465393 } ]
typescript
: Map<NDKRelay, Sub>;
import EventEmitter from "eventemitter3"; import { Filter as NostrFilter, matchFilter, Sub, nip19 } from "nostr-tools"; import { EventPointer } from "nostr-tools/lib/nip19"; import NDKEvent, { NDKEventId } from "../events/index.js"; import NDK from "../index.js"; import { NDKRelay } from "../relay"; import { calculateRelaySetFromFilter } from "../relay/sets/calculate"; import { NDKRelaySet } from "../relay/sets/index.js"; import { queryFullyFilled } from "./utils.js"; export type NDKFilter = NostrFilter; export enum NDKSubscriptionCacheUsage { // Only use cache, don't subscribe to relays ONLY_CACHE = "ONLY_CACHE", // Use cache, if no matches, use relays CACHE_FIRST = "CACHE_FIRST", // Use cache in addition to relays PARALLEL = "PARALLEL", // Skip cache, don't query it ONLY_RELAY = "ONLY_RELAY", } export interface NDKSubscriptionOptions { closeOnEose: boolean; cacheUsage?: NDKSubscriptionCacheUsage; /** * Groupable subscriptions are created with a slight time * delayed to allow similar filters to be grouped together. */ groupable?: boolean; /** * The delay to use when grouping subscriptions, specified in milliseconds. * @default 100 */ groupableDelay?: number; /** * The subscription ID to use for the subscription. */ subId?: string; } /** * Default subscription options. */ export const defaultOpts: NDKSubscriptionOptions = { closeOnEose: true, cacheUsage: NDKSubscriptionCacheUsage.CACHE_FIRST, groupable: true, groupableDelay: 100, }; /** * Represents a subscription to an NDK event stream. * * @event NDKSubscription#event * Emitted when an event is received by the subscription. * @param {NDKEvent} event - The event received by the subscription. * @param {NDKRelay} relay - The relay that received the event. * @param {NDKSubscription} subscription - The subscription that received the event. * * @event NDKSubscription#event:dup * Emitted when a duplicate event is received by the subscription. * @param {NDKEvent} event - The duplicate event received by the subscription. * @param {NDKRelay} relay - The relay that received the event. * @param {number} timeSinceFirstSeen - The time elapsed since the first time the event was seen. * @param {NDKSubscription} subscription - The subscription that received the event. * * @event NDKSubscription#eose - Emitted when all relays have reached the end of the event stream. * @param {NDKSubscription} subscription - The subscription that received EOSE. * * @event NDKSubscription#close - Emitted when the subscription is closed. * @param {NDKSubscription} subscription - The subscription that was closed. */ export class NDKSubscription extends EventEmitter { readonly subId: string; readonly filters: NDKFilter[]; readonly opts: NDKSubscriptionOptions; public relaySet?: NDKRelaySet; public ndk: NDK;
public relaySubscriptions: Map<NDKRelay, Sub>;
private debug: debug.Debugger; /** * Events that have been seen by the subscription, with the time they were first seen. */ public eventFirstSeen = new Map<NDKEventId, number>(); /** * Relays that have sent an EOSE. */ public eosesSeen = new Set<NDKRelay>(); /** * Events that have been seen by the subscription per relay. */ public eventsPerRelay: Map<NDKRelay, Set<NDKEventId>> = new Map(); public constructor( ndk: NDK, filters: NDKFilter | NDKFilter[], opts?: NDKSubscriptionOptions, relaySet?: NDKRelaySet, subId?: string ) { super(); this.ndk = ndk; this.opts = { ...defaultOpts, ...(opts || {}) }; this.filters = filters instanceof Array ? filters : [filters]; this.subId = subId || opts?.subId || generateFilterId(this.filters[0]); this.relaySet = relaySet; this.relaySubscriptions = new Map<NDKRelay, Sub>(); this.debug = ndk.debug.extend(`subscription:${this.subId}`); // validate that the caller is not expecting a persistent // subscription while using an option that will only hit the cache if ( this.opts.cacheUsage === NDKSubscriptionCacheUsage.ONLY_CACHE && !this.opts.closeOnEose ) { throw new Error( "Cannot use cache-only options with a persistent subscription" ); } } /** * Provides access to the first filter of the subscription for * backwards compatibility. */ get filter(): NDKFilter { return this.filters[0]; } /** * Calculates the groupable ID for this subscription. * * @returns The groupable ID, or null if the subscription is not groupable. */ public groupableId(): string | null { if (!this.opts?.groupable || this.filters.length > 1) { return null; } const filter = this.filters[0]; // Check if there is a kind and no time-based filters const noTimeConstraints = !filter.since && !filter.until; const noLimit = !filter.limit; if (noTimeConstraints && noLimit) { let id = filter.kinds ? filter.kinds.join(",") : ""; const keys = Object.keys(filter || {}) .sort() .join("-"); id += `-${keys}`; return id; } return null; } private shouldQueryCache(): boolean { return this.opts?.cacheUsage !== NDKSubscriptionCacheUsage.ONLY_RELAY; } private shouldQueryRelays(): boolean { return this.opts?.cacheUsage !== NDKSubscriptionCacheUsage.ONLY_CACHE; } private shouldWaitForCache(): boolean { return ( // Must want to close on EOSE; subscriptions // that want to receive further updates must // always hit the relay this.opts.closeOnEose && // Cache adapter must claim to be fast !!this.ndk.cacheAdapter?.locking && // If explicitly told to run in parallel, then // we should not wait for the cache this.opts.cacheUsage !== NDKSubscriptionCacheUsage.PARALLEL ); } /** * Start the subscription. This is the main method that should be called * after creating a subscription. */ public async start(): Promise<void> { let cachePromise; if (this.shouldQueryCache()) { cachePromise = this.startWithCache(); if (this.shouldWaitForCache()) { await cachePromise; // if the cache has a hit, return early if (queryFullyFilled(this)) { this.emit("eose", this); return; } } } if (this.shouldQueryRelays()) { this.startWithRelaySet(); } else { this.emit("eose", this); } return; } public stop(): void { this.relaySubscriptions.forEach((sub) => sub.unsub()); this.relaySubscriptions.clear(); this.emit("close", this); } private async startWithCache(): Promise<void> { if (this.ndk.cacheAdapter?.query) { const promise = this.ndk.cacheAdapter.query(this); if (this.ndk.cacheAdapter.locking) { await promise; } } } private startWithRelaySet(): void { if (!this.relaySet) { this.relaySet = calculateRelaySetFromFilter( this.ndk, this.filters[0] ); } if (this.relaySet) { this.relaySet.subscribe(this); } } // EVENT handling /** * Called when an event is received from a relay or the cache * @param event * @param relay * @param fromCache Whether the event was received from the cache */ public eventReceived( event: NDKEvent, relay: NDKRelay | undefined, fromCache = false ) { if (relay) event.relay = relay; if (!relay) relay = event.relay; if (!fromCache && relay) { // track the event per relay let events = this.eventsPerRelay.get(relay); if (!events) { events = new Set(); this.eventsPerRelay.set(relay, events); } events.add(event.id); // mark the event as seen const eventAlreadySeen = this.eventFirstSeen.has(event.id); if (eventAlreadySeen) { const timeSinceFirstSeen = Date.now() - (this.eventFirstSeen.get(event.id) || 0); relay.scoreSlowerEvent(timeSinceFirstSeen); this.emit("event:dup", event, relay, timeSinceFirstSeen, this); return; } if (this.ndk.cacheAdapter) { this.ndk.cacheAdapter.setEvent(event, this.filters[0], relay); } this.eventFirstSeen.set(`${event.id}`, Date.now()); } else { this.eventFirstSeen.set(`${event.id}`, 0); } this.emit("event", event, relay, this); } // EOSE handling private eoseTimeout: ReturnType<typeof setTimeout> | undefined; public eoseReceived(relay: NDKRelay): void { if (this.opts?.closeOnEose) { this.relaySubscriptions.get(relay)?.unsub(); this.relaySubscriptions.delete(relay); // if this was the last relay that needed to EOSE, emit that this subscription is closed if (this.relaySubscriptions.size === 0) { this.emit("close", this); } } this.eosesSeen.add(relay); const hasSeenAllEoses = this.eosesSeen.size === this.relaySet?.size(); if (hasSeenAllEoses) { this.emit("eose"); } else { if (this.eoseTimeout) { clearTimeout(this.eoseTimeout); } this.eoseTimeout = setTimeout(() => { this.emit("eose"); }, 500); } } } /** * Represents a group of subscriptions. * * Events emitted from the group will be emitted from each subscription. */ export class NDKSubscriptionGroup extends NDKSubscription { private subscriptions: NDKSubscription[]; constructor(ndk: NDK, subscriptions: NDKSubscription[]) { const debug = ndk.debug.extend("subscription-group"); const filters = mergeFilters(subscriptions.map((s) => s.filters[0])); super( ndk, filters, subscriptions[0].opts, // TODO: This should be merged subscriptions[0].relaySet // TODO: This should be merged ); this.subscriptions = subscriptions; debug("merged filters", { count: subscriptions.length, mergedFilters: this.filters[0], }); // forward events to the matching subscriptions this.on("event", this.forwardEvent); this.on("event:dup", this.forwardEventDup); this.on("eose", this.forwardEose); this.on("close", this.forwardClose); } private isEventForSubscription( event: NDKEvent, subscription: NDKSubscription ): boolean { const { filters } = subscription; if (!filters) return false; return matchFilter(filters[0], event.rawEvent() as any); // check if there is a filter whose key begins with '#'; if there is, check if the event has a tag with the same key on the first position // of the tags array of arrays and the same value in the second position // for (const key in filter) { // if (key === 'kinds' && filter.kinds!.includes(event.kind!)) return false; // else if (key === 'authors' && filter.authors!.includes(event.pubkey)) return false; // else if (key.startsWith('#')) { // const tagKey = key.slice(1); // const tagValue = filter[key]; // if (event.tags) { // for (const tag of event.tags) { // if (tag[0] === tagKey && tag[1] === tagValue) { // return false; // } // } // } // } // return true; } private forwardEvent(event: NDKEvent, relay: NDKRelay) { for (const subscription of this.subscriptions) { if (!this.isEventForSubscription(event, subscription)) { continue; } subscription.emit("event", event, relay, subscription); } } private forwardEventDup( event: NDKEvent, relay: NDKRelay, timeSinceFirstSeen: number ) { for (const subscription of this.subscriptions) { if (!this.isEventForSubscription(event, subscription)) { continue; } subscription.emit( "event:dup", event, relay, timeSinceFirstSeen, subscription ); } } private forwardEose() { for (const subscription of this.subscriptions) { subscription.emit("eose", subscription); } } private forwardClose() { for (const subscription of this.subscriptions) { subscription.emit("close", subscription); } } } /** * Go through all the passed filters, which should be * relatively similar, and merge them. */ export function mergeFilters(filters: NDKFilter[]): NDKFilter { const result: any = {}; filters.forEach((filter) => { Object.entries(filter).forEach(([key, value]) => { if (Array.isArray(value)) { if (result[key] === undefined) { result[key] = [...value]; } else { result[key] = Array.from( new Set([...result[key], ...value]) ); } } else { result[key] = value; } }); }); return result as NDKFilter; } /** * Creates a valid nostr filter from an event id or a NIP-19 bech32. */ export function filterFromId(id: string): NDKFilter { let decoded; try { decoded = nip19.decode(id); switch (decoded.type) { case "nevent": return { ids: [decoded.data.id] }; case "note": return { ids: [decoded.data] }; case "naddr": return { authors: [decoded.data.pubkey], "#d": [decoded.data.identifier], kinds: [decoded.data.kind], }; } } catch (e) {} return { ids: [id] }; } /** * Returns the specified relays from a NIP-19 bech32. * * @param bech32 The NIP-19 bech32. */ export function relaysFromBech32(bech32: string): NDKRelay[] { try { const decoded = nip19.decode(bech32); if (["naddr", "nevent"].includes(decoded?.type)) { const data = decoded.data as unknown as EventPointer; if (data?.relays) { return data.relays.map((r: string) => new NDKRelay(r)); } } } catch (e) { /* empty */ } return []; } /** * Generates a random filter id, based on the filter keys. */ function generateFilterId(filter: NDKFilter) { const keys = Object.keys(filter) || []; const subId = []; for (const key of keys) { if (key === "kinds") { const v = [key, filter.kinds!.join(",")]; subId.push(v.join(":")); } else { subId.push(key); } } subId.push(Math.floor(Math.random() * 999999999).toString()); return subId.join("-"); }
src/subscription/index.ts
nostr-dev-kit-ndk-ece64e1
[ { "filename": "src/relay/index.ts", "retrieved_chunk": " id: subscription.subId,\n });\n this.debug(`Subscribed to ${JSON.stringify(filters)}`);\n sub.on(\"event\", (event: NostrEvent) => {\n const e = new NDKEvent(undefined, event);\n e.relay = this;\n subscription.eventReceived(e, this);\n });\n sub.on(\"eose\", () => {\n subscription.eoseReceived(this);", "score": 0.8779346942901611 }, { "filename": "src/cache/index.ts", "retrieved_chunk": " query(subscription: NDKSubscription): Promise<void>;\n setEvent(\n event: NDKEvent,\n filter: NDKFilter,\n relay?: NDKRelay\n ): Promise<void>;\n}", "score": 0.8654970526695251 }, { "filename": "src/relay/index.ts", "retrieved_chunk": " // }, 60000);\n }\n this.emit(\"notice\", this, notice);\n }\n /**\n * Subscribes to a subscription.\n */\n public subscribe(subscription: NDKSubscription): Sub {\n const { filters } = subscription;\n const sub = this.relay.sub(filters, {", "score": 0.8630539178848267 }, { "filename": "src/index.ts", "retrieved_chunk": " * @returns NDKSubscription\n */\n public subscribe(\n filters: NDKFilter | NDKFilter[],\n opts?: NDKSubscriptionOptions,\n relaySet?: NDKRelaySet,\n autoStart = true\n ): NDKSubscription {\n const subscription = new NDKSubscription(this, filters, opts, relaySet);\n // Signal to the relays that they are explicitly being used", "score": 0.858863115310669 }, { "filename": "src/index.ts", "retrieved_chunk": " }\n return new Promise((resolve) => {\n const s = this.subscribe(\n filter,\n { ...(opts || {}), closeOnEose: true },\n relaySet,\n false\n );\n s.on(\"event\", (event) => {\n event.ndk = this;", "score": 0.8522491455078125 } ]
typescript
public relaySubscriptions: Map<NDKRelay, Sub>;
import EventEmitter from "eventemitter3"; import { Filter as NostrFilter, matchFilter, Sub, nip19 } from "nostr-tools"; import { EventPointer } from "nostr-tools/lib/nip19"; import NDKEvent, { NDKEventId } from "../events/index.js"; import NDK from "../index.js"; import { NDKRelay } from "../relay"; import { calculateRelaySetFromFilter } from "../relay/sets/calculate"; import { NDKRelaySet } from "../relay/sets/index.js"; import { queryFullyFilled } from "./utils.js"; export type NDKFilter = NostrFilter; export enum NDKSubscriptionCacheUsage { // Only use cache, don't subscribe to relays ONLY_CACHE = "ONLY_CACHE", // Use cache, if no matches, use relays CACHE_FIRST = "CACHE_FIRST", // Use cache in addition to relays PARALLEL = "PARALLEL", // Skip cache, don't query it ONLY_RELAY = "ONLY_RELAY", } export interface NDKSubscriptionOptions { closeOnEose: boolean; cacheUsage?: NDKSubscriptionCacheUsage; /** * Groupable subscriptions are created with a slight time * delayed to allow similar filters to be grouped together. */ groupable?: boolean; /** * The delay to use when grouping subscriptions, specified in milliseconds. * @default 100 */ groupableDelay?: number; /** * The subscription ID to use for the subscription. */ subId?: string; } /** * Default subscription options. */ export const defaultOpts: NDKSubscriptionOptions = { closeOnEose: true, cacheUsage: NDKSubscriptionCacheUsage.CACHE_FIRST, groupable: true, groupableDelay: 100, }; /** * Represents a subscription to an NDK event stream. * * @event NDKSubscription#event * Emitted when an event is received by the subscription. * @param {NDKEvent} event - The event received by the subscription. * @param {NDKRelay} relay - The relay that received the event. * @param {NDKSubscription} subscription - The subscription that received the event. * * @event NDKSubscription#event:dup * Emitted when a duplicate event is received by the subscription. * @param {NDKEvent} event - The duplicate event received by the subscription. * @param {NDKRelay} relay - The relay that received the event. * @param {number} timeSinceFirstSeen - The time elapsed since the first time the event was seen. * @param {NDKSubscription} subscription - The subscription that received the event. * * @event NDKSubscription#eose - Emitted when all relays have reached the end of the event stream. * @param {NDKSubscription} subscription - The subscription that received EOSE. * * @event NDKSubscription#close - Emitted when the subscription is closed. * @param {NDKSubscription} subscription - The subscription that was closed. */ export class NDKSubscription extends EventEmitter { readonly subId: string; readonly filters: NDKFilter[]; readonly opts: NDKSubscriptionOptions; public relaySet?: NDKRelaySet;
public ndk: NDK;
public relaySubscriptions: Map<NDKRelay, Sub>; private debug: debug.Debugger; /** * Events that have been seen by the subscription, with the time they were first seen. */ public eventFirstSeen = new Map<NDKEventId, number>(); /** * Relays that have sent an EOSE. */ public eosesSeen = new Set<NDKRelay>(); /** * Events that have been seen by the subscription per relay. */ public eventsPerRelay: Map<NDKRelay, Set<NDKEventId>> = new Map(); public constructor( ndk: NDK, filters: NDKFilter | NDKFilter[], opts?: NDKSubscriptionOptions, relaySet?: NDKRelaySet, subId?: string ) { super(); this.ndk = ndk; this.opts = { ...defaultOpts, ...(opts || {}) }; this.filters = filters instanceof Array ? filters : [filters]; this.subId = subId || opts?.subId || generateFilterId(this.filters[0]); this.relaySet = relaySet; this.relaySubscriptions = new Map<NDKRelay, Sub>(); this.debug = ndk.debug.extend(`subscription:${this.subId}`); // validate that the caller is not expecting a persistent // subscription while using an option that will only hit the cache if ( this.opts.cacheUsage === NDKSubscriptionCacheUsage.ONLY_CACHE && !this.opts.closeOnEose ) { throw new Error( "Cannot use cache-only options with a persistent subscription" ); } } /** * Provides access to the first filter of the subscription for * backwards compatibility. */ get filter(): NDKFilter { return this.filters[0]; } /** * Calculates the groupable ID for this subscription. * * @returns The groupable ID, or null if the subscription is not groupable. */ public groupableId(): string | null { if (!this.opts?.groupable || this.filters.length > 1) { return null; } const filter = this.filters[0]; // Check if there is a kind and no time-based filters const noTimeConstraints = !filter.since && !filter.until; const noLimit = !filter.limit; if (noTimeConstraints && noLimit) { let id = filter.kinds ? filter.kinds.join(",") : ""; const keys = Object.keys(filter || {}) .sort() .join("-"); id += `-${keys}`; return id; } return null; } private shouldQueryCache(): boolean { return this.opts?.cacheUsage !== NDKSubscriptionCacheUsage.ONLY_RELAY; } private shouldQueryRelays(): boolean { return this.opts?.cacheUsage !== NDKSubscriptionCacheUsage.ONLY_CACHE; } private shouldWaitForCache(): boolean { return ( // Must want to close on EOSE; subscriptions // that want to receive further updates must // always hit the relay this.opts.closeOnEose && // Cache adapter must claim to be fast !!this.ndk.cacheAdapter?.locking && // If explicitly told to run in parallel, then // we should not wait for the cache this.opts.cacheUsage !== NDKSubscriptionCacheUsage.PARALLEL ); } /** * Start the subscription. This is the main method that should be called * after creating a subscription. */ public async start(): Promise<void> { let cachePromise; if (this.shouldQueryCache()) { cachePromise = this.startWithCache(); if (this.shouldWaitForCache()) { await cachePromise; // if the cache has a hit, return early if (queryFullyFilled(this)) { this.emit("eose", this); return; } } } if (this.shouldQueryRelays()) { this.startWithRelaySet(); } else { this.emit("eose", this); } return; } public stop(): void { this.relaySubscriptions.forEach((sub) => sub.unsub()); this.relaySubscriptions.clear(); this.emit("close", this); } private async startWithCache(): Promise<void> { if (this.ndk.cacheAdapter?.query) { const promise = this.ndk.cacheAdapter.query(this); if (this.ndk.cacheAdapter.locking) { await promise; } } } private startWithRelaySet(): void { if (!this.relaySet) { this.relaySet = calculateRelaySetFromFilter( this.ndk, this.filters[0] ); } if (this.relaySet) { this.relaySet.subscribe(this); } } // EVENT handling /** * Called when an event is received from a relay or the cache * @param event * @param relay * @param fromCache Whether the event was received from the cache */ public eventReceived( event: NDKEvent, relay: NDKRelay | undefined, fromCache = false ) { if (relay) event.relay = relay; if (!relay) relay = event.relay; if (!fromCache && relay) { // track the event per relay let events = this.eventsPerRelay.get(relay); if (!events) { events = new Set(); this.eventsPerRelay.set(relay, events); } events.add(event.id); // mark the event as seen const eventAlreadySeen = this.eventFirstSeen.has(event.id); if (eventAlreadySeen) { const timeSinceFirstSeen = Date.now() - (this.eventFirstSeen.get(event.id) || 0); relay.scoreSlowerEvent(timeSinceFirstSeen); this.emit("event:dup", event, relay, timeSinceFirstSeen, this); return; } if (this.ndk.cacheAdapter) { this.ndk.cacheAdapter.setEvent(event, this.filters[0], relay); } this.eventFirstSeen.set(`${event.id}`, Date.now()); } else { this.eventFirstSeen.set(`${event.id}`, 0); } this.emit("event", event, relay, this); } // EOSE handling private eoseTimeout: ReturnType<typeof setTimeout> | undefined; public eoseReceived(relay: NDKRelay): void { if (this.opts?.closeOnEose) { this.relaySubscriptions.get(relay)?.unsub(); this.relaySubscriptions.delete(relay); // if this was the last relay that needed to EOSE, emit that this subscription is closed if (this.relaySubscriptions.size === 0) { this.emit("close", this); } } this.eosesSeen.add(relay); const hasSeenAllEoses = this.eosesSeen.size === this.relaySet?.size(); if (hasSeenAllEoses) { this.emit("eose"); } else { if (this.eoseTimeout) { clearTimeout(this.eoseTimeout); } this.eoseTimeout = setTimeout(() => { this.emit("eose"); }, 500); } } } /** * Represents a group of subscriptions. * * Events emitted from the group will be emitted from each subscription. */ export class NDKSubscriptionGroup extends NDKSubscription { private subscriptions: NDKSubscription[]; constructor(ndk: NDK, subscriptions: NDKSubscription[]) { const debug = ndk.debug.extend("subscription-group"); const filters = mergeFilters(subscriptions.map((s) => s.filters[0])); super( ndk, filters, subscriptions[0].opts, // TODO: This should be merged subscriptions[0].relaySet // TODO: This should be merged ); this.subscriptions = subscriptions; debug("merged filters", { count: subscriptions.length, mergedFilters: this.filters[0], }); // forward events to the matching subscriptions this.on("event", this.forwardEvent); this.on("event:dup", this.forwardEventDup); this.on("eose", this.forwardEose); this.on("close", this.forwardClose); } private isEventForSubscription( event: NDKEvent, subscription: NDKSubscription ): boolean { const { filters } = subscription; if (!filters) return false; return matchFilter(filters[0], event.rawEvent() as any); // check if there is a filter whose key begins with '#'; if there is, check if the event has a tag with the same key on the first position // of the tags array of arrays and the same value in the second position // for (const key in filter) { // if (key === 'kinds' && filter.kinds!.includes(event.kind!)) return false; // else if (key === 'authors' && filter.authors!.includes(event.pubkey)) return false; // else if (key.startsWith('#')) { // const tagKey = key.slice(1); // const tagValue = filter[key]; // if (event.tags) { // for (const tag of event.tags) { // if (tag[0] === tagKey && tag[1] === tagValue) { // return false; // } // } // } // } // return true; } private forwardEvent(event: NDKEvent, relay: NDKRelay) { for (const subscription of this.subscriptions) { if (!this.isEventForSubscription(event, subscription)) { continue; } subscription.emit("event", event, relay, subscription); } } private forwardEventDup( event: NDKEvent, relay: NDKRelay, timeSinceFirstSeen: number ) { for (const subscription of this.subscriptions) { if (!this.isEventForSubscription(event, subscription)) { continue; } subscription.emit( "event:dup", event, relay, timeSinceFirstSeen, subscription ); } } private forwardEose() { for (const subscription of this.subscriptions) { subscription.emit("eose", subscription); } } private forwardClose() { for (const subscription of this.subscriptions) { subscription.emit("close", subscription); } } } /** * Go through all the passed filters, which should be * relatively similar, and merge them. */ export function mergeFilters(filters: NDKFilter[]): NDKFilter { const result: any = {}; filters.forEach((filter) => { Object.entries(filter).forEach(([key, value]) => { if (Array.isArray(value)) { if (result[key] === undefined) { result[key] = [...value]; } else { result[key] = Array.from( new Set([...result[key], ...value]) ); } } else { result[key] = value; } }); }); return result as NDKFilter; } /** * Creates a valid nostr filter from an event id or a NIP-19 bech32. */ export function filterFromId(id: string): NDKFilter { let decoded; try { decoded = nip19.decode(id); switch (decoded.type) { case "nevent": return { ids: [decoded.data.id] }; case "note": return { ids: [decoded.data] }; case "naddr": return { authors: [decoded.data.pubkey], "#d": [decoded.data.identifier], kinds: [decoded.data.kind], }; } } catch (e) {} return { ids: [id] }; } /** * Returns the specified relays from a NIP-19 bech32. * * @param bech32 The NIP-19 bech32. */ export function relaysFromBech32(bech32: string): NDKRelay[] { try { const decoded = nip19.decode(bech32); if (["naddr", "nevent"].includes(decoded?.type)) { const data = decoded.data as unknown as EventPointer; if (data?.relays) { return data.relays.map((r: string) => new NDKRelay(r)); } } } catch (e) { /* empty */ } return []; } /** * Generates a random filter id, based on the filter keys. */ function generateFilterId(filter: NDKFilter) { const keys = Object.keys(filter) || []; const subId = []; for (const key of keys) { if (key === "kinds") { const v = [key, filter.kinds!.join(",")]; subId.push(v.join(":")); } else { subId.push(key); } } subId.push(Math.floor(Math.random() * 999999999).toString()); return subId.join("-"); }
src/subscription/index.ts
nostr-dev-kit-ndk-ece64e1
[ { "filename": "src/relay/index.ts", "retrieved_chunk": " id: subscription.subId,\n });\n this.debug(`Subscribed to ${JSON.stringify(filters)}`);\n sub.on(\"event\", (event: NostrEvent) => {\n const e = new NDKEvent(undefined, event);\n e.relay = this;\n subscription.eventReceived(e, this);\n });\n sub.on(\"eose\", () => {\n subscription.eoseReceived(this);", "score": 0.8848984837532043 }, { "filename": "src/cache/index.ts", "retrieved_chunk": " query(subscription: NDKSubscription): Promise<void>;\n setEvent(\n event: NDKEvent,\n filter: NDKFilter,\n relay?: NDKRelay\n ): Promise<void>;\n}", "score": 0.8820687532424927 }, { "filename": "src/index.ts", "retrieved_chunk": " * @returns NDKSubscription\n */\n public subscribe(\n filters: NDKFilter | NDKFilter[],\n opts?: NDKSubscriptionOptions,\n relaySet?: NDKRelaySet,\n autoStart = true\n ): NDKSubscription {\n const subscription = new NDKSubscription(this, filters, opts, relaySet);\n // Signal to the relays that they are explicitly being used", "score": 0.8661755323410034 }, { "filename": "src/relay/index.ts", "retrieved_chunk": " // }, 60000);\n }\n this.emit(\"notice\", this, notice);\n }\n /**\n * Subscribes to a subscription.\n */\n public subscribe(subscription: NDKSubscription): Sub {\n const { filters } = subscription;\n const sub = this.relay.sub(filters, {", "score": 0.866046130657196 }, { "filename": "src/index.ts", "retrieved_chunk": " }\n return new Promise((resolve) => {\n const s = this.subscribe(\n filter,\n { ...(opts || {}), closeOnEose: true },\n relaySet,\n false\n );\n s.on(\"event\", (event) => {\n event.ndk = this;", "score": 0.865312933921814 } ]
typescript
public ndk: NDK;
import EventEmitter from "eventemitter3"; import { Filter as NostrFilter, matchFilter, Sub, nip19 } from "nostr-tools"; import { EventPointer } from "nostr-tools/lib/nip19"; import NDKEvent, { NDKEventId } from "../events/index.js"; import NDK from "../index.js"; import { NDKRelay } from "../relay"; import { calculateRelaySetFromFilter } from "../relay/sets/calculate"; import { NDKRelaySet } from "../relay/sets/index.js"; import { queryFullyFilled } from "./utils.js"; export type NDKFilter = NostrFilter; export enum NDKSubscriptionCacheUsage { // Only use cache, don't subscribe to relays ONLY_CACHE = "ONLY_CACHE", // Use cache, if no matches, use relays CACHE_FIRST = "CACHE_FIRST", // Use cache in addition to relays PARALLEL = "PARALLEL", // Skip cache, don't query it ONLY_RELAY = "ONLY_RELAY", } export interface NDKSubscriptionOptions { closeOnEose: boolean; cacheUsage?: NDKSubscriptionCacheUsage; /** * Groupable subscriptions are created with a slight time * delayed to allow similar filters to be grouped together. */ groupable?: boolean; /** * The delay to use when grouping subscriptions, specified in milliseconds. * @default 100 */ groupableDelay?: number; /** * The subscription ID to use for the subscription. */ subId?: string; } /** * Default subscription options. */ export const defaultOpts: NDKSubscriptionOptions = { closeOnEose: true, cacheUsage: NDKSubscriptionCacheUsage.CACHE_FIRST, groupable: true, groupableDelay: 100, }; /** * Represents a subscription to an NDK event stream. * * @event NDKSubscription#event * Emitted when an event is received by the subscription. * @param {NDKEvent} event - The event received by the subscription. * @param {NDKRelay} relay - The relay that received the event. * @param {NDKSubscription} subscription - The subscription that received the event. * * @event NDKSubscription#event:dup * Emitted when a duplicate event is received by the subscription. * @param {NDKEvent} event - The duplicate event received by the subscription. * @param {NDKRelay} relay - The relay that received the event. * @param {number} timeSinceFirstSeen - The time elapsed since the first time the event was seen. * @param {NDKSubscription} subscription - The subscription that received the event. * * @event NDKSubscription#eose - Emitted when all relays have reached the end of the event stream. * @param {NDKSubscription} subscription - The subscription that received EOSE. * * @event NDKSubscription#close - Emitted when the subscription is closed. * @param {NDKSubscription} subscription - The subscription that was closed. */ export class NDKSubscription extends EventEmitter { readonly subId: string; readonly filters: NDKFilter[]; readonly opts: NDKSubscriptionOptions; public relaySet?: NDKRelaySet; public ndk: NDK; public relaySubscriptions: Map<NDKRelay, Sub>; private debug: debug.Debugger; /** * Events that have been seen by the subscription, with the time they were first seen. */ public eventFirstSeen = new Map<NDKEventId, number>(); /** * Relays that have sent an EOSE. */ public eosesSeen = new Set<NDKRelay>(); /** * Events that have been seen by the subscription per relay. */ public eventsPerRelay
: Map<NDKRelay, Set<NDKEventId>> = new Map();
public constructor( ndk: NDK, filters: NDKFilter | NDKFilter[], opts?: NDKSubscriptionOptions, relaySet?: NDKRelaySet, subId?: string ) { super(); this.ndk = ndk; this.opts = { ...defaultOpts, ...(opts || {}) }; this.filters = filters instanceof Array ? filters : [filters]; this.subId = subId || opts?.subId || generateFilterId(this.filters[0]); this.relaySet = relaySet; this.relaySubscriptions = new Map<NDKRelay, Sub>(); this.debug = ndk.debug.extend(`subscription:${this.subId}`); // validate that the caller is not expecting a persistent // subscription while using an option that will only hit the cache if ( this.opts.cacheUsage === NDKSubscriptionCacheUsage.ONLY_CACHE && !this.opts.closeOnEose ) { throw new Error( "Cannot use cache-only options with a persistent subscription" ); } } /** * Provides access to the first filter of the subscription for * backwards compatibility. */ get filter(): NDKFilter { return this.filters[0]; } /** * Calculates the groupable ID for this subscription. * * @returns The groupable ID, or null if the subscription is not groupable. */ public groupableId(): string | null { if (!this.opts?.groupable || this.filters.length > 1) { return null; } const filter = this.filters[0]; // Check if there is a kind and no time-based filters const noTimeConstraints = !filter.since && !filter.until; const noLimit = !filter.limit; if (noTimeConstraints && noLimit) { let id = filter.kinds ? filter.kinds.join(",") : ""; const keys = Object.keys(filter || {}) .sort() .join("-"); id += `-${keys}`; return id; } return null; } private shouldQueryCache(): boolean { return this.opts?.cacheUsage !== NDKSubscriptionCacheUsage.ONLY_RELAY; } private shouldQueryRelays(): boolean { return this.opts?.cacheUsage !== NDKSubscriptionCacheUsage.ONLY_CACHE; } private shouldWaitForCache(): boolean { return ( // Must want to close on EOSE; subscriptions // that want to receive further updates must // always hit the relay this.opts.closeOnEose && // Cache adapter must claim to be fast !!this.ndk.cacheAdapter?.locking && // If explicitly told to run in parallel, then // we should not wait for the cache this.opts.cacheUsage !== NDKSubscriptionCacheUsage.PARALLEL ); } /** * Start the subscription. This is the main method that should be called * after creating a subscription. */ public async start(): Promise<void> { let cachePromise; if (this.shouldQueryCache()) { cachePromise = this.startWithCache(); if (this.shouldWaitForCache()) { await cachePromise; // if the cache has a hit, return early if (queryFullyFilled(this)) { this.emit("eose", this); return; } } } if (this.shouldQueryRelays()) { this.startWithRelaySet(); } else { this.emit("eose", this); } return; } public stop(): void { this.relaySubscriptions.forEach((sub) => sub.unsub()); this.relaySubscriptions.clear(); this.emit("close", this); } private async startWithCache(): Promise<void> { if (this.ndk.cacheAdapter?.query) { const promise = this.ndk.cacheAdapter.query(this); if (this.ndk.cacheAdapter.locking) { await promise; } } } private startWithRelaySet(): void { if (!this.relaySet) { this.relaySet = calculateRelaySetFromFilter( this.ndk, this.filters[0] ); } if (this.relaySet) { this.relaySet.subscribe(this); } } // EVENT handling /** * Called when an event is received from a relay or the cache * @param event * @param relay * @param fromCache Whether the event was received from the cache */ public eventReceived( event: NDKEvent, relay: NDKRelay | undefined, fromCache = false ) { if (relay) event.relay = relay; if (!relay) relay = event.relay; if (!fromCache && relay) { // track the event per relay let events = this.eventsPerRelay.get(relay); if (!events) { events = new Set(); this.eventsPerRelay.set(relay, events); } events.add(event.id); // mark the event as seen const eventAlreadySeen = this.eventFirstSeen.has(event.id); if (eventAlreadySeen) { const timeSinceFirstSeen = Date.now() - (this.eventFirstSeen.get(event.id) || 0); relay.scoreSlowerEvent(timeSinceFirstSeen); this.emit("event:dup", event, relay, timeSinceFirstSeen, this); return; } if (this.ndk.cacheAdapter) { this.ndk.cacheAdapter.setEvent(event, this.filters[0], relay); } this.eventFirstSeen.set(`${event.id}`, Date.now()); } else { this.eventFirstSeen.set(`${event.id}`, 0); } this.emit("event", event, relay, this); } // EOSE handling private eoseTimeout: ReturnType<typeof setTimeout> | undefined; public eoseReceived(relay: NDKRelay): void { if (this.opts?.closeOnEose) { this.relaySubscriptions.get(relay)?.unsub(); this.relaySubscriptions.delete(relay); // if this was the last relay that needed to EOSE, emit that this subscription is closed if (this.relaySubscriptions.size === 0) { this.emit("close", this); } } this.eosesSeen.add(relay); const hasSeenAllEoses = this.eosesSeen.size === this.relaySet?.size(); if (hasSeenAllEoses) { this.emit("eose"); } else { if (this.eoseTimeout) { clearTimeout(this.eoseTimeout); } this.eoseTimeout = setTimeout(() => { this.emit("eose"); }, 500); } } } /** * Represents a group of subscriptions. * * Events emitted from the group will be emitted from each subscription. */ export class NDKSubscriptionGroup extends NDKSubscription { private subscriptions: NDKSubscription[]; constructor(ndk: NDK, subscriptions: NDKSubscription[]) { const debug = ndk.debug.extend("subscription-group"); const filters = mergeFilters(subscriptions.map((s) => s.filters[0])); super( ndk, filters, subscriptions[0].opts, // TODO: This should be merged subscriptions[0].relaySet // TODO: This should be merged ); this.subscriptions = subscriptions; debug("merged filters", { count: subscriptions.length, mergedFilters: this.filters[0], }); // forward events to the matching subscriptions this.on("event", this.forwardEvent); this.on("event:dup", this.forwardEventDup); this.on("eose", this.forwardEose); this.on("close", this.forwardClose); } private isEventForSubscription( event: NDKEvent, subscription: NDKSubscription ): boolean { const { filters } = subscription; if (!filters) return false; return matchFilter(filters[0], event.rawEvent() as any); // check if there is a filter whose key begins with '#'; if there is, check if the event has a tag with the same key on the first position // of the tags array of arrays and the same value in the second position // for (const key in filter) { // if (key === 'kinds' && filter.kinds!.includes(event.kind!)) return false; // else if (key === 'authors' && filter.authors!.includes(event.pubkey)) return false; // else if (key.startsWith('#')) { // const tagKey = key.slice(1); // const tagValue = filter[key]; // if (event.tags) { // for (const tag of event.tags) { // if (tag[0] === tagKey && tag[1] === tagValue) { // return false; // } // } // } // } // return true; } private forwardEvent(event: NDKEvent, relay: NDKRelay) { for (const subscription of this.subscriptions) { if (!this.isEventForSubscription(event, subscription)) { continue; } subscription.emit("event", event, relay, subscription); } } private forwardEventDup( event: NDKEvent, relay: NDKRelay, timeSinceFirstSeen: number ) { for (const subscription of this.subscriptions) { if (!this.isEventForSubscription(event, subscription)) { continue; } subscription.emit( "event:dup", event, relay, timeSinceFirstSeen, subscription ); } } private forwardEose() { for (const subscription of this.subscriptions) { subscription.emit("eose", subscription); } } private forwardClose() { for (const subscription of this.subscriptions) { subscription.emit("close", subscription); } } } /** * Go through all the passed filters, which should be * relatively similar, and merge them. */ export function mergeFilters(filters: NDKFilter[]): NDKFilter { const result: any = {}; filters.forEach((filter) => { Object.entries(filter).forEach(([key, value]) => { if (Array.isArray(value)) { if (result[key] === undefined) { result[key] = [...value]; } else { result[key] = Array.from( new Set([...result[key], ...value]) ); } } else { result[key] = value; } }); }); return result as NDKFilter; } /** * Creates a valid nostr filter from an event id or a NIP-19 bech32. */ export function filterFromId(id: string): NDKFilter { let decoded; try { decoded = nip19.decode(id); switch (decoded.type) { case "nevent": return { ids: [decoded.data.id] }; case "note": return { ids: [decoded.data] }; case "naddr": return { authors: [decoded.data.pubkey], "#d": [decoded.data.identifier], kinds: [decoded.data.kind], }; } } catch (e) {} return { ids: [id] }; } /** * Returns the specified relays from a NIP-19 bech32. * * @param bech32 The NIP-19 bech32. */ export function relaysFromBech32(bech32: string): NDKRelay[] { try { const decoded = nip19.decode(bech32); if (["naddr", "nevent"].includes(decoded?.type)) { const data = decoded.data as unknown as EventPointer; if (data?.relays) { return data.relays.map((r: string) => new NDKRelay(r)); } } } catch (e) { /* empty */ } return []; } /** * Generates a random filter id, based on the filter keys. */ function generateFilterId(filter: NDKFilter) { const keys = Object.keys(filter) || []; const subId = []; for (const key of keys) { if (key === "kinds") { const v = [key, filter.kinds!.join(",")]; subId.push(v.join(":")); } else { subId.push(key); } } subId.push(Math.floor(Math.random() * 999999999).toString()); return subId.join("-"); }
src/subscription/index.ts
nostr-dev-kit-ndk-ece64e1
[ { "filename": "src/index.ts", "retrieved_chunk": " event.ndk = this;\n events.set(dedupKey, event);\n };\n // We want to inspect duplicated events\n // so we can dedup them\n relaySetSubscription.on(\"event\", onEvent);\n relaySetSubscription.on(\"event:dup\", onEvent);\n relaySetSubscription.on(\"eose\", () => {\n resolve(new Set(events.values()));\n });", "score": 0.845024824142456 }, { "filename": "src/user/index.ts", "retrieved_chunk": " if (!this.ndk) throw new Error(\"NDK not set\");\n const relayListEvents = await this.ndk.fetchEvents({\n kinds: [10002],\n authors: [this.hexpubkey()],\n });\n if (relayListEvents) {\n return relayListEvents;\n }\n return new Set<NDKEvent>();\n }", "score": 0.8368200659751892 }, { "filename": "src/index.ts", "retrieved_chunk": " { ...(opts || {}), closeOnEose: true },\n relaySet,\n false\n );\n const onEvent = (event: NDKEvent) => {\n const dedupKey = event.deduplicationKey();\n const existingEvent = events.get(dedupKey);\n if (existingEvent) {\n event = dedupEvent(existingEvent, event);\n }", "score": 0.8306013345718384 }, { "filename": "src/relay/index.ts", "retrieved_chunk": " id: subscription.subId,\n });\n this.debug(`Subscribed to ${JSON.stringify(filters)}`);\n sub.on(\"event\", (event: NostrEvent) => {\n const e = new NDKEvent(undefined, event);\n e.relay = this;\n subscription.eventReceived(e, this);\n });\n sub.on(\"eose\", () => {\n subscription.eoseReceived(this);", "score": 0.8300305604934692 }, { "filename": "src/relay/sets/index.ts", "retrieved_chunk": "import { sha256 } from \"@noble/hashes/sha256\";\nimport { bytesToHex } from \"@noble/hashes/utils\";\nimport NDKEvent from \"../../events/index.js\";\nimport type NDK from \"../../index.js\";\nimport {\n NDKSubscription,\n NDKSubscriptionGroup,\n} from \"../../subscription/index.js\";\nimport { NDKRelay, NDKRelayStatus } from \"../index.js\";\n/**", "score": 0.8219565749168396 } ]
typescript
: Map<NDKRelay, Set<NDKEventId>> = new Map();
import EventEmitter from "eventemitter3"; import { Filter as NostrFilter, matchFilter, Sub, nip19 } from "nostr-tools"; import { EventPointer } from "nostr-tools/lib/nip19"; import NDKEvent, { NDKEventId } from "../events/index.js"; import NDK from "../index.js"; import { NDKRelay } from "../relay"; import { calculateRelaySetFromFilter } from "../relay/sets/calculate"; import { NDKRelaySet } from "../relay/sets/index.js"; import { queryFullyFilled } from "./utils.js"; export type NDKFilter = NostrFilter; export enum NDKSubscriptionCacheUsage { // Only use cache, don't subscribe to relays ONLY_CACHE = "ONLY_CACHE", // Use cache, if no matches, use relays CACHE_FIRST = "CACHE_FIRST", // Use cache in addition to relays PARALLEL = "PARALLEL", // Skip cache, don't query it ONLY_RELAY = "ONLY_RELAY", } export interface NDKSubscriptionOptions { closeOnEose: boolean; cacheUsage?: NDKSubscriptionCacheUsage; /** * Groupable subscriptions are created with a slight time * delayed to allow similar filters to be grouped together. */ groupable?: boolean; /** * The delay to use when grouping subscriptions, specified in milliseconds. * @default 100 */ groupableDelay?: number; /** * The subscription ID to use for the subscription. */ subId?: string; } /** * Default subscription options. */ export const defaultOpts: NDKSubscriptionOptions = { closeOnEose: true, cacheUsage: NDKSubscriptionCacheUsage.CACHE_FIRST, groupable: true, groupableDelay: 100, }; /** * Represents a subscription to an NDK event stream. * * @event NDKSubscription#event * Emitted when an event is received by the subscription. * @param {NDKEvent} event - The event received by the subscription. * @param {NDKRelay} relay - The relay that received the event. * @param {NDKSubscription} subscription - The subscription that received the event. * * @event NDKSubscription#event:dup * Emitted when a duplicate event is received by the subscription. * @param {NDKEvent} event - The duplicate event received by the subscription. * @param {NDKRelay} relay - The relay that received the event. * @param {number} timeSinceFirstSeen - The time elapsed since the first time the event was seen. * @param {NDKSubscription} subscription - The subscription that received the event. * * @event NDKSubscription#eose - Emitted when all relays have reached the end of the event stream. * @param {NDKSubscription} subscription - The subscription that received EOSE. * * @event NDKSubscription#close - Emitted when the subscription is closed. * @param {NDKSubscription} subscription - The subscription that was closed. */ export class NDKSubscription extends EventEmitter { readonly subId: string; readonly filters: NDKFilter[]; readonly opts: NDKSubscriptionOptions; public
relaySet?: NDKRelaySet;
public ndk: NDK; public relaySubscriptions: Map<NDKRelay, Sub>; private debug: debug.Debugger; /** * Events that have been seen by the subscription, with the time they were first seen. */ public eventFirstSeen = new Map<NDKEventId, number>(); /** * Relays that have sent an EOSE. */ public eosesSeen = new Set<NDKRelay>(); /** * Events that have been seen by the subscription per relay. */ public eventsPerRelay: Map<NDKRelay, Set<NDKEventId>> = new Map(); public constructor( ndk: NDK, filters: NDKFilter | NDKFilter[], opts?: NDKSubscriptionOptions, relaySet?: NDKRelaySet, subId?: string ) { super(); this.ndk = ndk; this.opts = { ...defaultOpts, ...(opts || {}) }; this.filters = filters instanceof Array ? filters : [filters]; this.subId = subId || opts?.subId || generateFilterId(this.filters[0]); this.relaySet = relaySet; this.relaySubscriptions = new Map<NDKRelay, Sub>(); this.debug = ndk.debug.extend(`subscription:${this.subId}`); // validate that the caller is not expecting a persistent // subscription while using an option that will only hit the cache if ( this.opts.cacheUsage === NDKSubscriptionCacheUsage.ONLY_CACHE && !this.opts.closeOnEose ) { throw new Error( "Cannot use cache-only options with a persistent subscription" ); } } /** * Provides access to the first filter of the subscription for * backwards compatibility. */ get filter(): NDKFilter { return this.filters[0]; } /** * Calculates the groupable ID for this subscription. * * @returns The groupable ID, or null if the subscription is not groupable. */ public groupableId(): string | null { if (!this.opts?.groupable || this.filters.length > 1) { return null; } const filter = this.filters[0]; // Check if there is a kind and no time-based filters const noTimeConstraints = !filter.since && !filter.until; const noLimit = !filter.limit; if (noTimeConstraints && noLimit) { let id = filter.kinds ? filter.kinds.join(",") : ""; const keys = Object.keys(filter || {}) .sort() .join("-"); id += `-${keys}`; return id; } return null; } private shouldQueryCache(): boolean { return this.opts?.cacheUsage !== NDKSubscriptionCacheUsage.ONLY_RELAY; } private shouldQueryRelays(): boolean { return this.opts?.cacheUsage !== NDKSubscriptionCacheUsage.ONLY_CACHE; } private shouldWaitForCache(): boolean { return ( // Must want to close on EOSE; subscriptions // that want to receive further updates must // always hit the relay this.opts.closeOnEose && // Cache adapter must claim to be fast !!this.ndk.cacheAdapter?.locking && // If explicitly told to run in parallel, then // we should not wait for the cache this.opts.cacheUsage !== NDKSubscriptionCacheUsage.PARALLEL ); } /** * Start the subscription. This is the main method that should be called * after creating a subscription. */ public async start(): Promise<void> { let cachePromise; if (this.shouldQueryCache()) { cachePromise = this.startWithCache(); if (this.shouldWaitForCache()) { await cachePromise; // if the cache has a hit, return early if (queryFullyFilled(this)) { this.emit("eose", this); return; } } } if (this.shouldQueryRelays()) { this.startWithRelaySet(); } else { this.emit("eose", this); } return; } public stop(): void { this.relaySubscriptions.forEach((sub) => sub.unsub()); this.relaySubscriptions.clear(); this.emit("close", this); } private async startWithCache(): Promise<void> { if (this.ndk.cacheAdapter?.query) { const promise = this.ndk.cacheAdapter.query(this); if (this.ndk.cacheAdapter.locking) { await promise; } } } private startWithRelaySet(): void { if (!this.relaySet) { this.relaySet = calculateRelaySetFromFilter( this.ndk, this.filters[0] ); } if (this.relaySet) { this.relaySet.subscribe(this); } } // EVENT handling /** * Called when an event is received from a relay or the cache * @param event * @param relay * @param fromCache Whether the event was received from the cache */ public eventReceived( event: NDKEvent, relay: NDKRelay | undefined, fromCache = false ) { if (relay) event.relay = relay; if (!relay) relay = event.relay; if (!fromCache && relay) { // track the event per relay let events = this.eventsPerRelay.get(relay); if (!events) { events = new Set(); this.eventsPerRelay.set(relay, events); } events.add(event.id); // mark the event as seen const eventAlreadySeen = this.eventFirstSeen.has(event.id); if (eventAlreadySeen) { const timeSinceFirstSeen = Date.now() - (this.eventFirstSeen.get(event.id) || 0); relay.scoreSlowerEvent(timeSinceFirstSeen); this.emit("event:dup", event, relay, timeSinceFirstSeen, this); return; } if (this.ndk.cacheAdapter) { this.ndk.cacheAdapter.setEvent(event, this.filters[0], relay); } this.eventFirstSeen.set(`${event.id}`, Date.now()); } else { this.eventFirstSeen.set(`${event.id}`, 0); } this.emit("event", event, relay, this); } // EOSE handling private eoseTimeout: ReturnType<typeof setTimeout> | undefined; public eoseReceived(relay: NDKRelay): void { if (this.opts?.closeOnEose) { this.relaySubscriptions.get(relay)?.unsub(); this.relaySubscriptions.delete(relay); // if this was the last relay that needed to EOSE, emit that this subscription is closed if (this.relaySubscriptions.size === 0) { this.emit("close", this); } } this.eosesSeen.add(relay); const hasSeenAllEoses = this.eosesSeen.size === this.relaySet?.size(); if (hasSeenAllEoses) { this.emit("eose"); } else { if (this.eoseTimeout) { clearTimeout(this.eoseTimeout); } this.eoseTimeout = setTimeout(() => { this.emit("eose"); }, 500); } } } /** * Represents a group of subscriptions. * * Events emitted from the group will be emitted from each subscription. */ export class NDKSubscriptionGroup extends NDKSubscription { private subscriptions: NDKSubscription[]; constructor(ndk: NDK, subscriptions: NDKSubscription[]) { const debug = ndk.debug.extend("subscription-group"); const filters = mergeFilters(subscriptions.map((s) => s.filters[0])); super( ndk, filters, subscriptions[0].opts, // TODO: This should be merged subscriptions[0].relaySet // TODO: This should be merged ); this.subscriptions = subscriptions; debug("merged filters", { count: subscriptions.length, mergedFilters: this.filters[0], }); // forward events to the matching subscriptions this.on("event", this.forwardEvent); this.on("event:dup", this.forwardEventDup); this.on("eose", this.forwardEose); this.on("close", this.forwardClose); } private isEventForSubscription( event: NDKEvent, subscription: NDKSubscription ): boolean { const { filters } = subscription; if (!filters) return false; return matchFilter(filters[0], event.rawEvent() as any); // check if there is a filter whose key begins with '#'; if there is, check if the event has a tag with the same key on the first position // of the tags array of arrays and the same value in the second position // for (const key in filter) { // if (key === 'kinds' && filter.kinds!.includes(event.kind!)) return false; // else if (key === 'authors' && filter.authors!.includes(event.pubkey)) return false; // else if (key.startsWith('#')) { // const tagKey = key.slice(1); // const tagValue = filter[key]; // if (event.tags) { // for (const tag of event.tags) { // if (tag[0] === tagKey && tag[1] === tagValue) { // return false; // } // } // } // } // return true; } private forwardEvent(event: NDKEvent, relay: NDKRelay) { for (const subscription of this.subscriptions) { if (!this.isEventForSubscription(event, subscription)) { continue; } subscription.emit("event", event, relay, subscription); } } private forwardEventDup( event: NDKEvent, relay: NDKRelay, timeSinceFirstSeen: number ) { for (const subscription of this.subscriptions) { if (!this.isEventForSubscription(event, subscription)) { continue; } subscription.emit( "event:dup", event, relay, timeSinceFirstSeen, subscription ); } } private forwardEose() { for (const subscription of this.subscriptions) { subscription.emit("eose", subscription); } } private forwardClose() { for (const subscription of this.subscriptions) { subscription.emit("close", subscription); } } } /** * Go through all the passed filters, which should be * relatively similar, and merge them. */ export function mergeFilters(filters: NDKFilter[]): NDKFilter { const result: any = {}; filters.forEach((filter) => { Object.entries(filter).forEach(([key, value]) => { if (Array.isArray(value)) { if (result[key] === undefined) { result[key] = [...value]; } else { result[key] = Array.from( new Set([...result[key], ...value]) ); } } else { result[key] = value; } }); }); return result as NDKFilter; } /** * Creates a valid nostr filter from an event id or a NIP-19 bech32. */ export function filterFromId(id: string): NDKFilter { let decoded; try { decoded = nip19.decode(id); switch (decoded.type) { case "nevent": return { ids: [decoded.data.id] }; case "note": return { ids: [decoded.data] }; case "naddr": return { authors: [decoded.data.pubkey], "#d": [decoded.data.identifier], kinds: [decoded.data.kind], }; } } catch (e) {} return { ids: [id] }; } /** * Returns the specified relays from a NIP-19 bech32. * * @param bech32 The NIP-19 bech32. */ export function relaysFromBech32(bech32: string): NDKRelay[] { try { const decoded = nip19.decode(bech32); if (["naddr", "nevent"].includes(decoded?.type)) { const data = decoded.data as unknown as EventPointer; if (data?.relays) { return data.relays.map((r: string) => new NDKRelay(r)); } } } catch (e) { /* empty */ } return []; } /** * Generates a random filter id, based on the filter keys. */ function generateFilterId(filter: NDKFilter) { const keys = Object.keys(filter) || []; const subId = []; for (const key of keys) { if (key === "kinds") { const v = [key, filter.kinds!.join(",")]; subId.push(v.join(":")); } else { subId.push(key); } } subId.push(Math.floor(Math.random() * 999999999).toString()); return subId.join("-"); }
src/subscription/index.ts
nostr-dev-kit-ndk-ece64e1
[ { "filename": "src/relay/index.ts", "retrieved_chunk": " id: subscription.subId,\n });\n this.debug(`Subscribed to ${JSON.stringify(filters)}`);\n sub.on(\"event\", (event: NostrEvent) => {\n const e = new NDKEvent(undefined, event);\n e.relay = this;\n subscription.eventReceived(e, this);\n });\n sub.on(\"eose\", () => {\n subscription.eoseReceived(this);", "score": 0.8780308961868286 }, { "filename": "src/cache/index.ts", "retrieved_chunk": " query(subscription: NDKSubscription): Promise<void>;\n setEvent(\n event: NDKEvent,\n filter: NDKFilter,\n relay?: NDKRelay\n ): Promise<void>;\n}", "score": 0.8677626848220825 }, { "filename": "src/relay/index.ts", "retrieved_chunk": " // }, 60000);\n }\n this.emit(\"notice\", this, notice);\n }\n /**\n * Subscribes to a subscription.\n */\n public subscribe(subscription: NDKSubscription): Sub {\n const { filters } = subscription;\n const sub = this.relay.sub(filters, {", "score": 0.8632489442825317 }, { "filename": "src/index.ts", "retrieved_chunk": " }\n return new Promise((resolve) => {\n const s = this.subscribe(\n filter,\n { ...(opts || {}), closeOnEose: true },\n relaySet,\n false\n );\n s.on(\"event\", (event) => {\n event.ndk = this;", "score": 0.8632122278213501 }, { "filename": "src/index.ts", "retrieved_chunk": " * @returns NDKSubscription\n */\n public subscribe(\n filters: NDKFilter | NDKFilter[],\n opts?: NDKSubscriptionOptions,\n relaySet?: NDKRelaySet,\n autoStart = true\n ): NDKSubscription {\n const subscription = new NDKSubscription(this, filters, opts, relaySet);\n // Signal to the relays that they are explicitly being used", "score": 0.8625049591064453 } ]
typescript
relaySet?: NDKRelaySet;
import EventEmitter from "eventemitter3"; import { Filter as NostrFilter, matchFilter, Sub, nip19 } from "nostr-tools"; import { EventPointer } from "nostr-tools/lib/nip19"; import NDKEvent, { NDKEventId } from "../events/index.js"; import NDK from "../index.js"; import { NDKRelay } from "../relay"; import { calculateRelaySetFromFilter } from "../relay/sets/calculate"; import { NDKRelaySet } from "../relay/sets/index.js"; import { queryFullyFilled } from "./utils.js"; export type NDKFilter = NostrFilter; export enum NDKSubscriptionCacheUsage { // Only use cache, don't subscribe to relays ONLY_CACHE = "ONLY_CACHE", // Use cache, if no matches, use relays CACHE_FIRST = "CACHE_FIRST", // Use cache in addition to relays PARALLEL = "PARALLEL", // Skip cache, don't query it ONLY_RELAY = "ONLY_RELAY", } export interface NDKSubscriptionOptions { closeOnEose: boolean; cacheUsage?: NDKSubscriptionCacheUsage; /** * Groupable subscriptions are created with a slight time * delayed to allow similar filters to be grouped together. */ groupable?: boolean; /** * The delay to use when grouping subscriptions, specified in milliseconds. * @default 100 */ groupableDelay?: number; /** * The subscription ID to use for the subscription. */ subId?: string; } /** * Default subscription options. */ export const defaultOpts: NDKSubscriptionOptions = { closeOnEose: true, cacheUsage: NDKSubscriptionCacheUsage.CACHE_FIRST, groupable: true, groupableDelay: 100, }; /** * Represents a subscription to an NDK event stream. * * @event NDKSubscription#event * Emitted when an event is received by the subscription. * @param {NDKEvent} event - The event received by the subscription. * @param {NDKRelay} relay - The relay that received the event. * @param {NDKSubscription} subscription - The subscription that received the event. * * @event NDKSubscription#event:dup * Emitted when a duplicate event is received by the subscription. * @param {NDKEvent} event - The duplicate event received by the subscription. * @param {NDKRelay} relay - The relay that received the event. * @param {number} timeSinceFirstSeen - The time elapsed since the first time the event was seen. * @param {NDKSubscription} subscription - The subscription that received the event. * * @event NDKSubscription#eose - Emitted when all relays have reached the end of the event stream. * @param {NDKSubscription} subscription - The subscription that received EOSE. * * @event NDKSubscription#close - Emitted when the subscription is closed. * @param {NDKSubscription} subscription - The subscription that was closed. */ export class NDKSubscription extends EventEmitter { readonly subId: string; readonly filters: NDKFilter[]; readonly opts: NDKSubscriptionOptions; public relaySet?: NDKRelaySet; public ndk: NDK; public relaySubscriptions: Map<NDKRelay, Sub>; private debug: debug.Debugger; /** * Events that have been seen by the subscription, with the time they were first seen. */ public eventFirstSeen = new Map<NDKEventId, number>(); /** * Relays that have sent an EOSE. */ public eosesSeen = new Set<NDKRelay>(); /** * Events that have been seen by the subscription per relay. */ public eventsPerRelay: Map<NDKRelay, Set<NDKEventId>> = new Map(); public constructor( ndk: NDK, filters: NDKFilter | NDKFilter[], opts?: NDKSubscriptionOptions, relaySet?
: NDKRelaySet, subId?: string ) {
super(); this.ndk = ndk; this.opts = { ...defaultOpts, ...(opts || {}) }; this.filters = filters instanceof Array ? filters : [filters]; this.subId = subId || opts?.subId || generateFilterId(this.filters[0]); this.relaySet = relaySet; this.relaySubscriptions = new Map<NDKRelay, Sub>(); this.debug = ndk.debug.extend(`subscription:${this.subId}`); // validate that the caller is not expecting a persistent // subscription while using an option that will only hit the cache if ( this.opts.cacheUsage === NDKSubscriptionCacheUsage.ONLY_CACHE && !this.opts.closeOnEose ) { throw new Error( "Cannot use cache-only options with a persistent subscription" ); } } /** * Provides access to the first filter of the subscription for * backwards compatibility. */ get filter(): NDKFilter { return this.filters[0]; } /** * Calculates the groupable ID for this subscription. * * @returns The groupable ID, or null if the subscription is not groupable. */ public groupableId(): string | null { if (!this.opts?.groupable || this.filters.length > 1) { return null; } const filter = this.filters[0]; // Check if there is a kind and no time-based filters const noTimeConstraints = !filter.since && !filter.until; const noLimit = !filter.limit; if (noTimeConstraints && noLimit) { let id = filter.kinds ? filter.kinds.join(",") : ""; const keys = Object.keys(filter || {}) .sort() .join("-"); id += `-${keys}`; return id; } return null; } private shouldQueryCache(): boolean { return this.opts?.cacheUsage !== NDKSubscriptionCacheUsage.ONLY_RELAY; } private shouldQueryRelays(): boolean { return this.opts?.cacheUsage !== NDKSubscriptionCacheUsage.ONLY_CACHE; } private shouldWaitForCache(): boolean { return ( // Must want to close on EOSE; subscriptions // that want to receive further updates must // always hit the relay this.opts.closeOnEose && // Cache adapter must claim to be fast !!this.ndk.cacheAdapter?.locking && // If explicitly told to run in parallel, then // we should not wait for the cache this.opts.cacheUsage !== NDKSubscriptionCacheUsage.PARALLEL ); } /** * Start the subscription. This is the main method that should be called * after creating a subscription. */ public async start(): Promise<void> { let cachePromise; if (this.shouldQueryCache()) { cachePromise = this.startWithCache(); if (this.shouldWaitForCache()) { await cachePromise; // if the cache has a hit, return early if (queryFullyFilled(this)) { this.emit("eose", this); return; } } } if (this.shouldQueryRelays()) { this.startWithRelaySet(); } else { this.emit("eose", this); } return; } public stop(): void { this.relaySubscriptions.forEach((sub) => sub.unsub()); this.relaySubscriptions.clear(); this.emit("close", this); } private async startWithCache(): Promise<void> { if (this.ndk.cacheAdapter?.query) { const promise = this.ndk.cacheAdapter.query(this); if (this.ndk.cacheAdapter.locking) { await promise; } } } private startWithRelaySet(): void { if (!this.relaySet) { this.relaySet = calculateRelaySetFromFilter( this.ndk, this.filters[0] ); } if (this.relaySet) { this.relaySet.subscribe(this); } } // EVENT handling /** * Called when an event is received from a relay or the cache * @param event * @param relay * @param fromCache Whether the event was received from the cache */ public eventReceived( event: NDKEvent, relay: NDKRelay | undefined, fromCache = false ) { if (relay) event.relay = relay; if (!relay) relay = event.relay; if (!fromCache && relay) { // track the event per relay let events = this.eventsPerRelay.get(relay); if (!events) { events = new Set(); this.eventsPerRelay.set(relay, events); } events.add(event.id); // mark the event as seen const eventAlreadySeen = this.eventFirstSeen.has(event.id); if (eventAlreadySeen) { const timeSinceFirstSeen = Date.now() - (this.eventFirstSeen.get(event.id) || 0); relay.scoreSlowerEvent(timeSinceFirstSeen); this.emit("event:dup", event, relay, timeSinceFirstSeen, this); return; } if (this.ndk.cacheAdapter) { this.ndk.cacheAdapter.setEvent(event, this.filters[0], relay); } this.eventFirstSeen.set(`${event.id}`, Date.now()); } else { this.eventFirstSeen.set(`${event.id}`, 0); } this.emit("event", event, relay, this); } // EOSE handling private eoseTimeout: ReturnType<typeof setTimeout> | undefined; public eoseReceived(relay: NDKRelay): void { if (this.opts?.closeOnEose) { this.relaySubscriptions.get(relay)?.unsub(); this.relaySubscriptions.delete(relay); // if this was the last relay that needed to EOSE, emit that this subscription is closed if (this.relaySubscriptions.size === 0) { this.emit("close", this); } } this.eosesSeen.add(relay); const hasSeenAllEoses = this.eosesSeen.size === this.relaySet?.size(); if (hasSeenAllEoses) { this.emit("eose"); } else { if (this.eoseTimeout) { clearTimeout(this.eoseTimeout); } this.eoseTimeout = setTimeout(() => { this.emit("eose"); }, 500); } } } /** * Represents a group of subscriptions. * * Events emitted from the group will be emitted from each subscription. */ export class NDKSubscriptionGroup extends NDKSubscription { private subscriptions: NDKSubscription[]; constructor(ndk: NDK, subscriptions: NDKSubscription[]) { const debug = ndk.debug.extend("subscription-group"); const filters = mergeFilters(subscriptions.map((s) => s.filters[0])); super( ndk, filters, subscriptions[0].opts, // TODO: This should be merged subscriptions[0].relaySet // TODO: This should be merged ); this.subscriptions = subscriptions; debug("merged filters", { count: subscriptions.length, mergedFilters: this.filters[0], }); // forward events to the matching subscriptions this.on("event", this.forwardEvent); this.on("event:dup", this.forwardEventDup); this.on("eose", this.forwardEose); this.on("close", this.forwardClose); } private isEventForSubscription( event: NDKEvent, subscription: NDKSubscription ): boolean { const { filters } = subscription; if (!filters) return false; return matchFilter(filters[0], event.rawEvent() as any); // check if there is a filter whose key begins with '#'; if there is, check if the event has a tag with the same key on the first position // of the tags array of arrays and the same value in the second position // for (const key in filter) { // if (key === 'kinds' && filter.kinds!.includes(event.kind!)) return false; // else if (key === 'authors' && filter.authors!.includes(event.pubkey)) return false; // else if (key.startsWith('#')) { // const tagKey = key.slice(1); // const tagValue = filter[key]; // if (event.tags) { // for (const tag of event.tags) { // if (tag[0] === tagKey && tag[1] === tagValue) { // return false; // } // } // } // } // return true; } private forwardEvent(event: NDKEvent, relay: NDKRelay) { for (const subscription of this.subscriptions) { if (!this.isEventForSubscription(event, subscription)) { continue; } subscription.emit("event", event, relay, subscription); } } private forwardEventDup( event: NDKEvent, relay: NDKRelay, timeSinceFirstSeen: number ) { for (const subscription of this.subscriptions) { if (!this.isEventForSubscription(event, subscription)) { continue; } subscription.emit( "event:dup", event, relay, timeSinceFirstSeen, subscription ); } } private forwardEose() { for (const subscription of this.subscriptions) { subscription.emit("eose", subscription); } } private forwardClose() { for (const subscription of this.subscriptions) { subscription.emit("close", subscription); } } } /** * Go through all the passed filters, which should be * relatively similar, and merge them. */ export function mergeFilters(filters: NDKFilter[]): NDKFilter { const result: any = {}; filters.forEach((filter) => { Object.entries(filter).forEach(([key, value]) => { if (Array.isArray(value)) { if (result[key] === undefined) { result[key] = [...value]; } else { result[key] = Array.from( new Set([...result[key], ...value]) ); } } else { result[key] = value; } }); }); return result as NDKFilter; } /** * Creates a valid nostr filter from an event id or a NIP-19 bech32. */ export function filterFromId(id: string): NDKFilter { let decoded; try { decoded = nip19.decode(id); switch (decoded.type) { case "nevent": return { ids: [decoded.data.id] }; case "note": return { ids: [decoded.data] }; case "naddr": return { authors: [decoded.data.pubkey], "#d": [decoded.data.identifier], kinds: [decoded.data.kind], }; } } catch (e) {} return { ids: [id] }; } /** * Returns the specified relays from a NIP-19 bech32. * * @param bech32 The NIP-19 bech32. */ export function relaysFromBech32(bech32: string): NDKRelay[] { try { const decoded = nip19.decode(bech32); if (["naddr", "nevent"].includes(decoded?.type)) { const data = decoded.data as unknown as EventPointer; if (data?.relays) { return data.relays.map((r: string) => new NDKRelay(r)); } } } catch (e) { /* empty */ } return []; } /** * Generates a random filter id, based on the filter keys. */ function generateFilterId(filter: NDKFilter) { const keys = Object.keys(filter) || []; const subId = []; for (const key of keys) { if (key === "kinds") { const v = [key, filter.kinds!.join(",")]; subId.push(v.join(":")); } else { subId.push(key); } } subId.push(Math.floor(Math.random() * 999999999).toString()); return subId.join("-"); }
src/subscription/index.ts
nostr-dev-kit-ndk-ece64e1
[ { "filename": "src/index.ts", "retrieved_chunk": " */\n public async fetchEvents(\n filters: NDKFilter | NDKFilter[],\n opts?: NDKSubscriptionOptions,\n relaySet?: NDKRelaySet\n ): Promise<Set<NDKEvent>> {\n return new Promise((resolve) => {\n const events: Map<string, NDKEvent> = new Map();\n const relaySetSubscription = this.subscribe(\n filters,", "score": 0.8998438715934753 }, { "filename": "src/index.ts", "retrieved_chunk": " public pool: NDKPool;\n public signer?: NDKSigner;\n public cacheAdapter?: NDKCacheAdapter;\n public debug: debug.Debugger;\n public devWriteRelaySet?: NDKRelaySet;\n public delayedSubscriptions: Map<string, NDKSubscription[]>;\n public constructor(opts: NDKConstructorParams = {}) {\n super();\n this.debug = opts.debug || debug(\"ndk\");\n this.pool = new NDKPool(opts.explicitRelayUrls || [], this);", "score": 0.8831238746643066 }, { "filename": "src/index.ts", "retrieved_chunk": " opts?: NDKSubscriptionOptions,\n relaySet?: NDKRelaySet\n ): Promise<NDKEvent | null> {\n let filter: NDKFilter;\n // if no relayset has been provided, try to get one from the event id\n if (!relaySet && typeof idOrFilter === \"string\") {\n const relays = relaysFromBech32(idOrFilter);\n if (relays.length > 0) {\n relaySet = new NDKRelaySet(new Set<NDKRelay>(relays), this);\n // Make sure we have connected relays in this set", "score": 0.8826170563697815 }, { "filename": "src/index.ts", "retrieved_chunk": " * @returns NDKSubscription\n */\n public subscribe(\n filters: NDKFilter | NDKFilter[],\n opts?: NDKSubscriptionOptions,\n relaySet?: NDKRelaySet,\n autoStart = true\n ): NDKSubscription {\n const subscription = new NDKSubscription(this, filters, opts, relaySet);\n // Signal to the relays that they are explicitly being used", "score": 0.8763694763183594 }, { "filename": "src/index.ts", "retrieved_chunk": " }\n return new Promise((resolve) => {\n const s = this.subscribe(\n filter,\n { ...(opts || {}), closeOnEose: true },\n relaySet,\n false\n );\n s.on(\"event\", (event) => {\n event.ndk = this;", "score": 0.8733583092689514 } ]
typescript
: NDKRelaySet, subId?: string ) {
import EventEmitter from "eventemitter3"; import { Filter as NostrFilter, matchFilter, Sub, nip19 } from "nostr-tools"; import { EventPointer } from "nostr-tools/lib/nip19"; import NDKEvent, { NDKEventId } from "../events/index.js"; import NDK from "../index.js"; import { NDKRelay } from "../relay"; import { calculateRelaySetFromFilter } from "../relay/sets/calculate"; import { NDKRelaySet } from "../relay/sets/index.js"; import { queryFullyFilled } from "./utils.js"; export type NDKFilter = NostrFilter; export enum NDKSubscriptionCacheUsage { // Only use cache, don't subscribe to relays ONLY_CACHE = "ONLY_CACHE", // Use cache, if no matches, use relays CACHE_FIRST = "CACHE_FIRST", // Use cache in addition to relays PARALLEL = "PARALLEL", // Skip cache, don't query it ONLY_RELAY = "ONLY_RELAY", } export interface NDKSubscriptionOptions { closeOnEose: boolean; cacheUsage?: NDKSubscriptionCacheUsage; /** * Groupable subscriptions are created with a slight time * delayed to allow similar filters to be grouped together. */ groupable?: boolean; /** * The delay to use when grouping subscriptions, specified in milliseconds. * @default 100 */ groupableDelay?: number; /** * The subscription ID to use for the subscription. */ subId?: string; } /** * Default subscription options. */ export const defaultOpts: NDKSubscriptionOptions = { closeOnEose: true, cacheUsage: NDKSubscriptionCacheUsage.CACHE_FIRST, groupable: true, groupableDelay: 100, }; /** * Represents a subscription to an NDK event stream. * * @event NDKSubscription#event * Emitted when an event is received by the subscription. * @param {NDKEvent} event - The event received by the subscription. * @param {NDKRelay} relay - The relay that received the event. * @param {NDKSubscription} subscription - The subscription that received the event. * * @event NDKSubscription#event:dup * Emitted when a duplicate event is received by the subscription. * @param {NDKEvent} event - The duplicate event received by the subscription. * @param {NDKRelay} relay - The relay that received the event. * @param {number} timeSinceFirstSeen - The time elapsed since the first time the event was seen. * @param {NDKSubscription} subscription - The subscription that received the event. * * @event NDKSubscription#eose - Emitted when all relays have reached the end of the event stream. * @param {NDKSubscription} subscription - The subscription that received EOSE. * * @event NDKSubscription#close - Emitted when the subscription is closed. * @param {NDKSubscription} subscription - The subscription that was closed. */ export class NDKSubscription extends EventEmitter { readonly subId: string; readonly filters: NDKFilter[]; readonly opts: NDKSubscriptionOptions; public relaySet?: NDKRelaySet; public ndk: NDK; public relaySubscriptions: Map<NDKRelay, Sub>; private debug: debug.Debugger; /** * Events that have been seen by the subscription, with the time they were first seen. */
public eventFirstSeen = new Map<NDKEventId, number>();
/** * Relays that have sent an EOSE. */ public eosesSeen = new Set<NDKRelay>(); /** * Events that have been seen by the subscription per relay. */ public eventsPerRelay: Map<NDKRelay, Set<NDKEventId>> = new Map(); public constructor( ndk: NDK, filters: NDKFilter | NDKFilter[], opts?: NDKSubscriptionOptions, relaySet?: NDKRelaySet, subId?: string ) { super(); this.ndk = ndk; this.opts = { ...defaultOpts, ...(opts || {}) }; this.filters = filters instanceof Array ? filters : [filters]; this.subId = subId || opts?.subId || generateFilterId(this.filters[0]); this.relaySet = relaySet; this.relaySubscriptions = new Map<NDKRelay, Sub>(); this.debug = ndk.debug.extend(`subscription:${this.subId}`); // validate that the caller is not expecting a persistent // subscription while using an option that will only hit the cache if ( this.opts.cacheUsage === NDKSubscriptionCacheUsage.ONLY_CACHE && !this.opts.closeOnEose ) { throw new Error( "Cannot use cache-only options with a persistent subscription" ); } } /** * Provides access to the first filter of the subscription for * backwards compatibility. */ get filter(): NDKFilter { return this.filters[0]; } /** * Calculates the groupable ID for this subscription. * * @returns The groupable ID, or null if the subscription is not groupable. */ public groupableId(): string | null { if (!this.opts?.groupable || this.filters.length > 1) { return null; } const filter = this.filters[0]; // Check if there is a kind and no time-based filters const noTimeConstraints = !filter.since && !filter.until; const noLimit = !filter.limit; if (noTimeConstraints && noLimit) { let id = filter.kinds ? filter.kinds.join(",") : ""; const keys = Object.keys(filter || {}) .sort() .join("-"); id += `-${keys}`; return id; } return null; } private shouldQueryCache(): boolean { return this.opts?.cacheUsage !== NDKSubscriptionCacheUsage.ONLY_RELAY; } private shouldQueryRelays(): boolean { return this.opts?.cacheUsage !== NDKSubscriptionCacheUsage.ONLY_CACHE; } private shouldWaitForCache(): boolean { return ( // Must want to close on EOSE; subscriptions // that want to receive further updates must // always hit the relay this.opts.closeOnEose && // Cache adapter must claim to be fast !!this.ndk.cacheAdapter?.locking && // If explicitly told to run in parallel, then // we should not wait for the cache this.opts.cacheUsage !== NDKSubscriptionCacheUsage.PARALLEL ); } /** * Start the subscription. This is the main method that should be called * after creating a subscription. */ public async start(): Promise<void> { let cachePromise; if (this.shouldQueryCache()) { cachePromise = this.startWithCache(); if (this.shouldWaitForCache()) { await cachePromise; // if the cache has a hit, return early if (queryFullyFilled(this)) { this.emit("eose", this); return; } } } if (this.shouldQueryRelays()) { this.startWithRelaySet(); } else { this.emit("eose", this); } return; } public stop(): void { this.relaySubscriptions.forEach((sub) => sub.unsub()); this.relaySubscriptions.clear(); this.emit("close", this); } private async startWithCache(): Promise<void> { if (this.ndk.cacheAdapter?.query) { const promise = this.ndk.cacheAdapter.query(this); if (this.ndk.cacheAdapter.locking) { await promise; } } } private startWithRelaySet(): void { if (!this.relaySet) { this.relaySet = calculateRelaySetFromFilter( this.ndk, this.filters[0] ); } if (this.relaySet) { this.relaySet.subscribe(this); } } // EVENT handling /** * Called when an event is received from a relay or the cache * @param event * @param relay * @param fromCache Whether the event was received from the cache */ public eventReceived( event: NDKEvent, relay: NDKRelay | undefined, fromCache = false ) { if (relay) event.relay = relay; if (!relay) relay = event.relay; if (!fromCache && relay) { // track the event per relay let events = this.eventsPerRelay.get(relay); if (!events) { events = new Set(); this.eventsPerRelay.set(relay, events); } events.add(event.id); // mark the event as seen const eventAlreadySeen = this.eventFirstSeen.has(event.id); if (eventAlreadySeen) { const timeSinceFirstSeen = Date.now() - (this.eventFirstSeen.get(event.id) || 0); relay.scoreSlowerEvent(timeSinceFirstSeen); this.emit("event:dup", event, relay, timeSinceFirstSeen, this); return; } if (this.ndk.cacheAdapter) { this.ndk.cacheAdapter.setEvent(event, this.filters[0], relay); } this.eventFirstSeen.set(`${event.id}`, Date.now()); } else { this.eventFirstSeen.set(`${event.id}`, 0); } this.emit("event", event, relay, this); } // EOSE handling private eoseTimeout: ReturnType<typeof setTimeout> | undefined; public eoseReceived(relay: NDKRelay): void { if (this.opts?.closeOnEose) { this.relaySubscriptions.get(relay)?.unsub(); this.relaySubscriptions.delete(relay); // if this was the last relay that needed to EOSE, emit that this subscription is closed if (this.relaySubscriptions.size === 0) { this.emit("close", this); } } this.eosesSeen.add(relay); const hasSeenAllEoses = this.eosesSeen.size === this.relaySet?.size(); if (hasSeenAllEoses) { this.emit("eose"); } else { if (this.eoseTimeout) { clearTimeout(this.eoseTimeout); } this.eoseTimeout = setTimeout(() => { this.emit("eose"); }, 500); } } } /** * Represents a group of subscriptions. * * Events emitted from the group will be emitted from each subscription. */ export class NDKSubscriptionGroup extends NDKSubscription { private subscriptions: NDKSubscription[]; constructor(ndk: NDK, subscriptions: NDKSubscription[]) { const debug = ndk.debug.extend("subscription-group"); const filters = mergeFilters(subscriptions.map((s) => s.filters[0])); super( ndk, filters, subscriptions[0].opts, // TODO: This should be merged subscriptions[0].relaySet // TODO: This should be merged ); this.subscriptions = subscriptions; debug("merged filters", { count: subscriptions.length, mergedFilters: this.filters[0], }); // forward events to the matching subscriptions this.on("event", this.forwardEvent); this.on("event:dup", this.forwardEventDup); this.on("eose", this.forwardEose); this.on("close", this.forwardClose); } private isEventForSubscription( event: NDKEvent, subscription: NDKSubscription ): boolean { const { filters } = subscription; if (!filters) return false; return matchFilter(filters[0], event.rawEvent() as any); // check if there is a filter whose key begins with '#'; if there is, check if the event has a tag with the same key on the first position // of the tags array of arrays and the same value in the second position // for (const key in filter) { // if (key === 'kinds' && filter.kinds!.includes(event.kind!)) return false; // else if (key === 'authors' && filter.authors!.includes(event.pubkey)) return false; // else if (key.startsWith('#')) { // const tagKey = key.slice(1); // const tagValue = filter[key]; // if (event.tags) { // for (const tag of event.tags) { // if (tag[0] === tagKey && tag[1] === tagValue) { // return false; // } // } // } // } // return true; } private forwardEvent(event: NDKEvent, relay: NDKRelay) { for (const subscription of this.subscriptions) { if (!this.isEventForSubscription(event, subscription)) { continue; } subscription.emit("event", event, relay, subscription); } } private forwardEventDup( event: NDKEvent, relay: NDKRelay, timeSinceFirstSeen: number ) { for (const subscription of this.subscriptions) { if (!this.isEventForSubscription(event, subscription)) { continue; } subscription.emit( "event:dup", event, relay, timeSinceFirstSeen, subscription ); } } private forwardEose() { for (const subscription of this.subscriptions) { subscription.emit("eose", subscription); } } private forwardClose() { for (const subscription of this.subscriptions) { subscription.emit("close", subscription); } } } /** * Go through all the passed filters, which should be * relatively similar, and merge them. */ export function mergeFilters(filters: NDKFilter[]): NDKFilter { const result: any = {}; filters.forEach((filter) => { Object.entries(filter).forEach(([key, value]) => { if (Array.isArray(value)) { if (result[key] === undefined) { result[key] = [...value]; } else { result[key] = Array.from( new Set([...result[key], ...value]) ); } } else { result[key] = value; } }); }); return result as NDKFilter; } /** * Creates a valid nostr filter from an event id or a NIP-19 bech32. */ export function filterFromId(id: string): NDKFilter { let decoded; try { decoded = nip19.decode(id); switch (decoded.type) { case "nevent": return { ids: [decoded.data.id] }; case "note": return { ids: [decoded.data] }; case "naddr": return { authors: [decoded.data.pubkey], "#d": [decoded.data.identifier], kinds: [decoded.data.kind], }; } } catch (e) {} return { ids: [id] }; } /** * Returns the specified relays from a NIP-19 bech32. * * @param bech32 The NIP-19 bech32. */ export function relaysFromBech32(bech32: string): NDKRelay[] { try { const decoded = nip19.decode(bech32); if (["naddr", "nevent"].includes(decoded?.type)) { const data = decoded.data as unknown as EventPointer; if (data?.relays) { return data.relays.map((r: string) => new NDKRelay(r)); } } } catch (e) { /* empty */ } return []; } /** * Generates a random filter id, based on the filter keys. */ function generateFilterId(filter: NDKFilter) { const keys = Object.keys(filter) || []; const subId = []; for (const key of keys) { if (key === "kinds") { const v = [key, filter.kinds!.join(",")]; subId.push(v.join(":")); } else { subId.push(key); } } subId.push(Math.floor(Math.random() * 999999999).toString()); return subId.join("-"); }
src/subscription/index.ts
nostr-dev-kit-ndk-ece64e1
[ { "filename": "src/index.ts", "retrieved_chunk": " public pool: NDKPool;\n public signer?: NDKSigner;\n public cacheAdapter?: NDKCacheAdapter;\n public debug: debug.Debugger;\n public devWriteRelaySet?: NDKRelaySet;\n public delayedSubscriptions: Map<string, NDKSubscription[]>;\n public constructor(opts: NDKConstructorParams = {}) {\n super();\n this.debug = opts.debug || debug(\"ndk\");\n this.pool = new NDKPool(opts.explicitRelayUrls || [], this);", "score": 0.8920858502388 }, { "filename": "src/index.ts", "retrieved_chunk": " */\n public async fetchEvents(\n filters: NDKFilter | NDKFilter[],\n opts?: NDKSubscriptionOptions,\n relaySet?: NDKRelaySet\n ): Promise<Set<NDKEvent>> {\n return new Promise((resolve) => {\n const events: Map<string, NDKEvent> = new Map();\n const relaySetSubscription = this.subscribe(\n filters,", "score": 0.8849828243255615 }, { "filename": "src/index.ts", "retrieved_chunk": " opts?: NDKSubscriptionOptions,\n relaySet?: NDKRelaySet\n ): Promise<NDKEvent | null> {\n let filter: NDKFilter;\n // if no relayset has been provided, try to get one from the event id\n if (!relaySet && typeof idOrFilter === \"string\") {\n const relays = relaysFromBech32(idOrFilter);\n if (relays.length > 0) {\n relaySet = new NDKRelaySet(new Set<NDKRelay>(relays), this);\n // Make sure we have connected relays in this set", "score": 0.8793155550956726 }, { "filename": "src/cache/index.ts", "retrieved_chunk": " query(subscription: NDKSubscription): Promise<void>;\n setEvent(\n event: NDKEvent,\n filter: NDKFilter,\n relay?: NDKRelay\n ): Promise<void>;\n}", "score": 0.8783679008483887 }, { "filename": "src/index.ts", "retrieved_chunk": " * @returns NDKSubscription\n */\n public subscribe(\n filters: NDKFilter | NDKFilter[],\n opts?: NDKSubscriptionOptions,\n relaySet?: NDKRelaySet,\n autoStart = true\n ): NDKSubscription {\n const subscription = new NDKSubscription(this, filters, opts, relaySet);\n // Signal to the relays that they are explicitly being used", "score": 0.8758276700973511 } ]
typescript
public eventFirstSeen = new Map<NDKEventId, number>();
import EventEmitter from "eventemitter3"; import { Filter as NostrFilter, matchFilter, Sub, nip19 } from "nostr-tools"; import { EventPointer } from "nostr-tools/lib/nip19"; import NDKEvent, { NDKEventId } from "../events/index.js"; import NDK from "../index.js"; import { NDKRelay } from "../relay"; import { calculateRelaySetFromFilter } from "../relay/sets/calculate"; import { NDKRelaySet } from "../relay/sets/index.js"; import { queryFullyFilled } from "./utils.js"; export type NDKFilter = NostrFilter; export enum NDKSubscriptionCacheUsage { // Only use cache, don't subscribe to relays ONLY_CACHE = "ONLY_CACHE", // Use cache, if no matches, use relays CACHE_FIRST = "CACHE_FIRST", // Use cache in addition to relays PARALLEL = "PARALLEL", // Skip cache, don't query it ONLY_RELAY = "ONLY_RELAY", } export interface NDKSubscriptionOptions { closeOnEose: boolean; cacheUsage?: NDKSubscriptionCacheUsage; /** * Groupable subscriptions are created with a slight time * delayed to allow similar filters to be grouped together. */ groupable?: boolean; /** * The delay to use when grouping subscriptions, specified in milliseconds. * @default 100 */ groupableDelay?: number; /** * The subscription ID to use for the subscription. */ subId?: string; } /** * Default subscription options. */ export const defaultOpts: NDKSubscriptionOptions = { closeOnEose: true, cacheUsage: NDKSubscriptionCacheUsage.CACHE_FIRST, groupable: true, groupableDelay: 100, }; /** * Represents a subscription to an NDK event stream. * * @event NDKSubscription#event * Emitted when an event is received by the subscription. * @param {NDKEvent} event - The event received by the subscription. * @param {NDKRelay} relay - The relay that received the event. * @param {NDKSubscription} subscription - The subscription that received the event. * * @event NDKSubscription#event:dup * Emitted when a duplicate event is received by the subscription. * @param {NDKEvent} event - The duplicate event received by the subscription. * @param {NDKRelay} relay - The relay that received the event. * @param {number} timeSinceFirstSeen - The time elapsed since the first time the event was seen. * @param {NDKSubscription} subscription - The subscription that received the event. * * @event NDKSubscription#eose - Emitted when all relays have reached the end of the event stream. * @param {NDKSubscription} subscription - The subscription that received EOSE. * * @event NDKSubscription#close - Emitted when the subscription is closed. * @param {NDKSubscription} subscription - The subscription that was closed. */ export class NDKSubscription extends EventEmitter { readonly subId: string; readonly filters: NDKFilter[]; readonly opts: NDKSubscriptionOptions; public relaySet?: NDKRelaySet; public ndk: NDK; public relaySubscriptions: Map<NDKRelay, Sub>; private debug: debug.Debugger; /** * Events that have been seen by the subscription, with the time they were first seen. */ public eventFirstSeen = new Map<NDKEventId, number>(); /** * Relays that have sent an EOSE. */ public eosesSeen = new Set<NDKRelay>(); /** * Events that have been seen by the subscription per relay. */ public eventsPerRelay: Map<NDKRelay, Set<NDKEventId>> = new Map(); public constructor( ndk: NDK, filters: NDKFilter | NDKFilter[], opts?: NDKSubscriptionOptions, relaySet?: NDKRelaySet, subId?: string ) { super(); this.ndk = ndk; this.opts = { ...defaultOpts, ...(opts || {}) }; this.filters = filters instanceof Array ? filters : [filters]; this.subId = subId || opts?.subId || generateFilterId(this.filters[0]); this.relaySet = relaySet; this.relaySubscriptions = new Map<NDKRelay, Sub>(); this.debug = ndk.debug.extend(`subscription:${this.subId}`); // validate that the caller is not expecting a persistent // subscription while using an option that will only hit the cache if ( this.opts.cacheUsage === NDKSubscriptionCacheUsage.ONLY_CACHE && !this.opts.closeOnEose ) { throw new Error( "Cannot use cache-only options with a persistent subscription" ); } } /** * Provides access to the first filter of the subscription for * backwards compatibility. */ get filter(): NDKFilter { return this.filters[0]; } /** * Calculates the groupable ID for this subscription. * * @returns The groupable ID, or null if the subscription is not groupable. */ public groupableId(): string | null { if (!this.opts?.groupable || this.filters.length > 1) { return null; } const filter = this.filters[0]; // Check if there is a kind and no time-based filters const noTimeConstraints = !filter.since && !filter.until; const noLimit = !filter.limit; if (noTimeConstraints && noLimit) { let id = filter.kinds ? filter.kinds.join(",") : ""; const keys = Object.keys(filter || {}) .sort() .join("-"); id += `-${keys}`; return id; } return null; } private shouldQueryCache(): boolean { return this.opts?.cacheUsage !== NDKSubscriptionCacheUsage.ONLY_RELAY; } private shouldQueryRelays(): boolean { return this.opts?.cacheUsage !== NDKSubscriptionCacheUsage.ONLY_CACHE; } private shouldWaitForCache(): boolean { return ( // Must want to close on EOSE; subscriptions // that want to receive further updates must // always hit the relay this.opts.closeOnEose && // Cache adapter must claim to be fast !!this.ndk.cacheAdapter?.locking && // If explicitly told to run in parallel, then // we should not wait for the cache this.opts.cacheUsage !== NDKSubscriptionCacheUsage.PARALLEL ); } /** * Start the subscription. This is the main method that should be called * after creating a subscription. */ public async start(): Promise<void> { let cachePromise; if (this.shouldQueryCache()) { cachePromise = this.startWithCache(); if (this.shouldWaitForCache()) { await cachePromise; // if the cache has a hit, return early if (
queryFullyFilled(this)) {
this.emit("eose", this); return; } } } if (this.shouldQueryRelays()) { this.startWithRelaySet(); } else { this.emit("eose", this); } return; } public stop(): void { this.relaySubscriptions.forEach((sub) => sub.unsub()); this.relaySubscriptions.clear(); this.emit("close", this); } private async startWithCache(): Promise<void> { if (this.ndk.cacheAdapter?.query) { const promise = this.ndk.cacheAdapter.query(this); if (this.ndk.cacheAdapter.locking) { await promise; } } } private startWithRelaySet(): void { if (!this.relaySet) { this.relaySet = calculateRelaySetFromFilter( this.ndk, this.filters[0] ); } if (this.relaySet) { this.relaySet.subscribe(this); } } // EVENT handling /** * Called when an event is received from a relay or the cache * @param event * @param relay * @param fromCache Whether the event was received from the cache */ public eventReceived( event: NDKEvent, relay: NDKRelay | undefined, fromCache = false ) { if (relay) event.relay = relay; if (!relay) relay = event.relay; if (!fromCache && relay) { // track the event per relay let events = this.eventsPerRelay.get(relay); if (!events) { events = new Set(); this.eventsPerRelay.set(relay, events); } events.add(event.id); // mark the event as seen const eventAlreadySeen = this.eventFirstSeen.has(event.id); if (eventAlreadySeen) { const timeSinceFirstSeen = Date.now() - (this.eventFirstSeen.get(event.id) || 0); relay.scoreSlowerEvent(timeSinceFirstSeen); this.emit("event:dup", event, relay, timeSinceFirstSeen, this); return; } if (this.ndk.cacheAdapter) { this.ndk.cacheAdapter.setEvent(event, this.filters[0], relay); } this.eventFirstSeen.set(`${event.id}`, Date.now()); } else { this.eventFirstSeen.set(`${event.id}`, 0); } this.emit("event", event, relay, this); } // EOSE handling private eoseTimeout: ReturnType<typeof setTimeout> | undefined; public eoseReceived(relay: NDKRelay): void { if (this.opts?.closeOnEose) { this.relaySubscriptions.get(relay)?.unsub(); this.relaySubscriptions.delete(relay); // if this was the last relay that needed to EOSE, emit that this subscription is closed if (this.relaySubscriptions.size === 0) { this.emit("close", this); } } this.eosesSeen.add(relay); const hasSeenAllEoses = this.eosesSeen.size === this.relaySet?.size(); if (hasSeenAllEoses) { this.emit("eose"); } else { if (this.eoseTimeout) { clearTimeout(this.eoseTimeout); } this.eoseTimeout = setTimeout(() => { this.emit("eose"); }, 500); } } } /** * Represents a group of subscriptions. * * Events emitted from the group will be emitted from each subscription. */ export class NDKSubscriptionGroup extends NDKSubscription { private subscriptions: NDKSubscription[]; constructor(ndk: NDK, subscriptions: NDKSubscription[]) { const debug = ndk.debug.extend("subscription-group"); const filters = mergeFilters(subscriptions.map((s) => s.filters[0])); super( ndk, filters, subscriptions[0].opts, // TODO: This should be merged subscriptions[0].relaySet // TODO: This should be merged ); this.subscriptions = subscriptions; debug("merged filters", { count: subscriptions.length, mergedFilters: this.filters[0], }); // forward events to the matching subscriptions this.on("event", this.forwardEvent); this.on("event:dup", this.forwardEventDup); this.on("eose", this.forwardEose); this.on("close", this.forwardClose); } private isEventForSubscription( event: NDKEvent, subscription: NDKSubscription ): boolean { const { filters } = subscription; if (!filters) return false; return matchFilter(filters[0], event.rawEvent() as any); // check if there is a filter whose key begins with '#'; if there is, check if the event has a tag with the same key on the first position // of the tags array of arrays and the same value in the second position // for (const key in filter) { // if (key === 'kinds' && filter.kinds!.includes(event.kind!)) return false; // else if (key === 'authors' && filter.authors!.includes(event.pubkey)) return false; // else if (key.startsWith('#')) { // const tagKey = key.slice(1); // const tagValue = filter[key]; // if (event.tags) { // for (const tag of event.tags) { // if (tag[0] === tagKey && tag[1] === tagValue) { // return false; // } // } // } // } // return true; } private forwardEvent(event: NDKEvent, relay: NDKRelay) { for (const subscription of this.subscriptions) { if (!this.isEventForSubscription(event, subscription)) { continue; } subscription.emit("event", event, relay, subscription); } } private forwardEventDup( event: NDKEvent, relay: NDKRelay, timeSinceFirstSeen: number ) { for (const subscription of this.subscriptions) { if (!this.isEventForSubscription(event, subscription)) { continue; } subscription.emit( "event:dup", event, relay, timeSinceFirstSeen, subscription ); } } private forwardEose() { for (const subscription of this.subscriptions) { subscription.emit("eose", subscription); } } private forwardClose() { for (const subscription of this.subscriptions) { subscription.emit("close", subscription); } } } /** * Go through all the passed filters, which should be * relatively similar, and merge them. */ export function mergeFilters(filters: NDKFilter[]): NDKFilter { const result: any = {}; filters.forEach((filter) => { Object.entries(filter).forEach(([key, value]) => { if (Array.isArray(value)) { if (result[key] === undefined) { result[key] = [...value]; } else { result[key] = Array.from( new Set([...result[key], ...value]) ); } } else { result[key] = value; } }); }); return result as NDKFilter; } /** * Creates a valid nostr filter from an event id or a NIP-19 bech32. */ export function filterFromId(id: string): NDKFilter { let decoded; try { decoded = nip19.decode(id); switch (decoded.type) { case "nevent": return { ids: [decoded.data.id] }; case "note": return { ids: [decoded.data] }; case "naddr": return { authors: [decoded.data.pubkey], "#d": [decoded.data.identifier], kinds: [decoded.data.kind], }; } } catch (e) {} return { ids: [id] }; } /** * Returns the specified relays from a NIP-19 bech32. * * @param bech32 The NIP-19 bech32. */ export function relaysFromBech32(bech32: string): NDKRelay[] { try { const decoded = nip19.decode(bech32); if (["naddr", "nevent"].includes(decoded?.type)) { const data = decoded.data as unknown as EventPointer; if (data?.relays) { return data.relays.map((r: string) => new NDKRelay(r)); } } } catch (e) { /* empty */ } return []; } /** * Generates a random filter id, based on the filter keys. */ function generateFilterId(filter: NDKFilter) { const keys = Object.keys(filter) || []; const subId = []; for (const key of keys) { if (key === "kinds") { const v = [key, filter.kinds!.join(",")]; subId.push(v.join(":")); } else { subId.push(key); } } subId.push(Math.floor(Math.random() * 999999999).toString()); return subId.join("-"); }
src/subscription/index.ts
nostr-dev-kit-ndk-ece64e1
[ { "filename": "src/relay/index.ts", "retrieved_chunk": " public async connect(): Promise<void> {\n try {\n this.updateConnectionStats.attempt();\n this._status = NDKRelayStatus.CONNECTING;\n await this.relay.connect();\n } catch (e) {\n this.debug(\"Failed to connect\", e);\n this._status = NDKRelayStatus.DISCONNECTED;\n throw e;\n }", "score": 0.7894368171691895 }, { "filename": "src/index.ts", "retrieved_chunk": " relaySetSubscription.start();\n });\n }\n /**\n * Ensures that a signer is available to sign an event.\n */\n public async assertSigner() {\n if (!this.signer) {\n this.emit(\"signerRequired\");\n throw new Error(\"Signer required\");", "score": 0.7787942886352539 }, { "filename": "src/index.ts", "retrieved_chunk": " resolve(event);\n });\n s.on(\"eose\", () => {\n resolve(null);\n });\n s.start();\n });\n }\n /**\n * Fetch events", "score": 0.7781466245651245 }, { "filename": "src/user/index.ts", "retrieved_chunk": " this.ndk.cacheAdapter && // and we have a cache\n this.ndk.cacheAdapter.locking // and the cache identifies itself as fast 😂\n ) {\n setMetadataEvents = await this.ndk.fetchEvents(\n {\n kinds: [0],\n authors: [this.hexpubkey()],\n },\n {\n cacheUsage: NDKSubscriptionCacheUsage.ONLY_CACHE,", "score": 0.7753006219863892 }, { "filename": "src/signers/nip46/backend/index.ts", "retrieved_chunk": " this.debug = ndk.debug.extend(\"nip46:backend\");\n this.rpc = new NDKNostrRpc(ndk, this.signer, this.debug);\n this.permitCallback = permitCallback;\n }\n /**\n * This method starts the backend, which will start listening for incoming\n * requests.\n */\n public async start() {\n this.localUser = await this.signer.user();", "score": 0.7744354605674744 } ]
typescript
queryFullyFilled(this)) {
import EventEmitter from "eventemitter3"; import { Filter as NostrFilter, matchFilter, Sub, nip19 } from "nostr-tools"; import { EventPointer } from "nostr-tools/lib/nip19"; import NDKEvent, { NDKEventId } from "../events/index.js"; import NDK from "../index.js"; import { NDKRelay } from "../relay"; import { calculateRelaySetFromFilter } from "../relay/sets/calculate"; import { NDKRelaySet } from "../relay/sets/index.js"; import { queryFullyFilled } from "./utils.js"; export type NDKFilter = NostrFilter; export enum NDKSubscriptionCacheUsage { // Only use cache, don't subscribe to relays ONLY_CACHE = "ONLY_CACHE", // Use cache, if no matches, use relays CACHE_FIRST = "CACHE_FIRST", // Use cache in addition to relays PARALLEL = "PARALLEL", // Skip cache, don't query it ONLY_RELAY = "ONLY_RELAY", } export interface NDKSubscriptionOptions { closeOnEose: boolean; cacheUsage?: NDKSubscriptionCacheUsage; /** * Groupable subscriptions are created with a slight time * delayed to allow similar filters to be grouped together. */ groupable?: boolean; /** * The delay to use when grouping subscriptions, specified in milliseconds. * @default 100 */ groupableDelay?: number; /** * The subscription ID to use for the subscription. */ subId?: string; } /** * Default subscription options. */ export const defaultOpts: NDKSubscriptionOptions = { closeOnEose: true, cacheUsage: NDKSubscriptionCacheUsage.CACHE_FIRST, groupable: true, groupableDelay: 100, }; /** * Represents a subscription to an NDK event stream. * * @event NDKSubscription#event * Emitted when an event is received by the subscription. * @param {NDKEvent} event - The event received by the subscription. * @param {NDKRelay} relay - The relay that received the event. * @param {NDKSubscription} subscription - The subscription that received the event. * * @event NDKSubscription#event:dup * Emitted when a duplicate event is received by the subscription. * @param {NDKEvent} event - The duplicate event received by the subscription. * @param {NDKRelay} relay - The relay that received the event. * @param {number} timeSinceFirstSeen - The time elapsed since the first time the event was seen. * @param {NDKSubscription} subscription - The subscription that received the event. * * @event NDKSubscription#eose - Emitted when all relays have reached the end of the event stream. * @param {NDKSubscription} subscription - The subscription that received EOSE. * * @event NDKSubscription#close - Emitted when the subscription is closed. * @param {NDKSubscription} subscription - The subscription that was closed. */ export class NDKSubscription extends EventEmitter { readonly subId: string; readonly filters: NDKFilter[]; readonly opts: NDKSubscriptionOptions; public relaySet?: NDKRelaySet; public ndk: NDK; public relaySubscriptions: Map<NDKRelay, Sub>; private debug: debug.Debugger; /** * Events that have been seen by the subscription, with the time they were first seen. */ public eventFirstSeen = new Map<NDKEventId, number>(); /** * Relays that have sent an EOSE. */ public eosesSeen = new Set<NDKRelay>(); /** * Events that have been seen by the subscription per relay. */ public eventsPerRelay: Map<NDKRelay, Set<NDKEventId>> = new Map(); public constructor( ndk: NDK, filters: NDKFilter | NDKFilter[], opts?: NDKSubscriptionOptions, relaySet?: NDKRelaySet, subId?: string ) { super(); this.ndk = ndk; this.opts = { ...defaultOpts, ...(opts || {}) }; this.filters = filters instanceof Array ? filters : [filters]; this.subId = subId || opts?.subId || generateFilterId(this.filters[0]); this.relaySet = relaySet; this.relaySubscriptions = new Map<NDKRelay, Sub>(); this.debug = ndk.debug.extend(`subscription:${this.subId}`); // validate that the caller is not expecting a persistent // subscription while using an option that will only hit the cache if ( this.opts.cacheUsage === NDKSubscriptionCacheUsage.ONLY_CACHE && !this.opts.closeOnEose ) { throw new Error( "Cannot use cache-only options with a persistent subscription" ); } } /** * Provides access to the first filter of the subscription for * backwards compatibility. */ get filter(): NDKFilter { return this.filters[0]; } /** * Calculates the groupable ID for this subscription. * * @returns The groupable ID, or null if the subscription is not groupable. */ public groupableId(): string | null { if (!this.opts?.groupable || this.filters.length > 1) { return null; } const filter = this.filters[0]; // Check if there is a kind and no time-based filters const noTimeConstraints = !filter.since && !filter.until; const noLimit = !filter.limit; if (noTimeConstraints && noLimit) { let id = filter.kinds ? filter.kinds.join(",") : ""; const keys = Object.keys(filter || {}) .sort() .join("-"); id += `-${keys}`; return id; } return null; } private shouldQueryCache(): boolean { return this.opts?.cacheUsage !== NDKSubscriptionCacheUsage.ONLY_RELAY; } private shouldQueryRelays(): boolean { return this.opts?.cacheUsage !== NDKSubscriptionCacheUsage.ONLY_CACHE; } private shouldWaitForCache(): boolean { return ( // Must want to close on EOSE; subscriptions // that want to receive further updates must // always hit the relay this.opts.closeOnEose && // Cache adapter must claim to be fast !!this.ndk.cacheAdapter?.locking && // If explicitly told to run in parallel, then // we should not wait for the cache this.opts.cacheUsage !== NDKSubscriptionCacheUsage.PARALLEL ); } /** * Start the subscription. This is the main method that should be called * after creating a subscription. */ public async start(): Promise<void> { let cachePromise; if (this.shouldQueryCache()) { cachePromise = this.startWithCache(); if (this.shouldWaitForCache()) { await cachePromise; // if the cache has a hit, return early if (queryFullyFilled(this)) { this.emit("eose", this); return; } } } if (this.shouldQueryRelays()) { this.startWithRelaySet(); } else { this.emit("eose", this); } return; } public stop(): void { this.relaySubscriptions.forEach((sub) => sub.unsub()); this.relaySubscriptions.clear(); this.emit("close", this); } private async startWithCache(): Promise<void> { if (this.ndk.cacheAdapter?.query) { const promise = this.ndk.cacheAdapter.query(this); if (this.ndk.cacheAdapter.locking) { await promise; } } } private startWithRelaySet(): void { if (!this.relaySet) { this.relaySet = calculateRelaySetFromFilter( this.ndk, this.filters[0] ); } if (this.relaySet) { this.relaySet.subscribe(this); } } // EVENT handling /** * Called when an event is received from a relay or the cache * @param event * @param relay * @param fromCache Whether the event was received from the cache */ public eventReceived(
event: NDKEvent, relay: NDKRelay | undefined, fromCache = false ) {
if (relay) event.relay = relay; if (!relay) relay = event.relay; if (!fromCache && relay) { // track the event per relay let events = this.eventsPerRelay.get(relay); if (!events) { events = new Set(); this.eventsPerRelay.set(relay, events); } events.add(event.id); // mark the event as seen const eventAlreadySeen = this.eventFirstSeen.has(event.id); if (eventAlreadySeen) { const timeSinceFirstSeen = Date.now() - (this.eventFirstSeen.get(event.id) || 0); relay.scoreSlowerEvent(timeSinceFirstSeen); this.emit("event:dup", event, relay, timeSinceFirstSeen, this); return; } if (this.ndk.cacheAdapter) { this.ndk.cacheAdapter.setEvent(event, this.filters[0], relay); } this.eventFirstSeen.set(`${event.id}`, Date.now()); } else { this.eventFirstSeen.set(`${event.id}`, 0); } this.emit("event", event, relay, this); } // EOSE handling private eoseTimeout: ReturnType<typeof setTimeout> | undefined; public eoseReceived(relay: NDKRelay): void { if (this.opts?.closeOnEose) { this.relaySubscriptions.get(relay)?.unsub(); this.relaySubscriptions.delete(relay); // if this was the last relay that needed to EOSE, emit that this subscription is closed if (this.relaySubscriptions.size === 0) { this.emit("close", this); } } this.eosesSeen.add(relay); const hasSeenAllEoses = this.eosesSeen.size === this.relaySet?.size(); if (hasSeenAllEoses) { this.emit("eose"); } else { if (this.eoseTimeout) { clearTimeout(this.eoseTimeout); } this.eoseTimeout = setTimeout(() => { this.emit("eose"); }, 500); } } } /** * Represents a group of subscriptions. * * Events emitted from the group will be emitted from each subscription. */ export class NDKSubscriptionGroup extends NDKSubscription { private subscriptions: NDKSubscription[]; constructor(ndk: NDK, subscriptions: NDKSubscription[]) { const debug = ndk.debug.extend("subscription-group"); const filters = mergeFilters(subscriptions.map((s) => s.filters[0])); super( ndk, filters, subscriptions[0].opts, // TODO: This should be merged subscriptions[0].relaySet // TODO: This should be merged ); this.subscriptions = subscriptions; debug("merged filters", { count: subscriptions.length, mergedFilters: this.filters[0], }); // forward events to the matching subscriptions this.on("event", this.forwardEvent); this.on("event:dup", this.forwardEventDup); this.on("eose", this.forwardEose); this.on("close", this.forwardClose); } private isEventForSubscription( event: NDKEvent, subscription: NDKSubscription ): boolean { const { filters } = subscription; if (!filters) return false; return matchFilter(filters[0], event.rawEvent() as any); // check if there is a filter whose key begins with '#'; if there is, check if the event has a tag with the same key on the first position // of the tags array of arrays and the same value in the second position // for (const key in filter) { // if (key === 'kinds' && filter.kinds!.includes(event.kind!)) return false; // else if (key === 'authors' && filter.authors!.includes(event.pubkey)) return false; // else if (key.startsWith('#')) { // const tagKey = key.slice(1); // const tagValue = filter[key]; // if (event.tags) { // for (const tag of event.tags) { // if (tag[0] === tagKey && tag[1] === tagValue) { // return false; // } // } // } // } // return true; } private forwardEvent(event: NDKEvent, relay: NDKRelay) { for (const subscription of this.subscriptions) { if (!this.isEventForSubscription(event, subscription)) { continue; } subscription.emit("event", event, relay, subscription); } } private forwardEventDup( event: NDKEvent, relay: NDKRelay, timeSinceFirstSeen: number ) { for (const subscription of this.subscriptions) { if (!this.isEventForSubscription(event, subscription)) { continue; } subscription.emit( "event:dup", event, relay, timeSinceFirstSeen, subscription ); } } private forwardEose() { for (const subscription of this.subscriptions) { subscription.emit("eose", subscription); } } private forwardClose() { for (const subscription of this.subscriptions) { subscription.emit("close", subscription); } } } /** * Go through all the passed filters, which should be * relatively similar, and merge them. */ export function mergeFilters(filters: NDKFilter[]): NDKFilter { const result: any = {}; filters.forEach((filter) => { Object.entries(filter).forEach(([key, value]) => { if (Array.isArray(value)) { if (result[key] === undefined) { result[key] = [...value]; } else { result[key] = Array.from( new Set([...result[key], ...value]) ); } } else { result[key] = value; } }); }); return result as NDKFilter; } /** * Creates a valid nostr filter from an event id or a NIP-19 bech32. */ export function filterFromId(id: string): NDKFilter { let decoded; try { decoded = nip19.decode(id); switch (decoded.type) { case "nevent": return { ids: [decoded.data.id] }; case "note": return { ids: [decoded.data] }; case "naddr": return { authors: [decoded.data.pubkey], "#d": [decoded.data.identifier], kinds: [decoded.data.kind], }; } } catch (e) {} return { ids: [id] }; } /** * Returns the specified relays from a NIP-19 bech32. * * @param bech32 The NIP-19 bech32. */ export function relaysFromBech32(bech32: string): NDKRelay[] { try { const decoded = nip19.decode(bech32); if (["naddr", "nevent"].includes(decoded?.type)) { const data = decoded.data as unknown as EventPointer; if (data?.relays) { return data.relays.map((r: string) => new NDKRelay(r)); } } } catch (e) { /* empty */ } return []; } /** * Generates a random filter id, based on the filter keys. */ function generateFilterId(filter: NDKFilter) { const keys = Object.keys(filter) || []; const subId = []; for (const key of keys) { if (key === "kinds") { const v = [key, filter.kinds!.join(",")]; subId.push(v.join(":")); } else { subId.push(key); } } subId.push(Math.floor(Math.random() * 999999999).toString()); return subId.join("-"); }
src/subscription/index.ts
nostr-dev-kit-ndk-ece64e1
[ { "filename": "src/events/index.ts", "retrieved_chunk": " * The relay that this event was first received from.\n */\n public relay: NDKRelay | undefined;\n constructor(ndk?: NDK, event?: NostrEvent) {\n super();\n this.ndk = ndk;\n this.created_at = event?.created_at;\n this.content = event?.content || \"\";\n this.tags = event?.tags || [];\n this.id = event?.id || \"\";", "score": 0.8489934802055359 }, { "filename": "src/relay/sets/calculate.ts", "retrieved_chunk": " * @param event {Event}\n * @returns Promise<NDKRelaySet>\n */\nexport function calculateRelaySetFromEvent(\n ndk: NDK,\n event: Event\n): NDKRelaySet {\n const relays: Set<NDKRelay> = new Set();\n ndk.pool?.relays.forEach((relay) => relays.add(relay));\n return new NDKRelaySet(relays, ndk);", "score": 0.8402374982833862 }, { "filename": "src/cache/index.ts", "retrieved_chunk": "import NDKEvent from \"../events/index.js\";\nimport { NDKRelay } from \"../relay/index.js\";\nimport { NDKFilter, NDKSubscription } from \"../subscription/index.js\";\nexport interface NDKCacheAdapter {\n /**\n * Whether this cache adapter is expected to be fast.\n * If this is true, the cache will be queried before the relays.\n * When this is false, the cache will be queried in addition to the relays.\n */\n locking: boolean;", "score": 0.8299187421798706 }, { "filename": "src/index.ts", "retrieved_chunk": " { ...(opts || {}), closeOnEose: true },\n relaySet,\n false\n );\n const onEvent = (event: NDKEvent) => {\n const dedupKey = event.deduplicationKey();\n const existingEvent = events.get(dedupKey);\n if (existingEvent) {\n event = dedupEvent(existingEvent, event);\n }", "score": 0.8244473338127136 }, { "filename": "src/index.ts", "retrieved_chunk": "import debug from \"debug\";\nimport EventEmitter from \"eventemitter3\";\nimport { NDKCacheAdapter } from \"./cache/index.js\";\nimport dedupEvent from \"./events/dedup.js\";\nimport NDKEvent from \"./events/index.js\";\nimport type { NDKRelay } from \"./relay/index.js\";\nimport { NDKPool } from \"./relay/pool/index.js\";\nimport { calculateRelaySetFromEvent } from \"./relay/sets/calculate.js\";\nimport { NDKRelaySet } from \"./relay/sets/index.js\";\nimport { correctRelaySet } from \"./relay/sets/utils.js\";", "score": 0.823260486125946 } ]
typescript
event: NDKEvent, relay: NDKRelay | undefined, fromCache = false ) {
import EventEmitter from "eventemitter3"; import { Filter as NostrFilter, matchFilter, Sub, nip19 } from "nostr-tools"; import { EventPointer } from "nostr-tools/lib/nip19"; import NDKEvent, { NDKEventId } from "../events/index.js"; import NDK from "../index.js"; import { NDKRelay } from "../relay"; import { calculateRelaySetFromFilter } from "../relay/sets/calculate"; import { NDKRelaySet } from "../relay/sets/index.js"; import { queryFullyFilled } from "./utils.js"; export type NDKFilter = NostrFilter; export enum NDKSubscriptionCacheUsage { // Only use cache, don't subscribe to relays ONLY_CACHE = "ONLY_CACHE", // Use cache, if no matches, use relays CACHE_FIRST = "CACHE_FIRST", // Use cache in addition to relays PARALLEL = "PARALLEL", // Skip cache, don't query it ONLY_RELAY = "ONLY_RELAY", } export interface NDKSubscriptionOptions { closeOnEose: boolean; cacheUsage?: NDKSubscriptionCacheUsage; /** * Groupable subscriptions are created with a slight time * delayed to allow similar filters to be grouped together. */ groupable?: boolean; /** * The delay to use when grouping subscriptions, specified in milliseconds. * @default 100 */ groupableDelay?: number; /** * The subscription ID to use for the subscription. */ subId?: string; } /** * Default subscription options. */ export const defaultOpts: NDKSubscriptionOptions = { closeOnEose: true, cacheUsage: NDKSubscriptionCacheUsage.CACHE_FIRST, groupable: true, groupableDelay: 100, }; /** * Represents a subscription to an NDK event stream. * * @event NDKSubscription#event * Emitted when an event is received by the subscription. * @param {NDKEvent} event - The event received by the subscription. * @param {NDKRelay} relay - The relay that received the event. * @param {NDKSubscription} subscription - The subscription that received the event. * * @event NDKSubscription#event:dup * Emitted when a duplicate event is received by the subscription. * @param {NDKEvent} event - The duplicate event received by the subscription. * @param {NDKRelay} relay - The relay that received the event. * @param {number} timeSinceFirstSeen - The time elapsed since the first time the event was seen. * @param {NDKSubscription} subscription - The subscription that received the event. * * @event NDKSubscription#eose - Emitted when all relays have reached the end of the event stream. * @param {NDKSubscription} subscription - The subscription that received EOSE. * * @event NDKSubscription#close - Emitted when the subscription is closed. * @param {NDKSubscription} subscription - The subscription that was closed. */ export class NDKSubscription extends EventEmitter { readonly subId: string; readonly filters: NDKFilter[]; readonly opts: NDKSubscriptionOptions; public relaySet?: NDKRelaySet; public ndk: NDK; public relaySubscriptions: Map<NDKRelay, Sub>; private debug: debug.Debugger; /** * Events that have been seen by the subscription, with the time they were first seen. */ public eventFirstSeen = new Map<NDKEventId, number>(); /** * Relays that have sent an EOSE. */ public eosesSeen = new Set<NDKRelay>(); /** * Events that have been seen by the subscription per relay. */ public eventsPerRelay: Map<NDKRelay, Set<NDKEventId>> = new Map(); public constructor( ndk: NDK, filters: NDKFilter | NDKFilter[], opts?: NDKSubscriptionOptions, relaySet?: NDKRelaySet, subId?: string ) { super(); this.ndk = ndk; this.opts = { ...defaultOpts, ...(opts || {}) }; this.filters = filters instanceof Array ? filters : [filters]; this.subId = subId || opts?.subId || generateFilterId(this.filters[0]); this.relaySet = relaySet; this.relaySubscriptions = new Map<NDKRelay, Sub>(); this.debug = ndk.debug.extend(`subscription:${this.subId}`); // validate that the caller is not expecting a persistent // subscription while using an option that will only hit the cache if ( this.opts.cacheUsage === NDKSubscriptionCacheUsage.ONLY_CACHE && !this.opts.closeOnEose ) { throw new Error( "Cannot use cache-only options with a persistent subscription" ); } } /** * Provides access to the first filter of the subscription for * backwards compatibility. */ get filter(): NDKFilter { return this.filters[0]; } /** * Calculates the groupable ID for this subscription. * * @returns The groupable ID, or null if the subscription is not groupable. */ public groupableId(): string | null { if (!this.opts?.groupable || this.filters.length > 1) { return null; } const filter = this.filters[0]; // Check if there is a kind and no time-based filters const noTimeConstraints = !filter.since && !filter.until; const noLimit = !filter.limit; if (noTimeConstraints && noLimit) { let id = filter.kinds ? filter.kinds.join(",") : ""; const keys = Object.keys(filter || {}) .sort() .join("-"); id += `-${keys}`; return id; } return null; } private shouldQueryCache(): boolean { return this.opts?.cacheUsage !== NDKSubscriptionCacheUsage.ONLY_RELAY; } private shouldQueryRelays(): boolean { return this.opts?.cacheUsage !== NDKSubscriptionCacheUsage.ONLY_CACHE; } private shouldWaitForCache(): boolean { return ( // Must want to close on EOSE; subscriptions // that want to receive further updates must // always hit the relay this.opts.closeOnEose && // Cache adapter must claim to be fast !!this.ndk.cacheAdapter?.locking && // If explicitly told to run in parallel, then // we should not wait for the cache this.opts.cacheUsage !== NDKSubscriptionCacheUsage.PARALLEL ); } /** * Start the subscription. This is the main method that should be called * after creating a subscription. */ public async start(): Promise<void> { let cachePromise; if (this.shouldQueryCache()) { cachePromise = this.startWithCache(); if (this.shouldWaitForCache()) { await cachePromise; // if the cache has a hit, return early if (queryFullyFilled(this)) { this.emit("eose", this); return; } } } if (this.shouldQueryRelays()) { this.startWithRelaySet(); } else { this.emit("eose", this); } return; } public stop(): void { this.relaySubscriptions.forEach((sub) => sub.unsub()); this.relaySubscriptions.clear(); this.emit("close", this); } private async startWithCache(): Promise<void> { if (this.ndk.cacheAdapter?.query) { const promise = this.ndk.cacheAdapter.query(this); if (this.ndk.cacheAdapter.locking) { await promise; } } } private startWithRelaySet(): void { if (!this.relaySet) { this.relaySet = calculateRelaySetFromFilter( this.ndk, this.filters[0] ); } if (this.relaySet) { this.relaySet.subscribe(this); } } // EVENT handling /** * Called when an event is received from a relay or the cache * @param event * @param relay * @param fromCache Whether the event was received from the cache */ public eventReceived( event:
NDKEvent, relay: NDKRelay | undefined, fromCache = false ) {
if (relay) event.relay = relay; if (!relay) relay = event.relay; if (!fromCache && relay) { // track the event per relay let events = this.eventsPerRelay.get(relay); if (!events) { events = new Set(); this.eventsPerRelay.set(relay, events); } events.add(event.id); // mark the event as seen const eventAlreadySeen = this.eventFirstSeen.has(event.id); if (eventAlreadySeen) { const timeSinceFirstSeen = Date.now() - (this.eventFirstSeen.get(event.id) || 0); relay.scoreSlowerEvent(timeSinceFirstSeen); this.emit("event:dup", event, relay, timeSinceFirstSeen, this); return; } if (this.ndk.cacheAdapter) { this.ndk.cacheAdapter.setEvent(event, this.filters[0], relay); } this.eventFirstSeen.set(`${event.id}`, Date.now()); } else { this.eventFirstSeen.set(`${event.id}`, 0); } this.emit("event", event, relay, this); } // EOSE handling private eoseTimeout: ReturnType<typeof setTimeout> | undefined; public eoseReceived(relay: NDKRelay): void { if (this.opts?.closeOnEose) { this.relaySubscriptions.get(relay)?.unsub(); this.relaySubscriptions.delete(relay); // if this was the last relay that needed to EOSE, emit that this subscription is closed if (this.relaySubscriptions.size === 0) { this.emit("close", this); } } this.eosesSeen.add(relay); const hasSeenAllEoses = this.eosesSeen.size === this.relaySet?.size(); if (hasSeenAllEoses) { this.emit("eose"); } else { if (this.eoseTimeout) { clearTimeout(this.eoseTimeout); } this.eoseTimeout = setTimeout(() => { this.emit("eose"); }, 500); } } } /** * Represents a group of subscriptions. * * Events emitted from the group will be emitted from each subscription. */ export class NDKSubscriptionGroup extends NDKSubscription { private subscriptions: NDKSubscription[]; constructor(ndk: NDK, subscriptions: NDKSubscription[]) { const debug = ndk.debug.extend("subscription-group"); const filters = mergeFilters(subscriptions.map((s) => s.filters[0])); super( ndk, filters, subscriptions[0].opts, // TODO: This should be merged subscriptions[0].relaySet // TODO: This should be merged ); this.subscriptions = subscriptions; debug("merged filters", { count: subscriptions.length, mergedFilters: this.filters[0], }); // forward events to the matching subscriptions this.on("event", this.forwardEvent); this.on("event:dup", this.forwardEventDup); this.on("eose", this.forwardEose); this.on("close", this.forwardClose); } private isEventForSubscription( event: NDKEvent, subscription: NDKSubscription ): boolean { const { filters } = subscription; if (!filters) return false; return matchFilter(filters[0], event.rawEvent() as any); // check if there is a filter whose key begins with '#'; if there is, check if the event has a tag with the same key on the first position // of the tags array of arrays and the same value in the second position // for (const key in filter) { // if (key === 'kinds' && filter.kinds!.includes(event.kind!)) return false; // else if (key === 'authors' && filter.authors!.includes(event.pubkey)) return false; // else if (key.startsWith('#')) { // const tagKey = key.slice(1); // const tagValue = filter[key]; // if (event.tags) { // for (const tag of event.tags) { // if (tag[0] === tagKey && tag[1] === tagValue) { // return false; // } // } // } // } // return true; } private forwardEvent(event: NDKEvent, relay: NDKRelay) { for (const subscription of this.subscriptions) { if (!this.isEventForSubscription(event, subscription)) { continue; } subscription.emit("event", event, relay, subscription); } } private forwardEventDup( event: NDKEvent, relay: NDKRelay, timeSinceFirstSeen: number ) { for (const subscription of this.subscriptions) { if (!this.isEventForSubscription(event, subscription)) { continue; } subscription.emit( "event:dup", event, relay, timeSinceFirstSeen, subscription ); } } private forwardEose() { for (const subscription of this.subscriptions) { subscription.emit("eose", subscription); } } private forwardClose() { for (const subscription of this.subscriptions) { subscription.emit("close", subscription); } } } /** * Go through all the passed filters, which should be * relatively similar, and merge them. */ export function mergeFilters(filters: NDKFilter[]): NDKFilter { const result: any = {}; filters.forEach((filter) => { Object.entries(filter).forEach(([key, value]) => { if (Array.isArray(value)) { if (result[key] === undefined) { result[key] = [...value]; } else { result[key] = Array.from( new Set([...result[key], ...value]) ); } } else { result[key] = value; } }); }); return result as NDKFilter; } /** * Creates a valid nostr filter from an event id or a NIP-19 bech32. */ export function filterFromId(id: string): NDKFilter { let decoded; try { decoded = nip19.decode(id); switch (decoded.type) { case "nevent": return { ids: [decoded.data.id] }; case "note": return { ids: [decoded.data] }; case "naddr": return { authors: [decoded.data.pubkey], "#d": [decoded.data.identifier], kinds: [decoded.data.kind], }; } } catch (e) {} return { ids: [id] }; } /** * Returns the specified relays from a NIP-19 bech32. * * @param bech32 The NIP-19 bech32. */ export function relaysFromBech32(bech32: string): NDKRelay[] { try { const decoded = nip19.decode(bech32); if (["naddr", "nevent"].includes(decoded?.type)) { const data = decoded.data as unknown as EventPointer; if (data?.relays) { return data.relays.map((r: string) => new NDKRelay(r)); } } } catch (e) { /* empty */ } return []; } /** * Generates a random filter id, based on the filter keys. */ function generateFilterId(filter: NDKFilter) { const keys = Object.keys(filter) || []; const subId = []; for (const key of keys) { if (key === "kinds") { const v = [key, filter.kinds!.join(",")]; subId.push(v.join(":")); } else { subId.push(key); } } subId.push(Math.floor(Math.random() * 999999999).toString()); return subId.join("-"); }
src/subscription/index.ts
nostr-dev-kit-ndk-ece64e1
[ { "filename": "src/events/index.ts", "retrieved_chunk": " * The relay that this event was first received from.\n */\n public relay: NDKRelay | undefined;\n constructor(ndk?: NDK, event?: NostrEvent) {\n super();\n this.ndk = ndk;\n this.created_at = event?.created_at;\n this.content = event?.content || \"\";\n this.tags = event?.tags || [];\n this.id = event?.id || \"\";", "score": 0.848857045173645 }, { "filename": "src/relay/sets/calculate.ts", "retrieved_chunk": " * @param event {Event}\n * @returns Promise<NDKRelaySet>\n */\nexport function calculateRelaySetFromEvent(\n ndk: NDK,\n event: Event\n): NDKRelaySet {\n const relays: Set<NDKRelay> = new Set();\n ndk.pool?.relays.forEach((relay) => relays.add(relay));\n return new NDKRelaySet(relays, ndk);", "score": 0.845986008644104 }, { "filename": "src/index.ts", "retrieved_chunk": " { ...(opts || {}), closeOnEose: true },\n relaySet,\n false\n );\n const onEvent = (event: NDKEvent) => {\n const dedupKey = event.deduplicationKey();\n const existingEvent = events.get(dedupKey);\n if (existingEvent) {\n event = dedupEvent(existingEvent, event);\n }", "score": 0.8255615234375 }, { "filename": "src/cache/index.ts", "retrieved_chunk": " query(subscription: NDKSubscription): Promise<void>;\n setEvent(\n event: NDKEvent,\n filter: NDKFilter,\n relay?: NDKRelay\n ): Promise<void>;\n}", "score": 0.8218288421630859 }, { "filename": "src/cache/index.ts", "retrieved_chunk": "import NDKEvent from \"../events/index.js\";\nimport { NDKRelay } from \"../relay/index.js\";\nimport { NDKFilter, NDKSubscription } from \"../subscription/index.js\";\nexport interface NDKCacheAdapter {\n /**\n * Whether this cache adapter is expected to be fast.\n * If this is true, the cache will be queried before the relays.\n * When this is false, the cache will be queried in addition to the relays.\n */\n locking: boolean;", "score": 0.8176181316375732 } ]
typescript
NDKEvent, relay: NDKRelay | undefined, fromCache = false ) {
import EventEmitter from "eventemitter3"; import { Filter as NostrFilter, matchFilter, Sub, nip19 } from "nostr-tools"; import { EventPointer } from "nostr-tools/lib/nip19"; import NDKEvent, { NDKEventId } from "../events/index.js"; import NDK from "../index.js"; import { NDKRelay } from "../relay"; import { calculateRelaySetFromFilter } from "../relay/sets/calculate"; import { NDKRelaySet } from "../relay/sets/index.js"; import { queryFullyFilled } from "./utils.js"; export type NDKFilter = NostrFilter; export enum NDKSubscriptionCacheUsage { // Only use cache, don't subscribe to relays ONLY_CACHE = "ONLY_CACHE", // Use cache, if no matches, use relays CACHE_FIRST = "CACHE_FIRST", // Use cache in addition to relays PARALLEL = "PARALLEL", // Skip cache, don't query it ONLY_RELAY = "ONLY_RELAY", } export interface NDKSubscriptionOptions { closeOnEose: boolean; cacheUsage?: NDKSubscriptionCacheUsage; /** * Groupable subscriptions are created with a slight time * delayed to allow similar filters to be grouped together. */ groupable?: boolean; /** * The delay to use when grouping subscriptions, specified in milliseconds. * @default 100 */ groupableDelay?: number; /** * The subscription ID to use for the subscription. */ subId?: string; } /** * Default subscription options. */ export const defaultOpts: NDKSubscriptionOptions = { closeOnEose: true, cacheUsage: NDKSubscriptionCacheUsage.CACHE_FIRST, groupable: true, groupableDelay: 100, }; /** * Represents a subscription to an NDK event stream. * * @event NDKSubscription#event * Emitted when an event is received by the subscription. * @param {NDKEvent} event - The event received by the subscription. * @param {NDKRelay} relay - The relay that received the event. * @param {NDKSubscription} subscription - The subscription that received the event. * * @event NDKSubscription#event:dup * Emitted when a duplicate event is received by the subscription. * @param {NDKEvent} event - The duplicate event received by the subscription. * @param {NDKRelay} relay - The relay that received the event. * @param {number} timeSinceFirstSeen - The time elapsed since the first time the event was seen. * @param {NDKSubscription} subscription - The subscription that received the event. * * @event NDKSubscription#eose - Emitted when all relays have reached the end of the event stream. * @param {NDKSubscription} subscription - The subscription that received EOSE. * * @event NDKSubscription#close - Emitted when the subscription is closed. * @param {NDKSubscription} subscription - The subscription that was closed. */ export class NDKSubscription extends EventEmitter { readonly subId: string; readonly filters: NDKFilter[]; readonly opts: NDKSubscriptionOptions; public relaySet?: NDKRelaySet; public ndk: NDK; public relaySubscriptions: Map<NDKRelay, Sub>; private debug: debug.Debugger; /** * Events that have been seen by the subscription, with the time they were first seen. */ public eventFirstSeen = new Map<NDKEventId, number>(); /** * Relays that have sent an EOSE. */ public eosesSeen = new Set<NDKRelay>(); /** * Events that have been seen by the subscription per relay. */ public eventsPerRelay: Map<
NDKRelay, Set<NDKEventId>> = new Map();
public constructor( ndk: NDK, filters: NDKFilter | NDKFilter[], opts?: NDKSubscriptionOptions, relaySet?: NDKRelaySet, subId?: string ) { super(); this.ndk = ndk; this.opts = { ...defaultOpts, ...(opts || {}) }; this.filters = filters instanceof Array ? filters : [filters]; this.subId = subId || opts?.subId || generateFilterId(this.filters[0]); this.relaySet = relaySet; this.relaySubscriptions = new Map<NDKRelay, Sub>(); this.debug = ndk.debug.extend(`subscription:${this.subId}`); // validate that the caller is not expecting a persistent // subscription while using an option that will only hit the cache if ( this.opts.cacheUsage === NDKSubscriptionCacheUsage.ONLY_CACHE && !this.opts.closeOnEose ) { throw new Error( "Cannot use cache-only options with a persistent subscription" ); } } /** * Provides access to the first filter of the subscription for * backwards compatibility. */ get filter(): NDKFilter { return this.filters[0]; } /** * Calculates the groupable ID for this subscription. * * @returns The groupable ID, or null if the subscription is not groupable. */ public groupableId(): string | null { if (!this.opts?.groupable || this.filters.length > 1) { return null; } const filter = this.filters[0]; // Check if there is a kind and no time-based filters const noTimeConstraints = !filter.since && !filter.until; const noLimit = !filter.limit; if (noTimeConstraints && noLimit) { let id = filter.kinds ? filter.kinds.join(",") : ""; const keys = Object.keys(filter || {}) .sort() .join("-"); id += `-${keys}`; return id; } return null; } private shouldQueryCache(): boolean { return this.opts?.cacheUsage !== NDKSubscriptionCacheUsage.ONLY_RELAY; } private shouldQueryRelays(): boolean { return this.opts?.cacheUsage !== NDKSubscriptionCacheUsage.ONLY_CACHE; } private shouldWaitForCache(): boolean { return ( // Must want to close on EOSE; subscriptions // that want to receive further updates must // always hit the relay this.opts.closeOnEose && // Cache adapter must claim to be fast !!this.ndk.cacheAdapter?.locking && // If explicitly told to run in parallel, then // we should not wait for the cache this.opts.cacheUsage !== NDKSubscriptionCacheUsage.PARALLEL ); } /** * Start the subscription. This is the main method that should be called * after creating a subscription. */ public async start(): Promise<void> { let cachePromise; if (this.shouldQueryCache()) { cachePromise = this.startWithCache(); if (this.shouldWaitForCache()) { await cachePromise; // if the cache has a hit, return early if (queryFullyFilled(this)) { this.emit("eose", this); return; } } } if (this.shouldQueryRelays()) { this.startWithRelaySet(); } else { this.emit("eose", this); } return; } public stop(): void { this.relaySubscriptions.forEach((sub) => sub.unsub()); this.relaySubscriptions.clear(); this.emit("close", this); } private async startWithCache(): Promise<void> { if (this.ndk.cacheAdapter?.query) { const promise = this.ndk.cacheAdapter.query(this); if (this.ndk.cacheAdapter.locking) { await promise; } } } private startWithRelaySet(): void { if (!this.relaySet) { this.relaySet = calculateRelaySetFromFilter( this.ndk, this.filters[0] ); } if (this.relaySet) { this.relaySet.subscribe(this); } } // EVENT handling /** * Called when an event is received from a relay or the cache * @param event * @param relay * @param fromCache Whether the event was received from the cache */ public eventReceived( event: NDKEvent, relay: NDKRelay | undefined, fromCache = false ) { if (relay) event.relay = relay; if (!relay) relay = event.relay; if (!fromCache && relay) { // track the event per relay let events = this.eventsPerRelay.get(relay); if (!events) { events = new Set(); this.eventsPerRelay.set(relay, events); } events.add(event.id); // mark the event as seen const eventAlreadySeen = this.eventFirstSeen.has(event.id); if (eventAlreadySeen) { const timeSinceFirstSeen = Date.now() - (this.eventFirstSeen.get(event.id) || 0); relay.scoreSlowerEvent(timeSinceFirstSeen); this.emit("event:dup", event, relay, timeSinceFirstSeen, this); return; } if (this.ndk.cacheAdapter) { this.ndk.cacheAdapter.setEvent(event, this.filters[0], relay); } this.eventFirstSeen.set(`${event.id}`, Date.now()); } else { this.eventFirstSeen.set(`${event.id}`, 0); } this.emit("event", event, relay, this); } // EOSE handling private eoseTimeout: ReturnType<typeof setTimeout> | undefined; public eoseReceived(relay: NDKRelay): void { if (this.opts?.closeOnEose) { this.relaySubscriptions.get(relay)?.unsub(); this.relaySubscriptions.delete(relay); // if this was the last relay that needed to EOSE, emit that this subscription is closed if (this.relaySubscriptions.size === 0) { this.emit("close", this); } } this.eosesSeen.add(relay); const hasSeenAllEoses = this.eosesSeen.size === this.relaySet?.size(); if (hasSeenAllEoses) { this.emit("eose"); } else { if (this.eoseTimeout) { clearTimeout(this.eoseTimeout); } this.eoseTimeout = setTimeout(() => { this.emit("eose"); }, 500); } } } /** * Represents a group of subscriptions. * * Events emitted from the group will be emitted from each subscription. */ export class NDKSubscriptionGroup extends NDKSubscription { private subscriptions: NDKSubscription[]; constructor(ndk: NDK, subscriptions: NDKSubscription[]) { const debug = ndk.debug.extend("subscription-group"); const filters = mergeFilters(subscriptions.map((s) => s.filters[0])); super( ndk, filters, subscriptions[0].opts, // TODO: This should be merged subscriptions[0].relaySet // TODO: This should be merged ); this.subscriptions = subscriptions; debug("merged filters", { count: subscriptions.length, mergedFilters: this.filters[0], }); // forward events to the matching subscriptions this.on("event", this.forwardEvent); this.on("event:dup", this.forwardEventDup); this.on("eose", this.forwardEose); this.on("close", this.forwardClose); } private isEventForSubscription( event: NDKEvent, subscription: NDKSubscription ): boolean { const { filters } = subscription; if (!filters) return false; return matchFilter(filters[0], event.rawEvent() as any); // check if there is a filter whose key begins with '#'; if there is, check if the event has a tag with the same key on the first position // of the tags array of arrays and the same value in the second position // for (const key in filter) { // if (key === 'kinds' && filter.kinds!.includes(event.kind!)) return false; // else if (key === 'authors' && filter.authors!.includes(event.pubkey)) return false; // else if (key.startsWith('#')) { // const tagKey = key.slice(1); // const tagValue = filter[key]; // if (event.tags) { // for (const tag of event.tags) { // if (tag[0] === tagKey && tag[1] === tagValue) { // return false; // } // } // } // } // return true; } private forwardEvent(event: NDKEvent, relay: NDKRelay) { for (const subscription of this.subscriptions) { if (!this.isEventForSubscription(event, subscription)) { continue; } subscription.emit("event", event, relay, subscription); } } private forwardEventDup( event: NDKEvent, relay: NDKRelay, timeSinceFirstSeen: number ) { for (const subscription of this.subscriptions) { if (!this.isEventForSubscription(event, subscription)) { continue; } subscription.emit( "event:dup", event, relay, timeSinceFirstSeen, subscription ); } } private forwardEose() { for (const subscription of this.subscriptions) { subscription.emit("eose", subscription); } } private forwardClose() { for (const subscription of this.subscriptions) { subscription.emit("close", subscription); } } } /** * Go through all the passed filters, which should be * relatively similar, and merge them. */ export function mergeFilters(filters: NDKFilter[]): NDKFilter { const result: any = {}; filters.forEach((filter) => { Object.entries(filter).forEach(([key, value]) => { if (Array.isArray(value)) { if (result[key] === undefined) { result[key] = [...value]; } else { result[key] = Array.from( new Set([...result[key], ...value]) ); } } else { result[key] = value; } }); }); return result as NDKFilter; } /** * Creates a valid nostr filter from an event id or a NIP-19 bech32. */ export function filterFromId(id: string): NDKFilter { let decoded; try { decoded = nip19.decode(id); switch (decoded.type) { case "nevent": return { ids: [decoded.data.id] }; case "note": return { ids: [decoded.data] }; case "naddr": return { authors: [decoded.data.pubkey], "#d": [decoded.data.identifier], kinds: [decoded.data.kind], }; } } catch (e) {} return { ids: [id] }; } /** * Returns the specified relays from a NIP-19 bech32. * * @param bech32 The NIP-19 bech32. */ export function relaysFromBech32(bech32: string): NDKRelay[] { try { const decoded = nip19.decode(bech32); if (["naddr", "nevent"].includes(decoded?.type)) { const data = decoded.data as unknown as EventPointer; if (data?.relays) { return data.relays.map((r: string) => new NDKRelay(r)); } } } catch (e) { /* empty */ } return []; } /** * Generates a random filter id, based on the filter keys. */ function generateFilterId(filter: NDKFilter) { const keys = Object.keys(filter) || []; const subId = []; for (const key of keys) { if (key === "kinds") { const v = [key, filter.kinds!.join(",")]; subId.push(v.join(":")); } else { subId.push(key); } } subId.push(Math.floor(Math.random() * 999999999).toString()); return subId.join("-"); }
src/subscription/index.ts
nostr-dev-kit-ndk-ece64e1
[ { "filename": "src/index.ts", "retrieved_chunk": " event.ndk = this;\n events.set(dedupKey, event);\n };\n // We want to inspect duplicated events\n // so we can dedup them\n relaySetSubscription.on(\"event\", onEvent);\n relaySetSubscription.on(\"event:dup\", onEvent);\n relaySetSubscription.on(\"eose\", () => {\n resolve(new Set(events.values()));\n });", "score": 0.8474396467208862 }, { "filename": "src/user/index.ts", "retrieved_chunk": " if (!this.ndk) throw new Error(\"NDK not set\");\n const relayListEvents = await this.ndk.fetchEvents({\n kinds: [10002],\n authors: [this.hexpubkey()],\n });\n if (relayListEvents) {\n return relayListEvents;\n }\n return new Set<NDKEvent>();\n }", "score": 0.8424757122993469 }, { "filename": "src/relay/index.ts", "retrieved_chunk": " id: subscription.subId,\n });\n this.debug(`Subscribed to ${JSON.stringify(filters)}`);\n sub.on(\"event\", (event: NostrEvent) => {\n const e = new NDKEvent(undefined, event);\n e.relay = this;\n subscription.eventReceived(e, this);\n });\n sub.on(\"eose\", () => {\n subscription.eoseReceived(this);", "score": 0.8327169418334961 }, { "filename": "src/index.ts", "retrieved_chunk": " { ...(opts || {}), closeOnEose: true },\n relaySet,\n false\n );\n const onEvent = (event: NDKEvent) => {\n const dedupKey = event.deduplicationKey();\n const existingEvent = events.get(dedupKey);\n if (existingEvent) {\n event = dedupEvent(existingEvent, event);\n }", "score": 0.8325273990631104 }, { "filename": "src/relay/pool/index.ts", "retrieved_chunk": " public relays = new Map<string, NDKRelay>();\n private debug: debug.Debugger;\n private temporaryRelayTimers = new Map<string, NodeJS.Timeout>();\n public constructor(relayUrls: string[] = [], ndk: NDK) {\n super();\n this.debug = ndk.debug.extend(\"pool\");\n for (const relayUrl of relayUrls) {\n const relay = new NDKRelay(relayUrl);\n this.addRelay(relay, false);\n }", "score": 0.8287400007247925 } ]
typescript
NDKRelay, Set<NDKEventId>> = new Map();
import EventEmitter from "eventemitter3"; import { Filter as NostrFilter, matchFilter, Sub, nip19 } from "nostr-tools"; import { EventPointer } from "nostr-tools/lib/nip19"; import NDKEvent, { NDKEventId } from "../events/index.js"; import NDK from "../index.js"; import { NDKRelay } from "../relay"; import { calculateRelaySetFromFilter } from "../relay/sets/calculate"; import { NDKRelaySet } from "../relay/sets/index.js"; import { queryFullyFilled } from "./utils.js"; export type NDKFilter = NostrFilter; export enum NDKSubscriptionCacheUsage { // Only use cache, don't subscribe to relays ONLY_CACHE = "ONLY_CACHE", // Use cache, if no matches, use relays CACHE_FIRST = "CACHE_FIRST", // Use cache in addition to relays PARALLEL = "PARALLEL", // Skip cache, don't query it ONLY_RELAY = "ONLY_RELAY", } export interface NDKSubscriptionOptions { closeOnEose: boolean; cacheUsage?: NDKSubscriptionCacheUsage; /** * Groupable subscriptions are created with a slight time * delayed to allow similar filters to be grouped together. */ groupable?: boolean; /** * The delay to use when grouping subscriptions, specified in milliseconds. * @default 100 */ groupableDelay?: number; /** * The subscription ID to use for the subscription. */ subId?: string; } /** * Default subscription options. */ export const defaultOpts: NDKSubscriptionOptions = { closeOnEose: true, cacheUsage: NDKSubscriptionCacheUsage.CACHE_FIRST, groupable: true, groupableDelay: 100, }; /** * Represents a subscription to an NDK event stream. * * @event NDKSubscription#event * Emitted when an event is received by the subscription. * @param {NDKEvent} event - The event received by the subscription. * @param {NDKRelay} relay - The relay that received the event. * @param {NDKSubscription} subscription - The subscription that received the event. * * @event NDKSubscription#event:dup * Emitted when a duplicate event is received by the subscription. * @param {NDKEvent} event - The duplicate event received by the subscription. * @param {NDKRelay} relay - The relay that received the event. * @param {number} timeSinceFirstSeen - The time elapsed since the first time the event was seen. * @param {NDKSubscription} subscription - The subscription that received the event. * * @event NDKSubscription#eose - Emitted when all relays have reached the end of the event stream. * @param {NDKSubscription} subscription - The subscription that received EOSE. * * @event NDKSubscription#close - Emitted when the subscription is closed. * @param {NDKSubscription} subscription - The subscription that was closed. */ export class NDKSubscription extends EventEmitter { readonly subId: string; readonly filters: NDKFilter[]; readonly opts: NDKSubscriptionOptions; public relaySet?: NDKRelaySet; public ndk: NDK; public relaySubscriptions: Map<NDKRelay, Sub>; private debug: debug.Debugger; /** * Events that have been seen by the subscription, with the time they were first seen. */ public eventFirstSeen = new Map<NDKEventId, number>(); /** * Relays that have sent an EOSE. */ public eosesSeen = new Set<NDKRelay>(); /** * Events that have been seen by the subscription per relay. */ public eventsPerRelay: Map<NDKRelay, Set<NDKEventId>> = new Map(); public constructor( ndk: NDK, filters: NDKFilter | NDKFilter[], opts?: NDKSubscriptionOptions, relaySet?: NDKRelaySet, subId?: string ) { super(); this.ndk = ndk; this.opts = { ...defaultOpts, ...(opts || {}) }; this.filters = filters instanceof Array ? filters : [filters]; this.subId = subId || opts?.subId || generateFilterId(this.filters[0]); this.relaySet = relaySet; this.relaySubscriptions = new Map<NDKRelay, Sub>(); this.debug = ndk.debug.extend(`subscription:${this.subId}`); // validate that the caller is not expecting a persistent // subscription while using an option that will only hit the cache if ( this.opts.cacheUsage === NDKSubscriptionCacheUsage.ONLY_CACHE && !this.opts.closeOnEose ) { throw new Error( "Cannot use cache-only options with a persistent subscription" ); } } /** * Provides access to the first filter of the subscription for * backwards compatibility. */ get filter(): NDKFilter { return this.filters[0]; } /** * Calculates the groupable ID for this subscription. * * @returns The groupable ID, or null if the subscription is not groupable. */ public groupableId(): string | null { if (!this.opts?.groupable || this.filters.length > 1) { return null; } const filter = this.filters[0]; // Check if there is a kind and no time-based filters const noTimeConstraints = !filter.since && !filter.until; const noLimit = !filter.limit; if (noTimeConstraints && noLimit) { let id = filter.kinds ? filter.kinds.join(",") : ""; const keys = Object.keys(filter || {}) .sort() .join("-"); id += `-${keys}`; return id; } return null; } private shouldQueryCache(): boolean { return this.opts?.cacheUsage !== NDKSubscriptionCacheUsage.ONLY_RELAY; } private shouldQueryRelays(): boolean { return this.opts?.cacheUsage !== NDKSubscriptionCacheUsage.ONLY_CACHE; } private shouldWaitForCache(): boolean { return ( // Must want to close on EOSE; subscriptions // that want to receive further updates must // always hit the relay this.opts.closeOnEose && // Cache adapter must claim to be fast !!this.ndk.cacheAdapter?.locking && // If explicitly told to run in parallel, then // we should not wait for the cache this.opts.cacheUsage !== NDKSubscriptionCacheUsage.PARALLEL ); } /** * Start the subscription. This is the main method that should be called * after creating a subscription. */ public async start(): Promise<void> { let cachePromise; if (this.shouldQueryCache()) { cachePromise = this.startWithCache(); if (this.shouldWaitForCache()) { await cachePromise; // if the cache has a hit, return early if (queryFullyFilled(this)) { this.emit("eose", this); return; } } } if (this.shouldQueryRelays()) { this.startWithRelaySet(); } else { this.emit("eose", this); } return; } public stop(): void { this.relaySubscriptions.forEach((sub) => sub.unsub()); this.relaySubscriptions.clear(); this.emit("close", this); } private async startWithCache(): Promise<void> { if (this.ndk.cacheAdapter?.query) { const promise = this.ndk.cacheAdapter.query(this); if (this.ndk.cacheAdapter.locking) { await promise; } } } private startWithRelaySet(): void { if (!this.relaySet) { this.
relaySet = calculateRelaySetFromFilter( this.ndk, this.filters[0] );
} if (this.relaySet) { this.relaySet.subscribe(this); } } // EVENT handling /** * Called when an event is received from a relay or the cache * @param event * @param relay * @param fromCache Whether the event was received from the cache */ public eventReceived( event: NDKEvent, relay: NDKRelay | undefined, fromCache = false ) { if (relay) event.relay = relay; if (!relay) relay = event.relay; if (!fromCache && relay) { // track the event per relay let events = this.eventsPerRelay.get(relay); if (!events) { events = new Set(); this.eventsPerRelay.set(relay, events); } events.add(event.id); // mark the event as seen const eventAlreadySeen = this.eventFirstSeen.has(event.id); if (eventAlreadySeen) { const timeSinceFirstSeen = Date.now() - (this.eventFirstSeen.get(event.id) || 0); relay.scoreSlowerEvent(timeSinceFirstSeen); this.emit("event:dup", event, relay, timeSinceFirstSeen, this); return; } if (this.ndk.cacheAdapter) { this.ndk.cacheAdapter.setEvent(event, this.filters[0], relay); } this.eventFirstSeen.set(`${event.id}`, Date.now()); } else { this.eventFirstSeen.set(`${event.id}`, 0); } this.emit("event", event, relay, this); } // EOSE handling private eoseTimeout: ReturnType<typeof setTimeout> | undefined; public eoseReceived(relay: NDKRelay): void { if (this.opts?.closeOnEose) { this.relaySubscriptions.get(relay)?.unsub(); this.relaySubscriptions.delete(relay); // if this was the last relay that needed to EOSE, emit that this subscription is closed if (this.relaySubscriptions.size === 0) { this.emit("close", this); } } this.eosesSeen.add(relay); const hasSeenAllEoses = this.eosesSeen.size === this.relaySet?.size(); if (hasSeenAllEoses) { this.emit("eose"); } else { if (this.eoseTimeout) { clearTimeout(this.eoseTimeout); } this.eoseTimeout = setTimeout(() => { this.emit("eose"); }, 500); } } } /** * Represents a group of subscriptions. * * Events emitted from the group will be emitted from each subscription. */ export class NDKSubscriptionGroup extends NDKSubscription { private subscriptions: NDKSubscription[]; constructor(ndk: NDK, subscriptions: NDKSubscription[]) { const debug = ndk.debug.extend("subscription-group"); const filters = mergeFilters(subscriptions.map((s) => s.filters[0])); super( ndk, filters, subscriptions[0].opts, // TODO: This should be merged subscriptions[0].relaySet // TODO: This should be merged ); this.subscriptions = subscriptions; debug("merged filters", { count: subscriptions.length, mergedFilters: this.filters[0], }); // forward events to the matching subscriptions this.on("event", this.forwardEvent); this.on("event:dup", this.forwardEventDup); this.on("eose", this.forwardEose); this.on("close", this.forwardClose); } private isEventForSubscription( event: NDKEvent, subscription: NDKSubscription ): boolean { const { filters } = subscription; if (!filters) return false; return matchFilter(filters[0], event.rawEvent() as any); // check if there is a filter whose key begins with '#'; if there is, check if the event has a tag with the same key on the first position // of the tags array of arrays and the same value in the second position // for (const key in filter) { // if (key === 'kinds' && filter.kinds!.includes(event.kind!)) return false; // else if (key === 'authors' && filter.authors!.includes(event.pubkey)) return false; // else if (key.startsWith('#')) { // const tagKey = key.slice(1); // const tagValue = filter[key]; // if (event.tags) { // for (const tag of event.tags) { // if (tag[0] === tagKey && tag[1] === tagValue) { // return false; // } // } // } // } // return true; } private forwardEvent(event: NDKEvent, relay: NDKRelay) { for (const subscription of this.subscriptions) { if (!this.isEventForSubscription(event, subscription)) { continue; } subscription.emit("event", event, relay, subscription); } } private forwardEventDup( event: NDKEvent, relay: NDKRelay, timeSinceFirstSeen: number ) { for (const subscription of this.subscriptions) { if (!this.isEventForSubscription(event, subscription)) { continue; } subscription.emit( "event:dup", event, relay, timeSinceFirstSeen, subscription ); } } private forwardEose() { for (const subscription of this.subscriptions) { subscription.emit("eose", subscription); } } private forwardClose() { for (const subscription of this.subscriptions) { subscription.emit("close", subscription); } } } /** * Go through all the passed filters, which should be * relatively similar, and merge them. */ export function mergeFilters(filters: NDKFilter[]): NDKFilter { const result: any = {}; filters.forEach((filter) => { Object.entries(filter).forEach(([key, value]) => { if (Array.isArray(value)) { if (result[key] === undefined) { result[key] = [...value]; } else { result[key] = Array.from( new Set([...result[key], ...value]) ); } } else { result[key] = value; } }); }); return result as NDKFilter; } /** * Creates a valid nostr filter from an event id or a NIP-19 bech32. */ export function filterFromId(id: string): NDKFilter { let decoded; try { decoded = nip19.decode(id); switch (decoded.type) { case "nevent": return { ids: [decoded.data.id] }; case "note": return { ids: [decoded.data] }; case "naddr": return { authors: [decoded.data.pubkey], "#d": [decoded.data.identifier], kinds: [decoded.data.kind], }; } } catch (e) {} return { ids: [id] }; } /** * Returns the specified relays from a NIP-19 bech32. * * @param bech32 The NIP-19 bech32. */ export function relaysFromBech32(bech32: string): NDKRelay[] { try { const decoded = nip19.decode(bech32); if (["naddr", "nevent"].includes(decoded?.type)) { const data = decoded.data as unknown as EventPointer; if (data?.relays) { return data.relays.map((r: string) => new NDKRelay(r)); } } } catch (e) { /* empty */ } return []; } /** * Generates a random filter id, based on the filter keys. */ function generateFilterId(filter: NDKFilter) { const keys = Object.keys(filter) || []; const subId = []; for (const key of keys) { if (key === "kinds") { const v = [key, filter.kinds!.join(",")]; subId.push(v.join(":")); } else { subId.push(key); } } subId.push(Math.floor(Math.random() * 999999999).toString()); return subId.join("-"); }
src/subscription/index.ts
nostr-dev-kit-ndk-ece64e1
[ { "filename": "src/relay/sets/calculate.ts", "retrieved_chunk": " const sets: Map<NDKFilter, NDKRelaySet> = new Map();\n filters.forEach((filter) => {\n const set = calculateRelaySetFromFilter(ndk, filter);\n sets.set(filter, set);\n });\n return sets;\n}", "score": 0.8873908519744873 }, { "filename": "src/relay/sets/calculate.ts", "retrieved_chunk": "}\n/**\n * Calculates a number of RelaySets for each filter.\n * @param ndk\n * @param filters\n */\nexport function calculateRelaySetsFromFilters(\n ndk: NDK,\n filters: NDKFilter[]\n): Map<NDKFilter, NDKRelaySet> {", "score": 0.8669322729110718 }, { "filename": "src/relay/sets/calculate.ts", "retrieved_chunk": "): NDKRelaySet {\n const relays: Set<NDKRelay> = new Set();\n ndk.pool?.relays.forEach((relay) => {\n if (!relay.complaining) {\n relays.add(relay);\n } else {\n ndk.debug(`Relay ${relay.url} is complaining, not adding to set`);\n }\n });\n return new NDKRelaySet(relays, ndk);", "score": 0.8601447939872742 }, { "filename": "src/relay/sets/calculate.ts", "retrieved_chunk": "}\n/**\n * Creates a NDKRelaySet for the specified filter\n * @param ndk\n * @param filter\n * @returns Promise<NDKRelaySet>\n */\nexport function calculateRelaySetFromFilter(\n ndk: NDK,\n filter: NDKFilter", "score": 0.8563278913497925 }, { "filename": "src/relay/sets/calculate.ts", "retrieved_chunk": " * @param event {Event}\n * @returns Promise<NDKRelaySet>\n */\nexport function calculateRelaySetFromEvent(\n ndk: NDK,\n event: Event\n): NDKRelaySet {\n const relays: Set<NDKRelay> = new Set();\n ndk.pool?.relays.forEach((relay) => relays.add(relay));\n return new NDKRelaySet(relays, ndk);", "score": 0.851089596748352 } ]
typescript
relaySet = calculateRelaySetFromFilter( this.ndk, this.filters[0] );
import EventEmitter from "eventemitter3"; import { Filter as NostrFilter, matchFilter, Sub, nip19 } from "nostr-tools"; import { EventPointer } from "nostr-tools/lib/nip19"; import NDKEvent, { NDKEventId } from "../events/index.js"; import NDK from "../index.js"; import { NDKRelay } from "../relay"; import { calculateRelaySetFromFilter } from "../relay/sets/calculate"; import { NDKRelaySet } from "../relay/sets/index.js"; import { queryFullyFilled } from "./utils.js"; export type NDKFilter = NostrFilter; export enum NDKSubscriptionCacheUsage { // Only use cache, don't subscribe to relays ONLY_CACHE = "ONLY_CACHE", // Use cache, if no matches, use relays CACHE_FIRST = "CACHE_FIRST", // Use cache in addition to relays PARALLEL = "PARALLEL", // Skip cache, don't query it ONLY_RELAY = "ONLY_RELAY", } export interface NDKSubscriptionOptions { closeOnEose: boolean; cacheUsage?: NDKSubscriptionCacheUsage; /** * Groupable subscriptions are created with a slight time * delayed to allow similar filters to be grouped together. */ groupable?: boolean; /** * The delay to use when grouping subscriptions, specified in milliseconds. * @default 100 */ groupableDelay?: number; /** * The subscription ID to use for the subscription. */ subId?: string; } /** * Default subscription options. */ export const defaultOpts: NDKSubscriptionOptions = { closeOnEose: true, cacheUsage: NDKSubscriptionCacheUsage.CACHE_FIRST, groupable: true, groupableDelay: 100, }; /** * Represents a subscription to an NDK event stream. * * @event NDKSubscription#event * Emitted when an event is received by the subscription. * @param {NDKEvent} event - The event received by the subscription. * @param {NDKRelay} relay - The relay that received the event. * @param {NDKSubscription} subscription - The subscription that received the event. * * @event NDKSubscription#event:dup * Emitted when a duplicate event is received by the subscription. * @param {NDKEvent} event - The duplicate event received by the subscription. * @param {NDKRelay} relay - The relay that received the event. * @param {number} timeSinceFirstSeen - The time elapsed since the first time the event was seen. * @param {NDKSubscription} subscription - The subscription that received the event. * * @event NDKSubscription#eose - Emitted when all relays have reached the end of the event stream. * @param {NDKSubscription} subscription - The subscription that received EOSE. * * @event NDKSubscription#close - Emitted when the subscription is closed. * @param {NDKSubscription} subscription - The subscription that was closed. */ export class NDKSubscription extends EventEmitter { readonly subId: string; readonly filters: NDKFilter[]; readonly opts: NDKSubscriptionOptions; public relaySet?: NDKRelaySet; public ndk: NDK; public relaySubscriptions: Map<NDKRelay, Sub>; private debug: debug.Debugger; /** * Events that have been seen by the subscription, with the time they were first seen. */ public eventFirstSeen = new Map<NDKEventId, number>(); /** * Relays that have sent an EOSE. */ public eosesSeen = new Set<NDKRelay>(); /** * Events that have been seen by the subscription per relay. */ public eventsPerRelay: Map<NDKRelay, Set<NDKEventId>> = new Map(); public constructor( ndk: NDK, filters: NDKFilter | NDKFilter[], opts?: NDKSubscriptionOptions, relaySet?: NDKRelaySet, subId?: string ) { super(); this.ndk = ndk; this.opts = { ...defaultOpts, ...(opts || {}) }; this.filters = filters instanceof Array ? filters : [filters]; this.subId = subId || opts?.subId || generateFilterId(this.filters[0]); this.relaySet = relaySet; this.relaySubscriptions = new Map<NDKRelay, Sub>(); this.debug = ndk.debug.extend(`subscription:${this.subId}`); // validate that the caller is not expecting a persistent // subscription while using an option that will only hit the cache if ( this.opts.cacheUsage === NDKSubscriptionCacheUsage.ONLY_CACHE && !this.opts.closeOnEose ) { throw new Error( "Cannot use cache-only options with a persistent subscription" ); } } /** * Provides access to the first filter of the subscription for * backwards compatibility. */ get filter(): NDKFilter { return this.filters[0]; } /** * Calculates the groupable ID for this subscription. * * @returns The groupable ID, or null if the subscription is not groupable. */ public groupableId(): string | null { if (!this.opts?.groupable || this.filters.length > 1) { return null; } const filter = this.filters[0]; // Check if there is a kind and no time-based filters const noTimeConstraints = !filter.since && !filter.until; const noLimit = !filter.limit; if (noTimeConstraints && noLimit) { let id = filter.kinds ? filter.kinds.join(",") : ""; const keys = Object.keys(filter || {}) .sort() .join("-"); id += `-${keys}`; return id; } return null; } private shouldQueryCache(): boolean { return this.opts?.cacheUsage !== NDKSubscriptionCacheUsage.ONLY_RELAY; } private shouldQueryRelays(): boolean { return this.opts?.cacheUsage !== NDKSubscriptionCacheUsage.ONLY_CACHE; } private shouldWaitForCache(): boolean { return ( // Must want to close on EOSE; subscriptions // that want to receive further updates must // always hit the relay this.opts.closeOnEose && // Cache adapter must claim to be fast !!this.ndk.cacheAdapter?.locking && // If explicitly told to run in parallel, then // we should not wait for the cache this.opts.cacheUsage !== NDKSubscriptionCacheUsage.PARALLEL ); } /** * Start the subscription. This is the main method that should be called * after creating a subscription. */ public async start(): Promise<void> { let cachePromise; if (this.shouldQueryCache()) { cachePromise = this.startWithCache(); if (this.shouldWaitForCache()) { await cachePromise; // if the cache has a hit, return early if (queryFullyFilled(this)) { this.emit("eose", this); return; } } } if (this.shouldQueryRelays()) { this.startWithRelaySet(); } else { this.emit("eose", this); } return; } public stop(): void { this.relaySubscriptions.forEach((sub) => sub.unsub()); this.relaySubscriptions.clear(); this.emit("close", this); } private async startWithCache(): Promise<void> { if (this.ndk.cacheAdapter?.query) { const promise = this.ndk.cacheAdapter.query(this); if (this.ndk.cacheAdapter.locking) { await promise; } } } private startWithRelaySet(): void { if (!this.relaySet) { this.relaySet = calculateRelaySetFromFilter( this.ndk, this.filters[0] ); } if (this.relaySet) { this.relaySet.subscribe(this); } } // EVENT handling /** * Called when an event is received from a relay or the cache * @param event * @param relay * @param fromCache Whether the event was received from the cache */ public eventReceived( event: NDKEvent, relay: NDKRelay | undefined, fromCache = false ) { if (relay) event.relay = relay; if (!relay) relay = event.relay; if (!fromCache && relay) { // track the event per relay let events = this.eventsPerRelay.get(relay); if (!events) { events = new Set(); this.eventsPerRelay.set(relay, events); } events.add(event.id); // mark the event as seen const eventAlreadySeen = this.eventFirstSeen.has(event.id); if (eventAlreadySeen) { const timeSinceFirstSeen = Date.now() - (this.eventFirstSeen.get(event.id) || 0); relay.scoreSlowerEvent(timeSinceFirstSeen); this.emit("event:dup", event, relay, timeSinceFirstSeen, this); return; } if (this.ndk.cacheAdapter) { this.ndk.cacheAdapter.setEvent(event, this.filters[0], relay); } this.eventFirstSeen.set(`${event.id}`, Date.now()); } else { this.eventFirstSeen.set(`${event.id}`, 0); } this.emit("event", event, relay, this); } // EOSE handling private eoseTimeout: ReturnType<typeof setTimeout> | undefined; public eoseReceived(relay: NDKRelay): void { if (this.opts?.closeOnEose) { this.relaySubscriptions.get(relay)?.unsub(); this.relaySubscriptions.delete(relay); // if this was the last relay that needed to EOSE, emit that this subscription is closed if (this.relaySubscriptions.size === 0) { this.emit("close", this); } } this.eosesSeen.add(relay); const hasSeenAllEoses = this.eosesSeen.size === this.relaySet?.size(); if (hasSeenAllEoses) { this.emit("eose"); } else { if (this.eoseTimeout) { clearTimeout(this.eoseTimeout); } this.eoseTimeout = setTimeout(() => { this.emit("eose"); }, 500); } } } /** * Represents a group of subscriptions. * * Events emitted from the group will be emitted from each subscription. */ export class NDKSubscriptionGroup extends NDKSubscription { private subscriptions: NDKSubscription[]; constructor(ndk: NDK, subscriptions: NDKSubscription[]) { const debug = ndk.debug.extend("subscription-group"); const filters = mergeFilters(subscriptions.map((s) => s.filters[0])); super( ndk, filters, subscriptions[0].opts, // TODO: This should be merged subscriptions[0].relaySet // TODO: This should be merged ); this.subscriptions = subscriptions; debug("merged filters", { count: subscriptions.length, mergedFilters: this.filters[0], }); // forward events to the matching subscriptions this.on("event", this.forwardEvent); this.on("event:dup", this.forwardEventDup); this.on("eose", this.forwardEose); this.on("close", this.forwardClose); } private isEventForSubscription( event: NDKEvent, subscription: NDKSubscription ): boolean { const { filters } = subscription; if (!filters) return false; return matchFilter(filters[0], event.rawEvent() as any); // check if there is a filter whose key begins with '#'; if there is, check if the event has a tag with the same key on the first position // of the tags array of arrays and the same value in the second position // for (const key in filter) { // if (key === 'kinds' && filter.kinds!.includes(event.kind!)) return false; // else if (key === 'authors' && filter.authors!.includes(event.pubkey)) return false; // else if (key.startsWith('#')) { // const tagKey = key.slice(1); // const tagValue = filter[key]; // if (event.tags) { // for (const tag of event.tags) { // if (tag[0] === tagKey && tag[1] === tagValue) { // return false; // } // } // } // } // return true; } private forwardEvent(event: NDKEvent, relay: NDKRelay) { for (const subscription of this.subscriptions) { if (!this.isEventForSubscription(event, subscription)) { continue; } subscription.emit("event", event, relay, subscription); } } private forwardEventDup( event: NDKEvent, relay: NDKRelay, timeSinceFirstSeen: number ) { for (const subscription of this.subscriptions) { if (!this.isEventForSubscription(event, subscription)) { continue; } subscription.emit( "event:dup", event, relay, timeSinceFirstSeen, subscription ); } } private forwardEose() { for (const subscription of this.subscriptions) { subscription.emit("eose", subscription); } } private forwardClose() { for (const subscription of this.subscriptions) { subscription.emit("close", subscription); } } } /** * Go through all the passed filters, which should be * relatively similar, and merge them. */ export function mergeFilters(filters: NDKFilter[]): NDKFilter { const result: any = {}; filters.forEach((filter) => { Object.entries(filter).forEach(([key, value]) => { if (Array.isArray(value)) { if (result[key] === undefined) { result[key] = [...value]; } else { result[key] = Array.from( new Set([...result[key], ...value]) ); } } else { result[key] = value; } }); }); return result as NDKFilter; } /** * Creates a valid nostr filter from an event id or a NIP-19 bech32. */ export function filterFromId(id: string): NDKFilter { let decoded; try { decoded = nip19.decode(id); switch (decoded.type) { case "nevent": return { ids: [decoded.data.id] }; case "note": return { ids: [decoded.data] }; case "naddr": return { authors: [decoded.data.pubkey], "#d": [decoded.data.identifier], kinds: [decoded.data.kind], }; } } catch (e) {} return { ids: [id] }; } /** * Returns the specified relays from a NIP-19 bech32. * * @param bech32 The NIP-19 bech32. */
export function relaysFromBech32(bech32: string): NDKRelay[] {
try { const decoded = nip19.decode(bech32); if (["naddr", "nevent"].includes(decoded?.type)) { const data = decoded.data as unknown as EventPointer; if (data?.relays) { return data.relays.map((r: string) => new NDKRelay(r)); } } } catch (e) { /* empty */ } return []; } /** * Generates a random filter id, based on the filter keys. */ function generateFilterId(filter: NDKFilter) { const keys = Object.keys(filter) || []; const subId = []; for (const key of keys) { if (key === "kinds") { const v = [key, filter.kinds!.join(",")]; subId.push(v.join(":")); } else { subId.push(key); } } subId.push(Math.floor(Math.random() * 999999999).toString()); return subId.join("-"); }
src/subscription/index.ts
nostr-dev-kit-ndk-ece64e1
[ { "filename": "src/zap/index.ts", "retrieved_chunk": "import { bech32 } from \"@scure/base\";\nimport EventEmitter from \"eventemitter3\";\nimport { nip57 } from \"nostr-tools\";\nimport type { NostrEvent } from \"../events/index.js\";\nimport NDKEvent, { NDKTag } from \"../events/index.js\";\nimport NDK from \"../index.js\";\nimport User from \"../user/index.js\";\nconst DEFAULT_RELAYS = [\n \"wss://nos.lol\",\n \"wss://relay.nostr.band\",", "score": 0.8324546813964844 }, { "filename": "src/zap/index.ts", "retrieved_chunk": " */\n private relays(): string[] {\n let r: string[] = [];\n if (this.ndk?.pool?.relays) {\n r = this.ndk.pool.urls();\n }\n if (!r.length) {\n r = DEFAULT_RELAYS;\n }\n return r;", "score": 0.8181737661361694 }, { "filename": "src/relay/sets/index.ts", "retrieved_chunk": " */\n static fromRelayUrls(relayUrls: string[], ndk: NDK): NDKRelaySet {\n const relays = new Set<NDKRelay>();\n for (const url of relayUrls) {\n const relay = ndk.pool.relays.get(url);\n if (relay) {\n relays.add(relay);\n }\n }\n return new NDKRelaySet(new Set(relays), ndk);", "score": 0.8173018097877502 }, { "filename": "src/index.ts", "retrieved_chunk": " opts?: NDKSubscriptionOptions,\n relaySet?: NDKRelaySet\n ): Promise<NDKEvent | null> {\n let filter: NDKFilter;\n // if no relayset has been provided, try to get one from the event id\n if (!relaySet && typeof idOrFilter === \"string\") {\n const relays = relaysFromBech32(idOrFilter);\n if (relays.length > 0) {\n relaySet = new NDKRelaySet(new Set<NDKRelay>(relays), this);\n // Make sure we have connected relays in this set", "score": 0.8169811367988586 }, { "filename": "src/relay/sets/calculate.ts", "retrieved_chunk": " const sets: Map<NDKFilter, NDKRelaySet> = new Map();\n filters.forEach((filter) => {\n const set = calculateRelaySetFromFilter(ndk, filter);\n sets.set(filter, set);\n });\n return sets;\n}", "score": 0.798317015171051 } ]
typescript
export function relaysFromBech32(bech32: string): NDKRelay[] {
import { bech32 } from "@scure/base"; import EventEmitter from "eventemitter3"; import { nip57 } from "nostr-tools"; import type { NostrEvent } from "../events/index.js"; import NDKEvent, { NDKTag } from "../events/index.js"; import NDK from "../index.js"; import User from "../user/index.js"; const DEFAULT_RELAYS = [ "wss://nos.lol", "wss://relay.nostr.band", "wss://relay.f7z.io", "wss://relay.damus.io", "wss://nostr.mom", "wss://no.str.cr", ]; interface ZapConstructorParams { ndk: NDK; zappedEvent?: NDKEvent; zappedUser?: User; } type ZapConstructorParamsRequired = Required< Pick<ZapConstructorParams, "zappedEvent"> > & Pick<ZapConstructorParams, "zappedUser"> & ZapConstructorParams; export default class Zap extends EventEmitter { public ndk?: NDK; public zappedEvent?: NDKEvent; public zappedUser: User; public constructor(args: ZapConstructorParamsRequired) { super(); this.ndk = args.ndk; this.zappedEvent = args.zappedEvent; this.zappedUser = args.zappedUser || this.ndk.getUser({ hexpubkey: this.zappedEvent.pubkey }); } public async getZapEndpoint(): Promise<string | undefined> { let lud06: string | undefined; let lud16: string | undefined; let zapEndpoint: string | undefined; let zapEndpointCallback: string | undefined; if (this.zappedEvent) { const zapTag = (await this.zappedEvent.getMatchingTags("zap"))[0]; if (zapTag) { switch (zapTag[2]) { case "lud06": lud06 = zapTag[1]; break; case "lud16": lud16 = zapTag[1]; break; default: throw new Error(`Unknown zap tag ${zapTag}`); } } } if (this.zappedUser && !lud06 && !lud16) { // check if user has a profile, otherwise request it if (!this.zappedUser.profile) { await this.zappedUser.fetchProfile(); } lud06 = (this.zappedUser.profile || {}).lud06; lud16 = (this.zappedUser.profile || {}).lud16; } if (lud16) { const [name, domain] = lud16.split("@"); zapEndpoint = `https://${domain}/.well-known/lnurlp/${name}`; } else if (lud06) { const { words } = bech32.decode(lud06, 1000); const data = bech32.fromWords(words); const utf8Decoder = new TextDecoder("utf-8"); zapEndpoint = utf8Decoder.decode(data); } if (!zapEndpoint) { throw new Error("No zap endpoint found"); } const response = await fetch(zapEndpoint); const body = await response.json(); if (body?.allowsNostr && (body?.nostrPubkey || body?.nostrPubKey)) { zapEndpointCallback = body.callback; } return zapEndpointCallback; } /** * Generates a kind:9734 zap request and returns the payment request * @param amount amount to zap in millisatoshis * @param comment optional comment to include in the zap request * @param extraTags optional extra tags to include in the zap request * @param relays optional relays to ask zapper to publish the zap to * @returns the payment request */ public async createZapRequest( amount: number, // amount to zap in millisatoshis comment?: string,
extraTags?: NDKTag[], relays?: string[] ): Promise<string | null> {
const zapEndpoint = await this.getZapEndpoint(); if (!zapEndpoint) { throw new Error("No zap endpoint found"); } if (!this.zappedEvent) throw new Error("No zapped event found"); const zapRequest = nip57.makeZapRequest({ profile: this.zappedUser.hexpubkey(), // set the event to null since nostr-tools doesn't support nip-33 zaps event: null, amount, comment: comment || "", relays: relays ?? this.relays(), }); // add the event tag if it exists; this supports both 'e' and 'a' tags if (this.zappedEvent) { const tag = this.zappedEvent.tagReference(); if (tag) { zapRequest.tags.push(tag); } } zapRequest.tags.push(["lnurl", zapEndpoint]); const zapRequestEvent = new NDKEvent( this.ndk, zapRequest as NostrEvent ); if (extraTags) { zapRequestEvent.tags = zapRequestEvent.tags.concat(extraTags); } await zapRequestEvent.sign(); const zapRequestNostrEvent = await zapRequestEvent.toNostrEvent(); const response = await fetch( `${zapEndpoint}?` + new URLSearchParams({ amount: amount.toString(), nostr: JSON.stringify(zapRequestNostrEvent), }) ); const body = await response.json(); return body.pr; } /** * @returns the relays to use for the zap request */ private relays(): string[] { let r: string[] = []; if (this.ndk?.pool?.relays) { r = this.ndk.pool.urls(); } if (!r.length) { r = DEFAULT_RELAYS; } return r; } }
src/zap/index.ts
nostr-dev-kit-ndk-ece64e1
[ { "filename": "src/events/index.ts", "retrieved_chunk": " async zap(\n amount: number,\n comment?: string,\n extraTags?: NDKTag[]\n ): Promise<string | null> {\n if (!this.ndk) throw new Error(\"No NDK instance found\");\n this.ndk.assertSigner();\n const zap = new Zap({\n ndk: this.ndk,\n zappedEvent: this,", "score": 0.8969060182571411 }, { "filename": "src/events/index.ts", "retrieved_chunk": " });\n const paymentRequest = await zap.createZapRequest(\n amount,\n comment,\n extraTags\n );\n // await zap.publish(amount);\n return paymentRequest;\n }\n /**", "score": 0.8682740926742554 }, { "filename": "src/events/index.ts", "retrieved_chunk": " return { \"#e\": [this.tagId()] };\n }\n }\n /**\n * Create a zap request for an existing event\n *\n * @param amount The amount to zap in millisatoshis\n * @param comment A comment to add to the zap request\n * @param extraTags Extra tags to add to the zap request\n */", "score": 0.8340004682540894 }, { "filename": "src/zap/invoice.ts", "retrieved_chunk": "import { decode } from \"light-bolt11-decoder\";\nimport NDKEvent, { type NDKEventId, type NostrEvent } from \"../events/index.js\";\nexport interface NDKZapInvoice {\n id?: NDKEventId;\n zapper: string; // pubkey of zapper app\n zappee: string; // pubkey of user sending zap\n zapped: string; // pubkey of user receiving zap\n zappedEvent?: string; // event zapped\n amount: number; // amount zapped in millisatoshis\n comment?: string;", "score": 0.8124066591262817 }, { "filename": "src/zap/invoice.ts", "retrieved_chunk": " const zapInvoice: NDKZapInvoice = {\n id: event.id,\n zapper: event.pubkey,\n zappee: sender,\n zapped: recipient,\n zappedEvent: zappedEventId,\n amount,\n comment: content,\n };\n return zapInvoice;", "score": 0.7937541604042053 } ]
typescript
extraTags?: NDKTag[], relays?: string[] ): Promise<string | null> {
import EventEmitter from "eventemitter3"; import { Filter as NostrFilter, matchFilter, Sub, nip19 } from "nostr-tools"; import { EventPointer } from "nostr-tools/lib/nip19"; import NDKEvent, { NDKEventId } from "../events/index.js"; import NDK from "../index.js"; import { NDKRelay } from "../relay"; import { calculateRelaySetFromFilter } from "../relay/sets/calculate"; import { NDKRelaySet } from "../relay/sets/index.js"; import { queryFullyFilled } from "./utils.js"; export type NDKFilter = NostrFilter; export enum NDKSubscriptionCacheUsage { // Only use cache, don't subscribe to relays ONLY_CACHE = "ONLY_CACHE", // Use cache, if no matches, use relays CACHE_FIRST = "CACHE_FIRST", // Use cache in addition to relays PARALLEL = "PARALLEL", // Skip cache, don't query it ONLY_RELAY = "ONLY_RELAY", } export interface NDKSubscriptionOptions { closeOnEose: boolean; cacheUsage?: NDKSubscriptionCacheUsage; /** * Groupable subscriptions are created with a slight time * delayed to allow similar filters to be grouped together. */ groupable?: boolean; /** * The delay to use when grouping subscriptions, specified in milliseconds. * @default 100 */ groupableDelay?: number; /** * The subscription ID to use for the subscription. */ subId?: string; } /** * Default subscription options. */ export const defaultOpts: NDKSubscriptionOptions = { closeOnEose: true, cacheUsage: NDKSubscriptionCacheUsage.CACHE_FIRST, groupable: true, groupableDelay: 100, }; /** * Represents a subscription to an NDK event stream. * * @event NDKSubscription#event * Emitted when an event is received by the subscription. * @param {NDKEvent} event - The event received by the subscription. * @param {NDKRelay} relay - The relay that received the event. * @param {NDKSubscription} subscription - The subscription that received the event. * * @event NDKSubscription#event:dup * Emitted when a duplicate event is received by the subscription. * @param {NDKEvent} event - The duplicate event received by the subscription. * @param {NDKRelay} relay - The relay that received the event. * @param {number} timeSinceFirstSeen - The time elapsed since the first time the event was seen. * @param {NDKSubscription} subscription - The subscription that received the event. * * @event NDKSubscription#eose - Emitted when all relays have reached the end of the event stream. * @param {NDKSubscription} subscription - The subscription that received EOSE. * * @event NDKSubscription#close - Emitted when the subscription is closed. * @param {NDKSubscription} subscription - The subscription that was closed. */ export class NDKSubscription extends EventEmitter { readonly subId: string; readonly filters: NDKFilter[]; readonly opts: NDKSubscriptionOptions; public relaySet?: NDKRelaySet; public ndk: NDK; public relaySubscriptions: Map<NDKRelay, Sub>; private debug: debug.Debugger; /** * Events that have been seen by the subscription, with the time they were first seen. */ public eventFirstSeen = new Map<NDKEventId, number>(); /** * Relays that have sent an EOSE. */ public eosesSeen = new Set<NDKRelay>(); /** * Events that have been seen by the subscription per relay. */ public eventsPerRelay: Map<NDKRelay, Set<NDKEventId>> = new Map(); public constructor( ndk: NDK, filters: NDKFilter | NDKFilter[], opts?: NDKSubscriptionOptions, relaySet?: NDKRelaySet, subId?: string ) { super(); this.ndk = ndk; this.opts = { ...defaultOpts, ...(opts || {}) }; this.filters = filters instanceof Array ? filters : [filters]; this.subId = subId || opts?.subId || generateFilterId(this.filters[0]); this.relaySet = relaySet; this.relaySubscriptions = new Map<NDKRelay, Sub>(); this.debug = ndk.debug.extend(`subscription:${this.subId}`); // validate that the caller is not expecting a persistent // subscription while using an option that will only hit the cache if ( this.opts.cacheUsage === NDKSubscriptionCacheUsage.ONLY_CACHE && !this.opts.closeOnEose ) { throw new Error( "Cannot use cache-only options with a persistent subscription" ); } } /** * Provides access to the first filter of the subscription for * backwards compatibility. */ get filter(): NDKFilter { return this.filters[0]; } /** * Calculates the groupable ID for this subscription. * * @returns The groupable ID, or null if the subscription is not groupable. */ public groupableId(): string | null { if (!this.opts?.groupable || this.filters.length > 1) { return null; } const filter = this.filters[0]; // Check if there is a kind and no time-based filters const noTimeConstraints = !filter.since && !filter.until; const noLimit = !filter.limit; if (noTimeConstraints && noLimit) { let id = filter.kinds ? filter.kinds.join(",") : ""; const keys = Object.keys(filter || {}) .sort() .join("-"); id += `-${keys}`; return id; } return null; } private shouldQueryCache(): boolean { return this.opts?.cacheUsage !== NDKSubscriptionCacheUsage.ONLY_RELAY; } private shouldQueryRelays(): boolean { return this.opts?.cacheUsage !== NDKSubscriptionCacheUsage.ONLY_CACHE; } private shouldWaitForCache(): boolean { return ( // Must want to close on EOSE; subscriptions // that want to receive further updates must // always hit the relay this.opts.closeOnEose && // Cache adapter must claim to be fast !!this.ndk.cacheAdapter?.locking && // If explicitly told to run in parallel, then // we should not wait for the cache this.opts.cacheUsage !== NDKSubscriptionCacheUsage.PARALLEL ); } /** * Start the subscription. This is the main method that should be called * after creating a subscription. */ public async start(): Promise<void> { let cachePromise; if (this.shouldQueryCache()) { cachePromise = this.startWithCache(); if (this.shouldWaitForCache()) { await cachePromise; // if the cache has a hit, return early if (queryFullyFilled(this)) { this.emit("eose", this); return; } } } if (this.shouldQueryRelays()) { this.startWithRelaySet(); } else { this.emit("eose", this); } return; } public stop(): void { this.relaySubscriptions.forEach((sub) => sub.unsub()); this.relaySubscriptions.clear(); this.emit("close", this); } private async startWithCache(): Promise<void> { if (this.ndk.cacheAdapter?.query) { const promise = this.ndk.cacheAdapter.query(this); if (this.ndk.cacheAdapter.locking) { await promise; } } } private startWithRelaySet(): void { if (!this.relaySet) { this.relaySet = calculateRelaySetFromFilter( this.ndk, this.filters[0] ); } if (this.relaySet) { this.relaySet.subscribe(this); } } // EVENT handling /** * Called when an event is received from a relay or the cache * @param event * @param relay * @param fromCache Whether the event was received from the cache */ public eventReceived( event: NDKEvent,
relay: NDKRelay | undefined, fromCache = false ) {
if (relay) event.relay = relay; if (!relay) relay = event.relay; if (!fromCache && relay) { // track the event per relay let events = this.eventsPerRelay.get(relay); if (!events) { events = new Set(); this.eventsPerRelay.set(relay, events); } events.add(event.id); // mark the event as seen const eventAlreadySeen = this.eventFirstSeen.has(event.id); if (eventAlreadySeen) { const timeSinceFirstSeen = Date.now() - (this.eventFirstSeen.get(event.id) || 0); relay.scoreSlowerEvent(timeSinceFirstSeen); this.emit("event:dup", event, relay, timeSinceFirstSeen, this); return; } if (this.ndk.cacheAdapter) { this.ndk.cacheAdapter.setEvent(event, this.filters[0], relay); } this.eventFirstSeen.set(`${event.id}`, Date.now()); } else { this.eventFirstSeen.set(`${event.id}`, 0); } this.emit("event", event, relay, this); } // EOSE handling private eoseTimeout: ReturnType<typeof setTimeout> | undefined; public eoseReceived(relay: NDKRelay): void { if (this.opts?.closeOnEose) { this.relaySubscriptions.get(relay)?.unsub(); this.relaySubscriptions.delete(relay); // if this was the last relay that needed to EOSE, emit that this subscription is closed if (this.relaySubscriptions.size === 0) { this.emit("close", this); } } this.eosesSeen.add(relay); const hasSeenAllEoses = this.eosesSeen.size === this.relaySet?.size(); if (hasSeenAllEoses) { this.emit("eose"); } else { if (this.eoseTimeout) { clearTimeout(this.eoseTimeout); } this.eoseTimeout = setTimeout(() => { this.emit("eose"); }, 500); } } } /** * Represents a group of subscriptions. * * Events emitted from the group will be emitted from each subscription. */ export class NDKSubscriptionGroup extends NDKSubscription { private subscriptions: NDKSubscription[]; constructor(ndk: NDK, subscriptions: NDKSubscription[]) { const debug = ndk.debug.extend("subscription-group"); const filters = mergeFilters(subscriptions.map((s) => s.filters[0])); super( ndk, filters, subscriptions[0].opts, // TODO: This should be merged subscriptions[0].relaySet // TODO: This should be merged ); this.subscriptions = subscriptions; debug("merged filters", { count: subscriptions.length, mergedFilters: this.filters[0], }); // forward events to the matching subscriptions this.on("event", this.forwardEvent); this.on("event:dup", this.forwardEventDup); this.on("eose", this.forwardEose); this.on("close", this.forwardClose); } private isEventForSubscription( event: NDKEvent, subscription: NDKSubscription ): boolean { const { filters } = subscription; if (!filters) return false; return matchFilter(filters[0], event.rawEvent() as any); // check if there is a filter whose key begins with '#'; if there is, check if the event has a tag with the same key on the first position // of the tags array of arrays and the same value in the second position // for (const key in filter) { // if (key === 'kinds' && filter.kinds!.includes(event.kind!)) return false; // else if (key === 'authors' && filter.authors!.includes(event.pubkey)) return false; // else if (key.startsWith('#')) { // const tagKey = key.slice(1); // const tagValue = filter[key]; // if (event.tags) { // for (const tag of event.tags) { // if (tag[0] === tagKey && tag[1] === tagValue) { // return false; // } // } // } // } // return true; } private forwardEvent(event: NDKEvent, relay: NDKRelay) { for (const subscription of this.subscriptions) { if (!this.isEventForSubscription(event, subscription)) { continue; } subscription.emit("event", event, relay, subscription); } } private forwardEventDup( event: NDKEvent, relay: NDKRelay, timeSinceFirstSeen: number ) { for (const subscription of this.subscriptions) { if (!this.isEventForSubscription(event, subscription)) { continue; } subscription.emit( "event:dup", event, relay, timeSinceFirstSeen, subscription ); } } private forwardEose() { for (const subscription of this.subscriptions) { subscription.emit("eose", subscription); } } private forwardClose() { for (const subscription of this.subscriptions) { subscription.emit("close", subscription); } } } /** * Go through all the passed filters, which should be * relatively similar, and merge them. */ export function mergeFilters(filters: NDKFilter[]): NDKFilter { const result: any = {}; filters.forEach((filter) => { Object.entries(filter).forEach(([key, value]) => { if (Array.isArray(value)) { if (result[key] === undefined) { result[key] = [...value]; } else { result[key] = Array.from( new Set([...result[key], ...value]) ); } } else { result[key] = value; } }); }); return result as NDKFilter; } /** * Creates a valid nostr filter from an event id or a NIP-19 bech32. */ export function filterFromId(id: string): NDKFilter { let decoded; try { decoded = nip19.decode(id); switch (decoded.type) { case "nevent": return { ids: [decoded.data.id] }; case "note": return { ids: [decoded.data] }; case "naddr": return { authors: [decoded.data.pubkey], "#d": [decoded.data.identifier], kinds: [decoded.data.kind], }; } } catch (e) {} return { ids: [id] }; } /** * Returns the specified relays from a NIP-19 bech32. * * @param bech32 The NIP-19 bech32. */ export function relaysFromBech32(bech32: string): NDKRelay[] { try { const decoded = nip19.decode(bech32); if (["naddr", "nevent"].includes(decoded?.type)) { const data = decoded.data as unknown as EventPointer; if (data?.relays) { return data.relays.map((r: string) => new NDKRelay(r)); } } } catch (e) { /* empty */ } return []; } /** * Generates a random filter id, based on the filter keys. */ function generateFilterId(filter: NDKFilter) { const keys = Object.keys(filter) || []; const subId = []; for (const key of keys) { if (key === "kinds") { const v = [key, filter.kinds!.join(",")]; subId.push(v.join(":")); } else { subId.push(key); } } subId.push(Math.floor(Math.random() * 999999999).toString()); return subId.join("-"); }
src/subscription/index.ts
nostr-dev-kit-ndk-ece64e1
[ { "filename": "src/events/index.ts", "retrieved_chunk": " * The relay that this event was first received from.\n */\n public relay: NDKRelay | undefined;\n constructor(ndk?: NDK, event?: NostrEvent) {\n super();\n this.ndk = ndk;\n this.created_at = event?.created_at;\n this.content = event?.content || \"\";\n this.tags = event?.tags || [];\n this.id = event?.id || \"\";", "score": 0.8491688966751099 }, { "filename": "src/relay/sets/calculate.ts", "retrieved_chunk": " * @param event {Event}\n * @returns Promise<NDKRelaySet>\n */\nexport function calculateRelaySetFromEvent(\n ndk: NDK,\n event: Event\n): NDKRelaySet {\n const relays: Set<NDKRelay> = new Set();\n ndk.pool?.relays.forEach((relay) => relays.add(relay));\n return new NDKRelaySet(relays, ndk);", "score": 0.8404048681259155 }, { "filename": "src/cache/index.ts", "retrieved_chunk": "import NDKEvent from \"../events/index.js\";\nimport { NDKRelay } from \"../relay/index.js\";\nimport { NDKFilter, NDKSubscription } from \"../subscription/index.js\";\nexport interface NDKCacheAdapter {\n /**\n * Whether this cache adapter is expected to be fast.\n * If this is true, the cache will be queried before the relays.\n * When this is false, the cache will be queried in addition to the relays.\n */\n locking: boolean;", "score": 0.8302488923072815 }, { "filename": "src/index.ts", "retrieved_chunk": " { ...(opts || {}), closeOnEose: true },\n relaySet,\n false\n );\n const onEvent = (event: NDKEvent) => {\n const dedupKey = event.deduplicationKey();\n const existingEvent = events.get(dedupKey);\n if (existingEvent) {\n event = dedupEvent(existingEvent, event);\n }", "score": 0.8247467279434204 }, { "filename": "src/index.ts", "retrieved_chunk": "import debug from \"debug\";\nimport EventEmitter from \"eventemitter3\";\nimport { NDKCacheAdapter } from \"./cache/index.js\";\nimport dedupEvent from \"./events/dedup.js\";\nimport NDKEvent from \"./events/index.js\";\nimport type { NDKRelay } from \"./relay/index.js\";\nimport { NDKPool } from \"./relay/pool/index.js\";\nimport { calculateRelaySetFromEvent } from \"./relay/sets/calculate.js\";\nimport { NDKRelaySet } from \"./relay/sets/index.js\";\nimport { correctRelaySet } from \"./relay/sets/utils.js\";", "score": 0.8235296010971069 } ]
typescript
relay: NDKRelay | undefined, fromCache = false ) {
import debug from "debug"; import EventEmitter from "eventemitter3"; import { Relay, relayInit, Sub } from "nostr-tools"; import "websocket-polyfill"; import NDKEvent, { NDKTag, NostrEvent } from "../events/index.js"; import { NDKSubscription } from "../subscription/index.js"; import User from "../user/index.js"; import { NDKRelayScore } from "./score.js"; export enum NDKRelayStatus { CONNECTING, CONNECTED, DISCONNECTING, DISCONNECTED, RECONNECTING, FLAPPING, } export interface NDKRelayConnectionStats { /** * The number of times a connection has been attempted. */ attempts: number; /** * The number of times a connection has been successfully established. */ success: number; /** * The durations of the last 100 connections in milliseconds. */ durations: number[]; /** * The time the current connection was established in milliseconds. */ connectedAt?: number; } /** * The NDKRelay class represents a connection to a relay. * * @emits NDKRelay#connect * @emits NDKRelay#disconnect * @emits NDKRelay#notice * @emits NDKRelay#event * @emits NDKRelay#published when an event is published to the relay * @emits NDKRelay#publish:failed when an event fails to publish to the relay * @emits NDKRelay#eose */ export class NDKRelay extends EventEmitter { readonly url: string; readonly scores
: Map<User, NDKRelayScore>;
private relay: Relay; private _status: NDKRelayStatus; private connectedAt?: number; private _connectionStats: NDKRelayConnectionStats = { attempts: 0, success: 0, durations: [], }; public complaining = false; private debug: debug.Debugger; /** * Active subscriptions this relay is connected to */ public activeSubscriptions = new Set<NDKSubscription>(); public constructor(url: string) { super(); this.url = url; this.relay = relayInit(url); this.scores = new Map<User, NDKRelayScore>(); this._status = NDKRelayStatus.DISCONNECTED; this.debug = debug(`ndk:relay:${url}`); this.relay.on("connect", () => { this.updateConnectionStats.connected(); this._status = NDKRelayStatus.CONNECTED; this.emit("connect"); }); this.relay.on("disconnect", () => { this.updateConnectionStats.disconnected(); if (this._status === NDKRelayStatus.CONNECTED) { this._status = NDKRelayStatus.DISCONNECTED; this.handleReconnection(); } this.emit("disconnect"); }); this.relay.on("notice", (notice: string) => this.handleNotice(notice)); } /** * Evaluates the connection stats to determine if the relay is flapping. */ private isFlapping(): boolean { const durations = this._connectionStats.durations; if (durations.length < 10) return false; const sum = durations.reduce((a, b) => a + b, 0); const avg = sum / durations.length; const variance = durations .map((x) => Math.pow(x - avg, 2)) .reduce((a, b) => a + b, 0) / durations.length; const stdDev = Math.sqrt(variance); const isFlapping = stdDev < 1000; return isFlapping; } /** * Called when the relay is unexpectedly disconnected. */ private handleReconnection() { if (this.isFlapping()) { this.emit("flapping", this, this._connectionStats); this._status = NDKRelayStatus.FLAPPING; } if (this.connectedAt && Date.now() - this.connectedAt < 5000) { setTimeout(() => this.connect(), 60000); } else { this.connect(); } } get status(): NDKRelayStatus { return this._status; } /** * Connects to the relay. */ public async connect(): Promise<void> { try { this.updateConnectionStats.attempt(); this._status = NDKRelayStatus.CONNECTING; await this.relay.connect(); } catch (e) { this.debug("Failed to connect", e); this._status = NDKRelayStatus.DISCONNECTED; throw e; } } /** * Disconnects from the relay. */ public disconnect(): void { this._status = NDKRelayStatus.DISCONNECTING; this.relay.close(); } async handleNotice(notice: string) { // This is a prototype; if the relay seems to be complaining // remove it from relay set selection for a minute. if (notice.includes("oo many") || notice.includes("aximum")) { this.disconnect(); // fixme setTimeout(() => this.connect(), 2000); this.debug(this.relay.url, "Relay complaining?", notice); // this.complaining = true; // setTimeout(() => { // this.complaining = false; // console.log(this.relay.url, 'Reactivate relay'); // }, 60000); } this.emit("notice", this, notice); } /** * Subscribes to a subscription. */ public subscribe(subscription: NDKSubscription): Sub { const { filters } = subscription; const sub = this.relay.sub(filters, { id: subscription.subId, }); this.debug(`Subscribed to ${JSON.stringify(filters)}`); sub.on("event", (event: NostrEvent) => { const e = new NDKEvent(undefined, event); e.relay = this; subscription.eventReceived(e, this); }); sub.on("eose", () => { subscription.eoseReceived(this); }); const unsub = sub.unsub; sub.unsub = () => { this.debug(`Unsubscribing from ${JSON.stringify(filters)}`); this.activeSubscriptions.delete(subscription); unsub(); }; this.activeSubscriptions.add(subscription); subscription.on("close", () => { this.activeSubscriptions.delete(subscription); }); return sub; } /** * Publishes an event to the relay with an optional timeout. * * If the relay is not connected, the event will be published when the relay connects, * unless the timeout is reached before the relay connects. * * @param event The event to publish * @param timeoutMs The timeout for the publish operation in milliseconds * @returns A promise that resolves when the event has been published or rejects if the operation times out */ public async publish(event: NDKEvent, timeoutMs = 2500): Promise<boolean> { if (this.status === NDKRelayStatus.CONNECTED) { return this.publishEvent(event, timeoutMs); } else { this.once("connect", () => { this.publishEvent(event, timeoutMs); }); return true; } } private async publishEvent( event: NDKEvent, timeoutMs?: number ): Promise<boolean> { const nostrEvent = await event.toNostrEvent(); const publish = this.relay.publish(nostrEvent as any); let publishTimeout: NodeJS.Timeout | number; const publishPromise = new Promise<boolean>((resolve, reject) => { publish .then(() => { clearTimeout(publishTimeout as unknown as NodeJS.Timeout); this.emit("published", event); resolve(true); }) .catch((err) => { clearTimeout(publishTimeout as NodeJS.Timeout); this.debug("Publish failed", err, event.id); this.emit("publish:failed", event, err); reject(err); }); }); // If no timeout is specified, just return the publish promise if (!timeoutMs) { return publishPromise; } // Create a promise that rejects after timeoutMs milliseconds const timeoutPromise = new Promise<boolean>((_, reject) => { publishTimeout = setTimeout(() => { this.debug("Publish timed out", event.rawEvent()); this.emit("publish:failed", event, "Timeout"); reject(new Error("Publish operation timed out")); }, timeoutMs); }); // wait for either the publish operation to complete or the timeout to occur return Promise.race([publishPromise, timeoutPromise]); } /** * Called when this relay has responded with an event but * wasn't the fastest one. * @param timeDiffInMs The time difference in ms between the fastest and this relay in milliseconds */ // eslint-disable-next-line @typescript-eslint/no-unused-vars public scoreSlowerEvent(timeDiffInMs: number): void { // TODO } /** * Utility functions to update the connection stats. */ private updateConnectionStats = { connected: () => { this._connectionStats.success++; this._connectionStats.connectedAt = Date.now(); }, disconnected: () => { if (this._connectionStats.connectedAt) { this._connectionStats.durations.push( Date.now() - this._connectionStats.connectedAt ); if (this._connectionStats.durations.length > 100) { this._connectionStats.durations.shift(); } } this._connectionStats.connectedAt = undefined; }, attempt: () => { this._connectionStats.attempts++; }, }; /** * Returns the connection stats. */ get connectionStats(): NDKRelayConnectionStats { return this._connectionStats; } public tagReference(marker?: string): NDKTag { const tag = ["r", this.relay.url]; if (marker) { tag.push(marker); } return tag; } }
src/relay/index.ts
nostr-dev-kit-ndk-ece64e1
[ { "filename": "src/relay/score.ts", "retrieved_chunk": "// TODO this will probably get more sophisticated\nexport type NDKRelayScore = number;", "score": 0.8380385041236877 }, { "filename": "src/relay/pool/index.ts", "retrieved_chunk": " public relays = new Map<string, NDKRelay>();\n private debug: debug.Debugger;\n private temporaryRelayTimers = new Map<string, NodeJS.Timeout>();\n public constructor(relayUrls: string[] = [], ndk: NDK) {\n super();\n this.debug = ndk.debug.extend(\"pool\");\n for (const relayUrl of relayUrls) {\n const relay = new NDKRelay(relayUrl);\n this.addRelay(relay, false);\n }", "score": 0.8352271318435669 }, { "filename": "src/index.ts", "retrieved_chunk": " devWriteRelayUrls?: string[];\n signer?: NDKSigner;\n cacheAdapter?: NDKCacheAdapter;\n debug?: debug.Debugger;\n}\nexport interface GetUserParams extends NDKUserParams {\n npub?: string;\n hexpubkey?: string;\n}\nexport default class NDK extends EventEmitter {", "score": 0.8328016400337219 }, { "filename": "src/relay/sets/calculate.ts", "retrieved_chunk": "): NDKRelaySet {\n const relays: Set<NDKRelay> = new Set();\n ndk.pool?.relays.forEach((relay) => {\n if (!relay.complaining) {\n relays.add(relay);\n } else {\n ndk.debug(`Relay ${relay.url} is complaining, not adding to set`);\n }\n });\n return new NDKRelaySet(relays, ndk);", "score": 0.8199835419654846 }, { "filename": "src/relay/pool/index.ts", "retrieved_chunk": "import debug from \"debug\";\nimport EventEmitter from \"eventemitter3\";\nimport NDK from \"../../index.js\";\nimport { NDKRelay, NDKRelayStatus } from \"../index.js\";\nexport type NDKPoolStats = {\n total: number;\n connected: number;\n disconnected: number;\n connecting: number;\n};", "score": 0.8155430555343628 } ]
typescript
: Map<User, NDKRelayScore>;
import { CommandModule } from "yargs"; import { logSuccess } from "./login"; import { accessTokenFromCookies, xsrfTokenFromCookies } from "../utils/cookies"; import { doCredentialsExist, persistCredentials } from "../utils/credentials"; import { getRequest, postRequest } from "../utils/networking"; import { logDAU } from "../utils/telemetry"; import { isEmailValid } from "../utils/validation"; const axios = require("axios"); const inquirer = require("inquirer"); const ora = require("ora"); const command = "signup"; const describe = "Create a Retool account."; const builder = {}; // eslint-disable-next-line @typescript-eslint/no-unused-vars const handler = async function (argv: any) { // Ask user if they want to overwrite existing credentials. if (doCredentialsExist()) { const { overwrite } = await inquirer.prompt([ { name: "overwrite", message: "You're already logged in. Do you want to log out and create a new account?", type: "confirm", }, ]); if (!overwrite) { return; } } // Step 1: Collect a valid email/password. let email, password, name, org; while (!email) { email = await collectEmail(); } while (!password) { password = await colllectPassword(); } // Step 2: Call signup endpoint, get cookies. const spinner = ora( "Verifying that the email and password are valid on the server" ).start(); const signupResponse = await postRequest( `https://login.retool.com/api/signup`, { email, password, planKey: "free", } ); spinner.stop(); const accessToken = accessTokenFromCookies( signupResponse.headers["set-cookie"] ); const xsrfToken = xsrfTokenFromCookies(signupResponse.headers["set-cookie"]); if (!accessToken || !xsrfToken) { if (process.env.DEBUG) { console.log(signupResponse); } console.log( "Error creating account, please try again or signup at https://login.retool.com/auth/signup?plan=free." ); return; } axios.defaults.headers["x-xsrf-token"] = xsrfToken; axios.defaults.headers.cookie = `accessToken=${accessToken};`; // Step 3: Collect a valid name/org. while (!name) { name = await collectName(); } while (!org) { org = await collectOrg(); } // Step 4: Initialize organization. await postRequest( `https://login.retool.com/api/organization/admin/initializeOrganization`, { subdomain: org, } ); // Step 5: Persist credentials const origin = `https://${org}.retool.com`;
const userRes = await getRequest(`${origin}/api/user`);
persistCredentials({ origin, accessToken, xsrf: xsrfToken, firstName: userRes.data.user?.firstName, lastName: userRes.data.user?.lastName, email: userRes.data.user?.email, telemetryEnabled: true, }); logSuccess(); await logDAU(); }; async function collectEmail(): Promise<string | undefined> { const { email } = await inquirer.prompt([ { name: "email", message: "What is your email?", type: "input", }, ]); if (!isEmailValid(email)) { console.log("Invalid email, try again."); return; } return email; } async function colllectPassword(): Promise<string | undefined> { const { password } = await inquirer.prompt([ { name: "password", message: "Please create a password (min 8 characters):", type: "password", }, ]); const { confirmedPassword } = await inquirer.prompt([ { name: "confirmedPassword", message: "Please confirm password:", type: "password", }, ]); if (password.length < 8) { console.log("Password must be at least 8 characters long, try again."); return; } if (password !== confirmedPassword) { console.log("Passwords do not match, try again."); return; } return password; } async function collectName(): Promise<string | undefined> { const { name } = await inquirer.prompt([ { name: "name", message: "What is your first and last name?", type: "input", }, ]); if (!name || name.length === 0) { console.log("Invalid name, try again."); return; } const parts = name.split(" "); const changeNameResponse = await postRequest( `https://login.retool.com/api/user/changeName`, { firstName: parts[0], lastName: parts[1], }, false ); if (!changeNameResponse) { return; } return name; } async function collectOrg(): Promise<string | undefined> { let { org } = await inquirer.prompt([ { name: "org", message: "What is your organization name? Leave blank to generate a random name.", type: "input", }, ]); if (!org || org.length === 0) { // Org must start with letter, append a random string after it. // https://stackoverflow.com/a/8084248 org = "z" + (Math.random() + 1).toString(36).substring(2); } const checkSubdomainAvailabilityResponse = await getRequest( `https://login.retool.com/api/organization/admin/checkSubdomainAvailability?subdomain=${org}`, false ); if (!checkSubdomainAvailabilityResponse.status) { return; } return org; } const commandModule: CommandModule = { command, describe, builder, handler }; export default commandModule;
src/commands/signup.ts
tryretool-retool-cli-91b2c68
[ { "filename": "src/commands/login.ts", "retrieved_chunk": " // Step 1: Hit /api/login with email and password.\n const login = await postRequest(`${loginOrigin}/api/login`, {\n email,\n password,\n });\n const { authUrl, authorizationToken } = login.data;\n if (!authUrl || !authorizationToken) {\n console.log(\"Error logging in, please try again\");\n return;\n }", "score": 0.8598932027816772 }, { "filename": "src/commands/login.ts", "retrieved_chunk": " // Step 2: Hit /auth/saveAuth with authorizationToken.\n const authResponse = await postRequest(\n localhost ? `${loginOrigin}${authUrl}` : authUrl,\n {\n authorizationToken,\n },\n true,\n {\n origin: loginOrigin,\n }", "score": 0.8500735759735107 }, { "filename": "src/utils/credentials.ts", "retrieved_chunk": " let credentials = getCredentials();\n if (!credentials) {\n spinner.stop();\n console.log(\n `Error: No credentials found. To log in, run: \\`retool login\\``\n );\n process.exit(1);\n }\n axios.defaults.headers[\"x-xsrf-token\"] = credentials.xsrf;\n axios.defaults.headers.cookie = `accessToken=${credentials.accessToken};`;", "score": 0.8273262977600098 }, { "filename": "src/commands/login.ts", "retrieved_chunk": " telemetryEnabled: true,\n });\n logSuccess();\n res.sendFile(path.join(__dirname, \"../loginPages/loginSuccess.html\"));\n server_online = false;\n });\n const server = app.listen(3020);\n // Step 1: Open up the google SSO page in the browser.\n // Step 2: User accepts the SSO request.\n open(`https://login.retool.com/googlelogin?retoolCliRedirect=true`);", "score": 0.8259477019309998 }, { "filename": "src/commands/login.ts", "retrieved_chunk": " const xsrfToken = xsrfTokenFromCookies(authResponse.headers[\"set-cookie\"]);\n // Step 3: Persist the credentials.\n if (redirectUrl?.origin && accessToken && xsrfToken) {\n persistCredentials({\n origin: redirectUrl.origin,\n accessToken,\n xsrf: xsrfToken,\n firstName: authResponse.data.user?.firstName,\n lastName: authResponse.data.user?.lastName,\n email: authResponse.data.user?.email,", "score": 0.8238883018493652 } ]
typescript
const userRes = await getRequest(`${origin}/api/user`);
import { CommandModule } from "yargs"; import { createAppForTable, deleteApp } from "../utils/apps"; import { Credentials, getAndVerifyCredentialsWithRetoolDB, } from "../utils/credentials"; import { getRequest, postRequest } from "../utils/networking"; import { collectColumnNames, collectTableName, createTable, createTableFromCSV, deleteTable, generateDataWithGPT, } from "../utils/table"; import type { DBInfoPayload } from "../utils/table"; import { logDAU } from "../utils/telemetry"; import { deleteWorkflow, generateCRUDWorkflow } from "../utils/workflows"; const inquirer = require("inquirer"); const command = "scaffold"; const describe = "Scaffold a Retool DB table, CRUD Workflow, and App."; const builder: CommandModule["builder"] = { name: { alias: "n", describe: `Name of table to scaffold. Usage: retool scaffold -n <table_name>`, type: "string", nargs: 1, }, columns: { alias: "c", describe: `Column names in DB to scaffold. Usage: retool scaffold -c <col1> <col2>`, type: "array", }, delete: { alias: "d", describe: `Delete a table, Workflow and App created via scaffold. Usage: retool scaffold -d <db_name>`, type: "string", nargs: 1, }, "from-csv": { alias: "f", describe: `Create a table, Workflow and App from a CSV file. Usage: retool scaffold -f <path-to-csv>`, type: "array", }, "no-workflow": { describe: `Modifier to avoid generating Workflow. Usage: retool scaffold --no-workflow`, type: "boolean", }, }; const handler = async function (argv: any) { const credentials = await getAndVerifyCredentialsWithRetoolDB(); // fire and forget void logDAU(credentials); // Handle `retool scaffold -d <db_name>` if (argv.delete) { const tableName = argv.delete; const workflowName = `${tableName} CRUD Workflow`; // Confirm deletion. const { confirm } = await inquirer.prompt([ { name: "confirm", message: `Are you sure you want to delete ${tableName} table, CRUD workflow and app?`, type: "confirm", }, ]); if (!confirm) { process.exit(0); } //TODO: Could be parallelized. //TODO: Verify existence before trying to delete. await deleteTable(tableName, credentials, false); await deleteWorkflow(workflowName, credentials, false); await deleteApp(`${tableName} App`, credentials, false); } // Handle `retool scaffold -f <path-to-csv>` else if (argv.f) { const csvFileNames = argv.f; for (const csvFileName of csvFileNames) { const { tableName, colNames } = await createTableFromCSV( csvFileName, credentials, false, false ); if (!argv["no-workflow"]) { console.log("\n"); await generateCRUDWorkflow(tableName, credentials); } console.log("\n"); const searchColumnName = colNames.length > 0 ? colNames[0] : "id"; await createAppForTable( `${tableName} App`, tableName, searchColumnName, credentials ); console.log(""); } } // Handle `retool scaffold` else { let tableName = argv.name; let colNames = argv.columns; if (!tableName || tableName.length == 0) { tableName = await collectTableName(); } if (!colNames || colNames.length == 0) { colNames = await collectColumnNames(); } await createTable(tableName, colNames, undefined, credentials, false); // Fire and forget void insertSampleData(tableName, credentials); if (!argv["no-workflow"]) { console.log("\n"); await generateCRUDWorkflow(tableName, credentials); } console.log("\n"); const searchColumnName = colNames.length > 0 ? colNames[0] : "id"; await createAppForTable( `${tableName} App`, tableName, searchColumnName, credentials ); } }; const insertSampleData = async function ( tableName: string, credentials: Credentials ) { const infoRes = await
getRequest( `${credentials.origin}/api/grid/${credentials.gridId}/table/${tableName}/info`, false );
const retoolDBInfo: DBInfoPayload = infoRes.data; const { fields } = retoolDBInfo.tableInfo; const generatedData = await generateDataWithGPT( retoolDBInfo, fields, 0, credentials, false ); if (generatedData) { await postRequest( `${credentials.origin}/api/grid/${credentials.gridId}/action`, { kind: "BulkInsertIntoTable", tableName: tableName, additions: generatedData, } ); } }; const commandModule: CommandModule = { command, describe, builder, handler, }; export default commandModule;
src/commands/scaffold.ts
tryretool-retool-cli-91b2c68
[ { "filename": "src/utils/table.ts", "retrieved_chunk": " const infoResponse = await getRequest(\n `${credentials.origin}/api/grid/${credentials.gridId}/table/${tableName}/info`\n );\n spinner.stop();\n const { tableInfo } = infoResponse.data;\n if (tableInfo) {\n return tableInfo;\n }\n}\nexport async function deleteTable(", "score": 0.8858531713485718 }, { "filename": "src/commands/db.ts", "retrieved_chunk": " // Verify that the provided db name exists.\n const tableName = argv.gendata;\n await verifyTableExists(tableName, credentials);\n // Fetch Retool DB schema and data.\n const spinner = ora(`Fetching ${tableName} metadata`).start();\n const infoReq = getRequest(\n `${credentials.origin}/api/grid/${credentials.gridId}/table/${tableName}/info`\n );\n const dataReq = postRequest(\n `${credentials.origin}/api/grid/${credentials.gridId}/table/${tableName}/data`,", "score": 0.8762341141700745 }, { "filename": "src/commands/db.ts", "retrieved_chunk": " );\n }\n // Insert to Retool DB.\n const bulkInsertRes = await postRequest(\n `${credentials.origin}/api/grid/${credentials.gridId}/action`,\n {\n kind: \"BulkInsertIntoTable\",\n tableName: tableName,\n additions: generatedData,\n }", "score": 0.8618407845497131 }, { "filename": "src/utils/table.ts", "retrieved_chunk": " await postRequest(\n `${credentials.origin}/api/grid/${credentials.gridId}/action`,\n {\n kind: \"DeleteTable\",\n payload: {\n table: tableName,\n },\n }\n );\n spinner.stop();", "score": 0.8553228378295898 }, { "filename": "src/utils/table.ts", "retrieved_chunk": " `${credentials.origin}/api/grid/${credentials.gridId}/action`,\n {\n ...payload,\n }\n );\n spinner.stop();\n if (!createTableResult.data.success) {\n console.log(\"Error creating table in RetoolDB.\");\n console.log(createTableResult.data);\n process.exit(1);", "score": 0.8497548699378967 } ]
typescript
getRequest( `${credentials.origin}/api/grid/${credentials.gridId}/table/${tableName}/info`, false );
import { Credentials } from "./credentials"; import { getRequest, postRequest } from "./networking"; export type ResourceByEnv = Record<string, Resource>; export type Resource = { displayName: string; id: number; name: string; type: string; environment: string; environmentId: string; uuid: string; organizationId: number; resourceFolderId: number; }; export async function getResourceByName( resourceName: string, credentials: Credentials ): Promise<ResourceByEnv> { const getResourceResult = await getRequest( `${credentials.origin}/api/resources/names/${resourceName}` ); const { resourceByEnv } = getResourceResult.data; if (!resourceByEnv) { console.log("Error finding resource by that id."); console.log(getResourceResult.data); process.exit(1); } else { return resourceByEnv; } } export async function createResource({ resourceType, credentials, displayName, resourceFolderId, resourceOptions, }: { resourceType: string;
credentials: Credentials;
displayName?: string; resourceFolderId?: number; resourceOptions?: Record<string, any>; }): Promise<Resource> { const createResourceResult = await postRequest( `${credentials.origin}/api/resources/`, { type: resourceType, displayName, resourceFolderId, options: resourceOptions ? resourceOptions : {}, }, false, {}, false ); const resource = createResourceResult.data; if (!resource) { throw new Error("Error creating resource."); } else { return resource; } }
src/utils/resources.ts
tryretool-retool-cli-91b2c68
[ { "filename": "src/commands/rpc.ts", "retrieved_chunk": " type: \"input\",\n validate: async (displayName: string) => {\n try {\n const resource = await createResource({\n resourceType: \"retoolSdk\",\n credentials,\n resourceOptions: {\n requireExplicitVersion: false,\n },\n displayName,", "score": 0.844801664352417 }, { "filename": "src/utils/playgroundQuery.ts", "retrieved_chunk": " organizationId: number;\n ownerId: number;\n saveId: number;\n template: Record<string, any>;\n resourceId: number;\n resourceUuid: string;\n adhocResourceType: string;\n};\nexport async function createPlaygroundQuery(\n resourceId: number,", "score": 0.8190720081329346 }, { "filename": "src/utils/apps.ts", "retrieved_chunk": " createdAt: string;\n updatedAt: string;\n folderType: string;\n accessLevel: string;\n};\nexport async function createApp(\n appName: string,\n credentials: Credentials\n): Promise<App | undefined> {\n const spinner = ora(\"Creating App\").start();", "score": 0.8180678486824036 }, { "filename": "src/commands/rpc.ts", "retrieved_chunk": " ])) as { destinationPath: string };\n const githubUrl =\n \"https://api.github.com/repos/tryretool/retool-examples/tarball/main\";\n const subfolderPath = \"hello_world/\" + languageType;\n await downloadGithubSubfolder(githubUrl, subfolderPath, destinationPath);\n const spinner = ora(\n \"Installing dependencies and creating starter code to connect to Retool...\"\n ).start();\n const queryResult = await createPlaygroundQuery(resourceId, credentials);\n const envVariables = {", "score": 0.799485445022583 }, { "filename": "src/utils/workflows.ts", "retrieved_chunk": "import { Credentials } from \"./credentials\";\nimport { deleteRequest, getRequest, postRequest } from \"./networking\";\nconst chalk = require(\"chalk\");\nconst inquirer = require(\"inquirer\");\nconst ora = require(\"ora\");\nexport type Workflow = {\n id: string; //UUID\n name: string;\n folderId: number;\n isEnabled: boolean;", "score": 0.789823055267334 } ]
typescript
credentials: Credentials;
import { CommandModule } from "yargs"; import { createAppForTable, deleteApp } from "../utils/apps"; import { Credentials, getAndVerifyCredentialsWithRetoolDB, } from "../utils/credentials"; import { getRequest, postRequest } from "../utils/networking"; import { collectColumnNames, collectTableName, createTable, createTableFromCSV, deleteTable, generateDataWithGPT, } from "../utils/table"; import type { DBInfoPayload } from "../utils/table"; import { logDAU } from "../utils/telemetry"; import { deleteWorkflow, generateCRUDWorkflow } from "../utils/workflows"; const inquirer = require("inquirer"); const command = "scaffold"; const describe = "Scaffold a Retool DB table, CRUD Workflow, and App."; const builder: CommandModule["builder"] = { name: { alias: "n", describe: `Name of table to scaffold. Usage: retool scaffold -n <table_name>`, type: "string", nargs: 1, }, columns: { alias: "c", describe: `Column names in DB to scaffold. Usage: retool scaffold -c <col1> <col2>`, type: "array", }, delete: { alias: "d", describe: `Delete a table, Workflow and App created via scaffold. Usage: retool scaffold -d <db_name>`, type: "string", nargs: 1, }, "from-csv": { alias: "f", describe: `Create a table, Workflow and App from a CSV file. Usage: retool scaffold -f <path-to-csv>`, type: "array", }, "no-workflow": { describe: `Modifier to avoid generating Workflow. Usage: retool scaffold --no-workflow`, type: "boolean", }, }; const handler = async function (argv: any) { const credentials = await getAndVerifyCredentialsWithRetoolDB(); // fire and forget void logDAU(credentials); // Handle `retool scaffold -d <db_name>` if (argv.delete) { const tableName = argv.delete; const workflowName = `${tableName} CRUD Workflow`; // Confirm deletion. const { confirm } = await inquirer.prompt([ { name: "confirm", message: `Are you sure you want to delete ${tableName} table, CRUD workflow and app?`, type: "confirm", }, ]); if (!confirm) { process.exit(0); } //TODO: Could be parallelized. //TODO: Verify existence before trying to delete. await deleteTable(tableName, credentials, false); await deleteWorkflow(workflowName, credentials, false); await deleteApp(`${tableName} App`, credentials, false); } // Handle `retool scaffold -f <path-to-csv>` else if (argv.f) { const csvFileNames = argv.f; for (const csvFileName of csvFileNames) { const { tableName, colNames } = await createTableFromCSV( csvFileName, credentials, false, false ); if (!argv["no-workflow"]) { console.log("\n");
await generateCRUDWorkflow(tableName, credentials);
} console.log("\n"); const searchColumnName = colNames.length > 0 ? colNames[0] : "id"; await createAppForTable( `${tableName} App`, tableName, searchColumnName, credentials ); console.log(""); } } // Handle `retool scaffold` else { let tableName = argv.name; let colNames = argv.columns; if (!tableName || tableName.length == 0) { tableName = await collectTableName(); } if (!colNames || colNames.length == 0) { colNames = await collectColumnNames(); } await createTable(tableName, colNames, undefined, credentials, false); // Fire and forget void insertSampleData(tableName, credentials); if (!argv["no-workflow"]) { console.log("\n"); await generateCRUDWorkflow(tableName, credentials); } console.log("\n"); const searchColumnName = colNames.length > 0 ? colNames[0] : "id"; await createAppForTable( `${tableName} App`, tableName, searchColumnName, credentials ); } }; const insertSampleData = async function ( tableName: string, credentials: Credentials ) { const infoRes = await getRequest( `${credentials.origin}/api/grid/${credentials.gridId}/table/${tableName}/info`, false ); const retoolDBInfo: DBInfoPayload = infoRes.data; const { fields } = retoolDBInfo.tableInfo; const generatedData = await generateDataWithGPT( retoolDBInfo, fields, 0, credentials, false ); if (generatedData) { await postRequest( `${credentials.origin}/api/grid/${credentials.gridId}/action`, { kind: "BulkInsertIntoTable", tableName: tableName, additions: generatedData, } ); } }; const commandModule: CommandModule = { command, describe, builder, handler, }; export default commandModule;
src/commands/scaffold.ts
tryretool-retool-cli-91b2c68
[ { "filename": "src/commands/db.ts", "retrieved_chunk": " // Handle `retool db --upload <path-to-csv>`\n if (argv.upload) {\n await createTableFromCSV(argv.upload, credentials, true, true);\n }\n // Handle `retool db --create`\n else if (argv.create) {\n const tableName = await collectTableName();\n const colNames = await collectColumnNames();\n await createTable(tableName, colNames, undefined, credentials, true);\n }", "score": 0.8658169507980347 }, { "filename": "src/commands/db.ts", "retrieved_chunk": " }\n // Handle `retool db --delete <table-name>`\n else if (argv.delete) {\n const tableNames = argv.delete;\n for (const tableName of tableNames) {\n await deleteTable(tableName, credentials, true);\n }\n }\n // Handle `retool db --gendata <table-name>`\n else if (argv.gendata) {", "score": 0.8551702499389648 }, { "filename": "src/utils/table.ts", "retrieved_chunk": " }/${tableName}?env=production`\n );\n if (credentials.hasConnectionString && printConnectionString) {\n await logConnectionStringDetails();\n }\n }\n}\nexport async function createTableFromCSV(\n csvFilePath: string,\n credentials: Credentials,", "score": 0.8492631316184998 }, { "filename": "src/commands/workflows.ts", "retrieved_chunk": " printWorkflows(workflows);\n }\n }\n }\n // Handle `retool workflows -d <workflow-name>`\n else if (argv.delete) {\n const workflowNames = argv.delete;\n for (const workflowName of workflowNames) {\n await deleteWorkflow(workflowName, credentials, true);\n }", "score": 0.8484591841697693 }, { "filename": "src/utils/table.ts", "retrieved_chunk": " // Remove spaces from table name.\n tableName = tableName.replace(/\\s/g, \"_\");\n const spinner = ora(\"Parsing CSV\").start();\n const parseResult = await parseCSV(filePath);\n spinner.stop();\n if (!parseResult.success) {\n console.log(\"Failed to parse CSV, error:\");\n console.error(parseResult.error);\n process.exit(1);\n }", "score": 0.8413594961166382 } ]
typescript
await generateCRUDWorkflow(tableName, credentials);
import { CommandModule } from "yargs"; import { createAppForTable, deleteApp } from "../utils/apps"; import { Credentials, getAndVerifyCredentialsWithRetoolDB, } from "../utils/credentials"; import { getRequest, postRequest } from "../utils/networking"; import { collectColumnNames, collectTableName, createTable, createTableFromCSV, deleteTable, generateDataWithGPT, } from "../utils/table"; import type { DBInfoPayload } from "../utils/table"; import { logDAU } from "../utils/telemetry"; import { deleteWorkflow, generateCRUDWorkflow } from "../utils/workflows"; const inquirer = require("inquirer"); const command = "scaffold"; const describe = "Scaffold a Retool DB table, CRUD Workflow, and App."; const builder: CommandModule["builder"] = { name: { alias: "n", describe: `Name of table to scaffold. Usage: retool scaffold -n <table_name>`, type: "string", nargs: 1, }, columns: { alias: "c", describe: `Column names in DB to scaffold. Usage: retool scaffold -c <col1> <col2>`, type: "array", }, delete: { alias: "d", describe: `Delete a table, Workflow and App created via scaffold. Usage: retool scaffold -d <db_name>`, type: "string", nargs: 1, }, "from-csv": { alias: "f", describe: `Create a table, Workflow and App from a CSV file. Usage: retool scaffold -f <path-to-csv>`, type: "array", }, "no-workflow": { describe: `Modifier to avoid generating Workflow. Usage: retool scaffold --no-workflow`, type: "boolean", }, }; const handler = async function (argv: any) { const credentials = await getAndVerifyCredentialsWithRetoolDB(); // fire and forget void logDAU(credentials); // Handle `retool scaffold -d <db_name>` if (argv.delete) { const tableName = argv.delete; const workflowName = `${tableName} CRUD Workflow`; // Confirm deletion. const { confirm } = await inquirer.prompt([ { name: "confirm", message: `Are you sure you want to delete ${tableName} table, CRUD workflow and app?`, type: "confirm", }, ]); if (!confirm) { process.exit(0); } //TODO: Could be parallelized. //TODO: Verify existence before trying to delete. await deleteTable(tableName, credentials, false); await deleteWorkflow(workflowName, credentials, false); await
deleteApp(`${tableName} App`, credentials, false);
} // Handle `retool scaffold -f <path-to-csv>` else if (argv.f) { const csvFileNames = argv.f; for (const csvFileName of csvFileNames) { const { tableName, colNames } = await createTableFromCSV( csvFileName, credentials, false, false ); if (!argv["no-workflow"]) { console.log("\n"); await generateCRUDWorkflow(tableName, credentials); } console.log("\n"); const searchColumnName = colNames.length > 0 ? colNames[0] : "id"; await createAppForTable( `${tableName} App`, tableName, searchColumnName, credentials ); console.log(""); } } // Handle `retool scaffold` else { let tableName = argv.name; let colNames = argv.columns; if (!tableName || tableName.length == 0) { tableName = await collectTableName(); } if (!colNames || colNames.length == 0) { colNames = await collectColumnNames(); } await createTable(tableName, colNames, undefined, credentials, false); // Fire and forget void insertSampleData(tableName, credentials); if (!argv["no-workflow"]) { console.log("\n"); await generateCRUDWorkflow(tableName, credentials); } console.log("\n"); const searchColumnName = colNames.length > 0 ? colNames[0] : "id"; await createAppForTable( `${tableName} App`, tableName, searchColumnName, credentials ); } }; const insertSampleData = async function ( tableName: string, credentials: Credentials ) { const infoRes = await getRequest( `${credentials.origin}/api/grid/${credentials.gridId}/table/${tableName}/info`, false ); const retoolDBInfo: DBInfoPayload = infoRes.data; const { fields } = retoolDBInfo.tableInfo; const generatedData = await generateDataWithGPT( retoolDBInfo, fields, 0, credentials, false ); if (generatedData) { await postRequest( `${credentials.origin}/api/grid/${credentials.gridId}/action`, { kind: "BulkInsertIntoTable", tableName: tableName, additions: generatedData, } ); } }; const commandModule: CommandModule = { command, describe, builder, handler, }; export default commandModule;
src/commands/scaffold.ts
tryretool-retool-cli-91b2c68
[ { "filename": "src/utils/table.ts", "retrieved_chunk": " message: `Are you sure you want to delete the ${tableName} table?`,\n type: \"confirm\",\n },\n ]);\n if (!confirm) {\n process.exit(0);\n }\n }\n // Delete the table.\n const spinner = ora(`Deleting ${tableName}`).start();", "score": 0.893546998500824 }, { "filename": "src/utils/table.ts", "retrieved_chunk": " tableName: string,\n credentials: Credentials,\n confirmDeletion: boolean\n) {\n // Verify that the provided table name exists.\n await verifyTableExists(tableName, credentials);\n if (confirmDeletion) {\n const { confirm } = await inquirer.prompt([\n {\n name: \"confirm\",", "score": 0.8828190565109253 }, { "filename": "src/utils/workflows.ts", "retrieved_chunk": " if (!confirm) {\n process.exit(0);\n }\n }\n // Verify that the provided workflowName exists.\n const { workflows } = await getWorkflowsAndFolders(credentials);\n const workflow = workflows?.filter((workflow) => {\n if (workflow.name === workflowName) {\n return workflow;\n }", "score": 0.8810045719146729 }, { "filename": "src/utils/workflows.ts", "retrieved_chunk": " });\n if (workflow?.length != 1) {\n console.log(`0 or >1 Workflows named ${workflowName} found. 😓`);\n process.exit(1);\n }\n // Delete the Workflow.\n const spinner = ora(`Deleting ${workflowName}`).start();\n await deleteRequest(`${credentials.origin}/api/workflow/${workflow[0].id}`);\n spinner.stop();\n console.log(`Deleted ${workflowName}. 🗑️`);", "score": 0.8734054565429688 }, { "filename": "src/commands/db.ts", "retrieved_chunk": " }\n // Handle `retool db --delete <table-name>`\n else if (argv.delete) {\n const tableNames = argv.delete;\n for (const tableName of tableNames) {\n await deleteTable(tableName, credentials, true);\n }\n }\n // Handle `retool db --gendata <table-name>`\n else if (argv.gendata) {", "score": 0.8686208724975586 } ]
typescript
deleteApp(`${tableName} App`, credentials, false);
import { CommandModule } from "yargs"; import { logSuccess } from "./login"; import { accessTokenFromCookies, xsrfTokenFromCookies } from "../utils/cookies"; import { doCredentialsExist, persistCredentials } from "../utils/credentials"; import { getRequest, postRequest } from "../utils/networking"; import { logDAU } from "../utils/telemetry"; import { isEmailValid } from "../utils/validation"; const axios = require("axios"); const inquirer = require("inquirer"); const ora = require("ora"); const command = "signup"; const describe = "Create a Retool account."; const builder = {}; // eslint-disable-next-line @typescript-eslint/no-unused-vars const handler = async function (argv: any) { // Ask user if they want to overwrite existing credentials. if (doCredentialsExist()) { const { overwrite } = await inquirer.prompt([ { name: "overwrite", message: "You're already logged in. Do you want to log out and create a new account?", type: "confirm", }, ]); if (!overwrite) { return; } } // Step 1: Collect a valid email/password. let email, password, name, org; while (!email) { email = await collectEmail(); } while (!password) { password = await colllectPassword(); } // Step 2: Call signup endpoint, get cookies. const spinner = ora( "Verifying that the email and password are valid on the server" ).start();
const signupResponse = await postRequest( `https://login.retool.com/api/signup`, {
email, password, planKey: "free", } ); spinner.stop(); const accessToken = accessTokenFromCookies( signupResponse.headers["set-cookie"] ); const xsrfToken = xsrfTokenFromCookies(signupResponse.headers["set-cookie"]); if (!accessToken || !xsrfToken) { if (process.env.DEBUG) { console.log(signupResponse); } console.log( "Error creating account, please try again or signup at https://login.retool.com/auth/signup?plan=free." ); return; } axios.defaults.headers["x-xsrf-token"] = xsrfToken; axios.defaults.headers.cookie = `accessToken=${accessToken};`; // Step 3: Collect a valid name/org. while (!name) { name = await collectName(); } while (!org) { org = await collectOrg(); } // Step 4: Initialize organization. await postRequest( `https://login.retool.com/api/organization/admin/initializeOrganization`, { subdomain: org, } ); // Step 5: Persist credentials const origin = `https://${org}.retool.com`; const userRes = await getRequest(`${origin}/api/user`); persistCredentials({ origin, accessToken, xsrf: xsrfToken, firstName: userRes.data.user?.firstName, lastName: userRes.data.user?.lastName, email: userRes.data.user?.email, telemetryEnabled: true, }); logSuccess(); await logDAU(); }; async function collectEmail(): Promise<string | undefined> { const { email } = await inquirer.prompt([ { name: "email", message: "What is your email?", type: "input", }, ]); if (!isEmailValid(email)) { console.log("Invalid email, try again."); return; } return email; } async function colllectPassword(): Promise<string | undefined> { const { password } = await inquirer.prompt([ { name: "password", message: "Please create a password (min 8 characters):", type: "password", }, ]); const { confirmedPassword } = await inquirer.prompt([ { name: "confirmedPassword", message: "Please confirm password:", type: "password", }, ]); if (password.length < 8) { console.log("Password must be at least 8 characters long, try again."); return; } if (password !== confirmedPassword) { console.log("Passwords do not match, try again."); return; } return password; } async function collectName(): Promise<string | undefined> { const { name } = await inquirer.prompt([ { name: "name", message: "What is your first and last name?", type: "input", }, ]); if (!name || name.length === 0) { console.log("Invalid name, try again."); return; } const parts = name.split(" "); const changeNameResponse = await postRequest( `https://login.retool.com/api/user/changeName`, { firstName: parts[0], lastName: parts[1], }, false ); if (!changeNameResponse) { return; } return name; } async function collectOrg(): Promise<string | undefined> { let { org } = await inquirer.prompt([ { name: "org", message: "What is your organization name? Leave blank to generate a random name.", type: "input", }, ]); if (!org || org.length === 0) { // Org must start with letter, append a random string after it. // https://stackoverflow.com/a/8084248 org = "z" + (Math.random() + 1).toString(36).substring(2); } const checkSubdomainAvailabilityResponse = await getRequest( `https://login.retool.com/api/organization/admin/checkSubdomainAvailability?subdomain=${org}`, false ); if (!checkSubdomainAvailabilityResponse.status) { return; } return org; } const commandModule: CommandModule = { command, describe, builder, handler }; export default commandModule;
src/commands/signup.ts
tryretool-retool-cli-91b2c68
[ { "filename": "src/commands/login.ts", "retrieved_chunk": "};\n// Ask the user to input their email and password.\n// Fire off a request to Retool's login & auth endpoints.\n// Persist the credentials.\nasync function loginViaEmail(localhost = false) {\n const { email, password } = await inquirer.prompt([\n {\n name: \"email\",\n message: \"What is your email?\",\n type: \"input\",", "score": 0.8684110045433044 }, { "filename": "src/commands/login.ts", "retrieved_chunk": " // Step 1: Hit /api/login with email and password.\n const login = await postRequest(`${loginOrigin}/api/login`, {\n email,\n password,\n });\n const { authUrl, authorizationToken } = login.data;\n if (!authUrl || !authorizationToken) {\n console.log(\"Error logging in, please try again\");\n return;\n }", "score": 0.8598058223724365 }, { "filename": "src/utils/credentials.ts", "retrieved_chunk": " return credentials;\n}\nexport function getAndVerifyCredentials() {\n const spinner = ora(\"Verifying Retool credentials\").start();\n const credentials = getCredentials();\n if (!credentials) {\n spinner.stop();\n console.log(\n `Error: No credentials found. To log in, run: \\`retool login\\``\n );", "score": 0.8535503149032593 }, { "filename": "src/commands/login.ts", "retrieved_chunk": " },\n {\n name: \"password\",\n message: \"What is your password?\",\n type: \"password\",\n },\n ]);\n const loginOrigin = localhost\n ? \"http://localhost:3000\"\n : \"https://login.retool.com\";", "score": 0.8438900113105774 }, { "filename": "src/utils/credentials.ts", "retrieved_chunk": " let credentials = getCredentials();\n if (!credentials) {\n spinner.stop();\n console.log(\n `Error: No credentials found. To log in, run: \\`retool login\\``\n );\n process.exit(1);\n }\n axios.defaults.headers[\"x-xsrf-token\"] = credentials.xsrf;\n axios.defaults.headers.cookie = `accessToken=${credentials.accessToken};`;", "score": 0.8417114615440369 } ]
typescript
const signupResponse = await postRequest( `https://login.retool.com/api/signup`, {
import { CommandModule } from "yargs"; import { createAppForTable, deleteApp } from "../utils/apps"; import { Credentials, getAndVerifyCredentialsWithRetoolDB, } from "../utils/credentials"; import { getRequest, postRequest } from "../utils/networking"; import { collectColumnNames, collectTableName, createTable, createTableFromCSV, deleteTable, generateDataWithGPT, } from "../utils/table"; import type { DBInfoPayload } from "../utils/table"; import { logDAU } from "../utils/telemetry"; import { deleteWorkflow, generateCRUDWorkflow } from "../utils/workflows"; const inquirer = require("inquirer"); const command = "scaffold"; const describe = "Scaffold a Retool DB table, CRUD Workflow, and App."; const builder: CommandModule["builder"] = { name: { alias: "n", describe: `Name of table to scaffold. Usage: retool scaffold -n <table_name>`, type: "string", nargs: 1, }, columns: { alias: "c", describe: `Column names in DB to scaffold. Usage: retool scaffold -c <col1> <col2>`, type: "array", }, delete: { alias: "d", describe: `Delete a table, Workflow and App created via scaffold. Usage: retool scaffold -d <db_name>`, type: "string", nargs: 1, }, "from-csv": { alias: "f", describe: `Create a table, Workflow and App from a CSV file. Usage: retool scaffold -f <path-to-csv>`, type: "array", }, "no-workflow": { describe: `Modifier to avoid generating Workflow. Usage: retool scaffold --no-workflow`, type: "boolean", }, }; const handler = async function (argv: any) { const credentials = await getAndVerifyCredentialsWithRetoolDB(); // fire and forget void logDAU(credentials); // Handle `retool scaffold -d <db_name>` if (argv.delete) { const tableName = argv.delete; const workflowName = `${tableName} CRUD Workflow`; // Confirm deletion. const { confirm } = await inquirer.prompt([ { name: "confirm", message: `Are you sure you want to delete ${tableName} table, CRUD workflow and app?`, type: "confirm", }, ]); if (!confirm) { process.exit(0); } //TODO: Could be parallelized. //TODO: Verify existence before trying to delete. await deleteTable(tableName, credentials, false); await deleteWorkflow(workflowName, credentials, false); await deleteApp(`${tableName} App`, credentials, false); } // Handle `retool scaffold -f <path-to-csv>` else if (argv.f) { const csvFileNames = argv.f; for (const csvFileName of csvFileNames) { const { tableName, colNames } = await createTableFromCSV( csvFileName, credentials, false, false ); if (!argv["no-workflow"]) { console.log("\n"); await generateCRUDWorkflow(tableName, credentials); } console.log("\n"); const searchColumnName = colNames.length > 0 ? colNames[0] : "id"; await createAppForTable( `${tableName} App`, tableName, searchColumnName, credentials ); console.log(""); } } // Handle `retool scaffold` else { let tableName = argv.name; let colNames = argv.columns; if (!tableName || tableName.length == 0) { tableName = await collectTableName(); } if (!colNames || colNames.length == 0) { colNames = await collectColumnNames(); } await createTable(tableName, colNames, undefined, credentials, false); // Fire and forget void insertSampleData(tableName, credentials); if (!argv["no-workflow"]) { console.log("\n"); await generateCRUDWorkflow(tableName, credentials); } console.log("\n"); const searchColumnName = colNames.length > 0 ? colNames[0] : "id"; await createAppForTable( `${tableName} App`, tableName, searchColumnName, credentials ); } }; const insertSampleData = async function ( tableName: string, credentials: Credentials ) { const infoRes = await getRequest( `${credentials.origin}/api/grid/${credentials.gridId}/table/${tableName}/info`, false ); const retoolDBInfo: DBInfoPayload = infoRes.data; const { fields } = retoolDBInfo.tableInfo; const generatedData = await generateDataWithGPT( retoolDBInfo, fields, 0, credentials, false ); if (generatedData) {
await postRequest( `${credentials.origin}/api/grid/${credentials.gridId}/action`, {
kind: "BulkInsertIntoTable", tableName: tableName, additions: generatedData, } ); } }; const commandModule: CommandModule = { command, describe, builder, handler, }; export default commandModule;
src/commands/scaffold.ts
tryretool-retool-cli-91b2c68
[ { "filename": "src/commands/db.ts", "retrieved_chunk": " );\n }\n // Insert to Retool DB.\n const bulkInsertRes = await postRequest(\n `${credentials.origin}/api/grid/${credentials.gridId}/action`,\n {\n kind: \"BulkInsertIntoTable\",\n tableName: tableName,\n additions: generatedData,\n }", "score": 0.8927172422409058 }, { "filename": "src/utils/table.ts", "retrieved_chunk": " | undefined\n> {\n const genDataRes: {\n data: {\n data: string[][];\n };\n } = await postRequest(\n `${credentials.origin}/api/grid/retooldb/generateData`,\n {\n fields: retoolDBInfo.tableInfo.fields.map((field) => {", "score": 0.8839465975761414 }, { "filename": "src/utils/credentials.ts", "retrieved_chunk": " if (retoolDBs?.length < 1) {\n console.log(\n `\\nError: Retool DB not found. Create one at ${credentials.origin}/resources`\n );\n return;\n }\n const retoolDBUuid = retoolDBs[0].name;\n // 3. Fetch Grid Info\n const grid = await getRequest(\n `${credentials.origin}/api/grid/retooldb/${retoolDBUuid}?env=production`", "score": 0.8750049471855164 }, { "filename": "src/utils/table.ts", "retrieved_chunk": " `${credentials.origin}/api/grid/${credentials.gridId}/action`,\n {\n ...payload,\n }\n );\n spinner.stop();\n if (!createTableResult.data.success) {\n console.log(\"Error creating table in RetoolDB.\");\n console.log(createTableResult.data);\n process.exit(1);", "score": 0.8643831014633179 }, { "filename": "src/commands/db.ts", "retrieved_chunk": " // Verify that the provided db name exists.\n const tableName = argv.gendata;\n await verifyTableExists(tableName, credentials);\n // Fetch Retool DB schema and data.\n const spinner = ora(`Fetching ${tableName} metadata`).start();\n const infoReq = getRequest(\n `${credentials.origin}/api/grid/${credentials.gridId}/table/${tableName}/info`\n );\n const dataReq = postRequest(\n `${credentials.origin}/api/grid/${credentials.gridId}/table/${tableName}/data`,", "score": 0.8557702302932739 } ]
typescript
await postRequest( `${credentials.origin}/api/grid/${credentials.gridId}/action`, {
import { CommandModule } from "yargs"; import { createAppForTable, deleteApp } from "../utils/apps"; import { Credentials, getAndVerifyCredentialsWithRetoolDB, } from "../utils/credentials"; import { getRequest, postRequest } from "../utils/networking"; import { collectColumnNames, collectTableName, createTable, createTableFromCSV, deleteTable, generateDataWithGPT, } from "../utils/table"; import type { DBInfoPayload } from "../utils/table"; import { logDAU } from "../utils/telemetry"; import { deleteWorkflow, generateCRUDWorkflow } from "../utils/workflows"; const inquirer = require("inquirer"); const command = "scaffold"; const describe = "Scaffold a Retool DB table, CRUD Workflow, and App."; const builder: CommandModule["builder"] = { name: { alias: "n", describe: `Name of table to scaffold. Usage: retool scaffold -n <table_name>`, type: "string", nargs: 1, }, columns: { alias: "c", describe: `Column names in DB to scaffold. Usage: retool scaffold -c <col1> <col2>`, type: "array", }, delete: { alias: "d", describe: `Delete a table, Workflow and App created via scaffold. Usage: retool scaffold -d <db_name>`, type: "string", nargs: 1, }, "from-csv": { alias: "f", describe: `Create a table, Workflow and App from a CSV file. Usage: retool scaffold -f <path-to-csv>`, type: "array", }, "no-workflow": { describe: `Modifier to avoid generating Workflow. Usage: retool scaffold --no-workflow`, type: "boolean", }, }; const handler = async function (argv: any) { const credentials = await getAndVerifyCredentialsWithRetoolDB(); // fire and forget void logDAU(credentials); // Handle `retool scaffold -d <db_name>` if (argv.delete) { const tableName = argv.delete; const workflowName = `${tableName} CRUD Workflow`; // Confirm deletion. const { confirm } = await inquirer.prompt([ { name: "confirm", message: `Are you sure you want to delete ${tableName} table, CRUD workflow and app?`, type: "confirm", }, ]); if (!confirm) { process.exit(0); } //TODO: Could be parallelized. //TODO: Verify existence before trying to delete. await deleteTable(tableName, credentials, false);
await deleteWorkflow(workflowName, credentials, false);
await deleteApp(`${tableName} App`, credentials, false); } // Handle `retool scaffold -f <path-to-csv>` else if (argv.f) { const csvFileNames = argv.f; for (const csvFileName of csvFileNames) { const { tableName, colNames } = await createTableFromCSV( csvFileName, credentials, false, false ); if (!argv["no-workflow"]) { console.log("\n"); await generateCRUDWorkflow(tableName, credentials); } console.log("\n"); const searchColumnName = colNames.length > 0 ? colNames[0] : "id"; await createAppForTable( `${tableName} App`, tableName, searchColumnName, credentials ); console.log(""); } } // Handle `retool scaffold` else { let tableName = argv.name; let colNames = argv.columns; if (!tableName || tableName.length == 0) { tableName = await collectTableName(); } if (!colNames || colNames.length == 0) { colNames = await collectColumnNames(); } await createTable(tableName, colNames, undefined, credentials, false); // Fire and forget void insertSampleData(tableName, credentials); if (!argv["no-workflow"]) { console.log("\n"); await generateCRUDWorkflow(tableName, credentials); } console.log("\n"); const searchColumnName = colNames.length > 0 ? colNames[0] : "id"; await createAppForTable( `${tableName} App`, tableName, searchColumnName, credentials ); } }; const insertSampleData = async function ( tableName: string, credentials: Credentials ) { const infoRes = await getRequest( `${credentials.origin}/api/grid/${credentials.gridId}/table/${tableName}/info`, false ); const retoolDBInfo: DBInfoPayload = infoRes.data; const { fields } = retoolDBInfo.tableInfo; const generatedData = await generateDataWithGPT( retoolDBInfo, fields, 0, credentials, false ); if (generatedData) { await postRequest( `${credentials.origin}/api/grid/${credentials.gridId}/action`, { kind: "BulkInsertIntoTable", tableName: tableName, additions: generatedData, } ); } }; const commandModule: CommandModule = { command, describe, builder, handler, }; export default commandModule;
src/commands/scaffold.ts
tryretool-retool-cli-91b2c68
[ { "filename": "src/utils/table.ts", "retrieved_chunk": " message: `Are you sure you want to delete the ${tableName} table?`,\n type: \"confirm\",\n },\n ]);\n if (!confirm) {\n process.exit(0);\n }\n }\n // Delete the table.\n const spinner = ora(`Deleting ${tableName}`).start();", "score": 0.9004313945770264 }, { "filename": "src/utils/workflows.ts", "retrieved_chunk": " if (!confirm) {\n process.exit(0);\n }\n }\n // Verify that the provided workflowName exists.\n const { workflows } = await getWorkflowsAndFolders(credentials);\n const workflow = workflows?.filter((workflow) => {\n if (workflow.name === workflowName) {\n return workflow;\n }", "score": 0.8913363814353943 }, { "filename": "src/utils/table.ts", "retrieved_chunk": " tableName: string,\n credentials: Credentials,\n confirmDeletion: boolean\n) {\n // Verify that the provided table name exists.\n await verifyTableExists(tableName, credentials);\n if (confirmDeletion) {\n const { confirm } = await inquirer.prompt([\n {\n name: \"confirm\",", "score": 0.8809521198272705 }, { "filename": "src/utils/workflows.ts", "retrieved_chunk": " });\n if (workflow?.length != 1) {\n console.log(`0 or >1 Workflows named ${workflowName} found. 😓`);\n process.exit(1);\n }\n // Delete the Workflow.\n const spinner = ora(`Deleting ${workflowName}`).start();\n await deleteRequest(`${credentials.origin}/api/workflow/${workflow[0].id}`);\n spinner.stop();\n console.log(`Deleted ${workflowName}. 🗑️`);", "score": 0.8786879181861877 }, { "filename": "src/utils/workflows.ts", "retrieved_chunk": " confirmDeletion: boolean\n) {\n if (confirmDeletion) {\n const { confirm } = await inquirer.prompt([\n {\n name: \"confirm\",\n message: `Are you sure you want to delete ${workflowName}?`,\n type: \"confirm\",\n },\n ]);", "score": 0.8649671077728271 } ]
typescript
await deleteWorkflow(workflowName, credentials, false);
import { CommandModule } from "yargs"; import { logSuccess } from "./login"; import { accessTokenFromCookies, xsrfTokenFromCookies } from "../utils/cookies"; import { doCredentialsExist, persistCredentials } from "../utils/credentials"; import { getRequest, postRequest } from "../utils/networking"; import { logDAU } from "../utils/telemetry"; import { isEmailValid } from "../utils/validation"; const axios = require("axios"); const inquirer = require("inquirer"); const ora = require("ora"); const command = "signup"; const describe = "Create a Retool account."; const builder = {}; // eslint-disable-next-line @typescript-eslint/no-unused-vars const handler = async function (argv: any) { // Ask user if they want to overwrite existing credentials. if (doCredentialsExist()) { const { overwrite } = await inquirer.prompt([ { name: "overwrite", message: "You're already logged in. Do you want to log out and create a new account?", type: "confirm", }, ]); if (!overwrite) { return; } } // Step 1: Collect a valid email/password. let email, password, name, org; while (!email) { email = await collectEmail(); } while (!password) { password = await colllectPassword(); } // Step 2: Call signup endpoint, get cookies. const spinner = ora( "Verifying that the email and password are valid on the server" ).start(); const signupResponse = await postRequest( `https://login.retool.com/api/signup`, { email, password, planKey: "free", } ); spinner.stop(); const accessToken
= accessTokenFromCookies( signupResponse.headers["set-cookie"] );
const xsrfToken = xsrfTokenFromCookies(signupResponse.headers["set-cookie"]); if (!accessToken || !xsrfToken) { if (process.env.DEBUG) { console.log(signupResponse); } console.log( "Error creating account, please try again or signup at https://login.retool.com/auth/signup?plan=free." ); return; } axios.defaults.headers["x-xsrf-token"] = xsrfToken; axios.defaults.headers.cookie = `accessToken=${accessToken};`; // Step 3: Collect a valid name/org. while (!name) { name = await collectName(); } while (!org) { org = await collectOrg(); } // Step 4: Initialize organization. await postRequest( `https://login.retool.com/api/organization/admin/initializeOrganization`, { subdomain: org, } ); // Step 5: Persist credentials const origin = `https://${org}.retool.com`; const userRes = await getRequest(`${origin}/api/user`); persistCredentials({ origin, accessToken, xsrf: xsrfToken, firstName: userRes.data.user?.firstName, lastName: userRes.data.user?.lastName, email: userRes.data.user?.email, telemetryEnabled: true, }); logSuccess(); await logDAU(); }; async function collectEmail(): Promise<string | undefined> { const { email } = await inquirer.prompt([ { name: "email", message: "What is your email?", type: "input", }, ]); if (!isEmailValid(email)) { console.log("Invalid email, try again."); return; } return email; } async function colllectPassword(): Promise<string | undefined> { const { password } = await inquirer.prompt([ { name: "password", message: "Please create a password (min 8 characters):", type: "password", }, ]); const { confirmedPassword } = await inquirer.prompt([ { name: "confirmedPassword", message: "Please confirm password:", type: "password", }, ]); if (password.length < 8) { console.log("Password must be at least 8 characters long, try again."); return; } if (password !== confirmedPassword) { console.log("Passwords do not match, try again."); return; } return password; } async function collectName(): Promise<string | undefined> { const { name } = await inquirer.prompt([ { name: "name", message: "What is your first and last name?", type: "input", }, ]); if (!name || name.length === 0) { console.log("Invalid name, try again."); return; } const parts = name.split(" "); const changeNameResponse = await postRequest( `https://login.retool.com/api/user/changeName`, { firstName: parts[0], lastName: parts[1], }, false ); if (!changeNameResponse) { return; } return name; } async function collectOrg(): Promise<string | undefined> { let { org } = await inquirer.prompt([ { name: "org", message: "What is your organization name? Leave blank to generate a random name.", type: "input", }, ]); if (!org || org.length === 0) { // Org must start with letter, append a random string after it. // https://stackoverflow.com/a/8084248 org = "z" + (Math.random() + 1).toString(36).substring(2); } const checkSubdomainAvailabilityResponse = await getRequest( `https://login.retool.com/api/organization/admin/checkSubdomainAvailability?subdomain=${org}`, false ); if (!checkSubdomainAvailabilityResponse.status) { return; } return org; } const commandModule: CommandModule = { command, describe, builder, handler }; export default commandModule;
src/commands/signup.ts
tryretool-retool-cli-91b2c68
[ { "filename": "src/commands/login.ts", "retrieved_chunk": " );\n const { redirectUri } = authResponse.data;\n const redirectUrl = localhost\n ? new URL(loginOrigin)\n : redirectUri\n ? new URL(redirectUri)\n : undefined;\n const accessToken = accessTokenFromCookies(\n authResponse.headers[\"set-cookie\"]\n );", "score": 0.8536702394485474 }, { "filename": "src/utils/credentials.ts", "retrieved_chunk": " process.exit(1);\n }\n axios.defaults.headers[\"x-xsrf-token\"] = credentials.xsrf;\n axios.defaults.headers.cookie = `accessToken=${credentials.accessToken};`;\n spinner.stop();\n return credentials;\n}", "score": 0.8482877016067505 }, { "filename": "src/commands/login.ts", "retrieved_chunk": " // Step 1: Hit /api/login with email and password.\n const login = await postRequest(`${loginOrigin}/api/login`, {\n email,\n password,\n });\n const { authUrl, authorizationToken } = login.data;\n if (!authUrl || !authorizationToken) {\n console.log(\"Error logging in, please try again\");\n return;\n }", "score": 0.8459893465042114 }, { "filename": "src/commands/login.ts", "retrieved_chunk": " const xsrfToken = xsrfTokenFromCookies(authResponse.headers[\"set-cookie\"]);\n // Step 3: Persist the credentials.\n if (redirectUrl?.origin && accessToken && xsrfToken) {\n persistCredentials({\n origin: redirectUrl.origin,\n accessToken,\n xsrf: xsrfToken,\n firstName: authResponse.data.user?.firstName,\n lastName: authResponse.data.user?.lastName,\n email: authResponse.data.user?.email,", "score": 0.8405081033706665 }, { "filename": "src/utils/credentials.ts", "retrieved_chunk": " let credentials = getCredentials();\n if (!credentials) {\n spinner.stop();\n console.log(\n `Error: No credentials found. To log in, run: \\`retool login\\``\n );\n process.exit(1);\n }\n axios.defaults.headers[\"x-xsrf-token\"] = credentials.xsrf;\n axios.defaults.headers.cookie = `accessToken=${credentials.accessToken};`;", "score": 0.8361527919769287 } ]
typescript
= accessTokenFromCookies( signupResponse.headers["set-cookie"] );
import { CommandModule } from "yargs"; import { createAppForTable, deleteApp } from "../utils/apps"; import { Credentials, getAndVerifyCredentialsWithRetoolDB, } from "../utils/credentials"; import { getRequest, postRequest } from "../utils/networking"; import { collectColumnNames, collectTableName, createTable, createTableFromCSV, deleteTable, generateDataWithGPT, } from "../utils/table"; import type { DBInfoPayload } from "../utils/table"; import { logDAU } from "../utils/telemetry"; import { deleteWorkflow, generateCRUDWorkflow } from "../utils/workflows"; const inquirer = require("inquirer"); const command = "scaffold"; const describe = "Scaffold a Retool DB table, CRUD Workflow, and App."; const builder: CommandModule["builder"] = { name: { alias: "n", describe: `Name of table to scaffold. Usage: retool scaffold -n <table_name>`, type: "string", nargs: 1, }, columns: { alias: "c", describe: `Column names in DB to scaffold. Usage: retool scaffold -c <col1> <col2>`, type: "array", }, delete: { alias: "d", describe: `Delete a table, Workflow and App created via scaffold. Usage: retool scaffold -d <db_name>`, type: "string", nargs: 1, }, "from-csv": { alias: "f", describe: `Create a table, Workflow and App from a CSV file. Usage: retool scaffold -f <path-to-csv>`, type: "array", }, "no-workflow": { describe: `Modifier to avoid generating Workflow. Usage: retool scaffold --no-workflow`, type: "boolean", }, }; const handler = async function (argv: any) { const credentials = await getAndVerifyCredentialsWithRetoolDB(); // fire and forget void logDAU(credentials); // Handle `retool scaffold -d <db_name>` if (argv.delete) { const tableName = argv.delete; const workflowName = `${tableName} CRUD Workflow`; // Confirm deletion. const { confirm } = await inquirer.prompt([ { name: "confirm", message: `Are you sure you want to delete ${tableName} table, CRUD workflow and app?`, type: "confirm", }, ]); if (!confirm) { process.exit(0); } //TODO: Could be parallelized. //TODO: Verify existence before trying to delete. await deleteTable(tableName, credentials, false); await
deleteWorkflow(workflowName, credentials, false);
await deleteApp(`${tableName} App`, credentials, false); } // Handle `retool scaffold -f <path-to-csv>` else if (argv.f) { const csvFileNames = argv.f; for (const csvFileName of csvFileNames) { const { tableName, colNames } = await createTableFromCSV( csvFileName, credentials, false, false ); if (!argv["no-workflow"]) { console.log("\n"); await generateCRUDWorkflow(tableName, credentials); } console.log("\n"); const searchColumnName = colNames.length > 0 ? colNames[0] : "id"; await createAppForTable( `${tableName} App`, tableName, searchColumnName, credentials ); console.log(""); } } // Handle `retool scaffold` else { let tableName = argv.name; let colNames = argv.columns; if (!tableName || tableName.length == 0) { tableName = await collectTableName(); } if (!colNames || colNames.length == 0) { colNames = await collectColumnNames(); } await createTable(tableName, colNames, undefined, credentials, false); // Fire and forget void insertSampleData(tableName, credentials); if (!argv["no-workflow"]) { console.log("\n"); await generateCRUDWorkflow(tableName, credentials); } console.log("\n"); const searchColumnName = colNames.length > 0 ? colNames[0] : "id"; await createAppForTable( `${tableName} App`, tableName, searchColumnName, credentials ); } }; const insertSampleData = async function ( tableName: string, credentials: Credentials ) { const infoRes = await getRequest( `${credentials.origin}/api/grid/${credentials.gridId}/table/${tableName}/info`, false ); const retoolDBInfo: DBInfoPayload = infoRes.data; const { fields } = retoolDBInfo.tableInfo; const generatedData = await generateDataWithGPT( retoolDBInfo, fields, 0, credentials, false ); if (generatedData) { await postRequest( `${credentials.origin}/api/grid/${credentials.gridId}/action`, { kind: "BulkInsertIntoTable", tableName: tableName, additions: generatedData, } ); } }; const commandModule: CommandModule = { command, describe, builder, handler, }; export default commandModule;
src/commands/scaffold.ts
tryretool-retool-cli-91b2c68
[ { "filename": "src/utils/workflows.ts", "retrieved_chunk": " if (!confirm) {\n process.exit(0);\n }\n }\n // Verify that the provided workflowName exists.\n const { workflows } = await getWorkflowsAndFolders(credentials);\n const workflow = workflows?.filter((workflow) => {\n if (workflow.name === workflowName) {\n return workflow;\n }", "score": 0.8886051177978516 }, { "filename": "src/utils/table.ts", "retrieved_chunk": " message: `Are you sure you want to delete the ${tableName} table?`,\n type: \"confirm\",\n },\n ]);\n if (!confirm) {\n process.exit(0);\n }\n }\n // Delete the table.\n const spinner = ora(`Deleting ${tableName}`).start();", "score": 0.886440098285675 }, { "filename": "src/utils/workflows.ts", "retrieved_chunk": " });\n if (workflow?.length != 1) {\n console.log(`0 or >1 Workflows named ${workflowName} found. 😓`);\n process.exit(1);\n }\n // Delete the Workflow.\n const spinner = ora(`Deleting ${workflowName}`).start();\n await deleteRequest(`${credentials.origin}/api/workflow/${workflow[0].id}`);\n spinner.stop();\n console.log(`Deleted ${workflowName}. 🗑️`);", "score": 0.8807428479194641 }, { "filename": "src/utils/table.ts", "retrieved_chunk": " tableName: string,\n credentials: Credentials,\n confirmDeletion: boolean\n) {\n // Verify that the provided table name exists.\n await verifyTableExists(tableName, credentials);\n if (confirmDeletion) {\n const { confirm } = await inquirer.prompt([\n {\n name: \"confirm\",", "score": 0.8761134743690491 }, { "filename": "src/commands/workflows.ts", "retrieved_chunk": " printWorkflows(workflows);\n }\n }\n }\n // Handle `retool workflows -d <workflow-name>`\n else if (argv.delete) {\n const workflowNames = argv.delete;\n for (const workflowName of workflowNames) {\n await deleteWorkflow(workflowName, credentials, true);\n }", "score": 0.8672293424606323 } ]
typescript
deleteWorkflow(workflowName, credentials, false);
import { bech32 } from "@scure/base"; import EventEmitter from "eventemitter3"; import { nip57 } from "nostr-tools"; import type { NostrEvent } from "../events/index.js"; import NDKEvent, { NDKTag } from "../events/index.js"; import NDK from "../index.js"; import User from "../user/index.js"; const DEFAULT_RELAYS = [ "wss://nos.lol", "wss://relay.nostr.band", "wss://relay.f7z.io", "wss://relay.damus.io", "wss://nostr.mom", "wss://no.str.cr", ]; interface ZapConstructorParams { ndk: NDK; zappedEvent?: NDKEvent; zappedUser?: User; } type ZapConstructorParamsRequired = Required< Pick<ZapConstructorParams, "zappedEvent"> > & Pick<ZapConstructorParams, "zappedUser"> & ZapConstructorParams; export default class Zap extends EventEmitter { public ndk?: NDK; public zappedEvent?: NDKEvent; public zappedUser: User; public constructor(args: ZapConstructorParamsRequired) { super(); this.ndk = args.ndk; this.zappedEvent = args.zappedEvent; this.zappedUser = args.zappedUser || this.ndk.getUser({ hexpubkey: this.zappedEvent.pubkey }); } public async getZapEndpoint(): Promise<string | undefined> { let lud06: string | undefined; let lud16: string | undefined; let zapEndpoint: string | undefined; let zapEndpointCallback: string | undefined; if (this.zappedEvent) { const zapTag = (await this.zappedEvent.getMatchingTags("zap"))[0]; if (zapTag) { switch (zapTag[2]) { case "lud06": lud06 = zapTag[1]; break; case "lud16": lud16 = zapTag[1]; break; default: throw new Error(`Unknown zap tag ${zapTag}`); } } } if (this.zappedUser && !lud06 && !lud16) { // check if user has a profile, otherwise request it if (!this.zappedUser.profile) { await this.zappedUser.fetchProfile(); } lud06 = (this.zappedUser.profile || {}).lud06; lud16 = (this.zappedUser.profile || {}).lud16; } if (lud16) { const [name, domain] = lud16.split("@"); zapEndpoint = `https://${domain}/.well-known/lnurlp/${name}`; } else if (lud06) { const { words } = bech32.decode(lud06, 1000); const data = bech32.fromWords(words); const utf8Decoder = new TextDecoder("utf-8"); zapEndpoint = utf8Decoder.decode(data); } if (!zapEndpoint) { throw new Error("No zap endpoint found"); } const response = await fetch(zapEndpoint); const body = await response.json(); if (body?.allowsNostr && (body?.nostrPubkey || body?.nostrPubKey)) { zapEndpointCallback = body.callback; } return zapEndpointCallback; } /** * Generates a kind:9734 zap request and returns the payment request * @param amount amount to zap in millisatoshis * @param comment optional comment to include in the zap request * @param extraTags optional extra tags to include in the zap request * @param relays optional relays to ask zapper to publish the zap to * @returns the payment request */ public async createZapRequest( amount: number, // amount to zap in millisatoshis comment?: string, extraTags
?: NDKTag[], relays?: string[] ): Promise<string | null> {
const zapEndpoint = await this.getZapEndpoint(); if (!zapEndpoint) { throw new Error("No zap endpoint found"); } if (!this.zappedEvent) throw new Error("No zapped event found"); const zapRequest = nip57.makeZapRequest({ profile: this.zappedUser.hexpubkey(), // set the event to null since nostr-tools doesn't support nip-33 zaps event: null, amount, comment: comment || "", relays: relays ?? this.relays(), }); // add the event tag if it exists; this supports both 'e' and 'a' tags if (this.zappedEvent) { const tag = this.zappedEvent.tagReference(); if (tag) { zapRequest.tags.push(tag); } } zapRequest.tags.push(["lnurl", zapEndpoint]); const zapRequestEvent = new NDKEvent( this.ndk, zapRequest as NostrEvent ); if (extraTags) { zapRequestEvent.tags = zapRequestEvent.tags.concat(extraTags); } await zapRequestEvent.sign(); const zapRequestNostrEvent = await zapRequestEvent.toNostrEvent(); const response = await fetch( `${zapEndpoint}?` + new URLSearchParams({ amount: amount.toString(), nostr: JSON.stringify(zapRequestNostrEvent), }) ); const body = await response.json(); return body.pr; } /** * @returns the relays to use for the zap request */ private relays(): string[] { let r: string[] = []; if (this.ndk?.pool?.relays) { r = this.ndk.pool.urls(); } if (!r.length) { r = DEFAULT_RELAYS; } return r; } }
src/zap/index.ts
nostr-dev-kit-ndk-ece64e1
[ { "filename": "src/events/index.ts", "retrieved_chunk": " async zap(\n amount: number,\n comment?: string,\n extraTags?: NDKTag[]\n ): Promise<string | null> {\n if (!this.ndk) throw new Error(\"No NDK instance found\");\n this.ndk.assertSigner();\n const zap = new Zap({\n ndk: this.ndk,\n zappedEvent: this,", "score": 0.8831863403320312 }, { "filename": "src/events/index.ts", "retrieved_chunk": " });\n const paymentRequest = await zap.createZapRequest(\n amount,\n comment,\n extraTags\n );\n // await zap.publish(amount);\n return paymentRequest;\n }\n /**", "score": 0.8599365949630737 }, { "filename": "src/events/index.ts", "retrieved_chunk": " return { \"#e\": [this.tagId()] };\n }\n }\n /**\n * Create a zap request for an existing event\n *\n * @param amount The amount to zap in millisatoshis\n * @param comment A comment to add to the zap request\n * @param extraTags Extra tags to add to the zap request\n */", "score": 0.8230295181274414 }, { "filename": "src/zap/invoice.ts", "retrieved_chunk": "import { decode } from \"light-bolt11-decoder\";\nimport NDKEvent, { type NDKEventId, type NostrEvent } from \"../events/index.js\";\nexport interface NDKZapInvoice {\n id?: NDKEventId;\n zapper: string; // pubkey of zapper app\n zappee: string; // pubkey of user sending zap\n zapped: string; // pubkey of user receiving zap\n zappedEvent?: string; // event zapped\n amount: number; // amount zapped in millisatoshis\n comment?: string;", "score": 0.8124083876609802 }, { "filename": "src/index.ts", "retrieved_chunk": " opts?: NDKSubscriptionOptions,\n relaySet?: NDKRelaySet\n ): Promise<NDKEvent | null> {\n let filter: NDKFilter;\n // if no relayset has been provided, try to get one from the event id\n if (!relaySet && typeof idOrFilter === \"string\") {\n const relays = relaysFromBech32(idOrFilter);\n if (relays.length > 0) {\n relaySet = new NDKRelaySet(new Set<NDKRelay>(relays), this);\n // Make sure we have connected relays in this set", "score": 0.7935816049575806 } ]
typescript
?: NDKTag[], relays?: string[] ): Promise<string | null> {
import { CommandModule } from "yargs"; import { createAppForTable, deleteApp } from "../utils/apps"; import { Credentials, getAndVerifyCredentialsWithRetoolDB, } from "../utils/credentials"; import { getRequest, postRequest } from "../utils/networking"; import { collectColumnNames, collectTableName, createTable, createTableFromCSV, deleteTable, generateDataWithGPT, } from "../utils/table"; import type { DBInfoPayload } from "../utils/table"; import { logDAU } from "../utils/telemetry"; import { deleteWorkflow, generateCRUDWorkflow } from "../utils/workflows"; const inquirer = require("inquirer"); const command = "scaffold"; const describe = "Scaffold a Retool DB table, CRUD Workflow, and App."; const builder: CommandModule["builder"] = { name: { alias: "n", describe: `Name of table to scaffold. Usage: retool scaffold -n <table_name>`, type: "string", nargs: 1, }, columns: { alias: "c", describe: `Column names in DB to scaffold. Usage: retool scaffold -c <col1> <col2>`, type: "array", }, delete: { alias: "d", describe: `Delete a table, Workflow and App created via scaffold. Usage: retool scaffold -d <db_name>`, type: "string", nargs: 1, }, "from-csv": { alias: "f", describe: `Create a table, Workflow and App from a CSV file. Usage: retool scaffold -f <path-to-csv>`, type: "array", }, "no-workflow": { describe: `Modifier to avoid generating Workflow. Usage: retool scaffold --no-workflow`, type: "boolean", }, }; const handler = async function (argv: any) { const credentials = await getAndVerifyCredentialsWithRetoolDB(); // fire and forget void logDAU(credentials); // Handle `retool scaffold -d <db_name>` if (argv.delete) { const tableName = argv.delete; const workflowName = `${tableName} CRUD Workflow`; // Confirm deletion. const { confirm } = await inquirer.prompt([ { name: "confirm", message: `Are you sure you want to delete ${tableName} table, CRUD workflow and app?`, type: "confirm", }, ]); if (!confirm) { process.exit(0); } //TODO: Could be parallelized. //TODO: Verify existence before trying to delete. await deleteTable(tableName, credentials, false); await deleteWorkflow(workflowName, credentials, false); await deleteApp(`${tableName} App`, credentials, false); } // Handle `retool scaffold -f <path-to-csv>` else if (argv.f) { const csvFileNames = argv.f; for (const csvFileName of csvFileNames) { const { tableName, colNames } = await createTableFromCSV( csvFileName, credentials, false, false ); if (!argv["no-workflow"]) { console.log("\n"); await
generateCRUDWorkflow(tableName, credentials);
} console.log("\n"); const searchColumnName = colNames.length > 0 ? colNames[0] : "id"; await createAppForTable( `${tableName} App`, tableName, searchColumnName, credentials ); console.log(""); } } // Handle `retool scaffold` else { let tableName = argv.name; let colNames = argv.columns; if (!tableName || tableName.length == 0) { tableName = await collectTableName(); } if (!colNames || colNames.length == 0) { colNames = await collectColumnNames(); } await createTable(tableName, colNames, undefined, credentials, false); // Fire and forget void insertSampleData(tableName, credentials); if (!argv["no-workflow"]) { console.log("\n"); await generateCRUDWorkflow(tableName, credentials); } console.log("\n"); const searchColumnName = colNames.length > 0 ? colNames[0] : "id"; await createAppForTable( `${tableName} App`, tableName, searchColumnName, credentials ); } }; const insertSampleData = async function ( tableName: string, credentials: Credentials ) { const infoRes = await getRequest( `${credentials.origin}/api/grid/${credentials.gridId}/table/${tableName}/info`, false ); const retoolDBInfo: DBInfoPayload = infoRes.data; const { fields } = retoolDBInfo.tableInfo; const generatedData = await generateDataWithGPT( retoolDBInfo, fields, 0, credentials, false ); if (generatedData) { await postRequest( `${credentials.origin}/api/grid/${credentials.gridId}/action`, { kind: "BulkInsertIntoTable", tableName: tableName, additions: generatedData, } ); } }; const commandModule: CommandModule = { command, describe, builder, handler, }; export default commandModule;
src/commands/scaffold.ts
tryretool-retool-cli-91b2c68
[ { "filename": "src/commands/db.ts", "retrieved_chunk": " // Handle `retool db --upload <path-to-csv>`\n if (argv.upload) {\n await createTableFromCSV(argv.upload, credentials, true, true);\n }\n // Handle `retool db --create`\n else if (argv.create) {\n const tableName = await collectTableName();\n const colNames = await collectColumnNames();\n await createTable(tableName, colNames, undefined, credentials, true);\n }", "score": 0.8804706335067749 }, { "filename": "src/utils/table.ts", "retrieved_chunk": " }/${tableName}?env=production`\n );\n if (credentials.hasConnectionString && printConnectionString) {\n await logConnectionStringDetails();\n }\n }\n}\nexport async function createTableFromCSV(\n csvFilePath: string,\n credentials: Credentials,", "score": 0.8700723648071289 }, { "filename": "src/utils/workflows.ts", "retrieved_chunk": "}\n// Generates a CRUD workflow for tableName from a template.\nexport async function generateCRUDWorkflow(\n tableName: string,\n credentials: Credentials\n) {\n let spinner = ora(\"Creating workflow\").start();\n // Generate workflow metadata via puppeteer.\n // Dynamic import b/c puppeteer is slow.\n const workflowMeta = await import(\"./puppeteer\").then(", "score": 0.8620030879974365 }, { "filename": "src/utils/table.ts", "retrieved_chunk": " const { headers, rows } = parseResult;\n await createTable(\n tableName,\n headers,\n rows,\n credentials,\n printConnectionString\n );\n return {\n tableName,", "score": 0.8560961484909058 }, { "filename": "src/utils/table.ts", "retrieved_chunk": " console.log(`Deleted ${tableName} table. 🗑️`);\n}\nexport async function createTable(\n tableName: string,\n headers: string[],\n rows: string[][] | undefined,\n credentials: Credentials,\n printConnectionString: boolean\n) {\n const spinner = ora(\"Uploading Table\").start();", "score": 0.854137122631073 } ]
typescript
generateCRUDWorkflow(tableName, credentials);
import { bech32 } from "@scure/base"; import EventEmitter from "eventemitter3"; import { nip57 } from "nostr-tools"; import type { NostrEvent } from "../events/index.js"; import NDKEvent, { NDKTag } from "../events/index.js"; import NDK from "../index.js"; import User from "../user/index.js"; const DEFAULT_RELAYS = [ "wss://nos.lol", "wss://relay.nostr.band", "wss://relay.f7z.io", "wss://relay.damus.io", "wss://nostr.mom", "wss://no.str.cr", ]; interface ZapConstructorParams { ndk: NDK; zappedEvent?: NDKEvent; zappedUser?: User; } type ZapConstructorParamsRequired = Required< Pick<ZapConstructorParams, "zappedEvent"> > & Pick<ZapConstructorParams, "zappedUser"> & ZapConstructorParams; export default class Zap extends EventEmitter { public ndk?: NDK; public zappedEvent?: NDKEvent; public zappedUser: User; public constructor(args: ZapConstructorParamsRequired) { super(); this.ndk = args.ndk; this.zappedEvent = args.zappedEvent; this.zappedUser = args.zappedUser || this.ndk.getUser({ hexpubkey: this.zappedEvent.pubkey }); } public async getZapEndpoint(): Promise<string | undefined> { let lud06: string | undefined; let lud16: string | undefined; let zapEndpoint: string | undefined; let zapEndpointCallback: string | undefined; if (this.zappedEvent) { const zapTag = (await this.zappedEvent.getMatchingTags("zap"))[0]; if (zapTag) { switch (zapTag[2]) { case "lud06": lud06 = zapTag[1]; break; case "lud16": lud16 = zapTag[1]; break; default: throw new Error(`Unknown zap tag ${zapTag}`); } } } if (this.zappedUser && !lud06 && !lud16) { // check if user has a profile, otherwise request it if (!this.zappedUser.profile) { await this.zappedUser.fetchProfile(); } lud06 = (this.zappedUser.profile || {}).lud06; lud16 = (this.zappedUser.profile || {}).lud16; } if (lud16) { const [name, domain] = lud16.split("@"); zapEndpoint = `https://${domain}/.well-known/lnurlp/${name}`; } else if (lud06) { const { words } = bech32.decode(lud06, 1000); const data = bech32.fromWords(words); const utf8Decoder = new TextDecoder("utf-8"); zapEndpoint = utf8Decoder.decode(data); } if (!zapEndpoint) { throw new Error("No zap endpoint found"); } const response = await fetch(zapEndpoint); const body = await response.json(); if (body?.allowsNostr && (body?.nostrPubkey || body?.nostrPubKey)) { zapEndpointCallback = body.callback; } return zapEndpointCallback; } /** * Generates a kind:9734 zap request and returns the payment request * @param amount amount to zap in millisatoshis * @param comment optional comment to include in the zap request * @param extraTags optional extra tags to include in the zap request * @param relays optional relays to ask zapper to publish the zap to * @returns the payment request */ public async createZapRequest( amount: number, // amount to zap in millisatoshis comment?: string, extraTags?: NDKTag[], relays?: string[] ): Promise<string | null> { const zapEndpoint = await this.getZapEndpoint(); if (!zapEndpoint) { throw new Error("No zap endpoint found"); } if (!this.zappedEvent) throw new Error("No zapped event found"); const zapRequest = nip57.makeZapRequest({ profile: this.zappedUser.hexpubkey(), // set the event to null since nostr-tools doesn't support nip-33 zaps event: null, amount, comment: comment || "", relays: relays ?? this.relays(), }); // add the event tag if it exists; this supports both 'e' and 'a' tags if (this.zappedEvent) { const tag = this.zappedEvent.tagReference(); if (tag) { zapRequest.tags.push(tag); } } zapRequest.tags.push(["lnurl", zapEndpoint]); const zapRequestEvent = new NDKEvent( this.ndk,
zapRequest as NostrEvent );
if (extraTags) { zapRequestEvent.tags = zapRequestEvent.tags.concat(extraTags); } await zapRequestEvent.sign(); const zapRequestNostrEvent = await zapRequestEvent.toNostrEvent(); const response = await fetch( `${zapEndpoint}?` + new URLSearchParams({ amount: amount.toString(), nostr: JSON.stringify(zapRequestNostrEvent), }) ); const body = await response.json(); return body.pr; } /** * @returns the relays to use for the zap request */ private relays(): string[] { let r: string[] = []; if (this.ndk?.pool?.relays) { r = this.ndk.pool.urls(); } if (!r.length) { r = DEFAULT_RELAYS; } return r; } }
src/zap/index.ts
nostr-dev-kit-ndk-ece64e1
[ { "filename": "src/events/index.ts", "retrieved_chunk": " async zap(\n amount: number,\n comment?: string,\n extraTags?: NDKTag[]\n ): Promise<string | null> {\n if (!this.ndk) throw new Error(\"No NDK instance found\");\n this.ndk.assertSigner();\n const zap = new Zap({\n ndk: this.ndk,\n zappedEvent: this,", "score": 0.8575601577758789 }, { "filename": "src/events/kinds/dvm/NDKDVMJobResult.ts", "retrieved_chunk": " this.tags.push([\"request\", JSON.stringify(event.rawEvent())]);\n this.tag(event);\n }\n }\n get jobRequest(): NDKEvent | undefined {\n const tag = this.tagValue(\"request\");\n if (tag === undefined) {\n return undefined;\n }\n return new NDKEvent(this.ndk, JSON.parse(tag));", "score": 0.8483407497406006 }, { "filename": "src/events/index.ts", "retrieved_chunk": "import EventEmitter from \"eventemitter3\";\nimport { getEventHash, UnsignedEvent } from \"nostr-tools\";\nimport NDK, { NDKFilter, NDKRelay, NDKRelaySet, NDKUser } from \"../index.js\";\nimport { NDKSigner } from \"../signers/index.js\";\nimport Zap from \"../zap/index.js\";\nimport { generateContentTags } from \"./content-tagger.js\";\nimport { isParamReplaceable, isReplaceable } from \"./kind.js\";\nimport { NDKKind } from \"./kinds/index.js\";\nimport { decrypt, encrypt } from \"./nip04.js\";\nimport { encode } from \"./nip19.js\";", "score": 0.8471720218658447 }, { "filename": "src/events/index.test.ts", "retrieved_chunk": " } as NostrEvent);\n otherEvent.author = user1;\n event.tag(otherEvent);\n expect(event.tags).toEqual([[\"e\", otherEvent.id]]);\n });\n it(\"tags an event with a marker\", () => {\n const otherEvent = new NDKEvent(ndk, {\n id: \"123\",\n kind: 1,\n } as NostrEvent);", "score": 0.8400437831878662 }, { "filename": "src/events/repost.ts", "retrieved_chunk": " if (!signer) {\n throw new Error(\"No signer available\");\n }\n const user = await signer.user();\n const e = new NDKEvent(this.ndk, {\n kind: getKind(this),\n content: \"\",\n pubkey: user.hexpubkey(),\n } as NostrEvent);\n e.tag(this);", "score": 0.8358687162399292 } ]
typescript
zapRequest as NostrEvent );
import { CommandModule } from "yargs"; import { createAppForTable, deleteApp } from "../utils/apps"; import { Credentials, getAndVerifyCredentialsWithRetoolDB, } from "../utils/credentials"; import { getRequest, postRequest } from "../utils/networking"; import { collectColumnNames, collectTableName, createTable, createTableFromCSV, deleteTable, generateDataWithGPT, } from "../utils/table"; import type { DBInfoPayload } from "../utils/table"; import { logDAU } from "../utils/telemetry"; import { deleteWorkflow, generateCRUDWorkflow } from "../utils/workflows"; const inquirer = require("inquirer"); const command = "scaffold"; const describe = "Scaffold a Retool DB table, CRUD Workflow, and App."; const builder: CommandModule["builder"] = { name: { alias: "n", describe: `Name of table to scaffold. Usage: retool scaffold -n <table_name>`, type: "string", nargs: 1, }, columns: { alias: "c", describe: `Column names in DB to scaffold. Usage: retool scaffold -c <col1> <col2>`, type: "array", }, delete: { alias: "d", describe: `Delete a table, Workflow and App created via scaffold. Usage: retool scaffold -d <db_name>`, type: "string", nargs: 1, }, "from-csv": { alias: "f", describe: `Create a table, Workflow and App from a CSV file. Usage: retool scaffold -f <path-to-csv>`, type: "array", }, "no-workflow": { describe: `Modifier to avoid generating Workflow. Usage: retool scaffold --no-workflow`, type: "boolean", }, }; const handler = async function (argv: any) { const credentials = await getAndVerifyCredentialsWithRetoolDB(); // fire and forget void logDAU(credentials); // Handle `retool scaffold -d <db_name>` if (argv.delete) { const tableName = argv.delete; const workflowName = `${tableName} CRUD Workflow`; // Confirm deletion. const { confirm } = await inquirer.prompt([ { name: "confirm", message: `Are you sure you want to delete ${tableName} table, CRUD workflow and app?`, type: "confirm", }, ]); if (!confirm) { process.exit(0); } //TODO: Could be parallelized. //TODO: Verify existence before trying to delete. await deleteTable(tableName, credentials, false); await deleteWorkflow(workflowName, credentials, false);
await deleteApp(`${tableName} App`, credentials, false);
} // Handle `retool scaffold -f <path-to-csv>` else if (argv.f) { const csvFileNames = argv.f; for (const csvFileName of csvFileNames) { const { tableName, colNames } = await createTableFromCSV( csvFileName, credentials, false, false ); if (!argv["no-workflow"]) { console.log("\n"); await generateCRUDWorkflow(tableName, credentials); } console.log("\n"); const searchColumnName = colNames.length > 0 ? colNames[0] : "id"; await createAppForTable( `${tableName} App`, tableName, searchColumnName, credentials ); console.log(""); } } // Handle `retool scaffold` else { let tableName = argv.name; let colNames = argv.columns; if (!tableName || tableName.length == 0) { tableName = await collectTableName(); } if (!colNames || colNames.length == 0) { colNames = await collectColumnNames(); } await createTable(tableName, colNames, undefined, credentials, false); // Fire and forget void insertSampleData(tableName, credentials); if (!argv["no-workflow"]) { console.log("\n"); await generateCRUDWorkflow(tableName, credentials); } console.log("\n"); const searchColumnName = colNames.length > 0 ? colNames[0] : "id"; await createAppForTable( `${tableName} App`, tableName, searchColumnName, credentials ); } }; const insertSampleData = async function ( tableName: string, credentials: Credentials ) { const infoRes = await getRequest( `${credentials.origin}/api/grid/${credentials.gridId}/table/${tableName}/info`, false ); const retoolDBInfo: DBInfoPayload = infoRes.data; const { fields } = retoolDBInfo.tableInfo; const generatedData = await generateDataWithGPT( retoolDBInfo, fields, 0, credentials, false ); if (generatedData) { await postRequest( `${credentials.origin}/api/grid/${credentials.gridId}/action`, { kind: "BulkInsertIntoTable", tableName: tableName, additions: generatedData, } ); } }; const commandModule: CommandModule = { command, describe, builder, handler, }; export default commandModule;
src/commands/scaffold.ts
tryretool-retool-cli-91b2c68
[ { "filename": "src/utils/table.ts", "retrieved_chunk": " message: `Are you sure you want to delete the ${tableName} table?`,\n type: \"confirm\",\n },\n ]);\n if (!confirm) {\n process.exit(0);\n }\n }\n // Delete the table.\n const spinner = ora(`Deleting ${tableName}`).start();", "score": 0.8901719450950623 }, { "filename": "src/utils/workflows.ts", "retrieved_chunk": " if (!confirm) {\n process.exit(0);\n }\n }\n // Verify that the provided workflowName exists.\n const { workflows } = await getWorkflowsAndFolders(credentials);\n const workflow = workflows?.filter((workflow) => {\n if (workflow.name === workflowName) {\n return workflow;\n }", "score": 0.8801488876342773 }, { "filename": "src/utils/table.ts", "retrieved_chunk": " tableName: string,\n credentials: Credentials,\n confirmDeletion: boolean\n) {\n // Verify that the provided table name exists.\n await verifyTableExists(tableName, credentials);\n if (confirmDeletion) {\n const { confirm } = await inquirer.prompt([\n {\n name: \"confirm\",", "score": 0.8777735829353333 }, { "filename": "src/utils/workflows.ts", "retrieved_chunk": " });\n if (workflow?.length != 1) {\n console.log(`0 or >1 Workflows named ${workflowName} found. 😓`);\n process.exit(1);\n }\n // Delete the Workflow.\n const spinner = ora(`Deleting ${workflowName}`).start();\n await deleteRequest(`${credentials.origin}/api/workflow/${workflow[0].id}`);\n spinner.stop();\n console.log(`Deleted ${workflowName}. 🗑️`);", "score": 0.874228835105896 }, { "filename": "src/commands/db.ts", "retrieved_chunk": " }\n // Handle `retool db --delete <table-name>`\n else if (argv.delete) {\n const tableNames = argv.delete;\n for (const tableName of tableNames) {\n await deleteTable(tableName, credentials, true);\n }\n }\n // Handle `retool db --gendata <table-name>`\n else if (argv.gendata) {", "score": 0.8690550327301025 } ]
typescript
await deleteApp(`${tableName} App`, credentials, false);
import { CommandModule } from "yargs"; import { logSuccess } from "./login"; import { accessTokenFromCookies, xsrfTokenFromCookies } from "../utils/cookies"; import { doCredentialsExist, persistCredentials } from "../utils/credentials"; import { getRequest, postRequest } from "../utils/networking"; import { logDAU } from "../utils/telemetry"; import { isEmailValid } from "../utils/validation"; const axios = require("axios"); const inquirer = require("inquirer"); const ora = require("ora"); const command = "signup"; const describe = "Create a Retool account."; const builder = {}; // eslint-disable-next-line @typescript-eslint/no-unused-vars const handler = async function (argv: any) { // Ask user if they want to overwrite existing credentials. if (doCredentialsExist()) { const { overwrite } = await inquirer.prompt([ { name: "overwrite", message: "You're already logged in. Do you want to log out and create a new account?", type: "confirm", }, ]); if (!overwrite) { return; } } // Step 1: Collect a valid email/password. let email, password, name, org; while (!email) { email = await collectEmail(); } while (!password) { password = await colllectPassword(); } // Step 2: Call signup endpoint, get cookies. const spinner = ora( "Verifying that the email and password are valid on the server" ).start(); const signupResponse = await postRequest( `https://login.retool.com/api/signup`, { email, password, planKey: "free", } ); spinner.stop(); const accessToken = accessTokenFromCookies( signupResponse.headers["set-cookie"] ); const xsrfToken = xsrfTokenFromCookies(signupResponse.headers["set-cookie"]); if (!accessToken || !xsrfToken) { if (process.env.DEBUG) { console.log(signupResponse); } console.log( "Error creating account, please try again or signup at https://login.retool.com/auth/signup?plan=free." ); return; } axios.defaults.headers["x-xsrf-token"] = xsrfToken; axios.defaults.headers.cookie = `accessToken=${accessToken};`; // Step 3: Collect a valid name/org. while (!name) { name = await collectName(); } while (!org) { org = await collectOrg(); } // Step 4: Initialize organization. await postRequest( `https://login.retool.com/api/organization/admin/initializeOrganization`, { subdomain: org, } ); // Step 5: Persist credentials const origin = `https://${org}.retool.com`; const userRes =
await getRequest(`${origin}/api/user`);
persistCredentials({ origin, accessToken, xsrf: xsrfToken, firstName: userRes.data.user?.firstName, lastName: userRes.data.user?.lastName, email: userRes.data.user?.email, telemetryEnabled: true, }); logSuccess(); await logDAU(); }; async function collectEmail(): Promise<string | undefined> { const { email } = await inquirer.prompt([ { name: "email", message: "What is your email?", type: "input", }, ]); if (!isEmailValid(email)) { console.log("Invalid email, try again."); return; } return email; } async function colllectPassword(): Promise<string | undefined> { const { password } = await inquirer.prompt([ { name: "password", message: "Please create a password (min 8 characters):", type: "password", }, ]); const { confirmedPassword } = await inquirer.prompt([ { name: "confirmedPassword", message: "Please confirm password:", type: "password", }, ]); if (password.length < 8) { console.log("Password must be at least 8 characters long, try again."); return; } if (password !== confirmedPassword) { console.log("Passwords do not match, try again."); return; } return password; } async function collectName(): Promise<string | undefined> { const { name } = await inquirer.prompt([ { name: "name", message: "What is your first and last name?", type: "input", }, ]); if (!name || name.length === 0) { console.log("Invalid name, try again."); return; } const parts = name.split(" "); const changeNameResponse = await postRequest( `https://login.retool.com/api/user/changeName`, { firstName: parts[0], lastName: parts[1], }, false ); if (!changeNameResponse) { return; } return name; } async function collectOrg(): Promise<string | undefined> { let { org } = await inquirer.prompt([ { name: "org", message: "What is your organization name? Leave blank to generate a random name.", type: "input", }, ]); if (!org || org.length === 0) { // Org must start with letter, append a random string after it. // https://stackoverflow.com/a/8084248 org = "z" + (Math.random() + 1).toString(36).substring(2); } const checkSubdomainAvailabilityResponse = await getRequest( `https://login.retool.com/api/organization/admin/checkSubdomainAvailability?subdomain=${org}`, false ); if (!checkSubdomainAvailabilityResponse.status) { return; } return org; } const commandModule: CommandModule = { command, describe, builder, handler }; export default commandModule;
src/commands/signup.ts
tryretool-retool-cli-91b2c68
[ { "filename": "src/commands/login.ts", "retrieved_chunk": " // Step 1: Hit /api/login with email and password.\n const login = await postRequest(`${loginOrigin}/api/login`, {\n email,\n password,\n });\n const { authUrl, authorizationToken } = login.data;\n if (!authUrl || !authorizationToken) {\n console.log(\"Error logging in, please try again\");\n return;\n }", "score": 0.8566437363624573 }, { "filename": "src/commands/login.ts", "retrieved_chunk": " // Step 2: Hit /auth/saveAuth with authorizationToken.\n const authResponse = await postRequest(\n localhost ? `${loginOrigin}${authUrl}` : authUrl,\n {\n authorizationToken,\n },\n true,\n {\n origin: loginOrigin,\n }", "score": 0.8476970195770264 }, { "filename": "src/utils/puppeteer.ts", "retrieved_chunk": " if (!credentials) {\n return;\n }\n try {\n // Launch Puppeteer and navigate to subdomain.retool.com/workflows\n const browser = await puppeteer.launch({\n headless: \"new\",\n // Uncomment this line to see the browser in action\n // headless: false,\n });", "score": 0.8309630155563354 }, { "filename": "src/utils/credentials.ts", "retrieved_chunk": " let credentials = getCredentials();\n if (!credentials) {\n spinner.stop();\n console.log(\n `Error: No credentials found. To log in, run: \\`retool login\\``\n );\n process.exit(1);\n }\n axios.defaults.headers[\"x-xsrf-token\"] = credentials.xsrf;\n axios.defaults.headers.cookie = `accessToken=${credentials.accessToken};`;", "score": 0.8303060531616211 }, { "filename": "src/commands/login.ts", "retrieved_chunk": " telemetryEnabled: true,\n });\n logSuccess();\n res.sendFile(path.join(__dirname, \"../loginPages/loginSuccess.html\"));\n server_online = false;\n });\n const server = app.listen(3020);\n // Step 1: Open up the google SSO page in the browser.\n // Step 2: User accepts the SSO request.\n open(`https://login.retool.com/googlelogin?retoolCliRedirect=true`);", "score": 0.8288528919219971 } ]
typescript
await getRequest(`${origin}/api/user`);
import { CommandModule } from "yargs"; import { logSuccess } from "./login"; import { accessTokenFromCookies, xsrfTokenFromCookies } from "../utils/cookies"; import { doCredentialsExist, persistCredentials } from "../utils/credentials"; import { getRequest, postRequest } from "../utils/networking"; import { logDAU } from "../utils/telemetry"; import { isEmailValid } from "../utils/validation"; const axios = require("axios"); const inquirer = require("inquirer"); const ora = require("ora"); const command = "signup"; const describe = "Create a Retool account."; const builder = {}; // eslint-disable-next-line @typescript-eslint/no-unused-vars const handler = async function (argv: any) { // Ask user if they want to overwrite existing credentials. if (doCredentialsExist()) { const { overwrite } = await inquirer.prompt([ { name: "overwrite", message: "You're already logged in. Do you want to log out and create a new account?", type: "confirm", }, ]); if (!overwrite) { return; } } // Step 1: Collect a valid email/password. let email, password, name, org; while (!email) { email = await collectEmail(); } while (!password) { password = await colllectPassword(); } // Step 2: Call signup endpoint, get cookies. const spinner = ora( "Verifying that the email and password are valid on the server" ).start(); const signupResponse = await postRequest( `https://login.retool.com/api/signup`, { email, password, planKey: "free", } ); spinner.stop(); const accessToken = accessTokenFromCookies( signupResponse.headers["set-cookie"] ); const xsrfToken = xsrfTokenFromCookies(signupResponse.headers["set-cookie"]); if (!accessToken || !xsrfToken) { if (process.env.DEBUG) { console.log(signupResponse); } console.log( "Error creating account, please try again or signup at https://login.retool.com/auth/signup?plan=free." ); return; } axios.defaults.headers["x-xsrf-token"] = xsrfToken; axios.defaults.headers.cookie = `accessToken=${accessToken};`; // Step 3: Collect a valid name/org. while (!name) { name = await collectName(); } while (!org) { org = await collectOrg(); } // Step 4: Initialize organization. await postRequest( `https://login.retool.com/api/organization/admin/initializeOrganization`, { subdomain: org, } ); // Step 5: Persist credentials const origin = `https://${org}.retool.com`; const userRes = await getRequest(`${origin}/api/user`); persistCredentials({ origin, accessToken, xsrf: xsrfToken, firstName: userRes.data.user?.firstName, lastName: userRes.data.user?.lastName, email: userRes.data.user?.email, telemetryEnabled: true, }); logSuccess(); await logDAU(); }; async function collectEmail(): Promise<string | undefined> { const { email } = await inquirer.prompt([ { name: "email", message: "What is your email?", type: "input", }, ]); if (
!isEmailValid(email)) {
console.log("Invalid email, try again."); return; } return email; } async function colllectPassword(): Promise<string | undefined> { const { password } = await inquirer.prompt([ { name: "password", message: "Please create a password (min 8 characters):", type: "password", }, ]); const { confirmedPassword } = await inquirer.prompt([ { name: "confirmedPassword", message: "Please confirm password:", type: "password", }, ]); if (password.length < 8) { console.log("Password must be at least 8 characters long, try again."); return; } if (password !== confirmedPassword) { console.log("Passwords do not match, try again."); return; } return password; } async function collectName(): Promise<string | undefined> { const { name } = await inquirer.prompt([ { name: "name", message: "What is your first and last name?", type: "input", }, ]); if (!name || name.length === 0) { console.log("Invalid name, try again."); return; } const parts = name.split(" "); const changeNameResponse = await postRequest( `https://login.retool.com/api/user/changeName`, { firstName: parts[0], lastName: parts[1], }, false ); if (!changeNameResponse) { return; } return name; } async function collectOrg(): Promise<string | undefined> { let { org } = await inquirer.prompt([ { name: "org", message: "What is your organization name? Leave blank to generate a random name.", type: "input", }, ]); if (!org || org.length === 0) { // Org must start with letter, append a random string after it. // https://stackoverflow.com/a/8084248 org = "z" + (Math.random() + 1).toString(36).substring(2); } const checkSubdomainAvailabilityResponse = await getRequest( `https://login.retool.com/api/organization/admin/checkSubdomainAvailability?subdomain=${org}`, false ); if (!checkSubdomainAvailabilityResponse.status) { return; } return org; } const commandModule: CommandModule = { command, describe, builder, handler }; export default commandModule;
src/commands/signup.ts
tryretool-retool-cli-91b2c68
[ { "filename": "src/utils/apps.ts", "retrieved_chunk": " return {\n apps: fetchAppsResponse?.data?.pages,\n folders: fetchAppsResponse?.data?.folders,\n };\n}\nexport async function collectAppName(): Promise<string> {\n const { appName } = await inquirer.prompt([\n {\n name: \"appName\",\n message: \"App name?\",", "score": 0.841305136680603 }, { "filename": "src/commands/login.ts", "retrieved_chunk": "};\n// Ask the user to input their email and password.\n// Fire off a request to Retool's login & auth endpoints.\n// Persist the credentials.\nasync function loginViaEmail(localhost = false) {\n const { email, password } = await inquirer.prompt([\n {\n name: \"email\",\n message: \"What is your email?\",\n type: \"input\",", "score": 0.8378098011016846 }, { "filename": "src/utils/table.ts", "retrieved_chunk": " return {\n fields: colNames,\n data: generatedRows,\n };\n}\nexport async function collectTableName(): Promise<string> {\n const { tableName } = await inquirer.prompt([\n {\n name: \"tableName\",\n message: \"Table name?\",", "score": 0.8305871486663818 }, { "filename": "src/utils/validation.ts", "retrieved_chunk": "/* eslint-disable */\nconst emailRegex =\n /^[-!#$%&'*+\\/0-9=?A-Z^_a-z{|}~](\\.?[-!#$%&'*+\\/0-9=?A-Z^_a-z`{|}~])*@[a-zA-Z0-9](-*\\.?[a-zA-Z0-9])*\\.[a-zA-Z](-?[a-zA-Z0-9])+$/;\n/* eslint-enable */\n//https://stackoverflow.com/questions/52456065/how-to-format-and-validate-email-node-js\nexport function isEmailValid(email: string) {\n if (!email) return false;\n if (email.length > 254) return false;\n if (!emailRegex.test(email)) return false;\n // Further checking of some things regex can't handle", "score": 0.8281190395355225 }, { "filename": "src/utils/table.ts", "retrieved_chunk": " const { columnName } = await inquirer.prompt([\n {\n name: \"columnName\",\n message: \"Column name? Leave blank to finish.\",\n type: \"input\",\n },\n ]);\n // Remove spaces from column name.\n return columnName.replace(/\\s/g, \"_\");\n}", "score": 0.8152444958686829 } ]
typescript
!isEmailValid(email)) {
import { CommandModule } from "yargs"; import { logSuccess } from "./login"; import { accessTokenFromCookies, xsrfTokenFromCookies } from "../utils/cookies"; import { doCredentialsExist, persistCredentials } from "../utils/credentials"; import { getRequest, postRequest } from "../utils/networking"; import { logDAU } from "../utils/telemetry"; import { isEmailValid } from "../utils/validation"; const axios = require("axios"); const inquirer = require("inquirer"); const ora = require("ora"); const command = "signup"; const describe = "Create a Retool account."; const builder = {}; // eslint-disable-next-line @typescript-eslint/no-unused-vars const handler = async function (argv: any) { // Ask user if they want to overwrite existing credentials. if (doCredentialsExist()) { const { overwrite } = await inquirer.prompt([ { name: "overwrite", message: "You're already logged in. Do you want to log out and create a new account?", type: "confirm", }, ]); if (!overwrite) { return; } } // Step 1: Collect a valid email/password. let email, password, name, org; while (!email) { email = await collectEmail(); } while (!password) { password = await colllectPassword(); } // Step 2: Call signup endpoint, get cookies. const spinner = ora( "Verifying that the email and password are valid on the server" ).start(); const signupResponse = await postRequest( `https://login.retool.com/api/signup`, { email, password, planKey: "free", } ); spinner.stop(); const
accessToken = accessTokenFromCookies( signupResponse.headers["set-cookie"] );
const xsrfToken = xsrfTokenFromCookies(signupResponse.headers["set-cookie"]); if (!accessToken || !xsrfToken) { if (process.env.DEBUG) { console.log(signupResponse); } console.log( "Error creating account, please try again or signup at https://login.retool.com/auth/signup?plan=free." ); return; } axios.defaults.headers["x-xsrf-token"] = xsrfToken; axios.defaults.headers.cookie = `accessToken=${accessToken};`; // Step 3: Collect a valid name/org. while (!name) { name = await collectName(); } while (!org) { org = await collectOrg(); } // Step 4: Initialize organization. await postRequest( `https://login.retool.com/api/organization/admin/initializeOrganization`, { subdomain: org, } ); // Step 5: Persist credentials const origin = `https://${org}.retool.com`; const userRes = await getRequest(`${origin}/api/user`); persistCredentials({ origin, accessToken, xsrf: xsrfToken, firstName: userRes.data.user?.firstName, lastName: userRes.data.user?.lastName, email: userRes.data.user?.email, telemetryEnabled: true, }); logSuccess(); await logDAU(); }; async function collectEmail(): Promise<string | undefined> { const { email } = await inquirer.prompt([ { name: "email", message: "What is your email?", type: "input", }, ]); if (!isEmailValid(email)) { console.log("Invalid email, try again."); return; } return email; } async function colllectPassword(): Promise<string | undefined> { const { password } = await inquirer.prompt([ { name: "password", message: "Please create a password (min 8 characters):", type: "password", }, ]); const { confirmedPassword } = await inquirer.prompt([ { name: "confirmedPassword", message: "Please confirm password:", type: "password", }, ]); if (password.length < 8) { console.log("Password must be at least 8 characters long, try again."); return; } if (password !== confirmedPassword) { console.log("Passwords do not match, try again."); return; } return password; } async function collectName(): Promise<string | undefined> { const { name } = await inquirer.prompt([ { name: "name", message: "What is your first and last name?", type: "input", }, ]); if (!name || name.length === 0) { console.log("Invalid name, try again."); return; } const parts = name.split(" "); const changeNameResponse = await postRequest( `https://login.retool.com/api/user/changeName`, { firstName: parts[0], lastName: parts[1], }, false ); if (!changeNameResponse) { return; } return name; } async function collectOrg(): Promise<string | undefined> { let { org } = await inquirer.prompt([ { name: "org", message: "What is your organization name? Leave blank to generate a random name.", type: "input", }, ]); if (!org || org.length === 0) { // Org must start with letter, append a random string after it. // https://stackoverflow.com/a/8084248 org = "z" + (Math.random() + 1).toString(36).substring(2); } const checkSubdomainAvailabilityResponse = await getRequest( `https://login.retool.com/api/organization/admin/checkSubdomainAvailability?subdomain=${org}`, false ); if (!checkSubdomainAvailabilityResponse.status) { return; } return org; } const commandModule: CommandModule = { command, describe, builder, handler }; export default commandModule;
src/commands/signup.ts
tryretool-retool-cli-91b2c68
[ { "filename": "src/commands/login.ts", "retrieved_chunk": " // Step 1: Hit /api/login with email and password.\n const login = await postRequest(`${loginOrigin}/api/login`, {\n email,\n password,\n });\n const { authUrl, authorizationToken } = login.data;\n if (!authUrl || !authorizationToken) {\n console.log(\"Error logging in, please try again\");\n return;\n }", "score": 0.8477556109428406 }, { "filename": "src/commands/login.ts", "retrieved_chunk": " );\n const { redirectUri } = authResponse.data;\n const redirectUrl = localhost\n ? new URL(loginOrigin)\n : redirectUri\n ? new URL(redirectUri)\n : undefined;\n const accessToken = accessTokenFromCookies(\n authResponse.headers[\"set-cookie\"]\n );", "score": 0.8473255634307861 }, { "filename": "src/utils/credentials.ts", "retrieved_chunk": " process.exit(1);\n }\n axios.defaults.headers[\"x-xsrf-token\"] = credentials.xsrf;\n axios.defaults.headers.cookie = `accessToken=${credentials.accessToken};`;\n spinner.stop();\n return credentials;\n}", "score": 0.8456023931503296 }, { "filename": "src/commands/login.ts", "retrieved_chunk": " const xsrfToken = xsrfTokenFromCookies(authResponse.headers[\"set-cookie\"]);\n // Step 3: Persist the credentials.\n if (redirectUrl?.origin && accessToken && xsrfToken) {\n persistCredentials({\n origin: redirectUrl.origin,\n accessToken,\n xsrf: xsrfToken,\n firstName: authResponse.data.user?.firstName,\n lastName: authResponse.data.user?.lastName,\n email: authResponse.data.user?.email,", "score": 0.8382459282875061 }, { "filename": "src/utils/credentials.ts", "retrieved_chunk": " let credentials = getCredentials();\n if (!credentials) {\n spinner.stop();\n console.log(\n `Error: No credentials found. To log in, run: \\`retool login\\``\n );\n process.exit(1);\n }\n axios.defaults.headers[\"x-xsrf-token\"] = credentials.xsrf;\n axios.defaults.headers.cookie = `accessToken=${credentials.accessToken};`;", "score": 0.8342299461364746 } ]
typescript
accessToken = accessTokenFromCookies( signupResponse.headers["set-cookie"] );
import { Credentials } from "./credentials"; import { getRequest, postRequest } from "./networking"; export type ResourceByEnv = Record<string, Resource>; export type Resource = { displayName: string; id: number; name: string; type: string; environment: string; environmentId: string; uuid: string; organizationId: number; resourceFolderId: number; }; export async function getResourceByName( resourceName: string, credentials: Credentials ): Promise<ResourceByEnv> { const getResourceResult = await getRequest( `${credentials.origin}/api/resources/names/${resourceName}` ); const { resourceByEnv } = getResourceResult.data; if (!resourceByEnv) { console.log("Error finding resource by that id."); console.log(getResourceResult.data); process.exit(1); } else { return resourceByEnv; } } export async function createResource({ resourceType, credentials, displayName, resourceFolderId, resourceOptions, }: { resourceType: string; credentials: Credentials; displayName?: string; resourceFolderId?: number; resourceOptions?: Record<string, any>; }): Promise<Resource> {
const createResourceResult = await postRequest( `${credentials.origin}/api/resources/`, {
type: resourceType, displayName, resourceFolderId, options: resourceOptions ? resourceOptions : {}, }, false, {}, false ); const resource = createResourceResult.data; if (!resource) { throw new Error("Error creating resource."); } else { return resource; } }
src/utils/resources.ts
tryretool-retool-cli-91b2c68
[ { "filename": "src/commands/rpc.ts", "retrieved_chunk": " type: \"input\",\n validate: async (displayName: string) => {\n try {\n const resource = await createResource({\n resourceType: \"retoolSdk\",\n credentials,\n resourceOptions: {\n requireExplicitVersion: false,\n },\n displayName,", "score": 0.8352020978927612 }, { "filename": "src/utils/playgroundQuery.ts", "retrieved_chunk": " credentials: Credentials,\n queryName?: string\n): Promise<PlaygroundQuery> {\n const createPlaygroundQueryResult = await postRequest(\n `${credentials.origin}/api/playground`,\n {\n name: queryName || \"CLI Generated RPC Query\",\n description: \"\",\n shared: false,\n resourceId,", "score": 0.8325205445289612 }, { "filename": "src/utils/playgroundQuery.ts", "retrieved_chunk": " organizationId: number;\n ownerId: number;\n saveId: number;\n template: Record<string, any>;\n resourceId: number;\n resourceUuid: string;\n adhocResourceType: string;\n};\nexport async function createPlaygroundQuery(\n resourceId: number,", "score": 0.8230995535850525 }, { "filename": "src/commands/rpc.ts", "retrieved_chunk": " });\n resourceName = resource.name;\n resourceId = resource.id;\n return true;\n } catch (error: any) {\n return (\n error.response?.data?.message || \"API call failed creating resource\"\n );\n }\n },", "score": 0.8200451731681824 }, { "filename": "src/utils/playgroundQuery.ts", "retrieved_chunk": "import { Credentials } from \"./credentials\";\nimport { postRequest } from \"./networking\";\nexport type PlaygroundQuery = {\n id: number;\n uuid: string;\n name: string;\n description: string;\n shared: boolean;\n createdAt: string;\n updatedAt: string;", "score": 0.8027528524398804 } ]
typescript
const createResourceResult = await postRequest( `${credentials.origin}/api/resources/`, {
import Actor from "./actor"; import { Timer } from "./performance"; import { CancelablePromise } from "./types"; class Local { received: any[][] = []; localAction = (x: number, y: number, z: number): CancelablePromise<void> => { this.received.push([x, y, z]); return { cancel() {}, value: Promise.resolve() }; }; } class Remote { received: any[][] = []; canceled = false; remoteAction = (x: number, y: number, z: number): CancelablePromise<void> => { this.received.push([x, y, z]); return { cancel() {}, value: Promise.resolve() }; }; remotePromise = (x: number, timer?: Timer): CancelablePromise<number> => { const oldNow = performance.now; if (timer) timer.timeOrigin = 100; performance.now = () => oldNow() - 100; const finish = timer?.marker("fetch"); performance.now = () => oldNow() - 99; finish?.(); performance.now = () => oldNow() + 2; return { cancel() { throw new Error("not expected"); }, value: Promise.resolve(x), }; }; remoteFail = (): CancelablePromise<number> => ({ cancel() {}, value: Promise.reject(new Error("error")), }); remoteNever = (): CancelablePromise<number> => ({ cancel: () => { this.canceled = true; }, value: new Promise(() => {}), }); } test("send and cancel messages", async () => { performance.now = () => 1; const remote = new Remote(); const local = new Local(); const workerFromMainThread: Worker = {} as any as Worker; const mainThreadFromWorker: Worker = {} as any as Worker; workerFromMainThread.postMessage = (data) => //@ts-ignore mainThreadFromWorker?.onmessage?.({ data }); mainThreadFromWorker.postMessage = (data) => //@ts-ignore workerFromMainThread?.onmessage?.({ data });
const mainActor = new Actor<Remote>(workerFromMainThread, local);
const workerActor = new Actor<Local>(mainThreadFromWorker, remote); mainActor.send("remoteAction", [], undefined, 1, 2, 3); expect(remote.received).toEqual([[1, 2, 3]]); workerActor.send("localAction", [], undefined, 4, 3, 2); expect(local.received).toEqual([[4, 3, 2]]); const timer = new Timer("main"); timer.timeOrigin = 0; expect(await mainActor.send("remotePromise", [], timer, 9).value).toBe(9); expect(timer.finish("url")).toMatchObject({ duration: 2, fetch: 1, marks: { fetch: [[1, 2]], main: [[1, 3]], }, }); const { cancel } = mainActor.send("remoteNever", []); expect(remote.canceled).toBeFalsy(); cancel(); expect(remote.canceled).toBeTruthy(); await expect(mainActor.send("remoteFail", []).value).rejects.toThrowError( "Error: error", ); });
src/actor.test.ts
onthegomap-maplibre-contour-0f2b64d
[ { "filename": "src/e2e.test.ts", "retrieved_chunk": " return { value: Promise.resolve(value), cancel() {} };\n});\nconst remote = new WorkerDispatch();\nconst local = new MainThreadDispatch();\nconst workerFromMainThread: Worker = {} as any as Worker;\nconst mainThreadFromWorker: Worker = {} as any as Worker;\nworkerFromMainThread.postMessage = (data) =>\n mainThreadFromWorker?.onmessage?.({ data } as any);\nmainThreadFromWorker.postMessage = (data) =>\n workerFromMainThread?.onmessage?.({ data } as any);", "score": 0.9161524772644043 }, { "filename": "src/worker.ts", "retrieved_chunk": "import Actor from \"./actor\";\nimport { MainThreadDispatch } from \"./remote-dem-manager\";\nimport WorkerDispatch from \"./worker-dispatch\";\nconst g: any =\n typeof self !== \"undefined\"\n ? self\n : typeof window !== \"undefined\"\n ? window\n : global;\ng.actor = new Actor<MainThreadDispatch>(g, new WorkerDispatch());", "score": 0.9018636345863342 }, { "filename": "src/e2e.test.ts", "retrieved_chunk": "const mainActor = new Actor<WorkerDispatch>(workerFromMainThread, local);\nconst workerActor = new Actor<MainThreadDispatch>(mainThreadFromWorker, remote);\nconst source = new DemSource({\n url: \"https://example/{z}/{x}/{y}.png\",\n cacheSize: 100,\n encoding: \"terrarium\",\n maxzoom: 11,\n worker: true,\n actor: mainActor,\n});", "score": 0.8943344950675964 }, { "filename": "src/remote-dem-manager.ts", "retrieved_chunk": "}\nfunction defaultActor(): Actor<WorkerDispatch> {\n if (!_actor) {\n const worker = new Worker(CONFIG.workerUrl);\n const dispatch = new MainThreadDispatch();\n _actor = new Actor(worker, dispatch);\n }\n return _actor;\n}\n/**", "score": 0.8628648519515991 }, { "filename": "src/decode-image.ts", "retrieved_chunk": "/* eslint-disable no-restricted-globals */\nimport type Actor from \"./actor\";\nimport { offscreenCanvasSupported } from \"./utils\";\nimport type { MainThreadDispatch } from \"./remote-dem-manager\";\nimport { CancelablePromise, DemTile, Encoding } from \"./types\";\nlet offscreenCanvas: OffscreenCanvas;\nlet offscreenContext: OffscreenCanvasRenderingContext2D | null;\nlet canvas: HTMLCanvasElement;\nlet canvasContext: CanvasRenderingContext2D | null;\n/**", "score": 0.8321531414985657 } ]
typescript
const mainActor = new Actor<Remote>(workerFromMainThread, local);
/* eslint-disable no-restricted-globals */ import type Actor from "./actor"; import { offscreenCanvasSupported } from "./utils"; import type { MainThreadDispatch } from "./remote-dem-manager"; import { CancelablePromise, DemTile, Encoding } from "./types"; let offscreenCanvas: OffscreenCanvas; let offscreenContext: OffscreenCanvasRenderingContext2D | null; let canvas: HTMLCanvasElement; let canvasContext: CanvasRenderingContext2D | null; /** * Parses a `raster-dem` image into a DemTile using OffscreenCanvas and createImageBitmap * only supported on newer browsers. */ function decodeImageModern( blob: Blob, encoding: Encoding, ): CancelablePromise<DemTile> { let canceled = false; const promise = createImageBitmap(blob).then((img) => { if (canceled) return null as any as DemTile; if (!offscreenCanvas) { offscreenCanvas = new OffscreenCanvas(img.width, img.height); offscreenContext = offscreenCanvas.getContext("2d", { willReadFrequently: true, }) as OffscreenCanvasRenderingContext2D; } return getElevations(img, encoding, offscreenCanvas, offscreenContext); }); return { value: promise, cancel: () => { canceled = true; }, }; } /** * Parses a `raster-dem` image into a DemTile using `<img>` element drawn to a `<canvas>`. * Only works on the main thread, but works across all browsers. */ function decodeImageOld( blob: Blob, encoding: Encoding, ): CancelablePromise<DemTile> { if (!canvas) { canvas = document.createElement("canvas"); canvasContext = canvas.getContext("2d", { willReadFrequently: true, }) as CanvasRenderingContext2D; } let canceled = false; const img: HTMLImageElement = new Image(); const value = new Promise<HTMLImageElement>((resolve, reject) => { img.onload = () => { if (!canceled) resolve(img); URL.revokeObjectURL(img.src); img.onload = null; }; img.onerror = () => reject(new Error("Could not load image.")); img.src = blob.size ? URL.createObjectURL(blob) : ""; }).then((img: HTMLImageElement) => getElevations(img, encoding, canvas, canvasContext), ); return { value, cancel: () => { canceled = true; img.src = ""; }, }; } /** * Parses a `raster-dem` image in a worker that doesn't support OffscreenCanvas and createImageBitmap * by running decodeImageOld on the main thread and returning the result. */ function decodeImageOnMainThread( blob: Blob, encoding: Encoding, ): CancelablePromise<DemTile> { return ((self as any).actor as Actor<MainThreadDispatch>).send( "decodeImage", [], undefined, blob, encoding, ); } function isWorker(): boolean { return ( // @ts-ignore typeof WorkerGlobalScope !== "undefined" && typeof self !== "undefined" && // @ts-ignore self instanceof WorkerGlobalScope ); } const defaultDecoder: ( blob: Blob, encoding: Encoding, ) => CancelablePromise<DemTile> =
offscreenCanvasSupported() ? decodeImageModern : isWorker() ? decodeImageOnMainThread : decodeImageOld;
export default defaultDecoder; function getElevations( img: ImageBitmap | HTMLImageElement, encoding: Encoding, canvas: HTMLCanvasElement | OffscreenCanvas, canvasContext: | CanvasRenderingContext2D | OffscreenCanvasRenderingContext2D | null, ): DemTile { canvas.width = img.width; canvas.height = img.height; if (!canvasContext) throw new Error("failed to get context"); canvasContext.drawImage(img, 0, 0, img.width, img.height); const rgba = canvasContext.getImageData(0, 0, img.width, img.height).data; return decodeParsedImage(img.width, img.height, encoding, rgba); } export function decodeParsedImage( width: number, height: number, encoding: Encoding, input: Uint8ClampedArray, ): DemTile { const decoder: (r: number, g: number, b: number) => number = encoding === "mapbox" ? (r, g, b) => -10000 + (r * 256 * 256 + g * 256 + b) * 0.1 : (r, g, b) => r * 256 + g + b / 256 - 32768; const data = new Float32Array(width * height); for (let i = 0; i < input.length; i += 4) { data[i / 4] = decoder(input[i], input[i + 1], input[i + 2]); } return { width, height, data }; }
src/decode-image.ts
onthegomap-maplibre-contour-0f2b64d
[ { "filename": "src/remote-dem-manager.ts", "retrieved_chunk": " Encoding,\n FetchResponse,\n IndividualContourTileOptions,\n} from \"./types\";\nimport { prepareDemTile } from \"./utils\";\nlet _actor: Actor<WorkerDispatch> | undefined;\nlet id = 0;\nexport class MainThreadDispatch {\n decodeImage = (blob: Blob, encoding: Encoding) =>\n prepareDemTile(decodeImage(blob, encoding), false);", "score": 0.8734526634216309 }, { "filename": "src/dem-manager.ts", "retrieved_chunk": " maxzoom: number;\n timeoutMs: number;\n loaded = Promise.resolve();\n decodeImage: (blob: Blob, encoding: Encoding) => CancelablePromise<DemTile> =\n decodeImage;\n constructor(\n demUrlPattern: string,\n cacheSize: number,\n encoding: Encoding,\n maxzoom: number,", "score": 0.8724315762519836 }, { "filename": "src/dem-source.ts", "retrieved_chunk": "import { DemManager, LocalDemManager } from \"./dem-manager\";\nimport { decodeOptions, encodeOptions, getOptionsForZoom } from \"./utils\";\nimport RemoteDemManager from \"./remote-dem-manager\";\nimport { DemTile, Cancelable, GlobalContourTileOptions, Timing } from \"./types\";\nimport type WorkerDispatch from \"./worker-dispatch\";\nimport Actor from \"./actor\";\nimport { Timer } from \"./performance\";\nif (!Blob.prototype.arrayBuffer) {\n Blob.prototype.arrayBuffer = function arrayBuffer() {\n return new Promise<ArrayBuffer>((resolve, reject) => {", "score": 0.8488551378250122 }, { "filename": "src/dem-manager.ts", "retrieved_chunk": "import AsyncCache from \"./cache\";\nimport decodeImage from \"./decode-image\";\nimport { HeightTile } from \"./height-tile\";\nimport generateIsolines from \"./isolines\";\nimport { encodeIndividualOptions, withTimeout } from \"./utils\";\nimport {\n CancelablePromise,\n ContourTile,\n DemTile,\n Encoding,", "score": 0.8347568511962891 }, { "filename": "src/dem-manager.ts", "retrieved_chunk": " timer?.useTile(url);\n return this.parsedCache.getCancelable(url, () => {\n const tile = self.fetchTile(z, x, y, timer);\n let canceled = false;\n let alsoCancel = () => {};\n return {\n value: tile.value.then(async (response) => {\n if (canceled) throw new Error(\"canceled\");\n const result = self.decodeImage(response.data, self.encoding);\n alsoCancel = result.cancel;", "score": 0.8198111057281494 } ]
typescript
offscreenCanvasSupported() ? decodeImageModern : isWorker() ? decodeImageOnMainThread : decodeImageOld;
import { CommandModule } from "yargs"; import { createAppForTable, deleteApp } from "../utils/apps"; import { Credentials, getAndVerifyCredentialsWithRetoolDB, } from "../utils/credentials"; import { getRequest, postRequest } from "../utils/networking"; import { collectColumnNames, collectTableName, createTable, createTableFromCSV, deleteTable, generateDataWithGPT, } from "../utils/table"; import type { DBInfoPayload } from "../utils/table"; import { logDAU } from "../utils/telemetry"; import { deleteWorkflow, generateCRUDWorkflow } from "../utils/workflows"; const inquirer = require("inquirer"); const command = "scaffold"; const describe = "Scaffold a Retool DB table, CRUD Workflow, and App."; const builder: CommandModule["builder"] = { name: { alias: "n", describe: `Name of table to scaffold. Usage: retool scaffold -n <table_name>`, type: "string", nargs: 1, }, columns: { alias: "c", describe: `Column names in DB to scaffold. Usage: retool scaffold -c <col1> <col2>`, type: "array", }, delete: { alias: "d", describe: `Delete a table, Workflow and App created via scaffold. Usage: retool scaffold -d <db_name>`, type: "string", nargs: 1, }, "from-csv": { alias: "f", describe: `Create a table, Workflow and App from a CSV file. Usage: retool scaffold -f <path-to-csv>`, type: "array", }, "no-workflow": { describe: `Modifier to avoid generating Workflow. Usage: retool scaffold --no-workflow`, type: "boolean", }, }; const handler = async function (argv: any) { const credentials = await getAndVerifyCredentialsWithRetoolDB(); // fire and forget void logDAU(credentials); // Handle `retool scaffold -d <db_name>` if (argv.delete) { const tableName = argv.delete; const workflowName = `${tableName} CRUD Workflow`; // Confirm deletion. const { confirm } = await inquirer.prompt([ { name: "confirm", message: `Are you sure you want to delete ${tableName} table, CRUD workflow and app?`, type: "confirm", }, ]); if (!confirm) { process.exit(0); } //TODO: Could be parallelized. //TODO: Verify existence before trying to delete. await deleteTable(tableName, credentials, false); await deleteWorkflow(workflowName, credentials, false); await deleteApp(`${tableName} App`, credentials, false); } // Handle `retool scaffold -f <path-to-csv>` else if (argv.f) { const csvFileNames = argv.f; for (const csvFileName of csvFileNames) { const { tableName, colNames } = await createTableFromCSV( csvFileName, credentials, false, false ); if (!argv["no-workflow"]) { console.log("\n"); await generateCRUDWorkflow(tableName, credentials); } console.log("\n"); const searchColumnName = colNames.length > 0 ? colNames[0] : "id"; await createAppForTable( `${tableName} App`, tableName, searchColumnName, credentials ); console.log(""); } } // Handle `retool scaffold` else { let tableName = argv.name; let colNames = argv.columns; if (!tableName || tableName.length == 0) { tableName = await collectTableName(); } if (!colNames || colNames.length == 0) { colNames = await collectColumnNames(); } await createTable(tableName, colNames, undefined, credentials, false); // Fire and forget void insertSampleData(tableName, credentials); if (!argv["no-workflow"]) { console.log("\n"); await generateCRUDWorkflow(tableName, credentials); } console.log("\n"); const searchColumnName = colNames.length > 0 ? colNames[0] : "id"; await createAppForTable( `${tableName} App`, tableName, searchColumnName, credentials ); } }; const insertSampleData = async function ( tableName: string, credentials: Credentials ) {
const infoRes = await getRequest( `${credentials.origin}/api/grid/${credentials.gridId}/table/${tableName}/info`, false );
const retoolDBInfo: DBInfoPayload = infoRes.data; const { fields } = retoolDBInfo.tableInfo; const generatedData = await generateDataWithGPT( retoolDBInfo, fields, 0, credentials, false ); if (generatedData) { await postRequest( `${credentials.origin}/api/grid/${credentials.gridId}/action`, { kind: "BulkInsertIntoTable", tableName: tableName, additions: generatedData, } ); } }; const commandModule: CommandModule = { command, describe, builder, handler, }; export default commandModule;
src/commands/scaffold.ts
tryretool-retool-cli-91b2c68
[ { "filename": "src/utils/table.ts", "retrieved_chunk": " const infoResponse = await getRequest(\n `${credentials.origin}/api/grid/${credentials.gridId}/table/${tableName}/info`\n );\n spinner.stop();\n const { tableInfo } = infoResponse.data;\n if (tableInfo) {\n return tableInfo;\n }\n}\nexport async function deleteTable(", "score": 0.8904591798782349 }, { "filename": "src/commands/db.ts", "retrieved_chunk": " // Verify that the provided db name exists.\n const tableName = argv.gendata;\n await verifyTableExists(tableName, credentials);\n // Fetch Retool DB schema and data.\n const spinner = ora(`Fetching ${tableName} metadata`).start();\n const infoReq = getRequest(\n `${credentials.origin}/api/grid/${credentials.gridId}/table/${tableName}/info`\n );\n const dataReq = postRequest(\n `${credentials.origin}/api/grid/${credentials.gridId}/table/${tableName}/data`,", "score": 0.8766206502914429 }, { "filename": "src/commands/db.ts", "retrieved_chunk": " );\n }\n // Insert to Retool DB.\n const bulkInsertRes = await postRequest(\n `${credentials.origin}/api/grid/${credentials.gridId}/action`,\n {\n kind: \"BulkInsertIntoTable\",\n tableName: tableName,\n additions: generatedData,\n }", "score": 0.863828182220459 }, { "filename": "src/utils/table.ts", "retrieved_chunk": " await postRequest(\n `${credentials.origin}/api/grid/${credentials.gridId}/action`,\n {\n kind: \"DeleteTable\",\n payload: {\n table: tableName,\n },\n }\n );\n spinner.stop();", "score": 0.8568492531776428 }, { "filename": "src/utils/table.ts", "retrieved_chunk": " `${credentials.origin}/api/grid/${credentials.gridId}/action`,\n {\n ...payload,\n }\n );\n spinner.stop();\n if (!createTableResult.data.success) {\n console.log(\"Error creating table in RetoolDB.\");\n console.log(createTableResult.data);\n process.exit(1);", "score": 0.8499792814254761 } ]
typescript
const infoRes = await getRequest( `${credentials.origin}/api/grid/${credentials.gridId}/table/${tableName}/info`, false );
import AsyncCache from "./cache"; import decodeImage from "./decode-image"; import { HeightTile } from "./height-tile"; import generateIsolines from "./isolines"; import { encodeIndividualOptions, withTimeout } from "./utils"; import { CancelablePromise, ContourTile, DemTile, Encoding, FetchResponse, IndividualContourTileOptions, } from "./types"; import encodeVectorTile, { GeomType } from "./vtpbf"; import { Timer } from "./performance"; /** * Holds cached tile state, and exposes `fetchContourTile` which fetches the necessary * tiles and returns an encoded contour vector tiles. */ export interface DemManager { loaded: Promise<any>; fetchTile( z: number, x: number, y: number, timer?: Timer, ): CancelablePromise<FetchResponse>; fetchAndParseTile( z: number, x: number, y: number, timer?: Timer, ): CancelablePromise<DemTile>; fetchContourTile( z: number, x: number, y: number, options: IndividualContourTileOptions, timer?: Timer, ): CancelablePromise<ContourTile>; } /** * Caches, decodes, and processes raster tiles in the current thread. */ export class LocalDemManager implements DemManager { tileCache:
AsyncCache<string, FetchResponse>;
parsedCache: AsyncCache<string, DemTile>; contourCache: AsyncCache<string, ContourTile>; demUrlPattern: string; encoding: Encoding; maxzoom: number; timeoutMs: number; loaded = Promise.resolve(); decodeImage: (blob: Blob, encoding: Encoding) => CancelablePromise<DemTile> = decodeImage; constructor( demUrlPattern: string, cacheSize: number, encoding: Encoding, maxzoom: number, timeoutMs: number, ) { this.tileCache = new AsyncCache(cacheSize); this.parsedCache = new AsyncCache(cacheSize); this.contourCache = new AsyncCache(cacheSize); this.timeoutMs = timeoutMs; this.demUrlPattern = demUrlPattern; this.encoding = encoding; this.maxzoom = maxzoom; } fetchTile( z: number, x: number, y: number, timer?: Timer, ): CancelablePromise<FetchResponse> { const url = this.demUrlPattern .replace("{z}", z.toString()) .replace("{x}", x.toString()) .replace("{y}", y.toString()); timer?.useTile(url); return this.tileCache.getCancelable(url, () => { let cancel = () => {}; const options: RequestInit = {}; try { const controller = new AbortController(); options.signal = controller.signal; cancel = () => controller.abort(); } catch (e) { // ignore } timer?.fetchTile(url); const mark = timer?.marker("fetch"); return withTimeout(this.timeoutMs, { value: fetch(url, options).then(async (response) => { mark?.(); if (!response.ok) { throw new Error(`Bad response: ${response.status} for ${url}`); } return { data: await response.blob(), expires: response.headers.get("expires") || undefined, cacheControl: response.headers.get("cache-control") || undefined, }; }), cancel, }); }); } fetchAndParseTile = ( z: number, x: number, y: number, timer?: Timer, ): CancelablePromise<DemTile> => { const self = this; const url = this.demUrlPattern .replace("{z}", z.toString()) .replace("{x}", x.toString()) .replace("{y}", y.toString()); timer?.useTile(url); return this.parsedCache.getCancelable(url, () => { const tile = self.fetchTile(z, x, y, timer); let canceled = false; let alsoCancel = () => {}; return { value: tile.value.then(async (response) => { if (canceled) throw new Error("canceled"); const result = self.decodeImage(response.data, self.encoding); alsoCancel = result.cancel; const mark = timer?.marker("decode"); const value = await result.value; mark?.(); return value; }), cancel: () => { canceled = true; alsoCancel(); tile.cancel(); }, }; }); }; fetchDem( z: number, x: number, y: number, options: IndividualContourTileOptions, timer?: Timer, ): CancelablePromise<HeightTile> { const zoom = Math.min(z - (options.overzoom || 0), this.maxzoom); const subZ = z - zoom; const div = 1 << subZ; const newX = Math.floor(x / div); const newY = Math.floor(y / div); const { value, cancel } = this.fetchAndParseTile(zoom, newX, newY, timer); const subX = x % div; const subY = y % div; return { value: value.then((tile) => HeightTile.fromRawDem(tile).split(subZ, subX, subY), ), cancel, }; } fetchContourTile( z: number, x: number, y: number, options: IndividualContourTileOptions, timer?: Timer, ): CancelablePromise<ContourTile> { const { levels, multiplier = 1, buffer = 1, extent = 4096, contourLayer = "contours", elevationKey = "ele", levelKey = "level", subsampleBelow = 100, } = options; // no levels means less than min zoom with levels specified if (!levels || levels.length === 0) { return { cancel() {}, value: Promise.resolve({ arrayBuffer: new ArrayBuffer(0) }), }; } const key = [z, x, y, encodeIndividualOptions(options)].join("/"); return this.contourCache.getCancelable(key, () => { const max = 1 << z; let canceled = false; const neighborPromises: (CancelablePromise<HeightTile> | null)[] = []; for (let iy = y - 1; iy <= y + 1; iy++) { for (let ix = x - 1; ix <= x + 1; ix++) { neighborPromises.push( iy < 0 || iy >= max ? null : this.fetchDem(z, (ix + max) % max, iy, options, timer), ); } } const value = Promise.all(neighborPromises.map((n) => n?.value)).then( async (neighbors) => { let virtualTile = HeightTile.combineNeighbors(neighbors); if (!virtualTile || canceled) { return { arrayBuffer: new Uint8Array().buffer }; } const mark = timer?.marker("isoline"); if (virtualTile.width >= subsampleBelow) { virtualTile = virtualTile.materialize(2); } else { while (virtualTile.width < subsampleBelow) { virtualTile = virtualTile.subsamplePixelCenters(2).materialize(2); } } virtualTile = virtualTile .averagePixelCentersToGrid() .scaleElevation(multiplier) .materialize(1); const isolines = generateIsolines( levels[0], virtualTile, extent, buffer, ); mark?.(); const result = encodeVectorTile({ extent, layers: { [contourLayer]: { features: Object.entries(isolines).map(([eleString, geom]) => { const ele = Number(eleString); return { type: GeomType.LINESTRING, geometry: geom, properties: { [elevationKey]: ele, [levelKey]: Math.max( ...levels.map((l, i) => (ele % l === 0 ? i : 0)), ), }, }; }), }, }, }); mark?.(); return { arrayBuffer: result.buffer }; }, ); return { value, cancel() { canceled = true; neighborPromises.forEach((n) => n && n.cancel()); }, }; }); } }
src/dem-manager.ts
onthegomap-maplibre-contour-0f2b64d
[ { "filename": "src/worker-dispatch.ts", "retrieved_chunk": "import { LocalDemManager } from \"./dem-manager\";\nimport { Timer } from \"./performance\";\nimport {\n CancelablePromise,\n ContourTile,\n FetchResponse,\n IndividualContourTileOptions,\n InitMessage,\n TransferrableDemTile,\n} from \"./types\";", "score": 0.9027892351150513 }, { "filename": "src/remote-dem-manager.ts", "retrieved_chunk": " ): CancelablePromise<FetchResponse> =>\n this.actor.send(\"fetchTile\", [], timer, this.managerId, z, x, y);\n fetchAndParseTile = (\n z: number,\n x: number,\n y: number,\n timer?: Timer,\n ): CancelablePromise<DemTile> =>\n this.actor.send(\"fetchAndParseTile\", [], timer, this.managerId, z, x, y);\n fetchContourTile = (", "score": 0.8572767376899719 }, { "filename": "src/remote-dem-manager.ts", "retrieved_chunk": " * Caches, decodes, and processes raster tiles in a shared web worker.\n */\nexport default class RemoteDemManager implements DemManager {\n managerId: number;\n actor: Actor<WorkerDispatch>;\n loaded: Promise<any>;\n constructor(\n demUrlPattern: string,\n cacheSize: number,\n encoding: Encoding,", "score": 0.8571711182594299 }, { "filename": "src/worker-dispatch.ts", "retrieved_chunk": " );\n fetchContourTile = (\n managerId: number,\n z: number,\n x: number,\n y: number,\n options: IndividualContourTileOptions,\n timer?: Timer,\n ): CancelablePromise<ContourTile> =>\n prepareContourTile(", "score": 0.8493630886077881 }, { "filename": "src/dem-source.ts", "retrieved_chunk": "import { DemManager, LocalDemManager } from \"./dem-manager\";\nimport { decodeOptions, encodeOptions, getOptionsForZoom } from \"./utils\";\nimport RemoteDemManager from \"./remote-dem-manager\";\nimport { DemTile, Cancelable, GlobalContourTileOptions, Timing } from \"./types\";\nimport type WorkerDispatch from \"./worker-dispatch\";\nimport Actor from \"./actor\";\nimport { Timer } from \"./performance\";\nif (!Blob.prototype.arrayBuffer) {\n Blob.prototype.arrayBuffer = function arrayBuffer() {\n return new Promise<ArrayBuffer>((resolve, reject) => {", "score": 0.847243070602417 } ]
typescript
AsyncCache<string, FetchResponse>;
import AsyncCache from "./cache"; import decodeImage from "./decode-image"; import { HeightTile } from "./height-tile"; import generateIsolines from "./isolines"; import { encodeIndividualOptions, withTimeout } from "./utils"; import { CancelablePromise, ContourTile, DemTile, Encoding, FetchResponse, IndividualContourTileOptions, } from "./types"; import encodeVectorTile, { GeomType } from "./vtpbf"; import { Timer } from "./performance"; /** * Holds cached tile state, and exposes `fetchContourTile` which fetches the necessary * tiles and returns an encoded contour vector tiles. */ export interface DemManager { loaded: Promise<any>; fetchTile( z: number, x: number, y: number, timer?: Timer, ): CancelablePromise<FetchResponse>; fetchAndParseTile( z: number, x: number, y: number, timer?: Timer, ): CancelablePromise<DemTile>; fetchContourTile( z: number, x: number, y: number, options: IndividualContourTileOptions, timer?: Timer, ): CancelablePromise<ContourTile>; } /** * Caches, decodes, and processes raster tiles in the current thread. */ export class LocalDemManager implements DemManager { tileCache: AsyncCache<string, FetchResponse>; parsedCache: AsyncCache<string, DemTile>; contourCache: AsyncCache<string, ContourTile>; demUrlPattern: string; encoding: Encoding; maxzoom: number; timeoutMs: number; loaded = Promise.resolve(); decodeImage: (blob: Blob, encoding: Encoding) => CancelablePromise<DemTile> = decodeImage; constructor( demUrlPattern: string, cacheSize: number, encoding: Encoding, maxzoom: number, timeoutMs: number, ) { this.tileCache = new AsyncCache(cacheSize); this.parsedCache = new AsyncCache(cacheSize); this.contourCache = new AsyncCache(cacheSize); this.timeoutMs = timeoutMs; this.demUrlPattern = demUrlPattern; this.encoding = encoding; this.maxzoom = maxzoom; } fetchTile( z: number, x: number, y: number, timer?: Timer, ): CancelablePromise<FetchResponse> { const url = this.demUrlPattern .replace("{z}", z.toString()) .replace("{x}", x.toString()) .replace("{y}", y.toString()); timer?.useTile(url); return this.tileCache.getCancelable(url, () => { let cancel = () => {}; const options: RequestInit = {}; try { const controller = new AbortController(); options.signal = controller.signal; cancel = () => controller.abort(); } catch (e) { // ignore } timer?.fetchTile(url); const mark = timer?.marker("fetch"); return withTimeout(this.timeoutMs, { value: fetch(url, options).then(async (response) => { mark?.(); if (!response.ok) { throw new Error(`Bad response: ${response.status} for ${url}`); } return { data: await response.blob(), expires: response.headers.get("expires") || undefined, cacheControl: response.headers.get("cache-control") || undefined, }; }), cancel, }); }); } fetchAndParseTile = ( z: number, x: number, y: number, timer?: Timer, ): CancelablePromise<DemTile> => { const self = this; const url = this.demUrlPattern .replace("{z}", z.toString()) .replace("{x}", x.toString()) .replace("{y}", y.toString()); timer?.useTile(url); return this.parsedCache.getCancelable(url, () => { const tile = self.fetchTile(z, x, y, timer); let canceled = false; let alsoCancel = () => {}; return { value: tile.value.then(async (response) => { if (canceled) throw new Error("canceled"); const result = self.decodeImage(response.data, self.encoding); alsoCancel = result.cancel; const mark = timer?.marker("decode"); const value = await result.value; mark?.(); return value; }), cancel: () => { canceled = true; alsoCancel(); tile.cancel(); }, }; }); }; fetchDem( z: number, x: number, y: number, options: IndividualContourTileOptions, timer?: Timer, ): CancelablePromise<HeightTile> { const zoom = Math.min(z - (options.overzoom || 0), this.maxzoom); const subZ = z - zoom; const div = 1 << subZ; const newX = Math.floor(x / div); const newY = Math.floor(y / div); const { value, cancel } = this.fetchAndParseTile(zoom, newX, newY, timer); const subX = x % div; const subY = y % div; return { value: value.then((tile) => HeightTile.fromRawDem(tile).split(subZ, subX, subY), ), cancel, }; } fetchContourTile( z: number, x: number, y: number, options: IndividualContourTileOptions, timer?: Timer, ): CancelablePromise<ContourTile> { const { levels, multiplier = 1, buffer = 1, extent = 4096, contourLayer = "contours", elevationKey = "ele", levelKey = "level", subsampleBelow = 100, } = options; // no levels means less than min zoom with levels specified if (!levels || levels.length === 0) { return { cancel() {}, value: Promise.resolve({ arrayBuffer: new ArrayBuffer(0) }), }; } const key = [z, x, y, encodeIndividualOptions(options)].join("/"); return this.contourCache.getCancelable(key, () => { const max = 1 << z; let canceled = false; const neighborPromises: (CancelablePromise<HeightTile> | null)[] = []; for (let iy = y - 1; iy <= y + 1; iy++) { for (let ix = x - 1; ix <= x + 1; ix++) { neighborPromises.push( iy < 0 || iy >= max ? null : this.fetchDem(z, (ix + max) % max, iy, options, timer), ); } } const value = Promise.all(neighborPromises.map((n) => n?.value)).then( async (neighbors) => { let virtualTile = HeightTile.combineNeighbors(neighbors); if (!virtualTile || canceled) { return { arrayBuffer: new Uint8Array().buffer }; } const mark = timer?.marker("isoline"); if (virtualTile.width >= subsampleBelow) { virtualTile = virtualTile.materialize(2); } else { while (virtualTile.width < subsampleBelow) { virtualTile = virtualTile.subsamplePixelCenters(2).materialize(2); } } virtualTile = virtualTile .averagePixelCentersToGrid() .scaleElevation(multiplier) .materialize(1); const isolines = generateIsolines( levels[0], virtualTile, extent, buffer, ); mark?.(); const result = encodeVectorTile({ extent, layers: { [contourLayer]: { features: Object.entries(isolines).map(([eleString, geom]) => { const ele = Number(eleString); return {
type: GeomType.LINESTRING, geometry: geom, properties: {
[elevationKey]: ele, [levelKey]: Math.max( ...levels.map((l, i) => (ele % l === 0 ? i : 0)), ), }, }; }), }, }, }); mark?.(); return { arrayBuffer: result.buffer }; }, ); return { value, cancel() { canceled = true; neighborPromises.forEach((n) => n && n.cancel()); }, }; }); } }
src/dem-manager.ts
onthegomap-maplibre-contour-0f2b64d
[ { "filename": "src/vtpbf.test.ts", "retrieved_chunk": "});\ntest(\"multi line\", () => {\n const encoded = encodeVectorTile({\n layers: {\n contours: {\n features: [\n {\n geometry: [\n [0, 1, 2, 3],\n [9, 8, 7, 6],", "score": 0.8710147142410278 }, { "filename": "src/vtpbf.test.ts", "retrieved_chunk": "test(\"simple line\", () => {\n const encoded = encodeVectorTile({\n layers: {\n contours: {\n features: [\n {\n geometry: [[0, 1, 2, 3]],\n type: GeomType.LINESTRING,\n properties: {\n key: \"value\",", "score": 0.8635071516036987 }, { "filename": "src/vtpbf.test.ts", "retrieved_chunk": " });\n const result = new VectorTile(new Pbf(encoded));\n expect(result.layers.contours.feature(0).properties).toEqual({\n key: 1,\n key2: true,\n });\n expect(result.layers.contours.feature(0).loadGeometry()).toEqual([\n [\n { x: 0, y: 1 },\n { x: 2, y: 3 },", "score": 0.8529521226882935 }, { "filename": "src/vtpbf.test.ts", "retrieved_chunk": " },\n },\n ],\n },\n },\n });\n const result = new VectorTile(new Pbf(encoded));\n expect(result.layers).toHaveProperty(\"contours\");\n expect(result.layers.contours.extent).toBe(4096);\n expect(result.layers.contours.version).toBe(2);", "score": 0.838394820690155 }, { "filename": "src/e2e.test.ts", "retrieved_chunk": " if (err) reject(err);\n else resolve(data);\n },\n );\n });\n const tile = new VectorTile(new Pbf(contourTile));\n expect(tile.layers.c.name).toBe(\"c\");\n expect(tile.layers.c.extent).toBe(4096);\n expect(tile.layers.c.length).toBe(1);\n expect(tile.layers.c.feature(0).properties).toEqual({", "score": 0.8349303007125854 } ]
typescript
type: GeomType.LINESTRING, geometry: geom, properties: {
import AsyncCache from "./cache"; import decodeImage from "./decode-image"; import { HeightTile } from "./height-tile"; import generateIsolines from "./isolines"; import { encodeIndividualOptions, withTimeout } from "./utils"; import { CancelablePromise, ContourTile, DemTile, Encoding, FetchResponse, IndividualContourTileOptions, } from "./types"; import encodeVectorTile, { GeomType } from "./vtpbf"; import { Timer } from "./performance"; /** * Holds cached tile state, and exposes `fetchContourTile` which fetches the necessary * tiles and returns an encoded contour vector tiles. */ export interface DemManager { loaded: Promise<any>; fetchTile( z: number, x: number, y: number, timer?: Timer, ): CancelablePromise<FetchResponse>; fetchAndParseTile( z: number, x: number, y: number, timer?: Timer, ): CancelablePromise<DemTile>; fetchContourTile( z: number, x: number, y: number, options: IndividualContourTileOptions, timer?: Timer, ): CancelablePromise<ContourTile>; } /** * Caches, decodes, and processes raster tiles in the current thread. */ export class LocalDemManager implements DemManager { tileCache: AsyncCache<string, FetchResponse>; parsedCache: AsyncCache<string, DemTile>; contourCache: AsyncCache<string, ContourTile>; demUrlPattern: string; encoding: Encoding; maxzoom: number; timeoutMs: number; loaded = Promise.resolve(); decodeImage: (blob: Blob, encoding: Encoding) => CancelablePromise<DemTile> = decodeImage; constructor( demUrlPattern: string, cacheSize: number, encoding: Encoding, maxzoom: number, timeoutMs: number, ) { this.tileCache = new AsyncCache(cacheSize); this.parsedCache = new AsyncCache(cacheSize); this.contourCache = new AsyncCache(cacheSize); this.timeoutMs = timeoutMs; this.demUrlPattern = demUrlPattern; this.encoding = encoding; this.maxzoom = maxzoom; } fetchTile( z: number, x: number, y: number, timer?: Timer, ): CancelablePromise<FetchResponse> { const url = this.demUrlPattern .replace("{z}", z.toString()) .replace("{x}", x.toString()) .replace("{y}", y.toString()); timer?.useTile(url); return this.tileCache.getCancelable(url, () => { let cancel = () => {}; const options: RequestInit = {}; try { const controller = new AbortController(); options.signal = controller.signal; cancel = () => controller.abort(); } catch (e) { // ignore } timer?.fetchTile(url); const mark = timer?.marker("fetch"); return withTimeout(this.timeoutMs, { value: fetch(url, options).then(async (response) => { mark?.(); if (!response.ok) { throw new Error(`Bad response: ${response.status} for ${url}`); } return { data: await response.blob(), expires: response.headers.get("expires") || undefined, cacheControl: response.headers.get("cache-control") || undefined, }; }), cancel, }); }); } fetchAndParseTile = ( z: number, x: number, y: number, timer?: Timer, ): CancelablePromise<DemTile> => { const self = this; const url = this.demUrlPattern .replace("{z}", z.toString()) .replace("{x}", x.toString()) .replace("{y}", y.toString()); timer?.useTile(url); return this.parsedCache.getCancelable(url, () => { const tile = self.fetchTile(z, x, y, timer); let canceled = false; let alsoCancel = () => {}; return { value: tile.value.then(async (response) => { if (canceled) throw new Error("canceled"); const result = self.decodeImage(response.data, self.encoding); alsoCancel = result.cancel; const mark = timer?.marker("decode"); const value = await result.value; mark?.(); return value; }), cancel: () => { canceled = true; alsoCancel(); tile.cancel(); }, }; }); }; fetchDem( z: number, x: number, y: number, options: IndividualContourTileOptions, timer?: Timer, )
: CancelablePromise<HeightTile> {
const zoom = Math.min(z - (options.overzoom || 0), this.maxzoom); const subZ = z - zoom; const div = 1 << subZ; const newX = Math.floor(x / div); const newY = Math.floor(y / div); const { value, cancel } = this.fetchAndParseTile(zoom, newX, newY, timer); const subX = x % div; const subY = y % div; return { value: value.then((tile) => HeightTile.fromRawDem(tile).split(subZ, subX, subY), ), cancel, }; } fetchContourTile( z: number, x: number, y: number, options: IndividualContourTileOptions, timer?: Timer, ): CancelablePromise<ContourTile> { const { levels, multiplier = 1, buffer = 1, extent = 4096, contourLayer = "contours", elevationKey = "ele", levelKey = "level", subsampleBelow = 100, } = options; // no levels means less than min zoom with levels specified if (!levels || levels.length === 0) { return { cancel() {}, value: Promise.resolve({ arrayBuffer: new ArrayBuffer(0) }), }; } const key = [z, x, y, encodeIndividualOptions(options)].join("/"); return this.contourCache.getCancelable(key, () => { const max = 1 << z; let canceled = false; const neighborPromises: (CancelablePromise<HeightTile> | null)[] = []; for (let iy = y - 1; iy <= y + 1; iy++) { for (let ix = x - 1; ix <= x + 1; ix++) { neighborPromises.push( iy < 0 || iy >= max ? null : this.fetchDem(z, (ix + max) % max, iy, options, timer), ); } } const value = Promise.all(neighborPromises.map((n) => n?.value)).then( async (neighbors) => { let virtualTile = HeightTile.combineNeighbors(neighbors); if (!virtualTile || canceled) { return { arrayBuffer: new Uint8Array().buffer }; } const mark = timer?.marker("isoline"); if (virtualTile.width >= subsampleBelow) { virtualTile = virtualTile.materialize(2); } else { while (virtualTile.width < subsampleBelow) { virtualTile = virtualTile.subsamplePixelCenters(2).materialize(2); } } virtualTile = virtualTile .averagePixelCentersToGrid() .scaleElevation(multiplier) .materialize(1); const isolines = generateIsolines( levels[0], virtualTile, extent, buffer, ); mark?.(); const result = encodeVectorTile({ extent, layers: { [contourLayer]: { features: Object.entries(isolines).map(([eleString, geom]) => { const ele = Number(eleString); return { type: GeomType.LINESTRING, geometry: geom, properties: { [elevationKey]: ele, [levelKey]: Math.max( ...levels.map((l, i) => (ele % l === 0 ? i : 0)), ), }, }; }), }, }, }); mark?.(); return { arrayBuffer: result.buffer }; }, ); return { value, cancel() { canceled = true; neighborPromises.forEach((n) => n && n.cancel()); }, }; }); } }
src/dem-manager.ts
onthegomap-maplibre-contour-0f2b64d
[ { "filename": "src/remote-dem-manager.ts", "retrieved_chunk": " z: number,\n x: number,\n y: number,\n options: IndividualContourTileOptions,\n timer?: Timer,\n ): CancelablePromise<ContourTile> =>\n this.actor.send(\n \"fetchContourTile\",\n [],\n timer,", "score": 0.9087842106819153 }, { "filename": "src/remote-dem-manager.ts", "retrieved_chunk": " ): CancelablePromise<FetchResponse> =>\n this.actor.send(\"fetchTile\", [], timer, this.managerId, z, x, y);\n fetchAndParseTile = (\n z: number,\n x: number,\n y: number,\n timer?: Timer,\n ): CancelablePromise<DemTile> =>\n this.actor.send(\"fetchAndParseTile\", [], timer, this.managerId, z, x, y);\n fetchContourTile = (", "score": 0.9056484699249268 }, { "filename": "src/worker-dispatch.ts", "retrieved_chunk": " );\n fetchContourTile = (\n managerId: number,\n z: number,\n x: number,\n y: number,\n options: IndividualContourTileOptions,\n timer?: Timer,\n ): CancelablePromise<ContourTile> =>\n prepareContourTile(", "score": 0.8865166306495667 }, { "filename": "src/worker-dispatch.ts", "retrieved_chunk": " managerId: number,\n z: number,\n x: number,\n y: number,\n timer?: Timer,\n ): CancelablePromise<TransferrableDemTile> =>\n prepareDemTile(\n this.managers[managerId]?.fetchAndParseTile(z, x, y, timer) ||\n noManager(managerId),\n true,", "score": 0.8863779902458191 }, { "filename": "src/dem-source.ts", "retrieved_chunk": " const result = this.manager.fetchContourTile(\n z,\n x,\n y,\n getOptionsForZoom(options, z),\n timer,\n );\n let canceled = false;\n (async () => {\n let timing: Timing;", "score": 0.8838955760002136 } ]
typescript
: CancelablePromise<HeightTile> {
import { Timer } from "./performance"; import { CancelablePromise, IsTransferrable, Timing } from "./types"; import { withTimeout } from "./utils"; let id = 0; interface Cancel { type: "cancel"; id: number; } interface Response { type: "response"; id: number; error?: string; response?: any; timings: Timing; } interface Request { type: "request"; id?: number; name: string; args: any[]; } type Message = Cancel | Response | Request; type MethodsReturning<T, R> = { [K in keyof T]: T[K] extends (...args: any) => R ? T[K] : never; }; /** * Utility for sending messages to a remote instance of `<T>` running in a web worker * from the main thread, or in the main thread running from a web worker. */ export default class Actor<T> { callbacks: { [id: number]: ( error: Error | undefined, message: any, timings: Timing, ) => void; }; cancels: { [id: number]: () => void }; dest: Worker; timeoutMs: number; constructor(dest: Worker, dispatcher: any, timeoutMs: number = 20_000) { this.callbacks = {}; this.cancels = {}; this.dest = dest; this.timeoutMs = timeoutMs; this.dest.onmessage = async ({ data }) => { const message: Message = data; if (message.type === "cancel") { const cancel = this.cancels[message.id]; delete this.cancels[message.id]; if (cancel) { cancel(); } } else if (message.type === "response") { const callback = this.callbacks[message.id]; delete this.callbacks[message.id]; if (callback) { callback( message.error ? new Error(message.error) : undefined, message.response, message.timings, ); } } else if (message.type === "request") { const timer = new Timer("worker"); const handler: Function = (dispatcher as any)[message.name]; const request = handler.apply(handler, [...message.args, timer]); const url = `${message.name}_${message.id}`; if (message.id && request) { this.cancels[message.id] = request.cancel; try { const response = await request.value; const transferrables =
(response as IsTransferrable) ?.transferrables;
this.postMessage( { id: message.id, type: "response", response, timings: timer.finish(url), }, transferrables, ); } catch (e: any) { this.postMessage({ id: message.id, type: "response", error: e?.toString() || "error", timings: timer.finish(url), }); } delete this.cancels[message.id]; } } }; } postMessage(message: Message, transferrables?: Transferable[]) { this.dest.postMessage(message, transferrables || []); } /** Invokes a method by name with a set of arguments in the remote context. */ send< R, M extends MethodsReturning<T, CancelablePromise<R>>, K extends keyof M & string, P extends Parameters<M[K]>, >( name: K, transferrables: Transferable[], timer?: Timer, ...args: P ): CancelablePromise<R> { const thisId = ++id; const value: Promise<R> = new Promise((resolve, reject) => { this.postMessage( { id: thisId, type: "request", name, args }, transferrables, ); this.callbacks[thisId] = (error, result, timings) => { timer?.addAll(timings); if (error) reject(error); else resolve(result); }; }); return withTimeout(this.timeoutMs, { value, cancel: () => { delete this.callbacks[thisId]; this.postMessage({ id: thisId, type: "cancel" }); }, }); } }
src/actor.ts
onthegomap-maplibre-contour-0f2b64d
[ { "filename": "src/dem-source.ts", "retrieved_chunk": " try {\n const data = await result.value;\n timing = timer.finish(request.url);\n if (canceled) return;\n response(undefined, data.arrayBuffer);\n } catch (error) {\n if (canceled) return;\n timing = timer.error(request.url);\n response(error as Error);\n }", "score": 0.8446875214576721 }, { "filename": "src/dem-source.ts", "retrieved_chunk": " timing = timer.finish(request.url);\n if (canceled) return;\n const arrayBuffer: ArrayBuffer = await data.data.arrayBuffer();\n if (canceled) return;\n response(undefined, arrayBuffer, data.cacheControl, data.expires);\n } catch (error) {\n timing = timer.error(request.url);\n if (canceled) return;\n response(error as Error);\n }", "score": 0.8387970924377441 }, { "filename": "src/dem-manager.ts", "retrieved_chunk": " timer?.useTile(url);\n return this.tileCache.getCancelable(url, () => {\n let cancel = () => {};\n const options: RequestInit = {};\n try {\n const controller = new AbortController();\n options.signal = controller.signal;\n cancel = () => controller.abort();\n } catch (e) {\n // ignore", "score": 0.812085747718811 }, { "filename": "src/actor.test.ts", "retrieved_chunk": "class Remote {\n received: any[][] = [];\n canceled = false;\n remoteAction = (x: number, y: number, z: number): CancelablePromise<void> => {\n this.received.push([x, y, z]);\n return { cancel() {}, value: Promise.resolve() };\n };\n remotePromise = (x: number, timer?: Timer): CancelablePromise<number> => {\n const oldNow = performance.now;\n if (timer) timer.timeOrigin = 100;", "score": 0.8114967942237854 }, { "filename": "src/dem-source.ts", "retrieved_chunk": " response: ResponseCallback,\n ): Cancelable => {\n const [z, x, y] = this.parseUrl(request.url);\n const timer = new Timer(\"main\");\n const result = this.manager.fetchTile(z, x, y, timer);\n let canceled = false;\n (async () => {\n let timing: Timing;\n try {\n const data = await result.value;", "score": 0.8088943958282471 } ]
typescript
(response as IsTransferrable) ?.transferrables;
import AsyncCache from "./cache"; import decodeImage from "./decode-image"; import { HeightTile } from "./height-tile"; import generateIsolines from "./isolines"; import { encodeIndividualOptions, withTimeout } from "./utils"; import { CancelablePromise, ContourTile, DemTile, Encoding, FetchResponse, IndividualContourTileOptions, } from "./types"; import encodeVectorTile, { GeomType } from "./vtpbf"; import { Timer } from "./performance"; /** * Holds cached tile state, and exposes `fetchContourTile` which fetches the necessary * tiles and returns an encoded contour vector tiles. */ export interface DemManager { loaded: Promise<any>; fetchTile( z: number, x: number, y: number, timer?: Timer, ): CancelablePromise<FetchResponse>; fetchAndParseTile( z: number, x: number, y: number, timer?: Timer, ): CancelablePromise<DemTile>; fetchContourTile( z: number, x: number, y: number, options: IndividualContourTileOptions, timer?: Timer, ): CancelablePromise<ContourTile>; } /** * Caches, decodes, and processes raster tiles in the current thread. */ export class LocalDemManager implements DemManager { tileCache: AsyncCache<string, FetchResponse>; parsedCache: AsyncCache<string, DemTile>; contourCache: AsyncCache<string, ContourTile>; demUrlPattern: string; encoding: Encoding; maxzoom: number; timeoutMs: number; loaded = Promise.resolve(); decodeImage: (blob: Blob, encoding: Encoding) => CancelablePromise<DemTile> = decodeImage; constructor( demUrlPattern: string, cacheSize: number, encoding: Encoding, maxzoom: number, timeoutMs: number, ) { this.tileCache = new AsyncCache(cacheSize); this.parsedCache = new AsyncCache(cacheSize); this.contourCache = new AsyncCache(cacheSize); this.timeoutMs = timeoutMs; this.demUrlPattern = demUrlPattern; this.encoding = encoding; this.maxzoom = maxzoom; } fetchTile( z: number, x: number, y: number, timer?: Timer, ): CancelablePromise<FetchResponse> { const url = this.demUrlPattern .replace("{z}", z.toString()) .replace("{x}", x.toString()) .replace("{y}", y.toString()); timer?.useTile(url); return this.tileCache.getCancelable(url, () => { let cancel = () => {}; const options: RequestInit = {}; try { const controller = new AbortController(); options.signal = controller.signal; cancel = () => controller.abort(); } catch (e) { // ignore } timer?.fetchTile(url); const mark = timer?.marker("fetch"); return withTimeout(this.timeoutMs, { value: fetch(url, options).then(async (response) => { mark?.(); if (!response.ok) { throw new Error(`Bad response: ${response.status} for ${url}`); } return { data: await response.blob(), expires: response.headers.get("expires") || undefined, cacheControl: response.headers.get("cache-control") || undefined, }; }), cancel, }); }); } fetchAndParseTile = ( z: number, x: number, y: number, timer?: Timer, ): CancelablePromise<DemTile> => { const self = this; const url = this.demUrlPattern .replace("{z}", z.toString()) .replace("{x}", x.toString()) .replace("{y}", y.toString()); timer?.useTile(url); return this.parsedCache.getCancelable(url, () => { const tile = self.fetchTile(z, x, y, timer); let canceled = false; let alsoCancel = () => {}; return { value: tile.value.then(async (response) => { if (canceled) throw new Error("canceled"); const result = self.decodeImage(response.data, self.encoding); alsoCancel = result.cancel; const mark = timer?.marker("decode"); const value = await result.value; mark?.(); return value; }), cancel: () => { canceled = true; alsoCancel(); tile.cancel(); }, }; }); }; fetchDem( z: number, x: number, y: number, options: IndividualContourTileOptions, timer?: Timer, ): CancelablePromise<HeightTile> { const zoom = Math.min(z - (options.overzoom || 0), this.maxzoom); const subZ = z - zoom; const div = 1 << subZ; const newX = Math.floor(x / div); const newY = Math.floor(y / div); const { value, cancel } = this.fetchAndParseTile(zoom, newX, newY, timer); const subX = x % div; const subY = y % div; return { value: value.then((tile) => HeightTile.fromRawDem(tile).split(subZ, subX, subY), ), cancel, }; } fetchContourTile( z: number, x: number, y: number, options: IndividualContourTileOptions, timer?: Timer, ): CancelablePromise<ContourTile> { const { levels, multiplier = 1, buffer = 1, extent = 4096, contourLayer = "contours", elevationKey = "ele", levelKey = "level", subsampleBelow = 100, } = options; // no levels means less than min zoom with levels specified if (!levels || levels.length === 0) { return { cancel() {}, value: Promise.resolve({ arrayBuffer: new ArrayBuffer(0) }), }; } const key = [z, x,
y, encodeIndividualOptions(options)].join("/");
return this.contourCache.getCancelable(key, () => { const max = 1 << z; let canceled = false; const neighborPromises: (CancelablePromise<HeightTile> | null)[] = []; for (let iy = y - 1; iy <= y + 1; iy++) { for (let ix = x - 1; ix <= x + 1; ix++) { neighborPromises.push( iy < 0 || iy >= max ? null : this.fetchDem(z, (ix + max) % max, iy, options, timer), ); } } const value = Promise.all(neighborPromises.map((n) => n?.value)).then( async (neighbors) => { let virtualTile = HeightTile.combineNeighbors(neighbors); if (!virtualTile || canceled) { return { arrayBuffer: new Uint8Array().buffer }; } const mark = timer?.marker("isoline"); if (virtualTile.width >= subsampleBelow) { virtualTile = virtualTile.materialize(2); } else { while (virtualTile.width < subsampleBelow) { virtualTile = virtualTile.subsamplePixelCenters(2).materialize(2); } } virtualTile = virtualTile .averagePixelCentersToGrid() .scaleElevation(multiplier) .materialize(1); const isolines = generateIsolines( levels[0], virtualTile, extent, buffer, ); mark?.(); const result = encodeVectorTile({ extent, layers: { [contourLayer]: { features: Object.entries(isolines).map(([eleString, geom]) => { const ele = Number(eleString); return { type: GeomType.LINESTRING, geometry: geom, properties: { [elevationKey]: ele, [levelKey]: Math.max( ...levels.map((l, i) => (ele % l === 0 ? i : 0)), ), }, }; }), }, }, }); mark?.(); return { arrayBuffer: result.buffer }; }, ); return { value, cancel() { canceled = true; neighborPromises.forEach((n) => n && n.cancel()); }, }; }); } }
src/dem-manager.ts
onthegomap-maplibre-contour-0f2b64d
[ { "filename": "src/utils.ts", "retrieved_chunk": " return sortedEntries(options)\n .map(([k, v]) => `${encodeURIComponent(k)}=${encodeURIComponent(v)}`)\n .join(\",\");\n}\nexport function getOptionsForZoom(\n options: GlobalContourTileOptions,\n zoom: number,\n): IndividualContourTileOptions {\n const { thresholds, ...rest } = options;\n let levels: number[] = [];", "score": 0.876280665397644 }, { "filename": "src/utils.test.ts", "retrieved_chunk": " ...rest,\n levels: [100, 1000],\n });\n expect(getOptionsForZoom(fullGlobalOptions, 12)).toEqual({\n ...rest,\n levels: [100, 1000],\n });\n});\ntest(\"encode individual options\", () => {\n const options: IndividualContourTileOptions = {", "score": 0.8598986864089966 }, { "filename": "src/utils.test.ts", "retrieved_chunk": " levels: [1, 2],\n contourLayer: \"contour layer\",\n elevationKey: \"elevation key\",\n extent: 123,\n levelKey: \"level key\",\n multiplier: 123,\n overzoom: 3,\n };\n const origEncoded = encodeIndividualOptions(options);\n expect(encodeIndividualOptions(options)).toBe(origEncoded);", "score": 0.8579636812210083 }, { "filename": "src/utils.ts", "retrieved_chunk": " let maxLessThanOrEqualTo: number = -Infinity;\n Object.entries(thresholds).forEach(([zString, value]) => {\n const z = Number(zString);\n if (z <= zoom && z > maxLessThanOrEqualTo) {\n maxLessThanOrEqualTo = z;\n levels = typeof value === \"number\" ? [value] : value;\n }\n });\n return {\n levels,", "score": 0.8470545411109924 }, { "filename": "src/utils.test.ts", "retrieved_chunk": " const { thresholds, ...rest } = fullGlobalOptions;\n expect(getOptionsForZoom(fullGlobalOptions, 9)).toEqual({\n ...rest,\n levels: [],\n });\n expect(getOptionsForZoom(fullGlobalOptions, 10)).toEqual({\n ...rest,\n levels: [500],\n });\n expect(getOptionsForZoom(fullGlobalOptions, 11)).toEqual({", "score": 0.8416805267333984 } ]
typescript
y, encodeIndividualOptions(options)].join("/");