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/signers/nip46/index.ts",
"retrieved_chunk": " */\nexport class NDKNip46Signer implements NDKSigner {\n private ndk: NDK;\n public remoteUser: NDKUser;\n public remotePubkey: string;\n public token: string | undefined;\n public localSigner: NDKSigner;\n private rpc: NDKNostrRpc;\n private debug: debug.Debugger;\n /**",
"score": 0.9023808240890503
},
{
"filename": "src/signers/nip46/backend/index.ts",
"retrieved_chunk": " * should run client-side, where the user wants to sign events from.\n */\nexport class NDKNip46Backend {\n readonly ndk: NDK;\n readonly signer: NDKPrivateKeySigner;\n public localUser?: NDKUser;\n readonly debug: debug.Debugger;\n private rpc: NDKNostrRpc;\n private permitCallback: Nip46PermitCallback;\n /**",
"score": 0.8986988067626953
},
{
"filename": "src/user/index.ts",
"retrieved_chunk": " npub?: string;\n hexpubkey?: string;\n nip05?: string;\n relayUrls?: string[];\n}\n/**\n * Represents a pubkey.\n */\nexport default class NDKUser {\n public ndk: NDK | undefined;",
"score": 0.883185088634491
},
{
"filename": "src/signers/nip46/rpc.ts",
"retrieved_chunk": "}\nexport class NDKNostrRpc extends EventEmitter {\n private ndk: NDK;\n private signer: NDKSigner;\n private debug: debug.Debugger;\n public constructor(ndk: NDK, signer: NDKSigner, debug: debug.Debugger) {\n super();\n this.ndk = ndk;\n this.signer = signer;\n this.debug = debug.extend(\"rpc\");",
"score": 0.854878306388855
},
{
"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.8432585000991821
}
] | typescript | public signer?: NDKSigner; |
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/sets/index.ts",
"retrieved_chunk": " }\n }\n return subscription;\n }\n /**\n * Publish an event to all relays in this set. Returns the number of relays that have received the event.\n * @param event\n * @param timeoutMs - timeout in milliseconds for each publish operation and connection operation\n * @returns A set where the event was successfully published to\n */",
"score": 0.9501204490661621
},
{
"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.9465430974960327
},
{
"filename": "src/subscription/index.ts",
"retrieved_chunk": " }\n }\n // EVENT handling\n /**\n * Called when an event is received from a relay or the cache\n * @param event\n * @param relay\n * @param fromCache Whether the event was received from the cache\n */\n public eventReceived(",
"score": 0.8997055292129517
},
{
"filename": "src/index.ts",
"retrieved_chunk": " return user;\n }\n /**\n * Create a new subscription. Subscriptions automatically start and finish when all relays\n * on the set send back an EOSE. (set `opts.closeOnEose` to `false` in order avoid this)\n *\n * @param filters\n * @param opts\n * @param relaySet explicit relay set to use\n * @param autoStart automatically start the subscription",
"score": 0.898533284664154
},
{
"filename": "src/relay/pool/index.ts",
"retrieved_chunk": "/**\n * Handles connections to all relays. A single pool should be used per NDK instance.\n *\n * @emit connect - Emitted when all relays in the pool are connected, or when the specified timeout has elapsed, and some relays are connected.\n * @emit notice - Emitted when a relay in the pool sends a notice.\n * @emit flapping - Emitted when a relay in the pool is flapping.\n * @emit relay:connect - Emitted when a relay in the pool connects.\n * @emit relay:disconnect - Emitted when a relay in the pool disconnects.\n */\nexport class NDKPool extends EventEmitter {",
"score": 0.8951790928840637
}
] | typescript | public async publish(event: NDKEvent, timeoutMs = 2500): Promise<boolean> { |
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": " }\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.9017620086669922
},
{
"filename": "src/subscription/index.ts",
"retrieved_chunk": " throw new Error(\n \"Cannot use cache-only options with a persistent subscription\"\n );\n }\n }\n /**\n * Provides access to the first filter of the subscription for\n * backwards compatibility.\n */\n get filter(): NDKFilter {",
"score": 0.8774058222770691
},
{
"filename": "src/subscription/index.ts",
"retrieved_chunk": " // we should not wait for the cache\n this.opts.cacheUsage !== NDKSubscriptionCacheUsage.PARALLEL\n );\n }\n /**\n * Start the subscription. This is the main method that should be called\n * after creating a subscription.\n */\n public async start(): Promise<void> {\n let cachePromise;",
"score": 0.8752114176750183
},
{
"filename": "src/user/index.ts",
"retrieved_chunk": " /**\n * Get the tag that can be used to reference this user in an event\n * @returns {NDKTag} an NDKTag\n */\n public tagReference(): NDKTag {\n return [\"p\", this.hexpubkey()];\n }\n /**\n * Publishes the current profile.\n */",
"score": 0.8678290247917175
},
{
"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.8661099076271057
}
] | typescript | (marker?: string): NDKTag { |
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.8998386859893799
},
{
"filename": "src/subscription/index.ts",
"retrieved_chunk": " public eventFirstSeen = new Map<NDKEventId, number>();\n /**\n * Relays that have sent an EOSE.\n */\n public eosesSeen = new Set<NDKRelay>();\n /**\n * Events that have been seen by the subscription per relay.\n */\n public eventsPerRelay: Map<NDKRelay, Set<NDKEventId>> = new Map();\n public constructor(",
"score": 0.8768184185028076
},
{
"filename": "src/subscription/index.ts",
"retrieved_chunk": " // we should not wait for the cache\n this.opts.cacheUsage !== NDKSubscriptionCacheUsage.PARALLEL\n );\n }\n /**\n * Start the subscription. This is the main method that should be called\n * after creating a subscription.\n */\n public async start(): Promise<void> {\n let cachePromise;",
"score": 0.8742508888244629
},
{
"filename": "src/subscription/index.ts",
"retrieved_chunk": " throw new Error(\n \"Cannot use cache-only options with a persistent subscription\"\n );\n }\n }\n /**\n * Provides access to the first filter of the subscription for\n * backwards compatibility.\n */\n get filter(): NDKFilter {",
"score": 0.8687564134597778
},
{
"filename": "src/subscription/index.ts",
"retrieved_chunk": " * @default 100\n */\n groupableDelay?: number;\n /**\n * The subscription ID to use for the subscription.\n */\n subId?: string;\n}\n/**\n * Default subscription options.",
"score": 0.8667271733283997
}
] | typescript | activeSubscriptions = new Set<NDKSubscription>(); |
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.8776003122329712
},
{
"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.8632659912109375
},
{
"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.8560754656791687
},
{
"filename": "src/relay/sets/index.ts",
"retrieved_chunk": " }\n private subscribeOnRelay(relay: NDKRelay, subscription: NDKSubscription) {\n const sub = relay.subscribe(subscription);\n subscription.relaySubscriptions.set(relay, sub);\n }\n /**\n * Calculates an ID of this specific combination of relays.\n */\n public getId() {\n const urls = Array.from(this.relays).map((r) => r.url);",
"score": 0.8356693387031555
},
{
"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.8305586576461792
}
] | typescript | relaySet = correctRelaySet(relaySet, this.pool); |
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": " });\n return sub;\n }\n /**\n * Publishes an event to the relay with an optional timeout.\n *\n * If the relay is not connected, the event will be published when the relay connects,\n * unless the timeout is reached before the relay connects.\n *\n * @param event The event to publish",
"score": 0.9057981967926025
},
{
"filename": "src/relay/sets/index.ts",
"retrieved_chunk": " }\n }\n return subscription;\n }\n /**\n * Publish an event to all relays in this set. Returns the number of relays that have received the event.\n * @param event\n * @param timeoutMs - timeout in milliseconds for each publish operation and connection operation\n * @returns A set where the event was successfully published to\n */",
"score": 0.8974305391311646
},
{
"filename": "src/index.ts",
"retrieved_chunk": " public toJSON(): string {\n return { relayCount: this.pool.relays.size }.toString();\n }\n /**\n * Connect to relays with optional timeout.\n * If the timeout is reached, the connection will be continued to be established in the background.\n */\n public async connect(timeoutMs?: number): Promise<void> {\n this.debug(\"Connecting to relays\", { timeoutMs });\n return this.pool.connect(timeoutMs);",
"score": 0.8821178078651428
},
{
"filename": "src/subscription/index.ts",
"retrieved_chunk": " }\n }\n // EVENT handling\n /**\n * Called when an event is received from a relay or the cache\n * @param event\n * @param relay\n * @param fromCache Whether the event was received from the cache\n */\n public eventReceived(",
"score": 0.8806549310684204
},
{
"filename": "src/relay/sets/index.ts",
"retrieved_chunk": " }\n /**\n * Creates a relay set from a list of relay URLs.\n *\n * This is useful for testing in development to pass a local relay\n * to publish methods.\n *\n * @param relayUrls - list of relay URLs to include in this set\n * @param ndk\n * @returns NDKRelaySet",
"score": 0.8779687881469727
}
] | typescript | public useTemporaryRelay(relay: NDKRelay, removeIfUnusedAfter = 600000) { |
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/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.8959081172943115
},
{
"filename": "src/relay/index.ts",
"retrieved_chunk": " }\n /**\n * Disconnects from the relay.\n */\n public disconnect(): void {\n this._status = NDKRelayStatus.DISCONNECTING;\n this.relay.close();\n }\n async handleNotice(notice: string) {\n // This is a prototype; if the relay seems to be complaining",
"score": 0.8894098997116089
},
{
"filename": "src/index.ts",
"retrieved_chunk": " public toJSON(): string {\n return { relayCount: this.pool.relays.size }.toString();\n }\n /**\n * Connect to relays with optional timeout.\n * If the timeout is reached, the connection will be continued to be established in the background.\n */\n public async connect(timeoutMs?: number): Promise<void> {\n this.debug(\"Connecting to relays\", { timeoutMs });\n return this.pool.connect(timeoutMs);",
"score": 0.8864311575889587
},
{
"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.8793350458145142
},
{
"filename": "src/relay/index.ts",
"retrieved_chunk": " });\n return sub;\n }\n /**\n * Publishes an event to the relay with an optional timeout.\n *\n * If the relay is not connected, the event will be published when the relay connects,\n * unless the timeout is reached before the relay connects.\n *\n * @param event The event to publish",
"score": 0.8762630224227905
}
] | typescript | relay.on("notice", (relay, notice) =>
this.emit("notice", relay, notice)
); |
#!/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(/ /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/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.7810388207435608
},
{
"filename": "src/types.ts",
"retrieved_chunk": " *\n * @default true\n */\n contributors?: boolean;\n /**\n * Name of the release\n */\n name?: string;\n /**\n * Mark the release as a draft",
"score": 0.7679280638694763
},
{
"filename": "src/config.ts",
"retrieved_chunk": " test: { title: '✅ Tests' },\n style: { title: '🎨 Styles' },\n ci: { title: '🤖 CI' }\n },\n titles: {\n breakingChanges: '🚨 Breaking Changes'\n },\n tokens: {\n github: process.env.CHANGELOGEN_TOKENS_GITHUB || process.env.GITHUB_TOKEN || process.env.GH_TOKEN\n },",
"score": 0.767806887626648
},
{
"filename": "src/types.ts",
"retrieved_chunk": " breakingChanges?: string;\n };\n /**\n * Capitalize commit messages\n * @default true\n */\n capitalize?: boolean;\n /**\n * Nest commit messages under their scopes\n * @default true",
"score": 0.7625561356544495
},
{
"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.7606250643730164
}
] | 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(/ /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.8403618335723877
},
{
"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.7866278886795044
},
{
"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.7434877157211304
},
{
"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.7430113554000854
},
{
"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 `### ${$name}`;",
"score": 0.7422082424163818
}
] | typescript | 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/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.7897583246231079
},
{
"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.7791227698326111
},
{
"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.7661674618721008
},
{
"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.7543390989303589
},
{
"filename": "src/git.ts",
"retrieved_chunk": "}\nexport async function getLastGitTag(delta = 0) {\n const tags = await execCommand('git', ['--no-pager', 'tag', '-l', '--sort=creatordate']).then(r => r.split('\\n'));\n return tags[tags.length + delta - 1];\n}\nexport async function isRefGitTag(to: string) {\n const { execa } = await import('execa');\n try {\n await execa('git', ['show-ref', '--verify', `refs/tags/${to}`], { reject: true });\n return true;",
"score": 0.7258787155151367
}
] | typescript | export async function resolveAuthors(commits: Commit[], options: ChangelogOptions) { |
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": " }\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.7729024887084961
},
{
"filename": "src/github.ts",
"retrieved_chunk": " await $fetch(`https://api.github.com/repos/${options.repo.repo}/git/ref/tags/${tag}`, {\n headers: getHeaders(options)\n });\n return true;\n } catch (e) {\n return false;\n }\n}",
"score": 0.7544165849685669
},
{
"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.7526204586029053
},
{
"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.7443408966064453
},
{
"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.7366855144500732
}
] | typescript | function getGitPushUrl(config: RepoConfig, token?: string) { |
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.8095992803573608
},
{
"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.7958889007568359
},
{
"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.7801610231399536
},
{
"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.7781453132629395
},
{
"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.7723211050033569
}
] | typescript | : string | undefined, to = 'HEAD'): Promise<RawGitCommit[]> { |
#!/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(/ /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.8048180341720581
},
{
"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.8004195690155029
},
{
"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.7877150774002075
},
{
"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.7702998518943787
},
{
"filename": "src/github.ts",
"retrieved_chunk": " if (nameSet.has(i.name)) {\n return false;\n }\n nameSet.add(i.name);\n }\n return true;\n });\n}\nexport async function hasTagOnGitHub(tag: string, options: ChangelogOptions) {\n try {",
"score": 0.7575747966766357
}
] | typescript | if (!commits.length && (await isRepoShallow())) { |
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/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.7933897376060486
},
{
"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.7491122484207153
},
{
"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.743535578250885
},
{
"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.7384055852890015
},
{
"filename": "src/git.ts",
"retrieved_chunk": " const $r: RawGitCommit = {\n message,\n shortHash,\n author: { name: authorName, email: authorEmail },\n body: _body.join('\\n')\n };\n return $r;\n });\n}\nexport function getGitRemoteURL(cwd: string, remote = 'origin') {",
"score": 0.7287476658821106
}
] | typescript | , info: AuthorInfo) { |
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.8544759750366211
},
{
"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.8445093631744385
},
{
"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.843429684638977
},
{
"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.8273824453353882
},
{
"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.8201329708099365
}
] | 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/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.8535733222961426
},
{
"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.8419208526611328
},
{
"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.8413174748420715
},
{
"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.8262430429458618
},
{
"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.8191603422164917
}
] | 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 = ` - ${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 `### ${$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('', `##### [View changes on GitHub](${url})`);
return convert(lines.join('\n').trim(), true);
}
| src/markdown.ts | soybeanjs-githublogen-0932953 | [
{
"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.7884854078292847
},
{
"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.7797784805297852
},
{
"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.7759782671928406
},
{
"filename": "src/parse.ts",
"retrieved_chunk": " for (const m of description.matchAll(PullRequestRE)) {\n references.push({ type: 'pull-request', value: m[1] });\n }\n for (const m of description.matchAll(IssueRE)) {\n if (!references.some(i => i.value === m[1])) {\n references.push({ type: 'issue', value: m[1] });\n }\n }\n references.push({ value: commit.shortHash, type: 'hash' });\n // Remove references and normalize",
"score": 0.760408341884613
},
{
"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.7593654990196228
}
] | 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 = ` - ${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 `### ${$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('', `##### [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.8365175724029541
},
{
"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.8290522694587708
},
{
"filename": "src/git.ts",
"retrieved_chunk": " const $r: RawGitCommit = {\n message,\n shortHash,\n author: { name: authorName, email: authorEmail },\n body: _body.join('\\n')\n };\n return $r;\n });\n}\nexport function getGitRemoteURL(cwd: string, remote = 'origin') {",
"score": 0.8063043355941772
},
{
"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.802553117275238
},
{
"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.7967160940170288
}
] | typescript | const scopes = groupBy(commits, 'scope'); |
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 = ` - ${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 `### ${$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('', `##### [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.8433185815811157
},
{
"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.8117305040359497
},
{
"filename": "src/parse.ts",
"retrieved_chunk": " if (!match?.groups) {\n return null;\n }\n const type = match.groups.type;\n let scope = match.groups.scope || '';\n scope = config.scopeMap[scope] || scope;\n const isBreaking = Boolean(match.groups.breaking);\n let description = match.groups.description;\n // Extract references from message\n const references: Reference[] = [];",
"score": 0.8064441084861755
},
{
"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.7961111664772034
},
{
"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.7880128026008606
}
] | typescript | if (!Object.entries(scopes).some(([k, v]) => k && v.length > 1)) { |
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 = ` - ${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 `### ${$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('', `##### [View changes on GitHub](${url})`);
return convert(lines.join('\n').trim(), true);
}
| src/markdown.ts | soybeanjs-githublogen-0932953 | [
{
"filename": "src/parse.ts",
"retrieved_chunk": " if (!match?.groups) {\n return null;\n }\n const type = match.groups.type;\n let scope = match.groups.scope || '';\n scope = config.scopeMap[scope] || scope;\n const isBreaking = Boolean(match.groups.breaking);\n let description = match.groups.description;\n // Extract references from message\n const references: Reference[] = [];",
"score": 0.7488818764686584
},
{
"filename": "src/cli.ts",
"retrieved_chunk": " const { config, md, commits } = await generate(cwd, args as unknown as ChangelogOptions);\n const markdown = md.replace(/ /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.744770348072052
},
{
"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.739539623260498
},
{
"filename": "src/cli.ts",
"retrieved_chunk": " .option('--capitalize', 'Should capitalize for each comment message')\n .option('--emoji', 'Use emojis in section titles', { default: true })\n .option('--group', 'Nest commit messages under their scopes')\n .option('--dry', 'Dry run')\n .help();\ncli.command('').action(async (args: any) => {\n try {\n console.log();\n console.log(dim(`${bold('github')}logen `) + dim(`v${version}`));\n const cwd = process.cwd();",
"score": 0.7358103394508362
},
{
"filename": "src/parse.ts",
"retrieved_chunk": " for (const m of description.matchAll(PullRequestRE)) {\n references.push({ type: 'pull-request', value: m[1] });\n }\n for (const m of description.matchAll(IssueRE)) {\n if (!references.some(i => i.value === m[1])) {\n references.push({ type: 'issue', value: m[1] });\n }\n }\n references.push({ value: commit.shortHash, type: 'hash' });\n // Remove references and normalize",
"score": 0.72576904296875
}
] | 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/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.8516378402709961
},
{
"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.8253321051597595
},
{
"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.819817841053009
},
{
"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.8148860335350037
},
{
"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.8148043751716614
}
] | 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 = ` - ${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 `### ${$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('', `##### [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.8064112663269043
},
{
"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.7982159852981567
},
{
"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.7707979679107666
},
{
"filename": "src/github.ts",
"retrieved_chunk": " if (nameSet.has(i.name)) {\n return false;\n }\n nameSet.add(i.name);\n }\n return true;\n });\n}\nexport async function hasTagOnGitHub(tag: string, options: ChangelogOptions) {\n try {",
"score": 0.770689845085144
},
{
"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.766958475112915
}
] | 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.818356454372406
},
{
"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.7715671062469482
},
{
"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.7600131034851074
},
{
"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.7549603581428528
},
{
"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 `### ${$name}`;",
"score": 0.7406289577484131
}
] | 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.8497582674026489
},
{
"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.8471629023551941
},
{
"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.8359841108322144
},
{
"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.8307172656059265
},
{
"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.8269610404968262
}
] | typescript | .map(commit => parseGitCommit(commit, config)).filter(notNullish); |
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": " 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.8926723003387451
},
{
"filename": "src/relay/index.ts",
"retrieved_chunk": " }\n /**\n * Disconnects from the relay.\n */\n public disconnect(): void {\n this._status = NDKRelayStatus.DISCONNECTING;\n this.relay.close();\n }\n async handleNotice(notice: string) {\n // This is a prototype; if the relay seems to be complaining",
"score": 0.8915896415710449
},
{
"filename": "src/index.ts",
"retrieved_chunk": " public toJSON(): string {\n return { relayCount: this.pool.relays.size }.toString();\n }\n /**\n * Connect to relays with optional timeout.\n * If the timeout is reached, the connection will be continued to be established in the background.\n */\n public async connect(timeoutMs?: number): Promise<void> {\n this.debug(\"Connecting to relays\", { timeoutMs });\n return this.pool.connect(timeoutMs);",
"score": 0.8831666707992554
},
{
"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.8782920241355896
},
{
"filename": "src/relay/sets/index.ts",
"retrieved_chunk": " }\n private subscribeOnRelay(relay: NDKRelay, subscription: NDKSubscription) {\n const sub = relay.subscribe(subscription);\n subscription.relaySubscriptions.set(relay, sub);\n }\n /**\n * Calculates an ID of this specific combination of relays.\n */\n public getId() {\n const urls = Array.from(this.relays).map((r) => r.url);",
"score": 0.8767773509025574
}
] | typescript | "notice", (relay, notice) =>
this.emit("notice", relay, notice)
); |
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": " 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.8202614188194275
},
{
"filename": "src/relay/index.ts",
"retrieved_chunk": " /**\n * Called when the relay is unexpectedly disconnected.\n */\n private handleReconnection() {\n if (this.isFlapping()) {\n this.emit(\"flapping\", this, this._connectionStats);\n this._status = NDKRelayStatus.FLAPPING;\n }\n if (this.connectedAt && Date.now() - this.connectedAt < 5000) {\n setTimeout(() => this.connect(), 60000);",
"score": 0.808986246585846
},
{
"filename": "src/relay/sets/utils.ts",
"retrieved_chunk": " // if connected relays is empty (such us when we're first starting, add all relays)\n if (connectedRelays.length === 0) {\n for (const relay of pool.relays.values()) {\n relaySet.addRelay(relay);\n }\n }\n return relaySet;\n}",
"score": 0.7970498204231262
},
{
"filename": "src/relay/index.ts",
"retrieved_chunk": " this.emit(\"disconnect\");\n });\n this.relay.on(\"notice\", (notice: string) => this.handleNotice(notice));\n }\n /**\n * Evaluates the connection stats to determine if the relay is flapping.\n */\n private isFlapping(): boolean {\n const durations = this._connectionStats.durations;\n if (durations.length < 10) return false;",
"score": 0.7935968637466431
},
{
"filename": "src/relay/index.ts",
"retrieved_chunk": " }\n /**\n * Disconnects from the relay.\n */\n public disconnect(): void {\n this._status = NDKRelayStatus.DISCONNECTING;\n this.relay.close();\n }\n async handleNotice(notice: string) {\n // This is a prototype; if the relay seems to be complaining",
"score": 0.7844691872596741
}
] | typescript | public connectedRelays(): NDKRelay[] { |
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": " }\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.7789421677589417
},
{
"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.774736762046814
},
{
"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.7708824872970581
},
{
"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.7689073085784912
},
{
"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.7680874466896057
}
] | 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(/ /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.7973209619522095
},
{
"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.7965648174285889
},
{
"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.7827833294868469
},
{
"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.7633348703384399
},
{
"filename": "src/github.ts",
"retrieved_chunk": " if (nameSet.has(i.name)) {\n return false;\n }\n nameSet.add(i.name);\n }\n return true;\n });\n}\nexport async function hasTagOnGitHub(tag: string, options: ChangelogOptions) {\n try {",
"score": 0.7607789039611816
}
] | 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": "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.8644648790359497
},
{
"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.813888430595398
},
{
"filename": "src/github.ts",
"retrieved_chunk": " };\n}\nexport async function resolveAuthorInfo(options: ChangelogOptions, info: AuthorInfo) {\n if (info.login) return info;\n // token not provided, skip github resolving\n if (!options.tokens.github) return info;\n try {\n const data = await $fetch(`https://api.github.com/search/users?q=${encodeURIComponent(info.email)}`, {\n headers: getHeaders(options)\n });",
"score": 0.7910223007202148
},
{
"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.7890698909759521
},
{
"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.7872601747512817
}
] | 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 = ` - ${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 `### ${$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('', `##### [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.8011308908462524
},
{
"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.7936131954193115
},
{
"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.7740265130996704
},
{
"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.7710476517677307
},
{
"filename": "src/git.ts",
"retrieved_chunk": "async function execCommand(cmd: string, args: string[]) {\n const { execa } = await import('execa');\n const res = await execa(cmd, args);\n return res.stdout.trim();\n}\nexport async function getGitDiff(from: string | undefined, to = 'HEAD'): Promise<RawGitCommit[]> {\n // https://git-scm.com/docs/pretty-formats\n const r = await execCommand('git', [\n '--no-pager',\n 'log',",
"score": 0.7705500721931458
}
] | 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(/ /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.8322187066078186
},
{
"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.7769551873207092
},
{
"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.7366272211074829
},
{
"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 `### ${$name}`;",
"score": 0.7346466183662415
},
{
"filename": "src/git.ts",
"retrieved_chunk": "async function execCommand(cmd: string, args: string[]) {\n const { execa } = await import('execa');\n const res = await execa(cmd, args);\n return res.stdout.trim();\n}\nexport async function getGitDiff(from: string | undefined, to = 'HEAD'): Promise<RawGitCommit[]> {\n // https://git-scm.com/docs/pretty-formats\n const r = await execCommand('git', [\n '--no-pager',\n 'log',",
"score": 0.7278255820274353
}
] | 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/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.7945528030395508
},
{
"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.7605001926422119
},
{
"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.7541429996490479
},
{
"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.7526888847351074
},
{
"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.7419129610061646
}
] | 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/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.8148378133773804
},
{
"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.7680131196975708
},
{
"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.7625007629394531
},
{
"filename": "src/git.ts",
"retrieved_chunk": " const $r: RawGitCommit = {\n message,\n shortHash,\n author: { name: authorName, email: authorEmail },\n body: _body.join('\\n')\n };\n return $r;\n });\n}\nexport function getGitRemoteURL(cwd: string, remote = 'origin') {",
"score": 0.7561696767807007
},
{
"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.7547802925109863
}
] | typescript | if (info.login) return info; |
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.8479728698730469
},
{
"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.8462634086608887
},
{
"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.8287492394447327
},
{
"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.8245438933372498
},
{
"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.8129773139953613
}
] | typescript | .map((a, idx) => { |
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/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.8873487710952759
},
{
"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.8749514818191528
},
{
"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.8690817952156067
},
{
"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.8509816527366638
},
{
"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.8433498740196228
}
] | typescript | NDKFilter[]
): Map<NDKFilter, NDKRelaySet> { |
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/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.7724004983901978
},
{
"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.7529909610748291
},
{
"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.7456361055374146
},
{
"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 = ` - ${refs}`;",
"score": 0.7383798360824585
},
{
"filename": "src/git.ts",
"retrieved_chunk": "}\nexport async function getLastGitTag(delta = 0) {\n const tags = await execCommand('git', ['--no-pager', 'tag', '-l', '--sort=creatordate']).then(r => r.split('\\n'));\n return tags[tags.length + delta - 1];\n}\nexport async function isRefGitTag(to: string) {\n const { execa } = await import('execa');\n try {\n await execa('git', ['show-ref', '--verify', `refs/tags/${to}`], { reject: true });\n return true;",
"score": 0.7331278324127197
}
] | 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 = ` - ${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 `### ${$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('', `##### [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.8038216829299927
},
{
"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.801869809627533
},
{
"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.7802942395210266
},
{
"filename": "src/github.ts",
"retrieved_chunk": " if (nameSet.has(i.name)) {\n return false;\n }\n nameSet.add(i.name);\n }\n return true;\n });\n}\nexport async function hasTagOnGitHub(tag: string, options: ChangelogOptions) {\n try {",
"score": 0.7724394798278809
},
{
"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.7706383466720581
}
] | typescript | [breaking, changes] = partition(commits, c => c.isBreaking); |
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.7783320546150208
},
{
"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 = ` - ${refs}`;",
"score": 0.7731829285621643
},
{
"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 `### ${$name}`;",
"score": 0.740885853767395
},
{
"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.7228308916091919
},
{
"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.7093575596809387
}
] | typescript | => (a.login || a.name).localeCompare(b.login || b.name))
.filter(i => { |
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.8546733260154724
},
{
"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.844832718372345
},
{
"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.8422478437423706
},
{
"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.8272615671157837
},
{
"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.8197270631790161
}
] | typescript | ((a, idx) => { |
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.8504172563552856
},
{
"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.849639356136322
},
{
"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.8454626202583313
},
{
"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.8256038427352905
},
{
"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.8224903345108032
}
] | 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.8364161252975464
},
{
"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.807440459728241
},
{
"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.8000297546386719
},
{
"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 `### ${$name}`;",
"score": 0.768393337726593
},
{
"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.7474672198295593
}
] | typescript | const part = config.repo?.provider === 'bitbucket' ? 'branches/compare' : 'compare'; |
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.8317440748214722
},
{
"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.7863866090774536
},
{
"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.7820405960083008
},
{
"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 `### ${$name}`;",
"score": 0.7547889947891235
},
{
"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.7479300498962402
}
] | 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/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.8420654535293579
},
{
"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.8306491374969482
},
{
"filename": "src/git.ts",
"retrieved_chunk": " const $r: RawGitCommit = {\n message,\n shortHash,\n author: { name: authorName, email: authorEmail },\n body: _body.join('\\n')\n };\n return $r;\n });\n}\nexport function getGitRemoteURL(cwd: string, remote = 'origin') {",
"score": 0.8279251456260681
},
{
"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.8210576176643372
},
{
"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 = ` - ${refs}`;",
"score": 0.8082529306411743
}
] | 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/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.8852671384811401
},
{
"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.8695111274719238
},
{
"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.8678945302963257
},
{
"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.8464552760124207
},
{
"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.8422161340713501
}
] | 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/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.7944084405899048
},
{
"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.7823870182037354
},
{
"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.7809711694717407
},
{
"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.7801011800765991
},
{
"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.7642121911048889
}
] | 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/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.8654886484146118
},
{
"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.8370922803878784
},
{
"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.8354109525680542
},
{
"filename": "src/user/follows.ts",
"retrieved_chunk": "import { nip19 } from \"nostr-tools\";\nimport NDKUser from \"./index.js\";\nexport async function follows(this: NDKUser): Promise<Set<NDKUser>> {\n if (!this.ndk) throw new Error(\"NDK not set\");\n const contactListEvents = await this.ndk.fetchEvents({\n kinds: [3],\n authors: [this.hexpubkey()],\n });\n if (contactListEvents) {\n const npubs = new Set<string>();",
"score": 0.8198630213737488
},
{
"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.8100427389144897
}
] | typescript | on("event", (e) => this.handleIncomingEvent(e)); |
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/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.7944084405899048
},
{
"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.7823870182037354
},
{
"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.7809711694717407
},
{
"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.7801011800765991
},
{
"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.7642121911048889
}
] | typescript | 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/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.769188404083252
},
{
"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.7592730522155762
},
{
"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.7530418038368225
},
{
"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.7525667548179626
},
{
"filename": "src/signers/nip46/index.ts",
"retrieved_chunk": "import NDK, {\n NDKPrivateKeySigner,\n NDKSigner,\n NDKUser,\n NostrEvent,\n} from \"../../index.js\";\nimport { NDKNostrRpc, NDKRpcResponse } from \"./rpc.js\";\n/**\n * This NDKSigner implements NIP-46, which allows remote signing of events.\n * This class is meant to be used client-side, paired with the NDKNip46Backend or a NIP-46 backend (like Nostr-Connect)",
"score": 0.7488113641738892
}
] | 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/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.7944084405899048
},
{
"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.7823870182037354
},
{
"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.7809711694717407
},
{
"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.7801011800765991
},
{
"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.7642121911048889
}
] | 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/signers/nip07/index.ts",
"retrieved_chunk": " recipientHexPubKey: string,\n value: string\n ): Promise<string>;\n decrypt(\n senderHexPubKey: string,\n value: string\n ): Promise<string>;\n };\n };\n }",
"score": 0.8909380435943604
},
{
"filename": "src/signers/nip46/index.ts",
"retrieved_chunk": " * @param localSigner - The signer that will be used to request events to be signed\n */\n public constructor(\n ndk: NDK,\n tokenOrRemotePubkey: string,\n localSigner?: NDKSigner\n ) {\n let remotePubkey: string;\n let token: string | undefined;\n if (tokenOrRemotePubkey.includes(\"#\")) {",
"score": 0.8602616190910339
},
{
"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.8402680158615112
},
{
"filename": "src/signers/nip46/rpc.ts",
"retrieved_chunk": " id: string,\n remotePubkey: string,\n result: string,\n kind = 24133,\n error?: string\n ) {\n const res = { id, result } as NDKRpcResponse;\n if (error) {\n res.error = error;\n }",
"score": 0.8292226195335388
},
{
"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.8282170295715332
}
] | typescript | senderUser: NDKUser,
payload: string
) { |
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.9601659178733826
},
{
"filename": "src/relay/index.ts",
"retrieved_chunk": " });\n return sub;\n }\n /**\n * Publishes an event to the relay with an optional timeout.\n *\n * If the relay is not connected, the event will be published when the relay connects,\n * unless the timeout is reached before the relay connects.\n *\n * @param event The event to publish",
"score": 0.9139492511749268
},
{
"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.9122231006622314
},
{
"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.9095532894134521
},
{
"filename": "src/index.ts",
"retrieved_chunk": " }\n /**\n * Fetch a single event.\n *\n * @param idOrFilter event id in bech32 format or filter\n * @param opts subscription options\n * @param relaySet explicit relay set to use\n */\n public async fetchEvent(\n idOrFilter: string | NDKFilter,",
"score": 0.8940220475196838
}
] | typescript | NDKEvent,
timeoutMs?: number
): Promise<Set<NDKRelay>> { |
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.957502543926239
},
{
"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.9182409644126892
},
{
"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.9179738759994507
},
{
"filename": "src/relay/index.ts",
"retrieved_chunk": " });\n return sub;\n }\n /**\n * Publishes an event to the relay with an optional timeout.\n *\n * If the relay is not connected, the event will be published when the relay connects,\n * unless the timeout is reached before the relay connects.\n *\n * @param event The event to publish",
"score": 0.9058455228805542
},
{
"filename": "src/index.ts",
"retrieved_chunk": " public toJSON(): string {\n return { relayCount: this.pool.relays.size }.toString();\n }\n /**\n * Connect to relays with optional timeout.\n * If the timeout is reached, the connection will be continued to be established in the background.\n */\n public async connect(timeoutMs?: number): Promise<void> {\n this.debug(\"Connecting to relays\", { timeoutMs });\n return this.pool.connect(timeoutMs);",
"score": 0.896365761756897
}
] | 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/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.9064599871635437
},
{
"filename": "src/subscription/index.ts",
"retrieved_chunk": " // we should not wait for the cache\n this.opts.cacheUsage !== NDKSubscriptionCacheUsage.PARALLEL\n );\n }\n /**\n * Start the subscription. This is the main method that should be called\n * after creating a subscription.\n */\n public async start(): Promise<void> {\n let cachePromise;",
"score": 0.8960543870925903
},
{
"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.8957273960113525
},
{
"filename": "src/events/kinds/lists/index.ts",
"retrieved_chunk": " * Adds a new item to the list.\n * @param relay Relay to add\n * @param mark Optional mark to add to the item\n * @param encrypted Whether to encrypt the item\n */\n async addItem(\n item: NDKListItem | NDKTag,\n mark: string | undefined = undefined,\n encrypted = false\n ): Promise<void> {",
"score": 0.8922238349914551
},
{
"filename": "src/index.ts",
"retrieved_chunk": " }\n /**\n * Fetch a single event.\n *\n * @param idOrFilter event id in bech32 format or filter\n * @param opts subscription options\n * @param relaySet explicit relay set to use\n */\n public async fetchEvent(\n idOrFilter: string | NDKFilter,",
"score": 0.885198712348938
}
] | typescript | protected async handleIncomingEvent(event: NDKEvent) { |
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/nip46/backend/index.ts",
"retrieved_chunk": " pubkey: string,\n method: string,\n params?: any\n) => Promise<boolean>;\nexport type Nip46ApplyTokenCallback = (\n pubkey: string,\n token: string\n) => Promise<void>;\nexport interface IEventHandlingStrategy {\n handle(",
"score": 0.8332661390304565
},
{
"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.8286426067352295
},
{
"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.8281970024108887
},
{
"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.8248704075813293
},
{
"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.8122771978378296
}
] | 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/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.9373524188995361
},
{
"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.9357960224151611
},
{
"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.8786870241165161
},
{
"filename": "src/signers/nip46/index.ts",
"retrieved_chunk": " * @param localSigner - The signer that will be used to request events to be signed\n */\n public constructor(\n ndk: NDK,\n tokenOrRemotePubkey: string,\n localSigner?: NDKSigner\n ) {\n let remotePubkey: string;\n let token: string | undefined;\n if (tokenOrRemotePubkey.includes(\"#\")) {",
"score": 0.8751368522644043
},
{
"filename": "src/index.ts",
"retrieved_chunk": " }\n /**\n * Fetch a single event.\n *\n * @param idOrFilter event id in bech32 format or filter\n * @param opts subscription options\n * @param relaySet explicit relay set to use\n */\n public async fetchEvent(\n idOrFilter: string | NDKFilter,",
"score": 0.8745253086090088
}
] | 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/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.8934795260429382
},
{
"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.8829295635223389
},
{
"filename": "src/signers/nip46/index.ts",
"retrieved_chunk": " * @param localSigner - The signer that will be used to request events to be signed\n */\n public constructor(\n ndk: NDK,\n tokenOrRemotePubkey: string,\n localSigner?: NDKSigner\n ) {\n let remotePubkey: string;\n let token: string | undefined;\n if (tokenOrRemotePubkey.includes(\"#\")) {",
"score": 0.8773735761642456
},
{
"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.8682892322540283
},
{
"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.8662521839141846
}
] | typescript | recipientUser: NDKUser,
payload: 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/relay/index.ts",
"retrieved_chunk": " * @emits NDKRelay#event\n * @emits NDKRelay#published when an event is published to the relay\n * @emits NDKRelay#publish:failed when an event fails to publish to the relay\n * @emits NDKRelay#eose\n */\nexport class NDKRelay extends EventEmitter {\n readonly url: string;\n readonly scores: Map<User, NDKRelayScore>;\n private relay: Relay;\n private _status: NDKRelayStatus;",
"score": 0.8671739101409912
},
{
"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.8500550389289856
},
{
"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.8478434085845947
},
{
"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.839144229888916
},
{
"filename": "src/signers/nip46/rpc.ts",
"retrieved_chunk": " }\n /**\n * Subscribe to a filter. This function will resolve once the subscription is ready.\n */\n public async subscribe(filter: NDKFilter): Promise<NDKSubscription> {\n const sub = this.ndk.subscribe(filter, { closeOnEose: false });\n sub.on(\"event\", async (event: NDKEvent) => {\n try {\n const parsedEvent = await this.parseEvent(event);\n if ((parsedEvent as NDKRpcRequest).method) {",
"score": 0.8382093906402588
}
] | 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/user/index.ts",
"retrieved_chunk": " }\n /**\n * Returns a set of users that this user follows.\n */\n public follows = follows.bind(this);\n /**\n * Returns a set of relay list events for a user.\n * @returns {Promise<Set<NDKEvent>>} A set of NDKEvents returned for the given user.\n */\n public async relayList(): Promise<Set<NDKEvent>> {",
"score": 0.8867213129997253
},
{
"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.8388403654098511
},
{
"filename": "src/events/index.ts",
"retrieved_chunk": " \"NDKEvent must be associated with an NDK instance to publish\"\n );\n return this.ndk.publish(this, relaySet, timeoutMs);\n }\n /**\n * Generates tags for users, notes, and other events tagged in content.\n * Will also generate random \"d\" tag for parameterized replaceable events where needed.\n * @returns {ContentTag} The tags and content of the event.\n */\n protected generateTags(): ContentTag {",
"score": 0.8356305956840515
},
{
"filename": "src/signers/index.ts",
"retrieved_chunk": " blockUntilReady(): Promise<NDKUser>;\n /**\n * Getter for the user property.\n * @returns A promise that resolves to the NDKUser instance.\n */\n user(): Promise<NDKUser>;\n /**\n * Signs the given Nostr event.\n * @param event - The Nostr event to be signed.\n * @returns A promise that resolves to the signature of the signed event.",
"score": 0.8309304714202881
},
{
"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.830521285533905
}
] | 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/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.8765506744384766
},
{
"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.866021990776062
},
{
"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.8613525629043579
},
{
"filename": "src/relay/index.ts",
"retrieved_chunk": " * @emits NDKRelay#event\n * @emits NDKRelay#published when an event is published to the relay\n * @emits NDKRelay#publish:failed when an event fails to publish to the relay\n * @emits NDKRelay#eose\n */\nexport class NDKRelay extends EventEmitter {\n readonly url: string;\n readonly scores: Map<User, NDKRelayScore>;\n private relay: Relay;\n private _status: NDKRelayStatus;",
"score": 0.8477516174316406
},
{
"filename": "src/events/kinds/repost.ts",
"retrieved_chunk": " private _repostedEvents: T[] | undefined;\n constructor(ndk?: NDK, rawEvent?: NostrEvent) {\n super(ndk, rawEvent);\n }\n static from(event: NDKEvent) {\n return new NDKRepost(event.ndk, event.rawEvent());\n }\n /**\n * Returns all reposted events by the current event.\n *",
"score": 0.8454031944274902
}
] | typescript | : Map<NDKRelay, Sub>; |
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/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.8884855508804321
},
{
"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.8741598725318909
},
{
"filename": "src/signers/nip46/index.ts",
"retrieved_chunk": " * @param localSigner - The signer that will be used to request events to be signed\n */\n public constructor(\n ndk: NDK,\n tokenOrRemotePubkey: string,\n localSigner?: NDKSigner\n ) {\n let remotePubkey: string;\n let token: string | undefined;\n if (tokenOrRemotePubkey.includes(\"#\")) {",
"score": 0.8719218969345093
},
{
"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.8652206659317017
},
{
"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.8587990999221802
}
] | 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/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.8773338794708252
},
{
"filename": "src/relay/index.ts",
"retrieved_chunk": " * @emits NDKRelay#event\n * @emits NDKRelay#published when an event is published to the relay\n * @emits NDKRelay#publish:failed when an event fails to publish to the relay\n * @emits NDKRelay#eose\n */\nexport class NDKRelay extends EventEmitter {\n readonly url: string;\n readonly scores: Map<User, NDKRelayScore>;\n private relay: Relay;\n private _status: NDKRelayStatus;",
"score": 0.8639326095581055
},
{
"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.8583463430404663
},
{
"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.8529268503189087
},
{
"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.8500222563743591
}
] | typescript | public relaySubscriptions: Map<NDKRelay, Sub>; |
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/backend/index.ts",
"retrieved_chunk": " } else {\n this.debug(\"unsupported method\", { method, params });\n }\n if (response) {\n this.debug(`sending response to ${remotePubkey}`, response);\n this.rpc.sendResponse(id, remotePubkey, response);\n } else {\n this.rpc.sendResponse(\n id,\n remotePubkey,",
"score": 0.8396928310394287
},
{
"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.836432933807373
},
{
"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.8325293064117432
},
{
"filename": "src/signers/nip46/backend/index.ts",
"retrieved_chunk": " } catch (e: any) {\n this.debug(\"error handling event\", e, { id, method, params });\n this.rpc.sendResponse(\n id,\n remotePubkey,\n \"error\",\n undefined,\n e.message\n );\n }",
"score": 0.8144465088844299
},
{
"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.7886005640029907
}
] | typescript | (response: NDKRpcResponse) => { |
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": " * @emits NDKRelay#event\n * @emits NDKRelay#published when an event is published to the relay\n * @emits NDKRelay#publish:failed when an event fails to publish to the relay\n * @emits NDKRelay#eose\n */\nexport class NDKRelay extends EventEmitter {\n readonly url: string;\n readonly scores: Map<User, NDKRelayScore>;\n private relay: Relay;\n private _status: NDKRelayStatus;",
"score": 0.8640204071998596
},
{
"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.8489895462989807
},
{
"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.8425077795982361
},
{
"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.8390666246414185
},
{
"filename": "src/signers/nip46/rpc.ts",
"retrieved_chunk": " }\n /**\n * Subscribe to a filter. This function will resolve once the subscription is ready.\n */\n public async subscribe(filter: NDKFilter): Promise<NDKSubscription> {\n const sub = this.ndk.subscribe(filter, { closeOnEose: false });\n sub.on(\"event\", async (event: NDKEvent) => {\n try {\n const parsedEvent = await this.parseEvent(event);\n if ((parsedEvent as NDKRpcRequest).method) {",
"score": 0.8373827934265137
}
] | 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.9059959650039673
},
{
"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.8965896368026733
},
{
"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.8635542392730713
},
{
"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.8625420331954956
},
{
"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.8418624997138977
}
] | 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/user/index.ts",
"retrieved_chunk": " }\n /**\n * Returns a set of users that this user follows.\n */\n public follows = follows.bind(this);\n /**\n * Returns a set of relay list events for a user.\n * @returns {Promise<Set<NDKEvent>>} A set of NDKEvents returned for the given user.\n */\n public async relayList(): Promise<Set<NDKEvent>> {",
"score": 0.8817699551582336
},
{
"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.8801571726799011
},
{
"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.8703120350837708
},
{
"filename": "src/relay/sets/index.ts",
"retrieved_chunk": " * A relay set is a group of relays. This grouping can be short-living, for a single\n * REQ or can be long-lasting, for example for the explicit relay list the user\n * has specified.\n *\n * Requests to relays should be sent through this interface.\n */\nexport class NDKRelaySet {\n readonly relays: Set<NDKRelay>;\n private debug: debug.Debugger;\n private ndk: NDK;",
"score": 0.8679558038711548
},
{
"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.8670313358306885
}
] | 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/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.9221224188804626
},
{
"filename": "src/index.ts",
"retrieved_chunk": " }\n /**\n * Fetch a single event.\n *\n * @param idOrFilter event id in bech32 format or filter\n * @param opts subscription options\n * @param relaySet explicit relay set to use\n */\n public async fetchEvent(\n idOrFilter: string | NDKFilter,",
"score": 0.8980515003204346
},
{
"filename": "src/events/kinds/lists/index.ts",
"retrieved_chunk": " * Adds a new item to the list.\n * @param relay Relay to add\n * @param mark Optional mark to add to the item\n * @param encrypted Whether to encrypt the item\n */\n async addItem(\n item: NDKListItem | NDKTag,\n mark: string | undefined = undefined,\n encrypted = false\n ): Promise<void> {",
"score": 0.8876532316207886
},
{
"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.8794411420822144
},
{
"filename": "src/relay/sets/index.ts",
"retrieved_chunk": " }\n }\n return subscription;\n }\n /**\n * Publish an event to all relays in this set. Returns the number of relays that have received the event.\n * @param event\n * @param timeoutMs - timeout in milliseconds for each publish operation and connection operation\n * @returns A set where the event was successfully published to\n */",
"score": 0.8760966062545776
}
] | 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": " * @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.9294347167015076
},
{
"filename": "src/index.ts",
"retrieved_chunk": " }\n /**\n * Fetch a single event.\n *\n * @param idOrFilter event id in bech32 format or filter\n * @param opts subscription options\n * @param relaySet explicit relay set to use\n */\n public async fetchEvent(\n idOrFilter: string | NDKFilter,",
"score": 0.9011228084564209
},
{
"filename": "src/relay/sets/index.ts",
"retrieved_chunk": " }\n }\n return subscription;\n }\n /**\n * Publish an event to all relays in this set. Returns the number of relays that have received the event.\n * @param event\n * @param timeoutMs - timeout in milliseconds for each publish operation and connection operation\n * @returns A set where the event was successfully published to\n */",
"score": 0.8939036130905151
},
{
"filename": "src/relay/index.ts",
"retrieved_chunk": " });\n return sub;\n }\n /**\n * Publishes an event to the relay with an optional timeout.\n *\n * If the relay is not connected, the event will be published when the relay connects,\n * unless the timeout is reached before the relay connects.\n *\n * @param event The event to publish",
"score": 0.8919763565063477
},
{
"filename": "src/events/kinds/lists/index.ts",
"retrieved_chunk": " * Adds a new item to the list.\n * @param relay Relay to add\n * @param mark Optional mark to add to the item\n * @param encrypted Whether to encrypt the item\n */\n async addItem(\n item: NDKListItem | NDKTag,\n mark: string | undefined = undefined,\n encrypted = false\n ): Promise<void> {",
"score": 0.8891584873199463
}
] | 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/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.8383311629295349
},
{
"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.832952082157135
},
{
"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.8171159029006958
},
{
"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.8028228282928467
},
{
"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.7769379615783691
}
] | 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/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.8369530439376831
},
{
"filename": "src/relay/index.ts",
"retrieved_chunk": " this.emit(\"publish:failed\", event, err);\n reject(err);\n });\n });\n // If no timeout is specified, just return the publish promise\n if (!timeoutMs) {\n return publishPromise;\n }\n // Create a promise that rejects after timeoutMs milliseconds\n const timeoutPromise = new Promise<boolean>((_, reject) => {",
"score": 0.8279539942741394
},
{
"filename": "src/index.ts",
"retrieved_chunk": " public toJSON(): string {\n return { relayCount: this.pool.relays.size }.toString();\n }\n /**\n * Connect to relays with optional timeout.\n * If the timeout is reached, the connection will be continued to be established in the background.\n */\n public async connect(timeoutMs?: number): Promise<void> {\n this.debug(\"Connecting to relays\", { timeoutMs });\n return this.pool.connect(timeoutMs);",
"score": 0.8238455653190613
},
{
"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.8162094354629517
},
{
"filename": "src/user/index.ts",
"retrieved_chunk": " ): Promise<Set<NDKEvent> | null> {\n if (!this.ndk) throw new Error(\"NDK not set\");\n if (!this.profile) this.profile = {};\n let setMetadataEvents: Set<NDKEvent> | null = null;\n // if no options have been set and we have a cache, try to load from cache with no grouping\n // This is done in favour of simply using NDKSubscriptionCacheUsage.CACHE_FIRST since\n // we want to avoid depending on the grouping, arguably, all queries should go through this\n // type of behavior when we have a locking cache\n if (\n !opts && // if no options have been set",
"score": 0.8137080073356628
}
] | 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/user/index.ts",
"retrieved_chunk": " }\n /**\n * Returns a set of users that this user follows.\n */\n public follows = follows.bind(this);\n /**\n * Returns a set of relay list events for a user.\n * @returns {Promise<Set<NDKEvent>>} A set of NDKEvents returned for the given user.\n */\n public async relayList(): Promise<Set<NDKEvent>> {",
"score": 0.8853716850280762
},
{
"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.8383482694625854
},
{
"filename": "src/events/index.ts",
"retrieved_chunk": " \"NDKEvent must be associated with an NDK instance to publish\"\n );\n return this.ndk.publish(this, relaySet, timeoutMs);\n }\n /**\n * Generates tags for users, notes, and other events tagged in content.\n * Will also generate random \"d\" tag for parameterized replaceable events where needed.\n * @returns {ContentTag} The tags and content of the event.\n */\n protected generateTags(): ContentTag {",
"score": 0.8343420624732971
},
{
"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.8323854207992554
},
{
"filename": "src/signers/index.ts",
"retrieved_chunk": " blockUntilReady(): Promise<NDKUser>;\n /**\n * Getter for the user property.\n * @returns A promise that resolves to the NDKUser instance.\n */\n user(): Promise<NDKUser>;\n /**\n * Signs the given Nostr event.\n * @param event - The Nostr event to be signed.\n * @returns A promise that resolves to the signature of the signed event.",
"score": 0.8290003538131714
}
] | 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/index.ts",
"retrieved_chunk": " }\n /**\n * Fetch a single event.\n *\n * @param idOrFilter event id in bech32 format or filter\n * @param opts subscription options\n * @param relaySet explicit relay set to use\n */\n public async fetchEvent(\n idOrFilter: string | NDKFilter,",
"score": 0.7867954969406128
},
{
"filename": "src/user/index.ts",
"retrieved_chunk": " npub?: string;\n hexpubkey?: string;\n nip05?: string;\n relayUrls?: string[];\n}\n/**\n * Represents a pubkey.\n */\nexport default class NDKUser {\n public ndk: NDK | undefined;",
"score": 0.7730218172073364
},
{
"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.7620261907577515
},
{
"filename": "src/events/index.ts",
"retrieved_chunk": " public isParamReplaceable = isParamReplaceable.bind(this);\n /**\n * Encodes a bech32 id.\n *\n * @returns {string} - Encoded naddr, note or nevent.\n */\n public encode = encode.bind(this);\n public encrypt = encrypt.bind(this);\n public decrypt = decrypt.bind(this);\n /**",
"score": 0.761573076248169
},
{
"filename": "src/signers/nip46/backend/index.ts",
"retrieved_chunk": " backend: NDKNip46Backend,\n remotePubkey: string,\n params: string[]\n ): Promise<string | undefined>;\n}\n/**\n * This class implements a NIP-46 backend, meaning that it will hold a private key\n * of the npub that wants to be published as.\n *\n * This backend is meant to be used by an NDKNip46Signer, which is the class that",
"score": 0.7612264156341553
}
] | 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/kinds/lists/index.ts",
"retrieved_chunk": " * Adds a new item to the list.\n * @param relay Relay to add\n * @param mark Optional mark to add to the item\n * @param encrypted Whether to encrypt the item\n */\n async addItem(\n item: NDKListItem | NDKTag,\n mark: string | undefined = undefined,\n encrypted = false\n ): Promise<void> {",
"score": 0.9104223251342773
},
{
"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.8912445306777954
},
{
"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.8763138055801392
},
{
"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.8761487007141113
},
{
"filename": "src/index.ts",
"retrieved_chunk": " }\n /**\n * Fetch a single event.\n *\n * @param idOrFilter event id in bech32 format or filter\n * @param opts subscription options\n * @param relaySet explicit relay set to use\n */\n public async fetchEvent(\n idOrFilter: string | NDKFilter,",
"score": 0.8757293224334717
}
] | 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/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.9294347167015076
},
{
"filename": "src/index.ts",
"retrieved_chunk": " }\n /**\n * Fetch a single event.\n *\n * @param idOrFilter event id in bech32 format or filter\n * @param opts subscription options\n * @param relaySet explicit relay set to use\n */\n public async fetchEvent(\n idOrFilter: string | NDKFilter,",
"score": 0.9011228084564209
},
{
"filename": "src/relay/sets/index.ts",
"retrieved_chunk": " }\n }\n return subscription;\n }\n /**\n * Publish an event to all relays in this set. Returns the number of relays that have received the event.\n * @param event\n * @param timeoutMs - timeout in milliseconds for each publish operation and connection operation\n * @returns A set where the event was successfully published to\n */",
"score": 0.8939036130905151
},
{
"filename": "src/relay/index.ts",
"retrieved_chunk": " });\n return sub;\n }\n /**\n * Publishes an event to the relay with an optional timeout.\n *\n * If the relay is not connected, the event will be published when the relay connects,\n * unless the timeout is reached before the relay connects.\n *\n * @param event The event to publish",
"score": 0.8919763565063477
},
{
"filename": "src/events/kinds/lists/index.ts",
"retrieved_chunk": " * Adds a new item to the list.\n * @param relay Relay to add\n * @param mark Optional mark to add to the item\n * @param encrypted Whether to encrypt the item\n */\n async addItem(\n item: NDKListItem | NDKTag,\n mark: string | undefined = undefined,\n encrypted = false\n ): Promise<void> {",
"score": 0.8891584873199463
}
] | typescript | relay: NDKRelay | undefined,
fromCache = 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/utils/telemetry.ts",
"retrieved_chunk": " \"CLI Version\": version,\n email: credentials.email,\n origin: credentials.origin,\n os: process.platform,\n };\n // Send a POST request to Retool's telemetry endpoint.\n const res = await postRequest(`https://p.retool.com/v2/p`, {\n event: \"CLI DAU\",\n properties: payload,\n });",
"score": 0.8026876449584961
},
{
"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.7997887134552002
},
{
"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.7990671396255493
},
{
"filename": "src/commands/scaffold.ts",
"retrieved_chunk": "};\nconst insertSampleData = async function (\n tableName: string,\n credentials: Credentials\n) {\n const infoRes = await getRequest(\n `${credentials.origin}/api/grid/${credentials.gridId}/table/${tableName}/info`,\n false\n );\n const retoolDBInfo: DBInfoPayload = infoRes.data;",
"score": 0.7874932289123535
},
{
"filename": "src/utils/apps.ts",
"retrieved_chunk": ") {\n const spinner = ora(\"Creating App\").start();\n const createAppResult = await postRequest(\n `${credentials.origin}/api/pages/autogeneratePage`,\n {\n appName,\n resourceName: credentials.retoolDBUuid,\n tableName,\n columnName,\n }",
"score": 0.7874215841293335
}
] | 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/resources.ts",
"retrieved_chunk": " uuid: string;\n organizationId: number;\n resourceFolderId: number;\n};\nexport async function getResourceByName(\n resourceName: string,\n credentials: Credentials\n): Promise<ResourceByEnv> {\n const getResourceResult = await getRequest(\n `${credentials.origin}/api/resources/names/${resourceName}`",
"score": 0.8578054904937744
},
{
"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.855131208896637
},
{
"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.8511934876441956
},
{
"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.8463637828826904
},
{
"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.8406832218170166
}
] | typescript | getRequest(
`${credentials.origin}/api/grid/${credentials.gridId}/table/${tableName}/info`,
false
); |
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": " | 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.8359938859939575
},
{
"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.8063173294067383
},
{
"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.7965933084487915
},
{
"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.7908064126968384
},
{
"filename": "src/utils/resources.ts",
"retrieved_chunk": " resourceFolderId?: number;\n resourceOptions?: Record<string, any>;\n}): Promise<Resource> {\n const createResourceResult = await postRequest(\n `${credentials.origin}/api/resources/`,\n {\n type: resourceType,\n displayName,\n resourceFolderId,\n options: resourceOptions ? resourceOptions : {},",
"score": 0.7887476682662964
}
] | typescript | await postRequest(
`${credentials.origin}/api/grid/${credentials.gridId}/action`,
{ |
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.8640406131744385
},
{
"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.8380974531173706
},
{
"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.8324601650238037
},
{
"filename": "src/utils/apps.ts",
"retrieved_chunk": " }`\n );\n return page;\n }\n}\nexport async function createAppForTable(\n appName: string,\n tableName: string,\n columnName: string, //The column to use for search bar.\n credentials: Credentials",
"score": 0.8305444717407227
},
{
"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.8204528093338013
}
] | 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.8755608797073364
},
{
"filename": "src/commands/apps.ts",
"retrieved_chunk": " appName,\n tableName,\n searchColumnName || tableInfo.primaryKeyColumn,\n credentials\n );\n }\n // Handle `retool apps --create`\n else if (argv.create) {\n const appName = await collectAppName();\n await createApp(appName, credentials);",
"score": 0.8615018129348755
},
{
"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.8614464402198792
},
{
"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.8506039381027222
},
{
"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.8425037264823914
}
] | 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": " 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.8596904277801514
},
{
"filename": "src/commands/apps.ts",
"retrieved_chunk": " appName,\n tableName,\n searchColumnName || tableInfo.primaryKeyColumn,\n credentials\n );\n }\n // Handle `retool apps --create`\n else if (argv.create) {\n const appName = await collectAppName();\n await createApp(appName, credentials);",
"score": 0.8587550520896912
},
{
"filename": "src/commands/apps.ts",
"retrieved_chunk": " }\n // Handle `retool apps -d <app-name>`\n else if (argv.delete) {\n const appNames = argv.delete;\n for (const appName of appNames) {\n await deleteApp(appName, credentials, true);\n }\n }\n // No flag specified.\n else {",
"score": 0.8365020751953125
},
{
"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.834445059299469
},
{
"filename": "src/commands/apps.ts",
"retrieved_chunk": " // List all apps in root folder.\n printApps(apps);\n }\n }\n }\n // Handle `retool apps --create-from-table`\n else if (argv.t) {\n const tableName = await collectTableName();\n await verifyTableExists(tableName, credentials);\n const tableInfo = await fetchTableInfo(tableName, credentials);",
"score": 0.8340404629707336
}
] | typescript | deleteApp(`${tableName} App`, credentials, 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/subscription/index.ts",
"retrieved_chunk": " * @param {number} timeSinceFirstSeen - The time elapsed since the first time the event was seen.\n * @param {NDKSubscription} subscription - The subscription that received the event.\n *\n * @event NDKSubscription#eose - Emitted when all relays have reached the end of the event stream.\n * @param {NDKSubscription} subscription - The subscription that received EOSE.\n *\n * @event NDKSubscription#close - Emitted when the subscription is closed.\n * @param {NDKSubscription} subscription - The subscription that was closed.\n */\nexport class NDKSubscription extends EventEmitter {",
"score": 0.7669013738632202
},
{
"filename": "src/relay/sets/calculate.ts",
"retrieved_chunk": "import Event from \"../../events/index.js\";\nimport NDK from \"../../index.js\";\nimport { NDKFilter } from \"../../subscription/index.js\";\nimport { NDKRelay } from \"../index.js\";\nimport { NDKRelaySet } from \"./index.js\";\n/**\n * Creates a NDKRelaySet for the specified event.\n * TODO: account for relays where tagged pubkeys or hashtags\n * tend to write to.\n * @param ndk {NDK}",
"score": 0.7459824085235596
},
{
"filename": "src/subscription/index.ts",
"retrieved_chunk": " * @event NDKSubscription#event\n * Emitted when an event is received by the subscription.\n * @param {NDKEvent} event - The event received by the subscription.\n * @param {NDKRelay} relay - The relay that received the event.\n * @param {NDKSubscription} subscription - The subscription that received the event.\n *\n * @event NDKSubscription#event:dup\n * Emitted when a duplicate event is received by the subscription.\n * @param {NDKEvent} event - The duplicate event received by the subscription.\n * @param {NDKRelay} relay - The relay that received the event.",
"score": 0.7403980493545532
},
{
"filename": "src/relay/pool/index.ts",
"retrieved_chunk": "/**\n * Handles connections to all relays. A single pool should be used per NDK instance.\n *\n * @emit connect - Emitted when all relays in the pool are connected, or when the specified timeout has elapsed, and some relays are connected.\n * @emit notice - Emitted when a relay in the pool sends a notice.\n * @emit flapping - Emitted when a relay in the pool is flapping.\n * @emit relay:connect - Emitted when a relay in the pool connects.\n * @emit relay:disconnect - Emitted when a relay in the pool disconnects.\n */\nexport class NDKPool extends EventEmitter {",
"score": 0.7377930879592896
},
{
"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.7343151569366455
}
] | 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.8710209131240845
},
{
"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.8699040412902832
},
{
"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.8508572578430176
},
{
"filename": "src/commands/rpc.ts",
"retrieved_chunk": " },\n ]);\n console.log(\n `Excellent choice! We've created resource ${resourceName} with that name. Now we'll need an access token.\\n`\n );\n const { rpcAccessToken } = (await inquirer.prompt([\n {\n name: \"rpcAccessToken\",\n message: `Please enter an RPC access token. You can add a new one here: ${origin}/settings/api`,\n type: \"password\",",
"score": 0.832837700843811
},
{
"filename": "src/utils/credentials.ts",
"retrieved_chunk": " },\n ]);\n if (!isXsrfValid(xsrf)) {\n console.log(\"Error: XSRF token is invalid.\");\n process.exit(1);\n }\n const { accessToken } = await inquirer.prompt([\n {\n name: \"accessToken\",\n message: `What is your access token? It's also found in the cookies inspector.`,",
"score": 0.8312137722969055
}
] | 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/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.878199577331543
},
{
"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.858930766582489
},
{
"filename": "src/commands/apps.ts",
"retrieved_chunk": " appName,\n tableName,\n searchColumnName || tableInfo.primaryKeyColumn,\n credentials\n );\n }\n // Handle `retool apps --create`\n else if (argv.create) {\n const appName = await collectAppName();\n await createApp(appName, credentials);",
"score": 0.857168436050415
},
{
"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.8491576910018921
},
{
"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.8464113473892212
}
] | 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.8383841514587402
},
{
"filename": "src/utils/credentials.ts",
"retrieved_chunk": " type: \"input\",\n },\n ]);\n if (!isAccessTokenValid(accessToken)) {\n console.log(\"Error: Access token is invalid.\");\n process.exit(1);\n }\n persistCredentials({\n origin,\n xsrf,",
"score": 0.7967954277992249
},
{
"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.795020580291748
},
{
"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.7910361289978027
},
{
"filename": "src/utils/credentials.ts",
"retrieved_chunk": " },\n ]);\n if (!isXsrfValid(xsrf)) {\n console.log(\"Error: XSRF token is invalid.\");\n process.exit(1);\n }\n const { accessToken } = await inquirer.prompt([\n {\n name: \"accessToken\",\n message: `What is your access token? It's also found in the cookies inspector.`,",
"score": 0.7828046679496765
}
] | 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/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.8550366163253784
},
{
"filename": "src/commands/apps.ts",
"retrieved_chunk": " appName,\n tableName,\n searchColumnName || tableInfo.primaryKeyColumn,\n credentials\n );\n }\n // Handle `retool apps --create`\n else if (argv.create) {\n const appName = await collectAppName();\n await createApp(appName, credentials);",
"score": 0.8411049246788025
},
{
"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.8375533223152161
},
{
"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.8321126699447632
},
{
"filename": "src/utils/table.ts",
"retrieved_chunk": " const generatedRows: string[][] = [];\n if (!genDataRes || colNames.length !== genDataRes?.data?.data[0]?.length) {\n if (exitOnFailure) {\n console.log(\"Error: GPT did not generate data with correct schema.\");\n process.exit(1);\n } else {\n return;\n }\n }\n // GPT does not generate primary keys correctly.",
"score": 0.8313742280006409
}
] | typescript | 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/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.9076734185218811
},
{
"filename": "src/utils/apps.ts",
"retrieved_chunk": ") {\n if (confirmDeletion) {\n const { confirm } = await inquirer.prompt([\n {\n name: \"confirm\",\n message: `Are you sure you want to delete ${appName}?`,\n type: \"confirm\",\n },\n ]);\n if (!confirm) {",
"score": 0.9046906232833862
},
{
"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.8892223834991455
},
{
"filename": "src/commands/login.ts",
"retrieved_chunk": "const handler = async function (argv: any) {\n // Ask user if they want to overwrite existing credentials.\n if (doCredentialsExist()) {\n const { overwrite } = await inquirer.prompt([\n {\n name: \"overwrite\",\n message: \"You're already logged in. Do you want to re-authenticate?\",\n type: \"confirm\",\n },\n ]);",
"score": 0.8872034549713135
},
{
"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.8853257894515991
}
] | typescript | !isEmailValid(email)) { |
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.8406139612197876
},
{
"filename": "src/commands/apps.ts",
"retrieved_chunk": " appName,\n tableName,\n searchColumnName || tableInfo.primaryKeyColumn,\n credentials\n );\n }\n // Handle `retool apps --create`\n else if (argv.create) {\n const appName = await collectAppName();\n await createApp(appName, credentials);",
"score": 0.8306335210800171
},
{
"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.8269274830818176
},
{
"filename": "src/commands/apps.ts",
"retrieved_chunk": " // List all apps in root folder.\n printApps(apps);\n }\n }\n }\n // Handle `retool apps --create-from-table`\n else if (argv.t) {\n const tableName = await collectTableName();\n await verifyTableExists(tableName, credentials);\n const tableInfo = await fetchTableInfo(tableName, credentials);",
"score": 0.8157588839530945
},
{
"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.813768208026886
}
] | typescript | 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/commands/apps.ts",
"retrieved_chunk": " appName,\n tableName,\n searchColumnName || tableInfo.primaryKeyColumn,\n credentials\n );\n }\n // Handle `retool apps --create`\n else if (argv.create) {\n const appName = await collectAppName();\n await createApp(appName, credentials);",
"score": 0.8696401715278625
},
{
"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.8640819787979126
},
{
"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.8472036719322205
},
{
"filename": "src/commands/apps.ts",
"retrieved_chunk": " // List all apps in root folder.\n printApps(apps);\n }\n }\n }\n // Handle `retool apps --create-from-table`\n else if (argv.t) {\n const tableName = await collectTableName();\n await verifyTableExists(tableName, credentials);\n const tableInfo = await fetchTableInfo(tableName, credentials);",
"score": 0.8468127250671387
},
{
"filename": "src/commands/apps.ts",
"retrieved_chunk": " }\n // Handle `retool apps -d <app-name>`\n else if (argv.delete) {\n const appNames = argv.delete;\n for (const appName of appNames) {\n await deleteApp(appName, credentials, true);\n }\n }\n // No flag specified.\n else {",
"score": 0.8448797464370728
}
] | typescript | await deleteApp(`${tableName} App`, 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/kinds/lists/index.ts",
"retrieved_chunk": " * Adds a new item to the list.\n * @param relay Relay to add\n * @param mark Optional mark to add to the item\n * @param encrypted Whether to encrypt the item\n */\n async addItem(\n item: NDKListItem | NDKTag,\n mark: string | undefined = undefined,\n encrypted = false\n ): Promise<void> {",
"score": 0.9045524001121521
},
{
"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.8799170255661011
},
{
"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.868971049785614
},
{
"filename": "src/signers/nip46/index.ts",
"retrieved_chunk": " * @param localSigner - The signer that will be used to request events to be signed\n */\n public constructor(\n ndk: NDK,\n tokenOrRemotePubkey: string,\n localSigner?: NDKSigner\n ) {\n let remotePubkey: string;\n let token: string | undefined;\n if (tokenOrRemotePubkey.includes(\"#\")) {",
"score": 0.8657171726226807
},
{
"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.8644964098930359
}
] | typescript | ?: NDKTag[],
relays?: string[]
): Promise<string | null> { |
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/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.7962658405303955
},
{
"filename": "src/utils/telemetry.ts",
"retrieved_chunk": " \"CLI Version\": version,\n email: credentials.email,\n origin: credentials.origin,\n os: process.platform,\n };\n // Send a POST request to Retool's telemetry endpoint.\n const res = await postRequest(`https://p.retool.com/v2/p`, {\n event: \"CLI DAU\",\n properties: payload,\n });",
"score": 0.7931283712387085
},
{
"filename": "src/utils/connectionString.ts",
"retrieved_chunk": " !credentials.retoolDBUuid ||\n !credentials.hasConnectionString\n ) {\n return;\n }\n const grid = await getRequest(\n `${credentials.origin}/api/grid/retooldb/${credentials.retoolDBUuid}?env=production`,\n false\n );\n return grid.data?.gridInfo?.connectionString;",
"score": 0.7816054821014404
},
{
"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.7803818583488464
},
{
"filename": "src/commands/scaffold.ts",
"retrieved_chunk": "};\nconst insertSampleData = async function (\n tableName: string,\n credentials: Credentials\n) {\n const infoRes = await getRequest(\n `${credentials.origin}/api/grid/${credentials.gridId}/table/${tableName}/info`,\n false\n );\n const retoolDBInfo: DBInfoPayload = infoRes.data;",
"score": 0.774070143699646
}
] | typescript | await getRequest(`${origin}/api/user`); |
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/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.8112871646881104
},
{
"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.7795640826225281
},
{
"filename": "src/user/index.ts",
"retrieved_chunk": " public async publish() {\n if (!this.ndk) throw new Error(\"No NDK instance found\");\n this.ndk.assertSigner();\n const event = new NDKEvent(this.ndk, {\n kind: 0,\n content: JSON.stringify(this.profile),\n } as NostrEvent);\n await event.publish();\n }\n /**",
"score": 0.7762564420700073
},
{
"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.7681750059127808
},
{
"filename": "src/events/kinds/dvm/NDKDVMRequest.ts",
"retrieved_chunk": " this.tags.push([\"relays\", ...ndk.pool.urls()]);\n }\n }\n static from(event: NDKEvent) {\n return new NDKDVMRequest(event.ndk, event.rawEvent());\n }\n /**\n * Create a new result event for this request\n */\n public createResult(data?: NostrEvent) {",
"score": 0.7506270408630371
}
] | typescript | zapRequest as NostrEvent
); |
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.8480252027511597
},
{
"filename": "src/utils/credentials.ts",
"retrieved_chunk": " type: \"input\",\n },\n ]);\n if (!isAccessTokenValid(accessToken)) {\n console.log(\"Error: Access token is invalid.\");\n process.exit(1);\n }\n persistCredentials({\n origin,\n xsrf,",
"score": 0.8086622357368469
},
{
"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.8034573793411255
},
{
"filename": "src/utils/credentials.ts",
"retrieved_chunk": " },\n ]);\n if (!isXsrfValid(xsrf)) {\n console.log(\"Error: XSRF token is invalid.\");\n process.exit(1);\n }\n const { accessToken } = await inquirer.prompt([\n {\n name: \"accessToken\",\n message: `What is your access token? It's also found in the cookies inspector.`,",
"score": 0.8003065586090088
},
{
"filename": "src/utils/puppeteer.ts",
"retrieved_chunk": " const page = await browser.newPage();\n const domain = new URL(credentials.origin).hostname;\n const cookies = [\n {\n domain,\n name: \"accessToken\",\n value: credentials.accessToken,\n },\n {\n domain,",
"score": 0.7948215007781982
}
] | typescript | accessToken = accessTokenFromCookies(
signupResponse.headers["set-cookie"]
); |
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": " );\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.9215481281280518
},
{
"filename": "src/worker-dispatch.ts",
"retrieved_chunk": " };\n fetchTile = (\n managerId: number,\n z: number,\n x: number,\n y: number,\n timer?: Timer,\n ): CancelablePromise<FetchResponse> =>\n this.managers[managerId]?.fetchTile(z, x, y, timer) || noManager(managerId);\n fetchAndParseTile = (",
"score": 0.9075334072113037
},
{
"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.9007672071456909
},
{
"filename": "src/remote-dem-manager.ts",
"retrieved_chunk": " maxzoom,\n managerId,\n timeoutMs,\n }).value;\n }\n fetchTile = (\n z: number,\n x: number,\n y: number,\n timer?: Timer,",
"score": 0.8951085805892944
},
{
"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.8700283765792847
}
] | typescript | : CancelablePromise<HeightTile> { |
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.9419100880622864
},
{
"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.8393815755844116
},
{
"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.8040196895599365
},
{
"filename": "src/worker-dispatch.ts",
"retrieved_chunk": "import { prepareContourTile, prepareDemTile } from \"./utils\";\nconst noManager = (managerId: number): CancelablePromise<any> => ({\n cancel() {},\n value: Promise.reject(new Error(`No manager registered for ${managerId}`)),\n});\n/**\n * Receives messages from an actor in the web worker.\n */\nexport default class WorkerDispatch {\n /** There is one worker shared between all managers in the main thread using the plugin, so need to store each of their configurations. */",
"score": 0.7914389967918396
},
{
"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.7831109762191772
}
] | 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/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.8423320055007935
},
{
"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.8222247958183289
},
{
"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.8156245946884155
},
{
"filename": "src/worker-dispatch.ts",
"retrieved_chunk": " };\n fetchTile = (\n managerId: number,\n z: number,\n x: number,\n y: number,\n timer?: Timer,\n ): CancelablePromise<FetchResponse> =>\n this.managers[managerId]?.fetchTile(z, x, y, timer) || noManager(managerId);\n fetchAndParseTile = (",
"score": 0.7993987202644348
},
{
"filename": "src/dem-manager.ts",
"retrieved_chunk": "}\n/**\n * Caches, decodes, and processes raster tiles in the current thread.\n */\nexport class LocalDemManager implements DemManager {\n tileCache: AsyncCache<string, FetchResponse>;\n parsedCache: AsyncCache<string, DemTile>;\n contourCache: AsyncCache<string, ContourTile>;\n demUrlPattern: string;\n encoding: Encoding;",
"score": 0.7962733507156372
}
] | typescript | offscreenCanvasSupported()
? decodeImageModern
: isWorker()
? decodeImageOnMainThread
: decodeImageOld; |
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": "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.9140588045120239
},
{
"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.8474535346031189
},
{
"filename": "src/utils.test.ts",
"retrieved_chunk": "} from \"./utils\";\nconst fullGlobalOptions: GlobalContourTileOptions = {\n thresholds: {\n 10: 500,\n 11: [100, 1000],\n },\n contourLayer: \"contour layer\",\n elevationKey: \"elevation key\",\n extent: 123,\n buffer: 1,",
"score": 0.8034518361091614
},
{
"filename": "src/vtpbf.test.ts",
"retrieved_chunk": " ],\n type: GeomType.LINESTRING,\n properties: {\n key: 1,\n key2: true,\n },\n },\n ],\n },\n },",
"score": 0.7981034517288208
},
{
"filename": "src/e2e.test.ts",
"retrieved_chunk": " source.onTiming((timing) => timings.push(timing));\n const contourTile: ArrayBuffer = await new Promise((resolve, reject) => {\n source.contourProtocol(\n {\n url: source\n .contourProtocolUrl({\n thresholds: {\n 10: 10,\n },\n buffer: 0,",
"score": 0.7966440916061401
}
] | 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": " * 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.8878458738327026
},
{
"filename": "src/worker-dispatch.ts",
"retrieved_chunk": "import { prepareContourTile, prepareDemTile } from \"./utils\";\nconst noManager = (managerId: number): CancelablePromise<any> => ({\n cancel() {},\n value: Promise.reject(new Error(`No manager registered for ${managerId}`)),\n});\n/**\n * Receives messages from an actor in the web worker.\n */\nexport default class WorkerDispatch {\n /** There is one worker shared between all managers in the main thread using the plugin, so need to store each of their configurations. */",
"score": 0.8619922399520874
},
{
"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.8600440621376038
},
{
"filename": "src/dem-source.ts",
"retrieved_chunk": " * A remote source of DEM tiles that can be connected to maplibre.\n */\nexport class DemSource {\n sharedDemProtocolId: string;\n contourProtocolId: string;\n contourProtocolUrlBase: string;\n manager: DemManager;\n sharedDemProtocolUrl: string;\n timingCallbacks: Array<(timing: Timing) => void> = [];\n constructor({",
"score": 0.8538610339164734
},
{
"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.8525927066802979
}
] | 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/decode-image.ts",
"retrieved_chunk": " getElevations(img, encoding, canvas, canvasContext),\n );\n return {\n value,\n cancel: () => {\n canceled = true;\n img.src = \"\";\n },\n };\n}",
"score": 0.8436787724494934
},
{
"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.8357818722724915
},
{
"filename": "src/e2e.test.ts",
"retrieved_chunk": " source.onTiming((timing) => timings.push(timing));\n const contourTile: ArrayBuffer = await new Promise((resolve, reject) => {\n source.contourProtocol(\n {\n url: source\n .contourProtocolUrl({\n thresholds: {\n 10: 10,\n },\n buffer: 0,",
"score": 0.8322576880455017
},
{
"filename": "src/utils.test.ts",
"retrieved_chunk": "} from \"./utils\";\nconst fullGlobalOptions: GlobalContourTileOptions = {\n thresholds: {\n 10: 500,\n 11: [100, 1000],\n },\n contourLayer: \"contour layer\",\n elevationKey: \"elevation key\",\n extent: 123,\n buffer: 1,",
"score": 0.8286412954330444
},
{
"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.8254982233047485
}
] | typescript | y, encodeIndividualOptions(options)].join("/"); |
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/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.8613702058792114
},
{
"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.8553575873374939
},
{
"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.8524587750434875
},
{
"filename": "src/utils/workflows.ts",
"retrieved_chunk": " updatedAt: string;\n folderType: string;\n accessLevel: string;\n};\nexport async function getWorkflowsAndFolders(\n credentials: Credentials\n): Promise<{ workflows?: Array<Workflow>; folders?: Array<WorkflowFolder> }> {\n const spinner = ora(\"Fetching Workflows\").start();\n const fetchWorkflowsResponse = await getRequest(\n `${credentials.origin}/api/workflow`",
"score": 0.8476046323776245
},
{
"filename": "src/commands/scaffold.ts",
"retrieved_chunk": "};\nconst insertSampleData = async function (\n tableName: string,\n credentials: Credentials\n) {\n const infoRes = await getRequest(\n `${credentials.origin}/api/grid/${credentials.gridId}/table/${tableName}/info`,\n false\n );\n const retoolDBInfo: DBInfoPayload = infoRes.data;",
"score": 0.8253449201583862
}
] | typescript | const createResourceResult = await postRequest(
`${credentials.origin}/api/resources/`,
{ |
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.8651987314224243
},
{
"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.8505920171737671
},
{
"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.8477553725242615
},
{
"filename": "src/utils/resources.ts",
"retrieved_chunk": " uuid: string;\n organizationId: number;\n resourceFolderId: number;\n};\nexport async function getResourceByName(\n resourceName: string,\n credentials: Credentials\n): Promise<ResourceByEnv> {\n const getResourceResult = await getRequest(\n `${credentials.origin}/api/resources/names/${resourceName}`",
"score": 0.8419493436813354
},
{
"filename": "src/utils/table.ts",
"retrieved_chunk": "// Fetches all existing tables from a Retool DB.\nexport async function fetchAllTables(\n credentials: Credentials\n): Promise<Array<Table> | undefined> {\n const spinner = ora(\"Fetching tables from Retool DB\").start();\n const fetchDBsResponse = await getRequest(\n `${credentials.origin}/api/grid/retooldb/${credentials.retoolDBUuid}?env=production`\n );\n spinner.stop();\n if (fetchDBsResponse.data) {",
"score": 0.8359094858169556
}
] | typescript | const infoRes = await getRequest(
`${credentials.origin}/api/grid/${credentials.gridId}/table/${tableName}/info`,
false
); |
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.7745755910873413
},
{
"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.7614935636520386
},
{
"filename": "src/dem-manager.ts",
"retrieved_chunk": " }\n timer?.fetchTile(url);\n const mark = timer?.marker(\"fetch\");\n return withTimeout(this.timeoutMs, {\n value: fetch(url, options).then(async (response) => {\n mark?.();\n if (!response.ok) {\n throw new Error(`Bad response: ${response.status} for ${url}`);\n }\n return {",
"score": 0.7556630373001099
},
{
"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.7532428503036499
},
{
"filename": "src/cache.ts",
"retrieved_chunk": " } else {\n result.lastUsed = ++num;\n result.waiting++;\n }\n const items = this.items;\n const value = result.item.then(\n (r) => r,\n (e) => {\n items.delete(key);\n return Promise.reject(e);",
"score": 0.7471389770507812
}
] | typescript | (response as IsTransferrable)
?.transferrables; |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.