You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
1004 lines
28 KiB
1004 lines
28 KiB
"use strict"; |
|
var __defProp = Object.defineProperty; |
|
var __getOwnPropDesc = Object.getOwnPropertyDescriptor; |
|
var __getOwnPropNames = Object.getOwnPropertyNames; |
|
var __hasOwnProp = Object.prototype.hasOwnProperty; |
|
var __export = (target, all) => { |
|
for (var name in all) |
|
__defProp(target, name, { get: all[name], enumerable: true }); |
|
}; |
|
var __copyProps = (to, from, except, desc) => { |
|
if (from && typeof from === "object" || typeof from === "function") { |
|
for (let key of __getOwnPropNames(from)) |
|
if (!__hasOwnProp.call(to, key) && key !== except) |
|
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); |
|
} |
|
return to; |
|
}; |
|
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); |
|
|
|
// pool.ts |
|
var pool_exports = {}; |
|
__export(pool_exports, { |
|
AbstractSimplePool: () => AbstractSimplePool, |
|
SimplePool: () => SimplePool, |
|
useWebSocketImplementation: () => useWebSocketImplementation |
|
}); |
|
module.exports = __toCommonJS(pool_exports); |
|
|
|
// pure.ts |
|
var import_secp256k1 = require("@noble/curves/secp256k1"); |
|
var import_utils2 = require("@noble/hashes/utils"); |
|
|
|
// core.ts |
|
var verifiedSymbol = Symbol("verified"); |
|
var isRecord = (obj) => obj instanceof Object; |
|
function validateEvent(event) { |
|
if (!isRecord(event)) |
|
return false; |
|
if (typeof event.kind !== "number") |
|
return false; |
|
if (typeof event.content !== "string") |
|
return false; |
|
if (typeof event.created_at !== "number") |
|
return false; |
|
if (typeof event.pubkey !== "string") |
|
return false; |
|
if (!event.pubkey.match(/^[a-f0-9]{64}$/)) |
|
return false; |
|
if (!Array.isArray(event.tags)) |
|
return false; |
|
for (let i2 = 0; i2 < event.tags.length; i2++) { |
|
let tag = event.tags[i2]; |
|
if (!Array.isArray(tag)) |
|
return false; |
|
for (let j = 0; j < tag.length; j++) { |
|
if (typeof tag[j] !== "string") |
|
return false; |
|
} |
|
} |
|
return true; |
|
} |
|
|
|
// pure.ts |
|
var import_sha256 = require("@noble/hashes/sha256"); |
|
|
|
// utils.ts |
|
var import_utils = require("@noble/hashes/utils"); |
|
var utf8Decoder = new TextDecoder("utf-8"); |
|
var utf8Encoder = new TextEncoder(); |
|
function normalizeURL(url) { |
|
try { |
|
if (url.indexOf("://") === -1) |
|
url = "wss://" + url; |
|
let p = new URL(url); |
|
if (p.protocol === "http:") |
|
p.protocol = "ws:"; |
|
else if (p.protocol === "https:") |
|
p.protocol = "wss:"; |
|
p.pathname = p.pathname.replace(/\/+/g, "/"); |
|
if (p.pathname.endsWith("/")) |
|
p.pathname = p.pathname.slice(0, -1); |
|
if (p.port === "80" && p.protocol === "ws:" || p.port === "443" && p.protocol === "wss:") |
|
p.port = ""; |
|
p.searchParams.sort(); |
|
p.hash = ""; |
|
return p.toString(); |
|
} catch (e) { |
|
throw new Error(`Invalid URL: ${url}`); |
|
} |
|
} |
|
var QueueNode = class { |
|
value; |
|
next = null; |
|
prev = null; |
|
constructor(message) { |
|
this.value = message; |
|
} |
|
}; |
|
var Queue = class { |
|
first; |
|
last; |
|
constructor() { |
|
this.first = null; |
|
this.last = null; |
|
} |
|
enqueue(value) { |
|
const newNode = new QueueNode(value); |
|
if (!this.last) { |
|
this.first = newNode; |
|
this.last = newNode; |
|
} else if (this.last === this.first) { |
|
this.last = newNode; |
|
this.last.prev = this.first; |
|
this.first.next = newNode; |
|
} else { |
|
newNode.prev = this.last; |
|
this.last.next = newNode; |
|
this.last = newNode; |
|
} |
|
return true; |
|
} |
|
dequeue() { |
|
if (!this.first) |
|
return null; |
|
if (this.first === this.last) { |
|
const target2 = this.first; |
|
this.first = null; |
|
this.last = null; |
|
return target2.value; |
|
} |
|
const target = this.first; |
|
this.first = target.next; |
|
if (this.first) { |
|
this.first.prev = null; |
|
} |
|
return target.value; |
|
} |
|
}; |
|
|
|
// pure.ts |
|
var JS = class { |
|
generateSecretKey() { |
|
return import_secp256k1.schnorr.utils.randomPrivateKey(); |
|
} |
|
getPublicKey(secretKey) { |
|
return (0, import_utils2.bytesToHex)(import_secp256k1.schnorr.getPublicKey(secretKey)); |
|
} |
|
finalizeEvent(t, secretKey) { |
|
const event = t; |
|
event.pubkey = (0, import_utils2.bytesToHex)(import_secp256k1.schnorr.getPublicKey(secretKey)); |
|
event.id = getEventHash(event); |
|
event.sig = (0, import_utils2.bytesToHex)(import_secp256k1.schnorr.sign(getEventHash(event), secretKey)); |
|
event[verifiedSymbol] = true; |
|
return event; |
|
} |
|
verifyEvent(event) { |
|
if (typeof event[verifiedSymbol] === "boolean") |
|
return event[verifiedSymbol]; |
|
const hash = getEventHash(event); |
|
if (hash !== event.id) { |
|
event[verifiedSymbol] = false; |
|
return false; |
|
} |
|
try { |
|
const valid = import_secp256k1.schnorr.verify(event.sig, hash, event.pubkey); |
|
event[verifiedSymbol] = valid; |
|
return valid; |
|
} catch (err) { |
|
event[verifiedSymbol] = false; |
|
return false; |
|
} |
|
} |
|
}; |
|
function serializeEvent(evt) { |
|
if (!validateEvent(evt)) |
|
throw new Error("can't serialize event with wrong or missing properties"); |
|
return JSON.stringify([0, evt.pubkey, evt.created_at, evt.kind, evt.tags, evt.content]); |
|
} |
|
function getEventHash(event) { |
|
let eventHash = (0, import_sha256.sha256)(utf8Encoder.encode(serializeEvent(event))); |
|
return (0, import_utils2.bytesToHex)(eventHash); |
|
} |
|
var i = new JS(); |
|
var generateSecretKey = i.generateSecretKey; |
|
var getPublicKey = i.getPublicKey; |
|
var finalizeEvent = i.finalizeEvent; |
|
var verifyEvent = i.verifyEvent; |
|
|
|
// kinds.ts |
|
var ClientAuth = 22242; |
|
|
|
// filter.ts |
|
function matchFilter(filter, event) { |
|
if (filter.ids && filter.ids.indexOf(event.id) === -1) { |
|
return false; |
|
} |
|
if (filter.kinds && filter.kinds.indexOf(event.kind) === -1) { |
|
return false; |
|
} |
|
if (filter.authors && filter.authors.indexOf(event.pubkey) === -1) { |
|
return false; |
|
} |
|
for (let f in filter) { |
|
if (f[0] === "#") { |
|
let tagName = f.slice(1); |
|
let values = filter[`#${tagName}`]; |
|
if (values && !event.tags.find(([t, v]) => t === f.slice(1) && values.indexOf(v) !== -1)) |
|
return false; |
|
} |
|
} |
|
if (filter.since && event.created_at < filter.since) |
|
return false; |
|
if (filter.until && event.created_at > filter.until) |
|
return false; |
|
return true; |
|
} |
|
function matchFilters(filters, event) { |
|
for (let i2 = 0; i2 < filters.length; i2++) { |
|
if (matchFilter(filters[i2], event)) { |
|
return true; |
|
} |
|
} |
|
return false; |
|
} |
|
|
|
// fakejson.ts |
|
function getHex64(json, field) { |
|
let len = field.length + 3; |
|
let idx = json.indexOf(`"${field}":`) + len; |
|
let s = json.slice(idx).indexOf(`"`) + idx + 1; |
|
return json.slice(s, s + 64); |
|
} |
|
function getSubscriptionId(json) { |
|
let idx = json.slice(0, 22).indexOf(`"EVENT"`); |
|
if (idx === -1) |
|
return null; |
|
let pstart = json.slice(idx + 7 + 1).indexOf(`"`); |
|
if (pstart === -1) |
|
return null; |
|
let start = idx + 7 + 1 + pstart; |
|
let pend = json.slice(start + 1, 80).indexOf(`"`); |
|
if (pend === -1) |
|
return null; |
|
let end = start + 1 + pend; |
|
return json.slice(start + 1, end); |
|
} |
|
|
|
// nip42.ts |
|
function makeAuthEvent(relayURL, challenge) { |
|
return { |
|
kind: ClientAuth, |
|
created_at: Math.floor(Date.now() / 1e3), |
|
tags: [ |
|
["relay", relayURL], |
|
["challenge", challenge] |
|
], |
|
content: "" |
|
}; |
|
} |
|
|
|
// helpers.ts |
|
async function yieldThread() { |
|
return new Promise((resolve, reject) => { |
|
try { |
|
if (typeof MessageChannel !== "undefined") { |
|
const ch = new MessageChannel(); |
|
const handler = () => { |
|
ch.port1.removeEventListener("message", handler); |
|
resolve(); |
|
}; |
|
ch.port1.addEventListener("message", handler); |
|
ch.port2.postMessage(0); |
|
ch.port1.start(); |
|
} else { |
|
if (typeof setImmediate !== "undefined") { |
|
setImmediate(resolve); |
|
} else if (typeof setTimeout !== "undefined") { |
|
setTimeout(resolve, 0); |
|
} else { |
|
resolve(); |
|
} |
|
} |
|
} catch (e) { |
|
console.error("during yield: ", e); |
|
reject(e); |
|
} |
|
}); |
|
} |
|
var alwaysTrue = (t) => { |
|
t[verifiedSymbol] = true; |
|
return true; |
|
}; |
|
|
|
// abstract-relay.ts |
|
var SendingOnClosedConnection = class extends Error { |
|
constructor(message, relay) { |
|
super(`Tried to send message '${message} on a closed connection to ${relay}.`); |
|
this.name = "SendingOnClosedConnection"; |
|
} |
|
}; |
|
var AbstractRelay = class { |
|
url; |
|
_connected = false; |
|
onclose = null; |
|
onnotice = (msg) => console.debug(`NOTICE from ${this.url}: ${msg}`); |
|
onauth; |
|
baseEoseTimeout = 4400; |
|
connectionTimeout = 4400; |
|
publishTimeout = 4400; |
|
pingFrequency = 29e3; |
|
pingTimeout = 2e4; |
|
resubscribeBackoff = [1e4, 1e4, 1e4, 2e4, 2e4, 3e4, 6e4]; |
|
openSubs = /* @__PURE__ */ new Map(); |
|
enablePing; |
|
enableReconnect; |
|
connectionTimeoutHandle; |
|
reconnectTimeoutHandle; |
|
pingIntervalHandle; |
|
reconnectAttempts = 0; |
|
closedIntentionally = false; |
|
connectionPromise; |
|
openCountRequests = /* @__PURE__ */ new Map(); |
|
openEventPublishes = /* @__PURE__ */ new Map(); |
|
ws; |
|
incomingMessageQueue = new Queue(); |
|
queueRunning = false; |
|
challenge; |
|
authPromise; |
|
serial = 0; |
|
verifyEvent; |
|
_WebSocket; |
|
constructor(url, opts) { |
|
this.url = normalizeURL(url); |
|
this.verifyEvent = opts.verifyEvent; |
|
this._WebSocket = opts.websocketImplementation || WebSocket; |
|
this.enablePing = opts.enablePing; |
|
this.enableReconnect = opts.enableReconnect || false; |
|
} |
|
static async connect(url, opts) { |
|
const relay = new AbstractRelay(url, opts); |
|
await relay.connect(); |
|
return relay; |
|
} |
|
closeAllSubscriptions(reason) { |
|
for (let [_, sub] of this.openSubs) { |
|
sub.close(reason); |
|
} |
|
this.openSubs.clear(); |
|
for (let [_, ep] of this.openEventPublishes) { |
|
ep.reject(new Error(reason)); |
|
} |
|
this.openEventPublishes.clear(); |
|
for (let [_, cr] of this.openCountRequests) { |
|
cr.reject(new Error(reason)); |
|
} |
|
this.openCountRequests.clear(); |
|
} |
|
get connected() { |
|
return this._connected; |
|
} |
|
async reconnect() { |
|
const backoff = this.resubscribeBackoff[Math.min(this.reconnectAttempts, this.resubscribeBackoff.length - 1)]; |
|
this.reconnectAttempts++; |
|
this.reconnectTimeoutHandle = setTimeout(async () => { |
|
try { |
|
await this.connect(); |
|
} catch (err) { |
|
} |
|
}, backoff); |
|
} |
|
handleHardClose(reason) { |
|
if (this.pingIntervalHandle) { |
|
clearInterval(this.pingIntervalHandle); |
|
this.pingIntervalHandle = void 0; |
|
} |
|
this._connected = false; |
|
this.connectionPromise = void 0; |
|
const wasIntentional = this.closedIntentionally; |
|
this.closedIntentionally = false; |
|
this.onclose?.(); |
|
if (this.enableReconnect && !wasIntentional) { |
|
this.reconnect(); |
|
} else { |
|
this.closeAllSubscriptions(reason); |
|
} |
|
} |
|
async connect() { |
|
if (this.connectionPromise) |
|
return this.connectionPromise; |
|
this.challenge = void 0; |
|
this.authPromise = void 0; |
|
this.connectionPromise = new Promise((resolve, reject) => { |
|
this.connectionTimeoutHandle = setTimeout(() => { |
|
reject("connection timed out"); |
|
this.connectionPromise = void 0; |
|
this.onclose?.(); |
|
this.closeAllSubscriptions("relay connection timed out"); |
|
}, this.connectionTimeout); |
|
try { |
|
this.ws = new this._WebSocket(this.url); |
|
} catch (err) { |
|
clearTimeout(this.connectionTimeoutHandle); |
|
reject(err); |
|
return; |
|
} |
|
this.ws.onopen = () => { |
|
if (this.reconnectTimeoutHandle) { |
|
clearTimeout(this.reconnectTimeoutHandle); |
|
this.reconnectTimeoutHandle = void 0; |
|
} |
|
clearTimeout(this.connectionTimeoutHandle); |
|
this._connected = true; |
|
const isReconnection = this.reconnectAttempts > 0; |
|
this.reconnectAttempts = 0; |
|
for (const sub of this.openSubs.values()) { |
|
sub.eosed = false; |
|
if (isReconnection) { |
|
for (let f = 0; f < sub.filters.length; f++) { |
|
if (sub.lastEmitted) { |
|
sub.filters[f].since = sub.lastEmitted + 1; |
|
} |
|
} |
|
} |
|
sub.fire(); |
|
} |
|
if (this.enablePing) { |
|
this.pingIntervalHandle = setInterval(() => this.pingpong(), this.pingFrequency); |
|
} |
|
resolve(); |
|
}; |
|
this.ws.onerror = (ev) => { |
|
clearTimeout(this.connectionTimeoutHandle); |
|
reject(ev.message || "websocket error"); |
|
this.handleHardClose("relay connection errored"); |
|
}; |
|
this.ws.onclose = (ev) => { |
|
clearTimeout(this.connectionTimeoutHandle); |
|
reject(ev.message || "websocket closed"); |
|
this.handleHardClose("relay connection closed"); |
|
}; |
|
this.ws.onmessage = this._onmessage.bind(this); |
|
}); |
|
return this.connectionPromise; |
|
} |
|
waitForPingPong() { |
|
return new Promise((resolve) => { |
|
; |
|
this.ws.once("pong", () => resolve(true)); |
|
this.ws.ping(); |
|
}); |
|
} |
|
waitForDummyReq() { |
|
return new Promise((resolve, reject) => { |
|
if (!this.connectionPromise) |
|
return reject(new Error(`no connection to ${this.url}, can't ping`)); |
|
try { |
|
const sub = this.subscribe( |
|
[{ ids: ["aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"], limit: 0 }], |
|
{ |
|
label: "forced-ping", |
|
oneose: () => { |
|
resolve(true); |
|
sub.close(); |
|
}, |
|
onclose() { |
|
resolve(true); |
|
}, |
|
eoseTimeout: this.pingTimeout + 1e3 |
|
} |
|
); |
|
} catch (err) { |
|
reject(err); |
|
} |
|
}); |
|
} |
|
async pingpong() { |
|
if (this.ws?.readyState === 1) { |
|
const result = await Promise.any([ |
|
this.ws && this.ws.ping && this.ws.once ? this.waitForPingPong() : this.waitForDummyReq(), |
|
new Promise((res) => setTimeout(() => res(false), this.pingTimeout)) |
|
]); |
|
if (!result) { |
|
if (this.ws?.readyState === this._WebSocket.OPEN) { |
|
this.ws?.close(); |
|
} |
|
} |
|
} |
|
} |
|
async runQueue() { |
|
this.queueRunning = true; |
|
while (true) { |
|
if (false === this.handleNext()) { |
|
break; |
|
} |
|
await yieldThread(); |
|
} |
|
this.queueRunning = false; |
|
} |
|
handleNext() { |
|
const json = this.incomingMessageQueue.dequeue(); |
|
if (!json) { |
|
return false; |
|
} |
|
const subid = getSubscriptionId(json); |
|
if (subid) { |
|
const so = this.openSubs.get(subid); |
|
if (!so) { |
|
return; |
|
} |
|
const id = getHex64(json, "id"); |
|
const alreadyHave = so.alreadyHaveEvent?.(id); |
|
so.receivedEvent?.(this, id); |
|
if (alreadyHave) { |
|
return; |
|
} |
|
} |
|
try { |
|
let data = JSON.parse(json); |
|
switch (data[0]) { |
|
case "EVENT": { |
|
const so = this.openSubs.get(data[1]); |
|
const event = data[2]; |
|
if (this.verifyEvent(event) && matchFilters(so.filters, event)) { |
|
so.onevent(event); |
|
} |
|
if (!so.lastEmitted || so.lastEmitted < event.created_at) |
|
so.lastEmitted = event.created_at; |
|
return; |
|
} |
|
case "COUNT": { |
|
const id = data[1]; |
|
const payload = data[2]; |
|
const cr = this.openCountRequests.get(id); |
|
if (cr) { |
|
cr.resolve(payload.count); |
|
this.openCountRequests.delete(id); |
|
} |
|
return; |
|
} |
|
case "EOSE": { |
|
const so = this.openSubs.get(data[1]); |
|
if (!so) |
|
return; |
|
so.receivedEose(); |
|
return; |
|
} |
|
case "OK": { |
|
const id = data[1]; |
|
const ok = data[2]; |
|
const reason = data[3]; |
|
const ep = this.openEventPublishes.get(id); |
|
if (ep) { |
|
clearTimeout(ep.timeout); |
|
if (ok) |
|
ep.resolve(reason); |
|
else |
|
ep.reject(new Error(reason)); |
|
this.openEventPublishes.delete(id); |
|
} |
|
return; |
|
} |
|
case "CLOSED": { |
|
const id = data[1]; |
|
const so = this.openSubs.get(id); |
|
if (!so) |
|
return; |
|
so.closed = true; |
|
so.close(data[2]); |
|
return; |
|
} |
|
case "NOTICE": { |
|
this.onnotice(data[1]); |
|
return; |
|
} |
|
case "AUTH": { |
|
this.challenge = data[1]; |
|
if (this.onauth) { |
|
this.auth(this.onauth); |
|
} |
|
return; |
|
} |
|
default: { |
|
const so = this.openSubs.get(data[1]); |
|
so?.oncustom?.(data); |
|
return; |
|
} |
|
} |
|
} catch (err) { |
|
return; |
|
} |
|
} |
|
async send(message) { |
|
if (!this.connectionPromise) |
|
throw new SendingOnClosedConnection(message, this.url); |
|
this.connectionPromise.then(() => { |
|
this.ws?.send(message); |
|
}); |
|
} |
|
async auth(signAuthEvent) { |
|
const challenge = this.challenge; |
|
if (!challenge) |
|
throw new Error("can't perform auth, no challenge was received"); |
|
if (this.authPromise) |
|
return this.authPromise; |
|
this.authPromise = new Promise(async (resolve, reject) => { |
|
try { |
|
let evt = await signAuthEvent(makeAuthEvent(this.url, challenge)); |
|
let timeout = setTimeout(() => { |
|
let ep = this.openEventPublishes.get(evt.id); |
|
if (ep) { |
|
ep.reject(new Error("auth timed out")); |
|
this.openEventPublishes.delete(evt.id); |
|
} |
|
}, this.publishTimeout); |
|
this.openEventPublishes.set(evt.id, { resolve, reject, timeout }); |
|
this.send('["AUTH",' + JSON.stringify(evt) + "]"); |
|
} catch (err) { |
|
console.warn("subscribe auth function failed:", err); |
|
} |
|
}); |
|
return this.authPromise; |
|
} |
|
async publish(event) { |
|
const ret = new Promise((resolve, reject) => { |
|
const timeout = setTimeout(() => { |
|
const ep = this.openEventPublishes.get(event.id); |
|
if (ep) { |
|
ep.reject(new Error("publish timed out")); |
|
this.openEventPublishes.delete(event.id); |
|
} |
|
}, this.publishTimeout); |
|
this.openEventPublishes.set(event.id, { resolve, reject, timeout }); |
|
}); |
|
this.send('["EVENT",' + JSON.stringify(event) + "]"); |
|
return ret; |
|
} |
|
async count(filters, params) { |
|
this.serial++; |
|
const id = params?.id || "count:" + this.serial; |
|
const ret = new Promise((resolve, reject) => { |
|
this.openCountRequests.set(id, { resolve, reject }); |
|
}); |
|
this.send('["COUNT","' + id + '",' + JSON.stringify(filters).substring(1)); |
|
return ret; |
|
} |
|
subscribe(filters, params) { |
|
const sub = this.prepareSubscription(filters, params); |
|
sub.fire(); |
|
return sub; |
|
} |
|
prepareSubscription(filters, params) { |
|
this.serial++; |
|
const id = params.id || (params.label ? params.label + ":" : "sub:") + this.serial; |
|
const subscription = new Subscription(this, id, filters, params); |
|
this.openSubs.set(id, subscription); |
|
return subscription; |
|
} |
|
close() { |
|
this.closedIntentionally = true; |
|
if (this.reconnectTimeoutHandle) { |
|
clearTimeout(this.reconnectTimeoutHandle); |
|
this.reconnectTimeoutHandle = void 0; |
|
} |
|
if (this.pingIntervalHandle) { |
|
clearInterval(this.pingIntervalHandle); |
|
this.pingIntervalHandle = void 0; |
|
} |
|
this.closeAllSubscriptions("relay connection closed by us"); |
|
this._connected = false; |
|
this.onclose?.(); |
|
if (this.ws?.readyState === this._WebSocket.OPEN) { |
|
this.ws?.close(); |
|
} |
|
} |
|
_onmessage(ev) { |
|
this.incomingMessageQueue.enqueue(ev.data); |
|
if (!this.queueRunning) { |
|
this.runQueue(); |
|
} |
|
} |
|
}; |
|
var Subscription = class { |
|
relay; |
|
id; |
|
lastEmitted; |
|
closed = false; |
|
eosed = false; |
|
filters; |
|
alreadyHaveEvent; |
|
receivedEvent; |
|
onevent; |
|
oneose; |
|
onclose; |
|
oncustom; |
|
eoseTimeout; |
|
eoseTimeoutHandle; |
|
constructor(relay, id, filters, params) { |
|
if (filters.length === 0) |
|
throw new Error("subscription can't be created with zero filters"); |
|
this.relay = relay; |
|
this.filters = filters; |
|
this.id = id; |
|
this.alreadyHaveEvent = params.alreadyHaveEvent; |
|
this.receivedEvent = params.receivedEvent; |
|
this.eoseTimeout = params.eoseTimeout || relay.baseEoseTimeout; |
|
this.oneose = params.oneose; |
|
this.onclose = params.onclose; |
|
this.onevent = params.onevent || ((event) => { |
|
console.warn( |
|
`onevent() callback not defined for subscription '${this.id}' in relay ${this.relay.url}. event received:`, |
|
event |
|
); |
|
}); |
|
} |
|
fire() { |
|
this.relay.send('["REQ","' + this.id + '",' + JSON.stringify(this.filters).substring(1)); |
|
this.eoseTimeoutHandle = setTimeout(this.receivedEose.bind(this), this.eoseTimeout); |
|
} |
|
receivedEose() { |
|
if (this.eosed) |
|
return; |
|
clearTimeout(this.eoseTimeoutHandle); |
|
this.eosed = true; |
|
this.oneose?.(); |
|
} |
|
close(reason = "closed by caller") { |
|
if (!this.closed && this.relay.connected) { |
|
try { |
|
this.relay.send('["CLOSE",' + JSON.stringify(this.id) + "]"); |
|
} catch (err) { |
|
if (err instanceof SendingOnClosedConnection) { |
|
} else { |
|
throw err; |
|
} |
|
} |
|
this.closed = true; |
|
} |
|
this.relay.openSubs.delete(this.id); |
|
this.onclose?.(reason); |
|
} |
|
}; |
|
|
|
// abstract-pool.ts |
|
var AbstractSimplePool = class { |
|
relays = /* @__PURE__ */ new Map(); |
|
seenOn = /* @__PURE__ */ new Map(); |
|
trackRelays = false; |
|
verifyEvent; |
|
enablePing; |
|
enableReconnect; |
|
automaticallyAuth; |
|
trustedRelayURLs = /* @__PURE__ */ new Set(); |
|
_WebSocket; |
|
constructor(opts) { |
|
this.verifyEvent = opts.verifyEvent; |
|
this._WebSocket = opts.websocketImplementation; |
|
this.enablePing = opts.enablePing; |
|
this.enableReconnect = opts.enableReconnect || false; |
|
this.automaticallyAuth = opts.automaticallyAuth; |
|
} |
|
async ensureRelay(url, params) { |
|
url = normalizeURL(url); |
|
let relay = this.relays.get(url); |
|
if (!relay) { |
|
relay = new AbstractRelay(url, { |
|
verifyEvent: this.trustedRelayURLs.has(url) ? alwaysTrue : this.verifyEvent, |
|
websocketImplementation: this._WebSocket, |
|
enablePing: this.enablePing, |
|
enableReconnect: this.enableReconnect |
|
}); |
|
relay.onclose = () => { |
|
if (relay && !relay.enableReconnect) { |
|
this.relays.delete(url); |
|
} |
|
}; |
|
if (params?.connectionTimeout) |
|
relay.connectionTimeout = params.connectionTimeout; |
|
this.relays.set(url, relay); |
|
} |
|
if (this.automaticallyAuth) { |
|
const authSignerFn = this.automaticallyAuth(url); |
|
if (authSignerFn) { |
|
relay.onauth = authSignerFn; |
|
} |
|
} |
|
await relay.connect(); |
|
return relay; |
|
} |
|
close(relays) { |
|
relays.map(normalizeURL).forEach((url) => { |
|
this.relays.get(url)?.close(); |
|
this.relays.delete(url); |
|
}); |
|
} |
|
subscribe(relays, filter, params) { |
|
const request = []; |
|
for (let i2 = 0; i2 < relays.length; i2++) { |
|
const url = normalizeURL(relays[i2]); |
|
if (!request.find((r) => r.url === url)) { |
|
request.push({ url, filter }); |
|
} |
|
} |
|
return this.subscribeMap(request, params); |
|
} |
|
subscribeMany(relays, filter, params) { |
|
const request = []; |
|
const uniqUrls = []; |
|
for (let i2 = 0; i2 < relays.length; i2++) { |
|
const url = normalizeURL(relays[i2]); |
|
if (uniqUrls.indexOf(url) === -1) { |
|
uniqUrls.push(url); |
|
request.push({ url, filter }); |
|
} |
|
} |
|
return this.subscribeMap(request, params); |
|
} |
|
subscribeMap(requests, params) { |
|
const grouped = /* @__PURE__ */ new Map(); |
|
for (const req of requests) { |
|
const { url, filter } = req; |
|
if (!grouped.has(url)) |
|
grouped.set(url, []); |
|
grouped.get(url).push(filter); |
|
} |
|
const groupedRequests = Array.from(grouped.entries()).map(([url, filters]) => ({ url, filters })); |
|
if (this.trackRelays) { |
|
params.receivedEvent = (relay, id) => { |
|
let set = this.seenOn.get(id); |
|
if (!set) { |
|
set = /* @__PURE__ */ new Set(); |
|
this.seenOn.set(id, set); |
|
} |
|
set.add(relay); |
|
}; |
|
} |
|
const _knownIds = /* @__PURE__ */ new Set(); |
|
const subs = []; |
|
const eosesReceived = []; |
|
let handleEose = (i2) => { |
|
if (eosesReceived[i2]) |
|
return; |
|
eosesReceived[i2] = true; |
|
if (eosesReceived.filter((a) => a).length === groupedRequests.length) { |
|
params.oneose?.(); |
|
handleEose = () => { |
|
}; |
|
} |
|
}; |
|
const closesReceived = []; |
|
let handleClose = (i2, reason) => { |
|
if (closesReceived[i2]) |
|
return; |
|
handleEose(i2); |
|
closesReceived[i2] = reason; |
|
if (closesReceived.filter((a) => a).length === groupedRequests.length) { |
|
params.onclose?.(closesReceived); |
|
handleClose = () => { |
|
}; |
|
} |
|
}; |
|
const localAlreadyHaveEventHandler = (id) => { |
|
if (params.alreadyHaveEvent?.(id)) { |
|
return true; |
|
} |
|
const have = _knownIds.has(id); |
|
_knownIds.add(id); |
|
return have; |
|
}; |
|
const allOpened = Promise.all( |
|
groupedRequests.map(async ({ url, filters }, i2) => { |
|
let relay; |
|
try { |
|
relay = await this.ensureRelay(url, { |
|
connectionTimeout: params.maxWait ? Math.max(params.maxWait * 0.8, params.maxWait - 1e3) : void 0 |
|
}); |
|
} catch (err) { |
|
handleClose(i2, err?.message || String(err)); |
|
return; |
|
} |
|
let subscription = relay.subscribe(filters, { |
|
...params, |
|
oneose: () => handleEose(i2), |
|
onclose: (reason) => { |
|
if (reason.startsWith("auth-required: ") && params.onauth) { |
|
relay.auth(params.onauth).then(() => { |
|
relay.subscribe(filters, { |
|
...params, |
|
oneose: () => handleEose(i2), |
|
onclose: (reason2) => { |
|
handleClose(i2, reason2); |
|
}, |
|
alreadyHaveEvent: localAlreadyHaveEventHandler, |
|
eoseTimeout: params.maxWait |
|
}); |
|
}).catch((err) => { |
|
handleClose(i2, `auth was required and attempted, but failed with: ${err}`); |
|
}); |
|
} else { |
|
handleClose(i2, reason); |
|
} |
|
}, |
|
alreadyHaveEvent: localAlreadyHaveEventHandler, |
|
eoseTimeout: params.maxWait |
|
}); |
|
subs.push(subscription); |
|
}) |
|
); |
|
return { |
|
async close(reason) { |
|
await allOpened; |
|
subs.forEach((sub) => { |
|
sub.close(reason); |
|
}); |
|
} |
|
}; |
|
} |
|
subscribeEose(relays, filter, params) { |
|
const subcloser = this.subscribe(relays, filter, { |
|
...params, |
|
oneose() { |
|
subcloser.close("closed automatically on eose"); |
|
} |
|
}); |
|
return subcloser; |
|
} |
|
subscribeManyEose(relays, filter, params) { |
|
const subcloser = this.subscribeMany(relays, filter, { |
|
...params, |
|
oneose() { |
|
subcloser.close("closed automatically on eose"); |
|
} |
|
}); |
|
return subcloser; |
|
} |
|
async querySync(relays, filter, params) { |
|
return new Promise(async (resolve) => { |
|
const events = []; |
|
this.subscribeEose(relays, filter, { |
|
...params, |
|
onevent(event) { |
|
events.push(event); |
|
}, |
|
onclose(_) { |
|
resolve(events); |
|
} |
|
}); |
|
}); |
|
} |
|
async get(relays, filter, params) { |
|
filter.limit = 1; |
|
const events = await this.querySync(relays, filter, params); |
|
events.sort((a, b) => b.created_at - a.created_at); |
|
return events[0] || null; |
|
} |
|
publish(relays, event, options) { |
|
return relays.map(normalizeURL).map(async (url, i2, arr) => { |
|
if (arr.indexOf(url) !== i2) { |
|
return Promise.reject("duplicate url"); |
|
} |
|
let r = await this.ensureRelay(url); |
|
return r.publish(event).catch(async (err) => { |
|
if (err instanceof Error && err.message.startsWith("auth-required: ") && options?.onauth) { |
|
await r.auth(options.onauth); |
|
return r.publish(event); |
|
} |
|
throw err; |
|
}).then((reason) => { |
|
if (this.trackRelays) { |
|
let set = this.seenOn.get(event.id); |
|
if (!set) { |
|
set = /* @__PURE__ */ new Set(); |
|
this.seenOn.set(event.id, set); |
|
} |
|
set.add(r); |
|
} |
|
return reason; |
|
}); |
|
}); |
|
} |
|
listConnectionStatus() { |
|
const map = /* @__PURE__ */ new Map(); |
|
this.relays.forEach((relay, url) => map.set(url, relay.connected)); |
|
return map; |
|
} |
|
destroy() { |
|
this.relays.forEach((conn) => conn.close()); |
|
this.relays = /* @__PURE__ */ new Map(); |
|
} |
|
}; |
|
|
|
// pool.ts |
|
var _WebSocket; |
|
try { |
|
_WebSocket = WebSocket; |
|
} catch { |
|
} |
|
function useWebSocketImplementation(websocketImplementation) { |
|
_WebSocket = websocketImplementation; |
|
} |
|
var SimplePool = class extends AbstractSimplePool { |
|
constructor(options) { |
|
super({ verifyEvent, websocketImplementation: _WebSocket, ...options }); |
|
} |
|
};
|
|
|