UNPKG

nostr-web-components

Version:

collection of web components that provide quick access to basic nostr things

1,465 lines (1,448 loc) 207 kB
"use strict"; (() => { var __defProp = Object.defineProperty; var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; var __export = (target, all) => { for (var name in all) __defProp(target, name, { get: all[name], enumerable: true }); }; var __publicField = (obj, key, value) => { __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value); return value; }; // node_modules/@jsr/fiatjaf__lru-cache/typed-arrays.js var MAX_8BIT_INTEGER = Math.pow(2, 8) - 1; var MAX_16BIT_INTEGER = Math.pow(2, 16) - 1; var MAX_32BIT_INTEGER = Math.pow(2, 32) - 1; var MAX_SIGNED_8BIT_INTEGER = Math.pow(2, 7) - 1; var MAX_SIGNED_16BIT_INTEGER = Math.pow(2, 15) - 1; var MAX_SIGNED_32BIT_INTEGER = Math.pow(2, 31) - 1; var getPointerArray = function(size) { var maxIndex = size - 1; if (maxIndex <= MAX_8BIT_INTEGER) return Uint8Array; if (maxIndex <= MAX_16BIT_INTEGER) return Uint16Array; if (maxIndex <= MAX_32BIT_INTEGER) return Uint32Array; throw new Error("mnemonist: Pointer Array of size > 4294967295 is not supported."); }; // node_modules/@jsr/fiatjaf__lru-cache/lru-cache.js function LRUCache(capacity) { this.capacity = capacity; if (typeof this.capacity !== "number" || this.capacity <= 0) throw new Error("mnemonist/lru-cache: capacity should be positive number."); else if (!isFinite(this.capacity) || Math.floor(this.capacity) !== this.capacity) throw new Error("mnemonist/lru-cache: capacity should be a finite positive integer."); var PointerArray = getPointerArray(capacity); this.forward = new PointerArray(capacity); this.backward = new PointerArray(capacity); this.K = new Array(capacity); this.V = new Array(capacity); this.size = 0; this.head = 0; this.tail = 0; this.items = {}; } LRUCache.prototype.clear = function() { this.size = 0; this.head = 0; this.tail = 0; this.items = {}; }; LRUCache.prototype.splayOnTop = function(pointer) { var oldHead = this.head; if (this.head === pointer) return this; var previous = this.backward[pointer], next2 = this.forward[pointer]; if (this.tail === pointer) { this.tail = previous; } else { this.backward[next2] = previous; } this.forward[previous] = next2; this.backward[oldHead] = pointer; this.head = pointer; this.forward[pointer] = oldHead; return this; }; LRUCache.prototype.set = function(key, value) { var pointer = this.items[key]; if (typeof pointer !== "undefined") { this.splayOnTop(pointer); this.V[pointer] = value; return; } if (this.size < this.capacity) { pointer = this.size++; } else { pointer = this.tail; this.tail = this.backward[pointer]; delete this.items[this.K[pointer]]; } this.items[key] = pointer; this.K[pointer] = key; this.V[pointer] = value; this.forward[pointer] = this.head; this.backward[this.head] = pointer; this.head = pointer; }; LRUCache.prototype.setpop = function(key, value) { var oldValue = null; var oldKey = null; var pointer = this.items[key]; if (typeof pointer !== "undefined") { this.splayOnTop(pointer); oldValue = this.V[pointer]; this.V[pointer] = value; return { evicted: false, key, value: oldValue }; } if (this.size < this.capacity) { pointer = this.size++; } else { pointer = this.tail; this.tail = this.backward[pointer]; oldValue = this.V[pointer]; oldKey = this.K[pointer]; delete this.items[oldKey]; } this.items[key] = pointer; this.K[pointer] = key; this.V[pointer] = value; this.forward[pointer] = this.head; this.backward[this.head] = pointer; this.head = pointer; if (oldKey) { return { evicted: true, key: oldKey, value: oldValue }; } else { return null; } }; LRUCache.prototype.has = function(key) { return key in this.items; }; LRUCache.prototype.get = function(key) { var pointer = this.items[key]; if (typeof pointer === "undefined") return; this.splayOnTop(pointer); return this.V[pointer]; }; LRUCache.prototype.peek = function(key) { var pointer = this.items[key]; if (typeof pointer === "undefined") return; return this.V[pointer]; }; // node_modules/@nostr/gadgets/dataloader.js var DataLoader = class { _batchLoadFn; _maxBatchSize; _cacheKeyFn; _cacheMap; _batch; constructor(batchLoadFn, options) { if (typeof batchLoadFn !== "function") { throw new TypeError(`DataLoader must be constructed with a function which accepts Array<key> and returns Promise<Array<value>>, but got: ${batchLoadFn}.`); } this._batchLoadFn = batchLoadFn; this._maxBatchSize = options?.maxBatchSize || Infinity; this._cacheKeyFn = options?.cacheKeyFn; const _cache = new LRUCache(2e3); this._cacheMap = { get: options.transformCacheHit ? (key) => _cache.get(key)?.then(options.transformCacheHit) : (key) => _cache.get(key), set(key, value) { return _cache.set(key, value); }, delete(key) { _cache.set(key, void 0); }, clear() { _cache.clear(); } }; this._batch = null; } load(key) { if (key === null || key === void 0) { throw new TypeError(`The loader.load() function must be called with a value, but got: ${String(key)}.`); } const batch = getCurrentBatch(this); const cacheKey = this._cacheKeyFn(key); const cachedPromise = this._cacheMap.get(cacheKey); if (cachedPromise) { const cacheHits = batch.cacheHits || (batch.cacheHits = []); return new Promise((resolve) => { cacheHits.push(() => { resolve(cachedPromise); }); }); } batch.keys.push(key); const promise = new Promise((resolve, reject) => { batch.callbacks.push({ resolve, reject }); }); this._cacheMap.set(cacheKey, promise); return promise; } clear(key) { const cacheMap = this._cacheMap; if (cacheMap) { const cacheKey = this._cacheKeyFn(key); cacheMap.delete(cacheKey); } return this; } }; function getCurrentBatch(loader) { const existingBatch = loader._batch; if (existingBatch !== null && !existingBatch.hasDispatched && existingBatch.keys.length < loader._maxBatchSize) { return existingBatch; } const newBatch = { hasDispatched: false, keys: [], callbacks: [] }; loader._batch = newBatch; setTimeout(() => { dispatchBatch(loader, newBatch); }); return newBatch; } function dispatchBatch(loader, batch) { batch.hasDispatched = true; if (batch.keys.length === 0) { resolveCacheHits(batch); return; } let batchPromise; try { batchPromise = loader._batchLoadFn(batch.keys); } catch (e) { return failedDispatch(loader, batch, new TypeError(`DataLoader must be constructed with a function which accepts Array<key> and returns Promise<Array<value>>, but the function errored synchronously: ${String(e)}.`)); } if (!batchPromise || typeof batchPromise.then !== "function") { return failedDispatch(loader, batch, new TypeError(`DataLoader must be constructed with a function which accepts Array<key> and returns Promise<Array<value>>, but the function did not return a Promise: ${String(batchPromise)}.`)); } batchPromise.then((values) => { if (values.length !== batch.keys.length) { throw new TypeError(`DataLoader must be constructed with a function which accepts Array<key> and returns Promise<Array<value>>, but the function did not return a Promise of an Array of the same length as the Array of keys. Keys: ${String(batch.keys)} Values: ${String(values)}`); } resolveCacheHits(batch); for (let i3 = 0; i3 < batch.callbacks.length; i3++) { const value = values[i3]; if (value instanceof Error) { batch.callbacks[i3].reject(value); } else { batch.callbacks[i3].resolve(value); } } }).catch((error) => { failedDispatch(loader, batch, error); }); } function failedDispatch(loader, batch, error) { resolveCacheHits(batch); for (let i3 = 0; i3 < batch.keys.length; i3++) { loader.clear(batch.keys[i3]); batch.callbacks[i3].reject(error); } } function resolveCacheHits(batch) { if (batch.cacheHits) { for (let i3 = 0; i3 < batch.cacheHits.length; i3++) { batch.cacheHits[i3](); } } } var dataloader_default = DataLoader; // ../nostr-tools/node_modules/@noble/hashes/esm/crypto.js var crypto = typeof globalThis === "object" && "crypto" in globalThis ? globalThis.crypto : void 0; // ../nostr-tools/node_modules/@noble/hashes/esm/utils.js var u8a = (a) => a instanceof Uint8Array; var createView = (arr) => new DataView(arr.buffer, arr.byteOffset, arr.byteLength); var rotr = (word, shift) => word << 32 - shift | word >>> shift; var isLE = new Uint8Array(new Uint32Array([287454020]).buffer)[0] === 68; if (!isLE) throw new Error("Non little-endian hardware is not supported"); var hexes = Array.from({ length: 256 }, (v, i3) => i3.toString(16).padStart(2, "0")); function bytesToHex(bytes3) { if (!u8a(bytes3)) throw new Error("Uint8Array expected"); let hex2 = ""; for (let i3 = 0; i3 < bytes3.length; i3++) { hex2 += hexes[bytes3[i3]]; } return hex2; } function hexToBytes(hex2) { if (typeof hex2 !== "string") throw new Error("hex string expected, got " + typeof hex2); const len = hex2.length; if (len % 2) throw new Error("padded hex string expected, got unpadded hex of length " + len); const array = new Uint8Array(len / 2); for (let i3 = 0; i3 < array.length; i3++) { const j = i3 * 2; const hexByte = hex2.slice(j, j + 2); const byte = Number.parseInt(hexByte, 16); if (Number.isNaN(byte) || byte < 0) throw new Error("Invalid byte sequence"); array[i3] = byte; } return array; } function utf8ToBytes(str) { if (typeof str !== "string") throw new Error(`utf8ToBytes expected string, got ${typeof str}`); return new Uint8Array(new TextEncoder().encode(str)); } function toBytes(data) { if (typeof data === "string") data = utf8ToBytes(data); if (!u8a(data)) throw new Error(`expected Uint8Array, got ${typeof data}`); return data; } function concatBytes(...arrays) { const r = new Uint8Array(arrays.reduce((sum, a) => sum + a.length, 0)); let pad = 0; arrays.forEach((a) => { if (!u8a(a)) throw new Error("Uint8Array expected"); r.set(a, pad); pad += a.length; }); return r; } var Hash = class { clone() { return this._cloneInto(); } }; function wrapConstructor(hashCons) { const hashC = (msg) => hashCons().update(toBytes(msg)).digest(); const tmp = hashCons(); hashC.outputLen = tmp.outputLen; hashC.blockLen = tmp.blockLen; hashC.create = () => hashCons(); return hashC; } // ../nostr-tools/node_modules/@scure/base/lib/esm/index.js function assertNumber(n) { if (!Number.isSafeInteger(n)) throw new Error(`Wrong integer: ${n}`); } function chain(...args) { const wrap = (a, b) => (c) => a(b(c)); const encode = Array.from(args).reverse().reduce((acc, i3) => acc ? wrap(acc, i3.encode) : i3.encode, void 0); const decode3 = args.reduce((acc, i3) => acc ? wrap(acc, i3.decode) : i3.decode, void 0); return { encode, decode: decode3 }; } function alphabet(alphabet2) { return { encode: (digits) => { if (!Array.isArray(digits) || digits.length && typeof digits[0] !== "number") throw new Error("alphabet.encode input should be an array of numbers"); return digits.map((i3) => { assertNumber(i3); if (i3 < 0 || i3 >= alphabet2.length) throw new Error(`Digit index outside alphabet: ${i3} (alphabet: ${alphabet2.length})`); return alphabet2[i3]; }); }, decode: (input) => { if (!Array.isArray(input) || input.length && typeof input[0] !== "string") throw new Error("alphabet.decode input should be array of strings"); return input.map((letter) => { if (typeof letter !== "string") throw new Error(`alphabet.decode: not string element=${letter}`); const index = alphabet2.indexOf(letter); if (index === -1) throw new Error(`Unknown letter: "${letter}". Allowed: ${alphabet2}`); return index; }); } }; } function join(separator = "") { if (typeof separator !== "string") throw new Error("join separator should be string"); return { encode: (from) => { if (!Array.isArray(from) || from.length && typeof from[0] !== "string") throw new Error("join.encode input should be array of strings"); for (let i3 of from) if (typeof i3 !== "string") throw new Error(`join.encode: non-string input=${i3}`); return from.join(separator); }, decode: (to) => { if (typeof to !== "string") throw new Error("join.decode input should be string"); return to.split(separator); } }; } function padding(bits, chr = "=") { assertNumber(bits); if (typeof chr !== "string") throw new Error("padding chr should be string"); return { encode(data) { if (!Array.isArray(data) || data.length && typeof data[0] !== "string") throw new Error("padding.encode input should be array of strings"); for (let i3 of data) if (typeof i3 !== "string") throw new Error(`padding.encode: non-string input=${i3}`); while (data.length * bits % 8) data.push(chr); return data; }, decode(input) { if (!Array.isArray(input) || input.length && typeof input[0] !== "string") throw new Error("padding.encode input should be array of strings"); for (let i3 of input) if (typeof i3 !== "string") throw new Error(`padding.decode: non-string input=${i3}`); let end = input.length; if (end * bits % 8) throw new Error("Invalid padding: string should have whole number of bytes"); for (; end > 0 && input[end - 1] === chr; end--) { if (!((end - 1) * bits % 8)) throw new Error("Invalid padding: string has too much padding"); } return input.slice(0, end); } }; } function normalize(fn) { if (typeof fn !== "function") throw new Error("normalize fn should be function"); return { encode: (from) => from, decode: (to) => fn(to) }; } function convertRadix(data, from, to) { if (from < 2) throw new Error(`convertRadix: wrong from=${from}, base cannot be less than 2`); if (to < 2) throw new Error(`convertRadix: wrong to=${to}, base cannot be less than 2`); if (!Array.isArray(data)) throw new Error("convertRadix: data should be array"); if (!data.length) return []; let pos = 0; const res = []; const digits = Array.from(data); digits.forEach((d) => { assertNumber(d); if (d < 0 || d >= from) throw new Error(`Wrong integer: ${d}`); }); while (true) { let carry = 0; let done = true; for (let i3 = pos; i3 < digits.length; i3++) { const digit = digits[i3]; const digitBase = from * carry + digit; if (!Number.isSafeInteger(digitBase) || from * carry / from !== carry || digitBase - digit !== from * carry) { throw new Error("convertRadix: carry overflow"); } carry = digitBase % to; digits[i3] = Math.floor(digitBase / to); if (!Number.isSafeInteger(digits[i3]) || digits[i3] * to + carry !== digitBase) throw new Error("convertRadix: carry overflow"); if (!done) continue; else if (!digits[i3]) pos = i3; else done = false; } res.push(carry); if (done) break; } for (let i3 = 0; i3 < data.length - 1 && data[i3] === 0; i3++) res.push(0); return res.reverse(); } var gcd = (a, b) => !b ? a : gcd(b, a % b); var radix2carry = (from, to) => from + (to - gcd(from, to)); function convertRadix2(data, from, to, padding2) { if (!Array.isArray(data)) throw new Error("convertRadix2: data should be array"); if (from <= 0 || from > 32) throw new Error(`convertRadix2: wrong from=${from}`); if (to <= 0 || to > 32) throw new Error(`convertRadix2: wrong to=${to}`); if (radix2carry(from, to) > 32) { throw new Error(`convertRadix2: carry overflow from=${from} to=${to} carryBits=${radix2carry(from, to)}`); } let carry = 0; let pos = 0; const mask = 2 ** to - 1; const res = []; for (const n of data) { assertNumber(n); if (n >= 2 ** from) throw new Error(`convertRadix2: invalid data word=${n} from=${from}`); carry = carry << from | n; if (pos + from > 32) throw new Error(`convertRadix2: carry overflow pos=${pos} from=${from}`); pos += from; for (; pos >= to; pos -= to) res.push((carry >> pos - to & mask) >>> 0); carry &= 2 ** pos - 1; } carry = carry << to - pos & mask; if (!padding2 && pos >= from) throw new Error("Excess padding"); if (!padding2 && carry) throw new Error(`Non-zero padding: ${carry}`); if (padding2 && pos > 0) res.push(carry >>> 0); return res; } function radix(num) { assertNumber(num); return { encode: (bytes3) => { if (!(bytes3 instanceof Uint8Array)) throw new Error("radix.encode input should be Uint8Array"); return convertRadix(Array.from(bytes3), 2 ** 8, num); }, decode: (digits) => { if (!Array.isArray(digits) || digits.length && typeof digits[0] !== "number") throw new Error("radix.decode input should be array of strings"); return Uint8Array.from(convertRadix(digits, num, 2 ** 8)); } }; } function radix2(bits, revPadding = false) { assertNumber(bits); if (bits <= 0 || bits > 32) throw new Error("radix2: bits should be in (0..32]"); if (radix2carry(8, bits) > 32 || radix2carry(bits, 8) > 32) throw new Error("radix2: carry overflow"); return { encode: (bytes3) => { if (!(bytes3 instanceof Uint8Array)) throw new Error("radix2.encode input should be Uint8Array"); return convertRadix2(Array.from(bytes3), 8, bits, !revPadding); }, decode: (digits) => { if (!Array.isArray(digits) || digits.length && typeof digits[0] !== "number") throw new Error("radix2.decode input should be array of strings"); return Uint8Array.from(convertRadix2(digits, bits, 8, revPadding)); } }; } function unsafeWrapper(fn) { if (typeof fn !== "function") throw new Error("unsafeWrapper fn should be function"); return function(...args) { try { return fn.apply(null, args); } catch (e) { } }; } var base16 = chain(radix2(4), alphabet("0123456789ABCDEF"), join("")); var base32 = chain(radix2(5), alphabet("ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"), padding(5), join("")); var base32hex = chain(radix2(5), alphabet("0123456789ABCDEFGHIJKLMNOPQRSTUV"), padding(5), join("")); var base32crockford = chain(radix2(5), alphabet("0123456789ABCDEFGHJKMNPQRSTVWXYZ"), join(""), normalize((s) => s.toUpperCase().replace(/O/g, "0").replace(/[IL]/g, "1"))); var base64 = chain(radix2(6), alphabet("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"), padding(6), join("")); var base64url = chain(radix2(6), alphabet("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"), padding(6), join("")); var genBase58 = (abc) => chain(radix(58), alphabet(abc), join("")); var base58 = genBase58("123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"); var base58flickr = genBase58("123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"); var base58xrp = genBase58("rpshnaf39wBUDNEGHJKLM4PQRST7VWXYZ2bcdeCg65jkm8oFqi1tuvAxyz"); var XMR_BLOCK_LEN = [0, 2, 3, 5, 6, 7, 9, 10, 11]; var base58xmr = { encode(data) { let res = ""; for (let i3 = 0; i3 < data.length; i3 += 8) { const block = data.subarray(i3, i3 + 8); res += base58.encode(block).padStart(XMR_BLOCK_LEN[block.length], "1"); } return res; }, decode(str) { let res = []; for (let i3 = 0; i3 < str.length; i3 += 11) { const slice = str.slice(i3, i3 + 11); const blockLen = XMR_BLOCK_LEN.indexOf(slice.length); const block = base58.decode(slice); for (let j = 0; j < block.length - blockLen; j++) { if (block[j] !== 0) throw new Error("base58xmr: wrong padding"); } res = res.concat(Array.from(block.slice(block.length - blockLen))); } return Uint8Array.from(res); } }; var BECH_ALPHABET = chain(alphabet("qpzry9x8gf2tvdw0s3jn54khce6mua7l"), join("")); var POLYMOD_GENERATORS = [996825010, 642813549, 513874426, 1027748829, 705979059]; function bech32Polymod(pre) { const b = pre >> 25; let chk = (pre & 33554431) << 5; for (let i3 = 0; i3 < POLYMOD_GENERATORS.length; i3++) { if ((b >> i3 & 1) === 1) chk ^= POLYMOD_GENERATORS[i3]; } return chk; } function bechChecksum(prefix, words, encodingConst = 1) { const len = prefix.length; let chk = 1; for (let i3 = 0; i3 < len; i3++) { const c = prefix.charCodeAt(i3); if (c < 33 || c > 126) throw new Error(`Invalid prefix (${prefix})`); chk = bech32Polymod(chk) ^ c >> 5; } chk = bech32Polymod(chk); for (let i3 = 0; i3 < len; i3++) chk = bech32Polymod(chk) ^ prefix.charCodeAt(i3) & 31; for (let v of words) chk = bech32Polymod(chk) ^ v; for (let i3 = 0; i3 < 6; i3++) chk = bech32Polymod(chk); chk ^= encodingConst; return BECH_ALPHABET.encode(convertRadix2([chk % 2 ** 30], 30, 5, false)); } function genBech32(encoding) { const ENCODING_CONST = encoding === "bech32" ? 1 : 734539939; const _words = radix2(5); const fromWords = _words.decode; const toWords = _words.encode; const fromWordsUnsafe = unsafeWrapper(fromWords); function encode(prefix, words, limit = 90) { if (typeof prefix !== "string") throw new Error(`bech32.encode prefix should be string, not ${typeof prefix}`); if (!Array.isArray(words) || words.length && typeof words[0] !== "number") throw new Error(`bech32.encode words should be array of numbers, not ${typeof words}`); const actualLength = prefix.length + 7 + words.length; if (limit !== false && actualLength > limit) throw new TypeError(`Length ${actualLength} exceeds limit ${limit}`); prefix = prefix.toLowerCase(); return `${prefix}1${BECH_ALPHABET.encode(words)}${bechChecksum(prefix, words, ENCODING_CONST)}`; } function decode3(str, limit = 90) { if (typeof str !== "string") throw new Error(`bech32.decode input should be string, not ${typeof str}`); if (str.length < 8 || limit !== false && str.length > limit) throw new TypeError(`Wrong string length: ${str.length} (${str}). Expected (8..${limit})`); const lowered = str.toLowerCase(); if (str !== lowered && str !== str.toUpperCase()) throw new Error(`String must be lowercase or uppercase`); str = lowered; const sepIndex = str.lastIndexOf("1"); if (sepIndex === 0 || sepIndex === -1) throw new Error(`Letter "1" must be present between prefix and data only`); const prefix = str.slice(0, sepIndex); const _words2 = str.slice(sepIndex + 1); if (_words2.length < 6) throw new Error("Data must be at least 6 characters long"); const words = BECH_ALPHABET.decode(_words2).slice(0, -6); const sum = bechChecksum(prefix, words, ENCODING_CONST); if (!_words2.endsWith(sum)) throw new Error(`Invalid checksum in ${str}: expected "${sum}"`); return { prefix, words }; } const decodeUnsafe = unsafeWrapper(decode3); function decodeToBytes(str) { const { prefix, words } = decode3(str, false); return { prefix, words, bytes: fromWords(words) }; } return { encode, decode: decode3, decodeToBytes, decodeUnsafe, fromWords, fromWordsUnsafe, toWords }; } var bech32 = genBech32("bech32"); var bech32m = genBech32("bech32m"); var utf8 = { encode: (data) => new TextDecoder().decode(data), decode: (str) => new TextEncoder().encode(str) }; var hex = chain(radix2(4), alphabet("0123456789abcdef"), join(""), normalize((s) => { if (typeof s !== "string" || s.length % 2) throw new TypeError(`hex.decode: expected string, got ${typeof s} with length ${s.length}`); return s.toLowerCase(); })); var CODERS = { utf8, hex, base16, base32, base64, base64url, base58, base58xmr }; var coderTypeError = `Invalid encoding type. Available types: ${Object.keys(CODERS).join(", ")}`; // ../nostr-tools/lib/esm/nip19.js var utf8Decoder = new TextDecoder("utf-8"); var utf8Encoder = new TextEncoder(); var Bech32MaxSize = 5e3; function integerToUint8Array(number3) { const uint8Array = new Uint8Array(4); uint8Array[0] = number3 >> 24 & 255; uint8Array[1] = number3 >> 16 & 255; uint8Array[2] = number3 >> 8 & 255; uint8Array[3] = number3 & 255; return uint8Array; } function decodeNostrURI(nip19code) { try { if (nip19code.startsWith("nostr:")) nip19code = nip19code.substring(6); return decode(nip19code); } catch (_err) { return { type: "invalid", data: null }; } } function decode(code) { let { prefix, words } = bech32.decode(code, Bech32MaxSize); let data = new Uint8Array(bech32.fromWords(words)); switch (prefix) { case "nprofile": { let tlv = parseTLV(data); if (!tlv[0]?.[0]) throw new Error("missing TLV 0 for nprofile"); if (tlv[0][0].length !== 32) throw new Error("TLV 0 should be 32 bytes"); return { type: "nprofile", data: { pubkey: bytesToHex(tlv[0][0]), relays: tlv[1] ? tlv[1].map((d) => utf8Decoder.decode(d)) : [] } }; } case "nevent": { let tlv = parseTLV(data); if (!tlv[0]?.[0]) throw new Error("missing TLV 0 for nevent"); if (tlv[0][0].length !== 32) throw new Error("TLV 0 should be 32 bytes"); if (tlv[2] && tlv[2][0].length !== 32) throw new Error("TLV 2 should be 32 bytes"); if (tlv[3] && tlv[3][0].length !== 4) throw new Error("TLV 3 should be 4 bytes"); return { type: "nevent", data: { id: bytesToHex(tlv[0][0]), relays: tlv[1] ? tlv[1].map((d) => utf8Decoder.decode(d)) : [], author: tlv[2]?.[0] ? bytesToHex(tlv[2][0]) : void 0, kind: tlv[3]?.[0] ? parseInt(bytesToHex(tlv[3][0]), 16) : void 0 } }; } case "naddr": { let tlv = parseTLV(data); if (!tlv[0]?.[0]) throw new Error("missing TLV 0 for naddr"); if (!tlv[2]?.[0]) throw new Error("missing TLV 2 for naddr"); if (tlv[2][0].length !== 32) throw new Error("TLV 2 should be 32 bytes"); if (!tlv[3]?.[0]) throw new Error("missing TLV 3 for naddr"); if (tlv[3][0].length !== 4) throw new Error("TLV 3 should be 4 bytes"); return { type: "naddr", data: { identifier: utf8Decoder.decode(tlv[0][0]), pubkey: bytesToHex(tlv[2][0]), kind: parseInt(bytesToHex(tlv[3][0]), 16), relays: tlv[1] ? tlv[1].map((d) => utf8Decoder.decode(d)) : [] } }; } case "nsec": return { type: prefix, data }; case "npub": case "note": return { type: prefix, data: bytesToHex(data) }; default: throw new Error(`unknown prefix ${prefix}`); } } function parseTLV(data) { let result = {}; let rest = data; while (rest.length > 0) { let t = rest[0]; let l = rest[1]; let v = rest.slice(2, 2 + l); rest = rest.slice(2 + l); if (v.length < l) throw new Error(`not enough data to read on TLV ${t}`); result[t] = result[t] || []; result[t].push(v); } return result; } function npubEncode(hex2) { return encodeBytes("npub", hexToBytes(hex2)); } function encodeBech32(prefix, data) { let words = bech32.toWords(data); return bech32.encode(prefix, words, Bech32MaxSize); } function encodeBytes(prefix, bytes3) { return encodeBech32(prefix, bytes3); } function nprofileEncode(profile) { let data = encodeTLV({ 0: [hexToBytes(profile.pubkey)], 1: (profile.relays || []).map((url) => utf8Encoder.encode(url)) }); return encodeBech32("nprofile", data); } function neventEncode(event) { let kindArray; if (event.kind !== void 0) { kindArray = integerToUint8Array(event.kind); } let data = encodeTLV({ 0: [hexToBytes(event.id)], 1: (event.relays || []).map((url) => utf8Encoder.encode(url)), 2: event.author ? [hexToBytes(event.author)] : [], 3: kindArray ? [new Uint8Array(kindArray)] : [] }); return encodeBech32("nevent", data); } function naddrEncode(addr) { let kind = new ArrayBuffer(4); new DataView(kind).setUint32(0, addr.kind, false); let data = encodeTLV({ 0: [utf8Encoder.encode(addr.identifier)], 1: (addr.relays || []).map((url) => utf8Encoder.encode(url)), 2: [hexToBytes(addr.pubkey)], 3: [new Uint8Array(kind)] }); return encodeBech32("naddr", data); } function encodeTLV(tlv) { let entries = []; Object.entries(tlv).reverse().forEach(([t, vs]) => { vs.forEach((v) => { let entry = new Uint8Array(v.length + 2); entry.set([parseInt(t)], 0); entry.set([v.length], 1); entry.set(v, 2); entries.push(entry); }); }); return concatBytes(...entries); } // node_modules/idb-keyval/dist/index.js function promisifyRequest(request) { return new Promise((resolve, reject) => { request.oncomplete = request.onsuccess = () => resolve(request.result); request.onabort = request.onerror = () => reject(request.error); }); } function createStore(dbName, storeName) { const request = indexedDB.open(dbName); request.onupgradeneeded = () => request.result.createObjectStore(storeName); const dbp = promisifyRequest(request); return (txMode, callback) => dbp.then((db) => callback(db.transaction(storeName, txMode).objectStore(storeName))); } var defaultGetStoreFunc; function defaultGetStore() { if (!defaultGetStoreFunc) { defaultGetStoreFunc = createStore("keyval-store", "keyval"); } return defaultGetStoreFunc; } function set(key, value, customStore = defaultGetStore()) { return customStore("readwrite", (store) => { store.put(value, key); return promisifyRequest(store.transaction); }); } function setMany(entries, customStore = defaultGetStore()) { return customStore("readwrite", (store) => { entries.forEach((entry) => store.put(entry[1], entry[0])); return promisifyRequest(store.transaction); }); } function getMany(keys, customStore = defaultGetStore()) { return customStore("readonly", (store) => Promise.all(keys.map((key) => promisifyRequest(store.get(key))))); } function del(key, customStore = defaultGetStore()) { return customStore("readwrite", (store) => { store.delete(key); return promisifyRequest(store.transaction); }); } // ../nostr-tools/node_modules/@noble/curves/node_modules/@noble/hashes/esm/_assert.js function number(n) { if (!Number.isSafeInteger(n) || n < 0) throw new Error(`Wrong positive integer: ${n}`); } function bytes(b, ...lengths) { if (!(b instanceof Uint8Array)) throw new Error("Expected Uint8Array"); if (lengths.length > 0 && !lengths.includes(b.length)) throw new Error(`Expected Uint8Array of length ${lengths}, not of length=${b.length}`); } function hash(hash3) { if (typeof hash3 !== "function" || typeof hash3.create !== "function") throw new Error("Hash should be wrapped by utils.wrapConstructor"); number(hash3.outputLen); number(hash3.blockLen); } function exists(instance, checkFinished = true) { if (instance.destroyed) throw new Error("Hash instance has been destroyed"); if (checkFinished && instance.finished) throw new Error("Hash#digest() has already been called"); } function output(out, instance) { bytes(out); const min = instance.outputLen; if (out.length < min) { throw new Error(`digestInto() expects output buffer of length at least ${min}`); } } // ../nostr-tools/node_modules/@noble/curves/node_modules/@noble/hashes/esm/crypto.js var crypto2 = typeof globalThis === "object" && "crypto" in globalThis ? globalThis.crypto : void 0; // ../nostr-tools/node_modules/@noble/curves/node_modules/@noble/hashes/esm/utils.js var u8a2 = (a) => a instanceof Uint8Array; var createView2 = (arr) => new DataView(arr.buffer, arr.byteOffset, arr.byteLength); var rotr2 = (word, shift) => word << 32 - shift | word >>> shift; var isLE2 = new Uint8Array(new Uint32Array([287454020]).buffer)[0] === 68; if (!isLE2) throw new Error("Non little-endian hardware is not supported"); function utf8ToBytes2(str) { if (typeof str !== "string") throw new Error(`utf8ToBytes expected string, got ${typeof str}`); return new Uint8Array(new TextEncoder().encode(str)); } function toBytes2(data) { if (typeof data === "string") data = utf8ToBytes2(data); if (!u8a2(data)) throw new Error(`expected Uint8Array, got ${typeof data}`); return data; } function concatBytes2(...arrays) { const r = new Uint8Array(arrays.reduce((sum, a) => sum + a.length, 0)); let pad = 0; arrays.forEach((a) => { if (!u8a2(a)) throw new Error("Uint8Array expected"); r.set(a, pad); pad += a.length; }); return r; } var Hash2 = class { clone() { return this._cloneInto(); } }; var toStr = {}.toString; function wrapConstructor2(hashCons) { const hashC = (msg) => hashCons().update(toBytes2(msg)).digest(); const tmp = hashCons(); hashC.outputLen = tmp.outputLen; hashC.blockLen = tmp.blockLen; hashC.create = () => hashCons(); return hashC; } function randomBytes(bytesLength = 32) { if (crypto2 && typeof crypto2.getRandomValues === "function") { return crypto2.getRandomValues(new Uint8Array(bytesLength)); } throw new Error("crypto.getRandomValues must be defined"); } // ../nostr-tools/node_modules/@noble/curves/node_modules/@noble/hashes/esm/_sha2.js function setBigUint64(view, byteOffset, value, isLE3) { if (typeof view.setBigUint64 === "function") return view.setBigUint64(byteOffset, value, isLE3); const _32n = BigInt(32); const _u32_max = BigInt(4294967295); const wh = Number(value >> _32n & _u32_max); const wl = Number(value & _u32_max); const h = isLE3 ? 4 : 0; const l = isLE3 ? 0 : 4; view.setUint32(byteOffset + h, wh, isLE3); view.setUint32(byteOffset + l, wl, isLE3); } var SHA2 = class extends Hash2 { constructor(blockLen, outputLen, padOffset, isLE3) { super(); this.blockLen = blockLen; this.outputLen = outputLen; this.padOffset = padOffset; this.isLE = isLE3; this.finished = false; this.length = 0; this.pos = 0; this.destroyed = false; this.buffer = new Uint8Array(blockLen); this.view = createView2(this.buffer); } update(data) { exists(this); const { view, buffer, blockLen } = this; data = toBytes2(data); const len = data.length; for (let pos = 0; pos < len; ) { const take = Math.min(blockLen - this.pos, len - pos); if (take === blockLen) { const dataView = createView2(data); for (; blockLen <= len - pos; pos += blockLen) this.process(dataView, pos); continue; } buffer.set(data.subarray(pos, pos + take), this.pos); this.pos += take; pos += take; if (this.pos === blockLen) { this.process(view, 0); this.pos = 0; } } this.length += data.length; this.roundClean(); return this; } digestInto(out) { exists(this); output(out, this); this.finished = true; const { buffer, view, blockLen, isLE: isLE3 } = this; let { pos } = this; buffer[pos++] = 128; this.buffer.subarray(pos).fill(0); if (this.padOffset > blockLen - pos) { this.process(view, 0); pos = 0; } for (let i3 = pos; i3 < blockLen; i3++) buffer[i3] = 0; setBigUint64(view, blockLen - 8, BigInt(this.length * 8), isLE3); this.process(view, 0); const oview = createView2(out); const len = this.outputLen; if (len % 4) throw new Error("_sha2: outputLen should be aligned to 32bit"); const outLen = len / 4; const state = this.get(); if (outLen > state.length) throw new Error("_sha2: outputLen bigger than state"); for (let i3 = 0; i3 < outLen; i3++) oview.setUint32(4 * i3, state[i3], isLE3); } digest() { const { buffer, outputLen } = this; this.digestInto(buffer); const res = buffer.slice(0, outputLen); this.destroy(); return res; } _cloneInto(to) { to || (to = new this.constructor()); to.set(...this.get()); const { blockLen, buffer, length, finished, destroyed, pos } = this; to.length = length; to.pos = pos; to.finished = finished; to.destroyed = destroyed; if (length % blockLen) to.buffer.set(buffer); return to; } }; // ../nostr-tools/node_modules/@noble/curves/node_modules/@noble/hashes/esm/sha256.js var Chi = (a, b, c) => a & b ^ ~a & c; var Maj = (a, b, c) => a & b ^ a & c ^ b & c; var SHA256_K = /* @__PURE__ */ new Uint32Array([ 1116352408, 1899447441, 3049323471, 3921009573, 961987163, 1508970993, 2453635748, 2870763221, 3624381080, 310598401, 607225278, 1426881987, 1925078388, 2162078206, 2614888103, 3248222580, 3835390401, 4022224774, 264347078, 604807628, 770255983, 1249150122, 1555081692, 1996064986, 2554220882, 2821834349, 2952996808, 3210313671, 3336571891, 3584528711, 113926993, 338241895, 666307205, 773529912, 1294757372, 1396182291, 1695183700, 1986661051, 2177026350, 2456956037, 2730485921, 2820302411, 3259730800, 3345764771, 3516065817, 3600352804, 4094571909, 275423344, 430227734, 506948616, 659060556, 883997877, 958139571, 1322822218, 1537002063, 1747873779, 1955562222, 2024104815, 2227730452, 2361852424, 2428436474, 2756734187, 3204031479, 3329325298 ]); var IV = /* @__PURE__ */ new Uint32Array([ 1779033703, 3144134277, 1013904242, 2773480762, 1359893119, 2600822924, 528734635, 1541459225 ]); var SHA256_W = /* @__PURE__ */ new Uint32Array(64); var SHA256 = class extends SHA2 { constructor() { super(64, 32, 8, false); this.A = IV[0] | 0; this.B = IV[1] | 0; this.C = IV[2] | 0; this.D = IV[3] | 0; this.E = IV[4] | 0; this.F = IV[5] | 0; this.G = IV[6] | 0; this.H = IV[7] | 0; } get() { const { A, B, C, D, E, F, G, H } = this; return [A, B, C, D, E, F, G, H]; } set(A, B, C, D, E, F, G, H) { this.A = A | 0; this.B = B | 0; this.C = C | 0; this.D = D | 0; this.E = E | 0; this.F = F | 0; this.G = G | 0; this.H = H | 0; } process(view, offset) { for (let i3 = 0; i3 < 16; i3++, offset += 4) SHA256_W[i3] = view.getUint32(offset, false); for (let i3 = 16; i3 < 64; i3++) { const W15 = SHA256_W[i3 - 15]; const W2 = SHA256_W[i3 - 2]; const s0 = rotr2(W15, 7) ^ rotr2(W15, 18) ^ W15 >>> 3; const s1 = rotr2(W2, 17) ^ rotr2(W2, 19) ^ W2 >>> 10; SHA256_W[i3] = s1 + SHA256_W[i3 - 7] + s0 + SHA256_W[i3 - 16] | 0; } let { A, B, C, D, E, F, G, H } = this; for (let i3 = 0; i3 < 64; i3++) { const sigma1 = rotr2(E, 6) ^ rotr2(E, 11) ^ rotr2(E, 25); const T1 = H + sigma1 + Chi(E, F, G) + SHA256_K[i3] + SHA256_W[i3] | 0; const sigma0 = rotr2(A, 2) ^ rotr2(A, 13) ^ rotr2(A, 22); const T2 = sigma0 + Maj(A, B, C) | 0; H = G; G = F; F = E; E = D + T1 | 0; D = C; C = B; B = A; A = T1 + T2 | 0; } A = A + this.A | 0; B = B + this.B | 0; C = C + this.C | 0; D = D + this.D | 0; E = E + this.E | 0; F = F + this.F | 0; G = G + this.G | 0; H = H + this.H | 0; this.set(A, B, C, D, E, F, G, H); } roundClean() { SHA256_W.fill(0); } destroy() { this.set(0, 0, 0, 0, 0, 0, 0, 0); this.buffer.fill(0); } }; var sha256 = /* @__PURE__ */ wrapConstructor2(() => new SHA256()); // ../nostr-tools/node_modules/@noble/curves/esm/abstract/utils.js var utils_exports = {}; __export(utils_exports, { bitGet: () => bitGet, bitLen: () => bitLen, bitMask: () => bitMask, bitSet: () => bitSet, bytesToHex: () => bytesToHex2, bytesToNumberBE: () => bytesToNumberBE, bytesToNumberLE: () => bytesToNumberLE, concatBytes: () => concatBytes3, createHmacDrbg: () => createHmacDrbg, ensureBytes: () => ensureBytes, equalBytes: () => equalBytes, hexToBytes: () => hexToBytes2, hexToNumber: () => hexToNumber, numberToBytesBE: () => numberToBytesBE, numberToBytesLE: () => numberToBytesLE, numberToHexUnpadded: () => numberToHexUnpadded, numberToVarBytesBE: () => numberToVarBytesBE, utf8ToBytes: () => utf8ToBytes3, validateObject: () => validateObject }); var _0n = BigInt(0); var _1n = BigInt(1); var _2n = BigInt(2); var u8a3 = (a) => a instanceof Uint8Array; var hexes2 = /* @__PURE__ */ Array.from({ length: 256 }, (_, i3) => i3.toString(16).padStart(2, "0")); function bytesToHex2(bytes3) { if (!u8a3(bytes3)) throw new Error("Uint8Array expected"); let hex2 = ""; for (let i3 = 0; i3 < bytes3.length; i3++) { hex2 += hexes2[bytes3[i3]]; } return hex2; } function numberToHexUnpadded(num) { const hex2 = num.toString(16); return hex2.length & 1 ? `0${hex2}` : hex2; } function hexToNumber(hex2) { if (typeof hex2 !== "string") throw new Error("hex string expected, got " + typeof hex2); return BigInt(hex2 === "" ? "0" : `0x${hex2}`); } function hexToBytes2(hex2) { if (typeof hex2 !== "string") throw new Error("hex string expected, got " + typeof hex2); const len = hex2.length; if (len % 2) throw new Error("padded hex string expected, got unpadded hex of length " + len); const array = new Uint8Array(len / 2); for (let i3 = 0; i3 < array.length; i3++) { const j = i3 * 2; const hexByte = hex2.slice(j, j + 2); const byte = Number.parseInt(hexByte, 16); if (Number.isNaN(byte) || byte < 0) throw new Error("Invalid byte sequence"); array[i3] = byte; } return array; } function bytesToNumberBE(bytes3) { return hexToNumber(bytesToHex2(bytes3)); } function bytesToNumberLE(bytes3) { if (!u8a3(bytes3)) throw new Error("Uint8Array expected"); return hexToNumber(bytesToHex2(Uint8Array.from(bytes3).reverse())); } function numberToBytesBE(n, len) { return hexToBytes2(n.toString(16).padStart(len * 2, "0")); } function numberToBytesLE(n, len) { return numberToBytesBE(n, len).reverse(); } function numberToVarBytesBE(n) { return hexToBytes2(numberToHexUnpadded(n)); } function ensureBytes(title, hex2, expectedLength) { let res; if (typeof hex2 === "string") { try { res = hexToBytes2(hex2); } catch (e) { throw new Error(`${title} must be valid hex string, got "${hex2}". Cause: ${e}`); } } else if (u8a3(hex2)) { res = Uint8Array.from(hex2); } else { throw new Error(`${title} must be hex string or Uint8Array`); } const len = res.length; if (typeof expectedLength === "number" && len !== expectedLength) throw new Error(`${title} expected ${expectedLength} bytes, got ${len}`); return res; } function concatBytes3(...arrays) { const r = new Uint8Array(arrays.reduce((sum, a) => sum + a.length, 0)); let pad = 0; arrays.forEach((a) => { if (!u8a3(a)) throw new Error("Uint8Array expected"); r.set(a, pad); pad += a.length; }); return r; } function equalBytes(b1, b2) { if (b1.length !== b2.length) return false; for (let i3 = 0; i3 < b1.length; i3++) if (b1[i3] !== b2[i3]) return false; return true; } function utf8ToBytes3(str) { if (typeof str !== "string") throw new Error(`utf8ToBytes expected string, got ${typeof str}`); return new Uint8Array(new TextEncoder().encode(str)); } function bitLen(n) { let len; for (len = 0; n > _0n; n >>= _1n, len += 1) ; return len; } function bitGet(n, pos) { return n >> BigInt(pos) & _1n; } var bitSet = (n, pos, value) => { return n | (value ? _1n : _0n) << BigInt(pos); }; var bitMask = (n) => (_2n << BigInt(n - 1)) - _1n; var u8n = (data) => new Uint8Array(data); var u8fr = (arr) => Uint8Array.from(arr); function createHmacDrbg(hashLen, qByteLen, hmacFn) { if (typeof hashLen !== "number" || hashLen < 2) throw new Error("hashLen must be a number"); if (typeof qByteLen !== "number" || qByteLen < 2) throw new Error("qByteLen must be a number"); if (typeof hmacFn !== "function") throw new Error("hmacFn must be a function"); let v = u8n(hashLen); let k = u8n(hashLen); let i3 = 0; const reset = () => { v.fill(1); k.fill(0); i3 = 0; }; const h = (...b) => hmacFn(k, v, ...b); const reseed = (seed = u8n()) => { k = h(u8fr([0]), seed); v = h(); if (seed.length === 0) return; k = h(u8fr([1]), seed); v = h(); }; const gen = () => { if (i3++ >= 1e3) throw new Error("drbg: tried 1000 values"); let len = 0; const out = []; while (len < qByteLen) { v = h(); const sl = v.slice(); out.push(sl); len += v.length; } return concatBytes3(...out); }; const genUntil = (seed, pred) => { reset(); reseed(seed); let res = void 0; while (!(res = pred(gen()))) reseed(); reset(); return res; }; return genUntil; } var validatorFns = { bigint: (val) => typeof val === "bigint", function: (val) => typeof val === "function", boolean: (val) => typeof val === "boolean", string: (val) => typeof val === "string", stringOrUint8Array: (val) => typeof val === "string" || val instanceof Uint8Array, isSafeInteger: (val) => Number.isSafeInteger(val), array: (val) => Array.isArray(val), field: (val, object) => object.Fp.isValid(val), hash: (val) => typeof val === "function" && Number.isSafeInteger(val.outputLen) }; function validateObject(object, validators, optValidators = {}) { const checkField = (fieldName, type, isOptional) => { const checkVal = validatorFns[type]; if (typeof checkVal !== "function") throw new Error(`Invalid validator "${type}", expected function`); const val = object[fieldName]; if (isOptional && val === void 0) return; if (!checkVal(val, object)) { throw new Error(`Invalid param ${String(fieldName)}=${val} (${typeof val}), expected ${type}`); } }; for (const [fieldName, type] of Object.entries(validators)) checkField(fieldName, type, false); for (const [fieldName, type] of Object.entries(optValidators)) checkField(fieldName, type, true); return object; } // ../nostr-tools/node_modules/@noble/curves/esm/abstract/modular.js var _0n2 = BigInt(0); var _1n2 = BigInt(1); var _2n2 = BigInt(2); var _3n = BigInt(3); var _4n = BigInt(4); var _5n = BigInt(5); var _8n = BigInt(8); var _9n = BigInt(9); var _16n = BigInt(16); function mod(a, b) { const result = a % b; return result >= _0n2 ? result : b +