nostr-tools 2.23.9 → 2.23.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -146,12 +146,14 @@ var AbstractRelay = class {
146
146
  openSubs = /* @__PURE__ */ new Map();
147
147
  enablePing;
148
148
  enableReconnect;
149
+ idleTimeout = 0;
149
150
  idleSince = Date.now();
150
151
  ongoingOperations = 0;
151
152
  reconnectTimeoutHandle;
152
153
  pingIntervalHandle;
153
154
  reconnectAttempts = 0;
154
155
  skipReconnection = false;
156
+ idleTimeoutHandle;
155
157
  connectionPromise;
156
158
  openCountRequests = /* @__PURE__ */ new Map();
157
159
  openEventPublishes = /* @__PURE__ */ new Map();
@@ -167,6 +169,8 @@ var AbstractRelay = class {
167
169
  this._WebSocket = opts.websocketImplementation || WebSocket;
168
170
  this.enablePing = opts.enablePing;
169
171
  this.enableReconnect = opts.enableReconnect || false;
172
+ if (opts.idleTimeout)
173
+ this.idleTimeout = opts.idleTimeout;
170
174
  }
171
175
  static async connect(url, opts) {
172
176
  const relay = new AbstractRelay(url, opts);
@@ -190,6 +194,22 @@ var AbstractRelay = class {
190
194
  get connected() {
191
195
  return this._connected;
192
196
  }
197
+ clearIdleTimeout() {
198
+ if (this.idleTimeoutHandle) {
199
+ clearTimeout(this.idleTimeoutHandle);
200
+ this.idleTimeoutHandle = void 0;
201
+ }
202
+ }
203
+ scheduleIdleClose() {
204
+ this.clearIdleTimeout();
205
+ if (this.idleTimeout > 0) {
206
+ this.idleTimeoutHandle = setTimeout(() => {
207
+ if (this.ongoingOperations === 0 && this.idleSince) {
208
+ this.close();
209
+ }
210
+ }, this.idleTimeout);
211
+ }
212
+ }
193
213
  async reconnect() {
194
214
  const backoff = this.resubscribeBackoff[Math.min(this.reconnectAttempts, this.resubscribeBackoff.length - 1)];
195
215
  this.reconnectAttempts++;
@@ -208,6 +228,7 @@ var AbstractRelay = class {
208
228
  this._connected = false;
209
229
  this.connectionPromise = void 0;
210
230
  this.idleSince = void 0;
231
+ this.clearIdleTimeout();
211
232
  if (this.enableReconnect && !this.skipReconnection) {
212
233
  this.reconnect();
213
234
  } else {
@@ -365,6 +386,7 @@ var AbstractRelay = class {
365
386
  }
366
387
  async publish(event) {
367
388
  this.idleSince = void 0;
389
+ this.clearIdleTimeout();
368
390
  this.ongoingOperations++;
369
391
  const ret = new Promise((resolve, reject) => {
370
392
  const timeout = setTimeout(() => {
@@ -386,8 +408,10 @@ var AbstractRelay = class {
386
408
  }
387
409
  }
388
410
  this.ongoingOperations--;
389
- if (this.ongoingOperations === 0)
411
+ if (this.ongoingOperations === 0) {
390
412
  this.idleSince = Date.now();
413
+ this.scheduleIdleClose();
414
+ }
391
415
  return ret;
392
416
  }
393
417
  async count(filters, params) {
@@ -413,6 +437,7 @@ var AbstractRelay = class {
413
437
  subscribe(filters, params) {
414
438
  if (params.label !== "<forced-ping>") {
415
439
  this.idleSince = void 0;
440
+ this.clearIdleTimeout();
416
441
  this.ongoingOperations++;
417
442
  }
418
443
  const sub = this.prepareSubscription(filters, params);
@@ -442,6 +467,7 @@ var AbstractRelay = class {
442
467
  this.closeAllSubscriptions("relay connection closed by us");
443
468
  this._connected = false;
444
469
  this.idleSince = void 0;
470
+ this.clearIdleTimeout();
445
471
  this.onclose?.();
446
472
  if (this.ws?.readyState === this._WebSocket.OPEN) {
447
473
  this.ws?.close();
@@ -619,8 +645,10 @@ var Subscription = class {
619
645
  }
620
646
  this.relay.openSubs.delete(this.id);
621
647
  this.relay.ongoingOperations--;
622
- if (this.relay.ongoingOperations === 0)
648
+ if (this.relay.ongoingOperations === 0) {
623
649
  this.relay.idleSince = Date.now();
650
+ this.relay.scheduleIdleClose();
651
+ }
624
652
  this.onclose?.(reason);
625
653
  }
626
654
  };
@@ -696,6 +724,7 @@ var AbstractSimplePool = class {
696
724
  verifyEvent;
697
725
  enablePing;
698
726
  enableReconnect;
727
+ idleTimeout = 2e4;
699
728
  automaticallyAuth;
700
729
  trustedRelayURLs = /* @__PURE__ */ new Set();
701
730
  onRelayConnectionFailure;
@@ -708,6 +737,8 @@ var AbstractSimplePool = class {
708
737
  this._WebSocket = opts.websocketImplementation;
709
738
  this.enablePing = opts.enablePing;
710
739
  this.enableReconnect = opts.enableReconnect || false;
740
+ if (opts.idleTimeout)
741
+ this.idleTimeout = opts.idleTimeout;
711
742
  this.automaticallyAuth = opts.automaticallyAuth;
712
743
  this.onRelayConnectionFailure = opts.onRelayConnectionFailure;
713
744
  this.onRelayConnectionSuccess = opts.onRelayConnectionSuccess;
@@ -722,7 +753,8 @@ var AbstractSimplePool = class {
722
753
  verifyEvent: this.trustedRelayURLs.has(url) ? alwaysTrue : this.verifyEvent,
723
754
  websocketImplementation: this._WebSocket,
724
755
  enablePing: this.enablePing,
725
- enableReconnect: this.enableReconnect
756
+ enableReconnect: this.enableReconnect,
757
+ idleTimeout: this.idleTimeout
726
758
  });
727
759
  relay.onclose = () => {
728
760
  this.relays.delete(url);
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../abstract-pool.ts", "../../core.ts", "../../utils.ts", "../../kinds.ts", "../../filter.ts", "../../fakejson.ts", "../../nip42.ts", "../../abstract-relay.ts", "../../helpers.ts", "../../nip45.ts"],
4
- "sourcesContent": ["/* global WebSocket */\n\nimport {\n AbstractRelay as AbstractRelay,\n SubscriptionParams,\n Subscription,\n type AbstractRelayConstructorOptions,\n} from './abstract-relay.ts'\nimport { normalizeURL } from './utils.ts'\n\nimport type { Event, EventTemplate, Nostr, VerifiedEvent } from './core.ts'\nimport { type Filter } from './filter.ts'\nimport { alwaysTrue } from './helpers.ts'\nimport { getCountManyFilter, hllDecode, hllEncode, mergeHll, type CountManyDirective } from './nip45.ts'\nimport { Relay } from './relay.ts'\n\nexport type SubCloser = { close: (reason?: string) => void }\n\nexport type AbstractPoolConstructorOptions = AbstractRelayConstructorOptions & {\n // automaticallyAuth takes a relay URL and should return null in case that relay shouldn't be authenticated against\n // or a function to sign the AUTH event template otherwise (that function may still throw in case of failure)\n automaticallyAuth?: (relayURL: string) => null | ((event: EventTemplate) => Promise<VerifiedEvent>)\n // onRelayConnectionFailure is called with the URL of a relay that failed the initial connection\n onRelayConnectionFailure?: (url: string) => void\n // onRelayConnectionSuccess is called with the URL of a relay that succeeds the initial connection\n onRelayConnectionSuccess?: (url: string) => void\n // allowConnectingToRelay takes a relay URL and the operation being performed\n // return false to skip connecting to that relay\n allowConnectingToRelay?: (url: string, operation: ['read', Filter[]] | ['write', Event]) => boolean\n // maxWaitForConnection takes a number in milliseconds that will be given to ensureRelay such that we\n // don't get stuck forever when attempting to connect to a relay, it is 3000 (3 seconds) by default\n maxWaitForConnection: number\n}\n\nexport type SubscribeManyParams = Omit<SubscriptionParams, 'onclose'> & {\n maxWait?: number\n abort?: AbortSignal\n onclose?: (reasons: string[]) => void\n onauth?: (event: EventTemplate) => Promise<VerifiedEvent>\n id?: string\n label?: string\n}\n\nexport class AbstractSimplePool {\n protected relays: Map<string, AbstractRelay> = new Map()\n public seenOn: Map<string, Set<AbstractRelay>> = new Map()\n public trackRelays: boolean = false\n\n public verifyEvent: Nostr['verifyEvent']\n public enablePing: boolean | undefined\n public enableReconnect: boolean\n public automaticallyAuth?: (relayURL: string) => null | ((event: EventTemplate) => Promise<VerifiedEvent>)\n public trustedRelayURLs: Set<string> = new Set()\n public onRelayConnectionFailure?: (url: string) => void\n public onRelayConnectionSuccess?: (url: string) => void\n public allowConnectingToRelay?: (url: string, operation: ['read', Filter[]] | ['write', Event]) => boolean\n public maxWaitForConnection: number\n\n private _WebSocket?: typeof WebSocket\n\n constructor(opts: AbstractPoolConstructorOptions) {\n this.verifyEvent = opts.verifyEvent\n this._WebSocket = opts.websocketImplementation\n this.enablePing = opts.enablePing\n this.enableReconnect = opts.enableReconnect || false\n this.automaticallyAuth = opts.automaticallyAuth\n this.onRelayConnectionFailure = opts.onRelayConnectionFailure\n this.onRelayConnectionSuccess = opts.onRelayConnectionSuccess\n this.allowConnectingToRelay = opts.allowConnectingToRelay\n this.maxWaitForConnection = opts.maxWaitForConnection || 3000\n }\n\n async ensureRelay(\n url: string,\n params?: {\n connectionTimeout?: number\n abort?: AbortSignal\n },\n ): Promise<AbstractRelay> {\n url = normalizeURL(url)\n\n let relay = this.relays.get(url)\n if (!relay) {\n relay = new AbstractRelay(url, {\n verifyEvent: this.trustedRelayURLs.has(url) ? alwaysTrue : this.verifyEvent,\n websocketImplementation: this._WebSocket,\n enablePing: this.enablePing,\n enableReconnect: this.enableReconnect,\n })\n relay.onclose = () => {\n this.relays.delete(url)\n }\n this.relays.set(url, relay)\n }\n\n if (this.automaticallyAuth) {\n const authSignerFn = this.automaticallyAuth(url)\n if (authSignerFn) {\n relay.onauth = authSignerFn\n }\n }\n\n try {\n await relay.connect({\n timeout: params?.connectionTimeout,\n abort: params?.abort,\n })\n } catch (err) {\n this.relays.delete(url)\n throw err\n }\n\n return relay\n }\n\n close(relays: string[]) {\n relays.map(normalizeURL).forEach(url => {\n this.relays.get(url)?.close()\n this.relays.delete(url)\n })\n }\n\n subscribe(relays: string[], filter: Filter, params: SubscribeManyParams): SubCloser {\n const request: { url: string; filter: Filter }[] = []\n const uniqUrls: string[] = []\n for (let i = 0; i < relays.length; i++) {\n const url = normalizeURL(relays[i])\n if (!request.find(r => r.url === url)) {\n if (uniqUrls.indexOf(url) === -1) {\n uniqUrls.push(url)\n request.push({ url, filter: filter })\n }\n }\n }\n\n return this.subscribeMap(request, params)\n }\n\n subscribeMany(relays: string[], filter: Filter, params: SubscribeManyParams): SubCloser {\n return this.subscribe(relays, filter, params)\n }\n\n subscribeMap(requests: { url: string; filter: Filter }[], params: SubscribeManyParams): SubCloser {\n const grouped = new Map<string, Filter[]>()\n for (const req of requests) {\n const { url, filter } = req\n if (!grouped.has(url)) grouped.set(url, [])\n grouped.get(url)!.push(filter)\n }\n const groupedRequests = Array.from(grouped.entries()).map(([url, filters]) => ({ url, filters }))\n\n if (this.trackRelays) {\n params.receivedEvent = (relay: AbstractRelay, id: string) => {\n let set = this.seenOn.get(id)\n if (!set) {\n set = new Set()\n this.seenOn.set(id, set)\n }\n set.add(relay)\n }\n }\n\n const _knownIds = new Set<string>()\n const subs: Subscription[] = []\n\n // batch all EOSEs into a single\n const eosesReceived: boolean[] = []\n let handleEose = (i: number) => {\n if (eosesReceived[i]) return // do not act twice for the same relay\n eosesReceived[i] = true\n if (eosesReceived.filter(a => a).length === groupedRequests.length) {\n params.oneose?.()\n handleEose = () => {}\n }\n }\n // batch all closes into a single\n const closesReceived: string[] = []\n let handleClose = (i: number, reason: string) => {\n if (closesReceived[i]) return // do not act twice for the same relay\n handleEose(i)\n closesReceived[i] = reason\n if (closesReceived.filter(a => a).length === groupedRequests.length) {\n params.onclose?.(closesReceived)\n handleClose = () => {}\n }\n }\n\n const localAlreadyHaveEventHandler = (id: string) => {\n if (params.alreadyHaveEvent?.(id)) {\n return true\n }\n const have = _knownIds.has(id)\n _knownIds.add(id)\n return have\n }\n\n // open a subscription in all given relays\n const allOpened = Promise.all(\n groupedRequests.map(async ({ url, filters }, i) => {\n if (this.allowConnectingToRelay?.(url, ['read', filters]) === false) {\n handleClose(i, 'connection skipped by allowConnectingToRelay')\n return\n }\n\n let relay: AbstractRelay\n try {\n relay = await this.ensureRelay(url, {\n connectionTimeout:\n this.maxWaitForConnection < (params.maxWait || 0)\n ? Math.max(params.maxWait! * 0.8, params.maxWait! - 1000)\n : this.maxWaitForConnection,\n abort: params.abort,\n })\n } catch (err) {\n this.onRelayConnectionFailure?.(url)\n handleClose(i, (err as any)?.message || String(err))\n return\n }\n\n this.onRelayConnectionSuccess?.(url)\n\n let subscription = relay.subscribe(filters, {\n ...params,\n oneose: () => handleEose(i),\n onclose: reason => {\n if (reason.startsWith('auth-required: ') && params.onauth) {\n relay\n .auth(params.onauth)\n .then(() => {\n relay.subscribe(filters, {\n ...params,\n oneose: () => handleEose(i),\n onclose: reason => {\n handleClose(i, reason) // the second time we won't try to auth anymore\n },\n alreadyHaveEvent: localAlreadyHaveEventHandler,\n eoseTimeout: params.maxWait,\n abort: params.abort,\n })\n })\n .catch(err => {\n handleClose(i, `auth was required and attempted, but failed with: ${err}`)\n })\n } else {\n handleClose(i, reason)\n }\n },\n alreadyHaveEvent: localAlreadyHaveEventHandler,\n eoseTimeout: params.maxWait,\n abort: params.abort,\n })\n\n subs.push(subscription)\n }),\n )\n\n return {\n async close(reason?: string) {\n await allOpened\n subs.forEach(sub => {\n sub.close(reason)\n })\n },\n }\n }\n\n subscribeEose(\n relays: string[],\n filter: Filter,\n params: Pick<SubscribeManyParams, 'label' | 'id' | 'onevent' | 'oninvalidevent' | 'onclose' | 'maxWait' | 'onauth'>,\n ): SubCloser {\n let subcloser: SubCloser\n subcloser = this.subscribe(relays, filter, {\n ...params,\n oneose() {\n const reason = 'closed automatically on eose'\n if (subcloser) subcloser.close(reason)\n else params.onclose?.(relays.map(_ => reason))\n },\n })\n return subcloser\n }\n\n subscribeManyEose(\n relays: string[],\n filter: Filter,\n params: Pick<SubscribeManyParams, 'label' | 'id' | 'onevent' | 'oninvalidevent' | 'onclose' | 'maxWait' | 'onauth'>,\n ): SubCloser {\n return this.subscribeEose(relays, filter, params)\n }\n\n async querySync(\n relays: string[],\n filter: Filter,\n params?: Pick<SubscribeManyParams, 'label' | 'id' | 'maxWait'>,\n ): Promise<Event[]> {\n return new Promise(async resolve => {\n const events: Event[] = []\n this.subscribeEose(relays, filter, {\n ...params,\n onevent(event: Event) {\n events.push(event)\n },\n onclose(_: string[]) {\n resolve(events)\n },\n })\n })\n }\n\n async get(\n relays: string[],\n filter: Filter,\n params?: Pick<SubscribeManyParams, 'label' | 'id' | 'maxWait'>,\n ): Promise<Event | null> {\n filter.limit = 1\n const events = await this.querySync(relays, filter, params)\n events.sort((a, b) => b.created_at - a.created_at)\n return events[0] || null\n }\n\n async countMany(\n relays: string[],\n target: string,\n directive: CountManyDirective,\n params?: { id?: string | null; maxWait?: number; abort?: AbortSignal },\n ): Promise<{ count: number; hll?: string }> {\n const filter = getCountManyFilter(target, directive)\n const urls: string[] = []\n\n for (let i = 0; i < relays.length; i++) {\n const url = normalizeURL(relays[i])\n if (urls.indexOf(url) === -1) urls.push(url)\n }\n\n const responses = await Promise.all(\n urls.map(async url => {\n if (this.allowConnectingToRelay?.(url, ['read', [filter]]) === false) return null\n\n let relay: AbstractRelay\n try {\n relay = await this.ensureRelay(url, {\n connectionTimeout:\n this.maxWaitForConnection < (params?.maxWait || 0)\n ? Math.max(params!.maxWait! * 0.8, params!.maxWait! - 1000)\n : this.maxWaitForConnection,\n abort: params?.abort,\n })\n } catch (err) {\n this.onRelayConnectionFailure?.(url)\n return null\n }\n\n this.onRelayConnectionSuccess?.(url)\n\n return relay.countWithHLL([filter], { id: params?.id }).catch(() => null)\n }),\n )\n\n let count = 0\n let hll: Uint8Array | undefined\n\n for (const response of responses) {\n if (!response) continue\n\n if (response.count > count) count = response.count\n\n if (!response.hll || response.hll.length !== 512) continue\n\n const registers = hllDecode(response.hll)\n if (!registers) continue\n\n hll = mergeHll(hll || new Uint8Array(0), registers)\n }\n\n return hll ? { count, hll: hllEncode(hll) } : { count }\n }\n\n publish(\n relays: string[],\n event: Event,\n params?: {\n onauth?: (evt: EventTemplate) => Promise<VerifiedEvent>\n maxWait?: number\n abort?: AbortSignal\n },\n ): Promise<string>[] {\n return relays.map(normalizeURL).map(async (url, i, arr) => {\n if (arr.indexOf(url) !== i) {\n // duplicate\n return Promise.reject('duplicate url')\n }\n\n if (this.allowConnectingToRelay?.(url, ['write', event]) === false) {\n return Promise.reject('connection skipped by allowConnectingToRelay')\n }\n\n let r: Relay\n try {\n r = await this.ensureRelay(url, {\n connectionTimeout:\n this.maxWaitForConnection < (params?.maxWait || 0)\n ? Math.max(params!.maxWait! * 0.8, params!.maxWait! - 1000)\n : this.maxWaitForConnection,\n abort: params?.abort,\n })\n } catch (err) {\n this.onRelayConnectionFailure?.(url)\n return String('connection failure: ' + String(err))\n }\n\n return r\n .publish(event)\n .catch(async err => {\n if (err instanceof Error && err.message.startsWith('auth-required: ') && params?.onauth) {\n await r.auth(params.onauth)\n return r.publish(event) // retry\n }\n throw err\n })\n .then(reason => {\n if (this.trackRelays) {\n let set = this.seenOn.get(event.id)\n if (!set) {\n set = new Set()\n this.seenOn.set(event.id, set)\n }\n set.add(r)\n }\n return reason\n })\n })\n }\n\n listConnectionStatus(): Map<string, boolean> {\n const map = new Map<string, boolean>()\n this.relays.forEach((relay, url) => map.set(url, relay.connected))\n\n return map\n }\n\n destroy(): void {\n this.relays.forEach(conn => conn.close())\n this.relays = new Map()\n }\n\n pruneIdleRelays(idleThresholdMs: number = 10000): string[] {\n const prunedUrls: string[] = []\n\n // check each relay's idle status and prune if over threshold\n for (const [url, relay] of this.relays) {\n if (relay.idleSince && Date.now() - relay.idleSince >= idleThresholdMs) {\n this.relays.delete(url)\n prunedUrls.push(url)\n relay.close()\n }\n }\n\n return prunedUrls\n }\n}\n", "export interface Nostr {\n generateSecretKey(): Uint8Array\n getPublicKey(secretKey: Uint8Array): string\n finalizeEvent(event: EventTemplate, secretKey: Uint8Array): VerifiedEvent\n verifyEvent(event: Event): event is VerifiedEvent\n}\n\n/** Designates a verified event signature. */\nexport const verifiedSymbol = Symbol('verified')\n\nexport type NostrEvent = {\n kind: number\n tags: string[][]\n content: string\n created_at: number\n pubkey: string\n id: string\n sig: string\n [verifiedSymbol]?: boolean\n}\n\nexport type Event = NostrEvent\nexport type EventTemplate = Pick<Event, 'kind' | 'tags' | 'content' | 'created_at'>\nexport type UnsignedEvent = Pick<Event, 'kind' | 'tags' | 'content' | 'created_at' | 'pubkey'>\n\n/** An event whose signature has been verified. */\nexport interface VerifiedEvent extends Event {\n [verifiedSymbol]: true\n}\n\nconst isRecord = (obj: unknown): obj is Record<string, unknown> => obj instanceof Object\n\nexport function validateEvent<T>(event: T): event is T & UnsignedEvent {\n if (!isRecord(event)) return false\n if (typeof event.kind !== 'number') return false\n if (typeof event.content !== 'string') return false\n if (typeof event.created_at !== 'number') return false\n if (typeof event.pubkey !== 'string') return false\n if (!event.pubkey.match(/^[a-f0-9]{64}$/)) return false\n\n if (!Array.isArray(event.tags)) return false\n for (let i = 0; i < event.tags.length; i++) {\n let tag = event.tags[i]\n if (!Array.isArray(tag)) return false\n for (let j = 0; j < tag.length; j++) {\n if (typeof tag[j] !== 'string') return false\n }\n }\n\n return true\n}\n\n/**\n * Sort events in reverse-chronological order by the `created_at` timestamp,\n * and then by the event `id` (lexicographically) in case of ties.\n * This mutates the array.\n */\nexport function sortEvents(events: Event[]): Event[] {\n return events.sort((a: NostrEvent, b: NostrEvent): number => {\n if (a.created_at !== b.created_at) {\n return b.created_at - a.created_at\n }\n return a.id.localeCompare(b.id)\n })\n}\n", "import type { NostrEvent } from './core.ts'\n\nexport const utf8Decoder: TextDecoder = new TextDecoder('utf-8')\nexport const utf8Encoder: TextEncoder = new TextEncoder()\n\nexport { bytesToHex, hexToBytes } from '@noble/hashes/utils.js'\n\nexport function normalizeURL(url: string): string {\n try {\n if (url.indexOf('://') === -1) url = 'wss://' + url\n let p = new URL(url)\n if (p.protocol === 'http:') p.protocol = 'ws:'\n else if (p.protocol === 'https:') p.protocol = 'wss:'\n p.pathname = p.pathname.replace(/\\/+/g, '/')\n if (p.pathname.endsWith('/')) p.pathname = p.pathname.slice(0, -1)\n if ((p.port === '80' && p.protocol === 'ws:') || (p.port === '443' && p.protocol === 'wss:')) p.port = ''\n p.searchParams.sort()\n p.hash = ''\n return p.toString()\n } catch (e) {\n throw new Error(`Invalid URL: ${url}`)\n }\n}\n\nexport function insertEventIntoDescendingList(sortedArray: NostrEvent[], event: NostrEvent): NostrEvent[] {\n const [idx, found] = binarySearch(sortedArray, b => {\n if (event.id === b.id) return 0\n if (event.created_at === b.created_at) return -1\n return b.created_at - event.created_at\n })\n if (!found) {\n sortedArray.splice(idx, 0, event)\n }\n return sortedArray\n}\n\nexport function insertEventIntoAscendingList(sortedArray: NostrEvent[], event: NostrEvent): NostrEvent[] {\n const [idx, found] = binarySearch(sortedArray, b => {\n if (event.id === b.id) return 0\n if (event.created_at === b.created_at) return -1\n return event.created_at - b.created_at\n })\n if (!found) {\n sortedArray.splice(idx, 0, event)\n }\n return sortedArray\n}\n\nexport function binarySearch<T>(arr: T[], compare: (b: T) => number): [number, boolean] {\n let start = 0\n let end = arr.length - 1\n\n while (start <= end) {\n const mid = Math.floor((start + end) / 2)\n const cmp = compare(arr[mid])\n\n if (cmp === 0) {\n return [mid, true]\n }\n\n if (cmp < 0) {\n end = mid - 1\n } else {\n start = mid + 1\n }\n }\n\n return [start, false]\n}\n\nexport function mergeReverseSortedLists(list1: NostrEvent[], list2: NostrEvent[]): NostrEvent[] {\n const result: NostrEvent[] = new Array(list1.length + list2.length)\n result.length = 0\n let i1 = 0\n let i2 = 0\n let sameTimestampIds: string[] = []\n\n while (i1 < list1.length && i2 < list2.length) {\n let next: NostrEvent\n if (list1[i1]?.created_at > list2[i2]?.created_at) {\n next = list1[i1]\n i1++\n } else {\n next = list2[i2]\n i2++\n }\n\n if (result.length > 0 && result[result.length - 1].created_at === next.created_at) {\n if (sameTimestampIds.includes(next.id)) continue\n } else {\n sameTimestampIds.length = 0\n }\n\n result.push(next)\n sameTimestampIds.push(next.id)\n }\n\n while (i1 < list1.length) {\n const next = list1[i1]\n i1++\n\n if (result.length > 0 && result[result.length - 1].created_at === next.created_at) {\n if (sameTimestampIds.includes(next.id)) continue\n } else {\n sameTimestampIds.length = 0\n }\n result.push(next)\n sameTimestampIds.push(next.id)\n }\n\n while (i2 < list2.length) {\n const next = list2[i2]\n i2++\n\n if (result.length > 0 && result[result.length - 1].created_at === next.created_at) {\n if (sameTimestampIds.includes(next.id)) continue\n } else {\n sameTimestampIds.length = 0\n }\n result.push(next)\n sameTimestampIds.push(next.id)\n }\n\n return result\n}\n", "import { NostrEvent, validateEvent } from './pure.ts'\n\n/** Events are **regular**, which means they're all expected to be stored by relays. */\nexport function isRegularKind(kind: number): boolean {\n return kind < 10000 && kind !== 0 && kind !== 3\n}\n\n/** Events are **replaceable**, which means that, for each combination of `pubkey` and `kind`, only the latest event is expected to (SHOULD) be stored by relays, older versions are expected to be discarded. */\nexport function isReplaceableKind(kind: number): boolean {\n return kind === 0 || kind === 3 || (10000 <= kind && kind < 20000)\n}\n\n/** Events are **ephemeral**, which means they are not expected to be stored by relays. */\nexport function isEphemeralKind(kind: number): boolean {\n return 20000 <= kind && kind < 30000\n}\n\n/** Events are **addressable**, which means that, for each combination of `pubkey`, `kind` and the `d` tag, only the latest event is expected to be stored by relays, older versions are expected to be discarded. */\nexport function isAddressableKind(kind: number): boolean {\n return 30000 <= kind && kind < 40000\n}\n\n/** Classification of the event kind. */\nexport type KindClassification = 'regular' | 'replaceable' | 'ephemeral' | 'parameterized' | 'unknown'\n\n/** Determine the classification of this kind of event if known, or `unknown`. */\nexport function classifyKind(kind: number): KindClassification {\n if (isRegularKind(kind)) return 'regular'\n if (isReplaceableKind(kind)) return 'replaceable'\n if (isEphemeralKind(kind)) return 'ephemeral'\n if (isAddressableKind(kind)) return 'parameterized'\n return 'unknown'\n}\n\nexport function isKind<T extends number>(event: unknown, kind: T | Array<T>): event is NostrEvent & { kind: T } {\n const kindAsArray: number[] = kind instanceof Array ? kind : [kind]\n return (validateEvent(event) && kindAsArray.includes(event.kind)) || false\n}\n\nexport const Metadata = 0\nexport type Metadata = typeof Metadata\nexport const ShortTextNote = 1\nexport type ShortTextNote = typeof ShortTextNote\nexport const RecommendRelay = 2\nexport type RecommendRelay = typeof RecommendRelay\nexport const Contacts = 3\nexport type Contacts = typeof Contacts\nexport const EncryptedDirectMessage = 4\nexport type EncryptedDirectMessage = typeof EncryptedDirectMessage\nexport const EventDeletion = 5\nexport type EventDeletion = typeof EventDeletion\nexport const Repost = 6\nexport type Repost = typeof Repost\nexport const Reaction = 7\nexport type Reaction = typeof Reaction\nexport const BadgeAward = 8\nexport type BadgeAward = typeof BadgeAward\nexport const ChatMessage = 9\nexport type ChatMessage = typeof ChatMessage\nexport const SimpleGroupThreadedReply = 10\nexport type SimpleGroupThreadedReply = typeof SimpleGroupThreadedReply\nexport const ForumThread = 11\nexport type ForumThread = typeof ForumThread\nexport const SimpleGroupReply = 12\nexport type SimpleGroupReply = typeof SimpleGroupReply\nexport const Seal = 13\nexport type Seal = typeof Seal\nexport const PrivateDirectMessage = 14\nexport type PrivateDirectMessage = typeof PrivateDirectMessage\nexport const FileMessage = 15\nexport type FileMessage = typeof FileMessage\nexport const GenericRepost = 16\nexport type GenericRepost = typeof GenericRepost\nexport const ReactionToWebsite = 17\nexport type ReactionToWebsite = typeof ReactionToWebsite\nexport const Photo = 20\nexport type Photo = typeof Photo\nexport const NormalVideo = 21\nexport type NormalVideo = typeof NormalVideo\nexport const ShortVideo = 22\nexport type ShortVideo = typeof ShortVideo\nexport const PublicMessage = 24\nexport type PublicMessage = typeof PublicMessage\nexport const ChannelCreation = 40\nexport type ChannelCreation = typeof ChannelCreation\nexport const ChannelMetadata = 41\nexport type ChannelMetadata = typeof ChannelMetadata\nexport const ChannelMessage = 42\nexport type ChannelMessage = typeof ChannelMessage\nexport const ChannelHideMessage = 43\nexport type ChannelHideMessage = typeof ChannelHideMessage\nexport const ChannelMuteUser = 44\nexport type ChannelMuteUser = typeof ChannelMuteUser\nexport const PodcastEpisode = 54\nexport type PodcastEpisode = typeof PodcastEpisode\nexport const Chess = 64\nexport type Chess = typeof Chess\nexport const MergeRequests = 818\nexport type MergeRequests = typeof MergeRequests\nexport const PollResponse = 1018\nexport type PollResponse = typeof PollResponse\nexport const Bid = 1021\nexport type Bid = typeof Bid\nexport const BidConfirmation = 1022\nexport type BidConfirmation = typeof BidConfirmation\nexport const OpenTimestamps = 1040\nexport type OpenTimestamps = typeof OpenTimestamps\nexport const GiftWrap = 1059\nexport type GiftWrap = typeof GiftWrap\nexport const FileMetadata = 1063\nexport type FileMetadata = typeof FileMetadata\nexport const Poll = 1068\nexport type Poll = typeof Poll\nexport const Comment = 1111\nexport type Comment = typeof Comment\nexport const Voice = 1222\nexport type Voice = typeof Voice\nexport const Scroll = 1227\nexport type Scroll = typeof Scroll\nexport const VoiceComment = 1244\nexport type VoiceComment = typeof VoiceComment\nexport const LiveChatMessage = 1311\nexport type LiveChatMessage = typeof LiveChatMessage\nexport const CodeSnippet = 1337\nexport type CodeSnippet = typeof CodeSnippet\nexport const Patch = 1617\nexport type Patch = typeof Patch\nexport const GitPullRequest = 1618\nexport type GitPullRequest = typeof GitPullRequest\nexport const GitPullRequestUpdate = 1619\nexport type GitPullRequestUpdate = typeof GitPullRequestUpdate\nexport const Issue = 1621\nexport type Issue = typeof Issue\nexport const Reply = 1622\nexport type Reply = typeof Reply\nexport const StatusOpen = 1630\nexport type StatusOpen = typeof StatusOpen\nexport const StatusApplied = 1631\nexport type StatusApplied = typeof StatusApplied\nexport const StatusClosed = 1632\nexport type StatusClosed = typeof StatusClosed\nexport const StatusDraft = 1633\nexport type StatusDraft = typeof StatusDraft\nexport const ProblemTracker = 1971\nexport type ProblemTracker = typeof ProblemTracker\nexport const Report = 1984\nexport type Report = typeof Report\nexport const Reporting = 1984\nexport type Reporting = typeof Reporting\nexport const Label = 1985\nexport type Label = typeof Label\nexport const RelayReviews = 1986\nexport type RelayReviews = typeof RelayReviews\nexport const AIEmbeddings = 1987\nexport type AIEmbeddings = typeof AIEmbeddings\nexport const Torrent = 2003\nexport type Torrent = typeof Torrent\nexport const TorrentComment = 2004\nexport type TorrentComment = typeof TorrentComment\nexport const CoinjoinPool = 2022\nexport type CoinjoinPool = typeof CoinjoinPool\nexport const DecoupledKeyClientAnnouncement = 4454\nexport type DecoupledKeyClientAnnouncement = typeof DecoupledKeyClientAnnouncement\nexport const DecoupledEncryptionKeyDistribution = 4455\nexport type DecoupledEncryptionKeyDistribution = typeof DecoupledEncryptionKeyDistribution\nexport const CommunityPostApproval = 4550\nexport type CommunityPostApproval = typeof CommunityPostApproval\nexport const JobRequest = 5999\nexport type JobRequest = typeof JobRequest\nexport const JobResult = 6999\nexport type JobResult = typeof JobResult\nexport const JobFeedback = 7000\nexport type JobFeedback = typeof JobFeedback\nexport const ReservedCashuWalletTokens = 7374\nexport type ReservedCashuWalletTokens = typeof ReservedCashuWalletTokens\nexport const CashuWalletTokens = 7375\nexport type CashuWalletTokens = typeof CashuWalletTokens\nexport const CashuWalletHistory = 7376\nexport type CashuWalletHistory = typeof CashuWalletHistory\nexport const GeocacheLog = 7516\nexport type GeocacheLog = typeof GeocacheLog\nexport const GeocacheProofOfFind = 7517\nexport type GeocacheProofOfFind = typeof GeocacheProofOfFind\nexport const SimpleGroupPutUser = 9000\nexport type SimpleGroupPutUser = typeof SimpleGroupPutUser\nexport const SimpleGroupRemoveUser = 9001\nexport type SimpleGroupRemoveUser = typeof SimpleGroupRemoveUser\nexport const SimpleGroupEditMetadata = 9002\nexport type SimpleGroupEditMetadata = typeof SimpleGroupEditMetadata\nexport const SimpleGroupDeleteEvent = 9005\nexport type SimpleGroupDeleteEvent = typeof SimpleGroupDeleteEvent\nexport const SimpleGroupCreateGroup = 9007\nexport type SimpleGroupCreateGroup = typeof SimpleGroupCreateGroup\nexport const SimpleGroupDeleteGroup = 9008\nexport type SimpleGroupDeleteGroup = typeof SimpleGroupDeleteGroup\nexport const SimpleGroupCreateInvite = 9009\nexport type SimpleGroupCreateInvite = typeof SimpleGroupCreateInvite\nexport const SimpleGroupJoinRequest = 9021\nexport type SimpleGroupJoinRequest = typeof SimpleGroupJoinRequest\nexport const SimpleGroupLeaveRequest = 9022\nexport type SimpleGroupLeaveRequest = typeof SimpleGroupLeaveRequest\nexport const ZapGoal = 9041\nexport type ZapGoal = typeof ZapGoal\nexport const NutZap = 9321\nexport type NutZap = typeof NutZap\nexport const TidalLogin = 9467\nexport type TidalLogin = typeof TidalLogin\nexport const ZapRequest = 9734\nexport type ZapRequest = typeof ZapRequest\nexport const Zap = 9735\nexport type Zap = typeof Zap\nexport const Highlights = 9802\nexport type Highlights = typeof Highlights\nexport const Mutelist = 10000\nexport type Mutelist = typeof Mutelist\nexport const Pinlist = 10001\nexport type Pinlist = typeof Pinlist\nexport const RelayList = 10002\nexport type RelayList = typeof RelayList\nexport const BookmarkList = 10003\nexport type BookmarkList = typeof BookmarkList\nexport const CommunitiesList = 10004\nexport type CommunitiesList = typeof CommunitiesList\nexport const PublicChatsList = 10005\nexport type PublicChatsList = typeof PublicChatsList\nexport const BlockedRelaysList = 10006\nexport type BlockedRelaysList = typeof BlockedRelaysList\nexport const SearchRelaysList = 10007\nexport type SearchRelaysList = typeof SearchRelaysList\nexport const SimpleGroupList = 10009\nexport type SimpleGroupList = typeof SimpleGroupList\nexport const FavoriteRelays = 10012\nexport type FavoriteRelays = typeof FavoriteRelays\nexport const PrivateEventRelayList = 10013\nexport type PrivateEventRelayList = typeof PrivateEventRelayList\nexport const InterestsList = 10015\nexport type InterestsList = typeof InterestsList\nexport const NutZapInfo = 10019\nexport type NutZapInfo = typeof NutZapInfo\nexport const MediaFollows = 10020\nexport type MediaFollows = typeof MediaFollows\nexport const UserEmojiList = 10030\nexport type UserEmojiList = typeof UserEmojiList\nexport const DecoupledKeyAnnouncement = 10044\nexport type DecoupledKeyAnnouncement = typeof DecoupledKeyAnnouncement\nexport const DirectMessageRelaysList = 10050\nexport type DirectMessageRelaysList = typeof DirectMessageRelaysList\nexport const FavoritePodcasts = 10054\nexport type FavoritePodcasts = typeof FavoritePodcasts\nexport const BlossomServerList = 10063\nexport type BlossomServerList = typeof BlossomServerList\nexport const FileServerPreference = 10096\nexport type FileServerPreference = typeof FileServerPreference\nexport const GoodWikiAuthorList = 10101\nexport type GoodWikiAuthorList = typeof GoodWikiAuthorList\nexport const GoodWikiRelayList = 10102\nexport type GoodWikiRelayList = typeof GoodWikiRelayList\nexport const PodcastMetadata = 10154\nexport type PodcastMetadata = typeof PodcastMetadata\nexport const AuthoredPodcasts = 10164\nexport type AuthoredPodcasts = typeof AuthoredPodcasts\nexport const RelayMonitorAnnouncement = 10166\nexport type RelayMonitorAnnouncement = typeof RelayMonitorAnnouncement\nexport const RoomPresence = 10312\nexport type RoomPresence = typeof RoomPresence\nexport const UserGraspList = 10317\nexport type UserGraspList = typeof UserGraspList\nexport const ProxyAnnouncement = 10377\nexport type ProxyAnnouncement = typeof ProxyAnnouncement\nexport const TransportMethodAnnouncement = 11111\nexport type TransportMethodAnnouncement = typeof TransportMethodAnnouncement\nexport const NWCWalletInfo = 13194\nexport type NWCWalletInfo = typeof NWCWalletInfo\nexport const NsiteRoot = 15128\nexport type NsiteRoot = typeof NsiteRoot\nexport const CashuWalletEvent = 17375\nexport type CashuWalletEvent = typeof CashuWalletEvent\nexport const LightningPubRPC = 21000\nexport type LightningPubRPC = typeof LightningPubRPC\nexport const ClientAuth = 22242\nexport type ClientAuth = typeof ClientAuth\nexport const NWCWalletRequest = 23194\nexport type NWCWalletRequest = typeof NWCWalletRequest\nexport const NWCWalletResponse = 23195\nexport type NWCWalletResponse = typeof NWCWalletResponse\nexport const NostrConnect = 24133\nexport type NostrConnect = typeof NostrConnect\nexport const BlobsAuth = 24242\nexport type BlobsAuth = typeof BlobsAuth\nexport const HTTPAuth = 27235\nexport type HTTPAuth = typeof HTTPAuth\nexport const Followsets = 30000\nexport type Followsets = typeof Followsets\nexport const Genericlists = 30001\nexport type Genericlists = typeof Genericlists\nexport const Relaysets = 30002\nexport type Relaysets = typeof Relaysets\nexport const Bookmarksets = 30003\nexport type Bookmarksets = typeof Bookmarksets\nexport const Curationsets = 30004\nexport type Curationsets = typeof Curationsets\nexport const CuratedVideoSets = 30005\nexport type CuratedVideoSets = typeof CuratedVideoSets\nexport const MuteSets = 30007\nexport type MuteSets = typeof MuteSets\nexport const ProfileBadges = 30008\nexport type ProfileBadges = typeof ProfileBadges\nexport const BadgeDefinition = 30009\nexport type BadgeDefinition = typeof BadgeDefinition\nexport const Interestsets = 30015\nexport type Interestsets = typeof Interestsets\nexport const CreateOrUpdateStall = 30017\nexport type CreateOrUpdateStall = typeof CreateOrUpdateStall\nexport const CreateOrUpdateProduct = 30018\nexport type CreateOrUpdateProduct = typeof CreateOrUpdateProduct\nexport const MarketplaceUI = 30019\nexport type MarketplaceUI = typeof MarketplaceUI\nexport const ProductSoldAsAuction = 30020\nexport type ProductSoldAsAuction = typeof ProductSoldAsAuction\nexport const LongFormArticle = 30023\nexport type LongFormArticle = typeof LongFormArticle\nexport const DraftLong = 30024\nexport type DraftLong = typeof DraftLong\nexport const Emojisets = 30030\nexport type Emojisets = typeof Emojisets\nexport const ModularArticleHeader = 30040\nexport type ModularArticleHeader = typeof ModularArticleHeader\nexport const ModularArticleContent = 30041\nexport type ModularArticleContent = typeof ModularArticleContent\nexport const ReleaseArtifactSets = 30063\nexport type ReleaseArtifactSets = typeof ReleaseArtifactSets\nexport const Application = 30078\nexport type Application = typeof Application\nexport const RelayDiscovery = 30166\nexport type RelayDiscovery = typeof RelayDiscovery\nexport const AppCurationSet = 30267\nexport type AppCurationSet = typeof AppCurationSet\nexport const LiveEvent = 30311\nexport type LiveEvent = typeof LiveEvent\nexport const InteractiveRoom = 30312\nexport type InteractiveRoom = typeof InteractiveRoom\nexport const ConferenceEvent = 30313\nexport type ConferenceEvent = typeof ConferenceEvent\nexport const UserStatuses = 30315\nexport type UserStatuses = typeof UserStatuses\nexport const SlideSet = 30388\nexport type SlideSet = typeof SlideSet\nexport const ClassifiedListing = 30402\nexport type ClassifiedListing = typeof ClassifiedListing\nexport const DraftClassifiedListing = 30403\nexport type DraftClassifiedListing = typeof DraftClassifiedListing\nexport const RepositoryAnnouncement = 30617\nexport type RepositoryAnnouncement = typeof RepositoryAnnouncement\nexport const RepositoryState = 30618\nexport type RepositoryState = typeof RepositoryState\nexport const WikiArticle = 30818\nexport type WikiArticle = typeof WikiArticle\nexport const Redirects = 30819\nexport type Redirects = typeof Redirects\nexport const DraftEvent = 31234\nexport type DraftEvent = typeof DraftEvent\nexport const LinkSet = 31388\nexport type LinkSet = typeof LinkSet\nexport const Feed = 31890\nexport type Feed = typeof Feed\nexport const Date = 31922\nexport type Date = typeof Date\nexport const Time = 31923\nexport type Time = typeof Time\nexport const Calendar = 31924\nexport type Calendar = typeof Calendar\nexport const CalendarEventRSVP = 31925\nexport type CalendarEventRSVP = typeof CalendarEventRSVP\nexport const RelayReview = 31987\nexport type RelayReview = typeof RelayReview\nexport const Handlerrecommendation = 31989\nexport type Handlerrecommendation = typeof Handlerrecommendation\nexport const Handlerinformation = 31990\nexport type Handlerinformation = typeof Handlerinformation\nexport const SoftwareApplication = 32267\nexport type SoftwareApplication = typeof SoftwareApplication\nexport const LegacyNsiteFile = 34128\nexport type LegacyNsiteFile = typeof LegacyNsiteFile\nexport const VideoViewEvent = 34237\nexport type VideoViewEvent = typeof VideoViewEvent\nexport const CommunityDefinition = 34550\nexport type CommunityDefinition = typeof CommunityDefinition\nexport const NsiteNamed = 35128\nexport type NsiteNamed = typeof NsiteNamed\nexport const GeocacheListing = 37515\nexport type GeocacheListing = typeof GeocacheListing\nexport const GeocacheLogEntry = 37516\nexport type GeocacheLogEntry = typeof GeocacheLogEntry\nexport const CashuMintAnnouncement = 38172\nexport type CashuMintAnnouncement = typeof CashuMintAnnouncement\nexport const FedimintAnnouncement = 38173\nexport type FedimintAnnouncement = typeof FedimintAnnouncement\nexport const PeerToPeerOrderEvents = 38383\nexport type PeerToPeerOrderEvents = typeof PeerToPeerOrderEvents\nexport const GroupMetadata = 39000\nexport type GroupMetadata = typeof GroupMetadata\nexport const SimpleGroupAdmins = 39001\nexport type SimpleGroupAdmins = typeof SimpleGroupAdmins\nexport const SimpleGroupMembers = 39002\nexport type SimpleGroupMembers = typeof SimpleGroupMembers\nexport const SimpleGroupRoles = 39003\nexport type SimpleGroupRoles = typeof SimpleGroupRoles\nexport const SimpleGroupLiveKitParticipants = 39004\nexport type SimpleGroupLiveKitParticipants = typeof SimpleGroupLiveKitParticipants\nexport const StarterPacks = 39089\nexport type StarterPacks = typeof StarterPacks\nexport const MediaStarterPacks = 39092\nexport type MediaStarterPacks = typeof MediaStarterPacks\nexport const WebBookmarks = 39701\nexport type WebBookmarks = typeof WebBookmarks\n", "import { Event } from './core.ts'\nimport { isAddressableKind, isReplaceableKind } from './kinds.ts'\n\nexport type Filter = {\n ids?: string[]\n kinds?: number[]\n authors?: string[]\n since?: number\n until?: number\n limit?: number\n search?: string\n [key: `#${string}`]: string[] | undefined\n}\n\nexport function matchFilter(filter: Filter, event: Event): boolean {\n if (filter.ids && filter.ids.indexOf(event.id) === -1) {\n return false\n }\n if (filter.kinds && filter.kinds.indexOf(event.kind) === -1) {\n return false\n }\n if (filter.authors && filter.authors.indexOf(event.pubkey) === -1) {\n return false\n }\n\n for (let f in filter) {\n if (f[0] === '#') {\n let tagName = f.slice(1)\n let values = filter[`#${tagName}`]\n if (values && !event.tags.find(([t, v]) => t === f.slice(1) && values!.indexOf(v) !== -1)) return false\n }\n }\n\n if (filter.since && event.created_at < filter.since) return false\n if (filter.until && event.created_at > filter.until) return false\n\n return true\n}\n\nexport function matchFilters(filters: Filter[], event: Event): boolean {\n for (let i = 0; i < filters.length; i++) {\n if (matchFilter(filters[i], event)) {\n return true\n }\n }\n return false\n}\n\nexport function mergeFilters(...filters: Filter[]): Filter {\n let result: Filter = {}\n for (let i = 0; i < filters.length; i++) {\n let filter = filters[i]\n Object.entries(filter).forEach(([property, values]) => {\n if (property === 'kinds' || property === 'ids' || property === 'authors' || property[0] === '#') {\n // @ts-ignore\n result[property] = result[property] || []\n // @ts-ignore\n for (let v = 0; v < values.length; v++) {\n // @ts-ignore\n let value = values[v]\n // @ts-ignore\n if (!result[property].includes(value)) result[property].push(value)\n }\n }\n })\n\n if (filter.limit && (!result.limit || filter.limit > result.limit)) result.limit = filter.limit\n if (filter.until && (!result.until || filter.until > result.until)) result.until = filter.until\n if (filter.since && (!result.since || filter.since < result.since)) result.since = filter.since\n }\n\n return result\n}\n\n/**\n * Calculate the intrinsic limit of a filter.\n * This function returns a positive integer, or `Infinity` if there is no intrinsic limit.\n */\nexport function getFilterLimit(filter: Filter): number {\n if (filter.ids && !filter.ids.length) return 0\n if (filter.kinds && !filter.kinds.length) return 0\n if (filter.authors && !filter.authors.length) return 0\n\n for (const [key, value] of Object.entries(filter)) {\n if (key[0] === '#' && Array.isArray(value) && !value.length) return 0\n }\n\n return Math.min(\n // The `limit` property creates an artificial limit.\n Math.max(0, filter.limit ?? Infinity),\n\n // There can only be one event per `id`.\n filter.ids?.length ?? Infinity,\n\n // Replaceable events are limited by the number of authors and kinds.\n filter.authors?.length && filter.kinds?.every(kind => isReplaceableKind(kind))\n ? filter.authors.length * filter.kinds.length\n : Infinity,\n\n // Parameterized replaceable events are limited by the number of authors, kinds, and \"d\" tags.\n filter.authors?.length && filter.kinds?.every(kind => isAddressableKind(kind)) && filter['#d']?.length\n ? filter.authors.length * filter.kinds.length * filter['#d'].length\n : Infinity,\n )\n}\n", "export function getHex64(json: string, field: string): string {\n let len = field.length + 3\n let idx = json.indexOf(`\"${field}\":`) + len\n let s = json.slice(idx).indexOf(`\"`) + idx + 1\n return json.slice(s, s + 64)\n}\n\nexport function getInt(json: string, field: string): number {\n let len = field.length\n let idx = json.indexOf(`\"${field}\":`) + len + 3\n let sliced = json.slice(idx)\n let end = Math.min(sliced.indexOf(','), sliced.indexOf('}'))\n return parseInt(sliced.slice(0, end), 10)\n}\n\nexport function getSubscriptionId(json: string): string | null {\n let idx = json.slice(0, 22).indexOf(`\"EVENT\"`)\n if (idx === -1) return null\n\n let pstart = json.slice(idx + 7 + 1).indexOf(`\"`)\n if (pstart === -1) return null\n let start = idx + 7 + 1 + pstart\n\n let pend = json.slice(start + 1, 80).indexOf(`\"`)\n if (pend === -1) return null\n let end = start + 1 + pend\n\n return json.slice(start + 1, end)\n}\n\nexport function matchEventId(json: string, id: string): boolean {\n return id === getHex64(json, 'id')\n}\n\nexport function matchEventPubkey(json: string, pubkey: string): boolean {\n return pubkey === getHex64(json, 'pubkey')\n}\n\nexport function matchEventKind(json: string, kind: number): boolean {\n return kind === getInt(json, 'kind')\n}\n", "import { EventTemplate } from './core.ts'\nimport { ClientAuth } from './kinds.ts'\n\n/**\n * creates an EventTemplate for an AUTH event to be signed.\n */\nexport function makeAuthEvent(relayURL: string, challenge: string): EventTemplate {\n return {\n kind: ClientAuth,\n created_at: Math.floor(Date.now() / 1000),\n tags: [\n ['relay', relayURL],\n ['challenge', challenge],\n ],\n content: '',\n }\n}\n", "/* global WebSocket */\n\nimport type { Event, EventTemplate, VerifiedEvent, Nostr, NostrEvent } from './core.ts'\nimport { matchFilters, type Filter } from './filter.ts'\nimport { getHex64, getSubscriptionId } from './fakejson.ts'\nimport { normalizeURL } from './utils.ts'\nimport { makeAuthEvent } from './nip42.ts'\n\ntype RelayWebSocket = WebSocket & {\n ping?(): void\n on?(event: 'pong', listener: () => void): any\n}\n\nexport type AbstractRelayConstructorOptions = {\n verifyEvent: Nostr['verifyEvent']\n websocketImplementation?: typeof WebSocket\n enablePing?: boolean\n enableReconnect?: boolean\n}\n\nexport class SendingOnClosedConnection extends Error {\n constructor(message: string, relay: string) {\n super(`Tried to send message '${message} on a closed connection to ${relay}.`)\n this.name = 'SendingOnClosedConnection'\n }\n}\n\nexport class AbstractRelay {\n public readonly url: string\n private _connected: boolean = false\n\n public onclose: (() => void) | null = null\n public onnotice: (msg: string) => void = msg => console.debug(`NOTICE from ${this.url}: ${msg}`)\n public onauth: undefined | ((evt: EventTemplate) => Promise<VerifiedEvent>)\n\n public baseEoseTimeout: number = 4400\n public publishTimeout: number = 4400\n public pingFrequency: number = 29000\n public pingTimeout: number = 20000\n public resubscribeBackoff: number[] = [10000, 10000, 10000, 20000, 20000, 30000, 60000]\n public openSubs: Map<string, Subscription> = new Map()\n public enablePing: boolean | undefined\n public enableReconnect: boolean\n public idleSince: number | undefined = Date.now() // when undefined that means it isn't idle\n public ongoingOperations: number = 0 // used to compute idleness\n private reconnectTimeoutHandle: ReturnType<typeof setTimeout> | undefined\n private pingIntervalHandle: ReturnType<typeof setInterval> | undefined\n private reconnectAttempts: number = 0\n private skipReconnection: boolean = false\n\n private connectionPromise: Promise<void> | undefined\n private openCountRequests = new Map<string, CountResolver>()\n private openEventPublishes = new Map<string, EventPublishResolver>()\n private ws: RelayWebSocket | undefined\n private challenge: string | undefined\n private authPromise: Promise<string> | undefined\n private serial: number = 0\n private verifyEvent: Nostr['verifyEvent']\n\n private _WebSocket: typeof WebSocket\n\n constructor(url: string, opts: AbstractRelayConstructorOptions) {\n this.url = normalizeURL(url)\n this.verifyEvent = opts.verifyEvent\n this._WebSocket = opts.websocketImplementation || WebSocket\n this.enablePing = opts.enablePing\n this.enableReconnect = opts.enableReconnect || false\n }\n\n static async connect(\n url: string,\n opts: AbstractRelayConstructorOptions & Parameters<AbstractRelay['connect']>[0],\n ): Promise<AbstractRelay> {\n const relay = new AbstractRelay(url, opts)\n await relay.connect(opts)\n return relay\n }\n\n private closeAllSubscriptions(reason: string) {\n for (let [_, sub] of this.openSubs) {\n sub.close(reason)\n }\n this.openSubs.clear()\n\n for (let [_, ep] of this.openEventPublishes) {\n ep.reject(new Error(reason))\n }\n this.openEventPublishes.clear()\n\n for (let [_, cr] of this.openCountRequests) {\n cr.reject(new Error(reason))\n }\n this.openCountRequests.clear()\n }\n\n public get connected(): boolean {\n return this._connected\n }\n\n private async reconnect(): Promise<void> {\n const backoff = this.resubscribeBackoff[Math.min(this.reconnectAttempts, this.resubscribeBackoff.length - 1)]\n this.reconnectAttempts++\n\n this.reconnectTimeoutHandle = setTimeout(async () => {\n try {\n await this.connect()\n } catch (err) {\n // this will be called again through onclose/onerror\n }\n }, backoff)\n }\n\n private handleHardClose(reason: string) {\n if (this.pingIntervalHandle) {\n clearInterval(this.pingIntervalHandle)\n this.pingIntervalHandle = undefined\n }\n\n this._connected = false\n this.connectionPromise = undefined\n this.idleSince = undefined\n\n if (this.enableReconnect && !this.skipReconnection) {\n this.reconnect()\n } else {\n this.onclose?.()\n this.closeAllSubscriptions(reason)\n }\n }\n\n public async connect(opts?: { timeout?: number; abort?: AbortSignal }): Promise<void> {\n let connectionTimeoutHandle: ReturnType<typeof setTimeout> | undefined\n\n if (this.connectionPromise) return this.connectionPromise\n\n this.challenge = undefined\n this.authPromise = undefined\n this.skipReconnection = false\n this.connectionPromise = new Promise((resolve, reject) => {\n if (opts?.timeout) {\n connectionTimeoutHandle = setTimeout(() => {\n reject('connection timed out')\n this.connectionPromise = undefined\n // Only give up on the initial connect; a slow reconnect\n // should fall through to the next backoff slot.\n if (this.reconnectAttempts === 0) {\n this.skipReconnection = true\n }\n this.onclose?.()\n this.handleHardClose('relay connection timed out')\n }, opts.timeout)\n }\n\n if (opts?.abort) {\n opts.abort.onabort = reject\n }\n\n try {\n this.ws = new this._WebSocket(this.url)\n } catch (err) {\n clearTimeout(connectionTimeoutHandle)\n reject(err)\n return\n }\n\n this.ws.onopen = () => {\n if (this.reconnectTimeoutHandle) {\n clearTimeout(this.reconnectTimeoutHandle)\n this.reconnectTimeoutHandle = undefined\n }\n clearTimeout(connectionTimeoutHandle)\n this._connected = true\n\n const isReconnection = this.reconnectAttempts > 0\n this.reconnectAttempts = 0\n\n // resubscribe to all open subscriptions\n for (const sub of this.openSubs.values()) {\n sub.eosed = false\n if (isReconnection) {\n for (let f = 0; f < sub.filters.length; f++) {\n if (sub.lastEmitted) {\n sub.filters[f].since = sub.lastEmitted + 1\n }\n }\n }\n sub.fire()\n }\n\n if (this.enablePing) {\n this.pingIntervalHandle = setInterval(() => this.pingpong(), this.pingFrequency)\n }\n resolve()\n }\n\n this.ws.onerror = () => {\n clearTimeout(connectionTimeoutHandle)\n reject('connection failed')\n this.connectionPromise = undefined\n // Only give up on the initial connect. A failed reconnect\n // attempt must fall through so the next backoff slot fires;\n // otherwise one failed retry tears down every subscription.\n if (this.reconnectAttempts === 0) {\n this.skipReconnection = true\n }\n this.onclose?.()\n this.handleHardClose('relay connection failed')\n }\n\n this.ws.onclose = ev => {\n clearTimeout(connectionTimeoutHandle)\n reject((ev as any).message || 'websocket closed')\n this.handleHardClose('relay connection closed')\n }\n\n this.ws.onmessage = this._onmessage.bind(this)\n })\n\n return this.connectionPromise\n }\n\n private waitForPingPong() {\n return new Promise(resolve => {\n // listen for pong\n ;(this.ws as any).once('pong', () => resolve(true))\n // send a ping\n this.ws!.ping!()\n })\n }\n\n private waitForDummyReq() {\n return new Promise((resolve, reject) => {\n if (!this.connectionPromise) return reject(new Error(`no connection to ${this.url}, can't ping`))\n\n // make a dummy request with expected empty eose reply\n // [\"REQ\", \"_\", {\"ids\":[\"aaaa...aaaa\"], \"limit\": 0}]\n try {\n const sub = this.subscribe(\n [{ ids: ['aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa'], limit: 0 }],\n {\n label: '<forced-ping>',\n oneose: () => {\n resolve(true)\n sub.close()\n },\n onclose() {\n // if we get a CLOSED it's because the relay is alive\n resolve(true)\n },\n eoseTimeout: this.pingTimeout + 1000,\n },\n )\n } catch (err) {\n reject(err)\n }\n })\n }\n\n // nodejs requires this magic here to ensure connections are closed when internet goes off and stuff\n // in browsers it's done automatically. see https://github.com/nbd-wtf/nostr-tools/issues/491\n private async pingpong() {\n // if the websocket is connected\n if (this.ws?.readyState === 1) {\n // wait for either a ping-pong reply or a timeout\n const result = await Promise.any([\n // browsers don't have ping so use a dummy req\n this.ws && this.ws.ping && (this.ws as any).once ? this.waitForPingPong() : this.waitForDummyReq(),\n new Promise(res => setTimeout(() => res(false), this.pingTimeout)),\n ])\n\n if (!result) {\n // pingpong closing socket\n if (this.ws?.readyState === this._WebSocket.OPEN) {\n this.ws?.close()\n }\n }\n }\n }\n\n public async send(message: string) {\n if (!this.connectionPromise) throw new SendingOnClosedConnection(message, this.url)\n\n this.connectionPromise.then(() => {\n this.ws?.send(message)\n })\n }\n\n public async auth(signAuthEvent: (evt: EventTemplate) => Promise<VerifiedEvent>): Promise<string> {\n const challenge = this.challenge\n if (!challenge) throw new Error(\"can't perform auth, no challenge was received\")\n if (this.authPromise) return this.authPromise\n\n this.authPromise = new Promise<string>(async (resolve, reject) => {\n try {\n let evt = await signAuthEvent(makeAuthEvent(this.url, challenge))\n let timeout = setTimeout(() => {\n let ep = this.openEventPublishes.get(evt.id) as EventPublishResolver\n if (ep) {\n ep.reject(new Error('auth timed out'))\n this.openEventPublishes.delete(evt.id)\n }\n }, this.publishTimeout)\n this.openEventPublishes.set(evt.id, { resolve, reject, timeout })\n this.send('[\"AUTH\",' + JSON.stringify(evt) + ']')\n } catch (err) {\n console.warn('subscribe auth function failed:', err)\n }\n })\n return this.authPromise\n }\n\n public async publish(event: Event): Promise<string> {\n this.idleSince = undefined\n this.ongoingOperations++\n\n const ret = new Promise<string>((resolve, reject) => {\n const timeout = setTimeout(() => {\n const ep = this.openEventPublishes.get(event.id) as EventPublishResolver\n if (ep) {\n ep.reject(new Error('publish timed out'))\n this.openEventPublishes.delete(event.id)\n }\n }, this.publishTimeout)\n this.openEventPublishes.set(event.id, { resolve, reject, timeout })\n })\n try {\n await this.send('[\"EVENT\",' + JSON.stringify(event) + ']')\n } catch (err) {\n const ep = this.openEventPublishes.get(event.id)\n if (ep) {\n ep.reject(err as Error)\n this.openEventPublishes.delete(event.id)\n }\n }\n\n // compute idleness state\n this.ongoingOperations--\n if (this.ongoingOperations === 0) this.idleSince = Date.now()\n\n return ret\n }\n\n public async count(filters: Filter[], params: { id?: string | null }): Promise<number> {\n return (await this.countWithHLL(filters, params)).count\n }\n\n public async countWithHLL(\n filters: Filter[],\n params: { id?: string | null },\n ): Promise<{ count: number; hll?: string }> {\n this.serial++\n const id = params?.id || 'count:' + this.serial\n const ret = new Promise<{ count: number; hll?: string }>((resolve, reject) => {\n this.openCountRequests.set(id, { resolve, reject })\n })\n try {\n await this.send('[\"COUNT\",\"' + id + '\",' + JSON.stringify(filters).substring(1))\n } catch (err) {\n const cr = this.openCountRequests.get(id)\n if (cr) {\n cr.reject(err as Error)\n this.openCountRequests.delete(id)\n }\n }\n return ret\n }\n\n public subscribe(\n filters: Filter[],\n params: Partial<SubscriptionParams> & { label?: string; id?: string },\n ): Subscription {\n if (params.label !== '<forced-ping>') {\n this.idleSince = undefined\n this.ongoingOperations++\n }\n\n const sub = this.prepareSubscription(filters, params)\n sub.fire()\n\n if (params.abort) {\n params.abort.onabort = () => sub.close(String(params.abort!.reason || '<aborted>'))\n }\n\n return sub\n }\n\n public prepareSubscription(\n filters: Filter[],\n params: Partial<SubscriptionParams> & { label?: string; id?: string },\n ): Subscription {\n this.serial++\n const id = params.id || (params.label ? params.label + ':' : 'sub:') + this.serial\n const sub = new Subscription(this, id, filters, params)\n this.openSubs.set(id, sub)\n return sub\n }\n\n public close() {\n this.skipReconnection = true\n if (this.reconnectTimeoutHandle) {\n clearTimeout(this.reconnectTimeoutHandle)\n this.reconnectTimeoutHandle = undefined\n }\n if (this.pingIntervalHandle) {\n clearInterval(this.pingIntervalHandle)\n this.pingIntervalHandle = undefined\n }\n this.closeAllSubscriptions('relay connection closed by us')\n this._connected = false\n this.idleSince = undefined\n this.onclose?.()\n if (this.ws?.readyState === this._WebSocket.OPEN) {\n this.ws?.close()\n }\n }\n\n // this is the function assigned to this.ws.onmessage\n // it's exposed for testing and debugging purposes\n public _onmessage(ev: MessageEvent<any>): void {\n const json = ev.data\n if (!json) {\n return\n }\n\n // shortcut EVENT sub\n const subid = getSubscriptionId(json)\n if (subid) {\n const so = this.openSubs.get(subid as string)\n if (!so) {\n // this is an EVENT message, but for a subscription we don't have, so just stop here\n return\n }\n\n // this will be called only when this message is a EVENT message for a subscription we have\n // we do this before parsing the JSON to not have to do that for duplicate events\n // since JSON parsing is slow\n const id = getHex64(json, 'id')\n const alreadyHave = so.alreadyHaveEvent?.(id)\n\n // notify any interested client that the relay has this event\n // (do this after alreadyHaveEvent() because the client may rely on this to answer that)\n so.receivedEvent?.(this, id)\n\n if (alreadyHave) {\n // if we had already seen this event we can just stop here\n return\n }\n }\n\n try {\n let data = JSON.parse(json)\n // we won't do any checks against the data since all failures (i.e. invalid messages from relays)\n // will naturally be caught by the encompassing try..catch block\n\n switch (data[0]) {\n case 'EVENT': {\n const so = this.openSubs.get(data[1] as string) as Subscription\n const event = data[2] as NostrEvent\n if (this.verifyEvent(event) && matchFilters(so.filters, event)) {\n so.onevent(event)\n } else {\n so.oninvalidevent?.(event)\n }\n if (!so.lastEmitted || so.lastEmitted < event.created_at) so.lastEmitted = event.created_at\n return\n }\n case 'COUNT': {\n const id: string = data[1]\n const payload = data[2] as { count: number; hll?: string }\n const cr = this.openCountRequests.get(id) as CountResolver\n if (cr) {\n cr.resolve(payload)\n this.openCountRequests.delete(id)\n }\n return\n }\n case 'EOSE': {\n const so = this.openSubs.get(data[1] as string)\n if (!so) return\n so.receivedEose()\n return\n }\n case 'OK': {\n const id: string = data[1]\n const ok: boolean = data[2]\n const reason: string = data[3]\n const ep = this.openEventPublishes.get(id) as EventPublishResolver\n if (ep) {\n clearTimeout(ep.timeout)\n if (ok) ep.resolve(reason)\n else ep.reject(new Error(reason))\n this.openEventPublishes.delete(id)\n }\n return\n }\n case 'CLOSED': {\n const id: string = data[1]\n const so = this.openSubs.get(id)\n if (!so) {\n const cr = this.openCountRequests.get(id) as CountResolver\n if (cr) {\n cr.reject(new Error(data[2] as string))\n this.openCountRequests.delete(id)\n }\n return\n }\n so.closed = true\n so.close(data[2] as string)\n return\n }\n case 'NOTICE': {\n this.onnotice(data[1] as string)\n return\n }\n case 'AUTH': {\n this.challenge = data[1] as string\n if (this.onauth) {\n this.auth(this.onauth).catch(err => {\n // If the connection closed before auth could be sent, just ignore it.\n // This is a race condition when relays close connections quickly\n // (e.g., WoT-enforced relays that reject unknown pubkeys).\n if (!(err instanceof SendingOnClosedConnection)) {\n throw err // re-throw other errors\n }\n })\n }\n return\n }\n default: {\n const so = this.openSubs.get(data[1])\n so?.oncustom?.(data)\n return\n }\n }\n } catch (err) {\n try {\n const [_, __, event] = JSON.parse(json)\n console.warn(`[nostr] relay ${this.url} error processing message:`, err, event)\n } catch (_) {\n console.warn(`[nostr] relay ${this.url} error processing message:`, err)\n }\n return\n }\n }\n}\n\nexport class Subscription {\n public readonly relay: AbstractRelay\n public readonly id: string\n\n public lastEmitted: number | undefined\n public closed: boolean = false\n public eosed: boolean = false\n public filters: Filter[]\n public alreadyHaveEvent: ((id: string) => boolean) | undefined\n public receivedEvent: ((relay: AbstractRelay, id: string) => void) | undefined\n\n public onevent: (evt: Event) => void\n public oninvalidevent: ((evt: unknown) => void) | undefined\n public oneose: (() => void) | undefined\n public onclose: ((reason: string) => void) | undefined\n\n // will get any messages that have this subscription id as their second item and are not default standard\n public oncustom: ((msg: string[]) => void) | undefined\n\n public eoseTimeout: number\n private eoseTimeoutHandle: ReturnType<typeof setTimeout> | undefined\n\n constructor(relay: AbstractRelay, id: string, filters: Filter[], params: SubscriptionParams) {\n if (filters.length === 0) throw new Error(\"subscription can't be created with zero filters\")\n\n this.relay = relay\n this.filters = filters\n this.id = id\n this.alreadyHaveEvent = params.alreadyHaveEvent\n this.receivedEvent = params.receivedEvent\n this.eoseTimeout = params.eoseTimeout || relay.baseEoseTimeout\n\n this.oneose = params.oneose\n this.onclose = params.onclose\n this.oninvalidevent = params.oninvalidevent\n this.onevent =\n params.onevent ||\n (event => {\n console.warn(\n `onevent() callback not defined for subscription '${this.id}' in relay ${this.relay.url}. event received:`,\n event,\n )\n })\n }\n\n public fire() {\n this.relay.send('[\"REQ\",\"' + this.id + '\",' + JSON.stringify(this.filters).substring(1))\n\n // only now we start counting the eoseTimeout\n this.eoseTimeoutHandle = setTimeout(this.receivedEose.bind(this), this.eoseTimeout)\n }\n\n public receivedEose() {\n if (this.eosed) return\n clearTimeout(this.eoseTimeoutHandle)\n this.eosed = true\n this.oneose?.()\n }\n\n public close(reason: string = 'closed by caller') {\n if (!this.closed && this.relay.connected) {\n // if the connection was closed by the user calling .close() we will send a CLOSE message\n // otherwise this._open will be already set to false so we will skip this\n try {\n this.relay.send('[\"CLOSE\",' + JSON.stringify(this.id) + ']')\n } catch (err) {\n if (err instanceof SendingOnClosedConnection) {\n /* doesn't matter, it's ok */\n } else {\n throw err\n }\n }\n this.closed = true\n }\n this.relay.openSubs.delete(this.id)\n\n // compute idleness state\n this.relay.ongoingOperations--\n if (this.relay.ongoingOperations === 0) this.relay.idleSince = Date.now()\n\n this.onclose?.(reason)\n }\n}\n\nexport type SubscriptionParams = {\n onevent?: (evt: Event) => void\n oninvalidevent?: (evt: unknown) => void\n oneose?: () => void\n onclose?: (reason: string) => void\n alreadyHaveEvent?: (id: string) => boolean\n receivedEvent?: (relay: AbstractRelay, id: string) => void\n eoseTimeout?: number\n abort?: AbortSignal\n}\n\nexport type CountResolver = {\n resolve: (payload: { count: number; hll?: string }) => void\n reject: (err: Error) => void\n}\n\nexport type EventPublishResolver = {\n resolve: (reason: string) => void\n reject: (err: Error) => void\n timeout: ReturnType<typeof setTimeout>\n}\n", "import { verifiedSymbol, type Event, type Nostr, VerifiedEvent } from './core.ts'\n\nexport const alwaysTrue: Nostr['verifyEvent'] = (t: Event): t is VerifiedEvent => {\n t[verifiedSymbol] = true\n return true\n}\n", "import { sha256 } from '@noble/hashes/sha2.js'\nimport { bytesToHex } from '@noble/hashes/utils.js'\n\nimport type { Event } from './core.ts'\nimport type { Filter } from './filter.ts'\n\nconst M = 256\nconst HLL_HEX_LENGTH = M * 2\nconst utf8Encoder = new TextEncoder()\n\nexport type CountManyDirective = 'reactions' | 'reposts' | 'quotes' | 'replies' | 'comments' | 'followers'\n\nexport function getCountManyFilter(target: string, directive: CountManyDirective): Filter {\n switch (directive) {\n case 'reactions':\n return { '#e': [target], kinds: [7] }\n case 'reposts':\n return { '#e': [target], kinds: [6] }\n case 'quotes':\n return { '#q': [target], kinds: [1, 1111] }\n case 'replies':\n return { '#e': [target], kinds: [1] }\n case 'comments':\n return { '#E': [target], kinds: [1111] }\n case 'followers':\n return { '#p': [target], kinds: [3] }\n }\n}\n\nexport function newHll(): Uint8Array {\n return new Uint8Array(M)\n}\n\nexport function hllDecode(hex: string): Uint8Array | undefined {\n if (hex.length !== HLL_HEX_LENGTH || !/^[0-9a-fA-F]+$/.test(hex)) return undefined\n\n const registers = new Uint8Array(M)\n for (let i = 0; i < M; i++) {\n registers[i] = parseInt(hex.slice(i * 2, i * 2 + 2), 16)\n }\n return registers\n}\n\nexport function hllEncode(registers: Uint8Array): string {\n if (registers.length !== M) throw new Error(`invalid number of registers ${registers.length}`)\n\n let hex = ''\n for (let i = 0; i < M; i++) {\n hex += registers[i].toString(16).padStart(2, '0')\n }\n return hex\n}\n\nexport function computeOffset(filterFirstTagValue: string): number {\n let hex = filterFirstTagValue\n\n if (!isHex64(hex)) {\n const parts = hex.split(':')\n if (parts.length === 3 && isHex64(parts[1])) {\n hex = parts[1]\n } else {\n hex = bytesToHex(sha256(utf8Encoder.encode(filterFirstTagValue)))\n }\n }\n\n return parseInt(hex[32], 16) + 8\n}\n\nexport function getFilterFirstTagValue(filter: Filter): string | undefined {\n for (const key in filter) {\n if (key[0] !== '#') continue\n\n const values = filter[key as `#${string}`]\n if (Array.isArray(values) && typeof values[0] === 'string') return values[0]\n }\n\n return undefined\n}\n\nexport function feedPubkey(hll: Uint8Array, pubkey: string, offset: number): Uint8Array {\n if (offset < 0 || offset > 24) throw new Error(`invalid offset ${offset}`)\n if (!isHex64(pubkey)) throw new Error('pubkey must be 32-byte hex')\n\n if (hll.length === 0) hll = newHll()\n if (hll.length !== M) throw new Error(`invalid number of registers ${hll.length}`)\n\n const ri = parseInt(pubkey.slice(offset * 2, offset * 2 + 2), 16)\n const value = countLeadingZeroBitsAfterOffset(pubkey, offset) + 1\n if (value > hll[ri]) hll[ri] = value\n\n return hll\n}\n\nexport function feedEvent(hll: Uint8Array, event: Event, offset: number): Uint8Array {\n return feedPubkey(hll, event.pubkey, offset)\n}\n\nexport function mergeHll(target: Uint8Array, source: Uint8Array): Uint8Array {\n if (target.length === 0) target = newHll()\n if (target.length !== M) throw new Error(`invalid number of registers ${target.length}`)\n if (source.length !== M) throw new Error(`invalid number of registers ${source.length}`)\n\n for (let i = 0; i < M; i++) {\n if (source[i] > target[i]) target[i] = source[i]\n }\n\n return target\n}\n\nexport function estimateCount(hll: Uint8Array): number {\n if (hll.length === 0) return 0\n if (hll.length !== M) throw new Error(`invalid number of registers ${hll.length}`)\n\n const v = countZeros(hll)\n if (v !== 0) {\n const lc = linearCounting(M, v)\n if (lc <= 220) return Math.floor(lc)\n }\n\n const estimate = calculateEstimate(hll)\n if (estimate <= M * 3 && v !== 0) return Math.floor(linearCounting(M, v))\n\n return Math.floor(estimate)\n}\n\nfunction isHex64(value: string): boolean {\n return /^[0-9a-fA-F]{64}$/.test(value)\n}\n\nfunction countLeadingZeroBitsAfterOffset(pubkey: string, offset: number): number {\n let zeroBits = 0\n for (let i = offset + 1; i < offset + 8; i++) {\n const byte = parseInt(pubkey.slice(i * 2, i * 2 + 2), 16)\n if (byte === 0) {\n zeroBits += 8\n continue\n }\n\n let mask = 0x80\n while ((byte & mask) === 0) {\n zeroBits++\n mask >>= 1\n }\n break\n }\n return zeroBits\n}\n\nfunction countZeros(registers: Uint8Array): number {\n let count = 0\n for (let i = 0; i < M; i++) {\n if (registers[i] === 0) count++\n }\n return count\n}\n\nfunction linearCounting(m: number, v: number): number {\n return m * Math.log(m / v)\n}\n\nfunction calculateEstimate(registers: Uint8Array): number {\n let sum = 0\n for (let i = 0; i < M; i++) {\n sum += 1 / 2 ** registers[i]\n }\n return (0.7182725932495458 * M * M) / sum\n}\n"],
5
- "mappings": ";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACQO,IAAM,iBAAiB,OAAO,UAAU;;;ACH/C,mBAAuC;AAHhC,IAAM,cAA2B,IAAI,YAAY,OAAO;AACxD,IAAM,cAA2B,IAAI,YAAY;AAIjD,SAAS,aAAa,KAAqB;AAChD,MAAI;AACF,QAAI,IAAI,QAAQ,KAAK,MAAM;AAAI,YAAM,WAAW;AAChD,QAAI,IAAI,IAAI,IAAI,GAAG;AACnB,QAAI,EAAE,aAAa;AAAS,QAAE,WAAW;AAAA,aAChC,EAAE,aAAa;AAAU,QAAE,WAAW;AAC/C,MAA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OAAO,OAAO,GAAG;AACtB,mBAAW,KAAK,GAAG;AACnB,cAAM,MAAM;AAAA,MACd;AAAA,IACF;AAEA,WAAO;AAAA,EACT;AACF;",
4
+ "sourcesContent": ["/* global WebSocket */\n\nimport {\n AbstractRelay as AbstractRelay,\n SubscriptionParams,\n Subscription,\n type AbstractRelayConstructorOptions,\n} from './abstract-relay.ts'\nimport { normalizeURL } from './utils.ts'\n\nimport type { Event, EventTemplate, Nostr, VerifiedEvent } from './core.ts'\nimport { type Filter } from './filter.ts'\nimport { alwaysTrue } from './helpers.ts'\nimport { getCountManyFilter, hllDecode, hllEncode, mergeHll, type CountManyDirective } from './nip45.ts'\nimport { Relay } from './relay.ts'\n\nexport type SubCloser = { close: (reason?: string) => void }\n\nexport type AbstractPoolConstructorOptions = AbstractRelayConstructorOptions & {\n // automaticallyAuth takes a relay URL and should return null in case that relay shouldn't be authenticated against\n // or a function to sign the AUTH event template otherwise (that function may still throw in case of failure)\n automaticallyAuth?: (relayURL: string) => null | ((event: EventTemplate) => Promise<VerifiedEvent>)\n // onRelayConnectionFailure is called with the URL of a relay that failed the initial connection\n onRelayConnectionFailure?: (url: string) => void\n // onRelayConnectionSuccess is called with the URL of a relay that succeeds the initial connection\n onRelayConnectionSuccess?: (url: string) => void\n // allowConnectingToRelay takes a relay URL and the operation being performed\n // return false to skip connecting to that relay\n allowConnectingToRelay?: (url: string, operation: ['read', Filter[]] | ['write', Event]) => boolean\n // maxWaitForConnection takes a number in milliseconds that will be given to ensureRelay such that we\n // don't get stuck forever when attempting to connect to a relay, it is 3000 (3 seconds) by default\n maxWaitForConnection: number\n}\n\nexport type SubscribeManyParams = Omit<SubscriptionParams, 'onclose'> & {\n maxWait?: number\n abort?: AbortSignal\n onclose?: (reasons: string[]) => void\n onauth?: (event: EventTemplate) => Promise<VerifiedEvent>\n id?: string\n label?: string\n}\n\nexport class AbstractSimplePool {\n protected relays: Map<string, AbstractRelay> = new Map()\n public seenOn: Map<string, Set<AbstractRelay>> = new Map()\n public trackRelays: boolean = false\n\n public verifyEvent: Nostr['verifyEvent']\n public enablePing: boolean | undefined\n public enableReconnect: boolean\n public idleTimeout: number = 20000\n public automaticallyAuth?: (relayURL: string) => null | ((event: EventTemplate) => Promise<VerifiedEvent>)\n public trustedRelayURLs: Set<string> = new Set()\n public onRelayConnectionFailure?: (url: string) => void\n public onRelayConnectionSuccess?: (url: string) => void\n public allowConnectingToRelay?: (url: string, operation: ['read', Filter[]] | ['write', Event]) => boolean\n public maxWaitForConnection: number\n\n private _WebSocket?: typeof WebSocket\n\n constructor(opts: AbstractPoolConstructorOptions) {\n this.verifyEvent = opts.verifyEvent\n this._WebSocket = opts.websocketImplementation\n this.enablePing = opts.enablePing\n this.enableReconnect = opts.enableReconnect || false\n if (opts.idleTimeout) this.idleTimeout = opts.idleTimeout\n this.automaticallyAuth = opts.automaticallyAuth\n this.onRelayConnectionFailure = opts.onRelayConnectionFailure\n this.onRelayConnectionSuccess = opts.onRelayConnectionSuccess\n this.allowConnectingToRelay = opts.allowConnectingToRelay\n this.maxWaitForConnection = opts.maxWaitForConnection || 3000\n }\n\n async ensureRelay(\n url: string,\n params?: {\n connectionTimeout?: number\n abort?: AbortSignal\n },\n ): Promise<AbstractRelay> {\n url = normalizeURL(url)\n\n let relay = this.relays.get(url)\n if (!relay) {\n relay = new AbstractRelay(url, {\n verifyEvent: this.trustedRelayURLs.has(url) ? alwaysTrue : this.verifyEvent,\n websocketImplementation: this._WebSocket,\n enablePing: this.enablePing,\n enableReconnect: this.enableReconnect,\n idleTimeout: this.idleTimeout,\n })\n relay.onclose = () => {\n this.relays.delete(url)\n }\n this.relays.set(url, relay)\n }\n\n if (this.automaticallyAuth) {\n const authSignerFn = this.automaticallyAuth(url)\n if (authSignerFn) {\n relay.onauth = authSignerFn\n }\n }\n\n try {\n await relay.connect({\n timeout: params?.connectionTimeout,\n abort: params?.abort,\n })\n } catch (err) {\n this.relays.delete(url)\n throw err\n }\n\n return relay\n }\n\n close(relays: string[]) {\n relays.map(normalizeURL).forEach(url => {\n this.relays.get(url)?.close()\n this.relays.delete(url)\n })\n }\n\n subscribe(relays: string[], filter: Filter, params: SubscribeManyParams): SubCloser {\n const request: { url: string; filter: Filter }[] = []\n const uniqUrls: string[] = []\n for (let i = 0; i < relays.length; i++) {\n const url = normalizeURL(relays[i])\n if (!request.find(r => r.url === url)) {\n if (uniqUrls.indexOf(url) === -1) {\n uniqUrls.push(url)\n request.push({ url, filter: filter })\n }\n }\n }\n\n return this.subscribeMap(request, params)\n }\n\n subscribeMany(relays: string[], filter: Filter, params: SubscribeManyParams): SubCloser {\n return this.subscribe(relays, filter, params)\n }\n\n subscribeMap(requests: { url: string; filter: Filter }[], params: SubscribeManyParams): SubCloser {\n const grouped = new Map<string, Filter[]>()\n for (const req of requests) {\n const { url, filter } = req\n if (!grouped.has(url)) grouped.set(url, [])\n grouped.get(url)!.push(filter)\n }\n const groupedRequests = Array.from(grouped.entries()).map(([url, filters]) => ({ url, filters }))\n\n if (this.trackRelays) {\n params.receivedEvent = (relay: AbstractRelay, id: string) => {\n let set = this.seenOn.get(id)\n if (!set) {\n set = new Set()\n this.seenOn.set(id, set)\n }\n set.add(relay)\n }\n }\n\n const _knownIds = new Set<string>()\n const subs: Subscription[] = []\n\n // batch all EOSEs into a single\n const eosesReceived: boolean[] = []\n let handleEose = (i: number) => {\n if (eosesReceived[i]) return // do not act twice for the same relay\n eosesReceived[i] = true\n if (eosesReceived.filter(a => a).length === groupedRequests.length) {\n params.oneose?.()\n handleEose = () => {}\n }\n }\n // batch all closes into a single\n const closesReceived: string[] = []\n let handleClose = (i: number, reason: string) => {\n if (closesReceived[i]) return // do not act twice for the same relay\n handleEose(i)\n closesReceived[i] = reason\n if (closesReceived.filter(a => a).length === groupedRequests.length) {\n params.onclose?.(closesReceived)\n handleClose = () => {}\n }\n }\n\n const localAlreadyHaveEventHandler = (id: string) => {\n if (params.alreadyHaveEvent?.(id)) {\n return true\n }\n const have = _knownIds.has(id)\n _knownIds.add(id)\n return have\n }\n\n // open a subscription in all given relays\n const allOpened = Promise.all(\n groupedRequests.map(async ({ url, filters }, i) => {\n if (this.allowConnectingToRelay?.(url, ['read', filters]) === false) {\n handleClose(i, 'connection skipped by allowConnectingToRelay')\n return\n }\n\n let relay: AbstractRelay\n try {\n relay = await this.ensureRelay(url, {\n connectionTimeout:\n this.maxWaitForConnection < (params.maxWait || 0)\n ? Math.max(params.maxWait! * 0.8, params.maxWait! - 1000)\n : this.maxWaitForConnection,\n abort: params.abort,\n })\n } catch (err) {\n this.onRelayConnectionFailure?.(url)\n handleClose(i, (err as any)?.message || String(err))\n return\n }\n\n this.onRelayConnectionSuccess?.(url)\n\n let subscription = relay.subscribe(filters, {\n ...params,\n oneose: () => handleEose(i),\n onclose: reason => {\n if (reason.startsWith('auth-required: ') && params.onauth) {\n relay\n .auth(params.onauth)\n .then(() => {\n relay.subscribe(filters, {\n ...params,\n oneose: () => handleEose(i),\n onclose: reason => {\n handleClose(i, reason) // the second time we won't try to auth anymore\n },\n alreadyHaveEvent: localAlreadyHaveEventHandler,\n eoseTimeout: params.maxWait,\n abort: params.abort,\n })\n })\n .catch(err => {\n handleClose(i, `auth was required and attempted, but failed with: ${err}`)\n })\n } else {\n handleClose(i, reason)\n }\n },\n alreadyHaveEvent: localAlreadyHaveEventHandler,\n eoseTimeout: params.maxWait,\n abort: params.abort,\n })\n\n subs.push(subscription)\n }),\n )\n\n return {\n async close(reason?: string) {\n await allOpened\n subs.forEach(sub => {\n sub.close(reason)\n })\n },\n }\n }\n\n subscribeEose(\n relays: string[],\n filter: Filter,\n params: Pick<SubscribeManyParams, 'label' | 'id' | 'onevent' | 'oninvalidevent' | 'onclose' | 'maxWait' | 'onauth'>,\n ): SubCloser {\n let subcloser: SubCloser\n subcloser = this.subscribe(relays, filter, {\n ...params,\n oneose() {\n const reason = 'closed automatically on eose'\n if (subcloser) subcloser.close(reason)\n else params.onclose?.(relays.map(_ => reason))\n },\n })\n return subcloser\n }\n\n subscribeManyEose(\n relays: string[],\n filter: Filter,\n params: Pick<SubscribeManyParams, 'label' | 'id' | 'onevent' | 'oninvalidevent' | 'onclose' | 'maxWait' | 'onauth'>,\n ): SubCloser {\n return this.subscribeEose(relays, filter, params)\n }\n\n async querySync(\n relays: string[],\n filter: Filter,\n params?: Pick<SubscribeManyParams, 'label' | 'id' | 'maxWait'>,\n ): Promise<Event[]> {\n return new Promise(async resolve => {\n const events: Event[] = []\n this.subscribeEose(relays, filter, {\n ...params,\n onevent(event: Event) {\n events.push(event)\n },\n onclose(_: string[]) {\n resolve(events)\n },\n })\n })\n }\n\n async get(\n relays: string[],\n filter: Filter,\n params?: Pick<SubscribeManyParams, 'label' | 'id' | 'maxWait'>,\n ): Promise<Event | null> {\n filter.limit = 1\n const events = await this.querySync(relays, filter, params)\n events.sort((a, b) => b.created_at - a.created_at)\n return events[0] || null\n }\n\n async countMany(\n relays: string[],\n target: string,\n directive: CountManyDirective,\n params?: { id?: string | null; maxWait?: number; abort?: AbortSignal },\n ): Promise<{ count: number; hll?: string }> {\n const filter = getCountManyFilter(target, directive)\n const urls: string[] = []\n\n for (let i = 0; i < relays.length; i++) {\n const url = normalizeURL(relays[i])\n if (urls.indexOf(url) === -1) urls.push(url)\n }\n\n const responses = await Promise.all(\n urls.map(async url => {\n if (this.allowConnectingToRelay?.(url, ['read', [filter]]) === false) return null\n\n let relay: AbstractRelay\n try {\n relay = await this.ensureRelay(url, {\n connectionTimeout:\n this.maxWaitForConnection < (params?.maxWait || 0)\n ? Math.max(params!.maxWait! * 0.8, params!.maxWait! - 1000)\n : this.maxWaitForConnection,\n abort: params?.abort,\n })\n } catch (err) {\n this.onRelayConnectionFailure?.(url)\n return null\n }\n\n this.onRelayConnectionSuccess?.(url)\n\n return relay.countWithHLL([filter], { id: params?.id }).catch(() => null)\n }),\n )\n\n let count = 0\n let hll: Uint8Array | undefined\n\n for (const response of responses) {\n if (!response) continue\n\n if (response.count > count) count = response.count\n\n if (!response.hll || response.hll.length !== 512) continue\n\n const registers = hllDecode(response.hll)\n if (!registers) continue\n\n hll = mergeHll(hll || new Uint8Array(0), registers)\n }\n\n return hll ? { count, hll: hllEncode(hll) } : { count }\n }\n\n publish(\n relays: string[],\n event: Event,\n params?: {\n onauth?: (evt: EventTemplate) => Promise<VerifiedEvent>\n maxWait?: number\n abort?: AbortSignal\n },\n ): Promise<string>[] {\n return relays.map(normalizeURL).map(async (url, i, arr) => {\n if (arr.indexOf(url) !== i) {\n // duplicate\n return Promise.reject('duplicate url')\n }\n\n if (this.allowConnectingToRelay?.(url, ['write', event]) === false) {\n return Promise.reject('connection skipped by allowConnectingToRelay')\n }\n\n let r: Relay\n try {\n r = await this.ensureRelay(url, {\n connectionTimeout:\n this.maxWaitForConnection < (params?.maxWait || 0)\n ? Math.max(params!.maxWait! * 0.8, params!.maxWait! - 1000)\n : this.maxWaitForConnection,\n abort: params?.abort,\n })\n } catch (err) {\n this.onRelayConnectionFailure?.(url)\n return String('connection failure: ' + String(err))\n }\n\n return r\n .publish(event)\n .catch(async err => {\n if (err instanceof Error && err.message.startsWith('auth-required: ') && params?.onauth) {\n await r.auth(params.onauth)\n return r.publish(event) // retry\n }\n throw err\n })\n .then(reason => {\n if (this.trackRelays) {\n let set = this.seenOn.get(event.id)\n if (!set) {\n set = new Set()\n this.seenOn.set(event.id, set)\n }\n set.add(r)\n }\n return reason\n })\n })\n }\n\n listConnectionStatus(): Map<string, boolean> {\n const map = new Map<string, boolean>()\n this.relays.forEach((relay, url) => map.set(url, relay.connected))\n\n return map\n }\n\n destroy(): void {\n this.relays.forEach(conn => conn.close())\n this.relays = new Map()\n }\n\n pruneIdleRelays(idleThresholdMs: number = 10000): string[] {\n const prunedUrls: string[] = []\n\n // check each relay's idle status and prune if over threshold\n for (const [url, relay] of this.relays) {\n if (relay.idleSince && Date.now() - relay.idleSince >= idleThresholdMs) {\n this.relays.delete(url)\n prunedUrls.push(url)\n relay.close()\n }\n }\n\n return prunedUrls\n }\n}\n", "export interface Nostr {\n generateSecretKey(): Uint8Array\n getPublicKey(secretKey: Uint8Array): string\n finalizeEvent(event: EventTemplate, secretKey: Uint8Array): VerifiedEvent\n verifyEvent(event: Event): event is VerifiedEvent\n}\n\n/** Designates a verified event signature. */\nexport const verifiedSymbol = Symbol('verified')\n\nexport type NostrEvent = {\n kind: number\n tags: string[][]\n content: string\n created_at: number\n pubkey: string\n id: string\n sig: string\n [verifiedSymbol]?: boolean\n}\n\nexport type Event = NostrEvent\nexport type EventTemplate = Pick<Event, 'kind' | 'tags' | 'content' | 'created_at'>\nexport type UnsignedEvent = Pick<Event, 'kind' | 'tags' | 'content' | 'created_at' | 'pubkey'>\n\n/** An event whose signature has been verified. */\nexport interface VerifiedEvent extends Event {\n [verifiedSymbol]: true\n}\n\nconst isRecord = (obj: unknown): obj is Record<string, unknown> => obj instanceof Object\n\nexport function validateEvent<T>(event: T): event is T & UnsignedEvent {\n if (!isRecord(event)) return false\n if (typeof event.kind !== 'number') return false\n if (typeof event.content !== 'string') return false\n if (typeof event.created_at !== 'number') return false\n if (typeof event.pubkey !== 'string') return false\n if (!event.pubkey.match(/^[a-f0-9]{64}$/)) return false\n\n if (!Array.isArray(event.tags)) return false\n for (let i = 0; i < event.tags.length; i++) {\n let tag = event.tags[i]\n if (!Array.isArray(tag)) return false\n for (let j = 0; j < tag.length; j++) {\n if (typeof tag[j] !== 'string') return false\n }\n }\n\n return true\n}\n\n/**\n * Sort events in reverse-chronological order by the `created_at` timestamp,\n * and then by the event `id` (lexicographically) in case of ties.\n * This mutates the array.\n */\nexport function sortEvents(events: Event[]): Event[] {\n return events.sort((a: NostrEvent, b: NostrEvent): number => {\n if (a.created_at !== b.created_at) {\n return b.created_at - a.created_at\n }\n return a.id.localeCompare(b.id)\n })\n}\n", "import type { NostrEvent } from './core.ts'\n\nexport const utf8Decoder: TextDecoder = new TextDecoder('utf-8')\nexport const utf8Encoder: TextEncoder = new TextEncoder()\n\nexport { bytesToHex, hexToBytes } from '@noble/hashes/utils.js'\n\nexport function normalizeURL(url: string): string {\n try {\n if (url.indexOf('://') === -1) url = 'wss://' + url\n let p = new URL(url)\n if (p.protocol === 'http:') p.protocol = 'ws:'\n else if (p.protocol === 'https:') p.protocol = 'wss:'\n p.pathname = p.pathname.replace(/\\/+/g, '/')\n if (p.pathname.endsWith('/')) p.pathname = p.pathname.slice(0, -1)\n if ((p.port === '80' && p.protocol === 'ws:') || (p.port === '443' && p.protocol === 'wss:')) p.port = ''\n p.searchParams.sort()\n p.hash = ''\n return p.toString()\n } catch (e) {\n throw new Error(`Invalid URL: ${url}`)\n }\n}\n\nexport function insertEventIntoDescendingList(sortedArray: NostrEvent[], event: NostrEvent): NostrEvent[] {\n const [idx, found] = binarySearch(sortedArray, b => {\n if (event.id === b.id) return 0\n if (event.created_at === b.created_at) return -1\n return b.created_at - event.created_at\n })\n if (!found) {\n sortedArray.splice(idx, 0, event)\n }\n return sortedArray\n}\n\nexport function insertEventIntoAscendingList(sortedArray: NostrEvent[], event: NostrEvent): NostrEvent[] {\n const [idx, found] = binarySearch(sortedArray, b => {\n if (event.id === b.id) return 0\n if (event.created_at === b.created_at) return -1\n return event.created_at - b.created_at\n })\n if (!found) {\n sortedArray.splice(idx, 0, event)\n }\n return sortedArray\n}\n\nexport function binarySearch<T>(arr: T[], compare: (b: T) => number): [number, boolean] {\n let start = 0\n let end = arr.length - 1\n\n while (start <= end) {\n const mid = Math.floor((start + end) / 2)\n const cmp = compare(arr[mid])\n\n if (cmp === 0) {\n return [mid, true]\n }\n\n if (cmp < 0) {\n end = mid - 1\n } else {\n start = mid + 1\n }\n }\n\n return [start, false]\n}\n\nexport function mergeReverseSortedLists(list1: NostrEvent[], list2: NostrEvent[]): NostrEvent[] {\n const result: NostrEvent[] = new Array(list1.length + list2.length)\n result.length = 0\n let i1 = 0\n let i2 = 0\n let sameTimestampIds: string[] = []\n\n while (i1 < list1.length && i2 < list2.length) {\n let next: NostrEvent\n if (list1[i1]?.created_at > list2[i2]?.created_at) {\n next = list1[i1]\n i1++\n } else {\n next = list2[i2]\n i2++\n }\n\n if (result.length > 0 && result[result.length - 1].created_at === next.created_at) {\n if (sameTimestampIds.includes(next.id)) continue\n } else {\n sameTimestampIds.length = 0\n }\n\n result.push(next)\n sameTimestampIds.push(next.id)\n }\n\n while (i1 < list1.length) {\n const next = list1[i1]\n i1++\n\n if (result.length > 0 && result[result.length - 1].created_at === next.created_at) {\n if (sameTimestampIds.includes(next.id)) continue\n } else {\n sameTimestampIds.length = 0\n }\n result.push(next)\n sameTimestampIds.push(next.id)\n }\n\n while (i2 < list2.length) {\n const next = list2[i2]\n i2++\n\n if (result.length > 0 && result[result.length - 1].created_at === next.created_at) {\n if (sameTimestampIds.includes(next.id)) continue\n } else {\n sameTimestampIds.length = 0\n }\n result.push(next)\n sameTimestampIds.push(next.id)\n }\n\n return result\n}\n", "import { NostrEvent, validateEvent } from './pure.ts'\n\n/** Events are **regular**, which means they're all expected to be stored by relays. */\nexport function isRegularKind(kind: number): boolean {\n return kind < 10000 && kind !== 0 && kind !== 3\n}\n\n/** Events are **replaceable**, which means that, for each combination of `pubkey` and `kind`, only the latest event is expected to (SHOULD) be stored by relays, older versions are expected to be discarded. */\nexport function isReplaceableKind(kind: number): boolean {\n return kind === 0 || kind === 3 || (10000 <= kind && kind < 20000)\n}\n\n/** Events are **ephemeral**, which means they are not expected to be stored by relays. */\nexport function isEphemeralKind(kind: number): boolean {\n return 20000 <= kind && kind < 30000\n}\n\n/** Events are **addressable**, which means that, for each combination of `pubkey`, `kind` and the `d` tag, only the latest event is expected to be stored by relays, older versions are expected to be discarded. */\nexport function isAddressableKind(kind: number): boolean {\n return 30000 <= kind && kind < 40000\n}\n\n/** Classification of the event kind. */\nexport type KindClassification = 'regular' | 'replaceable' | 'ephemeral' | 'parameterized' | 'unknown'\n\n/** Determine the classification of this kind of event if known, or `unknown`. */\nexport function classifyKind(kind: number): KindClassification {\n if (isRegularKind(kind)) return 'regular'\n if (isReplaceableKind(kind)) return 'replaceable'\n if (isEphemeralKind(kind)) return 'ephemeral'\n if (isAddressableKind(kind)) return 'parameterized'\n return 'unknown'\n}\n\nexport function isKind<T extends number>(event: unknown, kind: T | Array<T>): event is NostrEvent & { kind: T } {\n const kindAsArray: number[] = kind instanceof Array ? kind : [kind]\n return (validateEvent(event) && kindAsArray.includes(event.kind)) || false\n}\n\nexport const Metadata = 0\nexport type Metadata = typeof Metadata\nexport const ShortTextNote = 1\nexport type ShortTextNote = typeof ShortTextNote\nexport const RecommendRelay = 2\nexport type RecommendRelay = typeof RecommendRelay\nexport const Contacts = 3\nexport type Contacts = typeof Contacts\nexport const EncryptedDirectMessage = 4\nexport type EncryptedDirectMessage = typeof EncryptedDirectMessage\nexport const EventDeletion = 5\nexport type EventDeletion = typeof EventDeletion\nexport const Repost = 6\nexport type Repost = typeof Repost\nexport const Reaction = 7\nexport type Reaction = typeof Reaction\nexport const BadgeAward = 8\nexport type BadgeAward = typeof BadgeAward\nexport const ChatMessage = 9\nexport type ChatMessage = typeof ChatMessage\nexport const SimpleGroupThreadedReply = 10\nexport type SimpleGroupThreadedReply = typeof SimpleGroupThreadedReply\nexport const ForumThread = 11\nexport type ForumThread = typeof ForumThread\nexport const SimpleGroupReply = 12\nexport type SimpleGroupReply = typeof SimpleGroupReply\nexport const Seal = 13\nexport type Seal = typeof Seal\nexport const PrivateDirectMessage = 14\nexport type PrivateDirectMessage = typeof PrivateDirectMessage\nexport const FileMessage = 15\nexport type FileMessage = typeof FileMessage\nexport const GenericRepost = 16\nexport type GenericRepost = typeof GenericRepost\nexport const ReactionToWebsite = 17\nexport type ReactionToWebsite = typeof ReactionToWebsite\nexport const Photo = 20\nexport type Photo = typeof Photo\nexport const NormalVideo = 21\nexport type NormalVideo = typeof NormalVideo\nexport const ShortVideo = 22\nexport type ShortVideo = typeof ShortVideo\nexport const PublicMessage = 24\nexport type PublicMessage = typeof PublicMessage\nexport const ChannelCreation = 40\nexport type ChannelCreation = typeof ChannelCreation\nexport const ChannelMetadata = 41\nexport type ChannelMetadata = typeof ChannelMetadata\nexport const ChannelMessage = 42\nexport type ChannelMessage = typeof ChannelMessage\nexport const ChannelHideMessage = 43\nexport type ChannelHideMessage = typeof ChannelHideMessage\nexport const ChannelMuteUser = 44\nexport type ChannelMuteUser = typeof ChannelMuteUser\nexport const PodcastEpisode = 54\nexport type PodcastEpisode = typeof PodcastEpisode\nexport const Chess = 64\nexport type Chess = typeof Chess\nexport const MergeRequests = 818\nexport type MergeRequests = typeof MergeRequests\nexport const PollResponse = 1018\nexport type PollResponse = typeof PollResponse\nexport const Bid = 1021\nexport type Bid = typeof Bid\nexport const BidConfirmation = 1022\nexport type BidConfirmation = typeof BidConfirmation\nexport const OpenTimestamps = 1040\nexport type OpenTimestamps = typeof OpenTimestamps\nexport const GiftWrap = 1059\nexport type GiftWrap = typeof GiftWrap\nexport const FileMetadata = 1063\nexport type FileMetadata = typeof FileMetadata\nexport const Poll = 1068\nexport type Poll = typeof Poll\nexport const Comment = 1111\nexport type Comment = typeof Comment\nexport const Voice = 1222\nexport type Voice = typeof Voice\nexport const Scroll = 1227\nexport type Scroll = typeof Scroll\nexport const VoiceComment = 1244\nexport type VoiceComment = typeof VoiceComment\nexport const LiveChatMessage = 1311\nexport type LiveChatMessage = typeof LiveChatMessage\nexport const CodeSnippet = 1337\nexport type CodeSnippet = typeof CodeSnippet\nexport const Patch = 1617\nexport type Patch = typeof Patch\nexport const GitPullRequest = 1618\nexport type GitPullRequest = typeof GitPullRequest\nexport const GitPullRequestUpdate = 1619\nexport type GitPullRequestUpdate = typeof GitPullRequestUpdate\nexport const Issue = 1621\nexport type Issue = typeof Issue\nexport const Reply = 1622\nexport type Reply = typeof Reply\nexport const StatusOpen = 1630\nexport type StatusOpen = typeof StatusOpen\nexport const StatusApplied = 1631\nexport type StatusApplied = typeof StatusApplied\nexport const StatusClosed = 1632\nexport type StatusClosed = typeof StatusClosed\nexport const StatusDraft = 1633\nexport type StatusDraft = typeof StatusDraft\nexport const ProblemTracker = 1971\nexport type ProblemTracker = typeof ProblemTracker\nexport const Report = 1984\nexport type Report = typeof Report\nexport const Reporting = 1984\nexport type Reporting = typeof Reporting\nexport const Label = 1985\nexport type Label = typeof Label\nexport const RelayReviews = 1986\nexport type RelayReviews = typeof RelayReviews\nexport const AIEmbeddings = 1987\nexport type AIEmbeddings = typeof AIEmbeddings\nexport const Torrent = 2003\nexport type Torrent = typeof Torrent\nexport const TorrentComment = 2004\nexport type TorrentComment = typeof TorrentComment\nexport const CoinjoinPool = 2022\nexport type CoinjoinPool = typeof CoinjoinPool\nexport const DecoupledKeyClientAnnouncement = 4454\nexport type DecoupledKeyClientAnnouncement = typeof DecoupledKeyClientAnnouncement\nexport const DecoupledEncryptionKeyDistribution = 4455\nexport type DecoupledEncryptionKeyDistribution = typeof DecoupledEncryptionKeyDistribution\nexport const CommunityPostApproval = 4550\nexport type CommunityPostApproval = typeof CommunityPostApproval\nexport const JobRequest = 5999\nexport type JobRequest = typeof JobRequest\nexport const JobResult = 6999\nexport type JobResult = typeof JobResult\nexport const JobFeedback = 7000\nexport type JobFeedback = typeof JobFeedback\nexport const ReservedCashuWalletTokens = 7374\nexport type ReservedCashuWalletTokens = typeof ReservedCashuWalletTokens\nexport const CashuWalletTokens = 7375\nexport type CashuWalletTokens = typeof CashuWalletTokens\nexport const CashuWalletHistory = 7376\nexport type CashuWalletHistory = typeof CashuWalletHistory\nexport const GeocacheLog = 7516\nexport type GeocacheLog = typeof GeocacheLog\nexport const GeocacheProofOfFind = 7517\nexport type GeocacheProofOfFind = typeof GeocacheProofOfFind\nexport const SimpleGroupPutUser = 9000\nexport type SimpleGroupPutUser = typeof SimpleGroupPutUser\nexport const SimpleGroupRemoveUser = 9001\nexport type SimpleGroupRemoveUser = typeof SimpleGroupRemoveUser\nexport const SimpleGroupEditMetadata = 9002\nexport type SimpleGroupEditMetadata = typeof SimpleGroupEditMetadata\nexport const SimpleGroupDeleteEvent = 9005\nexport type SimpleGroupDeleteEvent = typeof SimpleGroupDeleteEvent\nexport const SimpleGroupCreateGroup = 9007\nexport type SimpleGroupCreateGroup = typeof SimpleGroupCreateGroup\nexport const SimpleGroupDeleteGroup = 9008\nexport type SimpleGroupDeleteGroup = typeof SimpleGroupDeleteGroup\nexport const SimpleGroupCreateInvite = 9009\nexport type SimpleGroupCreateInvite = typeof SimpleGroupCreateInvite\nexport const SimpleGroupJoinRequest = 9021\nexport type SimpleGroupJoinRequest = typeof SimpleGroupJoinRequest\nexport const SimpleGroupLeaveRequest = 9022\nexport type SimpleGroupLeaveRequest = typeof SimpleGroupLeaveRequest\nexport const ZapGoal = 9041\nexport type ZapGoal = typeof ZapGoal\nexport const NutZap = 9321\nexport type NutZap = typeof NutZap\nexport const TidalLogin = 9467\nexport type TidalLogin = typeof TidalLogin\nexport const ZapRequest = 9734\nexport type ZapRequest = typeof ZapRequest\nexport const Zap = 9735\nexport type Zap = typeof Zap\nexport const Highlights = 9802\nexport type Highlights = typeof Highlights\nexport const Mutelist = 10000\nexport type Mutelist = typeof Mutelist\nexport const Pinlist = 10001\nexport type Pinlist = typeof Pinlist\nexport const RelayList = 10002\nexport type RelayList = typeof RelayList\nexport const BookmarkList = 10003\nexport type BookmarkList = typeof BookmarkList\nexport const CommunitiesList = 10004\nexport type CommunitiesList = typeof CommunitiesList\nexport const PublicChatsList = 10005\nexport type PublicChatsList = typeof PublicChatsList\nexport const BlockedRelaysList = 10006\nexport type BlockedRelaysList = typeof BlockedRelaysList\nexport const SearchRelaysList = 10007\nexport type SearchRelaysList = typeof SearchRelaysList\nexport const SimpleGroupList = 10009\nexport type SimpleGroupList = typeof SimpleGroupList\nexport const FavoriteRelays = 10012\nexport type FavoriteRelays = typeof FavoriteRelays\nexport const PrivateEventRelayList = 10013\nexport type PrivateEventRelayList = typeof PrivateEventRelayList\nexport const InterestsList = 10015\nexport type InterestsList = typeof InterestsList\nexport const NutZapInfo = 10019\nexport type NutZapInfo = typeof NutZapInfo\nexport const MediaFollows = 10020\nexport type MediaFollows = typeof MediaFollows\nexport const UserEmojiList = 10030\nexport type UserEmojiList = typeof UserEmojiList\nexport const DecoupledKeyAnnouncement = 10044\nexport type DecoupledKeyAnnouncement = typeof DecoupledKeyAnnouncement\nexport const DirectMessageRelaysList = 10050\nexport type DirectMessageRelaysList = typeof DirectMessageRelaysList\nexport const FavoritePodcasts = 10054\nexport type FavoritePodcasts = typeof FavoritePodcasts\nexport const BlossomServerList = 10063\nexport type BlossomServerList = typeof BlossomServerList\nexport const FileServerPreference = 10096\nexport type FileServerPreference = typeof FileServerPreference\nexport const GoodWikiAuthorList = 10101\nexport type GoodWikiAuthorList = typeof GoodWikiAuthorList\nexport const GoodWikiRelayList = 10102\nexport type GoodWikiRelayList = typeof GoodWikiRelayList\nexport const PodcastMetadata = 10154\nexport type PodcastMetadata = typeof PodcastMetadata\nexport const AuthoredPodcasts = 10164\nexport type AuthoredPodcasts = typeof AuthoredPodcasts\nexport const RelayMonitorAnnouncement = 10166\nexport type RelayMonitorAnnouncement = typeof RelayMonitorAnnouncement\nexport const RoomPresence = 10312\nexport type RoomPresence = typeof RoomPresence\nexport const UserGraspList = 10317\nexport type UserGraspList = typeof UserGraspList\nexport const ProxyAnnouncement = 10377\nexport type ProxyAnnouncement = typeof ProxyAnnouncement\nexport const TransportMethodAnnouncement = 11111\nexport type TransportMethodAnnouncement = typeof TransportMethodAnnouncement\nexport const NWCWalletInfo = 13194\nexport type NWCWalletInfo = typeof NWCWalletInfo\nexport const NsiteRoot = 15128\nexport type NsiteRoot = typeof NsiteRoot\nexport const CashuWalletEvent = 17375\nexport type CashuWalletEvent = typeof CashuWalletEvent\nexport const LightningPubRPC = 21000\nexport type LightningPubRPC = typeof LightningPubRPC\nexport const ClientAuth = 22242\nexport type ClientAuth = typeof ClientAuth\nexport const NWCWalletRequest = 23194\nexport type NWCWalletRequest = typeof NWCWalletRequest\nexport const NWCWalletResponse = 23195\nexport type NWCWalletResponse = typeof NWCWalletResponse\nexport const NostrConnect = 24133\nexport type NostrConnect = typeof NostrConnect\nexport const BlobsAuth = 24242\nexport type BlobsAuth = typeof BlobsAuth\nexport const HTTPAuth = 27235\nexport type HTTPAuth = typeof HTTPAuth\nexport const Followsets = 30000\nexport type Followsets = typeof Followsets\nexport const Genericlists = 30001\nexport type Genericlists = typeof Genericlists\nexport const Relaysets = 30002\nexport type Relaysets = typeof Relaysets\nexport const Bookmarksets = 30003\nexport type Bookmarksets = typeof Bookmarksets\nexport const Curationsets = 30004\nexport type Curationsets = typeof Curationsets\nexport const CuratedVideoSets = 30005\nexport type CuratedVideoSets = typeof CuratedVideoSets\nexport const MuteSets = 30007\nexport type MuteSets = typeof MuteSets\nexport const ProfileBadges = 30008\nexport type ProfileBadges = typeof ProfileBadges\nexport const BadgeDefinition = 30009\nexport type BadgeDefinition = typeof BadgeDefinition\nexport const Interestsets = 30015\nexport type Interestsets = typeof Interestsets\nexport const CreateOrUpdateStall = 30017\nexport type CreateOrUpdateStall = typeof CreateOrUpdateStall\nexport const CreateOrUpdateProduct = 30018\nexport type CreateOrUpdateProduct = typeof CreateOrUpdateProduct\nexport const MarketplaceUI = 30019\nexport type MarketplaceUI = typeof MarketplaceUI\nexport const ProductSoldAsAuction = 30020\nexport type ProductSoldAsAuction = typeof ProductSoldAsAuction\nexport const LongFormArticle = 30023\nexport type LongFormArticle = typeof LongFormArticle\nexport const DraftLong = 30024\nexport type DraftLong = typeof DraftLong\nexport const Emojisets = 30030\nexport type Emojisets = typeof Emojisets\nexport const ModularArticleHeader = 30040\nexport type ModularArticleHeader = typeof ModularArticleHeader\nexport const ModularArticleContent = 30041\nexport type ModularArticleContent = typeof ModularArticleContent\nexport const ReleaseArtifactSets = 30063\nexport type ReleaseArtifactSets = typeof ReleaseArtifactSets\nexport const Application = 30078\nexport type Application = typeof Application\nexport const RelayDiscovery = 30166\nexport type RelayDiscovery = typeof RelayDiscovery\nexport const AppCurationSet = 30267\nexport type AppCurationSet = typeof AppCurationSet\nexport const LiveEvent = 30311\nexport type LiveEvent = typeof LiveEvent\nexport const InteractiveRoom = 30312\nexport type InteractiveRoom = typeof InteractiveRoom\nexport const ConferenceEvent = 30313\nexport type ConferenceEvent = typeof ConferenceEvent\nexport const UserStatuses = 30315\nexport type UserStatuses = typeof UserStatuses\nexport const SlideSet = 30388\nexport type SlideSet = typeof SlideSet\nexport const ClassifiedListing = 30402\nexport type ClassifiedListing = typeof ClassifiedListing\nexport const DraftClassifiedListing = 30403\nexport type DraftClassifiedListing = typeof DraftClassifiedListing\nexport const RepositoryAnnouncement = 30617\nexport type RepositoryAnnouncement = typeof RepositoryAnnouncement\nexport const RepositoryState = 30618\nexport type RepositoryState = typeof RepositoryState\nexport const WikiArticle = 30818\nexport type WikiArticle = typeof WikiArticle\nexport const Redirects = 30819\nexport type Redirects = typeof Redirects\nexport const DraftEvent = 31234\nexport type DraftEvent = typeof DraftEvent\nexport const LinkSet = 31388\nexport type LinkSet = typeof LinkSet\nexport const Feed = 31890\nexport type Feed = typeof Feed\nexport const Date = 31922\nexport type Date = typeof Date\nexport const Time = 31923\nexport type Time = typeof Time\nexport const Calendar = 31924\nexport type Calendar = typeof Calendar\nexport const CalendarEventRSVP = 31925\nexport type CalendarEventRSVP = typeof CalendarEventRSVP\nexport const RelayReview = 31987\nexport type RelayReview = typeof RelayReview\nexport const Handlerrecommendation = 31989\nexport type Handlerrecommendation = typeof Handlerrecommendation\nexport const Handlerinformation = 31990\nexport type Handlerinformation = typeof Handlerinformation\nexport const SoftwareApplication = 32267\nexport type SoftwareApplication = typeof SoftwareApplication\nexport const LegacyNsiteFile = 34128\nexport type LegacyNsiteFile = typeof LegacyNsiteFile\nexport const VideoViewEvent = 34237\nexport type VideoViewEvent = typeof VideoViewEvent\nexport const CommunityDefinition = 34550\nexport type CommunityDefinition = typeof CommunityDefinition\nexport const NsiteNamed = 35128\nexport type NsiteNamed = typeof NsiteNamed\nexport const GeocacheListing = 37515\nexport type GeocacheListing = typeof GeocacheListing\nexport const GeocacheLogEntry = 37516\nexport type GeocacheLogEntry = typeof GeocacheLogEntry\nexport const CashuMintAnnouncement = 38172\nexport type CashuMintAnnouncement = typeof CashuMintAnnouncement\nexport const FedimintAnnouncement = 38173\nexport type FedimintAnnouncement = typeof FedimintAnnouncement\nexport const PeerToPeerOrderEvents = 38383\nexport type PeerToPeerOrderEvents = typeof PeerToPeerOrderEvents\nexport const GroupMetadata = 39000\nexport type GroupMetadata = typeof GroupMetadata\nexport const SimpleGroupAdmins = 39001\nexport type SimpleGroupAdmins = typeof SimpleGroupAdmins\nexport const SimpleGroupMembers = 39002\nexport type SimpleGroupMembers = typeof SimpleGroupMembers\nexport const SimpleGroupRoles = 39003\nexport type SimpleGroupRoles = typeof SimpleGroupRoles\nexport const SimpleGroupLiveKitParticipants = 39004\nexport type SimpleGroupLiveKitParticipants = typeof SimpleGroupLiveKitParticipants\nexport const StarterPacks = 39089\nexport type StarterPacks = typeof StarterPacks\nexport const MediaStarterPacks = 39092\nexport type MediaStarterPacks = typeof MediaStarterPacks\nexport const WebBookmarks = 39701\nexport type WebBookmarks = typeof WebBookmarks\n", "import { Event } from './core.ts'\nimport { isAddressableKind, isReplaceableKind } from './kinds.ts'\n\nexport type Filter = {\n ids?: string[]\n kinds?: number[]\n authors?: string[]\n since?: number\n until?: number\n limit?: number\n search?: string\n [key: `#${string}`]: string[] | undefined\n}\n\nexport function matchFilter(filter: Filter, event: Event): boolean {\n if (filter.ids && filter.ids.indexOf(event.id) === -1) {\n return false\n }\n if (filter.kinds && filter.kinds.indexOf(event.kind) === -1) {\n return false\n }\n if (filter.authors && filter.authors.indexOf(event.pubkey) === -1) {\n return false\n }\n\n for (let f in filter) {\n if (f[0] === '#') {\n let tagName = f.slice(1)\n let values = filter[`#${tagName}`]\n if (values && !event.tags.find(([t, v]) => t === f.slice(1) && values!.indexOf(v) !== -1)) return false\n }\n }\n\n if (filter.since && event.created_at < filter.since) return false\n if (filter.until && event.created_at > filter.until) return false\n\n return true\n}\n\nexport function matchFilters(filters: Filter[], event: Event): boolean {\n for (let i = 0; i < filters.length; i++) {\n if (matchFilter(filters[i], event)) {\n return true\n }\n }\n return false\n}\n\nexport function mergeFilters(...filters: Filter[]): Filter {\n let result: Filter = {}\n for (let i = 0; i < filters.length; i++) {\n let filter = filters[i]\n Object.entries(filter).forEach(([property, values]) => {\n if (property === 'kinds' || property === 'ids' || property === 'authors' || property[0] === '#') {\n // @ts-ignore\n result[property] = result[property] || []\n // @ts-ignore\n for (let v = 0; v < values.length; v++) {\n // @ts-ignore\n let value = values[v]\n // @ts-ignore\n if (!result[property].includes(value)) result[property].push(value)\n }\n }\n })\n\n if (filter.limit && (!result.limit || filter.limit > result.limit)) result.limit = filter.limit\n if (filter.until && (!result.until || filter.until > result.until)) result.until = filter.until\n if (filter.since && (!result.since || filter.since < result.since)) result.since = filter.since\n }\n\n return result\n}\n\n/**\n * Calculate the intrinsic limit of a filter.\n * This function returns a positive integer, or `Infinity` if there is no intrinsic limit.\n */\nexport function getFilterLimit(filter: Filter): number {\n if (filter.ids && !filter.ids.length) return 0\n if (filter.kinds && !filter.kinds.length) return 0\n if (filter.authors && !filter.authors.length) return 0\n\n for (const [key, value] of Object.entries(filter)) {\n if (key[0] === '#' && Array.isArray(value) && !value.length) return 0\n }\n\n return Math.min(\n // The `limit` property creates an artificial limit.\n Math.max(0, filter.limit ?? Infinity),\n\n // There can only be one event per `id`.\n filter.ids?.length ?? Infinity,\n\n // Replaceable events are limited by the number of authors and kinds.\n filter.authors?.length && filter.kinds?.every(kind => isReplaceableKind(kind))\n ? filter.authors.length * filter.kinds.length\n : Infinity,\n\n // Parameterized replaceable events are limited by the number of authors, kinds, and \"d\" tags.\n filter.authors?.length && filter.kinds?.every(kind => isAddressableKind(kind)) && filter['#d']?.length\n ? filter.authors.length * filter.kinds.length * filter['#d'].length\n : Infinity,\n )\n}\n", "export function getHex64(json: string, field: string): string {\n let len = field.length + 3\n let idx = json.indexOf(`\"${field}\":`) + len\n let s = json.slice(idx).indexOf(`\"`) + idx + 1\n return json.slice(s, s + 64)\n}\n\nexport function getInt(json: string, field: string): number {\n let len = field.length\n let idx = json.indexOf(`\"${field}\":`) + len + 3\n let sliced = json.slice(idx)\n let end = Math.min(sliced.indexOf(','), sliced.indexOf('}'))\n return parseInt(sliced.slice(0, end), 10)\n}\n\nexport function getSubscriptionId(json: string): string | null {\n let idx = json.slice(0, 22).indexOf(`\"EVENT\"`)\n if (idx === -1) return null\n\n let pstart = json.slice(idx + 7 + 1).indexOf(`\"`)\n if (pstart === -1) return null\n let start = idx + 7 + 1 + pstart\n\n let pend = json.slice(start + 1, 80).indexOf(`\"`)\n if (pend === -1) return null\n let end = start + 1 + pend\n\n return json.slice(start + 1, end)\n}\n\nexport function matchEventId(json: string, id: string): boolean {\n return id === getHex64(json, 'id')\n}\n\nexport function matchEventPubkey(json: string, pubkey: string): boolean {\n return pubkey === getHex64(json, 'pubkey')\n}\n\nexport function matchEventKind(json: string, kind: number): boolean {\n return kind === getInt(json, 'kind')\n}\n", "import { EventTemplate } from './core.ts'\nimport { ClientAuth } from './kinds.ts'\n\n/**\n * creates an EventTemplate for an AUTH event to be signed.\n */\nexport function makeAuthEvent(relayURL: string, challenge: string): EventTemplate {\n return {\n kind: ClientAuth,\n created_at: Math.floor(Date.now() / 1000),\n tags: [\n ['relay', relayURL],\n ['challenge', challenge],\n ],\n content: '',\n }\n}\n", "/* global WebSocket */\n\nimport type { Event, EventTemplate, VerifiedEvent, Nostr, NostrEvent } from './core.ts'\nimport { matchFilters, type Filter } from './filter.ts'\nimport { getHex64, getSubscriptionId } from './fakejson.ts'\nimport { normalizeURL } from './utils.ts'\nimport { makeAuthEvent } from './nip42.ts'\n\ntype RelayWebSocket = WebSocket & {\n ping?(): void\n on?(event: 'pong', listener: () => void): any\n}\n\nexport type AbstractRelayConstructorOptions = {\n verifyEvent: Nostr['verifyEvent']\n websocketImplementation?: typeof WebSocket\n enablePing?: boolean\n enableReconnect?: boolean\n idleTimeout?: number\n}\n\nexport class SendingOnClosedConnection extends Error {\n constructor(message: string, relay: string) {\n super(`Tried to send message '${message} on a closed connection to ${relay}.`)\n this.name = 'SendingOnClosedConnection'\n }\n}\n\nexport class AbstractRelay {\n public readonly url: string\n private _connected: boolean = false\n\n public onclose: (() => void) | null = null\n public onnotice: (msg: string) => void = msg => console.debug(`NOTICE from ${this.url}: ${msg}`)\n public onauth: undefined | ((evt: EventTemplate) => Promise<VerifiedEvent>)\n\n public baseEoseTimeout: number = 4400\n public publishTimeout: number = 4400\n public pingFrequency: number = 29000\n public pingTimeout: number = 20000\n public resubscribeBackoff: number[] = [10000, 10000, 10000, 20000, 20000, 30000, 60000]\n public openSubs: Map<string, Subscription> = new Map()\n public enablePing: boolean | undefined\n public enableReconnect: boolean\n public idleTimeout: number = 0 // auto-close after ms of inactivity, 0 = disabled\n public idleSince: number | undefined = Date.now() // when undefined that means it isn't idle\n public ongoingOperations: number = 0 // used to compute idleness\n private reconnectTimeoutHandle: ReturnType<typeof setTimeout> | undefined\n private pingIntervalHandle: ReturnType<typeof setInterval> | undefined\n private reconnectAttempts: number = 0\n private skipReconnection: boolean = false\n private idleTimeoutHandle: ReturnType<typeof setTimeout> | undefined\n\n private connectionPromise: Promise<void> | undefined\n private openCountRequests = new Map<string, CountResolver>()\n private openEventPublishes = new Map<string, EventPublishResolver>()\n private ws: RelayWebSocket | undefined\n private challenge: string | undefined\n private authPromise: Promise<string> | undefined\n private serial: number = 0\n private verifyEvent: Nostr['verifyEvent']\n\n private _WebSocket: typeof WebSocket\n\n constructor(url: string, opts: AbstractRelayConstructorOptions) {\n this.url = normalizeURL(url)\n this.verifyEvent = opts.verifyEvent\n this._WebSocket = opts.websocketImplementation || WebSocket\n this.enablePing = opts.enablePing\n this.enableReconnect = opts.enableReconnect || false\n if (opts.idleTimeout) this.idleTimeout = opts.idleTimeout\n }\n\n static async connect(\n url: string,\n opts: AbstractRelayConstructorOptions & Parameters<AbstractRelay['connect']>[0],\n ): Promise<AbstractRelay> {\n const relay = new AbstractRelay(url, opts)\n await relay.connect(opts)\n return relay\n }\n\n private closeAllSubscriptions(reason: string) {\n for (let [_, sub] of this.openSubs) {\n sub.close(reason)\n }\n this.openSubs.clear()\n\n for (let [_, ep] of this.openEventPublishes) {\n ep.reject(new Error(reason))\n }\n this.openEventPublishes.clear()\n\n for (let [_, cr] of this.openCountRequests) {\n cr.reject(new Error(reason))\n }\n this.openCountRequests.clear()\n }\n\n public get connected(): boolean {\n return this._connected\n }\n\n private clearIdleTimeout() {\n if (this.idleTimeoutHandle) {\n clearTimeout(this.idleTimeoutHandle)\n this.idleTimeoutHandle = undefined\n }\n }\n\n public scheduleIdleClose() {\n this.clearIdleTimeout()\n if (this.idleTimeout > 0) {\n this.idleTimeoutHandle = setTimeout(() => {\n if (this.ongoingOperations === 0 && this.idleSince) {\n this.close()\n }\n }, this.idleTimeout)\n }\n }\n\n private async reconnect(): Promise<void> {\n const backoff = this.resubscribeBackoff[Math.min(this.reconnectAttempts, this.resubscribeBackoff.length - 1)]\n this.reconnectAttempts++\n\n this.reconnectTimeoutHandle = setTimeout(async () => {\n try {\n await this.connect()\n } catch (err) {\n // this will be called again through onclose/onerror\n }\n }, backoff)\n }\n\n private handleHardClose(reason: string) {\n if (this.pingIntervalHandle) {\n clearInterval(this.pingIntervalHandle)\n this.pingIntervalHandle = undefined\n }\n\n this._connected = false\n this.connectionPromise = undefined\n this.idleSince = undefined\n this.clearIdleTimeout()\n\n if (this.enableReconnect && !this.skipReconnection) {\n this.reconnect()\n } else {\n this.onclose?.()\n this.closeAllSubscriptions(reason)\n }\n }\n\n public async connect(opts?: { timeout?: number; abort?: AbortSignal }): Promise<void> {\n let connectionTimeoutHandle: ReturnType<typeof setTimeout> | undefined\n\n if (this.connectionPromise) return this.connectionPromise\n\n this.challenge = undefined\n this.authPromise = undefined\n this.skipReconnection = false\n this.connectionPromise = new Promise((resolve, reject) => {\n if (opts?.timeout) {\n connectionTimeoutHandle = setTimeout(() => {\n reject('connection timed out')\n this.connectionPromise = undefined\n // Only give up on the initial connect; a slow reconnect\n // should fall through to the next backoff slot.\n if (this.reconnectAttempts === 0) {\n this.skipReconnection = true\n }\n this.onclose?.()\n this.handleHardClose('relay connection timed out')\n }, opts.timeout)\n }\n\n if (opts?.abort) {\n opts.abort.onabort = reject\n }\n\n try {\n this.ws = new this._WebSocket(this.url)\n } catch (err) {\n clearTimeout(connectionTimeoutHandle)\n reject(err)\n return\n }\n\n this.ws.onopen = () => {\n if (this.reconnectTimeoutHandle) {\n clearTimeout(this.reconnectTimeoutHandle)\n this.reconnectTimeoutHandle = undefined\n }\n clearTimeout(connectionTimeoutHandle)\n this._connected = true\n\n const isReconnection = this.reconnectAttempts > 0\n this.reconnectAttempts = 0\n\n // resubscribe to all open subscriptions\n for (const sub of this.openSubs.values()) {\n sub.eosed = false\n if (isReconnection) {\n for (let f = 0; f < sub.filters.length; f++) {\n if (sub.lastEmitted) {\n sub.filters[f].since = sub.lastEmitted + 1\n }\n }\n }\n sub.fire()\n }\n\n if (this.enablePing) {\n this.pingIntervalHandle = setInterval(() => this.pingpong(), this.pingFrequency)\n }\n resolve()\n }\n\n this.ws.onerror = () => {\n clearTimeout(connectionTimeoutHandle)\n reject('connection failed')\n this.connectionPromise = undefined\n // Only give up on the initial connect. A failed reconnect\n // attempt must fall through so the next backoff slot fires;\n // otherwise one failed retry tears down every subscription.\n if (this.reconnectAttempts === 0) {\n this.skipReconnection = true\n }\n this.onclose?.()\n this.handleHardClose('relay connection failed')\n }\n\n this.ws.onclose = ev => {\n clearTimeout(connectionTimeoutHandle)\n reject((ev as any).message || 'websocket closed')\n this.handleHardClose('relay connection closed')\n }\n\n this.ws.onmessage = this._onmessage.bind(this)\n })\n\n return this.connectionPromise\n }\n\n private waitForPingPong() {\n return new Promise(resolve => {\n // listen for pong\n ;(this.ws as any).once('pong', () => resolve(true))\n // send a ping\n this.ws!.ping!()\n })\n }\n\n private waitForDummyReq() {\n return new Promise((resolve, reject) => {\n if (!this.connectionPromise) return reject(new Error(`no connection to ${this.url}, can't ping`))\n\n // make a dummy request with expected empty eose reply\n // [\"REQ\", \"_\", {\"ids\":[\"aaaa...aaaa\"], \"limit\": 0}]\n try {\n const sub = this.subscribe(\n [{ ids: ['aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa'], limit: 0 }],\n {\n label: '<forced-ping>',\n oneose: () => {\n resolve(true)\n sub.close()\n },\n onclose() {\n // if we get a CLOSED it's because the relay is alive\n resolve(true)\n },\n eoseTimeout: this.pingTimeout + 1000,\n },\n )\n } catch (err) {\n reject(err)\n }\n })\n }\n\n // nodejs requires this magic here to ensure connections are closed when internet goes off and stuff\n // in browsers it's done automatically. see https://github.com/nbd-wtf/nostr-tools/issues/491\n private async pingpong() {\n // if the websocket is connected\n if (this.ws?.readyState === 1) {\n // wait for either a ping-pong reply or a timeout\n const result = await Promise.any([\n // browsers don't have ping so use a dummy req\n this.ws && this.ws.ping && (this.ws as any).once ? this.waitForPingPong() : this.waitForDummyReq(),\n new Promise(res => setTimeout(() => res(false), this.pingTimeout)),\n ])\n\n if (!result) {\n // pingpong closing socket\n if (this.ws?.readyState === this._WebSocket.OPEN) {\n this.ws?.close()\n }\n }\n }\n }\n\n public async send(message: string) {\n if (!this.connectionPromise) throw new SendingOnClosedConnection(message, this.url)\n\n this.connectionPromise.then(() => {\n this.ws?.send(message)\n })\n }\n\n public async auth(signAuthEvent: (evt: EventTemplate) => Promise<VerifiedEvent>): Promise<string> {\n const challenge = this.challenge\n if (!challenge) throw new Error(\"can't perform auth, no challenge was received\")\n if (this.authPromise) return this.authPromise\n\n this.authPromise = new Promise<string>(async (resolve, reject) => {\n try {\n let evt = await signAuthEvent(makeAuthEvent(this.url, challenge))\n let timeout = setTimeout(() => {\n let ep = this.openEventPublishes.get(evt.id) as EventPublishResolver\n if (ep) {\n ep.reject(new Error('auth timed out'))\n this.openEventPublishes.delete(evt.id)\n }\n }, this.publishTimeout)\n this.openEventPublishes.set(evt.id, { resolve, reject, timeout })\n this.send('[\"AUTH\",' + JSON.stringify(evt) + ']')\n } catch (err) {\n console.warn('subscribe auth function failed:', err)\n }\n })\n return this.authPromise\n }\n\n public async publish(event: Event): Promise<string> {\n this.idleSince = undefined\n this.clearIdleTimeout()\n this.ongoingOperations++\n\n const ret = new Promise<string>((resolve, reject) => {\n const timeout = setTimeout(() => {\n const ep = this.openEventPublishes.get(event.id) as EventPublishResolver\n if (ep) {\n ep.reject(new Error('publish timed out'))\n this.openEventPublishes.delete(event.id)\n }\n }, this.publishTimeout)\n this.openEventPublishes.set(event.id, { resolve, reject, timeout })\n })\n try {\n await this.send('[\"EVENT\",' + JSON.stringify(event) + ']')\n } catch (err) {\n const ep = this.openEventPublishes.get(event.id)\n if (ep) {\n ep.reject(err as Error)\n this.openEventPublishes.delete(event.id)\n }\n }\n\n // compute idleness state\n this.ongoingOperations--\n if (this.ongoingOperations === 0) {\n this.idleSince = Date.now()\n this.scheduleIdleClose()\n }\n\n return ret\n }\n\n public async count(filters: Filter[], params: { id?: string | null }): Promise<number> {\n return (await this.countWithHLL(filters, params)).count\n }\n\n public async countWithHLL(\n filters: Filter[],\n params: { id?: string | null },\n ): Promise<{ count: number; hll?: string }> {\n this.serial++\n const id = params?.id || 'count:' + this.serial\n const ret = new Promise<{ count: number; hll?: string }>((resolve, reject) => {\n this.openCountRequests.set(id, { resolve, reject })\n })\n try {\n await this.send('[\"COUNT\",\"' + id + '\",' + JSON.stringify(filters).substring(1))\n } catch (err) {\n const cr = this.openCountRequests.get(id)\n if (cr) {\n cr.reject(err as Error)\n this.openCountRequests.delete(id)\n }\n }\n return ret\n }\n\n public subscribe(\n filters: Filter[],\n params: Partial<SubscriptionParams> & { label?: string; id?: string },\n ): Subscription {\n if (params.label !== '<forced-ping>') {\n this.idleSince = undefined\n this.clearIdleTimeout()\n this.ongoingOperations++\n }\n\n const sub = this.prepareSubscription(filters, params)\n sub.fire()\n\n if (params.abort) {\n params.abort.onabort = () => sub.close(String(params.abort!.reason || '<aborted>'))\n }\n\n return sub\n }\n\n public prepareSubscription(\n filters: Filter[],\n params: Partial<SubscriptionParams> & { label?: string; id?: string },\n ): Subscription {\n this.serial++\n const id = params.id || (params.label ? params.label + ':' : 'sub:') + this.serial\n const sub = new Subscription(this, id, filters, params)\n this.openSubs.set(id, sub)\n return sub\n }\n\n public close() {\n this.skipReconnection = true\n if (this.reconnectTimeoutHandle) {\n clearTimeout(this.reconnectTimeoutHandle)\n this.reconnectTimeoutHandle = undefined\n }\n if (this.pingIntervalHandle) {\n clearInterval(this.pingIntervalHandle)\n this.pingIntervalHandle = undefined\n }\n this.closeAllSubscriptions('relay connection closed by us')\n this._connected = false\n this.idleSince = undefined\n this.clearIdleTimeout()\n this.onclose?.()\n if (this.ws?.readyState === this._WebSocket.OPEN) {\n this.ws?.close()\n }\n }\n\n // this is the function assigned to this.ws.onmessage\n // it's exposed for testing and debugging purposes\n public _onmessage(ev: MessageEvent<any>): void {\n const json = ev.data\n if (!json) {\n return\n }\n\n // shortcut EVENT sub\n const subid = getSubscriptionId(json)\n if (subid) {\n const so = this.openSubs.get(subid as string)\n if (!so) {\n // this is an EVENT message, but for a subscription we don't have, so just stop here\n return\n }\n\n // this will be called only when this message is a EVENT message for a subscription we have\n // we do this before parsing the JSON to not have to do that for duplicate events\n // since JSON parsing is slow\n const id = getHex64(json, 'id')\n const alreadyHave = so.alreadyHaveEvent?.(id)\n\n // notify any interested client that the relay has this event\n // (do this after alreadyHaveEvent() because the client may rely on this to answer that)\n so.receivedEvent?.(this, id)\n\n if (alreadyHave) {\n // if we had already seen this event we can just stop here\n return\n }\n }\n\n try {\n let data = JSON.parse(json)\n // we won't do any checks against the data since all failures (i.e. invalid messages from relays)\n // will naturally be caught by the encompassing try..catch block\n\n switch (data[0]) {\n case 'EVENT': {\n const so = this.openSubs.get(data[1] as string) as Subscription\n const event = data[2] as NostrEvent\n if (this.verifyEvent(event) && matchFilters(so.filters, event)) {\n so.onevent(event)\n } else {\n so.oninvalidevent?.(event)\n }\n if (!so.lastEmitted || so.lastEmitted < event.created_at) so.lastEmitted = event.created_at\n return\n }\n case 'COUNT': {\n const id: string = data[1]\n const payload = data[2] as { count: number; hll?: string }\n const cr = this.openCountRequests.get(id) as CountResolver\n if (cr) {\n cr.resolve(payload)\n this.openCountRequests.delete(id)\n }\n return\n }\n case 'EOSE': {\n const so = this.openSubs.get(data[1] as string)\n if (!so) return\n so.receivedEose()\n return\n }\n case 'OK': {\n const id: string = data[1]\n const ok: boolean = data[2]\n const reason: string = data[3]\n const ep = this.openEventPublishes.get(id) as EventPublishResolver\n if (ep) {\n clearTimeout(ep.timeout)\n if (ok) ep.resolve(reason)\n else ep.reject(new Error(reason))\n this.openEventPublishes.delete(id)\n }\n return\n }\n case 'CLOSED': {\n const id: string = data[1]\n const so = this.openSubs.get(id)\n if (!so) {\n const cr = this.openCountRequests.get(id) as CountResolver\n if (cr) {\n cr.reject(new Error(data[2] as string))\n this.openCountRequests.delete(id)\n }\n return\n }\n so.closed = true\n so.close(data[2] as string)\n return\n }\n case 'NOTICE': {\n this.onnotice(data[1] as string)\n return\n }\n case 'AUTH': {\n this.challenge = data[1] as string\n if (this.onauth) {\n this.auth(this.onauth).catch(err => {\n // If the connection closed before auth could be sent, just ignore it.\n // This is a race condition when relays close connections quickly\n // (e.g., WoT-enforced relays that reject unknown pubkeys).\n if (!(err instanceof SendingOnClosedConnection)) {\n throw err // re-throw other errors\n }\n })\n }\n return\n }\n default: {\n const so = this.openSubs.get(data[1])\n so?.oncustom?.(data)\n return\n }\n }\n } catch (err) {\n try {\n const [_, __, event] = JSON.parse(json)\n console.warn(`[nostr] relay ${this.url} error processing message:`, err, event)\n } catch (_) {\n console.warn(`[nostr] relay ${this.url} error processing message:`, err)\n }\n return\n }\n }\n}\n\nexport class Subscription {\n public readonly relay: AbstractRelay\n public readonly id: string\n\n public lastEmitted: number | undefined\n public closed: boolean = false\n public eosed: boolean = false\n public filters: Filter[]\n public alreadyHaveEvent: ((id: string) => boolean) | undefined\n public receivedEvent: ((relay: AbstractRelay, id: string) => void) | undefined\n\n public onevent: (evt: Event) => void\n public oninvalidevent: ((evt: unknown) => void) | undefined\n public oneose: (() => void) | undefined\n public onclose: ((reason: string) => void) | undefined\n\n // will get any messages that have this subscription id as their second item and are not default standard\n public oncustom: ((msg: string[]) => void) | undefined\n\n public eoseTimeout: number\n private eoseTimeoutHandle: ReturnType<typeof setTimeout> | undefined\n\n constructor(relay: AbstractRelay, id: string, filters: Filter[], params: SubscriptionParams) {\n if (filters.length === 0) throw new Error(\"subscription can't be created with zero filters\")\n\n this.relay = relay\n this.filters = filters\n this.id = id\n this.alreadyHaveEvent = params.alreadyHaveEvent\n this.receivedEvent = params.receivedEvent\n this.eoseTimeout = params.eoseTimeout || relay.baseEoseTimeout\n\n this.oneose = params.oneose\n this.onclose = params.onclose\n this.oninvalidevent = params.oninvalidevent\n this.onevent =\n params.onevent ||\n (event => {\n console.warn(\n `onevent() callback not defined for subscription '${this.id}' in relay ${this.relay.url}. event received:`,\n event,\n )\n })\n }\n\n public fire() {\n this.relay.send('[\"REQ\",\"' + this.id + '\",' + JSON.stringify(this.filters).substring(1))\n\n // only now we start counting the eoseTimeout\n this.eoseTimeoutHandle = setTimeout(this.receivedEose.bind(this), this.eoseTimeout)\n }\n\n public receivedEose() {\n if (this.eosed) return\n clearTimeout(this.eoseTimeoutHandle)\n this.eosed = true\n this.oneose?.()\n }\n\n public close(reason: string = 'closed by caller') {\n if (!this.closed && this.relay.connected) {\n // if the connection was closed by the user calling .close() we will send a CLOSE message\n // otherwise this._open will be already set to false so we will skip this\n try {\n this.relay.send('[\"CLOSE\",' + JSON.stringify(this.id) + ']')\n } catch (err) {\n if (err instanceof SendingOnClosedConnection) {\n /* doesn't matter, it's ok */\n } else {\n throw err\n }\n }\n this.closed = true\n }\n this.relay.openSubs.delete(this.id)\n\n // compute idleness state\n this.relay.ongoingOperations--\n if (this.relay.ongoingOperations === 0) {\n this.relay.idleSince = Date.now()\n this.relay.scheduleIdleClose()\n }\n\n this.onclose?.(reason)\n }\n}\n\nexport type SubscriptionParams = {\n onevent?: (evt: Event) => void\n oninvalidevent?: (evt: unknown) => void\n oneose?: () => void\n onclose?: (reason: string) => void\n alreadyHaveEvent?: (id: string) => boolean\n receivedEvent?: (relay: AbstractRelay, id: string) => void\n eoseTimeout?: number\n abort?: AbortSignal\n}\n\nexport type CountResolver = {\n resolve: (payload: { count: number; hll?: string }) => void\n reject: (err: Error) => void\n}\n\nexport type EventPublishResolver = {\n resolve: (reason: string) => void\n reject: (err: Error) => void\n timeout: ReturnType<typeof setTimeout>\n}\n", "import { verifiedSymbol, type Event, type Nostr, VerifiedEvent } from './core.ts'\n\nexport const alwaysTrue: Nostr['verifyEvent'] = (t: Event): t is VerifiedEvent => {\n t[verifiedSymbol] = true\n return true\n}\n", "import { sha256 } from '@noble/hashes/sha2.js'\nimport { bytesToHex } from '@noble/hashes/utils.js'\n\nimport type { Event } from './core.ts'\nimport type { Filter } from './filter.ts'\n\nconst M = 256\nconst HLL_HEX_LENGTH = M * 2\nconst utf8Encoder = new TextEncoder()\n\nexport type CountManyDirective = 'reactions' | 'reposts' | 'quotes' | 'replies' | 'comments' | 'followers'\n\nexport function getCountManyFilter(target: string, directive: CountManyDirective): Filter {\n switch (directive) {\n case 'reactions':\n return { '#e': [target], kinds: [7] }\n case 'reposts':\n return { '#e': [target], kinds: [6] }\n case 'quotes':\n return { '#q': [target], kinds: [1, 1111] }\n case 'replies':\n return { '#e': [target], kinds: [1] }\n case 'comments':\n return { '#E': [target], kinds: [1111] }\n case 'followers':\n return { '#p': [target], kinds: [3] }\n }\n}\n\nexport function newHll(): Uint8Array {\n return new Uint8Array(M)\n}\n\nexport function hllDecode(hex: string): Uint8Array | undefined {\n if (hex.length !== HLL_HEX_LENGTH || !/^[0-9a-fA-F]+$/.test(hex)) return undefined\n\n const registers = new Uint8Array(M)\n for (let i = 0; i < M; i++) {\n registers[i] = parseInt(hex.slice(i * 2, i * 2 + 2), 16)\n }\n return registers\n}\n\nexport function hllEncode(registers: Uint8Array): string {\n if (registers.length !== M) throw new Error(`invalid number of registers ${registers.length}`)\n\n let hex = ''\n for (let i = 0; i < M; i++) {\n hex += registers[i].toString(16).padStart(2, '0')\n }\n return hex\n}\n\nexport function computeOffset(filterFirstTagValue: string): number {\n let hex = filterFirstTagValue\n\n if (!isHex64(hex)) {\n const parts = hex.split(':')\n if (parts.length === 3 && isHex64(parts[1])) {\n hex = parts[1]\n } else {\n hex = bytesToHex(sha256(utf8Encoder.encode(filterFirstTagValue)))\n }\n }\n\n return parseInt(hex[32], 16) + 8\n}\n\nexport function getFilterFirstTagValue(filter: Filter): string | undefined {\n for (const key in filter) {\n if (key[0] !== '#') continue\n\n const values = filter[key as `#${string}`]\n if (Array.isArray(values) && typeof values[0] === 'string') return values[0]\n }\n\n return undefined\n}\n\nexport function feedPubkey(hll: Uint8Array, pubkey: string, offset: number): Uint8Array {\n if (offset < 0 || offset > 24) throw new Error(`invalid offset ${offset}`)\n if (!isHex64(pubkey)) throw new Error('pubkey must be 32-byte hex')\n\n if (hll.length === 0) hll = newHll()\n if (hll.length !== M) throw new Error(`invalid number of registers ${hll.length}`)\n\n const ri = parseInt(pubkey.slice(offset * 2, offset * 2 + 2), 16)\n const value = countLeadingZeroBitsAfterOffset(pubkey, offset) + 1\n if (value > hll[ri]) hll[ri] = value\n\n return hll\n}\n\nexport function feedEvent(hll: Uint8Array, event: Event, offset: number): Uint8Array {\n return feedPubkey(hll, event.pubkey, offset)\n}\n\nexport function mergeHll(target: Uint8Array, source: Uint8Array): Uint8Array {\n if (target.length === 0) target = newHll()\n if (target.length !== M) throw new Error(`invalid number of registers ${target.length}`)\n if (source.length !== M) throw new Error(`invalid number of registers ${source.length}`)\n\n for (let i = 0; i < M; i++) {\n if (source[i] > target[i]) target[i] = source[i]\n }\n\n return target\n}\n\nexport function estimateCount(hll: Uint8Array): number {\n if (hll.length === 0) return 0\n if (hll.length !== M) throw new Error(`invalid number of registers ${hll.length}`)\n\n const v = countZeros(hll)\n if (v !== 0) {\n const lc = linearCounting(M, v)\n if (lc <= 220) return Math.floor(lc)\n }\n\n const estimate = calculateEstimate(hll)\n if (estimate <= M * 3 && v !== 0) return Math.floor(linearCounting(M, v))\n\n return Math.floor(estimate)\n}\n\nfunction isHex64(value: string): boolean {\n return /^[0-9a-fA-F]{64}$/.test(value)\n}\n\nfunction countLeadingZeroBitsAfterOffset(pubkey: string, offset: number): number {\n let zeroBits = 0\n for (let i = offset + 1; i < offset + 8; i++) {\n const byte = parseInt(pubkey.slice(i * 2, i * 2 + 2), 16)\n if (byte === 0) {\n zeroBits += 8\n continue\n }\n\n let mask = 0x80\n while ((byte & mask) === 0) {\n zeroBits++\n mask >>= 1\n }\n break\n }\n return zeroBits\n}\n\nfunction countZeros(registers: Uint8Array): number {\n let count = 0\n for (let i = 0; i < M; i++) {\n if (registers[i] === 0) count++\n }\n return count\n}\n\nfunction linearCounting(m: number, v: number): number {\n return m * Math.log(m / v)\n}\n\nfunction calculateEstimate(registers: Uint8Array): number {\n let sum = 0\n for (let i = 0; i < M; i++) {\n sum += 1 / 2 ** registers[i]\n }\n return (0.7182725932495458 * M * M) / sum\n}\n"],
5
+ "mappings": ";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACQO,IAAM,iBAAiB,OAAO,UAAU;;;ACH/C,mBAAuC;AAHhC,IAAM,cAA2B,IAAI,YAAY,OAAO;AACxD,IAAM,cAA2B,IAAI,YAAY;AAIjD,SAAS,aAAa,KAAqB;AAChD,MAAI;AACF,QAAI,IAAI,QAAQ,KAAK,MAAM;AAAI,YAAM,WAAW;AAChD,QAAI,IAAI,IAAI,IAAI,GAAG;AACnB,QAAI,EAAE,aAAa;AAAS,QAAE,WAAW;AAAA,aAChC,EAAE,aAAa;AAAU,QAAE,WAAW;AAC/C,MAAE,WAAW,EAAE,SAAS,QAAQ,QAAQ,GAAG;AAC3C,QAAI,EAAE,SAAS,SAAS,GAAG;AA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