From 16a95facc59e34495ed1bf3aa7b180c98d29877b Mon Sep 17 00:00:00 2001 From: Gigi Date: Thu, 2 Oct 2025 07:18:18 +0200 Subject: [PATCH] chore: remove vite cache files from tracking - Remove .vite/deps_temp_* files that were previously tracked - These files are now properly ignored by .gitignore - Clean up repository to exclude build artifacts --- .../deps_temp_742205d0/applesauce-core.js | 38 - .../deps_temp_742205d0/applesauce-core.js.map | 7 - .../deps_temp_742205d0/applesauce-react.js | 14995 ----------- .../applesauce-react.js.map | 7 - .../deps_temp_742205d0/chunk-DC5AMYBS.js | 39 - .../deps_temp_742205d0/chunk-DC5AMYBS.js.map | 7 - .../deps_temp_742205d0/chunk-ESJ34HX7.js | 16111 ------------ .../deps_temp_742205d0/chunk-ESJ34HX7.js.map | 7 - .../deps_temp_742205d0/chunk-NUMECXU6.js | 21628 ---------------- .../deps_temp_742205d0/chunk-NUMECXU6.js.map | 7 - .../deps_temp_742205d0/chunk-RLJ2RCJQ.js | 1906 -- .../deps_temp_742205d0/chunk-RLJ2RCJQ.js.map | 7 - .../deps_temp_742205d0/chunk-S725DACQ.js | 928 - .../deps_temp_742205d0/chunk-S725DACQ.js.map | 7 - .../.vite/deps_temp_742205d0/package.json | 3 - .../.vite/deps_temp_742205d0/react-dom.js | 7 - .../.vite/deps_temp_742205d0/react-dom.js.map | 7 - .../deps_temp_742205d0/react-dom_client.js | 39 - .../react-dom_client.js.map | 7 - .../.vite/deps_temp_742205d0/react.js | 6 - .../.vite/deps_temp_742205d0/react.js.map | 7 - .../react_jsx-dev-runtime.js | 913 - .../react_jsx-dev-runtime.js.map | 7 - .../deps_temp_742205d0/react_jsx-runtime.js | 7 - .../react_jsx-runtime.js.map | 7 - 25 files changed, 56704 deletions(-) delete mode 100644 node_modules/.vite/deps_temp_742205d0/applesauce-core.js delete mode 100644 node_modules/.vite/deps_temp_742205d0/applesauce-core.js.map delete mode 100644 node_modules/.vite/deps_temp_742205d0/applesauce-react.js delete mode 100644 node_modules/.vite/deps_temp_742205d0/applesauce-react.js.map delete mode 100644 node_modules/.vite/deps_temp_742205d0/chunk-DC5AMYBS.js delete mode 100644 node_modules/.vite/deps_temp_742205d0/chunk-DC5AMYBS.js.map delete mode 100644 node_modules/.vite/deps_temp_742205d0/chunk-ESJ34HX7.js delete mode 100644 node_modules/.vite/deps_temp_742205d0/chunk-ESJ34HX7.js.map delete mode 100644 node_modules/.vite/deps_temp_742205d0/chunk-NUMECXU6.js delete mode 100644 node_modules/.vite/deps_temp_742205d0/chunk-NUMECXU6.js.map delete mode 100644 node_modules/.vite/deps_temp_742205d0/chunk-RLJ2RCJQ.js delete mode 100644 node_modules/.vite/deps_temp_742205d0/chunk-RLJ2RCJQ.js.map delete mode 100644 node_modules/.vite/deps_temp_742205d0/chunk-S725DACQ.js delete mode 100644 node_modules/.vite/deps_temp_742205d0/chunk-S725DACQ.js.map delete mode 100644 node_modules/.vite/deps_temp_742205d0/package.json delete mode 100644 node_modules/.vite/deps_temp_742205d0/react-dom.js delete mode 100644 node_modules/.vite/deps_temp_742205d0/react-dom.js.map delete mode 100644 node_modules/.vite/deps_temp_742205d0/react-dom_client.js delete mode 100644 node_modules/.vite/deps_temp_742205d0/react-dom_client.js.map delete mode 100644 node_modules/.vite/deps_temp_742205d0/react.js delete mode 100644 node_modules/.vite/deps_temp_742205d0/react.js.map delete mode 100644 node_modules/.vite/deps_temp_742205d0/react_jsx-dev-runtime.js delete mode 100644 node_modules/.vite/deps_temp_742205d0/react_jsx-dev-runtime.js.map delete mode 100644 node_modules/.vite/deps_temp_742205d0/react_jsx-runtime.js delete mode 100644 node_modules/.vite/deps_temp_742205d0/react_jsx-runtime.js.map diff --git a/node_modules/.vite/deps_temp_742205d0/applesauce-core.js b/node_modules/.vite/deps_temp_742205d0/applesauce-core.js deleted file mode 100644 index 59ea8d6e..00000000 --- a/node_modules/.vite/deps_temp_742205d0/applesauce-core.js +++ /dev/null @@ -1,38 +0,0 @@ -import { - EventSet, - EventStore, - TimeoutError, - defined, - firstValueFrom, - getObservableValue, - helpers_exports, - lastValueFrom, - logger, - mapEventsToStore, - mapEventsToTimeline, - models_exports, - simpleTimeout, - watchEventUpdates, - watchEventsUpdates, - withImmediateValueOrDefault -} from "./chunk-ESJ34HX7.js"; -import "./chunk-DC5AMYBS.js"; -export { - EventSet, - EventStore, - helpers_exports as Helpers, - models_exports as Models, - TimeoutError, - defined, - firstValueFrom, - getObservableValue, - lastValueFrom, - logger, - mapEventsToStore, - mapEventsToTimeline, - simpleTimeout, - watchEventUpdates, - watchEventsUpdates, - withImmediateValueOrDefault -}; -//# sourceMappingURL=applesauce-core.js.map diff --git a/node_modules/.vite/deps_temp_742205d0/applesauce-core.js.map b/node_modules/.vite/deps_temp_742205d0/applesauce-core.js.map deleted file mode 100644 index 98652118..00000000 --- a/node_modules/.vite/deps_temp_742205d0/applesauce-core.js.map +++ /dev/null @@ -1,7 +0,0 @@ -{ - "version": 3, - "sources": [], - "sourcesContent": [], - "mappings": "", - "names": [] -} diff --git a/node_modules/.vite/deps_temp_742205d0/applesauce-react.js b/node_modules/.vite/deps_temp_742205d0/applesauce-react.js deleted file mode 100644 index a5515a7c..00000000 --- a/node_modules/.vite/deps_temp_742205d0/applesauce-react.js +++ /dev/null @@ -1,14995 +0,0 @@ -import { - require_jsx_runtime -} from "./chunk-S725DACQ.js"; -import { - require_react -} from "./chunk-RLJ2RCJQ.js"; -import { - BehaviorSubject, - Hash, - IMAGE_EXT, - NEVER, - Subject, - abytes, - aexists, - aoutput, - bytesToHex, - catchError, - clean, - convertToUrl, - createHasher, - createView, - decode, - distinctUntilChanged, - finalize, - getEmojiTag, - getHashtagTag, - getOrComputeCachedValue, - getURLFilename, - isObservable, - map, - of, - parseBolt11, - randomBytes, - require_hash_sum, - rotr, - switchMap, - toBytes, - withImmediateValueOrDefault -} from "./chunk-ESJ34HX7.js"; -import { - __commonJS, - __export, - __publicField, - __toESM -} from "./chunk-DC5AMYBS.js"; - -// node_modules/extend/index.js -var require_extend = __commonJS({ - "node_modules/extend/index.js"(exports, module) { - "use strict"; - var hasOwn = Object.prototype.hasOwnProperty; - var toStr = Object.prototype.toString; - var defineProperty = Object.defineProperty; - var gOPD = Object.getOwnPropertyDescriptor; - var isArray = function isArray2(arr) { - if (typeof Array.isArray === "function") { - return Array.isArray(arr); - } - return toStr.call(arr) === "[object Array]"; - }; - var isPlainObject2 = function isPlainObject3(obj) { - if (!obj || toStr.call(obj) !== "[object Object]") { - return false; - } - var hasOwnConstructor = hasOwn.call(obj, "constructor"); - var hasIsPrototypeOf = obj.constructor && obj.constructor.prototype && hasOwn.call(obj.constructor.prototype, "isPrototypeOf"); - if (obj.constructor && !hasOwnConstructor && !hasIsPrototypeOf) { - return false; - } - var key; - for (key in obj) { - } - return typeof key === "undefined" || hasOwn.call(obj, key); - }; - var setProperty = function setProperty2(target, options) { - if (defineProperty && options.name === "__proto__") { - defineProperty(target, options.name, { - enumerable: true, - configurable: true, - value: options.newValue, - writable: true - }); - } else { - target[options.name] = options.newValue; - } - }; - var getProperty = function getProperty2(obj, name) { - if (name === "__proto__") { - if (!hasOwn.call(obj, name)) { - return void 0; - } else if (gOPD) { - return gOPD(obj, name).value; - } - } - return obj[name]; - }; - module.exports = function extend2() { - var options, name, src, copy, copyIsArray, clone; - var target = arguments[0]; - var i = 1; - var length = arguments.length; - var deep = false; - if (typeof target === "boolean") { - deep = target; - target = arguments[1] || {}; - i = 2; - } - if (target == null || typeof target !== "object" && typeof target !== "function") { - target = {}; - } - for (; i < length; ++i) { - options = arguments[i]; - if (options != null) { - for (name in options) { - src = getProperty(target, name); - copy = getProperty(options, name); - if (target !== copy) { - if (deep && copy && (isPlainObject2(copy) || (copyIsArray = isArray(copy)))) { - if (copyIsArray) { - copyIsArray = false; - clone = src && isArray(src) ? src : []; - } else { - clone = src && isPlainObject2(src) ? src : {}; - } - setProperty(target, { name, newValue: extend2(deep, clone, copy) }); - } else if (typeof copy !== "undefined") { - setProperty(target, { name, newValue: copy }); - } - } - } - } - } - return target; - }; - } -}); - -// node_modules/base64-js/index.js -var require_base64_js = __commonJS({ - "node_modules/base64-js/index.js"(exports) { - "use strict"; - exports.byteLength = byteLength; - exports.toByteArray = toByteArray; - exports.fromByteArray = fromByteArray; - var lookup = []; - var revLookup = []; - var Arr = typeof Uint8Array !== "undefined" ? Uint8Array : Array; - var code = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; - for (i = 0, len = code.length; i < len; ++i) { - lookup[i] = code[i]; - revLookup[code.charCodeAt(i)] = i; - } - var i; - var len; - revLookup["-".charCodeAt(0)] = 62; - revLookup["_".charCodeAt(0)] = 63; - function getLens(b64) { - var len2 = b64.length; - if (len2 % 4 > 0) { - throw new Error("Invalid string. Length must be a multiple of 4"); - } - var validLen = b64.indexOf("="); - if (validLen === -1) validLen = len2; - var placeHoldersLen = validLen === len2 ? 0 : 4 - validLen % 4; - return [validLen, placeHoldersLen]; - } - function byteLength(b64) { - var lens = getLens(b64); - var validLen = lens[0]; - var placeHoldersLen = lens[1]; - return (validLen + placeHoldersLen) * 3 / 4 - placeHoldersLen; - } - function _byteLength(b64, validLen, placeHoldersLen) { - return (validLen + placeHoldersLen) * 3 / 4 - placeHoldersLen; - } - function toByteArray(b64) { - var tmp; - var lens = getLens(b64); - var validLen = lens[0]; - var placeHoldersLen = lens[1]; - var arr = new Arr(_byteLength(b64, validLen, placeHoldersLen)); - var curByte = 0; - var len2 = placeHoldersLen > 0 ? validLen - 4 : validLen; - var i2; - for (i2 = 0; i2 < len2; i2 += 4) { - tmp = revLookup[b64.charCodeAt(i2)] << 18 | revLookup[b64.charCodeAt(i2 + 1)] << 12 | revLookup[b64.charCodeAt(i2 + 2)] << 6 | revLookup[b64.charCodeAt(i2 + 3)]; - arr[curByte++] = tmp >> 16 & 255; - arr[curByte++] = tmp >> 8 & 255; - arr[curByte++] = tmp & 255; - } - if (placeHoldersLen === 2) { - tmp = revLookup[b64.charCodeAt(i2)] << 2 | revLookup[b64.charCodeAt(i2 + 1)] >> 4; - arr[curByte++] = tmp & 255; - } - if (placeHoldersLen === 1) { - tmp = revLookup[b64.charCodeAt(i2)] << 10 | revLookup[b64.charCodeAt(i2 + 1)] << 4 | revLookup[b64.charCodeAt(i2 + 2)] >> 2; - arr[curByte++] = tmp >> 8 & 255; - arr[curByte++] = tmp & 255; - } - return arr; - } - function tripletToBase64(num) { - return lookup[num >> 18 & 63] + lookup[num >> 12 & 63] + lookup[num >> 6 & 63] + lookup[num & 63]; - } - function encodeChunk(uint8, start, end) { - var tmp; - var output = []; - for (var i2 = start; i2 < end; i2 += 3) { - tmp = (uint8[i2] << 16 & 16711680) + (uint8[i2 + 1] << 8 & 65280) + (uint8[i2 + 2] & 255); - output.push(tripletToBase64(tmp)); - } - return output.join(""); - } - function fromByteArray(uint8) { - var tmp; - var len2 = uint8.length; - var extraBytes = len2 % 3; - var parts = []; - var maxChunkLength = 16383; - for (var i2 = 0, len22 = len2 - extraBytes; i2 < len22; i2 += maxChunkLength) { - parts.push(encodeChunk(uint8, i2, i2 + maxChunkLength > len22 ? len22 : i2 + maxChunkLength)); - } - if (extraBytes === 1) { - tmp = uint8[len2 - 1]; - parts.push( - lookup[tmp >> 2] + lookup[tmp << 4 & 63] + "==" - ); - } else if (extraBytes === 2) { - tmp = (uint8[len2 - 2] << 8) + uint8[len2 - 1]; - parts.push( - lookup[tmp >> 10] + lookup[tmp >> 4 & 63] + lookup[tmp << 2 & 63] + "=" - ); - } - return parts.join(""); - } - } -}); - -// node_modules/ieee754/index.js -var require_ieee754 = __commonJS({ - "node_modules/ieee754/index.js"(exports) { - exports.read = function(buffer, offset, isLE, mLen, nBytes) { - var e, m; - var eLen = nBytes * 8 - mLen - 1; - var eMax = (1 << eLen) - 1; - var eBias = eMax >> 1; - var nBits = -7; - var i = isLE ? nBytes - 1 : 0; - var d = isLE ? -1 : 1; - var s = buffer[offset + i]; - i += d; - e = s & (1 << -nBits) - 1; - s >>= -nBits; - nBits += eLen; - for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8) { - } - m = e & (1 << -nBits) - 1; - e >>= -nBits; - nBits += mLen; - for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8) { - } - if (e === 0) { - e = 1 - eBias; - } else if (e === eMax) { - return m ? NaN : (s ? -1 : 1) * Infinity; - } else { - m = m + Math.pow(2, mLen); - e = e - eBias; - } - return (s ? -1 : 1) * m * Math.pow(2, e - mLen); - }; - exports.write = function(buffer, value, offset, isLE, mLen, nBytes) { - var e, m, c; - var eLen = nBytes * 8 - mLen - 1; - var eMax = (1 << eLen) - 1; - var eBias = eMax >> 1; - var rt = mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0; - var i = isLE ? 0 : nBytes - 1; - var d = isLE ? 1 : -1; - var s = value < 0 || value === 0 && 1 / value < 0 ? 1 : 0; - value = Math.abs(value); - if (isNaN(value) || value === Infinity) { - m = isNaN(value) ? 1 : 0; - e = eMax; - } else { - e = Math.floor(Math.log(value) / Math.LN2); - if (value * (c = Math.pow(2, -e)) < 1) { - e--; - c *= 2; - } - if (e + eBias >= 1) { - value += rt / c; - } else { - value += rt * Math.pow(2, 1 - eBias); - } - if (value * c >= 2) { - e++; - c /= 2; - } - if (e + eBias >= eMax) { - m = 0; - e = eMax; - } else if (e + eBias >= 1) { - m = (value * c - 1) * Math.pow(2, mLen); - e = e + eBias; - } else { - m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen); - e = 0; - } - } - for (; mLen >= 8; buffer[offset + i] = m & 255, i += d, m /= 256, mLen -= 8) { - } - e = e << mLen | m; - eLen += mLen; - for (; eLen > 0; buffer[offset + i] = e & 255, i += d, e /= 256, eLen -= 8) { - } - buffer[offset + i - d] |= s * 128; - }; - } -}); - -// node_modules/buffer/index.js -var require_buffer = __commonJS({ - "node_modules/buffer/index.js"(exports) { - "use strict"; - var base64 = require_base64_js(); - var ieee754 = require_ieee754(); - var customInspectSymbol = typeof Symbol === "function" && typeof Symbol["for"] === "function" ? Symbol["for"]("nodejs.util.inspect.custom") : null; - exports.Buffer = Buffer4; - exports.SlowBuffer = SlowBuffer; - exports.INSPECT_MAX_BYTES = 50; - var K_MAX_LENGTH = 2147483647; - exports.kMaxLength = K_MAX_LENGTH; - Buffer4.TYPED_ARRAY_SUPPORT = typedArraySupport(); - if (!Buffer4.TYPED_ARRAY_SUPPORT && typeof console !== "undefined" && typeof console.error === "function") { - console.error( - "This browser lacks typed array (Uint8Array) support which is required by `buffer` v5.x. Use `buffer` v4.x if you require old browser support." - ); - } - function typedArraySupport() { - try { - const arr = new Uint8Array(1); - const proto = { foo: function() { - return 42; - } }; - Object.setPrototypeOf(proto, Uint8Array.prototype); - Object.setPrototypeOf(arr, proto); - return arr.foo() === 42; - } catch (e) { - return false; - } - } - Object.defineProperty(Buffer4.prototype, "parent", { - enumerable: true, - get: function() { - if (!Buffer4.isBuffer(this)) return void 0; - return this.buffer; - } - }); - Object.defineProperty(Buffer4.prototype, "offset", { - enumerable: true, - get: function() { - if (!Buffer4.isBuffer(this)) return void 0; - return this.byteOffset; - } - }); - function createBuffer(length) { - if (length > K_MAX_LENGTH) { - throw new RangeError('The value "' + length + '" is invalid for option "size"'); - } - const buf = new Uint8Array(length); - Object.setPrototypeOf(buf, Buffer4.prototype); - return buf; - } - function Buffer4(arg, encodingOrOffset, length) { - if (typeof arg === "number") { - if (typeof encodingOrOffset === "string") { - throw new TypeError( - 'The "string" argument must be of type string. Received type number' - ); - } - return allocUnsafe(arg); - } - return from(arg, encodingOrOffset, length); - } - Buffer4.poolSize = 8192; - function from(value, encodingOrOffset, length) { - if (typeof value === "string") { - return fromString(value, encodingOrOffset); - } - if (ArrayBuffer.isView(value)) { - return fromArrayView(value); - } - if (value == null) { - throw new TypeError( - "The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type " + typeof value - ); - } - if (isInstance(value, ArrayBuffer) || value && isInstance(value.buffer, ArrayBuffer)) { - return fromArrayBuffer(value, encodingOrOffset, length); - } - if (typeof SharedArrayBuffer !== "undefined" && (isInstance(value, SharedArrayBuffer) || value && isInstance(value.buffer, SharedArrayBuffer))) { - return fromArrayBuffer(value, encodingOrOffset, length); - } - if (typeof value === "number") { - throw new TypeError( - 'The "value" argument must not be of type number. Received type number' - ); - } - const valueOf = value.valueOf && value.valueOf(); - if (valueOf != null && valueOf !== value) { - return Buffer4.from(valueOf, encodingOrOffset, length); - } - const b = fromObject(value); - if (b) return b; - if (typeof Symbol !== "undefined" && Symbol.toPrimitive != null && typeof value[Symbol.toPrimitive] === "function") { - return Buffer4.from(value[Symbol.toPrimitive]("string"), encodingOrOffset, length); - } - throw new TypeError( - "The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type " + typeof value - ); - } - Buffer4.from = function(value, encodingOrOffset, length) { - return from(value, encodingOrOffset, length); - }; - Object.setPrototypeOf(Buffer4.prototype, Uint8Array.prototype); - Object.setPrototypeOf(Buffer4, Uint8Array); - function assertSize(size) { - if (typeof size !== "number") { - throw new TypeError('"size" argument must be of type number'); - } else if (size < 0) { - throw new RangeError('The value "' + size + '" is invalid for option "size"'); - } - } - function alloc(size, fill, encoding) { - assertSize(size); - if (size <= 0) { - return createBuffer(size); - } - if (fill !== void 0) { - return typeof encoding === "string" ? createBuffer(size).fill(fill, encoding) : createBuffer(size).fill(fill); - } - return createBuffer(size); - } - Buffer4.alloc = function(size, fill, encoding) { - return alloc(size, fill, encoding); - }; - function allocUnsafe(size) { - assertSize(size); - return createBuffer(size < 0 ? 0 : checked(size) | 0); - } - Buffer4.allocUnsafe = function(size) { - return allocUnsafe(size); - }; - Buffer4.allocUnsafeSlow = function(size) { - return allocUnsafe(size); - }; - function fromString(string, encoding) { - if (typeof encoding !== "string" || encoding === "") { - encoding = "utf8"; - } - if (!Buffer4.isEncoding(encoding)) { - throw new TypeError("Unknown encoding: " + encoding); - } - const length = byteLength(string, encoding) | 0; - let buf = createBuffer(length); - const actual = buf.write(string, encoding); - if (actual !== length) { - buf = buf.slice(0, actual); - } - return buf; - } - function fromArrayLike(array) { - const length = array.length < 0 ? 0 : checked(array.length) | 0; - const buf = createBuffer(length); - for (let i = 0; i < length; i += 1) { - buf[i] = array[i] & 255; - } - return buf; - } - function fromArrayView(arrayView) { - if (isInstance(arrayView, Uint8Array)) { - const copy = new Uint8Array(arrayView); - return fromArrayBuffer(copy.buffer, copy.byteOffset, copy.byteLength); - } - return fromArrayLike(arrayView); - } - function fromArrayBuffer(array, byteOffset, length) { - if (byteOffset < 0 || array.byteLength < byteOffset) { - throw new RangeError('"offset" is outside of buffer bounds'); - } - if (array.byteLength < byteOffset + (length || 0)) { - throw new RangeError('"length" is outside of buffer bounds'); - } - let buf; - if (byteOffset === void 0 && length === void 0) { - buf = new Uint8Array(array); - } else if (length === void 0) { - buf = new Uint8Array(array, byteOffset); - } else { - buf = new Uint8Array(array, byteOffset, length); - } - Object.setPrototypeOf(buf, Buffer4.prototype); - return buf; - } - function fromObject(obj) { - if (Buffer4.isBuffer(obj)) { - const len = checked(obj.length) | 0; - const buf = createBuffer(len); - if (buf.length === 0) { - return buf; - } - obj.copy(buf, 0, 0, len); - return buf; - } - if (obj.length !== void 0) { - if (typeof obj.length !== "number" || numberIsNaN(obj.length)) { - return createBuffer(0); - } - return fromArrayLike(obj); - } - if (obj.type === "Buffer" && Array.isArray(obj.data)) { - return fromArrayLike(obj.data); - } - } - function checked(length) { - if (length >= K_MAX_LENGTH) { - throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x" + K_MAX_LENGTH.toString(16) + " bytes"); - } - return length | 0; - } - function SlowBuffer(length) { - if (+length != length) { - length = 0; - } - return Buffer4.alloc(+length); - } - Buffer4.isBuffer = function isBuffer(b) { - return b != null && b._isBuffer === true && b !== Buffer4.prototype; - }; - Buffer4.compare = function compare(a, b) { - if (isInstance(a, Uint8Array)) a = Buffer4.from(a, a.offset, a.byteLength); - if (isInstance(b, Uint8Array)) b = Buffer4.from(b, b.offset, b.byteLength); - if (!Buffer4.isBuffer(a) || !Buffer4.isBuffer(b)) { - throw new TypeError( - 'The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array' - ); - } - if (a === b) return 0; - let x = a.length; - let y = b.length; - for (let i = 0, len = Math.min(x, y); i < len; ++i) { - if (a[i] !== b[i]) { - x = a[i]; - y = b[i]; - break; - } - } - if (x < y) return -1; - if (y < x) return 1; - return 0; - }; - Buffer4.isEncoding = function isEncoding(encoding) { - switch (String(encoding).toLowerCase()) { - case "hex": - case "utf8": - case "utf-8": - case "ascii": - case "latin1": - case "binary": - case "base64": - case "ucs2": - case "ucs-2": - case "utf16le": - case "utf-16le": - return true; - default: - return false; - } - }; - Buffer4.concat = function concat(list, length) { - if (!Array.isArray(list)) { - throw new TypeError('"list" argument must be an Array of Buffers'); - } - if (list.length === 0) { - return Buffer4.alloc(0); - } - let i; - if (length === void 0) { - length = 0; - for (i = 0; i < list.length; ++i) { - length += list[i].length; - } - } - const buffer = Buffer4.allocUnsafe(length); - let pos = 0; - for (i = 0; i < list.length; ++i) { - let buf = list[i]; - if (isInstance(buf, Uint8Array)) { - if (pos + buf.length > buffer.length) { - if (!Buffer4.isBuffer(buf)) buf = Buffer4.from(buf); - buf.copy(buffer, pos); - } else { - Uint8Array.prototype.set.call( - buffer, - buf, - pos - ); - } - } else if (!Buffer4.isBuffer(buf)) { - throw new TypeError('"list" argument must be an Array of Buffers'); - } else { - buf.copy(buffer, pos); - } - pos += buf.length; - } - return buffer; - }; - function byteLength(string, encoding) { - if (Buffer4.isBuffer(string)) { - return string.length; - } - if (ArrayBuffer.isView(string) || isInstance(string, ArrayBuffer)) { - return string.byteLength; - } - if (typeof string !== "string") { - throw new TypeError( - 'The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type ' + typeof string - ); - } - const len = string.length; - const mustMatch = arguments.length > 2 && arguments[2] === true; - if (!mustMatch && len === 0) return 0; - let loweredCase = false; - for (; ; ) { - switch (encoding) { - case "ascii": - case "latin1": - case "binary": - return len; - case "utf8": - case "utf-8": - return utf8ToBytes2(string).length; - case "ucs2": - case "ucs-2": - case "utf16le": - case "utf-16le": - return len * 2; - case "hex": - return len >>> 1; - case "base64": - return base64ToBytes(string).length; - default: - if (loweredCase) { - return mustMatch ? -1 : utf8ToBytes2(string).length; - } - encoding = ("" + encoding).toLowerCase(); - loweredCase = true; - } - } - } - Buffer4.byteLength = byteLength; - function slowToString(encoding, start, end) { - let loweredCase = false; - if (start === void 0 || start < 0) { - start = 0; - } - if (start > this.length) { - return ""; - } - if (end === void 0 || end > this.length) { - end = this.length; - } - if (end <= 0) { - return ""; - } - end >>>= 0; - start >>>= 0; - if (end <= start) { - return ""; - } - if (!encoding) encoding = "utf8"; - while (true) { - switch (encoding) { - case "hex": - return hexSlice(this, start, end); - case "utf8": - case "utf-8": - return utf8Slice(this, start, end); - case "ascii": - return asciiSlice(this, start, end); - case "latin1": - case "binary": - return latin1Slice(this, start, end); - case "base64": - return base64Slice(this, start, end); - case "ucs2": - case "ucs-2": - case "utf16le": - case "utf-16le": - return utf16leSlice(this, start, end); - default: - if (loweredCase) throw new TypeError("Unknown encoding: " + encoding); - encoding = (encoding + "").toLowerCase(); - loweredCase = true; - } - } - } - Buffer4.prototype._isBuffer = true; - function swap(b, n, m) { - const i = b[n]; - b[n] = b[m]; - b[m] = i; - } - Buffer4.prototype.swap16 = function swap16() { - const len = this.length; - if (len % 2 !== 0) { - throw new RangeError("Buffer size must be a multiple of 16-bits"); - } - for (let i = 0; i < len; i += 2) { - swap(this, i, i + 1); - } - return this; - }; - Buffer4.prototype.swap32 = function swap32() { - const len = this.length; - if (len % 4 !== 0) { - throw new RangeError("Buffer size must be a multiple of 32-bits"); - } - for (let i = 0; i < len; i += 4) { - swap(this, i, i + 3); - swap(this, i + 1, i + 2); - } - return this; - }; - Buffer4.prototype.swap64 = function swap64() { - const len = this.length; - if (len % 8 !== 0) { - throw new RangeError("Buffer size must be a multiple of 64-bits"); - } - for (let i = 0; i < len; i += 8) { - swap(this, i, i + 7); - swap(this, i + 1, i + 6); - swap(this, i + 2, i + 5); - swap(this, i + 3, i + 4); - } - return this; - }; - Buffer4.prototype.toString = function toString() { - const length = this.length; - if (length === 0) return ""; - if (arguments.length === 0) return utf8Slice(this, 0, length); - return slowToString.apply(this, arguments); - }; - Buffer4.prototype.toLocaleString = Buffer4.prototype.toString; - Buffer4.prototype.equals = function equals(b) { - if (!Buffer4.isBuffer(b)) throw new TypeError("Argument must be a Buffer"); - if (this === b) return true; - return Buffer4.compare(this, b) === 0; - }; - Buffer4.prototype.inspect = function inspect() { - let str = ""; - const max = exports.INSPECT_MAX_BYTES; - str = this.toString("hex", 0, max).replace(/(.{2})/g, "$1 ").trim(); - if (this.length > max) str += " ... "; - return ""; - }; - if (customInspectSymbol) { - Buffer4.prototype[customInspectSymbol] = Buffer4.prototype.inspect; - } - Buffer4.prototype.compare = function compare(target, start, end, thisStart, thisEnd) { - if (isInstance(target, Uint8Array)) { - target = Buffer4.from(target, target.offset, target.byteLength); - } - if (!Buffer4.isBuffer(target)) { - throw new TypeError( - 'The "target" argument must be one of type Buffer or Uint8Array. Received type ' + typeof target - ); - } - if (start === void 0) { - start = 0; - } - if (end === void 0) { - end = target ? target.length : 0; - } - if (thisStart === void 0) { - thisStart = 0; - } - if (thisEnd === void 0) { - thisEnd = this.length; - } - if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) { - throw new RangeError("out of range index"); - } - if (thisStart >= thisEnd && start >= end) { - return 0; - } - if (thisStart >= thisEnd) { - return -1; - } - if (start >= end) { - return 1; - } - start >>>= 0; - end >>>= 0; - thisStart >>>= 0; - thisEnd >>>= 0; - if (this === target) return 0; - let x = thisEnd - thisStart; - let y = end - start; - const len = Math.min(x, y); - const thisCopy = this.slice(thisStart, thisEnd); - const targetCopy = target.slice(start, end); - for (let i = 0; i < len; ++i) { - if (thisCopy[i] !== targetCopy[i]) { - x = thisCopy[i]; - y = targetCopy[i]; - break; - } - } - if (x < y) return -1; - if (y < x) return 1; - return 0; - }; - function bidirectionalIndexOf(buffer, val, byteOffset, encoding, dir) { - if (buffer.length === 0) return -1; - if (typeof byteOffset === "string") { - encoding = byteOffset; - byteOffset = 0; - } else if (byteOffset > 2147483647) { - byteOffset = 2147483647; - } else if (byteOffset < -2147483648) { - byteOffset = -2147483648; - } - byteOffset = +byteOffset; - if (numberIsNaN(byteOffset)) { - byteOffset = dir ? 0 : buffer.length - 1; - } - if (byteOffset < 0) byteOffset = buffer.length + byteOffset; - if (byteOffset >= buffer.length) { - if (dir) return -1; - else byteOffset = buffer.length - 1; - } else if (byteOffset < 0) { - if (dir) byteOffset = 0; - else return -1; - } - if (typeof val === "string") { - val = Buffer4.from(val, encoding); - } - if (Buffer4.isBuffer(val)) { - if (val.length === 0) { - return -1; - } - return arrayIndexOf(buffer, val, byteOffset, encoding, dir); - } else if (typeof val === "number") { - val = val & 255; - if (typeof Uint8Array.prototype.indexOf === "function") { - if (dir) { - return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset); - } else { - return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset); - } - } - return arrayIndexOf(buffer, [val], byteOffset, encoding, dir); - } - throw new TypeError("val must be string, number or Buffer"); - } - function arrayIndexOf(arr, val, byteOffset, encoding, dir) { - let indexSize = 1; - let arrLength = arr.length; - let valLength = val.length; - if (encoding !== void 0) { - encoding = String(encoding).toLowerCase(); - if (encoding === "ucs2" || encoding === "ucs-2" || encoding === "utf16le" || encoding === "utf-16le") { - if (arr.length < 2 || val.length < 2) { - return -1; - } - indexSize = 2; - arrLength /= 2; - valLength /= 2; - byteOffset /= 2; - } - } - function read(buf, i2) { - if (indexSize === 1) { - return buf[i2]; - } else { - return buf.readUInt16BE(i2 * indexSize); - } - } - let i; - if (dir) { - let foundIndex = -1; - for (i = byteOffset; i < arrLength; i++) { - if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) { - if (foundIndex === -1) foundIndex = i; - if (i - foundIndex + 1 === valLength) return foundIndex * indexSize; - } else { - if (foundIndex !== -1) i -= i - foundIndex; - foundIndex = -1; - } - } - } else { - if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength; - for (i = byteOffset; i >= 0; i--) { - let found = true; - for (let j = 0; j < valLength; j++) { - if (read(arr, i + j) !== read(val, j)) { - found = false; - break; - } - } - if (found) return i; - } - } - return -1; - } - Buffer4.prototype.includes = function includes(val, byteOffset, encoding) { - return this.indexOf(val, byteOffset, encoding) !== -1; - }; - Buffer4.prototype.indexOf = function indexOf(val, byteOffset, encoding) { - return bidirectionalIndexOf(this, val, byteOffset, encoding, true); - }; - Buffer4.prototype.lastIndexOf = function lastIndexOf(val, byteOffset, encoding) { - return bidirectionalIndexOf(this, val, byteOffset, encoding, false); - }; - function hexWrite(buf, string, offset, length) { - offset = Number(offset) || 0; - const remaining = buf.length - offset; - if (!length) { - length = remaining; - } else { - length = Number(length); - if (length > remaining) { - length = remaining; - } - } - const strLen = string.length; - if (length > strLen / 2) { - length = strLen / 2; - } - let i; - for (i = 0; i < length; ++i) { - const parsed = parseInt(string.substr(i * 2, 2), 16); - if (numberIsNaN(parsed)) return i; - buf[offset + i] = parsed; - } - return i; - } - function utf8Write(buf, string, offset, length) { - return blitBuffer(utf8ToBytes2(string, buf.length - offset), buf, offset, length); - } - function asciiWrite(buf, string, offset, length) { - return blitBuffer(asciiToBytes2(string), buf, offset, length); - } - function base64Write(buf, string, offset, length) { - return blitBuffer(base64ToBytes(string), buf, offset, length); - } - function ucs2Write(buf, string, offset, length) { - return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length); - } - Buffer4.prototype.write = function write(string, offset, length, encoding) { - if (offset === void 0) { - encoding = "utf8"; - length = this.length; - offset = 0; - } else if (length === void 0 && typeof offset === "string") { - encoding = offset; - length = this.length; - offset = 0; - } else if (isFinite(offset)) { - offset = offset >>> 0; - if (isFinite(length)) { - length = length >>> 0; - if (encoding === void 0) encoding = "utf8"; - } else { - encoding = length; - length = void 0; - } - } else { - throw new Error( - "Buffer.write(string, encoding, offset[, length]) is no longer supported" - ); - } - const remaining = this.length - offset; - if (length === void 0 || length > remaining) length = remaining; - if (string.length > 0 && (length < 0 || offset < 0) || offset > this.length) { - throw new RangeError("Attempt to write outside buffer bounds"); - } - if (!encoding) encoding = "utf8"; - let loweredCase = false; - for (; ; ) { - switch (encoding) { - case "hex": - return hexWrite(this, string, offset, length); - case "utf8": - case "utf-8": - return utf8Write(this, string, offset, length); - case "ascii": - case "latin1": - case "binary": - return asciiWrite(this, string, offset, length); - case "base64": - return base64Write(this, string, offset, length); - case "ucs2": - case "ucs-2": - case "utf16le": - case "utf-16le": - return ucs2Write(this, string, offset, length); - default: - if (loweredCase) throw new TypeError("Unknown encoding: " + encoding); - encoding = ("" + encoding).toLowerCase(); - loweredCase = true; - } - } - }; - Buffer4.prototype.toJSON = function toJSON() { - return { - type: "Buffer", - data: Array.prototype.slice.call(this._arr || this, 0) - }; - }; - function base64Slice(buf, start, end) { - if (start === 0 && end === buf.length) { - return base64.fromByteArray(buf); - } else { - return base64.fromByteArray(buf.slice(start, end)); - } - } - function utf8Slice(buf, start, end) { - end = Math.min(buf.length, end); - const res = []; - let i = start; - while (i < end) { - const firstByte = buf[i]; - let codePoint = null; - let bytesPerSequence = firstByte > 239 ? 4 : firstByte > 223 ? 3 : firstByte > 191 ? 2 : 1; - if (i + bytesPerSequence <= end) { - let secondByte, thirdByte, fourthByte, tempCodePoint; - switch (bytesPerSequence) { - case 1: - if (firstByte < 128) { - codePoint = firstByte; - } - break; - case 2: - secondByte = buf[i + 1]; - if ((secondByte & 192) === 128) { - tempCodePoint = (firstByte & 31) << 6 | secondByte & 63; - if (tempCodePoint > 127) { - codePoint = tempCodePoint; - } - } - break; - case 3: - secondByte = buf[i + 1]; - thirdByte = buf[i + 2]; - if ((secondByte & 192) === 128 && (thirdByte & 192) === 128) { - tempCodePoint = (firstByte & 15) << 12 | (secondByte & 63) << 6 | thirdByte & 63; - if (tempCodePoint > 2047 && (tempCodePoint < 55296 || tempCodePoint > 57343)) { - codePoint = tempCodePoint; - } - } - break; - case 4: - secondByte = buf[i + 1]; - thirdByte = buf[i + 2]; - fourthByte = buf[i + 3]; - if ((secondByte & 192) === 128 && (thirdByte & 192) === 128 && (fourthByte & 192) === 128) { - tempCodePoint = (firstByte & 15) << 18 | (secondByte & 63) << 12 | (thirdByte & 63) << 6 | fourthByte & 63; - if (tempCodePoint > 65535 && tempCodePoint < 1114112) { - codePoint = tempCodePoint; - } - } - } - } - if (codePoint === null) { - codePoint = 65533; - bytesPerSequence = 1; - } else if (codePoint > 65535) { - codePoint -= 65536; - res.push(codePoint >>> 10 & 1023 | 55296); - codePoint = 56320 | codePoint & 1023; - } - res.push(codePoint); - i += bytesPerSequence; - } - return decodeCodePointsArray(res); - } - var MAX_ARGUMENTS_LENGTH = 4096; - function decodeCodePointsArray(codePoints) { - const len = codePoints.length; - if (len <= MAX_ARGUMENTS_LENGTH) { - return String.fromCharCode.apply(String, codePoints); - } - let res = ""; - let i = 0; - while (i < len) { - res += String.fromCharCode.apply( - String, - codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH) - ); - } - return res; - } - function asciiSlice(buf, start, end) { - let ret = ""; - end = Math.min(buf.length, end); - for (let i = start; i < end; ++i) { - ret += String.fromCharCode(buf[i] & 127); - } - return ret; - } - function latin1Slice(buf, start, end) { - let ret = ""; - end = Math.min(buf.length, end); - for (let i = start; i < end; ++i) { - ret += String.fromCharCode(buf[i]); - } - return ret; - } - function hexSlice(buf, start, end) { - const len = buf.length; - if (!start || start < 0) start = 0; - if (!end || end < 0 || end > len) end = len; - let out = ""; - for (let i = start; i < end; ++i) { - out += hexSliceLookupTable[buf[i]]; - } - return out; - } - function utf16leSlice(buf, start, end) { - const bytes = buf.slice(start, end); - let res = ""; - for (let i = 0; i < bytes.length - 1; i += 2) { - res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256); - } - return res; - } - Buffer4.prototype.slice = function slice(start, end) { - const len = this.length; - start = ~~start; - end = end === void 0 ? len : ~~end; - if (start < 0) { - start += len; - if (start < 0) start = 0; - } else if (start > len) { - start = len; - } - if (end < 0) { - end += len; - if (end < 0) end = 0; - } else if (end > len) { - end = len; - } - if (end < start) end = start; - const newBuf = this.subarray(start, end); - Object.setPrototypeOf(newBuf, Buffer4.prototype); - return newBuf; - }; - function checkOffset(offset, ext, length) { - if (offset % 1 !== 0 || offset < 0) throw new RangeError("offset is not uint"); - if (offset + ext > length) throw new RangeError("Trying to access beyond buffer length"); - } - Buffer4.prototype.readUintLE = Buffer4.prototype.readUIntLE = function readUIntLE(offset, byteLength2, noAssert) { - offset = offset >>> 0; - byteLength2 = byteLength2 >>> 0; - if (!noAssert) checkOffset(offset, byteLength2, this.length); - let val = this[offset]; - let mul = 1; - let i = 0; - while (++i < byteLength2 && (mul *= 256)) { - val += this[offset + i] * mul; - } - return val; - }; - Buffer4.prototype.readUintBE = Buffer4.prototype.readUIntBE = function readUIntBE(offset, byteLength2, noAssert) { - offset = offset >>> 0; - byteLength2 = byteLength2 >>> 0; - if (!noAssert) { - checkOffset(offset, byteLength2, this.length); - } - let val = this[offset + --byteLength2]; - let mul = 1; - while (byteLength2 > 0 && (mul *= 256)) { - val += this[offset + --byteLength2] * mul; - } - return val; - }; - Buffer4.prototype.readUint8 = Buffer4.prototype.readUInt8 = function readUInt8(offset, noAssert) { - offset = offset >>> 0; - if (!noAssert) checkOffset(offset, 1, this.length); - return this[offset]; - }; - Buffer4.prototype.readUint16LE = Buffer4.prototype.readUInt16LE = function readUInt16LE(offset, noAssert) { - offset = offset >>> 0; - if (!noAssert) checkOffset(offset, 2, this.length); - return this[offset] | this[offset + 1] << 8; - }; - Buffer4.prototype.readUint16BE = Buffer4.prototype.readUInt16BE = function readUInt16BE(offset, noAssert) { - offset = offset >>> 0; - if (!noAssert) checkOffset(offset, 2, this.length); - return this[offset] << 8 | this[offset + 1]; - }; - Buffer4.prototype.readUint32LE = Buffer4.prototype.readUInt32LE = function readUInt32LE(offset, noAssert) { - offset = offset >>> 0; - if (!noAssert) checkOffset(offset, 4, this.length); - return (this[offset] | this[offset + 1] << 8 | this[offset + 2] << 16) + this[offset + 3] * 16777216; - }; - Buffer4.prototype.readUint32BE = Buffer4.prototype.readUInt32BE = function readUInt32BE(offset, noAssert) { - offset = offset >>> 0; - if (!noAssert) checkOffset(offset, 4, this.length); - return this[offset] * 16777216 + (this[offset + 1] << 16 | this[offset + 2] << 8 | this[offset + 3]); - }; - Buffer4.prototype.readBigUInt64LE = defineBigIntMethod(function readBigUInt64LE(offset) { - offset = offset >>> 0; - validateNumber(offset, "offset"); - const first = this[offset]; - const last = this[offset + 7]; - if (first === void 0 || last === void 0) { - boundsError(offset, this.length - 8); - } - const lo = first + this[++offset] * 2 ** 8 + this[++offset] * 2 ** 16 + this[++offset] * 2 ** 24; - const hi = this[++offset] + this[++offset] * 2 ** 8 + this[++offset] * 2 ** 16 + last * 2 ** 24; - return BigInt(lo) + (BigInt(hi) << BigInt(32)); - }); - Buffer4.prototype.readBigUInt64BE = defineBigIntMethod(function readBigUInt64BE(offset) { - offset = offset >>> 0; - validateNumber(offset, "offset"); - const first = this[offset]; - const last = this[offset + 7]; - if (first === void 0 || last === void 0) { - boundsError(offset, this.length - 8); - } - const hi = first * 2 ** 24 + this[++offset] * 2 ** 16 + this[++offset] * 2 ** 8 + this[++offset]; - const lo = this[++offset] * 2 ** 24 + this[++offset] * 2 ** 16 + this[++offset] * 2 ** 8 + last; - return (BigInt(hi) << BigInt(32)) + BigInt(lo); - }); - Buffer4.prototype.readIntLE = function readIntLE(offset, byteLength2, noAssert) { - offset = offset >>> 0; - byteLength2 = byteLength2 >>> 0; - if (!noAssert) checkOffset(offset, byteLength2, this.length); - let val = this[offset]; - let mul = 1; - let i = 0; - while (++i < byteLength2 && (mul *= 256)) { - val += this[offset + i] * mul; - } - mul *= 128; - if (val >= mul) val -= Math.pow(2, 8 * byteLength2); - return val; - }; - Buffer4.prototype.readIntBE = function readIntBE(offset, byteLength2, noAssert) { - offset = offset >>> 0; - byteLength2 = byteLength2 >>> 0; - if (!noAssert) checkOffset(offset, byteLength2, this.length); - let i = byteLength2; - let mul = 1; - let val = this[offset + --i]; - while (i > 0 && (mul *= 256)) { - val += this[offset + --i] * mul; - } - mul *= 128; - if (val >= mul) val -= Math.pow(2, 8 * byteLength2); - return val; - }; - Buffer4.prototype.readInt8 = function readInt8(offset, noAssert) { - offset = offset >>> 0; - if (!noAssert) checkOffset(offset, 1, this.length); - if (!(this[offset] & 128)) return this[offset]; - return (255 - this[offset] + 1) * -1; - }; - Buffer4.prototype.readInt16LE = function readInt16LE(offset, noAssert) { - offset = offset >>> 0; - if (!noAssert) checkOffset(offset, 2, this.length); - const val = this[offset] | this[offset + 1] << 8; - return val & 32768 ? val | 4294901760 : val; - }; - Buffer4.prototype.readInt16BE = function readInt16BE(offset, noAssert) { - offset = offset >>> 0; - if (!noAssert) checkOffset(offset, 2, this.length); - const val = this[offset + 1] | this[offset] << 8; - return val & 32768 ? val | 4294901760 : val; - }; - Buffer4.prototype.readInt32LE = function readInt32LE(offset, noAssert) { - offset = offset >>> 0; - if (!noAssert) checkOffset(offset, 4, this.length); - return this[offset] | this[offset + 1] << 8 | this[offset + 2] << 16 | this[offset + 3] << 24; - }; - Buffer4.prototype.readInt32BE = function readInt32BE(offset, noAssert) { - offset = offset >>> 0; - if (!noAssert) checkOffset(offset, 4, this.length); - return this[offset] << 24 | this[offset + 1] << 16 | this[offset + 2] << 8 | this[offset + 3]; - }; - Buffer4.prototype.readBigInt64LE = defineBigIntMethod(function readBigInt64LE(offset) { - offset = offset >>> 0; - validateNumber(offset, "offset"); - const first = this[offset]; - const last = this[offset + 7]; - if (first === void 0 || last === void 0) { - boundsError(offset, this.length - 8); - } - const val = this[offset + 4] + this[offset + 5] * 2 ** 8 + this[offset + 6] * 2 ** 16 + (last << 24); - return (BigInt(val) << BigInt(32)) + BigInt(first + this[++offset] * 2 ** 8 + this[++offset] * 2 ** 16 + this[++offset] * 2 ** 24); - }); - Buffer4.prototype.readBigInt64BE = defineBigIntMethod(function readBigInt64BE(offset) { - offset = offset >>> 0; - validateNumber(offset, "offset"); - const first = this[offset]; - const last = this[offset + 7]; - if (first === void 0 || last === void 0) { - boundsError(offset, this.length - 8); - } - const val = (first << 24) + // Overflow - this[++offset] * 2 ** 16 + this[++offset] * 2 ** 8 + this[++offset]; - return (BigInt(val) << BigInt(32)) + BigInt(this[++offset] * 2 ** 24 + this[++offset] * 2 ** 16 + this[++offset] * 2 ** 8 + last); - }); - Buffer4.prototype.readFloatLE = function readFloatLE(offset, noAssert) { - offset = offset >>> 0; - if (!noAssert) checkOffset(offset, 4, this.length); - return ieee754.read(this, offset, true, 23, 4); - }; - Buffer4.prototype.readFloatBE = function readFloatBE(offset, noAssert) { - offset = offset >>> 0; - if (!noAssert) checkOffset(offset, 4, this.length); - return ieee754.read(this, offset, false, 23, 4); - }; - Buffer4.prototype.readDoubleLE = function readDoubleLE(offset, noAssert) { - offset = offset >>> 0; - if (!noAssert) checkOffset(offset, 8, this.length); - return ieee754.read(this, offset, true, 52, 8); - }; - Buffer4.prototype.readDoubleBE = function readDoubleBE(offset, noAssert) { - offset = offset >>> 0; - if (!noAssert) checkOffset(offset, 8, this.length); - return ieee754.read(this, offset, false, 52, 8); - }; - function checkInt(buf, value, offset, ext, max, min) { - if (!Buffer4.isBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance'); - if (value > max || value < min) throw new RangeError('"value" argument is out of bounds'); - if (offset + ext > buf.length) throw new RangeError("Index out of range"); - } - Buffer4.prototype.writeUintLE = Buffer4.prototype.writeUIntLE = function writeUIntLE(value, offset, byteLength2, noAssert) { - value = +value; - offset = offset >>> 0; - byteLength2 = byteLength2 >>> 0; - if (!noAssert) { - const maxBytes = Math.pow(2, 8 * byteLength2) - 1; - checkInt(this, value, offset, byteLength2, maxBytes, 0); - } - let mul = 1; - let i = 0; - this[offset] = value & 255; - while (++i < byteLength2 && (mul *= 256)) { - this[offset + i] = value / mul & 255; - } - return offset + byteLength2; - }; - Buffer4.prototype.writeUintBE = Buffer4.prototype.writeUIntBE = function writeUIntBE(value, offset, byteLength2, noAssert) { - value = +value; - offset = offset >>> 0; - byteLength2 = byteLength2 >>> 0; - if (!noAssert) { - const maxBytes = Math.pow(2, 8 * byteLength2) - 1; - checkInt(this, value, offset, byteLength2, maxBytes, 0); - } - let i = byteLength2 - 1; - let mul = 1; - this[offset + i] = value & 255; - while (--i >= 0 && (mul *= 256)) { - this[offset + i] = value / mul & 255; - } - return offset + byteLength2; - }; - Buffer4.prototype.writeUint8 = Buffer4.prototype.writeUInt8 = function writeUInt8(value, offset, noAssert) { - value = +value; - offset = offset >>> 0; - if (!noAssert) checkInt(this, value, offset, 1, 255, 0); - this[offset] = value & 255; - return offset + 1; - }; - Buffer4.prototype.writeUint16LE = Buffer4.prototype.writeUInt16LE = function writeUInt16LE(value, offset, noAssert) { - value = +value; - offset = offset >>> 0; - if (!noAssert) checkInt(this, value, offset, 2, 65535, 0); - this[offset] = value & 255; - this[offset + 1] = value >>> 8; - return offset + 2; - }; - Buffer4.prototype.writeUint16BE = Buffer4.prototype.writeUInt16BE = function writeUInt16BE(value, offset, noAssert) { - value = +value; - offset = offset >>> 0; - if (!noAssert) checkInt(this, value, offset, 2, 65535, 0); - this[offset] = value >>> 8; - this[offset + 1] = value & 255; - return offset + 2; - }; - Buffer4.prototype.writeUint32LE = Buffer4.prototype.writeUInt32LE = function writeUInt32LE(value, offset, noAssert) { - value = +value; - offset = offset >>> 0; - if (!noAssert) checkInt(this, value, offset, 4, 4294967295, 0); - this[offset + 3] = value >>> 24; - this[offset + 2] = value >>> 16; - this[offset + 1] = value >>> 8; - this[offset] = value & 255; - return offset + 4; - }; - Buffer4.prototype.writeUint32BE = Buffer4.prototype.writeUInt32BE = function writeUInt32BE(value, offset, noAssert) { - value = +value; - offset = offset >>> 0; - if (!noAssert) checkInt(this, value, offset, 4, 4294967295, 0); - this[offset] = value >>> 24; - this[offset + 1] = value >>> 16; - this[offset + 2] = value >>> 8; - this[offset + 3] = value & 255; - return offset + 4; - }; - function wrtBigUInt64LE(buf, value, offset, min, max) { - checkIntBI(value, min, max, buf, offset, 7); - let lo = Number(value & BigInt(4294967295)); - buf[offset++] = lo; - lo = lo >> 8; - buf[offset++] = lo; - lo = lo >> 8; - buf[offset++] = lo; - lo = lo >> 8; - buf[offset++] = lo; - let hi = Number(value >> BigInt(32) & BigInt(4294967295)); - buf[offset++] = hi; - hi = hi >> 8; - buf[offset++] = hi; - hi = hi >> 8; - buf[offset++] = hi; - hi = hi >> 8; - buf[offset++] = hi; - return offset; - } - function wrtBigUInt64BE(buf, value, offset, min, max) { - checkIntBI(value, min, max, buf, offset, 7); - let lo = Number(value & BigInt(4294967295)); - buf[offset + 7] = lo; - lo = lo >> 8; - buf[offset + 6] = lo; - lo = lo >> 8; - buf[offset + 5] = lo; - lo = lo >> 8; - buf[offset + 4] = lo; - let hi = Number(value >> BigInt(32) & BigInt(4294967295)); - buf[offset + 3] = hi; - hi = hi >> 8; - buf[offset + 2] = hi; - hi = hi >> 8; - buf[offset + 1] = hi; - hi = hi >> 8; - buf[offset] = hi; - return offset + 8; - } - Buffer4.prototype.writeBigUInt64LE = defineBigIntMethod(function writeBigUInt64LE(value, offset = 0) { - return wrtBigUInt64LE(this, value, offset, BigInt(0), BigInt("0xffffffffffffffff")); - }); - Buffer4.prototype.writeBigUInt64BE = defineBigIntMethod(function writeBigUInt64BE(value, offset = 0) { - return wrtBigUInt64BE(this, value, offset, BigInt(0), BigInt("0xffffffffffffffff")); - }); - Buffer4.prototype.writeIntLE = function writeIntLE(value, offset, byteLength2, noAssert) { - value = +value; - offset = offset >>> 0; - if (!noAssert) { - const limit = Math.pow(2, 8 * byteLength2 - 1); - checkInt(this, value, offset, byteLength2, limit - 1, -limit); - } - let i = 0; - let mul = 1; - let sub = 0; - this[offset] = value & 255; - while (++i < byteLength2 && (mul *= 256)) { - if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) { - sub = 1; - } - this[offset + i] = (value / mul >> 0) - sub & 255; - } - return offset + byteLength2; - }; - Buffer4.prototype.writeIntBE = function writeIntBE(value, offset, byteLength2, noAssert) { - value = +value; - offset = offset >>> 0; - if (!noAssert) { - const limit = Math.pow(2, 8 * byteLength2 - 1); - checkInt(this, value, offset, byteLength2, limit - 1, -limit); - } - let i = byteLength2 - 1; - let mul = 1; - let sub = 0; - this[offset + i] = value & 255; - while (--i >= 0 && (mul *= 256)) { - if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) { - sub = 1; - } - this[offset + i] = (value / mul >> 0) - sub & 255; - } - return offset + byteLength2; - }; - Buffer4.prototype.writeInt8 = function writeInt8(value, offset, noAssert) { - value = +value; - offset = offset >>> 0; - if (!noAssert) checkInt(this, value, offset, 1, 127, -128); - if (value < 0) value = 255 + value + 1; - this[offset] = value & 255; - return offset + 1; - }; - Buffer4.prototype.writeInt16LE = function writeInt16LE(value, offset, noAssert) { - value = +value; - offset = offset >>> 0; - if (!noAssert) checkInt(this, value, offset, 2, 32767, -32768); - this[offset] = value & 255; - this[offset + 1] = value >>> 8; - return offset + 2; - }; - Buffer4.prototype.writeInt16BE = function writeInt16BE(value, offset, noAssert) { - value = +value; - offset = offset >>> 0; - if (!noAssert) checkInt(this, value, offset, 2, 32767, -32768); - this[offset] = value >>> 8; - this[offset + 1] = value & 255; - return offset + 2; - }; - Buffer4.prototype.writeInt32LE = function writeInt32LE(value, offset, noAssert) { - value = +value; - offset = offset >>> 0; - if (!noAssert) checkInt(this, value, offset, 4, 2147483647, -2147483648); - this[offset] = value & 255; - this[offset + 1] = value >>> 8; - this[offset + 2] = value >>> 16; - this[offset + 3] = value >>> 24; - return offset + 4; - }; - Buffer4.prototype.writeInt32BE = function writeInt32BE(value, offset, noAssert) { - value = +value; - offset = offset >>> 0; - if (!noAssert) checkInt(this, value, offset, 4, 2147483647, -2147483648); - if (value < 0) value = 4294967295 + value + 1; - this[offset] = value >>> 24; - this[offset + 1] = value >>> 16; - this[offset + 2] = value >>> 8; - this[offset + 3] = value & 255; - return offset + 4; - }; - Buffer4.prototype.writeBigInt64LE = defineBigIntMethod(function writeBigInt64LE(value, offset = 0) { - return wrtBigUInt64LE(this, value, offset, -BigInt("0x8000000000000000"), BigInt("0x7fffffffffffffff")); - }); - Buffer4.prototype.writeBigInt64BE = defineBigIntMethod(function writeBigInt64BE(value, offset = 0) { - return wrtBigUInt64BE(this, value, offset, -BigInt("0x8000000000000000"), BigInt("0x7fffffffffffffff")); - }); - function checkIEEE754(buf, value, offset, ext, max, min) { - if (offset + ext > buf.length) throw new RangeError("Index out of range"); - if (offset < 0) throw new RangeError("Index out of range"); - } - function writeFloat(buf, value, offset, littleEndian, noAssert) { - value = +value; - offset = offset >>> 0; - if (!noAssert) { - checkIEEE754(buf, value, offset, 4, 34028234663852886e22, -34028234663852886e22); - } - ieee754.write(buf, value, offset, littleEndian, 23, 4); - return offset + 4; - } - Buffer4.prototype.writeFloatLE = function writeFloatLE(value, offset, noAssert) { - return writeFloat(this, value, offset, true, noAssert); - }; - Buffer4.prototype.writeFloatBE = function writeFloatBE(value, offset, noAssert) { - return writeFloat(this, value, offset, false, noAssert); - }; - function writeDouble(buf, value, offset, littleEndian, noAssert) { - value = +value; - offset = offset >>> 0; - if (!noAssert) { - checkIEEE754(buf, value, offset, 8, 17976931348623157e292, -17976931348623157e292); - } - ieee754.write(buf, value, offset, littleEndian, 52, 8); - return offset + 8; - } - Buffer4.prototype.writeDoubleLE = function writeDoubleLE(value, offset, noAssert) { - return writeDouble(this, value, offset, true, noAssert); - }; - Buffer4.prototype.writeDoubleBE = function writeDoubleBE(value, offset, noAssert) { - return writeDouble(this, value, offset, false, noAssert); - }; - Buffer4.prototype.copy = function copy(target, targetStart, start, end) { - if (!Buffer4.isBuffer(target)) throw new TypeError("argument should be a Buffer"); - if (!start) start = 0; - if (!end && end !== 0) end = this.length; - if (targetStart >= target.length) targetStart = target.length; - if (!targetStart) targetStart = 0; - if (end > 0 && end < start) end = start; - if (end === start) return 0; - if (target.length === 0 || this.length === 0) return 0; - if (targetStart < 0) { - throw new RangeError("targetStart out of bounds"); - } - if (start < 0 || start >= this.length) throw new RangeError("Index out of range"); - if (end < 0) throw new RangeError("sourceEnd out of bounds"); - if (end > this.length) end = this.length; - if (target.length - targetStart < end - start) { - end = target.length - targetStart + start; - } - const len = end - start; - if (this === target && typeof Uint8Array.prototype.copyWithin === "function") { - this.copyWithin(targetStart, start, end); - } else { - Uint8Array.prototype.set.call( - target, - this.subarray(start, end), - targetStart - ); - } - return len; - }; - Buffer4.prototype.fill = function fill(val, start, end, encoding) { - if (typeof val === "string") { - if (typeof start === "string") { - encoding = start; - start = 0; - end = this.length; - } else if (typeof end === "string") { - encoding = end; - end = this.length; - } - if (encoding !== void 0 && typeof encoding !== "string") { - throw new TypeError("encoding must be a string"); - } - if (typeof encoding === "string" && !Buffer4.isEncoding(encoding)) { - throw new TypeError("Unknown encoding: " + encoding); - } - if (val.length === 1) { - const code = val.charCodeAt(0); - if (encoding === "utf8" && code < 128 || encoding === "latin1") { - val = code; - } - } - } else if (typeof val === "number") { - val = val & 255; - } else if (typeof val === "boolean") { - val = Number(val); - } - if (start < 0 || this.length < start || this.length < end) { - throw new RangeError("Out of range index"); - } - if (end <= start) { - return this; - } - start = start >>> 0; - end = end === void 0 ? this.length : end >>> 0; - if (!val) val = 0; - let i; - if (typeof val === "number") { - for (i = start; i < end; ++i) { - this[i] = val; - } - } else { - const bytes = Buffer4.isBuffer(val) ? val : Buffer4.from(val, encoding); - const len = bytes.length; - if (len === 0) { - throw new TypeError('The value "' + val + '" is invalid for argument "value"'); - } - for (i = 0; i < end - start; ++i) { - this[i + start] = bytes[i % len]; - } - } - return this; - }; - var errors = {}; - function E(sym, getMessage, Base) { - errors[sym] = class NodeError extends Base { - constructor() { - super(); - Object.defineProperty(this, "message", { - value: getMessage.apply(this, arguments), - writable: true, - configurable: true - }); - this.name = `${this.name} [${sym}]`; - this.stack; - delete this.name; - } - get code() { - return sym; - } - set code(value) { - Object.defineProperty(this, "code", { - configurable: true, - enumerable: true, - value, - writable: true - }); - } - toString() { - return `${this.name} [${sym}]: ${this.message}`; - } - }; - } - E( - "ERR_BUFFER_OUT_OF_BOUNDS", - function(name) { - if (name) { - return `${name} is outside of buffer bounds`; - } - return "Attempt to access memory outside buffer bounds"; - }, - RangeError - ); - E( - "ERR_INVALID_ARG_TYPE", - function(name, actual) { - return `The "${name}" argument must be of type number. Received type ${typeof actual}`; - }, - TypeError - ); - E( - "ERR_OUT_OF_RANGE", - function(str, range, input) { - let msg = `The value of "${str}" is out of range.`; - let received = input; - if (Number.isInteger(input) && Math.abs(input) > 2 ** 32) { - received = addNumericalSeparator(String(input)); - } else if (typeof input === "bigint") { - received = String(input); - if (input > BigInt(2) ** BigInt(32) || input < -(BigInt(2) ** BigInt(32))) { - received = addNumericalSeparator(received); - } - received += "n"; - } - msg += ` It must be ${range}. Received ${received}`; - return msg; - }, - RangeError - ); - function addNumericalSeparator(val) { - let res = ""; - let i = val.length; - const start = val[0] === "-" ? 1 : 0; - for (; i >= start + 4; i -= 3) { - res = `_${val.slice(i - 3, i)}${res}`; - } - return `${val.slice(0, i)}${res}`; - } - function checkBounds(buf, offset, byteLength2) { - validateNumber(offset, "offset"); - if (buf[offset] === void 0 || buf[offset + byteLength2] === void 0) { - boundsError(offset, buf.length - (byteLength2 + 1)); - } - } - function checkIntBI(value, min, max, buf, offset, byteLength2) { - if (value > max || value < min) { - const n = typeof min === "bigint" ? "n" : ""; - let range; - if (byteLength2 > 3) { - if (min === 0 || min === BigInt(0)) { - range = `>= 0${n} and < 2${n} ** ${(byteLength2 + 1) * 8}${n}`; - } else { - range = `>= -(2${n} ** ${(byteLength2 + 1) * 8 - 1}${n}) and < 2 ** ${(byteLength2 + 1) * 8 - 1}${n}`; - } - } else { - range = `>= ${min}${n} and <= ${max}${n}`; - } - throw new errors.ERR_OUT_OF_RANGE("value", range, value); - } - checkBounds(buf, offset, byteLength2); - } - function validateNumber(value, name) { - if (typeof value !== "number") { - throw new errors.ERR_INVALID_ARG_TYPE(name, "number", value); - } - } - function boundsError(value, length, type) { - if (Math.floor(value) !== value) { - validateNumber(value, type); - throw new errors.ERR_OUT_OF_RANGE(type || "offset", "an integer", value); - } - if (length < 0) { - throw new errors.ERR_BUFFER_OUT_OF_BOUNDS(); - } - throw new errors.ERR_OUT_OF_RANGE( - type || "offset", - `>= ${type ? 1 : 0} and <= ${length}`, - value - ); - } - var INVALID_BASE64_RE = /[^+/0-9A-Za-z-_]/g; - function base64clean(str) { - str = str.split("=")[0]; - str = str.trim().replace(INVALID_BASE64_RE, ""); - if (str.length < 2) return ""; - while (str.length % 4 !== 0) { - str = str + "="; - } - return str; - } - function utf8ToBytes2(string, units) { - units = units || Infinity; - let codePoint; - const length = string.length; - let leadSurrogate = null; - const bytes = []; - for (let i = 0; i < length; ++i) { - codePoint = string.charCodeAt(i); - if (codePoint > 55295 && codePoint < 57344) { - if (!leadSurrogate) { - if (codePoint > 56319) { - if ((units -= 3) > -1) bytes.push(239, 191, 189); - continue; - } else if (i + 1 === length) { - if ((units -= 3) > -1) bytes.push(239, 191, 189); - continue; - } - leadSurrogate = codePoint; - continue; - } - if (codePoint < 56320) { - if ((units -= 3) > -1) bytes.push(239, 191, 189); - leadSurrogate = codePoint; - continue; - } - codePoint = (leadSurrogate - 55296 << 10 | codePoint - 56320) + 65536; - } else if (leadSurrogate) { - if ((units -= 3) > -1) bytes.push(239, 191, 189); - } - leadSurrogate = null; - if (codePoint < 128) { - if ((units -= 1) < 0) break; - bytes.push(codePoint); - } else if (codePoint < 2048) { - if ((units -= 2) < 0) break; - bytes.push( - codePoint >> 6 | 192, - codePoint & 63 | 128 - ); - } else if (codePoint < 65536) { - if ((units -= 3) < 0) break; - bytes.push( - codePoint >> 12 | 224, - codePoint >> 6 & 63 | 128, - codePoint & 63 | 128 - ); - } else if (codePoint < 1114112) { - if ((units -= 4) < 0) break; - bytes.push( - codePoint >> 18 | 240, - codePoint >> 12 & 63 | 128, - codePoint >> 6 & 63 | 128, - codePoint & 63 | 128 - ); - } else { - throw new Error("Invalid code point"); - } - } - return bytes; - } - function asciiToBytes2(str) { - const byteArray = []; - for (let i = 0; i < str.length; ++i) { - byteArray.push(str.charCodeAt(i) & 255); - } - return byteArray; - } - function utf16leToBytes(str, units) { - let c, hi, lo; - const byteArray = []; - for (let i = 0; i < str.length; ++i) { - if ((units -= 2) < 0) break; - c = str.charCodeAt(i); - hi = c >> 8; - lo = c % 256; - byteArray.push(lo); - byteArray.push(hi); - } - return byteArray; - } - function base64ToBytes(str) { - return base64.toByteArray(base64clean(str)); - } - function blitBuffer(src, dst, offset, length) { - let i; - for (i = 0; i < length; ++i) { - if (i + offset >= dst.length || i >= src.length) break; - dst[i + offset] = src[i]; - } - return i; - } - function isInstance(obj, type) { - return obj instanceof type || obj != null && obj.constructor != null && obj.constructor.name != null && obj.constructor.name === type.name; - } - function numberIsNaN(obj) { - return obj !== obj; - } - var hexSliceLookupTable = function() { - const alphabet = "0123456789abcdef"; - const table = new Array(256); - for (let i = 0; i < 16; ++i) { - const i16 = i * 16; - for (let j = 0; j < 16; ++j) { - table[i16 + j] = alphabet[i] + alphabet[j]; - } - } - return table; - }(); - function defineBigIntMethod(fn) { - return typeof BigInt === "undefined" ? BufferBigIntNotDefined : fn; - } - function BufferBigIntNotDefined() { - throw new Error("BigInt not supported"); - } - } -}); - -// node_modules/@noble/hashes/crypto.js -var require_crypto = __commonJS({ - "node_modules/@noble/hashes/crypto.js"(exports) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.crypto = void 0; - exports.crypto = typeof globalThis === "object" && "crypto" in globalThis ? globalThis.crypto : void 0; - } -}); - -// node_modules/@noble/hashes/utils.js -var require_utils = __commonJS({ - "node_modules/@noble/hashes/utils.js"(exports) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.wrapXOFConstructorWithOpts = exports.wrapConstructorWithOpts = exports.wrapConstructor = exports.Hash = exports.nextTick = exports.swap32IfBE = exports.byteSwapIfBE = exports.swap8IfBE = exports.isLE = void 0; - exports.isBytes = isBytes2; - exports.anumber = anumber2; - exports.abytes = abytes2; - exports.ahash = ahash; - exports.aexists = aexists2; - exports.aoutput = aoutput2; - exports.u8 = u8; - exports.u32 = u32; - exports.clean = clean2; - exports.createView = createView2; - exports.rotr = rotr2; - exports.rotl = rotl; - exports.byteSwap = byteSwap; - exports.byteSwap32 = byteSwap32; - exports.bytesToHex = bytesToHex3; - exports.hexToBytes = hexToBytes3; - exports.asyncLoop = asyncLoop; - exports.utf8ToBytes = utf8ToBytes2; - exports.bytesToUtf8 = bytesToUtf82; - exports.toBytes = toBytes2; - exports.kdfInputToBytes = kdfInputToBytes; - exports.concatBytes = concatBytes2; - exports.checkOpts = checkOpts; - exports.createHasher = createHasher2; - exports.createOptHasher = createOptHasher; - exports.createXOFer = createXOFer; - exports.randomBytes = randomBytes2; - var crypto_1 = require_crypto(); - function isBytes2(a) { - return a instanceof Uint8Array || ArrayBuffer.isView(a) && a.constructor.name === "Uint8Array"; - } - function anumber2(n) { - if (!Number.isSafeInteger(n) || n < 0) - throw new Error("positive integer expected, got " + n); - } - function abytes2(b, ...lengths) { - if (!isBytes2(b)) - throw new Error("Uint8Array expected"); - if (lengths.length > 0 && !lengths.includes(b.length)) - throw new Error("Uint8Array expected of length " + lengths + ", got length=" + b.length); - } - function ahash(h) { - if (typeof h !== "function" || typeof h.create !== "function") - throw new Error("Hash should be wrapped by utils.createHasher"); - anumber2(h.outputLen); - anumber2(h.blockLen); - } - function aexists2(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 aoutput2(out, instance) { - abytes2(out); - const min = instance.outputLen; - if (out.length < min) { - throw new Error("digestInto() expects output buffer of length at least " + min); - } - } - function u8(arr) { - return new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength); - } - function u32(arr) { - return new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4)); - } - function clean2(...arrays) { - for (let i = 0; i < arrays.length; i++) { - arrays[i].fill(0); - } - } - function createView2(arr) { - return new DataView(arr.buffer, arr.byteOffset, arr.byteLength); - } - function rotr2(word, shift) { - return word << 32 - shift | word >>> shift; - } - function rotl(word, shift) { - return word << shift | word >>> 32 - shift >>> 0; - } - exports.isLE = (() => new Uint8Array(new Uint32Array([287454020]).buffer)[0] === 68)(); - function byteSwap(word) { - return word << 24 & 4278190080 | word << 8 & 16711680 | word >>> 8 & 65280 | word >>> 24 & 255; - } - exports.swap8IfBE = exports.isLE ? (n) => n : (n) => byteSwap(n); - exports.byteSwapIfBE = exports.swap8IfBE; - function byteSwap32(arr) { - for (let i = 0; i < arr.length; i++) { - arr[i] = byteSwap(arr[i]); - } - return arr; - } - exports.swap32IfBE = exports.isLE ? (u) => u : byteSwap32; - var hasHexBuiltin = (() => ( - // @ts-ignore - typeof Uint8Array.from([]).toHex === "function" && typeof Uint8Array.fromHex === "function" - ))(); - var hexes = Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, "0")); - function bytesToHex3(bytes) { - abytes2(bytes); - if (hasHexBuiltin) - return bytes.toHex(); - let hex = ""; - for (let i = 0; i < bytes.length; i++) { - hex += hexes[bytes[i]]; - } - return hex; - } - var asciis = { _0: 48, _9: 57, A: 65, F: 70, a: 97, f: 102 }; - function asciiToBase16(ch) { - if (ch >= asciis._0 && ch <= asciis._9) - return ch - asciis._0; - if (ch >= asciis.A && ch <= asciis.F) - return ch - (asciis.A - 10); - if (ch >= asciis.a && ch <= asciis.f) - return ch - (asciis.a - 10); - return; - } - function hexToBytes3(hex) { - if (typeof hex !== "string") - throw new Error("hex string expected, got " + typeof hex); - if (hasHexBuiltin) - return Uint8Array.fromHex(hex); - const hl = hex.length; - const al = hl / 2; - if (hl % 2) - throw new Error("hex string expected, got unpadded hex of length " + hl); - const array = new Uint8Array(al); - for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) { - const n1 = asciiToBase16(hex.charCodeAt(hi)); - const n2 = asciiToBase16(hex.charCodeAt(hi + 1)); - if (n1 === void 0 || n2 === void 0) { - const char = hex[hi] + hex[hi + 1]; - throw new Error('hex string expected, got non-hex character "' + char + '" at index ' + hi); - } - array[ai] = n1 * 16 + n2; - } - return array; - } - var nextTick = async () => { - }; - exports.nextTick = nextTick; - async function asyncLoop(iters, tick, cb) { - let ts = Date.now(); - for (let i = 0; i < iters; i++) { - cb(i); - const diff = Date.now() - ts; - if (diff >= 0 && diff < tick) - continue; - await (0, exports.nextTick)(); - ts += diff; - } - } - function utf8ToBytes2(str) { - if (typeof str !== "string") - throw new Error("string expected"); - return new Uint8Array(new TextEncoder().encode(str)); - } - function bytesToUtf82(bytes) { - return new TextDecoder().decode(bytes); - } - function toBytes2(data) { - if (typeof data === "string") - data = utf8ToBytes2(data); - abytes2(data); - return data; - } - function kdfInputToBytes(data) { - if (typeof data === "string") - data = utf8ToBytes2(data); - abytes2(data); - return data; - } - function concatBytes2(...arrays) { - let sum = 0; - for (let i = 0; i < arrays.length; i++) { - const a = arrays[i]; - abytes2(a); - sum += a.length; - } - const res = new Uint8Array(sum); - for (let i = 0, pad = 0; i < arrays.length; i++) { - const a = arrays[i]; - res.set(a, pad); - pad += a.length; - } - return res; - } - function checkOpts(defaults, opts) { - if (opts !== void 0 && {}.toString.call(opts) !== "[object Object]") - throw new Error("options should be object or undefined"); - const merged = Object.assign(defaults, opts); - return merged; - } - var Hash2 = class { - }; - exports.Hash = Hash2; - function createHasher2(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 createOptHasher(hashCons) { - const hashC = (msg, opts) => hashCons(opts).update(toBytes2(msg)).digest(); - const tmp = hashCons({}); - hashC.outputLen = tmp.outputLen; - hashC.blockLen = tmp.blockLen; - hashC.create = (opts) => hashCons(opts); - return hashC; - } - function createXOFer(hashCons) { - const hashC = (msg, opts) => hashCons(opts).update(toBytes2(msg)).digest(); - const tmp = hashCons({}); - hashC.outputLen = tmp.outputLen; - hashC.blockLen = tmp.blockLen; - hashC.create = (opts) => hashCons(opts); - return hashC; - } - exports.wrapConstructor = createHasher2; - exports.wrapConstructorWithOpts = createOptHasher; - exports.wrapXOFConstructorWithOpts = createXOFer; - function randomBytes2(bytesLength = 32) { - if (crypto_1.crypto && typeof crypto_1.crypto.getRandomValues === "function") { - return crypto_1.crypto.getRandomValues(new Uint8Array(bytesLength)); - } - if (crypto_1.crypto && typeof crypto_1.crypto.randomBytes === "function") { - return Uint8Array.from(crypto_1.crypto.randomBytes(bytesLength)); - } - throw new Error("crypto.getRandomValues must be defined"); - } - } -}); - -// node_modules/@noble/hashes/_md.js -var require_md = __commonJS({ - "node_modules/@noble/hashes/_md.js"(exports) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.SHA512_IV = exports.SHA384_IV = exports.SHA224_IV = exports.SHA256_IV = exports.HashMD = void 0; - exports.setBigUint64 = setBigUint642; - exports.Chi = Chi2; - exports.Maj = Maj2; - var utils_ts_1 = require_utils(); - function setBigUint642(view, byteOffset, value, isLE) { - if (typeof view.setBigUint64 === "function") - return view.setBigUint64(byteOffset, value, isLE); - const _32n2 = BigInt(32); - const _u32_max = BigInt(4294967295); - const wh = Number(value >> _32n2 & _u32_max); - const wl = Number(value & _u32_max); - const h = isLE ? 4 : 0; - const l = isLE ? 0 : 4; - view.setUint32(byteOffset + h, wh, isLE); - view.setUint32(byteOffset + l, wl, isLE); - } - function Chi2(a, b, c) { - return a & b ^ ~a & c; - } - function Maj2(a, b, c) { - return a & b ^ a & c ^ b & c; - } - var HashMD2 = class extends utils_ts_1.Hash { - constructor(blockLen, outputLen, padOffset, isLE) { - super(); - this.finished = false; - this.length = 0; - this.pos = 0; - this.destroyed = false; - this.blockLen = blockLen; - this.outputLen = outputLen; - this.padOffset = padOffset; - this.isLE = isLE; - this.buffer = new Uint8Array(blockLen); - this.view = (0, utils_ts_1.createView)(this.buffer); - } - update(data) { - (0, utils_ts_1.aexists)(this); - data = (0, utils_ts_1.toBytes)(data); - (0, utils_ts_1.abytes)(data); - const { view, buffer, blockLen } = this; - const len = data.length; - for (let pos = 0; pos < len; ) { - const take = Math.min(blockLen - this.pos, len - pos); - if (take === blockLen) { - const dataView = (0, utils_ts_1.createView)(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) { - (0, utils_ts_1.aexists)(this); - (0, utils_ts_1.aoutput)(out, this); - this.finished = true; - const { buffer, view, blockLen, isLE } = this; - let { pos } = this; - buffer[pos++] = 128; - (0, utils_ts_1.clean)(this.buffer.subarray(pos)); - if (this.padOffset > blockLen - pos) { - this.process(view, 0); - pos = 0; - } - for (let i = pos; i < blockLen; i++) - buffer[i] = 0; - setBigUint642(view, blockLen - 8, BigInt(this.length * 8), isLE); - this.process(view, 0); - const oview = (0, utils_ts_1.createView)(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 i = 0; i < outLen; i++) - oview.setUint32(4 * i, state[i], isLE); - } - 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.destroyed = destroyed; - to.finished = finished; - to.length = length; - to.pos = pos; - if (length % blockLen) - to.buffer.set(buffer); - return to; - } - clone() { - return this._cloneInto(); - } - }; - exports.HashMD = HashMD2; - exports.SHA256_IV = Uint32Array.from([ - 1779033703, - 3144134277, - 1013904242, - 2773480762, - 1359893119, - 2600822924, - 528734635, - 1541459225 - ]); - exports.SHA224_IV = Uint32Array.from([ - 3238371032, - 914150663, - 812702999, - 4144912697, - 4290775857, - 1750603025, - 1694076839, - 3204075428 - ]); - exports.SHA384_IV = Uint32Array.from([ - 3418070365, - 3238371032, - 1654270250, - 914150663, - 2438529370, - 812702999, - 355462360, - 4144912697, - 1731405415, - 4290775857, - 2394180231, - 1750603025, - 3675008525, - 1694076839, - 1203062813, - 3204075428 - ]); - exports.SHA512_IV = Uint32Array.from([ - 1779033703, - 4089235720, - 3144134277, - 2227873595, - 1013904242, - 4271175723, - 2773480762, - 1595750129, - 1359893119, - 2917565137, - 2600822924, - 725511199, - 528734635, - 4215389547, - 1541459225, - 327033209 - ]); - } -}); - -// node_modules/@noble/hashes/_u64.js -var require_u64 = __commonJS({ - "node_modules/@noble/hashes/_u64.js"(exports) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.toBig = exports.shrSL = exports.shrSH = exports.rotrSL = exports.rotrSH = exports.rotrBL = exports.rotrBH = exports.rotr32L = exports.rotr32H = exports.rotlSL = exports.rotlSH = exports.rotlBL = exports.rotlBH = exports.add5L = exports.add5H = exports.add4L = exports.add4H = exports.add3L = exports.add3H = void 0; - exports.add = add2; - exports.fromBig = fromBig2; - exports.split = split2; - var U32_MASK642 = BigInt(2 ** 32 - 1); - var _32n2 = BigInt(32); - function fromBig2(n, le = false) { - if (le) - return { h: Number(n & U32_MASK642), l: Number(n >> _32n2 & U32_MASK642) }; - return { h: Number(n >> _32n2 & U32_MASK642) | 0, l: Number(n & U32_MASK642) | 0 }; - } - function split2(lst, le = false) { - const len = lst.length; - let Ah = new Uint32Array(len); - let Al = new Uint32Array(len); - for (let i = 0; i < len; i++) { - const { h, l } = fromBig2(lst[i], le); - [Ah[i], Al[i]] = [h, l]; - } - return [Ah, Al]; - } - var toBig = (h, l) => BigInt(h >>> 0) << _32n2 | BigInt(l >>> 0); - exports.toBig = toBig; - var shrSH2 = (h, _l, s) => h >>> s; - exports.shrSH = shrSH2; - var shrSL2 = (h, l, s) => h << 32 - s | l >>> s; - exports.shrSL = shrSL2; - var rotrSH2 = (h, l, s) => h >>> s | l << 32 - s; - exports.rotrSH = rotrSH2; - var rotrSL2 = (h, l, s) => h << 32 - s | l >>> s; - exports.rotrSL = rotrSL2; - var rotrBH2 = (h, l, s) => h << 64 - s | l >>> s - 32; - exports.rotrBH = rotrBH2; - var rotrBL2 = (h, l, s) => h >>> s - 32 | l << 64 - s; - exports.rotrBL = rotrBL2; - var rotr32H = (_h, l) => l; - exports.rotr32H = rotr32H; - var rotr32L = (h, _l) => h; - exports.rotr32L = rotr32L; - var rotlSH = (h, l, s) => h << s | l >>> 32 - s; - exports.rotlSH = rotlSH; - var rotlSL = (h, l, s) => l << s | h >>> 32 - s; - exports.rotlSL = rotlSL; - var rotlBH = (h, l, s) => l << s - 32 | h >>> 64 - s; - exports.rotlBH = rotlBH; - var rotlBL = (h, l, s) => h << s - 32 | l >>> 64 - s; - exports.rotlBL = rotlBL; - function add2(Ah, Al, Bh, Bl) { - const l = (Al >>> 0) + (Bl >>> 0); - return { h: Ah + Bh + (l / 2 ** 32 | 0) | 0, l: l | 0 }; - } - var add3L2 = (Al, Bl, Cl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0); - exports.add3L = add3L2; - var add3H2 = (low, Ah, Bh, Ch) => Ah + Bh + Ch + (low / 2 ** 32 | 0) | 0; - exports.add3H = add3H2; - var add4L2 = (Al, Bl, Cl, Dl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0); - exports.add4L = add4L2; - var add4H2 = (low, Ah, Bh, Ch, Dh) => Ah + Bh + Ch + Dh + (low / 2 ** 32 | 0) | 0; - exports.add4H = add4H2; - var add5L2 = (Al, Bl, Cl, Dl, El) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0) + (El >>> 0); - exports.add5L = add5L2; - var add5H2 = (low, Ah, Bh, Ch, Dh, Eh) => Ah + Bh + Ch + Dh + Eh + (low / 2 ** 32 | 0) | 0; - exports.add5H = add5H2; - var u64 = { - fromBig: fromBig2, - split: split2, - toBig, - shrSH: shrSH2, - shrSL: shrSL2, - rotrSH: rotrSH2, - rotrSL: rotrSL2, - rotrBH: rotrBH2, - rotrBL: rotrBL2, - rotr32H, - rotr32L, - rotlSH, - rotlSL, - rotlBH, - rotlBL, - add: add2, - add3L: add3L2, - add3H: add3H2, - add4L: add4L2, - add4H: add4H2, - add5H: add5H2, - add5L: add5L2 - }; - exports.default = u64; - } -}); - -// node_modules/@noble/hashes/sha2.js -var require_sha2 = __commonJS({ - "node_modules/@noble/hashes/sha2.js"(exports) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.sha512_224 = exports.sha512_256 = exports.sha384 = exports.sha512 = exports.sha224 = exports.sha256 = exports.SHA512_256 = exports.SHA512_224 = exports.SHA384 = exports.SHA512 = exports.SHA224 = exports.SHA256 = void 0; - var _md_ts_1 = require_md(); - var u64 = require_u64(); - var utils_ts_1 = require_utils(); - var SHA256_K2 = Uint32Array.from([ - 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 SHA256_W2 = new Uint32Array(64); - var SHA2562 = class extends _md_ts_1.HashMD { - constructor(outputLen = 32) { - super(64, outputLen, 8, false); - this.A = _md_ts_1.SHA256_IV[0] | 0; - this.B = _md_ts_1.SHA256_IV[1] | 0; - this.C = _md_ts_1.SHA256_IV[2] | 0; - this.D = _md_ts_1.SHA256_IV[3] | 0; - this.E = _md_ts_1.SHA256_IV[4] | 0; - this.F = _md_ts_1.SHA256_IV[5] | 0; - this.G = _md_ts_1.SHA256_IV[6] | 0; - this.H = _md_ts_1.SHA256_IV[7] | 0; - } - get() { - const { A, B, C, D, E, F, G, H } = this; - return [A, B, C, D, E, F, G, H]; - } - // prettier-ignore - 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 i = 0; i < 16; i++, offset += 4) - SHA256_W2[i] = view.getUint32(offset, false); - for (let i = 16; i < 64; i++) { - const W15 = SHA256_W2[i - 15]; - const W2 = SHA256_W2[i - 2]; - const s0 = (0, utils_ts_1.rotr)(W15, 7) ^ (0, utils_ts_1.rotr)(W15, 18) ^ W15 >>> 3; - const s1 = (0, utils_ts_1.rotr)(W2, 17) ^ (0, utils_ts_1.rotr)(W2, 19) ^ W2 >>> 10; - SHA256_W2[i] = s1 + SHA256_W2[i - 7] + s0 + SHA256_W2[i - 16] | 0; - } - let { A, B, C, D, E, F, G, H } = this; - for (let i = 0; i < 64; i++) { - const sigma1 = (0, utils_ts_1.rotr)(E, 6) ^ (0, utils_ts_1.rotr)(E, 11) ^ (0, utils_ts_1.rotr)(E, 25); - const T1 = H + sigma1 + (0, _md_ts_1.Chi)(E, F, G) + SHA256_K2[i] + SHA256_W2[i] | 0; - const sigma0 = (0, utils_ts_1.rotr)(A, 2) ^ (0, utils_ts_1.rotr)(A, 13) ^ (0, utils_ts_1.rotr)(A, 22); - const T2 = sigma0 + (0, _md_ts_1.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() { - (0, utils_ts_1.clean)(SHA256_W2); - } - destroy() { - this.set(0, 0, 0, 0, 0, 0, 0, 0); - (0, utils_ts_1.clean)(this.buffer); - } - }; - exports.SHA256 = SHA2562; - var SHA2242 = class extends SHA2562 { - constructor() { - super(28); - this.A = _md_ts_1.SHA224_IV[0] | 0; - this.B = _md_ts_1.SHA224_IV[1] | 0; - this.C = _md_ts_1.SHA224_IV[2] | 0; - this.D = _md_ts_1.SHA224_IV[3] | 0; - this.E = _md_ts_1.SHA224_IV[4] | 0; - this.F = _md_ts_1.SHA224_IV[5] | 0; - this.G = _md_ts_1.SHA224_IV[6] | 0; - this.H = _md_ts_1.SHA224_IV[7] | 0; - } - }; - exports.SHA224 = SHA2242; - var K5122 = (() => u64.split([ - "0x428a2f98d728ae22", - "0x7137449123ef65cd", - "0xb5c0fbcfec4d3b2f", - "0xe9b5dba58189dbbc", - "0x3956c25bf348b538", - "0x59f111f1b605d019", - "0x923f82a4af194f9b", - "0xab1c5ed5da6d8118", - "0xd807aa98a3030242", - "0x12835b0145706fbe", - "0x243185be4ee4b28c", - "0x550c7dc3d5ffb4e2", - "0x72be5d74f27b896f", - "0x80deb1fe3b1696b1", - "0x9bdc06a725c71235", - "0xc19bf174cf692694", - "0xe49b69c19ef14ad2", - "0xefbe4786384f25e3", - "0x0fc19dc68b8cd5b5", - "0x240ca1cc77ac9c65", - "0x2de92c6f592b0275", - "0x4a7484aa6ea6e483", - "0x5cb0a9dcbd41fbd4", - "0x76f988da831153b5", - "0x983e5152ee66dfab", - "0xa831c66d2db43210", - "0xb00327c898fb213f", - "0xbf597fc7beef0ee4", - "0xc6e00bf33da88fc2", - "0xd5a79147930aa725", - "0x06ca6351e003826f", - "0x142929670a0e6e70", - "0x27b70a8546d22ffc", - "0x2e1b21385c26c926", - "0x4d2c6dfc5ac42aed", - "0x53380d139d95b3df", - "0x650a73548baf63de", - "0x766a0abb3c77b2a8", - "0x81c2c92e47edaee6", - "0x92722c851482353b", - "0xa2bfe8a14cf10364", - "0xa81a664bbc423001", - "0xc24b8b70d0f89791", - "0xc76c51a30654be30", - "0xd192e819d6ef5218", - "0xd69906245565a910", - "0xf40e35855771202a", - "0x106aa07032bbd1b8", - "0x19a4c116b8d2d0c8", - "0x1e376c085141ab53", - "0x2748774cdf8eeb99", - "0x34b0bcb5e19b48a8", - "0x391c0cb3c5c95a63", - "0x4ed8aa4ae3418acb", - "0x5b9cca4f7763e373", - "0x682e6ff3d6b2b8a3", - "0x748f82ee5defb2fc", - "0x78a5636f43172f60", - "0x84c87814a1f0ab72", - "0x8cc702081a6439ec", - "0x90befffa23631e28", - "0xa4506cebde82bde9", - "0xbef9a3f7b2c67915", - "0xc67178f2e372532b", - "0xca273eceea26619c", - "0xd186b8c721c0c207", - "0xeada7dd6cde0eb1e", - "0xf57d4f7fee6ed178", - "0x06f067aa72176fba", - "0x0a637dc5a2c898a6", - "0x113f9804bef90dae", - "0x1b710b35131c471b", - "0x28db77f523047d84", - "0x32caab7b40c72493", - "0x3c9ebe0a15c9bebc", - "0x431d67c49c100d4c", - "0x4cc5d4becb3e42b6", - "0x597f299cfc657e2a", - "0x5fcb6fab3ad6faec", - "0x6c44198c4a475817" - ].map((n) => BigInt(n))))(); - var SHA512_Kh2 = (() => K5122[0])(); - var SHA512_Kl2 = (() => K5122[1])(); - var SHA512_W_H2 = new Uint32Array(80); - var SHA512_W_L2 = new Uint32Array(80); - var SHA5122 = class extends _md_ts_1.HashMD { - constructor(outputLen = 64) { - super(128, outputLen, 16, false); - this.Ah = _md_ts_1.SHA512_IV[0] | 0; - this.Al = _md_ts_1.SHA512_IV[1] | 0; - this.Bh = _md_ts_1.SHA512_IV[2] | 0; - this.Bl = _md_ts_1.SHA512_IV[3] | 0; - this.Ch = _md_ts_1.SHA512_IV[4] | 0; - this.Cl = _md_ts_1.SHA512_IV[5] | 0; - this.Dh = _md_ts_1.SHA512_IV[6] | 0; - this.Dl = _md_ts_1.SHA512_IV[7] | 0; - this.Eh = _md_ts_1.SHA512_IV[8] | 0; - this.El = _md_ts_1.SHA512_IV[9] | 0; - this.Fh = _md_ts_1.SHA512_IV[10] | 0; - this.Fl = _md_ts_1.SHA512_IV[11] | 0; - this.Gh = _md_ts_1.SHA512_IV[12] | 0; - this.Gl = _md_ts_1.SHA512_IV[13] | 0; - this.Hh = _md_ts_1.SHA512_IV[14] | 0; - this.Hl = _md_ts_1.SHA512_IV[15] | 0; - } - // prettier-ignore - get() { - const { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this; - return [Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl]; - } - // prettier-ignore - set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl) { - this.Ah = Ah | 0; - this.Al = Al | 0; - this.Bh = Bh | 0; - this.Bl = Bl | 0; - this.Ch = Ch | 0; - this.Cl = Cl | 0; - this.Dh = Dh | 0; - this.Dl = Dl | 0; - this.Eh = Eh | 0; - this.El = El | 0; - this.Fh = Fh | 0; - this.Fl = Fl | 0; - this.Gh = Gh | 0; - this.Gl = Gl | 0; - this.Hh = Hh | 0; - this.Hl = Hl | 0; - } - process(view, offset) { - for (let i = 0; i < 16; i++, offset += 4) { - SHA512_W_H2[i] = view.getUint32(offset); - SHA512_W_L2[i] = view.getUint32(offset += 4); - } - for (let i = 16; i < 80; i++) { - const W15h = SHA512_W_H2[i - 15] | 0; - const W15l = SHA512_W_L2[i - 15] | 0; - const s0h = u64.rotrSH(W15h, W15l, 1) ^ u64.rotrSH(W15h, W15l, 8) ^ u64.shrSH(W15h, W15l, 7); - const s0l = u64.rotrSL(W15h, W15l, 1) ^ u64.rotrSL(W15h, W15l, 8) ^ u64.shrSL(W15h, W15l, 7); - const W2h = SHA512_W_H2[i - 2] | 0; - const W2l = SHA512_W_L2[i - 2] | 0; - const s1h = u64.rotrSH(W2h, W2l, 19) ^ u64.rotrBH(W2h, W2l, 61) ^ u64.shrSH(W2h, W2l, 6); - const s1l = u64.rotrSL(W2h, W2l, 19) ^ u64.rotrBL(W2h, W2l, 61) ^ u64.shrSL(W2h, W2l, 6); - const SUMl = u64.add4L(s0l, s1l, SHA512_W_L2[i - 7], SHA512_W_L2[i - 16]); - const SUMh = u64.add4H(SUMl, s0h, s1h, SHA512_W_H2[i - 7], SHA512_W_H2[i - 16]); - SHA512_W_H2[i] = SUMh | 0; - SHA512_W_L2[i] = SUMl | 0; - } - let { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this; - for (let i = 0; i < 80; i++) { - const sigma1h = u64.rotrSH(Eh, El, 14) ^ u64.rotrSH(Eh, El, 18) ^ u64.rotrBH(Eh, El, 41); - const sigma1l = u64.rotrSL(Eh, El, 14) ^ u64.rotrSL(Eh, El, 18) ^ u64.rotrBL(Eh, El, 41); - const CHIh = Eh & Fh ^ ~Eh & Gh; - const CHIl = El & Fl ^ ~El & Gl; - const T1ll = u64.add5L(Hl, sigma1l, CHIl, SHA512_Kl2[i], SHA512_W_L2[i]); - const T1h = u64.add5H(T1ll, Hh, sigma1h, CHIh, SHA512_Kh2[i], SHA512_W_H2[i]); - const T1l = T1ll | 0; - const sigma0h = u64.rotrSH(Ah, Al, 28) ^ u64.rotrBH(Ah, Al, 34) ^ u64.rotrBH(Ah, Al, 39); - const sigma0l = u64.rotrSL(Ah, Al, 28) ^ u64.rotrBL(Ah, Al, 34) ^ u64.rotrBL(Ah, Al, 39); - const MAJh = Ah & Bh ^ Ah & Ch ^ Bh & Ch; - const MAJl = Al & Bl ^ Al & Cl ^ Bl & Cl; - Hh = Gh | 0; - Hl = Gl | 0; - Gh = Fh | 0; - Gl = Fl | 0; - Fh = Eh | 0; - Fl = El | 0; - ({ h: Eh, l: El } = u64.add(Dh | 0, Dl | 0, T1h | 0, T1l | 0)); - Dh = Ch | 0; - Dl = Cl | 0; - Ch = Bh | 0; - Cl = Bl | 0; - Bh = Ah | 0; - Bl = Al | 0; - const All = u64.add3L(T1l, sigma0l, MAJl); - Ah = u64.add3H(All, T1h, sigma0h, MAJh); - Al = All | 0; - } - ({ h: Ah, l: Al } = u64.add(this.Ah | 0, this.Al | 0, Ah | 0, Al | 0)); - ({ h: Bh, l: Bl } = u64.add(this.Bh | 0, this.Bl | 0, Bh | 0, Bl | 0)); - ({ h: Ch, l: Cl } = u64.add(this.Ch | 0, this.Cl | 0, Ch | 0, Cl | 0)); - ({ h: Dh, l: Dl } = u64.add(this.Dh | 0, this.Dl | 0, Dh | 0, Dl | 0)); - ({ h: Eh, l: El } = u64.add(this.Eh | 0, this.El | 0, Eh | 0, El | 0)); - ({ h: Fh, l: Fl } = u64.add(this.Fh | 0, this.Fl | 0, Fh | 0, Fl | 0)); - ({ h: Gh, l: Gl } = u64.add(this.Gh | 0, this.Gl | 0, Gh | 0, Gl | 0)); - ({ h: Hh, l: Hl } = u64.add(this.Hh | 0, this.Hl | 0, Hh | 0, Hl | 0)); - this.set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl); - } - roundClean() { - (0, utils_ts_1.clean)(SHA512_W_H2, SHA512_W_L2); - } - destroy() { - (0, utils_ts_1.clean)(this.buffer); - this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0); - } - }; - exports.SHA512 = SHA5122; - var SHA3842 = class extends SHA5122 { - constructor() { - super(48); - this.Ah = _md_ts_1.SHA384_IV[0] | 0; - this.Al = _md_ts_1.SHA384_IV[1] | 0; - this.Bh = _md_ts_1.SHA384_IV[2] | 0; - this.Bl = _md_ts_1.SHA384_IV[3] | 0; - this.Ch = _md_ts_1.SHA384_IV[4] | 0; - this.Cl = _md_ts_1.SHA384_IV[5] | 0; - this.Dh = _md_ts_1.SHA384_IV[6] | 0; - this.Dl = _md_ts_1.SHA384_IV[7] | 0; - this.Eh = _md_ts_1.SHA384_IV[8] | 0; - this.El = _md_ts_1.SHA384_IV[9] | 0; - this.Fh = _md_ts_1.SHA384_IV[10] | 0; - this.Fl = _md_ts_1.SHA384_IV[11] | 0; - this.Gh = _md_ts_1.SHA384_IV[12] | 0; - this.Gl = _md_ts_1.SHA384_IV[13] | 0; - this.Hh = _md_ts_1.SHA384_IV[14] | 0; - this.Hl = _md_ts_1.SHA384_IV[15] | 0; - } - }; - exports.SHA384 = SHA3842; - var T224_IV2 = Uint32Array.from([ - 2352822216, - 424955298, - 1944164710, - 2312950998, - 502970286, - 855612546, - 1738396948, - 1479516111, - 258812777, - 2077511080, - 2011393907, - 79989058, - 1067287976, - 1780299464, - 286451373, - 2446758561 - ]); - var T256_IV2 = Uint32Array.from([ - 573645204, - 4230739756, - 2673172387, - 3360449730, - 596883563, - 1867755857, - 2520282905, - 1497426621, - 2519219938, - 2827943907, - 3193839141, - 1401305490, - 721525244, - 746961066, - 246885852, - 2177182882 - ]); - var SHA512_2242 = class extends SHA5122 { - constructor() { - super(28); - this.Ah = T224_IV2[0] | 0; - this.Al = T224_IV2[1] | 0; - this.Bh = T224_IV2[2] | 0; - this.Bl = T224_IV2[3] | 0; - this.Ch = T224_IV2[4] | 0; - this.Cl = T224_IV2[5] | 0; - this.Dh = T224_IV2[6] | 0; - this.Dl = T224_IV2[7] | 0; - this.Eh = T224_IV2[8] | 0; - this.El = T224_IV2[9] | 0; - this.Fh = T224_IV2[10] | 0; - this.Fl = T224_IV2[11] | 0; - this.Gh = T224_IV2[12] | 0; - this.Gl = T224_IV2[13] | 0; - this.Hh = T224_IV2[14] | 0; - this.Hl = T224_IV2[15] | 0; - } - }; - exports.SHA512_224 = SHA512_2242; - var SHA512_2562 = class extends SHA5122 { - constructor() { - super(32); - this.Ah = T256_IV2[0] | 0; - this.Al = T256_IV2[1] | 0; - this.Bh = T256_IV2[2] | 0; - this.Bl = T256_IV2[3] | 0; - this.Ch = T256_IV2[4] | 0; - this.Cl = T256_IV2[5] | 0; - this.Dh = T256_IV2[6] | 0; - this.Dl = T256_IV2[7] | 0; - this.Eh = T256_IV2[8] | 0; - this.El = T256_IV2[9] | 0; - this.Fh = T256_IV2[10] | 0; - this.Fl = T256_IV2[11] | 0; - this.Gh = T256_IV2[12] | 0; - this.Gl = T256_IV2[13] | 0; - this.Hh = T256_IV2[14] | 0; - this.Hl = T256_IV2[15] | 0; - } - }; - exports.SHA512_256 = SHA512_2562; - exports.sha256 = (0, utils_ts_1.createHasher)(() => new SHA2562()); - exports.sha224 = (0, utils_ts_1.createHasher)(() => new SHA2242()); - exports.sha512 = (0, utils_ts_1.createHasher)(() => new SHA5122()); - exports.sha384 = (0, utils_ts_1.createHasher)(() => new SHA3842()); - exports.sha512_256 = (0, utils_ts_1.createHasher)(() => new SHA512_2562()); - exports.sha512_224 = (0, utils_ts_1.createHasher)(() => new SHA512_2242()); - } -}); - -// node_modules/@noble/hashes/hmac.js -var require_hmac = __commonJS({ - "node_modules/@noble/hashes/hmac.js"(exports) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.hmac = exports.HMAC = void 0; - var utils_ts_1 = require_utils(); - var HMAC = class extends utils_ts_1.Hash { - constructor(hash, _key) { - super(); - this.finished = false; - this.destroyed = false; - (0, utils_ts_1.ahash)(hash); - const key = (0, utils_ts_1.toBytes)(_key); - this.iHash = hash.create(); - if (typeof this.iHash.update !== "function") - throw new Error("Expected instance of class which extends utils.Hash"); - this.blockLen = this.iHash.blockLen; - this.outputLen = this.iHash.outputLen; - const blockLen = this.blockLen; - const pad = new Uint8Array(blockLen); - pad.set(key.length > blockLen ? hash.create().update(key).digest() : key); - for (let i = 0; i < pad.length; i++) - pad[i] ^= 54; - this.iHash.update(pad); - this.oHash = hash.create(); - for (let i = 0; i < pad.length; i++) - pad[i] ^= 54 ^ 92; - this.oHash.update(pad); - (0, utils_ts_1.clean)(pad); - } - update(buf) { - (0, utils_ts_1.aexists)(this); - this.iHash.update(buf); - return this; - } - digestInto(out) { - (0, utils_ts_1.aexists)(this); - (0, utils_ts_1.abytes)(out, this.outputLen); - this.finished = true; - this.iHash.digestInto(out); - this.oHash.update(out); - this.oHash.digestInto(out); - this.destroy(); - } - digest() { - const out = new Uint8Array(this.oHash.outputLen); - this.digestInto(out); - return out; - } - _cloneInto(to) { - to || (to = Object.create(Object.getPrototypeOf(this), {})); - const { oHash, iHash, finished, destroyed, blockLen, outputLen } = this; - to = to; - to.finished = finished; - to.destroyed = destroyed; - to.blockLen = blockLen; - to.outputLen = outputLen; - to.oHash = oHash._cloneInto(to.oHash); - to.iHash = iHash._cloneInto(to.iHash); - return to; - } - clone() { - return this._cloneInto(); - } - destroy() { - this.destroyed = true; - this.oHash.destroy(); - this.iHash.destroy(); - } - }; - exports.HMAC = HMAC; - var hmac = (hash, key, message) => new HMAC(hash, key).update(message).digest(); - exports.hmac = hmac; - exports.hmac.create = (hash, key) => new HMAC(hash, key); - } -}); - -// node_modules/@noble/curves/utils.js -var require_utils2 = __commonJS({ - "node_modules/@noble/curves/utils.js"(exports) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.notImplemented = exports.bitMask = exports.utf8ToBytes = exports.randomBytes = exports.isBytes = exports.hexToBytes = exports.concatBytes = exports.bytesToUtf8 = exports.bytesToHex = exports.anumber = exports.abytes = void 0; - exports.abool = abool2; - exports._abool2 = _abool2; - exports._abytes2 = _abytes2; - exports.numberToHexUnpadded = numberToHexUnpadded2; - exports.hexToNumber = hexToNumber3; - exports.bytesToNumberBE = bytesToNumberBE2; - exports.bytesToNumberLE = bytesToNumberLE2; - exports.numberToBytesBE = numberToBytesBE2; - exports.numberToBytesLE = numberToBytesLE2; - exports.numberToVarBytesBE = numberToVarBytesBE2; - exports.ensureBytes = ensureBytes2; - exports.equalBytes = equalBytes2; - exports.copyBytes = copyBytes2; - exports.asciiToBytes = asciiToBytes2; - exports.inRange = inRange2; - exports.aInRange = aInRange2; - exports.bitLen = bitLen2; - exports.bitGet = bitGet2; - exports.bitSet = bitSet2; - exports.createHmacDrbg = createHmacDrbg2; - exports.validateObject = validateObject2; - exports.isHash = isHash2; - exports._validateObject = _validateObject; - exports.memoized = memoized2; - var utils_js_1 = require_utils(); - var utils_js_2 = require_utils(); - Object.defineProperty(exports, "abytes", { enumerable: true, get: function() { - return utils_js_2.abytes; - } }); - Object.defineProperty(exports, "anumber", { enumerable: true, get: function() { - return utils_js_2.anumber; - } }); - Object.defineProperty(exports, "bytesToHex", { enumerable: true, get: function() { - return utils_js_2.bytesToHex; - } }); - Object.defineProperty(exports, "bytesToUtf8", { enumerable: true, get: function() { - return utils_js_2.bytesToUtf8; - } }); - Object.defineProperty(exports, "concatBytes", { enumerable: true, get: function() { - return utils_js_2.concatBytes; - } }); - Object.defineProperty(exports, "hexToBytes", { enumerable: true, get: function() { - return utils_js_2.hexToBytes; - } }); - Object.defineProperty(exports, "isBytes", { enumerable: true, get: function() { - return utils_js_2.isBytes; - } }); - Object.defineProperty(exports, "randomBytes", { enumerable: true, get: function() { - return utils_js_2.randomBytes; - } }); - Object.defineProperty(exports, "utf8ToBytes", { enumerable: true, get: function() { - return utils_js_2.utf8ToBytes; - } }); - var _0n2 = BigInt(0); - var _1n2 = BigInt(1); - function abool2(title, value) { - if (typeof value !== "boolean") - throw new Error(title + " boolean expected, got " + value); - } - function _abool2(value, title = "") { - if (typeof value !== "boolean") { - const prefix = title && `"${title}"`; - throw new Error(prefix + "expected boolean, got type=" + typeof value); - } - return value; - } - function _abytes2(value, length, title = "") { - const bytes = (0, utils_js_1.isBytes)(value); - const len = value == null ? void 0 : value.length; - const needsLen = length !== void 0; - if (!bytes || needsLen && len !== length) { - const prefix = title && `"${title}" `; - const ofLen = needsLen ? ` of length ${length}` : ""; - const got = bytes ? `length=${len}` : `type=${typeof value}`; - throw new Error(prefix + "expected Uint8Array" + ofLen + ", got " + got); - } - return value; - } - function numberToHexUnpadded2(num) { - const hex = num.toString(16); - return hex.length & 1 ? "0" + hex : hex; - } - function hexToNumber3(hex) { - if (typeof hex !== "string") - throw new Error("hex string expected, got " + typeof hex); - return hex === "" ? _0n2 : BigInt("0x" + hex); - } - function bytesToNumberBE2(bytes) { - return hexToNumber3((0, utils_js_1.bytesToHex)(bytes)); - } - function bytesToNumberLE2(bytes) { - (0, utils_js_1.abytes)(bytes); - return hexToNumber3((0, utils_js_1.bytesToHex)(Uint8Array.from(bytes).reverse())); - } - function numberToBytesBE2(n, len) { - return (0, utils_js_1.hexToBytes)(n.toString(16).padStart(len * 2, "0")); - } - function numberToBytesLE2(n, len) { - return numberToBytesBE2(n, len).reverse(); - } - function numberToVarBytesBE2(n) { - return (0, utils_js_1.hexToBytes)(numberToHexUnpadded2(n)); - } - function ensureBytes2(title, hex, expectedLength) { - let res; - if (typeof hex === "string") { - try { - res = (0, utils_js_1.hexToBytes)(hex); - } catch (e) { - throw new Error(title + " must be hex string or Uint8Array, cause: " + e); - } - } else if ((0, utils_js_1.isBytes)(hex)) { - res = Uint8Array.from(hex); - } 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 + " of length " + expectedLength + " expected, got " + len); - return res; - } - function equalBytes2(a, b) { - if (a.length !== b.length) - return false; - let diff = 0; - for (let i = 0; i < a.length; i++) - diff |= a[i] ^ b[i]; - return diff === 0; - } - function copyBytes2(bytes) { - return Uint8Array.from(bytes); - } - function asciiToBytes2(ascii) { - return Uint8Array.from(ascii, (c, i) => { - const charCode = c.charCodeAt(0); - if (c.length !== 1 || charCode > 127) { - throw new Error(`string contains non-ASCII character "${ascii[i]}" with code ${charCode} at position ${i}`); - } - return charCode; - }); - } - var isPosBig = (n) => typeof n === "bigint" && _0n2 <= n; - function inRange2(n, min, max) { - return isPosBig(n) && isPosBig(min) && isPosBig(max) && min <= n && n < max; - } - function aInRange2(title, n, min, max) { - if (!inRange2(n, min, max)) - throw new Error("expected valid " + title + ": " + min + " <= n < " + max + ", got " + n); - } - function bitLen2(n) { - let len; - for (len = 0; n > _0n2; n >>= _1n2, len += 1) - ; - return len; - } - function bitGet2(n, pos) { - return n >> BigInt(pos) & _1n2; - } - function bitSet2(n, pos, value) { - return n | (value ? _1n2 : _0n2) << BigInt(pos); - } - var bitMask2 = (n) => (_1n2 << BigInt(n)) - _1n2; - exports.bitMask = bitMask2; - function createHmacDrbg2(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"); - const u8n = (len) => new Uint8Array(len); - const u8of = (byte) => Uint8Array.of(byte); - let v = u8n(hashLen); - let k = u8n(hashLen); - let i = 0; - const reset = () => { - v.fill(1); - k.fill(0); - i = 0; - }; - const h = (...b) => hmacFn(k, v, ...b); - const reseed = (seed = u8n(0)) => { - k = h(u8of(0), seed); - v = h(); - if (seed.length === 0) - return; - k = h(u8of(1), seed); - v = h(); - }; - const gen = () => { - if (i++ >= 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 (0, utils_js_1.concatBytes)(...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" || (0, utils_js_1.isBytes)(val), - 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 validateObject2(object, validators, optValidators = {}) { - const checkField = (fieldName, type, isOptional) => { - const checkVal = validatorFns[type]; - if (typeof checkVal !== "function") - throw new Error("invalid validator function"); - const val = object[fieldName]; - if (isOptional && val === void 0) - return; - if (!checkVal(val, object)) { - throw new Error("param " + String(fieldName) + " is invalid. Expected " + type + ", got " + val); - } - }; - 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; - } - function isHash2(val) { - return typeof val === "function" && Number.isSafeInteger(val.outputLen); - } - function _validateObject(object, fields, optFields = {}) { - if (!object || typeof object !== "object") - throw new Error("expected valid options object"); - function checkField(fieldName, expectedType, isOpt) { - const val = object[fieldName]; - if (isOpt && val === void 0) - return; - const current = typeof val; - if (current !== expectedType || val === null) - throw new Error(`param "${fieldName}" is invalid: expected ${expectedType}, got ${current}`); - } - Object.entries(fields).forEach(([k, v]) => checkField(k, v, false)); - Object.entries(optFields).forEach(([k, v]) => checkField(k, v, true)); - } - var notImplemented2 = () => { - throw new Error("not implemented"); - }; - exports.notImplemented = notImplemented2; - function memoized2(fn) { - const map2 = /* @__PURE__ */ new WeakMap(); - return (arg, ...args) => { - const val = map2.get(arg); - if (val !== void 0) - return val; - const computed = fn(arg, ...args); - map2.set(arg, computed); - return computed; - }; - } - } -}); - -// node_modules/@noble/curves/abstract/modular.js -var require_modular = __commonJS({ - "node_modules/@noble/curves/abstract/modular.js"(exports) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.isNegativeLE = void 0; - exports.mod = mod; - exports.pow = pow; - exports.pow2 = pow2; - exports.invert = invert; - exports.tonelliShanks = tonelliShanks; - exports.FpSqrt = FpSqrt; - exports.validateField = validateField; - exports.FpPow = FpPow; - exports.FpInvertBatch = FpInvertBatch; - exports.FpDiv = FpDiv; - exports.FpLegendre = FpLegendre; - exports.FpIsSquare = FpIsSquare; - exports.nLength = nLength; - exports.Field = Field; - exports.FpSqrtOdd = FpSqrtOdd; - exports.FpSqrtEven = FpSqrtEven; - exports.hashToPrivateScalar = hashToPrivateScalar; - exports.getFieldBytesLength = getFieldBytesLength; - exports.getMinHashLength = getMinHashLength; - exports.mapHashToField = mapHashToField; - var utils_ts_1 = require_utils2(); - var _0n2 = BigInt(0); - var _1n2 = BigInt(1); - var _2n = BigInt(2); - var _3n = BigInt(3); - var _4n = BigInt(4); - var _5n = BigInt(5); - var _7n = BigInt(7); - 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 + result; - } - function pow(num, power, modulo) { - return FpPow(Field(modulo), num, power); - } - function pow2(x, power, modulo) { - let res = x; - while (power-- > _0n2) { - res *= res; - res %= modulo; - } - return res; - } - function invert(number, modulo) { - if (number === _0n2) - throw new Error("invert: expected non-zero number"); - if (modulo <= _0n2) - throw new Error("invert: expected positive modulus, got " + modulo); - let a = mod(number, modulo); - let b = modulo; - let x = _0n2, y = _1n2, u = _1n2, v = _0n2; - while (a !== _0n2) { - const q = b / a; - const r = b % a; - const m = x - u * q; - const n = y - v * q; - b = a, a = r, x = u, y = v, u = m, v = n; - } - const gcd = b; - if (gcd !== _1n2) - throw new Error("invert: does not exist"); - return mod(x, modulo); - } - function assertIsSquare(Fp, root, n) { - if (!Fp.eql(Fp.sqr(root), n)) - throw new Error("Cannot find square root"); - } - function sqrt3mod4(Fp, n) { - const p1div4 = (Fp.ORDER + _1n2) / _4n; - const root = Fp.pow(n, p1div4); - assertIsSquare(Fp, root, n); - return root; - } - function sqrt5mod8(Fp, n) { - const p5div8 = (Fp.ORDER - _5n) / _8n; - const n2 = Fp.mul(n, _2n); - const v = Fp.pow(n2, p5div8); - const nv = Fp.mul(n, v); - const i = Fp.mul(Fp.mul(nv, _2n), v); - const root = Fp.mul(nv, Fp.sub(i, Fp.ONE)); - assertIsSquare(Fp, root, n); - return root; - } - function sqrt9mod16(P) { - const Fp_ = Field(P); - const tn = tonelliShanks(P); - const c1 = tn(Fp_, Fp_.neg(Fp_.ONE)); - const c2 = tn(Fp_, c1); - const c3 = tn(Fp_, Fp_.neg(c1)); - const c4 = (P + _7n) / _16n; - return (Fp, n) => { - let tv1 = Fp.pow(n, c4); - let tv2 = Fp.mul(tv1, c1); - const tv3 = Fp.mul(tv1, c2); - const tv4 = Fp.mul(tv1, c3); - const e1 = Fp.eql(Fp.sqr(tv2), n); - const e2 = Fp.eql(Fp.sqr(tv3), n); - tv1 = Fp.cmov(tv1, tv2, e1); - tv2 = Fp.cmov(tv4, tv3, e2); - const e3 = Fp.eql(Fp.sqr(tv2), n); - const root = Fp.cmov(tv1, tv2, e3); - assertIsSquare(Fp, root, n); - return root; - }; - } - function tonelliShanks(P) { - if (P < _3n) - throw new Error("sqrt is not defined for small field"); - let Q = P - _1n2; - let S = 0; - while (Q % _2n === _0n2) { - Q /= _2n; - S++; - } - let Z = _2n; - const _Fp = Field(P); - while (FpLegendre(_Fp, Z) === 1) { - if (Z++ > 1e3) - throw new Error("Cannot find square root: probably non-prime P"); - } - if (S === 1) - return sqrt3mod4; - let cc = _Fp.pow(Z, Q); - const Q1div2 = (Q + _1n2) / _2n; - return function tonelliSlow(Fp, n) { - if (Fp.is0(n)) - return n; - if (FpLegendre(Fp, n) !== 1) - throw new Error("Cannot find square root"); - let M = S; - let c = Fp.mul(Fp.ONE, cc); - let t = Fp.pow(n, Q); - let R = Fp.pow(n, Q1div2); - while (!Fp.eql(t, Fp.ONE)) { - if (Fp.is0(t)) - return Fp.ZERO; - let i = 1; - let t_tmp = Fp.sqr(t); - while (!Fp.eql(t_tmp, Fp.ONE)) { - i++; - t_tmp = Fp.sqr(t_tmp); - if (i === M) - throw new Error("Cannot find square root"); - } - const exponent = _1n2 << BigInt(M - i - 1); - const b = Fp.pow(c, exponent); - M = i; - c = Fp.sqr(b); - t = Fp.mul(t, c); - R = Fp.mul(R, b); - } - return R; - }; - } - function FpSqrt(P) { - if (P % _4n === _3n) - return sqrt3mod4; - if (P % _8n === _5n) - return sqrt5mod8; - if (P % _16n === _9n) - return sqrt9mod16(P); - return tonelliShanks(P); - } - var isNegativeLE = (num, modulo) => (mod(num, modulo) & _1n2) === _1n2; - exports.isNegativeLE = isNegativeLE; - var FIELD_FIELDS = [ - "create", - "isValid", - "is0", - "neg", - "inv", - "sqrt", - "sqr", - "eql", - "add", - "sub", - "mul", - "pow", - "div", - "addN", - "subN", - "mulN", - "sqrN" - ]; - function validateField(field) { - const initial = { - ORDER: "bigint", - MASK: "bigint", - BYTES: "number", - BITS: "number" - }; - const opts = FIELD_FIELDS.reduce((map2, val) => { - map2[val] = "function"; - return map2; - }, initial); - (0, utils_ts_1._validateObject)(field, opts); - return field; - } - function FpPow(Fp, num, power) { - if (power < _0n2) - throw new Error("invalid exponent, negatives unsupported"); - if (power === _0n2) - return Fp.ONE; - if (power === _1n2) - return num; - let p = Fp.ONE; - let d = num; - while (power > _0n2) { - if (power & _1n2) - p = Fp.mul(p, d); - d = Fp.sqr(d); - power >>= _1n2; - } - return p; - } - function FpInvertBatch(Fp, nums, passZero = false) { - const inverted = new Array(nums.length).fill(passZero ? Fp.ZERO : void 0); - const multipliedAcc = nums.reduce((acc, num, i) => { - if (Fp.is0(num)) - return acc; - inverted[i] = acc; - return Fp.mul(acc, num); - }, Fp.ONE); - const invertedAcc = Fp.inv(multipliedAcc); - nums.reduceRight((acc, num, i) => { - if (Fp.is0(num)) - return acc; - inverted[i] = Fp.mul(acc, inverted[i]); - return Fp.mul(acc, num); - }, invertedAcc); - return inverted; - } - function FpDiv(Fp, lhs, rhs) { - return Fp.mul(lhs, typeof rhs === "bigint" ? invert(rhs, Fp.ORDER) : Fp.inv(rhs)); - } - function FpLegendre(Fp, n) { - const p1mod2 = (Fp.ORDER - _1n2) / _2n; - const powered = Fp.pow(n, p1mod2); - const yes = Fp.eql(powered, Fp.ONE); - const zero = Fp.eql(powered, Fp.ZERO); - const no = Fp.eql(powered, Fp.neg(Fp.ONE)); - if (!yes && !zero && !no) - throw new Error("invalid Legendre symbol result"); - return yes ? 1 : zero ? 0 : -1; - } - function FpIsSquare(Fp, n) { - const l = FpLegendre(Fp, n); - return l === 1; - } - function nLength(n, nBitLength) { - if (nBitLength !== void 0) - (0, utils_ts_1.anumber)(nBitLength); - const _nBitLength = nBitLength !== void 0 ? nBitLength : n.toString(2).length; - const nByteLength = Math.ceil(_nBitLength / 8); - return { nBitLength: _nBitLength, nByteLength }; - } - function Field(ORDER, bitLenOrOpts, isLE = false, opts = {}) { - if (ORDER <= _0n2) - throw new Error("invalid field: expected ORDER > 0, got " + ORDER); - let _nbitLength = void 0; - let _sqrt = void 0; - let modFromBytes = false; - let allowedLengths = void 0; - if (typeof bitLenOrOpts === "object" && bitLenOrOpts != null) { - if (opts.sqrt || isLE) - throw new Error("cannot specify opts in two arguments"); - const _opts = bitLenOrOpts; - if (_opts.BITS) - _nbitLength = _opts.BITS; - if (_opts.sqrt) - _sqrt = _opts.sqrt; - if (typeof _opts.isLE === "boolean") - isLE = _opts.isLE; - if (typeof _opts.modFromBytes === "boolean") - modFromBytes = _opts.modFromBytes; - allowedLengths = _opts.allowedLengths; - } else { - if (typeof bitLenOrOpts === "number") - _nbitLength = bitLenOrOpts; - if (opts.sqrt) - _sqrt = opts.sqrt; - } - const { nBitLength: BITS, nByteLength: BYTES } = nLength(ORDER, _nbitLength); - if (BYTES > 2048) - throw new Error("invalid field: expected ORDER of <= 2048 bytes"); - let sqrtP; - const f = Object.freeze({ - ORDER, - isLE, - BITS, - BYTES, - MASK: (0, utils_ts_1.bitMask)(BITS), - ZERO: _0n2, - ONE: _1n2, - allowedLengths, - create: (num) => mod(num, ORDER), - isValid: (num) => { - if (typeof num !== "bigint") - throw new Error("invalid field element: expected bigint, got " + typeof num); - return _0n2 <= num && num < ORDER; - }, - is0: (num) => num === _0n2, - // is valid and invertible - isValidNot0: (num) => !f.is0(num) && f.isValid(num), - isOdd: (num) => (num & _1n2) === _1n2, - neg: (num) => mod(-num, ORDER), - eql: (lhs, rhs) => lhs === rhs, - sqr: (num) => mod(num * num, ORDER), - add: (lhs, rhs) => mod(lhs + rhs, ORDER), - sub: (lhs, rhs) => mod(lhs - rhs, ORDER), - mul: (lhs, rhs) => mod(lhs * rhs, ORDER), - pow: (num, power) => FpPow(f, num, power), - div: (lhs, rhs) => mod(lhs * invert(rhs, ORDER), ORDER), - // Same as above, but doesn't normalize - sqrN: (num) => num * num, - addN: (lhs, rhs) => lhs + rhs, - subN: (lhs, rhs) => lhs - rhs, - mulN: (lhs, rhs) => lhs * rhs, - inv: (num) => invert(num, ORDER), - sqrt: _sqrt || ((n) => { - if (!sqrtP) - sqrtP = FpSqrt(ORDER); - return sqrtP(f, n); - }), - toBytes: (num) => isLE ? (0, utils_ts_1.numberToBytesLE)(num, BYTES) : (0, utils_ts_1.numberToBytesBE)(num, BYTES), - fromBytes: (bytes, skipValidation = true) => { - if (allowedLengths) { - if (!allowedLengths.includes(bytes.length) || bytes.length > BYTES) { - throw new Error("Field.fromBytes: expected " + allowedLengths + " bytes, got " + bytes.length); - } - const padded = new Uint8Array(BYTES); - padded.set(bytes, isLE ? 0 : padded.length - bytes.length); - bytes = padded; - } - if (bytes.length !== BYTES) - throw new Error("Field.fromBytes: expected " + BYTES + " bytes, got " + bytes.length); - let scalar = isLE ? (0, utils_ts_1.bytesToNumberLE)(bytes) : (0, utils_ts_1.bytesToNumberBE)(bytes); - if (modFromBytes) - scalar = mod(scalar, ORDER); - if (!skipValidation) { - if (!f.isValid(scalar)) - throw new Error("invalid field element: outside of range 0..ORDER"); - } - return scalar; - }, - // TODO: we don't need it here, move out to separate fn - invertBatch: (lst) => FpInvertBatch(f, lst), - // We can't move this out because Fp6, Fp12 implement it - // and it's unclear what to return in there. - cmov: (a, b, c) => c ? b : a - }); - return Object.freeze(f); - } - function FpSqrtOdd(Fp, elm) { - if (!Fp.isOdd) - throw new Error("Field doesn't have isOdd"); - const root = Fp.sqrt(elm); - return Fp.isOdd(root) ? root : Fp.neg(root); - } - function FpSqrtEven(Fp, elm) { - if (!Fp.isOdd) - throw new Error("Field doesn't have isOdd"); - const root = Fp.sqrt(elm); - return Fp.isOdd(root) ? Fp.neg(root) : root; - } - function hashToPrivateScalar(hash, groupOrder, isLE = false) { - hash = (0, utils_ts_1.ensureBytes)("privateHash", hash); - const hashLen = hash.length; - const minLen = nLength(groupOrder).nByteLength + 8; - if (minLen < 24 || hashLen < minLen || hashLen > 1024) - throw new Error("hashToPrivateScalar: expected " + minLen + "-1024 bytes of input, got " + hashLen); - const num = isLE ? (0, utils_ts_1.bytesToNumberLE)(hash) : (0, utils_ts_1.bytesToNumberBE)(hash); - return mod(num, groupOrder - _1n2) + _1n2; - } - function getFieldBytesLength(fieldOrder) { - if (typeof fieldOrder !== "bigint") - throw new Error("field order must be bigint"); - const bitLength = fieldOrder.toString(2).length; - return Math.ceil(bitLength / 8); - } - function getMinHashLength(fieldOrder) { - const length = getFieldBytesLength(fieldOrder); - return length + Math.ceil(length / 2); - } - function mapHashToField(key, fieldOrder, isLE = false) { - const len = key.length; - const fieldLen = getFieldBytesLength(fieldOrder); - const minLen = getMinHashLength(fieldOrder); - if (len < 16 || len < minLen || len > 1024) - throw new Error("expected " + minLen + "-1024 bytes of input, got " + len); - const num = isLE ? (0, utils_ts_1.bytesToNumberLE)(key) : (0, utils_ts_1.bytesToNumberBE)(key); - const reduced = mod(num, fieldOrder - _1n2) + _1n2; - return isLE ? (0, utils_ts_1.numberToBytesLE)(reduced, fieldLen) : (0, utils_ts_1.numberToBytesBE)(reduced, fieldLen); - } - } -}); - -// node_modules/@noble/curves/abstract/curve.js -var require_curve = __commonJS({ - "node_modules/@noble/curves/abstract/curve.js"(exports) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.wNAF = void 0; - exports.negateCt = negateCt; - exports.normalizeZ = normalizeZ; - exports.mulEndoUnsafe = mulEndoUnsafe; - exports.pippenger = pippenger; - exports.precomputeMSMUnsafe = precomputeMSMUnsafe; - exports.validateBasic = validateBasic; - exports._createCurveFields = _createCurveFields; - var utils_ts_1 = require_utils2(); - var modular_ts_1 = require_modular(); - var _0n2 = BigInt(0); - var _1n2 = BigInt(1); - function negateCt(condition, item) { - const neg = item.negate(); - return condition ? neg : item; - } - function normalizeZ(c, points) { - const invertedZs = (0, modular_ts_1.FpInvertBatch)(c.Fp, points.map((p) => p.Z)); - return points.map((p, i) => c.fromAffine(p.toAffine(invertedZs[i]))); - } - function validateW(W, bits) { - if (!Number.isSafeInteger(W) || W <= 0 || W > bits) - throw new Error("invalid window size, expected [1.." + bits + "], got W=" + W); - } - function calcWOpts(W, scalarBits) { - validateW(W, scalarBits); - const windows = Math.ceil(scalarBits / W) + 1; - const windowSize = 2 ** (W - 1); - const maxNumber = 2 ** W; - const mask = (0, utils_ts_1.bitMask)(W); - const shiftBy = BigInt(W); - return { windows, windowSize, mask, maxNumber, shiftBy }; - } - function calcOffsets(n, window2, wOpts) { - const { windowSize, mask, maxNumber, shiftBy } = wOpts; - let wbits = Number(n & mask); - let nextN = n >> shiftBy; - if (wbits > windowSize) { - wbits -= maxNumber; - nextN += _1n2; - } - const offsetStart = window2 * windowSize; - const offset = offsetStart + Math.abs(wbits) - 1; - const isZero = wbits === 0; - const isNeg = wbits < 0; - const isNegF = window2 % 2 !== 0; - const offsetF = offsetStart; - return { nextN, offset, isZero, isNeg, isNegF, offsetF }; - } - function validateMSMPoints(points, c) { - if (!Array.isArray(points)) - throw new Error("array expected"); - points.forEach((p, i) => { - if (!(p instanceof c)) - throw new Error("invalid point at index " + i); - }); - } - function validateMSMScalars(scalars, field) { - if (!Array.isArray(scalars)) - throw new Error("array of scalars expected"); - scalars.forEach((s, i) => { - if (!field.isValid(s)) - throw new Error("invalid scalar at index " + i); - }); - } - var pointPrecomputes = /* @__PURE__ */ new WeakMap(); - var pointWindowSizes = /* @__PURE__ */ new WeakMap(); - function getW(P) { - return pointWindowSizes.get(P) || 1; - } - function assert0(n) { - if (n !== _0n2) - throw new Error("invalid wNAF"); - } - var wNAF = class { - // Parametrized with a given Point class (not individual point) - constructor(Point, bits) { - this.BASE = Point.BASE; - this.ZERO = Point.ZERO; - this.Fn = Point.Fn; - this.bits = bits; - } - // non-const time multiplication ladder - _unsafeLadder(elm, n, p = this.ZERO) { - let d = elm; - while (n > _0n2) { - if (n & _1n2) - p = p.add(d); - d = d.double(); - n >>= _1n2; - } - return p; - } - /** - * Creates a wNAF precomputation window. Used for caching. - * Default window size is set by `utils.precompute()` and is equal to 8. - * Number of precomputed points depends on the curve size: - * 2^(𝑊−1) * (Math.ceil(𝑛 / 𝑊) + 1), where: - * - 𝑊 is the window size - * - 𝑛 is the bitlength of the curve order. - * For a 256-bit curve and window size 8, the number of precomputed points is 128 * 33 = 4224. - * @param point Point instance - * @param W window size - * @returns precomputed point tables flattened to a single array - */ - precomputeWindow(point2, W) { - const { windows, windowSize } = calcWOpts(W, this.bits); - const points = []; - let p = point2; - let base = p; - for (let window2 = 0; window2 < windows; window2++) { - base = p; - points.push(base); - for (let i = 1; i < windowSize; i++) { - base = base.add(p); - points.push(base); - } - p = base.double(); - } - return points; - } - /** - * Implements ec multiplication using precomputed tables and w-ary non-adjacent form. - * More compact implementation: - * https://github.com/paulmillr/noble-secp256k1/blob/47cb1669b6e506ad66b35fe7d76132ae97465da2/index.ts#L502-L541 - * @returns real and fake (for const-time) points - */ - wNAF(W, precomputes, n) { - if (!this.Fn.isValid(n)) - throw new Error("invalid scalar"); - let p = this.ZERO; - let f = this.BASE; - const wo = calcWOpts(W, this.bits); - for (let window2 = 0; window2 < wo.windows; window2++) { - const { nextN, offset, isZero, isNeg, isNegF, offsetF } = calcOffsets(n, window2, wo); - n = nextN; - if (isZero) { - f = f.add(negateCt(isNegF, precomputes[offsetF])); - } else { - p = p.add(negateCt(isNeg, precomputes[offset])); - } - } - assert0(n); - return { p, f }; - } - /** - * Implements ec unsafe (non const-time) multiplication using precomputed tables and w-ary non-adjacent form. - * @param acc accumulator point to add result of multiplication - * @returns point - */ - wNAFUnsafe(W, precomputes, n, acc = this.ZERO) { - const wo = calcWOpts(W, this.bits); - for (let window2 = 0; window2 < wo.windows; window2++) { - if (n === _0n2) - break; - const { nextN, offset, isZero, isNeg } = calcOffsets(n, window2, wo); - n = nextN; - if (isZero) { - continue; - } else { - const item = precomputes[offset]; - acc = acc.add(isNeg ? item.negate() : item); - } - } - assert0(n); - return acc; - } - getPrecomputes(W, point2, transform) { - let comp = pointPrecomputes.get(point2); - if (!comp) { - comp = this.precomputeWindow(point2, W); - if (W !== 1) { - if (typeof transform === "function") - comp = transform(comp); - pointPrecomputes.set(point2, comp); - } - } - return comp; - } - cached(point2, scalar, transform) { - const W = getW(point2); - return this.wNAF(W, this.getPrecomputes(W, point2, transform), scalar); - } - unsafe(point2, scalar, transform, prev) { - const W = getW(point2); - if (W === 1) - return this._unsafeLadder(point2, scalar, prev); - return this.wNAFUnsafe(W, this.getPrecomputes(W, point2, transform), scalar, prev); - } - // We calculate precomputes for elliptic curve point multiplication - // using windowed method. This specifies window size and - // stores precomputed values. Usually only base point would be precomputed. - createCache(P, W) { - validateW(W, this.bits); - pointWindowSizes.set(P, W); - pointPrecomputes.delete(P); - } - hasCache(elm) { - return getW(elm) !== 1; - } - }; - exports.wNAF = wNAF; - function mulEndoUnsafe(Point, point2, k1, k2) { - let acc = point2; - let p1 = Point.ZERO; - let p2 = Point.ZERO; - while (k1 > _0n2 || k2 > _0n2) { - if (k1 & _1n2) - p1 = p1.add(acc); - if (k2 & _1n2) - p2 = p2.add(acc); - acc = acc.double(); - k1 >>= _1n2; - k2 >>= _1n2; - } - return { p1, p2 }; - } - function pippenger(c, fieldN, points, scalars) { - validateMSMPoints(points, c); - validateMSMScalars(scalars, fieldN); - const plength = points.length; - const slength = scalars.length; - if (plength !== slength) - throw new Error("arrays of points and scalars must have equal length"); - const zero = c.ZERO; - const wbits = (0, utils_ts_1.bitLen)(BigInt(plength)); - let windowSize = 1; - if (wbits > 12) - windowSize = wbits - 3; - else if (wbits > 4) - windowSize = wbits - 2; - else if (wbits > 0) - windowSize = 2; - const MASK = (0, utils_ts_1.bitMask)(windowSize); - const buckets = new Array(Number(MASK) + 1).fill(zero); - const lastBits = Math.floor((fieldN.BITS - 1) / windowSize) * windowSize; - let sum = zero; - for (let i = lastBits; i >= 0; i -= windowSize) { - buckets.fill(zero); - for (let j = 0; j < slength; j++) { - const scalar = scalars[j]; - const wbits2 = Number(scalar >> BigInt(i) & MASK); - buckets[wbits2] = buckets[wbits2].add(points[j]); - } - let resI = zero; - for (let j = buckets.length - 1, sumI = zero; j > 0; j--) { - sumI = sumI.add(buckets[j]); - resI = resI.add(sumI); - } - sum = sum.add(resI); - if (i !== 0) - for (let j = 0; j < windowSize; j++) - sum = sum.double(); - } - return sum; - } - function precomputeMSMUnsafe(c, fieldN, points, windowSize) { - validateW(windowSize, fieldN.BITS); - validateMSMPoints(points, c); - const zero = c.ZERO; - const tableSize = 2 ** windowSize - 1; - const chunks = Math.ceil(fieldN.BITS / windowSize); - const MASK = (0, utils_ts_1.bitMask)(windowSize); - const tables = points.map((p) => { - const res = []; - for (let i = 0, acc = p; i < tableSize; i++) { - res.push(acc); - acc = acc.add(p); - } - return res; - }); - return (scalars) => { - validateMSMScalars(scalars, fieldN); - if (scalars.length > points.length) - throw new Error("array of scalars must be smaller than array of points"); - let res = zero; - for (let i = 0; i < chunks; i++) { - if (res !== zero) - for (let j = 0; j < windowSize; j++) - res = res.double(); - const shiftBy = BigInt(chunks * windowSize - (i + 1) * windowSize); - for (let j = 0; j < scalars.length; j++) { - const n = scalars[j]; - const curr = Number(n >> shiftBy & MASK); - if (!curr) - continue; - res = res.add(tables[j][curr - 1]); - } - } - return res; - }; - } - function validateBasic(curve) { - (0, modular_ts_1.validateField)(curve.Fp); - (0, utils_ts_1.validateObject)(curve, { - n: "bigint", - h: "bigint", - Gx: "field", - Gy: "field" - }, { - nBitLength: "isSafeInteger", - nByteLength: "isSafeInteger" - }); - return Object.freeze({ - ...(0, modular_ts_1.nLength)(curve.n, curve.nBitLength), - ...curve, - ...{ p: curve.Fp.ORDER } - }); - } - function createField(order2, field, isLE) { - if (field) { - if (field.ORDER !== order2) - throw new Error("Field.ORDER must match order: Fp == p, Fn == n"); - (0, modular_ts_1.validateField)(field); - return field; - } else { - return (0, modular_ts_1.Field)(order2, { isLE }); - } - } - function _createCurveFields(type, CURVE, curveOpts = {}, FpFnLE) { - if (FpFnLE === void 0) - FpFnLE = type === "edwards"; - if (!CURVE || typeof CURVE !== "object") - throw new Error(`expected valid ${type} CURVE object`); - for (const p of ["p", "n", "h"]) { - const val = CURVE[p]; - if (!(typeof val === "bigint" && val > _0n2)) - throw new Error(`CURVE.${p} must be positive bigint`); - } - const Fp = createField(CURVE.p, curveOpts.Fp, FpFnLE); - const Fn = createField(CURVE.n, curveOpts.Fn, FpFnLE); - const _b = type === "weierstrass" ? "b" : "d"; - const params = ["Gx", "Gy", "a", _b]; - for (const p of params) { - if (!Fp.isValid(CURVE[p])) - throw new Error(`CURVE.${p} must be valid field element of CURVE.Fp`); - } - CURVE = Object.freeze(Object.assign({}, CURVE)); - return { CURVE, Fp, Fn }; - } - } -}); - -// node_modules/@noble/curves/abstract/weierstrass.js -var require_weierstrass = __commonJS({ - "node_modules/@noble/curves/abstract/weierstrass.js"(exports) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.DER = exports.DERErr = void 0; - exports._splitEndoScalar = _splitEndoScalar; - exports._normFnElement = _normFnElement; - exports.weierstrassN = weierstrassN; - exports.SWUFpSqrtRatio = SWUFpSqrtRatio; - exports.mapToCurveSimpleSWU = mapToCurveSimpleSWU; - exports.ecdh = ecdh; - exports.ecdsa = ecdsa; - exports.weierstrassPoints = weierstrassPoints; - exports._legacyHelperEquat = _legacyHelperEquat; - exports.weierstrass = weierstrass; - var hmac_js_1 = require_hmac(); - var utils_1 = require_utils(); - var utils_ts_1 = require_utils2(); - var curve_ts_1 = require_curve(); - var modular_ts_1 = require_modular(); - var divNearest = (num, den) => (num + (num >= 0 ? den : -den) / _2n) / den; - function _splitEndoScalar(k, basis, n) { - const [[a1, b1], [a2, b2]] = basis; - const c1 = divNearest(b2 * k, n); - const c2 = divNearest(-b1 * k, n); - let k1 = k - c1 * a1 - c2 * a2; - let k2 = -c1 * b1 - c2 * b2; - const k1neg = k1 < _0n2; - const k2neg = k2 < _0n2; - if (k1neg) - k1 = -k1; - if (k2neg) - k2 = -k2; - const MAX_NUM = (0, utils_ts_1.bitMask)(Math.ceil((0, utils_ts_1.bitLen)(n) / 2)) + _1n2; - if (k1 < _0n2 || k1 >= MAX_NUM || k2 < _0n2 || k2 >= MAX_NUM) { - throw new Error("splitScalar (endomorphism): failed, k=" + k); - } - return { k1neg, k1, k2neg, k2 }; - } - function validateSigFormat(format) { - if (!["compact", "recovered", "der"].includes(format)) - throw new Error('Signature format must be "compact", "recovered", or "der"'); - return format; - } - function validateSigOpts(opts, def) { - const optsn = {}; - for (let optName of Object.keys(def)) { - optsn[optName] = opts[optName] === void 0 ? def[optName] : opts[optName]; - } - (0, utils_ts_1._abool2)(optsn.lowS, "lowS"); - (0, utils_ts_1._abool2)(optsn.prehash, "prehash"); - if (optsn.format !== void 0) - validateSigFormat(optsn.format); - return optsn; - } - var DERErr = class extends Error { - constructor(m = "") { - super(m); - } - }; - exports.DERErr = DERErr; - exports.DER = { - // asn.1 DER encoding utils - Err: DERErr, - // Basic building block is TLV (Tag-Length-Value) - _tlv: { - encode: (tag, data) => { - const { Err: E } = exports.DER; - if (tag < 0 || tag > 256) - throw new E("tlv.encode: wrong tag"); - if (data.length & 1) - throw new E("tlv.encode: unpadded data"); - const dataLen = data.length / 2; - const len = (0, utils_ts_1.numberToHexUnpadded)(dataLen); - if (len.length / 2 & 128) - throw new E("tlv.encode: long form length too big"); - const lenLen = dataLen > 127 ? (0, utils_ts_1.numberToHexUnpadded)(len.length / 2 | 128) : ""; - const t = (0, utils_ts_1.numberToHexUnpadded)(tag); - return t + lenLen + len + data; - }, - // v - value, l - left bytes (unparsed) - decode(tag, data) { - const { Err: E } = exports.DER; - let pos = 0; - if (tag < 0 || tag > 256) - throw new E("tlv.encode: wrong tag"); - if (data.length < 2 || data[pos++] !== tag) - throw new E("tlv.decode: wrong tlv"); - const first = data[pos++]; - const isLong = !!(first & 128); - let length = 0; - if (!isLong) - length = first; - else { - const lenLen = first & 127; - if (!lenLen) - throw new E("tlv.decode(long): indefinite length not supported"); - if (lenLen > 4) - throw new E("tlv.decode(long): byte length is too big"); - const lengthBytes = data.subarray(pos, pos + lenLen); - if (lengthBytes.length !== lenLen) - throw new E("tlv.decode: length bytes not complete"); - if (lengthBytes[0] === 0) - throw new E("tlv.decode(long): zero leftmost byte"); - for (const b of lengthBytes) - length = length << 8 | b; - pos += lenLen; - if (length < 128) - throw new E("tlv.decode(long): not minimal encoding"); - } - const v = data.subarray(pos, pos + length); - if (v.length !== length) - throw new E("tlv.decode: wrong value length"); - return { v, l: data.subarray(pos + length) }; - } - }, - // https://crypto.stackexchange.com/a/57734 Leftmost bit of first byte is 'negative' flag, - // since we always use positive integers here. It must always be empty: - // - add zero byte if exists - // - if next byte doesn't have a flag, leading zero is not allowed (minimal encoding) - _int: { - encode(num) { - const { Err: E } = exports.DER; - if (num < _0n2) - throw new E("integer: negative integers are not allowed"); - let hex = (0, utils_ts_1.numberToHexUnpadded)(num); - if (Number.parseInt(hex[0], 16) & 8) - hex = "00" + hex; - if (hex.length & 1) - throw new E("unexpected DER parsing assertion: unpadded hex"); - return hex; - }, - decode(data) { - const { Err: E } = exports.DER; - if (data[0] & 128) - throw new E("invalid signature integer: negative"); - if (data[0] === 0 && !(data[1] & 128)) - throw new E("invalid signature integer: unnecessary leading zero"); - return (0, utils_ts_1.bytesToNumberBE)(data); - } - }, - toSig(hex) { - const { Err: E, _int: int, _tlv: tlv } = exports.DER; - const data = (0, utils_ts_1.ensureBytes)("signature", hex); - const { v: seqBytes, l: seqLeftBytes } = tlv.decode(48, data); - if (seqLeftBytes.length) - throw new E("invalid signature: left bytes after parsing"); - const { v: rBytes, l: rLeftBytes } = tlv.decode(2, seqBytes); - const { v: sBytes, l: sLeftBytes } = tlv.decode(2, rLeftBytes); - if (sLeftBytes.length) - throw new E("invalid signature: left bytes after parsing"); - return { r: int.decode(rBytes), s: int.decode(sBytes) }; - }, - hexFromSig(sig) { - const { _tlv: tlv, _int: int } = exports.DER; - const rs = tlv.encode(2, int.encode(sig.r)); - const ss = tlv.encode(2, int.encode(sig.s)); - const seq = rs + ss; - return tlv.encode(48, seq); - } - }; - var _0n2 = BigInt(0); - var _1n2 = BigInt(1); - var _2n = BigInt(2); - var _3n = BigInt(3); - var _4n = BigInt(4); - function _normFnElement(Fn, key) { - const { BYTES: expected } = Fn; - let num; - if (typeof key === "bigint") { - num = key; - } else { - let bytes = (0, utils_ts_1.ensureBytes)("private key", key); - try { - num = Fn.fromBytes(bytes); - } catch (error) { - throw new Error(`invalid private key: expected ui8a of size ${expected}, got ${typeof key}`); - } - } - if (!Fn.isValidNot0(num)) - throw new Error("invalid private key: out of range [1..N-1]"); - return num; - } - function weierstrassN(params, extraOpts = {}) { - const validated = (0, curve_ts_1._createCurveFields)("weierstrass", params, extraOpts); - const { Fp, Fn } = validated; - let CURVE = validated.CURVE; - const { h: cofactor, n: CURVE_ORDER } = CURVE; - (0, utils_ts_1._validateObject)(extraOpts, {}, { - allowInfinityPoint: "boolean", - clearCofactor: "function", - isTorsionFree: "function", - fromBytes: "function", - toBytes: "function", - endo: "object", - wrapPrivateKey: "boolean" - }); - const { endo } = extraOpts; - if (endo) { - if (!Fp.is0(CURVE.a) || typeof endo.beta !== "bigint" || !Array.isArray(endo.basises)) { - throw new Error('invalid endo: expected "beta": bigint and "basises": array'); - } - } - const lengths = getWLengths(Fp, Fn); - function assertCompressionIsSupported() { - if (!Fp.isOdd) - throw new Error("compression is not supported: Field does not have .isOdd()"); - } - function pointToBytes(_c, point2, isCompressed) { - const { x, y } = point2.toAffine(); - const bx = Fp.toBytes(x); - (0, utils_ts_1._abool2)(isCompressed, "isCompressed"); - if (isCompressed) { - assertCompressionIsSupported(); - const hasEvenY = !Fp.isOdd(y); - return (0, utils_ts_1.concatBytes)(pprefix(hasEvenY), bx); - } else { - return (0, utils_ts_1.concatBytes)(Uint8Array.of(4), bx, Fp.toBytes(y)); - } - } - function pointFromBytes(bytes) { - (0, utils_ts_1._abytes2)(bytes, void 0, "Point"); - const { publicKey: comp, publicKeyUncompressed: uncomp } = lengths; - const length = bytes.length; - const head = bytes[0]; - const tail = bytes.subarray(1); - if (length === comp && (head === 2 || head === 3)) { - const x = Fp.fromBytes(tail); - if (!Fp.isValid(x)) - throw new Error("bad point: is not on curve, wrong x"); - const y2 = weierstrassEquation(x); - let y; - try { - y = Fp.sqrt(y2); - } catch (sqrtError) { - const err = sqrtError instanceof Error ? ": " + sqrtError.message : ""; - throw new Error("bad point: is not on curve, sqrt error" + err); - } - assertCompressionIsSupported(); - const isYOdd = Fp.isOdd(y); - const isHeadOdd = (head & 1) === 1; - if (isHeadOdd !== isYOdd) - y = Fp.neg(y); - return { x, y }; - } else if (length === uncomp && head === 4) { - const L = Fp.BYTES; - const x = Fp.fromBytes(tail.subarray(0, L)); - const y = Fp.fromBytes(tail.subarray(L, L * 2)); - if (!isValidXY(x, y)) - throw new Error("bad point: is not on curve"); - return { x, y }; - } else { - throw new Error(`bad point: got length ${length}, expected compressed=${comp} or uncompressed=${uncomp}`); - } - } - const encodePoint = extraOpts.toBytes || pointToBytes; - const decodePoint = extraOpts.fromBytes || pointFromBytes; - function weierstrassEquation(x) { - const x2 = Fp.sqr(x); - const x3 = Fp.mul(x2, x); - return Fp.add(Fp.add(x3, Fp.mul(x, CURVE.a)), CURVE.b); - } - function isValidXY(x, y) { - const left = Fp.sqr(y); - const right = weierstrassEquation(x); - return Fp.eql(left, right); - } - if (!isValidXY(CURVE.Gx, CURVE.Gy)) - throw new Error("bad curve params: generator point"); - const _4a3 = Fp.mul(Fp.pow(CURVE.a, _3n), _4n); - const _27b2 = Fp.mul(Fp.sqr(CURVE.b), BigInt(27)); - if (Fp.is0(Fp.add(_4a3, _27b2))) - throw new Error("bad curve params: a or b"); - function acoord(title, n, banZero = false) { - if (!Fp.isValid(n) || banZero && Fp.is0(n)) - throw new Error(`bad point coordinate ${title}`); - return n; - } - function aprjpoint(other) { - if (!(other instanceof Point)) - throw new Error("ProjectivePoint expected"); - } - function splitEndoScalarN(k) { - if (!endo || !endo.basises) - throw new Error("no endo"); - return _splitEndoScalar(k, endo.basises, Fn.ORDER); - } - const toAffineMemo = (0, utils_ts_1.memoized)((p, iz) => { - const { X, Y, Z } = p; - if (Fp.eql(Z, Fp.ONE)) - return { x: X, y: Y }; - const is0 = p.is0(); - if (iz == null) - iz = is0 ? Fp.ONE : Fp.inv(Z); - const x = Fp.mul(X, iz); - const y = Fp.mul(Y, iz); - const zz = Fp.mul(Z, iz); - if (is0) - return { x: Fp.ZERO, y: Fp.ZERO }; - if (!Fp.eql(zz, Fp.ONE)) - throw new Error("invZ was invalid"); - return { x, y }; - }); - const assertValidMemo = (0, utils_ts_1.memoized)((p) => { - if (p.is0()) { - if (extraOpts.allowInfinityPoint && !Fp.is0(p.Y)) - return; - throw new Error("bad point: ZERO"); - } - const { x, y } = p.toAffine(); - if (!Fp.isValid(x) || !Fp.isValid(y)) - throw new Error("bad point: x or y not field elements"); - if (!isValidXY(x, y)) - throw new Error("bad point: equation left != right"); - if (!p.isTorsionFree()) - throw new Error("bad point: not in prime-order subgroup"); - return true; - }); - function finishEndo(endoBeta, k1p, k2p, k1neg, k2neg) { - k2p = new Point(Fp.mul(k2p.X, endoBeta), k2p.Y, k2p.Z); - k1p = (0, curve_ts_1.negateCt)(k1neg, k1p); - k2p = (0, curve_ts_1.negateCt)(k2neg, k2p); - return k1p.add(k2p); - } - class Point { - /** Does NOT validate if the point is valid. Use `.assertValidity()`. */ - constructor(X, Y, Z) { - this.X = acoord("x", X); - this.Y = acoord("y", Y, true); - this.Z = acoord("z", Z); - Object.freeze(this); - } - static CURVE() { - return CURVE; - } - /** Does NOT validate if the point is valid. Use `.assertValidity()`. */ - static fromAffine(p) { - const { x, y } = p || {}; - if (!p || !Fp.isValid(x) || !Fp.isValid(y)) - throw new Error("invalid affine point"); - if (p instanceof Point) - throw new Error("projective point not allowed"); - if (Fp.is0(x) && Fp.is0(y)) - return Point.ZERO; - return new Point(x, y, Fp.ONE); - } - static fromBytes(bytes) { - const P = Point.fromAffine(decodePoint((0, utils_ts_1._abytes2)(bytes, void 0, "point"))); - P.assertValidity(); - return P; - } - static fromHex(hex) { - return Point.fromBytes((0, utils_ts_1.ensureBytes)("pointHex", hex)); - } - get x() { - return this.toAffine().x; - } - get y() { - return this.toAffine().y; - } - /** - * - * @param windowSize - * @param isLazy true will defer table computation until the first multiplication - * @returns - */ - precompute(windowSize = 8, isLazy = true) { - wnaf.createCache(this, windowSize); - if (!isLazy) - this.multiply(_3n); - return this; - } - // TODO: return `this` - /** A point on curve is valid if it conforms to equation. */ - assertValidity() { - assertValidMemo(this); - } - hasEvenY() { - const { y } = this.toAffine(); - if (!Fp.isOdd) - throw new Error("Field doesn't support isOdd"); - return !Fp.isOdd(y); - } - /** Compare one point to another. */ - equals(other) { - aprjpoint(other); - const { X: X1, Y: Y1, Z: Z1 } = this; - const { X: X2, Y: Y2, Z: Z2 } = other; - const U1 = Fp.eql(Fp.mul(X1, Z2), Fp.mul(X2, Z1)); - const U2 = Fp.eql(Fp.mul(Y1, Z2), Fp.mul(Y2, Z1)); - return U1 && U2; - } - /** Flips point to one corresponding to (x, -y) in Affine coordinates. */ - negate() { - return new Point(this.X, Fp.neg(this.Y), this.Z); - } - // Renes-Costello-Batina exception-free doubling formula. - // There is 30% faster Jacobian formula, but it is not complete. - // https://eprint.iacr.org/2015/1060, algorithm 3 - // Cost: 8M + 3S + 3*a + 2*b3 + 15add. - double() { - const { a, b } = CURVE; - const b3 = Fp.mul(b, _3n); - const { X: X1, Y: Y1, Z: Z1 } = this; - let X3 = Fp.ZERO, Y3 = Fp.ZERO, Z3 = Fp.ZERO; - let t0 = Fp.mul(X1, X1); - let t1 = Fp.mul(Y1, Y1); - let t2 = Fp.mul(Z1, Z1); - let t3 = Fp.mul(X1, Y1); - t3 = Fp.add(t3, t3); - Z3 = Fp.mul(X1, Z1); - Z3 = Fp.add(Z3, Z3); - X3 = Fp.mul(a, Z3); - Y3 = Fp.mul(b3, t2); - Y3 = Fp.add(X3, Y3); - X3 = Fp.sub(t1, Y3); - Y3 = Fp.add(t1, Y3); - Y3 = Fp.mul(X3, Y3); - X3 = Fp.mul(t3, X3); - Z3 = Fp.mul(b3, Z3); - t2 = Fp.mul(a, t2); - t3 = Fp.sub(t0, t2); - t3 = Fp.mul(a, t3); - t3 = Fp.add(t3, Z3); - Z3 = Fp.add(t0, t0); - t0 = Fp.add(Z3, t0); - t0 = Fp.add(t0, t2); - t0 = Fp.mul(t0, t3); - Y3 = Fp.add(Y3, t0); - t2 = Fp.mul(Y1, Z1); - t2 = Fp.add(t2, t2); - t0 = Fp.mul(t2, t3); - X3 = Fp.sub(X3, t0); - Z3 = Fp.mul(t2, t1); - Z3 = Fp.add(Z3, Z3); - Z3 = Fp.add(Z3, Z3); - return new Point(X3, Y3, Z3); - } - // Renes-Costello-Batina exception-free addition formula. - // There is 30% faster Jacobian formula, but it is not complete. - // https://eprint.iacr.org/2015/1060, algorithm 1 - // Cost: 12M + 0S + 3*a + 3*b3 + 23add. - add(other) { - aprjpoint(other); - const { X: X1, Y: Y1, Z: Z1 } = this; - const { X: X2, Y: Y2, Z: Z2 } = other; - let X3 = Fp.ZERO, Y3 = Fp.ZERO, Z3 = Fp.ZERO; - const a = CURVE.a; - const b3 = Fp.mul(CURVE.b, _3n); - let t0 = Fp.mul(X1, X2); - let t1 = Fp.mul(Y1, Y2); - let t2 = Fp.mul(Z1, Z2); - let t3 = Fp.add(X1, Y1); - let t4 = Fp.add(X2, Y2); - t3 = Fp.mul(t3, t4); - t4 = Fp.add(t0, t1); - t3 = Fp.sub(t3, t4); - t4 = Fp.add(X1, Z1); - let t5 = Fp.add(X2, Z2); - t4 = Fp.mul(t4, t5); - t5 = Fp.add(t0, t2); - t4 = Fp.sub(t4, t5); - t5 = Fp.add(Y1, Z1); - X3 = Fp.add(Y2, Z2); - t5 = Fp.mul(t5, X3); - X3 = Fp.add(t1, t2); - t5 = Fp.sub(t5, X3); - Z3 = Fp.mul(a, t4); - X3 = Fp.mul(b3, t2); - Z3 = Fp.add(X3, Z3); - X3 = Fp.sub(t1, Z3); - Z3 = Fp.add(t1, Z3); - Y3 = Fp.mul(X3, Z3); - t1 = Fp.add(t0, t0); - t1 = Fp.add(t1, t0); - t2 = Fp.mul(a, t2); - t4 = Fp.mul(b3, t4); - t1 = Fp.add(t1, t2); - t2 = Fp.sub(t0, t2); - t2 = Fp.mul(a, t2); - t4 = Fp.add(t4, t2); - t0 = Fp.mul(t1, t4); - Y3 = Fp.add(Y3, t0); - t0 = Fp.mul(t5, t4); - X3 = Fp.mul(t3, X3); - X3 = Fp.sub(X3, t0); - t0 = Fp.mul(t3, t1); - Z3 = Fp.mul(t5, Z3); - Z3 = Fp.add(Z3, t0); - return new Point(X3, Y3, Z3); - } - subtract(other) { - return this.add(other.negate()); - } - is0() { - return this.equals(Point.ZERO); - } - /** - * Constant time multiplication. - * Uses wNAF method. Windowed method may be 10% faster, - * but takes 2x longer to generate and consumes 2x memory. - * Uses precomputes when available. - * Uses endomorphism for Koblitz curves. - * @param scalar by which the point would be multiplied - * @returns New point - */ - multiply(scalar) { - const { endo: endo2 } = extraOpts; - if (!Fn.isValidNot0(scalar)) - throw new Error("invalid scalar: out of range"); - let point2, fake; - const mul = (n) => wnaf.cached(this, n, (p) => (0, curve_ts_1.normalizeZ)(Point, p)); - if (endo2) { - const { k1neg, k1, k2neg, k2 } = splitEndoScalarN(scalar); - const { p: k1p, f: k1f } = mul(k1); - const { p: k2p, f: k2f } = mul(k2); - fake = k1f.add(k2f); - point2 = finishEndo(endo2.beta, k1p, k2p, k1neg, k2neg); - } else { - const { p, f } = mul(scalar); - point2 = p; - fake = f; - } - return (0, curve_ts_1.normalizeZ)(Point, [point2, fake])[0]; - } - /** - * Non-constant-time multiplication. Uses double-and-add algorithm. - * It's faster, but should only be used when you don't care about - * an exposed secret key e.g. sig verification, which works over *public* keys. - */ - multiplyUnsafe(sc) { - const { endo: endo2 } = extraOpts; - const p = this; - if (!Fn.isValid(sc)) - throw new Error("invalid scalar: out of range"); - if (sc === _0n2 || p.is0()) - return Point.ZERO; - if (sc === _1n2) - return p; - if (wnaf.hasCache(this)) - return this.multiply(sc); - if (endo2) { - const { k1neg, k1, k2neg, k2 } = splitEndoScalarN(sc); - const { p1, p2 } = (0, curve_ts_1.mulEndoUnsafe)(Point, p, k1, k2); - return finishEndo(endo2.beta, p1, p2, k1neg, k2neg); - } else { - return wnaf.unsafe(p, sc); - } - } - multiplyAndAddUnsafe(Q, a, b) { - const sum = this.multiplyUnsafe(a).add(Q.multiplyUnsafe(b)); - return sum.is0() ? void 0 : sum; - } - /** - * Converts Projective point to affine (x, y) coordinates. - * @param invertedZ Z^-1 (inverted zero) - optional, precomputation is useful for invertBatch - */ - toAffine(invertedZ) { - return toAffineMemo(this, invertedZ); - } - /** - * Checks whether Point is free of torsion elements (is in prime subgroup). - * Always torsion-free for cofactor=1 curves. - */ - isTorsionFree() { - const { isTorsionFree } = extraOpts; - if (cofactor === _1n2) - return true; - if (isTorsionFree) - return isTorsionFree(Point, this); - return wnaf.unsafe(this, CURVE_ORDER).is0(); - } - clearCofactor() { - const { clearCofactor } = extraOpts; - if (cofactor === _1n2) - return this; - if (clearCofactor) - return clearCofactor(Point, this); - return this.multiplyUnsafe(cofactor); - } - isSmallOrder() { - return this.multiplyUnsafe(cofactor).is0(); - } - toBytes(isCompressed = true) { - (0, utils_ts_1._abool2)(isCompressed, "isCompressed"); - this.assertValidity(); - return encodePoint(Point, this, isCompressed); - } - toHex(isCompressed = true) { - return (0, utils_ts_1.bytesToHex)(this.toBytes(isCompressed)); - } - toString() { - return ``; - } - // TODO: remove - get px() { - return this.X; - } - get py() { - return this.X; - } - get pz() { - return this.Z; - } - toRawBytes(isCompressed = true) { - return this.toBytes(isCompressed); - } - _setWindowSize(windowSize) { - this.precompute(windowSize); - } - static normalizeZ(points) { - return (0, curve_ts_1.normalizeZ)(Point, points); - } - static msm(points, scalars) { - return (0, curve_ts_1.pippenger)(Point, Fn, points, scalars); - } - static fromPrivateKey(privateKey) { - return Point.BASE.multiply(_normFnElement(Fn, privateKey)); - } - } - Point.BASE = new Point(CURVE.Gx, CURVE.Gy, Fp.ONE); - Point.ZERO = new Point(Fp.ZERO, Fp.ONE, Fp.ZERO); - Point.Fp = Fp; - Point.Fn = Fn; - const bits = Fn.BITS; - const wnaf = new curve_ts_1.wNAF(Point, extraOpts.endo ? Math.ceil(bits / 2) : bits); - Point.BASE.precompute(8); - return Point; - } - function pprefix(hasEvenY) { - return Uint8Array.of(hasEvenY ? 2 : 3); - } - function SWUFpSqrtRatio(Fp, Z) { - const q = Fp.ORDER; - let l = _0n2; - for (let o = q - _1n2; o % _2n === _0n2; o /= _2n) - l += _1n2; - const c1 = l; - const _2n_pow_c1_1 = _2n << c1 - _1n2 - _1n2; - const _2n_pow_c1 = _2n_pow_c1_1 * _2n; - const c2 = (q - _1n2) / _2n_pow_c1; - const c3 = (c2 - _1n2) / _2n; - const c4 = _2n_pow_c1 - _1n2; - const c5 = _2n_pow_c1_1; - const c6 = Fp.pow(Z, c2); - const c7 = Fp.pow(Z, (c2 + _1n2) / _2n); - let sqrtRatio = (u, v) => { - let tv1 = c6; - let tv2 = Fp.pow(v, c4); - let tv3 = Fp.sqr(tv2); - tv3 = Fp.mul(tv3, v); - let tv5 = Fp.mul(u, tv3); - tv5 = Fp.pow(tv5, c3); - tv5 = Fp.mul(tv5, tv2); - tv2 = Fp.mul(tv5, v); - tv3 = Fp.mul(tv5, u); - let tv4 = Fp.mul(tv3, tv2); - tv5 = Fp.pow(tv4, c5); - let isQR = Fp.eql(tv5, Fp.ONE); - tv2 = Fp.mul(tv3, c7); - tv5 = Fp.mul(tv4, tv1); - tv3 = Fp.cmov(tv2, tv3, isQR); - tv4 = Fp.cmov(tv5, tv4, isQR); - for (let i = c1; i > _1n2; i--) { - let tv52 = i - _2n; - tv52 = _2n << tv52 - _1n2; - let tvv5 = Fp.pow(tv4, tv52); - const e1 = Fp.eql(tvv5, Fp.ONE); - tv2 = Fp.mul(tv3, tv1); - tv1 = Fp.mul(tv1, tv1); - tvv5 = Fp.mul(tv4, tv1); - tv3 = Fp.cmov(tv2, tv3, e1); - tv4 = Fp.cmov(tvv5, tv4, e1); - } - return { isValid: isQR, value: tv3 }; - }; - if (Fp.ORDER % _4n === _3n) { - const c12 = (Fp.ORDER - _3n) / _4n; - const c22 = Fp.sqrt(Fp.neg(Z)); - sqrtRatio = (u, v) => { - let tv1 = Fp.sqr(v); - const tv2 = Fp.mul(u, v); - tv1 = Fp.mul(tv1, tv2); - let y1 = Fp.pow(tv1, c12); - y1 = Fp.mul(y1, tv2); - const y2 = Fp.mul(y1, c22); - const tv3 = Fp.mul(Fp.sqr(y1), v); - const isQR = Fp.eql(tv3, u); - let y = Fp.cmov(y2, y1, isQR); - return { isValid: isQR, value: y }; - }; - } - return sqrtRatio; - } - function mapToCurveSimpleSWU(Fp, opts) { - (0, modular_ts_1.validateField)(Fp); - const { A, B, Z } = opts; - if (!Fp.isValid(A) || !Fp.isValid(B) || !Fp.isValid(Z)) - throw new Error("mapToCurveSimpleSWU: invalid opts"); - const sqrtRatio = SWUFpSqrtRatio(Fp, Z); - if (!Fp.isOdd) - throw new Error("Field does not have .isOdd()"); - return (u) => { - let tv1, tv2, tv3, tv4, tv5, tv6, x, y; - tv1 = Fp.sqr(u); - tv1 = Fp.mul(tv1, Z); - tv2 = Fp.sqr(tv1); - tv2 = Fp.add(tv2, tv1); - tv3 = Fp.add(tv2, Fp.ONE); - tv3 = Fp.mul(tv3, B); - tv4 = Fp.cmov(Z, Fp.neg(tv2), !Fp.eql(tv2, Fp.ZERO)); - tv4 = Fp.mul(tv4, A); - tv2 = Fp.sqr(tv3); - tv6 = Fp.sqr(tv4); - tv5 = Fp.mul(tv6, A); - tv2 = Fp.add(tv2, tv5); - tv2 = Fp.mul(tv2, tv3); - tv6 = Fp.mul(tv6, tv4); - tv5 = Fp.mul(tv6, B); - tv2 = Fp.add(tv2, tv5); - x = Fp.mul(tv1, tv3); - const { isValid, value } = sqrtRatio(tv2, tv6); - y = Fp.mul(tv1, u); - y = Fp.mul(y, value); - x = Fp.cmov(x, tv3, isValid); - y = Fp.cmov(y, value, isValid); - const e1 = Fp.isOdd(u) === Fp.isOdd(y); - y = Fp.cmov(Fp.neg(y), y, e1); - const tv4_inv = (0, modular_ts_1.FpInvertBatch)(Fp, [tv4], true)[0]; - x = Fp.mul(x, tv4_inv); - return { x, y }; - }; - } - function getWLengths(Fp, Fn) { - return { - secretKey: Fn.BYTES, - publicKey: 1 + Fp.BYTES, - publicKeyUncompressed: 1 + 2 * Fp.BYTES, - publicKeyHasPrefix: true, - signature: 2 * Fn.BYTES - }; - } - function ecdh(Point, ecdhOpts = {}) { - const { Fn } = Point; - const randomBytes_ = ecdhOpts.randomBytes || utils_ts_1.randomBytes; - const lengths = Object.assign(getWLengths(Point.Fp, Fn), { seed: (0, modular_ts_1.getMinHashLength)(Fn.ORDER) }); - function isValidSecretKey(secretKey) { - try { - return !!_normFnElement(Fn, secretKey); - } catch (error) { - return false; - } - } - function isValidPublicKey(publicKey, isCompressed) { - const { publicKey: comp, publicKeyUncompressed } = lengths; - try { - const l = publicKey.length; - if (isCompressed === true && l !== comp) - return false; - if (isCompressed === false && l !== publicKeyUncompressed) - return false; - return !!Point.fromBytes(publicKey); - } catch (error) { - return false; - } - } - function randomSecretKey(seed = randomBytes_(lengths.seed)) { - return (0, modular_ts_1.mapHashToField)((0, utils_ts_1._abytes2)(seed, lengths.seed, "seed"), Fn.ORDER); - } - function getPublicKey(secretKey, isCompressed = true) { - return Point.BASE.multiply(_normFnElement(Fn, secretKey)).toBytes(isCompressed); - } - function keygen(seed) { - const secretKey = randomSecretKey(seed); - return { secretKey, publicKey: getPublicKey(secretKey) }; - } - function isProbPub(item) { - if (typeof item === "bigint") - return false; - if (item instanceof Point) - return true; - const { secretKey, publicKey, publicKeyUncompressed } = lengths; - if (Fn.allowedLengths || secretKey === publicKey) - return void 0; - const l = (0, utils_ts_1.ensureBytes)("key", item).length; - return l === publicKey || l === publicKeyUncompressed; - } - function getSharedSecret(secretKeyA, publicKeyB, isCompressed = true) { - if (isProbPub(secretKeyA) === true) - throw new Error("first arg must be private key"); - if (isProbPub(publicKeyB) === false) - throw new Error("second arg must be public key"); - const s = _normFnElement(Fn, secretKeyA); - const b = Point.fromHex(publicKeyB); - return b.multiply(s).toBytes(isCompressed); - } - const utils = { - isValidSecretKey, - isValidPublicKey, - randomSecretKey, - // TODO: remove - isValidPrivateKey: isValidSecretKey, - randomPrivateKey: randomSecretKey, - normPrivateKeyToScalar: (key) => _normFnElement(Fn, key), - precompute(windowSize = 8, point2 = Point.BASE) { - return point2.precompute(windowSize, false); - } - }; - return Object.freeze({ getPublicKey, getSharedSecret, keygen, Point, utils, lengths }); - } - function ecdsa(Point, hash, ecdsaOpts = {}) { - (0, utils_1.ahash)(hash); - (0, utils_ts_1._validateObject)(ecdsaOpts, {}, { - hmac: "function", - lowS: "boolean", - randomBytes: "function", - bits2int: "function", - bits2int_modN: "function" - }); - const randomBytes2 = ecdsaOpts.randomBytes || utils_ts_1.randomBytes; - const hmac = ecdsaOpts.hmac || ((key, ...msgs) => (0, hmac_js_1.hmac)(hash, key, (0, utils_ts_1.concatBytes)(...msgs))); - const { Fp, Fn } = Point; - const { ORDER: CURVE_ORDER, BITS: fnBits } = Fn; - const { keygen, getPublicKey, getSharedSecret, utils, lengths } = ecdh(Point, ecdsaOpts); - const defaultSigOpts = { - prehash: false, - lowS: typeof ecdsaOpts.lowS === "boolean" ? ecdsaOpts.lowS : false, - format: void 0, - //'compact' as ECDSASigFormat, - extraEntropy: false - }; - const defaultSigOpts_format = "compact"; - function isBiggerThanHalfOrder(number) { - const HALF = CURVE_ORDER >> _1n2; - return number > HALF; - } - function validateRS(title, num) { - if (!Fn.isValidNot0(num)) - throw new Error(`invalid signature ${title}: out of range 1..Point.Fn.ORDER`); - return num; - } - function validateSigLength(bytes, format) { - validateSigFormat(format); - const size = lengths.signature; - const sizer = format === "compact" ? size : format === "recovered" ? size + 1 : void 0; - return (0, utils_ts_1._abytes2)(bytes, sizer, `${format} signature`); - } - class Signature { - constructor(r, s, recovery) { - this.r = validateRS("r", r); - this.s = validateRS("s", s); - if (recovery != null) - this.recovery = recovery; - Object.freeze(this); - } - static fromBytes(bytes, format = defaultSigOpts_format) { - validateSigLength(bytes, format); - let recid; - if (format === "der") { - const { r: r2, s: s2 } = exports.DER.toSig((0, utils_ts_1._abytes2)(bytes)); - return new Signature(r2, s2); - } - if (format === "recovered") { - recid = bytes[0]; - format = "compact"; - bytes = bytes.subarray(1); - } - const L = Fn.BYTES; - const r = bytes.subarray(0, L); - const s = bytes.subarray(L, L * 2); - return new Signature(Fn.fromBytes(r), Fn.fromBytes(s), recid); - } - static fromHex(hex, format) { - return this.fromBytes((0, utils_ts_1.hexToBytes)(hex), format); - } - addRecoveryBit(recovery) { - return new Signature(this.r, this.s, recovery); - } - recoverPublicKey(messageHash) { - const FIELD_ORDER = Fp.ORDER; - const { r, s, recovery: rec } = this; - if (rec == null || ![0, 1, 2, 3].includes(rec)) - throw new Error("recovery id invalid"); - const hasCofactor = CURVE_ORDER * _2n < FIELD_ORDER; - if (hasCofactor && rec > 1) - throw new Error("recovery id is ambiguous for h>1 curve"); - const radj = rec === 2 || rec === 3 ? r + CURVE_ORDER : r; - if (!Fp.isValid(radj)) - throw new Error("recovery id 2 or 3 invalid"); - const x = Fp.toBytes(radj); - const R = Point.fromBytes((0, utils_ts_1.concatBytes)(pprefix((rec & 1) === 0), x)); - const ir = Fn.inv(radj); - const h = bits2int_modN((0, utils_ts_1.ensureBytes)("msgHash", messageHash)); - const u1 = Fn.create(-h * ir); - const u2 = Fn.create(s * ir); - const Q = Point.BASE.multiplyUnsafe(u1).add(R.multiplyUnsafe(u2)); - if (Q.is0()) - throw new Error("point at infinify"); - Q.assertValidity(); - return Q; - } - // Signatures should be low-s, to prevent malleability. - hasHighS() { - return isBiggerThanHalfOrder(this.s); - } - toBytes(format = defaultSigOpts_format) { - validateSigFormat(format); - if (format === "der") - return (0, utils_ts_1.hexToBytes)(exports.DER.hexFromSig(this)); - const r = Fn.toBytes(this.r); - const s = Fn.toBytes(this.s); - if (format === "recovered") { - if (this.recovery == null) - throw new Error("recovery bit must be present"); - return (0, utils_ts_1.concatBytes)(Uint8Array.of(this.recovery), r, s); - } - return (0, utils_ts_1.concatBytes)(r, s); - } - toHex(format) { - return (0, utils_ts_1.bytesToHex)(this.toBytes(format)); - } - // TODO: remove - assertValidity() { - } - static fromCompact(hex) { - return Signature.fromBytes((0, utils_ts_1.ensureBytes)("sig", hex), "compact"); - } - static fromDER(hex) { - return Signature.fromBytes((0, utils_ts_1.ensureBytes)("sig", hex), "der"); - } - normalizeS() { - return this.hasHighS() ? new Signature(this.r, Fn.neg(this.s), this.recovery) : this; - } - toDERRawBytes() { - return this.toBytes("der"); - } - toDERHex() { - return (0, utils_ts_1.bytesToHex)(this.toBytes("der")); - } - toCompactRawBytes() { - return this.toBytes("compact"); - } - toCompactHex() { - return (0, utils_ts_1.bytesToHex)(this.toBytes("compact")); - } - } - const bits2int = ecdsaOpts.bits2int || function bits2int_def(bytes) { - if (bytes.length > 8192) - throw new Error("input is too large"); - const num = (0, utils_ts_1.bytesToNumberBE)(bytes); - const delta = bytes.length * 8 - fnBits; - return delta > 0 ? num >> BigInt(delta) : num; - }; - const bits2int_modN = ecdsaOpts.bits2int_modN || function bits2int_modN_def(bytes) { - return Fn.create(bits2int(bytes)); - }; - const ORDER_MASK = (0, utils_ts_1.bitMask)(fnBits); - function int2octets(num) { - (0, utils_ts_1.aInRange)("num < 2^" + fnBits, num, _0n2, ORDER_MASK); - return Fn.toBytes(num); - } - function validateMsgAndHash(message, prehash) { - (0, utils_ts_1._abytes2)(message, void 0, "message"); - return prehash ? (0, utils_ts_1._abytes2)(hash(message), void 0, "prehashed message") : message; - } - function prepSig(message, privateKey, opts) { - if (["recovered", "canonical"].some((k) => k in opts)) - throw new Error("sign() legacy options not supported"); - const { lowS, prehash, extraEntropy } = validateSigOpts(opts, defaultSigOpts); - message = validateMsgAndHash(message, prehash); - const h1int = bits2int_modN(message); - const d = _normFnElement(Fn, privateKey); - const seedArgs = [int2octets(d), int2octets(h1int)]; - if (extraEntropy != null && extraEntropy !== false) { - const e = extraEntropy === true ? randomBytes2(lengths.secretKey) : extraEntropy; - seedArgs.push((0, utils_ts_1.ensureBytes)("extraEntropy", e)); - } - const seed = (0, utils_ts_1.concatBytes)(...seedArgs); - const m = h1int; - function k2sig(kBytes) { - const k = bits2int(kBytes); - if (!Fn.isValidNot0(k)) - return; - const ik = Fn.inv(k); - const q = Point.BASE.multiply(k).toAffine(); - const r = Fn.create(q.x); - if (r === _0n2) - return; - const s = Fn.create(ik * Fn.create(m + r * d)); - if (s === _0n2) - return; - let recovery = (q.x === r ? 0 : 2) | Number(q.y & _1n2); - let normS = s; - if (lowS && isBiggerThanHalfOrder(s)) { - normS = Fn.neg(s); - recovery ^= 1; - } - return new Signature(r, normS, recovery); - } - return { seed, k2sig }; - } - function sign(message, secretKey, opts = {}) { - message = (0, utils_ts_1.ensureBytes)("message", message); - const { seed, k2sig } = prepSig(message, secretKey, opts); - const drbg = (0, utils_ts_1.createHmacDrbg)(hash.outputLen, Fn.BYTES, hmac); - const sig = drbg(seed, k2sig); - return sig; - } - function tryParsingSig(sg) { - let sig = void 0; - const isHex = typeof sg === "string" || (0, utils_ts_1.isBytes)(sg); - const isObj2 = !isHex && sg !== null && typeof sg === "object" && typeof sg.r === "bigint" && typeof sg.s === "bigint"; - if (!isHex && !isObj2) - throw new Error("invalid signature, expected Uint8Array, hex string or Signature instance"); - if (isObj2) { - sig = new Signature(sg.r, sg.s); - } else if (isHex) { - try { - sig = Signature.fromBytes((0, utils_ts_1.ensureBytes)("sig", sg), "der"); - } catch (derError) { - if (!(derError instanceof exports.DER.Err)) - throw derError; - } - if (!sig) { - try { - sig = Signature.fromBytes((0, utils_ts_1.ensureBytes)("sig", sg), "compact"); - } catch (error) { - return false; - } - } - } - if (!sig) - return false; - return sig; - } - function verify(signature, message, publicKey, opts = {}) { - const { lowS, prehash, format } = validateSigOpts(opts, defaultSigOpts); - publicKey = (0, utils_ts_1.ensureBytes)("publicKey", publicKey); - message = validateMsgAndHash((0, utils_ts_1.ensureBytes)("message", message), prehash); - if ("strict" in opts) - throw new Error("options.strict was renamed to lowS"); - const sig = format === void 0 ? tryParsingSig(signature) : Signature.fromBytes((0, utils_ts_1.ensureBytes)("sig", signature), format); - if (sig === false) - return false; - try { - const P = Point.fromBytes(publicKey); - if (lowS && sig.hasHighS()) - return false; - const { r, s } = sig; - const h = bits2int_modN(message); - const is2 = Fn.inv(s); - const u1 = Fn.create(h * is2); - const u2 = Fn.create(r * is2); - const R = Point.BASE.multiplyUnsafe(u1).add(P.multiplyUnsafe(u2)); - if (R.is0()) - return false; - const v = Fn.create(R.x); - return v === r; - } catch (e) { - return false; - } - } - function recoverPublicKey(signature, message, opts = {}) { - const { prehash } = validateSigOpts(opts, defaultSigOpts); - message = validateMsgAndHash(message, prehash); - return Signature.fromBytes(signature, "recovered").recoverPublicKey(message).toBytes(); - } - return Object.freeze({ - keygen, - getPublicKey, - getSharedSecret, - utils, - lengths, - Point, - sign, - verify, - recoverPublicKey, - Signature, - hash - }); - } - function weierstrassPoints(c) { - const { CURVE, curveOpts } = _weierstrass_legacy_opts_to_new(c); - const Point = weierstrassN(CURVE, curveOpts); - return _weierstrass_new_output_to_legacy(c, Point); - } - function _weierstrass_legacy_opts_to_new(c) { - const CURVE = { - a: c.a, - b: c.b, - p: c.Fp.ORDER, - n: c.n, - h: c.h, - Gx: c.Gx, - Gy: c.Gy - }; - const Fp = c.Fp; - let allowedLengths = c.allowedPrivateKeyLengths ? Array.from(new Set(c.allowedPrivateKeyLengths.map((l) => Math.ceil(l / 2)))) : void 0; - const Fn = (0, modular_ts_1.Field)(CURVE.n, { - BITS: c.nBitLength, - allowedLengths, - modFromBytes: c.wrapPrivateKey - }); - const curveOpts = { - Fp, - Fn, - allowInfinityPoint: c.allowInfinityPoint, - endo: c.endo, - isTorsionFree: c.isTorsionFree, - clearCofactor: c.clearCofactor, - fromBytes: c.fromBytes, - toBytes: c.toBytes - }; - return { CURVE, curveOpts }; - } - function _ecdsa_legacy_opts_to_new(c) { - const { CURVE, curveOpts } = _weierstrass_legacy_opts_to_new(c); - const ecdsaOpts = { - hmac: c.hmac, - randomBytes: c.randomBytes, - lowS: c.lowS, - bits2int: c.bits2int, - bits2int_modN: c.bits2int_modN - }; - return { CURVE, curveOpts, hash: c.hash, ecdsaOpts }; - } - function _legacyHelperEquat(Fp, a, b) { - function weierstrassEquation(x) { - const x2 = Fp.sqr(x); - const x3 = Fp.mul(x2, x); - return Fp.add(Fp.add(x3, Fp.mul(x, a)), b); - } - return weierstrassEquation; - } - function _weierstrass_new_output_to_legacy(c, Point) { - const { Fp, Fn } = Point; - function isWithinCurveOrder(num) { - return (0, utils_ts_1.inRange)(num, _1n2, Fn.ORDER); - } - const weierstrassEquation = _legacyHelperEquat(Fp, c.a, c.b); - return Object.assign({}, { - CURVE: c, - Point, - ProjectivePoint: Point, - normPrivateKeyToScalar: (key) => _normFnElement(Fn, key), - weierstrassEquation, - isWithinCurveOrder - }); - } - function _ecdsa_new_output_to_legacy(c, _ecdsa) { - const Point = _ecdsa.Point; - return Object.assign({}, _ecdsa, { - ProjectivePoint: Point, - CURVE: Object.assign({}, c, (0, modular_ts_1.nLength)(Point.Fn.ORDER, Point.Fn.BITS)) - }); - } - function weierstrass(c) { - const { CURVE, curveOpts, hash, ecdsaOpts } = _ecdsa_legacy_opts_to_new(c); - const Point = weierstrassN(CURVE, curveOpts); - const signs = ecdsa(Point, hash, ecdsaOpts); - return _ecdsa_new_output_to_legacy(c, signs); - } - } -}); - -// node_modules/@noble/curves/_shortw_utils.js -var require_shortw_utils = __commonJS({ - "node_modules/@noble/curves/_shortw_utils.js"(exports) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.getHash = getHash; - exports.createCurve = createCurve; - var weierstrass_ts_1 = require_weierstrass(); - function getHash(hash) { - return { hash }; - } - function createCurve(curveDef, defHash) { - const create = (hash) => (0, weierstrass_ts_1.weierstrass)({ ...curveDef, hash }); - return { ...create(defHash), create }; - } - } -}); - -// node_modules/@noble/curves/abstract/hash-to-curve.js -var require_hash_to_curve = __commonJS({ - "node_modules/@noble/curves/abstract/hash-to-curve.js"(exports) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports._DST_scalar = void 0; - exports.expand_message_xmd = expand_message_xmd; - exports.expand_message_xof = expand_message_xof; - exports.hash_to_field = hash_to_field; - exports.isogenyMap = isogenyMap; - exports.createHasher = createHasher2; - var utils_ts_1 = require_utils2(); - var modular_ts_1 = require_modular(); - var os2ip = utils_ts_1.bytesToNumberBE; - function i2osp(value, length) { - anum(value); - anum(length); - if (value < 0 || value >= 1 << 8 * length) - throw new Error("invalid I2OSP input: " + value); - const res = Array.from({ length }).fill(0); - for (let i = length - 1; i >= 0; i--) { - res[i] = value & 255; - value >>>= 8; - } - return new Uint8Array(res); - } - function strxor(a, b) { - const arr = new Uint8Array(a.length); - for (let i = 0; i < a.length; i++) { - arr[i] = a[i] ^ b[i]; - } - return arr; - } - function anum(item) { - if (!Number.isSafeInteger(item)) - throw new Error("number expected"); - } - function normDST(DST) { - if (!(0, utils_ts_1.isBytes)(DST) && typeof DST !== "string") - throw new Error("DST must be Uint8Array or string"); - return typeof DST === "string" ? (0, utils_ts_1.utf8ToBytes)(DST) : DST; - } - function expand_message_xmd(msg, DST, lenInBytes, H) { - (0, utils_ts_1.abytes)(msg); - anum(lenInBytes); - DST = normDST(DST); - if (DST.length > 255) - DST = H((0, utils_ts_1.concatBytes)((0, utils_ts_1.utf8ToBytes)("H2C-OVERSIZE-DST-"), DST)); - const { outputLen: b_in_bytes, blockLen: r_in_bytes } = H; - const ell = Math.ceil(lenInBytes / b_in_bytes); - if (lenInBytes > 65535 || ell > 255) - throw new Error("expand_message_xmd: invalid lenInBytes"); - const DST_prime = (0, utils_ts_1.concatBytes)(DST, i2osp(DST.length, 1)); - const Z_pad = i2osp(0, r_in_bytes); - const l_i_b_str = i2osp(lenInBytes, 2); - const b = new Array(ell); - const b_0 = H((0, utils_ts_1.concatBytes)(Z_pad, msg, l_i_b_str, i2osp(0, 1), DST_prime)); - b[0] = H((0, utils_ts_1.concatBytes)(b_0, i2osp(1, 1), DST_prime)); - for (let i = 1; i <= ell; i++) { - const args = [strxor(b_0, b[i - 1]), i2osp(i + 1, 1), DST_prime]; - b[i] = H((0, utils_ts_1.concatBytes)(...args)); - } - const pseudo_random_bytes = (0, utils_ts_1.concatBytes)(...b); - return pseudo_random_bytes.slice(0, lenInBytes); - } - function expand_message_xof(msg, DST, lenInBytes, k, H) { - (0, utils_ts_1.abytes)(msg); - anum(lenInBytes); - DST = normDST(DST); - if (DST.length > 255) { - const dkLen = Math.ceil(2 * k / 8); - DST = H.create({ dkLen }).update((0, utils_ts_1.utf8ToBytes)("H2C-OVERSIZE-DST-")).update(DST).digest(); - } - if (lenInBytes > 65535 || DST.length > 255) - throw new Error("expand_message_xof: invalid lenInBytes"); - return H.create({ dkLen: lenInBytes }).update(msg).update(i2osp(lenInBytes, 2)).update(DST).update(i2osp(DST.length, 1)).digest(); - } - function hash_to_field(msg, count, options) { - (0, utils_ts_1._validateObject)(options, { - p: "bigint", - m: "number", - k: "number", - hash: "function" - }); - const { p, k, m, hash, expand, DST } = options; - if (!(0, utils_ts_1.isHash)(options.hash)) - throw new Error("expected valid hash"); - (0, utils_ts_1.abytes)(msg); - anum(count); - const log2p = p.toString(2).length; - const L = Math.ceil((log2p + k) / 8); - const len_in_bytes = count * m * L; - let prb; - if (expand === "xmd") { - prb = expand_message_xmd(msg, DST, len_in_bytes, hash); - } else if (expand === "xof") { - prb = expand_message_xof(msg, DST, len_in_bytes, k, hash); - } else if (expand === "_internal_pass") { - prb = msg; - } else { - throw new Error('expand must be "xmd" or "xof"'); - } - const u = new Array(count); - for (let i = 0; i < count; i++) { - const e = new Array(m); - for (let j = 0; j < m; j++) { - const elm_offset = L * (j + i * m); - const tv = prb.subarray(elm_offset, elm_offset + L); - e[j] = (0, modular_ts_1.mod)(os2ip(tv), p); - } - u[i] = e; - } - return u; - } - function isogenyMap(field, map2) { - const coeff = map2.map((i) => Array.from(i).reverse()); - return (x, y) => { - const [xn, xd, yn, yd] = coeff.map((val) => val.reduce((acc, i) => field.add(field.mul(acc, x), i))); - const [xd_inv, yd_inv] = (0, modular_ts_1.FpInvertBatch)(field, [xd, yd], true); - x = field.mul(xn, xd_inv); - y = field.mul(y, field.mul(yn, yd_inv)); - return { x, y }; - }; - } - exports._DST_scalar = (0, utils_ts_1.utf8ToBytes)("HashToScalar-"); - function createHasher2(Point, mapToCurve, defaults) { - if (typeof mapToCurve !== "function") - throw new Error("mapToCurve() must be defined"); - function map2(num) { - return Point.fromAffine(mapToCurve(num)); - } - function clear(initial) { - const P = initial.clearCofactor(); - if (P.equals(Point.ZERO)) - return Point.ZERO; - P.assertValidity(); - return P; - } - return { - defaults, - hashToCurve(msg, options) { - const opts = Object.assign({}, defaults, options); - const u = hash_to_field(msg, 2, opts); - const u0 = map2(u[0]); - const u1 = map2(u[1]); - return clear(u0.add(u1)); - }, - encodeToCurve(msg, options) { - const optsDst = defaults.encodeDST ? { DST: defaults.encodeDST } : {}; - const opts = Object.assign({}, defaults, optsDst, options); - const u = hash_to_field(msg, 1, opts); - const u0 = map2(u[0]); - return clear(u0); - }, - /** See {@link H2CHasher} */ - mapToCurve(scalars) { - if (!Array.isArray(scalars)) - throw new Error("expected array of bigints"); - for (const i of scalars) - if (typeof i !== "bigint") - throw new Error("expected array of bigints"); - return clear(map2(scalars)); - }, - // hash_to_scalar can produce 0: https://www.rfc-editor.org/errata/eid8393 - // RFC 9380, draft-irtf-cfrg-bbs-signatures-08 - hashToScalar(msg, options) { - const N = Point.Fn.ORDER; - const opts = Object.assign({}, defaults, { p: N, m: 1, DST: exports._DST_scalar }, options); - return hash_to_field(msg, 1, opts)[0][0]; - } - }; - } - } -}); - -// node_modules/@noble/curves/secp256k1.js -var require_secp256k1 = __commonJS({ - "node_modules/@noble/curves/secp256k1.js"(exports) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.encodeToCurve = exports.hashToCurve = exports.secp256k1_hasher = exports.schnorr = exports.secp256k1 = void 0; - var sha2_js_1 = require_sha2(); - var utils_js_1 = require_utils(); - var _shortw_utils_ts_1 = require_shortw_utils(); - var hash_to_curve_ts_1 = require_hash_to_curve(); - var modular_ts_1 = require_modular(); - var weierstrass_ts_1 = require_weierstrass(); - var utils_ts_1 = require_utils2(); - var secp256k1_CURVE = { - p: BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"), - n: BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"), - h: BigInt(1), - a: BigInt(0), - b: BigInt(7), - Gx: BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"), - Gy: BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8") - }; - var secp256k1_ENDO = { - beta: BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"), - basises: [ - [BigInt("0x3086d221a7d46bcde86c90e49284eb15"), -BigInt("0xe4437ed6010e88286f547fa90abfe4c3")], - [BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"), BigInt("0x3086d221a7d46bcde86c90e49284eb15")] - ] - }; - var _0n2 = BigInt(0); - var _1n2 = BigInt(1); - var _2n = BigInt(2); - function sqrtMod(y) { - const P = secp256k1_CURVE.p; - const _3n = BigInt(3), _6n = BigInt(6), _11n = BigInt(11), _22n = BigInt(22); - const _23n = BigInt(23), _44n = BigInt(44), _88n = BigInt(88); - const b2 = y * y * y % P; - const b3 = b2 * b2 * y % P; - const b6 = (0, modular_ts_1.pow2)(b3, _3n, P) * b3 % P; - const b9 = (0, modular_ts_1.pow2)(b6, _3n, P) * b3 % P; - const b11 = (0, modular_ts_1.pow2)(b9, _2n, P) * b2 % P; - const b22 = (0, modular_ts_1.pow2)(b11, _11n, P) * b11 % P; - const b44 = (0, modular_ts_1.pow2)(b22, _22n, P) * b22 % P; - const b88 = (0, modular_ts_1.pow2)(b44, _44n, P) * b44 % P; - const b176 = (0, modular_ts_1.pow2)(b88, _88n, P) * b88 % P; - const b220 = (0, modular_ts_1.pow2)(b176, _44n, P) * b44 % P; - const b223 = (0, modular_ts_1.pow2)(b220, _3n, P) * b3 % P; - const t1 = (0, modular_ts_1.pow2)(b223, _23n, P) * b22 % P; - const t2 = (0, modular_ts_1.pow2)(t1, _6n, P) * b2 % P; - const root = (0, modular_ts_1.pow2)(t2, _2n, P); - if (!Fpk1.eql(Fpk1.sqr(root), y)) - throw new Error("Cannot find square root"); - return root; - } - var Fpk1 = (0, modular_ts_1.Field)(secp256k1_CURVE.p, { sqrt: sqrtMod }); - exports.secp256k1 = (0, _shortw_utils_ts_1.createCurve)({ ...secp256k1_CURVE, Fp: Fpk1, lowS: true, endo: secp256k1_ENDO }, sha2_js_1.sha256); - var TAGGED_HASH_PREFIXES = {}; - function taggedHash(tag, ...messages) { - let tagP = TAGGED_HASH_PREFIXES[tag]; - if (tagP === void 0) { - const tagH = (0, sha2_js_1.sha256)((0, utils_ts_1.utf8ToBytes)(tag)); - tagP = (0, utils_ts_1.concatBytes)(tagH, tagH); - TAGGED_HASH_PREFIXES[tag] = tagP; - } - return (0, sha2_js_1.sha256)((0, utils_ts_1.concatBytes)(tagP, ...messages)); - } - var pointToBytes = (point2) => point2.toBytes(true).slice(1); - var Pointk1 = (() => exports.secp256k1.Point)(); - var hasEven = (y) => y % _2n === _0n2; - function schnorrGetExtPubKey(priv) { - const { Fn, BASE } = Pointk1; - const d_ = (0, weierstrass_ts_1._normFnElement)(Fn, priv); - const p = BASE.multiply(d_); - const scalar = hasEven(p.y) ? d_ : Fn.neg(d_); - return { scalar, bytes: pointToBytes(p) }; - } - function lift_x(x) { - const Fp = Fpk1; - if (!Fp.isValidNot0(x)) - throw new Error("invalid x: Fail if x ≥ p"); - const xx = Fp.create(x * x); - const c = Fp.create(xx * x + BigInt(7)); - let y = Fp.sqrt(c); - if (!hasEven(y)) - y = Fp.neg(y); - const p = Pointk1.fromAffine({ x, y }); - p.assertValidity(); - return p; - } - var num = utils_ts_1.bytesToNumberBE; - function challenge(...args) { - return Pointk1.Fn.create(num(taggedHash("BIP0340/challenge", ...args))); - } - function schnorrGetPublicKey(secretKey) { - return schnorrGetExtPubKey(secretKey).bytes; - } - function schnorrSign(message, secretKey, auxRand = (0, utils_js_1.randomBytes)(32)) { - const { Fn } = Pointk1; - const m = (0, utils_ts_1.ensureBytes)("message", message); - const { bytes: px, scalar: d } = schnorrGetExtPubKey(secretKey); - const a = (0, utils_ts_1.ensureBytes)("auxRand", auxRand, 32); - const t = Fn.toBytes(d ^ num(taggedHash("BIP0340/aux", a))); - const rand = taggedHash("BIP0340/nonce", t, px, m); - const { bytes: rx, scalar: k } = schnorrGetExtPubKey(rand); - const e = challenge(rx, px, m); - const sig = new Uint8Array(64); - sig.set(rx, 0); - sig.set(Fn.toBytes(Fn.create(k + e * d)), 32); - if (!schnorrVerify(sig, m, px)) - throw new Error("sign: Invalid signature produced"); - return sig; - } - function schnorrVerify(signature, message, publicKey) { - const { Fn, BASE } = Pointk1; - const sig = (0, utils_ts_1.ensureBytes)("signature", signature, 64); - const m = (0, utils_ts_1.ensureBytes)("message", message); - const pub = (0, utils_ts_1.ensureBytes)("publicKey", publicKey, 32); - try { - const P = lift_x(num(pub)); - const r = num(sig.subarray(0, 32)); - if (!(0, utils_ts_1.inRange)(r, _1n2, secp256k1_CURVE.p)) - return false; - const s = num(sig.subarray(32, 64)); - if (!(0, utils_ts_1.inRange)(s, _1n2, secp256k1_CURVE.n)) - return false; - const e = challenge(Fn.toBytes(r), pointToBytes(P), m); - const R = BASE.multiplyUnsafe(s).add(P.multiplyUnsafe(Fn.neg(e))); - const { x, y } = R.toAffine(); - if (R.is0() || !hasEven(y) || x !== r) - return false; - return true; - } catch (error) { - return false; - } - } - exports.schnorr = (() => { - const size = 32; - const seedLength = 48; - const randomSecretKey = (seed = (0, utils_js_1.randomBytes)(seedLength)) => { - return (0, modular_ts_1.mapHashToField)(seed, secp256k1_CURVE.n); - }; - exports.secp256k1.utils.randomSecretKey; - function keygen(seed) { - const secretKey = randomSecretKey(seed); - return { secretKey, publicKey: schnorrGetPublicKey(secretKey) }; - } - return { - keygen, - getPublicKey: schnorrGetPublicKey, - sign: schnorrSign, - verify: schnorrVerify, - Point: Pointk1, - utils: { - randomSecretKey, - randomPrivateKey: randomSecretKey, - taggedHash, - // TODO: remove - lift_x, - pointToBytes, - numberToBytesBE: utils_ts_1.numberToBytesBE, - bytesToNumberBE: utils_ts_1.bytesToNumberBE, - mod: modular_ts_1.mod - }, - lengths: { - secretKey: size, - publicKey: size, - publicKeyHasPrefix: false, - signature: size * 2, - seed: seedLength - } - }; - })(); - var isoMap = (() => (0, hash_to_curve_ts_1.isogenyMap)(Fpk1, [ - // xNum - [ - "0x8e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38daaaaa8c7", - "0x7d3d4c80bc321d5b9f315cea7fd44c5d595d2fc0bf63b92dfff1044f17c6581", - "0x534c328d23f234e6e2a413deca25caece4506144037c40314ecbd0b53d9dd262", - "0x8e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38daaaaa88c" - ], - // xDen - [ - "0xd35771193d94918a9ca34ccbb7b640dd86cd409542f8487d9fe6b745781eb49b", - "0xedadc6f64383dc1df7c4b2d51b54225406d36b641f5e41bbc52a56612a8c6d14", - "0x0000000000000000000000000000000000000000000000000000000000000001" - // LAST 1 - ], - // yNum - [ - "0x4bda12f684bda12f684bda12f684bda12f684bda12f684bda12f684b8e38e23c", - "0xc75e0c32d5cb7c0fa9d0a54b12a0a6d5647ab046d686da6fdffc90fc201d71a3", - "0x29a6194691f91a73715209ef6512e576722830a201be2018a765e85a9ecee931", - "0x2f684bda12f684bda12f684bda12f684bda12f684bda12f684bda12f38e38d84" - ], - // yDen - [ - "0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffff93b", - "0x7a06534bb8bdb49fd5e9e6632722c2989467c1bfc8e8d978dfb425d2685c2573", - "0x6484aa716545ca2cf3a70c3fa8fe337e0a3d21162f0d6299a7bf8192bfd2a76f", - "0x0000000000000000000000000000000000000000000000000000000000000001" - // LAST 1 - ] - ].map((i) => i.map((j) => BigInt(j)))))(); - var mapSWU = (() => (0, weierstrass_ts_1.mapToCurveSimpleSWU)(Fpk1, { - A: BigInt("0x3f8731abdd661adca08a5558f0f5d272e953d363cb6f0e5d405447c01a444533"), - B: BigInt("1771"), - Z: Fpk1.create(BigInt("-11")) - }))(); - exports.secp256k1_hasher = (() => (0, hash_to_curve_ts_1.createHasher)(exports.secp256k1.Point, (scalars) => { - const { x, y } = mapSWU(Fpk1.create(scalars[0])); - return isoMap(x, y); - }, { - DST: "secp256k1_XMD:SHA-256_SSWU_RO_", - encodeDST: "secp256k1_XMD:SHA-256_SSWU_NU_", - p: Fpk1.ORDER, - m: 1, - k: 128, - expand: "xmd", - hash: sha2_js_1.sha256 - }))(); - exports.hashToCurve = (() => exports.secp256k1_hasher.hashToCurve)(); - exports.encodeToCurve = (() => exports.secp256k1_hasher.encodeToCurve)(); - } -}); - -// node_modules/@noble/hashes/sha256.js -var require_sha256 = __commonJS({ - "node_modules/@noble/hashes/sha256.js"(exports) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.sha224 = exports.SHA224 = exports.sha256 = exports.SHA256 = void 0; - var sha2_ts_1 = require_sha2(); - exports.SHA256 = sha2_ts_1.SHA256; - exports.sha256 = sha2_ts_1.sha256; - exports.SHA224 = sha2_ts_1.SHA224; - exports.sha224 = sha2_ts_1.sha224; - } -}); - -// node_modules/@noble/curves/abstract/utils.js -var require_utils3 = __commonJS({ - "node_modules/@noble/curves/abstract/utils.js"(exports) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.isHash = exports.validateObject = exports.memoized = exports.notImplemented = exports.createHmacDrbg = exports.bitMask = exports.bitSet = exports.bitGet = exports.bitLen = exports.aInRange = exports.inRange = exports.asciiToBytes = exports.copyBytes = exports.equalBytes = exports.ensureBytes = exports.numberToVarBytesBE = exports.numberToBytesLE = exports.numberToBytesBE = exports.bytesToNumberLE = exports.bytesToNumberBE = exports.hexToNumber = exports.numberToHexUnpadded = exports.abool = exports.utf8ToBytes = exports.randomBytes = exports.isBytes = exports.hexToBytes = exports.concatBytes = exports.bytesToUtf8 = exports.bytesToHex = exports.anumber = exports.abytes = void 0; - var u = require_utils2(); - exports.abytes = u.abytes; - exports.anumber = u.anumber; - exports.bytesToHex = u.bytesToHex; - exports.bytesToUtf8 = u.bytesToUtf8; - exports.concatBytes = u.concatBytes; - exports.hexToBytes = u.hexToBytes; - exports.isBytes = u.isBytes; - exports.randomBytes = u.randomBytes; - exports.utf8ToBytes = u.utf8ToBytes; - exports.abool = u.abool; - exports.numberToHexUnpadded = u.numberToHexUnpadded; - exports.hexToNumber = u.hexToNumber; - exports.bytesToNumberBE = u.bytesToNumberBE; - exports.bytesToNumberLE = u.bytesToNumberLE; - exports.numberToBytesBE = u.numberToBytesBE; - exports.numberToBytesLE = u.numberToBytesLE; - exports.numberToVarBytesBE = u.numberToVarBytesBE; - exports.ensureBytes = u.ensureBytes; - exports.equalBytes = u.equalBytes; - exports.copyBytes = u.copyBytes; - exports.asciiToBytes = u.asciiToBytes; - exports.inRange = u.inRange; - exports.aInRange = u.aInRange; - exports.bitLen = u.bitLen; - exports.bitGet = u.bitGet; - exports.bitSet = u.bitSet; - exports.bitMask = u.bitMask; - exports.createHmacDrbg = u.createHmacDrbg; - exports.notImplemented = u.notImplemented; - exports.memoized = u.memoized; - exports.validateObject = u.validateObject; - exports.isHash = u.isHash; - } -}); - -// node_modules/@cashu/crypto/modules/esm/util/utils.js -var require_utils4 = __commonJS({ - "node_modules/@cashu/crypto/modules/esm/util/utils.js"(exports) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.encodeBase64toUint8 = exports.hexToNumber = exports.bytesToNumber = void 0; - var utils_1 = require_utils3(); - var buffer_1 = require_buffer(); - function bytesToNumber2(bytes) { - return hexToNumber3((0, utils_1.bytesToHex)(bytes)); - } - exports.bytesToNumber = bytesToNumber2; - function hexToNumber3(hex) { - return BigInt(`0x${hex}`); - } - exports.hexToNumber = hexToNumber3; - function encodeBase64toUint82(base64String) { - return buffer_1.Buffer.from(base64String, "base64"); - } - exports.encodeBase64toUint8 = encodeBase64toUint82; - } -}); - -// node_modules/@cashu/crypto/modules/esm/common/index.js -var require_common = __commonJS({ - "node_modules/@cashu/crypto/modules/esm/common/index.js"(exports) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.deriveKeysetId = exports.deserializeMintKeys = exports.serializeMintKeys = exports.createRandomPrivateKey = exports.getKeysetIdInt = exports.pointFromHex = exports.hashToCurve = void 0; - var secp256k1_1 = require_secp256k1(); - var sha256_1 = require_sha256(); - var utils_1 = require_utils3(); - var utils_js_1 = require_utils4(); - var buffer_1 = require_buffer(); - var DOMAIN_SEPARATOR = (0, utils_1.hexToBytes)("536563703235366b315f48617368546f43757276655f43617368755f"); - function hashToCurve2(secret) { - const msgToHash = (0, sha256_1.sha256)(buffer_1.Buffer.concat([DOMAIN_SEPARATOR, secret])); - const counter = new Uint32Array(1); - const maxIterations = 2 ** 16; - for (let i = 0; i < maxIterations; i++) { - const counterBytes = new Uint8Array(counter.buffer); - const hash = (0, sha256_1.sha256)(buffer_1.Buffer.concat([msgToHash, counterBytes])); - try { - return pointFromHex2((0, utils_1.bytesToHex)(buffer_1.Buffer.concat([new Uint8Array([2]), hash]))); - } catch (error) { - counter[0]++; - } - } - throw new Error("No valid point found"); - } - exports.hashToCurve = hashToCurve2; - function pointFromHex2(hex) { - return secp256k1_1.secp256k1.ProjectivePoint.fromHex(hex); - } - exports.pointFromHex = pointFromHex2; - var getKeysetIdInt = (keysetId) => { - let keysetIdInt; - if (/^[a-fA-F0-9]+$/.test(keysetId)) { - keysetIdInt = (0, utils_js_1.hexToNumber)(keysetId) % BigInt(2 ** 31 - 1); - } else { - keysetIdInt = (0, utils_js_1.bytesToNumber)((0, utils_js_1.encodeBase64toUint8)(keysetId)) % BigInt(2 ** 31 - 1); - } - return keysetIdInt; - }; - exports.getKeysetIdInt = getKeysetIdInt; - function createRandomPrivateKey() { - return secp256k1_1.secp256k1.utils.randomPrivateKey(); - } - exports.createRandomPrivateKey = createRandomPrivateKey; - function serializeMintKeys(mintKeys) { - const serializedMintKeys = {}; - Object.keys(mintKeys).forEach((p) => { - serializedMintKeys[p] = (0, utils_1.bytesToHex)(mintKeys[p]); - }); - return serializedMintKeys; - } - exports.serializeMintKeys = serializeMintKeys; - function deserializeMintKeys(serializedMintKeys) { - const mintKeys = {}; - Object.keys(serializedMintKeys).forEach((p) => { - mintKeys[p] = (0, utils_1.hexToBytes)(serializedMintKeys[p]); - }); - return mintKeys; - } - exports.deserializeMintKeys = deserializeMintKeys; - function deriveKeysetId2(keys) { - const KEYSET_VERSION = "00"; - const mapBigInt = (k) => { - return [BigInt(k[0]), k[1]]; - }; - const pubkeysConcat = Object.entries(serializeMintKeys(keys)).map(mapBigInt).sort((a, b) => a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : 0).map(([, pubKey]) => (0, utils_1.hexToBytes)(pubKey)).reduce((prev, curr) => mergeUInt8Arrays(prev, curr), new Uint8Array()); - const hash = (0, sha256_1.sha256)(pubkeysConcat); - const hashHex = buffer_1.Buffer.from(hash).toString("hex").slice(0, 14); - return "00" + hashHex; - } - exports.deriveKeysetId = deriveKeysetId2; - function mergeUInt8Arrays(a1, a2) { - const mergedArray = new Uint8Array(a1.length + a2.length); - mergedArray.set(a1); - mergedArray.set(a2, a1.length); - return mergedArray; - } - } -}); - -// node_modules/@cashu/crypto/modules/esm/client/index.js -var require_client = __commonJS({ - "node_modules/@cashu/crypto/modules/esm/client/index.js"(exports) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.serializeBlindedMessage = exports.deserializeProof = exports.serializeProof = exports.constructProofFromPromise = exports.unblindSignature = exports.blindMessage = exports.createRandomBlindedMessage = void 0; - var secp256k1_1 = require_secp256k1(); - var utils_1 = require_utils(); - var utils_js_1 = require_utils4(); - var index_js_1 = require_common(); - function createRandomBlindedMessage() { - return blindMessage2((0, utils_1.randomBytes)(32)); - } - exports.createRandomBlindedMessage = createRandomBlindedMessage; - function blindMessage2(secret, r) { - const Y = (0, index_js_1.hashToCurve)(secret); - if (!r) { - r = (0, utils_js_1.bytesToNumber)(secp256k1_1.secp256k1.utils.randomPrivateKey()); - } - const rG = secp256k1_1.secp256k1.ProjectivePoint.BASE.multiply(r); - const B_ = Y.add(rG); - return { B_, r, secret }; - } - exports.blindMessage = blindMessage2; - function unblindSignature(C_, r, A) { - const C = C_.subtract(A.multiply(r)); - return C; - } - exports.unblindSignature = unblindSignature; - function constructProofFromPromise2(promise, r, secret, key) { - const A = key; - const C = unblindSignature(promise.C_, r, A); - const proof = { - id: promise.id, - amount: promise.amount, - secret, - C - }; - return proof; - } - exports.constructProofFromPromise = constructProofFromPromise2; - var serializeProof2 = (proof) => { - return { - amount: proof.amount, - C: proof.C.toHex(true), - id: proof.id, - secret: new TextDecoder().decode(proof.secret), - witness: JSON.stringify(proof.witness) - }; - }; - exports.serializeProof = serializeProof2; - var deserializeProof = (proof) => { - return { - amount: proof.amount, - C: (0, index_js_1.pointFromHex)(proof.C), - id: proof.id, - secret: new TextEncoder().encode(proof.secret), - witness: proof.witness ? JSON.parse(proof.witness) : void 0 - }; - }; - exports.deserializeProof = deserializeProof; - var serializeBlindedMessage = (bm, amount) => { - return { - B_: bm.B_.toHex(true), - amount - }; - }; - exports.serializeBlindedMessage = serializeBlindedMessage; - } -}); - -// node_modules/@noble/hashes/legacy.js -var require_legacy = __commonJS({ - "node_modules/@noble/hashes/legacy.js"(exports) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.ripemd160 = exports.RIPEMD160 = exports.md5 = exports.MD5 = exports.sha1 = exports.SHA1 = void 0; - var _md_ts_1 = require_md(); - var utils_ts_1 = require_utils(); - var SHA1_IV = Uint32Array.from([ - 1732584193, - 4023233417, - 2562383102, - 271733878, - 3285377520 - ]); - var SHA1_W = new Uint32Array(80); - var SHA1 = class extends _md_ts_1.HashMD { - constructor() { - super(64, 20, 8, false); - this.A = SHA1_IV[0] | 0; - this.B = SHA1_IV[1] | 0; - this.C = SHA1_IV[2] | 0; - this.D = SHA1_IV[3] | 0; - this.E = SHA1_IV[4] | 0; - } - get() { - const { A, B, C, D, E } = this; - return [A, B, C, D, E]; - } - set(A, B, C, D, E) { - this.A = A | 0; - this.B = B | 0; - this.C = C | 0; - this.D = D | 0; - this.E = E | 0; - } - process(view, offset) { - for (let i = 0; i < 16; i++, offset += 4) - SHA1_W[i] = view.getUint32(offset, false); - for (let i = 16; i < 80; i++) - SHA1_W[i] = (0, utils_ts_1.rotl)(SHA1_W[i - 3] ^ SHA1_W[i - 8] ^ SHA1_W[i - 14] ^ SHA1_W[i - 16], 1); - let { A, B, C, D, E } = this; - for (let i = 0; i < 80; i++) { - let F, K2; - if (i < 20) { - F = (0, _md_ts_1.Chi)(B, C, D); - K2 = 1518500249; - } else if (i < 40) { - F = B ^ C ^ D; - K2 = 1859775393; - } else if (i < 60) { - F = (0, _md_ts_1.Maj)(B, C, D); - K2 = 2400959708; - } else { - F = B ^ C ^ D; - K2 = 3395469782; - } - const T = (0, utils_ts_1.rotl)(A, 5) + F + E + K2 + SHA1_W[i] | 0; - E = D; - D = C; - C = (0, utils_ts_1.rotl)(B, 30); - B = A; - A = T; - } - 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; - this.set(A, B, C, D, E); - } - roundClean() { - (0, utils_ts_1.clean)(SHA1_W); - } - destroy() { - this.set(0, 0, 0, 0, 0); - (0, utils_ts_1.clean)(this.buffer); - } - }; - exports.SHA1 = SHA1; - exports.sha1 = (0, utils_ts_1.createHasher)(() => new SHA1()); - var p32 = Math.pow(2, 32); - var K = Array.from({ length: 64 }, (_, i) => Math.floor(p32 * Math.abs(Math.sin(i + 1)))); - var MD5_IV = SHA1_IV.slice(0, 4); - var MD5_W = new Uint32Array(16); - var MD5 = class extends _md_ts_1.HashMD { - constructor() { - super(64, 16, 8, true); - this.A = MD5_IV[0] | 0; - this.B = MD5_IV[1] | 0; - this.C = MD5_IV[2] | 0; - this.D = MD5_IV[3] | 0; - } - get() { - const { A, B, C, D } = this; - return [A, B, C, D]; - } - set(A, B, C, D) { - this.A = A | 0; - this.B = B | 0; - this.C = C | 0; - this.D = D | 0; - } - process(view, offset) { - for (let i = 0; i < 16; i++, offset += 4) - MD5_W[i] = view.getUint32(offset, true); - let { A, B, C, D } = this; - for (let i = 0; i < 64; i++) { - let F, g, s; - if (i < 16) { - F = (0, _md_ts_1.Chi)(B, C, D); - g = i; - s = [7, 12, 17, 22]; - } else if (i < 32) { - F = (0, _md_ts_1.Chi)(D, B, C); - g = (5 * i + 1) % 16; - s = [5, 9, 14, 20]; - } else if (i < 48) { - F = B ^ C ^ D; - g = (3 * i + 5) % 16; - s = [4, 11, 16, 23]; - } else { - F = C ^ (B | ~D); - g = 7 * i % 16; - s = [6, 10, 15, 21]; - } - F = F + A + K[i] + MD5_W[g]; - A = D; - D = C; - C = B; - B = B + (0, utils_ts_1.rotl)(F, s[i % 4]); - } - A = A + this.A | 0; - B = B + this.B | 0; - C = C + this.C | 0; - D = D + this.D | 0; - this.set(A, B, C, D); - } - roundClean() { - (0, utils_ts_1.clean)(MD5_W); - } - destroy() { - this.set(0, 0, 0, 0); - (0, utils_ts_1.clean)(this.buffer); - } - }; - exports.MD5 = MD5; - exports.md5 = (0, utils_ts_1.createHasher)(() => new MD5()); - var Rho160 = Uint8Array.from([ - 7, - 4, - 13, - 1, - 10, - 6, - 15, - 3, - 12, - 0, - 9, - 5, - 2, - 14, - 11, - 8 - ]); - var Id160 = (() => Uint8Array.from(new Array(16).fill(0).map((_, i) => i)))(); - var Pi160 = (() => Id160.map((i) => (9 * i + 5) % 16))(); - var idxLR = (() => { - const L = [Id160]; - const R = [Pi160]; - const res = [L, R]; - for (let i = 0; i < 4; i++) - for (let j of res) - j.push(j[i].map((k) => Rho160[k])); - return res; - })(); - var idxL = (() => idxLR[0])(); - var idxR = (() => idxLR[1])(); - var shifts160 = [ - [11, 14, 15, 12, 5, 8, 7, 9, 11, 13, 14, 15, 6, 7, 9, 8], - [12, 13, 11, 15, 6, 9, 9, 7, 12, 15, 11, 13, 7, 8, 7, 7], - [13, 15, 14, 11, 7, 7, 6, 8, 13, 14, 13, 12, 5, 5, 6, 9], - [14, 11, 12, 14, 8, 6, 5, 5, 15, 12, 15, 14, 9, 9, 8, 6], - [15, 12, 13, 13, 9, 5, 8, 6, 14, 11, 12, 11, 8, 6, 5, 5] - ].map((i) => Uint8Array.from(i)); - var shiftsL160 = idxL.map((idx, i) => idx.map((j) => shifts160[i][j])); - var shiftsR160 = idxR.map((idx, i) => idx.map((j) => shifts160[i][j])); - var Kl160 = Uint32Array.from([ - 0, - 1518500249, - 1859775393, - 2400959708, - 2840853838 - ]); - var Kr160 = Uint32Array.from([ - 1352829926, - 1548603684, - 1836072691, - 2053994217, - 0 - ]); - function ripemd_f(group, x, y, z) { - if (group === 0) - return x ^ y ^ z; - if (group === 1) - return x & y | ~x & z; - if (group === 2) - return (x | ~y) ^ z; - if (group === 3) - return x & z | y & ~z; - return x ^ (y | ~z); - } - var BUF_160 = new Uint32Array(16); - var RIPEMD160 = class extends _md_ts_1.HashMD { - constructor() { - super(64, 20, 8, true); - this.h0 = 1732584193 | 0; - this.h1 = 4023233417 | 0; - this.h2 = 2562383102 | 0; - this.h3 = 271733878 | 0; - this.h4 = 3285377520 | 0; - } - get() { - const { h0, h1, h2, h3, h4 } = this; - return [h0, h1, h2, h3, h4]; - } - set(h0, h1, h2, h3, h4) { - this.h0 = h0 | 0; - this.h1 = h1 | 0; - this.h2 = h2 | 0; - this.h3 = h3 | 0; - this.h4 = h4 | 0; - } - process(view, offset) { - for (let i = 0; i < 16; i++, offset += 4) - BUF_160[i] = view.getUint32(offset, true); - let al = this.h0 | 0, ar = al, bl = this.h1 | 0, br = bl, cl = this.h2 | 0, cr = cl, dl = this.h3 | 0, dr = dl, el = this.h4 | 0, er = el; - for (let group = 0; group < 5; group++) { - const rGroup = 4 - group; - const hbl = Kl160[group], hbr = Kr160[group]; - const rl = idxL[group], rr = idxR[group]; - const sl = shiftsL160[group], sr = shiftsR160[group]; - for (let i = 0; i < 16; i++) { - const tl = (0, utils_ts_1.rotl)(al + ripemd_f(group, bl, cl, dl) + BUF_160[rl[i]] + hbl, sl[i]) + el | 0; - al = el, el = dl, dl = (0, utils_ts_1.rotl)(cl, 10) | 0, cl = bl, bl = tl; - } - for (let i = 0; i < 16; i++) { - const tr = (0, utils_ts_1.rotl)(ar + ripemd_f(rGroup, br, cr, dr) + BUF_160[rr[i]] + hbr, sr[i]) + er | 0; - ar = er, er = dr, dr = (0, utils_ts_1.rotl)(cr, 10) | 0, cr = br, br = tr; - } - } - this.set(this.h1 + cl + dr | 0, this.h2 + dl + er | 0, this.h3 + el + ar | 0, this.h4 + al + br | 0, this.h0 + bl + cr | 0); - } - roundClean() { - (0, utils_ts_1.clean)(BUF_160); - } - destroy() { - this.destroyed = true; - (0, utils_ts_1.clean)(this.buffer); - this.set(0, 0, 0, 0, 0); - } - }; - exports.RIPEMD160 = RIPEMD160; - exports.ripemd160 = (0, utils_ts_1.createHasher)(() => new RIPEMD160()); - } -}); - -// node_modules/@scure/base/lib/index.js -var require_lib = __commonJS({ - "node_modules/@scure/base/lib/index.js"(exports) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.bytes = exports.stringToBytes = exports.str = exports.bytesToString = exports.hex = exports.utf8 = exports.bech32m = exports.bech32 = exports.base58check = exports.createBase58check = exports.base58xmr = exports.base58xrp = exports.base58flickr = exports.base58 = exports.base64urlnopad = exports.base64url = exports.base64nopad = exports.base64 = exports.base32crockford = exports.base32hexnopad = exports.base32hex = exports.base32nopad = exports.base32 = exports.base16 = exports.utils = void 0; - function isBytes2(a) { - return a instanceof Uint8Array || ArrayBuffer.isView(a) && a.constructor.name === "Uint8Array"; - } - function abytes2(b, ...lengths) { - if (!isBytes2(b)) - throw new Error("Uint8Array expected"); - if (lengths.length > 0 && !lengths.includes(b.length)) - throw new Error("Uint8Array expected of length " + lengths + ", got length=" + b.length); - } - function isArrayOf(isString, arr) { - if (!Array.isArray(arr)) - return false; - if (arr.length === 0) - return true; - if (isString) { - return arr.every((item) => typeof item === "string"); - } else { - return arr.every((item) => Number.isSafeInteger(item)); - } - } - function afn(input) { - if (typeof input !== "function") - throw new Error("function expected"); - return true; - } - function astr(label, input) { - if (typeof input !== "string") - throw new Error(`${label}: string expected`); - return true; - } - function anumber2(n) { - if (!Number.isSafeInteger(n)) - throw new Error(`invalid integer: ${n}`); - } - function aArr(input) { - if (!Array.isArray(input)) - throw new Error("array expected"); - } - function astrArr(label, input) { - if (!isArrayOf(true, input)) - throw new Error(`${label}: array of strings expected`); - } - function anumArr(label, input) { - if (!isArrayOf(false, input)) - throw new Error(`${label}: array of numbers expected`); - } - function chain(...args) { - const id = (a) => a; - const wrap2 = (a, b) => (c) => a(b(c)); - const encode = args.map((x) => x.encode).reduceRight(wrap2, id); - const decode2 = args.map((x) => x.decode).reduce(wrap2, id); - return { encode, decode: decode2 }; - } - function alphabet(letters) { - const lettersA = typeof letters === "string" ? letters.split("") : letters; - const len = lettersA.length; - astrArr("alphabet", lettersA); - const indexes = new Map(lettersA.map((l, i) => [l, i])); - return { - encode: (digits) => { - aArr(digits); - return digits.map((i) => { - if (!Number.isSafeInteger(i) || i < 0 || i >= len) - throw new Error(`alphabet.encode: digit index outside alphabet "${i}". Allowed: ${letters}`); - return lettersA[i]; - }); - }, - decode: (input) => { - aArr(input); - return input.map((letter) => { - astr("alphabet.decode", letter); - const i = indexes.get(letter); - if (i === void 0) - throw new Error(`Unknown letter: "${letter}". Allowed: ${letters}`); - return i; - }); - } - }; - } - function join2(separator = "") { - astr("join", separator); - return { - encode: (from) => { - astrArr("join.decode", from); - return from.join(separator); - }, - decode: (to) => { - astr("join.decode", to); - return to.split(separator); - } - }; - } - function padding(bits, chr = "=") { - anumber2(bits); - astr("padding", chr); - return { - encode(data) { - astrArr("padding.encode", data); - while (data.length * bits % 8) - data.push(chr); - return data; - }, - decode(input) { - astrArr("padding.decode", input); - let end = input.length; - if (end * bits % 8) - throw new Error("padding: invalid, string should have whole number of bytes"); - for (; end > 0 && input[end - 1] === chr; end--) { - const last = end - 1; - const byte = last * bits; - if (byte % 8 === 0) - throw new Error("padding: invalid, string has too much padding"); - } - return input.slice(0, end); - } - }; - } - function normalize2(fn) { - afn(fn); - return { encode: (from) => from, decode: (to) => fn(to) }; - } - function convertRadix(data, from, to) { - if (from < 2) - throw new Error(`convertRadix: invalid from=${from}, base cannot be less than 2`); - if (to < 2) - throw new Error(`convertRadix: invalid to=${to}, base cannot be less than 2`); - aArr(data); - if (!data.length) - return []; - let pos = 0; - const res = []; - const digits = Array.from(data, (d) => { - anumber2(d); - if (d < 0 || d >= from) - throw new Error(`invalid integer: ${d}`); - return d; - }); - const dlen = digits.length; - while (true) { - let carry = 0; - let done = true; - for (let i = pos; i < dlen; i++) { - const digit = digits[i]; - const fromCarry = from * carry; - const digitBase = fromCarry + digit; - if (!Number.isSafeInteger(digitBase) || fromCarry / from !== carry || digitBase - digit !== fromCarry) { - throw new Error("convertRadix: carry overflow"); - } - const div = digitBase / to; - carry = digitBase % to; - const rounded = Math.floor(div); - digits[i] = rounded; - if (!Number.isSafeInteger(rounded) || rounded * to + carry !== digitBase) - throw new Error("convertRadix: carry overflow"); - if (!done) - continue; - else if (!rounded) - pos = i; - else - done = false; - } - res.push(carry); - if (done) - break; - } - for (let i = 0; i < data.length - 1 && data[i] === 0; i++) - res.push(0); - return res.reverse(); - } - var gcd = (a, b) => b === 0 ? a : gcd(b, a % b); - var radix2carry = (from, to) => from + (to - gcd(from, to)); - var powers = (() => { - let res = []; - for (let i = 0; i < 40; i++) - res.push(2 ** i); - return res; - })(); - function convertRadix2(data, from, to, padding2) { - aArr(data); - 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 max = powers[from]; - const mask = powers[to] - 1; - const res = []; - for (const n of data) { - anumber2(n); - if (n >= max) - 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); - const pow = powers[pos]; - if (pow === void 0) - throw new Error("invalid carry"); - carry &= pow - 1; - } - carry = carry << to - pos & mask; - if (!padding2 && pos >= from) - throw new Error("Excess padding"); - if (!padding2 && carry > 0) - throw new Error(`Non-zero padding: ${carry}`); - if (padding2 && pos > 0) - res.push(carry >>> 0); - return res; - } - function radix(num) { - anumber2(num); - const _256 = 2 ** 8; - return { - encode: (bytes) => { - if (!isBytes2(bytes)) - throw new Error("radix.encode input should be Uint8Array"); - return convertRadix(Array.from(bytes), _256, num); - }, - decode: (digits) => { - anumArr("radix.decode", digits); - return Uint8Array.from(convertRadix(digits, num, _256)); - } - }; - } - function radix2(bits, revPadding = false) { - anumber2(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: (bytes) => { - if (!isBytes2(bytes)) - throw new Error("radix2.encode input should be Uint8Array"); - return convertRadix2(Array.from(bytes), 8, bits, !revPadding); - }, - decode: (digits) => { - anumArr("radix2.decode", digits); - return Uint8Array.from(convertRadix2(digits, bits, 8, revPadding)); - } - }; - } - function unsafeWrapper(fn) { - afn(fn); - return function(...args) { - try { - return fn.apply(null, args); - } catch (e) { - } - }; - } - function checksum(len, fn) { - anumber2(len); - afn(fn); - return { - encode(data) { - if (!isBytes2(data)) - throw new Error("checksum.encode: input should be Uint8Array"); - const sum = fn(data).slice(0, len); - const res = new Uint8Array(data.length + len); - res.set(data); - res.set(sum, data.length); - return res; - }, - decode(data) { - if (!isBytes2(data)) - throw new Error("checksum.decode: input should be Uint8Array"); - const payload = data.slice(0, -len); - const oldChecksum = data.slice(-len); - const newChecksum = fn(payload).slice(0, len); - for (let i = 0; i < len; i++) - if (newChecksum[i] !== oldChecksum[i]) - throw new Error("Invalid checksum"); - return payload; - } - }; - } - exports.utils = { - alphabet, - chain, - checksum, - convertRadix, - convertRadix2, - radix, - radix2, - join: join2, - padding - }; - exports.base16 = chain(radix2(4), alphabet("0123456789ABCDEF"), join2("")); - exports.base32 = chain(radix2(5), alphabet("ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"), padding(5), join2("")); - exports.base32nopad = chain(radix2(5), alphabet("ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"), join2("")); - exports.base32hex = chain(radix2(5), alphabet("0123456789ABCDEFGHIJKLMNOPQRSTUV"), padding(5), join2("")); - exports.base32hexnopad = chain(radix2(5), alphabet("0123456789ABCDEFGHIJKLMNOPQRSTUV"), join2("")); - exports.base32crockford = chain(radix2(5), alphabet("0123456789ABCDEFGHJKMNPQRSTVWXYZ"), join2(""), normalize2((s) => s.toUpperCase().replace(/O/g, "0").replace(/[IL]/g, "1"))); - var hasBase64Builtin = (() => typeof Uint8Array.from([]).toBase64 === "function" && typeof Uint8Array.fromBase64 === "function")(); - var decodeBase64Builtin = (s, isUrl2) => { - astr("base64", s); - const re = isUrl2 ? /^[A-Za-z0-9=_-]+$/ : /^[A-Za-z0-9=+/]+$/; - const alphabet2 = isUrl2 ? "base64url" : "base64"; - if (s.length > 0 && !re.test(s)) - throw new Error("invalid base64"); - return Uint8Array.fromBase64(s, { alphabet: alphabet2, lastChunkHandling: "strict" }); - }; - exports.base64 = hasBase64Builtin ? { - encode(b) { - abytes2(b); - return b.toBase64(); - }, - decode(s) { - return decodeBase64Builtin(s, false); - } - } : chain(radix2(6), alphabet("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"), padding(6), join2("")); - exports.base64nopad = chain(radix2(6), alphabet("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"), join2("")); - exports.base64url = hasBase64Builtin ? { - encode(b) { - abytes2(b); - return b.toBase64({ alphabet: "base64url" }); - }, - decode(s) { - return decodeBase64Builtin(s, true); - } - } : chain(radix2(6), alphabet("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"), padding(6), join2("")); - exports.base64urlnopad = chain(radix2(6), alphabet("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"), join2("")); - var genBase58 = (abc) => chain(radix(58), alphabet(abc), join2("")); - exports.base58 = genBase58("123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"); - exports.base58flickr = genBase58("123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"); - exports.base58xrp = genBase58("rpshnaf39wBUDNEGHJKLM4PQRST7VWXYZ2bcdeCg65jkm8oFqi1tuvAxyz"); - var XMR_BLOCK_LEN = [0, 2, 3, 5, 6, 7, 9, 10, 11]; - exports.base58xmr = { - encode(data) { - let res = ""; - for (let i = 0; i < data.length; i += 8) { - const block = data.subarray(i, i + 8); - res += exports.base58.encode(block).padStart(XMR_BLOCK_LEN[block.length], "1"); - } - return res; - }, - decode(str) { - let res = []; - for (let i = 0; i < str.length; i += 11) { - const slice = str.slice(i, i + 11); - const blockLen = XMR_BLOCK_LEN.indexOf(slice.length); - const block = exports.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 createBase58check = (sha2563) => chain(checksum(4, (data) => sha2563(sha2563(data))), exports.base58); - exports.createBase58check = createBase58check; - exports.base58check = exports.createBase58check; - var BECH_ALPHABET = chain(alphabet("qpzry9x8gf2tvdw0s3jn54khce6mua7l"), join2("")); - var POLYMOD_GENERATORS = [996825010, 642813549, 513874426, 1027748829, 705979059]; - function bech32Polymod(pre) { - const b = pre >> 25; - let chk = (pre & 33554431) << 5; - for (let i = 0; i < POLYMOD_GENERATORS.length; i++) { - if ((b >> i & 1) === 1) - chk ^= POLYMOD_GENERATORS[i]; - } - return chk; - } - function bechChecksum(prefix, words, encodingConst = 1) { - const len = prefix.length; - let chk = 1; - for (let i = 0; i < len; i++) { - const c = prefix.charCodeAt(i); - if (c < 33 || c > 126) - throw new Error(`Invalid prefix (${prefix})`); - chk = bech32Polymod(chk) ^ c >> 5; - } - chk = bech32Polymod(chk); - for (let i = 0; i < len; i++) - chk = bech32Polymod(chk) ^ prefix.charCodeAt(i) & 31; - for (let v of words) - chk = bech32Polymod(chk) ^ v; - for (let i = 0; i < 6; i++) - chk = bech32Polymod(chk); - chk ^= encodingConst; - return BECH_ALPHABET.encode(convertRadix2([chk % powers[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) { - astr("bech32.encode prefix", prefix); - if (isBytes2(words)) - words = Array.from(words); - anumArr("bech32.encode", words); - const plen = prefix.length; - if (plen === 0) - throw new TypeError(`Invalid prefix length ${plen}`); - const actualLength = plen + 7 + words.length; - if (limit !== false && actualLength > limit) - throw new TypeError(`Length ${actualLength} exceeds limit ${limit}`); - const lowered = prefix.toLowerCase(); - const sum = bechChecksum(lowered, words, ENCODING_CONST); - return `${lowered}1${BECH_ALPHABET.encode(words)}${sum}`; - } - function decode2(str, limit = 90) { - astr("bech32.decode input", str); - const slen = str.length; - if (slen < 8 || limit !== false && slen > limit) - throw new TypeError(`invalid string length: ${slen} (${str}). Expected (8..${limit})`); - const lowered = str.toLowerCase(); - if (str !== lowered && str !== str.toUpperCase()) - throw new Error(`String must be lowercase or uppercase`); - const sepIndex = lowered.lastIndexOf("1"); - if (sepIndex === 0 || sepIndex === -1) - throw new Error(`Letter "1" must be present between prefix and data only`); - const prefix = lowered.slice(0, sepIndex); - const data = lowered.slice(sepIndex + 1); - if (data.length < 6) - throw new Error("Data must be at least 6 characters long"); - const words = BECH_ALPHABET.decode(data).slice(0, -6); - const sum = bechChecksum(prefix, words, ENCODING_CONST); - if (!data.endsWith(sum)) - throw new Error(`Invalid checksum in ${str}: expected "${sum}"`); - return { prefix, words }; - } - const decodeUnsafe = unsafeWrapper(decode2); - function decodeToBytes(str) { - const { prefix, words } = decode2(str, false); - return { prefix, words, bytes: fromWords(words) }; - } - function encodeFromBytes(prefix, bytes) { - return encode(prefix, toWords(bytes)); - } - return { - encode, - decode: decode2, - encodeFromBytes, - decodeToBytes, - decodeUnsafe, - fromWords, - fromWordsUnsafe, - toWords - }; - } - exports.bech32 = genBech32("bech32"); - exports.bech32m = genBech32("bech32m"); - exports.utf8 = { - encode: (data) => new TextDecoder().decode(data), - decode: (str) => new TextEncoder().encode(str) - }; - var hasHexBuiltin = (() => typeof Uint8Array.from([]).toHex === "function" && typeof Uint8Array.fromHex === "function")(); - var hexBuiltin = { - encode(data) { - abytes2(data); - return data.toHex(); - }, - decode(s) { - astr("hex", s); - return Uint8Array.fromHex(s); - } - }; - exports.hex = hasHexBuiltin ? hexBuiltin : chain(radix2(4), alphabet("0123456789abcdef"), join2(""), normalize2((s) => { - if (typeof s !== "string" || s.length % 2 !== 0) - throw new TypeError(`hex.decode: expected string, got ${typeof s} with length ${s.length}`); - return s.toLowerCase(); - })); - var CODERS = { - utf8: exports.utf8, - hex: exports.hex, - base16: exports.base16, - base32: exports.base32, - base64: exports.base64, - base64url: exports.base64url, - base58: exports.base58, - base58xmr: exports.base58xmr - }; - var coderTypeError = "Invalid encoding type. Available types: utf8, hex, base16, base32, base64, base64url, base58, base58xmr"; - var bytesToString = (type, bytes) => { - if (typeof type !== "string" || !CODERS.hasOwnProperty(type)) - throw new TypeError(coderTypeError); - if (!isBytes2(bytes)) - throw new TypeError("bytesToString() expects Uint8Array"); - return CODERS[type].encode(bytes); - }; - exports.bytesToString = bytesToString; - exports.str = exports.bytesToString; - var stringToBytes = (type, str) => { - if (!CODERS.hasOwnProperty(type)) - throw new TypeError(coderTypeError); - if (typeof str !== "string") - throw new TypeError("stringToBytes() expects string"); - return CODERS[type].decode(str); - }; - exports.stringToBytes = stringToBytes; - exports.bytes = exports.stringToBytes; - } -}); - -// node_modules/@scure/bip32/lib/index.js -var require_lib2 = __commonJS({ - "node_modules/@scure/bip32/lib/index.js"(exports) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.HDKey = exports.HARDENED_OFFSET = void 0; - var modular_1 = require_modular(); - var secp256k1_1 = require_secp256k1(); - var hmac_1 = require_hmac(); - var legacy_1 = require_legacy(); - var sha2_1 = require_sha2(); - var utils_1 = require_utils(); - var base_1 = require_lib(); - var Point = secp256k1_1.secp256k1.ProjectivePoint; - var base58check = (0, base_1.createBase58check)(sha2_1.sha256); - function bytesToNumber2(bytes) { - (0, utils_1.abytes)(bytes); - const h = bytes.length === 0 ? "0" : (0, utils_1.bytesToHex)(bytes); - return BigInt("0x" + h); - } - function numberToBytes(num) { - if (typeof num !== "bigint") - throw new Error("bigint expected"); - return (0, utils_1.hexToBytes)(num.toString(16).padStart(64, "0")); - } - var MASTER_SECRET = (0, utils_1.utf8ToBytes)("Bitcoin seed"); - var BITCOIN_VERSIONS = { private: 76066276, public: 76067358 }; - exports.HARDENED_OFFSET = 2147483648; - var hash160 = (data) => (0, legacy_1.ripemd160)((0, sha2_1.sha256)(data)); - var fromU32 = (data) => (0, utils_1.createView)(data).getUint32(0, false); - var toU32 = (n) => { - if (!Number.isSafeInteger(n) || n < 0 || n > 2 ** 32 - 1) { - throw new Error("invalid number, should be from 0 to 2**32-1, got " + n); - } - const buf = new Uint8Array(4); - (0, utils_1.createView)(buf).setUint32(0, n, false); - return buf; - }; - var HDKey = class _HDKey { - get fingerprint() { - if (!this.pubHash) { - throw new Error("No publicKey set!"); - } - return fromU32(this.pubHash); - } - get identifier() { - return this.pubHash; - } - get pubKeyHash() { - return this.pubHash; - } - get privateKey() { - return this.privKeyBytes || null; - } - get publicKey() { - return this.pubKey || null; - } - get privateExtendedKey() { - const priv = this.privateKey; - if (!priv) { - throw new Error("No private key"); - } - return base58check.encode(this.serialize(this.versions.private, (0, utils_1.concatBytes)(new Uint8Array([0]), priv))); - } - get publicExtendedKey() { - if (!this.pubKey) { - throw new Error("No public key"); - } - return base58check.encode(this.serialize(this.versions.public, this.pubKey)); - } - static fromMasterSeed(seed, versions = BITCOIN_VERSIONS) { - (0, utils_1.abytes)(seed); - if (8 * seed.length < 128 || 8 * seed.length > 512) { - throw new Error("HDKey: seed length must be between 128 and 512 bits; 256 bits is advised, got " + seed.length); - } - const I = (0, hmac_1.hmac)(sha2_1.sha512, MASTER_SECRET, seed); - return new _HDKey({ - versions, - chainCode: I.slice(32), - privateKey: I.slice(0, 32) - }); - } - static fromExtendedKey(base58key, versions = BITCOIN_VERSIONS) { - const keyBuffer = base58check.decode(base58key); - const keyView = (0, utils_1.createView)(keyBuffer); - const version = keyView.getUint32(0, false); - const opt = { - versions, - depth: keyBuffer[4], - parentFingerprint: keyView.getUint32(5, false), - index: keyView.getUint32(9, false), - chainCode: keyBuffer.slice(13, 45) - }; - const key = keyBuffer.slice(45); - const isPriv = key[0] === 0; - if (version !== versions[isPriv ? "private" : "public"]) { - throw new Error("Version mismatch"); - } - if (isPriv) { - return new _HDKey({ ...opt, privateKey: key.slice(1) }); - } else { - return new _HDKey({ ...opt, publicKey: key }); - } - } - static fromJSON(json) { - return _HDKey.fromExtendedKey(json.xpriv); - } - constructor(opt) { - this.depth = 0; - this.index = 0; - this.chainCode = null; - this.parentFingerprint = 0; - if (!opt || typeof opt !== "object") { - throw new Error("HDKey.constructor must not be called directly"); - } - this.versions = opt.versions || BITCOIN_VERSIONS; - this.depth = opt.depth || 0; - this.chainCode = opt.chainCode || null; - this.index = opt.index || 0; - this.parentFingerprint = opt.parentFingerprint || 0; - if (!this.depth) { - if (this.parentFingerprint || this.index) { - throw new Error("HDKey: zero depth with non-zero index/parent fingerprint"); - } - } - if (opt.publicKey && opt.privateKey) { - throw new Error("HDKey: publicKey and privateKey at same time."); - } - if (opt.privateKey) { - if (!secp256k1_1.secp256k1.utils.isValidPrivateKey(opt.privateKey)) { - throw new Error("Invalid private key"); - } - this.privKey = typeof opt.privateKey === "bigint" ? opt.privateKey : bytesToNumber2(opt.privateKey); - this.privKeyBytes = numberToBytes(this.privKey); - this.pubKey = secp256k1_1.secp256k1.getPublicKey(opt.privateKey, true); - } else if (opt.publicKey) { - this.pubKey = Point.fromHex(opt.publicKey).toRawBytes(true); - } else { - throw new Error("HDKey: no public or private key provided"); - } - this.pubHash = hash160(this.pubKey); - } - derive(path) { - if (!/^[mM]'?/.test(path)) { - throw new Error('Path must start with "m" or "M"'); - } - if (/^[mM]'?$/.test(path)) { - return this; - } - const parts = path.replace(/^[mM]'?\//, "").split("/"); - let child = this; - for (const c of parts) { - const m = /^(\d+)('?)$/.exec(c); - const m1 = m && m[1]; - if (!m || m.length !== 3 || typeof m1 !== "string") - throw new Error("invalid child index: " + c); - let idx = +m1; - if (!Number.isSafeInteger(idx) || idx >= exports.HARDENED_OFFSET) { - throw new Error("Invalid index"); - } - if (m[2] === "'") { - idx += exports.HARDENED_OFFSET; - } - child = child.deriveChild(idx); - } - return child; - } - deriveChild(index2) { - if (!this.pubKey || !this.chainCode) { - throw new Error("No publicKey or chainCode set"); - } - let data = toU32(index2); - if (index2 >= exports.HARDENED_OFFSET) { - const priv = this.privateKey; - if (!priv) { - throw new Error("Could not derive hardened child key"); - } - data = (0, utils_1.concatBytes)(new Uint8Array([0]), priv, data); - } else { - data = (0, utils_1.concatBytes)(this.pubKey, data); - } - const I = (0, hmac_1.hmac)(sha2_1.sha512, this.chainCode, data); - const childTweak = bytesToNumber2(I.slice(0, 32)); - const chainCode = I.slice(32); - if (!secp256k1_1.secp256k1.utils.isValidPrivateKey(childTweak)) { - throw new Error("Tweak bigger than curve order"); - } - const opt = { - versions: this.versions, - chainCode, - depth: this.depth + 1, - parentFingerprint: this.fingerprint, - index: index2 - }; - try { - if (this.privateKey) { - const added = (0, modular_1.mod)(this.privKey + childTweak, secp256k1_1.secp256k1.CURVE.n); - if (!secp256k1_1.secp256k1.utils.isValidPrivateKey(added)) { - throw new Error("The tweak was out of range or the resulted private key is invalid"); - } - opt.privateKey = added; - } else { - const added = Point.fromHex(this.pubKey).add(Point.fromPrivateKey(childTweak)); - if (added.equals(Point.ZERO)) { - throw new Error("The tweak was equal to negative P, which made the result key invalid"); - } - opt.publicKey = added.toRawBytes(true); - } - return new _HDKey(opt); - } catch (err) { - return this.deriveChild(index2 + 1); - } - } - sign(hash) { - if (!this.privateKey) { - throw new Error("No privateKey set!"); - } - (0, utils_1.abytes)(hash, 32); - return secp256k1_1.secp256k1.sign(hash, this.privKey).toCompactRawBytes(); - } - verify(hash, signature) { - (0, utils_1.abytes)(hash, 32); - (0, utils_1.abytes)(signature, 64); - if (!this.publicKey) { - throw new Error("No publicKey set!"); - } - let sig; - try { - sig = secp256k1_1.secp256k1.Signature.fromCompact(signature); - } catch (error) { - return false; - } - return secp256k1_1.secp256k1.verify(sig, hash, this.publicKey); - } - wipePrivateData() { - this.privKey = void 0; - if (this.privKeyBytes) { - this.privKeyBytes.fill(0); - this.privKeyBytes = void 0; - } - return this; - } - toJSON() { - return { - xpriv: this.privateExtendedKey, - xpub: this.publicExtendedKey - }; - } - serialize(version, key) { - if (!this.chainCode) { - throw new Error("No chainCode set"); - } - (0, utils_1.abytes)(key, 33); - return (0, utils_1.concatBytes)(toU32(version), new Uint8Array([this.depth]), toU32(this.parentFingerprint), toU32(this.index), this.chainCode, key); - } - }; - exports.HDKey = HDKey; - } -}); - -// node_modules/@noble/hashes/pbkdf2.js -var require_pbkdf2 = __commonJS({ - "node_modules/@noble/hashes/pbkdf2.js"(exports) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.pbkdf2 = pbkdf2; - exports.pbkdf2Async = pbkdf2Async; - var hmac_ts_1 = require_hmac(); - var utils_ts_1 = require_utils(); - function pbkdf2Init(hash, _password, _salt, _opts) { - (0, utils_ts_1.ahash)(hash); - const opts = (0, utils_ts_1.checkOpts)({ dkLen: 32, asyncTick: 10 }, _opts); - const { c, dkLen, asyncTick } = opts; - (0, utils_ts_1.anumber)(c); - (0, utils_ts_1.anumber)(dkLen); - (0, utils_ts_1.anumber)(asyncTick); - if (c < 1) - throw new Error("iterations (c) should be >= 1"); - const password = (0, utils_ts_1.kdfInputToBytes)(_password); - const salt = (0, utils_ts_1.kdfInputToBytes)(_salt); - const DK = new Uint8Array(dkLen); - const PRF = hmac_ts_1.hmac.create(hash, password); - const PRFSalt = PRF._cloneInto().update(salt); - return { c, dkLen, asyncTick, DK, PRF, PRFSalt }; - } - function pbkdf2Output(PRF, PRFSalt, DK, prfW, u) { - PRF.destroy(); - PRFSalt.destroy(); - if (prfW) - prfW.destroy(); - (0, utils_ts_1.clean)(u); - return DK; - } - function pbkdf2(hash, password, salt, opts) { - const { c, dkLen, DK, PRF, PRFSalt } = pbkdf2Init(hash, password, salt, opts); - let prfW; - const arr = new Uint8Array(4); - const view = (0, utils_ts_1.createView)(arr); - const u = new Uint8Array(PRF.outputLen); - for (let ti = 1, pos = 0; pos < dkLen; ti++, pos += PRF.outputLen) { - const Ti = DK.subarray(pos, pos + PRF.outputLen); - view.setInt32(0, ti, false); - (prfW = PRFSalt._cloneInto(prfW)).update(arr).digestInto(u); - Ti.set(u.subarray(0, Ti.length)); - for (let ui = 1; ui < c; ui++) { - PRF._cloneInto(prfW).update(u).digestInto(u); - for (let i = 0; i < Ti.length; i++) - Ti[i] ^= u[i]; - } - } - return pbkdf2Output(PRF, PRFSalt, DK, prfW, u); - } - async function pbkdf2Async(hash, password, salt, opts) { - const { c, dkLen, asyncTick, DK, PRF, PRFSalt } = pbkdf2Init(hash, password, salt, opts); - let prfW; - const arr = new Uint8Array(4); - const view = (0, utils_ts_1.createView)(arr); - const u = new Uint8Array(PRF.outputLen); - for (let ti = 1, pos = 0; pos < dkLen; ti++, pos += PRF.outputLen) { - const Ti = DK.subarray(pos, pos + PRF.outputLen); - view.setInt32(0, ti, false); - (prfW = PRFSalt._cloneInto(prfW)).update(arr).digestInto(u); - Ti.set(u.subarray(0, Ti.length)); - await (0, utils_ts_1.asyncLoop)(c - 1, asyncTick, () => { - PRF._cloneInto(prfW).update(u).digestInto(u); - for (let i = 0; i < Ti.length; i++) - Ti[i] ^= u[i]; - }); - } - return pbkdf2Output(PRF, PRFSalt, DK, prfW, u); - } - } -}); - -// node_modules/@scure/bip39/index.js -var require_bip39 = __commonJS({ - "node_modules/@scure/bip39/index.js"(exports) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.generateMnemonic = generateMnemonic; - exports.mnemonicToEntropy = mnemonicToEntropy; - exports.entropyToMnemonic = entropyToMnemonic; - exports.validateMnemonic = validateMnemonic; - exports.mnemonicToSeed = mnemonicToSeed; - exports.mnemonicToSeedSync = mnemonicToSeedSync; - var pbkdf2_1 = require_pbkdf2(); - var sha2_1 = require_sha2(); - var utils_1 = require_utils(); - var base_1 = require_lib(); - var isJapanese = (wordlist) => wordlist[0] === "あいこくしん"; - function nfkd(str) { - if (typeof str !== "string") - throw new TypeError("invalid mnemonic type: " + typeof str); - return str.normalize("NFKD"); - } - function normalize2(str) { - const norm = nfkd(str); - const words = norm.split(" "); - if (![12, 15, 18, 21, 24].includes(words.length)) - throw new Error("Invalid mnemonic"); - return { nfkd: norm, words }; - } - function aentropy(ent) { - (0, utils_1.abytes)(ent, 16, 20, 24, 28, 32); - } - function generateMnemonic(wordlist, strength = 128) { - (0, utils_1.anumber)(strength); - if (strength % 32 !== 0 || strength > 256) - throw new TypeError("Invalid entropy"); - return entropyToMnemonic((0, utils_1.randomBytes)(strength / 8), wordlist); - } - var calcChecksum = (entropy) => { - const bitsLeft = 8 - entropy.length / 4; - return new Uint8Array([(0, sha2_1.sha256)(entropy)[0] >> bitsLeft << bitsLeft]); - }; - function getCoder(wordlist) { - if (!Array.isArray(wordlist) || wordlist.length !== 2048 || typeof wordlist[0] !== "string") - throw new Error("Wordlist: expected array of 2048 strings"); - wordlist.forEach((i) => { - if (typeof i !== "string") - throw new Error("wordlist: non-string element: " + i); - }); - return base_1.utils.chain(base_1.utils.checksum(1, calcChecksum), base_1.utils.radix2(11, true), base_1.utils.alphabet(wordlist)); - } - function mnemonicToEntropy(mnemonic, wordlist) { - const { words } = normalize2(mnemonic); - const entropy = getCoder(wordlist).decode(words); - aentropy(entropy); - return entropy; - } - function entropyToMnemonic(entropy, wordlist) { - aentropy(entropy); - const words = getCoder(wordlist).encode(entropy); - return words.join(isJapanese(wordlist) ? " " : " "); - } - function validateMnemonic(mnemonic, wordlist) { - try { - mnemonicToEntropy(mnemonic, wordlist); - } catch (e) { - return false; - } - return true; - } - var psalt = (passphrase) => nfkd("mnemonic" + passphrase); - function mnemonicToSeed(mnemonic, passphrase = "") { - return (0, pbkdf2_1.pbkdf2Async)(sha2_1.sha512, normalize2(mnemonic).nfkd, psalt(passphrase), { c: 2048, dkLen: 64 }); - } - function mnemonicToSeedSync(mnemonic, passphrase = "") { - return (0, pbkdf2_1.pbkdf2)(sha2_1.sha512, normalize2(mnemonic).nfkd, psalt(passphrase), { c: 2048, dkLen: 64 }); - } - } -}); - -// node_modules/@scure/bip39/wordlists/english.js -var require_english = __commonJS({ - "node_modules/@scure/bip39/wordlists/english.js"(exports) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.wordlist = void 0; - exports.wordlist = `abandon -ability -able -about -above -absent -absorb -abstract -absurd -abuse -access -accident -account -accuse -achieve -acid -acoustic -acquire -across -act -action -actor -actress -actual -adapt -add -addict -address -adjust -admit -adult -advance -advice -aerobic -affair -afford -afraid -again -age -agent -agree -ahead -aim -air -airport -aisle -alarm -album -alcohol -alert -alien -all -alley -allow -almost -alone -alpha -already -also -alter -always -amateur -amazing -among -amount -amused -analyst -anchor -ancient -anger -angle -angry -animal -ankle -announce -annual -another -answer -antenna -antique -anxiety -any -apart -apology -appear -apple -approve -april -arch -arctic -area -arena -argue -arm -armed -armor -army -around -arrange -arrest -arrive -arrow -art -artefact -artist -artwork -ask -aspect -assault -asset -assist -assume -asthma -athlete -atom -attack -attend -attitude -attract -auction -audit -august -aunt -author -auto -autumn -average -avocado -avoid -awake -aware -away -awesome -awful -awkward -axis -baby -bachelor -bacon -badge -bag -balance -balcony -ball -bamboo -banana -banner -bar -barely -bargain -barrel -base -basic -basket -battle -beach -bean -beauty -because -become -beef -before -begin -behave -behind -believe -below -belt -bench -benefit -best -betray -better -between -beyond -bicycle -bid -bike -bind -biology -bird -birth -bitter -black -blade -blame -blanket -blast -bleak -bless -blind -blood -blossom -blouse -blue -blur -blush -board -boat -body -boil -bomb -bone -bonus -book -boost -border -boring -borrow -boss -bottom -bounce -box -boy -bracket -brain -brand -brass -brave -bread -breeze -brick -bridge -brief -bright -bring -brisk -broccoli -broken -bronze -broom -brother -brown -brush -bubble -buddy -budget -buffalo -build -bulb -bulk -bullet -bundle -bunker -burden -burger -burst -bus -business -busy -butter -buyer -buzz -cabbage -cabin -cable -cactus -cage -cake -call -calm -camera -camp -can -canal -cancel -candy -cannon -canoe -canvas -canyon -capable -capital -captain -car -carbon -card -cargo -carpet -carry -cart -case -cash -casino -castle -casual -cat -catalog -catch -category -cattle -caught -cause -caution -cave -ceiling -celery -cement -census -century -cereal -certain -chair -chalk -champion -change -chaos -chapter -charge -chase -chat -cheap -check -cheese -chef -cherry -chest -chicken -chief -child -chimney -choice -choose -chronic -chuckle -chunk -churn -cigar -cinnamon -circle -citizen -city -civil -claim -clap -clarify -claw -clay -clean -clerk -clever -click -client -cliff -climb -clinic -clip -clock -clog -close -cloth -cloud -clown -club -clump -cluster -clutch -coach -coast -coconut -code -coffee -coil -coin -collect -color -column -combine -come -comfort -comic -common -company -concert -conduct -confirm -congress -connect -consider -control -convince -cook -cool -copper -copy -coral -core -corn -correct -cost -cotton -couch -country -couple -course -cousin -cover -coyote -crack -cradle -craft -cram -crane -crash -crater -crawl -crazy -cream -credit -creek -crew -cricket -crime -crisp -critic -crop -cross -crouch -crowd -crucial -cruel -cruise -crumble -crunch -crush -cry -crystal -cube -culture -cup -cupboard -curious -current -curtain -curve -cushion -custom -cute -cycle -dad -damage -damp -dance -danger -daring -dash -daughter -dawn -day -deal -debate -debris -decade -december -decide -decline -decorate -decrease -deer -defense -define -defy -degree -delay -deliver -demand -demise -denial -dentist -deny -depart -depend -deposit -depth -deputy -derive -describe -desert -design -desk -despair -destroy -detail -detect -develop -device -devote -diagram -dial -diamond -diary -dice -diesel -diet -differ -digital -dignity -dilemma -dinner -dinosaur -direct -dirt -disagree -discover -disease -dish -dismiss -disorder -display -distance -divert -divide -divorce -dizzy -doctor -document -dog -doll -dolphin -domain -donate -donkey -donor -door -dose -double -dove -draft -dragon -drama -drastic -draw -dream -dress -drift -drill -drink -drip -drive -drop -drum -dry -duck -dumb -dune -during -dust -dutch -duty -dwarf -dynamic -eager -eagle -early -earn -earth -easily -east -easy -echo -ecology -economy -edge -edit -educate -effort -egg -eight -either -elbow -elder -electric -elegant -element -elephant -elevator -elite -else -embark -embody -embrace -emerge -emotion -employ -empower -empty -enable -enact -end -endless -endorse -enemy -energy -enforce -engage -engine -enhance -enjoy -enlist -enough -enrich -enroll -ensure -enter -entire -entry -envelope -episode -equal -equip -era -erase -erode -erosion -error -erupt -escape -essay -essence -estate -eternal -ethics -evidence -evil -evoke -evolve -exact -example -excess -exchange -excite -exclude -excuse -execute -exercise -exhaust -exhibit -exile -exist -exit -exotic -expand -expect -expire -explain -expose -express -extend -extra -eye -eyebrow -fabric -face -faculty -fade -faint -faith -fall -false -fame -family -famous -fan -fancy -fantasy -farm -fashion -fat -fatal -father -fatigue -fault -favorite -feature -february -federal -fee -feed -feel -female -fence -festival -fetch -fever -few -fiber -fiction -field -figure -file -film -filter -final -find -fine -finger -finish -fire -firm -first -fiscal -fish -fit -fitness -fix -flag -flame -flash -flat -flavor -flee -flight -flip -float -flock -floor -flower -fluid -flush -fly -foam -focus -fog -foil -fold -follow -food -foot -force -forest -forget -fork -fortune -forum -forward -fossil -foster -found -fox -fragile -frame -frequent -fresh -friend -fringe -frog -front -frost -frown -frozen -fruit -fuel -fun -funny -furnace -fury -future -gadget -gain -galaxy -gallery -game -gap -garage -garbage -garden -garlic -garment -gas -gasp -gate -gather -gauge -gaze -general -genius -genre -gentle -genuine -gesture -ghost -giant -gift -giggle -ginger -giraffe -girl -give -glad -glance -glare -glass -glide -glimpse -globe -gloom -glory -glove -glow -glue -goat -goddess -gold -good -goose -gorilla -gospel -gossip -govern -gown -grab -grace -grain -grant -grape -grass -gravity -great -green -grid -grief -grit -grocery -group -grow -grunt -guard -guess -guide -guilt -guitar -gun -gym -habit -hair -half -hammer -hamster -hand -happy -harbor -hard -harsh -harvest -hat -have -hawk -hazard -head -health -heart -heavy -hedgehog -height -hello -helmet -help -hen -hero -hidden -high -hill -hint -hip -hire -history -hobby -hockey -hold -hole -holiday -hollow -home -honey -hood -hope -horn -horror -horse -hospital -host -hotel -hour -hover -hub -huge -human -humble -humor -hundred -hungry -hunt -hurdle -hurry -hurt -husband -hybrid -ice -icon -idea -identify -idle -ignore -ill -illegal -illness -image -imitate -immense -immune -impact -impose -improve -impulse -inch -include -income -increase -index -indicate -indoor -industry -infant -inflict -inform -inhale -inherit -initial -inject -injury -inmate -inner -innocent -input -inquiry -insane -insect -inside -inspire -install -intact -interest -into -invest -invite -involve -iron -island -isolate -issue -item -ivory -jacket -jaguar -jar -jazz -jealous -jeans -jelly -jewel -job -join -joke -journey -joy -judge -juice -jump -jungle -junior -junk -just -kangaroo -keen -keep -ketchup -key -kick -kid -kidney -kind -kingdom -kiss -kit -kitchen -kite -kitten -kiwi -knee -knife -knock -know -lab -label -labor -ladder -lady -lake -lamp -language -laptop -large -later -latin -laugh -laundry -lava -law -lawn -lawsuit -layer -lazy -leader -leaf -learn -leave -lecture -left -leg -legal -legend -leisure -lemon -lend -length -lens -leopard -lesson -letter -level -liar -liberty -library -license -life -lift -light -like -limb -limit -link -lion -liquid -list -little -live -lizard -load -loan -lobster -local -lock -logic -lonely -long -loop -lottery -loud -lounge -love -loyal -lucky -luggage -lumber -lunar -lunch -luxury -lyrics -machine -mad -magic -magnet -maid -mail -main -major -make -mammal -man -manage -mandate -mango -mansion -manual -maple -marble -march -margin -marine -market -marriage -mask -mass -master -match -material -math -matrix -matter -maximum -maze -meadow -mean -measure -meat -mechanic -medal -media -melody -melt -member -memory -mention -menu -mercy -merge -merit -merry -mesh -message -metal -method -middle -midnight -milk -million -mimic -mind -minimum -minor -minute -miracle -mirror -misery -miss -mistake -mix -mixed -mixture -mobile -model -modify -mom -moment -monitor -monkey -monster -month -moon -moral -more -morning -mosquito -mother -motion -motor -mountain -mouse -move -movie -much -muffin -mule -multiply -muscle -museum -mushroom -music -must -mutual -myself -mystery -myth -naive -name -napkin -narrow -nasty -nation -nature -near -neck -need -negative -neglect -neither -nephew -nerve -nest -net -network -neutral -never -news -next -nice -night -noble -noise -nominee -noodle -normal -north -nose -notable -note -nothing -notice -novel -now -nuclear -number -nurse -nut -oak -obey -object -oblige -obscure -observe -obtain -obvious -occur -ocean -october -odor -off -offer -office -often -oil -okay -old -olive -olympic -omit -once -one -onion -online -only -open -opera -opinion -oppose -option -orange -orbit -orchard -order -ordinary -organ -orient -original -orphan -ostrich -other -outdoor -outer -output -outside -oval -oven -over -own -owner -oxygen -oyster -ozone -pact -paddle -page -pair -palace -palm -panda -panel -panic -panther -paper -parade -parent -park -parrot -party -pass -patch -path -patient -patrol -pattern -pause -pave -payment -peace -peanut -pear -peasant -pelican -pen -penalty -pencil -people -pepper -perfect -permit -person -pet -phone -photo -phrase -physical -piano -picnic -picture -piece -pig -pigeon -pill -pilot -pink -pioneer -pipe -pistol -pitch -pizza -place -planet -plastic -plate -play -please -pledge -pluck -plug -plunge -poem -poet -point -polar -pole -police -pond -pony -pool -popular -portion -position -possible -post -potato -pottery -poverty -powder -power -practice -praise -predict -prefer -prepare -present -pretty -prevent -price -pride -primary -print -priority -prison -private -prize -problem -process -produce -profit -program -project -promote -proof -property -prosper -protect -proud -provide -public -pudding -pull -pulp -pulse -pumpkin -punch -pupil -puppy -purchase -purity -purpose -purse -push -put -puzzle -pyramid -quality -quantum -quarter -question -quick -quit -quiz -quote -rabbit -raccoon -race -rack -radar -radio -rail -rain -raise -rally -ramp -ranch -random -range -rapid -rare -rate -rather -raven -raw -razor -ready -real -reason -rebel -rebuild -recall -receive -recipe -record -recycle -reduce -reflect -reform -refuse -region -regret -regular -reject -relax -release -relief -rely -remain -remember -remind -remove -render -renew -rent -reopen -repair -repeat -replace -report -require -rescue -resemble -resist -resource -response -result -retire -retreat -return -reunion -reveal -review -reward -rhythm -rib -ribbon -rice -rich -ride -ridge -rifle -right -rigid -ring -riot -ripple -risk -ritual -rival -river -road -roast -robot -robust -rocket -romance -roof -rookie -room -rose -rotate -rough -round -route -royal -rubber -rude -rug -rule -run -runway -rural -sad -saddle -sadness -safe -sail -salad -salmon -salon -salt -salute -same -sample -sand -satisfy -satoshi -sauce -sausage -save -say -scale -scan -scare -scatter -scene -scheme -school -science -scissors -scorpion -scout -scrap -screen -script -scrub -sea -search -season -seat -second -secret -section -security -seed -seek -segment -select -sell -seminar -senior -sense -sentence -series -service -session -settle -setup -seven -shadow -shaft -shallow -share -shed -shell -sheriff -shield -shift -shine -ship -shiver -shock -shoe -shoot -shop -short -shoulder -shove -shrimp -shrug -shuffle -shy -sibling -sick -side -siege -sight -sign -silent -silk -silly -silver -similar -simple -since -sing -siren -sister -situate -six -size -skate -sketch -ski -skill -skin -skirt -skull -slab -slam -sleep -slender -slice -slide -slight -slim -slogan -slot -slow -slush -small -smart -smile -smoke -smooth -snack -snake -snap -sniff -snow -soap -soccer -social -sock -soda -soft -solar -soldier -solid -solution -solve -someone -song -soon -sorry -sort -soul -sound -soup -source -south -space -spare -spatial -spawn -speak -special -speed -spell -spend -sphere -spice -spider -spike -spin -spirit -split -spoil -sponsor -spoon -sport -spot -spray -spread -spring -spy -square -squeeze -squirrel -stable -stadium -staff -stage -stairs -stamp -stand -start -state -stay -steak -steel -stem -step -stereo -stick -still -sting -stock -stomach -stone -stool -story -stove -strategy -street -strike -strong -struggle -student -stuff -stumble -style -subject -submit -subway -success -such -sudden -suffer -sugar -suggest -suit -summer -sun -sunny -sunset -super -supply -supreme -sure -surface -surge -surprise -surround -survey -suspect -sustain -swallow -swamp -swap -swarm -swear -sweet -swift -swim -swing -switch -sword -symbol -symptom -syrup -system -table -tackle -tag -tail -talent -talk -tank -tape -target -task -taste -tattoo -taxi -teach -team -tell -ten -tenant -tennis -tent -term -test -text -thank -that -theme -then -theory -there -they -thing -this -thought -three -thrive -throw -thumb -thunder -ticket -tide -tiger -tilt -timber -time -tiny -tip -tired -tissue -title -toast -tobacco -today -toddler -toe -together -toilet -token -tomato -tomorrow -tone -tongue -tonight -tool -tooth -top -topic -topple -torch -tornado -tortoise -toss -total -tourist -toward -tower -town -toy -track -trade -traffic -tragic -train -transfer -trap -trash -travel -tray -treat -tree -trend -trial -tribe -trick -trigger -trim -trip -trophy -trouble -truck -true -truly -trumpet -trust -truth -try -tube -tuition -tumble -tuna -tunnel -turkey -turn -turtle -twelve -twenty -twice -twin -twist -two -type -typical -ugly -umbrella -unable -unaware -uncle -uncover -under -undo -unfair -unfold -unhappy -uniform -unique -unit -universe -unknown -unlock -until -unusual -unveil -update -upgrade -uphold -upon -upper -upset -urban -urge -usage -use -used -useful -useless -usual -utility -vacant -vacuum -vague -valid -valley -valve -van -vanish -vapor -various -vast -vault -vehicle -velvet -vendor -venture -venue -verb -verify -version -very -vessel -veteran -viable -vibrant -vicious -victory -video -view -village -vintage -violin -virtual -virus -visa -visit -visual -vital -vivid -vocal -voice -void -volcano -volume -vote -voyage -wage -wagon -wait -walk -wall -walnut -want -warfare -warm -warrior -wash -wasp -waste -water -wave -way -wealth -weapon -wear -weasel -weather -web -wedding -weekend -weird -welcome -west -wet -whale -what -wheat -wheel -when -where -whip -whisper -wide -width -wife -wild -will -win -window -wine -wing -wink -winner -winter -wire -wisdom -wise -wish -witness -wolf -woman -wonder -wood -wool -word -work -world -worry -worth -wrap -wreck -wrestle -wrist -write -wrong -yard -year -yellow -you -young -youth -zebra -zero -zone -zoo`.split("\n"); - } -}); - -// node_modules/@cashu/crypto/modules/esm/client/NUT09.js -var require_NUT09 = __commonJS({ - "node_modules/@cashu/crypto/modules/esm/client/NUT09.js"(exports) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.deriveSeedFromMnemonic = exports.generateNewMnemonic = exports.deriveBlindingFactor = exports.deriveSecret = void 0; - var bip32_1 = require_lib2(); - var index_js_1 = require_common(); - var bip39_1 = require_bip39(); - var english_1 = require_english(); - var STANDARD_DERIVATION_PATH = `m/129372'/0'`; - var DerivationType; - (function(DerivationType2) { - DerivationType2[DerivationType2["SECRET"] = 0] = "SECRET"; - DerivationType2[DerivationType2["BLINDING_FACTOR"] = 1] = "BLINDING_FACTOR"; - })(DerivationType || (DerivationType = {})); - var deriveSecret2 = (seed, keysetId, counter) => { - return derive(seed, keysetId, counter, DerivationType.SECRET); - }; - exports.deriveSecret = deriveSecret2; - var deriveBlindingFactor2 = (seed, keysetId, counter) => { - return derive(seed, keysetId, counter, DerivationType.BLINDING_FACTOR); - }; - exports.deriveBlindingFactor = deriveBlindingFactor2; - var derive = (seed, keysetId, counter, secretOrBlinding) => { - const hdkey = bip32_1.HDKey.fromMasterSeed(seed); - const keysetIdInt = (0, index_js_1.getKeysetIdInt)(keysetId); - const derivationPath = `${STANDARD_DERIVATION_PATH}/${keysetIdInt}'/${counter}'/${secretOrBlinding}`; - const derived = hdkey.derive(derivationPath); - if (derived.privateKey === null) { - throw new Error("Could not derive private key"); - } - return derived.privateKey; - }; - var generateNewMnemonic = () => { - const mnemonic = (0, bip39_1.generateMnemonic)(english_1.wordlist, 128); - return mnemonic; - }; - exports.generateNewMnemonic = generateNewMnemonic; - var deriveSeedFromMnemonic = (mnemonic) => { - const seed = (0, bip39_1.mnemonicToSeedSync)(mnemonic); - return seed; - }; - exports.deriveSeedFromMnemonic = deriveSeedFromMnemonic; - } -}); - -// node_modules/@cashu/crypto/modules/esm/common/NUT11.js -var require_NUT11 = __commonJS({ - "node_modules/@cashu/crypto/modules/esm/common/NUT11.js"(exports) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.parseSecret = void 0; - var parseSecret = (secret) => { - try { - if (secret instanceof Uint8Array) { - secret = new TextDecoder().decode(secret); - } - return JSON.parse(secret); - } catch (e) { - throw new Error("can't parse secret"); - } - }; - exports.parseSecret = parseSecret; - } -}); - -// node_modules/@cashu/crypto/modules/esm/client/NUT11.js -var require_NUT112 = __commonJS({ - "node_modules/@cashu/crypto/modules/esm/client/NUT11.js"(exports) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.getSignedProof = exports.getSignedProofs = exports.signP2PKsecret = exports.createP2PKsecret = void 0; - var utils_1 = require_utils3(); - var sha256_1 = require_sha256(); - var secp256k1_1 = require_secp256k1(); - var utils_2 = require_utils(); - var NUT11_js_1 = require_NUT11(); - var createP2PKsecret2 = (pubkey) => { - const newSecret = [ - "P2PK", - { - nonce: (0, utils_1.bytesToHex)((0, utils_2.randomBytes)(32)), - data: pubkey - } - ]; - const parsed = JSON.stringify(newSecret); - return new TextEncoder().encode(parsed); - }; - exports.createP2PKsecret = createP2PKsecret2; - var signP2PKsecret = (secret, privateKey) => { - const msghash = (0, sha256_1.sha256)(new TextDecoder().decode(secret)); - const sig = secp256k1_1.schnorr.sign(msghash, privateKey); - return sig; - }; - exports.signP2PKsecret = signP2PKsecret; - var getSignedProofs2 = (proofs, privateKey) => { - return proofs.map((p) => { - try { - const parsed = (0, NUT11_js_1.parseSecret)(p.secret); - if (parsed[0] !== "P2PK") { - throw new Error("unknown secret type"); - } - return (0, exports.getSignedProof)(p, (0, utils_1.hexToBytes)(privateKey)); - } catch (error) { - return p; - } - }); - }; - exports.getSignedProofs = getSignedProofs2; - var getSignedProof = (proof, privateKey) => { - if (!proof.witness) { - proof.witness = { - signatures: [(0, utils_1.bytesToHex)((0, exports.signP2PKsecret)(proof.secret, privateKey))] - }; - } - return proof; - }; - exports.getSignedProof = getSignedProof; - } -}); - -// node_modules/applesauce-react/dist/helpers/index.js -var helpers_exports = {}; -__export(helpers_exports, { - buildLinkRenderer: () => buildLinkRenderer, - renderNast: () => renderNast -}); - -// node_modules/applesauce-react/dist/helpers/nast.js -var import_jsx_runtime = __toESM(require_jsx_runtime(), 1); -function renderNast(root, components) { - const indexes = {}; - return (0, import_jsx_runtime.jsx)(import_jsx_runtime.Fragment, { children: root.children.map((node) => { - indexes[node.type] = indexes[node.type] ?? 0; - const index2 = indexes[node.type]; - indexes[node.type]++; - const Component = components[node.type]; - if (!Component) - return null; - return (0, import_jsx_runtime.jsx)(Component, { node }, node.type + "-" + index2); - }) }); -} - -// node_modules/applesauce-react/dist/helpers/build-link-renderer.js -var import_jsx_runtime2 = __toESM(require_jsx_runtime(), 1); -var import_react = __toESM(require_react(), 1); -function buildLinkRenderer(handlers) { - const LinkRenderer = ({ node }) => { - const content = (0, import_react.useMemo)(() => { - try { - const url = new URL(node.href); - for (const handler of handlers) { - try { - const content2 = handler(url, node); - if (content2) - return content2; - } catch (e) { - } - } - } catch (error) { - } - return null; - }, [node.href, node.value]); - return content || (0, import_jsx_runtime2.jsx)(import_jsx_runtime2.Fragment, { children: node.value }); - }; - return (0, import_react.memo)(LinkRenderer); -} - -// node_modules/applesauce-react/dist/hooks/index.js -var hooks_exports = {}; -__export(hooks_exports, { - ObservableResource: () => ObservableResource, - identity: () => identity, - pluckCurrentTargetChecked: () => pluckCurrentTargetChecked, - pluckCurrentTargetValue: () => pluckCurrentTargetValue, - pluckFirst: () => pluckFirst, - useAccountManager: () => useAccountManager, - useAccounts: () => useAccounts, - useAction: () => useAction, - useActionHub: () => useActionHub, - useActiveAccount: () => useActiveAccount, - useEventFactory: () => useEventFactory, - useEventModel: () => useEventModel, - useEventStore: () => useEventStore, - useForceUpdate: () => useForceUpdate, - useLayoutObservable: () => useLayoutObservable, - useLayoutObservableState: () => useLayoutObservableState, - useLayoutSubscription: () => useLayoutSubscription, - useObservable: () => useObservable, - useObservableCallback: () => useObservableCallback, - useObservableEagerMemo: () => useObservableEagerMemo, - useObservableEagerState: () => useObservableEagerState, - useObservableGetState: () => useObservableGetState, - useObservableMemo: () => useObservableMemo, - useObservablePickState: () => useObservablePickState, - useObservableRef: () => useObservableRef, - useObservableState: () => useObservableState, - useObservableSuspense: () => useObservableSuspense, - useRefFn: () => useRefFn, - useRenderNast: () => useRenderNast, - useRenderThrow: () => useRenderThrow, - useRenderedContent: () => useRenderedContent, - useSubscription: () => useSubscription -}); - -// node_modules/applesauce-react/dist/hooks/use-account-manager.js -var import_react3 = __toESM(require_react(), 1); - -// node_modules/applesauce-react/dist/providers/accounts-provider.js -var import_jsx_runtime3 = __toESM(require_jsx_runtime(), 1); -var import_react2 = __toESM(require_react(), 1); -var AccountsContext = (0, import_react2.createContext)(void 0); -function AccountsProvider({ manager, children }) { - return (0, import_jsx_runtime3.jsx)(AccountsContext.Provider, { value: manager, children }); -} - -// node_modules/applesauce-react/dist/hooks/use-account-manager.js -function useAccountManager(require2 = true) { - const manager = (0, import_react3.useContext)(AccountsContext); - if (!manager && require2) - throw new Error("Missing AccountsProvider"); - return manager; -} - -// node_modules/observable-hooks/dist/index.mjs -var import_react4 = __toESM(require_react(), 1); -function useObservableInternal(useCustomEffect, init, inputs) { - if (!inputs) { - return (0, import_react4.useState)(init)[0]; - } - const [inputs$] = (0, import_react4.useState)(() => new BehaviorSubject(inputs)); - const [source$] = (0, import_react4.useState)(() => init(inputs$)); - const firstEffectRef = (0, import_react4.useRef)(true); - useCustomEffect(() => { - if (firstEffectRef.current) { - firstEffectRef.current = false; - return; - } - inputs$.next(inputs); - }, inputs); - return source$; -} -function useObservable(init, inputs) { - return useObservableInternal(import_react4.useEffect, init, inputs); -} -var identity = (value) => value; -var pluckFirst = (inputs$) => map((input) => input[0])(inputs$); -var pluckCurrentTargetValue = (event$) => map( - (event) => event.currentTarget.value -)(event$); -var pluckCurrentTargetChecked = (event$) => map( - (event) => event.currentTarget.checked -)(event$); -var getEmptySubject = () => new Subject(); -var useRefFn = (init) => { - const firstRef = (0, import_react4.useRef)(true); - const ref = (0, import_react4.useRef)(null); - if (firstRef.current) { - firstRef.current = false; - ref.current = init(); - } - return ref; -}; -var increment = (n) => n + 1 | 0; -var useForceUpdate = () => { - const updateState = (0, import_react4.useState)(0)[1]; - return (0, import_react4.useRef)(() => updateState(increment)).current; -}; -var useIsomorphicLayoutEffect = /* @__PURE__ */ (() => ( - /* istanbul ignore next */ - typeof window === "undefined" ? import_react4.useEffect : import_react4.useLayoutEffect -))(); -function useLayoutObservable(init, inputs) { - return useObservableInternal(useIsomorphicLayoutEffect, init, inputs); -} -function useObservableCallback(init = identity, selector) { - const [events$] = (0, import_react4.useState)(getEmptySubject); - const [outputs$] = (0, import_react4.useState)(() => init(events$)); - const callback = (0, import_react4.useRef)((...args) => { - events$.next(selector ? selector(args) : args[0]); - }).current; - return [callback, outputs$]; -} -var toObserver = (args) => { - var _a; - return ((_a = args[1]) == null ? void 0 : _a.next) ? args[1] : { - next: args[1], - error: args[2], - complete: args[3] - }; -}; -function useSubscriptionInternal(useCustomEffect, args) { - const argsRef = (0, import_react4.useRef)(args); - const observerRef = (0, import_react4.useRef)(); - const subscriptionRef = (0, import_react4.useRef)(); - useIsomorphicLayoutEffect(() => { - argsRef.current = args; - observerRef.current = toObserver(args); - }); - useCustomEffect(() => { - const input$ = argsRef.current[0]; - if (!observerRef.current) { - observerRef.current = toObserver(argsRef.current); - } - const subscription = input$.subscribe({ - next: (value) => { - var _a, _b; - if (input$ === argsRef.current[0]) { - (_b = (_a = observerRef.current).next) == null ? void 0 : _b.call(_a, value); - } - }, - error: (error) => { - if (input$ === argsRef.current[0]) { - observerRef.current.error ? observerRef.current.error(error) : console.error(error); - } - }, - complete: () => { - var _a, _b; - if (input$ === argsRef.current[0]) { - (_b = (_a = observerRef.current).complete) == null ? void 0 : _b.call(_a); - } - } - }); - subscriptionRef.current = subscription; - return () => { - subscription.unsubscribe(); - }; - }, [args[0]]); - return subscriptionRef; -} -function useSubscription(input$, observerOrNext$, error, complete) { - return useSubscriptionInternal(import_react4.useEffect, [ - input$, - observerOrNext$, - error, - complete - ]); -} -function useLayoutSubscription(input$, observerOrNext$, error, complete) { - return useSubscriptionInternal(useIsomorphicLayoutEffect, [ - input$, - observerOrNext$, - error, - complete - ]); -} -function useRenderThrow(input$) { - const forceUpdate = useForceUpdate(); - const errorRef = (0, import_react4.useRef)(); - const output$ = useObservable( - (inputs$) => inputs$.pipe( - switchMap(([input$2]) => { - errorRef.current = null; - return input$2.pipe( - catchError((error) => { - errorRef.current = error; - forceUpdate(); - return NEVER; - }) - ); - }) - ), - [input$] - ); - if (errorRef.current) { - throw errorRef.current; - } - return output$; -} -function useObservableStateInternal(useSubscription2, state$OrInit, initialState) { - if (isObservable(state$OrInit)) { - const state$ = state$OrInit; - const [state, setState] = (0, import_react4.useState)(() => { - if (state$ instanceof BehaviorSubject || state$.value !== void 0) { - return state$.value; - } - if (typeof initialState === "function") { - return initialState(); - } - return initialState; - }); - useSubscription2(state$, setState); - (0, import_react4.useDebugValue)(state); - return state; - } else { - const init = state$OrInit; - const [state, setState] = (0, import_react4.useState)(initialState); - const [input$] = (0, import_react4.useState)(getEmptySubject); - const [state$] = (0, import_react4.useState)(() => init(input$, state)); - const callback = (0, import_react4.useRef)((state2) => input$.next(state2)).current; - useSubscription2(state$, setState); - (0, import_react4.useDebugValue)(state); - return [state, callback]; - } -} -function useObservableState(state$OrInit, initialState) { - return useObservableStateInternal( - useSubscription, - state$OrInit, - initialState - ); -} -function useLayoutObservableState(state$OrInit, initialState) { - return useObservableStateInternal( - useLayoutSubscription, - state$OrInit, - initialState - ); -} -function useObservableEagerState(state$) { - const forceUpdate = useForceUpdate(); - const state$Ref = (0, import_react4.useRef)(state$); - const errorRef = (0, import_react4.useRef)(); - const isAsyncEmissionRef = (0, import_react4.useRef)(false); - const didSyncEmit = (0, import_react4.useRef)(false); - const [state, setState] = (0, import_react4.useState)(() => { - let state2; - state$.subscribe({ - next: (value) => { - didSyncEmit.current = true; - state2 = value; - }, - error: (error) => { - errorRef.current = error; - } - }).unsubscribe(); - return state2; - }); - useIsomorphicLayoutEffect(() => { - state$Ref.current = state$; - }); - (0, import_react4.useEffect)(() => { - errorRef.current = null; - const input$ = state$Ref.current; - let secondInitialValue = state; - const subscription = input$.subscribe({ - next: (value) => { - if (input$ !== state$Ref.current) { - return; - } - if (isAsyncEmissionRef.current) { - setState(() => value); - } else { - secondInitialValue = value; - } - }, - error: (error) => { - if (input$ !== state$Ref.current) { - return; - } - errorRef.current = error; - forceUpdate(); - } - }); - if (!isAsyncEmissionRef.current) { - if (secondInitialValue !== state) { - setState(() => secondInitialValue); - } - } - isAsyncEmissionRef.current = true; - return () => { - subscription.unsubscribe(); - }; - }, [state$]); - if (errorRef.current) { - throw errorRef.current; - } - if (didSyncEmit.current) { - (0, import_react4.useDebugValue)(state); - return state; - } else { - throw new Error("Observable did not synchronously emit a value."); - } -} -function useObservableGetState(state$, initialState, ...path) { - const value = useObservableState( - useObservable( - () => state$.pipe(map((state) => path.reduce(getValue, state))) - ), - initialState - ); - (0, import_react4.useDebugValue)(value); - return value; -} -function getValue(obj, key) { - return obj[key]; -} -function useObservablePickState(state$, initialState, ...keys) { - const value = useObservableState( - useObservable( - () => state$.pipe( - distinctUntilChanged((s1, s2) => keys.every((k) => s1[k] === s2[k])), - map( - (state) => keys.reduce( - // eslint-disable-next-line no-sequences - (o, k) => (o[k] = state[k], o), - {} - ) - ) - ) - ), - initialState - ); - (0, import_react4.useDebugValue)(value); - return value; -} -function useObservableSuspense(resource) { - const resourceValue = resource.read(); - const forceUpdate = useForceUpdate(); - const [state, setState] = (0, import_react4.useState)(resourceValue); - useSubscription(resource.valueRef$$, (valueRef) => { - if (valueRef) { - setState(valueRef.current); - } - }); - useSubscription(resource.shouldUpdate$$, forceUpdate); - (0, import_react4.useDebugValue)(state); - return state; -} -function useObservableRef(initialValue) { - const [value$] = (0, import_react4.useState)(() => new BehaviorSubject(initialValue)); - const [ref] = (0, import_react4.useState)(() => ({ - get current() { - return value$.value; - }, - set current(value) { - value$.next(value); - } - })); - return [ref, value$]; -} -var createHandler = () => { - const handler = {}; - handler.b = new Promise((resolve) => { - handler.a = resolve; - }); - return handler; -}; -var ObservableResource = class { - /** - * @param input$ An Observable. - * @param isSuccess A function that determines if the value emitted from - * `input$` is of success state. If false a Suspense is triggered. - * Default all true. - */ - constructor(input$, isSuccess) { - /** - * Unlike Promise, Observable is a multiple push mechanism. - * Only force update when Suspense needs to restart. - */ - __publicField(this, "shouldUpdate$$", new Subject()); - __publicField(this, "valueRef$$", new BehaviorSubject(void 0)); - __publicField(this, "input$"); - __publicField(this, "_h", createHandler()); - __publicField(this, "_e", null); - __publicField(this, "_b"); - __publicField(this, "_d", false); - __publicField(this, "_o"); - this.input$ = input$; - this._o = { - next: (value) => { - var _a; - this._e = null; - if (!isSuccess || isSuccess(value)) { - if (((_a = this.valueRef$$.value) == null ? void 0 : _a.current) !== value) { - this.valueRef$$.next({ current: value }); - } - if (this._h) { - const { a: resolve } = this._h; - this._h = null; - resolve(); - } - } else if (!this._h) { - this._h = createHandler(); - this.shouldUpdate$$.next(true); - } - }, - error: (error) => { - this._e = error; - if (this._h) { - const { a: resolve } = this._h; - this._h = null; - resolve(); - } else { - this.shouldUpdate$$.next(true); - } - }, - complete: () => { - if (this._h) { - this._e = new Error("Suspender ended unexpectedly."); - const { a: resolve } = this._h; - this._h = null; - resolve(); - } - } - }; - this._b = input$.subscribe(this._o); - } - get isDestroyed() { - return this._d; - } - read() { - var _a; - if (this._e) { - throw this._e; - } - if (this._h) { - throw this._h.b; - } - return (_a = this.valueRef$$.value) == null ? void 0 : _a.current; - } - reload(newInput$) { - if (this._d) { - throw new Error("Cannot reload a destroyed Observable Resource"); - } - if (newInput$) { - this.input$ = newInput$; - } - this._b.unsubscribe(); - this._e = null; - if (this._h) { - this._h.a(); - this._h = createHandler(); - } - this._b = this.input$.subscribe(this._o); - } - destroy() { - this._d = true; - this._b.unsubscribe(); - this.shouldUpdate$$.complete(); - if (this._h) { - this._e = new Error("Resource has been destroyed."); - const { a: resolve } = this._h; - this._h = null; - resolve(); - } - } -}; - -// node_modules/applesauce-react/dist/hooks/use-accounts.js -function useAccounts() { - const manager = useAccountManager(); - return useObservableEagerState(manager.accounts$); -} - -// node_modules/applesauce-react/dist/hooks/use-action-hub.js -var import_react6 = __toESM(require_react(), 1); - -// node_modules/applesauce-react/dist/providers/actions-provider.js -var import_jsx_runtime4 = __toESM(require_jsx_runtime(), 1); -var import_react5 = __toESM(require_react(), 1); -var ActionsContext = (0, import_react5.createContext)(void 0); -function ActionsProvider({ actionHub, children }) { - return (0, import_jsx_runtime4.jsx)(ActionsContext.Provider, { value: actionHub, children }); -} - -// node_modules/applesauce-react/dist/hooks/use-action-hub.js -function useActionHub() { - const hub = (0, import_react6.useContext)(ActionsContext); - if (!hub) - throw new Error("Missing ActionsProvider"); - return hub; -} - -// node_modules/applesauce-react/dist/hooks/use-action.js -var import_react7 = __toESM(require_react(), 1); -function useAction(Action, args) { - const [loading, setLoading] = (0, import_react7.useState)(false); - const ref = (0, import_react7.useRef)(args); - ref.current = args; - const hub = useActionHub(); - const run = (0, import_react7.useCallback)(async () => { - if (args === void 0) - return; - setLoading(true); - try { - await hub.run(Action, ...args); - setLoading(false); - } catch (error) { - setLoading(false); - throw error; - } - }, [Action]); - const exec = (0, import_react7.useCallback)(() => { - if (args === void 0) - return; - setLoading(true); - try { - return hub.exec(Action, ...args).pipe(finalize(() => { - setLoading(false); - })); - } catch (error) { - setLoading(false); - throw error; - } - }, [Action]); - return { loading, run, exec }; -} - -// node_modules/applesauce-react/dist/hooks/use-active-account.js -function useActiveAccount() { - const manager = useAccountManager(); - return useObservableEagerState(manager.active$); -} - -// node_modules/applesauce-react/dist/hooks/use-event-factory.js -var import_react9 = __toESM(require_react(), 1); - -// node_modules/applesauce-react/dist/providers/factory-provider.js -var import_jsx_runtime5 = __toESM(require_jsx_runtime(), 1); -var import_react8 = __toESM(require_react(), 1); -var FactoryContext = (0, import_react8.createContext)(void 0); -function FactoryProvider({ factory, children }) { - return (0, import_jsx_runtime5.jsx)(FactoryContext.Provider, { value: factory, children }); -} - -// node_modules/applesauce-react/dist/hooks/use-event-factory.js -function useEventFactory(require2 = true) { - const factory = (0, import_react9.useContext)(FactoryContext); - if (!require2 && !factory) - throw new Error("Missing EventFactoryProvider"); - return factory; -} - -// node_modules/applesauce-react/dist/hooks/use-event-model.js -var import_hash_sum = __toESM(require_hash_sum(), 1); - -// node_modules/applesauce-react/dist/hooks/use-event-store.js -var import_react11 = __toESM(require_react(), 1); - -// node_modules/applesauce-react/dist/providers/store-provider.js -var import_jsx_runtime6 = __toESM(require_jsx_runtime(), 1); -var import_react10 = __toESM(require_react(), 1); -var EventStoreContext = (0, import_react10.createContext)(null); -function EventStoreProvider({ eventStore, children }) { - return (0, import_jsx_runtime6.jsx)(EventStoreContext.Provider, { value: eventStore, children }); -} - -// node_modules/applesauce-react/dist/hooks/use-event-store.js -function useEventStore() { - const store = (0, import_react11.useContext)(EventStoreContext); - if (!store) - throw new Error("Missing EventStoreProvider"); - return store; -} - -// node_modules/applesauce-react/dist/hooks/use-observable-memo.js -var import_react12 = __toESM(require_react(), 1); -function useObservableMemo(factory, deps) { - return useObservableState((0, import_react12.useMemo)(() => factory() || of(void 0), deps)); -} -function useObservableEagerMemo(factory, deps) { - return useObservableEagerState((0, import_react12.useMemo)(() => factory() || of(void 0), deps)); -} - -// node_modules/applesauce-react/dist/hooks/use-event-model.js -function useEventModel(factory, args) { - const store = useEventStore(); - return useObservableEagerMemo(() => { - if (args) - return store.model(factory, ...args).pipe(withImmediateValueOrDefault(void 0)); - else - return of(void 0); - }, [(0, import_hash_sum.default)(args), store, factory]); -} - -// node_modules/applesauce-react/dist/hooks/use-render-nast.js -var import_react13 = __toESM(require_react(), 1); -function useRenderNast(root, components) { - return (0, import_react13.useMemo)(() => root ? renderNast(root, components) : null, [root, Object.keys(components).join("|")]); -} - -// node_modules/applesauce-react/dist/hooks/use-rendered-content.js -var import_react14 = __toESM(require_react(), 1); - -// node_modules/unist-util-is/lib/index.js -var convert = ( - // Note: overloads in JSDoc can’t yet use different `@template`s. - /** - * @type {( - * ((test: Condition) => (node: unknown, index?: number | null | undefined, parent?: Parent | null | undefined, context?: unknown) => node is Node & {type: Condition}) & - * ((test: Condition) => (node: unknown, index?: number | null | undefined, parent?: Parent | null | undefined, context?: unknown) => node is Node & Condition) & - * ((test: Condition) => (node: unknown, index?: number | null | undefined, parent?: Parent | null | undefined, context?: unknown) => node is Node & Predicate) & - * ((test?: null | undefined) => (node?: unknown, index?: number | null | undefined, parent?: Parent | null | undefined, context?: unknown) => node is Node) & - * ((test?: Test) => Check) - * )} - */ - /** - * @param {Test} [test] - * @returns {Check} - */ - function(test) { - if (test === null || test === void 0) { - return ok; - } - if (typeof test === "function") { - return castFactory(test); - } - if (typeof test === "object") { - return Array.isArray(test) ? anyFactory(test) : propsFactory(test); - } - if (typeof test === "string") { - return typeFactory(test); - } - throw new Error("Expected function, string, or object as test"); - } -); -function anyFactory(tests) { - const checks = []; - let index2 = -1; - while (++index2 < tests.length) { - checks[index2] = convert(tests[index2]); - } - return castFactory(any); - function any(...parameters) { - let index3 = -1; - while (++index3 < checks.length) { - if (checks[index3].apply(this, parameters)) return true; - } - return false; - } -} -function propsFactory(check) { - const checkAsRecord = ( - /** @type {Record} */ - check - ); - return castFactory(all); - function all(node) { - const nodeAsRecord = ( - /** @type {Record} */ - /** @type {unknown} */ - node - ); - let key; - for (key in check) { - if (nodeAsRecord[key] !== checkAsRecord[key]) return false; - } - return true; - } -} -function typeFactory(check) { - return castFactory(type); - function type(node) { - return node && node.type === check; - } -} -function castFactory(testFunction) { - return check; - function check(value, index2, parent) { - return Boolean( - looksLikeANode(value) && testFunction.call( - this, - value, - typeof index2 === "number" ? index2 : void 0, - parent || void 0 - ) - ); - } -} -function ok() { - return true; -} -function looksLikeANode(value) { - return value !== null && typeof value === "object" && "type" in value; -} - -// node_modules/unist-util-visit-parents/lib/color.js -function color(d) { - return d; -} - -// node_modules/unist-util-visit-parents/lib/index.js -var empty = []; -var CONTINUE = true; -var EXIT = false; -var SKIP = "skip"; -function visitParents(tree, test, visitor, reverse) { - let check; - if (typeof test === "function" && typeof visitor !== "function") { - reverse = visitor; - visitor = test; - } else { - check = test; - } - const is2 = convert(check); - const step = reverse ? -1 : 1; - factory(tree, void 0, [])(); - function factory(node, index2, parents) { - const value = ( - /** @type {Record} */ - node && typeof node === "object" ? node : {} - ); - if (typeof value.type === "string") { - const name = ( - // `hast` - typeof value.tagName === "string" ? value.tagName : ( - // `xast` - typeof value.name === "string" ? value.name : void 0 - ) - ); - Object.defineProperty(visit, "name", { - value: "node (" + color(node.type + (name ? "<" + name + ">" : "")) + ")" - }); - } - return visit; - function visit() { - let result = empty; - let subresult; - let offset; - let grandparents; - if (!test || is2(node, index2, parents[parents.length - 1] || void 0)) { - result = toResult(visitor(node, parents)); - if (result[0] === EXIT) { - return result; - } - } - if ("children" in node && node.children) { - const nodeAsParent = ( - /** @type {UnistParent} */ - node - ); - if (nodeAsParent.children && result[0] !== SKIP) { - offset = (reverse ? nodeAsParent.children.length : -1) + step; - grandparents = parents.concat(nodeAsParent); - while (offset > -1 && offset < nodeAsParent.children.length) { - const child = nodeAsParent.children[offset]; - subresult = factory(child, offset, grandparents)(); - if (subresult[0] === EXIT) { - return subresult; - } - offset = typeof subresult[1] === "number" ? subresult[1] : offset + step; - } - } - } - return result; - } - } -} -function toResult(value) { - if (Array.isArray(value)) { - return value; - } - if (typeof value === "number") { - return [CONTINUE, value]; - } - return value === null || value === void 0 ? empty : [value]; -} - -// node_modules/applesauce-content/dist/nast/find-and-replace.js -function findAndReplace(tree, list) { - const pairs = list; - let pairIndex = -1; - const visitor = (node, parents) => { - let index2 = -1; - let grandparent; - while (++index2 < parents.length) { - const parent = parents[index2]; - grandparent = parent; - } - if (grandparent) { - return handler(node, parents); - } - return void 0; - }; - while (++pairIndex < pairs.length) { - visitParents(tree, "text", visitor); - } - function handler(node, parents) { - const parent = parents[parents.length - 1]; - const find = pairs[pairIndex][0]; - const replace = pairs[pairIndex][1]; - let start = 0; - const siblings = parent.children; - const index2 = siblings.indexOf(node); - let change = false; - let nodes = []; - find.lastIndex = 0; - let match = find.exec(node.value); - while (match) { - const position2 = match.index; - let value = replace(...match); - if (typeof value === "string") { - value = value.length > 0 ? { type: "text", value } : void 0; - } - if (value === false) { - find.lastIndex = position2 + 1; - } else { - if (start !== position2) { - nodes.push({ - type: "text", - value: node.value.slice(start, position2) - }); - } - if (Array.isArray(value)) { - nodes.push(...value); - } else if (value) { - nodes.push(value); - } - start = position2 + match[0].length; - change = true; - } - if (!find.global) { - break; - } - match = find.exec(node.value); - } - if (change) { - if (start < node.value.length) { - nodes.push({ type: "text", value: node.value.slice(start) }); - } - parent.children.splice(index2, 1, ...nodes); - } else { - nodes = [node]; - } - return index2 + nodes.length; - } -} - -// node_modules/applesauce-content/dist/nast/eol-metadata.js -function eolMetadata() { - return (tree) => { - for (let i = 0; i < tree.children.length; i++) { - const node = tree.children[i]; - const next = tree.children[i + 1]; - if (node.type === "text" && node.value.endsWith("\n") || !next || next.type === "text" && next.value.startsWith("\n")) { - node.data = node.data || {}; - node.data.eol = true; - } - } - }; -} - -// node_modules/applesauce-content/dist/nast/truncate.js -function truncateContent(tree, maxLength = 256) { - let length = 0; - for (let i = 0; i < tree.children.length; i++) { - const node = tree.children[i]; - switch (node.type) { - case "hashtag": - length += 1 + node.hashtag.length; - break; - case "mention": - length += 10; - break; - case "cashu": - length += node.raw.length; - break; - case "gallery": - length += node.links.reduce((t, l) => t + l.length, 0); - break; - case "link": - case "text": - length += node.value.length; - break; - case "emoji": - length += 1; - break; - } - if (length > maxLength) { - if (node.type === "text") { - const children = i > 0 ? tree.children.slice(0, i) : []; - const chunkLength = node.value.length - (length - maxLength); - const newLines = node.value.matchAll(/\n/g); - for (const match of newLines) { - if (match.index && match.index > chunkLength) { - children.push({ type: "text", value: node.value.slice(0, match.index) }); - return { ...tree, children, truncated: true }; - } - } - children.push({ type: "text", value: node.value.slice(0, maxLength - length) }); - return { ...tree, children, truncated: true }; - } else - return { ...tree, children: tree.children.slice(0, i), truncated: true }; - } - } - return tree; -} - -// node_modules/bail/index.js -function bail(error) { - if (error) { - throw error; - } -} - -// node_modules/unified/lib/index.js -var import_extend = __toESM(require_extend(), 1); - -// node_modules/devlop/lib/development.js -var AssertionError = class extends Error { - /** - * Create an assertion error. - * - * @param {string} message - * Message explaining error. - * @param {unknown} actual - * Value. - * @param {unknown} expected - * Baseline. - * @param {string} operator - * Name of equality operation. - * @param {boolean} generated - * Whether `message` is a custom message or not - * @returns - * Instance. - */ - // eslint-disable-next-line max-params - constructor(message, actual, expected, operator, generated) { - super(message); - __publicField( - this, - "name", - /** @type {const} */ - "Assertion" - ); - __publicField( - this, - "code", - /** @type {const} */ - "ERR_ASSERTION" - ); - if (Error.captureStackTrace) { - Error.captureStackTrace(this, this.constructor); - } - this.actual = actual; - this.expected = expected; - this.generated = generated; - this.operator = operator; - } -}; -function ok2(value, message) { - assert( - Boolean(value), - false, - true, - "ok", - "Expected value to be truthy", - message - ); -} -function assert(bool, actual, expected, operator, defaultMessage, userMessage) { - if (!bool) { - throw userMessage instanceof Error ? userMessage : new AssertionError( - userMessage || defaultMessage, - actual, - expected, - operator, - !userMessage - ); - } -} - -// node_modules/is-plain-obj/index.js -function isPlainObject(value) { - if (typeof value !== "object" || value === null) { - return false; - } - const prototype = Object.getPrototypeOf(value); - return (prototype === null || prototype === Object.prototype || Object.getPrototypeOf(prototype) === null) && !(Symbol.toStringTag in value) && !(Symbol.iterator in value); -} - -// node_modules/trough/lib/index.js -function trough() { - const fns = []; - const pipeline = { run, use }; - return pipeline; - function run(...values) { - let middlewareIndex = -1; - const callback = values.pop(); - if (typeof callback !== "function") { - throw new TypeError("Expected function as last argument, not " + callback); - } - next(null, ...values); - function next(error, ...output) { - const fn = fns[++middlewareIndex]; - let index2 = -1; - if (error) { - callback(error); - return; - } - while (++index2 < values.length) { - if (output[index2] === null || output[index2] === void 0) { - output[index2] = values[index2]; - } - } - values = output; - if (fn) { - wrap(fn, next)(...output); - } else { - callback(null, ...output); - } - } - } - function use(middelware) { - if (typeof middelware !== "function") { - throw new TypeError( - "Expected `middelware` to be a function, not " + middelware - ); - } - fns.push(middelware); - return pipeline; - } -} -function wrap(middleware, callback) { - let called; - return wrapped; - function wrapped(...parameters) { - const fnExpectsCallback = middleware.length > parameters.length; - let result; - if (fnExpectsCallback) { - parameters.push(done); - } - try { - result = middleware.apply(this, parameters); - } catch (error) { - const exception = ( - /** @type {Error} */ - error - ); - if (fnExpectsCallback && called) { - throw exception; - } - return done(exception); - } - if (!fnExpectsCallback) { - if (result && result.then && typeof result.then === "function") { - result.then(then, done); - } else if (result instanceof Error) { - done(result); - } else { - then(result); - } - } - } - function done(error, ...output) { - if (!called) { - called = true; - callback(error, ...output); - } - } - function then(value) { - done(null, value); - } -} - -// node_modules/unist-util-stringify-position/lib/index.js -function stringifyPosition(value) { - if (!value || typeof value !== "object") { - return ""; - } - if ("position" in value || "type" in value) { - return position(value.position); - } - if ("start" in value || "end" in value) { - return position(value); - } - if ("line" in value || "column" in value) { - return point(value); - } - return ""; -} -function point(point2) { - return index(point2 && point2.line) + ":" + index(point2 && point2.column); -} -function position(pos) { - return point(pos && pos.start) + "-" + point(pos && pos.end); -} -function index(value) { - return value && typeof value === "number" ? value : 1; -} - -// node_modules/vfile-message/lib/index.js -var VFileMessage = class extends Error { - /** - * Create a message for `reason`. - * - * > 🪦 **Note**: also has obsolete signatures. - * - * @overload - * @param {string} reason - * @param {Options | null | undefined} [options] - * @returns - * - * @overload - * @param {string} reason - * @param {Node | NodeLike | null | undefined} parent - * @param {string | null | undefined} [origin] - * @returns - * - * @overload - * @param {string} reason - * @param {Point | Position | null | undefined} place - * @param {string | null | undefined} [origin] - * @returns - * - * @overload - * @param {string} reason - * @param {string | null | undefined} [origin] - * @returns - * - * @overload - * @param {Error | VFileMessage} cause - * @param {Node | NodeLike | null | undefined} parent - * @param {string | null | undefined} [origin] - * @returns - * - * @overload - * @param {Error | VFileMessage} cause - * @param {Point | Position | null | undefined} place - * @param {string | null | undefined} [origin] - * @returns - * - * @overload - * @param {Error | VFileMessage} cause - * @param {string | null | undefined} [origin] - * @returns - * - * @param {Error | VFileMessage | string} causeOrReason - * Reason for message, should use markdown. - * @param {Node | NodeLike | Options | Point | Position | string | null | undefined} [optionsOrParentOrPlace] - * Configuration (optional). - * @param {string | null | undefined} [origin] - * Place in code where the message originates (example: - * `'my-package:my-rule'` or `'my-rule'`). - * @returns - * Instance of `VFileMessage`. - */ - // eslint-disable-next-line complexity - constructor(causeOrReason, optionsOrParentOrPlace, origin) { - super(); - if (typeof optionsOrParentOrPlace === "string") { - origin = optionsOrParentOrPlace; - optionsOrParentOrPlace = void 0; - } - let reason = ""; - let options = {}; - let legacyCause = false; - if (optionsOrParentOrPlace) { - if ("line" in optionsOrParentOrPlace && "column" in optionsOrParentOrPlace) { - options = { place: optionsOrParentOrPlace }; - } else if ("start" in optionsOrParentOrPlace && "end" in optionsOrParentOrPlace) { - options = { place: optionsOrParentOrPlace }; - } else if ("type" in optionsOrParentOrPlace) { - options = { - ancestors: [optionsOrParentOrPlace], - place: optionsOrParentOrPlace.position - }; - } else { - options = { ...optionsOrParentOrPlace }; - } - } - if (typeof causeOrReason === "string") { - reason = causeOrReason; - } else if (!options.cause && causeOrReason) { - legacyCause = true; - reason = causeOrReason.message; - options.cause = causeOrReason; - } - if (!options.ruleId && !options.source && typeof origin === "string") { - const index2 = origin.indexOf(":"); - if (index2 === -1) { - options.ruleId = origin; - } else { - options.source = origin.slice(0, index2); - options.ruleId = origin.slice(index2 + 1); - } - } - if (!options.place && options.ancestors && options.ancestors) { - const parent = options.ancestors[options.ancestors.length - 1]; - if (parent) { - options.place = parent.position; - } - } - const start = options.place && "start" in options.place ? options.place.start : options.place; - this.ancestors = options.ancestors || void 0; - this.cause = options.cause || void 0; - this.column = start ? start.column : void 0; - this.fatal = void 0; - this.file = ""; - this.message = reason; - this.line = start ? start.line : void 0; - this.name = stringifyPosition(options.place) || "1:1"; - this.place = options.place || void 0; - this.reason = this.message; - this.ruleId = options.ruleId || void 0; - this.source = options.source || void 0; - this.stack = legacyCause && options.cause && typeof options.cause.stack === "string" ? options.cause.stack : ""; - this.actual = void 0; - this.expected = void 0; - this.note = void 0; - this.url = void 0; - } -}; -VFileMessage.prototype.file = ""; -VFileMessage.prototype.name = ""; -VFileMessage.prototype.reason = ""; -VFileMessage.prototype.message = ""; -VFileMessage.prototype.stack = ""; -VFileMessage.prototype.column = void 0; -VFileMessage.prototype.line = void 0; -VFileMessage.prototype.ancestors = void 0; -VFileMessage.prototype.cause = void 0; -VFileMessage.prototype.fatal = void 0; -VFileMessage.prototype.place = void 0; -VFileMessage.prototype.ruleId = void 0; -VFileMessage.prototype.source = void 0; - -// node_modules/vfile/lib/minpath.browser.js -var minpath = { basename, dirname, extname, join, sep: "/" }; -function basename(path, extname2) { - if (extname2 !== void 0 && typeof extname2 !== "string") { - throw new TypeError('"ext" argument must be a string'); - } - assertPath(path); - let start = 0; - let end = -1; - let index2 = path.length; - let seenNonSlash; - if (extname2 === void 0 || extname2.length === 0 || extname2.length > path.length) { - while (index2--) { - if (path.codePointAt(index2) === 47) { - if (seenNonSlash) { - start = index2 + 1; - break; - } - } else if (end < 0) { - seenNonSlash = true; - end = index2 + 1; - } - } - return end < 0 ? "" : path.slice(start, end); - } - if (extname2 === path) { - return ""; - } - let firstNonSlashEnd = -1; - let extnameIndex = extname2.length - 1; - while (index2--) { - if (path.codePointAt(index2) === 47) { - if (seenNonSlash) { - start = index2 + 1; - break; - } - } else { - if (firstNonSlashEnd < 0) { - seenNonSlash = true; - firstNonSlashEnd = index2 + 1; - } - if (extnameIndex > -1) { - if (path.codePointAt(index2) === extname2.codePointAt(extnameIndex--)) { - if (extnameIndex < 0) { - end = index2; - } - } else { - extnameIndex = -1; - end = firstNonSlashEnd; - } - } - } - } - if (start === end) { - end = firstNonSlashEnd; - } else if (end < 0) { - end = path.length; - } - return path.slice(start, end); -} -function dirname(path) { - assertPath(path); - if (path.length === 0) { - return "."; - } - let end = -1; - let index2 = path.length; - let unmatchedSlash; - while (--index2) { - if (path.codePointAt(index2) === 47) { - if (unmatchedSlash) { - end = index2; - break; - } - } else if (!unmatchedSlash) { - unmatchedSlash = true; - } - } - return end < 0 ? path.codePointAt(0) === 47 ? "/" : "." : end === 1 && path.codePointAt(0) === 47 ? "//" : path.slice(0, end); -} -function extname(path) { - assertPath(path); - let index2 = path.length; - let end = -1; - let startPart = 0; - let startDot = -1; - let preDotState = 0; - let unmatchedSlash; - while (index2--) { - const code = path.codePointAt(index2); - if (code === 47) { - if (unmatchedSlash) { - startPart = index2 + 1; - break; - } - continue; - } - if (end < 0) { - unmatchedSlash = true; - end = index2 + 1; - } - if (code === 46) { - if (startDot < 0) { - startDot = index2; - } else if (preDotState !== 1) { - preDotState = 1; - } - } else if (startDot > -1) { - preDotState = -1; - } - } - if (startDot < 0 || end < 0 || // We saw a non-dot character immediately before the dot. - preDotState === 0 || // The (right-most) trimmed path component is exactly `..`. - preDotState === 1 && startDot === end - 1 && startDot === startPart + 1) { - return ""; - } - return path.slice(startDot, end); -} -function join(...segments) { - let index2 = -1; - let joined; - while (++index2 < segments.length) { - assertPath(segments[index2]); - if (segments[index2]) { - joined = joined === void 0 ? segments[index2] : joined + "/" + segments[index2]; - } - } - return joined === void 0 ? "." : normalize(joined); -} -function normalize(path) { - assertPath(path); - const absolute = path.codePointAt(0) === 47; - let value = normalizeString(path, !absolute); - if (value.length === 0 && !absolute) { - value = "."; - } - if (value.length > 0 && path.codePointAt(path.length - 1) === 47) { - value += "/"; - } - return absolute ? "/" + value : value; -} -function normalizeString(path, allowAboveRoot) { - let result = ""; - let lastSegmentLength = 0; - let lastSlash = -1; - let dots = 0; - let index2 = -1; - let code; - let lastSlashIndex; - while (++index2 <= path.length) { - if (index2 < path.length) { - code = path.codePointAt(index2); - } else if (code === 47) { - break; - } else { - code = 47; - } - if (code === 47) { - if (lastSlash === index2 - 1 || dots === 1) { - } else if (lastSlash !== index2 - 1 && dots === 2) { - if (result.length < 2 || lastSegmentLength !== 2 || result.codePointAt(result.length - 1) !== 46 || result.codePointAt(result.length - 2) !== 46) { - if (result.length > 2) { - lastSlashIndex = result.lastIndexOf("/"); - if (lastSlashIndex !== result.length - 1) { - if (lastSlashIndex < 0) { - result = ""; - lastSegmentLength = 0; - } else { - result = result.slice(0, lastSlashIndex); - lastSegmentLength = result.length - 1 - result.lastIndexOf("/"); - } - lastSlash = index2; - dots = 0; - continue; - } - } else if (result.length > 0) { - result = ""; - lastSegmentLength = 0; - lastSlash = index2; - dots = 0; - continue; - } - } - if (allowAboveRoot) { - result = result.length > 0 ? result + "/.." : ".."; - lastSegmentLength = 2; - } - } else { - if (result.length > 0) { - result += "/" + path.slice(lastSlash + 1, index2); - } else { - result = path.slice(lastSlash + 1, index2); - } - lastSegmentLength = index2 - lastSlash - 1; - } - lastSlash = index2; - dots = 0; - } else if (code === 46 && dots > -1) { - dots++; - } else { - dots = -1; - } - } - return result; -} -function assertPath(path) { - if (typeof path !== "string") { - throw new TypeError( - "Path must be a string. Received " + JSON.stringify(path) - ); - } -} - -// node_modules/vfile/lib/minproc.browser.js -var minproc = { cwd }; -function cwd() { - return "/"; -} - -// node_modules/vfile/lib/minurl.shared.js -function isUrl(fileUrlOrPath) { - return Boolean( - fileUrlOrPath !== null && typeof fileUrlOrPath === "object" && "href" in fileUrlOrPath && fileUrlOrPath.href && "protocol" in fileUrlOrPath && fileUrlOrPath.protocol && // @ts-expect-error: indexing is fine. - fileUrlOrPath.auth === void 0 - ); -} - -// node_modules/vfile/lib/minurl.browser.js -function urlToPath(path) { - if (typeof path === "string") { - path = new URL(path); - } else if (!isUrl(path)) { - const error = new TypeError( - 'The "path" argument must be of type string or an instance of URL. Received `' + path + "`" - ); - error.code = "ERR_INVALID_ARG_TYPE"; - throw error; - } - if (path.protocol !== "file:") { - const error = new TypeError("The URL must be of scheme file"); - error.code = "ERR_INVALID_URL_SCHEME"; - throw error; - } - return getPathFromURLPosix(path); -} -function getPathFromURLPosix(url) { - if (url.hostname !== "") { - const error = new TypeError( - 'File URL host must be "localhost" or empty on darwin' - ); - error.code = "ERR_INVALID_FILE_URL_HOST"; - throw error; - } - const pathname = url.pathname; - let index2 = -1; - while (++index2 < pathname.length) { - if (pathname.codePointAt(index2) === 37 && pathname.codePointAt(index2 + 1) === 50) { - const third = pathname.codePointAt(index2 + 2); - if (third === 70 || third === 102) { - const error = new TypeError( - "File URL path must not include encoded / characters" - ); - error.code = "ERR_INVALID_FILE_URL_PATH"; - throw error; - } - } - } - return decodeURIComponent(pathname); -} - -// node_modules/vfile/lib/index.js -var order = ( - /** @type {const} */ - [ - "history", - "path", - "basename", - "stem", - "extname", - "dirname" - ] -); -var VFile = class { - /** - * Create a new virtual file. - * - * `options` is treated as: - * - * * `string` or `Uint8Array` — `{value: options}` - * * `URL` — `{path: options}` - * * `VFile` — shallow copies its data over to the new file - * * `object` — all fields are shallow copied over to the new file - * - * Path related fields are set in the following order (least specific to - * most specific): `history`, `path`, `basename`, `stem`, `extname`, - * `dirname`. - * - * You cannot set `dirname` or `extname` without setting either `history`, - * `path`, `basename`, or `stem` too. - * - * @param {Compatible | null | undefined} [value] - * File value. - * @returns - * New instance. - */ - constructor(value) { - let options; - if (!value) { - options = {}; - } else if (isUrl(value)) { - options = { path: value }; - } else if (typeof value === "string" || isUint8Array(value)) { - options = { value }; - } else { - options = value; - } - this.cwd = "cwd" in options ? "" : minproc.cwd(); - this.data = {}; - this.history = []; - this.messages = []; - this.value; - this.map; - this.result; - this.stored; - let index2 = -1; - while (++index2 < order.length) { - const field2 = order[index2]; - if (field2 in options && options[field2] !== void 0 && options[field2] !== null) { - this[field2] = field2 === "history" ? [...options[field2]] : options[field2]; - } - } - let field; - for (field in options) { - if (!order.includes(field)) { - this[field] = options[field]; - } - } - } - /** - * Get the basename (including extname) (example: `'index.min.js'`). - * - * @returns {string | undefined} - * Basename. - */ - get basename() { - return typeof this.path === "string" ? minpath.basename(this.path) : void 0; - } - /** - * Set basename (including extname) (`'index.min.js'`). - * - * Cannot contain path separators (`'/'` on unix, macOS, and browsers, `'\'` - * on windows). - * Cannot be nullified (use `file.path = file.dirname` instead). - * - * @param {string} basename - * Basename. - * @returns {undefined} - * Nothing. - */ - set basename(basename2) { - assertNonEmpty(basename2, "basename"); - assertPart(basename2, "basename"); - this.path = minpath.join(this.dirname || "", basename2); - } - /** - * Get the parent path (example: `'~'`). - * - * @returns {string | undefined} - * Dirname. - */ - get dirname() { - return typeof this.path === "string" ? minpath.dirname(this.path) : void 0; - } - /** - * Set the parent path (example: `'~'`). - * - * Cannot be set if there’s no `path` yet. - * - * @param {string | undefined} dirname - * Dirname. - * @returns {undefined} - * Nothing. - */ - set dirname(dirname2) { - assertPath2(this.basename, "dirname"); - this.path = minpath.join(dirname2 || "", this.basename); - } - /** - * Get the extname (including dot) (example: `'.js'`). - * - * @returns {string | undefined} - * Extname. - */ - get extname() { - return typeof this.path === "string" ? minpath.extname(this.path) : void 0; - } - /** - * Set the extname (including dot) (example: `'.js'`). - * - * Cannot contain path separators (`'/'` on unix, macOS, and browsers, `'\'` - * on windows). - * Cannot be set if there’s no `path` yet. - * - * @param {string | undefined} extname - * Extname. - * @returns {undefined} - * Nothing. - */ - set extname(extname2) { - assertPart(extname2, "extname"); - assertPath2(this.dirname, "extname"); - if (extname2) { - if (extname2.codePointAt(0) !== 46) { - throw new Error("`extname` must start with `.`"); - } - if (extname2.includes(".", 1)) { - throw new Error("`extname` cannot contain multiple dots"); - } - } - this.path = minpath.join(this.dirname, this.stem + (extname2 || "")); - } - /** - * Get the full path (example: `'~/index.min.js'`). - * - * @returns {string} - * Path. - */ - get path() { - return this.history[this.history.length - 1]; - } - /** - * Set the full path (example: `'~/index.min.js'`). - * - * Cannot be nullified. - * You can set a file URL (a `URL` object with a `file:` protocol) which will - * be turned into a path with `url.fileURLToPath`. - * - * @param {URL | string} path - * Path. - * @returns {undefined} - * Nothing. - */ - set path(path) { - if (isUrl(path)) { - path = urlToPath(path); - } - assertNonEmpty(path, "path"); - if (this.path !== path) { - this.history.push(path); - } - } - /** - * Get the stem (basename w/o extname) (example: `'index.min'`). - * - * @returns {string | undefined} - * Stem. - */ - get stem() { - return typeof this.path === "string" ? minpath.basename(this.path, this.extname) : void 0; - } - /** - * Set the stem (basename w/o extname) (example: `'index.min'`). - * - * Cannot contain path separators (`'/'` on unix, macOS, and browsers, `'\'` - * on windows). - * Cannot be nullified (use `file.path = file.dirname` instead). - * - * @param {string} stem - * Stem. - * @returns {undefined} - * Nothing. - */ - set stem(stem) { - assertNonEmpty(stem, "stem"); - assertPart(stem, "stem"); - this.path = minpath.join(this.dirname || "", stem + (this.extname || "")); - } - // Normal prototypal methods. - /** - * Create a fatal message for `reason` associated with the file. - * - * The `fatal` field of the message is set to `true` (error; file not usable) - * and the `file` field is set to the current file path. - * The message is added to the `messages` field on `file`. - * - * > 🪦 **Note**: also has obsolete signatures. - * - * @overload - * @param {string} reason - * @param {MessageOptions | null | undefined} [options] - * @returns {never} - * - * @overload - * @param {string} reason - * @param {Node | NodeLike | null | undefined} parent - * @param {string | null | undefined} [origin] - * @returns {never} - * - * @overload - * @param {string} reason - * @param {Point | Position | null | undefined} place - * @param {string | null | undefined} [origin] - * @returns {never} - * - * @overload - * @param {string} reason - * @param {string | null | undefined} [origin] - * @returns {never} - * - * @overload - * @param {Error | VFileMessage} cause - * @param {Node | NodeLike | null | undefined} parent - * @param {string | null | undefined} [origin] - * @returns {never} - * - * @overload - * @param {Error | VFileMessage} cause - * @param {Point | Position | null | undefined} place - * @param {string | null | undefined} [origin] - * @returns {never} - * - * @overload - * @param {Error | VFileMessage} cause - * @param {string | null | undefined} [origin] - * @returns {never} - * - * @param {Error | VFileMessage | string} causeOrReason - * Reason for message, should use markdown. - * @param {Node | NodeLike | MessageOptions | Point | Position | string | null | undefined} [optionsOrParentOrPlace] - * Configuration (optional). - * @param {string | null | undefined} [origin] - * Place in code where the message originates (example: - * `'my-package:my-rule'` or `'my-rule'`). - * @returns {never} - * Never. - * @throws {VFileMessage} - * Message. - */ - fail(causeOrReason, optionsOrParentOrPlace, origin) { - const message = this.message(causeOrReason, optionsOrParentOrPlace, origin); - message.fatal = true; - throw message; - } - /** - * Create an info message for `reason` associated with the file. - * - * The `fatal` field of the message is set to `undefined` (info; change - * likely not needed) and the `file` field is set to the current file path. - * The message is added to the `messages` field on `file`. - * - * > 🪦 **Note**: also has obsolete signatures. - * - * @overload - * @param {string} reason - * @param {MessageOptions | null | undefined} [options] - * @returns {VFileMessage} - * - * @overload - * @param {string} reason - * @param {Node | NodeLike | null | undefined} parent - * @param {string | null | undefined} [origin] - * @returns {VFileMessage} - * - * @overload - * @param {string} reason - * @param {Point | Position | null | undefined} place - * @param {string | null | undefined} [origin] - * @returns {VFileMessage} - * - * @overload - * @param {string} reason - * @param {string | null | undefined} [origin] - * @returns {VFileMessage} - * - * @overload - * @param {Error | VFileMessage} cause - * @param {Node | NodeLike | null | undefined} parent - * @param {string | null | undefined} [origin] - * @returns {VFileMessage} - * - * @overload - * @param {Error | VFileMessage} cause - * @param {Point | Position | null | undefined} place - * @param {string | null | undefined} [origin] - * @returns {VFileMessage} - * - * @overload - * @param {Error | VFileMessage} cause - * @param {string | null | undefined} [origin] - * @returns {VFileMessage} - * - * @param {Error | VFileMessage | string} causeOrReason - * Reason for message, should use markdown. - * @param {Node | NodeLike | MessageOptions | Point | Position | string | null | undefined} [optionsOrParentOrPlace] - * Configuration (optional). - * @param {string | null | undefined} [origin] - * Place in code where the message originates (example: - * `'my-package:my-rule'` or `'my-rule'`). - * @returns {VFileMessage} - * Message. - */ - info(causeOrReason, optionsOrParentOrPlace, origin) { - const message = this.message(causeOrReason, optionsOrParentOrPlace, origin); - message.fatal = void 0; - return message; - } - /** - * Create a message for `reason` associated with the file. - * - * The `fatal` field of the message is set to `false` (warning; change may be - * needed) and the `file` field is set to the current file path. - * The message is added to the `messages` field on `file`. - * - * > 🪦 **Note**: also has obsolete signatures. - * - * @overload - * @param {string} reason - * @param {MessageOptions | null | undefined} [options] - * @returns {VFileMessage} - * - * @overload - * @param {string} reason - * @param {Node | NodeLike | null | undefined} parent - * @param {string | null | undefined} [origin] - * @returns {VFileMessage} - * - * @overload - * @param {string} reason - * @param {Point | Position | null | undefined} place - * @param {string | null | undefined} [origin] - * @returns {VFileMessage} - * - * @overload - * @param {string} reason - * @param {string | null | undefined} [origin] - * @returns {VFileMessage} - * - * @overload - * @param {Error | VFileMessage} cause - * @param {Node | NodeLike | null | undefined} parent - * @param {string | null | undefined} [origin] - * @returns {VFileMessage} - * - * @overload - * @param {Error | VFileMessage} cause - * @param {Point | Position | null | undefined} place - * @param {string | null | undefined} [origin] - * @returns {VFileMessage} - * - * @overload - * @param {Error | VFileMessage} cause - * @param {string | null | undefined} [origin] - * @returns {VFileMessage} - * - * @param {Error | VFileMessage | string} causeOrReason - * Reason for message, should use markdown. - * @param {Node | NodeLike | MessageOptions | Point | Position | string | null | undefined} [optionsOrParentOrPlace] - * Configuration (optional). - * @param {string | null | undefined} [origin] - * Place in code where the message originates (example: - * `'my-package:my-rule'` or `'my-rule'`). - * @returns {VFileMessage} - * Message. - */ - message(causeOrReason, optionsOrParentOrPlace, origin) { - const message = new VFileMessage( - // @ts-expect-error: the overloads are fine. - causeOrReason, - optionsOrParentOrPlace, - origin - ); - if (this.path) { - message.name = this.path + ":" + message.name; - message.file = this.path; - } - message.fatal = false; - this.messages.push(message); - return message; - } - /** - * Serialize the file. - * - * > **Note**: which encodings are supported depends on the engine. - * > For info on Node.js, see: - * > . - * - * @param {string | null | undefined} [encoding='utf8'] - * Character encoding to understand `value` as when it’s a `Uint8Array` - * (default: `'utf-8'`). - * @returns {string} - * Serialized file. - */ - toString(encoding) { - if (this.value === void 0) { - return ""; - } - if (typeof this.value === "string") { - return this.value; - } - const decoder = new TextDecoder(encoding || void 0); - return decoder.decode(this.value); - } -}; -function assertPart(part, name) { - if (part && part.includes(minpath.sep)) { - throw new Error( - "`" + name + "` cannot be a path: did not expect `" + minpath.sep + "`" - ); - } -} -function assertNonEmpty(part, name) { - if (!part) { - throw new Error("`" + name + "` cannot be empty"); - } -} -function assertPath2(path, name) { - if (!path) { - throw new Error("Setting `" + name + "` requires `path` to be set too"); - } -} -function isUint8Array(value) { - return Boolean( - value && typeof value === "object" && "byteLength" in value && "byteOffset" in value - ); -} - -// node_modules/unified/lib/callable-instance.js -var CallableInstance = ( - /** - * @type {new , Result>(property: string | symbol) => (...parameters: Parameters) => Result} - */ - /** @type {unknown} */ - /** - * @this {Function} - * @param {string | symbol} property - * @returns {(...parameters: Array) => unknown} - */ - function(property) { - const self = this; - const constr = self.constructor; - const proto = ( - /** @type {Record} */ - // Prototypes do exist. - // type-coverage:ignore-next-line - constr.prototype - ); - const value = proto[property]; - const apply = function() { - return value.apply(apply, arguments); - }; - Object.setPrototypeOf(apply, proto); - return apply; - } -); - -// node_modules/unified/lib/index.js -var own = {}.hasOwnProperty; -var Processor = class _Processor extends CallableInstance { - /** - * Create a processor. - */ - constructor() { - super("copy"); - this.Compiler = void 0; - this.Parser = void 0; - this.attachers = []; - this.compiler = void 0; - this.freezeIndex = -1; - this.frozen = void 0; - this.namespace = {}; - this.parser = void 0; - this.transformers = trough(); - } - /** - * Copy a processor. - * - * @deprecated - * This is a private internal method and should not be used. - * @returns {Processor} - * New *unfrozen* processor ({@linkcode Processor}) that is - * configured to work the same as its ancestor. - * When the descendant processor is configured in the future it does not - * affect the ancestral processor. - */ - copy() { - const destination = ( - /** @type {Processor} */ - new _Processor() - ); - let index2 = -1; - while (++index2 < this.attachers.length) { - const attacher = this.attachers[index2]; - destination.use(...attacher); - } - destination.data((0, import_extend.default)(true, {}, this.namespace)); - return destination; - } - /** - * Configure the processor with info available to all plugins. - * Information is stored in an object. - * - * Typically, options can be given to a specific plugin, but sometimes it - * makes sense to have information shared with several plugins. - * For example, a list of HTML elements that are self-closing, which is - * needed during all phases. - * - * > **Note**: setting information cannot occur on *frozen* processors. - * > Call the processor first to create a new unfrozen processor. - * - * > **Note**: to register custom data in TypeScript, augment the - * > {@linkcode Data} interface. - * - * @example - * This example show how to get and set info: - * - * ```js - * import {unified} from 'unified' - * - * const processor = unified().data('alpha', 'bravo') - * - * processor.data('alpha') // => 'bravo' - * - * processor.data() // => {alpha: 'bravo'} - * - * processor.data({charlie: 'delta'}) - * - * processor.data() // => {charlie: 'delta'} - * ``` - * - * @template {keyof Data} Key - * - * @overload - * @returns {Data} - * - * @overload - * @param {Data} dataset - * @returns {Processor} - * - * @overload - * @param {Key} key - * @returns {Data[Key]} - * - * @overload - * @param {Key} key - * @param {Data[Key]} value - * @returns {Processor} - * - * @param {Data | Key} [key] - * Key to get or set, or entire dataset to set, or nothing to get the - * entire dataset (optional). - * @param {Data[Key]} [value] - * Value to set (optional). - * @returns {unknown} - * The current processor when setting, the value at `key` when getting, or - * the entire dataset when getting without key. - */ - data(key, value) { - if (typeof key === "string") { - if (arguments.length === 2) { - assertUnfrozen("data", this.frozen); - this.namespace[key] = value; - return this; - } - return own.call(this.namespace, key) && this.namespace[key] || void 0; - } - if (key) { - assertUnfrozen("data", this.frozen); - this.namespace = key; - return this; - } - return this.namespace; - } - /** - * Freeze a processor. - * - * Frozen processors are meant to be extended and not to be configured - * directly. - * - * When a processor is frozen it cannot be unfrozen. - * New processors working the same way can be created by calling the - * processor. - * - * It’s possible to freeze processors explicitly by calling `.freeze()`. - * Processors freeze automatically when `.parse()`, `.run()`, `.runSync()`, - * `.stringify()`, `.process()`, or `.processSync()` are called. - * - * @returns {Processor} - * The current processor. - */ - freeze() { - if (this.frozen) { - return this; - } - const self = ( - /** @type {Processor} */ - /** @type {unknown} */ - this - ); - while (++this.freezeIndex < this.attachers.length) { - const [attacher, ...options] = this.attachers[this.freezeIndex]; - if (options[0] === false) { - continue; - } - if (options[0] === true) { - options[0] = void 0; - } - const transformer = attacher.call(self, ...options); - if (typeof transformer === "function") { - this.transformers.use(transformer); - } - } - this.frozen = true; - this.freezeIndex = Number.POSITIVE_INFINITY; - return this; - } - /** - * Parse text to a syntax tree. - * - * > **Note**: `parse` freezes the processor if not already *frozen*. - * - * > **Note**: `parse` performs the parse phase, not the run phase or other - * > phases. - * - * @param {Compatible | undefined} [file] - * file to parse (optional); typically `string` or `VFile`; any value - * accepted as `x` in `new VFile(x)`. - * @returns {ParseTree extends undefined ? Node : ParseTree} - * Syntax tree representing `file`. - */ - parse(file) { - this.freeze(); - const realFile = vfile(file); - const parser = this.parser || this.Parser; - assertParser("parse", parser); - return parser(String(realFile), realFile); - } - /** - * Process the given file as configured on the processor. - * - * > **Note**: `process` freezes the processor if not already *frozen*. - * - * > **Note**: `process` performs the parse, run, and stringify phases. - * - * @overload - * @param {Compatible | undefined} file - * @param {ProcessCallback>} done - * @returns {undefined} - * - * @overload - * @param {Compatible | undefined} [file] - * @returns {Promise>} - * - * @param {Compatible | undefined} [file] - * File (optional); typically `string` or `VFile`]; any value accepted as - * `x` in `new VFile(x)`. - * @param {ProcessCallback> | undefined} [done] - * Callback (optional). - * @returns {Promise | undefined} - * Nothing if `done` is given. - * Otherwise a promise, rejected with a fatal error or resolved with the - * processed file. - * - * The parsed, transformed, and compiled value is available at - * `file.value` (see note). - * - * > **Note**: unified typically compiles by serializing: most - * > compilers return `string` (or `Uint8Array`). - * > Some compilers, such as the one configured with - * > [`rehype-react`][rehype-react], return other values (in this case, a - * > React tree). - * > If you’re using a compiler that doesn’t serialize, expect different - * > result values. - * > - * > To register custom results in TypeScript, add them to - * > {@linkcode CompileResultMap}. - * - * [rehype-react]: https://github.com/rehypejs/rehype-react - */ - process(file, done) { - const self = this; - this.freeze(); - assertParser("process", this.parser || this.Parser); - assertCompiler("process", this.compiler || this.Compiler); - return done ? executor(void 0, done) : new Promise(executor); - function executor(resolve, reject) { - const realFile = vfile(file); - const parseTree = ( - /** @type {HeadTree extends undefined ? Node : HeadTree} */ - /** @type {unknown} */ - self.parse(realFile) - ); - self.run(parseTree, realFile, function(error, tree, file2) { - if (error || !tree || !file2) { - return realDone(error); - } - const compileTree = ( - /** @type {CompileTree extends undefined ? Node : CompileTree} */ - /** @type {unknown} */ - tree - ); - const compileResult = self.stringify(compileTree, file2); - if (looksLikeAValue(compileResult)) { - file2.value = compileResult; - } else { - file2.result = compileResult; - } - realDone( - error, - /** @type {VFileWithOutput} */ - file2 - ); - }); - function realDone(error, file2) { - if (error || !file2) { - reject(error); - } else if (resolve) { - resolve(file2); - } else { - ok2(done, "`done` is defined if `resolve` is not"); - done(void 0, file2); - } - } - } - } - /** - * Process the given file as configured on the processor. - * - * An error is thrown if asynchronous transforms are configured. - * - * > **Note**: `processSync` freezes the processor if not already *frozen*. - * - * > **Note**: `processSync` performs the parse, run, and stringify phases. - * - * @param {Compatible | undefined} [file] - * File (optional); typically `string` or `VFile`; any value accepted as - * `x` in `new VFile(x)`. - * @returns {VFileWithOutput} - * The processed file. - * - * The parsed, transformed, and compiled value is available at - * `file.value` (see note). - * - * > **Note**: unified typically compiles by serializing: most - * > compilers return `string` (or `Uint8Array`). - * > Some compilers, such as the one configured with - * > [`rehype-react`][rehype-react], return other values (in this case, a - * > React tree). - * > If you’re using a compiler that doesn’t serialize, expect different - * > result values. - * > - * > To register custom results in TypeScript, add them to - * > {@linkcode CompileResultMap}. - * - * [rehype-react]: https://github.com/rehypejs/rehype-react - */ - processSync(file) { - let complete = false; - let result; - this.freeze(); - assertParser("processSync", this.parser || this.Parser); - assertCompiler("processSync", this.compiler || this.Compiler); - this.process(file, realDone); - assertDone("processSync", "process", complete); - ok2(result, "we either bailed on an error or have a tree"); - return result; - function realDone(error, file2) { - complete = true; - bail(error); - result = file2; - } - } - /** - * Run *transformers* on a syntax tree. - * - * > **Note**: `run` freezes the processor if not already *frozen*. - * - * > **Note**: `run` performs the run phase, not other phases. - * - * @overload - * @param {HeadTree extends undefined ? Node : HeadTree} tree - * @param {RunCallback} done - * @returns {undefined} - * - * @overload - * @param {HeadTree extends undefined ? Node : HeadTree} tree - * @param {Compatible | undefined} file - * @param {RunCallback} done - * @returns {undefined} - * - * @overload - * @param {HeadTree extends undefined ? Node : HeadTree} tree - * @param {Compatible | undefined} [file] - * @returns {Promise} - * - * @param {HeadTree extends undefined ? Node : HeadTree} tree - * Tree to transform and inspect. - * @param {( - * RunCallback | - * Compatible - * )} [file] - * File associated with `node` (optional); any value accepted as `x` in - * `new VFile(x)`. - * @param {RunCallback} [done] - * Callback (optional). - * @returns {Promise | undefined} - * Nothing if `done` is given. - * Otherwise, a promise rejected with a fatal error or resolved with the - * transformed tree. - */ - run(tree, file, done) { - assertNode(tree); - this.freeze(); - const transformers = this.transformers; - if (!done && typeof file === "function") { - done = file; - file = void 0; - } - return done ? executor(void 0, done) : new Promise(executor); - function executor(resolve, reject) { - ok2( - typeof file !== "function", - "`file` can’t be a `done` anymore, we checked" - ); - const realFile = vfile(file); - transformers.run(tree, realFile, realDone); - function realDone(error, outputTree, file2) { - const resultingTree = ( - /** @type {TailTree extends undefined ? Node : TailTree} */ - outputTree || tree - ); - if (error) { - reject(error); - } else if (resolve) { - resolve(resultingTree); - } else { - ok2(done, "`done` is defined if `resolve` is not"); - done(void 0, resultingTree, file2); - } - } - } - } - /** - * Run *transformers* on a syntax tree. - * - * An error is thrown if asynchronous transforms are configured. - * - * > **Note**: `runSync` freezes the processor if not already *frozen*. - * - * > **Note**: `runSync` performs the run phase, not other phases. - * - * @param {HeadTree extends undefined ? Node : HeadTree} tree - * Tree to transform and inspect. - * @param {Compatible | undefined} [file] - * File associated with `node` (optional); any value accepted as `x` in - * `new VFile(x)`. - * @returns {TailTree extends undefined ? Node : TailTree} - * Transformed tree. - */ - runSync(tree, file) { - let complete = false; - let result; - this.run(tree, file, realDone); - assertDone("runSync", "run", complete); - ok2(result, "we either bailed on an error or have a tree"); - return result; - function realDone(error, tree2) { - bail(error); - result = tree2; - complete = true; - } - } - /** - * Compile a syntax tree. - * - * > **Note**: `stringify` freezes the processor if not already *frozen*. - * - * > **Note**: `stringify` performs the stringify phase, not the run phase - * > or other phases. - * - * @param {CompileTree extends undefined ? Node : CompileTree} tree - * Tree to compile. - * @param {Compatible | undefined} [file] - * File associated with `node` (optional); any value accepted as `x` in - * `new VFile(x)`. - * @returns {CompileResult extends undefined ? Value : CompileResult} - * Textual representation of the tree (see note). - * - * > **Note**: unified typically compiles by serializing: most compilers - * > return `string` (or `Uint8Array`). - * > Some compilers, such as the one configured with - * > [`rehype-react`][rehype-react], return other values (in this case, a - * > React tree). - * > If you’re using a compiler that doesn’t serialize, expect different - * > result values. - * > - * > To register custom results in TypeScript, add them to - * > {@linkcode CompileResultMap}. - * - * [rehype-react]: https://github.com/rehypejs/rehype-react - */ - stringify(tree, file) { - this.freeze(); - const realFile = vfile(file); - const compiler = this.compiler || this.Compiler; - assertCompiler("stringify", compiler); - assertNode(tree); - return compiler(tree, realFile); - } - /** - * Configure the processor to use a plugin, a list of usable values, or a - * preset. - * - * If the processor is already using a plugin, the previous plugin - * configuration is changed based on the options that are passed in. - * In other words, the plugin is not added a second time. - * - * > **Note**: `use` cannot be called on *frozen* processors. - * > Call the processor first to create a new unfrozen processor. - * - * @example - * There are many ways to pass plugins to `.use()`. - * This example gives an overview: - * - * ```js - * import {unified} from 'unified' - * - * unified() - * // Plugin with options: - * .use(pluginA, {x: true, y: true}) - * // Passing the same plugin again merges configuration (to `{x: true, y: false, z: true}`): - * .use(pluginA, {y: false, z: true}) - * // Plugins: - * .use([pluginB, pluginC]) - * // Two plugins, the second with options: - * .use([pluginD, [pluginE, {}]]) - * // Preset with plugins and settings: - * .use({plugins: [pluginF, [pluginG, {}]], settings: {position: false}}) - * // Settings only: - * .use({settings: {position: false}}) - * ``` - * - * @template {Array} [Parameters=[]] - * @template {Node | string | undefined} [Input=undefined] - * @template [Output=Input] - * - * @overload - * @param {Preset | null | undefined} [preset] - * @returns {Processor} - * - * @overload - * @param {PluggableList} list - * @returns {Processor} - * - * @overload - * @param {Plugin} plugin - * @param {...(Parameters | [boolean])} parameters - * @returns {UsePlugin} - * - * @param {PluggableList | Plugin | Preset | null | undefined} value - * Usable value. - * @param {...unknown} parameters - * Parameters, when a plugin is given as a usable value. - * @returns {Processor} - * Current processor. - */ - use(value, ...parameters) { - const attachers = this.attachers; - const namespace = this.namespace; - assertUnfrozen("use", this.frozen); - if (value === null || value === void 0) { - } else if (typeof value === "function") { - addPlugin(value, parameters); - } else if (typeof value === "object") { - if (Array.isArray(value)) { - addList(value); - } else { - addPreset(value); - } - } else { - throw new TypeError("Expected usable value, not `" + value + "`"); - } - return this; - function add2(value2) { - if (typeof value2 === "function") { - addPlugin(value2, []); - } else if (typeof value2 === "object") { - if (Array.isArray(value2)) { - const [plugin, ...parameters2] = ( - /** @type {PluginTuple>} */ - value2 - ); - addPlugin(plugin, parameters2); - } else { - addPreset(value2); - } - } else { - throw new TypeError("Expected usable value, not `" + value2 + "`"); - } - } - function addPreset(result) { - if (!("plugins" in result) && !("settings" in result)) { - throw new Error( - "Expected usable value but received an empty preset, which is probably a mistake: presets typically come with `plugins` and sometimes with `settings`, but this has neither" - ); - } - addList(result.plugins); - if (result.settings) { - namespace.settings = (0, import_extend.default)(true, namespace.settings, result.settings); - } - } - function addList(plugins) { - let index2 = -1; - if (plugins === null || plugins === void 0) { - } else if (Array.isArray(plugins)) { - while (++index2 < plugins.length) { - const thing = plugins[index2]; - add2(thing); - } - } else { - throw new TypeError("Expected a list of plugins, not `" + plugins + "`"); - } - } - function addPlugin(plugin, parameters2) { - let index2 = -1; - let entryIndex = -1; - while (++index2 < attachers.length) { - if (attachers[index2][0] === plugin) { - entryIndex = index2; - break; - } - } - if (entryIndex === -1) { - attachers.push([plugin, ...parameters2]); - } else if (parameters2.length > 0) { - let [primary, ...rest] = parameters2; - const currentPrimary = attachers[entryIndex][1]; - if (isPlainObject(currentPrimary) && isPlainObject(primary)) { - primary = (0, import_extend.default)(true, currentPrimary, primary); - } - attachers[entryIndex] = [plugin, primary, ...rest]; - } - } - } -}; -var unified = new Processor().freeze(); -function assertParser(name, value) { - if (typeof value !== "function") { - throw new TypeError("Cannot `" + name + "` without `parser`"); - } -} -function assertCompiler(name, value) { - if (typeof value !== "function") { - throw new TypeError("Cannot `" + name + "` without `compiler`"); - } -} -function assertUnfrozen(name, frozen) { - if (frozen) { - throw new Error( - "Cannot call `" + name + "` on a frozen processor.\nCreate a new processor first, by calling it: use `processor()` instead of `processor`." - ); - } -} -function assertNode(node) { - if (!isPlainObject(node) || typeof node.type !== "string") { - throw new TypeError("Expected node, got `" + node + "`"); - } -} -function assertDone(name, asyncName, complete) { - if (!complete) { - throw new Error( - "`" + name + "` finished async. Use `" + asyncName + "` instead" - ); - } -} -function vfile(value) { - return looksLikeAVFile(value) ? value : new VFile(value); -} -function looksLikeAVFile(value) { - return Boolean( - value && typeof value === "object" && "message" in value && "messages" in value - ); -} -function looksLikeAValue(value) { - return typeof value === "string" || isUint8Array2(value); -} -function isUint8Array2(value) { - return Boolean( - value && typeof value === "object" && "byteLength" in value && "byteOffset" in value - ); -} - -// node_modules/applesauce-content/dist/helpers/regexp.js -var Expressions = { - get url() { - return /(?:https?|wss?|ircs?|s?ftp):\/\/([a-zA-Z0-9\.\-]+\.[a-zA-Z]+(?::\d+)?)([\/\?#][\p{L}\p{N}\p{M}&\.-\/\?=#\-@%\+_,:!~*]*)?/gu; - }, - get link() { - return /https?:\/\/([a-zA-Z0-9\.\-]+\.[a-zA-Z]+(?::\d+)?)([\/\?#][\p{L}\p{N}\p{M}&\.-\/\?=#\-@%\+_,:!~*]*)?/gu; - }, - get cashu() { - return /(?:cashu:\/{0,2})?(cashu(?:A|B)[A-Za-z0-9_-]{100,}={0,3})/gi; - }, - get nostrLink() { - return /(?:nostr:)?((npub|note|nprofile|nevent|naddr)1[qpzry9x8gf2tvdw0s3jn54khce6mua7l]{58,})/gi; - }, - get emoji() { - return /:([a-zA-Z0-9_-]+):/gi; - }, - get hashtag() { - return new RegExp("(?<=^|[^\\p{L}#\\/])#([\\p{L}\\p{N}\\p{M}]+)(?=\\p{Z}|$|\\s)", "gu"); - }, - get lightning() { - return /(?:lightning:)?(LNBC[A-Za-z0-9]+)/gim; - } -}; -var Tokens = { - get url() { - return Expressions.url; - }, - get link() { - return Expressions.link; - }, - get cashu() { - return new RegExp(`(?<=^|\\s)${Expressions.cashu.source}`, "gi"); - }, - get nostrLink() { - return new RegExp(`(?<=^|\\s)${Expressions.nostrLink.source}`, "gi"); - }, - get emoji() { - return Expressions.emoji; - }, - get hashtag() { - return Expressions.hashtag; - }, - get lightning() { - return new RegExp(`(?<=^|\\s)${Expressions.lightning.source}`, "gim"); - } -}; - -// node_modules/applesauce-content/dist/text/mentions.js -function nostrMentions() { - return (tree) => { - findAndReplace(tree, [ - [ - Tokens.nostrLink, - (_, $1) => { - try { - return { - type: "mention", - decoded: decode($1), - encoded: $1 - }; - } catch (error) { - } - return false; - } - ] - ]); - }; -} - -// node_modules/@cashu/cashu-ts/dist/lib/es6/model/types/mint/responses.js -var CheckStateEnum; -(function(CheckStateEnum2) { - CheckStateEnum2["UNSPENT"] = "UNSPENT"; - CheckStateEnum2["PENDING"] = "PENDING"; - CheckStateEnum2["SPENT"] = "SPENT"; -})(CheckStateEnum || (CheckStateEnum = {})); -var MeltQuoteState; -(function(MeltQuoteState2) { - MeltQuoteState2["UNPAID"] = "UNPAID"; - MeltQuoteState2["PENDING"] = "PENDING"; - MeltQuoteState2["PAID"] = "PAID"; -})(MeltQuoteState || (MeltQuoteState = {})); -var MintQuoteState; -(function(MintQuoteState2) { - MintQuoteState2["UNPAID"] = "UNPAID"; - MintQuoteState2["PAID"] = "PAID"; - MintQuoteState2["ISSUED"] = "ISSUED"; -})(MintQuoteState || (MintQuoteState = {})); - -// node_modules/@cashu/cashu-ts/dist/lib/es6/model/types/wallet/paymentRequests.js -var PaymentRequestTransportType; -(function(PaymentRequestTransportType2) { - PaymentRequestTransportType2["POST"] = "post"; - PaymentRequestTransportType2["NOSTR"] = "nostr"; -})(PaymentRequestTransportType || (PaymentRequestTransportType = {})); - -// node_modules/@cashu/cashu-ts/dist/lib/es6/model/Errors.js -var __extends = /* @__PURE__ */ function() { - var extendStatics = function(d, b) { - extendStatics = Object.setPrototypeOf || { __proto__: [] } instanceof Array && function(d2, b2) { - d2.__proto__ = b2; - } || function(d2, b2) { - for (var p in b2) if (Object.prototype.hasOwnProperty.call(b2, p)) d2[p] = b2[p]; - }; - return extendStatics(d, b); - }; - return function(d, b) { - if (typeof b !== "function" && b !== null) - throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); - extendStatics(d, b); - function __() { - this.constructor = d; - } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); - }; -}(); -var HttpResponseError = ( - /** @class */ - function(_super) { - __extends(HttpResponseError2, _super); - function HttpResponseError2(message, status) { - var _this = _super.call(this, message) || this; - _this.status = status; - return _this; - } - return HttpResponseError2; - }(Error) -); - -// node_modules/@cashu/cashu-ts/dist/lib/es6/request.js -var __assign = function() { - __assign = Object.assign || function(t) { - for (var s, i = 1, n = arguments.length; i < n; i++) { - s = arguments[i]; - for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) - t[p] = s[p]; - } - return t; - }; - return __assign.apply(this, arguments); -}; -var __awaiter = function(thisArg, _arguments, P, generator) { - function adopt(value) { - return value instanceof P ? value : new P(function(resolve) { - resolve(value); - }); - } - return new (P || (P = Promise))(function(resolve, reject) { - function fulfilled(value) { - try { - step(generator.next(value)); - } catch (e) { - reject(e); - } - } - function rejected(value) { - try { - step(generator["throw"](value)); - } catch (e) { - reject(e); - } - } - function step(result) { - result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); - } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -var __generator = function(thisArg, body) { - var _ = { label: 0, sent: function() { - if (t[0] & 1) throw t[1]; - return t[1]; - }, trys: [], ops: [] }, f, y, t, g; - return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { - return this; - }), g; - function verb(n) { - return function(v) { - return step([n, v]); - }; - } - function step(op) { - if (f) throw new TypeError("Generator is already executing."); - while (g && (g = 0, op[0] && (_ = 0)), _) try { - if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; - if (y = 0, t) op = [op[0] & 2, t.value]; - switch (op[0]) { - case 0: - case 1: - t = op; - break; - case 4: - _.label++; - return { value: op[1], done: false }; - case 5: - _.label++; - y = op[1]; - op = [0]; - continue; - case 7: - op = _.ops.pop(); - _.trys.pop(); - continue; - default: - if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { - _ = 0; - continue; - } - if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) { - _.label = op[1]; - break; - } - if (op[0] === 6 && _.label < t[1]) { - _.label = t[1]; - t = op; - break; - } - if (t && _.label < t[2]) { - _.label = t[2]; - _.ops.push(op); - break; - } - if (t[2]) _.ops.pop(); - _.trys.pop(); - continue; - } - op = body.call(thisArg, _); - } catch (e) { - op = [6, e]; - y = 0; - } finally { - f = t = 0; - } - if (op[0] & 5) throw op[1]; - return { value: op[0] ? op[1] : void 0, done: true }; - } -}; -var __rest = function(s, e) { - var t = {}; - for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) - t[p] = s[p]; - if (s != null && typeof Object.getOwnPropertySymbols === "function") - for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) { - if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) - t[p[i]] = s[p[i]]; - } - return t; -}; -var globalRequestOptions = {}; -function _request(_a) { - var endpoint = _a.endpoint, requestBody = _a.requestBody, requestHeaders = _a.headers, options = __rest(_a, ["endpoint", "requestBody", "headers"]); - return __awaiter(this, void 0, void 0, function() { - var body, headers, response, _b, error, detail, err_1; - return __generator(this, function(_c) { - switch (_c.label) { - case 0: - body = requestBody ? JSON.stringify(requestBody) : void 0; - headers = __assign(__assign({ Accept: "application/json, text/plain, */*" }, body ? { "Content-Type": "application/json" } : void 0), requestHeaders); - return [4, fetch(endpoint, __assign({ body, headers }, options))]; - case 1: - response = _c.sent(); - if (!!response.ok) return [3, 3]; - return [4, response.json().catch(function() { - return { error: "bad response" }; - })]; - case 2: - _b = _c.sent(), error = _b.error, detail = _b.detail; - throw new HttpResponseError(error || detail || "bad response", response.status); - case 3: - _c.trys.push([3, 5, , 6]); - return [4, response.json()]; - case 4: - return [2, _c.sent()]; - case 5: - err_1 = _c.sent(); - console.error("Failed to parse HTTP response", err_1); - throw new HttpResponseError("bad response", response.status); - case 6: - return [ - 2 - /*return*/ - ]; - } - }); - }); -} -function request(options) { - return __awaiter(this, void 0, void 0, function() { - var data; - return __generator(this, function(_a) { - switch (_a.label) { - case 0: - return [4, _request(__assign(__assign({}, options), globalRequestOptions))]; - case 1: - data = _a.sent(); - return [2, data]; - } - }); - }); -} - -// node_modules/@cashu/cashu-ts/dist/lib/es6/base64.js -var import_buffer = __toESM(require_buffer()); -function encodeBase64toUint8(base64String) { - return import_buffer.Buffer.from(base64String, "base64"); -} -function encodeBase64ToJson(base64String) { - var jsonString = import_buffer.Buffer.from(base64urlToBase64(base64String), "base64").toString(); - var jsonObj = JSON.parse(jsonString); - return jsonObj; -} -function base64urlToBase64(str) { - return str.replace(/-/g, "+").replace(/_/g, "/").split("=")[0]; -} - -// node_modules/@noble/curves/esm/utils.js -var _0n = BigInt(0); -var _1n = BigInt(1); - -// node_modules/@noble/curves/esm/abstract/utils.js -var bytesToHex2 = bytesToHex; - -// node_modules/@noble/hashes/esm/_md.js -function setBigUint64(view, byteOffset, value, isLE) { - if (typeof view.setBigUint64 === "function") - return view.setBigUint64(byteOffset, value, isLE); - const _32n2 = BigInt(32); - const _u32_max = BigInt(4294967295); - const wh = Number(value >> _32n2 & _u32_max); - const wl = Number(value & _u32_max); - const h = isLE ? 4 : 0; - const l = isLE ? 0 : 4; - view.setUint32(byteOffset + h, wh, isLE); - view.setUint32(byteOffset + l, wl, isLE); -} -function Chi(a, b, c) { - return a & b ^ ~a & c; -} -function Maj(a, b, c) { - return a & b ^ a & c ^ b & c; -} -var HashMD = class extends Hash { - constructor(blockLen, outputLen, padOffset, isLE) { - super(); - this.finished = false; - this.length = 0; - this.pos = 0; - this.destroyed = false; - this.blockLen = blockLen; - this.outputLen = outputLen; - this.padOffset = padOffset; - this.isLE = isLE; - this.buffer = new Uint8Array(blockLen); - this.view = createView(this.buffer); - } - update(data) { - aexists(this); - data = toBytes(data); - abytes(data); - const { view, buffer, blockLen } = this; - const len = data.length; - for (let pos = 0; pos < len; ) { - const take = Math.min(blockLen - this.pos, len - pos); - if (take === blockLen) { - const dataView = createView(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) { - aexists(this); - aoutput(out, this); - this.finished = true; - const { buffer, view, blockLen, isLE } = this; - let { pos } = this; - buffer[pos++] = 128; - clean(this.buffer.subarray(pos)); - if (this.padOffset > blockLen - pos) { - this.process(view, 0); - pos = 0; - } - for (let i = pos; i < blockLen; i++) - buffer[i] = 0; - setBigUint64(view, blockLen - 8, BigInt(this.length * 8), isLE); - this.process(view, 0); - const oview = createView(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 i = 0; i < outLen; i++) - oview.setUint32(4 * i, state[i], isLE); - } - 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.destroyed = destroyed; - to.finished = finished; - to.length = length; - to.pos = pos; - if (length % blockLen) - to.buffer.set(buffer); - return to; - } - clone() { - return this._cloneInto(); - } -}; -var SHA256_IV = Uint32Array.from([ - 1779033703, - 3144134277, - 1013904242, - 2773480762, - 1359893119, - 2600822924, - 528734635, - 1541459225 -]); -var SHA224_IV = Uint32Array.from([ - 3238371032, - 914150663, - 812702999, - 4144912697, - 4290775857, - 1750603025, - 1694076839, - 3204075428 -]); -var SHA384_IV = Uint32Array.from([ - 3418070365, - 3238371032, - 1654270250, - 914150663, - 2438529370, - 812702999, - 355462360, - 4144912697, - 1731405415, - 4290775857, - 2394180231, - 1750603025, - 3675008525, - 1694076839, - 1203062813, - 3204075428 -]); -var SHA512_IV = Uint32Array.from([ - 1779033703, - 4089235720, - 3144134277, - 2227873595, - 1013904242, - 4271175723, - 2773480762, - 1595750129, - 1359893119, - 2917565137, - 2600822924, - 725511199, - 528734635, - 4215389547, - 1541459225, - 327033209 -]); - -// node_modules/@noble/hashes/esm/_u64.js -var U32_MASK64 = BigInt(2 ** 32 - 1); -var _32n = BigInt(32); -function fromBig(n, le = false) { - if (le) - return { h: Number(n & U32_MASK64), l: Number(n >> _32n & U32_MASK64) }; - return { h: Number(n >> _32n & U32_MASK64) | 0, l: Number(n & U32_MASK64) | 0 }; -} -function split(lst, le = false) { - const len = lst.length; - let Ah = new Uint32Array(len); - let Al = new Uint32Array(len); - for (let i = 0; i < len; i++) { - const { h, l } = fromBig(lst[i], le); - [Ah[i], Al[i]] = [h, l]; - } - return [Ah, Al]; -} -var shrSH = (h, _l, s) => h >>> s; -var shrSL = (h, l, s) => h << 32 - s | l >>> s; -var rotrSH = (h, l, s) => h >>> s | l << 32 - s; -var rotrSL = (h, l, s) => h << 32 - s | l >>> s; -var rotrBH = (h, l, s) => h << 64 - s | l >>> s - 32; -var rotrBL = (h, l, s) => h >>> s - 32 | l << 64 - s; -function add(Ah, Al, Bh, Bl) { - const l = (Al >>> 0) + (Bl >>> 0); - return { h: Ah + Bh + (l / 2 ** 32 | 0) | 0, l: l | 0 }; -} -var add3L = (Al, Bl, Cl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0); -var add3H = (low, Ah, Bh, Ch) => Ah + Bh + Ch + (low / 2 ** 32 | 0) | 0; -var add4L = (Al, Bl, Cl, Dl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0); -var add4H = (low, Ah, Bh, Ch, Dh) => Ah + Bh + Ch + Dh + (low / 2 ** 32 | 0) | 0; -var add5L = (Al, Bl, Cl, Dl, El) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0) + (El >>> 0); -var add5H = (low, Ah, Bh, Ch, Dh, Eh) => Ah + Bh + Ch + Dh + Eh + (low / 2 ** 32 | 0) | 0; - -// node_modules/@noble/hashes/esm/sha2.js -var SHA256_K = Uint32Array.from([ - 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 SHA256_W = new Uint32Array(64); -var SHA256 = class extends HashMD { - constructor(outputLen = 32) { - super(64, outputLen, 8, false); - this.A = SHA256_IV[0] | 0; - this.B = SHA256_IV[1] | 0; - this.C = SHA256_IV[2] | 0; - this.D = SHA256_IV[3] | 0; - this.E = SHA256_IV[4] | 0; - this.F = SHA256_IV[5] | 0; - this.G = SHA256_IV[6] | 0; - this.H = SHA256_IV[7] | 0; - } - get() { - const { A, B, C, D, E, F, G, H } = this; - return [A, B, C, D, E, F, G, H]; - } - // prettier-ignore - 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 i = 0; i < 16; i++, offset += 4) - SHA256_W[i] = view.getUint32(offset, false); - for (let i = 16; i < 64; i++) { - const W15 = SHA256_W[i - 15]; - const W2 = SHA256_W[i - 2]; - const s0 = rotr(W15, 7) ^ rotr(W15, 18) ^ W15 >>> 3; - const s1 = rotr(W2, 17) ^ rotr(W2, 19) ^ W2 >>> 10; - SHA256_W[i] = s1 + SHA256_W[i - 7] + s0 + SHA256_W[i - 16] | 0; - } - let { A, B, C, D, E, F, G, H } = this; - for (let i = 0; i < 64; i++) { - const sigma1 = rotr(E, 6) ^ rotr(E, 11) ^ rotr(E, 25); - const T1 = H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i] | 0; - const sigma0 = rotr(A, 2) ^ rotr(A, 13) ^ rotr(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() { - clean(SHA256_W); - } - destroy() { - this.set(0, 0, 0, 0, 0, 0, 0, 0); - clean(this.buffer); - } -}; -var SHA224 = class extends SHA256 { - constructor() { - super(28); - this.A = SHA224_IV[0] | 0; - this.B = SHA224_IV[1] | 0; - this.C = SHA224_IV[2] | 0; - this.D = SHA224_IV[3] | 0; - this.E = SHA224_IV[4] | 0; - this.F = SHA224_IV[5] | 0; - this.G = SHA224_IV[6] | 0; - this.H = SHA224_IV[7] | 0; - } -}; -var K512 = (() => split([ - "0x428a2f98d728ae22", - "0x7137449123ef65cd", - "0xb5c0fbcfec4d3b2f", - "0xe9b5dba58189dbbc", - "0x3956c25bf348b538", - "0x59f111f1b605d019", - "0x923f82a4af194f9b", - "0xab1c5ed5da6d8118", - "0xd807aa98a3030242", - "0x12835b0145706fbe", - "0x243185be4ee4b28c", - "0x550c7dc3d5ffb4e2", - "0x72be5d74f27b896f", - "0x80deb1fe3b1696b1", - "0x9bdc06a725c71235", - "0xc19bf174cf692694", - "0xe49b69c19ef14ad2", - "0xefbe4786384f25e3", - "0x0fc19dc68b8cd5b5", - "0x240ca1cc77ac9c65", - "0x2de92c6f592b0275", - "0x4a7484aa6ea6e483", - "0x5cb0a9dcbd41fbd4", - "0x76f988da831153b5", - "0x983e5152ee66dfab", - "0xa831c66d2db43210", - "0xb00327c898fb213f", - "0xbf597fc7beef0ee4", - "0xc6e00bf33da88fc2", - "0xd5a79147930aa725", - "0x06ca6351e003826f", - "0x142929670a0e6e70", - "0x27b70a8546d22ffc", - "0x2e1b21385c26c926", - "0x4d2c6dfc5ac42aed", - "0x53380d139d95b3df", - "0x650a73548baf63de", - "0x766a0abb3c77b2a8", - "0x81c2c92e47edaee6", - "0x92722c851482353b", - "0xa2bfe8a14cf10364", - "0xa81a664bbc423001", - "0xc24b8b70d0f89791", - "0xc76c51a30654be30", - "0xd192e819d6ef5218", - "0xd69906245565a910", - "0xf40e35855771202a", - "0x106aa07032bbd1b8", - "0x19a4c116b8d2d0c8", - "0x1e376c085141ab53", - "0x2748774cdf8eeb99", - "0x34b0bcb5e19b48a8", - "0x391c0cb3c5c95a63", - "0x4ed8aa4ae3418acb", - "0x5b9cca4f7763e373", - "0x682e6ff3d6b2b8a3", - "0x748f82ee5defb2fc", - "0x78a5636f43172f60", - "0x84c87814a1f0ab72", - "0x8cc702081a6439ec", - "0x90befffa23631e28", - "0xa4506cebde82bde9", - "0xbef9a3f7b2c67915", - "0xc67178f2e372532b", - "0xca273eceea26619c", - "0xd186b8c721c0c207", - "0xeada7dd6cde0eb1e", - "0xf57d4f7fee6ed178", - "0x06f067aa72176fba", - "0x0a637dc5a2c898a6", - "0x113f9804bef90dae", - "0x1b710b35131c471b", - "0x28db77f523047d84", - "0x32caab7b40c72493", - "0x3c9ebe0a15c9bebc", - "0x431d67c49c100d4c", - "0x4cc5d4becb3e42b6", - "0x597f299cfc657e2a", - "0x5fcb6fab3ad6faec", - "0x6c44198c4a475817" -].map((n) => BigInt(n))))(); -var SHA512_Kh = (() => K512[0])(); -var SHA512_Kl = (() => K512[1])(); -var SHA512_W_H = new Uint32Array(80); -var SHA512_W_L = new Uint32Array(80); -var SHA512 = class extends HashMD { - constructor(outputLen = 64) { - super(128, outputLen, 16, false); - this.Ah = SHA512_IV[0] | 0; - this.Al = SHA512_IV[1] | 0; - this.Bh = SHA512_IV[2] | 0; - this.Bl = SHA512_IV[3] | 0; - this.Ch = SHA512_IV[4] | 0; - this.Cl = SHA512_IV[5] | 0; - this.Dh = SHA512_IV[6] | 0; - this.Dl = SHA512_IV[7] | 0; - this.Eh = SHA512_IV[8] | 0; - this.El = SHA512_IV[9] | 0; - this.Fh = SHA512_IV[10] | 0; - this.Fl = SHA512_IV[11] | 0; - this.Gh = SHA512_IV[12] | 0; - this.Gl = SHA512_IV[13] | 0; - this.Hh = SHA512_IV[14] | 0; - this.Hl = SHA512_IV[15] | 0; - } - // prettier-ignore - get() { - const { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this; - return [Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl]; - } - // prettier-ignore - set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl) { - this.Ah = Ah | 0; - this.Al = Al | 0; - this.Bh = Bh | 0; - this.Bl = Bl | 0; - this.Ch = Ch | 0; - this.Cl = Cl | 0; - this.Dh = Dh | 0; - this.Dl = Dl | 0; - this.Eh = Eh | 0; - this.El = El | 0; - this.Fh = Fh | 0; - this.Fl = Fl | 0; - this.Gh = Gh | 0; - this.Gl = Gl | 0; - this.Hh = Hh | 0; - this.Hl = Hl | 0; - } - process(view, offset) { - for (let i = 0; i < 16; i++, offset += 4) { - SHA512_W_H[i] = view.getUint32(offset); - SHA512_W_L[i] = view.getUint32(offset += 4); - } - for (let i = 16; i < 80; i++) { - const W15h = SHA512_W_H[i - 15] | 0; - const W15l = SHA512_W_L[i - 15] | 0; - const s0h = rotrSH(W15h, W15l, 1) ^ rotrSH(W15h, W15l, 8) ^ shrSH(W15h, W15l, 7); - const s0l = rotrSL(W15h, W15l, 1) ^ rotrSL(W15h, W15l, 8) ^ shrSL(W15h, W15l, 7); - const W2h = SHA512_W_H[i - 2] | 0; - const W2l = SHA512_W_L[i - 2] | 0; - const s1h = rotrSH(W2h, W2l, 19) ^ rotrBH(W2h, W2l, 61) ^ shrSH(W2h, W2l, 6); - const s1l = rotrSL(W2h, W2l, 19) ^ rotrBL(W2h, W2l, 61) ^ shrSL(W2h, W2l, 6); - const SUMl = add4L(s0l, s1l, SHA512_W_L[i - 7], SHA512_W_L[i - 16]); - const SUMh = add4H(SUMl, s0h, s1h, SHA512_W_H[i - 7], SHA512_W_H[i - 16]); - SHA512_W_H[i] = SUMh | 0; - SHA512_W_L[i] = SUMl | 0; - } - let { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this; - for (let i = 0; i < 80; i++) { - const sigma1h = rotrSH(Eh, El, 14) ^ rotrSH(Eh, El, 18) ^ rotrBH(Eh, El, 41); - const sigma1l = rotrSL(Eh, El, 14) ^ rotrSL(Eh, El, 18) ^ rotrBL(Eh, El, 41); - const CHIh = Eh & Fh ^ ~Eh & Gh; - const CHIl = El & Fl ^ ~El & Gl; - const T1ll = add5L(Hl, sigma1l, CHIl, SHA512_Kl[i], SHA512_W_L[i]); - const T1h = add5H(T1ll, Hh, sigma1h, CHIh, SHA512_Kh[i], SHA512_W_H[i]); - const T1l = T1ll | 0; - const sigma0h = rotrSH(Ah, Al, 28) ^ rotrBH(Ah, Al, 34) ^ rotrBH(Ah, Al, 39); - const sigma0l = rotrSL(Ah, Al, 28) ^ rotrBL(Ah, Al, 34) ^ rotrBL(Ah, Al, 39); - const MAJh = Ah & Bh ^ Ah & Ch ^ Bh & Ch; - const MAJl = Al & Bl ^ Al & Cl ^ Bl & Cl; - Hh = Gh | 0; - Hl = Gl | 0; - Gh = Fh | 0; - Gl = Fl | 0; - Fh = Eh | 0; - Fl = El | 0; - ({ h: Eh, l: El } = add(Dh | 0, Dl | 0, T1h | 0, T1l | 0)); - Dh = Ch | 0; - Dl = Cl | 0; - Ch = Bh | 0; - Cl = Bl | 0; - Bh = Ah | 0; - Bl = Al | 0; - const All = add3L(T1l, sigma0l, MAJl); - Ah = add3H(All, T1h, sigma0h, MAJh); - Al = All | 0; - } - ({ h: Ah, l: Al } = add(this.Ah | 0, this.Al | 0, Ah | 0, Al | 0)); - ({ h: Bh, l: Bl } = add(this.Bh | 0, this.Bl | 0, Bh | 0, Bl | 0)); - ({ h: Ch, l: Cl } = add(this.Ch | 0, this.Cl | 0, Ch | 0, Cl | 0)); - ({ h: Dh, l: Dl } = add(this.Dh | 0, this.Dl | 0, Dh | 0, Dl | 0)); - ({ h: Eh, l: El } = add(this.Eh | 0, this.El | 0, Eh | 0, El | 0)); - ({ h: Fh, l: Fl } = add(this.Fh | 0, this.Fl | 0, Fh | 0, Fl | 0)); - ({ h: Gh, l: Gl } = add(this.Gh | 0, this.Gl | 0, Gh | 0, Gl | 0)); - ({ h: Hh, l: Hl } = add(this.Hh | 0, this.Hl | 0, Hh | 0, Hl | 0)); - this.set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl); - } - roundClean() { - clean(SHA512_W_H, SHA512_W_L); - } - destroy() { - clean(this.buffer); - this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0); - } -}; -var SHA384 = class extends SHA512 { - constructor() { - super(48); - this.Ah = SHA384_IV[0] | 0; - this.Al = SHA384_IV[1] | 0; - this.Bh = SHA384_IV[2] | 0; - this.Bl = SHA384_IV[3] | 0; - this.Ch = SHA384_IV[4] | 0; - this.Cl = SHA384_IV[5] | 0; - this.Dh = SHA384_IV[6] | 0; - this.Dl = SHA384_IV[7] | 0; - this.Eh = SHA384_IV[8] | 0; - this.El = SHA384_IV[9] | 0; - this.Fh = SHA384_IV[10] | 0; - this.Fl = SHA384_IV[11] | 0; - this.Gh = SHA384_IV[12] | 0; - this.Gl = SHA384_IV[13] | 0; - this.Hh = SHA384_IV[14] | 0; - this.Hl = SHA384_IV[15] | 0; - } -}; -var T224_IV = Uint32Array.from([ - 2352822216, - 424955298, - 1944164710, - 2312950998, - 502970286, - 855612546, - 1738396948, - 1479516111, - 258812777, - 2077511080, - 2011393907, - 79989058, - 1067287976, - 1780299464, - 286451373, - 2446758561 -]); -var T256_IV = Uint32Array.from([ - 573645204, - 4230739756, - 2673172387, - 3360449730, - 596883563, - 1867755857, - 2520282905, - 1497426621, - 2519219938, - 2827943907, - 3193839141, - 1401305490, - 721525244, - 746961066, - 246885852, - 2177182882 -]); -var SHA512_224 = class extends SHA512 { - constructor() { - super(28); - this.Ah = T224_IV[0] | 0; - this.Al = T224_IV[1] | 0; - this.Bh = T224_IV[2] | 0; - this.Bl = T224_IV[3] | 0; - this.Ch = T224_IV[4] | 0; - this.Cl = T224_IV[5] | 0; - this.Dh = T224_IV[6] | 0; - this.Dl = T224_IV[7] | 0; - this.Eh = T224_IV[8] | 0; - this.El = T224_IV[9] | 0; - this.Fh = T224_IV[10] | 0; - this.Fl = T224_IV[11] | 0; - this.Gh = T224_IV[12] | 0; - this.Gl = T224_IV[13] | 0; - this.Hh = T224_IV[14] | 0; - this.Hl = T224_IV[15] | 0; - } -}; -var SHA512_256 = class extends SHA512 { - constructor() { - super(32); - this.Ah = T256_IV[0] | 0; - this.Al = T256_IV[1] | 0; - this.Bh = T256_IV[2] | 0; - this.Bl = T256_IV[3] | 0; - this.Ch = T256_IV[4] | 0; - this.Cl = T256_IV[5] | 0; - this.Dh = T256_IV[6] | 0; - this.Dl = T256_IV[7] | 0; - this.Eh = T256_IV[8] | 0; - this.El = T256_IV[9] | 0; - this.Fh = T256_IV[10] | 0; - this.Fl = T256_IV[11] | 0; - this.Gh = T256_IV[12] | 0; - this.Gl = T256_IV[13] | 0; - this.Hh = T256_IV[14] | 0; - this.Hl = T256_IV[15] | 0; - } -}; -var sha256 = createHasher(() => new SHA256()); -var sha224 = createHasher(() => new SHA224()); -var sha512 = createHasher(() => new SHA512()); -var sha384 = createHasher(() => new SHA384()); -var sha512_256 = createHasher(() => new SHA512_256()); -var sha512_224 = createHasher(() => new SHA512_224()); - -// node_modules/@cashu/cashu-ts/dist/lib/es6/cbor.js -function isResultKeyType(value) { - return typeof value === "number" || typeof value === "string"; -} -function encodeCBOR(value) { - var buffer = []; - encodeItem(value, buffer); - return new Uint8Array(buffer); -} -function encodeItem(value, buffer) { - if (value === null) { - buffer.push(246); - } else if (value === void 0) { - buffer.push(247); - } else if (typeof value === "boolean") { - buffer.push(value ? 245 : 244); - } else if (typeof value === "number") { - encodeUnsigned(value, buffer); - } else if (typeof value === "string") { - encodeString(value, buffer); - } else if (Array.isArray(value)) { - encodeArray(value, buffer); - } else if (value instanceof Uint8Array) { - encodeByteString(value, buffer); - } else if (typeof value === "object") { - encodeObject(value, buffer); - } else { - throw new Error("Unsupported type"); - } -} -function encodeUnsigned(value, buffer) { - if (value < 24) { - buffer.push(value); - } else if (value < 256) { - buffer.push(24, value); - } else if (value < 65536) { - buffer.push(25, value >> 8, value & 255); - } else if (value < 4294967296) { - buffer.push(26, value >> 24, value >> 16 & 255, value >> 8 & 255, value & 255); - } else { - throw new Error("Unsupported integer size"); - } -} -function encodeByteString(value, buffer) { - var length = value.length; - if (length < 24) { - buffer.push(64 + length); - } else if (length < 256) { - buffer.push(88, length); - } else if (length < 65536) { - buffer.push(89, length >> 8 & 255, length & 255); - } else if (length < 4294967296) { - buffer.push(90, length >> 24 & 255, length >> 16 & 255, length >> 8 & 255, length & 255); - } else { - throw new Error("Byte string too long to encode"); - } - for (var i = 0; i < value.length; i++) { - buffer.push(value[i]); - } -} -function encodeString(value, buffer) { - var utf8 = new TextEncoder().encode(value); - var length = utf8.length; - if (length < 24) { - buffer.push(96 + length); - } else if (length < 256) { - buffer.push(120, length); - } else if (length < 65536) { - buffer.push(121, length >> 8 & 255, length & 255); - } else if (length < 4294967296) { - buffer.push(122, length >> 24 & 255, length >> 16 & 255, length >> 8 & 255, length & 255); - } else { - throw new Error("String too long to encode"); - } - for (var i = 0; i < utf8.length; i++) { - buffer.push(utf8[i]); - } -} -function encodeArray(value, buffer) { - var length = value.length; - if (length < 24) { - buffer.push(128 | length); - } else if (length < 256) { - buffer.push(152, length); - } else if (length < 65536) { - buffer.push(153, length >> 8, length & 255); - } else { - throw new Error("Unsupported array length"); - } - for (var _i = 0, value_1 = value; _i < value_1.length; _i++) { - var item = value_1[_i]; - encodeItem(item, buffer); - } -} -function encodeObject(value, buffer) { - var keys = Object.keys(value); - encodeUnsigned(keys.length, buffer); - buffer[buffer.length - 1] |= 160; - for (var _i = 0, keys_1 = keys; _i < keys_1.length; _i++) { - var key = keys_1[_i]; - encodeString(key, buffer); - encodeItem(value[key], buffer); - } -} -function decodeCBOR(data) { - var view = new DataView(data.buffer, data.byteOffset, data.byteLength); - var result = decodeItem(view, 0); - return result.value; -} -function decodeItem(view, offset) { - if (offset >= view.byteLength) { - throw new Error("Unexpected end of data"); - } - var initialByte = view.getUint8(offset++); - var majorType = initialByte >> 5; - var additionalInfo = initialByte & 31; - switch (majorType) { - case 0: - return decodeUnsigned(view, offset, additionalInfo); - case 1: - return decodeSigned(view, offset, additionalInfo); - case 2: - return decodeByteString(view, offset, additionalInfo); - case 3: - return decodeString(view, offset, additionalInfo); - case 4: - return decodeArray(view, offset, additionalInfo); - case 5: - return decodeMap(view, offset, additionalInfo); - case 7: - return decodeSimpleAndFloat(view, offset, additionalInfo); - default: - throw new Error("Unsupported major type: ".concat(majorType)); - } -} -function decodeLength(view, offset, additionalInfo) { - if (additionalInfo < 24) - return { value: additionalInfo, offset }; - if (additionalInfo === 24) - return { value: view.getUint8(offset++), offset }; - if (additionalInfo === 25) { - var value = view.getUint16(offset, false); - offset += 2; - return { value, offset }; - } - if (additionalInfo === 26) { - var value = view.getUint32(offset, false); - offset += 4; - return { value, offset }; - } - if (additionalInfo === 27) { - var hi = view.getUint32(offset, false); - var lo = view.getUint32(offset + 4, false); - offset += 8; - return { value: hi * Math.pow(2, 32) + lo, offset }; - } - throw new Error("Unsupported length: ".concat(additionalInfo)); -} -function decodeUnsigned(view, offset, additionalInfo) { - var _a = decodeLength(view, offset, additionalInfo), value = _a.value, newOffset = _a.offset; - return { value, offset: newOffset }; -} -function decodeSigned(view, offset, additionalInfo) { - var _a = decodeLength(view, offset, additionalInfo), value = _a.value, newOffset = _a.offset; - return { value: -1 - value, offset: newOffset }; -} -function decodeByteString(view, offset, additionalInfo) { - var _a = decodeLength(view, offset, additionalInfo), length = _a.value, newOffset = _a.offset; - if (newOffset + length > view.byteLength) { - throw new Error("Byte string length exceeds data length"); - } - var value = new Uint8Array(view.buffer, view.byteOffset + newOffset, length); - return { value, offset: newOffset + length }; -} -function decodeString(view, offset, additionalInfo) { - var _a = decodeLength(view, offset, additionalInfo), length = _a.value, newOffset = _a.offset; - if (newOffset + length > view.byteLength) { - throw new Error("String length exceeds data length"); - } - var bytes = new Uint8Array(view.buffer, view.byteOffset + newOffset, length); - var value = new TextDecoder().decode(bytes); - return { value, offset: newOffset + length }; -} -function decodeArray(view, offset, additionalInfo) { - var _a = decodeLength(view, offset, additionalInfo), length = _a.value, newOffset = _a.offset; - var array = []; - var currentOffset = newOffset; - for (var i = 0; i < length; i++) { - var result = decodeItem(view, currentOffset); - array.push(result.value); - currentOffset = result.offset; - } - return { value: array, offset: currentOffset }; -} -function decodeMap(view, offset, additionalInfo) { - var _a = decodeLength(view, offset, additionalInfo), length = _a.value, newOffset = _a.offset; - var map2 = {}; - var currentOffset = newOffset; - for (var i = 0; i < length; i++) { - var keyResult = decodeItem(view, currentOffset); - if (!isResultKeyType(keyResult.value)) { - throw new Error("Invalid key type"); - } - var valueResult = decodeItem(view, keyResult.offset); - map2[keyResult.value] = valueResult.value; - currentOffset = valueResult.offset; - } - return { value: map2, offset: currentOffset }; -} -function decodeFloat16(uint16) { - var exponent = (uint16 & 31744) >> 10; - var fraction = uint16 & 1023; - var sign = uint16 & 32768 ? -1 : 1; - if (exponent === 0) { - return sign * Math.pow(2, -14) * (fraction / 1024); - } else if (exponent === 31) { - return fraction ? NaN : sign * Infinity; - } - return sign * Math.pow(2, exponent - 15) * (1 + fraction / 1024); -} -function decodeSimpleAndFloat(view, offset, additionalInfo) { - if (additionalInfo < 24) { - switch (additionalInfo) { - case 20: - return { value: false, offset }; - case 21: - return { value: true, offset }; - case 22: - return { value: null, offset }; - case 23: - return { value: void 0, offset }; - default: - throw new Error("Unknown simple value: ".concat(additionalInfo)); - } - } - if (additionalInfo === 24) - return { value: view.getUint8(offset++), offset }; - if (additionalInfo === 25) { - var value = decodeFloat16(view.getUint16(offset, false)); - offset += 2; - return { value, offset }; - } - if (additionalInfo === 26) { - var value = view.getFloat32(offset, false); - offset += 4; - return { value, offset }; - } - if (additionalInfo === 27) { - var value = view.getFloat64(offset, false); - offset += 8; - return { value, offset }; - } - throw new Error("Unknown simple or float value: ".concat(additionalInfo)); -} - -// node_modules/@cashu/cashu-ts/dist/lib/es6/model/PaymentRequest.js -var import_buffer2 = __toESM(require_buffer()); -var PaymentRequest = ( - /** @class */ - function() { - function PaymentRequest2(transport, id, amount, unit, mints, description, singleUse) { - if (singleUse === void 0) { - singleUse = false; - } - this.transport = transport; - this.id = id; - this.amount = amount; - this.unit = unit; - this.mints = mints; - this.description = description; - this.singleUse = singleUse; - } - PaymentRequest2.prototype.toEncodedRequest = function() { - var rawRequest = { - t: this.transport.map(function(t) { - return { t: t.type, a: t.target, g: t.tags }; - }) - }; - if (this.id) { - rawRequest.i = this.id; - } - if (this.amount) { - rawRequest.a = this.amount; - } - if (this.unit) { - rawRequest.u = this.unit; - } - if (this.mints) { - rawRequest.m = this.mints; - } - if (this.description) { - rawRequest.d = this.description; - } - if (this.singleUse) { - rawRequest.s = this.singleUse; - } - var data = encodeCBOR(rawRequest); - var encodedData = import_buffer2.Buffer.from(data).toString("base64"); - return "creqA" + encodedData; - }; - PaymentRequest2.prototype.getTransport = function(type) { - return this.transport.find(function(t) { - return t.type === type; - }); - }; - PaymentRequest2.fromEncodedRequest = function(encodedRequest) { - if (!encodedRequest.startsWith("creq")) { - throw new Error("unsupported pr: invalid prefix"); - } - var version = encodedRequest[4]; - if (version !== "A") { - throw new Error("unsupported pr version"); - } - var encodedData = encodedRequest.slice(5); - var data = encodeBase64toUint8(encodedData); - var decoded = decodeCBOR(data); - var transports = decoded.t.map(function(t) { - return { type: t.t, target: t.a, tags: t.g }; - }); - return new PaymentRequest2(transports, decoded.i, decoded.a, decoded.u, decoded.m, decoded.d, decoded.s); - }; - return PaymentRequest2; - }() -); - -// node_modules/@cashu/cashu-ts/dist/lib/es6/utils.js -function splitAmount(value, keyset, split2, order2) { - if (split2) { - if (split2.reduce(function(a, b) { - return a + b; - }, 0) > value) { - throw new Error("Split is greater than total amount: ".concat(split2.reduce(function(a, b) { - return a + b; - }, 0), " > ").concat(value)); - } - split2.forEach(function(amt) { - if (!hasCorrespondingKey(amt, keyset)) { - throw new Error("Provided amount preferences do not match the amounts of the mint keyset."); - } - }); - value = value - split2.reduce(function(curr, acc) { - return curr + acc; - }, 0); - } else { - split2 = []; - } - var sortedKeyAmounts = getKeysetAmounts(keyset); - sortedKeyAmounts.forEach(function(amt) { - var q = Math.floor(value / amt); - for (var i = 0; i < q; ++i) - split2 === null || split2 === void 0 ? void 0 : split2.push(amt); - value %= amt; - }); - return split2.sort(function(a, b) { - return order2 === "desc" ? b - a : a - b; - }); -} -function getKeepAmounts(proofsWeHave, amountToKeep, keys, targetCount) { - var amountsWeWant = []; - var amountsWeHave = proofsWeHave.map(function(p) { - return p.amount; - }); - var sortedKeyAmounts = getKeysetAmounts(keys, "asc"); - sortedKeyAmounts.forEach(function(amt) { - var countWeHave = amountsWeHave.filter(function(a) { - return a === amt; - }).length; - var countWeWant = Math.max(targetCount - countWeHave, 0); - for (var i = 0; i < countWeWant; ++i) { - if (amountsWeWant.reduce(function(a, b) { - return a + b; - }, 0) + amt > amountToKeep) { - break; - } - amountsWeWant.push(amt); - } - }); - var amountDiff = amountToKeep - amountsWeWant.reduce(function(a, b) { - return a + b; - }, 0); - if (amountDiff) { - var remainingAmounts = splitAmount(amountDiff, keys); - remainingAmounts.forEach(function(amt) { - amountsWeWant.push(amt); - }); - } - var sortedAmountsWeWant = amountsWeWant.sort(function(a, b) { - return a - b; - }); - return sortedAmountsWeWant; -} -function getKeysetAmounts(keyset, order2) { - if (order2 === void 0) { - order2 = "desc"; - } - if (order2 == "desc") { - return Object.keys(keyset).map(function(k) { - return parseInt(k); - }).sort(function(a, b) { - return b - a; - }); - } - return Object.keys(keyset).map(function(k) { - return parseInt(k); - }).sort(function(a, b) { - return a - b; - }); -} -function hasCorrespondingKey(amount, keyset) { - return amount in keyset; -} -function bytesToNumber(bytes) { - return hexToNumber2(bytesToHex2(bytes)); -} -function hexToNumber2(hex) { - return BigInt("0x".concat(hex)); -} -function getDecodedToken(token) { - var uriPrefixes = ["web+cashu://", "cashu://", "cashu:", "cashu"]; - uriPrefixes.forEach(function(prefix) { - if (!token.startsWith(prefix)) { - return; - } - token = token.slice(prefix.length); - }); - return handleTokens(token); -} -function handleTokens(token) { - var version = token.slice(0, 1); - var encodedToken = token.slice(1); - if (version === "A") { - var parsedV3Token = encodeBase64ToJson(encodedToken); - if (parsedV3Token.token.length > 1) { - throw new Error("Multi entry token are not supported"); - } - var entry = parsedV3Token.token[0]; - var tokenObj = { - mint: entry.mint, - proofs: entry.proofs, - unit: parsedV3Token.unit || "sat" - }; - if (parsedV3Token.memo) { - tokenObj.memo = parsedV3Token.memo; - } - return tokenObj; - } else if (version === "B") { - var uInt8Token = encodeBase64toUint8(encodedToken); - var tokenData = decodeCBOR(uInt8Token); - var proofs_1 = []; - tokenData.t.forEach(function(t) { - return t.p.forEach(function(p) { - proofs_1.push({ - secret: p.s, - C: bytesToHex2(p.c), - amount: p.a, - id: bytesToHex2(t.i) - }); - }); - }); - var decodedToken = { mint: tokenData.m, proofs: proofs_1, unit: tokenData.u || "sat" }; - if (tokenData.d) { - decodedToken.memo = tokenData.d; - } - return decodedToken; - } - throw new Error("Token version is not supported"); -} -function isObj(v) { - return typeof v === "object"; -} -function joinUrls() { - var parts = []; - for (var _i = 0; _i < arguments.length; _i++) { - parts[_i] = arguments[_i]; - } - return parts.map(function(part) { - return part.replace(/(^\/+|\/+$)/g, ""); - }).join("/"); -} -function sanitizeUrl(url) { - return url.replace(/\/$/, ""); -} -function sumProofs(proofs) { - return proofs.reduce(function(acc, proof) { - return acc + proof.amount; - }, 0); -} - -// node_modules/@cashu/cashu-ts/dist/lib/es6/legacy/nut-05.js -function handleMeltQuoteResponseDeprecated(response) { - if (!response.state) { - console.warn("Field 'state' not found in MeltQuoteResponse. Update NUT-05 of mint: https://github.com/cashubtc/nuts/pull/136)"); - if (typeof response.paid === "boolean") { - response.state = response.paid ? MeltQuoteState.PAID : MeltQuoteState.UNPAID; - } - } - return response; -} - -// node_modules/@cashu/cashu-ts/dist/lib/es6/legacy/nut-04.js -function handleMintQuoteResponseDeprecated(response) { - if (!response.state) { - console.warn("Field 'state' not found in MintQuoteResponse. Update NUT-04 of mint: https://github.com/cashubtc/nuts/pull/141)"); - if (typeof response.paid === "boolean") { - response.state = response.paid ? MintQuoteState.PAID : MintQuoteState.UNPAID; - } - } - return response; -} - -// node_modules/@cashu/cashu-ts/dist/lib/es6/legacy/nut-06.js -function handleMintInfoContactFieldDeprecated(data) { - if (Array.isArray(data === null || data === void 0 ? void 0 : data.contact) && (data === null || data === void 0 ? void 0 : data.contact.length) > 0) { - data.contact = data.contact.map(function(contact) { - if (Array.isArray(contact) && contact.length === 2 && typeof contact[0] === "string" && typeof contact[1] === "string") { - console.warn("Mint returned deprecated 'contact' field: Update NUT-06: https://github.com/cashubtc/nuts/pull/117"); - return { method: contact[0], info: contact[1] }; - } - return contact; - }); - } - return data; -} - -// node_modules/@cashu/cashu-ts/dist/lib/es6/CashuMint.js -var __awaiter2 = function(thisArg, _arguments, P, generator) { - function adopt(value) { - return value instanceof P ? value : new P(function(resolve) { - resolve(value); - }); - } - return new (P || (P = Promise))(function(resolve, reject) { - function fulfilled(value) { - try { - step(generator.next(value)); - } catch (e) { - reject(e); - } - } - function rejected(value) { - try { - step(generator["throw"](value)); - } catch (e) { - reject(e); - } - } - function step(result) { - result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); - } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -var __generator2 = function(thisArg, body) { - var _ = { label: 0, sent: function() { - if (t[0] & 1) throw t[1]; - return t[1]; - }, trys: [], ops: [] }, f, y, t, g; - return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { - return this; - }), g; - function verb(n) { - return function(v) { - return step([n, v]); - }; - } - function step(op) { - if (f) throw new TypeError("Generator is already executing."); - while (g && (g = 0, op[0] && (_ = 0)), _) try { - if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; - if (y = 0, t) op = [op[0] & 2, t.value]; - switch (op[0]) { - case 0: - case 1: - t = op; - break; - case 4: - _.label++; - return { value: op[1], done: false }; - case 5: - _.label++; - y = op[1]; - op = [0]; - continue; - case 7: - op = _.ops.pop(); - _.trys.pop(); - continue; - default: - if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { - _ = 0; - continue; - } - if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) { - _.label = op[1]; - break; - } - if (op[0] === 6 && _.label < t[1]) { - _.label = t[1]; - t = op; - break; - } - if (t && _.label < t[2]) { - _.label = t[2]; - _.ops.push(op); - break; - } - if (t[2]) _.ops.pop(); - _.trys.pop(); - continue; - } - op = body.call(thisArg, _); - } catch (e) { - op = [6, e]; - y = 0; - } finally { - f = t = 0; - } - if (op[0] & 5) throw op[1]; - return { value: op[0] ? op[1] : void 0, done: true }; - } -}; -var CashuMint = ( - /** @class */ - function() { - function CashuMint2(_mintUrl, _customRequest) { - this._mintUrl = _mintUrl; - this._customRequest = _customRequest; - this._mintUrl = sanitizeUrl(_mintUrl); - this._customRequest = _customRequest; - } - Object.defineProperty(CashuMint2.prototype, "mintUrl", { - get: function() { - return this._mintUrl; - }, - enumerable: false, - configurable: true - }); - CashuMint2.getInfo = function(mintUrl, customRequest) { - return __awaiter2(this, void 0, void 0, function() { - var requestInstance, response, data; - return __generator2(this, function(_a) { - switch (_a.label) { - case 0: - requestInstance = customRequest || request; - return [4, requestInstance({ - endpoint: joinUrls(mintUrl, "/v1/info") - })]; - case 1: - response = _a.sent(); - data = handleMintInfoContactFieldDeprecated(response); - return [2, data]; - } - }); - }); - }; - CashuMint2.prototype.getInfo = function() { - return __awaiter2(this, void 0, void 0, function() { - return __generator2(this, function(_a) { - return [2, CashuMint2.getInfo(this._mintUrl, this._customRequest)]; - }); - }); - }; - CashuMint2.swap = function(mintUrl, swapPayload, customRequest) { - var _a; - return __awaiter2(this, void 0, void 0, function() { - var requestInstance, data; - return __generator2(this, function(_b) { - switch (_b.label) { - case 0: - requestInstance = customRequest || request; - return [4, requestInstance({ - endpoint: joinUrls(mintUrl, "/v1/swap"), - method: "POST", - requestBody: swapPayload - })]; - case 1: - data = _b.sent(); - if (!isObj(data) || !Array.isArray(data === null || data === void 0 ? void 0 : data.signatures)) { - throw new Error((_a = data.detail) !== null && _a !== void 0 ? _a : "bad response"); - } - return [2, data]; - } - }); - }); - }; - CashuMint2.prototype.swap = function(swapPayload) { - return __awaiter2(this, void 0, void 0, function() { - return __generator2(this, function(_a) { - return [2, CashuMint2.swap(this._mintUrl, swapPayload, this._customRequest)]; - }); - }); - }; - CashuMint2.createMintQuote = function(mintUrl, mintQuotePayload, customRequest) { - return __awaiter2(this, void 0, void 0, function() { - var requestInstance, response, data; - return __generator2(this, function(_a) { - switch (_a.label) { - case 0: - requestInstance = customRequest || request; - return [4, requestInstance({ - endpoint: joinUrls(mintUrl, "/v1/mint/quote/bolt11"), - method: "POST", - requestBody: mintQuotePayload - })]; - case 1: - response = _a.sent(); - data = handleMintQuoteResponseDeprecated(response); - return [2, data]; - } - }); - }); - }; - CashuMint2.prototype.createMintQuote = function(mintQuotePayload) { - return __awaiter2(this, void 0, void 0, function() { - return __generator2(this, function(_a) { - return [2, CashuMint2.createMintQuote(this._mintUrl, mintQuotePayload, this._customRequest)]; - }); - }); - }; - CashuMint2.checkMintQuote = function(mintUrl, quote, customRequest) { - return __awaiter2(this, void 0, void 0, function() { - var requestInstance, response, data; - return __generator2(this, function(_a) { - switch (_a.label) { - case 0: - requestInstance = customRequest || request; - return [4, requestInstance({ - endpoint: joinUrls(mintUrl, "/v1/mint/quote/bolt11", quote), - method: "GET" - })]; - case 1: - response = _a.sent(); - data = handleMintQuoteResponseDeprecated(response); - return [2, data]; - } - }); - }); - }; - CashuMint2.prototype.checkMintQuote = function(quote) { - return __awaiter2(this, void 0, void 0, function() { - return __generator2(this, function(_a) { - return [2, CashuMint2.checkMintQuote(this._mintUrl, quote, this._customRequest)]; - }); - }); - }; - CashuMint2.mint = function(mintUrl, mintPayload, customRequest) { - return __awaiter2(this, void 0, void 0, function() { - var requestInstance, data; - return __generator2(this, function(_a) { - switch (_a.label) { - case 0: - requestInstance = customRequest || request; - return [4, requestInstance({ - endpoint: joinUrls(mintUrl, "/v1/mint/bolt11"), - method: "POST", - requestBody: mintPayload - })]; - case 1: - data = _a.sent(); - if (!isObj(data) || !Array.isArray(data === null || data === void 0 ? void 0 : data.signatures)) { - throw new Error("bad response"); - } - return [2, data]; - } - }); - }); - }; - CashuMint2.prototype.mint = function(mintPayload) { - return __awaiter2(this, void 0, void 0, function() { - return __generator2(this, function(_a) { - return [2, CashuMint2.mint(this._mintUrl, mintPayload, this._customRequest)]; - }); - }); - }; - CashuMint2.createMeltQuote = function(mintUrl, meltQuotePayload, customRequest) { - return __awaiter2(this, void 0, void 0, function() { - var requestInstance, response, data; - return __generator2(this, function(_a) { - switch (_a.label) { - case 0: - requestInstance = customRequest || request; - return [4, requestInstance({ - endpoint: joinUrls(mintUrl, "/v1/melt/quote/bolt11"), - method: "POST", - requestBody: meltQuotePayload - })]; - case 1: - response = _a.sent(); - data = handleMeltQuoteResponseDeprecated(response); - if (!isObj(data) || typeof (data === null || data === void 0 ? void 0 : data.amount) !== "number" || typeof (data === null || data === void 0 ? void 0 : data.fee_reserve) !== "number" || typeof (data === null || data === void 0 ? void 0 : data.quote) !== "string") { - throw new Error("bad response"); - } - return [2, data]; - } - }); - }); - }; - CashuMint2.prototype.createMeltQuote = function(meltQuotePayload) { - return __awaiter2(this, void 0, void 0, function() { - return __generator2(this, function(_a) { - return [2, CashuMint2.createMeltQuote(this._mintUrl, meltQuotePayload, this._customRequest)]; - }); - }); - }; - CashuMint2.checkMeltQuote = function(mintUrl, quote, customRequest) { - return __awaiter2(this, void 0, void 0, function() { - var requestInstance, response, data; - return __generator2(this, function(_a) { - switch (_a.label) { - case 0: - requestInstance = customRequest || request; - return [4, requestInstance({ - endpoint: joinUrls(mintUrl, "/v1/melt/quote/bolt11", quote), - method: "GET" - })]; - case 1: - response = _a.sent(); - data = handleMeltQuoteResponseDeprecated(response); - if (!isObj(data) || typeof (data === null || data === void 0 ? void 0 : data.amount) !== "number" || typeof (data === null || data === void 0 ? void 0 : data.fee_reserve) !== "number" || typeof (data === null || data === void 0 ? void 0 : data.quote) !== "string" || typeof (data === null || data === void 0 ? void 0 : data.state) !== "string" || !Object.values(MeltQuoteState).includes(data.state)) { - throw new Error("bad response"); - } - return [2, data]; - } - }); - }); - }; - CashuMint2.prototype.checkMeltQuote = function(quote) { - return __awaiter2(this, void 0, void 0, function() { - return __generator2(this, function(_a) { - return [2, CashuMint2.checkMeltQuote(this._mintUrl, quote, this._customRequest)]; - }); - }); - }; - CashuMint2.melt = function(mintUrl, meltPayload, customRequest) { - return __awaiter2(this, void 0, void 0, function() { - var requestInstance, response, data; - return __generator2(this, function(_a) { - switch (_a.label) { - case 0: - requestInstance = customRequest || request; - return [4, requestInstance({ - endpoint: joinUrls(mintUrl, "/v1/melt/bolt11"), - method: "POST", - requestBody: meltPayload - })]; - case 1: - response = _a.sent(); - data = handleMeltQuoteResponseDeprecated(response); - if (!isObj(data) || typeof (data === null || data === void 0 ? void 0 : data.state) !== "string" || !Object.values(MeltQuoteState).includes(data.state)) { - throw new Error("bad response"); - } - return [2, data]; - } - }); - }); - }; - CashuMint2.prototype.melt = function(meltPayload) { - return __awaiter2(this, void 0, void 0, function() { - return __generator2(this, function(_a) { - return [2, CashuMint2.melt(this._mintUrl, meltPayload, this._customRequest)]; - }); - }); - }; - CashuMint2.check = function(mintUrl, checkPayload, customRequest) { - return __awaiter2(this, void 0, void 0, function() { - var requestInstance, data; - return __generator2(this, function(_a) { - switch (_a.label) { - case 0: - requestInstance = customRequest || request; - return [4, requestInstance({ - endpoint: joinUrls(mintUrl, "/v1/checkstate"), - method: "POST", - requestBody: checkPayload - })]; - case 1: - data = _a.sent(); - if (!isObj(data) || !Array.isArray(data === null || data === void 0 ? void 0 : data.states)) { - throw new Error("bad response"); - } - return [2, data]; - } - }); - }); - }; - CashuMint2.getKeys = function(mintUrl, keysetId, customRequest) { - return __awaiter2(this, void 0, void 0, function() { - var requestInstance, data; - return __generator2(this, function(_a) { - switch (_a.label) { - case 0: - if (keysetId) { - keysetId = keysetId.replace(/\//g, "_").replace(/\+/g, "-"); - } - requestInstance = customRequest || request; - return [4, requestInstance({ - endpoint: keysetId ? joinUrls(mintUrl, "/v1/keys", keysetId) : joinUrls(mintUrl, "/v1/keys") - })]; - case 1: - data = _a.sent(); - if (!isObj(data) || !Array.isArray(data.keysets)) { - throw new Error("bad response"); - } - return [2, data]; - } - }); - }); - }; - CashuMint2.prototype.getKeys = function(keysetId, mintUrl) { - return __awaiter2(this, void 0, void 0, function() { - var allKeys; - return __generator2(this, function(_a) { - switch (_a.label) { - case 0: - return [4, CashuMint2.getKeys(mintUrl || this._mintUrl, keysetId, this._customRequest)]; - case 1: - allKeys = _a.sent(); - return [2, allKeys]; - } - }); - }); - }; - CashuMint2.getKeySets = function(mintUrl, customRequest) { - return __awaiter2(this, void 0, void 0, function() { - var requestInstance; - return __generator2(this, function(_a) { - requestInstance = customRequest || request; - return [2, requestInstance({ endpoint: joinUrls(mintUrl, "/v1/keysets") })]; - }); - }); - }; - CashuMint2.prototype.getKeySets = function() { - return __awaiter2(this, void 0, void 0, function() { - return __generator2(this, function(_a) { - return [2, CashuMint2.getKeySets(this._mintUrl, this._customRequest)]; - }); - }); - }; - CashuMint2.prototype.check = function(checkPayload) { - return __awaiter2(this, void 0, void 0, function() { - return __generator2(this, function(_a) { - return [2, CashuMint2.check(this._mintUrl, checkPayload, this._customRequest)]; - }); - }); - }; - CashuMint2.restore = function(mintUrl, restorePayload, customRequest) { - return __awaiter2(this, void 0, void 0, function() { - var requestInstance, data; - return __generator2(this, function(_a) { - switch (_a.label) { - case 0: - requestInstance = customRequest || request; - return [4, requestInstance({ - endpoint: joinUrls(mintUrl, "/v1/restore"), - method: "POST", - requestBody: restorePayload - })]; - case 1: - data = _a.sent(); - if (!isObj(data) || !Array.isArray(data === null || data === void 0 ? void 0 : data.outputs) || !Array.isArray(data === null || data === void 0 ? void 0 : data.promises)) { - throw new Error("bad response"); - } - return [2, data]; - } - }); - }); - }; - CashuMint2.prototype.restore = function(restorePayload) { - return __awaiter2(this, void 0, void 0, function() { - return __generator2(this, function(_a) { - return [2, CashuMint2.restore(this._mintUrl, restorePayload, this._customRequest)]; - }); - }); - }; - return CashuMint2; - }() -); - -// node_modules/@cashu/cashu-ts/dist/lib/es6/model/BlindedMessage.js -var BlindedMessage = ( - /** @class */ - function() { - function BlindedMessage2(amount, B_, id) { - this.amount = amount; - this.B_ = B_; - this.id = id; - } - BlindedMessage2.prototype.getSerializedBlindedMessage = function() { - return { amount: this.amount, B_: this.B_.toHex(true), id: this.id }; - }; - return BlindedMessage2; - }() -); - -// node_modules/@cashu/cashu-ts/dist/lib/es6/CashuWallet.js -var import_common = __toESM(require_common()); -var import_client = __toESM(require_client()); -var import_NUT09 = __toESM(require_NUT09()); -var import_NUT11 = __toESM(require_NUT112()); -var __awaiter3 = function(thisArg, _arguments, P, generator) { - function adopt(value) { - return value instanceof P ? value : new P(function(resolve) { - resolve(value); - }); - } - return new (P || (P = Promise))(function(resolve, reject) { - function fulfilled(value) { - try { - step(generator.next(value)); - } catch (e) { - reject(e); - } - } - function rejected(value) { - try { - step(generator["throw"](value)); - } catch (e) { - reject(e); - } - } - function step(result) { - result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); - } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -var __generator3 = function(thisArg, body) { - var _ = { label: 0, sent: function() { - if (t[0] & 1) throw t[1]; - return t[1]; - }, trys: [], ops: [] }, f, y, t, g; - return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { - return this; - }), g; - function verb(n) { - return function(v) { - return step([n, v]); - }; - } - function step(op) { - if (f) throw new TypeError("Generator is already executing."); - while (g && (g = 0, op[0] && (_ = 0)), _) try { - if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; - if (y = 0, t) op = [op[0] & 2, t.value]; - switch (op[0]) { - case 0: - case 1: - t = op; - break; - case 4: - _.label++; - return { value: op[1], done: false }; - case 5: - _.label++; - y = op[1]; - op = [0]; - continue; - case 7: - op = _.ops.pop(); - _.trys.pop(); - continue; - default: - if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { - _ = 0; - continue; - } - if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) { - _.label = op[1]; - break; - } - if (op[0] === 6 && _.label < t[1]) { - _.label = t[1]; - t = op; - break; - } - if (t && _.label < t[2]) { - _.label = t[2]; - _.ops.push(op); - break; - } - if (t[2]) _.ops.pop(); - _.trys.pop(); - continue; - } - op = body.call(thisArg, _); - } catch (e) { - op = [6, e]; - y = 0; - } finally { - f = t = 0; - } - if (op[0] & 5) throw op[1]; - return { value: op[0] ? op[1] : void 0, done: true }; - } -}; -var __spreadArray = function(to, from, pack) { - if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) { - if (ar || !(i in from)) { - if (!ar) ar = Array.prototype.slice.call(from, 0, i); - ar[i] = from[i]; - } - } - return to.concat(ar || Array.prototype.slice.call(from)); -}; -var DEFAULT_DENOMINATION_TARGET = 3; -var DEFAULT_UNIT = "sat"; -var CashuWallet = ( - /** @class */ - function() { - function CashuWallet2(mint, options) { - var _this = this; - this._keys = /* @__PURE__ */ new Map(); - this._keysets = []; - this._seed = void 0; - this._unit = DEFAULT_UNIT; - this._mintInfo = void 0; - this._denominationTarget = DEFAULT_DENOMINATION_TARGET; - this.mint = mint; - var keys = []; - if ((options === null || options === void 0 ? void 0 : options.keys) && !Array.isArray(options.keys)) { - keys = [options.keys]; - } else if ((options === null || options === void 0 ? void 0 : options.keys) && Array.isArray(options === null || options === void 0 ? void 0 : options.keys)) { - keys = options === null || options === void 0 ? void 0 : options.keys; - } - if (keys) - keys.forEach(function(key) { - return _this._keys.set(key.id, key); - }); - if (options === null || options === void 0 ? void 0 : options.unit) - this._unit = options === null || options === void 0 ? void 0 : options.unit; - if (options === null || options === void 0 ? void 0 : options.keysets) - this._keysets = options.keysets; - if (options === null || options === void 0 ? void 0 : options.denominationTarget) { - this._denominationTarget = options.denominationTarget; - } - if (options === null || options === void 0 ? void 0 : options.bip39seed) { - if (options.bip39seed instanceof Uint8Array) { - this._seed = options.bip39seed; - return; - } - throw new Error("bip39seed must be a valid UInt8Array"); - } - } - Object.defineProperty(CashuWallet2.prototype, "unit", { - get: function() { - return this._unit; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(CashuWallet2.prototype, "keys", { - get: function() { - return this._keys; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(CashuWallet2.prototype, "keysetId", { - get: function() { - if (!this._keysetId) { - throw new Error("No keysetId set"); - } - return this._keysetId; - }, - set: function(keysetId) { - this._keysetId = keysetId; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(CashuWallet2.prototype, "keysets", { - get: function() { - return this._keysets; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(CashuWallet2.prototype, "mintInfo", { - get: function() { - if (!this._mintInfo) { - throw new Error("Mint info not loaded"); - } - return this._mintInfo; - }, - enumerable: false, - configurable: true - }); - CashuWallet2.prototype.getMintInfo = function() { - return __awaiter3(this, void 0, void 0, function() { - var _a; - return __generator3(this, function(_b) { - switch (_b.label) { - case 0: - _a = this; - return [4, this.mint.getInfo()]; - case 1: - _a._mintInfo = _b.sent(); - return [2, this._mintInfo]; - } - }); - }); - }; - CashuWallet2.prototype.loadMint = function() { - return __awaiter3(this, void 0, void 0, function() { - return __generator3(this, function(_a) { - switch (_a.label) { - case 0: - return [4, this.getMintInfo()]; - case 1: - _a.sent(); - return [4, this.getKeySets()]; - case 2: - _a.sent(); - return [4, this.getKeys()]; - case 3: - _a.sent(); - return [ - 2 - /*return*/ - ]; - } - }); - }); - }; - CashuWallet2.prototype.getActiveKeyset = function(keysets) { - var activeKeysets = keysets.filter(function(k) { - return k.active; - }); - activeKeysets = activeKeysets.filter(function(k) { - return k.id.startsWith("00"); - }); - var activeKeyset = activeKeysets.sort(function(a, b) { - var _a, _b; - return ((_a = a.input_fee_ppk) !== null && _a !== void 0 ? _a : 0) - ((_b = b.input_fee_ppk) !== null && _b !== void 0 ? _b : 0); - })[0]; - if (!activeKeyset) { - throw new Error("No active keyset found"); - } - return activeKeyset; - }; - CashuWallet2.prototype.getKeySets = function() { - return __awaiter3(this, void 0, void 0, function() { - var allKeysets, unitKeysets; - var _this = this; - return __generator3(this, function(_a) { - switch (_a.label) { - case 0: - return [4, this.mint.getKeySets()]; - case 1: - allKeysets = _a.sent(); - unitKeysets = allKeysets.keysets.filter(function(k) { - return k.unit === _this._unit; - }); - this._keysets = unitKeysets; - return [2, this._keysets]; - } - }); - }); - }; - CashuWallet2.prototype.getAllKeys = function() { - return __awaiter3(this, void 0, void 0, function() { - var keysets; - return __generator3(this, function(_a) { - switch (_a.label) { - case 0: - return [4, this.mint.getKeys()]; - case 1: - keysets = _a.sent(); - this._keys = new Map(keysets.keysets.map(function(k) { - return [k.id, k]; - })); - this.keysetId = this.getActiveKeyset(this._keysets).id; - return [2, keysets.keysets]; - } - }); - }); - }; - CashuWallet2.prototype.getKeys = function(keysetId, forceRefresh) { - return __awaiter3(this, void 0, void 0, function() { - var localKeyset, keys; - return __generator3(this, function(_a) { - switch (_a.label) { - case 0: - if (!(!(this._keysets.length > 0) || forceRefresh)) return [3, 2]; - return [4, this.getKeySets()]; - case 1: - _a.sent(); - _a.label = 2; - case 2: - if (!keysetId) { - localKeyset = this.getActiveKeyset(this._keysets); - keysetId = localKeyset.id; - } - if (!!this._keysets.find(function(k) { - return k.id === keysetId; - })) return [3, 4]; - return [4, this.getKeySets()]; - case 3: - _a.sent(); - if (!this._keysets.find(function(k) { - return k.id === keysetId; - })) { - throw new Error("could not initialize keys. No keyset with id '".concat(keysetId, "' found")); - } - _a.label = 4; - case 4: - if (!!this._keys.get(keysetId)) return [3, 6]; - return [4, this.mint.getKeys(keysetId)]; - case 5: - keys = _a.sent(); - this._keys.set(keysetId, keys.keysets[0]); - _a.label = 6; - case 6: - this.keysetId = keysetId; - return [2, this._keys.get(keysetId)]; - } - }); - }); - }; - CashuWallet2.prototype.receive = function(token, options) { - return __awaiter3(this, void 0, void 0, function() { - var keys, amount, _a, payload, blindingData, signatures, freshProofs; - return __generator3(this, function(_b) { - switch (_b.label) { - case 0: - if (typeof token === "string") { - token = getDecodedToken(token); - } - return [4, this.getKeys(options === null || options === void 0 ? void 0 : options.keysetId)]; - case 1: - keys = _b.sent(); - amount = sumProofs(token.proofs) - this.getFeesForProofs(token.proofs); - _a = this.createSwapPayload(amount, token.proofs, keys, options === null || options === void 0 ? void 0 : options.outputAmounts, options === null || options === void 0 ? void 0 : options.counter, options === null || options === void 0 ? void 0 : options.pubkey, options === null || options === void 0 ? void 0 : options.privkey), payload = _a.payload, blindingData = _a.blindingData; - return [4, this.mint.swap(payload)]; - case 2: - signatures = _b.sent().signatures; - freshProofs = this.constructProofs(signatures, blindingData.blindingFactors, blindingData.secrets, keys); - return [2, freshProofs]; - } - }); - }); - }; - CashuWallet2.prototype.send = function(amount, proofs, options) { - var _a; - return __awaiter3(this, void 0, void 0, function() { - var _b, keepProofsOffline, sendProofOffline, expectedFee, _c, keepProofsSelect, sendProofs, _d, keep, send, keepProofs; - return __generator3(this, function(_e) { - switch (_e.label) { - case 0: - if (sumProofs(proofs) < amount) { - throw new Error("Not enough funds available to send"); - } - _b = this.selectProofsToSend(proofs, amount, options === null || options === void 0 ? void 0 : options.includeFees), keepProofsOffline = _b.keep, sendProofOffline = _b.send; - expectedFee = (options === null || options === void 0 ? void 0 : options.includeFees) ? this.getFeesForProofs(sendProofOffline) : 0; - if (!(!(options === null || options === void 0 ? void 0 : options.offline) && (sumProofs(sendProofOffline) != amount + expectedFee || // if the exact amount cannot be selected - (options === null || options === void 0 ? void 0 : options.outputAmounts) || (options === null || options === void 0 ? void 0 : options.pubkey) || (options === null || options === void 0 ? void 0 : options.privkey) || (options === null || options === void 0 ? void 0 : options.keysetId)))) return [3, 2]; - _c = this.selectProofsToSend(proofs, amount, true), keepProofsSelect = _c.keep, sendProofs = _c.send; - (_a = options === null || options === void 0 ? void 0 : options.proofsWeHave) === null || _a === void 0 ? void 0 : _a.push.apply(_a, keepProofsSelect); - return [4, this.swap(amount, sendProofs, options)]; - case 1: - _d = _e.sent(), keep = _d.keep, send = _d.send; - keepProofs = keepProofsSelect.concat(keep); - return [2, { keep: keepProofs, send }]; - case 2: - if (sumProofs(sendProofOffline) < amount + expectedFee) { - throw new Error("Not enough funds available to send"); - } - return [2, { keep: keepProofsOffline, send: sendProofOffline }]; - } - }); - }); - }; - CashuWallet2.prototype.selectProofsToSend = function(proofs, amountToSend, includeFees) { - var sortedProofs = proofs.sort(function(a, b) { - return a.amount - b.amount; - }); - var smallerProofs = sortedProofs.filter(function(p) { - return p.amount <= amountToSend; - }).sort(function(a, b) { - return b.amount - a.amount; - }); - var biggerProofs = sortedProofs.filter(function(p) { - return p.amount > amountToSend; - }).sort(function(a, b) { - return a.amount - b.amount; - }); - var nextBigger = biggerProofs[0]; - if (!smallerProofs.length && nextBigger) { - return { - keep: proofs.filter(function(p) { - return p.secret !== nextBigger.secret; - }), - send: [nextBigger] - }; - } - if (!smallerProofs.length && !nextBigger) { - return { keep: proofs, send: [] }; - } - var remainder = amountToSend; - var selectedProofs = [smallerProofs[0]]; - var returnedProofs = []; - var feePPK = includeFees ? this.getFeesForProofs(selectedProofs) : 0; - remainder -= selectedProofs[0].amount - feePPK / 1e3; - if (remainder > 0) { - var _a = this.selectProofsToSend(smallerProofs.slice(1), remainder, includeFees), keep = _a.keep, send = _a.send; - selectedProofs.push.apply(selectedProofs, send); - returnedProofs.push.apply(returnedProofs, keep); - } - var selectedFeePPK = includeFees ? this.getFeesForProofs(selectedProofs) : 0; - if (sumProofs(selectedProofs) < amountToSend + selectedFeePPK && nextBigger) { - selectedProofs = [nextBigger]; - } - return { - keep: proofs.filter(function(p) { - return !selectedProofs.includes(p); - }), - send: selectedProofs - }; - }; - CashuWallet2.prototype.getFeesForProofs = function(proofs) { - var _this = this; - if (!this._keysets.length) { - throw new Error("Could not calculate fees. No keysets found"); - } - var keysetIds = new Set(proofs.map(function(p) { - return p.id; - })); - keysetIds.forEach(function(id) { - if (!_this._keysets.find(function(k) { - return k.id === id; - })) { - throw new Error("Could not calculate fees. No keyset found with id: ".concat(id)); - } - }); - var fees = Math.floor(Math.max((proofs.reduce(function(total, curr) { - var _a; - return total + (((_a = _this._keysets.find(function(k) { - return k.id === curr.id; - })) === null || _a === void 0 ? void 0 : _a.input_fee_ppk) || 0); - }, 0) + 999) / 1e3, 0)); - return fees; - }; - CashuWallet2.prototype.getFeesForKeyset = function(nInputs, keysetId) { - var _a; - var fees = Math.floor(Math.max((nInputs * (((_a = this._keysets.find(function(k) { - return k.id === keysetId; - })) === null || _a === void 0 ? void 0 : _a.input_fee_ppk) || 0) + 999) / 1e3, 0)); - return fees; - }; - CashuWallet2.prototype.swap = function(amount, proofs, options) { - var _a, _b, _c; - return __awaiter3(this, void 0, void 0, function() { - var keyset, proofsToSend, amountToSend, amountAvailable, amountToKeep, sendAmounts, outputFee, sendAmountsFee, keepAmounts, _d, payload, blindingData, signatures, swapProofs, splitProofsToKeep, splitProofsToSend, amountToKeepCounter; - return __generator3(this, function(_e) { - switch (_e.label) { - case 0: - if (!options) - options = {}; - return [4, this.getKeys(options.keysetId)]; - case 1: - keyset = _e.sent(); - proofsToSend = proofs; - amountToSend = amount; - amountAvailable = sumProofs(proofs); - amountToKeep = amountAvailable - amountToSend - this.getFeesForProofs(proofsToSend); - sendAmounts = ((_a = options === null || options === void 0 ? void 0 : options.outputAmounts) === null || _a === void 0 ? void 0 : _a.sendAmounts) || splitAmount(amountToSend, keyset.keys); - if (options === null || options === void 0 ? void 0 : options.includeFees) { - outputFee = this.getFeesForKeyset(sendAmounts.length, keyset.id); - sendAmountsFee = splitAmount(outputFee, keyset.keys); - while (this.getFeesForKeyset(sendAmounts.concat(sendAmountsFee).length, keyset.id) > outputFee) { - outputFee++; - sendAmountsFee = splitAmount(outputFee, keyset.keys); - } - sendAmounts = sendAmounts.concat(sendAmountsFee); - amountToSend += outputFee; - amountToKeep -= outputFee; - } - if (options && !((_b = options.outputAmounts) === null || _b === void 0 ? void 0 : _b.keepAmounts) && options.proofsWeHave) { - keepAmounts = getKeepAmounts(options.proofsWeHave, amountToKeep, keyset.keys, this._denominationTarget); - } else if (options.outputAmounts) { - if (((_c = options.outputAmounts.keepAmounts) === null || _c === void 0 ? void 0 : _c.reduce(function(a, b) { - return a + b; - }, 0)) != amountToKeep) { - throw new Error("Keep amounts do not match amount to keep"); - } - keepAmounts = options.outputAmounts.keepAmounts; - } - if (amountToSend + this.getFeesForProofs(proofsToSend) > amountAvailable) { - console.error("Not enough funds available (".concat(amountAvailable, ") for swap amountToSend: ").concat(amountToSend, " + fee: ").concat(this.getFeesForProofs(proofsToSend), " | length: ").concat(proofsToSend.length)); - throw new Error("Not enough funds available for swap"); - } - if (amountToSend + this.getFeesForProofs(proofsToSend) + amountToKeep != amountAvailable) { - throw new Error("Amounts do not match for swap"); - } - options.outputAmounts = { - keepAmounts, - sendAmounts - }; - _d = this.createSwapPayload(amountToSend, proofsToSend, keyset, options === null || options === void 0 ? void 0 : options.outputAmounts, options === null || options === void 0 ? void 0 : options.counter, options === null || options === void 0 ? void 0 : options.pubkey, options === null || options === void 0 ? void 0 : options.privkey), payload = _d.payload, blindingData = _d.blindingData; - return [4, this.mint.swap(payload)]; - case 2: - signatures = _e.sent().signatures; - swapProofs = this.constructProofs(signatures, blindingData.blindingFactors, blindingData.secrets, keyset); - splitProofsToKeep = []; - splitProofsToSend = []; - amountToKeepCounter = 0; - swapProofs.forEach(function(proof) { - if (amountToKeepCounter < amountToKeep) { - amountToKeepCounter += proof.amount; - splitProofsToKeep.push(proof); - return; - } - splitProofsToSend.push(proof); - }); - return [2, { - keep: splitProofsToKeep, - send: splitProofsToSend - }]; - } - }); - }); - }; - CashuWallet2.prototype.restore = function(start, count, options) { - return __awaiter3(this, void 0, void 0, function() { - var keys, amounts, _a, blindedMessages, blindingFactors, secrets, _b, outputs, promises, validBlindingFactors, validSecrets; - return __generator3(this, function(_c) { - switch (_c.label) { - case 0: - return [4, this.getKeys(options === null || options === void 0 ? void 0 : options.keysetId)]; - case 1: - keys = _c.sent(); - if (!this._seed) { - throw new Error("CashuWallet must be initialized with a seed to use restore"); - } - amounts = Array(count).fill(0); - _a = this.createBlindedMessages(amounts, keys.id, start), blindedMessages = _a.blindedMessages, blindingFactors = _a.blindingFactors, secrets = _a.secrets; - return [4, this.mint.restore({ outputs: blindedMessages })]; - case 2: - _b = _c.sent(), outputs = _b.outputs, promises = _b.promises; - validBlindingFactors = blindingFactors.filter(function(_, i) { - return outputs.map(function(o) { - return o.B_; - }).includes(blindedMessages[i].B_); - }); - validSecrets = secrets.filter(function(_, i) { - return outputs.map(function(o) { - return o.B_; - }).includes(blindedMessages[i].B_); - }); - return [2, { - proofs: this.constructProofs(promises, validBlindingFactors, validSecrets, keys) - }]; - } - }); - }); - }; - CashuWallet2.prototype.createMintQuote = function(amount, description) { - return __awaiter3(this, void 0, void 0, function() { - var mintQuotePayload; - return __generator3(this, function(_a) { - switch (_a.label) { - case 0: - mintQuotePayload = { - unit: this._unit, - amount, - description - }; - return [4, this.mint.createMintQuote(mintQuotePayload)]; - case 1: - return [2, _a.sent()]; - } - }); - }); - }; - CashuWallet2.prototype.checkMintQuote = function(quote) { - return __awaiter3(this, void 0, void 0, function() { - return __generator3(this, function(_a) { - switch (_a.label) { - case 0: - return [4, this.mint.checkMintQuote(quote)]; - case 1: - return [2, _a.sent()]; - } - }); - }); - }; - CashuWallet2.prototype.mintProofs = function(amount, quote, options) { - var _a; - return __awaiter3(this, void 0, void 0, function() { - var keyset, _b, blindedMessages, secrets, blindingFactors, mintPayload, signatures; - return __generator3(this, function(_c) { - switch (_c.label) { - case 0: - return [4, this.getKeys(options === null || options === void 0 ? void 0 : options.keysetId)]; - case 1: - keyset = _c.sent(); - if (!(options === null || options === void 0 ? void 0 : options.outputAmounts) && (options === null || options === void 0 ? void 0 : options.proofsWeHave)) { - options.outputAmounts = { - keepAmounts: getKeepAmounts(options.proofsWeHave, amount, keyset.keys, this._denominationTarget), - sendAmounts: [] - }; - } - _b = this.createRandomBlindedMessages(amount, keyset, (_a = options === null || options === void 0 ? void 0 : options.outputAmounts) === null || _a === void 0 ? void 0 : _a.keepAmounts, options === null || options === void 0 ? void 0 : options.counter, options === null || options === void 0 ? void 0 : options.pubkey), blindedMessages = _b.blindedMessages, secrets = _b.secrets, blindingFactors = _b.blindingFactors; - mintPayload = { - outputs: blindedMessages, - quote - }; - return [4, this.mint.mint(mintPayload)]; - case 2: - signatures = _c.sent().signatures; - return [2, { - proofs: this.constructProofs(signatures, blindingFactors, secrets, keyset) - }]; - } - }); - }); - }; - CashuWallet2.prototype.createMeltQuote = function(invoice) { - return __awaiter3(this, void 0, void 0, function() { - var meltQuotePayload, meltQuote; - return __generator3(this, function(_a) { - switch (_a.label) { - case 0: - meltQuotePayload = { - unit: this._unit, - request: invoice - }; - return [4, this.mint.createMeltQuote(meltQuotePayload)]; - case 1: - meltQuote = _a.sent(); - return [2, meltQuote]; - } - }); - }); - }; - CashuWallet2.prototype.checkMeltQuote = function(quote) { - return __awaiter3(this, void 0, void 0, function() { - var meltQuote; - return __generator3(this, function(_a) { - switch (_a.label) { - case 0: - return [4, this.mint.checkMeltQuote(quote)]; - case 1: - meltQuote = _a.sent(); - return [2, meltQuote]; - } - }); - }); - }; - CashuWallet2.prototype.meltProofs = function(meltQuote, proofsToSend, options) { - return __awaiter3(this, void 0, void 0, function() { - var keys, _a, blindedMessages, secrets, blindingFactors, meltPayload, meltResponse, change; - return __generator3(this, function(_b) { - switch (_b.label) { - case 0: - return [4, this.getKeys(options === null || options === void 0 ? void 0 : options.keysetId)]; - case 1: - keys = _b.sent(); - _a = this.createBlankOutputs(sumProofs(proofsToSend) - meltQuote.amount, keys.id, options === null || options === void 0 ? void 0 : options.counter), blindedMessages = _a.blindedMessages, secrets = _a.secrets, blindingFactors = _a.blindingFactors; - if ((options === null || options === void 0 ? void 0 : options.privkey) != void 0) { - proofsToSend = (0, import_NUT11.getSignedProofs)(proofsToSend.map(function(p) { - return { - amount: p.amount, - C: (0, import_common.pointFromHex)(p.C), - id: p.id, - secret: new TextEncoder().encode(p.secret) - }; - }), options.privkey).map(function(p) { - return (0, import_client.serializeProof)(p); - }); - } - meltPayload = { - quote: meltQuote.quote, - inputs: proofsToSend, - outputs: __spreadArray([], blindedMessages, true) - }; - return [4, this.mint.melt(meltPayload)]; - case 2: - meltResponse = _b.sent(); - change = []; - if (meltResponse.change) { - change = this.constructProofs(meltResponse.change, blindingFactors, secrets, keys); - } - return [2, { - quote: meltResponse, - change - }]; - } - }); - }); - }; - CashuWallet2.prototype.createSwapPayload = function(amount, proofsToSend, keyset, outputAmounts, counter, pubkey, privkey) { - var totalAmount = proofsToSend.reduce(function(total, curr) { - return total + curr.amount; - }, 0); - if (outputAmounts && outputAmounts.sendAmounts && !outputAmounts.keepAmounts) { - outputAmounts.keepAmounts = splitAmount(totalAmount - amount - this.getFeesForProofs(proofsToSend), keyset.keys); - } - var keepBlindedMessages = this.createRandomBlindedMessages(totalAmount - amount - this.getFeesForProofs(proofsToSend), keyset, outputAmounts === null || outputAmounts === void 0 ? void 0 : outputAmounts.keepAmounts, counter); - if (this._seed && counter) { - counter = counter + keepBlindedMessages.secrets.length; - } - var sendBlindedMessages = this.createRandomBlindedMessages(amount, keyset, outputAmounts === null || outputAmounts === void 0 ? void 0 : outputAmounts.sendAmounts, counter, pubkey); - if (privkey) { - proofsToSend = (0, import_NUT11.getSignedProofs)(proofsToSend.map(function(p) { - return { - amount: p.amount, - C: (0, import_common.pointFromHex)(p.C), - id: p.id, - secret: new TextEncoder().encode(p.secret) - }; - }), privkey).map(function(p) { - return (0, import_client.serializeProof)(p); - }); - } - var blindingData = { - blindedMessages: __spreadArray(__spreadArray([], keepBlindedMessages.blindedMessages, true), sendBlindedMessages.blindedMessages, true), - secrets: __spreadArray(__spreadArray([], keepBlindedMessages.secrets, true), sendBlindedMessages.secrets, true), - blindingFactors: __spreadArray(__spreadArray([], keepBlindedMessages.blindingFactors, true), sendBlindedMessages.blindingFactors, true) - }; - var payload = { - inputs: proofsToSend, - outputs: __spreadArray([], blindingData.blindedMessages, true) - }; - return { payload, blindingData }; - }; - CashuWallet2.prototype.checkProofsStates = function(proofs) { - return __awaiter3(this, void 0, void 0, function() { - var enc, Ys, BATCH_SIZE, states, _loop_1, this_1, i; - return __generator3(this, function(_a) { - switch (_a.label) { - case 0: - enc = new TextEncoder(); - Ys = proofs.map(function(p) { - return (0, import_common.hashToCurve)(enc.encode(p.secret)).toHex(true); - }); - BATCH_SIZE = 100; - states = []; - _loop_1 = function(i2) { - var YsSlice, batchStates, stateMap, j, state; - return __generator3(this, function(_b) { - switch (_b.label) { - case 0: - YsSlice = Ys.slice(i2, i2 + BATCH_SIZE); - return [4, this_1.mint.check({ - Ys: YsSlice - })]; - case 1: - batchStates = _b.sent().states; - stateMap = {}; - batchStates.forEach(function(s) { - stateMap[s.Y] = s; - }); - for (j = 0; j < YsSlice.length; j++) { - state = stateMap[YsSlice[j]]; - if (!state) { - throw new Error("Could not find state for proof with Y: " + YsSlice[j]); - } - states.push(state); - } - return [ - 2 - /*return*/ - ]; - } - }); - }; - this_1 = this; - i = 0; - _a.label = 1; - case 1: - if (!(i < Ys.length)) return [3, 4]; - return [5, _loop_1(i)]; - case 2: - _a.sent(); - _a.label = 3; - case 3: - i += BATCH_SIZE; - return [3, 1]; - case 4: - return [2, states]; - } - }); - }); - }; - CashuWallet2.prototype.createRandomBlindedMessages = function(amount, keyset, split2, counter, pubkey) { - var amounts = splitAmount(amount, keyset.keys, split2); - return this.createBlindedMessages(amounts, keyset.id, counter, pubkey); - }; - CashuWallet2.prototype.createBlindedMessages = function(amounts, keysetId, counter, pubkey) { - if (counter != void 0 && !this._seed) { - throw new Error("Cannot create deterministic messages without seed. Instantiate CashuWallet with a bip39seed, or omit counter param."); - } - var blindedMessages = []; - var secrets = []; - var blindingFactors = []; - for (var i = 0; i < amounts.length; i++) { - var deterministicR = void 0; - var secretBytes = void 0; - if (pubkey) { - secretBytes = (0, import_NUT11.createP2PKsecret)(pubkey); - } else if (this._seed && counter != void 0) { - secretBytes = (0, import_NUT09.deriveSecret)(this._seed, keysetId, counter + i); - deterministicR = bytesToNumber((0, import_NUT09.deriveBlindingFactor)(this._seed, keysetId, counter + i)); - } else { - secretBytes = randomBytes(32); - } - if (!pubkey) { - var secretHex = bytesToHex(secretBytes); - secretBytes = new TextEncoder().encode(secretHex); - } - secrets.push(secretBytes); - var _a = (0, import_client.blindMessage)(secretBytes, deterministicR), B_ = _a.B_, r = _a.r; - blindingFactors.push(r); - var blindedMessage = new BlindedMessage(amounts[i], B_, keysetId); - blindedMessages.push(blindedMessage.getSerializedBlindedMessage()); - } - return { blindedMessages, secrets, blindingFactors, amounts }; - }; - CashuWallet2.prototype.createBlankOutputs = function(amount, keysetId, counter) { - var count = Math.ceil(Math.log2(amount)) || 1; - if (count < 0) { - count = 0; - } - var amounts = count ? Array(count).fill(1) : []; - var _a = this.createBlindedMessages(amounts, keysetId, counter), blindedMessages = _a.blindedMessages, blindingFactors = _a.blindingFactors, secrets = _a.secrets; - return { blindedMessages, secrets, blindingFactors }; - }; - CashuWallet2.prototype.constructProofs = function(promises, rs, secrets, keyset) { - return promises.map(function(p, i) { - var blindSignature = { id: p.id, amount: p.amount, C_: (0, import_common.pointFromHex)(p.C_) }; - var r = rs[i]; - var secret = secrets[i]; - var A = (0, import_common.pointFromHex)(keyset.keys[p.amount]); - return (0, import_client.constructProofFromPromise)(blindSignature, r, secret, A); - }).map(function(p) { - return (0, import_client.serializeProof)(p); - }); - }; - return CashuWallet2; - }() -); - -// node_modules/applesauce-content/dist/text/cashu.js -function cashuTokens() { - return (tree) => { - findAndReplace(tree, [ - [ - Tokens.cashu, - (_, $1) => { - try { - const token = getDecodedToken($1); - return { - type: "cashu", - token, - raw: $1 - }; - } catch (error) { - } - return false; - } - ] - ]); - }; -} - -// node_modules/applesauce-content/dist/text/emoji.js -function emojis() { - return (tree) => { - const event = tree.event; - if (!event) - return; - findAndReplace(tree, [ - [ - Tokens.emoji, - (full, $1) => { - try { - const tag = getEmojiTag(event, $1); - if (!tag) - return false; - return { - type: "emoji", - tag, - raw: full, - code: tag[1].toLowerCase(), - url: tag[2] - }; - } catch (error) { - } - return false; - } - ] - ]); - }; -} - -// node_modules/applesauce-content/dist/text/parser.js -function createEventContentTree(event, content) { - return { - type: "root", - event: typeof event !== "string" ? event : void 0, - children: [ - { - type: "text", - value: content || (typeof event === "string" ? event : event.content) - } - ] - }; -} - -// node_modules/applesauce-content/dist/text/hashtag.js -function hashtags() { - return (tree) => { - const event = tree.event; - findAndReplace(tree, [ - [ - Tokens.hashtag, - (_, $1) => { - try { - const tag = event && getHashtagTag(event, $1); - if (!tag && event) - return false; - return { - type: "hashtag", - tag, - name: $1, - hashtag: (tag == null ? void 0 : tag[1].toLowerCase()) || $1.toLowerCase() - }; - } catch (error) { - } - return false; - } - ] - ]); - }; -} - -// node_modules/applesauce-content/dist/text/gallery.js -function galleries(types = IMAGE_EXT) { - return (tree) => { - let links2 = []; - const commit = (index2) => { - if (links2.length > 1) { - const start = tree.children.indexOf(links2[0]); - const end = tree.children.indexOf(links2[links2.length - 1]); - tree.children.splice(start, 1 + end - start, { type: "gallery", links: links2.map((l) => l.href) }); - links2 = []; - return end - 1; - } else { - links2 = []; - return index2; - } - }; - for (let i = 0; i < tree.children.length; i++) { - const node = tree.children[i]; - try { - if (node.type === "link") { - const url = convertToUrl(node.href); - const filename = getURLFilename(url); - if (filename && types.some((ext) => filename.endsWith(ext))) { - links2.push(node); - } else { - i = commit(i); - } - } else if (node.type === "text" && links2.length > 0) { - const isEmpty = node.value === "\n" || !node.value.match(/[^\s]/g); - if (!isEmpty) - i = commit(i); - } - } catch (error) { - i = commit(i); - } - } - commit(tree.children.length); - }; -} - -// node_modules/applesauce-content/dist/text/lightning.js -function lightningInvoices() { - return (tree) => { - findAndReplace(tree, [ - [ - Tokens.lightning, - (_, $1) => { - try { - const invoice = $1; - const parsed = parseBolt11(invoice); - return { - type: "lightning", - invoice, - parsed - }; - } catch (error) { - } - return false; - } - ] - ]); - }; -} - -// node_modules/applesauce-content/dist/text/links.js -function links() { - return (tree) => { - findAndReplace(tree, [ - [ - Tokens.link, - (_) => { - try { - return { - type: "link", - href: new URL(_).toString(), - value: _ - }; - } catch (error) { - } - return false; - } - ] - ]); - }; -} - -// node_modules/applesauce-content/dist/text/content.js -var TextNoteContentSymbol = Symbol.for("text-note-content"); -var textNoteTransformers = [ - links, - nostrMentions, - galleries, - emojis, - hashtags, - lightningInvoices, - cashuTokens, - eolMetadata -]; -function getParsedContent(event, content, transformers = textNoteTransformers, cacheKey = TextNoteContentSymbol) { - if (typeof event === "string") { - const processor = unified(); - for (const transformer of transformers) { - processor.use(transformer); - } - return processor.runSync(createEventContentTree(event, content)); - } - if (!cacheKey) { - const processor = unified(); - for (const transformer of transformers) { - processor.use(transformer); - } - return processor.runSync(createEventContentTree(event, content)); - } - return getOrComputeCachedValue(event, cacheKey, () => { - const processor = unified(); - for (const transformer of transformers) { - processor.use(transformer); - } - return processor.runSync(createEventContentTree(event, content)); - }); -} - -// node_modules/applesauce-react/dist/hooks/use-rendered-content.js -function useRenderedContent(event, components, opts) { - const _components = (0, import_react14.useMemo)(() => (opts == null ? void 0 : opts.linkRenderers) ? { ...components, link: buildLinkRenderer(opts.linkRenderers) } : components, [opts == null ? void 0 : opts.linkRenderers, components]); - const nast = (0, import_react14.useMemo)(() => event ? getParsedContent(event, opts == null ? void 0 : opts.content, opts == null ? void 0 : opts.transformers, opts == null ? void 0 : opts.cacheKey) : void 0, [event, opts == null ? void 0 : opts.content, opts == null ? void 0 : opts.transformers, opts == null ? void 0 : opts.cacheKey]); - let truncated = nast; - if ((opts == null ? void 0 : opts.maxLength) && nast) - truncated = truncateContent(nast, opts.maxLength); - return useRenderNast(truncated, _components); -} -export { - AccountsContext, - AccountsProvider, - ActionsContext, - ActionsProvider, - EventStoreContext, - EventStoreProvider, - FactoryContext, - FactoryProvider, - helpers_exports as Helpers, - hooks_exports as Hooks -}; -/*! Bundled license information: - -ieee754/index.js: - (*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh *) - -buffer/index.js: - (*! - * The buffer module from node.js, for the browser. - * - * @author Feross Aboukhadijeh - * @license MIT - *) - -@noble/hashes/utils.js: - (*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) *) - -@noble/curves/utils.js: - (*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) *) - -@noble/curves/abstract/modular.js: - (*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) *) - -@noble/curves/abstract/curve.js: - (*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) *) - -@noble/curves/abstract/weierstrass.js: - (*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) *) - -@noble/curves/_shortw_utils.js: - (*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) *) - -@noble/curves/secp256k1.js: - (*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) *) - -@scure/base/lib/index.js: - (*! scure-base - MIT License (c) 2022 Paul Miller (paulmillr.com) *) - -@scure/bip32/lib/index.js: - (*! scure-bip32 - MIT License (c) 2022 Patricio Palladino, Paul Miller (paulmillr.com) *) - -@scure/bip39/index.js: - (*! scure-bip39 - MIT License (c) 2022 Patricio Palladino, Paul Miller (paulmillr.com) *) - -@noble/curves/esm/utils.js: - (*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) *) -*/ -//# sourceMappingURL=applesauce-react.js.map diff --git a/node_modules/.vite/deps_temp_742205d0/applesauce-react.js.map b/node_modules/.vite/deps_temp_742205d0/applesauce-react.js.map deleted file mode 100644 index 282b62e8..00000000 --- a/node_modules/.vite/deps_temp_742205d0/applesauce-react.js.map +++ /dev/null @@ -1,7 +0,0 @@ -{ - "version": 3, - "sources": ["../../extend/index.js", "../../base64-js/index.js", "../../ieee754/index.js", "../../buffer/index.js", "../../@noble/hashes/src/crypto.ts", "../../@noble/hashes/src/utils.ts", "../../@noble/hashes/src/_md.ts", "../../@noble/hashes/src/_u64.ts", "../../@noble/hashes/src/sha2.ts", "../../@noble/hashes/src/hmac.ts", "../../@noble/curves/src/utils.ts", "../../@noble/curves/src/abstract/modular.ts", "../../@noble/curves/src/abstract/curve.ts", "../../@noble/curves/src/abstract/weierstrass.ts", "../../@noble/curves/src/_shortw_utils.ts", "../../@noble/curves/src/abstract/hash-to-curve.ts", "../../@noble/curves/src/secp256k1.ts", "../../@noble/hashes/src/sha256.ts", "../../@noble/curves/src/abstract/utils.ts", "../../@cashu/crypto/src/util/utils.ts", "../../@cashu/crypto/src/common/index.ts", "../../@cashu/crypto/src/client/index.ts", "../../@noble/hashes/src/legacy.ts", "../../@scure/base/index.ts", "../../@scure/bip32/index.ts", "../../@noble/hashes/src/pbkdf2.ts", "../../@scure/bip39/index.js", "../../@scure/bip39/wordlists/english.js", "../../@cashu/crypto/src/client/NUT09.ts", "../../@cashu/crypto/src/common/NUT11.ts", "../../@cashu/crypto/src/client/NUT11.ts", "../../applesauce-react/dist/helpers/index.js", "../../applesauce-react/dist/helpers/nast.js", "../../applesauce-react/dist/helpers/build-link-renderer.js", "../../applesauce-react/dist/hooks/index.js", "../../applesauce-react/dist/hooks/use-account-manager.js", "../../applesauce-react/dist/providers/accounts-provider.js", "../../observable-hooks/dist/index.mjs", "../../applesauce-react/dist/hooks/use-accounts.js", "../../applesauce-react/dist/hooks/use-action-hub.js", "../../applesauce-react/dist/providers/actions-provider.js", "../../applesauce-react/dist/hooks/use-action.js", "../../applesauce-react/dist/hooks/use-active-account.js", "../../applesauce-react/dist/hooks/use-event-factory.js", "../../applesauce-react/dist/providers/factory-provider.js", "../../applesauce-react/dist/hooks/use-event-model.js", "../../applesauce-react/dist/hooks/use-event-store.js", "../../applesauce-react/dist/providers/store-provider.js", "../../applesauce-react/dist/hooks/use-observable-memo.js", "../../applesauce-react/dist/hooks/use-render-nast.js", "../../applesauce-react/dist/hooks/use-rendered-content.js", "../../unist-util-is/lib/index.js", "../../unist-util-visit-parents/lib/color.js", "../../unist-util-visit-parents/lib/index.js", "../../applesauce-content/dist/nast/find-and-replace.js", "../../applesauce-content/dist/nast/eol-metadata.js", "../../applesauce-content/dist/nast/truncate.js", "../../bail/index.js", "../../unified/lib/index.js", "../../devlop/lib/development.js", "../../is-plain-obj/index.js", "../../trough/lib/index.js", "../../unist-util-stringify-position/lib/index.js", "../../vfile-message/lib/index.js", "../../vfile/lib/minpath.browser.js", "../../vfile/lib/minproc.browser.js", "../../vfile/lib/minurl.shared.js", "../../vfile/lib/minurl.browser.js", "../../vfile/lib/index.js", "../../unified/lib/callable-instance.js", "../../applesauce-content/dist/helpers/regexp.js", "../../applesauce-content/dist/text/mentions.js", "../../@cashu/cashu-ts/src/model/types/mint/responses.ts", "../../@cashu/cashu-ts/src/model/types/wallet/paymentRequests.ts", "../../@cashu/cashu-ts/src/model/Errors.ts", "../../@cashu/cashu-ts/src/request.ts", "../../@cashu/cashu-ts/src/base64.ts", "../../@noble/curves/src/utils.ts", "../../@noble/curves/src/abstract/utils.ts", "../../@noble/hashes/src/_md.ts", "../../@noble/hashes/src/_u64.ts", "../../@noble/hashes/src/sha2.ts", "../../@cashu/cashu-ts/src/cbor.ts", "../../@cashu/cashu-ts/src/model/PaymentRequest.ts", "../../@cashu/cashu-ts/src/utils.ts", "../../@cashu/cashu-ts/src/legacy/nut-05.ts", "../../@cashu/cashu-ts/src/legacy/nut-04.ts", "../../@cashu/cashu-ts/src/legacy/nut-06.ts", "../../@cashu/cashu-ts/src/CashuMint.ts", "../../@cashu/cashu-ts/src/model/BlindedMessage.ts", "../../@cashu/cashu-ts/src/CashuWallet.ts", "../../applesauce-content/dist/text/cashu.js", "../../applesauce-content/dist/text/emoji.js", "../../applesauce-content/dist/text/parser.js", "../../applesauce-content/dist/text/hashtag.js", "../../applesauce-content/dist/text/gallery.js", "../../applesauce-content/dist/text/lightning.js", "../../applesauce-content/dist/text/links.js", "../../applesauce-content/dist/text/content.js"], - "sourcesContent": ["'use strict';\n\nvar hasOwn = Object.prototype.hasOwnProperty;\nvar toStr = Object.prototype.toString;\nvar defineProperty = Object.defineProperty;\nvar gOPD = Object.getOwnPropertyDescriptor;\n\nvar isArray = function isArray(arr) {\n\tif (typeof Array.isArray === 'function') {\n\t\treturn Array.isArray(arr);\n\t}\n\n\treturn toStr.call(arr) === '[object Array]';\n};\n\nvar isPlainObject = function isPlainObject(obj) {\n\tif (!obj || toStr.call(obj) !== '[object Object]') {\n\t\treturn false;\n\t}\n\n\tvar hasOwnConstructor = hasOwn.call(obj, 'constructor');\n\tvar hasIsPrototypeOf = obj.constructor && obj.constructor.prototype && hasOwn.call(obj.constructor.prototype, 'isPrototypeOf');\n\t// Not own constructor property must be Object\n\tif (obj.constructor && !hasOwnConstructor && !hasIsPrototypeOf) {\n\t\treturn false;\n\t}\n\n\t// Own properties are enumerated firstly, so to speed up,\n\t// if last one is own, then all properties are own.\n\tvar key;\n\tfor (key in obj) { /**/ }\n\n\treturn typeof key === 'undefined' || hasOwn.call(obj, key);\n};\n\n// If name is '__proto__', and Object.defineProperty is available, define __proto__ as an own property on target\nvar setProperty = function setProperty(target, options) {\n\tif (defineProperty && options.name === '__proto__') {\n\t\tdefineProperty(target, options.name, {\n\t\t\tenumerable: true,\n\t\t\tconfigurable: true,\n\t\t\tvalue: options.newValue,\n\t\t\twritable: true\n\t\t});\n\t} else {\n\t\ttarget[options.name] = options.newValue;\n\t}\n};\n\n// Return undefined instead of __proto__ if '__proto__' is not an own property\nvar getProperty = function getProperty(obj, name) {\n\tif (name === '__proto__') {\n\t\tif (!hasOwn.call(obj, name)) {\n\t\t\treturn void 0;\n\t\t} else if (gOPD) {\n\t\t\t// In early versions of node, obj['__proto__'] is buggy when obj has\n\t\t\t// __proto__ as an own property. Object.getOwnPropertyDescriptor() works.\n\t\t\treturn gOPD(obj, name).value;\n\t\t}\n\t}\n\n\treturn obj[name];\n};\n\nmodule.exports = function extend() {\n\tvar options, name, src, copy, copyIsArray, clone;\n\tvar target = arguments[0];\n\tvar i = 1;\n\tvar length = arguments.length;\n\tvar deep = false;\n\n\t// Handle a deep copy situation\n\tif (typeof target === 'boolean') {\n\t\tdeep = target;\n\t\ttarget = arguments[1] || {};\n\t\t// skip the boolean and the target\n\t\ti = 2;\n\t}\n\tif (target == null || (typeof target !== 'object' && typeof target !== 'function')) {\n\t\ttarget = {};\n\t}\n\n\tfor (; i < length; ++i) {\n\t\toptions = arguments[i];\n\t\t// Only deal with non-null/undefined values\n\t\tif (options != null) {\n\t\t\t// Extend the base object\n\t\t\tfor (name in options) {\n\t\t\t\tsrc = getProperty(target, name);\n\t\t\t\tcopy = getProperty(options, name);\n\n\t\t\t\t// Prevent never-ending loop\n\t\t\t\tif (target !== copy) {\n\t\t\t\t\t// Recurse if we're merging plain objects or arrays\n\t\t\t\t\tif (deep && copy && (isPlainObject(copy) || (copyIsArray = isArray(copy)))) {\n\t\t\t\t\t\tif (copyIsArray) {\n\t\t\t\t\t\t\tcopyIsArray = false;\n\t\t\t\t\t\t\tclone = src && isArray(src) ? src : [];\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tclone = src && isPlainObject(src) ? src : {};\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t// Never move original objects, clone them\n\t\t\t\t\t\tsetProperty(target, { name: name, newValue: extend(deep, clone, copy) });\n\n\t\t\t\t\t// Don't bring in undefined values\n\t\t\t\t\t} else if (typeof copy !== 'undefined') {\n\t\t\t\t\t\tsetProperty(target, { name: name, newValue: copy });\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t// Return the modified object\n\treturn target;\n};\n", "'use strict'\n\nexports.byteLength = byteLength\nexports.toByteArray = toByteArray\nexports.fromByteArray = fromByteArray\n\nvar lookup = []\nvar revLookup = []\nvar Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array\n\nvar code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'\nfor (var i = 0, len = code.length; i < len; ++i) {\n lookup[i] = code[i]\n revLookup[code.charCodeAt(i)] = i\n}\n\n// Support decoding URL-safe base64 strings, as Node.js does.\n// See: https://en.wikipedia.org/wiki/Base64#URL_applications\nrevLookup['-'.charCodeAt(0)] = 62\nrevLookup['_'.charCodeAt(0)] = 63\n\nfunction getLens (b64) {\n var len = b64.length\n\n if (len % 4 > 0) {\n throw new Error('Invalid string. Length must be a multiple of 4')\n }\n\n // Trim off extra bytes after placeholder bytes are found\n // See: https://github.com/beatgammit/base64-js/issues/42\n var validLen = b64.indexOf('=')\n if (validLen === -1) validLen = len\n\n var placeHoldersLen = validLen === len\n ? 0\n : 4 - (validLen % 4)\n\n return [validLen, placeHoldersLen]\n}\n\n// base64 is 4/3 + up to two characters of the original data\nfunction byteLength (b64) {\n var lens = getLens(b64)\n var validLen = lens[0]\n var placeHoldersLen = lens[1]\n return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen\n}\n\nfunction _byteLength (b64, validLen, placeHoldersLen) {\n return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen\n}\n\nfunction toByteArray (b64) {\n var tmp\n var lens = getLens(b64)\n var validLen = lens[0]\n var placeHoldersLen = lens[1]\n\n var arr = new Arr(_byteLength(b64, validLen, placeHoldersLen))\n\n var curByte = 0\n\n // if there are placeholders, only get up to the last complete 4 chars\n var len = placeHoldersLen > 0\n ? validLen - 4\n : validLen\n\n var i\n for (i = 0; i < len; i += 4) {\n tmp =\n (revLookup[b64.charCodeAt(i)] << 18) |\n (revLookup[b64.charCodeAt(i + 1)] << 12) |\n (revLookup[b64.charCodeAt(i + 2)] << 6) |\n revLookup[b64.charCodeAt(i + 3)]\n arr[curByte++] = (tmp >> 16) & 0xFF\n arr[curByte++] = (tmp >> 8) & 0xFF\n arr[curByte++] = tmp & 0xFF\n }\n\n if (placeHoldersLen === 2) {\n tmp =\n (revLookup[b64.charCodeAt(i)] << 2) |\n (revLookup[b64.charCodeAt(i + 1)] >> 4)\n arr[curByte++] = tmp & 0xFF\n }\n\n if (placeHoldersLen === 1) {\n tmp =\n (revLookup[b64.charCodeAt(i)] << 10) |\n (revLookup[b64.charCodeAt(i + 1)] << 4) |\n (revLookup[b64.charCodeAt(i + 2)] >> 2)\n arr[curByte++] = (tmp >> 8) & 0xFF\n arr[curByte++] = tmp & 0xFF\n }\n\n return arr\n}\n\nfunction tripletToBase64 (num) {\n return lookup[num >> 18 & 0x3F] +\n lookup[num >> 12 & 0x3F] +\n lookup[num >> 6 & 0x3F] +\n lookup[num & 0x3F]\n}\n\nfunction encodeChunk (uint8, start, end) {\n var tmp\n var output = []\n for (var i = start; i < end; i += 3) {\n tmp =\n ((uint8[i] << 16) & 0xFF0000) +\n ((uint8[i + 1] << 8) & 0xFF00) +\n (uint8[i + 2] & 0xFF)\n output.push(tripletToBase64(tmp))\n }\n return output.join('')\n}\n\nfunction fromByteArray (uint8) {\n var tmp\n var len = uint8.length\n var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes\n var parts = []\n var maxChunkLength = 16383 // must be multiple of 3\n\n // go through the array every three bytes, we'll deal with trailing stuff later\n for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) {\n parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength)))\n }\n\n // pad the end with zeros, but make sure to not forget the extra bytes\n if (extraBytes === 1) {\n tmp = uint8[len - 1]\n parts.push(\n lookup[tmp >> 2] +\n lookup[(tmp << 4) & 0x3F] +\n '=='\n )\n } else if (extraBytes === 2) {\n tmp = (uint8[len - 2] << 8) + uint8[len - 1]\n parts.push(\n lookup[tmp >> 10] +\n lookup[(tmp >> 4) & 0x3F] +\n lookup[(tmp << 2) & 0x3F] +\n '='\n )\n }\n\n return parts.join('')\n}\n", "/*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh */\nexports.read = function (buffer, offset, isLE, mLen, nBytes) {\n var e, m\n var eLen = (nBytes * 8) - mLen - 1\n var eMax = (1 << eLen) - 1\n var eBias = eMax >> 1\n var nBits = -7\n var i = isLE ? (nBytes - 1) : 0\n var d = isLE ? -1 : 1\n var s = buffer[offset + i]\n\n i += d\n\n e = s & ((1 << (-nBits)) - 1)\n s >>= (-nBits)\n nBits += eLen\n for (; nBits > 0; e = (e * 256) + buffer[offset + i], i += d, nBits -= 8) {}\n\n m = e & ((1 << (-nBits)) - 1)\n e >>= (-nBits)\n nBits += mLen\n for (; nBits > 0; m = (m * 256) + buffer[offset + i], i += d, nBits -= 8) {}\n\n if (e === 0) {\n e = 1 - eBias\n } else if (e === eMax) {\n return m ? NaN : ((s ? -1 : 1) * Infinity)\n } else {\n m = m + Math.pow(2, mLen)\n e = e - eBias\n }\n return (s ? -1 : 1) * m * Math.pow(2, e - mLen)\n}\n\nexports.write = function (buffer, value, offset, isLE, mLen, nBytes) {\n var e, m, c\n var eLen = (nBytes * 8) - mLen - 1\n var eMax = (1 << eLen) - 1\n var eBias = eMax >> 1\n var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0)\n var i = isLE ? 0 : (nBytes - 1)\n var d = isLE ? 1 : -1\n var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0\n\n value = Math.abs(value)\n\n if (isNaN(value) || value === Infinity) {\n m = isNaN(value) ? 1 : 0\n e = eMax\n } else {\n e = Math.floor(Math.log(value) / Math.LN2)\n if (value * (c = Math.pow(2, -e)) < 1) {\n e--\n c *= 2\n }\n if (e + eBias >= 1) {\n value += rt / c\n } else {\n value += rt * Math.pow(2, 1 - eBias)\n }\n if (value * c >= 2) {\n e++\n c /= 2\n }\n\n if (e + eBias >= eMax) {\n m = 0\n e = eMax\n } else if (e + eBias >= 1) {\n m = ((value * c) - 1) * Math.pow(2, mLen)\n e = e + eBias\n } else {\n m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen)\n e = 0\n }\n }\n\n for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {}\n\n e = (e << mLen) | m\n eLen += mLen\n for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {}\n\n buffer[offset + i - d] |= s * 128\n}\n", "/*!\n * The buffer module from node.js, for the browser.\n *\n * @author Feross Aboukhadijeh \n * @license MIT\n */\n/* eslint-disable no-proto */\n\n'use strict'\n\nconst base64 = require('base64-js')\nconst ieee754 = require('ieee754')\nconst customInspectSymbol =\n (typeof Symbol === 'function' && typeof Symbol['for'] === 'function') // eslint-disable-line dot-notation\n ? Symbol['for']('nodejs.util.inspect.custom') // eslint-disable-line dot-notation\n : null\n\nexports.Buffer = Buffer\nexports.SlowBuffer = SlowBuffer\nexports.INSPECT_MAX_BYTES = 50\n\nconst K_MAX_LENGTH = 0x7fffffff\nexports.kMaxLength = K_MAX_LENGTH\n\n/**\n * If `Buffer.TYPED_ARRAY_SUPPORT`:\n * === true Use Uint8Array implementation (fastest)\n * === false Print warning and recommend using `buffer` v4.x which has an Object\n * implementation (most compatible, even IE6)\n *\n * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+,\n * Opera 11.6+, iOS 4.2+.\n *\n * We report that the browser does not support typed arrays if the are not subclassable\n * using __proto__. Firefox 4-29 lacks support for adding new properties to `Uint8Array`\n * (See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438). IE 10 lacks support\n * for __proto__ and has a buggy typed array implementation.\n */\nBuffer.TYPED_ARRAY_SUPPORT = typedArraySupport()\n\nif (!Buffer.TYPED_ARRAY_SUPPORT && typeof console !== 'undefined' &&\n typeof console.error === 'function') {\n console.error(\n 'This browser lacks typed array (Uint8Array) support which is required by ' +\n '`buffer` v5.x. Use `buffer` v4.x if you require old browser support.'\n )\n}\n\nfunction typedArraySupport () {\n // Can typed array instances can be augmented?\n try {\n const arr = new Uint8Array(1)\n const proto = { foo: function () { return 42 } }\n Object.setPrototypeOf(proto, Uint8Array.prototype)\n Object.setPrototypeOf(arr, proto)\n return arr.foo() === 42\n } catch (e) {\n return false\n }\n}\n\nObject.defineProperty(Buffer.prototype, 'parent', {\n enumerable: true,\n get: function () {\n if (!Buffer.isBuffer(this)) return undefined\n return this.buffer\n }\n})\n\nObject.defineProperty(Buffer.prototype, 'offset', {\n enumerable: true,\n get: function () {\n if (!Buffer.isBuffer(this)) return undefined\n return this.byteOffset\n }\n})\n\nfunction createBuffer (length) {\n if (length > K_MAX_LENGTH) {\n throw new RangeError('The value \"' + length + '\" is invalid for option \"size\"')\n }\n // Return an augmented `Uint8Array` instance\n const buf = new Uint8Array(length)\n Object.setPrototypeOf(buf, Buffer.prototype)\n return buf\n}\n\n/**\n * The Buffer constructor returns instances of `Uint8Array` that have their\n * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of\n * `Uint8Array`, so the returned instances will have all the node `Buffer` methods\n * and the `Uint8Array` methods. Square bracket notation works as expected -- it\n * returns a single octet.\n *\n * The `Uint8Array` prototype remains unmodified.\n */\n\nfunction Buffer (arg, encodingOrOffset, length) {\n // Common case.\n if (typeof arg === 'number') {\n if (typeof encodingOrOffset === 'string') {\n throw new TypeError(\n 'The \"string\" argument must be of type string. Received type number'\n )\n }\n return allocUnsafe(arg)\n }\n return from(arg, encodingOrOffset, length)\n}\n\nBuffer.poolSize = 8192 // not used by this implementation\n\nfunction from (value, encodingOrOffset, length) {\n if (typeof value === 'string') {\n return fromString(value, encodingOrOffset)\n }\n\n if (ArrayBuffer.isView(value)) {\n return fromArrayView(value)\n }\n\n if (value == null) {\n throw new TypeError(\n 'The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' +\n 'or Array-like Object. Received type ' + (typeof value)\n )\n }\n\n if (isInstance(value, ArrayBuffer) ||\n (value && isInstance(value.buffer, ArrayBuffer))) {\n return fromArrayBuffer(value, encodingOrOffset, length)\n }\n\n if (typeof SharedArrayBuffer !== 'undefined' &&\n (isInstance(value, SharedArrayBuffer) ||\n (value && isInstance(value.buffer, SharedArrayBuffer)))) {\n return fromArrayBuffer(value, encodingOrOffset, length)\n }\n\n if (typeof value === 'number') {\n throw new TypeError(\n 'The \"value\" argument must not be of type number. Received type number'\n )\n }\n\n const valueOf = value.valueOf && value.valueOf()\n if (valueOf != null && valueOf !== value) {\n return Buffer.from(valueOf, encodingOrOffset, length)\n }\n\n const b = fromObject(value)\n if (b) return b\n\n if (typeof Symbol !== 'undefined' && Symbol.toPrimitive != null &&\n typeof value[Symbol.toPrimitive] === 'function') {\n return Buffer.from(value[Symbol.toPrimitive]('string'), encodingOrOffset, length)\n }\n\n throw new TypeError(\n 'The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' +\n 'or Array-like Object. Received type ' + (typeof value)\n )\n}\n\n/**\n * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError\n * if value is a number.\n * Buffer.from(str[, encoding])\n * Buffer.from(array)\n * Buffer.from(buffer)\n * Buffer.from(arrayBuffer[, byteOffset[, length]])\n **/\nBuffer.from = function (value, encodingOrOffset, length) {\n return from(value, encodingOrOffset, length)\n}\n\n// Note: Change prototype *after* Buffer.from is defined to workaround Chrome bug:\n// https://github.com/feross/buffer/pull/148\nObject.setPrototypeOf(Buffer.prototype, Uint8Array.prototype)\nObject.setPrototypeOf(Buffer, Uint8Array)\n\nfunction assertSize (size) {\n if (typeof size !== 'number') {\n throw new TypeError('\"size\" argument must be of type number')\n } else if (size < 0) {\n throw new RangeError('The value \"' + size + '\" is invalid for option \"size\"')\n }\n}\n\nfunction alloc (size, fill, encoding) {\n assertSize(size)\n if (size <= 0) {\n return createBuffer(size)\n }\n if (fill !== undefined) {\n // Only pay attention to encoding if it's a string. This\n // prevents accidentally sending in a number that would\n // be interpreted as a start offset.\n return typeof encoding === 'string'\n ? createBuffer(size).fill(fill, encoding)\n : createBuffer(size).fill(fill)\n }\n return createBuffer(size)\n}\n\n/**\n * Creates a new filled Buffer instance.\n * alloc(size[, fill[, encoding]])\n **/\nBuffer.alloc = function (size, fill, encoding) {\n return alloc(size, fill, encoding)\n}\n\nfunction allocUnsafe (size) {\n assertSize(size)\n return createBuffer(size < 0 ? 0 : checked(size) | 0)\n}\n\n/**\n * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance.\n * */\nBuffer.allocUnsafe = function (size) {\n return allocUnsafe(size)\n}\n/**\n * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance.\n */\nBuffer.allocUnsafeSlow = function (size) {\n return allocUnsafe(size)\n}\n\nfunction fromString (string, encoding) {\n if (typeof encoding !== 'string' || encoding === '') {\n encoding = 'utf8'\n }\n\n if (!Buffer.isEncoding(encoding)) {\n throw new TypeError('Unknown encoding: ' + encoding)\n }\n\n const length = byteLength(string, encoding) | 0\n let buf = createBuffer(length)\n\n const actual = buf.write(string, encoding)\n\n if (actual !== length) {\n // Writing a hex string, for example, that contains invalid characters will\n // cause everything after the first invalid character to be ignored. (e.g.\n // 'abxxcd' will be treated as 'ab')\n buf = buf.slice(0, actual)\n }\n\n return buf\n}\n\nfunction fromArrayLike (array) {\n const length = array.length < 0 ? 0 : checked(array.length) | 0\n const buf = createBuffer(length)\n for (let i = 0; i < length; i += 1) {\n buf[i] = array[i] & 255\n }\n return buf\n}\n\nfunction fromArrayView (arrayView) {\n if (isInstance(arrayView, Uint8Array)) {\n const copy = new Uint8Array(arrayView)\n return fromArrayBuffer(copy.buffer, copy.byteOffset, copy.byteLength)\n }\n return fromArrayLike(arrayView)\n}\n\nfunction fromArrayBuffer (array, byteOffset, length) {\n if (byteOffset < 0 || array.byteLength < byteOffset) {\n throw new RangeError('\"offset\" is outside of buffer bounds')\n }\n\n if (array.byteLength < byteOffset + (length || 0)) {\n throw new RangeError('\"length\" is outside of buffer bounds')\n }\n\n let buf\n if (byteOffset === undefined && length === undefined) {\n buf = new Uint8Array(array)\n } else if (length === undefined) {\n buf = new Uint8Array(array, byteOffset)\n } else {\n buf = new Uint8Array(array, byteOffset, length)\n }\n\n // Return an augmented `Uint8Array` instance\n Object.setPrototypeOf(buf, Buffer.prototype)\n\n return buf\n}\n\nfunction fromObject (obj) {\n if (Buffer.isBuffer(obj)) {\n const len = checked(obj.length) | 0\n const buf = createBuffer(len)\n\n if (buf.length === 0) {\n return buf\n }\n\n obj.copy(buf, 0, 0, len)\n return buf\n }\n\n if (obj.length !== undefined) {\n if (typeof obj.length !== 'number' || numberIsNaN(obj.length)) {\n return createBuffer(0)\n }\n return fromArrayLike(obj)\n }\n\n if (obj.type === 'Buffer' && Array.isArray(obj.data)) {\n return fromArrayLike(obj.data)\n }\n}\n\nfunction checked (length) {\n // Note: cannot use `length < K_MAX_LENGTH` here because that fails when\n // length is NaN (which is otherwise coerced to zero.)\n if (length >= K_MAX_LENGTH) {\n throw new RangeError('Attempt to allocate Buffer larger than maximum ' +\n 'size: 0x' + K_MAX_LENGTH.toString(16) + ' bytes')\n }\n return length | 0\n}\n\nfunction SlowBuffer (length) {\n if (+length != length) { // eslint-disable-line eqeqeq\n length = 0\n }\n return Buffer.alloc(+length)\n}\n\nBuffer.isBuffer = function isBuffer (b) {\n return b != null && b._isBuffer === true &&\n b !== Buffer.prototype // so Buffer.isBuffer(Buffer.prototype) will be false\n}\n\nBuffer.compare = function compare (a, b) {\n if (isInstance(a, Uint8Array)) a = Buffer.from(a, a.offset, a.byteLength)\n if (isInstance(b, Uint8Array)) b = Buffer.from(b, b.offset, b.byteLength)\n if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) {\n throw new TypeError(\n 'The \"buf1\", \"buf2\" arguments must be one of type Buffer or Uint8Array'\n )\n }\n\n if (a === b) return 0\n\n let x = a.length\n let y = b.length\n\n for (let i = 0, len = Math.min(x, y); i < len; ++i) {\n if (a[i] !== b[i]) {\n x = a[i]\n y = b[i]\n break\n }\n }\n\n if (x < y) return -1\n if (y < x) return 1\n return 0\n}\n\nBuffer.isEncoding = function isEncoding (encoding) {\n switch (String(encoding).toLowerCase()) {\n case 'hex':\n case 'utf8':\n case 'utf-8':\n case 'ascii':\n case 'latin1':\n case 'binary':\n case 'base64':\n case 'ucs2':\n case 'ucs-2':\n case 'utf16le':\n case 'utf-16le':\n return true\n default:\n return false\n }\n}\n\nBuffer.concat = function concat (list, length) {\n if (!Array.isArray(list)) {\n throw new TypeError('\"list\" argument must be an Array of Buffers')\n }\n\n if (list.length === 0) {\n return Buffer.alloc(0)\n }\n\n let i\n if (length === undefined) {\n length = 0\n for (i = 0; i < list.length; ++i) {\n length += list[i].length\n }\n }\n\n const buffer = Buffer.allocUnsafe(length)\n let pos = 0\n for (i = 0; i < list.length; ++i) {\n let buf = list[i]\n if (isInstance(buf, Uint8Array)) {\n if (pos + buf.length > buffer.length) {\n if (!Buffer.isBuffer(buf)) buf = Buffer.from(buf)\n buf.copy(buffer, pos)\n } else {\n Uint8Array.prototype.set.call(\n buffer,\n buf,\n pos\n )\n }\n } else if (!Buffer.isBuffer(buf)) {\n throw new TypeError('\"list\" argument must be an Array of Buffers')\n } else {\n buf.copy(buffer, pos)\n }\n pos += buf.length\n }\n return buffer\n}\n\nfunction byteLength (string, encoding) {\n if (Buffer.isBuffer(string)) {\n return string.length\n }\n if (ArrayBuffer.isView(string) || isInstance(string, ArrayBuffer)) {\n return string.byteLength\n }\n if (typeof string !== 'string') {\n throw new TypeError(\n 'The \"string\" argument must be one of type string, Buffer, or ArrayBuffer. ' +\n 'Received type ' + typeof string\n )\n }\n\n const len = string.length\n const mustMatch = (arguments.length > 2 && arguments[2] === true)\n if (!mustMatch && len === 0) return 0\n\n // Use a for loop to avoid recursion\n let loweredCase = false\n for (;;) {\n switch (encoding) {\n case 'ascii':\n case 'latin1':\n case 'binary':\n return len\n case 'utf8':\n case 'utf-8':\n return utf8ToBytes(string).length\n case 'ucs2':\n case 'ucs-2':\n case 'utf16le':\n case 'utf-16le':\n return len * 2\n case 'hex':\n return len >>> 1\n case 'base64':\n return base64ToBytes(string).length\n default:\n if (loweredCase) {\n return mustMatch ? -1 : utf8ToBytes(string).length // assume utf8\n }\n encoding = ('' + encoding).toLowerCase()\n loweredCase = true\n }\n }\n}\nBuffer.byteLength = byteLength\n\nfunction slowToString (encoding, start, end) {\n let loweredCase = false\n\n // No need to verify that \"this.length <= MAX_UINT32\" since it's a read-only\n // property of a typed array.\n\n // This behaves neither like String nor Uint8Array in that we set start/end\n // to their upper/lower bounds if the value passed is out of range.\n // undefined is handled specially as per ECMA-262 6th Edition,\n // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization.\n if (start === undefined || start < 0) {\n start = 0\n }\n // Return early if start > this.length. Done here to prevent potential uint32\n // coercion fail below.\n if (start > this.length) {\n return ''\n }\n\n if (end === undefined || end > this.length) {\n end = this.length\n }\n\n if (end <= 0) {\n return ''\n }\n\n // Force coercion to uint32. This will also coerce falsey/NaN values to 0.\n end >>>= 0\n start >>>= 0\n\n if (end <= start) {\n return ''\n }\n\n if (!encoding) encoding = 'utf8'\n\n while (true) {\n switch (encoding) {\n case 'hex':\n return hexSlice(this, start, end)\n\n case 'utf8':\n case 'utf-8':\n return utf8Slice(this, start, end)\n\n case 'ascii':\n return asciiSlice(this, start, end)\n\n case 'latin1':\n case 'binary':\n return latin1Slice(this, start, end)\n\n case 'base64':\n return base64Slice(this, start, end)\n\n case 'ucs2':\n case 'ucs-2':\n case 'utf16le':\n case 'utf-16le':\n return utf16leSlice(this, start, end)\n\n default:\n if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)\n encoding = (encoding + '').toLowerCase()\n loweredCase = true\n }\n }\n}\n\n// This property is used by `Buffer.isBuffer` (and the `is-buffer` npm package)\n// to detect a Buffer instance. It's not possible to use `instanceof Buffer`\n// reliably in a browserify context because there could be multiple different\n// copies of the 'buffer' package in use. This method works even for Buffer\n// instances that were created from another copy of the `buffer` package.\n// See: https://github.com/feross/buffer/issues/154\nBuffer.prototype._isBuffer = true\n\nfunction swap (b, n, m) {\n const i = b[n]\n b[n] = b[m]\n b[m] = i\n}\n\nBuffer.prototype.swap16 = function swap16 () {\n const len = this.length\n if (len % 2 !== 0) {\n throw new RangeError('Buffer size must be a multiple of 16-bits')\n }\n for (let i = 0; i < len; i += 2) {\n swap(this, i, i + 1)\n }\n return this\n}\n\nBuffer.prototype.swap32 = function swap32 () {\n const len = this.length\n if (len % 4 !== 0) {\n throw new RangeError('Buffer size must be a multiple of 32-bits')\n }\n for (let i = 0; i < len; i += 4) {\n swap(this, i, i + 3)\n swap(this, i + 1, i + 2)\n }\n return this\n}\n\nBuffer.prototype.swap64 = function swap64 () {\n const len = this.length\n if (len % 8 !== 0) {\n throw new RangeError('Buffer size must be a multiple of 64-bits')\n }\n for (let i = 0; i < len; i += 8) {\n swap(this, i, i + 7)\n swap(this, i + 1, i + 6)\n swap(this, i + 2, i + 5)\n swap(this, i + 3, i + 4)\n }\n return this\n}\n\nBuffer.prototype.toString = function toString () {\n const length = this.length\n if (length === 0) return ''\n if (arguments.length === 0) return utf8Slice(this, 0, length)\n return slowToString.apply(this, arguments)\n}\n\nBuffer.prototype.toLocaleString = Buffer.prototype.toString\n\nBuffer.prototype.equals = function equals (b) {\n if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer')\n if (this === b) return true\n return Buffer.compare(this, b) === 0\n}\n\nBuffer.prototype.inspect = function inspect () {\n let str = ''\n const max = exports.INSPECT_MAX_BYTES\n str = this.toString('hex', 0, max).replace(/(.{2})/g, '$1 ').trim()\n if (this.length > max) str += ' ... '\n return ''\n}\nif (customInspectSymbol) {\n Buffer.prototype[customInspectSymbol] = Buffer.prototype.inspect\n}\n\nBuffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) {\n if (isInstance(target, Uint8Array)) {\n target = Buffer.from(target, target.offset, target.byteLength)\n }\n if (!Buffer.isBuffer(target)) {\n throw new TypeError(\n 'The \"target\" argument must be one of type Buffer or Uint8Array. ' +\n 'Received type ' + (typeof target)\n )\n }\n\n if (start === undefined) {\n start = 0\n }\n if (end === undefined) {\n end = target ? target.length : 0\n }\n if (thisStart === undefined) {\n thisStart = 0\n }\n if (thisEnd === undefined) {\n thisEnd = this.length\n }\n\n if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) {\n throw new RangeError('out of range index')\n }\n\n if (thisStart >= thisEnd && start >= end) {\n return 0\n }\n if (thisStart >= thisEnd) {\n return -1\n }\n if (start >= end) {\n return 1\n }\n\n start >>>= 0\n end >>>= 0\n thisStart >>>= 0\n thisEnd >>>= 0\n\n if (this === target) return 0\n\n let x = thisEnd - thisStart\n let y = end - start\n const len = Math.min(x, y)\n\n const thisCopy = this.slice(thisStart, thisEnd)\n const targetCopy = target.slice(start, end)\n\n for (let i = 0; i < len; ++i) {\n if (thisCopy[i] !== targetCopy[i]) {\n x = thisCopy[i]\n y = targetCopy[i]\n break\n }\n }\n\n if (x < y) return -1\n if (y < x) return 1\n return 0\n}\n\n// Finds either the first index of `val` in `buffer` at offset >= `byteOffset`,\n// OR the last index of `val` in `buffer` at offset <= `byteOffset`.\n//\n// Arguments:\n// - buffer - a Buffer to search\n// - val - a string, Buffer, or number\n// - byteOffset - an index into `buffer`; will be clamped to an int32\n// - encoding - an optional encoding, relevant is val is a string\n// - dir - true for indexOf, false for lastIndexOf\nfunction bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) {\n // Empty buffer means no match\n if (buffer.length === 0) return -1\n\n // Normalize byteOffset\n if (typeof byteOffset === 'string') {\n encoding = byteOffset\n byteOffset = 0\n } else if (byteOffset > 0x7fffffff) {\n byteOffset = 0x7fffffff\n } else if (byteOffset < -0x80000000) {\n byteOffset = -0x80000000\n }\n byteOffset = +byteOffset // Coerce to Number.\n if (numberIsNaN(byteOffset)) {\n // byteOffset: it it's undefined, null, NaN, \"foo\", etc, search whole buffer\n byteOffset = dir ? 0 : (buffer.length - 1)\n }\n\n // Normalize byteOffset: negative offsets start from the end of the buffer\n if (byteOffset < 0) byteOffset = buffer.length + byteOffset\n if (byteOffset >= buffer.length) {\n if (dir) return -1\n else byteOffset = buffer.length - 1\n } else if (byteOffset < 0) {\n if (dir) byteOffset = 0\n else return -1\n }\n\n // Normalize val\n if (typeof val === 'string') {\n val = Buffer.from(val, encoding)\n }\n\n // Finally, search either indexOf (if dir is true) or lastIndexOf\n if (Buffer.isBuffer(val)) {\n // Special case: looking for empty string/buffer always fails\n if (val.length === 0) {\n return -1\n }\n return arrayIndexOf(buffer, val, byteOffset, encoding, dir)\n } else if (typeof val === 'number') {\n val = val & 0xFF // Search for a byte value [0-255]\n if (typeof Uint8Array.prototype.indexOf === 'function') {\n if (dir) {\n return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset)\n } else {\n return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset)\n }\n }\n return arrayIndexOf(buffer, [val], byteOffset, encoding, dir)\n }\n\n throw new TypeError('val must be string, number or Buffer')\n}\n\nfunction arrayIndexOf (arr, val, byteOffset, encoding, dir) {\n let indexSize = 1\n let arrLength = arr.length\n let valLength = val.length\n\n if (encoding !== undefined) {\n encoding = String(encoding).toLowerCase()\n if (encoding === 'ucs2' || encoding === 'ucs-2' ||\n encoding === 'utf16le' || encoding === 'utf-16le') {\n if (arr.length < 2 || val.length < 2) {\n return -1\n }\n indexSize = 2\n arrLength /= 2\n valLength /= 2\n byteOffset /= 2\n }\n }\n\n function read (buf, i) {\n if (indexSize === 1) {\n return buf[i]\n } else {\n return buf.readUInt16BE(i * indexSize)\n }\n }\n\n let i\n if (dir) {\n let foundIndex = -1\n for (i = byteOffset; i < arrLength; i++) {\n if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) {\n if (foundIndex === -1) foundIndex = i\n if (i - foundIndex + 1 === valLength) return foundIndex * indexSize\n } else {\n if (foundIndex !== -1) i -= i - foundIndex\n foundIndex = -1\n }\n }\n } else {\n if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength\n for (i = byteOffset; i >= 0; i--) {\n let found = true\n for (let j = 0; j < valLength; j++) {\n if (read(arr, i + j) !== read(val, j)) {\n found = false\n break\n }\n }\n if (found) return i\n }\n }\n\n return -1\n}\n\nBuffer.prototype.includes = function includes (val, byteOffset, encoding) {\n return this.indexOf(val, byteOffset, encoding) !== -1\n}\n\nBuffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) {\n return bidirectionalIndexOf(this, val, byteOffset, encoding, true)\n}\n\nBuffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) {\n return bidirectionalIndexOf(this, val, byteOffset, encoding, false)\n}\n\nfunction hexWrite (buf, string, offset, length) {\n offset = Number(offset) || 0\n const remaining = buf.length - offset\n if (!length) {\n length = remaining\n } else {\n length = Number(length)\n if (length > remaining) {\n length = remaining\n }\n }\n\n const strLen = string.length\n\n if (length > strLen / 2) {\n length = strLen / 2\n }\n let i\n for (i = 0; i < length; ++i) {\n const parsed = parseInt(string.substr(i * 2, 2), 16)\n if (numberIsNaN(parsed)) return i\n buf[offset + i] = parsed\n }\n return i\n}\n\nfunction utf8Write (buf, string, offset, length) {\n return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length)\n}\n\nfunction asciiWrite (buf, string, offset, length) {\n return blitBuffer(asciiToBytes(string), buf, offset, length)\n}\n\nfunction base64Write (buf, string, offset, length) {\n return blitBuffer(base64ToBytes(string), buf, offset, length)\n}\n\nfunction ucs2Write (buf, string, offset, length) {\n return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length)\n}\n\nBuffer.prototype.write = function write (string, offset, length, encoding) {\n // Buffer#write(string)\n if (offset === undefined) {\n encoding = 'utf8'\n length = this.length\n offset = 0\n // Buffer#write(string, encoding)\n } else if (length === undefined && typeof offset === 'string') {\n encoding = offset\n length = this.length\n offset = 0\n // Buffer#write(string, offset[, length][, encoding])\n } else if (isFinite(offset)) {\n offset = offset >>> 0\n if (isFinite(length)) {\n length = length >>> 0\n if (encoding === undefined) encoding = 'utf8'\n } else {\n encoding = length\n length = undefined\n }\n } else {\n throw new Error(\n 'Buffer.write(string, encoding, offset[, length]) is no longer supported'\n )\n }\n\n const remaining = this.length - offset\n if (length === undefined || length > remaining) length = remaining\n\n if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) {\n throw new RangeError('Attempt to write outside buffer bounds')\n }\n\n if (!encoding) encoding = 'utf8'\n\n let loweredCase = false\n for (;;) {\n switch (encoding) {\n case 'hex':\n return hexWrite(this, string, offset, length)\n\n case 'utf8':\n case 'utf-8':\n return utf8Write(this, string, offset, length)\n\n case 'ascii':\n case 'latin1':\n case 'binary':\n return asciiWrite(this, string, offset, length)\n\n case 'base64':\n // Warning: maxLength not taken into account in base64Write\n return base64Write(this, string, offset, length)\n\n case 'ucs2':\n case 'ucs-2':\n case 'utf16le':\n case 'utf-16le':\n return ucs2Write(this, string, offset, length)\n\n default:\n if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)\n encoding = ('' + encoding).toLowerCase()\n loweredCase = true\n }\n }\n}\n\nBuffer.prototype.toJSON = function toJSON () {\n return {\n type: 'Buffer',\n data: Array.prototype.slice.call(this._arr || this, 0)\n }\n}\n\nfunction base64Slice (buf, start, end) {\n if (start === 0 && end === buf.length) {\n return base64.fromByteArray(buf)\n } else {\n return base64.fromByteArray(buf.slice(start, end))\n }\n}\n\nfunction utf8Slice (buf, start, end) {\n end = Math.min(buf.length, end)\n const res = []\n\n let i = start\n while (i < end) {\n const firstByte = buf[i]\n let codePoint = null\n let bytesPerSequence = (firstByte > 0xEF)\n ? 4\n : (firstByte > 0xDF)\n ? 3\n : (firstByte > 0xBF)\n ? 2\n : 1\n\n if (i + bytesPerSequence <= end) {\n let secondByte, thirdByte, fourthByte, tempCodePoint\n\n switch (bytesPerSequence) {\n case 1:\n if (firstByte < 0x80) {\n codePoint = firstByte\n }\n break\n case 2:\n secondByte = buf[i + 1]\n if ((secondByte & 0xC0) === 0x80) {\n tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F)\n if (tempCodePoint > 0x7F) {\n codePoint = tempCodePoint\n }\n }\n break\n case 3:\n secondByte = buf[i + 1]\n thirdByte = buf[i + 2]\n if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) {\n tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F)\n if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) {\n codePoint = tempCodePoint\n }\n }\n break\n case 4:\n secondByte = buf[i + 1]\n thirdByte = buf[i + 2]\n fourthByte = buf[i + 3]\n if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) {\n tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F)\n if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) {\n codePoint = tempCodePoint\n }\n }\n }\n }\n\n if (codePoint === null) {\n // we did not generate a valid codePoint so insert a\n // replacement char (U+FFFD) and advance only 1 byte\n codePoint = 0xFFFD\n bytesPerSequence = 1\n } else if (codePoint > 0xFFFF) {\n // encode to utf16 (surrogate pair dance)\n codePoint -= 0x10000\n res.push(codePoint >>> 10 & 0x3FF | 0xD800)\n codePoint = 0xDC00 | codePoint & 0x3FF\n }\n\n res.push(codePoint)\n i += bytesPerSequence\n }\n\n return decodeCodePointsArray(res)\n}\n\n// Based on http://stackoverflow.com/a/22747272/680742, the browser with\n// the lowest limit is Chrome, with 0x10000 args.\n// We go 1 magnitude less, for safety\nconst MAX_ARGUMENTS_LENGTH = 0x1000\n\nfunction decodeCodePointsArray (codePoints) {\n const len = codePoints.length\n if (len <= MAX_ARGUMENTS_LENGTH) {\n return String.fromCharCode.apply(String, codePoints) // avoid extra slice()\n }\n\n // Decode in chunks to avoid \"call stack size exceeded\".\n let res = ''\n let i = 0\n while (i < len) {\n res += String.fromCharCode.apply(\n String,\n codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH)\n )\n }\n return res\n}\n\nfunction asciiSlice (buf, start, end) {\n let ret = ''\n end = Math.min(buf.length, end)\n\n for (let i = start; i < end; ++i) {\n ret += String.fromCharCode(buf[i] & 0x7F)\n }\n return ret\n}\n\nfunction latin1Slice (buf, start, end) {\n let ret = ''\n end = Math.min(buf.length, end)\n\n for (let i = start; i < end; ++i) {\n ret += String.fromCharCode(buf[i])\n }\n return ret\n}\n\nfunction hexSlice (buf, start, end) {\n const len = buf.length\n\n if (!start || start < 0) start = 0\n if (!end || end < 0 || end > len) end = len\n\n let out = ''\n for (let i = start; i < end; ++i) {\n out += hexSliceLookupTable[buf[i]]\n }\n return out\n}\n\nfunction utf16leSlice (buf, start, end) {\n const bytes = buf.slice(start, end)\n let res = ''\n // If bytes.length is odd, the last 8 bits must be ignored (same as node.js)\n for (let i = 0; i < bytes.length - 1; i += 2) {\n res += String.fromCharCode(bytes[i] + (bytes[i + 1] * 256))\n }\n return res\n}\n\nBuffer.prototype.slice = function slice (start, end) {\n const len = this.length\n start = ~~start\n end = end === undefined ? len : ~~end\n\n if (start < 0) {\n start += len\n if (start < 0) start = 0\n } else if (start > len) {\n start = len\n }\n\n if (end < 0) {\n end += len\n if (end < 0) end = 0\n } else if (end > len) {\n end = len\n }\n\n if (end < start) end = start\n\n const newBuf = this.subarray(start, end)\n // Return an augmented `Uint8Array` instance\n Object.setPrototypeOf(newBuf, Buffer.prototype)\n\n return newBuf\n}\n\n/*\n * Need to make sure that buffer isn't trying to write out of bounds.\n */\nfunction checkOffset (offset, ext, length) {\n if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint')\n if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length')\n}\n\nBuffer.prototype.readUintLE =\nBuffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) {\n offset = offset >>> 0\n byteLength = byteLength >>> 0\n if (!noAssert) checkOffset(offset, byteLength, this.length)\n\n let val = this[offset]\n let mul = 1\n let i = 0\n while (++i < byteLength && (mul *= 0x100)) {\n val += this[offset + i] * mul\n }\n\n return val\n}\n\nBuffer.prototype.readUintBE =\nBuffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) {\n offset = offset >>> 0\n byteLength = byteLength >>> 0\n if (!noAssert) {\n checkOffset(offset, byteLength, this.length)\n }\n\n let val = this[offset + --byteLength]\n let mul = 1\n while (byteLength > 0 && (mul *= 0x100)) {\n val += this[offset + --byteLength] * mul\n }\n\n return val\n}\n\nBuffer.prototype.readUint8 =\nBuffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 1, this.length)\n return this[offset]\n}\n\nBuffer.prototype.readUint16LE =\nBuffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 2, this.length)\n return this[offset] | (this[offset + 1] << 8)\n}\n\nBuffer.prototype.readUint16BE =\nBuffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 2, this.length)\n return (this[offset] << 8) | this[offset + 1]\n}\n\nBuffer.prototype.readUint32LE =\nBuffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 4, this.length)\n\n return ((this[offset]) |\n (this[offset + 1] << 8) |\n (this[offset + 2] << 16)) +\n (this[offset + 3] * 0x1000000)\n}\n\nBuffer.prototype.readUint32BE =\nBuffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 4, this.length)\n\n return (this[offset] * 0x1000000) +\n ((this[offset + 1] << 16) |\n (this[offset + 2] << 8) |\n this[offset + 3])\n}\n\nBuffer.prototype.readBigUInt64LE = defineBigIntMethod(function readBigUInt64LE (offset) {\n offset = offset >>> 0\n validateNumber(offset, 'offset')\n const first = this[offset]\n const last = this[offset + 7]\n if (first === undefined || last === undefined) {\n boundsError(offset, this.length - 8)\n }\n\n const lo = first +\n this[++offset] * 2 ** 8 +\n this[++offset] * 2 ** 16 +\n this[++offset] * 2 ** 24\n\n const hi = this[++offset] +\n this[++offset] * 2 ** 8 +\n this[++offset] * 2 ** 16 +\n last * 2 ** 24\n\n return BigInt(lo) + (BigInt(hi) << BigInt(32))\n})\n\nBuffer.prototype.readBigUInt64BE = defineBigIntMethod(function readBigUInt64BE (offset) {\n offset = offset >>> 0\n validateNumber(offset, 'offset')\n const first = this[offset]\n const last = this[offset + 7]\n if (first === undefined || last === undefined) {\n boundsError(offset, this.length - 8)\n }\n\n const hi = first * 2 ** 24 +\n this[++offset] * 2 ** 16 +\n this[++offset] * 2 ** 8 +\n this[++offset]\n\n const lo = this[++offset] * 2 ** 24 +\n this[++offset] * 2 ** 16 +\n this[++offset] * 2 ** 8 +\n last\n\n return (BigInt(hi) << BigInt(32)) + BigInt(lo)\n})\n\nBuffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) {\n offset = offset >>> 0\n byteLength = byteLength >>> 0\n if (!noAssert) checkOffset(offset, byteLength, this.length)\n\n let val = this[offset]\n let mul = 1\n let i = 0\n while (++i < byteLength && (mul *= 0x100)) {\n val += this[offset + i] * mul\n }\n mul *= 0x80\n\n if (val >= mul) val -= Math.pow(2, 8 * byteLength)\n\n return val\n}\n\nBuffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) {\n offset = offset >>> 0\n byteLength = byteLength >>> 0\n if (!noAssert) checkOffset(offset, byteLength, this.length)\n\n let i = byteLength\n let mul = 1\n let val = this[offset + --i]\n while (i > 0 && (mul *= 0x100)) {\n val += this[offset + --i] * mul\n }\n mul *= 0x80\n\n if (val >= mul) val -= Math.pow(2, 8 * byteLength)\n\n return val\n}\n\nBuffer.prototype.readInt8 = function readInt8 (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 1, this.length)\n if (!(this[offset] & 0x80)) return (this[offset])\n return ((0xff - this[offset] + 1) * -1)\n}\n\nBuffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 2, this.length)\n const val = this[offset] | (this[offset + 1] << 8)\n return (val & 0x8000) ? val | 0xFFFF0000 : val\n}\n\nBuffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 2, this.length)\n const val = this[offset + 1] | (this[offset] << 8)\n return (val & 0x8000) ? val | 0xFFFF0000 : val\n}\n\nBuffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 4, this.length)\n\n return (this[offset]) |\n (this[offset + 1] << 8) |\n (this[offset + 2] << 16) |\n (this[offset + 3] << 24)\n}\n\nBuffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 4, this.length)\n\n return (this[offset] << 24) |\n (this[offset + 1] << 16) |\n (this[offset + 2] << 8) |\n (this[offset + 3])\n}\n\nBuffer.prototype.readBigInt64LE = defineBigIntMethod(function readBigInt64LE (offset) {\n offset = offset >>> 0\n validateNumber(offset, 'offset')\n const first = this[offset]\n const last = this[offset + 7]\n if (first === undefined || last === undefined) {\n boundsError(offset, this.length - 8)\n }\n\n const val = this[offset + 4] +\n this[offset + 5] * 2 ** 8 +\n this[offset + 6] * 2 ** 16 +\n (last << 24) // Overflow\n\n return (BigInt(val) << BigInt(32)) +\n BigInt(first +\n this[++offset] * 2 ** 8 +\n this[++offset] * 2 ** 16 +\n this[++offset] * 2 ** 24)\n})\n\nBuffer.prototype.readBigInt64BE = defineBigIntMethod(function readBigInt64BE (offset) {\n offset = offset >>> 0\n validateNumber(offset, 'offset')\n const first = this[offset]\n const last = this[offset + 7]\n if (first === undefined || last === undefined) {\n boundsError(offset, this.length - 8)\n }\n\n const val = (first << 24) + // Overflow\n this[++offset] * 2 ** 16 +\n this[++offset] * 2 ** 8 +\n this[++offset]\n\n return (BigInt(val) << BigInt(32)) +\n BigInt(this[++offset] * 2 ** 24 +\n this[++offset] * 2 ** 16 +\n this[++offset] * 2 ** 8 +\n last)\n})\n\nBuffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 4, this.length)\n return ieee754.read(this, offset, true, 23, 4)\n}\n\nBuffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 4, this.length)\n return ieee754.read(this, offset, false, 23, 4)\n}\n\nBuffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 8, this.length)\n return ieee754.read(this, offset, true, 52, 8)\n}\n\nBuffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 8, this.length)\n return ieee754.read(this, offset, false, 52, 8)\n}\n\nfunction checkInt (buf, value, offset, ext, max, min) {\n if (!Buffer.isBuffer(buf)) throw new TypeError('\"buffer\" argument must be a Buffer instance')\n if (value > max || value < min) throw new RangeError('\"value\" argument is out of bounds')\n if (offset + ext > buf.length) throw new RangeError('Index out of range')\n}\n\nBuffer.prototype.writeUintLE =\nBuffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) {\n value = +value\n offset = offset >>> 0\n byteLength = byteLength >>> 0\n if (!noAssert) {\n const maxBytes = Math.pow(2, 8 * byteLength) - 1\n checkInt(this, value, offset, byteLength, maxBytes, 0)\n }\n\n let mul = 1\n let i = 0\n this[offset] = value & 0xFF\n while (++i < byteLength && (mul *= 0x100)) {\n this[offset + i] = (value / mul) & 0xFF\n }\n\n return offset + byteLength\n}\n\nBuffer.prototype.writeUintBE =\nBuffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) {\n value = +value\n offset = offset >>> 0\n byteLength = byteLength >>> 0\n if (!noAssert) {\n const maxBytes = Math.pow(2, 8 * byteLength) - 1\n checkInt(this, value, offset, byteLength, maxBytes, 0)\n }\n\n let i = byteLength - 1\n let mul = 1\n this[offset + i] = value & 0xFF\n while (--i >= 0 && (mul *= 0x100)) {\n this[offset + i] = (value / mul) & 0xFF\n }\n\n return offset + byteLength\n}\n\nBuffer.prototype.writeUint8 =\nBuffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0)\n this[offset] = (value & 0xff)\n return offset + 1\n}\n\nBuffer.prototype.writeUint16LE =\nBuffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)\n this[offset] = (value & 0xff)\n this[offset + 1] = (value >>> 8)\n return offset + 2\n}\n\nBuffer.prototype.writeUint16BE =\nBuffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)\n this[offset] = (value >>> 8)\n this[offset + 1] = (value & 0xff)\n return offset + 2\n}\n\nBuffer.prototype.writeUint32LE =\nBuffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)\n this[offset + 3] = (value >>> 24)\n this[offset + 2] = (value >>> 16)\n this[offset + 1] = (value >>> 8)\n this[offset] = (value & 0xff)\n return offset + 4\n}\n\nBuffer.prototype.writeUint32BE =\nBuffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)\n this[offset] = (value >>> 24)\n this[offset + 1] = (value >>> 16)\n this[offset + 2] = (value >>> 8)\n this[offset + 3] = (value & 0xff)\n return offset + 4\n}\n\nfunction wrtBigUInt64LE (buf, value, offset, min, max) {\n checkIntBI(value, min, max, buf, offset, 7)\n\n let lo = Number(value & BigInt(0xffffffff))\n buf[offset++] = lo\n lo = lo >> 8\n buf[offset++] = lo\n lo = lo >> 8\n buf[offset++] = lo\n lo = lo >> 8\n buf[offset++] = lo\n let hi = Number(value >> BigInt(32) & BigInt(0xffffffff))\n buf[offset++] = hi\n hi = hi >> 8\n buf[offset++] = hi\n hi = hi >> 8\n buf[offset++] = hi\n hi = hi >> 8\n buf[offset++] = hi\n return offset\n}\n\nfunction wrtBigUInt64BE (buf, value, offset, min, max) {\n checkIntBI(value, min, max, buf, offset, 7)\n\n let lo = Number(value & BigInt(0xffffffff))\n buf[offset + 7] = lo\n lo = lo >> 8\n buf[offset + 6] = lo\n lo = lo >> 8\n buf[offset + 5] = lo\n lo = lo >> 8\n buf[offset + 4] = lo\n let hi = Number(value >> BigInt(32) & BigInt(0xffffffff))\n buf[offset + 3] = hi\n hi = hi >> 8\n buf[offset + 2] = hi\n hi = hi >> 8\n buf[offset + 1] = hi\n hi = hi >> 8\n buf[offset] = hi\n return offset + 8\n}\n\nBuffer.prototype.writeBigUInt64LE = defineBigIntMethod(function writeBigUInt64LE (value, offset = 0) {\n return wrtBigUInt64LE(this, value, offset, BigInt(0), BigInt('0xffffffffffffffff'))\n})\n\nBuffer.prototype.writeBigUInt64BE = defineBigIntMethod(function writeBigUInt64BE (value, offset = 0) {\n return wrtBigUInt64BE(this, value, offset, BigInt(0), BigInt('0xffffffffffffffff'))\n})\n\nBuffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) {\n const limit = Math.pow(2, (8 * byteLength) - 1)\n\n checkInt(this, value, offset, byteLength, limit - 1, -limit)\n }\n\n let i = 0\n let mul = 1\n let sub = 0\n this[offset] = value & 0xFF\n while (++i < byteLength && (mul *= 0x100)) {\n if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) {\n sub = 1\n }\n this[offset + i] = ((value / mul) >> 0) - sub & 0xFF\n }\n\n return offset + byteLength\n}\n\nBuffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) {\n const limit = Math.pow(2, (8 * byteLength) - 1)\n\n checkInt(this, value, offset, byteLength, limit - 1, -limit)\n }\n\n let i = byteLength - 1\n let mul = 1\n let sub = 0\n this[offset + i] = value & 0xFF\n while (--i >= 0 && (mul *= 0x100)) {\n if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) {\n sub = 1\n }\n this[offset + i] = ((value / mul) >> 0) - sub & 0xFF\n }\n\n return offset + byteLength\n}\n\nBuffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80)\n if (value < 0) value = 0xff + value + 1\n this[offset] = (value & 0xff)\n return offset + 1\n}\n\nBuffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)\n this[offset] = (value & 0xff)\n this[offset + 1] = (value >>> 8)\n return offset + 2\n}\n\nBuffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)\n this[offset] = (value >>> 8)\n this[offset + 1] = (value & 0xff)\n return offset + 2\n}\n\nBuffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)\n this[offset] = (value & 0xff)\n this[offset + 1] = (value >>> 8)\n this[offset + 2] = (value >>> 16)\n this[offset + 3] = (value >>> 24)\n return offset + 4\n}\n\nBuffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)\n if (value < 0) value = 0xffffffff + value + 1\n this[offset] = (value >>> 24)\n this[offset + 1] = (value >>> 16)\n this[offset + 2] = (value >>> 8)\n this[offset + 3] = (value & 0xff)\n return offset + 4\n}\n\nBuffer.prototype.writeBigInt64LE = defineBigIntMethod(function writeBigInt64LE (value, offset = 0) {\n return wrtBigUInt64LE(this, value, offset, -BigInt('0x8000000000000000'), BigInt('0x7fffffffffffffff'))\n})\n\nBuffer.prototype.writeBigInt64BE = defineBigIntMethod(function writeBigInt64BE (value, offset = 0) {\n return wrtBigUInt64BE(this, value, offset, -BigInt('0x8000000000000000'), BigInt('0x7fffffffffffffff'))\n})\n\nfunction checkIEEE754 (buf, value, offset, ext, max, min) {\n if (offset + ext > buf.length) throw new RangeError('Index out of range')\n if (offset < 0) throw new RangeError('Index out of range')\n}\n\nfunction writeFloat (buf, value, offset, littleEndian, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) {\n checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38)\n }\n ieee754.write(buf, value, offset, littleEndian, 23, 4)\n return offset + 4\n}\n\nBuffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) {\n return writeFloat(this, value, offset, true, noAssert)\n}\n\nBuffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) {\n return writeFloat(this, value, offset, false, noAssert)\n}\n\nfunction writeDouble (buf, value, offset, littleEndian, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) {\n checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308)\n }\n ieee754.write(buf, value, offset, littleEndian, 52, 8)\n return offset + 8\n}\n\nBuffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) {\n return writeDouble(this, value, offset, true, noAssert)\n}\n\nBuffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) {\n return writeDouble(this, value, offset, false, noAssert)\n}\n\n// copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length)\nBuffer.prototype.copy = function copy (target, targetStart, start, end) {\n if (!Buffer.isBuffer(target)) throw new TypeError('argument should be a Buffer')\n if (!start) start = 0\n if (!end && end !== 0) end = this.length\n if (targetStart >= target.length) targetStart = target.length\n if (!targetStart) targetStart = 0\n if (end > 0 && end < start) end = start\n\n // Copy 0 bytes; we're done\n if (end === start) return 0\n if (target.length === 0 || this.length === 0) return 0\n\n // Fatal error conditions\n if (targetStart < 0) {\n throw new RangeError('targetStart out of bounds')\n }\n if (start < 0 || start >= this.length) throw new RangeError('Index out of range')\n if (end < 0) throw new RangeError('sourceEnd out of bounds')\n\n // Are we oob?\n if (end > this.length) end = this.length\n if (target.length - targetStart < end - start) {\n end = target.length - targetStart + start\n }\n\n const len = end - start\n\n if (this === target && typeof Uint8Array.prototype.copyWithin === 'function') {\n // Use built-in when available, missing from IE11\n this.copyWithin(targetStart, start, end)\n } else {\n Uint8Array.prototype.set.call(\n target,\n this.subarray(start, end),\n targetStart\n )\n }\n\n return len\n}\n\n// Usage:\n// buffer.fill(number[, offset[, end]])\n// buffer.fill(buffer[, offset[, end]])\n// buffer.fill(string[, offset[, end]][, encoding])\nBuffer.prototype.fill = function fill (val, start, end, encoding) {\n // Handle string cases:\n if (typeof val === 'string') {\n if (typeof start === 'string') {\n encoding = start\n start = 0\n end = this.length\n } else if (typeof end === 'string') {\n encoding = end\n end = this.length\n }\n if (encoding !== undefined && typeof encoding !== 'string') {\n throw new TypeError('encoding must be a string')\n }\n if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) {\n throw new TypeError('Unknown encoding: ' + encoding)\n }\n if (val.length === 1) {\n const code = val.charCodeAt(0)\n if ((encoding === 'utf8' && code < 128) ||\n encoding === 'latin1') {\n // Fast path: If `val` fits into a single byte, use that numeric value.\n val = code\n }\n }\n } else if (typeof val === 'number') {\n val = val & 255\n } else if (typeof val === 'boolean') {\n val = Number(val)\n }\n\n // Invalid ranges are not set to a default, so can range check early.\n if (start < 0 || this.length < start || this.length < end) {\n throw new RangeError('Out of range index')\n }\n\n if (end <= start) {\n return this\n }\n\n start = start >>> 0\n end = end === undefined ? this.length : end >>> 0\n\n if (!val) val = 0\n\n let i\n if (typeof val === 'number') {\n for (i = start; i < end; ++i) {\n this[i] = val\n }\n } else {\n const bytes = Buffer.isBuffer(val)\n ? val\n : Buffer.from(val, encoding)\n const len = bytes.length\n if (len === 0) {\n throw new TypeError('The value \"' + val +\n '\" is invalid for argument \"value\"')\n }\n for (i = 0; i < end - start; ++i) {\n this[i + start] = bytes[i % len]\n }\n }\n\n return this\n}\n\n// CUSTOM ERRORS\n// =============\n\n// Simplified versions from Node, changed for Buffer-only usage\nconst errors = {}\nfunction E (sym, getMessage, Base) {\n errors[sym] = class NodeError extends Base {\n constructor () {\n super()\n\n Object.defineProperty(this, 'message', {\n value: getMessage.apply(this, arguments),\n writable: true,\n configurable: true\n })\n\n // Add the error code to the name to include it in the stack trace.\n this.name = `${this.name} [${sym}]`\n // Access the stack to generate the error message including the error code\n // from the name.\n this.stack // eslint-disable-line no-unused-expressions\n // Reset the name to the actual name.\n delete this.name\n }\n\n get code () {\n return sym\n }\n\n set code (value) {\n Object.defineProperty(this, 'code', {\n configurable: true,\n enumerable: true,\n value,\n writable: true\n })\n }\n\n toString () {\n return `${this.name} [${sym}]: ${this.message}`\n }\n }\n}\n\nE('ERR_BUFFER_OUT_OF_BOUNDS',\n function (name) {\n if (name) {\n return `${name} is outside of buffer bounds`\n }\n\n return 'Attempt to access memory outside buffer bounds'\n }, RangeError)\nE('ERR_INVALID_ARG_TYPE',\n function (name, actual) {\n return `The \"${name}\" argument must be of type number. Received type ${typeof actual}`\n }, TypeError)\nE('ERR_OUT_OF_RANGE',\n function (str, range, input) {\n let msg = `The value of \"${str}\" is out of range.`\n let received = input\n if (Number.isInteger(input) && Math.abs(input) > 2 ** 32) {\n received = addNumericalSeparator(String(input))\n } else if (typeof input === 'bigint') {\n received = String(input)\n if (input > BigInt(2) ** BigInt(32) || input < -(BigInt(2) ** BigInt(32))) {\n received = addNumericalSeparator(received)\n }\n received += 'n'\n }\n msg += ` It must be ${range}. Received ${received}`\n return msg\n }, RangeError)\n\nfunction addNumericalSeparator (val) {\n let res = ''\n let i = val.length\n const start = val[0] === '-' ? 1 : 0\n for (; i >= start + 4; i -= 3) {\n res = `_${val.slice(i - 3, i)}${res}`\n }\n return `${val.slice(0, i)}${res}`\n}\n\n// CHECK FUNCTIONS\n// ===============\n\nfunction checkBounds (buf, offset, byteLength) {\n validateNumber(offset, 'offset')\n if (buf[offset] === undefined || buf[offset + byteLength] === undefined) {\n boundsError(offset, buf.length - (byteLength + 1))\n }\n}\n\nfunction checkIntBI (value, min, max, buf, offset, byteLength) {\n if (value > max || value < min) {\n const n = typeof min === 'bigint' ? 'n' : ''\n let range\n if (byteLength > 3) {\n if (min === 0 || min === BigInt(0)) {\n range = `>= 0${n} and < 2${n} ** ${(byteLength + 1) * 8}${n}`\n } else {\n range = `>= -(2${n} ** ${(byteLength + 1) * 8 - 1}${n}) and < 2 ** ` +\n `${(byteLength + 1) * 8 - 1}${n}`\n }\n } else {\n range = `>= ${min}${n} and <= ${max}${n}`\n }\n throw new errors.ERR_OUT_OF_RANGE('value', range, value)\n }\n checkBounds(buf, offset, byteLength)\n}\n\nfunction validateNumber (value, name) {\n if (typeof value !== 'number') {\n throw new errors.ERR_INVALID_ARG_TYPE(name, 'number', value)\n }\n}\n\nfunction boundsError (value, length, type) {\n if (Math.floor(value) !== value) {\n validateNumber(value, type)\n throw new errors.ERR_OUT_OF_RANGE(type || 'offset', 'an integer', value)\n }\n\n if (length < 0) {\n throw new errors.ERR_BUFFER_OUT_OF_BOUNDS()\n }\n\n throw new errors.ERR_OUT_OF_RANGE(type || 'offset',\n `>= ${type ? 1 : 0} and <= ${length}`,\n value)\n}\n\n// HELPER FUNCTIONS\n// ================\n\nconst INVALID_BASE64_RE = /[^+/0-9A-Za-z-_]/g\n\nfunction base64clean (str) {\n // Node takes equal signs as end of the Base64 encoding\n str = str.split('=')[0]\n // Node strips out invalid characters like \\n and \\t from the string, base64-js does not\n str = str.trim().replace(INVALID_BASE64_RE, '')\n // Node converts strings with length < 2 to ''\n if (str.length < 2) return ''\n // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not\n while (str.length % 4 !== 0) {\n str = str + '='\n }\n return str\n}\n\nfunction utf8ToBytes (string, units) {\n units = units || Infinity\n let codePoint\n const length = string.length\n let leadSurrogate = null\n const bytes = []\n\n for (let i = 0; i < length; ++i) {\n codePoint = string.charCodeAt(i)\n\n // is surrogate component\n if (codePoint > 0xD7FF && codePoint < 0xE000) {\n // last char was a lead\n if (!leadSurrogate) {\n // no lead yet\n if (codePoint > 0xDBFF) {\n // unexpected trail\n if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)\n continue\n } else if (i + 1 === length) {\n // unpaired lead\n if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)\n continue\n }\n\n // valid lead\n leadSurrogate = codePoint\n\n continue\n }\n\n // 2 leads in a row\n if (codePoint < 0xDC00) {\n if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)\n leadSurrogate = codePoint\n continue\n }\n\n // valid surrogate pair\n codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000\n } else if (leadSurrogate) {\n // valid bmp char, but last char was a lead\n if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)\n }\n\n leadSurrogate = null\n\n // encode utf8\n if (codePoint < 0x80) {\n if ((units -= 1) < 0) break\n bytes.push(codePoint)\n } else if (codePoint < 0x800) {\n if ((units -= 2) < 0) break\n bytes.push(\n codePoint >> 0x6 | 0xC0,\n codePoint & 0x3F | 0x80\n )\n } else if (codePoint < 0x10000) {\n if ((units -= 3) < 0) break\n bytes.push(\n codePoint >> 0xC | 0xE0,\n codePoint >> 0x6 & 0x3F | 0x80,\n codePoint & 0x3F | 0x80\n )\n } else if (codePoint < 0x110000) {\n if ((units -= 4) < 0) break\n bytes.push(\n codePoint >> 0x12 | 0xF0,\n codePoint >> 0xC & 0x3F | 0x80,\n codePoint >> 0x6 & 0x3F | 0x80,\n codePoint & 0x3F | 0x80\n )\n } else {\n throw new Error('Invalid code point')\n }\n }\n\n return bytes\n}\n\nfunction asciiToBytes (str) {\n const byteArray = []\n for (let i = 0; i < str.length; ++i) {\n // Node's code seems to be doing this and not & 0x7F..\n byteArray.push(str.charCodeAt(i) & 0xFF)\n }\n return byteArray\n}\n\nfunction utf16leToBytes (str, units) {\n let c, hi, lo\n const byteArray = []\n for (let i = 0; i < str.length; ++i) {\n if ((units -= 2) < 0) break\n\n c = str.charCodeAt(i)\n hi = c >> 8\n lo = c % 256\n byteArray.push(lo)\n byteArray.push(hi)\n }\n\n return byteArray\n}\n\nfunction base64ToBytes (str) {\n return base64.toByteArray(base64clean(str))\n}\n\nfunction blitBuffer (src, dst, offset, length) {\n let i\n for (i = 0; i < length; ++i) {\n if ((i + offset >= dst.length) || (i >= src.length)) break\n dst[i + offset] = src[i]\n }\n return i\n}\n\n// ArrayBuffer or Uint8Array objects from other contexts (i.e. iframes) do not pass\n// the `instanceof` check but they should be treated as of that type.\n// See: https://github.com/feross/buffer/issues/166\nfunction isInstance (obj, type) {\n return obj instanceof type ||\n (obj != null && obj.constructor != null && obj.constructor.name != null &&\n obj.constructor.name === type.name)\n}\nfunction numberIsNaN (obj) {\n // For IE11 support\n return obj !== obj // eslint-disable-line no-self-compare\n}\n\n// Create lookup table for `toString('hex')`\n// See: https://github.com/feross/buffer/issues/219\nconst hexSliceLookupTable = (function () {\n const alphabet = '0123456789abcdef'\n const table = new Array(256)\n for (let i = 0; i < 16; ++i) {\n const i16 = i * 16\n for (let j = 0; j < 16; ++j) {\n table[i16 + j] = alphabet[i] + alphabet[j]\n }\n }\n return table\n})()\n\n// Return not function with Error if BigInt not supported\nfunction defineBigIntMethod (fn) {\n return typeof BigInt === 'undefined' ? BufferBigIntNotDefined : fn\n}\n\nfunction BufferBigIntNotDefined () {\n throw new Error('BigInt not supported')\n}\n", "/**\n * Internal webcrypto alias.\n * We use WebCrypto aka globalThis.crypto, which exists in browsers and node.js 16+.\n * See utils.ts for details.\n * @module\n */\ndeclare const globalThis: Record | undefined;\nexport const crypto: any =\n typeof globalThis === 'object' && 'crypto' in globalThis ? globalThis.crypto : undefined;\n", "/**\n * Utilities for hex, bytes, CSPRNG.\n * @module\n */\n/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */\n\n// We use WebCrypto aka globalThis.crypto, which exists in browsers and node.js 16+.\n// node.js versions earlier than v19 don't declare it in global scope.\n// For node.js, package.json#exports field mapping rewrites import\n// from `crypto` to `cryptoNode`, which imports native module.\n// Makes the utils un-importable in browsers without a bundler.\n// Once node.js 18 is deprecated (2025-04-30), we can just drop the import.\nimport { crypto } from '@noble/hashes/crypto';\n\n/** Checks if something is Uint8Array. Be careful: nodejs Buffer will return true. */\nexport function isBytes(a: unknown): a is Uint8Array {\n return a instanceof Uint8Array || (ArrayBuffer.isView(a) && a.constructor.name === 'Uint8Array');\n}\n\n/** Asserts something is positive integer. */\nexport function anumber(n: number): void {\n if (!Number.isSafeInteger(n) || n < 0) throw new Error('positive integer expected, got ' + n);\n}\n\n/** Asserts something is Uint8Array. */\nexport function abytes(b: Uint8Array | undefined, ...lengths: number[]): void {\n if (!isBytes(b)) throw new Error('Uint8Array expected');\n if (lengths.length > 0 && !lengths.includes(b.length))\n throw new Error('Uint8Array expected of length ' + lengths + ', got length=' + b.length);\n}\n\n/** Asserts something is hash */\nexport function ahash(h: IHash): void {\n if (typeof h !== 'function' || typeof h.create !== 'function')\n throw new Error('Hash should be wrapped by utils.createHasher');\n anumber(h.outputLen);\n anumber(h.blockLen);\n}\n\n/** Asserts a hash instance has not been destroyed / finished */\nexport function aexists(instance: any, checkFinished = true): void {\n if (instance.destroyed) throw new Error('Hash instance has been destroyed');\n if (checkFinished && instance.finished) throw new Error('Hash#digest() has already been called');\n}\n\n/** Asserts output is properly-sized byte array */\nexport function aoutput(out: any, instance: any): void {\n abytes(out);\n const min = instance.outputLen;\n if (out.length < min) {\n throw new Error('digestInto() expects output buffer of length at least ' + min);\n }\n}\n\n/** Generic type encompassing 8/16/32-byte arrays - but not 64-byte. */\n// prettier-ignore\nexport type TypedArray = Int8Array | Uint8ClampedArray | Uint8Array |\n Uint16Array | Int16Array | Uint32Array | Int32Array;\n\n/** Cast u8 / u16 / u32 to u8. */\nexport function u8(arr: TypedArray): Uint8Array {\n return new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength);\n}\n\n/** Cast u8 / u16 / u32 to u32. */\nexport function u32(arr: TypedArray): Uint32Array {\n return new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4));\n}\n\n/** Zeroize a byte array. Warning: JS provides no guarantees. */\nexport function clean(...arrays: TypedArray[]): void {\n for (let i = 0; i < arrays.length; i++) {\n arrays[i].fill(0);\n }\n}\n\n/** Create DataView of an array for easy byte-level manipulation. */\nexport function createView(arr: TypedArray): DataView {\n return new DataView(arr.buffer, arr.byteOffset, arr.byteLength);\n}\n\n/** The rotate right (circular right shift) operation for uint32 */\nexport function rotr(word: number, shift: number): number {\n return (word << (32 - shift)) | (word >>> shift);\n}\n\n/** The rotate left (circular left shift) operation for uint32 */\nexport function rotl(word: number, shift: number): number {\n return (word << shift) | ((word >>> (32 - shift)) >>> 0);\n}\n\n/** Is current platform little-endian? Most are. Big-Endian platform: IBM */\nexport const isLE: boolean = /* @__PURE__ */ (() =>\n new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44)();\n\n/** The byte swap operation for uint32 */\nexport function byteSwap(word: number): number {\n return (\n ((word << 24) & 0xff000000) |\n ((word << 8) & 0xff0000) |\n ((word >>> 8) & 0xff00) |\n ((word >>> 24) & 0xff)\n );\n}\n/** Conditionally byte swap if on a big-endian platform */\nexport const swap8IfBE: (n: number) => number = isLE\n ? (n: number) => n\n : (n: number) => byteSwap(n);\n\n/** @deprecated */\nexport const byteSwapIfBE: typeof swap8IfBE = swap8IfBE;\n/** In place byte swap for Uint32Array */\nexport function byteSwap32(arr: Uint32Array): Uint32Array {\n for (let i = 0; i < arr.length; i++) {\n arr[i] = byteSwap(arr[i]);\n }\n return arr;\n}\n\nexport const swap32IfBE: (u: Uint32Array) => Uint32Array = isLE\n ? (u: Uint32Array) => u\n : byteSwap32;\n\n// Built-in hex conversion https://caniuse.com/mdn-javascript_builtins_uint8array_fromhex\nconst hasHexBuiltin: boolean = /* @__PURE__ */ (() =>\n // @ts-ignore\n typeof Uint8Array.from([]).toHex === 'function' && typeof Uint8Array.fromHex === 'function')();\n\n// Array where index 0xf0 (240) is mapped to string 'f0'\nconst hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) =>\n i.toString(16).padStart(2, '0')\n);\n\n/**\n * Convert byte array to hex string. Uses built-in function, when available.\n * @example bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])) // 'cafe0123'\n */\nexport function bytesToHex(bytes: Uint8Array): string {\n abytes(bytes);\n // @ts-ignore\n if (hasHexBuiltin) return bytes.toHex();\n // pre-caching improves the speed 6x\n let hex = '';\n for (let i = 0; i < bytes.length; i++) {\n hex += hexes[bytes[i]];\n }\n return hex;\n}\n\n// We use optimized technique to convert hex string to byte array\nconst asciis = { _0: 48, _9: 57, A: 65, F: 70, a: 97, f: 102 } as const;\nfunction asciiToBase16(ch: number): number | undefined {\n if (ch >= asciis._0 && ch <= asciis._9) return ch - asciis._0; // '2' => 50-48\n if (ch >= asciis.A && ch <= asciis.F) return ch - (asciis.A - 10); // 'B' => 66-(65-10)\n if (ch >= asciis.a && ch <= asciis.f) return ch - (asciis.a - 10); // 'b' => 98-(97-10)\n return;\n}\n\n/**\n * Convert hex string to byte array. Uses built-in function, when available.\n * @example hexToBytes('cafe0123') // Uint8Array.from([0xca, 0xfe, 0x01, 0x23])\n */\nexport function hexToBytes(hex: string): Uint8Array {\n if (typeof hex !== 'string') throw new Error('hex string expected, got ' + typeof hex);\n // @ts-ignore\n if (hasHexBuiltin) return Uint8Array.fromHex(hex);\n const hl = hex.length;\n const al = hl / 2;\n if (hl % 2) throw new Error('hex string expected, got unpadded hex of length ' + hl);\n const array = new Uint8Array(al);\n for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {\n const n1 = asciiToBase16(hex.charCodeAt(hi));\n const n2 = asciiToBase16(hex.charCodeAt(hi + 1));\n if (n1 === undefined || n2 === undefined) {\n const char = hex[hi] + hex[hi + 1];\n throw new Error('hex string expected, got non-hex character \"' + char + '\" at index ' + hi);\n }\n array[ai] = n1 * 16 + n2; // multiply first octet, e.g. 'a3' => 10*16+3 => 160 + 3 => 163\n }\n return array;\n}\n\n/**\n * There is no setImmediate in browser and setTimeout is slow.\n * Call of async fn will return Promise, which will be fullfiled only on\n * next scheduler queue processing step and this is exactly what we need.\n */\nexport const nextTick = async (): Promise => {};\n\n/** Returns control to thread each 'tick' ms to avoid blocking. */\nexport async function asyncLoop(\n iters: number,\n tick: number,\n cb: (i: number) => void\n): Promise {\n let ts = Date.now();\n for (let i = 0; i < iters; i++) {\n cb(i);\n // Date.now() is not monotonic, so in case if clock goes backwards we return return control too\n const diff = Date.now() - ts;\n if (diff >= 0 && diff < tick) continue;\n await nextTick();\n ts += diff;\n }\n}\n\n// Global symbols, but ts doesn't see them: https://github.com/microsoft/TypeScript/issues/31535\ndeclare const TextEncoder: any;\ndeclare const TextDecoder: any;\n\n/**\n * Converts string to bytes using UTF8 encoding.\n * @example utf8ToBytes('abc') // Uint8Array.from([97, 98, 99])\n */\nexport function utf8ToBytes(str: string): Uint8Array {\n if (typeof str !== 'string') throw new Error('string expected');\n return new Uint8Array(new TextEncoder().encode(str)); // https://bugzil.la/1681809\n}\n\n/**\n * Converts bytes to string using UTF8 encoding.\n * @example bytesToUtf8(Uint8Array.from([97, 98, 99])) // 'abc'\n */\nexport function bytesToUtf8(bytes: Uint8Array): string {\n return new TextDecoder().decode(bytes);\n}\n\n/** Accepted input of hash functions. Strings are converted to byte arrays. */\nexport type Input = string | Uint8Array;\n/**\n * Normalizes (non-hex) string or Uint8Array to Uint8Array.\n * Warning: when Uint8Array is passed, it would NOT get copied.\n * Keep in mind for future mutable operations.\n */\nexport function toBytes(data: Input): Uint8Array {\n if (typeof data === 'string') data = utf8ToBytes(data);\n abytes(data);\n return data;\n}\n\n/** KDFs can accept string or Uint8Array for user convenience. */\nexport type KDFInput = string | Uint8Array;\n/**\n * Helper for KDFs: consumes uint8array or string.\n * When string is passed, does utf8 decoding, using TextDecoder.\n */\nexport function kdfInputToBytes(data: KDFInput): Uint8Array {\n if (typeof data === 'string') data = utf8ToBytes(data);\n abytes(data);\n return data;\n}\n\n/** Copies several Uint8Arrays into one. */\nexport function concatBytes(...arrays: Uint8Array[]): Uint8Array {\n let sum = 0;\n for (let i = 0; i < arrays.length; i++) {\n const a = arrays[i];\n abytes(a);\n sum += a.length;\n }\n const res = new Uint8Array(sum);\n for (let i = 0, pad = 0; i < arrays.length; i++) {\n const a = arrays[i];\n res.set(a, pad);\n pad += a.length;\n }\n return res;\n}\n\ntype EmptyObj = {};\nexport function checkOpts(\n defaults: T1,\n opts?: T2\n): T1 & T2 {\n if (opts !== undefined && {}.toString.call(opts) !== '[object Object]')\n throw new Error('options should be object or undefined');\n const merged = Object.assign(defaults, opts);\n return merged as T1 & T2;\n}\n\n/** Hash interface. */\nexport type IHash = {\n (data: Uint8Array): Uint8Array;\n blockLen: number;\n outputLen: number;\n create: any;\n};\n\n/** For runtime check if class implements interface */\nexport abstract class Hash> {\n abstract blockLen: number; // Bytes per block\n abstract outputLen: number; // Bytes in output\n abstract update(buf: Input): this;\n // Writes digest into buf\n abstract digestInto(buf: Uint8Array): void;\n abstract digest(): Uint8Array;\n /**\n * Resets internal state. Makes Hash instance unusable.\n * Reset is impossible for keyed hashes if key is consumed into state. If digest is not consumed\n * by user, they will need to manually call `destroy()` when zeroing is necessary.\n */\n abstract destroy(): void;\n /**\n * Clones hash instance. Unsafe: doesn't check whether `to` is valid. Can be used as `clone()`\n * when no options are passed.\n * Reasons to use `_cloneInto` instead of clone: 1) performance 2) reuse instance => all internal\n * buffers are overwritten => causes buffer overwrite which is used for digest in some cases.\n * There are no guarantees for clean-up because it's impossible in JS.\n */\n abstract _cloneInto(to?: T): T;\n // Safe version that clones internal state\n abstract clone(): T;\n}\n\n/**\n * XOF: streaming API to read digest in chunks.\n * Same as 'squeeze' in keccak/k12 and 'seek' in blake3, but more generic name.\n * When hash used in XOF mode it is up to user to call '.destroy' afterwards, since we cannot\n * destroy state, next call can require more bytes.\n */\nexport type HashXOF> = Hash & {\n xof(bytes: number): Uint8Array; // Read 'bytes' bytes from digest stream\n xofInto(buf: Uint8Array): Uint8Array; // read buf.length bytes from digest stream into buf\n};\n\n/** Hash function */\nexport type CHash = ReturnType;\n/** Hash function with output */\nexport type CHashO = ReturnType;\n/** XOF with output */\nexport type CHashXO = ReturnType;\n\n/** Wraps hash function, creating an interface on top of it */\nexport function createHasher>(\n hashCons: () => Hash\n): {\n (msg: Input): Uint8Array;\n outputLen: number;\n blockLen: number;\n create(): Hash;\n} {\n const hashC = (msg: Input): Uint8Array => hashCons().update(toBytes(msg)).digest();\n const tmp = hashCons();\n hashC.outputLen = tmp.outputLen;\n hashC.blockLen = tmp.blockLen;\n hashC.create = () => hashCons();\n return hashC;\n}\n\nexport function createOptHasher, T extends Object>(\n hashCons: (opts?: T) => Hash\n): {\n (msg: Input, opts?: T): Uint8Array;\n outputLen: number;\n blockLen: number;\n create(opts?: T): Hash;\n} {\n const hashC = (msg: Input, opts?: T): Uint8Array => hashCons(opts).update(toBytes(msg)).digest();\n const tmp = hashCons({} as T);\n hashC.outputLen = tmp.outputLen;\n hashC.blockLen = tmp.blockLen;\n hashC.create = (opts?: T) => hashCons(opts);\n return hashC;\n}\n\nexport function createXOFer, T extends Object>(\n hashCons: (opts?: T) => HashXOF\n): {\n (msg: Input, opts?: T): Uint8Array;\n outputLen: number;\n blockLen: number;\n create(opts?: T): HashXOF;\n} {\n const hashC = (msg: Input, opts?: T): Uint8Array => hashCons(opts).update(toBytes(msg)).digest();\n const tmp = hashCons({} as T);\n hashC.outputLen = tmp.outputLen;\n hashC.blockLen = tmp.blockLen;\n hashC.create = (opts?: T) => hashCons(opts);\n return hashC;\n}\nexport const wrapConstructor: typeof createHasher = createHasher;\nexport const wrapConstructorWithOpts: typeof createOptHasher = createOptHasher;\nexport const wrapXOFConstructorWithOpts: typeof createXOFer = createXOFer;\n\n/** Cryptographically secure PRNG. Uses internal OS-level `crypto.getRandomValues`. */\nexport function randomBytes(bytesLength = 32): Uint8Array {\n if (crypto && typeof crypto.getRandomValues === 'function') {\n return crypto.getRandomValues(new Uint8Array(bytesLength));\n }\n // Legacy Node.js compatibility\n if (crypto && typeof crypto.randomBytes === 'function') {\n return Uint8Array.from(crypto.randomBytes(bytesLength));\n }\n throw new Error('crypto.getRandomValues must be defined');\n}\n", "/**\n * Internal Merkle-Damgard hash utils.\n * @module\n */\nimport { type Input, Hash, abytes, aexists, aoutput, clean, createView, toBytes } from './utils.ts';\n\n/** Polyfill for Safari 14. https://caniuse.com/mdn-javascript_builtins_dataview_setbiguint64 */\nexport function setBigUint64(\n view: DataView,\n byteOffset: number,\n value: bigint,\n isLE: boolean\n): void {\n if (typeof view.setBigUint64 === 'function') return view.setBigUint64(byteOffset, value, isLE);\n const _32n = BigInt(32);\n const _u32_max = BigInt(0xffffffff);\n const wh = Number((value >> _32n) & _u32_max);\n const wl = Number(value & _u32_max);\n const h = isLE ? 4 : 0;\n const l = isLE ? 0 : 4;\n view.setUint32(byteOffset + h, wh, isLE);\n view.setUint32(byteOffset + l, wl, isLE);\n}\n\n/** Choice: a ? b : c */\nexport function Chi(a: number, b: number, c: number): number {\n return (a & b) ^ (~a & c);\n}\n\n/** Majority function, true if any two inputs is true. */\nexport function Maj(a: number, b: number, c: number): number {\n return (a & b) ^ (a & c) ^ (b & c);\n}\n\n/**\n * Merkle-Damgard hash construction base class.\n * Could be used to create MD5, RIPEMD, SHA1, SHA2.\n */\nexport abstract class HashMD> extends Hash {\n protected abstract process(buf: DataView, offset: number): void;\n protected abstract get(): number[];\n protected abstract set(...args: number[]): void;\n abstract destroy(): void;\n protected abstract roundClean(): void;\n\n readonly blockLen: number;\n readonly outputLen: number;\n readonly padOffset: number;\n readonly isLE: boolean;\n\n // For partial updates less than block size\n protected buffer: Uint8Array;\n protected view: DataView;\n protected finished = false;\n protected length = 0;\n protected pos = 0;\n protected destroyed = false;\n\n constructor(blockLen: number, outputLen: number, padOffset: number, isLE: boolean) {\n super();\n this.blockLen = blockLen;\n this.outputLen = outputLen;\n this.padOffset = padOffset;\n this.isLE = isLE;\n this.buffer = new Uint8Array(blockLen);\n this.view = createView(this.buffer);\n }\n update(data: Input): this {\n aexists(this);\n data = toBytes(data);\n abytes(data);\n const { view, buffer, blockLen } = this;\n const len = data.length;\n for (let pos = 0; pos < len; ) {\n const take = Math.min(blockLen - this.pos, len - pos);\n // Fast path: we have at least one block in input, cast it to view and process\n if (take === blockLen) {\n const dataView = createView(data);\n for (; blockLen <= len - pos; pos += blockLen) this.process(dataView, pos);\n continue;\n }\n buffer.set(data.subarray(pos, pos + take), this.pos);\n this.pos += take;\n pos += take;\n if (this.pos === blockLen) {\n this.process(view, 0);\n this.pos = 0;\n }\n }\n this.length += data.length;\n this.roundClean();\n return this;\n }\n digestInto(out: Uint8Array): void {\n aexists(this);\n aoutput(out, this);\n this.finished = true;\n // Padding\n // We can avoid allocation of buffer for padding completely if it\n // was previously not allocated here. But it won't change performance.\n const { buffer, view, blockLen, isLE } = this;\n let { pos } = this;\n // append the bit '1' to the message\n buffer[pos++] = 0b10000000;\n clean(this.buffer.subarray(pos));\n // we have less than padOffset left in buffer, so we cannot put length in\n // current block, need process it and pad again\n if (this.padOffset > blockLen - pos) {\n this.process(view, 0);\n pos = 0;\n }\n // Pad until full block byte with zeros\n for (let i = pos; i < blockLen; i++) buffer[i] = 0;\n // Note: sha512 requires length to be 128bit integer, but length in JS will overflow before that\n // You need to write around 2 exabytes (u64_max / 8 / (1024**6)) for this to happen.\n // So we just write lowest 64 bits of that value.\n setBigUint64(view, blockLen - 8, BigInt(this.length * 8), isLE);\n this.process(view, 0);\n const oview = createView(out);\n const len = this.outputLen;\n // NOTE: we do division by 4 later, which should be fused in single op with modulo by JIT\n if (len % 4) throw new Error('_sha2: outputLen should be aligned to 32bit');\n const outLen = len / 4;\n const state = this.get();\n if (outLen > state.length) throw new Error('_sha2: outputLen bigger than state');\n for (let i = 0; i < outLen; i++) oview.setUint32(4 * i, state[i], isLE);\n }\n digest(): Uint8Array {\n const { buffer, outputLen } = this;\n this.digestInto(buffer);\n const res = buffer.slice(0, outputLen);\n this.destroy();\n return res;\n }\n _cloneInto(to?: T): T {\n to ||= new (this.constructor as any)() as T;\n to.set(...this.get());\n const { blockLen, buffer, length, finished, destroyed, pos } = this;\n to.destroyed = destroyed;\n to.finished = finished;\n to.length = length;\n to.pos = pos;\n if (length % blockLen) to.buffer.set(buffer);\n return to;\n }\n clone(): T {\n return this._cloneInto();\n }\n}\n\n/**\n * Initial SHA-2 state: fractional parts of square roots of first 16 primes 2..53.\n * Check out `test/misc/sha2-gen-iv.js` for recomputation guide.\n */\n\n/** Initial SHA256 state. Bits 0..32 of frac part of sqrt of primes 2..19 */\nexport const SHA256_IV: Uint32Array = /* @__PURE__ */ Uint32Array.from([\n 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19,\n]);\n\n/** Initial SHA224 state. Bits 32..64 of frac part of sqrt of primes 23..53 */\nexport const SHA224_IV: Uint32Array = /* @__PURE__ */ Uint32Array.from([\n 0xc1059ed8, 0x367cd507, 0x3070dd17, 0xf70e5939, 0xffc00b31, 0x68581511, 0x64f98fa7, 0xbefa4fa4,\n]);\n\n/** Initial SHA384 state. Bits 0..64 of frac part of sqrt of primes 23..53 */\nexport const SHA384_IV: Uint32Array = /* @__PURE__ */ Uint32Array.from([\n 0xcbbb9d5d, 0xc1059ed8, 0x629a292a, 0x367cd507, 0x9159015a, 0x3070dd17, 0x152fecd8, 0xf70e5939,\n 0x67332667, 0xffc00b31, 0x8eb44a87, 0x68581511, 0xdb0c2e0d, 0x64f98fa7, 0x47b5481d, 0xbefa4fa4,\n]);\n\n/** Initial SHA512 state. Bits 0..64 of frac part of sqrt of primes 2..19 */\nexport const SHA512_IV: Uint32Array = /* @__PURE__ */ Uint32Array.from([\n 0x6a09e667, 0xf3bcc908, 0xbb67ae85, 0x84caa73b, 0x3c6ef372, 0xfe94f82b, 0xa54ff53a, 0x5f1d36f1,\n 0x510e527f, 0xade682d1, 0x9b05688c, 0x2b3e6c1f, 0x1f83d9ab, 0xfb41bd6b, 0x5be0cd19, 0x137e2179,\n]);\n", "/**\n * Internal helpers for u64. BigUint64Array is too slow as per 2025, so we implement it using Uint32Array.\n * @todo re-check https://issues.chromium.org/issues/42212588\n * @module\n */\nconst U32_MASK64 = /* @__PURE__ */ BigInt(2 ** 32 - 1);\nconst _32n = /* @__PURE__ */ BigInt(32);\n\nfunction fromBig(\n n: bigint,\n le = false\n): {\n h: number;\n l: number;\n} {\n if (le) return { h: Number(n & U32_MASK64), l: Number((n >> _32n) & U32_MASK64) };\n return { h: Number((n >> _32n) & U32_MASK64) | 0, l: Number(n & U32_MASK64) | 0 };\n}\n\nfunction split(lst: bigint[], le = false): Uint32Array[] {\n const len = lst.length;\n let Ah = new Uint32Array(len);\n let Al = new Uint32Array(len);\n for (let i = 0; i < len; i++) {\n const { h, l } = fromBig(lst[i], le);\n [Ah[i], Al[i]] = [h, l];\n }\n return [Ah, Al];\n}\n\nconst toBig = (h: number, l: number): bigint => (BigInt(h >>> 0) << _32n) | BigInt(l >>> 0);\n// for Shift in [0, 32)\nconst shrSH = (h: number, _l: number, s: number): number => h >>> s;\nconst shrSL = (h: number, l: number, s: number): number => (h << (32 - s)) | (l >>> s);\n// Right rotate for Shift in [1, 32)\nconst rotrSH = (h: number, l: number, s: number): number => (h >>> s) | (l << (32 - s));\nconst rotrSL = (h: number, l: number, s: number): number => (h << (32 - s)) | (l >>> s);\n// Right rotate for Shift in (32, 64), NOTE: 32 is special case.\nconst rotrBH = (h: number, l: number, s: number): number => (h << (64 - s)) | (l >>> (s - 32));\nconst rotrBL = (h: number, l: number, s: number): number => (h >>> (s - 32)) | (l << (64 - s));\n// Right rotate for shift===32 (just swaps l&h)\nconst rotr32H = (_h: number, l: number): number => l;\nconst rotr32L = (h: number, _l: number): number => h;\n// Left rotate for Shift in [1, 32)\nconst rotlSH = (h: number, l: number, s: number): number => (h << s) | (l >>> (32 - s));\nconst rotlSL = (h: number, l: number, s: number): number => (l << s) | (h >>> (32 - s));\n// Left rotate for Shift in (32, 64), NOTE: 32 is special case.\nconst rotlBH = (h: number, l: number, s: number): number => (l << (s - 32)) | (h >>> (64 - s));\nconst rotlBL = (h: number, l: number, s: number): number => (h << (s - 32)) | (l >>> (64 - s));\n\n// JS uses 32-bit signed integers for bitwise operations which means we cannot\n// simple take carry out of low bit sum by shift, we need to use division.\nfunction add(\n Ah: number,\n Al: number,\n Bh: number,\n Bl: number\n): {\n h: number;\n l: number;\n} {\n const l = (Al >>> 0) + (Bl >>> 0);\n return { h: (Ah + Bh + ((l / 2 ** 32) | 0)) | 0, l: l | 0 };\n}\n// Addition with more than 2 elements\nconst add3L = (Al: number, Bl: number, Cl: number): number => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0);\nconst add3H = (low: number, Ah: number, Bh: number, Ch: number): number =>\n (Ah + Bh + Ch + ((low / 2 ** 32) | 0)) | 0;\nconst add4L = (Al: number, Bl: number, Cl: number, Dl: number): number =>\n (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0);\nconst add4H = (low: number, Ah: number, Bh: number, Ch: number, Dh: number): number =>\n (Ah + Bh + Ch + Dh + ((low / 2 ** 32) | 0)) | 0;\nconst add5L = (Al: number, Bl: number, Cl: number, Dl: number, El: number): number =>\n (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0) + (El >>> 0);\nconst add5H = (low: number, Ah: number, Bh: number, Ch: number, Dh: number, Eh: number): number =>\n (Ah + Bh + Ch + Dh + Eh + ((low / 2 ** 32) | 0)) | 0;\n\n// prettier-ignore\nexport {\n add, add3H, add3L, add4H, add4L, add5H, add5L, fromBig, rotlBH, rotlBL, rotlSH, rotlSL, rotr32H, rotr32L, rotrBH, rotrBL, rotrSH, rotrSL, shrSH, shrSL, split, toBig\n};\n// prettier-ignore\nconst u64: { fromBig: typeof fromBig; split: typeof split; toBig: (h: number, l: number) => bigint; shrSH: (h: number, _l: number, s: number) => number; shrSL: (h: number, l: number, s: number) => number; rotrSH: (h: number, l: number, s: number) => number; rotrSL: (h: number, l: number, s: number) => number; rotrBH: (h: number, l: number, s: number) => number; rotrBL: (h: number, l: number, s: number) => number; rotr32H: (_h: number, l: number) => number; rotr32L: (h: number, _l: number) => number; rotlSH: (h: number, l: number, s: number) => number; rotlSL: (h: number, l: number, s: number) => number; rotlBH: (h: number, l: number, s: number) => number; rotlBL: (h: number, l: number, s: number) => number; add: typeof add; add3L: (Al: number, Bl: number, Cl: number) => number; add3H: (low: number, Ah: number, Bh: number, Ch: number) => number; add4L: (Al: number, Bl: number, Cl: number, Dl: number) => number; add4H: (low: number, Ah: number, Bh: number, Ch: number, Dh: number) => number; add5H: (low: number, Ah: number, Bh: number, Ch: number, Dh: number, Eh: number) => number; add5L: (Al: number, Bl: number, Cl: number, Dl: number, El: number) => number; } = {\n fromBig, split, toBig,\n shrSH, shrSL,\n rotrSH, rotrSL, rotrBH, rotrBL,\n rotr32H, rotr32L,\n rotlSH, rotlSL, rotlBH, rotlBL,\n add, add3L, add3H, add4L, add4H, add5H, add5L,\n};\nexport default u64;\n", "/**\n * SHA2 hash function. A.k.a. sha256, sha384, sha512, sha512_224, sha512_256.\n * SHA256 is the fastest hash implementable in JS, even faster than Blake3.\n * Check out [RFC 4634](https://datatracker.ietf.org/doc/html/rfc4634) and\n * [FIPS 180-4](https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.180-4.pdf).\n * @module\n */\nimport { Chi, HashMD, Maj, SHA224_IV, SHA256_IV, SHA384_IV, SHA512_IV } from './_md.ts';\nimport * as u64 from './_u64.ts';\nimport { type CHash, clean, createHasher, rotr } from './utils.ts';\n\n/**\n * Round constants:\n * First 32 bits of fractional parts of the cube roots of the first 64 primes 2..311)\n */\n// prettier-ignore\nconst SHA256_K = /* @__PURE__ */ Uint32Array.from([\n 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,\n 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,\n 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,\n 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,\n 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,\n 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,\n 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,\n 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2\n]);\n\n/** Reusable temporary buffer. \"W\" comes straight from spec. */\nconst SHA256_W = /* @__PURE__ */ new Uint32Array(64);\nexport class SHA256 extends HashMD {\n // We cannot use array here since array allows indexing by variable\n // which means optimizer/compiler cannot use registers.\n protected A: number = SHA256_IV[0] | 0;\n protected B: number = SHA256_IV[1] | 0;\n protected C: number = SHA256_IV[2] | 0;\n protected D: number = SHA256_IV[3] | 0;\n protected E: number = SHA256_IV[4] | 0;\n protected F: number = SHA256_IV[5] | 0;\n protected G: number = SHA256_IV[6] | 0;\n protected H: number = SHA256_IV[7] | 0;\n\n constructor(outputLen: number = 32) {\n super(64, outputLen, 8, false);\n }\n protected get(): [number, number, number, number, number, number, number, number] {\n const { A, B, C, D, E, F, G, H } = this;\n return [A, B, C, D, E, F, G, H];\n }\n // prettier-ignore\n protected set(\n A: number, B: number, C: number, D: number, E: number, F: number, G: number, H: number\n ): void {\n this.A = A | 0;\n this.B = B | 0;\n this.C = C | 0;\n this.D = D | 0;\n this.E = E | 0;\n this.F = F | 0;\n this.G = G | 0;\n this.H = H | 0;\n }\n protected process(view: DataView, offset: number): void {\n // Extend the first 16 words into the remaining 48 words w[16..63] of the message schedule array\n for (let i = 0; i < 16; i++, offset += 4) SHA256_W[i] = view.getUint32(offset, false);\n for (let i = 16; i < 64; i++) {\n const W15 = SHA256_W[i - 15];\n const W2 = SHA256_W[i - 2];\n const s0 = rotr(W15, 7) ^ rotr(W15, 18) ^ (W15 >>> 3);\n const s1 = rotr(W2, 17) ^ rotr(W2, 19) ^ (W2 >>> 10);\n SHA256_W[i] = (s1 + SHA256_W[i - 7] + s0 + SHA256_W[i - 16]) | 0;\n }\n // Compression function main loop, 64 rounds\n let { A, B, C, D, E, F, G, H } = this;\n for (let i = 0; i < 64; i++) {\n const sigma1 = rotr(E, 6) ^ rotr(E, 11) ^ rotr(E, 25);\n const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0;\n const sigma0 = rotr(A, 2) ^ rotr(A, 13) ^ rotr(A, 22);\n const T2 = (sigma0 + Maj(A, B, C)) | 0;\n H = G;\n G = F;\n F = E;\n E = (D + T1) | 0;\n D = C;\n C = B;\n B = A;\n A = (T1 + T2) | 0;\n }\n // Add the compressed chunk to the current hash value\n A = (A + this.A) | 0;\n B = (B + this.B) | 0;\n C = (C + this.C) | 0;\n D = (D + this.D) | 0;\n E = (E + this.E) | 0;\n F = (F + this.F) | 0;\n G = (G + this.G) | 0;\n H = (H + this.H) | 0;\n this.set(A, B, C, D, E, F, G, H);\n }\n protected roundClean(): void {\n clean(SHA256_W);\n }\n destroy(): void {\n this.set(0, 0, 0, 0, 0, 0, 0, 0);\n clean(this.buffer);\n }\n}\n\nexport class SHA224 extends SHA256 {\n protected A: number = SHA224_IV[0] | 0;\n protected B: number = SHA224_IV[1] | 0;\n protected C: number = SHA224_IV[2] | 0;\n protected D: number = SHA224_IV[3] | 0;\n protected E: number = SHA224_IV[4] | 0;\n protected F: number = SHA224_IV[5] | 0;\n protected G: number = SHA224_IV[6] | 0;\n protected H: number = SHA224_IV[7] | 0;\n constructor() {\n super(28);\n }\n}\n\n// SHA2-512 is slower than sha256 in js because u64 operations are slow.\n\n// Round contants\n// First 32 bits of the fractional parts of the cube roots of the first 80 primes 2..409\n// prettier-ignore\nconst K512 = /* @__PURE__ */ (() => u64.split([\n '0x428a2f98d728ae22', '0x7137449123ef65cd', '0xb5c0fbcfec4d3b2f', '0xe9b5dba58189dbbc',\n '0x3956c25bf348b538', '0x59f111f1b605d019', '0x923f82a4af194f9b', '0xab1c5ed5da6d8118',\n '0xd807aa98a3030242', '0x12835b0145706fbe', '0x243185be4ee4b28c', '0x550c7dc3d5ffb4e2',\n '0x72be5d74f27b896f', '0x80deb1fe3b1696b1', '0x9bdc06a725c71235', '0xc19bf174cf692694',\n '0xe49b69c19ef14ad2', '0xefbe4786384f25e3', '0x0fc19dc68b8cd5b5', '0x240ca1cc77ac9c65',\n '0x2de92c6f592b0275', '0x4a7484aa6ea6e483', '0x5cb0a9dcbd41fbd4', '0x76f988da831153b5',\n '0x983e5152ee66dfab', '0xa831c66d2db43210', '0xb00327c898fb213f', '0xbf597fc7beef0ee4',\n '0xc6e00bf33da88fc2', '0xd5a79147930aa725', '0x06ca6351e003826f', '0x142929670a0e6e70',\n '0x27b70a8546d22ffc', '0x2e1b21385c26c926', '0x4d2c6dfc5ac42aed', '0x53380d139d95b3df',\n '0x650a73548baf63de', '0x766a0abb3c77b2a8', '0x81c2c92e47edaee6', '0x92722c851482353b',\n '0xa2bfe8a14cf10364', '0xa81a664bbc423001', '0xc24b8b70d0f89791', '0xc76c51a30654be30',\n '0xd192e819d6ef5218', '0xd69906245565a910', '0xf40e35855771202a', '0x106aa07032bbd1b8',\n '0x19a4c116b8d2d0c8', '0x1e376c085141ab53', '0x2748774cdf8eeb99', '0x34b0bcb5e19b48a8',\n '0x391c0cb3c5c95a63', '0x4ed8aa4ae3418acb', '0x5b9cca4f7763e373', '0x682e6ff3d6b2b8a3',\n '0x748f82ee5defb2fc', '0x78a5636f43172f60', '0x84c87814a1f0ab72', '0x8cc702081a6439ec',\n '0x90befffa23631e28', '0xa4506cebde82bde9', '0xbef9a3f7b2c67915', '0xc67178f2e372532b',\n '0xca273eceea26619c', '0xd186b8c721c0c207', '0xeada7dd6cde0eb1e', '0xf57d4f7fee6ed178',\n '0x06f067aa72176fba', '0x0a637dc5a2c898a6', '0x113f9804bef90dae', '0x1b710b35131c471b',\n '0x28db77f523047d84', '0x32caab7b40c72493', '0x3c9ebe0a15c9bebc', '0x431d67c49c100d4c',\n '0x4cc5d4becb3e42b6', '0x597f299cfc657e2a', '0x5fcb6fab3ad6faec', '0x6c44198c4a475817'\n].map(n => BigInt(n))))();\nconst SHA512_Kh = /* @__PURE__ */ (() => K512[0])();\nconst SHA512_Kl = /* @__PURE__ */ (() => K512[1])();\n\n// Reusable temporary buffers\nconst SHA512_W_H = /* @__PURE__ */ new Uint32Array(80);\nconst SHA512_W_L = /* @__PURE__ */ new Uint32Array(80);\n\nexport class SHA512 extends HashMD {\n // We cannot use array here since array allows indexing by variable\n // which means optimizer/compiler cannot use registers.\n // h -- high 32 bits, l -- low 32 bits\n protected Ah: number = SHA512_IV[0] | 0;\n protected Al: number = SHA512_IV[1] | 0;\n protected Bh: number = SHA512_IV[2] | 0;\n protected Bl: number = SHA512_IV[3] | 0;\n protected Ch: number = SHA512_IV[4] | 0;\n protected Cl: number = SHA512_IV[5] | 0;\n protected Dh: number = SHA512_IV[6] | 0;\n protected Dl: number = SHA512_IV[7] | 0;\n protected Eh: number = SHA512_IV[8] | 0;\n protected El: number = SHA512_IV[9] | 0;\n protected Fh: number = SHA512_IV[10] | 0;\n protected Fl: number = SHA512_IV[11] | 0;\n protected Gh: number = SHA512_IV[12] | 0;\n protected Gl: number = SHA512_IV[13] | 0;\n protected Hh: number = SHA512_IV[14] | 0;\n protected Hl: number = SHA512_IV[15] | 0;\n\n constructor(outputLen: number = 64) {\n super(128, outputLen, 16, false);\n }\n // prettier-ignore\n protected get(): [\n number, number, number, number, number, number, number, number,\n number, number, number, number, number, number, number, number\n ] {\n const { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;\n return [Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl];\n }\n // prettier-ignore\n protected set(\n Ah: number, Al: number, Bh: number, Bl: number, Ch: number, Cl: number, Dh: number, Dl: number,\n Eh: number, El: number, Fh: number, Fl: number, Gh: number, Gl: number, Hh: number, Hl: number\n ): void {\n this.Ah = Ah | 0;\n this.Al = Al | 0;\n this.Bh = Bh | 0;\n this.Bl = Bl | 0;\n this.Ch = Ch | 0;\n this.Cl = Cl | 0;\n this.Dh = Dh | 0;\n this.Dl = Dl | 0;\n this.Eh = Eh | 0;\n this.El = El | 0;\n this.Fh = Fh | 0;\n this.Fl = Fl | 0;\n this.Gh = Gh | 0;\n this.Gl = Gl | 0;\n this.Hh = Hh | 0;\n this.Hl = Hl | 0;\n }\n protected process(view: DataView, offset: number): void {\n // Extend the first 16 words into the remaining 64 words w[16..79] of the message schedule array\n for (let i = 0; i < 16; i++, offset += 4) {\n SHA512_W_H[i] = view.getUint32(offset);\n SHA512_W_L[i] = view.getUint32((offset += 4));\n }\n for (let i = 16; i < 80; i++) {\n // s0 := (w[i-15] rightrotate 1) xor (w[i-15] rightrotate 8) xor (w[i-15] rightshift 7)\n const W15h = SHA512_W_H[i - 15] | 0;\n const W15l = SHA512_W_L[i - 15] | 0;\n const s0h = u64.rotrSH(W15h, W15l, 1) ^ u64.rotrSH(W15h, W15l, 8) ^ u64.shrSH(W15h, W15l, 7);\n const s0l = u64.rotrSL(W15h, W15l, 1) ^ u64.rotrSL(W15h, W15l, 8) ^ u64.shrSL(W15h, W15l, 7);\n // s1 := (w[i-2] rightrotate 19) xor (w[i-2] rightrotate 61) xor (w[i-2] rightshift 6)\n const W2h = SHA512_W_H[i - 2] | 0;\n const W2l = SHA512_W_L[i - 2] | 0;\n const s1h = u64.rotrSH(W2h, W2l, 19) ^ u64.rotrBH(W2h, W2l, 61) ^ u64.shrSH(W2h, W2l, 6);\n const s1l = u64.rotrSL(W2h, W2l, 19) ^ u64.rotrBL(W2h, W2l, 61) ^ u64.shrSL(W2h, W2l, 6);\n // SHA256_W[i] = s0 + s1 + SHA256_W[i - 7] + SHA256_W[i - 16];\n const SUMl = u64.add4L(s0l, s1l, SHA512_W_L[i - 7], SHA512_W_L[i - 16]);\n const SUMh = u64.add4H(SUMl, s0h, s1h, SHA512_W_H[i - 7], SHA512_W_H[i - 16]);\n SHA512_W_H[i] = SUMh | 0;\n SHA512_W_L[i] = SUMl | 0;\n }\n let { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;\n // Compression function main loop, 80 rounds\n for (let i = 0; i < 80; i++) {\n // S1 := (e rightrotate 14) xor (e rightrotate 18) xor (e rightrotate 41)\n const sigma1h = u64.rotrSH(Eh, El, 14) ^ u64.rotrSH(Eh, El, 18) ^ u64.rotrBH(Eh, El, 41);\n const sigma1l = u64.rotrSL(Eh, El, 14) ^ u64.rotrSL(Eh, El, 18) ^ u64.rotrBL(Eh, El, 41);\n //const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0;\n const CHIh = (Eh & Fh) ^ (~Eh & Gh);\n const CHIl = (El & Fl) ^ (~El & Gl);\n // T1 = H + sigma1 + Chi(E, F, G) + SHA512_K[i] + SHA512_W[i]\n // prettier-ignore\n const T1ll = u64.add5L(Hl, sigma1l, CHIl, SHA512_Kl[i], SHA512_W_L[i]);\n const T1h = u64.add5H(T1ll, Hh, sigma1h, CHIh, SHA512_Kh[i], SHA512_W_H[i]);\n const T1l = T1ll | 0;\n // S0 := (a rightrotate 28) xor (a rightrotate 34) xor (a rightrotate 39)\n const sigma0h = u64.rotrSH(Ah, Al, 28) ^ u64.rotrBH(Ah, Al, 34) ^ u64.rotrBH(Ah, Al, 39);\n const sigma0l = u64.rotrSL(Ah, Al, 28) ^ u64.rotrBL(Ah, Al, 34) ^ u64.rotrBL(Ah, Al, 39);\n const MAJh = (Ah & Bh) ^ (Ah & Ch) ^ (Bh & Ch);\n const MAJl = (Al & Bl) ^ (Al & Cl) ^ (Bl & Cl);\n Hh = Gh | 0;\n Hl = Gl | 0;\n Gh = Fh | 0;\n Gl = Fl | 0;\n Fh = Eh | 0;\n Fl = El | 0;\n ({ h: Eh, l: El } = u64.add(Dh | 0, Dl | 0, T1h | 0, T1l | 0));\n Dh = Ch | 0;\n Dl = Cl | 0;\n Ch = Bh | 0;\n Cl = Bl | 0;\n Bh = Ah | 0;\n Bl = Al | 0;\n const All = u64.add3L(T1l, sigma0l, MAJl);\n Ah = u64.add3H(All, T1h, sigma0h, MAJh);\n Al = All | 0;\n }\n // Add the compressed chunk to the current hash value\n ({ h: Ah, l: Al } = u64.add(this.Ah | 0, this.Al | 0, Ah | 0, Al | 0));\n ({ h: Bh, l: Bl } = u64.add(this.Bh | 0, this.Bl | 0, Bh | 0, Bl | 0));\n ({ h: Ch, l: Cl } = u64.add(this.Ch | 0, this.Cl | 0, Ch | 0, Cl | 0));\n ({ h: Dh, l: Dl } = u64.add(this.Dh | 0, this.Dl | 0, Dh | 0, Dl | 0));\n ({ h: Eh, l: El } = u64.add(this.Eh | 0, this.El | 0, Eh | 0, El | 0));\n ({ h: Fh, l: Fl } = u64.add(this.Fh | 0, this.Fl | 0, Fh | 0, Fl | 0));\n ({ h: Gh, l: Gl } = u64.add(this.Gh | 0, this.Gl | 0, Gh | 0, Gl | 0));\n ({ h: Hh, l: Hl } = u64.add(this.Hh | 0, this.Hl | 0, Hh | 0, Hl | 0));\n this.set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl);\n }\n protected roundClean(): void {\n clean(SHA512_W_H, SHA512_W_L);\n }\n destroy(): void {\n clean(this.buffer);\n this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);\n }\n}\n\nexport class SHA384 extends SHA512 {\n protected Ah: number = SHA384_IV[0] | 0;\n protected Al: number = SHA384_IV[1] | 0;\n protected Bh: number = SHA384_IV[2] | 0;\n protected Bl: number = SHA384_IV[3] | 0;\n protected Ch: number = SHA384_IV[4] | 0;\n protected Cl: number = SHA384_IV[5] | 0;\n protected Dh: number = SHA384_IV[6] | 0;\n protected Dl: number = SHA384_IV[7] | 0;\n protected Eh: number = SHA384_IV[8] | 0;\n protected El: number = SHA384_IV[9] | 0;\n protected Fh: number = SHA384_IV[10] | 0;\n protected Fl: number = SHA384_IV[11] | 0;\n protected Gh: number = SHA384_IV[12] | 0;\n protected Gl: number = SHA384_IV[13] | 0;\n protected Hh: number = SHA384_IV[14] | 0;\n protected Hl: number = SHA384_IV[15] | 0;\n\n constructor() {\n super(48);\n }\n}\n\n/**\n * Truncated SHA512/256 and SHA512/224.\n * SHA512_IV is XORed with 0xa5a5a5a5a5a5a5a5, then used as \"intermediary\" IV of SHA512/t.\n * Then t hashes string to produce result IV.\n * See `test/misc/sha2-gen-iv.js`.\n */\n\n/** SHA512/224 IV */\nconst T224_IV = /* @__PURE__ */ Uint32Array.from([\n 0x8c3d37c8, 0x19544da2, 0x73e19966, 0x89dcd4d6, 0x1dfab7ae, 0x32ff9c82, 0x679dd514, 0x582f9fcf,\n 0x0f6d2b69, 0x7bd44da8, 0x77e36f73, 0x04c48942, 0x3f9d85a8, 0x6a1d36c8, 0x1112e6ad, 0x91d692a1,\n]);\n\n/** SHA512/256 IV */\nconst T256_IV = /* @__PURE__ */ Uint32Array.from([\n 0x22312194, 0xfc2bf72c, 0x9f555fa3, 0xc84c64c2, 0x2393b86b, 0x6f53b151, 0x96387719, 0x5940eabd,\n 0x96283ee2, 0xa88effe3, 0xbe5e1e25, 0x53863992, 0x2b0199fc, 0x2c85b8aa, 0x0eb72ddc, 0x81c52ca2,\n]);\n\nexport class SHA512_224 extends SHA512 {\n protected Ah: number = T224_IV[0] | 0;\n protected Al: number = T224_IV[1] | 0;\n protected Bh: number = T224_IV[2] | 0;\n protected Bl: number = T224_IV[3] | 0;\n protected Ch: number = T224_IV[4] | 0;\n protected Cl: number = T224_IV[5] | 0;\n protected Dh: number = T224_IV[6] | 0;\n protected Dl: number = T224_IV[7] | 0;\n protected Eh: number = T224_IV[8] | 0;\n protected El: number = T224_IV[9] | 0;\n protected Fh: number = T224_IV[10] | 0;\n protected Fl: number = T224_IV[11] | 0;\n protected Gh: number = T224_IV[12] | 0;\n protected Gl: number = T224_IV[13] | 0;\n protected Hh: number = T224_IV[14] | 0;\n protected Hl: number = T224_IV[15] | 0;\n\n constructor() {\n super(28);\n }\n}\n\nexport class SHA512_256 extends SHA512 {\n protected Ah: number = T256_IV[0] | 0;\n protected Al: number = T256_IV[1] | 0;\n protected Bh: number = T256_IV[2] | 0;\n protected Bl: number = T256_IV[3] | 0;\n protected Ch: number = T256_IV[4] | 0;\n protected Cl: number = T256_IV[5] | 0;\n protected Dh: number = T256_IV[6] | 0;\n protected Dl: number = T256_IV[7] | 0;\n protected Eh: number = T256_IV[8] | 0;\n protected El: number = T256_IV[9] | 0;\n protected Fh: number = T256_IV[10] | 0;\n protected Fl: number = T256_IV[11] | 0;\n protected Gh: number = T256_IV[12] | 0;\n protected Gl: number = T256_IV[13] | 0;\n protected Hh: number = T256_IV[14] | 0;\n protected Hl: number = T256_IV[15] | 0;\n\n constructor() {\n super(32);\n }\n}\n\n/**\n * SHA2-256 hash function from RFC 4634.\n *\n * It is the fastest JS hash, even faster than Blake3.\n * To break sha256 using birthday attack, attackers need to try 2^128 hashes.\n * BTC network is doing 2^70 hashes/sec (2^95 hashes/year) as per 2025.\n */\nexport const sha256: CHash = /* @__PURE__ */ createHasher(() => new SHA256());\n/** SHA2-224 hash function from RFC 4634 */\nexport const sha224: CHash = /* @__PURE__ */ createHasher(() => new SHA224());\n\n/** SHA2-512 hash function from RFC 4634. */\nexport const sha512: CHash = /* @__PURE__ */ createHasher(() => new SHA512());\n/** SHA2-384 hash function from RFC 4634. */\nexport const sha384: CHash = /* @__PURE__ */ createHasher(() => new SHA384());\n\n/**\n * SHA2-512/256 \"truncated\" hash function, with improved resistance to length extension attacks.\n * See the paper on [truncated SHA512](https://eprint.iacr.org/2010/548.pdf).\n */\nexport const sha512_256: CHash = /* @__PURE__ */ createHasher(() => new SHA512_256());\n/**\n * SHA2-512/224 \"truncated\" hash function, with improved resistance to length extension attacks.\n * See the paper on [truncated SHA512](https://eprint.iacr.org/2010/548.pdf).\n */\nexport const sha512_224: CHash = /* @__PURE__ */ createHasher(() => new SHA512_224());\n", "/**\n * HMAC: RFC2104 message authentication code.\n * @module\n */\nimport { abytes, aexists, ahash, clean, Hash, toBytes, type CHash, type Input } from './utils.ts';\n\nexport class HMAC> extends Hash> {\n oHash: T;\n iHash: T;\n blockLen: number;\n outputLen: number;\n private finished = false;\n private destroyed = false;\n\n constructor(hash: CHash, _key: Input) {\n super();\n ahash(hash);\n const key = toBytes(_key);\n this.iHash = hash.create() as T;\n if (typeof this.iHash.update !== 'function')\n throw new Error('Expected instance of class which extends utils.Hash');\n this.blockLen = this.iHash.blockLen;\n this.outputLen = this.iHash.outputLen;\n const blockLen = this.blockLen;\n const pad = new Uint8Array(blockLen);\n // blockLen can be bigger than outputLen\n pad.set(key.length > blockLen ? hash.create().update(key).digest() : key);\n for (let i = 0; i < pad.length; i++) pad[i] ^= 0x36;\n this.iHash.update(pad);\n // By doing update (processing of first block) of outer hash here we can re-use it between multiple calls via clone\n this.oHash = hash.create() as T;\n // Undo internal XOR && apply outer XOR\n for (let i = 0; i < pad.length; i++) pad[i] ^= 0x36 ^ 0x5c;\n this.oHash.update(pad);\n clean(pad);\n }\n update(buf: Input): this {\n aexists(this);\n this.iHash.update(buf);\n return this;\n }\n digestInto(out: Uint8Array): void {\n aexists(this);\n abytes(out, this.outputLen);\n this.finished = true;\n this.iHash.digestInto(out);\n this.oHash.update(out);\n this.oHash.digestInto(out);\n this.destroy();\n }\n digest(): Uint8Array {\n const out = new Uint8Array(this.oHash.outputLen);\n this.digestInto(out);\n return out;\n }\n _cloneInto(to?: HMAC): HMAC {\n // Create new instance without calling constructor since key already in state and we don't know it.\n to ||= Object.create(Object.getPrototypeOf(this), {});\n const { oHash, iHash, finished, destroyed, blockLen, outputLen } = this;\n to = to as this;\n to.finished = finished;\n to.destroyed = destroyed;\n to.blockLen = blockLen;\n to.outputLen = outputLen;\n to.oHash = oHash._cloneInto(to.oHash);\n to.iHash = iHash._cloneInto(to.iHash);\n return to;\n }\n clone(): HMAC {\n return this._cloneInto();\n }\n destroy(): void {\n this.destroyed = true;\n this.oHash.destroy();\n this.iHash.destroy();\n }\n}\n\n/**\n * HMAC: RFC2104 message authentication code.\n * @param hash - function that would be used e.g. sha256\n * @param key - message key\n * @param message - message data\n * @example\n * import { hmac } from '@noble/hashes/hmac';\n * import { sha256 } from '@noble/hashes/sha2';\n * const mac1 = hmac(sha256, 'key', 'message');\n */\nexport const hmac: {\n (hash: CHash, key: Input, message: Input): Uint8Array;\n create(hash: CHash, key: Input): HMAC;\n} = (hash: CHash, key: Input, message: Input): Uint8Array =>\n new HMAC(hash, key).update(message).digest();\nhmac.create = (hash: CHash, key: Input) => new HMAC(hash, key);\n", "/**\n * Hex, bytes and number utilities.\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport {\n abytes as abytes_,\n bytesToHex as bytesToHex_,\n concatBytes as concatBytes_,\n hexToBytes as hexToBytes_,\n isBytes as isBytes_,\n} from '@noble/hashes/utils.js';\nexport {\n abytes,\n anumber,\n bytesToHex,\n bytesToUtf8,\n concatBytes,\n hexToBytes,\n isBytes,\n randomBytes,\n utf8ToBytes,\n} from '@noble/hashes/utils.js';\nconst _0n = /* @__PURE__ */ BigInt(0);\nconst _1n = /* @__PURE__ */ BigInt(1);\nexport type Hex = Uint8Array | string; // hex strings are accepted for simplicity\nexport type PrivKey = Hex | bigint; // bigints are accepted to ease learning curve\nexport type CHash = {\n (message: Uint8Array | string): Uint8Array;\n blockLen: number;\n outputLen: number;\n create(opts?: { dkLen?: number }): any; // For shake\n};\nexport type FHash = (message: Uint8Array | string) => Uint8Array;\n\nexport function abool(title: string, value: boolean): void {\n if (typeof value !== 'boolean') throw new Error(title + ' boolean expected, got ' + value);\n}\n\n// tmp name until v2\nexport function _abool2(value: boolean, title: string = ''): boolean {\n if (typeof value !== 'boolean') {\n const prefix = title && `\"${title}\"`;\n throw new Error(prefix + 'expected boolean, got type=' + typeof value);\n }\n return value;\n}\n\n// tmp name until v2\n/** Asserts something is Uint8Array. */\nexport function _abytes2(value: Uint8Array, length?: number, title: string = ''): Uint8Array {\n const bytes = isBytes_(value);\n const len = value?.length;\n const needsLen = length !== undefined;\n if (!bytes || (needsLen && len !== length)) {\n const prefix = title && `\"${title}\" `;\n const ofLen = needsLen ? ` of length ${length}` : '';\n const got = bytes ? `length=${len}` : `type=${typeof value}`;\n throw new Error(prefix + 'expected Uint8Array' + ofLen + ', got ' + got);\n }\n return value;\n}\n\n// Used in weierstrass, der\nexport function numberToHexUnpadded(num: number | bigint): string {\n const hex = num.toString(16);\n return hex.length & 1 ? '0' + hex : hex;\n}\n\nexport function hexToNumber(hex: string): bigint {\n if (typeof hex !== 'string') throw new Error('hex string expected, got ' + typeof hex);\n return hex === '' ? _0n : BigInt('0x' + hex); // Big Endian\n}\n\n// BE: Big Endian, LE: Little Endian\nexport function bytesToNumberBE(bytes: Uint8Array): bigint {\n return hexToNumber(bytesToHex_(bytes));\n}\nexport function bytesToNumberLE(bytes: Uint8Array): bigint {\n abytes_(bytes);\n return hexToNumber(bytesToHex_(Uint8Array.from(bytes).reverse()));\n}\n\nexport function numberToBytesBE(n: number | bigint, len: number): Uint8Array {\n return hexToBytes_(n.toString(16).padStart(len * 2, '0'));\n}\nexport function numberToBytesLE(n: number | bigint, len: number): Uint8Array {\n return numberToBytesBE(n, len).reverse();\n}\n// Unpadded, rarely used\nexport function numberToVarBytesBE(n: number | bigint): Uint8Array {\n return hexToBytes_(numberToHexUnpadded(n));\n}\n\n/**\n * Takes hex string or Uint8Array, converts to Uint8Array.\n * Validates output length.\n * Will throw error for other types.\n * @param title descriptive title for an error e.g. 'secret key'\n * @param hex hex string or Uint8Array\n * @param expectedLength optional, will compare to result array's length\n * @returns\n */\nexport function ensureBytes(title: string, hex: Hex, expectedLength?: number): Uint8Array {\n let res: Uint8Array;\n if (typeof hex === 'string') {\n try {\n res = hexToBytes_(hex);\n } catch (e) {\n throw new Error(title + ' must be hex string or Uint8Array, cause: ' + e);\n }\n } else if (isBytes_(hex)) {\n // Uint8Array.from() instead of hash.slice() because node.js Buffer\n // is instance of Uint8Array, and its slice() creates **mutable** copy\n res = Uint8Array.from(hex);\n } else {\n throw new Error(title + ' must be hex string or Uint8Array');\n }\n const len = res.length;\n if (typeof expectedLength === 'number' && len !== expectedLength)\n throw new Error(title + ' of length ' + expectedLength + ' expected, got ' + len);\n return res;\n}\n\n// Compares 2 u8a-s in kinda constant time\nexport function equalBytes(a: Uint8Array, b: Uint8Array): boolean {\n if (a.length !== b.length) return false;\n let diff = 0;\n for (let i = 0; i < a.length; i++) diff |= a[i] ^ b[i];\n return diff === 0;\n}\n/**\n * Copies Uint8Array. We can't use u8a.slice(), because u8a can be Buffer,\n * and Buffer#slice creates mutable copy. Never use Buffers!\n */\nexport function copyBytes(bytes: Uint8Array): Uint8Array {\n return Uint8Array.from(bytes);\n}\n\n/**\n * Decodes 7-bit ASCII string to Uint8Array, throws on non-ascii symbols\n * Should be safe to use for things expected to be ASCII.\n * Returns exact same result as utf8ToBytes for ASCII or throws.\n */\nexport function asciiToBytes(ascii: string): Uint8Array {\n return Uint8Array.from(ascii, (c, i) => {\n const charCode = c.charCodeAt(0);\n if (c.length !== 1 || charCode > 127) {\n throw new Error(\n `string contains non-ASCII character \"${ascii[i]}\" with code ${charCode} at position ${i}`\n );\n }\n return charCode;\n });\n}\n\n/**\n * @example utf8ToBytes('abc') // new Uint8Array([97, 98, 99])\n */\n// export const utf8ToBytes: typeof utf8ToBytes_ = utf8ToBytes_;\n/**\n * Converts bytes to string using UTF8 encoding.\n * @example bytesToUtf8(Uint8Array.from([97, 98, 99])) // 'abc'\n */\n// export const bytesToUtf8: typeof bytesToUtf8_ = bytesToUtf8_;\n\n// Is positive bigint\nconst isPosBig = (n: bigint) => typeof n === 'bigint' && _0n <= n;\n\nexport function inRange(n: bigint, min: bigint, max: bigint): boolean {\n return isPosBig(n) && isPosBig(min) && isPosBig(max) && min <= n && n < max;\n}\n\n/**\n * Asserts min <= n < max. NOTE: It's < max and not <= max.\n * @example\n * aInRange('x', x, 1n, 256n); // would assume x is in (1n..255n)\n */\nexport function aInRange(title: string, n: bigint, min: bigint, max: bigint): void {\n // Why min <= n < max and not a (min < n < max) OR b (min <= n <= max)?\n // consider P=256n, min=0n, max=P\n // - a for min=0 would require -1: `inRange('x', x, -1n, P)`\n // - b would commonly require subtraction: `inRange('x', x, 0n, P - 1n)`\n // - our way is the cleanest: `inRange('x', x, 0n, P)\n if (!inRange(n, min, max))\n throw new Error('expected valid ' + title + ': ' + min + ' <= n < ' + max + ', got ' + n);\n}\n\n// Bit operations\n\n/**\n * Calculates amount of bits in a bigint.\n * Same as `n.toString(2).length`\n * TODO: merge with nLength in modular\n */\nexport function bitLen(n: bigint): number {\n let len;\n for (len = 0; n > _0n; n >>= _1n, len += 1);\n return len;\n}\n\n/**\n * Gets single bit at position.\n * NOTE: first bit position is 0 (same as arrays)\n * Same as `!!+Array.from(n.toString(2)).reverse()[pos]`\n */\nexport function bitGet(n: bigint, pos: number): bigint {\n return (n >> BigInt(pos)) & _1n;\n}\n\n/**\n * Sets single bit at position.\n */\nexport function bitSet(n: bigint, pos: number, value: boolean): bigint {\n return n | ((value ? _1n : _0n) << BigInt(pos));\n}\n\n/**\n * Calculate mask for N bits. Not using ** operator with bigints because of old engines.\n * Same as BigInt(`0b${Array(i).fill('1').join('')}`)\n */\nexport const bitMask = (n: number): bigint => (_1n << BigInt(n)) - _1n;\n\n// DRBG\n\ntype Pred = (v: Uint8Array) => T | undefined;\n/**\n * Minimal HMAC-DRBG from NIST 800-90 for RFC6979 sigs.\n * @returns function that will call DRBG until 2nd arg returns something meaningful\n * @example\n * const drbg = createHmacDRBG(32, 32, hmac);\n * drbg(seed, bytesToKey); // bytesToKey must return Key or undefined\n */\nexport function createHmacDrbg(\n hashLen: number,\n qByteLen: number,\n hmacFn: (key: Uint8Array, ...messages: Uint8Array[]) => Uint8Array\n): (seed: Uint8Array, predicate: Pred) => T {\n if (typeof hashLen !== 'number' || hashLen < 2) throw new Error('hashLen must be a number');\n if (typeof qByteLen !== 'number' || qByteLen < 2) throw new Error('qByteLen must be a number');\n if (typeof hmacFn !== 'function') throw new Error('hmacFn must be a function');\n // Step B, Step C: set hashLen to 8*ceil(hlen/8)\n const u8n = (len: number) => new Uint8Array(len); // creates Uint8Array\n const u8of = (byte: number) => Uint8Array.of(byte); // another shortcut\n let v = u8n(hashLen); // Minimal non-full-spec HMAC-DRBG from NIST 800-90 for RFC6979 sigs.\n let k = u8n(hashLen); // Steps B and C of RFC6979 3.2: set hashLen, in our case always same\n let i = 0; // Iterations counter, will throw when over 1000\n const reset = () => {\n v.fill(1);\n k.fill(0);\n i = 0;\n };\n const h = (...b: Uint8Array[]) => hmacFn(k, v, ...b); // hmac(k)(v, ...values)\n const reseed = (seed = u8n(0)) => {\n // HMAC-DRBG reseed() function. Steps D-G\n k = h(u8of(0x00), seed); // k = hmac(k || v || 0x00 || seed)\n v = h(); // v = hmac(k || v)\n if (seed.length === 0) return;\n k = h(u8of(0x01), seed); // k = hmac(k || v || 0x01 || seed)\n v = h(); // v = hmac(k || v)\n };\n const gen = () => {\n // HMAC-DRBG generate() function\n if (i++ >= 1000) throw new Error('drbg: tried 1000 values');\n let len = 0;\n const out: Uint8Array[] = [];\n while (len < qByteLen) {\n v = h();\n const sl = v.slice();\n out.push(sl);\n len += v.length;\n }\n return concatBytes_(...out);\n };\n const genUntil = (seed: Uint8Array, pred: Pred): T => {\n reset();\n reseed(seed); // Steps D-G\n let res: T | undefined = undefined; // Step H: grind until k is in [1..n-1]\n while (!(res = pred(gen()))) reseed();\n reset();\n return res;\n };\n return genUntil;\n}\n\n// Validating curves and fields\n\nconst validatorFns = {\n bigint: (val: any): boolean => typeof val === 'bigint',\n function: (val: any): boolean => typeof val === 'function',\n boolean: (val: any): boolean => typeof val === 'boolean',\n string: (val: any): boolean => typeof val === 'string',\n stringOrUint8Array: (val: any): boolean => typeof val === 'string' || isBytes_(val),\n isSafeInteger: (val: any): boolean => Number.isSafeInteger(val),\n array: (val: any): boolean => Array.isArray(val),\n field: (val: any, object: any): any => (object as any).Fp.isValid(val),\n hash: (val: any): boolean => typeof val === 'function' && Number.isSafeInteger(val.outputLen),\n} as const;\ntype Validator = keyof typeof validatorFns;\ntype ValMap> = { [K in keyof T]?: Validator };\n// type Record = { [P in K]: T; }\n\nexport function validateObject>(\n object: T,\n validators: ValMap,\n optValidators: ValMap = {}\n): T {\n const checkField = (fieldName: keyof T, type: Validator, isOptional: boolean) => {\n const checkVal = validatorFns[type];\n if (typeof checkVal !== 'function') throw new Error('invalid validator function');\n\n const val = object[fieldName as keyof typeof object];\n if (isOptional && val === undefined) return;\n if (!checkVal(val, object)) {\n throw new Error(\n 'param ' + String(fieldName) + ' is invalid. Expected ' + type + ', got ' + val\n );\n }\n };\n for (const [fieldName, type] of Object.entries(validators)) checkField(fieldName, type!, false);\n for (const [fieldName, type] of Object.entries(optValidators)) checkField(fieldName, type!, true);\n return object;\n}\n// validate type tests\n// const o: { a: number; b: number; c: number } = { a: 1, b: 5, c: 6 };\n// const z0 = validateObject(o, { a: 'isSafeInteger' }, { c: 'bigint' }); // Ok!\n// // Should fail type-check\n// const z1 = validateObject(o, { a: 'tmp' }, { c: 'zz' });\n// const z2 = validateObject(o, { a: 'isSafeInteger' }, { c: 'zz' });\n// const z3 = validateObject(o, { test: 'boolean', z: 'bug' });\n// const z4 = validateObject(o, { a: 'boolean', z: 'bug' });\n\nexport function isHash(val: CHash): boolean {\n return typeof val === 'function' && Number.isSafeInteger(val.outputLen);\n}\nexport function _validateObject(\n object: Record,\n fields: Record,\n optFields: Record = {}\n): void {\n if (!object || typeof object !== 'object') throw new Error('expected valid options object');\n type Item = keyof typeof object;\n function checkField(fieldName: Item, expectedType: string, isOpt: boolean) {\n const val = object[fieldName];\n if (isOpt && val === undefined) return;\n const current = typeof val;\n if (current !== expectedType || val === null)\n throw new Error(`param \"${fieldName}\" is invalid: expected ${expectedType}, got ${current}`);\n }\n Object.entries(fields).forEach(([k, v]) => checkField(k, v, false));\n Object.entries(optFields).forEach(([k, v]) => checkField(k, v, true));\n}\n\n/**\n * throws not implemented error\n */\nexport const notImplemented = (): never => {\n throw new Error('not implemented');\n};\n\n/**\n * Memoizes (caches) computation result.\n * Uses WeakMap: the value is going auto-cleaned by GC after last reference is removed.\n */\nexport function memoized(\n fn: (arg: T, ...args: O) => R\n): (arg: T, ...args: O) => R {\n const map = new WeakMap();\n return (arg: T, ...args: O): R => {\n const val = map.get(arg);\n if (val !== undefined) return val;\n const computed = fn(arg, ...args);\n map.set(arg, computed);\n return computed;\n };\n}\n", "/**\n * Utils for modular division and fields.\n * Field over 11 is a finite (Galois) field is integer number operations `mod 11`.\n * There is no division: it is replaced by modular multiplicative inverse.\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport {\n _validateObject,\n anumber,\n bitMask,\n bytesToNumberBE,\n bytesToNumberLE,\n ensureBytes,\n numberToBytesBE,\n numberToBytesLE,\n} from '../utils.ts';\n\n// prettier-ignore\nconst _0n = BigInt(0), _1n = BigInt(1), _2n = /* @__PURE__ */ BigInt(2), _3n = /* @__PURE__ */ BigInt(3);\n// prettier-ignore\nconst _4n = /* @__PURE__ */ BigInt(4), _5n = /* @__PURE__ */ BigInt(5), _7n = /* @__PURE__ */ BigInt(7);\n// prettier-ignore\nconst _8n = /* @__PURE__ */ BigInt(8), _9n = /* @__PURE__ */ BigInt(9), _16n = /* @__PURE__ */ BigInt(16);\n\n// Calculates a modulo b\nexport function mod(a: bigint, b: bigint): bigint {\n const result = a % b;\n return result >= _0n ? result : b + result;\n}\n/**\n * Efficiently raise num to power and do modular division.\n * Unsafe in some contexts: uses ladder, so can expose bigint bits.\n * @example\n * pow(2n, 6n, 11n) // 64n % 11n == 9n\n */\nexport function pow(num: bigint, power: bigint, modulo: bigint): bigint {\n return FpPow(Field(modulo), num, power);\n}\n\n/** Does `x^(2^power)` mod p. `pow2(30, 4)` == `30^(2^4)` */\nexport function pow2(x: bigint, power: bigint, modulo: bigint): bigint {\n let res = x;\n while (power-- > _0n) {\n res *= res;\n res %= modulo;\n }\n return res;\n}\n\n/**\n * Inverses number over modulo.\n * Implemented using [Euclidean GCD](https://brilliant.org/wiki/extended-euclidean-algorithm/).\n */\nexport function invert(number: bigint, modulo: bigint): bigint {\n if (number === _0n) throw new Error('invert: expected non-zero number');\n if (modulo <= _0n) throw new Error('invert: expected positive modulus, got ' + modulo);\n // Fermat's little theorem \"CT-like\" version inv(n) = n^(m-2) mod m is 30x slower.\n let a = mod(number, modulo);\n let b = modulo;\n // prettier-ignore\n let x = _0n, y = _1n, u = _1n, v = _0n;\n while (a !== _0n) {\n // JIT applies optimization if those two lines follow each other\n const q = b / a;\n const r = b % a;\n const m = x - u * q;\n const n = y - v * q;\n // prettier-ignore\n b = a, a = r, x = u, y = v, u = m, v = n;\n }\n const gcd = b;\n if (gcd !== _1n) throw new Error('invert: does not exist');\n return mod(x, modulo);\n}\n\nfunction assertIsSquare(Fp: IField, root: T, n: T): void {\n if (!Fp.eql(Fp.sqr(root), n)) throw new Error('Cannot find square root');\n}\n\n// Not all roots are possible! Example which will throw:\n// const NUM =\n// n = 72057594037927816n;\n// Fp = Field(BigInt('0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaaab'));\nfunction sqrt3mod4(Fp: IField, n: T) {\n const p1div4 = (Fp.ORDER + _1n) / _4n;\n const root = Fp.pow(n, p1div4);\n assertIsSquare(Fp, root, n);\n return root;\n}\n\nfunction sqrt5mod8(Fp: IField, n: T) {\n const p5div8 = (Fp.ORDER - _5n) / _8n;\n const n2 = Fp.mul(n, _2n);\n const v = Fp.pow(n2, p5div8);\n const nv = Fp.mul(n, v);\n const i = Fp.mul(Fp.mul(nv, _2n), v);\n const root = Fp.mul(nv, Fp.sub(i, Fp.ONE));\n assertIsSquare(Fp, root, n);\n return root;\n}\n\n// Based on RFC9380, Kong algorithm\n// prettier-ignore\nfunction sqrt9mod16(P: bigint): (Fp: IField, n: T) => T {\n const Fp_ = Field(P);\n const tn = tonelliShanks(P);\n const c1 = tn(Fp_, Fp_.neg(Fp_.ONE));// 1. c1 = sqrt(-1) in F, i.e., (c1^2) == -1 in F\n const c2 = tn(Fp_, c1); // 2. c2 = sqrt(c1) in F, i.e., (c2^2) == c1 in F\n const c3 = tn(Fp_, Fp_.neg(c1)); // 3. c3 = sqrt(-c1) in F, i.e., (c3^2) == -c1 in F\n const c4 = (P + _7n) / _16n; // 4. c4 = (q + 7) / 16 # Integer arithmetic\n return (Fp: IField, n: T) => {\n let tv1 = Fp.pow(n, c4); // 1. tv1 = x^c4\n let tv2 = Fp.mul(tv1, c1); // 2. tv2 = c1 * tv1\n const tv3 = Fp.mul(tv1, c2); // 3. tv3 = c2 * tv1\n const tv4 = Fp.mul(tv1, c3); // 4. tv4 = c3 * tv1\n const e1 = Fp.eql(Fp.sqr(tv2), n); // 5. e1 = (tv2^2) == x\n const e2 = Fp.eql(Fp.sqr(tv3), n); // 6. e2 = (tv3^2) == x\n tv1 = Fp.cmov(tv1, tv2, e1); // 7. tv1 = CMOV(tv1, tv2, e1) # Select tv2 if (tv2^2) == x\n tv2 = Fp.cmov(tv4, tv3, e2); // 8. tv2 = CMOV(tv4, tv3, e2) # Select tv3 if (tv3^2) == x\n const e3 = Fp.eql(Fp.sqr(tv2), n); // 9. e3 = (tv2^2) == x\n const root = Fp.cmov(tv1, tv2, e3);// 10. z = CMOV(tv1, tv2, e3) # Select sqrt from tv1 & tv2\n assertIsSquare(Fp, root, n);\n return root;\n };\n}\n\n/**\n * Tonelli-Shanks square root search algorithm.\n * 1. https://eprint.iacr.org/2012/685.pdf (page 12)\n * 2. Square Roots from 1; 24, 51, 10 to Dan Shanks\n * @param P field order\n * @returns function that takes field Fp (created from P) and number n\n */\nexport function tonelliShanks(P: bigint): (Fp: IField, n: T) => T {\n // Initialization (precomputation).\n // Caching initialization could boost perf by 7%.\n if (P < _3n) throw new Error('sqrt is not defined for small field');\n // Factor P - 1 = Q * 2^S, where Q is odd\n let Q = P - _1n;\n let S = 0;\n while (Q % _2n === _0n) {\n Q /= _2n;\n S++;\n }\n\n // Find the first quadratic non-residue Z >= 2\n let Z = _2n;\n const _Fp = Field(P);\n while (FpLegendre(_Fp, Z) === 1) {\n // Basic primality test for P. After x iterations, chance of\n // not finding quadratic non-residue is 2^x, so 2^1000.\n if (Z++ > 1000) throw new Error('Cannot find square root: probably non-prime P');\n }\n // Fast-path; usually done before Z, but we do \"primality test\".\n if (S === 1) return sqrt3mod4;\n\n // Slow-path\n // TODO: test on Fp2 and others\n let cc = _Fp.pow(Z, Q); // c = z^Q\n const Q1div2 = (Q + _1n) / _2n;\n return function tonelliSlow(Fp: IField, n: T): T {\n if (Fp.is0(n)) return n;\n // Check if n is a quadratic residue using Legendre symbol\n if (FpLegendre(Fp, n) !== 1) throw new Error('Cannot find square root');\n\n // Initialize variables for the main loop\n let M = S;\n let c = Fp.mul(Fp.ONE, cc); // c = z^Q, move cc from field _Fp into field Fp\n let t = Fp.pow(n, Q); // t = n^Q, first guess at the fudge factor\n let R = Fp.pow(n, Q1div2); // R = n^((Q+1)/2), first guess at the square root\n\n // Main loop\n // while t != 1\n while (!Fp.eql(t, Fp.ONE)) {\n if (Fp.is0(t)) return Fp.ZERO; // if t=0 return R=0\n let i = 1;\n\n // Find the smallest i >= 1 such that t^(2^i) ≡ 1 (mod P)\n let t_tmp = Fp.sqr(t); // t^(2^1)\n while (!Fp.eql(t_tmp, Fp.ONE)) {\n i++;\n t_tmp = Fp.sqr(t_tmp); // t^(2^2)...\n if (i === M) throw new Error('Cannot find square root');\n }\n\n // Calculate the exponent for b: 2^(M - i - 1)\n const exponent = _1n << BigInt(M - i - 1); // bigint is important\n const b = Fp.pow(c, exponent); // b = 2^(M - i - 1)\n\n // Update variables\n M = i;\n c = Fp.sqr(b); // c = b^2\n t = Fp.mul(t, c); // t = (t * b^2)\n R = Fp.mul(R, b); // R = R*b\n }\n return R;\n };\n}\n\n/**\n * Square root for a finite field. Will try optimized versions first:\n *\n * 1. P ≡ 3 (mod 4)\n * 2. P ≡ 5 (mod 8)\n * 3. P ≡ 9 (mod 16)\n * 4. Tonelli-Shanks algorithm\n *\n * Different algorithms can give different roots, it is up to user to decide which one they want.\n * For example there is FpSqrtOdd/FpSqrtEven to choice root based on oddness (used for hash-to-curve).\n */\nexport function FpSqrt(P: bigint): (Fp: IField, n: T) => T {\n // P ≡ 3 (mod 4) => √n = n^((P+1)/4)\n if (P % _4n === _3n) return sqrt3mod4;\n // P ≡ 5 (mod 8) => Atkin algorithm, page 10 of https://eprint.iacr.org/2012/685.pdf\n if (P % _8n === _5n) return sqrt5mod8;\n // P ≡ 9 (mod 16) => Kong algorithm, page 11 of https://eprint.iacr.org/2012/685.pdf (algorithm 4)\n if (P % _16n === _9n) return sqrt9mod16(P);\n // Tonelli-Shanks algorithm\n return tonelliShanks(P);\n}\n\n// Little-endian check for first LE bit (last BE bit);\nexport const isNegativeLE = (num: bigint, modulo: bigint): boolean =>\n (mod(num, modulo) & _1n) === _1n;\n\n/** Field is not always over prime: for example, Fp2 has ORDER(q)=p^m. */\nexport interface IField {\n ORDER: bigint;\n isLE: boolean;\n BYTES: number;\n BITS: number;\n MASK: bigint;\n ZERO: T;\n ONE: T;\n // 1-arg\n create: (num: T) => T;\n isValid: (num: T) => boolean;\n is0: (num: T) => boolean;\n isValidNot0: (num: T) => boolean;\n neg(num: T): T;\n inv(num: T): T;\n sqrt(num: T): T;\n sqr(num: T): T;\n // 2-args\n eql(lhs: T, rhs: T): boolean;\n add(lhs: T, rhs: T): T;\n sub(lhs: T, rhs: T): T;\n mul(lhs: T, rhs: T | bigint): T;\n pow(lhs: T, power: bigint): T;\n div(lhs: T, rhs: T | bigint): T;\n // N for NonNormalized (for now)\n addN(lhs: T, rhs: T): T;\n subN(lhs: T, rhs: T): T;\n mulN(lhs: T, rhs: T | bigint): T;\n sqrN(num: T): T;\n\n // Optional\n // Should be same as sgn0 function in\n // [RFC9380](https://www.rfc-editor.org/rfc/rfc9380#section-4.1).\n // NOTE: sgn0 is 'negative in LE', which is same as odd. And negative in LE is kinda strange definition anyway.\n isOdd?(num: T): boolean; // Odd instead of even since we have it for Fp2\n allowedLengths?: number[];\n // legendre?(num: T): T;\n invertBatch: (lst: T[]) => T[];\n toBytes(num: T): Uint8Array;\n fromBytes(bytes: Uint8Array, skipValidation?: boolean): T;\n // If c is False, CMOV returns a, otherwise it returns b.\n cmov(a: T, b: T, c: boolean): T;\n}\n// prettier-ignore\nconst FIELD_FIELDS = [\n 'create', 'isValid', 'is0', 'neg', 'inv', 'sqrt', 'sqr',\n 'eql', 'add', 'sub', 'mul', 'pow', 'div',\n 'addN', 'subN', 'mulN', 'sqrN'\n] as const;\nexport function validateField(field: IField): IField {\n const initial = {\n ORDER: 'bigint',\n MASK: 'bigint',\n BYTES: 'number',\n BITS: 'number',\n } as Record;\n const opts = FIELD_FIELDS.reduce((map, val: string) => {\n map[val] = 'function';\n return map;\n }, initial);\n _validateObject(field, opts);\n // const max = 16384;\n // if (field.BYTES < 1 || field.BYTES > max) throw new Error('invalid field');\n // if (field.BITS < 1 || field.BITS > 8 * max) throw new Error('invalid field');\n return field;\n}\n\n// Generic field functions\n\n/**\n * Same as `pow` but for Fp: non-constant-time.\n * Unsafe in some contexts: uses ladder, so can expose bigint bits.\n */\nexport function FpPow(Fp: IField, num: T, power: bigint): T {\n if (power < _0n) throw new Error('invalid exponent, negatives unsupported');\n if (power === _0n) return Fp.ONE;\n if (power === _1n) return num;\n let p = Fp.ONE;\n let d = num;\n while (power > _0n) {\n if (power & _1n) p = Fp.mul(p, d);\n d = Fp.sqr(d);\n power >>= _1n;\n }\n return p;\n}\n\n/**\n * Efficiently invert an array of Field elements.\n * Exception-free. Will return `undefined` for 0 elements.\n * @param passZero map 0 to 0 (instead of undefined)\n */\nexport function FpInvertBatch(Fp: IField, nums: T[], passZero = false): T[] {\n const inverted = new Array(nums.length).fill(passZero ? Fp.ZERO : undefined);\n // Walk from first to last, multiply them by each other MOD p\n const multipliedAcc = nums.reduce((acc, num, i) => {\n if (Fp.is0(num)) return acc;\n inverted[i] = acc;\n return Fp.mul(acc, num);\n }, Fp.ONE);\n // Invert last element\n const invertedAcc = Fp.inv(multipliedAcc);\n // Walk from last to first, multiply them by inverted each other MOD p\n nums.reduceRight((acc, num, i) => {\n if (Fp.is0(num)) return acc;\n inverted[i] = Fp.mul(acc, inverted[i]);\n return Fp.mul(acc, num);\n }, invertedAcc);\n return inverted;\n}\n\n// TODO: remove\nexport function FpDiv(Fp: IField, lhs: T, rhs: T | bigint): T {\n return Fp.mul(lhs, typeof rhs === 'bigint' ? invert(rhs, Fp.ORDER) : Fp.inv(rhs));\n}\n\n/**\n * Legendre symbol.\n * Legendre constant is used to calculate Legendre symbol (a | p)\n * which denotes the value of a^((p-1)/2) (mod p).\n *\n * * (a | p) ≡ 1 if a is a square (mod p), quadratic residue\n * * (a | p) ≡ -1 if a is not a square (mod p), quadratic non residue\n * * (a | p) ≡ 0 if a ≡ 0 (mod p)\n */\nexport function FpLegendre(Fp: IField, n: T): -1 | 0 | 1 {\n // We can use 3rd argument as optional cache of this value\n // but seems unneeded for now. The operation is very fast.\n const p1mod2 = (Fp.ORDER - _1n) / _2n;\n const powered = Fp.pow(n, p1mod2);\n const yes = Fp.eql(powered, Fp.ONE);\n const zero = Fp.eql(powered, Fp.ZERO);\n const no = Fp.eql(powered, Fp.neg(Fp.ONE));\n if (!yes && !zero && !no) throw new Error('invalid Legendre symbol result');\n return yes ? 1 : zero ? 0 : -1;\n}\n\n// This function returns True whenever the value x is a square in the field F.\nexport function FpIsSquare(Fp: IField, n: T): boolean {\n const l = FpLegendre(Fp, n);\n return l === 1;\n}\n\nexport type NLength = { nByteLength: number; nBitLength: number };\n// CURVE.n lengths\nexport function nLength(n: bigint, nBitLength?: number): NLength {\n // Bit size, byte size of CURVE.n\n if (nBitLength !== undefined) anumber(nBitLength);\n const _nBitLength = nBitLength !== undefined ? nBitLength : n.toString(2).length;\n const nByteLength = Math.ceil(_nBitLength / 8);\n return { nBitLength: _nBitLength, nByteLength };\n}\n\ntype FpField = IField & Required, 'isOdd'>>;\ntype SqrtFn = (n: bigint) => bigint;\ntype FieldOpts = Partial<{\n sqrt: SqrtFn;\n isLE: boolean;\n BITS: number;\n modFromBytes: boolean; // bls12-381 requires mod(n) instead of rejecting keys >= n\n allowedLengths?: readonly number[]; // for P521 (adds padding for smaller sizes)\n}>;\n/**\n * Creates a finite field. Major performance optimizations:\n * * 1. Denormalized operations like mulN instead of mul.\n * * 2. Identical object shape: never add or remove keys.\n * * 3. `Object.freeze`.\n * Fragile: always run a benchmark on a change.\n * Security note: operations don't check 'isValid' for all elements for performance reasons,\n * it is caller responsibility to check this.\n * This is low-level code, please make sure you know what you're doing.\n *\n * Note about field properties:\n * * CHARACTERISTIC p = prime number, number of elements in main subgroup.\n * * ORDER q = similar to cofactor in curves, may be composite `q = p^m`.\n *\n * @param ORDER field order, probably prime, or could be composite\n * @param bitLen how many bits the field consumes\n * @param isLE (default: false) if encoding / decoding should be in little-endian\n * @param redef optional faster redefinitions of sqrt and other methods\n */\nexport function Field(\n ORDER: bigint,\n bitLenOrOpts?: number | FieldOpts, // TODO: use opts only in v2?\n isLE = false,\n opts: { sqrt?: SqrtFn } = {}\n): Readonly {\n if (ORDER <= _0n) throw new Error('invalid field: expected ORDER > 0, got ' + ORDER);\n let _nbitLength: number | undefined = undefined;\n let _sqrt: SqrtFn | undefined = undefined;\n let modFromBytes: boolean = false;\n let allowedLengths: undefined | readonly number[] = undefined;\n if (typeof bitLenOrOpts === 'object' && bitLenOrOpts != null) {\n if (opts.sqrt || isLE) throw new Error('cannot specify opts in two arguments');\n const _opts = bitLenOrOpts;\n if (_opts.BITS) _nbitLength = _opts.BITS;\n if (_opts.sqrt) _sqrt = _opts.sqrt;\n if (typeof _opts.isLE === 'boolean') isLE = _opts.isLE;\n if (typeof _opts.modFromBytes === 'boolean') modFromBytes = _opts.modFromBytes;\n allowedLengths = _opts.allowedLengths;\n } else {\n if (typeof bitLenOrOpts === 'number') _nbitLength = bitLenOrOpts;\n if (opts.sqrt) _sqrt = opts.sqrt;\n }\n const { nBitLength: BITS, nByteLength: BYTES } = nLength(ORDER, _nbitLength);\n if (BYTES > 2048) throw new Error('invalid field: expected ORDER of <= 2048 bytes');\n let sqrtP: ReturnType; // cached sqrtP\n const f: Readonly = Object.freeze({\n ORDER,\n isLE,\n BITS,\n BYTES,\n MASK: bitMask(BITS),\n ZERO: _0n,\n ONE: _1n,\n allowedLengths: allowedLengths,\n create: (num) => mod(num, ORDER),\n isValid: (num) => {\n if (typeof num !== 'bigint')\n throw new Error('invalid field element: expected bigint, got ' + typeof num);\n return _0n <= num && num < ORDER; // 0 is valid element, but it's not invertible\n },\n is0: (num) => num === _0n,\n // is valid and invertible\n isValidNot0: (num: bigint) => !f.is0(num) && f.isValid(num),\n isOdd: (num) => (num & _1n) === _1n,\n neg: (num) => mod(-num, ORDER),\n eql: (lhs, rhs) => lhs === rhs,\n\n sqr: (num) => mod(num * num, ORDER),\n add: (lhs, rhs) => mod(lhs + rhs, ORDER),\n sub: (lhs, rhs) => mod(lhs - rhs, ORDER),\n mul: (lhs, rhs) => mod(lhs * rhs, ORDER),\n pow: (num, power) => FpPow(f, num, power),\n div: (lhs, rhs) => mod(lhs * invert(rhs, ORDER), ORDER),\n\n // Same as above, but doesn't normalize\n sqrN: (num) => num * num,\n addN: (lhs, rhs) => lhs + rhs,\n subN: (lhs, rhs) => lhs - rhs,\n mulN: (lhs, rhs) => lhs * rhs,\n\n inv: (num) => invert(num, ORDER),\n sqrt:\n _sqrt ||\n ((n) => {\n if (!sqrtP) sqrtP = FpSqrt(ORDER);\n return sqrtP(f, n);\n }),\n toBytes: (num) => (isLE ? numberToBytesLE(num, BYTES) : numberToBytesBE(num, BYTES)),\n fromBytes: (bytes, skipValidation = true) => {\n if (allowedLengths) {\n if (!allowedLengths.includes(bytes.length) || bytes.length > BYTES) {\n throw new Error(\n 'Field.fromBytes: expected ' + allowedLengths + ' bytes, got ' + bytes.length\n );\n }\n const padded = new Uint8Array(BYTES);\n // isLE add 0 to right, !isLE to the left.\n padded.set(bytes, isLE ? 0 : padded.length - bytes.length);\n bytes = padded;\n }\n if (bytes.length !== BYTES)\n throw new Error('Field.fromBytes: expected ' + BYTES + ' bytes, got ' + bytes.length);\n let scalar = isLE ? bytesToNumberLE(bytes) : bytesToNumberBE(bytes);\n if (modFromBytes) scalar = mod(scalar, ORDER);\n if (!skipValidation)\n if (!f.isValid(scalar)) throw new Error('invalid field element: outside of range 0..ORDER');\n // NOTE: we don't validate scalar here, please use isValid. This done such way because some\n // protocol may allow non-reduced scalar that reduced later or changed some other way.\n return scalar;\n },\n // TODO: we don't need it here, move out to separate fn\n invertBatch: (lst) => FpInvertBatch(f, lst),\n // We can't move this out because Fp6, Fp12 implement it\n // and it's unclear what to return in there.\n cmov: (a, b, c) => (c ? b : a),\n } as FpField);\n return Object.freeze(f);\n}\n\n// Generic random scalar, we can do same for other fields if via Fp2.mul(Fp2.ONE, Fp2.random)?\n// This allows unsafe methods like ignore bias or zero. These unsafe, but often used in different protocols (if deterministic RNG).\n// which mean we cannot force this via opts.\n// Not sure what to do with randomBytes, we can accept it inside opts if wanted.\n// Probably need to export getMinHashLength somewhere?\n// random(bytes?: Uint8Array, unsafeAllowZero = false, unsafeAllowBias = false) {\n// const LEN = !unsafeAllowBias ? getMinHashLength(ORDER) : BYTES;\n// if (bytes === undefined) bytes = randomBytes(LEN); // _opts.randomBytes?\n// const num = isLE ? bytesToNumberLE(bytes) : bytesToNumberBE(bytes);\n// // `mod(x, 11)` can sometimes produce 0. `mod(x, 10) + 1` is the same, but no 0\n// const reduced = unsafeAllowZero ? mod(num, ORDER) : mod(num, ORDER - _1n) + _1n;\n// return reduced;\n// },\n\nexport function FpSqrtOdd(Fp: IField, elm: T): T {\n if (!Fp.isOdd) throw new Error(\"Field doesn't have isOdd\");\n const root = Fp.sqrt(elm);\n return Fp.isOdd(root) ? root : Fp.neg(root);\n}\n\nexport function FpSqrtEven(Fp: IField, elm: T): T {\n if (!Fp.isOdd) throw new Error(\"Field doesn't have isOdd\");\n const root = Fp.sqrt(elm);\n return Fp.isOdd(root) ? Fp.neg(root) : root;\n}\n\n/**\n * \"Constant-time\" private key generation utility.\n * Same as mapKeyToField, but accepts less bytes (40 instead of 48 for 32-byte field).\n * Which makes it slightly more biased, less secure.\n * @deprecated use `mapKeyToField` instead\n */\nexport function hashToPrivateScalar(\n hash: string | Uint8Array,\n groupOrder: bigint,\n isLE = false\n): bigint {\n hash = ensureBytes('privateHash', hash);\n const hashLen = hash.length;\n const minLen = nLength(groupOrder).nByteLength + 8;\n if (minLen < 24 || hashLen < minLen || hashLen > 1024)\n throw new Error(\n 'hashToPrivateScalar: expected ' + minLen + '-1024 bytes of input, got ' + hashLen\n );\n const num = isLE ? bytesToNumberLE(hash) : bytesToNumberBE(hash);\n return mod(num, groupOrder - _1n) + _1n;\n}\n\n/**\n * Returns total number of bytes consumed by the field element.\n * For example, 32 bytes for usual 256-bit weierstrass curve.\n * @param fieldOrder number of field elements, usually CURVE.n\n * @returns byte length of field\n */\nexport function getFieldBytesLength(fieldOrder: bigint): number {\n if (typeof fieldOrder !== 'bigint') throw new Error('field order must be bigint');\n const bitLength = fieldOrder.toString(2).length;\n return Math.ceil(bitLength / 8);\n}\n\n/**\n * Returns minimal amount of bytes that can be safely reduced\n * by field order.\n * Should be 2^-128 for 128-bit curve such as P256.\n * @param fieldOrder number of field elements, usually CURVE.n\n * @returns byte length of target hash\n */\nexport function getMinHashLength(fieldOrder: bigint): number {\n const length = getFieldBytesLength(fieldOrder);\n return length + Math.ceil(length / 2);\n}\n\n/**\n * \"Constant-time\" private key generation utility.\n * Can take (n + n/2) or more bytes of uniform input e.g. from CSPRNG or KDF\n * and convert them into private scalar, with the modulo bias being negligible.\n * Needs at least 48 bytes of input for 32-byte private key.\n * https://research.kudelskisecurity.com/2020/07/28/the-definitive-guide-to-modulo-bias-and-how-to-avoid-it/\n * FIPS 186-5, A.2 https://csrc.nist.gov/publications/detail/fips/186/5/final\n * RFC 9380, https://www.rfc-editor.org/rfc/rfc9380#section-5\n * @param hash hash output from SHA3 or a similar function\n * @param groupOrder size of subgroup - (e.g. secp256k1.CURVE.n)\n * @param isLE interpret hash bytes as LE num\n * @returns valid private scalar\n */\nexport function mapHashToField(key: Uint8Array, fieldOrder: bigint, isLE = false): Uint8Array {\n const len = key.length;\n const fieldLen = getFieldBytesLength(fieldOrder);\n const minLen = getMinHashLength(fieldOrder);\n // No small numbers: need to understand bias story. No huge numbers: easier to detect JS timings.\n if (len < 16 || len < minLen || len > 1024)\n throw new Error('expected ' + minLen + '-1024 bytes of input, got ' + len);\n const num = isLE ? bytesToNumberLE(key) : bytesToNumberBE(key);\n // `mod(x, 11)` can sometimes produce 0. `mod(x, 10) + 1` is the same, but no 0\n const reduced = mod(num, fieldOrder - _1n) + _1n;\n return isLE ? numberToBytesLE(reduced, fieldLen) : numberToBytesBE(reduced, fieldLen);\n}\n", "/**\n * Methods for elliptic curve multiplication by scalars.\n * Contains wNAF, pippenger.\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { bitLen, bitMask, validateObject } from '../utils.ts';\nimport { Field, FpInvertBatch, nLength, validateField, type IField } from './modular.ts';\n\nconst _0n = BigInt(0);\nconst _1n = BigInt(1);\n\nexport type AffinePoint = {\n x: T;\n y: T;\n} & { Z?: never };\n\n// This was initialy do this way to re-use montgomery ladder in field (add->mul,double->sqr), but\n// that didn't happen and there is probably not much reason to have separate Group like this?\nexport interface Group> {\n double(): T;\n negate(): T;\n add(other: T): T;\n subtract(other: T): T;\n equals(other: T): boolean;\n multiply(scalar: bigint): T;\n toAffine?(invertedZ?: any): AffinePoint;\n}\n\n// We can't \"abstract out\" coordinates (X, Y, Z; and T in Edwards): argument names of constructor\n// are not accessible. See Typescript gh-56093, gh-41594.\n//\n// We have to use recursive types, so it will return actual point, not constained `CurvePoint`.\n// If, at any point, P is `any`, it will erase all types and replace it\n// with `any`, because of recursion, `any implements CurvePoint`,\n// but we lose all constrains on methods.\n\n/** Base interface for all elliptic curve Points. */\nexport interface CurvePoint> extends Group

{\n /** Affine x coordinate. Different from projective / extended X coordinate. */\n x: F;\n /** Affine y coordinate. Different from projective / extended Y coordinate. */\n y: F;\n Z?: F;\n double(): P;\n negate(): P;\n add(other: P): P;\n subtract(other: P): P;\n equals(other: P): boolean;\n multiply(scalar: bigint): P;\n assertValidity(): void;\n clearCofactor(): P;\n is0(): boolean;\n isTorsionFree(): boolean;\n isSmallOrder(): boolean;\n multiplyUnsafe(scalar: bigint): P;\n /**\n * Massively speeds up `p.multiply(n)` by using precompute tables (caching). See {@link wNAF}.\n * @param isLazy calculate cache now. Default (true) ensures it's deferred to first `multiply()`\n */\n precompute(windowSize?: number, isLazy?: boolean): P;\n /** Converts point to 2D xy affine coordinates */\n toAffine(invertedZ?: F): AffinePoint;\n toBytes(): Uint8Array;\n toHex(): string;\n}\n\n/** Base interface for all elliptic curve Point constructors. */\nexport interface CurvePointCons

> {\n [Symbol.hasInstance]: (item: unknown) => boolean;\n BASE: P;\n ZERO: P;\n /** Field for basic curve math */\n Fp: IField>;\n /** Scalar field, for scalars in multiply and others */\n Fn: IField;\n /** Creates point from x, y. Does NOT validate if the point is valid. Use `.assertValidity()`. */\n fromAffine(p: AffinePoint>): P;\n fromBytes(bytes: Uint8Array): P;\n fromHex(hex: Uint8Array | string): P;\n}\n\n// Type inference helpers: PC - PointConstructor, P - Point, Fp - Field element\n// Short names, because we use them a lot in result types:\n// * we can't do 'P = GetCurvePoint': this is default value and doesn't constrain anything\n// * we can't do 'type X = GetCurvePoint': it won't be accesible for arguments/return types\n// * `CurvePointCons

>` constraints from interface definition\n// won't propagate, if `PC extends CurvePointCons`: the P would be 'any', which is incorrect\n// * PC could be super specific with super specific P, which implements CurvePoint.\n// this means we need to do stuff like\n// `function test

, PC extends CurvePointCons

>(`\n// if we want type safety around P, otherwise PC_P will be any\n\n/** Returns Fp type from Point (P_F

== P.F) */\nexport type P_F

> = P extends CurvePoint ? F : never;\n/** Returns Fp type from PointCons (PC_F == PC.P.F) */\nexport type PC_F>> = PC['Fp']['ZERO'];\n/** Returns Point type from PointCons (PC_P == PC.P) */\nexport type PC_P>> = PC['ZERO'];\n\n// Ugly hack to get proper type inference, because in typescript fails to infer resursively.\n// The hack allows to do up to 10 chained operations without applying type erasure.\n//\n// Types which won't work:\n// * `CurvePointCons>`, will return `any` after 1 operation\n// * `CurvePointCons: WeierstrassPointCons extends CurvePointCons = false`\n// * `P extends CurvePoint, PC extends CurvePointCons

`\n// * It can't infer P from PC alone\n// * Too many relations between F, P & PC\n// * It will infer P/F if `arg: CurvePointCons`, but will fail if PC is generic\n// * It will work correctly if there is an additional argument of type P\n// * But generally, we don't want to parametrize `CurvePointCons` over `F`: it will complicate\n// types, making them un-inferable\n// prettier-ignore\nexport type PC_ANY = CurvePointCons<\n CurvePoint\n >>>>>>>>>\n>;\n\nexport interface CurveLengths {\n secretKey?: number;\n publicKey?: number;\n publicKeyUncompressed?: number;\n publicKeyHasPrefix?: boolean;\n signature?: number;\n seed?: number;\n}\nexport type GroupConstructor = {\n BASE: T;\n ZERO: T;\n};\n/** @deprecated */\nexport type ExtendedGroupConstructor = GroupConstructor & {\n Fp: IField;\n Fn: IField;\n fromAffine(ap: AffinePoint): T;\n};\nexport type Mapper = (i: T[]) => T[];\n\nexport function negateCt T }>(condition: boolean, item: T): T {\n const neg = item.negate();\n return condition ? neg : item;\n}\n\n/**\n * Takes a bunch of Projective Points but executes only one\n * inversion on all of them. Inversion is very slow operation,\n * so this improves performance massively.\n * Optimization: converts a list of projective points to a list of identical points with Z=1.\n */\nexport function normalizeZ

, PC extends CurvePointCons

>(\n c: PC,\n points: P[]\n): P[] {\n const invertedZs = FpInvertBatch(\n c.Fp,\n points.map((p) => p.Z!)\n );\n return points.map((p, i) => c.fromAffine(p.toAffine(invertedZs[i])));\n}\n\nfunction validateW(W: number, bits: number) {\n if (!Number.isSafeInteger(W) || W <= 0 || W > bits)\n throw new Error('invalid window size, expected [1..' + bits + '], got W=' + W);\n}\n\n/** Internal wNAF opts for specific W and scalarBits */\nexport type WOpts = {\n windows: number;\n windowSize: number;\n mask: bigint;\n maxNumber: number;\n shiftBy: bigint;\n};\n\nfunction calcWOpts(W: number, scalarBits: number): WOpts {\n validateW(W, scalarBits);\n const windows = Math.ceil(scalarBits / W) + 1; // W=8 33. Not 32, because we skip zero\n const windowSize = 2 ** (W - 1); // W=8 128. Not 256, because we skip zero\n const maxNumber = 2 ** W; // W=8 256\n const mask = bitMask(W); // W=8 255 == mask 0b11111111\n const shiftBy = BigInt(W); // W=8 8\n return { windows, windowSize, mask, maxNumber, shiftBy };\n}\n\nfunction calcOffsets(n: bigint, window: number, wOpts: WOpts) {\n const { windowSize, mask, maxNumber, shiftBy } = wOpts;\n let wbits = Number(n & mask); // extract W bits.\n let nextN = n >> shiftBy; // shift number by W bits.\n\n // What actually happens here:\n // const highestBit = Number(mask ^ (mask >> 1n));\n // let wbits2 = wbits - 1; // skip zero\n // if (wbits2 & highestBit) { wbits2 ^= Number(mask); // (~);\n\n // split if bits > max: +224 => 256-32\n if (wbits > windowSize) {\n // we skip zero, which means instead of `>= size-1`, we do `> size`\n wbits -= maxNumber; // -32, can be maxNumber - wbits, but then we need to set isNeg here.\n nextN += _1n; // +256 (carry)\n }\n const offsetStart = window * windowSize;\n const offset = offsetStart + Math.abs(wbits) - 1; // -1 because we skip zero\n const isZero = wbits === 0; // is current window slice a 0?\n const isNeg = wbits < 0; // is current window slice negative?\n const isNegF = window % 2 !== 0; // fake random statement for noise\n const offsetF = offsetStart; // fake offset for noise\n return { nextN, offset, isZero, isNeg, isNegF, offsetF };\n}\n\nfunction validateMSMPoints(points: any[], c: any) {\n if (!Array.isArray(points)) throw new Error('array expected');\n points.forEach((p, i) => {\n if (!(p instanceof c)) throw new Error('invalid point at index ' + i);\n });\n}\nfunction validateMSMScalars(scalars: any[], field: any) {\n if (!Array.isArray(scalars)) throw new Error('array of scalars expected');\n scalars.forEach((s, i) => {\n if (!field.isValid(s)) throw new Error('invalid scalar at index ' + i);\n });\n}\n\n// Since points in different groups cannot be equal (different object constructor),\n// we can have single place to store precomputes.\n// Allows to make points frozen / immutable.\nconst pointPrecomputes = new WeakMap();\nconst pointWindowSizes = new WeakMap();\n\nfunction getW(P: any): number {\n // To disable precomputes:\n // return 1;\n return pointWindowSizes.get(P) || 1;\n}\n\nfunction assert0(n: bigint): void {\n if (n !== _0n) throw new Error('invalid wNAF');\n}\n\n/**\n * Elliptic curve multiplication of Point by scalar. Fragile.\n * Table generation takes **30MB of ram and 10ms on high-end CPU**,\n * but may take much longer on slow devices. Actual generation will happen on\n * first call of `multiply()`. By default, `BASE` point is precomputed.\n *\n * Scalars should always be less than curve order: this should be checked inside of a curve itself.\n * Creates precomputation tables for fast multiplication:\n * - private scalar is split by fixed size windows of W bits\n * - every window point is collected from window's table & added to accumulator\n * - since windows are different, same point inside tables won't be accessed more than once per calc\n * - each multiplication is 'Math.ceil(CURVE_ORDER / 𝑊) + 1' point additions (fixed for any scalar)\n * - +1 window is neccessary for wNAF\n * - wNAF reduces table size: 2x less memory + 2x faster generation, but 10% slower multiplication\n *\n * @todo Research returning 2d JS array of windows, instead of a single window.\n * This would allow windows to be in different memory locations\n */\nexport class wNAF {\n private readonly BASE: PC_P;\n private readonly ZERO: PC_P;\n private readonly Fn: PC['Fn'];\n readonly bits: number;\n\n // Parametrized with a given Point class (not individual point)\n constructor(Point: PC, bits: number) {\n this.BASE = Point.BASE;\n this.ZERO = Point.ZERO;\n this.Fn = Point.Fn;\n this.bits = bits;\n }\n\n // non-const time multiplication ladder\n _unsafeLadder(elm: PC_P, n: bigint, p: PC_P = this.ZERO): PC_P {\n let d: PC_P = elm;\n while (n > _0n) {\n if (n & _1n) p = p.add(d);\n d = d.double();\n n >>= _1n;\n }\n return p;\n }\n\n /**\n * Creates a wNAF precomputation window. Used for caching.\n * Default window size is set by `utils.precompute()` and is equal to 8.\n * Number of precomputed points depends on the curve size:\n * 2^(𝑊−1) * (Math.ceil(𝑛 / 𝑊) + 1), where:\n * - 𝑊 is the window size\n * - 𝑛 is the bitlength of the curve order.\n * For a 256-bit curve and window size 8, the number of precomputed points is 128 * 33 = 4224.\n * @param point Point instance\n * @param W window size\n * @returns precomputed point tables flattened to a single array\n */\n private precomputeWindow(point: PC_P, W: number): PC_P[] {\n const { windows, windowSize } = calcWOpts(W, this.bits);\n const points: PC_P[] = [];\n let p: PC_P = point;\n let base = p;\n for (let window = 0; window < windows; window++) {\n base = p;\n points.push(base);\n // i=1, bc we skip 0\n for (let i = 1; i < windowSize; i++) {\n base = base.add(p);\n points.push(base);\n }\n p = base.double();\n }\n return points;\n }\n\n /**\n * Implements ec multiplication using precomputed tables and w-ary non-adjacent form.\n * More compact implementation:\n * https://github.com/paulmillr/noble-secp256k1/blob/47cb1669b6e506ad66b35fe7d76132ae97465da2/index.ts#L502-L541\n * @returns real and fake (for const-time) points\n */\n private wNAF(W: number, precomputes: PC_P[], n: bigint): { p: PC_P; f: PC_P } {\n // Scalar should be smaller than field order\n if (!this.Fn.isValid(n)) throw new Error('invalid scalar');\n // Accumulators\n let p = this.ZERO;\n let f = this.BASE;\n // This code was first written with assumption that 'f' and 'p' will never be infinity point:\n // since each addition is multiplied by 2 ** W, it cannot cancel each other. However,\n // there is negate now: it is possible that negated element from low value\n // would be the same as high element, which will create carry into next window.\n // It's not obvious how this can fail, but still worth investigating later.\n const wo = calcWOpts(W, this.bits);\n for (let window = 0; window < wo.windows; window++) {\n // (n === _0n) is handled and not early-exited. isEven and offsetF are used for noise\n const { nextN, offset, isZero, isNeg, isNegF, offsetF } = calcOffsets(n, window, wo);\n n = nextN;\n if (isZero) {\n // bits are 0: add garbage to fake point\n // Important part for const-time getPublicKey: add random \"noise\" point to f.\n f = f.add(negateCt(isNegF, precomputes[offsetF]));\n } else {\n // bits are 1: add to result point\n p = p.add(negateCt(isNeg, precomputes[offset]));\n }\n }\n assert0(n);\n // Return both real and fake points: JIT won't eliminate f.\n // At this point there is a way to F be infinity-point even if p is not,\n // which makes it less const-time: around 1 bigint multiply.\n return { p, f };\n }\n\n /**\n * Implements ec unsafe (non const-time) multiplication using precomputed tables and w-ary non-adjacent form.\n * @param acc accumulator point to add result of multiplication\n * @returns point\n */\n private wNAFUnsafe(\n W: number,\n precomputes: PC_P[],\n n: bigint,\n acc: PC_P = this.ZERO\n ): PC_P {\n const wo = calcWOpts(W, this.bits);\n for (let window = 0; window < wo.windows; window++) {\n if (n === _0n) break; // Early-exit, skip 0 value\n const { nextN, offset, isZero, isNeg } = calcOffsets(n, window, wo);\n n = nextN;\n if (isZero) {\n // Window bits are 0: skip processing.\n // Move to next window.\n continue;\n } else {\n const item = precomputes[offset];\n acc = acc.add(isNeg ? item.negate() : item); // Re-using acc allows to save adds in MSM\n }\n }\n assert0(n);\n return acc;\n }\n\n private getPrecomputes(W: number, point: PC_P, transform?: Mapper>): PC_P[] {\n // Calculate precomputes on a first run, reuse them after\n let comp = pointPrecomputes.get(point);\n if (!comp) {\n comp = this.precomputeWindow(point, W) as PC_P[];\n if (W !== 1) {\n // Doing transform outside of if brings 15% perf hit\n if (typeof transform === 'function') comp = transform(comp);\n pointPrecomputes.set(point, comp);\n }\n }\n return comp;\n }\n\n cached(\n point: PC_P,\n scalar: bigint,\n transform?: Mapper>\n ): { p: PC_P; f: PC_P } {\n const W = getW(point);\n return this.wNAF(W, this.getPrecomputes(W, point, transform), scalar);\n }\n\n unsafe(point: PC_P, scalar: bigint, transform?: Mapper>, prev?: PC_P): PC_P {\n const W = getW(point);\n if (W === 1) return this._unsafeLadder(point, scalar, prev); // For W=1 ladder is ~x2 faster\n return this.wNAFUnsafe(W, this.getPrecomputes(W, point, transform), scalar, prev);\n }\n\n // We calculate precomputes for elliptic curve point multiplication\n // using windowed method. This specifies window size and\n // stores precomputed values. Usually only base point would be precomputed.\n createCache(P: PC_P, W: number): void {\n validateW(W, this.bits);\n pointWindowSizes.set(P, W);\n pointPrecomputes.delete(P);\n }\n\n hasCache(elm: PC_P): boolean {\n return getW(elm) !== 1;\n }\n}\n\n/**\n * Endomorphism-specific multiplication for Koblitz curves.\n * Cost: 128 dbl, 0-256 adds.\n */\nexport function mulEndoUnsafe

, PC extends CurvePointCons

>(\n Point: PC,\n point: P,\n k1: bigint,\n k2: bigint\n): { p1: P; p2: P } {\n let acc = point;\n let p1 = Point.ZERO;\n let p2 = Point.ZERO;\n while (k1 > _0n || k2 > _0n) {\n if (k1 & _1n) p1 = p1.add(acc);\n if (k2 & _1n) p2 = p2.add(acc);\n acc = acc.double();\n k1 >>= _1n;\n k2 >>= _1n;\n }\n return { p1, p2 };\n}\n\n/**\n * Pippenger algorithm for multi-scalar multiplication (MSM, Pa + Qb + Rc + ...).\n * 30x faster vs naive addition on L=4096, 10x faster than precomputes.\n * For N=254bit, L=1, it does: 1024 ADD + 254 DBL. For L=5: 1536 ADD + 254 DBL.\n * Algorithmically constant-time (for same L), even when 1 point + scalar, or when scalar = 0.\n * @param c Curve Point constructor\n * @param fieldN field over CURVE.N - important that it's not over CURVE.P\n * @param points array of L curve points\n * @param scalars array of L scalars (aka secret keys / bigints)\n */\nexport function pippenger

, PC extends CurvePointCons

>(\n c: PC,\n fieldN: IField,\n points: P[],\n scalars: bigint[]\n): P {\n // If we split scalars by some window (let's say 8 bits), every chunk will only\n // take 256 buckets even if there are 4096 scalars, also re-uses double.\n // TODO:\n // - https://eprint.iacr.org/2024/750.pdf\n // - https://tches.iacr.org/index.php/TCHES/article/view/10287\n // 0 is accepted in scalars\n validateMSMPoints(points, c);\n validateMSMScalars(scalars, fieldN);\n const plength = points.length;\n const slength = scalars.length;\n if (plength !== slength) throw new Error('arrays of points and scalars must have equal length');\n // if (plength === 0) throw new Error('array must be of length >= 2');\n const zero = c.ZERO;\n const wbits = bitLen(BigInt(plength));\n let windowSize = 1; // bits\n if (wbits > 12) windowSize = wbits - 3;\n else if (wbits > 4) windowSize = wbits - 2;\n else if (wbits > 0) windowSize = 2;\n const MASK = bitMask(windowSize);\n const buckets = new Array(Number(MASK) + 1).fill(zero); // +1 for zero array\n const lastBits = Math.floor((fieldN.BITS - 1) / windowSize) * windowSize;\n let sum = zero;\n for (let i = lastBits; i >= 0; i -= windowSize) {\n buckets.fill(zero);\n for (let j = 0; j < slength; j++) {\n const scalar = scalars[j];\n const wbits = Number((scalar >> BigInt(i)) & MASK);\n buckets[wbits] = buckets[wbits].add(points[j]);\n }\n let resI = zero; // not using this will do small speed-up, but will lose ct\n // Skip first bucket, because it is zero\n for (let j = buckets.length - 1, sumI = zero; j > 0; j--) {\n sumI = sumI.add(buckets[j]);\n resI = resI.add(sumI);\n }\n sum = sum.add(resI);\n if (i !== 0) for (let j = 0; j < windowSize; j++) sum = sum.double();\n }\n return sum as P;\n}\n/**\n * Precomputed multi-scalar multiplication (MSM, Pa + Qb + Rc + ...).\n * @param c Curve Point constructor\n * @param fieldN field over CURVE.N - important that it's not over CURVE.P\n * @param points array of L curve points\n * @returns function which multiplies points with scaars\n */\nexport function precomputeMSMUnsafe

, PC extends CurvePointCons

>(\n c: PC,\n fieldN: IField,\n points: P[],\n windowSize: number\n): (scalars: bigint[]) => P {\n /**\n * Performance Analysis of Window-based Precomputation\n *\n * Base Case (256-bit scalar, 8-bit window):\n * - Standard precomputation requires:\n * - 31 additions per scalar × 256 scalars = 7,936 ops\n * - Plus 255 summary additions = 8,191 total ops\n * Note: Summary additions can be optimized via accumulator\n *\n * Chunked Precomputation Analysis:\n * - Using 32 chunks requires:\n * - 255 additions per chunk\n * - 256 doublings\n * - Total: (255 × 32) + 256 = 8,416 ops\n *\n * Memory Usage Comparison:\n * Window Size | Standard Points | Chunked Points\n * ------------|-----------------|---------------\n * 4-bit | 520 | 15\n * 8-bit | 4,224 | 255\n * 10-bit | 13,824 | 1,023\n * 16-bit | 557,056 | 65,535\n *\n * Key Advantages:\n * 1. Enables larger window sizes due to reduced memory overhead\n * 2. More efficient for smaller scalar counts:\n * - 16 chunks: (16 × 255) + 256 = 4,336 ops\n * - ~2x faster than standard 8,191 ops\n *\n * Limitations:\n * - Not suitable for plain precomputes (requires 256 constant doublings)\n * - Performance degrades with larger scalar counts:\n * - Optimal for ~256 scalars\n * - Less efficient for 4096+ scalars (Pippenger preferred)\n */\n validateW(windowSize, fieldN.BITS);\n validateMSMPoints(points, c);\n const zero = c.ZERO;\n const tableSize = 2 ** windowSize - 1; // table size (without zero)\n const chunks = Math.ceil(fieldN.BITS / windowSize); // chunks of item\n const MASK = bitMask(windowSize);\n const tables = points.map((p: P) => {\n const res = [];\n for (let i = 0, acc = p; i < tableSize; i++) {\n res.push(acc);\n acc = acc.add(p);\n }\n return res;\n });\n return (scalars: bigint[]): P => {\n validateMSMScalars(scalars, fieldN);\n if (scalars.length > points.length)\n throw new Error('array of scalars must be smaller than array of points');\n let res = zero;\n for (let i = 0; i < chunks; i++) {\n // No need to double if accumulator is still zero.\n if (res !== zero) for (let j = 0; j < windowSize; j++) res = res.double();\n const shiftBy = BigInt(chunks * windowSize - (i + 1) * windowSize);\n for (let j = 0; j < scalars.length; j++) {\n const n = scalars[j];\n const curr = Number((n >> shiftBy) & MASK);\n if (!curr) continue; // skip zero scalars chunks\n res = res.add(tables[j][curr - 1]);\n }\n }\n return res;\n };\n}\n\n// TODO: remove\n/**\n * Generic BasicCurve interface: works even for polynomial fields (BLS): P, n, h would be ok.\n * Though generator can be different (Fp2 / Fp6 for BLS).\n */\nexport type BasicCurve = {\n Fp: IField; // Field over which we'll do calculations (Fp)\n n: bigint; // Curve order, total count of valid points in the field\n nBitLength?: number; // bit length of curve order\n nByteLength?: number; // byte length of curve order\n h: bigint; // cofactor. we can assign default=1, but users will just ignore it w/o validation\n hEff?: bigint; // Number to multiply to clear cofactor\n Gx: T; // base point X coordinate\n Gy: T; // base point Y coordinate\n allowInfinityPoint?: boolean; // bls12-381 requires it. ZERO point is valid, but invalid pubkey\n};\n\n// TODO: remove\n/** @deprecated */\nexport function validateBasic(\n curve: BasicCurve & T\n): Readonly<\n {\n readonly nBitLength: number;\n readonly nByteLength: number;\n } & BasicCurve &\n T & {\n p: bigint;\n }\n> {\n validateField(curve.Fp);\n validateObject(\n curve,\n {\n n: 'bigint',\n h: 'bigint',\n Gx: 'field',\n Gy: 'field',\n },\n {\n nBitLength: 'isSafeInteger',\n nByteLength: 'isSafeInteger',\n }\n );\n // Set defaults\n return Object.freeze({\n ...nLength(curve.n, curve.nBitLength),\n ...curve,\n ...{ p: curve.Fp.ORDER },\n } as const);\n}\n\nexport type ValidCurveParams = {\n p: bigint;\n n: bigint;\n h: bigint;\n a: T;\n b?: T;\n d?: T;\n Gx: T;\n Gy: T;\n};\n\nfunction createField(order: bigint, field?: IField, isLE?: boolean): IField {\n if (field) {\n if (field.ORDER !== order) throw new Error('Field.ORDER must match order: Fp == p, Fn == n');\n validateField(field);\n return field;\n } else {\n return Field(order, { isLE }) as unknown as IField;\n }\n}\nexport type FpFn = { Fp: IField; Fn: IField };\n\n/** Validates CURVE opts and creates fields */\nexport function _createCurveFields(\n type: 'weierstrass' | 'edwards',\n CURVE: ValidCurveParams,\n curveOpts: Partial> = {},\n FpFnLE?: boolean\n): FpFn & { CURVE: ValidCurveParams } {\n if (FpFnLE === undefined) FpFnLE = type === 'edwards';\n if (!CURVE || typeof CURVE !== 'object') throw new Error(`expected valid ${type} CURVE object`);\n for (const p of ['p', 'n', 'h'] as const) {\n const val = CURVE[p];\n if (!(typeof val === 'bigint' && val > _0n))\n throw new Error(`CURVE.${p} must be positive bigint`);\n }\n const Fp = createField(CURVE.p, curveOpts.Fp, FpFnLE);\n const Fn = createField(CURVE.n, curveOpts.Fn, FpFnLE);\n const _b: 'b' | 'd' = type === 'weierstrass' ? 'b' : 'd';\n const params = ['Gx', 'Gy', 'a', _b] as const;\n for (const p of params) {\n // @ts-ignore\n if (!Fp.isValid(CURVE[p]))\n throw new Error(`CURVE.${p} must be valid field element of CURVE.Fp`);\n }\n CURVE = Object.freeze(Object.assign({}, CURVE));\n return { CURVE, Fp, Fn };\n}\n", "/**\n * Short Weierstrass curve methods. The formula is: y² = x³ + ax + b.\n *\n * ### Design rationale for types\n *\n * * Interaction between classes from different curves should fail:\n * `k256.Point.BASE.add(p256.Point.BASE)`\n * * For this purpose we want to use `instanceof` operator, which is fast and works during runtime\n * * Different calls of `curve()` would return different classes -\n * `curve(params) !== curve(params)`: if somebody decided to monkey-patch their curve,\n * it won't affect others\n *\n * TypeScript can't infer types for classes created inside a function. Classes is one instance\n * of nominative types in TypeScript and interfaces only check for shape, so it's hard to create\n * unique type for every function call.\n *\n * We can use generic types via some param, like curve opts, but that would:\n * 1. Enable interaction between `curve(params)` and `curve(params)` (curves of same params)\n * which is hard to debug.\n * 2. Params can be generic and we can't enforce them to be constant value:\n * if somebody creates curve from non-constant params,\n * it would be allowed to interact with other curves with non-constant params\n *\n * @todo https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-7.html#unique-symbol\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { hmac as nobleHmac } from '@noble/hashes/hmac.js';\nimport { ahash } from '@noble/hashes/utils';\nimport {\n _validateObject,\n _abool2 as abool,\n _abytes2 as abytes,\n aInRange,\n bitLen,\n bitMask,\n bytesToHex,\n bytesToNumberBE,\n concatBytes,\n createHmacDrbg,\n ensureBytes,\n hexToBytes,\n inRange,\n isBytes,\n memoized,\n numberToHexUnpadded,\n randomBytes as randomBytesWeb,\n type CHash,\n type Hex,\n type PrivKey,\n} from '../utils.ts';\nimport {\n _createCurveFields,\n mulEndoUnsafe,\n negateCt,\n normalizeZ,\n pippenger,\n wNAF,\n type AffinePoint,\n type BasicCurve,\n type CurveLengths,\n type CurvePoint,\n type CurvePointCons,\n} from './curve.ts';\nimport {\n Field,\n FpInvertBatch,\n getMinHashLength,\n mapHashToField,\n nLength,\n validateField,\n type IField,\n type NLength,\n} from './modular.ts';\n\nexport type { AffinePoint };\nexport type HmacFnSync = (key: Uint8Array, ...messages: Uint8Array[]) => Uint8Array;\n\ntype EndoBasis = [[bigint, bigint], [bigint, bigint]];\n/**\n * When Weierstrass curve has `a=0`, it becomes Koblitz curve.\n * Koblitz curves allow using **efficiently-computable GLV endomorphism ψ**.\n * Endomorphism uses 2x less RAM, speeds up precomputation by 2x and ECDH / key recovery by 20%.\n * For precomputed wNAF it trades off 1/2 init time & 1/3 ram for 20% perf hit.\n *\n * Endomorphism consists of beta, lambda and splitScalar:\n *\n * 1. GLV endomorphism ψ transforms a point: `P = (x, y) ↦ ψ(P) = (β·x mod p, y)`\n * 2. GLV scalar decomposition transforms a scalar: `k ≡ k₁ + k₂·λ (mod n)`\n * 3. Then these are combined: `k·P = k₁·P + k₂·ψ(P)`\n * 4. Two 128-bit point-by-scalar multiplications + one point addition is faster than\n * one 256-bit multiplication.\n *\n * where\n * * beta: β ∈ Fₚ with β³ = 1, β ≠ 1\n * * lambda: λ ∈ Fₙ with λ³ = 1, λ ≠ 1\n * * splitScalar decomposes k ↦ k₁, k₂, by using reduced basis vectors.\n * Gauss lattice reduction calculates them from initial basis vectors `(n, 0), (-λ, 0)`\n *\n * Check out `test/misc/endomorphism.js` and\n * [gist](https://gist.github.com/paulmillr/eb670806793e84df628a7c434a873066).\n */\nexport type EndomorphismOpts = {\n beta: bigint;\n basises?: EndoBasis;\n splitScalar?: (k: bigint) => { k1neg: boolean; k1: bigint; k2neg: boolean; k2: bigint };\n};\n\n// We construct basis in such way that den is always positive and equals n, but num sign depends on basis (not on secret value)\nconst divNearest = (num: bigint, den: bigint) => (num + (num >= 0 ? den : -den) / _2n) / den;\n\nexport type ScalarEndoParts = { k1neg: boolean; k1: bigint; k2neg: boolean; k2: bigint };\n\n/**\n * Splits scalar for GLV endomorphism.\n */\nexport function _splitEndoScalar(k: bigint, basis: EndoBasis, n: bigint): ScalarEndoParts {\n // Split scalar into two such that part is ~half bits: `abs(part) < sqrt(N)`\n // Since part can be negative, we need to do this on point.\n // TODO: verifyScalar function which consumes lambda\n const [[a1, b1], [a2, b2]] = basis;\n const c1 = divNearest(b2 * k, n);\n const c2 = divNearest(-b1 * k, n);\n // |k1|/|k2| is < sqrt(N), but can be negative.\n // If we do `k1 mod N`, we'll get big scalar (`> sqrt(N)`): so, we do cheaper negation instead.\n let k1 = k - c1 * a1 - c2 * a2;\n let k2 = -c1 * b1 - c2 * b2;\n const k1neg = k1 < _0n;\n const k2neg = k2 < _0n;\n if (k1neg) k1 = -k1;\n if (k2neg) k2 = -k2;\n // Double check that resulting scalar less than half bits of N: otherwise wNAF will fail.\n // This should only happen on wrong basises. Also, math inside is too complex and I don't trust it.\n const MAX_NUM = bitMask(Math.ceil(bitLen(n) / 2)) + _1n; // Half bits of N\n if (k1 < _0n || k1 >= MAX_NUM || k2 < _0n || k2 >= MAX_NUM) {\n throw new Error('splitScalar (endomorphism): failed, k=' + k);\n }\n return { k1neg, k1, k2neg, k2 };\n}\n\nexport type ECDSASigFormat = 'compact' | 'recovered' | 'der';\nexport type ECDSARecoverOpts = {\n prehash?: boolean;\n};\nexport type ECDSAVerifyOpts = {\n prehash?: boolean;\n lowS?: boolean;\n format?: ECDSASigFormat;\n};\nexport type ECDSASignOpts = {\n prehash?: boolean;\n lowS?: boolean;\n format?: ECDSASigFormat;\n extraEntropy?: Uint8Array | boolean;\n};\n\nfunction validateSigFormat(format: string): ECDSASigFormat {\n if (!['compact', 'recovered', 'der'].includes(format))\n throw new Error('Signature format must be \"compact\", \"recovered\", or \"der\"');\n return format as ECDSASigFormat;\n}\n\nfunction validateSigOpts>(\n opts: T,\n def: D\n): Required {\n const optsn: ECDSASignOpts = {};\n for (let optName of Object.keys(def)) {\n // @ts-ignore\n optsn[optName] = opts[optName] === undefined ? def[optName] : opts[optName];\n }\n abool(optsn.lowS!, 'lowS');\n abool(optsn.prehash!, 'prehash');\n if (optsn.format !== undefined) validateSigFormat(optsn.format);\n return optsn as Required;\n}\n\n/** Instance methods for 3D XYZ projective points. */\nexport interface WeierstrassPoint extends CurvePoint> {\n /** projective X coordinate. Different from affine x. */\n readonly X: T;\n /** projective Y coordinate. Different from affine y. */\n readonly Y: T;\n /** projective z coordinate */\n readonly Z: T;\n /** affine x coordinate. Different from projective X. */\n get x(): T;\n /** affine y coordinate. Different from projective Y. */\n get y(): T;\n /** Encodes point using IEEE P1363 (DER) encoding. First byte is 2/3/4. Default = isCompressed. */\n toBytes(isCompressed?: boolean): Uint8Array;\n toHex(isCompressed?: boolean): string;\n\n /** @deprecated use `.X` */\n readonly px: T;\n /** @deprecated use `.Y` */\n readonly py: T;\n /** @deprecated use `.Z` */\n readonly pz: T;\n /** @deprecated use `toBytes` */\n toRawBytes(isCompressed?: boolean): Uint8Array;\n /** @deprecated use `multiplyUnsafe` */\n multiplyAndAddUnsafe(\n Q: WeierstrassPoint,\n a: bigint,\n b: bigint\n ): WeierstrassPoint | undefined;\n /** @deprecated use `p.y % 2n === 0n` */\n hasEvenY(): boolean;\n /** @deprecated use `p.precompute(windowSize)` */\n _setWindowSize(windowSize: number): void;\n}\n\n/** Static methods for 3D XYZ projective points. */\nexport interface WeierstrassPointCons extends CurvePointCons> {\n /** Does NOT validate if the point is valid. Use `.assertValidity()`. */\n new (X: T, Y: T, Z: T): WeierstrassPoint;\n CURVE(): WeierstrassOpts;\n /** @deprecated use `Point.BASE.multiply(Point.Fn.fromBytes(privateKey))` */\n fromPrivateKey(privateKey: PrivKey): WeierstrassPoint;\n /** @deprecated use `import { normalizeZ } from '@noble/curves/abstract/curve.js';` */\n normalizeZ(points: WeierstrassPoint[]): WeierstrassPoint[];\n /** @deprecated use `import { pippenger } from '@noble/curves/abstract/curve.js';` */\n msm(points: WeierstrassPoint[], scalars: bigint[]): WeierstrassPoint;\n}\n\n/**\n * Weierstrass curve options.\n *\n * * p: prime characteristic (order) of finite field, in which arithmetics is done\n * * n: order of prime subgroup a.k.a total amount of valid curve points\n * * h: cofactor, usually 1. h*n is group order; n is subgroup order\n * * a: formula param, must be in field of p\n * * b: formula param, must be in field of p\n * * Gx: x coordinate of generator point a.k.a. base point\n * * Gy: y coordinate of generator point\n */\nexport type WeierstrassOpts = Readonly<{\n p: bigint;\n n: bigint;\n h: bigint;\n a: T;\n b: T;\n Gx: T;\n Gy: T;\n}>;\n\n// When a cofactor != 1, there can be an effective methods to:\n// 1. Determine whether a point is torsion-free\n// 2. Clear torsion component\n// wrapPrivateKey: bls12-381 requires mod(n) instead of rejecting keys >= n\nexport type WeierstrassExtraOpts = Partial<{\n Fp: IField;\n Fn: IField;\n allowInfinityPoint: boolean;\n endo: EndomorphismOpts;\n isTorsionFree: (c: WeierstrassPointCons, point: WeierstrassPoint) => boolean;\n clearCofactor: (c: WeierstrassPointCons, point: WeierstrassPoint) => WeierstrassPoint;\n fromBytes: (bytes: Uint8Array) => AffinePoint;\n toBytes: (\n c: WeierstrassPointCons,\n point: WeierstrassPoint,\n isCompressed: boolean\n ) => Uint8Array;\n}>;\n\n/**\n * Options for ECDSA signatures over a Weierstrass curve.\n *\n * * lowS: (default: true) whether produced / verified signatures occupy low half of ecdsaOpts.p. Prevents malleability.\n * * hmac: (default: noble-hashes hmac) function, would be used to init hmac-drbg for k generation.\n * * randomBytes: (default: webcrypto os-level CSPRNG) custom method for fetching secure randomness.\n * * bits2int, bits2int_modN: used in sigs, sometimes overridden by curves\n */\nexport type ECDSAOpts = Partial<{\n lowS: boolean;\n hmac: HmacFnSync;\n randomBytes: (bytesLength?: number) => Uint8Array;\n bits2int: (bytes: Uint8Array) => bigint;\n bits2int_modN: (bytes: Uint8Array) => bigint;\n}>;\n\n/**\n * Elliptic Curve Diffie-Hellman interface.\n * Provides keygen, secret-to-public conversion, calculating shared secrets.\n */\nexport interface ECDH {\n keygen: (seed?: Uint8Array) => { secretKey: Uint8Array; publicKey: Uint8Array };\n getPublicKey: (secretKey: PrivKey, isCompressed?: boolean) => Uint8Array;\n getSharedSecret: (secretKeyA: PrivKey, publicKeyB: Hex, isCompressed?: boolean) => Uint8Array;\n Point: WeierstrassPointCons;\n utils: {\n isValidSecretKey: (secretKey: PrivKey) => boolean;\n isValidPublicKey: (publicKey: Uint8Array, isCompressed?: boolean) => boolean;\n randomSecretKey: (seed?: Uint8Array) => Uint8Array;\n /** @deprecated use `randomSecretKey` */\n randomPrivateKey: (seed?: Uint8Array) => Uint8Array;\n /** @deprecated use `isValidSecretKey` */\n isValidPrivateKey: (secretKey: PrivKey) => boolean;\n /** @deprecated use `Point.Fn.fromBytes()` */\n normPrivateKeyToScalar: (key: PrivKey) => bigint;\n /** @deprecated use `point.precompute()` */\n precompute: (windowSize?: number, point?: WeierstrassPoint) => WeierstrassPoint;\n };\n lengths: CurveLengths;\n}\n\n/**\n * ECDSA interface.\n * Only supported for prime fields, not Fp2 (extension fields).\n */\nexport interface ECDSA extends ECDH {\n sign: (message: Hex, secretKey: PrivKey, opts?: ECDSASignOpts) => ECDSASigRecovered;\n verify: (\n signature: Uint8Array,\n message: Uint8Array,\n publicKey: Uint8Array,\n opts?: ECDSAVerifyOpts\n ) => boolean;\n recoverPublicKey(signature: Uint8Array, message: Uint8Array, opts?: ECDSARecoverOpts): Uint8Array;\n Signature: ECDSASignatureCons;\n}\nexport class DERErr extends Error {\n constructor(m = '') {\n super(m);\n }\n}\nexport type IDER = {\n // asn.1 DER encoding utils\n Err: typeof DERErr;\n // Basic building block is TLV (Tag-Length-Value)\n _tlv: {\n encode: (tag: number, data: string) => string;\n // v - value, l - left bytes (unparsed)\n decode(tag: number, data: Uint8Array): { v: Uint8Array; l: Uint8Array };\n };\n // https://crypto.stackexchange.com/a/57734 Leftmost bit of first byte is 'negative' flag,\n // since we always use positive integers here. It must always be empty:\n // - add zero byte if exists\n // - if next byte doesn't have a flag, leading zero is not allowed (minimal encoding)\n _int: {\n encode(num: bigint): string;\n decode(data: Uint8Array): bigint;\n };\n toSig(hex: string | Uint8Array): { r: bigint; s: bigint };\n hexFromSig(sig: { r: bigint; s: bigint }): string;\n};\n/**\n * ASN.1 DER encoding utilities. ASN is very complex & fragile. Format:\n *\n * [0x30 (SEQUENCE), bytelength, 0x02 (INTEGER), intLength, R, 0x02 (INTEGER), intLength, S]\n *\n * Docs: https://letsencrypt.org/docs/a-warm-welcome-to-asn1-and-der/, https://luca.ntop.org/Teaching/Appunti/asn1.html\n */\nexport const DER: IDER = {\n // asn.1 DER encoding utils\n Err: DERErr,\n // Basic building block is TLV (Tag-Length-Value)\n _tlv: {\n encode: (tag: number, data: string): string => {\n const { Err: E } = DER;\n if (tag < 0 || tag > 256) throw new E('tlv.encode: wrong tag');\n if (data.length & 1) throw new E('tlv.encode: unpadded data');\n const dataLen = data.length / 2;\n const len = numberToHexUnpadded(dataLen);\n if ((len.length / 2) & 0b1000_0000) throw new E('tlv.encode: long form length too big');\n // length of length with long form flag\n const lenLen = dataLen > 127 ? numberToHexUnpadded((len.length / 2) | 0b1000_0000) : '';\n const t = numberToHexUnpadded(tag);\n return t + lenLen + len + data;\n },\n // v - value, l - left bytes (unparsed)\n decode(tag: number, data: Uint8Array): { v: Uint8Array; l: Uint8Array } {\n const { Err: E } = DER;\n let pos = 0;\n if (tag < 0 || tag > 256) throw new E('tlv.encode: wrong tag');\n if (data.length < 2 || data[pos++] !== tag) throw new E('tlv.decode: wrong tlv');\n const first = data[pos++];\n const isLong = !!(first & 0b1000_0000); // First bit of first length byte is flag for short/long form\n let length = 0;\n if (!isLong) length = first;\n else {\n // Long form: [longFlag(1bit), lengthLength(7bit), length (BE)]\n const lenLen = first & 0b0111_1111;\n if (!lenLen) throw new E('tlv.decode(long): indefinite length not supported');\n if (lenLen > 4) throw new E('tlv.decode(long): byte length is too big'); // this will overflow u32 in js\n const lengthBytes = data.subarray(pos, pos + lenLen);\n if (lengthBytes.length !== lenLen) throw new E('tlv.decode: length bytes not complete');\n if (lengthBytes[0] === 0) throw new E('tlv.decode(long): zero leftmost byte');\n for (const b of lengthBytes) length = (length << 8) | b;\n pos += lenLen;\n if (length < 128) throw new E('tlv.decode(long): not minimal encoding');\n }\n const v = data.subarray(pos, pos + length);\n if (v.length !== length) throw new E('tlv.decode: wrong value length');\n return { v, l: data.subarray(pos + length) };\n },\n },\n // https://crypto.stackexchange.com/a/57734 Leftmost bit of first byte is 'negative' flag,\n // since we always use positive integers here. It must always be empty:\n // - add zero byte if exists\n // - if next byte doesn't have a flag, leading zero is not allowed (minimal encoding)\n _int: {\n encode(num: bigint): string {\n const { Err: E } = DER;\n if (num < _0n) throw new E('integer: negative integers are not allowed');\n let hex = numberToHexUnpadded(num);\n // Pad with zero byte if negative flag is present\n if (Number.parseInt(hex[0], 16) & 0b1000) hex = '00' + hex;\n if (hex.length & 1) throw new E('unexpected DER parsing assertion: unpadded hex');\n return hex;\n },\n decode(data: Uint8Array): bigint {\n const { Err: E } = DER;\n if (data[0] & 0b1000_0000) throw new E('invalid signature integer: negative');\n if (data[0] === 0x00 && !(data[1] & 0b1000_0000))\n throw new E('invalid signature integer: unnecessary leading zero');\n return bytesToNumberBE(data);\n },\n },\n toSig(hex: string | Uint8Array): { r: bigint; s: bigint } {\n // parse DER signature\n const { Err: E, _int: int, _tlv: tlv } = DER;\n const data = ensureBytes('signature', hex);\n const { v: seqBytes, l: seqLeftBytes } = tlv.decode(0x30, data);\n if (seqLeftBytes.length) throw new E('invalid signature: left bytes after parsing');\n const { v: rBytes, l: rLeftBytes } = tlv.decode(0x02, seqBytes);\n const { v: sBytes, l: sLeftBytes } = tlv.decode(0x02, rLeftBytes);\n if (sLeftBytes.length) throw new E('invalid signature: left bytes after parsing');\n return { r: int.decode(rBytes), s: int.decode(sBytes) };\n },\n hexFromSig(sig: { r: bigint; s: bigint }): string {\n const { _tlv: tlv, _int: int } = DER;\n const rs = tlv.encode(0x02, int.encode(sig.r));\n const ss = tlv.encode(0x02, int.encode(sig.s));\n const seq = rs + ss;\n return tlv.encode(0x30, seq);\n },\n};\n\n// Be friendly to bad ECMAScript parsers by not using bigint literals\n// prettier-ignore\nconst _0n = BigInt(0), _1n = BigInt(1), _2n = BigInt(2), _3n = BigInt(3), _4n = BigInt(4);\n\nexport function _normFnElement(Fn: IField, key: PrivKey): bigint {\n const { BYTES: expected } = Fn;\n let num: bigint;\n if (typeof key === 'bigint') {\n num = key;\n } else {\n let bytes = ensureBytes('private key', key);\n try {\n num = Fn.fromBytes(bytes);\n } catch (error) {\n throw new Error(`invalid private key: expected ui8a of size ${expected}, got ${typeof key}`);\n }\n }\n if (!Fn.isValidNot0(num)) throw new Error('invalid private key: out of range [1..N-1]');\n return num;\n}\n\n/**\n * Creates weierstrass Point constructor, based on specified curve options.\n *\n * @example\n```js\nconst opts = {\n p: BigInt('0xffffffff00000001000000000000000000000000ffffffffffffffffffffffff'),\n n: BigInt('0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551'),\n h: BigInt(1),\n a: BigInt('0xffffffff00000001000000000000000000000000fffffffffffffffffffffffc'),\n b: BigInt('0x5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b'),\n Gx: BigInt('0x6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296'),\n Gy: BigInt('0x4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5'),\n};\nconst p256_Point = weierstrass(opts);\n```\n */\nexport function weierstrassN(\n params: WeierstrassOpts,\n extraOpts: WeierstrassExtraOpts = {}\n): WeierstrassPointCons {\n const validated = _createCurveFields('weierstrass', params, extraOpts);\n const { Fp, Fn } = validated;\n let CURVE = validated.CURVE as WeierstrassOpts;\n const { h: cofactor, n: CURVE_ORDER } = CURVE;\n _validateObject(\n extraOpts,\n {},\n {\n allowInfinityPoint: 'boolean',\n clearCofactor: 'function',\n isTorsionFree: 'function',\n fromBytes: 'function',\n toBytes: 'function',\n endo: 'object',\n wrapPrivateKey: 'boolean',\n }\n );\n\n const { endo } = extraOpts;\n if (endo) {\n // validateObject(endo, { beta: 'bigint', splitScalar: 'function' });\n if (!Fp.is0(CURVE.a) || typeof endo.beta !== 'bigint' || !Array.isArray(endo.basises)) {\n throw new Error('invalid endo: expected \"beta\": bigint and \"basises\": array');\n }\n }\n\n const lengths = getWLengths(Fp, Fn);\n\n function assertCompressionIsSupported() {\n if (!Fp.isOdd) throw new Error('compression is not supported: Field does not have .isOdd()');\n }\n\n // Implements IEEE P1363 point encoding\n function pointToBytes(\n _c: WeierstrassPointCons,\n point: WeierstrassPoint,\n isCompressed: boolean\n ): Uint8Array {\n const { x, y } = point.toAffine();\n const bx = Fp.toBytes(x);\n abool(isCompressed, 'isCompressed');\n if (isCompressed) {\n assertCompressionIsSupported();\n const hasEvenY = !Fp.isOdd!(y);\n return concatBytes(pprefix(hasEvenY), bx);\n } else {\n return concatBytes(Uint8Array.of(0x04), bx, Fp.toBytes(y));\n }\n }\n function pointFromBytes(bytes: Uint8Array) {\n abytes(bytes, undefined, 'Point');\n const { publicKey: comp, publicKeyUncompressed: uncomp } = lengths; // e.g. for 32-byte: 33, 65\n const length = bytes.length;\n const head = bytes[0];\n const tail = bytes.subarray(1);\n // No actual validation is done here: use .assertValidity()\n if (length === comp && (head === 0x02 || head === 0x03)) {\n const x = Fp.fromBytes(tail);\n if (!Fp.isValid(x)) throw new Error('bad point: is not on curve, wrong x');\n const y2 = weierstrassEquation(x); // y² = x³ + ax + b\n let y: T;\n try {\n y = Fp.sqrt(y2); // y = y² ^ (p+1)/4\n } catch (sqrtError) {\n const err = sqrtError instanceof Error ? ': ' + sqrtError.message : '';\n throw new Error('bad point: is not on curve, sqrt error' + err);\n }\n assertCompressionIsSupported();\n const isYOdd = Fp.isOdd!(y); // (y & _1n) === _1n;\n const isHeadOdd = (head & 1) === 1; // ECDSA-specific\n if (isHeadOdd !== isYOdd) y = Fp.neg(y);\n return { x, y };\n } else if (length === uncomp && head === 0x04) {\n // TODO: more checks\n const L = Fp.BYTES;\n const x = Fp.fromBytes(tail.subarray(0, L));\n const y = Fp.fromBytes(tail.subarray(L, L * 2));\n if (!isValidXY(x, y)) throw new Error('bad point: is not on curve');\n return { x, y };\n } else {\n throw new Error(\n `bad point: got length ${length}, expected compressed=${comp} or uncompressed=${uncomp}`\n );\n }\n }\n\n const encodePoint = extraOpts.toBytes || pointToBytes;\n const decodePoint = extraOpts.fromBytes || pointFromBytes;\n function weierstrassEquation(x: T): T {\n const x2 = Fp.sqr(x); // x * x\n const x3 = Fp.mul(x2, x); // x² * x\n return Fp.add(Fp.add(x3, Fp.mul(x, CURVE.a)), CURVE.b); // x³ + a * x + b\n }\n\n // TODO: move top-level\n /** Checks whether equation holds for given x, y: y² == x³ + ax + b */\n function isValidXY(x: T, y: T): boolean {\n const left = Fp.sqr(y); // y²\n const right = weierstrassEquation(x); // x³ + ax + b\n return Fp.eql(left, right);\n }\n\n // Validate whether the passed curve params are valid.\n // Test 1: equation y² = x³ + ax + b should work for generator point.\n if (!isValidXY(CURVE.Gx, CURVE.Gy)) throw new Error('bad curve params: generator point');\n\n // Test 2: discriminant Δ part should be non-zero: 4a³ + 27b² != 0.\n // Guarantees curve is genus-1, smooth (non-singular).\n const _4a3 = Fp.mul(Fp.pow(CURVE.a, _3n), _4n);\n const _27b2 = Fp.mul(Fp.sqr(CURVE.b), BigInt(27));\n if (Fp.is0(Fp.add(_4a3, _27b2))) throw new Error('bad curve params: a or b');\n\n /** Asserts coordinate is valid: 0 <= n < Fp.ORDER. */\n function acoord(title: string, n: T, banZero = false) {\n if (!Fp.isValid(n) || (banZero && Fp.is0(n))) throw new Error(`bad point coordinate ${title}`);\n return n;\n }\n\n function aprjpoint(other: unknown) {\n if (!(other instanceof Point)) throw new Error('ProjectivePoint expected');\n }\n\n function splitEndoScalarN(k: bigint) {\n if (!endo || !endo.basises) throw new Error('no endo');\n return _splitEndoScalar(k, endo.basises, Fn.ORDER);\n }\n\n // Memoized toAffine / validity check. They are heavy. Points are immutable.\n\n // Converts Projective point to affine (x, y) coordinates.\n // Can accept precomputed Z^-1 - for example, from invertBatch.\n // (X, Y, Z) ∋ (x=X/Z, y=Y/Z)\n const toAffineMemo = memoized((p: Point, iz?: T): AffinePoint => {\n const { X, Y, Z } = p;\n // Fast-path for normalized points\n if (Fp.eql(Z, Fp.ONE)) return { x: X, y: Y };\n const is0 = p.is0();\n // If invZ was 0, we return zero point. However we still want to execute\n // all operations, so we replace invZ with a random number, 1.\n if (iz == null) iz = is0 ? Fp.ONE : Fp.inv(Z);\n const x = Fp.mul(X, iz);\n const y = Fp.mul(Y, iz);\n const zz = Fp.mul(Z, iz);\n if (is0) return { x: Fp.ZERO, y: Fp.ZERO };\n if (!Fp.eql(zz, Fp.ONE)) throw new Error('invZ was invalid');\n return { x, y };\n });\n // NOTE: on exception this will crash 'cached' and no value will be set.\n // Otherwise true will be return\n const assertValidMemo = memoized((p: Point) => {\n if (p.is0()) {\n // (0, 1, 0) aka ZERO is invalid in most contexts.\n // In BLS, ZERO can be serialized, so we allow it.\n // (0, 0, 0) is invalid representation of ZERO.\n if (extraOpts.allowInfinityPoint && !Fp.is0(p.Y)) return;\n throw new Error('bad point: ZERO');\n }\n // Some 3rd-party test vectors require different wording between here & `fromCompressedHex`\n const { x, y } = p.toAffine();\n if (!Fp.isValid(x) || !Fp.isValid(y)) throw new Error('bad point: x or y not field elements');\n if (!isValidXY(x, y)) throw new Error('bad point: equation left != right');\n if (!p.isTorsionFree()) throw new Error('bad point: not in prime-order subgroup');\n return true;\n });\n\n function finishEndo(\n endoBeta: EndomorphismOpts['beta'],\n k1p: Point,\n k2p: Point,\n k1neg: boolean,\n k2neg: boolean\n ) {\n k2p = new Point(Fp.mul(k2p.X, endoBeta), k2p.Y, k2p.Z);\n k1p = negateCt(k1neg, k1p);\n k2p = negateCt(k2neg, k2p);\n return k1p.add(k2p);\n }\n\n /**\n * Projective Point works in 3d / projective (homogeneous) coordinates:(X, Y, Z) ∋ (x=X/Z, y=Y/Z).\n * Default Point works in 2d / affine coordinates: (x, y).\n * We're doing calculations in projective, because its operations don't require costly inversion.\n */\n class Point implements WeierstrassPoint {\n // base / generator point\n static readonly BASE = new Point(CURVE.Gx, CURVE.Gy, Fp.ONE);\n // zero / infinity / identity point\n static readonly ZERO = new Point(Fp.ZERO, Fp.ONE, Fp.ZERO); // 0, 1, 0\n // math field\n static readonly Fp = Fp;\n // scalar field\n static readonly Fn = Fn;\n\n readonly X: T;\n readonly Y: T;\n readonly Z: T;\n\n /** Does NOT validate if the point is valid. Use `.assertValidity()`. */\n constructor(X: T, Y: T, Z: T) {\n this.X = acoord('x', X);\n this.Y = acoord('y', Y, true);\n this.Z = acoord('z', Z);\n Object.freeze(this);\n }\n\n static CURVE(): WeierstrassOpts {\n return CURVE;\n }\n\n /** Does NOT validate if the point is valid. Use `.assertValidity()`. */\n static fromAffine(p: AffinePoint): Point {\n const { x, y } = p || {};\n if (!p || !Fp.isValid(x) || !Fp.isValid(y)) throw new Error('invalid affine point');\n if (p instanceof Point) throw new Error('projective point not allowed');\n // (0, 0) would've produced (0, 0, 1) - instead, we need (0, 1, 0)\n if (Fp.is0(x) && Fp.is0(y)) return Point.ZERO;\n return new Point(x, y, Fp.ONE);\n }\n\n static fromBytes(bytes: Uint8Array): Point {\n const P = Point.fromAffine(decodePoint(abytes(bytes, undefined, 'point')));\n P.assertValidity();\n return P;\n }\n static fromHex(hex: Hex): Point {\n return Point.fromBytes(ensureBytes('pointHex', hex));\n }\n\n get x(): T {\n return this.toAffine().x;\n }\n get y(): T {\n return this.toAffine().y;\n }\n\n /**\n *\n * @param windowSize\n * @param isLazy true will defer table computation until the first multiplication\n * @returns\n */\n precompute(windowSize: number = 8, isLazy = true): Point {\n wnaf.createCache(this, windowSize);\n if (!isLazy) this.multiply(_3n); // random number\n return this;\n }\n\n // TODO: return `this`\n /** A point on curve is valid if it conforms to equation. */\n assertValidity(): void {\n assertValidMemo(this);\n }\n\n hasEvenY(): boolean {\n const { y } = this.toAffine();\n if (!Fp.isOdd) throw new Error(\"Field doesn't support isOdd\");\n return !Fp.isOdd(y);\n }\n\n /** Compare one point to another. */\n equals(other: Point): boolean {\n aprjpoint(other);\n const { X: X1, Y: Y1, Z: Z1 } = this;\n const { X: X2, Y: Y2, Z: Z2 } = other;\n const U1 = Fp.eql(Fp.mul(X1, Z2), Fp.mul(X2, Z1));\n const U2 = Fp.eql(Fp.mul(Y1, Z2), Fp.mul(Y2, Z1));\n return U1 && U2;\n }\n\n /** Flips point to one corresponding to (x, -y) in Affine coordinates. */\n negate(): Point {\n return new Point(this.X, Fp.neg(this.Y), this.Z);\n }\n\n // Renes-Costello-Batina exception-free doubling formula.\n // There is 30% faster Jacobian formula, but it is not complete.\n // https://eprint.iacr.org/2015/1060, algorithm 3\n // Cost: 8M + 3S + 3*a + 2*b3 + 15add.\n double() {\n const { a, b } = CURVE;\n const b3 = Fp.mul(b, _3n);\n const { X: X1, Y: Y1, Z: Z1 } = this;\n let X3 = Fp.ZERO, Y3 = Fp.ZERO, Z3 = Fp.ZERO; // prettier-ignore\n let t0 = Fp.mul(X1, X1); // step 1\n let t1 = Fp.mul(Y1, Y1);\n let t2 = Fp.mul(Z1, Z1);\n let t3 = Fp.mul(X1, Y1);\n t3 = Fp.add(t3, t3); // step 5\n Z3 = Fp.mul(X1, Z1);\n Z3 = Fp.add(Z3, Z3);\n X3 = Fp.mul(a, Z3);\n Y3 = Fp.mul(b3, t2);\n Y3 = Fp.add(X3, Y3); // step 10\n X3 = Fp.sub(t1, Y3);\n Y3 = Fp.add(t1, Y3);\n Y3 = Fp.mul(X3, Y3);\n X3 = Fp.mul(t3, X3);\n Z3 = Fp.mul(b3, Z3); // step 15\n t2 = Fp.mul(a, t2);\n t3 = Fp.sub(t0, t2);\n t3 = Fp.mul(a, t3);\n t3 = Fp.add(t3, Z3);\n Z3 = Fp.add(t0, t0); // step 20\n t0 = Fp.add(Z3, t0);\n t0 = Fp.add(t0, t2);\n t0 = Fp.mul(t0, t3);\n Y3 = Fp.add(Y3, t0);\n t2 = Fp.mul(Y1, Z1); // step 25\n t2 = Fp.add(t2, t2);\n t0 = Fp.mul(t2, t3);\n X3 = Fp.sub(X3, t0);\n Z3 = Fp.mul(t2, t1);\n Z3 = Fp.add(Z3, Z3); // step 30\n Z3 = Fp.add(Z3, Z3);\n return new Point(X3, Y3, Z3);\n }\n\n // Renes-Costello-Batina exception-free addition formula.\n // There is 30% faster Jacobian formula, but it is not complete.\n // https://eprint.iacr.org/2015/1060, algorithm 1\n // Cost: 12M + 0S + 3*a + 3*b3 + 23add.\n add(other: Point): Point {\n aprjpoint(other);\n const { X: X1, Y: Y1, Z: Z1 } = this;\n const { X: X2, Y: Y2, Z: Z2 } = other;\n let X3 = Fp.ZERO, Y3 = Fp.ZERO, Z3 = Fp.ZERO; // prettier-ignore\n const a = CURVE.a;\n const b3 = Fp.mul(CURVE.b, _3n);\n let t0 = Fp.mul(X1, X2); // step 1\n let t1 = Fp.mul(Y1, Y2);\n let t2 = Fp.mul(Z1, Z2);\n let t3 = Fp.add(X1, Y1);\n let t4 = Fp.add(X2, Y2); // step 5\n t3 = Fp.mul(t3, t4);\n t4 = Fp.add(t0, t1);\n t3 = Fp.sub(t3, t4);\n t4 = Fp.add(X1, Z1);\n let t5 = Fp.add(X2, Z2); // step 10\n t4 = Fp.mul(t4, t5);\n t5 = Fp.add(t0, t2);\n t4 = Fp.sub(t4, t5);\n t5 = Fp.add(Y1, Z1);\n X3 = Fp.add(Y2, Z2); // step 15\n t5 = Fp.mul(t5, X3);\n X3 = Fp.add(t1, t2);\n t5 = Fp.sub(t5, X3);\n Z3 = Fp.mul(a, t4);\n X3 = Fp.mul(b3, t2); // step 20\n Z3 = Fp.add(X3, Z3);\n X3 = Fp.sub(t1, Z3);\n Z3 = Fp.add(t1, Z3);\n Y3 = Fp.mul(X3, Z3);\n t1 = Fp.add(t0, t0); // step 25\n t1 = Fp.add(t1, t0);\n t2 = Fp.mul(a, t2);\n t4 = Fp.mul(b3, t4);\n t1 = Fp.add(t1, t2);\n t2 = Fp.sub(t0, t2); // step 30\n t2 = Fp.mul(a, t2);\n t4 = Fp.add(t4, t2);\n t0 = Fp.mul(t1, t4);\n Y3 = Fp.add(Y3, t0);\n t0 = Fp.mul(t5, t4); // step 35\n X3 = Fp.mul(t3, X3);\n X3 = Fp.sub(X3, t0);\n t0 = Fp.mul(t3, t1);\n Z3 = Fp.mul(t5, Z3);\n Z3 = Fp.add(Z3, t0); // step 40\n return new Point(X3, Y3, Z3);\n }\n\n subtract(other: Point) {\n return this.add(other.negate());\n }\n\n is0(): boolean {\n return this.equals(Point.ZERO);\n }\n\n /**\n * Constant time multiplication.\n * Uses wNAF method. Windowed method may be 10% faster,\n * but takes 2x longer to generate and consumes 2x memory.\n * Uses precomputes when available.\n * Uses endomorphism for Koblitz curves.\n * @param scalar by which the point would be multiplied\n * @returns New point\n */\n multiply(scalar: bigint): Point {\n const { endo } = extraOpts;\n if (!Fn.isValidNot0(scalar)) throw new Error('invalid scalar: out of range'); // 0 is invalid\n let point: Point, fake: Point; // Fake point is used to const-time mult\n const mul = (n: bigint) => wnaf.cached(this, n, (p) => normalizeZ(Point, p));\n /** See docs for {@link EndomorphismOpts} */\n if (endo) {\n const { k1neg, k1, k2neg, k2 } = splitEndoScalarN(scalar);\n const { p: k1p, f: k1f } = mul(k1);\n const { p: k2p, f: k2f } = mul(k2);\n fake = k1f.add(k2f);\n point = finishEndo(endo.beta, k1p, k2p, k1neg, k2neg);\n } else {\n const { p, f } = mul(scalar);\n point = p;\n fake = f;\n }\n // Normalize `z` for both points, but return only real one\n return normalizeZ(Point, [point, fake])[0];\n }\n\n /**\n * Non-constant-time multiplication. Uses double-and-add algorithm.\n * It's faster, but should only be used when you don't care about\n * an exposed secret key e.g. sig verification, which works over *public* keys.\n */\n multiplyUnsafe(sc: bigint): Point {\n const { endo } = extraOpts;\n const p = this as Point;\n if (!Fn.isValid(sc)) throw new Error('invalid scalar: out of range'); // 0 is valid\n if (sc === _0n || p.is0()) return Point.ZERO;\n if (sc === _1n) return p; // fast-path\n if (wnaf.hasCache(this)) return this.multiply(sc);\n if (endo) {\n const { k1neg, k1, k2neg, k2 } = splitEndoScalarN(sc);\n const { p1, p2 } = mulEndoUnsafe(Point, p, k1, k2); // 30% faster vs wnaf.unsafe\n return finishEndo(endo.beta, p1, p2, k1neg, k2neg);\n } else {\n return wnaf.unsafe(p, sc);\n }\n }\n\n multiplyAndAddUnsafe(Q: Point, a: bigint, b: bigint): Point | undefined {\n const sum = this.multiplyUnsafe(a).add(Q.multiplyUnsafe(b));\n return sum.is0() ? undefined : sum;\n }\n\n /**\n * Converts Projective point to affine (x, y) coordinates.\n * @param invertedZ Z^-1 (inverted zero) - optional, precomputation is useful for invertBatch\n */\n toAffine(invertedZ?: T): AffinePoint {\n return toAffineMemo(this, invertedZ);\n }\n\n /**\n * Checks whether Point is free of torsion elements (is in prime subgroup).\n * Always torsion-free for cofactor=1 curves.\n */\n isTorsionFree(): boolean {\n const { isTorsionFree } = extraOpts;\n if (cofactor === _1n) return true;\n if (isTorsionFree) return isTorsionFree(Point, this);\n return wnaf.unsafe(this, CURVE_ORDER).is0();\n }\n\n clearCofactor(): Point {\n const { clearCofactor } = extraOpts;\n if (cofactor === _1n) return this; // Fast-path\n if (clearCofactor) return clearCofactor(Point, this) as Point;\n return this.multiplyUnsafe(cofactor);\n }\n\n isSmallOrder(): boolean {\n // can we use this.clearCofactor()?\n return this.multiplyUnsafe(cofactor).is0();\n }\n\n toBytes(isCompressed = true): Uint8Array {\n abool(isCompressed, 'isCompressed');\n this.assertValidity();\n return encodePoint(Point, this, isCompressed);\n }\n\n toHex(isCompressed = true): string {\n return bytesToHex(this.toBytes(isCompressed));\n }\n\n toString() {\n return ``;\n }\n\n // TODO: remove\n get px(): T {\n return this.X;\n }\n get py(): T {\n return this.X;\n }\n get pz(): T {\n return this.Z;\n }\n toRawBytes(isCompressed = true): Uint8Array {\n return this.toBytes(isCompressed);\n }\n _setWindowSize(windowSize: number) {\n this.precompute(windowSize);\n }\n static normalizeZ(points: Point[]): Point[] {\n return normalizeZ(Point, points);\n }\n static msm(points: Point[], scalars: bigint[]): Point {\n return pippenger(Point, Fn, points, scalars);\n }\n static fromPrivateKey(privateKey: PrivKey) {\n return Point.BASE.multiply(_normFnElement(Fn, privateKey));\n }\n }\n const bits = Fn.BITS;\n const wnaf = new wNAF(Point, extraOpts.endo ? Math.ceil(bits / 2) : bits);\n Point.BASE.precompute(8); // Enable precomputes. Slows down first publicKey computation by 20ms.\n return Point;\n}\n\n/** Methods of ECDSA signature instance. */\nexport interface ECDSASignature {\n readonly r: bigint;\n readonly s: bigint;\n readonly recovery?: number;\n addRecoveryBit(recovery: number): ECDSASigRecovered;\n hasHighS(): boolean;\n toBytes(format?: string): Uint8Array;\n toHex(format?: string): string;\n\n /** @deprecated */\n assertValidity(): void;\n /** @deprecated */\n normalizeS(): ECDSASignature;\n /** @deprecated use standalone method `curve.recoverPublicKey(sig.toBytes('recovered'), msg)` */\n recoverPublicKey(msgHash: Hex): WeierstrassPoint;\n /** @deprecated use `.toBytes('compact')` */\n toCompactRawBytes(): Uint8Array;\n /** @deprecated use `.toBytes('compact')` */\n toCompactHex(): string;\n /** @deprecated use `.toBytes('der')` */\n toDERRawBytes(): Uint8Array;\n /** @deprecated use `.toBytes('der')` */\n toDERHex(): string;\n}\nexport type ECDSASigRecovered = ECDSASignature & {\n readonly recovery: number;\n};\n/** Methods of ECDSA signature constructor. */\nexport type ECDSASignatureCons = {\n new (r: bigint, s: bigint, recovery?: number): ECDSASignature;\n fromBytes(bytes: Uint8Array, format?: ECDSASigFormat): ECDSASignature;\n fromHex(hex: string, format?: ECDSASigFormat): ECDSASignature;\n\n /** @deprecated use `.fromBytes(bytes, 'compact')` */\n fromCompact(hex: Hex): ECDSASignature;\n /** @deprecated use `.fromBytes(bytes, 'der')` */\n fromDER(hex: Hex): ECDSASignature;\n};\n\n// Points start with byte 0x02 when y is even; otherwise 0x03\nfunction pprefix(hasEvenY: boolean): Uint8Array {\n return Uint8Array.of(hasEvenY ? 0x02 : 0x03);\n}\n\n/**\n * Implementation of the Shallue and van de Woestijne method for any weierstrass curve.\n * TODO: check if there is a way to merge this with uvRatio in Edwards; move to modular.\n * b = True and y = sqrt(u / v) if (u / v) is square in F, and\n * b = False and y = sqrt(Z * (u / v)) otherwise.\n * @param Fp\n * @param Z\n * @returns\n */\nexport function SWUFpSqrtRatio(\n Fp: IField,\n Z: T\n): (u: T, v: T) => { isValid: boolean; value: T } {\n // Generic implementation\n const q = Fp.ORDER;\n let l = _0n;\n for (let o = q - _1n; o % _2n === _0n; o /= _2n) l += _1n;\n const c1 = l; // 1. c1, the largest integer such that 2^c1 divides q - 1.\n // We need 2n ** c1 and 2n ** (c1-1). We can't use **; but we can use <<.\n // 2n ** c1 == 2n << (c1-1)\n const _2n_pow_c1_1 = _2n << (c1 - _1n - _1n);\n const _2n_pow_c1 = _2n_pow_c1_1 * _2n;\n const c2 = (q - _1n) / _2n_pow_c1; // 2. c2 = (q - 1) / (2^c1) # Integer arithmetic\n const c3 = (c2 - _1n) / _2n; // 3. c3 = (c2 - 1) / 2 # Integer arithmetic\n const c4 = _2n_pow_c1 - _1n; // 4. c4 = 2^c1 - 1 # Integer arithmetic\n const c5 = _2n_pow_c1_1; // 5. c5 = 2^(c1 - 1) # Integer arithmetic\n const c6 = Fp.pow(Z, c2); // 6. c6 = Z^c2\n const c7 = Fp.pow(Z, (c2 + _1n) / _2n); // 7. c7 = Z^((c2 + 1) / 2)\n let sqrtRatio = (u: T, v: T): { isValid: boolean; value: T } => {\n let tv1 = c6; // 1. tv1 = c6\n let tv2 = Fp.pow(v, c4); // 2. tv2 = v^c4\n let tv3 = Fp.sqr(tv2); // 3. tv3 = tv2^2\n tv3 = Fp.mul(tv3, v); // 4. tv3 = tv3 * v\n let tv5 = Fp.mul(u, tv3); // 5. tv5 = u * tv3\n tv5 = Fp.pow(tv5, c3); // 6. tv5 = tv5^c3\n tv5 = Fp.mul(tv5, tv2); // 7. tv5 = tv5 * tv2\n tv2 = Fp.mul(tv5, v); // 8. tv2 = tv5 * v\n tv3 = Fp.mul(tv5, u); // 9. tv3 = tv5 * u\n let tv4 = Fp.mul(tv3, tv2); // 10. tv4 = tv3 * tv2\n tv5 = Fp.pow(tv4, c5); // 11. tv5 = tv4^c5\n let isQR = Fp.eql(tv5, Fp.ONE); // 12. isQR = tv5 == 1\n tv2 = Fp.mul(tv3, c7); // 13. tv2 = tv3 * c7\n tv5 = Fp.mul(tv4, tv1); // 14. tv5 = tv4 * tv1\n tv3 = Fp.cmov(tv2, tv3, isQR); // 15. tv3 = CMOV(tv2, tv3, isQR)\n tv4 = Fp.cmov(tv5, tv4, isQR); // 16. tv4 = CMOV(tv5, tv4, isQR)\n // 17. for i in (c1, c1 - 1, ..., 2):\n for (let i = c1; i > _1n; i--) {\n let tv5 = i - _2n; // 18. tv5 = i - 2\n tv5 = _2n << (tv5 - _1n); // 19. tv5 = 2^tv5\n let tvv5 = Fp.pow(tv4, tv5); // 20. tv5 = tv4^tv5\n const e1 = Fp.eql(tvv5, Fp.ONE); // 21. e1 = tv5 == 1\n tv2 = Fp.mul(tv3, tv1); // 22. tv2 = tv3 * tv1\n tv1 = Fp.mul(tv1, tv1); // 23. tv1 = tv1 * tv1\n tvv5 = Fp.mul(tv4, tv1); // 24. tv5 = tv4 * tv1\n tv3 = Fp.cmov(tv2, tv3, e1); // 25. tv3 = CMOV(tv2, tv3, e1)\n tv4 = Fp.cmov(tvv5, tv4, e1); // 26. tv4 = CMOV(tv5, tv4, e1)\n }\n return { isValid: isQR, value: tv3 };\n };\n if (Fp.ORDER % _4n === _3n) {\n // sqrt_ratio_3mod4(u, v)\n const c1 = (Fp.ORDER - _3n) / _4n; // 1. c1 = (q - 3) / 4 # Integer arithmetic\n const c2 = Fp.sqrt(Fp.neg(Z)); // 2. c2 = sqrt(-Z)\n sqrtRatio = (u: T, v: T) => {\n let tv1 = Fp.sqr(v); // 1. tv1 = v^2\n const tv2 = Fp.mul(u, v); // 2. tv2 = u * v\n tv1 = Fp.mul(tv1, tv2); // 3. tv1 = tv1 * tv2\n let y1 = Fp.pow(tv1, c1); // 4. y1 = tv1^c1\n y1 = Fp.mul(y1, tv2); // 5. y1 = y1 * tv2\n const y2 = Fp.mul(y1, c2); // 6. y2 = y1 * c2\n const tv3 = Fp.mul(Fp.sqr(y1), v); // 7. tv3 = y1^2; 8. tv3 = tv3 * v\n const isQR = Fp.eql(tv3, u); // 9. isQR = tv3 == u\n let y = Fp.cmov(y2, y1, isQR); // 10. y = CMOV(y2, y1, isQR)\n return { isValid: isQR, value: y }; // 11. return (isQR, y) isQR ? y : y*c2\n };\n }\n // No curves uses that\n // if (Fp.ORDER % _8n === _5n) // sqrt_ratio_5mod8\n return sqrtRatio;\n}\n/**\n * Simplified Shallue-van de Woestijne-Ulas Method\n * https://www.rfc-editor.org/rfc/rfc9380#section-6.6.2\n */\nexport function mapToCurveSimpleSWU(\n Fp: IField,\n opts: {\n A: T;\n B: T;\n Z: T;\n }\n): (u: T) => { x: T; y: T } {\n validateField(Fp);\n const { A, B, Z } = opts;\n if (!Fp.isValid(A) || !Fp.isValid(B) || !Fp.isValid(Z))\n throw new Error('mapToCurveSimpleSWU: invalid opts');\n const sqrtRatio = SWUFpSqrtRatio(Fp, Z);\n if (!Fp.isOdd) throw new Error('Field does not have .isOdd()');\n // Input: u, an element of F.\n // Output: (x, y), a point on E.\n return (u: T): { x: T; y: T } => {\n // prettier-ignore\n let tv1, tv2, tv3, tv4, tv5, tv6, x, y;\n tv1 = Fp.sqr(u); // 1. tv1 = u^2\n tv1 = Fp.mul(tv1, Z); // 2. tv1 = Z * tv1\n tv2 = Fp.sqr(tv1); // 3. tv2 = tv1^2\n tv2 = Fp.add(tv2, tv1); // 4. tv2 = tv2 + tv1\n tv3 = Fp.add(tv2, Fp.ONE); // 5. tv3 = tv2 + 1\n tv3 = Fp.mul(tv3, B); // 6. tv3 = B * tv3\n tv4 = Fp.cmov(Z, Fp.neg(tv2), !Fp.eql(tv2, Fp.ZERO)); // 7. tv4 = CMOV(Z, -tv2, tv2 != 0)\n tv4 = Fp.mul(tv4, A); // 8. tv4 = A * tv4\n tv2 = Fp.sqr(tv3); // 9. tv2 = tv3^2\n tv6 = Fp.sqr(tv4); // 10. tv6 = tv4^2\n tv5 = Fp.mul(tv6, A); // 11. tv5 = A * tv6\n tv2 = Fp.add(tv2, tv5); // 12. tv2 = tv2 + tv5\n tv2 = Fp.mul(tv2, tv3); // 13. tv2 = tv2 * tv3\n tv6 = Fp.mul(tv6, tv4); // 14. tv6 = tv6 * tv4\n tv5 = Fp.mul(tv6, B); // 15. tv5 = B * tv6\n tv2 = Fp.add(tv2, tv5); // 16. tv2 = tv2 + tv5\n x = Fp.mul(tv1, tv3); // 17. x = tv1 * tv3\n const { isValid, value } = sqrtRatio(tv2, tv6); // 18. (is_gx1_square, y1) = sqrt_ratio(tv2, tv6)\n y = Fp.mul(tv1, u); // 19. y = tv1 * u -> Z * u^3 * y1\n y = Fp.mul(y, value); // 20. y = y * y1\n x = Fp.cmov(x, tv3, isValid); // 21. x = CMOV(x, tv3, is_gx1_square)\n y = Fp.cmov(y, value, isValid); // 22. y = CMOV(y, y1, is_gx1_square)\n const e1 = Fp.isOdd!(u) === Fp.isOdd!(y); // 23. e1 = sgn0(u) == sgn0(y)\n y = Fp.cmov(Fp.neg(y), y, e1); // 24. y = CMOV(-y, y, e1)\n const tv4_inv = FpInvertBatch(Fp, [tv4], true)[0];\n x = Fp.mul(x, tv4_inv); // 25. x = x / tv4\n return { x, y };\n };\n}\n\nfunction getWLengths(Fp: IField, Fn: IField) {\n return {\n secretKey: Fn.BYTES,\n publicKey: 1 + Fp.BYTES,\n publicKeyUncompressed: 1 + 2 * Fp.BYTES,\n publicKeyHasPrefix: true,\n signature: 2 * Fn.BYTES,\n };\n}\n\n/**\n * Sometimes users only need getPublicKey, getSharedSecret, and secret key handling.\n * This helper ensures no signature functionality is present. Less code, smaller bundle size.\n */\nexport function ecdh(\n Point: WeierstrassPointCons,\n ecdhOpts: { randomBytes?: (bytesLength?: number) => Uint8Array } = {}\n): ECDH {\n const { Fn } = Point;\n const randomBytes_ = ecdhOpts.randomBytes || randomBytesWeb;\n const lengths = Object.assign(getWLengths(Point.Fp, Fn), { seed: getMinHashLength(Fn.ORDER) });\n\n function isValidSecretKey(secretKey: PrivKey) {\n try {\n return !!_normFnElement(Fn, secretKey);\n } catch (error) {\n return false;\n }\n }\n\n function isValidPublicKey(publicKey: Uint8Array, isCompressed?: boolean): boolean {\n const { publicKey: comp, publicKeyUncompressed } = lengths;\n try {\n const l = publicKey.length;\n if (isCompressed === true && l !== comp) return false;\n if (isCompressed === false && l !== publicKeyUncompressed) return false;\n return !!Point.fromBytes(publicKey);\n } catch (error) {\n return false;\n }\n }\n\n /**\n * Produces cryptographically secure secret key from random of size\n * (groupLen + ceil(groupLen / 2)) with modulo bias being negligible.\n */\n function randomSecretKey(seed = randomBytes_(lengths.seed)): Uint8Array {\n return mapHashToField(abytes(seed, lengths.seed, 'seed'), Fn.ORDER);\n }\n\n /**\n * Computes public key for a secret key. Checks for validity of the secret key.\n * @param isCompressed whether to return compact (default), or full key\n * @returns Public key, full when isCompressed=false; short when isCompressed=true\n */\n function getPublicKey(secretKey: PrivKey, isCompressed = true): Uint8Array {\n return Point.BASE.multiply(_normFnElement(Fn, secretKey)).toBytes(isCompressed);\n }\n\n function keygen(seed?: Uint8Array) {\n const secretKey = randomSecretKey(seed);\n return { secretKey, publicKey: getPublicKey(secretKey) };\n }\n\n /**\n * Quick and dirty check for item being public key. Does not validate hex, or being on-curve.\n */\n function isProbPub(item: PrivKey | PubKey): boolean | undefined {\n if (typeof item === 'bigint') return false;\n if (item instanceof Point) return true;\n const { secretKey, publicKey, publicKeyUncompressed } = lengths;\n if (Fn.allowedLengths || secretKey === publicKey) return undefined;\n const l = ensureBytes('key', item).length;\n return l === publicKey || l === publicKeyUncompressed;\n }\n\n /**\n * ECDH (Elliptic Curve Diffie Hellman).\n * Computes shared public key from secret key A and public key B.\n * Checks: 1) secret key validity 2) shared key is on-curve.\n * Does NOT hash the result.\n * @param isCompressed whether to return compact (default), or full key\n * @returns shared public key\n */\n function getSharedSecret(secretKeyA: PrivKey, publicKeyB: Hex, isCompressed = true): Uint8Array {\n if (isProbPub(secretKeyA) === true) throw new Error('first arg must be private key');\n if (isProbPub(publicKeyB) === false) throw new Error('second arg must be public key');\n const s = _normFnElement(Fn, secretKeyA);\n const b = Point.fromHex(publicKeyB); // checks for being on-curve\n return b.multiply(s).toBytes(isCompressed);\n }\n\n const utils = {\n isValidSecretKey,\n isValidPublicKey,\n randomSecretKey,\n\n // TODO: remove\n isValidPrivateKey: isValidSecretKey,\n randomPrivateKey: randomSecretKey,\n normPrivateKeyToScalar: (key: PrivKey) => _normFnElement(Fn, key),\n precompute(windowSize = 8, point = Point.BASE): WeierstrassPoint {\n return point.precompute(windowSize, false);\n },\n };\n\n return Object.freeze({ getPublicKey, getSharedSecret, keygen, Point, utils, lengths });\n}\n\n/**\n * Creates ECDSA signing interface for given elliptic curve `Point` and `hash` function.\n * We need `hash` for 2 features:\n * 1. Message prehash-ing. NOT used if `sign` / `verify` are called with `prehash: false`\n * 2. k generation in `sign`, using HMAC-drbg(hash)\n *\n * ECDSAOpts are only rarely needed.\n *\n * @example\n * ```js\n * const p256_Point = weierstrass(...);\n * const p256_sha256 = ecdsa(p256_Point, sha256);\n * const p256_sha224 = ecdsa(p256_Point, sha224);\n * const p256_sha224_r = ecdsa(p256_Point, sha224, { randomBytes: (length) => { ... } });\n * ```\n */\nexport function ecdsa(\n Point: WeierstrassPointCons,\n hash: CHash,\n ecdsaOpts: ECDSAOpts = {}\n): ECDSA {\n ahash(hash);\n _validateObject(\n ecdsaOpts,\n {},\n {\n hmac: 'function',\n lowS: 'boolean',\n randomBytes: 'function',\n bits2int: 'function',\n bits2int_modN: 'function',\n }\n );\n\n const randomBytes = ecdsaOpts.randomBytes || randomBytesWeb;\n const hmac: HmacFnSync =\n ecdsaOpts.hmac ||\n (((key, ...msgs) => nobleHmac(hash, key, concatBytes(...msgs))) satisfies HmacFnSync);\n\n const { Fp, Fn } = Point;\n const { ORDER: CURVE_ORDER, BITS: fnBits } = Fn;\n const { keygen, getPublicKey, getSharedSecret, utils, lengths } = ecdh(Point, ecdsaOpts);\n const defaultSigOpts: Required = {\n prehash: false,\n lowS: typeof ecdsaOpts.lowS === 'boolean' ? ecdsaOpts.lowS : false,\n format: undefined as any, //'compact' as ECDSASigFormat,\n extraEntropy: false,\n };\n const defaultSigOpts_format = 'compact';\n\n function isBiggerThanHalfOrder(number: bigint) {\n const HALF = CURVE_ORDER >> _1n;\n return number > HALF;\n }\n function validateRS(title: string, num: bigint): bigint {\n if (!Fn.isValidNot0(num))\n throw new Error(`invalid signature ${title}: out of range 1..Point.Fn.ORDER`);\n return num;\n }\n function validateSigLength(bytes: Uint8Array, format: ECDSASigFormat) {\n validateSigFormat(format);\n const size = lengths.signature!;\n const sizer = format === 'compact' ? size : format === 'recovered' ? size + 1 : undefined;\n return abytes(bytes, sizer, `${format} signature`);\n }\n\n /**\n * ECDSA signature with its (r, s) properties. Supports compact, recovered & DER representations.\n */\n class Signature implements ECDSASignature {\n readonly r: bigint;\n readonly s: bigint;\n readonly recovery?: number;\n constructor(r: bigint, s: bigint, recovery?: number) {\n this.r = validateRS('r', r); // r in [1..N-1];\n this.s = validateRS('s', s); // s in [1..N-1];\n if (recovery != null) this.recovery = recovery;\n Object.freeze(this);\n }\n\n static fromBytes(bytes: Uint8Array, format: ECDSASigFormat = defaultSigOpts_format): Signature {\n validateSigLength(bytes, format);\n let recid: number | undefined;\n if (format === 'der') {\n const { r, s } = DER.toSig(abytes(bytes));\n return new Signature(r, s);\n }\n if (format === 'recovered') {\n recid = bytes[0];\n format = 'compact';\n bytes = bytes.subarray(1);\n }\n const L = Fn.BYTES;\n const r = bytes.subarray(0, L);\n const s = bytes.subarray(L, L * 2);\n return new Signature(Fn.fromBytes(r), Fn.fromBytes(s), recid);\n }\n\n static fromHex(hex: string, format?: ECDSASigFormat) {\n return this.fromBytes(hexToBytes(hex), format);\n }\n\n addRecoveryBit(recovery: number): RecoveredSignature {\n return new Signature(this.r, this.s, recovery) as RecoveredSignature;\n }\n\n recoverPublicKey(messageHash: Hex): WeierstrassPoint {\n const FIELD_ORDER = Fp.ORDER;\n const { r, s, recovery: rec } = this;\n if (rec == null || ![0, 1, 2, 3].includes(rec)) throw new Error('recovery id invalid');\n\n // ECDSA recovery is hard for cofactor > 1 curves.\n // In sign, `r = q.x mod n`, and here we recover q.x from r.\n // While recovering q.x >= n, we need to add r+n for cofactor=1 curves.\n // However, for cofactor>1, r+n may not get q.x:\n // r+n*i would need to be done instead where i is unknown.\n // To easily get i, we either need to:\n // a. increase amount of valid recid values (4, 5...); OR\n // b. prohibit non-prime-order signatures (recid > 1).\n const hasCofactor = CURVE_ORDER * _2n < FIELD_ORDER;\n if (hasCofactor && rec > 1) throw new Error('recovery id is ambiguous for h>1 curve');\n\n const radj = rec === 2 || rec === 3 ? r + CURVE_ORDER : r;\n if (!Fp.isValid(radj)) throw new Error('recovery id 2 or 3 invalid');\n const x = Fp.toBytes(radj);\n const R = Point.fromBytes(concatBytes(pprefix((rec & 1) === 0), x));\n const ir = Fn.inv(radj); // r^-1\n const h = bits2int_modN(ensureBytes('msgHash', messageHash)); // Truncate hash\n const u1 = Fn.create(-h * ir); // -hr^-1\n const u2 = Fn.create(s * ir); // sr^-1\n // (sr^-1)R-(hr^-1)G = -(hr^-1)G + (sr^-1). unsafe is fine: there is no private data.\n const Q = Point.BASE.multiplyUnsafe(u1).add(R.multiplyUnsafe(u2));\n if (Q.is0()) throw new Error('point at infinify');\n Q.assertValidity();\n return Q;\n }\n\n // Signatures should be low-s, to prevent malleability.\n hasHighS(): boolean {\n return isBiggerThanHalfOrder(this.s);\n }\n\n toBytes(format: ECDSASigFormat = defaultSigOpts_format) {\n validateSigFormat(format);\n if (format === 'der') return hexToBytes(DER.hexFromSig(this));\n const r = Fn.toBytes(this.r);\n const s = Fn.toBytes(this.s);\n if (format === 'recovered') {\n if (this.recovery == null) throw new Error('recovery bit must be present');\n return concatBytes(Uint8Array.of(this.recovery), r, s);\n }\n return concatBytes(r, s);\n }\n\n toHex(format?: ECDSASigFormat) {\n return bytesToHex(this.toBytes(format));\n }\n\n // TODO: remove\n assertValidity(): void {}\n static fromCompact(hex: Hex) {\n return Signature.fromBytes(ensureBytes('sig', hex), 'compact');\n }\n static fromDER(hex: Hex) {\n return Signature.fromBytes(ensureBytes('sig', hex), 'der');\n }\n normalizeS() {\n return this.hasHighS() ? new Signature(this.r, Fn.neg(this.s), this.recovery) : this;\n }\n toDERRawBytes() {\n return this.toBytes('der');\n }\n toDERHex() {\n return bytesToHex(this.toBytes('der'));\n }\n toCompactRawBytes() {\n return this.toBytes('compact');\n }\n toCompactHex() {\n return bytesToHex(this.toBytes('compact'));\n }\n }\n type RecoveredSignature = Signature & { recovery: number };\n\n // RFC6979: ensure ECDSA msg is X bytes and < N. RFC suggests optional truncating via bits2octets.\n // FIPS 186-4 4.6 suggests the leftmost min(nBitLen, outLen) bits, which matches bits2int.\n // bits2int can produce res>N, we can do mod(res, N) since the bitLen is the same.\n // int2octets can't be used; pads small msgs with 0: unacceptatble for trunc as per RFC vectors\n const bits2int =\n ecdsaOpts.bits2int ||\n function bits2int_def(bytes: Uint8Array): bigint {\n // Our custom check \"just in case\", for protection against DoS\n if (bytes.length > 8192) throw new Error('input is too large');\n // For curves with nBitLength % 8 !== 0: bits2octets(bits2octets(m)) !== bits2octets(m)\n // for some cases, since bytes.length * 8 is not actual bitLength.\n const num = bytesToNumberBE(bytes); // check for == u8 done here\n const delta = bytes.length * 8 - fnBits; // truncate to nBitLength leftmost bits\n return delta > 0 ? num >> BigInt(delta) : num;\n };\n const bits2int_modN =\n ecdsaOpts.bits2int_modN ||\n function bits2int_modN_def(bytes: Uint8Array): bigint {\n return Fn.create(bits2int(bytes)); // can't use bytesToNumberBE here\n };\n // Pads output with zero as per spec\n const ORDER_MASK = bitMask(fnBits);\n /** Converts to bytes. Checks if num in `[0..ORDER_MASK-1]` e.g.: `[0..2^256-1]`. */\n function int2octets(num: bigint): Uint8Array {\n // IMPORTANT: the check ensures working for case `Fn.BYTES != Fn.BITS * 8`\n aInRange('num < 2^' + fnBits, num, _0n, ORDER_MASK);\n return Fn.toBytes(num);\n }\n\n function validateMsgAndHash(message: Uint8Array, prehash: boolean) {\n abytes(message, undefined, 'message');\n return prehash ? abytes(hash(message), undefined, 'prehashed message') : message;\n }\n\n /**\n * Steps A, D of RFC6979 3.2.\n * Creates RFC6979 seed; converts msg/privKey to numbers.\n * Used only in sign, not in verify.\n *\n * Warning: we cannot assume here that message has same amount of bytes as curve order,\n * this will be invalid at least for P521. Also it can be bigger for P224 + SHA256.\n */\n function prepSig(message: Uint8Array, privateKey: PrivKey, opts: ECDSASignOpts) {\n if (['recovered', 'canonical'].some((k) => k in opts))\n throw new Error('sign() legacy options not supported');\n const { lowS, prehash, extraEntropy } = validateSigOpts(opts, defaultSigOpts);\n message = validateMsgAndHash(message, prehash); // RFC6979 3.2 A: h1 = H(m)\n // We can't later call bits2octets, since nested bits2int is broken for curves\n // with fnBits % 8 !== 0. Because of that, we unwrap it here as int2octets call.\n // const bits2octets = (bits) => int2octets(bits2int_modN(bits))\n const h1int = bits2int_modN(message);\n const d = _normFnElement(Fn, privateKey); // validate secret key, convert to bigint\n const seedArgs = [int2octets(d), int2octets(h1int)];\n // extraEntropy. RFC6979 3.6: additional k' (optional).\n if (extraEntropy != null && extraEntropy !== false) {\n // K = HMAC_K(V || 0x00 || int2octets(x) || bits2octets(h1) || k')\n // gen random bytes OR pass as-is\n const e = extraEntropy === true ? randomBytes(lengths.secretKey) : extraEntropy;\n seedArgs.push(ensureBytes('extraEntropy', e)); // check for being bytes\n }\n const seed = concatBytes(...seedArgs); // Step D of RFC6979 3.2\n const m = h1int; // NOTE: no need to call bits2int second time here, it is inside truncateHash!\n // Converts signature params into point w r/s, checks result for validity.\n // To transform k => Signature:\n // q = k⋅G\n // r = q.x mod n\n // s = k^-1(m + rd) mod n\n // Can use scalar blinding b^-1(bm + bdr) where b ∈ [1,q−1] according to\n // https://tches.iacr.org/index.php/TCHES/article/view/7337/6509. We've decided against it:\n // a) dependency on CSPRNG b) 15% slowdown c) doesn't really help since bigints are not CT\n function k2sig(kBytes: Uint8Array): RecoveredSignature | undefined {\n // RFC 6979 Section 3.2, step 3: k = bits2int(T)\n // Important: all mod() calls here must be done over N\n const k = bits2int(kBytes); // mod n, not mod p\n if (!Fn.isValidNot0(k)) return; // Valid scalars (including k) must be in 1..N-1\n const ik = Fn.inv(k); // k^-1 mod n\n const q = Point.BASE.multiply(k).toAffine(); // q = k⋅G\n const r = Fn.create(q.x); // r = q.x mod n\n if (r === _0n) return;\n const s = Fn.create(ik * Fn.create(m + r * d)); // Not using blinding here, see comment above\n if (s === _0n) return;\n let recovery = (q.x === r ? 0 : 2) | Number(q.y & _1n); // recovery bit (2 or 3, when q.x > n)\n let normS = s;\n if (lowS && isBiggerThanHalfOrder(s)) {\n normS = Fn.neg(s); // if lowS was passed, ensure s is always\n recovery ^= 1; // // in the bottom half of N\n }\n return new Signature(r, normS, recovery) as RecoveredSignature; // use normS, not s\n }\n return { seed, k2sig };\n }\n\n /**\n * Signs message hash with a secret key.\n *\n * ```\n * sign(m, d) where\n * k = rfc6979_hmac_drbg(m, d)\n * (x, y) = G × k\n * r = x mod n\n * s = (m + dr) / k mod n\n * ```\n */\n function sign(message: Hex, secretKey: PrivKey, opts: ECDSASignOpts = {}): RecoveredSignature {\n message = ensureBytes('message', message);\n const { seed, k2sig } = prepSig(message, secretKey, opts); // Steps A, D of RFC6979 3.2.\n const drbg = createHmacDrbg(hash.outputLen, Fn.BYTES, hmac);\n const sig = drbg(seed, k2sig); // Steps B, C, D, E, F, G\n return sig;\n }\n\n function tryParsingSig(sg: Hex | SignatureLike) {\n // Try to deduce format\n let sig: Signature | undefined = undefined;\n const isHex = typeof sg === 'string' || isBytes(sg);\n const isObj =\n !isHex &&\n sg !== null &&\n typeof sg === 'object' &&\n typeof sg.r === 'bigint' &&\n typeof sg.s === 'bigint';\n if (!isHex && !isObj)\n throw new Error('invalid signature, expected Uint8Array, hex string or Signature instance');\n if (isObj) {\n sig = new Signature(sg.r, sg.s);\n } else if (isHex) {\n try {\n sig = Signature.fromBytes(ensureBytes('sig', sg), 'der');\n } catch (derError) {\n if (!(derError instanceof DER.Err)) throw derError;\n }\n if (!sig) {\n try {\n sig = Signature.fromBytes(ensureBytes('sig', sg), 'compact');\n } catch (error) {\n return false;\n }\n }\n }\n if (!sig) return false;\n return sig;\n }\n\n /**\n * Verifies a signature against message and public key.\n * Rejects lowS signatures by default: see {@link ECDSAVerifyOpts}.\n * Implements section 4.1.4 from https://www.secg.org/sec1-v2.pdf:\n *\n * ```\n * verify(r, s, h, P) where\n * u1 = hs^-1 mod n\n * u2 = rs^-1 mod n\n * R = u1⋅G + u2⋅P\n * mod(R.x, n) == r\n * ```\n */\n function verify(\n signature: Hex | SignatureLike,\n message: Hex,\n publicKey: Hex,\n opts: ECDSAVerifyOpts = {}\n ): boolean {\n const { lowS, prehash, format } = validateSigOpts(opts, defaultSigOpts);\n publicKey = ensureBytes('publicKey', publicKey);\n message = validateMsgAndHash(ensureBytes('message', message), prehash);\n if ('strict' in opts) throw new Error('options.strict was renamed to lowS');\n const sig =\n format === undefined\n ? tryParsingSig(signature)\n : Signature.fromBytes(ensureBytes('sig', signature as Hex), format);\n if (sig === false) return false;\n try {\n const P = Point.fromBytes(publicKey);\n if (lowS && sig.hasHighS()) return false;\n const { r, s } = sig;\n const h = bits2int_modN(message); // mod n, not mod p\n const is = Fn.inv(s); // s^-1 mod n\n const u1 = Fn.create(h * is); // u1 = hs^-1 mod n\n const u2 = Fn.create(r * is); // u2 = rs^-1 mod n\n const R = Point.BASE.multiplyUnsafe(u1).add(P.multiplyUnsafe(u2)); // u1⋅G + u2⋅P\n if (R.is0()) return false;\n const v = Fn.create(R.x); // v = r.x mod n\n return v === r;\n } catch (e) {\n return false;\n }\n }\n\n function recoverPublicKey(\n signature: Uint8Array,\n message: Uint8Array,\n opts: ECDSARecoverOpts = {}\n ): Uint8Array {\n const { prehash } = validateSigOpts(opts, defaultSigOpts);\n message = validateMsgAndHash(message, prehash);\n return Signature.fromBytes(signature, 'recovered').recoverPublicKey(message).toBytes();\n }\n\n return Object.freeze({\n keygen,\n getPublicKey,\n getSharedSecret,\n utils,\n lengths,\n Point,\n sign,\n verify,\n recoverPublicKey,\n Signature,\n hash,\n });\n}\n\n// TODO: remove everything below\n/** @deprecated use ECDSASignature */\nexport type SignatureType = ECDSASignature;\n/** @deprecated use ECDSASigRecovered */\nexport type RecoveredSignatureType = ECDSASigRecovered;\n/** @deprecated switch to Uint8Array signatures in format 'compact' */\nexport type SignatureLike = { r: bigint; s: bigint };\nexport type ECDSAExtraEntropy = Hex | boolean;\n/** @deprecated use `ECDSAExtraEntropy` */\nexport type Entropy = Hex | boolean;\nexport type BasicWCurve = BasicCurve & {\n // Params: a, b\n a: T;\n b: T;\n\n // Optional params\n allowedPrivateKeyLengths?: readonly number[]; // for P521\n wrapPrivateKey?: boolean; // bls12-381 requires mod(n) instead of rejecting keys >= n\n endo?: EndomorphismOpts;\n // When a cofactor != 1, there can be an effective methods to:\n // 1. Determine whether a point is torsion-free\n isTorsionFree?: (c: WeierstrassPointCons, point: WeierstrassPoint) => boolean;\n // 2. Clear torsion component\n clearCofactor?: (c: WeierstrassPointCons, point: WeierstrassPoint) => WeierstrassPoint;\n};\n/** @deprecated use ECDSASignOpts */\nexport type SignOpts = ECDSASignOpts;\n/** @deprecated use ECDSASignOpts */\nexport type VerOpts = ECDSAVerifyOpts;\n\n/** @deprecated use WeierstrassPoint */\nexport type ProjPointType = WeierstrassPoint;\n/** @deprecated use WeierstrassPointCons */\nexport type ProjConstructor = WeierstrassPointCons;\n/** @deprecated use ECDSASignatureCons */\nexport type SignatureConstructor = ECDSASignatureCons;\n\n// TODO: remove\nexport type CurvePointsType = BasicWCurve & {\n fromBytes?: (bytes: Uint8Array) => AffinePoint;\n toBytes?: (\n c: WeierstrassPointCons,\n point: WeierstrassPoint,\n isCompressed: boolean\n ) => Uint8Array;\n};\n\n// LegacyWeierstrassOpts\nexport type CurvePointsTypeWithLength = Readonly & Partial>;\n\n// LegacyWeierstrass\nexport type CurvePointsRes = {\n Point: WeierstrassPointCons;\n\n /** @deprecated use `Point.CURVE()` */\n CURVE: CurvePointsType;\n /** @deprecated use `Point` */\n ProjectivePoint: WeierstrassPointCons;\n /** @deprecated use `Point.Fn.fromBytes(privateKey)` */\n normPrivateKeyToScalar: (key: PrivKey) => bigint;\n /** @deprecated */\n weierstrassEquation: (x: T) => T;\n /** @deprecated use `Point.Fn.isValidNot0(num)` */\n isWithinCurveOrder: (num: bigint) => boolean;\n};\n\n// Aliases to legacy types\n// export type CurveType = LegacyECDSAOpts;\n// export type CurveFn = LegacyECDSA;\n// export type CurvePointsRes = LegacyWeierstrass;\n// export type CurvePointsType = LegacyWeierstrassOpts;\n// export type CurvePointsTypeWithLength = LegacyWeierstrassOpts;\n// export type BasicWCurve = LegacyWeierstrassOpts;\n\n/** @deprecated use `Uint8Array` */\nexport type PubKey = Hex | WeierstrassPoint;\nexport type CurveType = BasicWCurve & {\n hash: CHash; // CHash not FHash because we need outputLen for DRBG\n hmac?: HmacFnSync;\n randomBytes?: (bytesLength?: number) => Uint8Array;\n lowS?: boolean;\n bits2int?: (bytes: Uint8Array) => bigint;\n bits2int_modN?: (bytes: Uint8Array) => bigint;\n};\nexport type CurveFn = {\n /** @deprecated use `Point.CURVE()` */\n CURVE: CurvePointsType;\n keygen: ECDSA['keygen'];\n getPublicKey: ECDSA['getPublicKey'];\n getSharedSecret: ECDSA['getSharedSecret'];\n sign: ECDSA['sign'];\n verify: ECDSA['verify'];\n Point: WeierstrassPointCons;\n /** @deprecated use `Point` */\n ProjectivePoint: WeierstrassPointCons;\n Signature: ECDSASignatureCons;\n utils: ECDSA['utils'];\n lengths: ECDSA['lengths'];\n};\n/** @deprecated use `weierstrass` in newer releases */\nexport function weierstrassPoints(c: CurvePointsTypeWithLength): CurvePointsRes {\n const { CURVE, curveOpts } = _weierstrass_legacy_opts_to_new(c);\n const Point = weierstrassN(CURVE, curveOpts);\n return _weierstrass_new_output_to_legacy(c, Point);\n}\nexport type WsPointComposed = {\n CURVE: WeierstrassOpts;\n curveOpts: WeierstrassExtraOpts;\n};\nexport type WsComposed = {\n /** @deprecated use `Point.CURVE()` */\n CURVE: WeierstrassOpts;\n hash: CHash;\n curveOpts: WeierstrassExtraOpts;\n ecdsaOpts: ECDSAOpts;\n};\nfunction _weierstrass_legacy_opts_to_new(c: CurvePointsType): WsPointComposed {\n const CURVE: WeierstrassOpts = {\n a: c.a,\n b: c.b,\n p: c.Fp.ORDER,\n n: c.n,\n h: c.h,\n Gx: c.Gx,\n Gy: c.Gy,\n };\n const Fp = c.Fp;\n let allowedLengths = c.allowedPrivateKeyLengths\n ? Array.from(new Set(c.allowedPrivateKeyLengths.map((l) => Math.ceil(l / 2))))\n : undefined;\n const Fn = Field(CURVE.n, {\n BITS: c.nBitLength,\n allowedLengths: allowedLengths,\n modFromBytes: c.wrapPrivateKey,\n });\n const curveOpts: WeierstrassExtraOpts = {\n Fp,\n Fn,\n allowInfinityPoint: c.allowInfinityPoint,\n endo: c.endo,\n isTorsionFree: c.isTorsionFree,\n clearCofactor: c.clearCofactor,\n fromBytes: c.fromBytes,\n toBytes: c.toBytes,\n };\n return { CURVE, curveOpts };\n}\nfunction _ecdsa_legacy_opts_to_new(c: CurveType): WsComposed {\n const { CURVE, curveOpts } = _weierstrass_legacy_opts_to_new(c);\n const ecdsaOpts: ECDSAOpts = {\n hmac: c.hmac,\n randomBytes: c.randomBytes,\n lowS: c.lowS,\n bits2int: c.bits2int,\n bits2int_modN: c.bits2int_modN,\n };\n return { CURVE, curveOpts, hash: c.hash, ecdsaOpts };\n}\nexport function _legacyHelperEquat(Fp: IField, a: T, b: T): (x: T) => T {\n /**\n * y² = x³ + ax + b: Short weierstrass curve formula. Takes x, returns y².\n * @returns y²\n */\n function weierstrassEquation(x: T): T {\n const x2 = Fp.sqr(x); // x * x\n const x3 = Fp.mul(x2, x); // x² * x\n return Fp.add(Fp.add(x3, Fp.mul(x, a)), b); // x³ + a * x + b\n }\n return weierstrassEquation;\n}\nfunction _weierstrass_new_output_to_legacy(\n c: CurvePointsType,\n Point: WeierstrassPointCons\n): CurvePointsRes {\n const { Fp, Fn } = Point;\n function isWithinCurveOrder(num: bigint): boolean {\n return inRange(num, _1n, Fn.ORDER);\n }\n const weierstrassEquation = _legacyHelperEquat(Fp, c.a, c.b);\n return Object.assign(\n {},\n {\n CURVE: c,\n Point: Point,\n ProjectivePoint: Point,\n normPrivateKeyToScalar: (key: PrivKey) => _normFnElement(Fn, key),\n weierstrassEquation,\n isWithinCurveOrder,\n }\n );\n}\nfunction _ecdsa_new_output_to_legacy(c: CurveType, _ecdsa: ECDSA): CurveFn {\n const Point = _ecdsa.Point;\n return Object.assign({}, _ecdsa, {\n ProjectivePoint: Point,\n CURVE: Object.assign({}, c, nLength(Point.Fn.ORDER, Point.Fn.BITS)),\n });\n}\n\n// _ecdsa_legacy\nexport function weierstrass(c: CurveType): CurveFn {\n const { CURVE, curveOpts, hash, ecdsaOpts } = _ecdsa_legacy_opts_to_new(c);\n const Point = weierstrassN(CURVE, curveOpts);\n const signs = ecdsa(Point, hash, ecdsaOpts);\n return _ecdsa_new_output_to_legacy(c, signs);\n}\n", "/**\n * Utilities for short weierstrass curves, combined with noble-hashes.\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { type CurveFn, type CurveType, weierstrass } from './abstract/weierstrass.ts';\nimport type { CHash } from './utils.ts';\n\n/** connects noble-curves to noble-hashes */\nexport function getHash(hash: CHash): { hash: CHash } {\n return { hash };\n}\n/** Same API as @noble/hashes, with ability to create curve with custom hash */\nexport type CurveDef = Readonly>;\nexport type CurveFnWithCreate = CurveFn & { create: (hash: CHash) => CurveFn };\n\n/** @deprecated use new `weierstrass()` and `ecdsa()` methods */\nexport function createCurve(curveDef: CurveDef, defHash: CHash): CurveFnWithCreate {\n const create = (hash: CHash): CurveFn => weierstrass({ ...curveDef, hash: hash });\n return { ...create(defHash), create };\n}\n", "/**\n * hash-to-curve from RFC 9380.\n * Hashes arbitrary-length byte strings to a list of one or more elements of a finite field F.\n * https://www.rfc-editor.org/rfc/rfc9380\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport type { CHash } from '../utils.ts';\nimport {\n _validateObject,\n abytes,\n bytesToNumberBE,\n concatBytes,\n isBytes,\n isHash,\n utf8ToBytes,\n} from '../utils.ts';\nimport type { AffinePoint, Group, GroupConstructor } from './curve.ts';\nimport { FpInvertBatch, mod, type IField } from './modular.ts';\n\nexport type UnicodeOrBytes = string | Uint8Array;\n\n/**\n * * `DST` is a domain separation tag, defined in section 2.2.5\n * * `p` characteristic of F, where F is a finite field of characteristic p and order q = p^m\n * * `m` is extension degree (1 for prime fields)\n * * `k` is the target security target in bits (e.g. 128), from section 5.1\n * * `expand` is `xmd` (SHA2, SHA3, BLAKE) or `xof` (SHAKE, BLAKE-XOF)\n * * `hash` conforming to `utils.CHash` interface, with `outputLen` / `blockLen` props\n */\nexport type H2COpts = {\n DST: UnicodeOrBytes;\n expand: 'xmd' | 'xof';\n hash: CHash;\n p: bigint;\n m: number;\n k: number;\n};\nexport type H2CHashOpts = {\n expand: 'xmd' | 'xof';\n hash: CHash;\n};\n// todo: remove\nexport type Opts = H2COpts;\n\n// Octet Stream to Integer. \"spec\" implementation of os2ip is 2.5x slower vs bytesToNumberBE.\nconst os2ip = bytesToNumberBE;\n\n// Integer to Octet Stream (numberToBytesBE)\nfunction i2osp(value: number, length: number): Uint8Array {\n anum(value);\n anum(length);\n if (value < 0 || value >= 1 << (8 * length)) throw new Error('invalid I2OSP input: ' + value);\n const res = Array.from({ length }).fill(0) as number[];\n for (let i = length - 1; i >= 0; i--) {\n res[i] = value & 0xff;\n value >>>= 8;\n }\n return new Uint8Array(res);\n}\n\nfunction strxor(a: Uint8Array, b: Uint8Array): Uint8Array {\n const arr = new Uint8Array(a.length);\n for (let i = 0; i < a.length; i++) {\n arr[i] = a[i] ^ b[i];\n }\n return arr;\n}\n\nfunction anum(item: unknown): void {\n if (!Number.isSafeInteger(item)) throw new Error('number expected');\n}\n\nfunction normDST(DST: UnicodeOrBytes): Uint8Array {\n if (!isBytes(DST) && typeof DST !== 'string') throw new Error('DST must be Uint8Array or string');\n return typeof DST === 'string' ? utf8ToBytes(DST) : DST;\n}\n\n/**\n * Produces a uniformly random byte string using a cryptographic hash function H that outputs b bits.\n * [RFC 9380 5.3.1](https://www.rfc-editor.org/rfc/rfc9380#section-5.3.1).\n */\nexport function expand_message_xmd(\n msg: Uint8Array,\n DST: UnicodeOrBytes,\n lenInBytes: number,\n H: CHash\n): Uint8Array {\n abytes(msg);\n anum(lenInBytes);\n DST = normDST(DST);\n // https://www.rfc-editor.org/rfc/rfc9380#section-5.3.3\n if (DST.length > 255) DST = H(concatBytes(utf8ToBytes('H2C-OVERSIZE-DST-'), DST));\n const { outputLen: b_in_bytes, blockLen: r_in_bytes } = H;\n const ell = Math.ceil(lenInBytes / b_in_bytes);\n if (lenInBytes > 65535 || ell > 255) throw new Error('expand_message_xmd: invalid lenInBytes');\n const DST_prime = concatBytes(DST, i2osp(DST.length, 1));\n const Z_pad = i2osp(0, r_in_bytes);\n const l_i_b_str = i2osp(lenInBytes, 2); // len_in_bytes_str\n const b = new Array(ell);\n const b_0 = H(concatBytes(Z_pad, msg, l_i_b_str, i2osp(0, 1), DST_prime));\n b[0] = H(concatBytes(b_0, i2osp(1, 1), DST_prime));\n for (let i = 1; i <= ell; i++) {\n const args = [strxor(b_0, b[i - 1]), i2osp(i + 1, 1), DST_prime];\n b[i] = H(concatBytes(...args));\n }\n const pseudo_random_bytes = concatBytes(...b);\n return pseudo_random_bytes.slice(0, lenInBytes);\n}\n\n/**\n * Produces a uniformly random byte string using an extendable-output function (XOF) H.\n * 1. The collision resistance of H MUST be at least k bits.\n * 2. H MUST be an XOF that has been proved indifferentiable from\n * a random oracle under a reasonable cryptographic assumption.\n * [RFC 9380 5.3.2](https://www.rfc-editor.org/rfc/rfc9380#section-5.3.2).\n */\nexport function expand_message_xof(\n msg: Uint8Array,\n DST: UnicodeOrBytes,\n lenInBytes: number,\n k: number,\n H: CHash\n): Uint8Array {\n abytes(msg);\n anum(lenInBytes);\n DST = normDST(DST);\n // https://www.rfc-editor.org/rfc/rfc9380#section-5.3.3\n // DST = H('H2C-OVERSIZE-DST-' || a_very_long_DST, Math.ceil((lenInBytes * k) / 8));\n if (DST.length > 255) {\n const dkLen = Math.ceil((2 * k) / 8);\n DST = H.create({ dkLen }).update(utf8ToBytes('H2C-OVERSIZE-DST-')).update(DST).digest();\n }\n if (lenInBytes > 65535 || DST.length > 255)\n throw new Error('expand_message_xof: invalid lenInBytes');\n return (\n H.create({ dkLen: lenInBytes })\n .update(msg)\n .update(i2osp(lenInBytes, 2))\n // 2. DST_prime = DST || I2OSP(len(DST), 1)\n .update(DST)\n .update(i2osp(DST.length, 1))\n .digest()\n );\n}\n\n/**\n * Hashes arbitrary-length byte strings to a list of one or more elements of a finite field F.\n * [RFC 9380 5.2](https://www.rfc-editor.org/rfc/rfc9380#section-5.2).\n * @param msg a byte string containing the message to hash\n * @param count the number of elements of F to output\n * @param options `{DST: string, p: bigint, m: number, k: number, expand: 'xmd' | 'xof', hash: H}`, see above\n * @returns [u_0, ..., u_(count - 1)], a list of field elements.\n */\nexport function hash_to_field(msg: Uint8Array, count: number, options: H2COpts): bigint[][] {\n _validateObject(options, {\n p: 'bigint',\n m: 'number',\n k: 'number',\n hash: 'function',\n });\n const { p, k, m, hash, expand, DST } = options;\n if (!isHash(options.hash)) throw new Error('expected valid hash');\n abytes(msg);\n anum(count);\n const log2p = p.toString(2).length;\n const L = Math.ceil((log2p + k) / 8); // section 5.1 of ietf draft link above\n const len_in_bytes = count * m * L;\n let prb; // pseudo_random_bytes\n if (expand === 'xmd') {\n prb = expand_message_xmd(msg, DST, len_in_bytes, hash);\n } else if (expand === 'xof') {\n prb = expand_message_xof(msg, DST, len_in_bytes, k, hash);\n } else if (expand === '_internal_pass') {\n // for internal tests only\n prb = msg;\n } else {\n throw new Error('expand must be \"xmd\" or \"xof\"');\n }\n const u = new Array(count);\n for (let i = 0; i < count; i++) {\n const e = new Array(m);\n for (let j = 0; j < m; j++) {\n const elm_offset = L * (j + i * m);\n const tv = prb.subarray(elm_offset, elm_offset + L);\n e[j] = mod(os2ip(tv), p);\n }\n u[i] = e;\n }\n return u;\n}\n\nexport type XY = (x: T, y: T) => { x: T; y: T };\nexport type XYRatio = [T[], T[], T[], T[]]; // xn/xd, yn/yd\nexport function isogenyMap>(field: F, map: XYRatio): XY {\n // Make same order as in spec\n const coeff = map.map((i) => Array.from(i).reverse());\n return (x: T, y: T) => {\n const [xn, xd, yn, yd] = coeff.map((val) =>\n val.reduce((acc, i) => field.add(field.mul(acc, x), i))\n );\n // 6.6.3\n // Exceptional cases of iso_map are inputs that cause the denominator of\n // either rational function to evaluate to zero; such cases MUST return\n // the identity point on E.\n const [xd_inv, yd_inv] = FpInvertBatch(field, [xd, yd], true);\n x = field.mul(xn, xd_inv); // xNum / xDen\n y = field.mul(y, field.mul(yn, yd_inv)); // y * (yNum / yDev)\n return { x, y };\n };\n}\n\n/** Point interface, which curves must implement to work correctly with the module. */\nexport interface H2CPoint extends Group> {\n add(rhs: H2CPoint): H2CPoint;\n toAffine(iz?: bigint): AffinePoint;\n clearCofactor(): H2CPoint;\n assertValidity(): void;\n}\n\nexport interface H2CPointConstructor extends GroupConstructor> {\n fromAffine(ap: AffinePoint): H2CPoint;\n}\n\nexport type MapToCurve = (scalar: bigint[]) => AffinePoint;\n\n// Separated from initialization opts, so users won't accidentally change per-curve parameters\n// (changing DST is ok!)\nexport type htfBasicOpts = { DST: UnicodeOrBytes };\nexport type H2CMethod = (msg: Uint8Array, options?: htfBasicOpts) => H2CPoint;\n// TODO: remove\nexport type HTFMethod = H2CMethod;\nexport type MapMethod = (scalars: bigint[]) => H2CPoint;\nexport type H2CHasherBase = {\n hashToCurve: H2CMethod;\n hashToScalar: (msg: Uint8Array, options: htfBasicOpts) => bigint;\n};\n/**\n * RFC 9380 methods, with cofactor clearing. See https://www.rfc-editor.org/rfc/rfc9380#section-3.\n *\n * * hashToCurve: `map(hash(input))`, encodes RANDOM bytes to curve (WITH hashing)\n * * encodeToCurve: `map(hash(input))`, encodes NON-UNIFORM bytes to curve (WITH hashing)\n * * mapToCurve: `map(scalars)`, encodes NON-UNIFORM scalars to curve (NO hashing)\n */\nexport type H2CHasher = H2CHasherBase & {\n encodeToCurve: H2CMethod;\n mapToCurve: MapMethod;\n defaults: H2COpts & { encodeDST?: UnicodeOrBytes };\n};\n// TODO: remove\nexport type Hasher = H2CHasher;\n\nexport const _DST_scalar: Uint8Array = utf8ToBytes('HashToScalar-');\n\n/** Creates hash-to-curve methods from EC Point and mapToCurve function. See {@link H2CHasher}. */\nexport function createHasher(\n Point: H2CPointConstructor,\n mapToCurve: MapToCurve,\n defaults: H2COpts & { encodeDST?: UnicodeOrBytes }\n): H2CHasher {\n if (typeof mapToCurve !== 'function') throw new Error('mapToCurve() must be defined');\n function map(num: bigint[]) {\n return Point.fromAffine(mapToCurve(num));\n }\n function clear(initial: H2CPoint) {\n const P = initial.clearCofactor();\n if (P.equals(Point.ZERO)) return Point.ZERO; // zero will throw in assert\n P.assertValidity();\n return P;\n }\n\n return {\n defaults,\n\n hashToCurve(msg: Uint8Array, options?: htfBasicOpts): H2CPoint {\n const opts = Object.assign({}, defaults, options);\n const u = hash_to_field(msg, 2, opts);\n const u0 = map(u[0]);\n const u1 = map(u[1]);\n return clear(u0.add(u1));\n },\n encodeToCurve(msg: Uint8Array, options?: htfBasicOpts): H2CPoint {\n const optsDst = defaults.encodeDST ? { DST: defaults.encodeDST } : {};\n const opts = Object.assign({}, defaults, optsDst, options);\n const u = hash_to_field(msg, 1, opts);\n const u0 = map(u[0]);\n return clear(u0);\n },\n /** See {@link H2CHasher} */\n mapToCurve(scalars: bigint[]): H2CPoint {\n if (!Array.isArray(scalars)) throw new Error('expected array of bigints');\n for (const i of scalars)\n if (typeof i !== 'bigint') throw new Error('expected array of bigints');\n return clear(map(scalars));\n },\n\n // hash_to_scalar can produce 0: https://www.rfc-editor.org/errata/eid8393\n // RFC 9380, draft-irtf-cfrg-bbs-signatures-08\n hashToScalar(msg: Uint8Array, options?: htfBasicOpts): bigint {\n // @ts-ignore\n const N = Point.Fn.ORDER;\n const opts = Object.assign({}, defaults, { p: N, m: 1, DST: _DST_scalar }, options);\n return hash_to_field(msg, 1, opts)[0][0];\n },\n };\n}\n", "/**\n * SECG secp256k1. See [pdf](https://www.secg.org/sec2-v2.pdf).\n *\n * Belongs to Koblitz curves: it has efficiently-computable GLV endomorphism ψ,\n * check out {@link EndomorphismOpts}. Seems to be rigid (not backdoored).\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { sha256 } from '@noble/hashes/sha2.js';\nimport { randomBytes } from '@noble/hashes/utils.js';\nimport { createCurve, type CurveFnWithCreate } from './_shortw_utils.ts';\nimport type { CurveLengths } from './abstract/curve.ts';\nimport {\n createHasher,\n type H2CHasher,\n type H2CMethod,\n isogenyMap,\n} from './abstract/hash-to-curve.ts';\nimport { Field, mapHashToField, mod, pow2 } from './abstract/modular.ts';\nimport {\n _normFnElement,\n type EndomorphismOpts,\n mapToCurveSimpleSWU,\n type WeierstrassPoint as PointType,\n type WeierstrassOpts,\n type WeierstrassPointCons,\n} from './abstract/weierstrass.ts';\nimport type { Hex, PrivKey } from './utils.ts';\nimport {\n bytesToNumberBE,\n concatBytes,\n ensureBytes,\n inRange,\n numberToBytesBE,\n utf8ToBytes,\n} from './utils.ts';\n\n// Seems like generator was produced from some seed:\n// `Point.BASE.multiply(Point.Fn.inv(2n, N)).toAffine().x`\n// // gives short x 0x3b78ce563f89a0ed9414f5aa28ad0d96d6795f9c63n\nconst secp256k1_CURVE: WeierstrassOpts = {\n p: BigInt('0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f'),\n n: BigInt('0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141'),\n h: BigInt(1),\n a: BigInt(0),\n b: BigInt(7),\n Gx: BigInt('0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798'),\n Gy: BigInt('0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8'),\n};\n\nconst secp256k1_ENDO: EndomorphismOpts = {\n beta: BigInt('0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee'),\n basises: [\n [BigInt('0x3086d221a7d46bcde86c90e49284eb15'), -BigInt('0xe4437ed6010e88286f547fa90abfe4c3')],\n [BigInt('0x114ca50f7a8e2f3f657c1108d9d44cfd8'), BigInt('0x3086d221a7d46bcde86c90e49284eb15')],\n ],\n};\n\nconst _0n = /* @__PURE__ */ BigInt(0);\nconst _1n = /* @__PURE__ */ BigInt(1);\nconst _2n = /* @__PURE__ */ BigInt(2);\n\n/**\n * √n = n^((p+1)/4) for fields p = 3 mod 4. We unwrap the loop and multiply bit-by-bit.\n * (P+1n/4n).toString(2) would produce bits [223x 1, 0, 22x 1, 4x 0, 11, 00]\n */\nfunction sqrtMod(y: bigint): bigint {\n const P = secp256k1_CURVE.p;\n // prettier-ignore\n const _3n = BigInt(3), _6n = BigInt(6), _11n = BigInt(11), _22n = BigInt(22);\n // prettier-ignore\n const _23n = BigInt(23), _44n = BigInt(44), _88n = BigInt(88);\n const b2 = (y * y * y) % P; // x^3, 11\n const b3 = (b2 * b2 * y) % P; // x^7\n const b6 = (pow2(b3, _3n, P) * b3) % P;\n const b9 = (pow2(b6, _3n, P) * b3) % P;\n const b11 = (pow2(b9, _2n, P) * b2) % P;\n const b22 = (pow2(b11, _11n, P) * b11) % P;\n const b44 = (pow2(b22, _22n, P) * b22) % P;\n const b88 = (pow2(b44, _44n, P) * b44) % P;\n const b176 = (pow2(b88, _88n, P) * b88) % P;\n const b220 = (pow2(b176, _44n, P) * b44) % P;\n const b223 = (pow2(b220, _3n, P) * b3) % P;\n const t1 = (pow2(b223, _23n, P) * b22) % P;\n const t2 = (pow2(t1, _6n, P) * b2) % P;\n const root = pow2(t2, _2n, P);\n if (!Fpk1.eql(Fpk1.sqr(root), y)) throw new Error('Cannot find square root');\n return root;\n}\n\nconst Fpk1 = Field(secp256k1_CURVE.p, { sqrt: sqrtMod });\n\n/**\n * secp256k1 curve, ECDSA and ECDH methods.\n *\n * Field: `2n**256n - 2n**32n - 2n**9n - 2n**8n - 2n**7n - 2n**6n - 2n**4n - 1n`\n *\n * @example\n * ```js\n * import { secp256k1 } from '@noble/curves/secp256k1';\n * const { secretKey, publicKey } = secp256k1.keygen();\n * const msg = new TextEncoder().encode('hello');\n * const sig = secp256k1.sign(msg, secretKey);\n * const isValid = secp256k1.verify(sig, msg, publicKey) === true;\n * ```\n */\nexport const secp256k1: CurveFnWithCreate = createCurve(\n { ...secp256k1_CURVE, Fp: Fpk1, lowS: true, endo: secp256k1_ENDO },\n sha256\n);\n\n// Schnorr signatures are superior to ECDSA from above. Below is Schnorr-specific BIP0340 code.\n// https://github.com/bitcoin/bips/blob/master/bip-0340.mediawiki\n/** An object mapping tags to their tagged hash prefix of [SHA256(tag) | SHA256(tag)] */\nconst TAGGED_HASH_PREFIXES: { [tag: string]: Uint8Array } = {};\nfunction taggedHash(tag: string, ...messages: Uint8Array[]): Uint8Array {\n let tagP = TAGGED_HASH_PREFIXES[tag];\n if (tagP === undefined) {\n const tagH = sha256(utf8ToBytes(tag));\n tagP = concatBytes(tagH, tagH);\n TAGGED_HASH_PREFIXES[tag] = tagP;\n }\n return sha256(concatBytes(tagP, ...messages));\n}\n\n// ECDSA compact points are 33-byte. Schnorr is 32: we strip first byte 0x02 or 0x03\nconst pointToBytes = (point: PointType) => point.toBytes(true).slice(1);\nconst Pointk1 = /* @__PURE__ */ (() => secp256k1.Point)();\nconst hasEven = (y: bigint) => y % _2n === _0n;\n\n// Calculate point, scalar and bytes\nfunction schnorrGetExtPubKey(priv: PrivKey) {\n const { Fn, BASE } = Pointk1;\n const d_ = _normFnElement(Fn, priv);\n const p = BASE.multiply(d_); // P = d'⋅G; 0 < d' < n check is done inside\n const scalar = hasEven(p.y) ? d_ : Fn.neg(d_);\n return { scalar, bytes: pointToBytes(p) };\n}\n/**\n * lift_x from BIP340. Convert 32-byte x coordinate to elliptic curve point.\n * @returns valid point checked for being on-curve\n */\nfunction lift_x(x: bigint): PointType {\n const Fp = Fpk1;\n if (!Fp.isValidNot0(x)) throw new Error('invalid x: Fail if x ≥ p');\n const xx = Fp.create(x * x);\n const c = Fp.create(xx * x + BigInt(7)); // Let c = x³ + 7 mod p.\n let y = Fp.sqrt(c); // Let y = c^(p+1)/4 mod p. Same as sqrt().\n // Return the unique point P such that x(P) = x and\n // y(P) = y if y mod 2 = 0 or y(P) = p-y otherwise.\n if (!hasEven(y)) y = Fp.neg(y);\n const p = Pointk1.fromAffine({ x, y });\n p.assertValidity();\n return p;\n}\nconst num = bytesToNumberBE;\n/**\n * Create tagged hash, convert it to bigint, reduce modulo-n.\n */\nfunction challenge(...args: Uint8Array[]): bigint {\n return Pointk1.Fn.create(num(taggedHash('BIP0340/challenge', ...args)));\n}\n\n/**\n * Schnorr public key is just `x` coordinate of Point as per BIP340.\n */\nfunction schnorrGetPublicKey(secretKey: Hex): Uint8Array {\n return schnorrGetExtPubKey(secretKey).bytes; // d'=int(sk). Fail if d'=0 or d'≥n. Ret bytes(d'⋅G)\n}\n\n/**\n * Creates Schnorr signature as per BIP340. Verifies itself before returning anything.\n * auxRand is optional and is not the sole source of k generation: bad CSPRNG won't be dangerous.\n */\nfunction schnorrSign(message: Hex, secretKey: PrivKey, auxRand: Hex = randomBytes(32)): Uint8Array {\n const { Fn } = Pointk1;\n const m = ensureBytes('message', message);\n const { bytes: px, scalar: d } = schnorrGetExtPubKey(secretKey); // checks for isWithinCurveOrder\n const a = ensureBytes('auxRand', auxRand, 32); // Auxiliary random data a: a 32-byte array\n const t = Fn.toBytes(d ^ num(taggedHash('BIP0340/aux', a))); // Let t be the byte-wise xor of bytes(d) and hash/aux(a)\n const rand = taggedHash('BIP0340/nonce', t, px, m); // Let rand = hash/nonce(t || bytes(P) || m)\n // Let k' = int(rand) mod n. Fail if k' = 0. Let R = k'⋅G\n const { bytes: rx, scalar: k } = schnorrGetExtPubKey(rand);\n const e = challenge(rx, px, m); // Let e = int(hash/challenge(bytes(R) || bytes(P) || m)) mod n.\n const sig = new Uint8Array(64); // Let sig = bytes(R) || bytes((k + ed) mod n).\n sig.set(rx, 0);\n sig.set(Fn.toBytes(Fn.create(k + e * d)), 32);\n // If Verify(bytes(P), m, sig) (see below) returns failure, abort\n if (!schnorrVerify(sig, m, px)) throw new Error('sign: Invalid signature produced');\n return sig;\n}\n\n/**\n * Verifies Schnorr signature.\n * Will swallow errors & return false except for initial type validation of arguments.\n */\nfunction schnorrVerify(signature: Hex, message: Hex, publicKey: Hex): boolean {\n const { Fn, BASE } = Pointk1;\n const sig = ensureBytes('signature', signature, 64);\n const m = ensureBytes('message', message);\n const pub = ensureBytes('publicKey', publicKey, 32);\n try {\n const P = lift_x(num(pub)); // P = lift_x(int(pk)); fail if that fails\n const r = num(sig.subarray(0, 32)); // Let r = int(sig[0:32]); fail if r ≥ p.\n if (!inRange(r, _1n, secp256k1_CURVE.p)) return false;\n const s = num(sig.subarray(32, 64)); // Let s = int(sig[32:64]); fail if s ≥ n.\n if (!inRange(s, _1n, secp256k1_CURVE.n)) return false;\n // int(challenge(bytes(r)||bytes(P)||m))%n\n const e = challenge(Fn.toBytes(r), pointToBytes(P), m);\n // R = s⋅G - e⋅P, where -eP == (n-e)P\n const R = BASE.multiplyUnsafe(s).add(P.multiplyUnsafe(Fn.neg(e)));\n const { x, y } = R.toAffine();\n // Fail if is_infinite(R) / not has_even_y(R) / x(R) ≠ r.\n if (R.is0() || !hasEven(y) || x !== r) return false;\n return true;\n } catch (error) {\n return false;\n }\n}\n\nexport type SecpSchnorr = {\n keygen: (seed?: Uint8Array) => { secretKey: Uint8Array; publicKey: Uint8Array };\n getPublicKey: typeof schnorrGetPublicKey;\n sign: typeof schnorrSign;\n verify: typeof schnorrVerify;\n Point: WeierstrassPointCons;\n utils: {\n randomSecretKey: (seed?: Uint8Array) => Uint8Array;\n pointToBytes: (point: PointType) => Uint8Array;\n lift_x: typeof lift_x;\n taggedHash: typeof taggedHash;\n\n /** @deprecated use `randomSecretKey` */\n randomPrivateKey: (seed?: Uint8Array) => Uint8Array;\n /** @deprecated use `utils` */\n numberToBytesBE: typeof numberToBytesBE;\n /** @deprecated use `utils` */\n bytesToNumberBE: typeof bytesToNumberBE;\n /** @deprecated use `modular` */\n mod: typeof mod;\n };\n lengths: CurveLengths;\n};\n/**\n * Schnorr signatures over secp256k1.\n * https://github.com/bitcoin/bips/blob/master/bip-0340.mediawiki\n * @example\n * ```js\n * import { schnorr } from '@noble/curves/secp256k1';\n * const { secretKey, publicKey } = schnorr.keygen();\n * // const publicKey = schnorr.getPublicKey(secretKey);\n * const msg = new TextEncoder().encode('hello');\n * const sig = schnorr.sign(msg, secretKey);\n * const isValid = schnorr.verify(sig, msg, publicKey);\n * ```\n */\nexport const schnorr: SecpSchnorr = /* @__PURE__ */ (() => {\n const size = 32;\n const seedLength = 48;\n const randomSecretKey = (seed = randomBytes(seedLength)): Uint8Array => {\n return mapHashToField(seed, secp256k1_CURVE.n);\n };\n // TODO: remove\n secp256k1.utils.randomSecretKey;\n function keygen(seed?: Uint8Array) {\n const secretKey = randomSecretKey(seed);\n return { secretKey, publicKey: schnorrGetPublicKey(secretKey) };\n }\n return {\n keygen,\n getPublicKey: schnorrGetPublicKey,\n sign: schnorrSign,\n verify: schnorrVerify,\n Point: Pointk1,\n utils: {\n randomSecretKey: randomSecretKey,\n randomPrivateKey: randomSecretKey,\n taggedHash,\n\n // TODO: remove\n lift_x,\n pointToBytes,\n numberToBytesBE,\n bytesToNumberBE,\n mod,\n },\n lengths: {\n secretKey: size,\n publicKey: size,\n publicKeyHasPrefix: false,\n signature: size * 2,\n seed: seedLength,\n },\n };\n})();\n\nconst isoMap = /* @__PURE__ */ (() =>\n isogenyMap(\n Fpk1,\n [\n // xNum\n [\n '0x8e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38daaaaa8c7',\n '0x7d3d4c80bc321d5b9f315cea7fd44c5d595d2fc0bf63b92dfff1044f17c6581',\n '0x534c328d23f234e6e2a413deca25caece4506144037c40314ecbd0b53d9dd262',\n '0x8e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38daaaaa88c',\n ],\n // xDen\n [\n '0xd35771193d94918a9ca34ccbb7b640dd86cd409542f8487d9fe6b745781eb49b',\n '0xedadc6f64383dc1df7c4b2d51b54225406d36b641f5e41bbc52a56612a8c6d14',\n '0x0000000000000000000000000000000000000000000000000000000000000001', // LAST 1\n ],\n // yNum\n [\n '0x4bda12f684bda12f684bda12f684bda12f684bda12f684bda12f684b8e38e23c',\n '0xc75e0c32d5cb7c0fa9d0a54b12a0a6d5647ab046d686da6fdffc90fc201d71a3',\n '0x29a6194691f91a73715209ef6512e576722830a201be2018a765e85a9ecee931',\n '0x2f684bda12f684bda12f684bda12f684bda12f684bda12f684bda12f38e38d84',\n ],\n // yDen\n [\n '0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffff93b',\n '0x7a06534bb8bdb49fd5e9e6632722c2989467c1bfc8e8d978dfb425d2685c2573',\n '0x6484aa716545ca2cf3a70c3fa8fe337e0a3d21162f0d6299a7bf8192bfd2a76f',\n '0x0000000000000000000000000000000000000000000000000000000000000001', // LAST 1\n ],\n ].map((i) => i.map((j) => BigInt(j))) as [bigint[], bigint[], bigint[], bigint[]]\n ))();\nconst mapSWU = /* @__PURE__ */ (() =>\n mapToCurveSimpleSWU(Fpk1, {\n A: BigInt('0x3f8731abdd661adca08a5558f0f5d272e953d363cb6f0e5d405447c01a444533'),\n B: BigInt('1771'),\n Z: Fpk1.create(BigInt('-11')),\n }))();\n\n/** Hashing / encoding to secp256k1 points / field. RFC 9380 methods. */\nexport const secp256k1_hasher: H2CHasher = /* @__PURE__ */ (() =>\n createHasher(\n secp256k1.Point,\n (scalars: bigint[]) => {\n const { x, y } = mapSWU(Fpk1.create(scalars[0]));\n return isoMap(x, y);\n },\n {\n DST: 'secp256k1_XMD:SHA-256_SSWU_RO_',\n encodeDST: 'secp256k1_XMD:SHA-256_SSWU_NU_',\n p: Fpk1.ORDER,\n m: 1,\n k: 128,\n expand: 'xmd',\n hash: sha256,\n }\n ))();\n\n/** @deprecated use `import { secp256k1_hasher } from '@noble/curves/secp256k1.js';` */\nexport const hashToCurve: H2CMethod = /* @__PURE__ */ (() =>\n secp256k1_hasher.hashToCurve)();\n\n/** @deprecated use `import { secp256k1_hasher } from '@noble/curves/secp256k1.js';` */\nexport const encodeToCurve: H2CMethod = /* @__PURE__ */ (() =>\n secp256k1_hasher.encodeToCurve)();\n", "/**\n * SHA2-256 a.k.a. sha256. In JS, it is the fastest hash, even faster than Blake3.\n *\n * To break sha256 using birthday attack, attackers need to try 2^128 hashes.\n * BTC network is doing 2^70 hashes/sec (2^95 hashes/year) as per 2025.\n *\n * Check out [FIPS 180-4](https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.180-4.pdf).\n * @module\n * @deprecated\n */\nimport {\n SHA224 as SHA224n,\n sha224 as sha224n,\n SHA256 as SHA256n,\n sha256 as sha256n,\n} from './sha2.ts';\n/** @deprecated Use import from `noble/hashes/sha2` module */\nexport const SHA256: typeof SHA256n = SHA256n;\n/** @deprecated Use import from `noble/hashes/sha2` module */\nexport const sha256: typeof sha256n = sha256n;\n/** @deprecated Use import from `noble/hashes/sha2` module */\nexport const SHA224: typeof SHA224n = SHA224n;\n/** @deprecated Use import from `noble/hashes/sha2` module */\nexport const sha224: typeof sha224n = sha224n;\n", "/**\n * Deprecated module: moved from curves/abstract/utils.js to curves/utils.js\n * @module\n */\nimport * as u from '../utils.ts';\n\n/** @deprecated moved to `@noble/curves/utils.js` */\nexport type Hex = u.Hex;\n/** @deprecated moved to `@noble/curves/utils.js` */\nexport type PrivKey = u.PrivKey;\n/** @deprecated moved to `@noble/curves/utils.js` */\nexport type CHash = u.CHash;\n/** @deprecated moved to `@noble/curves/utils.js` */\nexport type FHash = u.FHash;\n\n/** @deprecated moved to `@noble/curves/utils.js` */\nexport const abytes: typeof u.abytes = u.abytes;\n/** @deprecated moved to `@noble/curves/utils.js` */\nexport const anumber: typeof u.anumber = u.anumber;\n/** @deprecated moved to `@noble/curves/utils.js` */\nexport const bytesToHex: typeof u.bytesToHex = u.bytesToHex;\n/** @deprecated moved to `@noble/curves/utils.js` */\nexport const bytesToUtf8: typeof u.bytesToUtf8 = u.bytesToUtf8;\n/** @deprecated moved to `@noble/curves/utils.js` */\nexport const concatBytes: typeof u.concatBytes = u.concatBytes;\n/** @deprecated moved to `@noble/curves/utils.js` */\nexport const hexToBytes: typeof u.hexToBytes = u.hexToBytes;\n/** @deprecated moved to `@noble/curves/utils.js` */\nexport const isBytes: typeof u.isBytes = u.isBytes;\n/** @deprecated moved to `@noble/curves/utils.js` */\nexport const randomBytes: typeof u.randomBytes = u.randomBytes;\n/** @deprecated moved to `@noble/curves/utils.js` */\nexport const utf8ToBytes: typeof u.utf8ToBytes = u.utf8ToBytes;\n\n/** @deprecated moved to `@noble/curves/utils.js` */\nexport const abool: typeof u.abool = u.abool;\n/** @deprecated moved to `@noble/curves/utils.js` */\nexport const numberToHexUnpadded: typeof u.numberToHexUnpadded = u.numberToHexUnpadded;\n/** @deprecated moved to `@noble/curves/utils.js` */\nexport const hexToNumber: typeof u.hexToNumber = u.hexToNumber;\n/** @deprecated moved to `@noble/curves/utils.js` */\nexport const bytesToNumberBE: typeof u.bytesToNumberBE = u.bytesToNumberBE;\n/** @deprecated moved to `@noble/curves/utils.js` */\nexport const bytesToNumberLE: typeof u.bytesToNumberLE = u.bytesToNumberLE;\n/** @deprecated moved to `@noble/curves/utils.js` */\nexport const numberToBytesBE: typeof u.numberToBytesBE = u.numberToBytesBE;\n/** @deprecated moved to `@noble/curves/utils.js` */\nexport const numberToBytesLE: typeof u.numberToBytesLE = u.numberToBytesLE;\n/** @deprecated moved to `@noble/curves/utils.js` */\nexport const numberToVarBytesBE: typeof u.numberToVarBytesBE = u.numberToVarBytesBE;\n/** @deprecated moved to `@noble/curves/utils.js` */\nexport const ensureBytes: typeof u.ensureBytes = u.ensureBytes;\n/** @deprecated moved to `@noble/curves/utils.js` */\nexport const equalBytes: typeof u.equalBytes = u.equalBytes;\n/** @deprecated moved to `@noble/curves/utils.js` */\nexport const copyBytes: typeof u.copyBytes = u.copyBytes;\n/** @deprecated moved to `@noble/curves/utils.js` */\nexport const asciiToBytes: typeof u.asciiToBytes = u.asciiToBytes;\n/** @deprecated moved to `@noble/curves/utils.js` */\nexport const inRange: typeof u.inRange = u.inRange;\n/** @deprecated moved to `@noble/curves/utils.js` */\nexport const aInRange: typeof u.aInRange = u.aInRange;\n/** @deprecated moved to `@noble/curves/utils.js` */\nexport const bitLen: typeof u.bitLen = u.bitLen;\n/** @deprecated moved to `@noble/curves/utils.js` */\nexport const bitGet: typeof u.bitGet = u.bitGet;\n/** @deprecated moved to `@noble/curves/utils.js` */\nexport const bitSet: typeof u.bitSet = u.bitSet;\n/** @deprecated moved to `@noble/curves/utils.js` */\nexport const bitMask: typeof u.bitMask = u.bitMask;\n/** @deprecated moved to `@noble/curves/utils.js` */\nexport const createHmacDrbg: typeof u.createHmacDrbg = u.createHmacDrbg;\n/** @deprecated moved to `@noble/curves/utils.js` */\nexport const notImplemented: typeof u.notImplemented = u.notImplemented;\n/** @deprecated moved to `@noble/curves/utils.js` */\nexport const memoized: typeof u.memoized = u.memoized;\n/** @deprecated moved to `@noble/curves/utils.js` */\nexport const validateObject: typeof u.validateObject = u.validateObject;\n/** @deprecated moved to `@noble/curves/utils.js` */\nexport const isHash: typeof u.isHash = u.isHash;\n", "import { bytesToHex } from '@noble/curves/abstract/utils';\nimport { Buffer } from 'buffer/';\n\nexport function bytesToNumber(bytes: Uint8Array): bigint {\n\treturn hexToNumber(bytesToHex(bytes));\n}\n\nexport function hexToNumber(hex: string): bigint {\n\treturn BigInt(`0x${hex}`);\n}\n\nexport function encodeBase64toUint8(base64String: string): Uint8Array {\n\treturn Buffer.from(base64String, 'base64');\n}\n", "import { ProjPointType } from '@noble/curves/abstract/weierstrass';\nimport { secp256k1 } from '@noble/curves/secp256k1';\nimport { sha256 } from '@noble/hashes/sha256';\nimport { bytesToHex, hexToBytes } from '@noble/curves/abstract/utils';\nimport { bytesToNumber, encodeBase64toUint8, hexToNumber } from '../util/utils.js';\nimport { Buffer } from 'buffer/';\n\nexport type Enumerate = Acc['length'] extends N\n\t? Acc[number]\n\t: Enumerate;\n\nexport type IntRange = Exclude, Enumerate>;\n\nexport type MintKeys = { [k: string]: Uint8Array };\n\nexport type SerializedMintKeys = {\n\t[k: string]: string;\n};\n\nexport type Keyset = {\n\tid: string;\n\tunit: string;\n\tactive: boolean;\n};\n\nexport type BlindSignature = {\n\tC_: ProjPointType;\n\tamount: number;\n\tid: string;\n};\n\nexport type SerializedBlindSignature = {\n\tC_: string;\n\tamount: number;\n\tid: string;\n};\n\nexport type Proof = {\n\tC: ProjPointType;\n\tsecret: Uint8Array;\n\tamount: number;\n\tid: string;\n\twitness?: Witness;\n};\n\nexport type SerializedProof = {\n\tC: string;\n\tsecret: string;\n\tamount: number;\n\tid: string;\n\twitness?: string;\n};\n\nexport type SerializedBlindedMessage = {\n\tB_: string;\n\tamount: number;\n\twitness?: string;\n};\n\nexport type Secret = [WellKnownSecret, SecretData];\n\nexport type WellKnownSecret = 'P2PK';\n\nexport type SecretData = {\n\tnonce: string;\n\tdata: string;\n\ttags?: Array>;\n};\n\nexport type Witness = {\n\tsignatures: Array;\n};\n\nexport type Tags = {\n\t[k: string]: string;\n};\n\nexport type SigFlag = 'SIG_INPUTS' | 'SIG_ALL';\n\nconst DOMAIN_SEPARATOR = hexToBytes('536563703235366b315f48617368546f43757276655f43617368755f');\n\nexport function hashToCurve(secret: Uint8Array): ProjPointType {\n\tconst msgToHash = sha256(Buffer.concat([DOMAIN_SEPARATOR, secret]));\n\tconst counter = new Uint32Array(1);\n\tconst maxIterations = 2 ** 16;\n\tfor (let i = 0; i < maxIterations; i++) {\n\t\tconst counterBytes = new Uint8Array(counter.buffer);\n\t\tconst hash = sha256(Buffer.concat([msgToHash, counterBytes]));\n\t\ttry {\n\t\t\treturn pointFromHex(bytesToHex(Buffer.concat([new Uint8Array([0x02]), hash])));\n\t\t} catch (error) {\n\t\t\tcounter[0]++;\n\t\t}\n\t}\n\tthrow new Error('No valid point found');\n}\n\nexport function pointFromHex(hex: string) {\n\treturn secp256k1.ProjectivePoint.fromHex(hex);\n}\n\nexport const getKeysetIdInt = (keysetId: string): bigint => {\n\tlet keysetIdInt: bigint;\n\tif (/^[a-fA-F0-9]+$/.test(keysetId)) {\n\t\tkeysetIdInt = hexToNumber(keysetId) % BigInt(2 ** 31 - 1);\n\t} else {\n\t\t//legacy keyset compatibility\n\t\tkeysetIdInt = bytesToNumber(encodeBase64toUint8(keysetId)) % BigInt(2 ** 31 - 1);\n\t}\n\treturn keysetIdInt;\n};\n\nexport function createRandomPrivateKey() {\n\treturn secp256k1.utils.randomPrivateKey();\n}\n\nexport function serializeMintKeys(mintKeys: MintKeys): SerializedMintKeys {\n\tconst serializedMintKeys: SerializedMintKeys = {};\n\tObject.keys(mintKeys).forEach((p) => {\n\t\tserializedMintKeys[p] = bytesToHex(mintKeys[p]);\n\t});\n\treturn serializedMintKeys;\n}\n\nexport function deserializeMintKeys(serializedMintKeys: SerializedMintKeys): MintKeys {\n\tconst mintKeys: MintKeys = {};\n\tObject.keys(serializedMintKeys).forEach((p) => {\n\t\tmintKeys[p] = hexToBytes(serializedMintKeys[p]);\n\t});\n\treturn mintKeys;\n}\n\nexport function deriveKeysetId(keys: MintKeys): string {\n\tconst KEYSET_VERSION = '00';\n\tconst mapBigInt = (k: [string, string]): [bigint, string] => {\n\t\treturn [BigInt(k[0]), k[1]];\n\t};\n\tconst pubkeysConcat = Object.entries(serializeMintKeys(keys))\n\t\t.map(mapBigInt)\n\t\t.sort((a, b) => (a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : 0))\n\t\t.map(([, pubKey]) => hexToBytes(pubKey))\n\t\t.reduce((prev, curr) => mergeUInt8Arrays(prev, curr), new Uint8Array());\n\tconst hash = sha256(pubkeysConcat);\n\tconst hashHex = Buffer.from(hash).toString('hex').slice(0, 14);\n\treturn '00' + hashHex;\n}\n\nfunction mergeUInt8Arrays(a1: Uint8Array, a2: Uint8Array): Uint8Array {\n\t// sum of individual array lengths\n\tconst mergedArray = new Uint8Array(a1.length + a2.length);\n\tmergedArray.set(a1);\n\tmergedArray.set(a2, a1.length);\n\treturn mergedArray;\n}\n", "import { ProjPointType } from '@noble/curves/abstract/weierstrass';\nimport { secp256k1 } from '@noble/curves/secp256k1';\nimport { bytesToHex, hexToBytes, randomBytes } from '@noble/hashes/utils';\nimport { bytesToNumber } from '../util/utils.js';\nimport type {\n\tBlindSignature,\n\tProof,\n\tSerializedBlindedMessage,\n\tSerializedProof\n} from '../common/index.js';\nimport { hashToCurve, pointFromHex } from '../common/index.js';\nimport { Witness } from '../common/index';\n\nexport type BlindedMessage = {\n\tB_: ProjPointType;\n\tr: bigint;\n\tsecret: Uint8Array;\n};\n\nexport function createRandomBlindedMessage(): BlindedMessage {\n\treturn blindMessage(randomBytes(32));\n}\n\nexport function blindMessage(secret: Uint8Array, r?: bigint): BlindedMessage {\n\tconst Y = hashToCurve(secret);\n\tif (!r) {\n\t\tr = bytesToNumber(secp256k1.utils.randomPrivateKey());\n\t}\n\tconst rG = secp256k1.ProjectivePoint.BASE.multiply(r);\n\tconst B_ = Y.add(rG);\n\treturn { B_, r, secret };\n}\n\nexport function unblindSignature(\n\tC_: ProjPointType,\n\tr: bigint,\n\tA: ProjPointType\n): ProjPointType {\n\tconst C = C_.subtract(A.multiply(r));\n\treturn C;\n}\n\nexport function constructProofFromPromise(\n\tpromise: BlindSignature,\n\tr: bigint,\n\tsecret: Uint8Array,\n\tkey: ProjPointType\n): Proof {\n\tconst A = key;\n\tconst C = unblindSignature(promise.C_, r, A);\n\tconst proof = {\n\t\tid: promise.id,\n\t\tamount: promise.amount,\n\t\tsecret,\n\t\tC\n\t};\n\treturn proof;\n}\n\nexport const serializeProof = (proof: Proof): SerializedProof => {\n\treturn {\n\t\tamount: proof.amount,\n\t\tC: proof.C.toHex(true),\n\t\tid: proof.id,\n\t\tsecret: new TextDecoder().decode(proof.secret),\n\t\twitness: JSON.stringify(proof.witness)\n\t};\n};\n\nexport const deserializeProof = (proof: SerializedProof): Proof => {\n\treturn {\n\t\tamount: proof.amount,\n\t\tC: pointFromHex(proof.C),\n\t\tid: proof.id,\n\t\tsecret: new TextEncoder().encode(proof.secret),\n\t\twitness: proof.witness?JSON.parse(proof.witness):undefined\n\t};\n};\nexport const serializeBlindedMessage = (\n\tbm: BlindedMessage,\n\tamount: number\n): SerializedBlindedMessage => {\n\treturn {\n\t\tB_: bm.B_.toHex(true),\n\t\tamount: amount\n\t};\n};\n", "/**\n\nSHA1 (RFC 3174), MD5 (RFC 1321) and RIPEMD160 (RFC 2286) legacy, weak hash functions.\nDon't use them in a new protocol. What \"weak\" means:\n\n- Collisions can be made with 2^18 effort in MD5, 2^60 in SHA1, 2^80 in RIPEMD160.\n- No practical pre-image attacks (only theoretical, 2^123.4)\n- HMAC seems kinda ok: https://datatracker.ietf.org/doc/html/rfc6151\n * @module\n */\nimport { Chi, HashMD, Maj } from './_md.ts';\nimport { type CHash, clean, createHasher, rotl } from './utils.ts';\n\n/** Initial SHA1 state */\nconst SHA1_IV = /* @__PURE__ */ Uint32Array.from([\n 0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0,\n]);\n\n// Reusable temporary buffer\nconst SHA1_W = /* @__PURE__ */ new Uint32Array(80);\n\n/** SHA1 legacy hash class. */\nexport class SHA1 extends HashMD {\n private A = SHA1_IV[0] | 0;\n private B = SHA1_IV[1] | 0;\n private C = SHA1_IV[2] | 0;\n private D = SHA1_IV[3] | 0;\n private E = SHA1_IV[4] | 0;\n\n constructor() {\n super(64, 20, 8, false);\n }\n protected get(): [number, number, number, number, number] {\n const { A, B, C, D, E } = this;\n return [A, B, C, D, E];\n }\n protected set(A: number, B: number, C: number, D: number, E: number): void {\n this.A = A | 0;\n this.B = B | 0;\n this.C = C | 0;\n this.D = D | 0;\n this.E = E | 0;\n }\n protected process(view: DataView, offset: number): void {\n for (let i = 0; i < 16; i++, offset += 4) SHA1_W[i] = view.getUint32(offset, false);\n for (let i = 16; i < 80; i++)\n SHA1_W[i] = rotl(SHA1_W[i - 3] ^ SHA1_W[i - 8] ^ SHA1_W[i - 14] ^ SHA1_W[i - 16], 1);\n // Compression function main loop, 80 rounds\n let { A, B, C, D, E } = this;\n for (let i = 0; i < 80; i++) {\n let F, K;\n if (i < 20) {\n F = Chi(B, C, D);\n K = 0x5a827999;\n } else if (i < 40) {\n F = B ^ C ^ D;\n K = 0x6ed9eba1;\n } else if (i < 60) {\n F = Maj(B, C, D);\n K = 0x8f1bbcdc;\n } else {\n F = B ^ C ^ D;\n K = 0xca62c1d6;\n }\n const T = (rotl(A, 5) + F + E + K + SHA1_W[i]) | 0;\n E = D;\n D = C;\n C = rotl(B, 30);\n B = A;\n A = T;\n }\n // Add the compressed chunk to the current hash value\n A = (A + this.A) | 0;\n B = (B + this.B) | 0;\n C = (C + this.C) | 0;\n D = (D + this.D) | 0;\n E = (E + this.E) | 0;\n this.set(A, B, C, D, E);\n }\n protected roundClean(): void {\n clean(SHA1_W);\n }\n destroy(): void {\n this.set(0, 0, 0, 0, 0);\n clean(this.buffer);\n }\n}\n\n/** SHA1 (RFC 3174) legacy hash function. It was cryptographically broken. */\nexport const sha1: CHash = /* @__PURE__ */ createHasher(() => new SHA1());\n\n/** Per-round constants */\nconst p32 = /* @__PURE__ */ Math.pow(2, 32);\nconst K = /* @__PURE__ */ Array.from({ length: 64 }, (_, i) =>\n Math.floor(p32 * Math.abs(Math.sin(i + 1)))\n);\n\n/** md5 initial state: same as sha1, but 4 u32 instead of 5. */\nconst MD5_IV = /* @__PURE__ */ SHA1_IV.slice(0, 4);\n\n// Reusable temporary buffer\nconst MD5_W = /* @__PURE__ */ new Uint32Array(16);\n/** MD5 legacy hash class. */\nexport class MD5 extends HashMD {\n private A = MD5_IV[0] | 0;\n private B = MD5_IV[1] | 0;\n private C = MD5_IV[2] | 0;\n private D = MD5_IV[3] | 0;\n\n constructor() {\n super(64, 16, 8, true);\n }\n protected get(): [number, number, number, number] {\n const { A, B, C, D } = this;\n return [A, B, C, D];\n }\n protected set(A: number, B: number, C: number, D: number): void {\n this.A = A | 0;\n this.B = B | 0;\n this.C = C | 0;\n this.D = D | 0;\n }\n protected process(view: DataView, offset: number): void {\n for (let i = 0; i < 16; i++, offset += 4) MD5_W[i] = view.getUint32(offset, true);\n // Compression function main loop, 64 rounds\n let { A, B, C, D } = this;\n for (let i = 0; i < 64; i++) {\n let F, g, s;\n if (i < 16) {\n F = Chi(B, C, D);\n g = i;\n s = [7, 12, 17, 22];\n } else if (i < 32) {\n F = Chi(D, B, C);\n g = (5 * i + 1) % 16;\n s = [5, 9, 14, 20];\n } else if (i < 48) {\n F = B ^ C ^ D;\n g = (3 * i + 5) % 16;\n s = [4, 11, 16, 23];\n } else {\n F = C ^ (B | ~D);\n g = (7 * i) % 16;\n s = [6, 10, 15, 21];\n }\n F = F + A + K[i] + MD5_W[g];\n A = D;\n D = C;\n C = B;\n B = B + rotl(F, s[i % 4]);\n }\n // Add the compressed chunk to the current hash value\n A = (A + this.A) | 0;\n B = (B + this.B) | 0;\n C = (C + this.C) | 0;\n D = (D + this.D) | 0;\n this.set(A, B, C, D);\n }\n protected roundClean(): void {\n clean(MD5_W);\n }\n destroy(): void {\n this.set(0, 0, 0, 0);\n clean(this.buffer);\n }\n}\n\n/**\n * MD5 (RFC 1321) legacy hash function. It was cryptographically broken.\n * MD5 architecture is similar to SHA1, with some differences:\n * - Reduced output length: 16 bytes (128 bit) instead of 20\n * - 64 rounds, instead of 80\n * - Little-endian: could be faster, but will require more code\n * - Non-linear index selection: huge speed-up for unroll\n * - Per round constants: more memory accesses, additional speed-up for unroll\n */\nexport const md5: CHash = /* @__PURE__ */ createHasher(() => new MD5());\n\n// RIPEMD-160\n\nconst Rho160 = /* @__PURE__ */ Uint8Array.from([\n 7, 4, 13, 1, 10, 6, 15, 3, 12, 0, 9, 5, 2, 14, 11, 8,\n]);\nconst Id160 = /* @__PURE__ */ (() => Uint8Array.from(new Array(16).fill(0).map((_, i) => i)))();\nconst Pi160 = /* @__PURE__ */ (() => Id160.map((i) => (9 * i + 5) % 16))();\nconst idxLR = /* @__PURE__ */ (() => {\n const L = [Id160];\n const R = [Pi160];\n const res = [L, R];\n for (let i = 0; i < 4; i++) for (let j of res) j.push(j[i].map((k) => Rho160[k]));\n return res;\n})();\nconst idxL = /* @__PURE__ */ (() => idxLR[0])();\nconst idxR = /* @__PURE__ */ (() => idxLR[1])();\n// const [idxL, idxR] = idxLR;\n\nconst shifts160 = /* @__PURE__ */ [\n [11, 14, 15, 12, 5, 8, 7, 9, 11, 13, 14, 15, 6, 7, 9, 8],\n [12, 13, 11, 15, 6, 9, 9, 7, 12, 15, 11, 13, 7, 8, 7, 7],\n [13, 15, 14, 11, 7, 7, 6, 8, 13, 14, 13, 12, 5, 5, 6, 9],\n [14, 11, 12, 14, 8, 6, 5, 5, 15, 12, 15, 14, 9, 9, 8, 6],\n [15, 12, 13, 13, 9, 5, 8, 6, 14, 11, 12, 11, 8, 6, 5, 5],\n].map((i) => Uint8Array.from(i));\nconst shiftsL160 = /* @__PURE__ */ idxL.map((idx, i) => idx.map((j) => shifts160[i][j]));\nconst shiftsR160 = /* @__PURE__ */ idxR.map((idx, i) => idx.map((j) => shifts160[i][j]));\nconst Kl160 = /* @__PURE__ */ Uint32Array.from([\n 0x00000000, 0x5a827999, 0x6ed9eba1, 0x8f1bbcdc, 0xa953fd4e,\n]);\nconst Kr160 = /* @__PURE__ */ Uint32Array.from([\n 0x50a28be6, 0x5c4dd124, 0x6d703ef3, 0x7a6d76e9, 0x00000000,\n]);\n// It's called f() in spec.\nfunction ripemd_f(group: number, x: number, y: number, z: number): number {\n if (group === 0) return x ^ y ^ z;\n if (group === 1) return (x & y) | (~x & z);\n if (group === 2) return (x | ~y) ^ z;\n if (group === 3) return (x & z) | (y & ~z);\n return x ^ (y | ~z);\n}\n// Reusable temporary buffer\nconst BUF_160 = /* @__PURE__ */ new Uint32Array(16);\nexport class RIPEMD160 extends HashMD {\n private h0 = 0x67452301 | 0;\n private h1 = 0xefcdab89 | 0;\n private h2 = 0x98badcfe | 0;\n private h3 = 0x10325476 | 0;\n private h4 = 0xc3d2e1f0 | 0;\n\n constructor() {\n super(64, 20, 8, true);\n }\n protected get(): [number, number, number, number, number] {\n const { h0, h1, h2, h3, h4 } = this;\n return [h0, h1, h2, h3, h4];\n }\n protected set(h0: number, h1: number, h2: number, h3: number, h4: number): void {\n this.h0 = h0 | 0;\n this.h1 = h1 | 0;\n this.h2 = h2 | 0;\n this.h3 = h3 | 0;\n this.h4 = h4 | 0;\n }\n protected process(view: DataView, offset: number): void {\n for (let i = 0; i < 16; i++, offset += 4) BUF_160[i] = view.getUint32(offset, true);\n // prettier-ignore\n let al = this.h0 | 0, ar = al,\n bl = this.h1 | 0, br = bl,\n cl = this.h2 | 0, cr = cl,\n dl = this.h3 | 0, dr = dl,\n el = this.h4 | 0, er = el;\n\n // Instead of iterating 0 to 80, we split it into 5 groups\n // And use the groups in constants, functions, etc. Much simpler\n for (let group = 0; group < 5; group++) {\n const rGroup = 4 - group;\n const hbl = Kl160[group], hbr = Kr160[group]; // prettier-ignore\n const rl = idxL[group], rr = idxR[group]; // prettier-ignore\n const sl = shiftsL160[group], sr = shiftsR160[group]; // prettier-ignore\n for (let i = 0; i < 16; i++) {\n const tl = (rotl(al + ripemd_f(group, bl, cl, dl) + BUF_160[rl[i]] + hbl, sl[i]) + el) | 0;\n al = el, el = dl, dl = rotl(cl, 10) | 0, cl = bl, bl = tl; // prettier-ignore\n }\n // 2 loops are 10% faster\n for (let i = 0; i < 16; i++) {\n const tr = (rotl(ar + ripemd_f(rGroup, br, cr, dr) + BUF_160[rr[i]] + hbr, sr[i]) + er) | 0;\n ar = er, er = dr, dr = rotl(cr, 10) | 0, cr = br, br = tr; // prettier-ignore\n }\n }\n // Add the compressed chunk to the current hash value\n this.set(\n (this.h1 + cl + dr) | 0,\n (this.h2 + dl + er) | 0,\n (this.h3 + el + ar) | 0,\n (this.h4 + al + br) | 0,\n (this.h0 + bl + cr) | 0\n );\n }\n protected roundClean(): void {\n clean(BUF_160);\n }\n destroy(): void {\n this.destroyed = true;\n clean(this.buffer);\n this.set(0, 0, 0, 0, 0);\n }\n}\n\n/**\n * RIPEMD-160 - a legacy hash function from 1990s.\n * * https://homes.esat.kuleuven.be/~bosselae/ripemd160.html\n * * https://homes.esat.kuleuven.be/~bosselae/ripemd160/pdf/AB-9601/AB-9601.pdf\n */\nexport const ripemd160: CHash = /* @__PURE__ */ createHasher(() => new RIPEMD160());\n", "/*! scure-base - MIT License (c) 2022 Paul Miller (paulmillr.com) */\n\nexport interface Coder {\n encode(from: F): T;\n decode(to: T): F;\n}\n\nexport interface BytesCoder extends Coder {\n encode: (data: Uint8Array) => string;\n decode: (str: string) => Uint8Array;\n}\n\nfunction isBytes(a: unknown): a is Uint8Array {\n return a instanceof Uint8Array || (ArrayBuffer.isView(a) && a.constructor.name === 'Uint8Array');\n}\n/** Asserts something is Uint8Array. */\nfunction abytes(b: Uint8Array | undefined, ...lengths: number[]): void {\n if (!isBytes(b)) throw new Error('Uint8Array expected');\n if (lengths.length > 0 && !lengths.includes(b.length))\n throw new Error('Uint8Array expected of length ' + lengths + ', got length=' + b.length);\n}\n\nfunction isArrayOf(isString: boolean, arr: any[]) {\n if (!Array.isArray(arr)) return false;\n if (arr.length === 0) return true;\n if (isString) {\n return arr.every((item) => typeof item === 'string');\n } else {\n return arr.every((item) => Number.isSafeInteger(item));\n }\n}\n\n// no abytes: seems to have 10% slowdown. Why?!\n\nfunction afn(input: Function): input is Function {\n if (typeof input !== 'function') throw new Error('function expected');\n return true;\n}\n\nfunction astr(label: string, input: unknown): input is string {\n if (typeof input !== 'string') throw new Error(`${label}: string expected`);\n return true;\n}\n\nfunction anumber(n: number): void {\n if (!Number.isSafeInteger(n)) throw new Error(`invalid integer: ${n}`);\n}\n\nfunction aArr(input: any[]) {\n if (!Array.isArray(input)) throw new Error('array expected');\n}\nfunction astrArr(label: string, input: string[]) {\n if (!isArrayOf(true, input)) throw new Error(`${label}: array of strings expected`);\n}\nfunction anumArr(label: string, input: number[]) {\n if (!isArrayOf(false, input)) throw new Error(`${label}: array of numbers expected`);\n}\n\n// TODO: some recusive type inference so it would check correct order of input/output inside rest?\n// like , , \ntype Chain = [Coder, ...Coder[]];\n// Extract info from Coder type\ntype Input = F extends Coder ? T : never;\ntype Output = F extends Coder ? T : never;\n// Generic function for arrays\ntype First = T extends [infer U, ...any[]] ? U : never;\ntype Last = T extends [...any[], infer U] ? U : never;\ntype Tail = T extends [any, ...infer U] ? U : never;\n\ntype AsChain> = {\n // C[K] = Coder, Input>\n [K in keyof C]: Coder, Input>;\n};\n\n/**\n * @__NO_SIDE_EFFECTS__\n */\nfunction chain>(...args: T): Coder>, Output>> {\n const id = (a: any) => a;\n // Wrap call in closure so JIT can inline calls\n const wrap = (a: any, b: any) => (c: any) => a(b(c));\n // Construct chain of args[-1].encode(args[-2].encode([...]))\n const encode = args.map((x) => x.encode).reduceRight(wrap, id);\n // Construct chain of args[0].decode(args[1].decode(...))\n const decode = args.map((x) => x.decode).reduce(wrap, id);\n return { encode, decode };\n}\n\n/**\n * Encodes integer radix representation to array of strings using alphabet and back.\n * Could also be array of strings.\n * @__NO_SIDE_EFFECTS__\n */\nfunction alphabet(letters: string | string[]): Coder {\n // mapping 1 to \"b\"\n const lettersA = typeof letters === 'string' ? letters.split('') : letters;\n const len = lettersA.length;\n astrArr('alphabet', lettersA);\n\n // mapping \"b\" to 1\n const indexes = new Map(lettersA.map((l, i) => [l, i]));\n return {\n encode: (digits: number[]) => {\n aArr(digits);\n return digits.map((i) => {\n if (!Number.isSafeInteger(i) || i < 0 || i >= len)\n throw new Error(\n `alphabet.encode: digit index outside alphabet \"${i}\". Allowed: ${letters}`\n );\n return lettersA[i]!;\n });\n },\n decode: (input: string[]): number[] => {\n aArr(input);\n return input.map((letter) => {\n astr('alphabet.decode', letter);\n const i = indexes.get(letter);\n if (i === undefined) throw new Error(`Unknown letter: \"${letter}\". Allowed: ${letters}`);\n return i;\n });\n },\n };\n}\n\n/**\n * @__NO_SIDE_EFFECTS__\n */\nfunction join(separator = ''): Coder {\n astr('join', separator);\n return {\n encode: (from) => {\n astrArr('join.decode', from);\n return from.join(separator);\n },\n decode: (to) => {\n astr('join.decode', to);\n return to.split(separator);\n },\n };\n}\n\n/**\n * Pad strings array so it has integer number of bits\n * @__NO_SIDE_EFFECTS__\n */\nfunction padding(bits: number, chr = '='): Coder {\n anumber(bits);\n astr('padding', chr);\n return {\n encode(data: string[]): string[] {\n astrArr('padding.encode', data);\n while ((data.length * bits) % 8) data.push(chr);\n return data;\n },\n decode(input: string[]): string[] {\n astrArr('padding.decode', input);\n let end = input.length;\n if ((end * bits) % 8)\n throw new Error('padding: invalid, string should have whole number of bytes');\n for (; end > 0 && input[end - 1] === chr; end--) {\n const last = end - 1;\n const byte = last * bits;\n if (byte % 8 === 0) throw new Error('padding: invalid, string has too much padding');\n }\n return input.slice(0, end);\n },\n };\n}\n\n/**\n * @__NO_SIDE_EFFECTS__\n */\nfunction normalize(fn: (val: T) => T): Coder {\n afn(fn);\n return { encode: (from: T) => from, decode: (to: T) => fn(to) };\n}\n\n/**\n * Slow: O(n^2) time complexity\n */\nfunction convertRadix(data: number[], from: number, to: number): number[] {\n // base 1 is impossible\n if (from < 2) throw new Error(`convertRadix: invalid from=${from}, base cannot be less than 2`);\n if (to < 2) throw new Error(`convertRadix: invalid to=${to}, base cannot be less than 2`);\n aArr(data);\n if (!data.length) return [];\n let pos = 0;\n const res = [];\n const digits = Array.from(data, (d) => {\n anumber(d);\n if (d < 0 || d >= from) throw new Error(`invalid integer: ${d}`);\n return d;\n });\n const dlen = digits.length;\n while (true) {\n let carry = 0;\n let done = true;\n for (let i = pos; i < dlen; i++) {\n const digit = digits[i]!;\n const fromCarry = from * carry;\n const digitBase = fromCarry + digit;\n if (\n !Number.isSafeInteger(digitBase) ||\n fromCarry / from !== carry ||\n digitBase - digit !== fromCarry\n ) {\n throw new Error('convertRadix: carry overflow');\n }\n const div = digitBase / to;\n carry = digitBase % to;\n const rounded = Math.floor(div);\n digits[i] = rounded;\n if (!Number.isSafeInteger(rounded) || rounded * to + carry !== digitBase)\n throw new Error('convertRadix: carry overflow');\n if (!done) continue;\n else if (!rounded) pos = i;\n else done = false;\n }\n res.push(carry);\n if (done) break;\n }\n for (let i = 0; i < data.length - 1 && data[i] === 0; i++) res.push(0);\n return res.reverse();\n}\n\nconst gcd = (a: number, b: number): number => (b === 0 ? a : gcd(b, a % b));\nconst radix2carry = /* @__NO_SIDE_EFFECTS__ */ (from: number, to: number) =>\n from + (to - gcd(from, to));\nconst powers: number[] = /* @__PURE__ */ (() => {\n let res = [];\n for (let i = 0; i < 40; i++) res.push(2 ** i);\n return res;\n})();\n/**\n * Implemented with numbers, because BigInt is 5x slower\n */\nfunction convertRadix2(data: number[], from: number, to: number, padding: boolean): number[] {\n aArr(data);\n if (from <= 0 || from > 32) throw new Error(`convertRadix2: wrong from=${from}`);\n if (to <= 0 || to > 32) throw new Error(`convertRadix2: wrong to=${to}`);\n if (radix2carry(from, to) > 32) {\n throw new Error(\n `convertRadix2: carry overflow from=${from} to=${to} carryBits=${radix2carry(from, to)}`\n );\n }\n let carry = 0;\n let pos = 0; // bitwise position in current element\n const max = powers[from]!;\n const mask = powers[to]! - 1;\n const res: number[] = [];\n for (const n of data) {\n anumber(n);\n if (n >= max) throw new Error(`convertRadix2: invalid data word=${n} from=${from}`);\n carry = (carry << from) | n;\n if (pos + from > 32) throw new Error(`convertRadix2: carry overflow pos=${pos} from=${from}`);\n pos += from;\n for (; pos >= to; pos -= to) res.push(((carry >> (pos - to)) & mask) >>> 0);\n const pow = powers[pos];\n if (pow === undefined) throw new Error('invalid carry');\n carry &= pow - 1; // clean carry, otherwise it will cause overflow\n }\n carry = (carry << (to - pos)) & mask;\n if (!padding && pos >= from) throw new Error('Excess padding');\n if (!padding && carry > 0) throw new Error(`Non-zero padding: ${carry}`);\n if (padding && pos > 0) res.push(carry >>> 0);\n return res;\n}\n\n/**\n * @__NO_SIDE_EFFECTS__\n */\nfunction radix(num: number): Coder {\n anumber(num);\n const _256 = 2 ** 8;\n return {\n encode: (bytes: Uint8Array) => {\n if (!isBytes(bytes)) throw new Error('radix.encode input should be Uint8Array');\n return convertRadix(Array.from(bytes), _256, num);\n },\n decode: (digits: number[]) => {\n anumArr('radix.decode', digits);\n return Uint8Array.from(convertRadix(digits, num, _256));\n },\n };\n}\n\n/**\n * If both bases are power of same number (like `2**8 <-> 2**64`),\n * there is a linear algorithm. For now we have implementation for power-of-two bases only.\n * @__NO_SIDE_EFFECTS__\n */\nfunction radix2(bits: number, revPadding = false): Coder {\n anumber(bits);\n if (bits <= 0 || bits > 32) throw new Error('radix2: bits should be in (0..32]');\n if (radix2carry(8, bits) > 32 || radix2carry(bits, 8) > 32)\n throw new Error('radix2: carry overflow');\n return {\n encode: (bytes: Uint8Array) => {\n if (!isBytes(bytes)) throw new Error('radix2.encode input should be Uint8Array');\n return convertRadix2(Array.from(bytes), 8, bits, !revPadding);\n },\n decode: (digits: number[]) => {\n anumArr('radix2.decode', digits);\n return Uint8Array.from(convertRadix2(digits, bits, 8, revPadding));\n },\n };\n}\n\ntype ArgumentTypes = F extends (...args: infer A) => any ? A : never;\nfunction unsafeWrapper any>(fn: T) {\n afn(fn);\n return function (...args: ArgumentTypes): ReturnType | void {\n try {\n return fn.apply(null, args);\n } catch (e) {}\n };\n}\n\nfunction checksum(\n len: number,\n fn: (data: Uint8Array) => Uint8Array\n): Coder {\n anumber(len);\n afn(fn);\n return {\n encode(data: Uint8Array) {\n if (!isBytes(data)) throw new Error('checksum.encode: input should be Uint8Array');\n const sum = fn(data).slice(0, len);\n const res = new Uint8Array(data.length + len);\n res.set(data);\n res.set(sum, data.length);\n return res;\n },\n decode(data: Uint8Array) {\n if (!isBytes(data)) throw new Error('checksum.decode: input should be Uint8Array');\n const payload = data.slice(0, -len);\n const oldChecksum = data.slice(-len);\n const newChecksum = fn(payload).slice(0, len);\n for (let i = 0; i < len; i++)\n if (newChecksum[i] !== oldChecksum[i]) throw new Error('Invalid checksum');\n return payload;\n },\n };\n}\n\n// prettier-ignore\nexport const utils: { alphabet: typeof alphabet; chain: typeof chain; checksum: typeof checksum; convertRadix: typeof convertRadix; convertRadix2: typeof convertRadix2; radix: typeof radix; radix2: typeof radix2; join: typeof join; padding: typeof padding; } = {\n alphabet, chain, checksum, convertRadix, convertRadix2, radix, radix2, join, padding,\n};\n\n// RFC 4648 aka RFC 3548\n// ---------------------\n\n/**\n * base16 encoding from RFC 4648.\n * @example\n * ```js\n * base16.encode(Uint8Array.from([0x12, 0xab]));\n * // => '12AB'\n * ```\n */\nexport const base16: BytesCoder = chain(radix2(4), alphabet('0123456789ABCDEF'), join(''));\n\n/**\n * base32 encoding from RFC 4648. Has padding.\n * Use `base32nopad` for unpadded version.\n * Also check out `base32hex`, `base32hexnopad`, `base32crockford`.\n * @example\n * ```js\n * base32.encode(Uint8Array.from([0x12, 0xab]));\n * // => 'CKVQ===='\n * base32.decode('CKVQ====');\n * // => Uint8Array.from([0x12, 0xab])\n * ```\n */\nexport const base32: BytesCoder = chain(\n radix2(5),\n alphabet('ABCDEFGHIJKLMNOPQRSTUVWXYZ234567'),\n padding(5),\n join('')\n);\n\n/**\n * base32 encoding from RFC 4648. No padding.\n * Use `base32` for padded version.\n * Also check out `base32hex`, `base32hexnopad`, `base32crockford`.\n * @example\n * ```js\n * base32nopad.encode(Uint8Array.from([0x12, 0xab]));\n * // => 'CKVQ'\n * base32nopad.decode('CKVQ');\n * // => Uint8Array.from([0x12, 0xab])\n * ```\n */\nexport const base32nopad: BytesCoder = chain(\n radix2(5),\n alphabet('ABCDEFGHIJKLMNOPQRSTUVWXYZ234567'),\n join('')\n);\n/**\n * base32 encoding from RFC 4648. Padded. Compared to ordinary `base32`, slightly different alphabet.\n * Use `base32hexnopad` for unpadded version.\n * @example\n * ```js\n * base32hex.encode(Uint8Array.from([0x12, 0xab]));\n * // => '2ALG===='\n * base32hex.decode('2ALG====');\n * // => Uint8Array.from([0x12, 0xab])\n * ```\n */\nexport const base32hex: BytesCoder = chain(\n radix2(5),\n alphabet('0123456789ABCDEFGHIJKLMNOPQRSTUV'),\n padding(5),\n join('')\n);\n\n/**\n * base32 encoding from RFC 4648. No padding. Compared to ordinary `base32`, slightly different alphabet.\n * Use `base32hex` for padded version.\n * @example\n * ```js\n * base32hexnopad.encode(Uint8Array.from([0x12, 0xab]));\n * // => '2ALG'\n * base32hexnopad.decode('2ALG');\n * // => Uint8Array.from([0x12, 0xab])\n * ```\n */\nexport const base32hexnopad: BytesCoder = chain(\n radix2(5),\n alphabet('0123456789ABCDEFGHIJKLMNOPQRSTUV'),\n join('')\n);\n/**\n * base32 encoding from RFC 4648. Doug Crockford's version.\n * https://www.crockford.com/base32.html\n * @example\n * ```js\n * base32crockford.encode(Uint8Array.from([0x12, 0xab]));\n * // => '2ANG'\n * base32crockford.decode('2ANG');\n * // => Uint8Array.from([0x12, 0xab])\n * ```\n */\nexport const base32crockford: BytesCoder = chain(\n radix2(5),\n alphabet('0123456789ABCDEFGHJKMNPQRSTVWXYZ'),\n join(''),\n normalize((s: string) => s.toUpperCase().replace(/O/g, '0').replace(/[IL]/g, '1'))\n);\n\n// Built-in base64 conversion https://caniuse.com/mdn-javascript_builtins_uint8array_frombase64\n// prettier-ignore\nconst hasBase64Builtin: boolean = /* @__PURE__ */ (() =>\n typeof (Uint8Array as any).from([]).toBase64 === 'function' &&\n typeof (Uint8Array as any).fromBase64 === 'function')();\n\nconst decodeBase64Builtin = (s: string, isUrl: boolean) => {\n astr('base64', s);\n const re = isUrl ? /^[A-Za-z0-9=_-]+$/ : /^[A-Za-z0-9=+/]+$/;\n const alphabet = isUrl ? 'base64url' : 'base64';\n if (s.length > 0 && !re.test(s)) throw new Error('invalid base64');\n return (Uint8Array as any).fromBase64(s, { alphabet, lastChunkHandling: 'strict' });\n};\n\n/**\n * base64 from RFC 4648. Padded.\n * Use `base64nopad` for unpadded version.\n * Also check out `base64url`, `base64urlnopad`.\n * Falls back to built-in function, when available.\n * @example\n * ```js\n * base64.encode(Uint8Array.from([0x12, 0xab]));\n * // => 'Eqs='\n * base64.decode('Eqs=');\n * // => Uint8Array.from([0x12, 0xab])\n * ```\n */\n// prettier-ignore\nexport const base64: BytesCoder = hasBase64Builtin ? {\n encode(b) { abytes(b); return (b as any).toBase64(); },\n decode(s) { return decodeBase64Builtin(s, false); },\n} : chain(\n radix2(6),\n alphabet('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'),\n padding(6),\n join('')\n);\n/**\n * base64 from RFC 4648. No padding.\n * Use `base64` for padded version.\n * @example\n * ```js\n * base64nopad.encode(Uint8Array.from([0x12, 0xab]));\n * // => 'Eqs'\n * base64nopad.decode('Eqs');\n * // => Uint8Array.from([0x12, 0xab])\n * ```\n */\nexport const base64nopad: BytesCoder = chain(\n radix2(6),\n alphabet('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'),\n join('')\n);\n\n/**\n * base64 from RFC 4648, using URL-safe alphabet. Padded.\n * Use `base64urlnopad` for unpadded version.\n * Falls back to built-in function, when available.\n * @example\n * ```js\n * base64url.encode(Uint8Array.from([0x12, 0xab]));\n * // => 'Eqs='\n * base64url.decode('Eqs=');\n * // => Uint8Array.from([0x12, 0xab])\n * ```\n */\n// prettier-ignore\nexport const base64url: BytesCoder = hasBase64Builtin ? {\n encode(b) { abytes(b); return (b as any).toBase64({ alphabet: 'base64url' }); },\n decode(s) { return decodeBase64Builtin(s, true); },\n} : chain(\n radix2(6),\n alphabet('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_'),\n padding(6),\n join('')\n);\n\n/**\n * base64 from RFC 4648, using URL-safe alphabet. No padding.\n * Use `base64url` for padded version.\n * @example\n * ```js\n * base64urlnopad.encode(Uint8Array.from([0x12, 0xab]));\n * // => 'Eqs'\n * base64urlnopad.decode('Eqs');\n * // => Uint8Array.from([0x12, 0xab])\n * ```\n */\nexport const base64urlnopad: BytesCoder = chain(\n radix2(6),\n alphabet('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_'),\n join('')\n);\n\n// base58 code\n// -----------\nconst genBase58 = /* @__NO_SIDE_EFFECTS__ */ (abc: string) =>\n chain(radix(58), alphabet(abc), join(''));\n\n/**\n * base58: base64 without ambigous characters +, /, 0, O, I, l.\n * Quadratic (O(n^2)) - so, can't be used on large inputs.\n * @example\n * ```js\n * base58.decode('01abcdef');\n * // => '3UhJW'\n * ```\n */\nexport const base58: BytesCoder = genBase58(\n '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'\n);\n/**\n * base58: flickr version. Check out `base58`.\n */\nexport const base58flickr: BytesCoder = genBase58(\n '123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ'\n);\n/**\n * base58: XRP version. Check out `base58`.\n */\nexport const base58xrp: BytesCoder = genBase58(\n 'rpshnaf39wBUDNEGHJKLM4PQRST7VWXYZ2bcdeCg65jkm8oFqi1tuvAxyz'\n);\n\n// Data len (index) -> encoded block len\nconst XMR_BLOCK_LEN = [0, 2, 3, 5, 6, 7, 9, 10, 11];\n\n/**\n * base58: XMR version. Check out `base58`.\n * Done in 8-byte blocks (which equals 11 chars in decoding). Last (non-full) block padded with '1' to size in XMR_BLOCK_LEN.\n * Block encoding significantly reduces quadratic complexity of base58.\n */\nexport const base58xmr: BytesCoder = {\n encode(data: Uint8Array) {\n let res = '';\n for (let i = 0; i < data.length; i += 8) {\n const block = data.subarray(i, i + 8);\n res += base58.encode(block).padStart(XMR_BLOCK_LEN[block.length]!, '1');\n }\n return res;\n },\n decode(str: string) {\n let res: number[] = [];\n for (let i = 0; i < str.length; i += 11) {\n const slice = str.slice(i, i + 11);\n const blockLen = XMR_BLOCK_LEN.indexOf(slice.length);\n const block = base58.decode(slice);\n for (let j = 0; j < block.length - blockLen; j++) {\n if (block[j] !== 0) throw new Error('base58xmr: wrong padding');\n }\n res = res.concat(Array.from(block.slice(block.length - blockLen)));\n }\n return Uint8Array.from(res);\n },\n};\n\n/**\n * Method, which creates base58check encoder.\n * Requires function, calculating sha256.\n */\nexport const createBase58check = (sha256: (data: Uint8Array) => Uint8Array): BytesCoder =>\n chain(\n checksum(4, (data) => sha256(sha256(data))),\n base58\n );\n\n/**\n * Use `createBase58check` instead.\n * @deprecated\n */\nexport const base58check: (sha256: (data: Uint8Array) => Uint8Array) => BytesCoder =\n createBase58check;\n\n// Bech32 code\n// -----------\nexport interface Bech32Decoded {\n prefix: Prefix;\n words: number[];\n}\nexport interface Bech32DecodedWithArray {\n prefix: Prefix;\n words: number[];\n bytes: Uint8Array;\n}\n\nconst BECH_ALPHABET: Coder = chain(\n alphabet('qpzry9x8gf2tvdw0s3jn54khce6mua7l'),\n join('')\n);\n\nconst POLYMOD_GENERATORS = [0x3b6a57b2, 0x26508e6d, 0x1ea119fa, 0x3d4233dd, 0x2a1462b3];\nfunction bech32Polymod(pre: number): number {\n const b = pre >> 25;\n let chk = (pre & 0x1ffffff) << 5;\n for (let i = 0; i < POLYMOD_GENERATORS.length; i++) {\n if (((b >> i) & 1) === 1) chk ^= POLYMOD_GENERATORS[i]!;\n }\n return chk;\n}\n\nfunction bechChecksum(prefix: string, words: number[], encodingConst = 1): string {\n const len = prefix.length;\n let chk = 1;\n for (let i = 0; i < len; i++) {\n const c = prefix.charCodeAt(i);\n if (c < 33 || c > 126) throw new Error(`Invalid prefix (${prefix})`);\n chk = bech32Polymod(chk) ^ (c >> 5);\n }\n chk = bech32Polymod(chk);\n for (let i = 0; i < len; i++) chk = bech32Polymod(chk) ^ (prefix.charCodeAt(i) & 0x1f);\n for (let v of words) chk = bech32Polymod(chk) ^ v;\n for (let i = 0; i < 6; i++) chk = bech32Polymod(chk);\n chk ^= encodingConst;\n return BECH_ALPHABET.encode(convertRadix2([chk % powers[30]!], 30, 5, false));\n}\n\nexport interface Bech32 {\n encode(\n prefix: Prefix,\n words: number[] | Uint8Array,\n limit?: number | false\n ): `${Lowercase}1${string}`;\n decode(\n str: `${Prefix}1${string}`,\n limit?: number | false\n ): Bech32Decoded;\n encodeFromBytes(prefix: string, bytes: Uint8Array): string;\n decodeToBytes(str: string): Bech32DecodedWithArray;\n decodeUnsafe(str: string, limit?: number | false): void | Bech32Decoded;\n fromWords(to: number[]): Uint8Array;\n fromWordsUnsafe(to: number[]): void | Uint8Array;\n toWords(from: Uint8Array): number[];\n}\n/**\n * @__NO_SIDE_EFFECTS__\n */\nfunction genBech32(encoding: 'bech32' | 'bech32m'): Bech32 {\n const ENCODING_CONST = encoding === 'bech32' ? 1 : 0x2bc830a3;\n const _words = radix2(5);\n const fromWords = _words.decode;\n const toWords = _words.encode;\n const fromWordsUnsafe = unsafeWrapper(fromWords);\n\n function encode(\n prefix: Prefix,\n words: number[] | Uint8Array,\n limit: number | false = 90\n ): `${Lowercase}1${string}` {\n astr('bech32.encode prefix', prefix);\n if (isBytes(words)) words = Array.from(words);\n anumArr('bech32.encode', words);\n const plen = prefix.length;\n if (plen === 0) throw new TypeError(`Invalid prefix length ${plen}`);\n const actualLength = plen + 7 + words.length;\n if (limit !== false && actualLength > limit)\n throw new TypeError(`Length ${actualLength} exceeds limit ${limit}`);\n const lowered = prefix.toLowerCase();\n const sum = bechChecksum(lowered, words, ENCODING_CONST);\n return `${lowered}1${BECH_ALPHABET.encode(words)}${sum}` as `${Lowercase}1${string}`;\n }\n\n function decode(\n str: `${Prefix}1${string}`,\n limit?: number | false\n ): Bech32Decoded;\n function decode(str: string, limit?: number | false): Bech32Decoded;\n function decode(str: string, limit: number | false = 90): Bech32Decoded {\n astr('bech32.decode input', str);\n const slen = str.length;\n if (slen < 8 || (limit !== false && slen > limit))\n throw new TypeError(`invalid string length: ${slen} (${str}). Expected (8..${limit})`);\n // don't allow mixed case\n const lowered = str.toLowerCase();\n if (str !== lowered && str !== str.toUpperCase())\n throw new Error(`String must be lowercase or uppercase`);\n const sepIndex = lowered.lastIndexOf('1');\n if (sepIndex === 0 || sepIndex === -1)\n throw new Error(`Letter \"1\" must be present between prefix and data only`);\n const prefix = lowered.slice(0, sepIndex);\n const data = lowered.slice(sepIndex + 1);\n if (data.length < 6) throw new Error('Data must be at least 6 characters long');\n const words = BECH_ALPHABET.decode(data).slice(0, -6);\n const sum = bechChecksum(prefix, words, ENCODING_CONST);\n if (!data.endsWith(sum)) throw new Error(`Invalid checksum in ${str}: expected \"${sum}\"`);\n return { prefix, words };\n }\n\n const decodeUnsafe = unsafeWrapper(decode);\n\n function decodeToBytes(str: string): Bech32DecodedWithArray {\n const { prefix, words } = decode(str, false);\n return { prefix, words, bytes: fromWords(words) };\n }\n\n function encodeFromBytes(prefix: string, bytes: Uint8Array) {\n return encode(prefix, toWords(bytes));\n }\n\n return {\n encode,\n decode,\n encodeFromBytes,\n decodeToBytes,\n decodeUnsafe,\n fromWords,\n fromWordsUnsafe,\n toWords,\n };\n}\n\n/**\n * bech32 from BIP 173. Operates on words.\n * For high-level, check out scure-btc-signer:\n * https://github.com/paulmillr/scure-btc-signer.\n */\nexport const bech32: Bech32 = genBech32('bech32');\n\n/**\n * bech32m from BIP 350. Operates on words.\n * It was to mitigate `bech32` weaknesses.\n * For high-level, check out scure-btc-signer:\n * https://github.com/paulmillr/scure-btc-signer.\n */\nexport const bech32m: Bech32 = genBech32('bech32m');\n\ndeclare const TextEncoder: any;\ndeclare const TextDecoder: any;\n\n/**\n * UTF-8-to-byte decoder. Uses built-in TextDecoder / TextEncoder.\n * @example\n * ```js\n * const b = utf8.decode(\"hey\"); // => new Uint8Array([ 104, 101, 121 ])\n * const str = utf8.encode(b); // \"hey\"\n * ```\n */\nexport const utf8: BytesCoder = {\n encode: (data) => new TextDecoder().decode(data),\n decode: (str) => new TextEncoder().encode(str),\n};\n\n// Built-in hex conversion https://caniuse.com/mdn-javascript_builtins_uint8array_fromhex\n// prettier-ignore\nconst hasHexBuiltin: boolean = /* @__PURE__ */ (() =>\n typeof (Uint8Array as any).from([]).toHex === 'function' &&\n typeof (Uint8Array as any).fromHex === 'function')();\n// prettier-ignore\nconst hexBuiltin: BytesCoder = {\n encode(data) { abytes(data); return (data as any).toHex(); },\n decode(s) { astr('hex', s); return (Uint8Array as any).fromHex(s); },\n};\n/**\n * hex string decoder. Uses built-in function, when available.\n * @example\n * ```js\n * const b = hex.decode(\"0102ff\"); // => new Uint8Array([ 1, 2, 255 ])\n * const str = hex.encode(b); // \"0102ff\"\n * ```\n */\nexport const hex: BytesCoder = hasHexBuiltin\n ? hexBuiltin\n : chain(\n radix2(4),\n alphabet('0123456789abcdef'),\n join(''),\n normalize((s: string) => {\n if (typeof s !== 'string' || s.length % 2 !== 0)\n throw new TypeError(\n `hex.decode: expected string, got ${typeof s} with length ${s.length}`\n );\n return s.toLowerCase();\n })\n );\n\nexport type SomeCoders = {\n utf8: BytesCoder;\n hex: BytesCoder;\n base16: BytesCoder;\n base32: BytesCoder;\n base64: BytesCoder;\n base64url: BytesCoder;\n base58: BytesCoder;\n base58xmr: BytesCoder;\n};\n// prettier-ignore\nconst CODERS: SomeCoders = {\n utf8, hex, base16, base32, base64, base64url, base58, base58xmr\n};\ntype CoderType = keyof SomeCoders;\nconst coderTypeError =\n 'Invalid encoding type. Available types: utf8, hex, base16, base32, base64, base64url, base58, base58xmr';\n\n/** @deprecated */\nexport const bytesToString = (type: CoderType, bytes: Uint8Array): string => {\n if (typeof type !== 'string' || !CODERS.hasOwnProperty(type)) throw new TypeError(coderTypeError);\n if (!isBytes(bytes)) throw new TypeError('bytesToString() expects Uint8Array');\n return CODERS[type].encode(bytes);\n};\n\n/** @deprecated */\nexport const str: (type: CoderType, bytes: Uint8Array) => string = bytesToString; // as in python, but for bytes only\n\n/** @deprecated */\nexport const stringToBytes = (type: CoderType, str: string): Uint8Array => {\n if (!CODERS.hasOwnProperty(type)) throw new TypeError(coderTypeError);\n if (typeof str !== 'string') throw new TypeError('stringToBytes() expects string');\n return CODERS[type].decode(str);\n};\n/** @deprecated */\nexport const bytes: (type: CoderType, str: string) => Uint8Array = stringToBytes;\n", "/**\n * @module BIP32 hierarchical deterministic (HD) wallets over secp256k1.\n * @example\n * ```js\n * import { HDKey } from \"@scure/bip32\";\n * const hdkey1 = HDKey.fromMasterSeed(seed);\n * const hdkey2 = HDKey.fromExtendedKey(base58key);\n * const hdkey3 = HDKey.fromJSON({ xpriv: string });\n *\n * // props\n * [hdkey1.depth, hdkey1.index, hdkey1.chainCode];\n * console.log(hdkey2.privateKey, hdkey2.publicKey);\n * console.log(hdkey3.derive(\"m/0/2147483647'/1\"));\n * const sig = hdkey3.sign(hash);\n * hdkey3.verify(hash, sig);\n * ```\n */\n/*! scure-bip32 - MIT License (c) 2022 Patricio Palladino, Paul Miller (paulmillr.com) */\nimport { mod } from '@noble/curves/abstract/modular';\nimport { secp256k1 as secp } from '@noble/curves/secp256k1';\nimport { hmac } from '@noble/hashes/hmac';\nimport { ripemd160 } from '@noble/hashes/legacy';\nimport { sha256, sha512 } from '@noble/hashes/sha2';\nimport {\n abytes,\n bytesToHex,\n concatBytes,\n createView,\n hexToBytes,\n utf8ToBytes,\n} from '@noble/hashes/utils';\nimport { createBase58check } from '@scure/base';\n\nconst Point = secp.ProjectivePoint;\nconst base58check = createBase58check(sha256);\n\nfunction bytesToNumber(bytes: Uint8Array): bigint {\n abytes(bytes);\n const h = bytes.length === 0 ? '0' : bytesToHex(bytes);\n return BigInt('0x' + h);\n}\n\nfunction numberToBytes(num: bigint): Uint8Array {\n if (typeof num !== 'bigint') throw new Error('bigint expected');\n return hexToBytes(num.toString(16).padStart(64, '0'));\n}\n\nconst MASTER_SECRET = utf8ToBytes('Bitcoin seed');\n// Bitcoin hardcoded by default\nconst BITCOIN_VERSIONS: Versions = { private: 0x0488ade4, public: 0x0488b21e };\nexport const HARDENED_OFFSET: number = 0x80000000;\n\nexport interface Versions {\n private: number;\n public: number;\n}\n\nconst hash160 = (data: Uint8Array) => ripemd160(sha256(data));\nconst fromU32 = (data: Uint8Array) => createView(data).getUint32(0, false);\nconst toU32 = (n: number) => {\n if (!Number.isSafeInteger(n) || n < 0 || n > 2 ** 32 - 1) {\n throw new Error('invalid number, should be from 0 to 2**32-1, got ' + n);\n }\n const buf = new Uint8Array(4);\n createView(buf).setUint32(0, n, false);\n return buf;\n};\n\ninterface HDKeyOpt {\n versions?: Versions;\n depth?: number;\n index?: number;\n parentFingerprint?: number;\n chainCode?: Uint8Array;\n publicKey?: Uint8Array;\n privateKey?: Uint8Array | bigint;\n}\n\nexport class HDKey {\n get fingerprint(): number {\n if (!this.pubHash) {\n throw new Error('No publicKey set!');\n }\n return fromU32(this.pubHash);\n }\n get identifier(): Uint8Array | undefined {\n return this.pubHash;\n }\n get pubKeyHash(): Uint8Array | undefined {\n return this.pubHash;\n }\n get privateKey(): Uint8Array | null {\n return this.privKeyBytes || null;\n }\n get publicKey(): Uint8Array | null {\n return this.pubKey || null;\n }\n get privateExtendedKey(): string {\n const priv = this.privateKey;\n if (!priv) {\n throw new Error('No private key');\n }\n return base58check.encode(\n this.serialize(this.versions.private, concatBytes(new Uint8Array([0]), priv))\n );\n }\n get publicExtendedKey(): string {\n if (!this.pubKey) {\n throw new Error('No public key');\n }\n return base58check.encode(this.serialize(this.versions.public, this.pubKey));\n }\n\n public static fromMasterSeed(seed: Uint8Array, versions: Versions = BITCOIN_VERSIONS): HDKey {\n abytes(seed);\n if (8 * seed.length < 128 || 8 * seed.length > 512) {\n throw new Error(\n 'HDKey: seed length must be between 128 and 512 bits; 256 bits is advised, got ' +\n seed.length\n );\n }\n const I = hmac(sha512, MASTER_SECRET, seed);\n return new HDKey({\n versions,\n chainCode: I.slice(32),\n privateKey: I.slice(0, 32),\n });\n }\n\n public static fromExtendedKey(base58key: string, versions: Versions = BITCOIN_VERSIONS): HDKey {\n // => version(4) || depth(1) || fingerprint(4) || index(4) || chain(32) || key(33)\n const keyBuffer: Uint8Array = base58check.decode(base58key);\n const keyView = createView(keyBuffer);\n const version = keyView.getUint32(0, false);\n const opt = {\n versions,\n depth: keyBuffer[4],\n parentFingerprint: keyView.getUint32(5, false),\n index: keyView.getUint32(9, false),\n chainCode: keyBuffer.slice(13, 45),\n };\n const key = keyBuffer.slice(45);\n const isPriv = key[0] === 0;\n if (version !== versions[isPriv ? 'private' : 'public']) {\n throw new Error('Version mismatch');\n }\n if (isPriv) {\n return new HDKey({ ...opt, privateKey: key.slice(1) });\n } else {\n return new HDKey({ ...opt, publicKey: key });\n }\n }\n\n public static fromJSON(json: { xpriv: string }): HDKey {\n return HDKey.fromExtendedKey(json.xpriv);\n }\n public readonly versions: Versions;\n public readonly depth: number = 0;\n public readonly index: number = 0;\n public readonly chainCode: Uint8Array | null = null;\n public readonly parentFingerprint: number = 0;\n private privKey?: bigint;\n private privKeyBytes?: Uint8Array;\n private pubKey?: Uint8Array;\n private pubHash: Uint8Array | undefined;\n\n constructor(opt: HDKeyOpt) {\n if (!opt || typeof opt !== 'object') {\n throw new Error('HDKey.constructor must not be called directly');\n }\n this.versions = opt.versions || BITCOIN_VERSIONS;\n this.depth = opt.depth || 0;\n this.chainCode = opt.chainCode || null;\n this.index = opt.index || 0;\n this.parentFingerprint = opt.parentFingerprint || 0;\n if (!this.depth) {\n if (this.parentFingerprint || this.index) {\n throw new Error('HDKey: zero depth with non-zero index/parent fingerprint');\n }\n }\n if (opt.publicKey && opt.privateKey) {\n throw new Error('HDKey: publicKey and privateKey at same time.');\n }\n if (opt.privateKey) {\n if (!secp.utils.isValidPrivateKey(opt.privateKey)) {\n throw new Error('Invalid private key');\n }\n this.privKey =\n typeof opt.privateKey === 'bigint' ? opt.privateKey : bytesToNumber(opt.privateKey);\n this.privKeyBytes = numberToBytes(this.privKey);\n this.pubKey = secp.getPublicKey(opt.privateKey, true);\n } else if (opt.publicKey) {\n this.pubKey = Point.fromHex(opt.publicKey).toRawBytes(true); // force compressed point\n } else {\n throw new Error('HDKey: no public or private key provided');\n }\n this.pubHash = hash160(this.pubKey);\n }\n\n public derive(path: string): HDKey {\n if (!/^[mM]'?/.test(path)) {\n throw new Error('Path must start with \"m\" or \"M\"');\n }\n if (/^[mM]'?$/.test(path)) {\n return this;\n }\n const parts = path.replace(/^[mM]'?\\//, '').split('/');\n // tslint:disable-next-line\n let child: HDKey = this;\n for (const c of parts) {\n const m = /^(\\d+)('?)$/.exec(c);\n const m1 = m && m[1];\n if (!m || m.length !== 3 || typeof m1 !== 'string')\n throw new Error('invalid child index: ' + c);\n let idx = +m1;\n if (!Number.isSafeInteger(idx) || idx >= HARDENED_OFFSET) {\n throw new Error('Invalid index');\n }\n // hardened key\n if (m[2] === \"'\") {\n idx += HARDENED_OFFSET;\n }\n child = child.deriveChild(idx);\n }\n return child;\n }\n\n public deriveChild(index: number): HDKey {\n if (!this.pubKey || !this.chainCode) {\n throw new Error('No publicKey or chainCode set');\n }\n let data = toU32(index);\n if (index >= HARDENED_OFFSET) {\n // Hardened\n const priv = this.privateKey;\n if (!priv) {\n throw new Error('Could not derive hardened child key');\n }\n // Hardened child: 0x00 || ser256(kpar) || ser32(index)\n data = concatBytes(new Uint8Array([0]), priv, data);\n } else {\n // Normal child: serP(point(kpar)) || ser32(index)\n data = concatBytes(this.pubKey, data);\n }\n const I = hmac(sha512, this.chainCode, data);\n const childTweak = bytesToNumber(I.slice(0, 32));\n const chainCode = I.slice(32);\n if (!secp.utils.isValidPrivateKey(childTweak)) {\n throw new Error('Tweak bigger than curve order');\n }\n const opt: HDKeyOpt = {\n versions: this.versions,\n chainCode,\n depth: this.depth + 1,\n parentFingerprint: this.fingerprint,\n index,\n };\n try {\n // Private parent key -> private child key\n if (this.privateKey) {\n const added = mod(this.privKey! + childTweak, secp.CURVE.n);\n if (!secp.utils.isValidPrivateKey(added)) {\n throw new Error('The tweak was out of range or the resulted private key is invalid');\n }\n opt.privateKey = added;\n } else {\n const added = Point.fromHex(this.pubKey).add(Point.fromPrivateKey(childTweak));\n // Cryptographically impossible: hmac-sha512 preimage would need to be found\n if (added.equals(Point.ZERO)) {\n throw new Error('The tweak was equal to negative P, which made the result key invalid');\n }\n opt.publicKey = added.toRawBytes(true);\n }\n return new HDKey(opt);\n } catch (err) {\n return this.deriveChild(index + 1);\n }\n }\n\n public sign(hash: Uint8Array): Uint8Array {\n if (!this.privateKey) {\n throw new Error('No privateKey set!');\n }\n abytes(hash, 32);\n return secp.sign(hash, this.privKey!).toCompactRawBytes();\n }\n\n public verify(hash: Uint8Array, signature: Uint8Array): boolean {\n abytes(hash, 32);\n abytes(signature, 64);\n if (!this.publicKey) {\n throw new Error('No publicKey set!');\n }\n let sig;\n try {\n sig = secp.Signature.fromCompact(signature);\n } catch (error) {\n return false;\n }\n return secp.verify(sig, hash, this.publicKey);\n }\n\n public wipePrivateData(): this {\n this.privKey = undefined;\n if (this.privKeyBytes) {\n this.privKeyBytes.fill(0);\n this.privKeyBytes = undefined;\n }\n return this;\n }\n public toJSON(): { xpriv: string; xpub: string } {\n return {\n xpriv: this.privateExtendedKey,\n xpub: this.publicExtendedKey,\n };\n }\n\n private serialize(version: number, key: Uint8Array) {\n if (!this.chainCode) {\n throw new Error('No chainCode set');\n }\n abytes(key, 33);\n // version(4) || depth(1) || fingerprint(4) || index(4) || chain(32) || key(33)\n return concatBytes(\n toU32(version),\n new Uint8Array([this.depth]),\n toU32(this.parentFingerprint),\n toU32(this.index),\n this.chainCode,\n key\n );\n }\n}\n", "/**\n * PBKDF (RFC 2898). Can be used to create a key from password and salt.\n * @module\n */\nimport { hmac } from './hmac.ts';\n// prettier-ignore\nimport {\n ahash, anumber,\n asyncLoop, checkOpts, clean, createView, Hash, kdfInputToBytes,\n type CHash,\n type KDFInput\n} from './utils.ts';\n\nexport type Pbkdf2Opt = {\n c: number; // Iterations\n dkLen?: number; // Desired key length in bytes (Intended output length in octets of the derived key\n asyncTick?: number; // Maximum time in ms for which async function can block execution\n};\n// Common prologue and epilogue for sync/async functions\nfunction pbkdf2Init(hash: CHash, _password: KDFInput, _salt: KDFInput, _opts: Pbkdf2Opt) {\n ahash(hash);\n const opts = checkOpts({ dkLen: 32, asyncTick: 10 }, _opts);\n const { c, dkLen, asyncTick } = opts;\n anumber(c);\n anumber(dkLen);\n anumber(asyncTick);\n if (c < 1) throw new Error('iterations (c) should be >= 1');\n const password = kdfInputToBytes(_password);\n const salt = kdfInputToBytes(_salt);\n // DK = PBKDF2(PRF, Password, Salt, c, dkLen);\n const DK = new Uint8Array(dkLen);\n // U1 = PRF(Password, Salt + INT_32_BE(i))\n const PRF = hmac.create(hash, password);\n const PRFSalt = PRF._cloneInto().update(salt);\n return { c, dkLen, asyncTick, DK, PRF, PRFSalt };\n}\n\nfunction pbkdf2Output>(\n PRF: Hash,\n PRFSalt: Hash,\n DK: Uint8Array,\n prfW: Hash,\n u: Uint8Array\n) {\n PRF.destroy();\n PRFSalt.destroy();\n if (prfW) prfW.destroy();\n clean(u);\n return DK;\n}\n\n/**\n * PBKDF2-HMAC: RFC 2898 key derivation function\n * @param hash - hash function that would be used e.g. sha256\n * @param password - password from which a derived key is generated\n * @param salt - cryptographic salt\n * @param opts - {c, dkLen} where c is work factor and dkLen is output message size\n * @example\n * const key = pbkdf2(sha256, 'password', 'salt', { dkLen: 32, c: Math.pow(2, 18) });\n */\nexport function pbkdf2(\n hash: CHash,\n password: KDFInput,\n salt: KDFInput,\n opts: Pbkdf2Opt\n): Uint8Array {\n const { c, dkLen, DK, PRF, PRFSalt } = pbkdf2Init(hash, password, salt, opts);\n let prfW: any; // Working copy\n const arr = new Uint8Array(4);\n const view = createView(arr);\n const u = new Uint8Array(PRF.outputLen);\n // DK = T1 + T2 + ⋯ + Tdklen/hlen\n for (let ti = 1, pos = 0; pos < dkLen; ti++, pos += PRF.outputLen) {\n // Ti = F(Password, Salt, c, i)\n const Ti = DK.subarray(pos, pos + PRF.outputLen);\n view.setInt32(0, ti, false);\n // F(Password, Salt, c, i) = U1 ^ U2 ^ ⋯ ^ Uc\n // U1 = PRF(Password, Salt + INT_32_BE(i))\n (prfW = PRFSalt._cloneInto(prfW)).update(arr).digestInto(u);\n Ti.set(u.subarray(0, Ti.length));\n for (let ui = 1; ui < c; ui++) {\n // Uc = PRF(Password, Uc−1)\n PRF._cloneInto(prfW).update(u).digestInto(u);\n for (let i = 0; i < Ti.length; i++) Ti[i] ^= u[i];\n }\n }\n return pbkdf2Output(PRF, PRFSalt, DK, prfW, u);\n}\n\n/**\n * PBKDF2-HMAC: RFC 2898 key derivation function. Async version.\n * @example\n * await pbkdf2Async(sha256, 'password', 'salt', { dkLen: 32, c: 500_000 });\n */\nexport async function pbkdf2Async(\n hash: CHash,\n password: KDFInput,\n salt: KDFInput,\n opts: Pbkdf2Opt\n): Promise {\n const { c, dkLen, asyncTick, DK, PRF, PRFSalt } = pbkdf2Init(hash, password, salt, opts);\n let prfW: any; // Working copy\n const arr = new Uint8Array(4);\n const view = createView(arr);\n const u = new Uint8Array(PRF.outputLen);\n // DK = T1 + T2 + ⋯ + Tdklen/hlen\n for (let ti = 1, pos = 0; pos < dkLen; ti++, pos += PRF.outputLen) {\n // Ti = F(Password, Salt, c, i)\n const Ti = DK.subarray(pos, pos + PRF.outputLen);\n view.setInt32(0, ti, false);\n // F(Password, Salt, c, i) = U1 ^ U2 ^ ⋯ ^ Uc\n // U1 = PRF(Password, Salt + INT_32_BE(i))\n (prfW = PRFSalt._cloneInto(prfW)).update(arr).digestInto(u);\n Ti.set(u.subarray(0, Ti.length));\n await asyncLoop(c - 1, asyncTick, () => {\n // Uc = PRF(Password, Uc−1)\n PRF._cloneInto(prfW).update(u).digestInto(u);\n for (let i = 0; i < Ti.length; i++) Ti[i] ^= u[i];\n });\n }\n return pbkdf2Output(PRF, PRFSalt, DK, prfW, u);\n}\n", "\"use strict\";\n/**\n * Audited & minimal JS implementation of\n * [BIP39 mnemonic phrases](https://github.com/bitcoin/bips/blob/master/bip-0039.mediawiki).\n * @module\n * @example\n```js\nimport * as bip39 from '@scure/bip39';\nimport { wordlist } from '@scure/bip39/wordlists/english';\nconst mn = bip39.generateMnemonic(wordlist);\nconsole.log(mn);\nconst ent = bip39.mnemonicToEntropy(mn, wordlist)\nbip39.entropyToMnemonic(ent, wordlist);\nbip39.validateMnemonic(mn, wordlist);\nawait bip39.mnemonicToSeed(mn, 'password');\nbip39.mnemonicToSeedSync(mn, 'password');\n\n// Wordlists\nimport { wordlist as czech } from '@scure/bip39/wordlists/czech';\nimport { wordlist as english } from '@scure/bip39/wordlists/english';\nimport { wordlist as french } from '@scure/bip39/wordlists/french';\nimport { wordlist as italian } from '@scure/bip39/wordlists/italian';\nimport { wordlist as japanese } from '@scure/bip39/wordlists/japanese';\nimport { wordlist as korean } from '@scure/bip39/wordlists/korean';\nimport { wordlist as portuguese } from '@scure/bip39/wordlists/portuguese';\nimport { wordlist as simplifiedChinese } from '@scure/bip39/wordlists/simplified-chinese';\nimport { wordlist as spanish } from '@scure/bip39/wordlists/spanish';\nimport { wordlist as traditionalChinese } from '@scure/bip39/wordlists/traditional-chinese';\n```\n */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.generateMnemonic = generateMnemonic;\nexports.mnemonicToEntropy = mnemonicToEntropy;\nexports.entropyToMnemonic = entropyToMnemonic;\nexports.validateMnemonic = validateMnemonic;\nexports.mnemonicToSeed = mnemonicToSeed;\nexports.mnemonicToSeedSync = mnemonicToSeedSync;\n/*! scure-bip39 - MIT License (c) 2022 Patricio Palladino, Paul Miller (paulmillr.com) */\nconst pbkdf2_1 = require(\"@noble/hashes/pbkdf2\");\nconst sha2_1 = require(\"@noble/hashes/sha2\");\nconst utils_1 = require(\"@noble/hashes/utils\");\nconst base_1 = require(\"@scure/base\");\n// Japanese wordlist\nconst isJapanese = (wordlist) => wordlist[0] === '\\u3042\\u3044\\u3053\\u304f\\u3057\\u3093';\n// Normalization replaces equivalent sequences of characters\n// so that any two texts that are equivalent will be reduced\n// to the same sequence of code points, called the normal form of the original text.\n// https://tonsky.me/blog/unicode/#why-is-a----\nfunction nfkd(str) {\n if (typeof str !== 'string')\n throw new TypeError('invalid mnemonic type: ' + typeof str);\n return str.normalize('NFKD');\n}\nfunction normalize(str) {\n const norm = nfkd(str);\n const words = norm.split(' ');\n if (![12, 15, 18, 21, 24].includes(words.length))\n throw new Error('Invalid mnemonic');\n return { nfkd: norm, words };\n}\nfunction aentropy(ent) {\n (0, utils_1.abytes)(ent, 16, 20, 24, 28, 32);\n}\n/**\n * Generate x random words. Uses Cryptographically-Secure Random Number Generator.\n * @param wordlist imported wordlist for specific language\n * @param strength mnemonic strength 128-256 bits\n * @example\n * generateMnemonic(wordlist, 128)\n * // 'legal winner thank year wave sausage worth useful legal winner thank yellow'\n */\nfunction generateMnemonic(wordlist, strength = 128) {\n (0, utils_1.anumber)(strength);\n if (strength % 32 !== 0 || strength > 256)\n throw new TypeError('Invalid entropy');\n return entropyToMnemonic((0, utils_1.randomBytes)(strength / 8), wordlist);\n}\nconst calcChecksum = (entropy) => {\n // Checksum is ent.length/4 bits long\n const bitsLeft = 8 - entropy.length / 4;\n // Zero rightmost \"bitsLeft\" bits in byte\n // For example: bitsLeft=4 val=10111101 -> 10110000\n return new Uint8Array([((0, sha2_1.sha256)(entropy)[0] >> bitsLeft) << bitsLeft]);\n};\nfunction getCoder(wordlist) {\n if (!Array.isArray(wordlist) || wordlist.length !== 2048 || typeof wordlist[0] !== 'string')\n throw new Error('Wordlist: expected array of 2048 strings');\n wordlist.forEach((i) => {\n if (typeof i !== 'string')\n throw new Error('wordlist: non-string element: ' + i);\n });\n return base_1.utils.chain(base_1.utils.checksum(1, calcChecksum), base_1.utils.radix2(11, true), base_1.utils.alphabet(wordlist));\n}\n/**\n * Reversible: Converts mnemonic string to raw entropy in form of byte array.\n * @param mnemonic 12-24 words\n * @param wordlist imported wordlist for specific language\n * @example\n * const mnem = 'legal winner thank year wave sausage worth useful legal winner thank yellow';\n * mnemonicToEntropy(mnem, wordlist)\n * // Produces\n * new Uint8Array([\n * 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f,\n * 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f\n * ])\n */\nfunction mnemonicToEntropy(mnemonic, wordlist) {\n const { words } = normalize(mnemonic);\n const entropy = getCoder(wordlist).decode(words);\n aentropy(entropy);\n return entropy;\n}\n/**\n * Reversible: Converts raw entropy in form of byte array to mnemonic string.\n * @param entropy byte array\n * @param wordlist imported wordlist for specific language\n * @returns 12-24 words\n * @example\n * const ent = new Uint8Array([\n * 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f,\n * 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f\n * ]);\n * entropyToMnemonic(ent, wordlist);\n * // 'legal winner thank year wave sausage worth useful legal winner thank yellow'\n */\nfunction entropyToMnemonic(entropy, wordlist) {\n aentropy(entropy);\n const words = getCoder(wordlist).encode(entropy);\n return words.join(isJapanese(wordlist) ? '\\u3000' : ' ');\n}\n/**\n * Validates mnemonic for being 12-24 words contained in `wordlist`.\n */\nfunction validateMnemonic(mnemonic, wordlist) {\n try {\n mnemonicToEntropy(mnemonic, wordlist);\n }\n catch (e) {\n return false;\n }\n return true;\n}\nconst psalt = (passphrase) => nfkd('mnemonic' + passphrase);\n/**\n * Irreversible: Uses KDF to derive 64 bytes of key data from mnemonic + optional password.\n * @param mnemonic 12-24 words\n * @param passphrase string that will additionally protect the key\n * @returns 64 bytes of key data\n * @example\n * const mnem = 'legal winner thank year wave sausage worth useful legal winner thank yellow';\n * await mnemonicToSeed(mnem, 'password');\n * // new Uint8Array([...64 bytes])\n */\nfunction mnemonicToSeed(mnemonic, passphrase = '') {\n return (0, pbkdf2_1.pbkdf2Async)(sha2_1.sha512, normalize(mnemonic).nfkd, psalt(passphrase), { c: 2048, dkLen: 64 });\n}\n/**\n * Irreversible: Uses KDF to derive 64 bytes of key data from mnemonic + optional password.\n * @param mnemonic 12-24 words\n * @param passphrase string that will additionally protect the key\n * @returns 64 bytes of key data\n * @example\n * const mnem = 'legal winner thank year wave sausage worth useful legal winner thank yellow';\n * mnemonicToSeedSync(mnem, 'password');\n * // new Uint8Array([...64 bytes])\n */\nfunction mnemonicToSeedSync(mnemonic, passphrase = '') {\n return (0, pbkdf2_1.pbkdf2)(sha2_1.sha512, normalize(mnemonic).nfkd, psalt(passphrase), { c: 2048, dkLen: 64 });\n}\n", "\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.wordlist = void 0;\nexports.wordlist = `abandon\nability\nable\nabout\nabove\nabsent\nabsorb\nabstract\nabsurd\nabuse\naccess\naccident\naccount\naccuse\nachieve\nacid\nacoustic\nacquire\nacross\nact\naction\nactor\nactress\nactual\nadapt\nadd\naddict\naddress\nadjust\nadmit\nadult\nadvance\nadvice\naerobic\naffair\nafford\nafraid\nagain\nage\nagent\nagree\nahead\naim\nair\nairport\naisle\nalarm\nalbum\nalcohol\nalert\nalien\nall\nalley\nallow\nalmost\nalone\nalpha\nalready\nalso\nalter\nalways\namateur\namazing\namong\namount\namused\nanalyst\nanchor\nancient\nanger\nangle\nangry\nanimal\nankle\nannounce\nannual\nanother\nanswer\nantenna\nantique\nanxiety\nany\napart\napology\nappear\napple\napprove\napril\narch\narctic\narea\narena\nargue\narm\narmed\narmor\narmy\naround\narrange\narrest\narrive\narrow\nart\nartefact\nartist\nartwork\nask\naspect\nassault\nasset\nassist\nassume\nasthma\nathlete\natom\nattack\nattend\nattitude\nattract\nauction\naudit\naugust\naunt\nauthor\nauto\nautumn\naverage\navocado\navoid\nawake\naware\naway\nawesome\nawful\nawkward\naxis\nbaby\nbachelor\nbacon\nbadge\nbag\nbalance\nbalcony\nball\nbamboo\nbanana\nbanner\nbar\nbarely\nbargain\nbarrel\nbase\nbasic\nbasket\nbattle\nbeach\nbean\nbeauty\nbecause\nbecome\nbeef\nbefore\nbegin\nbehave\nbehind\nbelieve\nbelow\nbelt\nbench\nbenefit\nbest\nbetray\nbetter\nbetween\nbeyond\nbicycle\nbid\nbike\nbind\nbiology\nbird\nbirth\nbitter\nblack\nblade\nblame\nblanket\nblast\nbleak\nbless\nblind\nblood\nblossom\nblouse\nblue\nblur\nblush\nboard\nboat\nbody\nboil\nbomb\nbone\nbonus\nbook\nboost\nborder\nboring\nborrow\nboss\nbottom\nbounce\nbox\nboy\nbracket\nbrain\nbrand\nbrass\nbrave\nbread\nbreeze\nbrick\nbridge\nbrief\nbright\nbring\nbrisk\nbroccoli\nbroken\nbronze\nbroom\nbrother\nbrown\nbrush\nbubble\nbuddy\nbudget\nbuffalo\nbuild\nbulb\nbulk\nbullet\nbundle\nbunker\nburden\nburger\nburst\nbus\nbusiness\nbusy\nbutter\nbuyer\nbuzz\ncabbage\ncabin\ncable\ncactus\ncage\ncake\ncall\ncalm\ncamera\ncamp\ncan\ncanal\ncancel\ncandy\ncannon\ncanoe\ncanvas\ncanyon\ncapable\ncapital\ncaptain\ncar\ncarbon\ncard\ncargo\ncarpet\ncarry\ncart\ncase\ncash\ncasino\ncastle\ncasual\ncat\ncatalog\ncatch\ncategory\ncattle\ncaught\ncause\ncaution\ncave\nceiling\ncelery\ncement\ncensus\ncentury\ncereal\ncertain\nchair\nchalk\nchampion\nchange\nchaos\nchapter\ncharge\nchase\nchat\ncheap\ncheck\ncheese\nchef\ncherry\nchest\nchicken\nchief\nchild\nchimney\nchoice\nchoose\nchronic\nchuckle\nchunk\nchurn\ncigar\ncinnamon\ncircle\ncitizen\ncity\ncivil\nclaim\nclap\nclarify\nclaw\nclay\nclean\nclerk\nclever\nclick\nclient\ncliff\nclimb\nclinic\nclip\nclock\nclog\nclose\ncloth\ncloud\nclown\nclub\nclump\ncluster\nclutch\ncoach\ncoast\ncoconut\ncode\ncoffee\ncoil\ncoin\ncollect\ncolor\ncolumn\ncombine\ncome\ncomfort\ncomic\ncommon\ncompany\nconcert\nconduct\nconfirm\ncongress\nconnect\nconsider\ncontrol\nconvince\ncook\ncool\ncopper\ncopy\ncoral\ncore\ncorn\ncorrect\ncost\ncotton\ncouch\ncountry\ncouple\ncourse\ncousin\ncover\ncoyote\ncrack\ncradle\ncraft\ncram\ncrane\ncrash\ncrater\ncrawl\ncrazy\ncream\ncredit\ncreek\ncrew\ncricket\ncrime\ncrisp\ncritic\ncrop\ncross\ncrouch\ncrowd\ncrucial\ncruel\ncruise\ncrumble\ncrunch\ncrush\ncry\ncrystal\ncube\nculture\ncup\ncupboard\ncurious\ncurrent\ncurtain\ncurve\ncushion\ncustom\ncute\ncycle\ndad\ndamage\ndamp\ndance\ndanger\ndaring\ndash\ndaughter\ndawn\nday\ndeal\ndebate\ndebris\ndecade\ndecember\ndecide\ndecline\ndecorate\ndecrease\ndeer\ndefense\ndefine\ndefy\ndegree\ndelay\ndeliver\ndemand\ndemise\ndenial\ndentist\ndeny\ndepart\ndepend\ndeposit\ndepth\ndeputy\nderive\ndescribe\ndesert\ndesign\ndesk\ndespair\ndestroy\ndetail\ndetect\ndevelop\ndevice\ndevote\ndiagram\ndial\ndiamond\ndiary\ndice\ndiesel\ndiet\ndiffer\ndigital\ndignity\ndilemma\ndinner\ndinosaur\ndirect\ndirt\ndisagree\ndiscover\ndisease\ndish\ndismiss\ndisorder\ndisplay\ndistance\ndivert\ndivide\ndivorce\ndizzy\ndoctor\ndocument\ndog\ndoll\ndolphin\ndomain\ndonate\ndonkey\ndonor\ndoor\ndose\ndouble\ndove\ndraft\ndragon\ndrama\ndrastic\ndraw\ndream\ndress\ndrift\ndrill\ndrink\ndrip\ndrive\ndrop\ndrum\ndry\nduck\ndumb\ndune\nduring\ndust\ndutch\nduty\ndwarf\ndynamic\neager\neagle\nearly\nearn\nearth\neasily\neast\neasy\necho\necology\neconomy\nedge\nedit\neducate\neffort\negg\neight\neither\nelbow\nelder\nelectric\nelegant\nelement\nelephant\nelevator\nelite\nelse\nembark\nembody\nembrace\nemerge\nemotion\nemploy\nempower\nempty\nenable\nenact\nend\nendless\nendorse\nenemy\nenergy\nenforce\nengage\nengine\nenhance\nenjoy\nenlist\nenough\nenrich\nenroll\nensure\nenter\nentire\nentry\nenvelope\nepisode\nequal\nequip\nera\nerase\nerode\nerosion\nerror\nerupt\nescape\nessay\nessence\nestate\neternal\nethics\nevidence\nevil\nevoke\nevolve\nexact\nexample\nexcess\nexchange\nexcite\nexclude\nexcuse\nexecute\nexercise\nexhaust\nexhibit\nexile\nexist\nexit\nexotic\nexpand\nexpect\nexpire\nexplain\nexpose\nexpress\nextend\nextra\neye\neyebrow\nfabric\nface\nfaculty\nfade\nfaint\nfaith\nfall\nfalse\nfame\nfamily\nfamous\nfan\nfancy\nfantasy\nfarm\nfashion\nfat\nfatal\nfather\nfatigue\nfault\nfavorite\nfeature\nfebruary\nfederal\nfee\nfeed\nfeel\nfemale\nfence\nfestival\nfetch\nfever\nfew\nfiber\nfiction\nfield\nfigure\nfile\nfilm\nfilter\nfinal\nfind\nfine\nfinger\nfinish\nfire\nfirm\nfirst\nfiscal\nfish\nfit\nfitness\nfix\nflag\nflame\nflash\nflat\nflavor\nflee\nflight\nflip\nfloat\nflock\nfloor\nflower\nfluid\nflush\nfly\nfoam\nfocus\nfog\nfoil\nfold\nfollow\nfood\nfoot\nforce\nforest\nforget\nfork\nfortune\nforum\nforward\nfossil\nfoster\nfound\nfox\nfragile\nframe\nfrequent\nfresh\nfriend\nfringe\nfrog\nfront\nfrost\nfrown\nfrozen\nfruit\nfuel\nfun\nfunny\nfurnace\nfury\nfuture\ngadget\ngain\ngalaxy\ngallery\ngame\ngap\ngarage\ngarbage\ngarden\ngarlic\ngarment\ngas\ngasp\ngate\ngather\ngauge\ngaze\ngeneral\ngenius\ngenre\ngentle\ngenuine\ngesture\nghost\ngiant\ngift\ngiggle\nginger\ngiraffe\ngirl\ngive\nglad\nglance\nglare\nglass\nglide\nglimpse\nglobe\ngloom\nglory\nglove\nglow\nglue\ngoat\ngoddess\ngold\ngood\ngoose\ngorilla\ngospel\ngossip\ngovern\ngown\ngrab\ngrace\ngrain\ngrant\ngrape\ngrass\ngravity\ngreat\ngreen\ngrid\ngrief\ngrit\ngrocery\ngroup\ngrow\ngrunt\nguard\nguess\nguide\nguilt\nguitar\ngun\ngym\nhabit\nhair\nhalf\nhammer\nhamster\nhand\nhappy\nharbor\nhard\nharsh\nharvest\nhat\nhave\nhawk\nhazard\nhead\nhealth\nheart\nheavy\nhedgehog\nheight\nhello\nhelmet\nhelp\nhen\nhero\nhidden\nhigh\nhill\nhint\nhip\nhire\nhistory\nhobby\nhockey\nhold\nhole\nholiday\nhollow\nhome\nhoney\nhood\nhope\nhorn\nhorror\nhorse\nhospital\nhost\nhotel\nhour\nhover\nhub\nhuge\nhuman\nhumble\nhumor\nhundred\nhungry\nhunt\nhurdle\nhurry\nhurt\nhusband\nhybrid\nice\nicon\nidea\nidentify\nidle\nignore\nill\nillegal\nillness\nimage\nimitate\nimmense\nimmune\nimpact\nimpose\nimprove\nimpulse\ninch\ninclude\nincome\nincrease\nindex\nindicate\nindoor\nindustry\ninfant\ninflict\ninform\ninhale\ninherit\ninitial\ninject\ninjury\ninmate\ninner\ninnocent\ninput\ninquiry\ninsane\ninsect\ninside\ninspire\ninstall\nintact\ninterest\ninto\ninvest\ninvite\ninvolve\niron\nisland\nisolate\nissue\nitem\nivory\njacket\njaguar\njar\njazz\njealous\njeans\njelly\njewel\njob\njoin\njoke\njourney\njoy\njudge\njuice\njump\njungle\njunior\njunk\njust\nkangaroo\nkeen\nkeep\nketchup\nkey\nkick\nkid\nkidney\nkind\nkingdom\nkiss\nkit\nkitchen\nkite\nkitten\nkiwi\nknee\nknife\nknock\nknow\nlab\nlabel\nlabor\nladder\nlady\nlake\nlamp\nlanguage\nlaptop\nlarge\nlater\nlatin\nlaugh\nlaundry\nlava\nlaw\nlawn\nlawsuit\nlayer\nlazy\nleader\nleaf\nlearn\nleave\nlecture\nleft\nleg\nlegal\nlegend\nleisure\nlemon\nlend\nlength\nlens\nleopard\nlesson\nletter\nlevel\nliar\nliberty\nlibrary\nlicense\nlife\nlift\nlight\nlike\nlimb\nlimit\nlink\nlion\nliquid\nlist\nlittle\nlive\nlizard\nload\nloan\nlobster\nlocal\nlock\nlogic\nlonely\nlong\nloop\nlottery\nloud\nlounge\nlove\nloyal\nlucky\nluggage\nlumber\nlunar\nlunch\nluxury\nlyrics\nmachine\nmad\nmagic\nmagnet\nmaid\nmail\nmain\nmajor\nmake\nmammal\nman\nmanage\nmandate\nmango\nmansion\nmanual\nmaple\nmarble\nmarch\nmargin\nmarine\nmarket\nmarriage\nmask\nmass\nmaster\nmatch\nmaterial\nmath\nmatrix\nmatter\nmaximum\nmaze\nmeadow\nmean\nmeasure\nmeat\nmechanic\nmedal\nmedia\nmelody\nmelt\nmember\nmemory\nmention\nmenu\nmercy\nmerge\nmerit\nmerry\nmesh\nmessage\nmetal\nmethod\nmiddle\nmidnight\nmilk\nmillion\nmimic\nmind\nminimum\nminor\nminute\nmiracle\nmirror\nmisery\nmiss\nmistake\nmix\nmixed\nmixture\nmobile\nmodel\nmodify\nmom\nmoment\nmonitor\nmonkey\nmonster\nmonth\nmoon\nmoral\nmore\nmorning\nmosquito\nmother\nmotion\nmotor\nmountain\nmouse\nmove\nmovie\nmuch\nmuffin\nmule\nmultiply\nmuscle\nmuseum\nmushroom\nmusic\nmust\nmutual\nmyself\nmystery\nmyth\nnaive\nname\nnapkin\nnarrow\nnasty\nnation\nnature\nnear\nneck\nneed\nnegative\nneglect\nneither\nnephew\nnerve\nnest\nnet\nnetwork\nneutral\nnever\nnews\nnext\nnice\nnight\nnoble\nnoise\nnominee\nnoodle\nnormal\nnorth\nnose\nnotable\nnote\nnothing\nnotice\nnovel\nnow\nnuclear\nnumber\nnurse\nnut\noak\nobey\nobject\noblige\nobscure\nobserve\nobtain\nobvious\noccur\nocean\noctober\nodor\noff\noffer\noffice\noften\noil\nokay\nold\nolive\nolympic\nomit\nonce\none\nonion\nonline\nonly\nopen\nopera\nopinion\noppose\noption\norange\norbit\norchard\norder\nordinary\norgan\norient\noriginal\norphan\nostrich\nother\noutdoor\nouter\noutput\noutside\noval\noven\nover\nown\nowner\noxygen\noyster\nozone\npact\npaddle\npage\npair\npalace\npalm\npanda\npanel\npanic\npanther\npaper\nparade\nparent\npark\nparrot\nparty\npass\npatch\npath\npatient\npatrol\npattern\npause\npave\npayment\npeace\npeanut\npear\npeasant\npelican\npen\npenalty\npencil\npeople\npepper\nperfect\npermit\nperson\npet\nphone\nphoto\nphrase\nphysical\npiano\npicnic\npicture\npiece\npig\npigeon\npill\npilot\npink\npioneer\npipe\npistol\npitch\npizza\nplace\nplanet\nplastic\nplate\nplay\nplease\npledge\npluck\nplug\nplunge\npoem\npoet\npoint\npolar\npole\npolice\npond\npony\npool\npopular\nportion\nposition\npossible\npost\npotato\npottery\npoverty\npowder\npower\npractice\npraise\npredict\nprefer\nprepare\npresent\npretty\nprevent\nprice\npride\nprimary\nprint\npriority\nprison\nprivate\nprize\nproblem\nprocess\nproduce\nprofit\nprogram\nproject\npromote\nproof\nproperty\nprosper\nprotect\nproud\nprovide\npublic\npudding\npull\npulp\npulse\npumpkin\npunch\npupil\npuppy\npurchase\npurity\npurpose\npurse\npush\nput\npuzzle\npyramid\nquality\nquantum\nquarter\nquestion\nquick\nquit\nquiz\nquote\nrabbit\nraccoon\nrace\nrack\nradar\nradio\nrail\nrain\nraise\nrally\nramp\nranch\nrandom\nrange\nrapid\nrare\nrate\nrather\nraven\nraw\nrazor\nready\nreal\nreason\nrebel\nrebuild\nrecall\nreceive\nrecipe\nrecord\nrecycle\nreduce\nreflect\nreform\nrefuse\nregion\nregret\nregular\nreject\nrelax\nrelease\nrelief\nrely\nremain\nremember\nremind\nremove\nrender\nrenew\nrent\nreopen\nrepair\nrepeat\nreplace\nreport\nrequire\nrescue\nresemble\nresist\nresource\nresponse\nresult\nretire\nretreat\nreturn\nreunion\nreveal\nreview\nreward\nrhythm\nrib\nribbon\nrice\nrich\nride\nridge\nrifle\nright\nrigid\nring\nriot\nripple\nrisk\nritual\nrival\nriver\nroad\nroast\nrobot\nrobust\nrocket\nromance\nroof\nrookie\nroom\nrose\nrotate\nrough\nround\nroute\nroyal\nrubber\nrude\nrug\nrule\nrun\nrunway\nrural\nsad\nsaddle\nsadness\nsafe\nsail\nsalad\nsalmon\nsalon\nsalt\nsalute\nsame\nsample\nsand\nsatisfy\nsatoshi\nsauce\nsausage\nsave\nsay\nscale\nscan\nscare\nscatter\nscene\nscheme\nschool\nscience\nscissors\nscorpion\nscout\nscrap\nscreen\nscript\nscrub\nsea\nsearch\nseason\nseat\nsecond\nsecret\nsection\nsecurity\nseed\nseek\nsegment\nselect\nsell\nseminar\nsenior\nsense\nsentence\nseries\nservice\nsession\nsettle\nsetup\nseven\nshadow\nshaft\nshallow\nshare\nshed\nshell\nsheriff\nshield\nshift\nshine\nship\nshiver\nshock\nshoe\nshoot\nshop\nshort\nshoulder\nshove\nshrimp\nshrug\nshuffle\nshy\nsibling\nsick\nside\nsiege\nsight\nsign\nsilent\nsilk\nsilly\nsilver\nsimilar\nsimple\nsince\nsing\nsiren\nsister\nsituate\nsix\nsize\nskate\nsketch\nski\nskill\nskin\nskirt\nskull\nslab\nslam\nsleep\nslender\nslice\nslide\nslight\nslim\nslogan\nslot\nslow\nslush\nsmall\nsmart\nsmile\nsmoke\nsmooth\nsnack\nsnake\nsnap\nsniff\nsnow\nsoap\nsoccer\nsocial\nsock\nsoda\nsoft\nsolar\nsoldier\nsolid\nsolution\nsolve\nsomeone\nsong\nsoon\nsorry\nsort\nsoul\nsound\nsoup\nsource\nsouth\nspace\nspare\nspatial\nspawn\nspeak\nspecial\nspeed\nspell\nspend\nsphere\nspice\nspider\nspike\nspin\nspirit\nsplit\nspoil\nsponsor\nspoon\nsport\nspot\nspray\nspread\nspring\nspy\nsquare\nsqueeze\nsquirrel\nstable\nstadium\nstaff\nstage\nstairs\nstamp\nstand\nstart\nstate\nstay\nsteak\nsteel\nstem\nstep\nstereo\nstick\nstill\nsting\nstock\nstomach\nstone\nstool\nstory\nstove\nstrategy\nstreet\nstrike\nstrong\nstruggle\nstudent\nstuff\nstumble\nstyle\nsubject\nsubmit\nsubway\nsuccess\nsuch\nsudden\nsuffer\nsugar\nsuggest\nsuit\nsummer\nsun\nsunny\nsunset\nsuper\nsupply\nsupreme\nsure\nsurface\nsurge\nsurprise\nsurround\nsurvey\nsuspect\nsustain\nswallow\nswamp\nswap\nswarm\nswear\nsweet\nswift\nswim\nswing\nswitch\nsword\nsymbol\nsymptom\nsyrup\nsystem\ntable\ntackle\ntag\ntail\ntalent\ntalk\ntank\ntape\ntarget\ntask\ntaste\ntattoo\ntaxi\nteach\nteam\ntell\nten\ntenant\ntennis\ntent\nterm\ntest\ntext\nthank\nthat\ntheme\nthen\ntheory\nthere\nthey\nthing\nthis\nthought\nthree\nthrive\nthrow\nthumb\nthunder\nticket\ntide\ntiger\ntilt\ntimber\ntime\ntiny\ntip\ntired\ntissue\ntitle\ntoast\ntobacco\ntoday\ntoddler\ntoe\ntogether\ntoilet\ntoken\ntomato\ntomorrow\ntone\ntongue\ntonight\ntool\ntooth\ntop\ntopic\ntopple\ntorch\ntornado\ntortoise\ntoss\ntotal\ntourist\ntoward\ntower\ntown\ntoy\ntrack\ntrade\ntraffic\ntragic\ntrain\ntransfer\ntrap\ntrash\ntravel\ntray\ntreat\ntree\ntrend\ntrial\ntribe\ntrick\ntrigger\ntrim\ntrip\ntrophy\ntrouble\ntruck\ntrue\ntruly\ntrumpet\ntrust\ntruth\ntry\ntube\ntuition\ntumble\ntuna\ntunnel\nturkey\nturn\nturtle\ntwelve\ntwenty\ntwice\ntwin\ntwist\ntwo\ntype\ntypical\nugly\numbrella\nunable\nunaware\nuncle\nuncover\nunder\nundo\nunfair\nunfold\nunhappy\nuniform\nunique\nunit\nuniverse\nunknown\nunlock\nuntil\nunusual\nunveil\nupdate\nupgrade\nuphold\nupon\nupper\nupset\nurban\nurge\nusage\nuse\nused\nuseful\nuseless\nusual\nutility\nvacant\nvacuum\nvague\nvalid\nvalley\nvalve\nvan\nvanish\nvapor\nvarious\nvast\nvault\nvehicle\nvelvet\nvendor\nventure\nvenue\nverb\nverify\nversion\nvery\nvessel\nveteran\nviable\nvibrant\nvicious\nvictory\nvideo\nview\nvillage\nvintage\nviolin\nvirtual\nvirus\nvisa\nvisit\nvisual\nvital\nvivid\nvocal\nvoice\nvoid\nvolcano\nvolume\nvote\nvoyage\nwage\nwagon\nwait\nwalk\nwall\nwalnut\nwant\nwarfare\nwarm\nwarrior\nwash\nwasp\nwaste\nwater\nwave\nway\nwealth\nweapon\nwear\nweasel\nweather\nweb\nwedding\nweekend\nweird\nwelcome\nwest\nwet\nwhale\nwhat\nwheat\nwheel\nwhen\nwhere\nwhip\nwhisper\nwide\nwidth\nwife\nwild\nwill\nwin\nwindow\nwine\nwing\nwink\nwinner\nwinter\nwire\nwisdom\nwise\nwish\nwitness\nwolf\nwoman\nwonder\nwood\nwool\nword\nwork\nworld\nworry\nworth\nwrap\nwreck\nwrestle\nwrist\nwrite\nwrong\nyard\nyear\nyellow\nyou\nyoung\nyouth\nzebra\nzero\nzone\nzoo`.split('\\n');\n", "import { HDKey } from '@scure/bip32';\nimport { getKeysetIdInt } from '../common/index.js';\nimport { generateMnemonic, mnemonicToSeedSync } from '@scure/bip39';\nimport { wordlist } from '@scure/bip39/wordlists/english';\n\nconst STANDARD_DERIVATION_PATH = `m/129372'/0'`;\n\nenum DerivationType {\n\tSECRET = 0,\n\tBLINDING_FACTOR = 1\n}\n\nexport const deriveSecret = (seed: Uint8Array, keysetId: string, counter: number): Uint8Array => {\n\treturn derive(seed, keysetId, counter, DerivationType.SECRET);\n};\n\nexport const deriveBlindingFactor = (\n\tseed: Uint8Array,\n\tkeysetId: string,\n\tcounter: number\n): Uint8Array => {\n\treturn derive(seed, keysetId, counter, DerivationType.BLINDING_FACTOR);\n};\n\nconst derive = (\n\tseed: Uint8Array,\n\tkeysetId: string,\n\tcounter: number,\n\tsecretOrBlinding: DerivationType\n): Uint8Array => {\n\tconst hdkey = HDKey.fromMasterSeed(seed);\n\tconst keysetIdInt = getKeysetIdInt(keysetId);\n\tconst derivationPath = `${STANDARD_DERIVATION_PATH}/${keysetIdInt}'/${counter}'/${secretOrBlinding}`;\n\tconst derived = hdkey.derive(derivationPath);\n\tif (derived.privateKey === null) {\n\t\tthrow new Error('Could not derive private key');\n\t}\n\treturn derived.privateKey;\n};\n\nexport const generateNewMnemonic = (): string => {\n\tconst mnemonic = generateMnemonic(wordlist, 128);\n\treturn mnemonic;\n};\n\nexport const deriveSeedFromMnemonic = (mnemonic: string): Uint8Array => {\n\tconst seed = mnemonicToSeedSync(mnemonic);\n\treturn seed;\n};\n", "import { Secret } from \"./index.js\";\n\nexport const parseSecret = (secret: string | Uint8Array): Secret => {\n\ttry {\n\t\tif (secret instanceof Uint8Array) {\n\t\t\tsecret = new TextDecoder().decode(secret);\n\t\t}\n\t\treturn JSON.parse(secret);\n\t} catch (e) {\n\t\tthrow new Error(\"can't parse secret\");\n\t}\n};\n", "import { PrivKey, bytesToHex, hexToBytes } from '@noble/curves/abstract/utils';\nimport { sha256 } from '@noble/hashes/sha256';\nimport { schnorr } from '@noble/curves/secp256k1';\nimport { randomBytes } from '@noble/hashes/utils';\nimport { parseSecret } from '../common/NUT11.js';\nimport { Proof, Secret } from '../common/index.js';\n\nexport const createP2PKsecret = (pubkey: string): Uint8Array => {\n\tconst newSecret: Secret = [\n\t\t'P2PK',\n\t\t{\n\t\t\tnonce: bytesToHex(randomBytes(32)),\n\t\t\tdata: pubkey\n\t\t}\n\t];\n\tconst parsed = JSON.stringify(newSecret);\n\treturn new TextEncoder().encode(parsed);\n};\n\nexport const signP2PKsecret = (secret: Uint8Array, privateKey: PrivKey) => {\n\tconst msghash = sha256(new TextDecoder().decode(secret));\n\tconst sig = schnorr.sign(msghash, privateKey);\n\treturn sig;\n};\n\nexport const getSignedProofs = (proofs: Array, privateKey: string): Array => {\n\treturn proofs.map((p) => {\n\t\ttry {\n\t\t\tconst parsed: Secret = parseSecret(p.secret);\n\t\t\tif (parsed[0] !== 'P2PK') {\n\t\t\t\tthrow new Error('unknown secret type');\n\t\t\t}\n\t\t\treturn getSignedProof(p, hexToBytes(privateKey));\n\t\t} catch (error) {\n\t\t\treturn p;\n\t\t}\n\t});\n};\n\nexport const getSignedProof = (proof: Proof, privateKey: PrivKey): Proof => {\n\tif (!proof.witness) {\n\t\tproof.witness = {\n\t\t\tsignatures: [bytesToHex(signP2PKsecret(proof.secret, privateKey))]\n\t\t};\n\t}\n\treturn proof;\n};\n", "export * from \"./nast.js\";\nexport * from \"./build-link-renderer.js\";\n", "import { jsx as _jsx, Fragment as _Fragment } from \"react/jsx-runtime\";\n/** Render a nostr syntax tree to JSX components */\nexport function renderNast(root, components) {\n const indexes = {};\n return (_jsx(_Fragment, { children: root.children.map((node) => {\n indexes[node.type] = indexes[node.type] ?? 0;\n const index = indexes[node.type];\n indexes[node.type]++;\n const Component = components[node.type];\n if (!Component)\n return null;\n // @ts-expect-error\n return _jsx(Component, { node: node }, node.type + \"-\" + index);\n }) }));\n}\n", "import { Fragment as _Fragment, jsx as _jsx } from \"react/jsx-runtime\";\nimport { memo, useMemo } from \"react\";\nexport function buildLinkRenderer(handlers) {\n const LinkRenderer = ({ node }) => {\n const content = useMemo(() => {\n try {\n const url = new URL(node.href);\n for (const handler of handlers) {\n try {\n const content = handler(url, node);\n if (content)\n return content;\n }\n catch (e) { }\n }\n }\n catch (error) { }\n return null;\n }, [node.href, node.value]);\n return content || _jsx(_Fragment, { children: node.value });\n };\n return memo(LinkRenderer);\n}\n", "export * from \"./use-account-manager.js\";\nexport * from \"./use-accounts.js\";\nexport * from \"./use-action-hub.js\";\nexport * from \"./use-action.js\";\nexport * from \"./use-active-account.js\";\nexport * from \"./use-event-factory.js\";\nexport * from \"./use-event-model.js\";\nexport * from \"./use-event-store.js\";\nexport * from \"./use-observable-memo.js\";\nexport * from \"./use-observable.js\";\nexport * from \"./use-render-nast.js\";\nexport * from \"./use-rendered-content.js\";\n", "import { useContext } from \"react\";\nimport { AccountsContext } from \"../providers/accounts-provider.js\";\nexport function useAccountManager(require = true) {\n const manager = useContext(AccountsContext);\n if (!manager && require)\n throw new Error(\"Missing AccountsProvider\");\n return manager;\n}\n", "import { jsx as _jsx } from \"react/jsx-runtime\";\nimport { createContext } from \"react\";\nexport const AccountsContext = createContext(undefined);\n/** Provides an AccountManager to the component tree */\nexport function AccountsProvider({ manager, children }) {\n return _jsx(AccountsContext.Provider, { value: manager, children: children });\n}\n", "import { BehaviorSubject, Subject, NEVER, isObservable } from 'rxjs';\nimport { useRef, useState, useEffect, useDebugValue, useLayoutEffect } from 'react';\nimport { map, switchMap, catchError, distinctUntilChanged } from 'rxjs/operators';\n\n// src/internal/use-observable-internal.ts\nfunction useObservableInternal(useCustomEffect, init, inputs) {\n if (!inputs) {\n return useState(init)[0];\n }\n const [inputs$] = useState(() => new BehaviorSubject(inputs));\n const [source$] = useState(() => init(inputs$));\n const firstEffectRef = useRef(true);\n useCustomEffect(() => {\n if (firstEffectRef.current) {\n firstEffectRef.current = false;\n return;\n }\n inputs$.next(inputs);\n }, inputs);\n return source$;\n}\nfunction useObservable(init, inputs) {\n return useObservableInternal(useEffect, init, inputs);\n}\nvar identity = (value) => value;\nvar pluckFirst = (inputs$) => map((input) => input[0])(inputs$);\nvar pluckCurrentTargetValue = (event$) => map(\n (event) => event.currentTarget.value\n)(event$);\nvar pluckCurrentTargetChecked = (event$) => map(\n (event) => event.currentTarget.checked\n)(event$);\nvar getEmptySubject = () => new Subject();\nvar useRefFn = (init) => {\n const firstRef = useRef(true);\n const ref = useRef(null);\n if (firstRef.current) {\n firstRef.current = false;\n ref.current = init();\n }\n return ref;\n};\nvar increment = (n) => n + 1 | 0;\nvar useForceUpdate = () => {\n const updateState = useState(0)[1];\n return useRef(() => updateState(increment)).current;\n};\nvar useIsomorphicLayoutEffect = /* @__PURE__ */ (() => (\n /* istanbul ignore next */\n typeof window === \"undefined\" ? useEffect : useLayoutEffect\n))();\n\n// src/use-layout-observable.ts\nfunction useLayoutObservable(init, inputs) {\n return useObservableInternal(useIsomorphicLayoutEffect, init, inputs);\n}\nfunction useObservableCallback(init = identity, selector) {\n const [events$] = useState(getEmptySubject);\n const [outputs$] = useState(() => init(events$));\n const callback = useRef((...args) => {\n events$.next(selector ? selector(args) : args[0]);\n }).current;\n return [callback, outputs$];\n}\nvar toObserver = (args) => args[1]?.next ? args[1] : {\n next: args[1],\n error: args[2],\n complete: args[3]\n};\nfunction useSubscriptionInternal(useCustomEffect, args) {\n const argsRef = useRef(args);\n const observerRef = useRef();\n const subscriptionRef = useRef();\n useIsomorphicLayoutEffect(() => {\n argsRef.current = args;\n observerRef.current = toObserver(args);\n });\n useCustomEffect(() => {\n const input$ = argsRef.current[0];\n if (!observerRef.current) {\n observerRef.current = toObserver(argsRef.current);\n }\n const subscription = input$.subscribe({\n next: (value) => {\n if (input$ === argsRef.current[0]) {\n observerRef.current.next?.(value);\n }\n },\n error: (error) => {\n if (input$ === argsRef.current[0]) {\n observerRef.current.error ? observerRef.current.error(error) : console.error(error);\n }\n },\n complete: () => {\n if (input$ === argsRef.current[0]) {\n observerRef.current.complete?.();\n }\n }\n });\n subscriptionRef.current = subscription;\n return () => {\n subscription.unsubscribe();\n };\n }, [args[0]]);\n return subscriptionRef;\n}\n\n// src/use-subscription.ts\nfunction useSubscription(input$, observerOrNext$, error, complete) {\n return useSubscriptionInternal(useEffect, [\n input$,\n observerOrNext$,\n error,\n complete\n ]);\n}\n\n// src/use-layout-subscription.ts\nfunction useLayoutSubscription(input$, observerOrNext$, error, complete) {\n return useSubscriptionInternal(useIsomorphicLayoutEffect, [\n input$,\n observerOrNext$,\n error,\n complete\n ]);\n}\nfunction useRenderThrow(input$) {\n const forceUpdate = useForceUpdate();\n const errorRef = useRef();\n const output$ = useObservable(\n (inputs$) => inputs$.pipe(\n switchMap(([input$2]) => {\n errorRef.current = null;\n return input$2.pipe(\n catchError((error) => {\n errorRef.current = error;\n forceUpdate();\n return NEVER;\n })\n );\n })\n ),\n [input$]\n );\n if (errorRef.current) {\n throw errorRef.current;\n }\n return output$;\n}\nfunction useObservableStateInternal(useSubscription2, state$OrInit, initialState) {\n if (isObservable(state$OrInit)) {\n const state$ = state$OrInit;\n const [state, setState] = useState(() => {\n if (state$ instanceof BehaviorSubject || state$.value !== void 0) {\n return state$.value;\n }\n if (typeof initialState === \"function\") {\n return initialState();\n }\n return initialState;\n });\n useSubscription2(state$, setState);\n useDebugValue(state);\n return state;\n } else {\n const init = state$OrInit;\n const [state, setState] = useState(initialState);\n const [input$] = useState(getEmptySubject);\n const [state$] = useState(() => init(input$, state));\n const callback = useRef((state2) => input$.next(state2)).current;\n useSubscription2(state$, setState);\n useDebugValue(state);\n return [state, callback];\n }\n}\n\n// src/use-observable-state.ts\nfunction useObservableState(state$OrInit, initialState) {\n return useObservableStateInternal(\n useSubscription,\n state$OrInit,\n initialState\n );\n}\n\n// src/use-layout-observable-state.ts\nfunction useLayoutObservableState(state$OrInit, initialState) {\n return useObservableStateInternal(\n useLayoutSubscription,\n state$OrInit,\n initialState\n );\n}\nfunction useObservableEagerState(state$) {\n const forceUpdate = useForceUpdate();\n const state$Ref = useRef(state$);\n const errorRef = useRef();\n const isAsyncEmissionRef = useRef(false);\n const didSyncEmit = useRef(false);\n const [state, setState] = useState(() => {\n let state2;\n state$.subscribe({\n next: (value) => {\n didSyncEmit.current = true;\n state2 = value;\n },\n error: (error) => {\n errorRef.current = error;\n }\n }).unsubscribe();\n return state2;\n });\n useIsomorphicLayoutEffect(() => {\n state$Ref.current = state$;\n });\n useEffect(() => {\n errorRef.current = null;\n const input$ = state$Ref.current;\n let secondInitialValue = state;\n const subscription = input$.subscribe({\n next: (value) => {\n if (input$ !== state$Ref.current) {\n return;\n }\n if (isAsyncEmissionRef.current) {\n setState(() => value);\n } else {\n secondInitialValue = value;\n }\n },\n error: (error) => {\n if (input$ !== state$Ref.current) {\n return;\n }\n errorRef.current = error;\n forceUpdate();\n }\n });\n if (!isAsyncEmissionRef.current) {\n if (secondInitialValue !== state) {\n setState(() => secondInitialValue);\n }\n }\n isAsyncEmissionRef.current = true;\n return () => {\n subscription.unsubscribe();\n };\n }, [state$]);\n if (errorRef.current) {\n throw errorRef.current;\n }\n if (didSyncEmit.current) {\n useDebugValue(state);\n return state;\n } else {\n throw new Error(\"Observable did not synchronously emit a value.\");\n }\n}\nfunction useObservableGetState(state$, initialState, ...path) {\n const value = useObservableState(\n useObservable(\n () => state$.pipe(map((state) => path.reduce(getValue, state)))\n ),\n initialState\n );\n useDebugValue(value);\n return value;\n}\nfunction getValue(obj, key) {\n return obj[key];\n}\nfunction useObservablePickState(state$, initialState, ...keys) {\n const value = useObservableState(\n useObservable(\n () => state$.pipe(\n distinctUntilChanged((s1, s2) => keys.every((k) => s1[k] === s2[k])),\n map(\n (state) => keys.reduce(\n // eslint-disable-next-line no-sequences\n (o, k) => (o[k] = state[k], o),\n {}\n )\n )\n )\n ),\n initialState\n );\n useDebugValue(value);\n return value;\n}\nfunction useObservableSuspense(resource) {\n const resourceValue = resource.read();\n const forceUpdate = useForceUpdate();\n const [state, setState] = useState(resourceValue);\n useSubscription(resource.valueRef$$, (valueRef) => {\n if (valueRef) {\n setState(valueRef.current);\n }\n });\n useSubscription(resource.shouldUpdate$$, forceUpdate);\n useDebugValue(state);\n return state;\n}\nfunction useObservableRef(initialValue) {\n const [value$] = useState(() => new BehaviorSubject(initialValue));\n const [ref] = useState(() => ({\n get current() {\n return value$.value;\n },\n set current(value) {\n value$.next(value);\n }\n }));\n return [ref, value$];\n}\nvar createHandler = () => {\n const handler = {};\n handler.b = new Promise((resolve) => {\n handler.a = resolve;\n });\n return handler;\n};\nvar ObservableResource = class {\n /**\n * Unlike Promise, Observable is a multiple push mechanism.\n * Only force update when Suspense needs to restart.\n */\n shouldUpdate$$ = new Subject();\n get isDestroyed() {\n return this._d;\n }\n valueRef$$ = new BehaviorSubject(void 0);\n input$;\n _h = createHandler();\n _e = null;\n _b;\n _d = false;\n _o;\n /**\n * @param input$ An Observable.\n * @param isSuccess A function that determines if the value emitted from\n * `input$` is of success state. If false a Suspense is triggered.\n * Default all true.\n */\n constructor(input$, isSuccess) {\n this.input$ = input$;\n this._o = {\n next: (value) => {\n this._e = null;\n if (!isSuccess || isSuccess(value)) {\n if (this.valueRef$$.value?.current !== value) {\n this.valueRef$$.next({ current: value });\n }\n if (this._h) {\n const { a: resolve } = this._h;\n this._h = null;\n resolve();\n }\n } else if (!this._h) {\n this._h = createHandler();\n this.shouldUpdate$$.next(true);\n }\n },\n error: (error) => {\n this._e = error;\n if (this._h) {\n const { a: resolve } = this._h;\n this._h = null;\n resolve();\n } else {\n this.shouldUpdate$$.next(true);\n }\n },\n complete: () => {\n if (this._h) {\n this._e = new Error(\"Suspender ended unexpectedly.\");\n const { a: resolve } = this._h;\n this._h = null;\n resolve();\n }\n }\n };\n this._b = input$.subscribe(this._o);\n }\n read() {\n if (this._e) {\n throw this._e;\n }\n if (this._h) {\n throw this._h.b;\n }\n return this.valueRef$$.value?.current;\n }\n reload(newInput$) {\n if (this._d) {\n throw new Error(\"Cannot reload a destroyed Observable Resource\");\n }\n if (newInput$) {\n this.input$ = newInput$;\n }\n this._b.unsubscribe();\n this._e = null;\n if (this._h) {\n this._h.a();\n this._h = createHandler();\n }\n this._b = this.input$.subscribe(this._o);\n }\n destroy() {\n this._d = true;\n this._b.unsubscribe();\n this.shouldUpdate$$.complete();\n if (this._h) {\n this._e = new Error(\"Resource has been destroyed.\");\n const { a: resolve } = this._h;\n this._h = null;\n resolve();\n }\n }\n};\n\nexport { ObservableResource, identity, pluckCurrentTargetChecked, pluckCurrentTargetValue, pluckFirst, useForceUpdate, useLayoutObservable, useLayoutObservableState, useLayoutSubscription, useObservable, useObservableCallback, useObservableEagerState, useObservableGetState, useObservablePickState, useObservableRef, useObservableState, useObservableSuspense, useRefFn, useRenderThrow, useSubscription };\n", "import { useObservableEagerState } from \"observable-hooks\";\nimport { useAccountManager } from \"./use-account-manager.js\";\nexport function useAccounts() {\n const manager = useAccountManager();\n return useObservableEagerState(manager.accounts$);\n}\n", "import { useContext } from \"react\";\nimport { ActionsContext } from \"../providers/actions-provider.js\";\nexport function useActionHub() {\n const hub = useContext(ActionsContext);\n if (!hub)\n throw new Error(\"Missing ActionsProvider\");\n return hub;\n}\n", "import { jsx as _jsx } from \"react/jsx-runtime\";\nimport { createContext } from \"react\";\nexport const ActionsContext = createContext(undefined);\n/** Provides an ActionHub to the component tree */\nexport function ActionsProvider({ actionHub, children }) {\n return _jsx(ActionsContext.Provider, { value: actionHub, children: children });\n}\n", "import { useCallback, useRef, useState } from \"react\";\nimport { finalize } from \"rxjs\";\nimport { useActionHub } from \"./use-action-hub.js\";\nexport function useAction(Action, args) {\n const [loading, setLoading] = useState(false);\n const ref = useRef(args);\n ref.current = args;\n const hub = useActionHub();\n const run = useCallback(async () => {\n if (args === undefined)\n return;\n setLoading(true);\n try {\n await hub.run(Action, ...args);\n setLoading(false);\n }\n catch (error) {\n setLoading(false);\n throw error;\n }\n }, [Action]);\n const exec = useCallback(() => {\n if (args === undefined)\n return;\n setLoading(true);\n try {\n return hub.exec(Action, ...args).pipe(finalize(() => {\n setLoading(false);\n }));\n }\n catch (error) {\n setLoading(false);\n throw error;\n }\n }, [Action]);\n return { loading, run, exec };\n}\n", "import { useObservableEagerState } from \"observable-hooks\";\nimport { useAccountManager } from \"./use-account-manager.js\";\nexport function useActiveAccount() {\n const manager = useAccountManager();\n return useObservableEagerState(manager.active$);\n}\n", "import { useContext } from \"react\";\nimport { FactoryContext } from \"../providers/factory-provider.js\";\nexport function useEventFactory(require = true) {\n const factory = useContext(FactoryContext);\n if (!require && !factory)\n throw new Error(\"Missing EventFactoryProvider\");\n return factory;\n}\n", "import { jsx as _jsx } from \"react/jsx-runtime\";\nimport { createContext } from \"react\";\nexport const FactoryContext = createContext(undefined);\n/** Provides an {@link EventFactory} to the component tree */\nexport function FactoryProvider({ factory, children }) {\n return _jsx(FactoryContext.Provider, { value: factory, children: children });\n}\n", "import { withImmediateValueOrDefault } from \"applesauce-core\";\nimport hash_sum from \"hash-sum\";\nimport { of } from \"rxjs\";\nimport { useEventStore } from \"./use-event-store.js\";\nimport { useObservableEagerMemo } from \"./use-observable-memo.js\";\n/** Runs and subscribes to a model on the event store */\nexport function useEventModel(factory, args) {\n const store = useEventStore();\n return useObservableEagerMemo(() => {\n if (args)\n return store.model(factory, ...args).pipe(withImmediateValueOrDefault(undefined));\n else\n return of(undefined);\n }, [hash_sum(args), store, factory]);\n}\n", "import { useContext } from \"react\";\nimport { EventStoreContext } from \"../providers/store-provider.js\";\n/**\n * Gets the EventStore from a parent {@link EventStoreProvider} component\n * If there is none it throws an error\n */\nexport function useEventStore() {\n const store = useContext(EventStoreContext);\n if (!store)\n throw new Error(\"Missing EventStoreProvider\");\n return store;\n}\n", "import { jsx as _jsx } from \"react/jsx-runtime\";\nimport { createContext } from \"react\";\nexport const EventStoreContext = createContext(null);\n/** Provides a EventStore to the component tree */\nexport function EventStoreProvider({ eventStore, children }) {\n return _jsx(EventStoreContext.Provider, { value: eventStore, children: children });\n}\n", "import { useObservableEagerState, useObservableState } from \"observable-hooks\";\nimport { useMemo } from \"react\";\nimport { of } from \"rxjs\";\nexport function useObservableMemo(factory, deps) {\n return useObservableState(useMemo(() => factory() || of(undefined), deps));\n}\nexport function useObservableEagerMemo(factory, deps) {\n return useObservableEagerState(useMemo(() => factory() || of(undefined), deps));\n}\n", "import { useMemo } from \"react\";\nimport { renderNast } from \"../helpers/nast.js\";\n/** A hook to get the rendered output of a nostr syntax tree */\nexport function useRenderNast(root, components) {\n return useMemo(() => (root ? renderNast(root, components) : null), [root, Object.keys(components).join(\"|\")]);\n}\n", "import { useMemo } from \"react\";\nimport { truncateContent } from \"applesauce-content/nast\";\nimport { getParsedContent } from \"applesauce-content/text\";\nimport { useRenderNast } from \"./use-render-nast.js\";\nimport { buildLinkRenderer } from \"../helpers/build-link-renderer.js\";\n/** Returns the parsed and render text content for an event */\nexport function useRenderedContent(event, components, opts) {\n // if link renderers are set, override the link components\n const _components = useMemo(() => (opts?.linkRenderers ? { ...components, link: buildLinkRenderer(opts.linkRenderers) } : components), [opts?.linkRenderers, components]);\n // add additional transformers\n const nast = useMemo(() => (event ? getParsedContent(event, opts?.content, opts?.transformers, opts?.cacheKey) : undefined), [event, opts?.content, opts?.transformers, opts?.cacheKey]);\n let truncated = nast;\n if (opts?.maxLength && nast)\n truncated = truncateContent(nast, opts.maxLength);\n return useRenderNast(truncated, _components);\n}\n", "/**\n * @typedef {import('unist').Node} Node\n * @typedef {import('unist').Parent} Parent\n */\n\n/**\n * @template Fn\n * @template Fallback\n * @typedef {Fn extends (value: any) => value is infer Thing ? Thing : Fallback} Predicate\n */\n\n/**\n * @callback Check\n * Check that an arbitrary value is a node.\n * @param {unknown} this\n * The given context.\n * @param {unknown} [node]\n * Anything (typically a node).\n * @param {number | null | undefined} [index]\n * The node’s position in its parent.\n * @param {Parent | null | undefined} [parent]\n * The node’s parent.\n * @returns {boolean}\n * Whether this is a node and passes a test.\n *\n * @typedef {Record | Node} Props\n * Object to check for equivalence.\n *\n * Note: `Node` is included as it is common but is not indexable.\n *\n * @typedef {Array | Props | TestFunction | string | null | undefined} Test\n * Check for an arbitrary node.\n *\n * @callback TestFunction\n * Check if a node passes a test.\n * @param {unknown} this\n * The given context.\n * @param {Node} node\n * A node.\n * @param {number | undefined} [index]\n * The node’s position in its parent.\n * @param {Parent | undefined} [parent]\n * The node’s parent.\n * @returns {boolean | undefined | void}\n * Whether this node passes the test.\n *\n * Note: `void` is included until TS sees no return as `undefined`.\n */\n\n/**\n * Check if `node` is a `Node` and whether it passes the given test.\n *\n * @param {unknown} node\n * Thing to check, typically `Node`.\n * @param {Test} test\n * A check for a specific node.\n * @param {number | null | undefined} index\n * The node’s position in its parent.\n * @param {Parent | null | undefined} parent\n * The node’s parent.\n * @param {unknown} context\n * Context object (`this`) to pass to `test` functions.\n * @returns {boolean}\n * Whether `node` is a node and passes a test.\n */\nexport const is =\n // Note: overloads in JSDoc can’t yet use different `@template`s.\n /**\n * @type {(\n * ((node: unknown, test: Condition, index?: number | null | undefined, parent?: Parent | null | undefined, context?: unknown) => node is Node & {type: Condition}) &\n * ((node: unknown, test: Condition, index?: number | null | undefined, parent?: Parent | null | undefined, context?: unknown) => node is Node & Condition) &\n * ((node: unknown, test: Condition, index?: number | null | undefined, parent?: Parent | null | undefined, context?: unknown) => node is Node & Predicate) &\n * ((node?: null | undefined) => false) &\n * ((node: unknown, test?: null | undefined, index?: number | null | undefined, parent?: Parent | null | undefined, context?: unknown) => node is Node) &\n * ((node: unknown, test?: Test, index?: number | null | undefined, parent?: Parent | null | undefined, context?: unknown) => boolean)\n * )}\n */\n (\n /**\n * @param {unknown} [node]\n * @param {Test} [test]\n * @param {number | null | undefined} [index]\n * @param {Parent | null | undefined} [parent]\n * @param {unknown} [context]\n * @returns {boolean}\n */\n // eslint-disable-next-line max-params\n function (node, test, index, parent, context) {\n const check = convert(test)\n\n if (\n index !== undefined &&\n index !== null &&\n (typeof index !== 'number' ||\n index < 0 ||\n index === Number.POSITIVE_INFINITY)\n ) {\n throw new Error('Expected positive finite index')\n }\n\n if (\n parent !== undefined &&\n parent !== null &&\n (!is(parent) || !parent.children)\n ) {\n throw new Error('Expected parent node')\n }\n\n if (\n (parent === undefined || parent === null) !==\n (index === undefined || index === null)\n ) {\n throw new Error('Expected both parent and index')\n }\n\n return looksLikeANode(node)\n ? check.call(context, node, index, parent)\n : false\n }\n )\n\n/**\n * Generate an assertion from a test.\n *\n * Useful if you’re going to test many nodes, for example when creating a\n * utility where something else passes a compatible test.\n *\n * The created function is a bit faster because it expects valid input only:\n * a `node`, `index`, and `parent`.\n *\n * @param {Test} test\n * * when nullish, checks if `node` is a `Node`.\n * * when `string`, works like passing `(node) => node.type === test`.\n * * when `function` checks if function passed the node is true.\n * * when `object`, checks that all keys in test are in node, and that they have (strictly) equal values.\n * * when `array`, checks if any one of the subtests pass.\n * @returns {Check}\n * An assertion.\n */\nexport const convert =\n // Note: overloads in JSDoc can’t yet use different `@template`s.\n /**\n * @type {(\n * ((test: Condition) => (node: unknown, index?: number | null | undefined, parent?: Parent | null | undefined, context?: unknown) => node is Node & {type: Condition}) &\n * ((test: Condition) => (node: unknown, index?: number | null | undefined, parent?: Parent | null | undefined, context?: unknown) => node is Node & Condition) &\n * ((test: Condition) => (node: unknown, index?: number | null | undefined, parent?: Parent | null | undefined, context?: unknown) => node is Node & Predicate) &\n * ((test?: null | undefined) => (node?: unknown, index?: number | null | undefined, parent?: Parent | null | undefined, context?: unknown) => node is Node) &\n * ((test?: Test) => Check)\n * )}\n */\n (\n /**\n * @param {Test} [test]\n * @returns {Check}\n */\n function (test) {\n if (test === null || test === undefined) {\n return ok\n }\n\n if (typeof test === 'function') {\n return castFactory(test)\n }\n\n if (typeof test === 'object') {\n return Array.isArray(test) ? anyFactory(test) : propsFactory(test)\n }\n\n if (typeof test === 'string') {\n return typeFactory(test)\n }\n\n throw new Error('Expected function, string, or object as test')\n }\n )\n\n/**\n * @param {Array} tests\n * @returns {Check}\n */\nfunction anyFactory(tests) {\n /** @type {Array} */\n const checks = []\n let index = -1\n\n while (++index < tests.length) {\n checks[index] = convert(tests[index])\n }\n\n return castFactory(any)\n\n /**\n * @this {unknown}\n * @type {TestFunction}\n */\n function any(...parameters) {\n let index = -1\n\n while (++index < checks.length) {\n if (checks[index].apply(this, parameters)) return true\n }\n\n return false\n }\n}\n\n/**\n * Turn an object into a test for a node with a certain fields.\n *\n * @param {Props} check\n * @returns {Check}\n */\nfunction propsFactory(check) {\n const checkAsRecord = /** @type {Record} */ (check)\n\n return castFactory(all)\n\n /**\n * @param {Node} node\n * @returns {boolean}\n */\n function all(node) {\n const nodeAsRecord = /** @type {Record} */ (\n /** @type {unknown} */ (node)\n )\n\n /** @type {string} */\n let key\n\n for (key in check) {\n if (nodeAsRecord[key] !== checkAsRecord[key]) return false\n }\n\n return true\n }\n}\n\n/**\n * Turn a string into a test for a node with a certain type.\n *\n * @param {string} check\n * @returns {Check}\n */\nfunction typeFactory(check) {\n return castFactory(type)\n\n /**\n * @param {Node} node\n */\n function type(node) {\n return node && node.type === check\n }\n}\n\n/**\n * Turn a custom test into a test for a node that passes that test.\n *\n * @param {TestFunction} testFunction\n * @returns {Check}\n */\nfunction castFactory(testFunction) {\n return check\n\n /**\n * @this {unknown}\n * @type {Check}\n */\n function check(value, index, parent) {\n return Boolean(\n looksLikeANode(value) &&\n testFunction.call(\n this,\n value,\n typeof index === 'number' ? index : undefined,\n parent || undefined\n )\n )\n }\n}\n\nfunction ok() {\n return true\n}\n\n/**\n * @param {unknown} value\n * @returns {value is Node}\n */\nfunction looksLikeANode(value) {\n return value !== null && typeof value === 'object' && 'type' in value\n}\n", "/**\n * @param {string} d\n * @returns {string}\n */\nexport function color(d) {\n return d\n}\n", "/**\n * @typedef {import('unist').Node} UnistNode\n * @typedef {import('unist').Parent} UnistParent\n */\n\n/**\n * @typedef {Exclude | undefined} Test\n * Test from `unist-util-is`.\n *\n * Note: we have remove and add `undefined`, because otherwise when generating\n * automatic `.d.ts` files, TS tries to flatten paths from a local perspective,\n * which doesn’t work when publishing on npm.\n */\n\n/**\n * @typedef {(\n * Fn extends (value: any) => value is infer Thing\n * ? Thing\n * : Fallback\n * )} Predicate\n * Get the value of a type guard `Fn`.\n * @template Fn\n * Value; typically function that is a type guard (such as `(x): x is Y`).\n * @template Fallback\n * Value to yield if `Fn` is not a type guard.\n */\n\n/**\n * @typedef {(\n * Check extends null | undefined // No test.\n * ? Value\n * : Value extends {type: Check} // String (type) test.\n * ? Value\n * : Value extends Check // Partial test.\n * ? Value\n * : Check extends Function // Function test.\n * ? Predicate extends Value\n * ? Predicate\n * : never\n * : never // Some other test?\n * )} MatchesOne\n * Check whether a node matches a primitive check in the type system.\n * @template Value\n * Value; typically unist `Node`.\n * @template Check\n * Value; typically `unist-util-is`-compatible test, but not arrays.\n */\n\n/**\n * @typedef {(\n * Check extends Array\n * ? MatchesOne\n * : MatchesOne\n * )} Matches\n * Check whether a node matches a check in the type system.\n * @template Value\n * Value; typically unist `Node`.\n * @template Check\n * Value; typically `unist-util-is`-compatible test.\n */\n\n/**\n * @typedef {0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10} Uint\n * Number; capped reasonably.\n */\n\n/**\n * @typedef {I extends 0 ? 1 : I extends 1 ? 2 : I extends 2 ? 3 : I extends 3 ? 4 : I extends 4 ? 5 : I extends 5 ? 6 : I extends 6 ? 7 : I extends 7 ? 8 : I extends 8 ? 9 : 10} Increment\n * Increment a number in the type system.\n * @template {Uint} [I=0]\n * Index.\n */\n\n/**\n * @typedef {(\n * Node extends UnistParent\n * ? Node extends {children: Array}\n * ? Child extends Children ? Node : never\n * : never\n * : never\n * )} InternalParent\n * Collect nodes that can be parents of `Child`.\n * @template {UnistNode} Node\n * All node types in a tree.\n * @template {UnistNode} Child\n * Node to search for.\n */\n\n/**\n * @typedef {InternalParent, Child>} Parent\n * Collect nodes in `Tree` that can be parents of `Child`.\n * @template {UnistNode} Tree\n * All node types in a tree.\n * @template {UnistNode} Child\n * Node to search for.\n */\n\n/**\n * @typedef {(\n * Depth extends Max\n * ? never\n * :\n * | InternalParent\n * | InternalAncestor, Max, Increment>\n * )} InternalAncestor\n * Collect nodes in `Tree` that can be ancestors of `Child`.\n * @template {UnistNode} Node\n * All node types in a tree.\n * @template {UnistNode} Child\n * Node to search for.\n * @template {Uint} [Max=10]\n * Max; searches up to this depth.\n * @template {Uint} [Depth=0]\n * Current depth.\n */\n\n/**\n * @typedef {InternalAncestor, Child>} Ancestor\n * Collect nodes in `Tree` that can be ancestors of `Child`.\n * @template {UnistNode} Tree\n * All node types in a tree.\n * @template {UnistNode} Child\n * Node to search for.\n */\n\n/**\n * @typedef {(\n * Tree extends UnistParent\n * ? Depth extends Max\n * ? Tree\n * : Tree | InclusiveDescendant>\n * : Tree\n * )} InclusiveDescendant\n * Collect all (inclusive) descendants of `Tree`.\n *\n * > 👉 **Note**: for performance reasons, this seems to be the fastest way to\n * > recurse without actually running into an infinite loop, which the\n * > previous version did.\n * >\n * > Practically, a max of `2` is typically enough assuming a `Root` is\n * > passed, but it doesn’t improve performance.\n * > It gets higher with `List > ListItem > Table > TableRow > TableCell`.\n * > Using up to `10` doesn’t hurt or help either.\n * @template {UnistNode} Tree\n * Tree type.\n * @template {Uint} [Max=10]\n * Max; searches up to this depth.\n * @template {Uint} [Depth=0]\n * Current depth.\n */\n\n/**\n * @typedef {'skip' | boolean} Action\n * Union of the action types.\n *\n * @typedef {number} Index\n * Move to the sibling at `index` next (after node itself is completely\n * traversed).\n *\n * Useful if mutating the tree, such as removing the node the visitor is\n * currently on, or any of its previous siblings.\n * Results less than 0 or greater than or equal to `children.length` stop\n * traversing the parent.\n *\n * @typedef {[(Action | null | undefined | void)?, (Index | null | undefined)?]} ActionTuple\n * List with one or two values, the first an action, the second an index.\n *\n * @typedef {Action | ActionTuple | Index | null | undefined | void} VisitorResult\n * Any value that can be returned from a visitor.\n */\n\n/**\n * @callback Visitor\n * Handle a node (matching `test`, if given).\n *\n * Visitors are free to transform `node`.\n * They can also transform the parent of node (the last of `ancestors`).\n *\n * Replacing `node` itself, if `SKIP` is not returned, still causes its\n * descendants to be walked (which is a bug).\n *\n * When adding or removing previous siblings of `node` (or next siblings, in\n * case of reverse), the `Visitor` should return a new `Index` to specify the\n * sibling to traverse after `node` is traversed.\n * Adding or removing next siblings of `node` (or previous siblings, in case\n * of reverse) is handled as expected without needing to return a new `Index`.\n *\n * Removing the children property of an ancestor still results in them being\n * traversed.\n * @param {Visited} node\n * Found node.\n * @param {Array} ancestors\n * Ancestors of `node`.\n * @returns {VisitorResult}\n * What to do next.\n *\n * An `Index` is treated as a tuple of `[CONTINUE, Index]`.\n * An `Action` is treated as a tuple of `[Action]`.\n *\n * Passing a tuple back only makes sense if the `Action` is `SKIP`.\n * When the `Action` is `EXIT`, that action can be returned.\n * When the `Action` is `CONTINUE`, `Index` can be returned.\n * @template {UnistNode} [Visited=UnistNode]\n * Visited node type.\n * @template {UnistParent} [VisitedParents=UnistParent]\n * Ancestor type.\n */\n\n/**\n * @typedef {Visitor, Check>, Ancestor, Check>>>} BuildVisitor\n * Build a typed `Visitor` function from a tree and a test.\n *\n * It will infer which values are passed as `node` and which as `parents`.\n * @template {UnistNode} [Tree=UnistNode]\n * Tree type.\n * @template {Test} [Check=Test]\n * Test type.\n */\n\nimport {convert} from 'unist-util-is'\nimport {color} from 'unist-util-visit-parents/do-not-use-color'\n\n/** @type {Readonly} */\nconst empty = []\n\n/**\n * Continue traversing as normal.\n */\nexport const CONTINUE = true\n\n/**\n * Stop traversing immediately.\n */\nexport const EXIT = false\n\n/**\n * Do not traverse this node’s children.\n */\nexport const SKIP = 'skip'\n\n/**\n * Visit nodes, with ancestral information.\n *\n * This algorithm performs *depth-first* *tree traversal* in *preorder*\n * (**NLR**) or if `reverse` is given, in *reverse preorder* (**NRL**).\n *\n * You can choose for which nodes `visitor` is called by passing a `test`.\n * For complex tests, you should test yourself in `visitor`, as it will be\n * faster and will have improved type information.\n *\n * Walking the tree is an intensive task.\n * Make use of the return values of the visitor when possible.\n * Instead of walking a tree multiple times, walk it once, use `unist-util-is`\n * to check if a node matches, and then perform different operations.\n *\n * You can change the tree.\n * See `Visitor` for more info.\n *\n * @overload\n * @param {Tree} tree\n * @param {Check} check\n * @param {BuildVisitor} visitor\n * @param {boolean | null | undefined} [reverse]\n * @returns {undefined}\n *\n * @overload\n * @param {Tree} tree\n * @param {BuildVisitor} visitor\n * @param {boolean | null | undefined} [reverse]\n * @returns {undefined}\n *\n * @param {UnistNode} tree\n * Tree to traverse.\n * @param {Visitor | Test} test\n * `unist-util-is`-compatible test\n * @param {Visitor | boolean | null | undefined} [visitor]\n * Handle each node.\n * @param {boolean | null | undefined} [reverse]\n * Traverse in reverse preorder (NRL) instead of the default preorder (NLR).\n * @returns {undefined}\n * Nothing.\n *\n * @template {UnistNode} Tree\n * Node type.\n * @template {Test} Check\n * `unist-util-is`-compatible test.\n */\nexport function visitParents(tree, test, visitor, reverse) {\n /** @type {Test} */\n let check\n\n if (typeof test === 'function' && typeof visitor !== 'function') {\n reverse = visitor\n // @ts-expect-error no visitor given, so `visitor` is test.\n visitor = test\n } else {\n // @ts-expect-error visitor given, so `test` isn’t a visitor.\n check = test\n }\n\n const is = convert(check)\n const step = reverse ? -1 : 1\n\n factory(tree, undefined, [])()\n\n /**\n * @param {UnistNode} node\n * @param {number | undefined} index\n * @param {Array} parents\n */\n function factory(node, index, parents) {\n const value = /** @type {Record} */ (\n node && typeof node === 'object' ? node : {}\n )\n\n if (typeof value.type === 'string') {\n const name =\n // `hast`\n typeof value.tagName === 'string'\n ? value.tagName\n : // `xast`\n typeof value.name === 'string'\n ? value.name\n : undefined\n\n Object.defineProperty(visit, 'name', {\n value:\n 'node (' + color(node.type + (name ? '<' + name + '>' : '')) + ')'\n })\n }\n\n return visit\n\n function visit() {\n /** @type {Readonly} */\n let result = empty\n /** @type {Readonly} */\n let subresult\n /** @type {number} */\n let offset\n /** @type {Array} */\n let grandparents\n\n if (!test || is(node, index, parents[parents.length - 1] || undefined)) {\n // @ts-expect-error: `visitor` is now a visitor.\n result = toResult(visitor(node, parents))\n\n if (result[0] === EXIT) {\n return result\n }\n }\n\n if ('children' in node && node.children) {\n const nodeAsParent = /** @type {UnistParent} */ (node)\n\n if (nodeAsParent.children && result[0] !== SKIP) {\n offset = (reverse ? nodeAsParent.children.length : -1) + step\n grandparents = parents.concat(nodeAsParent)\n\n while (offset > -1 && offset < nodeAsParent.children.length) {\n const child = nodeAsParent.children[offset]\n\n subresult = factory(child, offset, grandparents)()\n\n if (subresult[0] === EXIT) {\n return subresult\n }\n\n offset =\n typeof subresult[1] === 'number' ? subresult[1] : offset + step\n }\n }\n }\n\n return result\n }\n }\n}\n\n/**\n * Turn a return value into a clean result.\n *\n * @param {VisitorResult} value\n * Valid return values from visitors.\n * @returns {Readonly}\n * Clean result.\n */\nfunction toResult(value) {\n if (Array.isArray(value)) {\n return value\n }\n\n if (typeof value === 'number') {\n return [CONTINUE, value]\n }\n\n return value === null || value === undefined ? empty : [value]\n}\n", "import { visitParents } from \"unist-util-visit-parents\";\nexport function findAndReplace(tree, list) {\n const pairs = list;\n let pairIndex = -1;\n const visitor = (node, parents) => {\n let index = -1;\n /** @type {Parents | undefined} */\n let grandparent;\n while (++index < parents.length) {\n const parent = parents[index];\n // const siblings = grandparent ? grandparent.children : undefined;\n grandparent = parent;\n }\n if (grandparent) {\n return handler(node, parents);\n }\n return undefined;\n };\n while (++pairIndex < pairs.length) {\n visitParents(tree, \"text\", visitor);\n }\n /**\n * Handle a text node which is not in an ignored parent.\n *\n * @param {Text} node\n * Text node.\n * @param {Array} parents\n * Parents.\n * @returns {VisitorResult}\n * Result.\n */\n function handler(node, parents) {\n const parent = parents[parents.length - 1];\n const find = pairs[pairIndex][0];\n const replace = pairs[pairIndex][1];\n let start = 0;\n const siblings = parent.children;\n const index = siblings.indexOf(node);\n let change = false;\n let nodes = [];\n find.lastIndex = 0;\n let match = find.exec(node.value);\n while (match) {\n const position = match.index;\n /** @type {RegExpMatchObject} */\n // const matchObject = {\n // index: match.index,\n // input: match.input,\n // stack: [...parents, node],\n // };\n // let value = replace(...match, matchObject);\n let value = replace(...match);\n if (typeof value === \"string\") {\n value = value.length > 0 ? { type: \"text\", value } : undefined;\n }\n // It wasn’t a match after all.\n if (value === false) {\n // False acts as if there was no match.\n // So we need to reset `lastIndex`, which currently being at the end of\n // the current match, to the beginning.\n find.lastIndex = position + 1;\n }\n else {\n if (start !== position) {\n nodes.push({\n type: \"text\",\n value: node.value.slice(start, position),\n });\n }\n if (Array.isArray(value)) {\n nodes.push(...value);\n }\n else if (value) {\n nodes.push(value);\n }\n start = position + match[0].length;\n change = true;\n }\n if (!find.global) {\n break;\n }\n match = find.exec(node.value);\n }\n if (change) {\n if (start < node.value.length) {\n nodes.push({ type: \"text\", value: node.value.slice(start) });\n }\n parent.children.splice(index, 1, ...nodes);\n }\n else {\n nodes = [node];\n }\n return index + nodes.length;\n }\n}\n", "export function eolMetadata() {\n return (tree) => {\n for (let i = 0; i < tree.children.length; i++) {\n const node = tree.children[i];\n const next = tree.children[i + 1];\n if ((node.type === \"text\" && node.value.endsWith(\"\\n\")) ||\n !next ||\n (next.type === \"text\" && next.value.startsWith(\"\\n\"))) {\n node.data = node.data || {};\n node.data.eol = true;\n }\n }\n };\n}\n", "export function truncateContent(tree, maxLength = 256) {\n let length = 0;\n for (let i = 0; i < tree.children.length; i++) {\n const node = tree.children[i];\n switch (node.type) {\n case \"hashtag\":\n length += 1 + node.hashtag.length;\n break;\n case \"mention\":\n // guess user names are about 10 long\n length += 10;\n break;\n case \"cashu\":\n length += node.raw.length;\n break;\n case \"gallery\":\n length += node.links.reduce((t, l) => t + l.length, 0);\n break;\n case \"link\":\n case \"text\":\n length += node.value.length;\n break;\n case \"emoji\":\n length += 1;\n break;\n }\n if (length > maxLength) {\n if (node.type === \"text\") {\n const children = i > 0 ? tree.children.slice(0, i) : [];\n const chunkLength = node.value.length - (length - maxLength);\n // find the nearest newline\n const newLines = node.value.matchAll(/\\n/g);\n for (const match of newLines) {\n if (match.index && match.index > chunkLength) {\n children.push({ type: \"text\", value: node.value.slice(0, match.index) });\n return { ...tree, children, truncated: true };\n }\n }\n // just cut the string\n children.push({ type: \"text\", value: node.value.slice(0, maxLength - length) });\n return { ...tree, children, truncated: true };\n }\n else\n return { ...tree, children: tree.children.slice(0, i), truncated: true };\n }\n }\n return tree;\n}\n", "/**\n * Throw a given error.\n *\n * @param {Error|null|undefined} [error]\n * Maybe error.\n * @returns {asserts error is null|undefined}\n */\nexport function bail(error) {\n if (error) {\n throw error\n }\n}\n", "/**\n * @typedef {import('trough').Pipeline} Pipeline\n *\n * @typedef {import('unist').Node} Node\n *\n * @typedef {import('vfile').Compatible} Compatible\n * @typedef {import('vfile').Value} Value\n *\n * @typedef {import('../index.js').CompileResultMap} CompileResultMap\n * @typedef {import('../index.js').Data} Data\n * @typedef {import('../index.js').Settings} Settings\n */\n\n/**\n * @typedef {CompileResultMap[keyof CompileResultMap]} CompileResults\n * Acceptable results from compilers.\n *\n * To register custom results, add them to\n * {@linkcode CompileResultMap}.\n */\n\n/**\n * @template {Node} [Tree=Node]\n * The node that the compiler receives (default: `Node`).\n * @template {CompileResults} [Result=CompileResults]\n * The thing that the compiler yields (default: `CompileResults`).\n * @callback Compiler\n * A **compiler** handles the compiling of a syntax tree to something else\n * (in most cases, text) (TypeScript type).\n *\n * It is used in the stringify phase and called with a {@linkcode Node}\n * and {@linkcode VFile} representation of the document to compile.\n * It should return the textual representation of the given tree (typically\n * `string`).\n *\n * > **Note**: unified typically compiles by serializing: most compilers\n * > return `string` (or `Uint8Array`).\n * > Some compilers, such as the one configured with\n * > [`rehype-react`][rehype-react], return other values (in this case, a\n * > React tree).\n * > If you’re using a compiler that doesn’t serialize, expect different\n * > result values.\n * >\n * > To register custom results in TypeScript, add them to\n * > {@linkcode CompileResultMap}.\n *\n * [rehype-react]: https://github.com/rehypejs/rehype-react\n * @param {Tree} tree\n * Tree to compile.\n * @param {VFile} file\n * File associated with `tree`.\n * @returns {Result}\n * New content: compiled text (`string` or `Uint8Array`, for `file.value`) or\n * something else (for `file.result`).\n */\n\n/**\n * @template {Node} [Tree=Node]\n * The node that the parser yields (default: `Node`)\n * @callback Parser\n * A **parser** handles the parsing of text to a syntax tree.\n *\n * It is used in the parse phase and is called with a `string` and\n * {@linkcode VFile} of the document to parse.\n * It must return the syntax tree representation of the given file\n * ({@linkcode Node}).\n * @param {string} document\n * Document to parse.\n * @param {VFile} file\n * File associated with `document`.\n * @returns {Tree}\n * Node representing the given file.\n */\n\n/**\n * @typedef {(\n * Plugin, any, any> |\n * PluginTuple, any, any> |\n * Preset\n * )} Pluggable\n * Union of the different ways to add plugins and settings.\n */\n\n/**\n * @typedef {Array} PluggableList\n * List of plugins and presets.\n */\n\n// Note: we can’t use `callback` yet as it messes up `this`:\n// .\n/**\n * @template {Array} [PluginParameters=[]]\n * Arguments passed to the plugin (default: `[]`, the empty tuple).\n * @template {Node | string | undefined} [Input=Node]\n * Value that is expected as input (default: `Node`).\n *\n * * If the plugin returns a {@linkcode Transformer}, this\n * should be the node it expects.\n * * If the plugin sets a {@linkcode Parser}, this should be\n * `string`.\n * * If the plugin sets a {@linkcode Compiler}, this should be the\n * node it expects.\n * @template [Output=Input]\n * Value that is yielded as output (default: `Input`).\n *\n * * If the plugin returns a {@linkcode Transformer}, this\n * should be the node that that yields.\n * * If the plugin sets a {@linkcode Parser}, this should be the\n * node that it yields.\n * * If the plugin sets a {@linkcode Compiler}, this should be\n * result it yields.\n * @typedef {(\n * (this: Processor, ...parameters: PluginParameters) =>\n * Input extends string ? // Parser.\n * Output extends Node | undefined ? undefined | void : never :\n * Output extends CompileResults ? // Compiler.\n * Input extends Node | undefined ? undefined | void : never :\n * Transformer<\n * Input extends Node ? Input : Node,\n * Output extends Node ? Output : Node\n * > | undefined | void\n * )} Plugin\n * Single plugin.\n *\n * Plugins configure the processors they are applied on in the following\n * ways:\n *\n * * they change the processor, such as the parser, the compiler, or by\n * configuring data\n * * they specify how to handle trees and files\n *\n * In practice, they are functions that can receive options and configure the\n * processor (`this`).\n *\n * > **Note**: plugins are called when the processor is *frozen*, not when\n * > they are applied.\n */\n\n/**\n * Tuple of a plugin and its configuration.\n *\n * The first item is a plugin, the rest are its parameters.\n *\n * @template {Array} [TupleParameters=[]]\n * Arguments passed to the plugin (default: `[]`, the empty tuple).\n * @template {Node | string | undefined} [Input=undefined]\n * Value that is expected as input (optional).\n *\n * * If the plugin returns a {@linkcode Transformer}, this\n * should be the node it expects.\n * * If the plugin sets a {@linkcode Parser}, this should be\n * `string`.\n * * If the plugin sets a {@linkcode Compiler}, this should be the\n * node it expects.\n * @template [Output=undefined] (optional).\n * Value that is yielded as output.\n *\n * * If the plugin returns a {@linkcode Transformer}, this\n * should be the node that that yields.\n * * If the plugin sets a {@linkcode Parser}, this should be the\n * node that it yields.\n * * If the plugin sets a {@linkcode Compiler}, this should be\n * result it yields.\n * @typedef {(\n * [\n * plugin: Plugin,\n * ...parameters: TupleParameters\n * ]\n * )} PluginTuple\n */\n\n/**\n * @typedef Preset\n * Sharable configuration.\n *\n * They can contain plugins and settings.\n * @property {PluggableList | undefined} [plugins]\n * List of plugins and presets (optional).\n * @property {Settings | undefined} [settings]\n * Shared settings for parsers and compilers (optional).\n */\n\n/**\n * @template {VFile} [File=VFile]\n * The file that the callback receives (default: `VFile`).\n * @callback ProcessCallback\n * Callback called when the process is done.\n *\n * Called with either an error or a result.\n * @param {Error | undefined} [error]\n * Fatal error (optional).\n * @param {File | undefined} [file]\n * Processed file (optional).\n * @returns {undefined}\n * Nothing.\n */\n\n/**\n * @template {Node} [Tree=Node]\n * The tree that the callback receives (default: `Node`).\n * @callback RunCallback\n * Callback called when transformers are done.\n *\n * Called with either an error or results.\n * @param {Error | undefined} [error]\n * Fatal error (optional).\n * @param {Tree | undefined} [tree]\n * Transformed tree (optional).\n * @param {VFile | undefined} [file]\n * File (optional).\n * @returns {undefined}\n * Nothing.\n */\n\n/**\n * @template {Node} [Output=Node]\n * Node type that the transformer yields (default: `Node`).\n * @callback TransformCallback\n * Callback passed to transforms.\n *\n * If the signature of a `transformer` accepts a third argument, the\n * transformer may perform asynchronous operations, and must call it.\n * @param {Error | undefined} [error]\n * Fatal error to stop the process (optional).\n * @param {Output | undefined} [tree]\n * New, changed, tree (optional).\n * @param {VFile | undefined} [file]\n * New, changed, file (optional).\n * @returns {undefined}\n * Nothing.\n */\n\n/**\n * @template {Node} [Input=Node]\n * Node type that the transformer expects (default: `Node`).\n * @template {Node} [Output=Input]\n * Node type that the transformer yields (default: `Input`).\n * @callback Transformer\n * Transformers handle syntax trees and files.\n *\n * They are functions that are called each time a syntax tree and file are\n * passed through the run phase.\n * When an error occurs in them (either because it’s thrown, returned,\n * rejected, or passed to `next`), the process stops.\n *\n * The run phase is handled by [`trough`][trough], see its documentation for\n * the exact semantics of these functions.\n *\n * > **Note**: you should likely ignore `next`: don’t accept it.\n * > it supports callback-style async work.\n * > But promises are likely easier to reason about.\n *\n * [trough]: https://github.com/wooorm/trough#function-fninput-next\n * @param {Input} tree\n * Tree to handle.\n * @param {VFile} file\n * File to handle.\n * @param {TransformCallback} next\n * Callback.\n * @returns {(\n * Promise |\n * Promise | // For some reason this is needed separately.\n * Output |\n * Error |\n * undefined |\n * void\n * )}\n * If you accept `next`, nothing.\n * Otherwise:\n *\n * * `Error` — fatal error to stop the process\n * * `Promise` or `undefined` — the next transformer keeps using\n * same tree\n * * `Promise` or `Node` — new, changed, tree\n */\n\n/**\n * @template {Node | undefined} ParseTree\n * Output of `parse`.\n * @template {Node | undefined} HeadTree\n * Input for `run`.\n * @template {Node | undefined} TailTree\n * Output for `run`.\n * @template {Node | undefined} CompileTree\n * Input of `stringify`.\n * @template {CompileResults | undefined} CompileResult\n * Output of `stringify`.\n * @template {Node | string | undefined} Input\n * Input of plugin.\n * @template Output\n * Output of plugin (optional).\n * @typedef {(\n * Input extends string\n * ? Output extends Node | undefined\n * ? // Parser.\n * Processor<\n * Output extends undefined ? ParseTree : Output,\n * HeadTree,\n * TailTree,\n * CompileTree,\n * CompileResult\n * >\n * : // Unknown.\n * Processor\n * : Output extends CompileResults\n * ? Input extends Node | undefined\n * ? // Compiler.\n * Processor<\n * ParseTree,\n * HeadTree,\n * TailTree,\n * Input extends undefined ? CompileTree : Input,\n * Output extends undefined ? CompileResult : Output\n * >\n * : // Unknown.\n * Processor\n * : Input extends Node | undefined\n * ? Output extends Node | undefined\n * ? // Transform.\n * Processor<\n * ParseTree,\n * HeadTree extends undefined ? Input : HeadTree,\n * Output extends undefined ? TailTree : Output,\n * CompileTree,\n * CompileResult\n * >\n * : // Unknown.\n * Processor\n * : // Unknown.\n * Processor\n * )} UsePlugin\n * Create a processor based on the input/output of a {@link Plugin plugin}.\n */\n\n/**\n * @template {CompileResults | undefined} Result\n * Node type that the transformer yields.\n * @typedef {(\n * Result extends Value | undefined ?\n * VFile :\n * VFile & {result: Result}\n * )} VFileWithOutput\n * Type to generate a {@linkcode VFile} corresponding to a compiler result.\n *\n * If a result that is not acceptable on a `VFile` is used, that will\n * be stored on the `result` field of {@linkcode VFile}.\n */\n\nimport {bail} from 'bail'\nimport extend from 'extend'\nimport {ok as assert} from 'devlop'\nimport isPlainObj from 'is-plain-obj'\nimport {trough} from 'trough'\nimport {VFile} from 'vfile'\nimport {CallableInstance} from './callable-instance.js'\n\n// To do: next major: drop `Compiler`, `Parser`: prefer lowercase.\n\n// To do: we could start yielding `never` in TS when a parser is missing and\n// `parse` is called.\n// Currently, we allow directly setting `processor.parser`, which is untyped.\n\nconst own = {}.hasOwnProperty\n\n/**\n * @template {Node | undefined} [ParseTree=undefined]\n * Output of `parse` (optional).\n * @template {Node | undefined} [HeadTree=undefined]\n * Input for `run` (optional).\n * @template {Node | undefined} [TailTree=undefined]\n * Output for `run` (optional).\n * @template {Node | undefined} [CompileTree=undefined]\n * Input of `stringify` (optional).\n * @template {CompileResults | undefined} [CompileResult=undefined]\n * Output of `stringify` (optional).\n * @extends {CallableInstance<[], Processor>}\n */\nexport class Processor extends CallableInstance {\n /**\n * Create a processor.\n */\n constructor() {\n // If `Processor()` is called (w/o new), `copy` is called instead.\n super('copy')\n\n /**\n * Compiler to use (deprecated).\n *\n * @deprecated\n * Use `compiler` instead.\n * @type {(\n * Compiler<\n * CompileTree extends undefined ? Node : CompileTree,\n * CompileResult extends undefined ? CompileResults : CompileResult\n * > |\n * undefined\n * )}\n */\n this.Compiler = undefined\n\n /**\n * Parser to use (deprecated).\n *\n * @deprecated\n * Use `parser` instead.\n * @type {(\n * Parser |\n * undefined\n * )}\n */\n this.Parser = undefined\n\n // Note: the following fields are considered private.\n // However, they are needed for tests, and TSC generates an untyped\n // `private freezeIndex` field for, which trips `type-coverage` up.\n // Instead, we use `@deprecated` to visualize that they shouldn’t be used.\n /**\n * Internal list of configured plugins.\n *\n * @deprecated\n * This is a private internal property and should not be used.\n * @type {Array>>}\n */\n this.attachers = []\n\n /**\n * Compiler to use.\n *\n * @type {(\n * Compiler<\n * CompileTree extends undefined ? Node : CompileTree,\n * CompileResult extends undefined ? CompileResults : CompileResult\n * > |\n * undefined\n * )}\n */\n this.compiler = undefined\n\n /**\n * Internal state to track where we are while freezing.\n *\n * @deprecated\n * This is a private internal property and should not be used.\n * @type {number}\n */\n this.freezeIndex = -1\n\n /**\n * Internal state to track whether we’re frozen.\n *\n * @deprecated\n * This is a private internal property and should not be used.\n * @type {boolean | undefined}\n */\n this.frozen = undefined\n\n /**\n * Internal state.\n *\n * @deprecated\n * This is a private internal property and should not be used.\n * @type {Data}\n */\n this.namespace = {}\n\n /**\n * Parser to use.\n *\n * @type {(\n * Parser |\n * undefined\n * )}\n */\n this.parser = undefined\n\n /**\n * Internal list of configured transformers.\n *\n * @deprecated\n * This is a private internal property and should not be used.\n * @type {Pipeline}\n */\n this.transformers = trough()\n }\n\n /**\n * Copy a processor.\n *\n * @deprecated\n * This is a private internal method and should not be used.\n * @returns {Processor}\n * New *unfrozen* processor ({@linkcode Processor}) that is\n * configured to work the same as its ancestor.\n * When the descendant processor is configured in the future it does not\n * affect the ancestral processor.\n */\n copy() {\n // Cast as the type parameters will be the same after attaching.\n const destination =\n /** @type {Processor} */ (\n new Processor()\n )\n let index = -1\n\n while (++index < this.attachers.length) {\n const attacher = this.attachers[index]\n destination.use(...attacher)\n }\n\n destination.data(extend(true, {}, this.namespace))\n\n return destination\n }\n\n /**\n * Configure the processor with info available to all plugins.\n * Information is stored in an object.\n *\n * Typically, options can be given to a specific plugin, but sometimes it\n * makes sense to have information shared with several plugins.\n * For example, a list of HTML elements that are self-closing, which is\n * needed during all phases.\n *\n * > **Note**: setting information cannot occur on *frozen* processors.\n * > Call the processor first to create a new unfrozen processor.\n *\n * > **Note**: to register custom data in TypeScript, augment the\n * > {@linkcode Data} interface.\n *\n * @example\n * This example show how to get and set info:\n *\n * ```js\n * import {unified} from 'unified'\n *\n * const processor = unified().data('alpha', 'bravo')\n *\n * processor.data('alpha') // => 'bravo'\n *\n * processor.data() // => {alpha: 'bravo'}\n *\n * processor.data({charlie: 'delta'})\n *\n * processor.data() // => {charlie: 'delta'}\n * ```\n *\n * @template {keyof Data} Key\n *\n * @overload\n * @returns {Data}\n *\n * @overload\n * @param {Data} dataset\n * @returns {Processor}\n *\n * @overload\n * @param {Key} key\n * @returns {Data[Key]}\n *\n * @overload\n * @param {Key} key\n * @param {Data[Key]} value\n * @returns {Processor}\n *\n * @param {Data | Key} [key]\n * Key to get or set, or entire dataset to set, or nothing to get the\n * entire dataset (optional).\n * @param {Data[Key]} [value]\n * Value to set (optional).\n * @returns {unknown}\n * The current processor when setting, the value at `key` when getting, or\n * the entire dataset when getting without key.\n */\n data(key, value) {\n if (typeof key === 'string') {\n // Set `key`.\n if (arguments.length === 2) {\n assertUnfrozen('data', this.frozen)\n this.namespace[key] = value\n return this\n }\n\n // Get `key`.\n return (own.call(this.namespace, key) && this.namespace[key]) || undefined\n }\n\n // Set space.\n if (key) {\n assertUnfrozen('data', this.frozen)\n this.namespace = key\n return this\n }\n\n // Get space.\n return this.namespace\n }\n\n /**\n * Freeze a processor.\n *\n * Frozen processors are meant to be extended and not to be configured\n * directly.\n *\n * When a processor is frozen it cannot be unfrozen.\n * New processors working the same way can be created by calling the\n * processor.\n *\n * It’s possible to freeze processors explicitly by calling `.freeze()`.\n * Processors freeze automatically when `.parse()`, `.run()`, `.runSync()`,\n * `.stringify()`, `.process()`, or `.processSync()` are called.\n *\n * @returns {Processor}\n * The current processor.\n */\n freeze() {\n if (this.frozen) {\n return this\n }\n\n // Cast so that we can type plugins easier.\n // Plugins are supposed to be usable on different processors, not just on\n // this exact processor.\n const self = /** @type {Processor} */ (/** @type {unknown} */ (this))\n\n while (++this.freezeIndex < this.attachers.length) {\n const [attacher, ...options] = this.attachers[this.freezeIndex]\n\n if (options[0] === false) {\n continue\n }\n\n if (options[0] === true) {\n options[0] = undefined\n }\n\n const transformer = attacher.call(self, ...options)\n\n if (typeof transformer === 'function') {\n this.transformers.use(transformer)\n }\n }\n\n this.frozen = true\n this.freezeIndex = Number.POSITIVE_INFINITY\n\n return this\n }\n\n /**\n * Parse text to a syntax tree.\n *\n * > **Note**: `parse` freezes the processor if not already *frozen*.\n *\n * > **Note**: `parse` performs the parse phase, not the run phase or other\n * > phases.\n *\n * @param {Compatible | undefined} [file]\n * file to parse (optional); typically `string` or `VFile`; any value\n * accepted as `x` in `new VFile(x)`.\n * @returns {ParseTree extends undefined ? Node : ParseTree}\n * Syntax tree representing `file`.\n */\n parse(file) {\n this.freeze()\n const realFile = vfile(file)\n const parser = this.parser || this.Parser\n assertParser('parse', parser)\n return parser(String(realFile), realFile)\n }\n\n /**\n * Process the given file as configured on the processor.\n *\n * > **Note**: `process` freezes the processor if not already *frozen*.\n *\n * > **Note**: `process` performs the parse, run, and stringify phases.\n *\n * @overload\n * @param {Compatible | undefined} file\n * @param {ProcessCallback>} done\n * @returns {undefined}\n *\n * @overload\n * @param {Compatible | undefined} [file]\n * @returns {Promise>}\n *\n * @param {Compatible | undefined} [file]\n * File (optional); typically `string` or `VFile`]; any value accepted as\n * `x` in `new VFile(x)`.\n * @param {ProcessCallback> | undefined} [done]\n * Callback (optional).\n * @returns {Promise | undefined}\n * Nothing if `done` is given.\n * Otherwise a promise, rejected with a fatal error or resolved with the\n * processed file.\n *\n * The parsed, transformed, and compiled value is available at\n * `file.value` (see note).\n *\n * > **Note**: unified typically compiles by serializing: most\n * > compilers return `string` (or `Uint8Array`).\n * > Some compilers, such as the one configured with\n * > [`rehype-react`][rehype-react], return other values (in this case, a\n * > React tree).\n * > If you’re using a compiler that doesn’t serialize, expect different\n * > result values.\n * >\n * > To register custom results in TypeScript, add them to\n * > {@linkcode CompileResultMap}.\n *\n * [rehype-react]: https://github.com/rehypejs/rehype-react\n */\n process(file, done) {\n const self = this\n\n this.freeze()\n assertParser('process', this.parser || this.Parser)\n assertCompiler('process', this.compiler || this.Compiler)\n\n return done ? executor(undefined, done) : new Promise(executor)\n\n // Note: `void`s needed for TS.\n /**\n * @param {((file: VFileWithOutput) => undefined | void) | undefined} resolve\n * @param {(error: Error | undefined) => undefined | void} reject\n * @returns {undefined}\n */\n function executor(resolve, reject) {\n const realFile = vfile(file)\n // Assume `ParseTree` (the result of the parser) matches `HeadTree` (the\n // input of the first transform).\n const parseTree =\n /** @type {HeadTree extends undefined ? Node : HeadTree} */ (\n /** @type {unknown} */ (self.parse(realFile))\n )\n\n self.run(parseTree, realFile, function (error, tree, file) {\n if (error || !tree || !file) {\n return realDone(error)\n }\n\n // Assume `TailTree` (the output of the last transform) matches\n // `CompileTree` (the input of the compiler).\n const compileTree =\n /** @type {CompileTree extends undefined ? Node : CompileTree} */ (\n /** @type {unknown} */ (tree)\n )\n\n const compileResult = self.stringify(compileTree, file)\n\n if (looksLikeAValue(compileResult)) {\n file.value = compileResult\n } else {\n file.result = compileResult\n }\n\n realDone(error, /** @type {VFileWithOutput} */ (file))\n })\n\n /**\n * @param {Error | undefined} error\n * @param {VFileWithOutput | undefined} [file]\n * @returns {undefined}\n */\n function realDone(error, file) {\n if (error || !file) {\n reject(error)\n } else if (resolve) {\n resolve(file)\n } else {\n assert(done, '`done` is defined if `resolve` is not')\n done(undefined, file)\n }\n }\n }\n }\n\n /**\n * Process the given file as configured on the processor.\n *\n * An error is thrown if asynchronous transforms are configured.\n *\n * > **Note**: `processSync` freezes the processor if not already *frozen*.\n *\n * > **Note**: `processSync` performs the parse, run, and stringify phases.\n *\n * @param {Compatible | undefined} [file]\n * File (optional); typically `string` or `VFile`; any value accepted as\n * `x` in `new VFile(x)`.\n * @returns {VFileWithOutput}\n * The processed file.\n *\n * The parsed, transformed, and compiled value is available at\n * `file.value` (see note).\n *\n * > **Note**: unified typically compiles by serializing: most\n * > compilers return `string` (or `Uint8Array`).\n * > Some compilers, such as the one configured with\n * > [`rehype-react`][rehype-react], return other values (in this case, a\n * > React tree).\n * > If you’re using a compiler that doesn’t serialize, expect different\n * > result values.\n * >\n * > To register custom results in TypeScript, add them to\n * > {@linkcode CompileResultMap}.\n *\n * [rehype-react]: https://github.com/rehypejs/rehype-react\n */\n processSync(file) {\n /** @type {boolean} */\n let complete = false\n /** @type {VFileWithOutput | undefined} */\n let result\n\n this.freeze()\n assertParser('processSync', this.parser || this.Parser)\n assertCompiler('processSync', this.compiler || this.Compiler)\n\n this.process(file, realDone)\n assertDone('processSync', 'process', complete)\n assert(result, 'we either bailed on an error or have a tree')\n\n return result\n\n /**\n * @type {ProcessCallback>}\n */\n function realDone(error, file) {\n complete = true\n bail(error)\n result = file\n }\n }\n\n /**\n * Run *transformers* on a syntax tree.\n *\n * > **Note**: `run` freezes the processor if not already *frozen*.\n *\n * > **Note**: `run` performs the run phase, not other phases.\n *\n * @overload\n * @param {HeadTree extends undefined ? Node : HeadTree} tree\n * @param {RunCallback} done\n * @returns {undefined}\n *\n * @overload\n * @param {HeadTree extends undefined ? Node : HeadTree} tree\n * @param {Compatible | undefined} file\n * @param {RunCallback} done\n * @returns {undefined}\n *\n * @overload\n * @param {HeadTree extends undefined ? Node : HeadTree} tree\n * @param {Compatible | undefined} [file]\n * @returns {Promise}\n *\n * @param {HeadTree extends undefined ? Node : HeadTree} tree\n * Tree to transform and inspect.\n * @param {(\n * RunCallback |\n * Compatible\n * )} [file]\n * File associated with `node` (optional); any value accepted as `x` in\n * `new VFile(x)`.\n * @param {RunCallback} [done]\n * Callback (optional).\n * @returns {Promise | undefined}\n * Nothing if `done` is given.\n * Otherwise, a promise rejected with a fatal error or resolved with the\n * transformed tree.\n */\n run(tree, file, done) {\n assertNode(tree)\n this.freeze()\n\n const transformers = this.transformers\n\n if (!done && typeof file === 'function') {\n done = file\n file = undefined\n }\n\n return done ? executor(undefined, done) : new Promise(executor)\n\n // Note: `void`s needed for TS.\n /**\n * @param {(\n * ((tree: TailTree extends undefined ? Node : TailTree) => undefined | void) |\n * undefined\n * )} resolve\n * @param {(error: Error) => undefined | void} reject\n * @returns {undefined}\n */\n function executor(resolve, reject) {\n assert(\n typeof file !== 'function',\n '`file` can’t be a `done` anymore, we checked'\n )\n const realFile = vfile(file)\n transformers.run(tree, realFile, realDone)\n\n /**\n * @param {Error | undefined} error\n * @param {Node} outputTree\n * @param {VFile} file\n * @returns {undefined}\n */\n function realDone(error, outputTree, file) {\n const resultingTree =\n /** @type {TailTree extends undefined ? Node : TailTree} */ (\n outputTree || tree\n )\n\n if (error) {\n reject(error)\n } else if (resolve) {\n resolve(resultingTree)\n } else {\n assert(done, '`done` is defined if `resolve` is not')\n done(undefined, resultingTree, file)\n }\n }\n }\n }\n\n /**\n * Run *transformers* on a syntax tree.\n *\n * An error is thrown if asynchronous transforms are configured.\n *\n * > **Note**: `runSync` freezes the processor if not already *frozen*.\n *\n * > **Note**: `runSync` performs the run phase, not other phases.\n *\n * @param {HeadTree extends undefined ? Node : HeadTree} tree\n * Tree to transform and inspect.\n * @param {Compatible | undefined} [file]\n * File associated with `node` (optional); any value accepted as `x` in\n * `new VFile(x)`.\n * @returns {TailTree extends undefined ? Node : TailTree}\n * Transformed tree.\n */\n runSync(tree, file) {\n /** @type {boolean} */\n let complete = false\n /** @type {(TailTree extends undefined ? Node : TailTree) | undefined} */\n let result\n\n this.run(tree, file, realDone)\n\n assertDone('runSync', 'run', complete)\n assert(result, 'we either bailed on an error or have a tree')\n return result\n\n /**\n * @type {RunCallback}\n */\n function realDone(error, tree) {\n bail(error)\n result = tree\n complete = true\n }\n }\n\n /**\n * Compile a syntax tree.\n *\n * > **Note**: `stringify` freezes the processor if not already *frozen*.\n *\n * > **Note**: `stringify` performs the stringify phase, not the run phase\n * > or other phases.\n *\n * @param {CompileTree extends undefined ? Node : CompileTree} tree\n * Tree to compile.\n * @param {Compatible | undefined} [file]\n * File associated with `node` (optional); any value accepted as `x` in\n * `new VFile(x)`.\n * @returns {CompileResult extends undefined ? Value : CompileResult}\n * Textual representation of the tree (see note).\n *\n * > **Note**: unified typically compiles by serializing: most compilers\n * > return `string` (or `Uint8Array`).\n * > Some compilers, such as the one configured with\n * > [`rehype-react`][rehype-react], return other values (in this case, a\n * > React tree).\n * > If you’re using a compiler that doesn’t serialize, expect different\n * > result values.\n * >\n * > To register custom results in TypeScript, add them to\n * > {@linkcode CompileResultMap}.\n *\n * [rehype-react]: https://github.com/rehypejs/rehype-react\n */\n stringify(tree, file) {\n this.freeze()\n const realFile = vfile(file)\n const compiler = this.compiler || this.Compiler\n assertCompiler('stringify', compiler)\n assertNode(tree)\n\n return compiler(tree, realFile)\n }\n\n /**\n * Configure the processor to use a plugin, a list of usable values, or a\n * preset.\n *\n * If the processor is already using a plugin, the previous plugin\n * configuration is changed based on the options that are passed in.\n * In other words, the plugin is not added a second time.\n *\n * > **Note**: `use` cannot be called on *frozen* processors.\n * > Call the processor first to create a new unfrozen processor.\n *\n * @example\n * There are many ways to pass plugins to `.use()`.\n * This example gives an overview:\n *\n * ```js\n * import {unified} from 'unified'\n *\n * unified()\n * // Plugin with options:\n * .use(pluginA, {x: true, y: true})\n * // Passing the same plugin again merges configuration (to `{x: true, y: false, z: true}`):\n * .use(pluginA, {y: false, z: true})\n * // Plugins:\n * .use([pluginB, pluginC])\n * // Two plugins, the second with options:\n * .use([pluginD, [pluginE, {}]])\n * // Preset with plugins and settings:\n * .use({plugins: [pluginF, [pluginG, {}]], settings: {position: false}})\n * // Settings only:\n * .use({settings: {position: false}})\n * ```\n *\n * @template {Array} [Parameters=[]]\n * @template {Node | string | undefined} [Input=undefined]\n * @template [Output=Input]\n *\n * @overload\n * @param {Preset | null | undefined} [preset]\n * @returns {Processor}\n *\n * @overload\n * @param {PluggableList} list\n * @returns {Processor}\n *\n * @overload\n * @param {Plugin} plugin\n * @param {...(Parameters | [boolean])} parameters\n * @returns {UsePlugin}\n *\n * @param {PluggableList | Plugin | Preset | null | undefined} value\n * Usable value.\n * @param {...unknown} parameters\n * Parameters, when a plugin is given as a usable value.\n * @returns {Processor}\n * Current processor.\n */\n use(value, ...parameters) {\n const attachers = this.attachers\n const namespace = this.namespace\n\n assertUnfrozen('use', this.frozen)\n\n if (value === null || value === undefined) {\n // Empty.\n } else if (typeof value === 'function') {\n addPlugin(value, parameters)\n } else if (typeof value === 'object') {\n if (Array.isArray(value)) {\n addList(value)\n } else {\n addPreset(value)\n }\n } else {\n throw new TypeError('Expected usable value, not `' + value + '`')\n }\n\n return this\n\n /**\n * @param {Pluggable} value\n * @returns {undefined}\n */\n function add(value) {\n if (typeof value === 'function') {\n addPlugin(value, [])\n } else if (typeof value === 'object') {\n if (Array.isArray(value)) {\n const [plugin, ...parameters] =\n /** @type {PluginTuple>} */ (value)\n addPlugin(plugin, parameters)\n } else {\n addPreset(value)\n }\n } else {\n throw new TypeError('Expected usable value, not `' + value + '`')\n }\n }\n\n /**\n * @param {Preset} result\n * @returns {undefined}\n */\n function addPreset(result) {\n if (!('plugins' in result) && !('settings' in result)) {\n throw new Error(\n 'Expected usable value but received an empty preset, which is probably a mistake: presets typically come with `plugins` and sometimes with `settings`, but this has neither'\n )\n }\n\n addList(result.plugins)\n\n if (result.settings) {\n namespace.settings = extend(true, namespace.settings, result.settings)\n }\n }\n\n /**\n * @param {PluggableList | null | undefined} plugins\n * @returns {undefined}\n */\n function addList(plugins) {\n let index = -1\n\n if (plugins === null || plugins === undefined) {\n // Empty.\n } else if (Array.isArray(plugins)) {\n while (++index < plugins.length) {\n const thing = plugins[index]\n add(thing)\n }\n } else {\n throw new TypeError('Expected a list of plugins, not `' + plugins + '`')\n }\n }\n\n /**\n * @param {Plugin} plugin\n * @param {Array} parameters\n * @returns {undefined}\n */\n function addPlugin(plugin, parameters) {\n let index = -1\n let entryIndex = -1\n\n while (++index < attachers.length) {\n if (attachers[index][0] === plugin) {\n entryIndex = index\n break\n }\n }\n\n if (entryIndex === -1) {\n attachers.push([plugin, ...parameters])\n }\n // Only set if there was at least a `primary` value, otherwise we’d change\n // `arguments.length`.\n else if (parameters.length > 0) {\n let [primary, ...rest] = parameters\n const currentPrimary = attachers[entryIndex][1]\n if (isPlainObj(currentPrimary) && isPlainObj(primary)) {\n primary = extend(true, currentPrimary, primary)\n }\n\n attachers[entryIndex] = [plugin, primary, ...rest]\n }\n }\n }\n}\n\n// Note: this returns a *callable* instance.\n// That’s why it’s documented as a function.\n/**\n * Create a new processor.\n *\n * @example\n * This example shows how a new processor can be created (from `remark`) and linked\n * to **stdin**(4) and **stdout**(4).\n *\n * ```js\n * import process from 'node:process'\n * import concatStream from 'concat-stream'\n * import {remark} from 'remark'\n *\n * process.stdin.pipe(\n * concatStream(function (buf) {\n * process.stdout.write(String(remark().processSync(buf)))\n * })\n * )\n * ```\n *\n * @returns\n * New *unfrozen* processor (`processor`).\n *\n * This processor is configured to work the same as its ancestor.\n * When the descendant processor is configured in the future it does not\n * affect the ancestral processor.\n */\nexport const unified = new Processor().freeze()\n\n/**\n * Assert a parser is available.\n *\n * @param {string} name\n * @param {unknown} value\n * @returns {asserts value is Parser}\n */\nfunction assertParser(name, value) {\n if (typeof value !== 'function') {\n throw new TypeError('Cannot `' + name + '` without `parser`')\n }\n}\n\n/**\n * Assert a compiler is available.\n *\n * @param {string} name\n * @param {unknown} value\n * @returns {asserts value is Compiler}\n */\nfunction assertCompiler(name, value) {\n if (typeof value !== 'function') {\n throw new TypeError('Cannot `' + name + '` without `compiler`')\n }\n}\n\n/**\n * Assert the processor is not frozen.\n *\n * @param {string} name\n * @param {unknown} frozen\n * @returns {asserts frozen is false}\n */\nfunction assertUnfrozen(name, frozen) {\n if (frozen) {\n throw new Error(\n 'Cannot call `' +\n name +\n '` on a frozen processor.\\nCreate a new processor first, by calling it: use `processor()` instead of `processor`.'\n )\n }\n}\n\n/**\n * Assert `node` is a unist node.\n *\n * @param {unknown} node\n * @returns {asserts node is Node}\n */\nfunction assertNode(node) {\n // `isPlainObj` unfortunately uses `any` instead of `unknown`.\n // type-coverage:ignore-next-line\n if (!isPlainObj(node) || typeof node.type !== 'string') {\n throw new TypeError('Expected node, got `' + node + '`')\n // Fine.\n }\n}\n\n/**\n * Assert that `complete` is `true`.\n *\n * @param {string} name\n * @param {string} asyncName\n * @param {unknown} complete\n * @returns {asserts complete is true}\n */\nfunction assertDone(name, asyncName, complete) {\n if (!complete) {\n throw new Error(\n '`' + name + '` finished async. Use `' + asyncName + '` instead'\n )\n }\n}\n\n/**\n * @param {Compatible | undefined} [value]\n * @returns {VFile}\n */\nfunction vfile(value) {\n return looksLikeAVFile(value) ? value : new VFile(value)\n}\n\n/**\n * @param {Compatible | undefined} [value]\n * @returns {value is VFile}\n */\nfunction looksLikeAVFile(value) {\n return Boolean(\n value &&\n typeof value === 'object' &&\n 'message' in value &&\n 'messages' in value\n )\n}\n\n/**\n * @param {unknown} [value]\n * @returns {value is Value}\n */\nfunction looksLikeAValue(value) {\n return typeof value === 'string' || isUint8Array(value)\n}\n\n/**\n * Assert `value` is an `Uint8Array`.\n *\n * @param {unknown} value\n * thing.\n * @returns {value is Uint8Array}\n * Whether `value` is an `Uint8Array`.\n */\nfunction isUint8Array(value) {\n return Boolean(\n value &&\n typeof value === 'object' &&\n 'byteLength' in value &&\n 'byteOffset' in value\n )\n}\n", "import {dequal} from 'dequal'\n\n/**\n * @type {Set}\n */\nconst codesWarned = new Set()\n\nclass AssertionError extends Error {\n name = /** @type {const} */ ('Assertion')\n code = /** @type {const} */ ('ERR_ASSERTION')\n\n /**\n * Create an assertion error.\n *\n * @param {string} message\n * Message explaining error.\n * @param {unknown} actual\n * Value.\n * @param {unknown} expected\n * Baseline.\n * @param {string} operator\n * Name of equality operation.\n * @param {boolean} generated\n * Whether `message` is a custom message or not\n * @returns\n * Instance.\n */\n // eslint-disable-next-line max-params\n constructor(message, actual, expected, operator, generated) {\n super(message)\n\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, this.constructor)\n }\n\n /**\n * @type {unknown}\n */\n this.actual = actual\n\n /**\n * @type {unknown}\n */\n this.expected = expected\n\n /**\n * @type {boolean}\n */\n this.generated = generated\n\n /**\n * @type {string}\n */\n this.operator = operator\n }\n}\n\nclass DeprecationError extends Error {\n name = /** @type {const} */ ('DeprecationWarning')\n\n /**\n * Create a deprecation message.\n *\n * @param {string} message\n * Message explaining deprecation.\n * @param {string | undefined} code\n * Deprecation identifier; deprecation messages will be generated only once per code.\n * @returns\n * Instance.\n */\n constructor(message, code) {\n super(message)\n\n /**\n * @type {string | undefined}\n */\n this.code = code\n }\n}\n\n/**\n * Wrap a function or class to show a deprecation message when first called.\n *\n * > 👉 **Important**: only shows a message when the `development` condition is\n * > used, does nothing in production.\n *\n * When the resulting wrapped `fn` is called, emits a warning once to\n * `console.error` (`stderr`).\n * If a code is given, one warning message will be emitted in total per code.\n *\n * @template {Function} T\n * Function or class kind.\n * @param {T} fn\n * Function or class.\n * @param {string} message\n * Message explaining deprecation.\n * @param {string | null | undefined} [code]\n * Deprecation identifier (optional); deprecation messages will be generated\n * only once per code.\n * @returns {T}\n * Wrapped `fn`.\n */\nexport function deprecate(fn, message, code) {\n let warned = false\n\n // The wrapper will keep the same prototype as fn to maintain prototype chain\n Object.setPrototypeOf(deprecated, fn)\n\n // @ts-expect-error: it’s perfect, typescript…\n return deprecated\n\n /**\n * @this {unknown}\n * @param {...Array} args\n * @returns {unknown}\n */\n function deprecated(...args) {\n if (!warned) {\n warned = true\n\n if (typeof code === 'string' && codesWarned.has(code)) {\n // Empty.\n } else {\n console.error(new DeprecationError(message, code || undefined))\n\n if (typeof code === 'string') codesWarned.add(code)\n }\n }\n\n return new.target\n ? Reflect.construct(fn, args, new.target)\n : Reflect.apply(fn, this, args)\n }\n}\n\n/**\n * Assert deep strict equivalence.\n *\n * > 👉 **Important**: only asserts when the `development` condition is used,\n * > does nothing in production.\n *\n * @template {unknown} T\n * Expected kind.\n * @param {unknown} actual\n * Value.\n * @param {T} expected\n * Baseline.\n * @param {Error | string | null | undefined} [message]\n * Message for assertion error (default: `'Expected values to be deeply equal'`).\n * @returns {asserts actual is T}\n * Nothing; throws when `actual` is not deep strict equal to `expected`.\n * @throws {AssertionError}\n * Throws when `actual` is not deep strict equal to `expected`.\n */\nexport function equal(actual, expected, message) {\n assert(\n dequal(actual, expected),\n actual,\n expected,\n 'equal',\n 'Expected values to be deeply equal',\n message\n )\n}\n\n/**\n * Assert if `value` is truthy.\n *\n * > 👉 **Important**: only asserts when the `development` condition is used,\n * > does nothing in production.\n *\n * @param {unknown} value\n * Value to assert.\n * @param {Error | string | null | undefined} [message]\n * Message for assertion error (default: `'Expected value to be truthy'`).\n * @returns {asserts value}\n * Nothing; throws when `value` is falsey.\n * @throws {AssertionError}\n * Throws when `value` is falsey.\n */\nexport function ok(value, message) {\n assert(\n Boolean(value),\n false,\n true,\n 'ok',\n 'Expected value to be truthy',\n message\n )\n}\n\n/**\n * Assert that a code path never happens.\n *\n * > 👉 **Important**: only asserts when the `development` condition is used,\n * > does nothing in production.\n *\n * @param {Error | string | null | undefined} [message]\n * Message for assertion error (default: `'Unreachable'`).\n * @returns {never}\n * Nothing; always throws.\n * @throws {AssertionError}\n * Throws when `value` is falsey.\n */\nexport function unreachable(message) {\n assert(false, false, true, 'ok', 'Unreachable', message)\n}\n\n/**\n * @param {boolean} bool\n * Whether to skip this operation.\n * @param {unknown} actual\n * Actual value.\n * @param {unknown} expected\n * Expected value.\n * @param {string} operator\n * Operator.\n * @param {string} defaultMessage\n * Default message for operation.\n * @param {Error | string | null | undefined} userMessage\n * User-provided message.\n * @returns {asserts bool}\n * Nothing; throws when falsey.\n */\n// eslint-disable-next-line max-params\nfunction assert(bool, actual, expected, operator, defaultMessage, userMessage) {\n if (!bool) {\n throw userMessage instanceof Error\n ? userMessage\n : new AssertionError(\n userMessage || defaultMessage,\n actual,\n expected,\n operator,\n !userMessage\n )\n }\n}\n", "export default function isPlainObject(value) {\n\tif (typeof value !== 'object' || value === null) {\n\t\treturn false;\n\t}\n\n\tconst prototype = Object.getPrototypeOf(value);\n\treturn (prototype === null || prototype === Object.prototype || Object.getPrototypeOf(prototype) === null) && !(Symbol.toStringTag in value) && !(Symbol.iterator in value);\n}\n", "// To do: remove `void`s\n// To do: remove `null` from output of our APIs, allow it as user APIs.\n\n/**\n * @typedef {(error?: Error | null | undefined, ...output: Array) => void} Callback\n * Callback.\n *\n * @typedef {(...input: Array) => any} Middleware\n * Ware.\n *\n * @typedef Pipeline\n * Pipeline.\n * @property {Run} run\n * Run the pipeline.\n * @property {Use} use\n * Add middleware.\n *\n * @typedef {(...input: Array) => void} Run\n * Call all middleware.\n *\n * Calls `done` on completion with either an error or the output of the\n * last middleware.\n *\n * > 👉 **Note**: as the length of input defines whether async functions get a\n * > `next` function,\n * > it’s recommended to keep `input` at one value normally.\n\n *\n * @typedef {(fn: Middleware) => Pipeline} Use\n * Add middleware.\n */\n\n/**\n * Create new middleware.\n *\n * @returns {Pipeline}\n * Pipeline.\n */\nexport function trough() {\n /** @type {Array} */\n const fns = []\n /** @type {Pipeline} */\n const pipeline = {run, use}\n\n return pipeline\n\n /** @type {Run} */\n function run(...values) {\n let middlewareIndex = -1\n /** @type {Callback} */\n const callback = values.pop()\n\n if (typeof callback !== 'function') {\n throw new TypeError('Expected function as last argument, not ' + callback)\n }\n\n next(null, ...values)\n\n /**\n * Run the next `fn`, or we’re done.\n *\n * @param {Error | null | undefined} error\n * @param {Array} output\n */\n function next(error, ...output) {\n const fn = fns[++middlewareIndex]\n let index = -1\n\n if (error) {\n callback(error)\n return\n }\n\n // Copy non-nullish input into values.\n while (++index < values.length) {\n if (output[index] === null || output[index] === undefined) {\n output[index] = values[index]\n }\n }\n\n // Save the newly created `output` for the next call.\n values = output\n\n // Next or done.\n if (fn) {\n wrap(fn, next)(...output)\n } else {\n callback(null, ...output)\n }\n }\n }\n\n /** @type {Use} */\n function use(middelware) {\n if (typeof middelware !== 'function') {\n throw new TypeError(\n 'Expected `middelware` to be a function, not ' + middelware\n )\n }\n\n fns.push(middelware)\n return pipeline\n }\n}\n\n/**\n * Wrap `middleware` into a uniform interface.\n *\n * You can pass all input to the resulting function.\n * `callback` is then called with the output of `middleware`.\n *\n * If `middleware` accepts more arguments than the later given in input,\n * an extra `done` function is passed to it after that input,\n * which must be called by `middleware`.\n *\n * The first value in `input` is the main input value.\n * All other input values are the rest input values.\n * The values given to `callback` are the input values,\n * merged with every non-nullish output value.\n *\n * * if `middleware` throws an error,\n * returns a promise that is rejected,\n * or calls the given `done` function with an error,\n * `callback` is called with that error\n * * if `middleware` returns a value or returns a promise that is resolved,\n * that value is the main output value\n * * if `middleware` calls `done`,\n * all non-nullish values except for the first one (the error) overwrite the\n * output values\n *\n * @param {Middleware} middleware\n * Function to wrap.\n * @param {Callback} callback\n * Callback called with the output of `middleware`.\n * @returns {Run}\n * Wrapped middleware.\n */\nexport function wrap(middleware, callback) {\n /** @type {boolean} */\n let called\n\n return wrapped\n\n /**\n * Call `middleware`.\n * @this {any}\n * @param {Array} parameters\n * @returns {void}\n */\n function wrapped(...parameters) {\n const fnExpectsCallback = middleware.length > parameters.length\n /** @type {any} */\n let result\n\n if (fnExpectsCallback) {\n parameters.push(done)\n }\n\n try {\n result = middleware.apply(this, parameters)\n } catch (error) {\n const exception = /** @type {Error} */ (error)\n\n // Well, this is quite the pickle.\n // `middleware` received a callback and called it synchronously, but that\n // threw an error.\n // The only thing left to do is to throw the thing instead.\n if (fnExpectsCallback && called) {\n throw exception\n }\n\n return done(exception)\n }\n\n if (!fnExpectsCallback) {\n if (result && result.then && typeof result.then === 'function') {\n result.then(then, done)\n } else if (result instanceof Error) {\n done(result)\n } else {\n then(result)\n }\n }\n }\n\n /**\n * Call `callback`, only once.\n *\n * @type {Callback}\n */\n function done(error, ...output) {\n if (!called) {\n called = true\n callback(error, ...output)\n }\n }\n\n /**\n * Call `done` with one value.\n *\n * @param {any} [value]\n */\n function then(value) {\n done(null, value)\n }\n}\n", "/**\n * @typedef {import('unist').Node} Node\n * @typedef {import('unist').Point} Point\n * @typedef {import('unist').Position} Position\n */\n\n/**\n * @typedef NodeLike\n * @property {string} type\n * @property {PositionLike | null | undefined} [position]\n *\n * @typedef PointLike\n * @property {number | null | undefined} [line]\n * @property {number | null | undefined} [column]\n * @property {number | null | undefined} [offset]\n *\n * @typedef PositionLike\n * @property {PointLike | null | undefined} [start]\n * @property {PointLike | null | undefined} [end]\n */\n\n/**\n * Serialize the positional info of a point, position (start and end points),\n * or node.\n *\n * @param {Node | NodeLike | Point | PointLike | Position | PositionLike | null | undefined} [value]\n * Node, position, or point.\n * @returns {string}\n * Pretty printed positional info of a node (`string`).\n *\n * In the format of a range `ls:cs-le:ce` (when given `node` or `position`)\n * or a point `l:c` (when given `point`), where `l` stands for line, `c` for\n * column, `s` for `start`, and `e` for end.\n * An empty string (`''`) is returned if the given value is neither `node`,\n * `position`, nor `point`.\n */\nexport function stringifyPosition(value) {\n // Nothing.\n if (!value || typeof value !== 'object') {\n return ''\n }\n\n // Node.\n if ('position' in value || 'type' in value) {\n return position(value.position)\n }\n\n // Position.\n if ('start' in value || 'end' in value) {\n return position(value)\n }\n\n // Point.\n if ('line' in value || 'column' in value) {\n return point(value)\n }\n\n // ?\n return ''\n}\n\n/**\n * @param {Point | PointLike | null | undefined} point\n * @returns {string}\n */\nfunction point(point) {\n return index(point && point.line) + ':' + index(point && point.column)\n}\n\n/**\n * @param {Position | PositionLike | null | undefined} pos\n * @returns {string}\n */\nfunction position(pos) {\n return point(pos && pos.start) + '-' + point(pos && pos.end)\n}\n\n/**\n * @param {number | null | undefined} value\n * @returns {number}\n */\nfunction index(value) {\n return value && typeof value === 'number' ? value : 1\n}\n", "/**\n * @import {Node, Point, Position} from 'unist'\n */\n\n/**\n * @typedef {object & {type: string, position?: Position | undefined}} NodeLike\n *\n * @typedef Options\n * Configuration.\n * @property {Array | null | undefined} [ancestors]\n * Stack of (inclusive) ancestor nodes surrounding the message (optional).\n * @property {Error | null | undefined} [cause]\n * Original error cause of the message (optional).\n * @property {Point | Position | null | undefined} [place]\n * Place of message (optional).\n * @property {string | null | undefined} [ruleId]\n * Category of message (optional, example: `'my-rule'`).\n * @property {string | null | undefined} [source]\n * Namespace of who sent the message (optional, example: `'my-package'`).\n */\n\nimport {stringifyPosition} from 'unist-util-stringify-position'\n\n/**\n * Message.\n */\nexport class VFileMessage extends Error {\n /**\n * Create a message for `reason`.\n *\n * > 🪦 **Note**: also has obsolete signatures.\n *\n * @overload\n * @param {string} reason\n * @param {Options | null | undefined} [options]\n * @returns\n *\n * @overload\n * @param {string} reason\n * @param {Node | NodeLike | null | undefined} parent\n * @param {string | null | undefined} [origin]\n * @returns\n *\n * @overload\n * @param {string} reason\n * @param {Point | Position | null | undefined} place\n * @param {string | null | undefined} [origin]\n * @returns\n *\n * @overload\n * @param {string} reason\n * @param {string | null | undefined} [origin]\n * @returns\n *\n * @overload\n * @param {Error | VFileMessage} cause\n * @param {Node | NodeLike | null | undefined} parent\n * @param {string | null | undefined} [origin]\n * @returns\n *\n * @overload\n * @param {Error | VFileMessage} cause\n * @param {Point | Position | null | undefined} place\n * @param {string | null | undefined} [origin]\n * @returns\n *\n * @overload\n * @param {Error | VFileMessage} cause\n * @param {string | null | undefined} [origin]\n * @returns\n *\n * @param {Error | VFileMessage | string} causeOrReason\n * Reason for message, should use markdown.\n * @param {Node | NodeLike | Options | Point | Position | string | null | undefined} [optionsOrParentOrPlace]\n * Configuration (optional).\n * @param {string | null | undefined} [origin]\n * Place in code where the message originates (example:\n * `'my-package:my-rule'` or `'my-rule'`).\n * @returns\n * Instance of `VFileMessage`.\n */\n // eslint-disable-next-line complexity\n constructor(causeOrReason, optionsOrParentOrPlace, origin) {\n super()\n\n if (typeof optionsOrParentOrPlace === 'string') {\n origin = optionsOrParentOrPlace\n optionsOrParentOrPlace = undefined\n }\n\n /** @type {string} */\n let reason = ''\n /** @type {Options} */\n let options = {}\n let legacyCause = false\n\n if (optionsOrParentOrPlace) {\n // Point.\n if (\n 'line' in optionsOrParentOrPlace &&\n 'column' in optionsOrParentOrPlace\n ) {\n options = {place: optionsOrParentOrPlace}\n }\n // Position.\n else if (\n 'start' in optionsOrParentOrPlace &&\n 'end' in optionsOrParentOrPlace\n ) {\n options = {place: optionsOrParentOrPlace}\n }\n // Node.\n else if ('type' in optionsOrParentOrPlace) {\n options = {\n ancestors: [optionsOrParentOrPlace],\n place: optionsOrParentOrPlace.position\n }\n }\n // Options.\n else {\n options = {...optionsOrParentOrPlace}\n }\n }\n\n if (typeof causeOrReason === 'string') {\n reason = causeOrReason\n }\n // Error.\n else if (!options.cause && causeOrReason) {\n legacyCause = true\n reason = causeOrReason.message\n options.cause = causeOrReason\n }\n\n if (!options.ruleId && !options.source && typeof origin === 'string') {\n const index = origin.indexOf(':')\n\n if (index === -1) {\n options.ruleId = origin\n } else {\n options.source = origin.slice(0, index)\n options.ruleId = origin.slice(index + 1)\n }\n }\n\n if (!options.place && options.ancestors && options.ancestors) {\n const parent = options.ancestors[options.ancestors.length - 1]\n\n if (parent) {\n options.place = parent.position\n }\n }\n\n const start =\n options.place && 'start' in options.place\n ? options.place.start\n : options.place\n\n /**\n * Stack of ancestor nodes surrounding the message.\n *\n * @type {Array | undefined}\n */\n this.ancestors = options.ancestors || undefined\n\n /**\n * Original error cause of the message.\n *\n * @type {Error | undefined}\n */\n this.cause = options.cause || undefined\n\n /**\n * Starting column of message.\n *\n * @type {number | undefined}\n */\n this.column = start ? start.column : undefined\n\n /**\n * State of problem.\n *\n * * `true` — error, file not usable\n * * `false` — warning, change may be needed\n * * `undefined` — change likely not needed\n *\n * @type {boolean | null | undefined}\n */\n this.fatal = undefined\n\n /**\n * Path of a file (used throughout the `VFile` ecosystem).\n *\n * @type {string | undefined}\n */\n this.file = ''\n\n // Field from `Error`.\n /**\n * Reason for message.\n *\n * @type {string}\n */\n this.message = reason\n\n /**\n * Starting line of error.\n *\n * @type {number | undefined}\n */\n this.line = start ? start.line : undefined\n\n // Field from `Error`.\n /**\n * Serialized positional info of message.\n *\n * On normal errors, this would be something like `ParseError`, buit in\n * `VFile` messages we use this space to show where an error happened.\n */\n this.name = stringifyPosition(options.place) || '1:1'\n\n /**\n * Place of message.\n *\n * @type {Point | Position | undefined}\n */\n this.place = options.place || undefined\n\n /**\n * Reason for message, should use markdown.\n *\n * @type {string}\n */\n this.reason = this.message\n\n /**\n * Category of message (example: `'my-rule'`).\n *\n * @type {string | undefined}\n */\n this.ruleId = options.ruleId || undefined\n\n /**\n * Namespace of message (example: `'my-package'`).\n *\n * @type {string | undefined}\n */\n this.source = options.source || undefined\n\n // Field from `Error`.\n /**\n * Stack of message.\n *\n * This is used by normal errors to show where something happened in\n * programming code, irrelevant for `VFile` messages,\n *\n * @type {string}\n */\n this.stack =\n legacyCause && options.cause && typeof options.cause.stack === 'string'\n ? options.cause.stack\n : ''\n\n // The following fields are “well known”.\n // Not standard.\n // Feel free to add other non-standard fields to your messages.\n\n /**\n * Specify the source value that’s being reported, which is deemed\n * incorrect.\n *\n * @type {string | undefined}\n */\n this.actual = undefined\n\n /**\n * Suggest acceptable values that can be used instead of `actual`.\n *\n * @type {Array | undefined}\n */\n this.expected = undefined\n\n /**\n * Long form description of the message (you should use markdown).\n *\n * @type {string | undefined}\n */\n this.note = undefined\n\n /**\n * Link to docs for the message.\n *\n * > 👉 **Note**: this must be an absolute URL that can be passed as `x`\n * > to `new URL(x)`.\n *\n * @type {string | undefined}\n */\n this.url = undefined\n }\n}\n\nVFileMessage.prototype.file = ''\nVFileMessage.prototype.name = ''\nVFileMessage.prototype.reason = ''\nVFileMessage.prototype.message = ''\nVFileMessage.prototype.stack = ''\nVFileMessage.prototype.column = undefined\nVFileMessage.prototype.line = undefined\nVFileMessage.prototype.ancestors = undefined\nVFileMessage.prototype.cause = undefined\nVFileMessage.prototype.fatal = undefined\nVFileMessage.prototype.place = undefined\nVFileMessage.prototype.ruleId = undefined\nVFileMessage.prototype.source = undefined\n", "// A derivative work based on:\n// .\n// Which is licensed:\n//\n// MIT License\n//\n// Copyright (c) 2013 James Halliday\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy of\n// this software and associated documentation files (the \"Software\"), to deal in\n// the Software without restriction, including without limitation the rights to\n// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of\n// the Software, and to permit persons to whom the Software is furnished to do so,\n// subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in all\n// copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS\n// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR\n// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER\n// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\n// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n// A derivative work based on:\n//\n// Parts of that are extracted from Node’s internal `path` module:\n// .\n// Which is licensed:\n//\n// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\nexport const minpath = {basename, dirname, extname, join, sep: '/'}\n\n/* eslint-disable max-depth, complexity */\n\n/**\n * Get the basename from a path.\n *\n * @param {string} path\n * File path.\n * @param {string | null | undefined} [extname]\n * Extension to strip.\n * @returns {string}\n * Stem or basename.\n */\nfunction basename(path, extname) {\n if (extname !== undefined && typeof extname !== 'string') {\n throw new TypeError('\"ext\" argument must be a string')\n }\n\n assertPath(path)\n let start = 0\n let end = -1\n let index = path.length\n /** @type {boolean | undefined} */\n let seenNonSlash\n\n if (\n extname === undefined ||\n extname.length === 0 ||\n extname.length > path.length\n ) {\n while (index--) {\n if (path.codePointAt(index) === 47 /* `/` */) {\n // If we reached a path separator that was not part of a set of path\n // separators at the end of the string, stop now.\n if (seenNonSlash) {\n start = index + 1\n break\n }\n } else if (end < 0) {\n // We saw the first non-path separator, mark this as the end of our\n // path component.\n seenNonSlash = true\n end = index + 1\n }\n }\n\n return end < 0 ? '' : path.slice(start, end)\n }\n\n if (extname === path) {\n return ''\n }\n\n let firstNonSlashEnd = -1\n let extnameIndex = extname.length - 1\n\n while (index--) {\n if (path.codePointAt(index) === 47 /* `/` */) {\n // If we reached a path separator that was not part of a set of path\n // separators at the end of the string, stop now.\n if (seenNonSlash) {\n start = index + 1\n break\n }\n } else {\n if (firstNonSlashEnd < 0) {\n // We saw the first non-path separator, remember this index in case\n // we need it if the extension ends up not matching.\n seenNonSlash = true\n firstNonSlashEnd = index + 1\n }\n\n if (extnameIndex > -1) {\n // Try to match the explicit extension.\n if (path.codePointAt(index) === extname.codePointAt(extnameIndex--)) {\n if (extnameIndex < 0) {\n // We matched the extension, so mark this as the end of our path\n // component\n end = index\n }\n } else {\n // Extension does not match, so our result is the entire path\n // component\n extnameIndex = -1\n end = firstNonSlashEnd\n }\n }\n }\n }\n\n if (start === end) {\n end = firstNonSlashEnd\n } else if (end < 0) {\n end = path.length\n }\n\n return path.slice(start, end)\n}\n\n/**\n * Get the dirname from a path.\n *\n * @param {string} path\n * File path.\n * @returns {string}\n * File path.\n */\nfunction dirname(path) {\n assertPath(path)\n\n if (path.length === 0) {\n return '.'\n }\n\n let end = -1\n let index = path.length\n /** @type {boolean | undefined} */\n let unmatchedSlash\n\n // Prefix `--` is important to not run on `0`.\n while (--index) {\n if (path.codePointAt(index) === 47 /* `/` */) {\n if (unmatchedSlash) {\n end = index\n break\n }\n } else if (!unmatchedSlash) {\n // We saw the first non-path separator\n unmatchedSlash = true\n }\n }\n\n return end < 0\n ? path.codePointAt(0) === 47 /* `/` */\n ? '/'\n : '.'\n : end === 1 && path.codePointAt(0) === 47 /* `/` */\n ? '//'\n : path.slice(0, end)\n}\n\n/**\n * Get an extname from a path.\n *\n * @param {string} path\n * File path.\n * @returns {string}\n * Extname.\n */\nfunction extname(path) {\n assertPath(path)\n\n let index = path.length\n\n let end = -1\n let startPart = 0\n let startDot = -1\n // Track the state of characters (if any) we see before our first dot and\n // after any path separator we find.\n let preDotState = 0\n /** @type {boolean | undefined} */\n let unmatchedSlash\n\n while (index--) {\n const code = path.codePointAt(index)\n\n if (code === 47 /* `/` */) {\n // If we reached a path separator that was not part of a set of path\n // separators at the end of the string, stop now.\n if (unmatchedSlash) {\n startPart = index + 1\n break\n }\n\n continue\n }\n\n if (end < 0) {\n // We saw the first non-path separator, mark this as the end of our\n // extension.\n unmatchedSlash = true\n end = index + 1\n }\n\n if (code === 46 /* `.` */) {\n // If this is our first dot, mark it as the start of our extension.\n if (startDot < 0) {\n startDot = index\n } else if (preDotState !== 1) {\n preDotState = 1\n }\n } else if (startDot > -1) {\n // We saw a non-dot and non-path separator before our dot, so we should\n // have a good chance at having a non-empty extension.\n preDotState = -1\n }\n }\n\n if (\n startDot < 0 ||\n end < 0 ||\n // We saw a non-dot character immediately before the dot.\n preDotState === 0 ||\n // The (right-most) trimmed path component is exactly `..`.\n (preDotState === 1 && startDot === end - 1 && startDot === startPart + 1)\n ) {\n return ''\n }\n\n return path.slice(startDot, end)\n}\n\n/**\n * Join segments from a path.\n *\n * @param {Array} segments\n * Path segments.\n * @returns {string}\n * File path.\n */\nfunction join(...segments) {\n let index = -1\n /** @type {string | undefined} */\n let joined\n\n while (++index < segments.length) {\n assertPath(segments[index])\n\n if (segments[index]) {\n joined =\n joined === undefined ? segments[index] : joined + '/' + segments[index]\n }\n }\n\n return joined === undefined ? '.' : normalize(joined)\n}\n\n/**\n * Normalize a basic file path.\n *\n * @param {string} path\n * File path.\n * @returns {string}\n * File path.\n */\n// Note: `normalize` is not exposed as `path.normalize`, so some code is\n// manually removed from it.\nfunction normalize(path) {\n assertPath(path)\n\n const absolute = path.codePointAt(0) === 47 /* `/` */\n\n // Normalize the path according to POSIX rules.\n let value = normalizeString(path, !absolute)\n\n if (value.length === 0 && !absolute) {\n value = '.'\n }\n\n if (value.length > 0 && path.codePointAt(path.length - 1) === 47 /* / */) {\n value += '/'\n }\n\n return absolute ? '/' + value : value\n}\n\n/**\n * Resolve `.` and `..` elements in a path with directory names.\n *\n * @param {string} path\n * File path.\n * @param {boolean} allowAboveRoot\n * Whether `..` can move above root.\n * @returns {string}\n * File path.\n */\nfunction normalizeString(path, allowAboveRoot) {\n let result = ''\n let lastSegmentLength = 0\n let lastSlash = -1\n let dots = 0\n let index = -1\n /** @type {number | undefined} */\n let code\n /** @type {number} */\n let lastSlashIndex\n\n while (++index <= path.length) {\n if (index < path.length) {\n code = path.codePointAt(index)\n } else if (code === 47 /* `/` */) {\n break\n } else {\n code = 47 /* `/` */\n }\n\n if (code === 47 /* `/` */) {\n if (lastSlash === index - 1 || dots === 1) {\n // Empty.\n } else if (lastSlash !== index - 1 && dots === 2) {\n if (\n result.length < 2 ||\n lastSegmentLength !== 2 ||\n result.codePointAt(result.length - 1) !== 46 /* `.` */ ||\n result.codePointAt(result.length - 2) !== 46 /* `.` */\n ) {\n if (result.length > 2) {\n lastSlashIndex = result.lastIndexOf('/')\n\n if (lastSlashIndex !== result.length - 1) {\n if (lastSlashIndex < 0) {\n result = ''\n lastSegmentLength = 0\n } else {\n result = result.slice(0, lastSlashIndex)\n lastSegmentLength = result.length - 1 - result.lastIndexOf('/')\n }\n\n lastSlash = index\n dots = 0\n continue\n }\n } else if (result.length > 0) {\n result = ''\n lastSegmentLength = 0\n lastSlash = index\n dots = 0\n continue\n }\n }\n\n if (allowAboveRoot) {\n result = result.length > 0 ? result + '/..' : '..'\n lastSegmentLength = 2\n }\n } else {\n if (result.length > 0) {\n result += '/' + path.slice(lastSlash + 1, index)\n } else {\n result = path.slice(lastSlash + 1, index)\n }\n\n lastSegmentLength = index - lastSlash - 1\n }\n\n lastSlash = index\n dots = 0\n } else if (code === 46 /* `.` */ && dots > -1) {\n dots++\n } else {\n dots = -1\n }\n }\n\n return result\n}\n\n/**\n * Make sure `path` is a string.\n *\n * @param {string} path\n * File path.\n * @returns {asserts path is string}\n * Nothing.\n */\nfunction assertPath(path) {\n if (typeof path !== 'string') {\n throw new TypeError(\n 'Path must be a string. Received ' + JSON.stringify(path)\n )\n }\n}\n\n/* eslint-enable max-depth, complexity */\n", "// Somewhat based on:\n// .\n// But I don’t think one tiny line of code can be copyrighted. 😅\nexport const minproc = {cwd}\n\nfunction cwd() {\n return '/'\n}\n", "/**\n * Checks if a value has the shape of a WHATWG URL object.\n *\n * Using a symbol or instanceof would not be able to recognize URL objects\n * coming from other implementations (e.g. in Electron), so instead we are\n * checking some well known properties for a lack of a better test.\n *\n * We use `href` and `protocol` as they are the only properties that are\n * easy to retrieve and calculate due to the lazy nature of the getters.\n *\n * We check for auth attribute to distinguish legacy url instance with\n * WHATWG URL instance.\n *\n * @param {unknown} fileUrlOrPath\n * File path or URL.\n * @returns {fileUrlOrPath is URL}\n * Whether it’s a URL.\n */\n// From: \nexport function isUrl(fileUrlOrPath) {\n return Boolean(\n fileUrlOrPath !== null &&\n typeof fileUrlOrPath === 'object' &&\n 'href' in fileUrlOrPath &&\n fileUrlOrPath.href &&\n 'protocol' in fileUrlOrPath &&\n fileUrlOrPath.protocol &&\n // @ts-expect-error: indexing is fine.\n fileUrlOrPath.auth === undefined\n )\n}\n", "import {isUrl} from './minurl.shared.js'\n\nexport {isUrl} from './minurl.shared.js'\n\n// See: \n\n/**\n * @param {URL | string} path\n * File URL.\n * @returns {string}\n * File URL.\n */\nexport function urlToPath(path) {\n if (typeof path === 'string') {\n path = new URL(path)\n } else if (!isUrl(path)) {\n /** @type {NodeJS.ErrnoException} */\n const error = new TypeError(\n 'The \"path\" argument must be of type string or an instance of URL. Received `' +\n path +\n '`'\n )\n error.code = 'ERR_INVALID_ARG_TYPE'\n throw error\n }\n\n if (path.protocol !== 'file:') {\n /** @type {NodeJS.ErrnoException} */\n const error = new TypeError('The URL must be of scheme file')\n error.code = 'ERR_INVALID_URL_SCHEME'\n throw error\n }\n\n return getPathFromURLPosix(path)\n}\n\n/**\n * Get a path from a POSIX URL.\n *\n * @param {URL} url\n * URL.\n * @returns {string}\n * File path.\n */\nfunction getPathFromURLPosix(url) {\n if (url.hostname !== '') {\n /** @type {NodeJS.ErrnoException} */\n const error = new TypeError(\n 'File URL host must be \"localhost\" or empty on darwin'\n )\n error.code = 'ERR_INVALID_FILE_URL_HOST'\n throw error\n }\n\n const pathname = url.pathname\n let index = -1\n\n while (++index < pathname.length) {\n if (\n pathname.codePointAt(index) === 37 /* `%` */ &&\n pathname.codePointAt(index + 1) === 50 /* `2` */\n ) {\n const third = pathname.codePointAt(index + 2)\n if (third === 70 /* `F` */ || third === 102 /* `f` */) {\n /** @type {NodeJS.ErrnoException} */\n const error = new TypeError(\n 'File URL path must not include encoded / characters'\n )\n error.code = 'ERR_INVALID_FILE_URL_PATH'\n throw error\n }\n }\n }\n\n return decodeURIComponent(pathname)\n}\n", "/**\n * @import {Node, Point, Position} from 'unist'\n * @import {Options as MessageOptions} from 'vfile-message'\n * @import {Compatible, Data, Map, Options, Value} from 'vfile'\n */\n\n/**\n * @typedef {object & {type: string, position?: Position | undefined}} NodeLike\n */\n\nimport {VFileMessage} from 'vfile-message'\nimport {minpath} from '#minpath'\nimport {minproc} from '#minproc'\nimport {urlToPath, isUrl} from '#minurl'\n\n/**\n * Order of setting (least specific to most), we need this because otherwise\n * `{stem: 'a', path: '~/b.js'}` would throw, as a path is needed before a\n * stem can be set.\n */\nconst order = /** @type {const} */ ([\n 'history',\n 'path',\n 'basename',\n 'stem',\n 'extname',\n 'dirname'\n])\n\nexport class VFile {\n /**\n * Create a new virtual file.\n *\n * `options` is treated as:\n *\n * * `string` or `Uint8Array` — `{value: options}`\n * * `URL` — `{path: options}`\n * * `VFile` — shallow copies its data over to the new file\n * * `object` — all fields are shallow copied over to the new file\n *\n * Path related fields are set in the following order (least specific to\n * most specific): `history`, `path`, `basename`, `stem`, `extname`,\n * `dirname`.\n *\n * You cannot set `dirname` or `extname` without setting either `history`,\n * `path`, `basename`, or `stem` too.\n *\n * @param {Compatible | null | undefined} [value]\n * File value.\n * @returns\n * New instance.\n */\n constructor(value) {\n /** @type {Options | VFile} */\n let options\n\n if (!value) {\n options = {}\n } else if (isUrl(value)) {\n options = {path: value}\n } else if (typeof value === 'string' || isUint8Array(value)) {\n options = {value}\n } else {\n options = value\n }\n\n /* eslint-disable no-unused-expressions */\n\n /**\n * Base of `path` (default: `process.cwd()` or `'/'` in browsers).\n *\n * @type {string}\n */\n // Prevent calling `cwd` (which could be expensive) if it’s not needed;\n // the empty string will be overridden in the next block.\n this.cwd = 'cwd' in options ? '' : minproc.cwd()\n\n /**\n * Place to store custom info (default: `{}`).\n *\n * It’s OK to store custom data directly on the file but moving it to\n * `data` is recommended.\n *\n * @type {Data}\n */\n this.data = {}\n\n /**\n * List of file paths the file moved between.\n *\n * The first is the original path and the last is the current path.\n *\n * @type {Array}\n */\n this.history = []\n\n /**\n * List of messages associated with the file.\n *\n * @type {Array}\n */\n this.messages = []\n\n /**\n * Raw value.\n *\n * @type {Value}\n */\n this.value\n\n // The below are non-standard, they are “well-known”.\n // As in, used in several tools.\n /**\n * Source map.\n *\n * This type is equivalent to the `RawSourceMap` type from the `source-map`\n * module.\n *\n * @type {Map | null | undefined}\n */\n this.map\n\n /**\n * Custom, non-string, compiled, representation.\n *\n * This is used by unified to store non-string results.\n * One example is when turning markdown into React nodes.\n *\n * @type {unknown}\n */\n this.result\n\n /**\n * Whether a file was saved to disk.\n *\n * This is used by vfile reporters.\n *\n * @type {boolean}\n */\n this.stored\n /* eslint-enable no-unused-expressions */\n\n // Set path related properties in the correct order.\n let index = -1\n\n while (++index < order.length) {\n const field = order[index]\n\n // Note: we specifically use `in` instead of `hasOwnProperty` to accept\n // `vfile`s too.\n if (\n field in options &&\n options[field] !== undefined &&\n options[field] !== null\n ) {\n // @ts-expect-error: TS doesn’t understand basic reality.\n this[field] = field === 'history' ? [...options[field]] : options[field]\n }\n }\n\n /** @type {string} */\n let field\n\n // Set non-path related properties.\n for (field in options) {\n // @ts-expect-error: fine to set other things.\n if (!order.includes(field)) {\n // @ts-expect-error: fine to set other things.\n this[field] = options[field]\n }\n }\n }\n\n /**\n * Get the basename (including extname) (example: `'index.min.js'`).\n *\n * @returns {string | undefined}\n * Basename.\n */\n get basename() {\n return typeof this.path === 'string'\n ? minpath.basename(this.path)\n : undefined\n }\n\n /**\n * Set basename (including extname) (`'index.min.js'`).\n *\n * Cannot contain path separators (`'/'` on unix, macOS, and browsers, `'\\'`\n * on windows).\n * Cannot be nullified (use `file.path = file.dirname` instead).\n *\n * @param {string} basename\n * Basename.\n * @returns {undefined}\n * Nothing.\n */\n set basename(basename) {\n assertNonEmpty(basename, 'basename')\n assertPart(basename, 'basename')\n this.path = minpath.join(this.dirname || '', basename)\n }\n\n /**\n * Get the parent path (example: `'~'`).\n *\n * @returns {string | undefined}\n * Dirname.\n */\n get dirname() {\n return typeof this.path === 'string'\n ? minpath.dirname(this.path)\n : undefined\n }\n\n /**\n * Set the parent path (example: `'~'`).\n *\n * Cannot be set if there’s no `path` yet.\n *\n * @param {string | undefined} dirname\n * Dirname.\n * @returns {undefined}\n * Nothing.\n */\n set dirname(dirname) {\n assertPath(this.basename, 'dirname')\n this.path = minpath.join(dirname || '', this.basename)\n }\n\n /**\n * Get the extname (including dot) (example: `'.js'`).\n *\n * @returns {string | undefined}\n * Extname.\n */\n get extname() {\n return typeof this.path === 'string'\n ? minpath.extname(this.path)\n : undefined\n }\n\n /**\n * Set the extname (including dot) (example: `'.js'`).\n *\n * Cannot contain path separators (`'/'` on unix, macOS, and browsers, `'\\'`\n * on windows).\n * Cannot be set if there’s no `path` yet.\n *\n * @param {string | undefined} extname\n * Extname.\n * @returns {undefined}\n * Nothing.\n */\n set extname(extname) {\n assertPart(extname, 'extname')\n assertPath(this.dirname, 'extname')\n\n if (extname) {\n if (extname.codePointAt(0) !== 46 /* `.` */) {\n throw new Error('`extname` must start with `.`')\n }\n\n if (extname.includes('.', 1)) {\n throw new Error('`extname` cannot contain multiple dots')\n }\n }\n\n this.path = minpath.join(this.dirname, this.stem + (extname || ''))\n }\n\n /**\n * Get the full path (example: `'~/index.min.js'`).\n *\n * @returns {string}\n * Path.\n */\n get path() {\n return this.history[this.history.length - 1]\n }\n\n /**\n * Set the full path (example: `'~/index.min.js'`).\n *\n * Cannot be nullified.\n * You can set a file URL (a `URL` object with a `file:` protocol) which will\n * be turned into a path with `url.fileURLToPath`.\n *\n * @param {URL | string} path\n * Path.\n * @returns {undefined}\n * Nothing.\n */\n set path(path) {\n if (isUrl(path)) {\n path = urlToPath(path)\n }\n\n assertNonEmpty(path, 'path')\n\n if (this.path !== path) {\n this.history.push(path)\n }\n }\n\n /**\n * Get the stem (basename w/o extname) (example: `'index.min'`).\n *\n * @returns {string | undefined}\n * Stem.\n */\n get stem() {\n return typeof this.path === 'string'\n ? minpath.basename(this.path, this.extname)\n : undefined\n }\n\n /**\n * Set the stem (basename w/o extname) (example: `'index.min'`).\n *\n * Cannot contain path separators (`'/'` on unix, macOS, and browsers, `'\\'`\n * on windows).\n * Cannot be nullified (use `file.path = file.dirname` instead).\n *\n * @param {string} stem\n * Stem.\n * @returns {undefined}\n * Nothing.\n */\n set stem(stem) {\n assertNonEmpty(stem, 'stem')\n assertPart(stem, 'stem')\n this.path = minpath.join(this.dirname || '', stem + (this.extname || ''))\n }\n\n // Normal prototypal methods.\n /**\n * Create a fatal message for `reason` associated with the file.\n *\n * The `fatal` field of the message is set to `true` (error; file not usable)\n * and the `file` field is set to the current file path.\n * The message is added to the `messages` field on `file`.\n *\n * > 🪦 **Note**: also has obsolete signatures.\n *\n * @overload\n * @param {string} reason\n * @param {MessageOptions | null | undefined} [options]\n * @returns {never}\n *\n * @overload\n * @param {string} reason\n * @param {Node | NodeLike | null | undefined} parent\n * @param {string | null | undefined} [origin]\n * @returns {never}\n *\n * @overload\n * @param {string} reason\n * @param {Point | Position | null | undefined} place\n * @param {string | null | undefined} [origin]\n * @returns {never}\n *\n * @overload\n * @param {string} reason\n * @param {string | null | undefined} [origin]\n * @returns {never}\n *\n * @overload\n * @param {Error | VFileMessage} cause\n * @param {Node | NodeLike | null | undefined} parent\n * @param {string | null | undefined} [origin]\n * @returns {never}\n *\n * @overload\n * @param {Error | VFileMessage} cause\n * @param {Point | Position | null | undefined} place\n * @param {string | null | undefined} [origin]\n * @returns {never}\n *\n * @overload\n * @param {Error | VFileMessage} cause\n * @param {string | null | undefined} [origin]\n * @returns {never}\n *\n * @param {Error | VFileMessage | string} causeOrReason\n * Reason for message, should use markdown.\n * @param {Node | NodeLike | MessageOptions | Point | Position | string | null | undefined} [optionsOrParentOrPlace]\n * Configuration (optional).\n * @param {string | null | undefined} [origin]\n * Place in code where the message originates (example:\n * `'my-package:my-rule'` or `'my-rule'`).\n * @returns {never}\n * Never.\n * @throws {VFileMessage}\n * Message.\n */\n fail(causeOrReason, optionsOrParentOrPlace, origin) {\n // @ts-expect-error: the overloads are fine.\n const message = this.message(causeOrReason, optionsOrParentOrPlace, origin)\n\n message.fatal = true\n\n throw message\n }\n\n /**\n * Create an info message for `reason` associated with the file.\n *\n * The `fatal` field of the message is set to `undefined` (info; change\n * likely not needed) and the `file` field is set to the current file path.\n * The message is added to the `messages` field on `file`.\n *\n * > 🪦 **Note**: also has obsolete signatures.\n *\n * @overload\n * @param {string} reason\n * @param {MessageOptions | null | undefined} [options]\n * @returns {VFileMessage}\n *\n * @overload\n * @param {string} reason\n * @param {Node | NodeLike | null | undefined} parent\n * @param {string | null | undefined} [origin]\n * @returns {VFileMessage}\n *\n * @overload\n * @param {string} reason\n * @param {Point | Position | null | undefined} place\n * @param {string | null | undefined} [origin]\n * @returns {VFileMessage}\n *\n * @overload\n * @param {string} reason\n * @param {string | null | undefined} [origin]\n * @returns {VFileMessage}\n *\n * @overload\n * @param {Error | VFileMessage} cause\n * @param {Node | NodeLike | null | undefined} parent\n * @param {string | null | undefined} [origin]\n * @returns {VFileMessage}\n *\n * @overload\n * @param {Error | VFileMessage} cause\n * @param {Point | Position | null | undefined} place\n * @param {string | null | undefined} [origin]\n * @returns {VFileMessage}\n *\n * @overload\n * @param {Error | VFileMessage} cause\n * @param {string | null | undefined} [origin]\n * @returns {VFileMessage}\n *\n * @param {Error | VFileMessage | string} causeOrReason\n * Reason for message, should use markdown.\n * @param {Node | NodeLike | MessageOptions | Point | Position | string | null | undefined} [optionsOrParentOrPlace]\n * Configuration (optional).\n * @param {string | null | undefined} [origin]\n * Place in code where the message originates (example:\n * `'my-package:my-rule'` or `'my-rule'`).\n * @returns {VFileMessage}\n * Message.\n */\n info(causeOrReason, optionsOrParentOrPlace, origin) {\n // @ts-expect-error: the overloads are fine.\n const message = this.message(causeOrReason, optionsOrParentOrPlace, origin)\n\n message.fatal = undefined\n\n return message\n }\n\n /**\n * Create a message for `reason` associated with the file.\n *\n * The `fatal` field of the message is set to `false` (warning; change may be\n * needed) and the `file` field is set to the current file path.\n * The message is added to the `messages` field on `file`.\n *\n * > 🪦 **Note**: also has obsolete signatures.\n *\n * @overload\n * @param {string} reason\n * @param {MessageOptions | null | undefined} [options]\n * @returns {VFileMessage}\n *\n * @overload\n * @param {string} reason\n * @param {Node | NodeLike | null | undefined} parent\n * @param {string | null | undefined} [origin]\n * @returns {VFileMessage}\n *\n * @overload\n * @param {string} reason\n * @param {Point | Position | null | undefined} place\n * @param {string | null | undefined} [origin]\n * @returns {VFileMessage}\n *\n * @overload\n * @param {string} reason\n * @param {string | null | undefined} [origin]\n * @returns {VFileMessage}\n *\n * @overload\n * @param {Error | VFileMessage} cause\n * @param {Node | NodeLike | null | undefined} parent\n * @param {string | null | undefined} [origin]\n * @returns {VFileMessage}\n *\n * @overload\n * @param {Error | VFileMessage} cause\n * @param {Point | Position | null | undefined} place\n * @param {string | null | undefined} [origin]\n * @returns {VFileMessage}\n *\n * @overload\n * @param {Error | VFileMessage} cause\n * @param {string | null | undefined} [origin]\n * @returns {VFileMessage}\n *\n * @param {Error | VFileMessage | string} causeOrReason\n * Reason for message, should use markdown.\n * @param {Node | NodeLike | MessageOptions | Point | Position | string | null | undefined} [optionsOrParentOrPlace]\n * Configuration (optional).\n * @param {string | null | undefined} [origin]\n * Place in code where the message originates (example:\n * `'my-package:my-rule'` or `'my-rule'`).\n * @returns {VFileMessage}\n * Message.\n */\n message(causeOrReason, optionsOrParentOrPlace, origin) {\n const message = new VFileMessage(\n // @ts-expect-error: the overloads are fine.\n causeOrReason,\n optionsOrParentOrPlace,\n origin\n )\n\n if (this.path) {\n message.name = this.path + ':' + message.name\n message.file = this.path\n }\n\n message.fatal = false\n\n this.messages.push(message)\n\n return message\n }\n\n /**\n * Serialize the file.\n *\n * > **Note**: which encodings are supported depends on the engine.\n * > For info on Node.js, see:\n * > .\n *\n * @param {string | null | undefined} [encoding='utf8']\n * Character encoding to understand `value` as when it’s a `Uint8Array`\n * (default: `'utf-8'`).\n * @returns {string}\n * Serialized file.\n */\n toString(encoding) {\n if (this.value === undefined) {\n return ''\n }\n\n if (typeof this.value === 'string') {\n return this.value\n }\n\n const decoder = new TextDecoder(encoding || undefined)\n return decoder.decode(this.value)\n }\n}\n\n/**\n * Assert that `part` is not a path (as in, does not contain `path.sep`).\n *\n * @param {string | null | undefined} part\n * File path part.\n * @param {string} name\n * Part name.\n * @returns {undefined}\n * Nothing.\n */\nfunction assertPart(part, name) {\n if (part && part.includes(minpath.sep)) {\n throw new Error(\n '`' + name + '` cannot be a path: did not expect `' + minpath.sep + '`'\n )\n }\n}\n\n/**\n * Assert that `part` is not empty.\n *\n * @param {string | undefined} part\n * Thing.\n * @param {string} name\n * Part name.\n * @returns {asserts part is string}\n * Nothing.\n */\nfunction assertNonEmpty(part, name) {\n if (!part) {\n throw new Error('`' + name + '` cannot be empty')\n }\n}\n\n/**\n * Assert `path` exists.\n *\n * @param {string | undefined} path\n * Path.\n * @param {string} name\n * Dependency name.\n * @returns {asserts path is string}\n * Nothing.\n */\nfunction assertPath(path, name) {\n if (!path) {\n throw new Error('Setting `' + name + '` requires `path` to be set too')\n }\n}\n\n/**\n * Assert `value` is an `Uint8Array`.\n *\n * @param {unknown} value\n * thing.\n * @returns {value is Uint8Array}\n * Whether `value` is an `Uint8Array`.\n */\nfunction isUint8Array(value) {\n return Boolean(\n value &&\n typeof value === 'object' &&\n 'byteLength' in value &&\n 'byteOffset' in value\n )\n}\n", "export const CallableInstance =\n /**\n * @type {new , Result>(property: string | symbol) => (...parameters: Parameters) => Result}\n */\n (\n /** @type {unknown} */\n (\n /**\n * @this {Function}\n * @param {string | symbol} property\n * @returns {(...parameters: Array) => unknown}\n */\n function (property) {\n const self = this\n const constr = self.constructor\n const proto = /** @type {Record} */ (\n // Prototypes do exist.\n // type-coverage:ignore-next-line\n constr.prototype\n )\n const value = proto[property]\n /** @type {(...parameters: Array) => unknown} */\n const apply = function () {\n return value.apply(apply, arguments)\n }\n\n Object.setPrototypeOf(apply, proto)\n\n // Not needed for us in `unified`: we only call this on the `copy`\n // function,\n // and we don't need to add its fields (`length`, `name`)\n // over.\n // See also: GH-246.\n // const names = Object.getOwnPropertyNames(value)\n //\n // for (const p of names) {\n // const descriptor = Object.getOwnPropertyDescriptor(value, p)\n // if (descriptor) Object.defineProperty(apply, p, descriptor)\n // }\n\n return apply\n }\n )\n )\n", "export const Expressions = {\n get url() {\n return /(?:https?|wss?|ircs?|s?ftp):\\/\\/([a-zA-Z0-9\\.\\-]+\\.[a-zA-Z]+(?::\\d+)?)([\\/\\?#][\\p{L}\\p{N}\\p{M}&\\.-\\/\\?=#\\-@%\\+_,:!~*]*)?/gu;\n },\n get link() {\n return /https?:\\/\\/([a-zA-Z0-9\\.\\-]+\\.[a-zA-Z]+(?::\\d+)?)([\\/\\?#][\\p{L}\\p{N}\\p{M}&\\.-\\/\\?=#\\-@%\\+_,:!~*]*)?/gu;\n },\n get cashu() {\n return /(?:cashu:\\/{0,2})?(cashu(?:A|B)[A-Za-z0-9_-]{100,}={0,3})/gi;\n },\n get nostrLink() {\n return /(?:nostr:)?((npub|note|nprofile|nevent|naddr)1[qpzry9x8gf2tvdw0s3jn54khce6mua7l]{58,})/gi;\n },\n get emoji() {\n return /:([a-zA-Z0-9_-]+):/gi;\n },\n get hashtag() {\n // NOTE: cant use \\b here because it uses \\w which only matches latin letters\n return /(?<=^|[^\\p{L}#\\/])#([\\p{L}\\p{N}\\p{M}]+)(?=\\p{Z}|$|\\s)/gu;\n },\n get lightning() {\n return /(?:lightning:)?(LNBC[A-Za-z0-9]+)/gim;\n },\n};\n/** A list of Regular Expressions that match tokens surrounded by whitespace to avoid matching in URLs */\nexport const Tokens = {\n get url() {\n return Expressions.url;\n },\n get link() {\n return Expressions.link;\n },\n get cashu() {\n return new RegExp(`(?<=^|\\\\s)${Expressions.cashu.source}`, \"gi\");\n },\n get nostrLink() {\n return new RegExp(`(?<=^|\\\\s)${Expressions.nostrLink.source}`, \"gi\");\n },\n get emoji() {\n return Expressions.emoji;\n },\n get hashtag() {\n return Expressions.hashtag;\n },\n get lightning() {\n return new RegExp(`(?<=^|\\\\s)${Expressions.lightning.source}`, \"gim\");\n },\n};\n", "import { decode } from \"nostr-tools/nip19\";\nimport { Tokens } from \"../helpers/regexp.js\";\nimport { findAndReplace } from \"../nast/find-and-replace.js\";\n/** Finds and creates NIP-19 nostr mentions in the tree */\nexport function nostrMentions() {\n return (tree) => {\n findAndReplace(tree, [\n [\n Tokens.nostrLink,\n (_, $1) => {\n try {\n return {\n type: \"mention\",\n decoded: decode($1),\n encoded: $1,\n };\n }\n catch (error) { }\n return false;\n },\n ],\n ]);\n };\n}\n", "import { SerializedBlindedMessage } from '../wallet';\n\n/**\n * Cashu api error\n */\nexport type ApiError = {\n\t/**\n\t * Error message\n\t */\n\terror?: string;\n\t/**\n\t * HTTP error code\n\t */\n\tcode?: number;\n\t/**\n\t * Detailed error message\n\t */\n\tdetail?: string;\n};\n\n/**\n * Entries of CheckStateResponse with state of the proof\n */\nexport type ProofState = {\n\tY: string;\n\tstate: CheckStateEnum;\n\twitness: string | null;\n};\n\n/**\n * Enum for the state of a proof\n */\nexport enum CheckStateEnum {\n\tUNSPENT = 'UNSPENT',\n\tPENDING = 'PENDING',\n\tSPENT = 'SPENT'\n}\n\n/**\n * Response when checking proofs if they are spendable. Should not rely on this for receiving, since it can be easily cheated.\n */\nexport type CheckStateResponse = {\n\t/**\n\t *\n\t */\n\tstates: Array;\n} & ApiError;\n\n/**\n * Response from mint at /info endpoint\n */\nexport type GetInfoResponse = {\n\tname: string;\n\tpubkey: string;\n\tversion: string;\n\tdescription?: string;\n\tdescription_long?: string;\n\tcontact: Array;\n\tnuts: {\n\t\t'4': {\n\t\t\tmethods: Array;\n\t\t\tdisabled: boolean;\n\t\t};\n\t\t'5': {\n\t\t\tmethods: Array;\n\t\t\tdisabled: boolean;\n\t\t};\n\t\t'7'?: {\n\t\t\tsupported: boolean;\n\t\t};\n\t\t'8'?: {\n\t\t\tsupported: boolean;\n\t\t};\n\t\t'9'?: {\n\t\t\tsupported: boolean;\n\t\t};\n\t\t'10'?: {\n\t\t\tsupported: boolean;\n\t\t};\n\t\t'11'?: {\n\t\t\tsupported: boolean;\n\t\t};\n\t\t'12'?: {\n\t\t\tsupported: boolean;\n\t\t};\n\t\t'13'?: {\n\t\t\tsupported: boolean;\n\t\t};\n\t};\n\tmotd?: string;\n};\n\n/**\n * Response from the mint after requesting a melt quote\n */\nexport type MeltQuoteResponse = {\n\t/**\n\t * Quote ID\n\t */\n\tquote: string;\n\t/**\n\t * Amount to be melted\n\t */\n\tamount: number;\n\t/**\n\t * Fee reserve to be added to the amount\n\t */\n\tfee_reserve: number;\n\t/**\n\t * State of the melt quote\n\t */\n\tstate: MeltQuoteState;\n\t/**\n\t * Timestamp of when the quote expires\n\t */\n\texpiry: number;\n\t/**\n\t * preimage of the paid invoice. is null if it the invoice has not been paid yet. can be null, depending on which LN-backend the mint uses\n\t */\n\tpayment_preimage: string | null;\n\t/**\n\t * Return/Change from overpaid fees. This happens due to Lighting fee estimation being inaccurate\n\t */\n\tchange?: Array;\n} & ApiError;\n\nexport enum MeltQuoteState {\n\tUNPAID = 'UNPAID',\n\tPENDING = 'PENDING',\n\tPAID = 'PAID'\n}\n\nexport type MintContactInfo = {\n\tmethod: string;\n\tinfo: string;\n};\n\nexport enum MintQuoteState {\n\tUNPAID = 'UNPAID',\n\tPAID = 'PAID',\n\tISSUED = 'ISSUED'\n}\n\n/**\n * Response from the mint after requesting a mint\n */\nexport type MintQuoteResponse = {\n\t/**\n\t * Payment request\n\t */\n\trequest: string;\n\t/**\n\t * Quote ID\n\t */\n\tquote: string;\n\t/**\n\t * State of the mint quote\n\t */\n\tstate: MintQuoteState;\n\t/**\n\t * Timestamp of when the quote expires\n\t */\n\texpiry: number;\n} & ApiError;\n\n/**\n * Response from the mint after requesting a mint\n */\nexport type MintResponse = {\n\tsignatures: Array;\n} & ApiError;\n\n/**\n * Response from mint at /v1/restore endpoint\n */\nexport type PostRestoreResponse = {\n\toutputs: Array;\n\tpromises: Array;\n};\n\n/**\n * Blinded signature as it is received from the mint\n */\nexport type SerializedBlindedSignature = {\n\t/**\n\t * keyset id for indicating which public key was used to sign the blinded message\n\t */\n\tid: string;\n\t/**\n\t * Amount denominated in Satoshi\n\t */\n\tamount: number;\n\t/**\n\t * Blinded signature\n\t */\n\tC_: string;\n};\n\n/**\n * Ecash to other MoE swap method, displayed in @type {GetInfoResponse}\n */\nexport type SwapMethod = {\n\tmethod: string;\n\tunit: string;\n\tmin_amount: number;\n\tmax_amount: number;\n};\n\n/**\n * Response from the mint after performing a split action\n */\nexport type SwapResponse = {\n\t/**\n\t * represents the outputs after the split\n\t */\n\tsignatures: Array;\n} & ApiError;\n", "import { Proof } from './index';\n\nexport type RawTransport = {\n\tt: PaymentRequestTransportType; // type\n\ta: string; // target\n\tg?: Array>; // tags\n};\n\nexport type RawPaymentRequest = {\n\ti?: string; // id\n\ta?: number; // amount\n\tu?: string; // unit\n\ts?: boolean; // single use\n\tm?: Array; // mints\n\td?: string; // description\n\tt: Array; // transports\n};\n\nexport type PaymentRequestTransport = {\n\ttype: PaymentRequestTransportType;\n\ttarget: string;\n\ttags?: Array>;\n};\n\nexport enum PaymentRequestTransportType {\n\tPOST = 'post',\n\tNOSTR = 'nostr'\n}\n\nexport type PaymentRequestPayload = {\n\tid?: string;\n\tmemo?: string;\n\tunit: string;\n\tmint: string;\n\tproofs: Array;\n};\n", "export class HttpResponseError extends Error {\n\tstatus: number;\n\tconstructor(message: string, status: number) {\n\t\tsuper(message);\n\t\tthis.status = status;\n\t}\n}\n", "import { HttpResponseError } from './model/Errors';\n\ntype RequestArgs = {\n\tendpoint: string;\n\trequestBody?: Record;\n\theaders?: Record;\n};\n\ntype RequestOptions = RequestArgs & Omit;\n\nlet globalRequestOptions: Partial = {};\n\n/**\n * An object containing any custom settings that you want to apply to the global fetch method.\n * @param options See possible options here: https://developer.mozilla.org/en-US/docs/Web/API/fetch#options\n */\nexport function setGlobalRequestOptions(options: Partial): void {\n\tglobalRequestOptions = options;\n}\n\nasync function _request({\n\tendpoint,\n\trequestBody,\n\theaders: requestHeaders,\n\t...options\n}: RequestOptions): Promise {\n\tconst body = requestBody ? JSON.stringify(requestBody) : undefined;\n\tconst headers = {\n\t\t...{ Accept: 'application/json, text/plain, */*' },\n\t\t...(body ? { 'Content-Type': 'application/json' } : undefined),\n\t\t...requestHeaders\n\t};\n\n\tconst response = await fetch(endpoint, { body, headers, ...options });\n\n\tif (!response.ok) {\n\t\t// expecting: { error: '', code: 0 }\n\t\t// or: { detail: '' } (cashuBtc via pythonApi)\n\t\tconst { error, detail } = await response.json().catch(() => ({ error: 'bad response' }));\n\t\tthrow new HttpResponseError(error || detail || 'bad response', response.status);\n\t}\n\n\ttry {\n\t\treturn await response.json();\n\t} catch (err) {\n\t\tconsole.error('Failed to parse HTTP response', err);\n\t\tthrow new HttpResponseError('bad response', response.status);\n\t}\n}\n\nexport default async function request(options: RequestOptions): Promise {\n\tconst data = await _request({ ...options, ...globalRequestOptions });\n\treturn data as T;\n}\n", "import { Buffer } from 'buffer';\n\nfunction encodeUint8toBase64(uint8array: Uint8Array): string {\n\treturn Buffer.from(uint8array).toString('base64');\n}\n\nfunction encodeUint8toBase64Url(bytes: Uint8Array): string {\n\treturn Buffer.from(bytes)\n\t\t.toString('base64')\n\t\t.replace(/\\+/g, '-') // Replace + with -\n\t\t.replace(/\\//g, '_') // Replace / with _\n\t\t.replace(/=+$/, ''); // Remove padding characters\n}\n\nfunction encodeBase64toUint8(base64String: string): Uint8Array {\n\treturn Buffer.from(base64String, 'base64');\n}\n\nfunction encodeJsonToBase64(jsonObj: unknown): string {\n\tconst jsonString = JSON.stringify(jsonObj);\n\treturn base64urlFromBase64(Buffer.from(jsonString).toString('base64'));\n}\n\nfunction encodeBase64ToJson(base64String: string): T {\n\tconst jsonString = Buffer.from(base64urlToBase64(base64String), 'base64').toString();\n\tconst jsonObj = JSON.parse(jsonString) as T;\n\treturn jsonObj;\n}\n\nfunction base64urlToBase64(str: string) {\n\treturn str.replace(/-/g, '+').replace(/_/g, '/').split('=')[0];\n\t// .replace(/./g, '=');\n}\n\nfunction base64urlFromBase64(str: string) {\n\treturn str.replace(/\\+/g, '-').replace(/\\//g, '_').split('=')[0];\n\t// .replace(/=/g, '.');\n}\n\nexport {\n\tencodeUint8toBase64,\n\tencodeUint8toBase64Url,\n\tencodeBase64toUint8,\n\tencodeJsonToBase64,\n\tencodeBase64ToJson\n};\n", "/**\n * Hex, bytes and number utilities.\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport {\n abytes as abytes_,\n bytesToHex as bytesToHex_,\n concatBytes as concatBytes_,\n hexToBytes as hexToBytes_,\n isBytes as isBytes_,\n} from '@noble/hashes/utils.js';\nexport {\n abytes,\n anumber,\n bytesToHex,\n bytesToUtf8,\n concatBytes,\n hexToBytes,\n isBytes,\n randomBytes,\n utf8ToBytes,\n} from '@noble/hashes/utils.js';\nconst _0n = /* @__PURE__ */ BigInt(0);\nconst _1n = /* @__PURE__ */ BigInt(1);\nexport type Hex = Uint8Array | string; // hex strings are accepted for simplicity\nexport type PrivKey = Hex | bigint; // bigints are accepted to ease learning curve\nexport type CHash = {\n (message: Uint8Array | string): Uint8Array;\n blockLen: number;\n outputLen: number;\n create(opts?: { dkLen?: number }): any; // For shake\n};\nexport type FHash = (message: Uint8Array | string) => Uint8Array;\n\nexport function abool(title: string, value: boolean): void {\n if (typeof value !== 'boolean') throw new Error(title + ' boolean expected, got ' + value);\n}\n\n// tmp name until v2\nexport function _abool2(value: boolean, title: string = ''): boolean {\n if (typeof value !== 'boolean') {\n const prefix = title && `\"${title}\"`;\n throw new Error(prefix + 'expected boolean, got type=' + typeof value);\n }\n return value;\n}\n\n// tmp name until v2\n/** Asserts something is Uint8Array. */\nexport function _abytes2(value: Uint8Array, length?: number, title: string = ''): Uint8Array {\n const bytes = isBytes_(value);\n const len = value?.length;\n const needsLen = length !== undefined;\n if (!bytes || (needsLen && len !== length)) {\n const prefix = title && `\"${title}\" `;\n const ofLen = needsLen ? ` of length ${length}` : '';\n const got = bytes ? `length=${len}` : `type=${typeof value}`;\n throw new Error(prefix + 'expected Uint8Array' + ofLen + ', got ' + got);\n }\n return value;\n}\n\n// Used in weierstrass, der\nexport function numberToHexUnpadded(num: number | bigint): string {\n const hex = num.toString(16);\n return hex.length & 1 ? '0' + hex : hex;\n}\n\nexport function hexToNumber(hex: string): bigint {\n if (typeof hex !== 'string') throw new Error('hex string expected, got ' + typeof hex);\n return hex === '' ? _0n : BigInt('0x' + hex); // Big Endian\n}\n\n// BE: Big Endian, LE: Little Endian\nexport function bytesToNumberBE(bytes: Uint8Array): bigint {\n return hexToNumber(bytesToHex_(bytes));\n}\nexport function bytesToNumberLE(bytes: Uint8Array): bigint {\n abytes_(bytes);\n return hexToNumber(bytesToHex_(Uint8Array.from(bytes).reverse()));\n}\n\nexport function numberToBytesBE(n: number | bigint, len: number): Uint8Array {\n return hexToBytes_(n.toString(16).padStart(len * 2, '0'));\n}\nexport function numberToBytesLE(n: number | bigint, len: number): Uint8Array {\n return numberToBytesBE(n, len).reverse();\n}\n// Unpadded, rarely used\nexport function numberToVarBytesBE(n: number | bigint): Uint8Array {\n return hexToBytes_(numberToHexUnpadded(n));\n}\n\n/**\n * Takes hex string or Uint8Array, converts to Uint8Array.\n * Validates output length.\n * Will throw error for other types.\n * @param title descriptive title for an error e.g. 'secret key'\n * @param hex hex string or Uint8Array\n * @param expectedLength optional, will compare to result array's length\n * @returns\n */\nexport function ensureBytes(title: string, hex: Hex, expectedLength?: number): Uint8Array {\n let res: Uint8Array;\n if (typeof hex === 'string') {\n try {\n res = hexToBytes_(hex);\n } catch (e) {\n throw new Error(title + ' must be hex string or Uint8Array, cause: ' + e);\n }\n } else if (isBytes_(hex)) {\n // Uint8Array.from() instead of hash.slice() because node.js Buffer\n // is instance of Uint8Array, and its slice() creates **mutable** copy\n res = Uint8Array.from(hex);\n } else {\n throw new Error(title + ' must be hex string or Uint8Array');\n }\n const len = res.length;\n if (typeof expectedLength === 'number' && len !== expectedLength)\n throw new Error(title + ' of length ' + expectedLength + ' expected, got ' + len);\n return res;\n}\n\n// Compares 2 u8a-s in kinda constant time\nexport function equalBytes(a: Uint8Array, b: Uint8Array): boolean {\n if (a.length !== b.length) return false;\n let diff = 0;\n for (let i = 0; i < a.length; i++) diff |= a[i] ^ b[i];\n return diff === 0;\n}\n/**\n * Copies Uint8Array. We can't use u8a.slice(), because u8a can be Buffer,\n * and Buffer#slice creates mutable copy. Never use Buffers!\n */\nexport function copyBytes(bytes: Uint8Array): Uint8Array {\n return Uint8Array.from(bytes);\n}\n\n/**\n * Decodes 7-bit ASCII string to Uint8Array, throws on non-ascii symbols\n * Should be safe to use for things expected to be ASCII.\n * Returns exact same result as utf8ToBytes for ASCII or throws.\n */\nexport function asciiToBytes(ascii: string): Uint8Array {\n return Uint8Array.from(ascii, (c, i) => {\n const charCode = c.charCodeAt(0);\n if (c.length !== 1 || charCode > 127) {\n throw new Error(\n `string contains non-ASCII character \"${ascii[i]}\" with code ${charCode} at position ${i}`\n );\n }\n return charCode;\n });\n}\n\n/**\n * @example utf8ToBytes('abc') // new Uint8Array([97, 98, 99])\n */\n// export const utf8ToBytes: typeof utf8ToBytes_ = utf8ToBytes_;\n/**\n * Converts bytes to string using UTF8 encoding.\n * @example bytesToUtf8(Uint8Array.from([97, 98, 99])) // 'abc'\n */\n// export const bytesToUtf8: typeof bytesToUtf8_ = bytesToUtf8_;\n\n// Is positive bigint\nconst isPosBig = (n: bigint) => typeof n === 'bigint' && _0n <= n;\n\nexport function inRange(n: bigint, min: bigint, max: bigint): boolean {\n return isPosBig(n) && isPosBig(min) && isPosBig(max) && min <= n && n < max;\n}\n\n/**\n * Asserts min <= n < max. NOTE: It's < max and not <= max.\n * @example\n * aInRange('x', x, 1n, 256n); // would assume x is in (1n..255n)\n */\nexport function aInRange(title: string, n: bigint, min: bigint, max: bigint): void {\n // Why min <= n < max and not a (min < n < max) OR b (min <= n <= max)?\n // consider P=256n, min=0n, max=P\n // - a for min=0 would require -1: `inRange('x', x, -1n, P)`\n // - b would commonly require subtraction: `inRange('x', x, 0n, P - 1n)`\n // - our way is the cleanest: `inRange('x', x, 0n, P)\n if (!inRange(n, min, max))\n throw new Error('expected valid ' + title + ': ' + min + ' <= n < ' + max + ', got ' + n);\n}\n\n// Bit operations\n\n/**\n * Calculates amount of bits in a bigint.\n * Same as `n.toString(2).length`\n * TODO: merge with nLength in modular\n */\nexport function bitLen(n: bigint): number {\n let len;\n for (len = 0; n > _0n; n >>= _1n, len += 1);\n return len;\n}\n\n/**\n * Gets single bit at position.\n * NOTE: first bit position is 0 (same as arrays)\n * Same as `!!+Array.from(n.toString(2)).reverse()[pos]`\n */\nexport function bitGet(n: bigint, pos: number): bigint {\n return (n >> BigInt(pos)) & _1n;\n}\n\n/**\n * Sets single bit at position.\n */\nexport function bitSet(n: bigint, pos: number, value: boolean): bigint {\n return n | ((value ? _1n : _0n) << BigInt(pos));\n}\n\n/**\n * Calculate mask for N bits. Not using ** operator with bigints because of old engines.\n * Same as BigInt(`0b${Array(i).fill('1').join('')}`)\n */\nexport const bitMask = (n: number): bigint => (_1n << BigInt(n)) - _1n;\n\n// DRBG\n\ntype Pred = (v: Uint8Array) => T | undefined;\n/**\n * Minimal HMAC-DRBG from NIST 800-90 for RFC6979 sigs.\n * @returns function that will call DRBG until 2nd arg returns something meaningful\n * @example\n * const drbg = createHmacDRBG(32, 32, hmac);\n * drbg(seed, bytesToKey); // bytesToKey must return Key or undefined\n */\nexport function createHmacDrbg(\n hashLen: number,\n qByteLen: number,\n hmacFn: (key: Uint8Array, ...messages: Uint8Array[]) => Uint8Array\n): (seed: Uint8Array, predicate: Pred) => T {\n if (typeof hashLen !== 'number' || hashLen < 2) throw new Error('hashLen must be a number');\n if (typeof qByteLen !== 'number' || qByteLen < 2) throw new Error('qByteLen must be a number');\n if (typeof hmacFn !== 'function') throw new Error('hmacFn must be a function');\n // Step B, Step C: set hashLen to 8*ceil(hlen/8)\n const u8n = (len: number) => new Uint8Array(len); // creates Uint8Array\n const u8of = (byte: number) => Uint8Array.of(byte); // another shortcut\n let v = u8n(hashLen); // Minimal non-full-spec HMAC-DRBG from NIST 800-90 for RFC6979 sigs.\n let k = u8n(hashLen); // Steps B and C of RFC6979 3.2: set hashLen, in our case always same\n let i = 0; // Iterations counter, will throw when over 1000\n const reset = () => {\n v.fill(1);\n k.fill(0);\n i = 0;\n };\n const h = (...b: Uint8Array[]) => hmacFn(k, v, ...b); // hmac(k)(v, ...values)\n const reseed = (seed = u8n(0)) => {\n // HMAC-DRBG reseed() function. Steps D-G\n k = h(u8of(0x00), seed); // k = hmac(k || v || 0x00 || seed)\n v = h(); // v = hmac(k || v)\n if (seed.length === 0) return;\n k = h(u8of(0x01), seed); // k = hmac(k || v || 0x01 || seed)\n v = h(); // v = hmac(k || v)\n };\n const gen = () => {\n // HMAC-DRBG generate() function\n if (i++ >= 1000) throw new Error('drbg: tried 1000 values');\n let len = 0;\n const out: Uint8Array[] = [];\n while (len < qByteLen) {\n v = h();\n const sl = v.slice();\n out.push(sl);\n len += v.length;\n }\n return concatBytes_(...out);\n };\n const genUntil = (seed: Uint8Array, pred: Pred): T => {\n reset();\n reseed(seed); // Steps D-G\n let res: T | undefined = undefined; // Step H: grind until k is in [1..n-1]\n while (!(res = pred(gen()))) reseed();\n reset();\n return res;\n };\n return genUntil;\n}\n\n// Validating curves and fields\n\nconst validatorFns = {\n bigint: (val: any): boolean => typeof val === 'bigint',\n function: (val: any): boolean => typeof val === 'function',\n boolean: (val: any): boolean => typeof val === 'boolean',\n string: (val: any): boolean => typeof val === 'string',\n stringOrUint8Array: (val: any): boolean => typeof val === 'string' || isBytes_(val),\n isSafeInteger: (val: any): boolean => Number.isSafeInteger(val),\n array: (val: any): boolean => Array.isArray(val),\n field: (val: any, object: any): any => (object as any).Fp.isValid(val),\n hash: (val: any): boolean => typeof val === 'function' && Number.isSafeInteger(val.outputLen),\n} as const;\ntype Validator = keyof typeof validatorFns;\ntype ValMap> = { [K in keyof T]?: Validator };\n// type Record = { [P in K]: T; }\n\nexport function validateObject>(\n object: T,\n validators: ValMap,\n optValidators: ValMap = {}\n): T {\n const checkField = (fieldName: keyof T, type: Validator, isOptional: boolean) => {\n const checkVal = validatorFns[type];\n if (typeof checkVal !== 'function') throw new Error('invalid validator function');\n\n const val = object[fieldName as keyof typeof object];\n if (isOptional && val === undefined) return;\n if (!checkVal(val, object)) {\n throw new Error(\n 'param ' + String(fieldName) + ' is invalid. Expected ' + type + ', got ' + val\n );\n }\n };\n for (const [fieldName, type] of Object.entries(validators)) checkField(fieldName, type!, false);\n for (const [fieldName, type] of Object.entries(optValidators)) checkField(fieldName, type!, true);\n return object;\n}\n// validate type tests\n// const o: { a: number; b: number; c: number } = { a: 1, b: 5, c: 6 };\n// const z0 = validateObject(o, { a: 'isSafeInteger' }, { c: 'bigint' }); // Ok!\n// // Should fail type-check\n// const z1 = validateObject(o, { a: 'tmp' }, { c: 'zz' });\n// const z2 = validateObject(o, { a: 'isSafeInteger' }, { c: 'zz' });\n// const z3 = validateObject(o, { test: 'boolean', z: 'bug' });\n// const z4 = validateObject(o, { a: 'boolean', z: 'bug' });\n\nexport function isHash(val: CHash): boolean {\n return typeof val === 'function' && Number.isSafeInteger(val.outputLen);\n}\nexport function _validateObject(\n object: Record,\n fields: Record,\n optFields: Record = {}\n): void {\n if (!object || typeof object !== 'object') throw new Error('expected valid options object');\n type Item = keyof typeof object;\n function checkField(fieldName: Item, expectedType: string, isOpt: boolean) {\n const val = object[fieldName];\n if (isOpt && val === undefined) return;\n const current = typeof val;\n if (current !== expectedType || val === null)\n throw new Error(`param \"${fieldName}\" is invalid: expected ${expectedType}, got ${current}`);\n }\n Object.entries(fields).forEach(([k, v]) => checkField(k, v, false));\n Object.entries(optFields).forEach(([k, v]) => checkField(k, v, true));\n}\n\n/**\n * throws not implemented error\n */\nexport const notImplemented = (): never => {\n throw new Error('not implemented');\n};\n\n/**\n * Memoizes (caches) computation result.\n * Uses WeakMap: the value is going auto-cleaned by GC after last reference is removed.\n */\nexport function memoized(\n fn: (arg: T, ...args: O) => R\n): (arg: T, ...args: O) => R {\n const map = new WeakMap();\n return (arg: T, ...args: O): R => {\n const val = map.get(arg);\n if (val !== undefined) return val;\n const computed = fn(arg, ...args);\n map.set(arg, computed);\n return computed;\n };\n}\n", "/**\n * Deprecated module: moved from curves/abstract/utils.js to curves/utils.js\n * @module\n */\nimport * as u from '../utils.ts';\n\n/** @deprecated moved to `@noble/curves/utils.js` */\nexport type Hex = u.Hex;\n/** @deprecated moved to `@noble/curves/utils.js` */\nexport type PrivKey = u.PrivKey;\n/** @deprecated moved to `@noble/curves/utils.js` */\nexport type CHash = u.CHash;\n/** @deprecated moved to `@noble/curves/utils.js` */\nexport type FHash = u.FHash;\n\n/** @deprecated moved to `@noble/curves/utils.js` */\nexport const abytes: typeof u.abytes = u.abytes;\n/** @deprecated moved to `@noble/curves/utils.js` */\nexport const anumber: typeof u.anumber = u.anumber;\n/** @deprecated moved to `@noble/curves/utils.js` */\nexport const bytesToHex: typeof u.bytesToHex = u.bytesToHex;\n/** @deprecated moved to `@noble/curves/utils.js` */\nexport const bytesToUtf8: typeof u.bytesToUtf8 = u.bytesToUtf8;\n/** @deprecated moved to `@noble/curves/utils.js` */\nexport const concatBytes: typeof u.concatBytes = u.concatBytes;\n/** @deprecated moved to `@noble/curves/utils.js` */\nexport const hexToBytes: typeof u.hexToBytes = u.hexToBytes;\n/** @deprecated moved to `@noble/curves/utils.js` */\nexport const isBytes: typeof u.isBytes = u.isBytes;\n/** @deprecated moved to `@noble/curves/utils.js` */\nexport const randomBytes: typeof u.randomBytes = u.randomBytes;\n/** @deprecated moved to `@noble/curves/utils.js` */\nexport const utf8ToBytes: typeof u.utf8ToBytes = u.utf8ToBytes;\n\n/** @deprecated moved to `@noble/curves/utils.js` */\nexport const abool: typeof u.abool = u.abool;\n/** @deprecated moved to `@noble/curves/utils.js` */\nexport const numberToHexUnpadded: typeof u.numberToHexUnpadded = u.numberToHexUnpadded;\n/** @deprecated moved to `@noble/curves/utils.js` */\nexport const hexToNumber: typeof u.hexToNumber = u.hexToNumber;\n/** @deprecated moved to `@noble/curves/utils.js` */\nexport const bytesToNumberBE: typeof u.bytesToNumberBE = u.bytesToNumberBE;\n/** @deprecated moved to `@noble/curves/utils.js` */\nexport const bytesToNumberLE: typeof u.bytesToNumberLE = u.bytesToNumberLE;\n/** @deprecated moved to `@noble/curves/utils.js` */\nexport const numberToBytesBE: typeof u.numberToBytesBE = u.numberToBytesBE;\n/** @deprecated moved to `@noble/curves/utils.js` */\nexport const numberToBytesLE: typeof u.numberToBytesLE = u.numberToBytesLE;\n/** @deprecated moved to `@noble/curves/utils.js` */\nexport const numberToVarBytesBE: typeof u.numberToVarBytesBE = u.numberToVarBytesBE;\n/** @deprecated moved to `@noble/curves/utils.js` */\nexport const ensureBytes: typeof u.ensureBytes = u.ensureBytes;\n/** @deprecated moved to `@noble/curves/utils.js` */\nexport const equalBytes: typeof u.equalBytes = u.equalBytes;\n/** @deprecated moved to `@noble/curves/utils.js` */\nexport const copyBytes: typeof u.copyBytes = u.copyBytes;\n/** @deprecated moved to `@noble/curves/utils.js` */\nexport const asciiToBytes: typeof u.asciiToBytes = u.asciiToBytes;\n/** @deprecated moved to `@noble/curves/utils.js` */\nexport const inRange: typeof u.inRange = u.inRange;\n/** @deprecated moved to `@noble/curves/utils.js` */\nexport const aInRange: typeof u.aInRange = u.aInRange;\n/** @deprecated moved to `@noble/curves/utils.js` */\nexport const bitLen: typeof u.bitLen = u.bitLen;\n/** @deprecated moved to `@noble/curves/utils.js` */\nexport const bitGet: typeof u.bitGet = u.bitGet;\n/** @deprecated moved to `@noble/curves/utils.js` */\nexport const bitSet: typeof u.bitSet = u.bitSet;\n/** @deprecated moved to `@noble/curves/utils.js` */\nexport const bitMask: typeof u.bitMask = u.bitMask;\n/** @deprecated moved to `@noble/curves/utils.js` */\nexport const createHmacDrbg: typeof u.createHmacDrbg = u.createHmacDrbg;\n/** @deprecated moved to `@noble/curves/utils.js` */\nexport const notImplemented: typeof u.notImplemented = u.notImplemented;\n/** @deprecated moved to `@noble/curves/utils.js` */\nexport const memoized: typeof u.memoized = u.memoized;\n/** @deprecated moved to `@noble/curves/utils.js` */\nexport const validateObject: typeof u.validateObject = u.validateObject;\n/** @deprecated moved to `@noble/curves/utils.js` */\nexport const isHash: typeof u.isHash = u.isHash;\n", "/**\n * Internal Merkle-Damgard hash utils.\n * @module\n */\nimport { type Input, Hash, abytes, aexists, aoutput, clean, createView, toBytes } from './utils.ts';\n\n/** Polyfill for Safari 14. https://caniuse.com/mdn-javascript_builtins_dataview_setbiguint64 */\nexport function setBigUint64(\n view: DataView,\n byteOffset: number,\n value: bigint,\n isLE: boolean\n): void {\n if (typeof view.setBigUint64 === 'function') return view.setBigUint64(byteOffset, value, isLE);\n const _32n = BigInt(32);\n const _u32_max = BigInt(0xffffffff);\n const wh = Number((value >> _32n) & _u32_max);\n const wl = Number(value & _u32_max);\n const h = isLE ? 4 : 0;\n const l = isLE ? 0 : 4;\n view.setUint32(byteOffset + h, wh, isLE);\n view.setUint32(byteOffset + l, wl, isLE);\n}\n\n/** Choice: a ? b : c */\nexport function Chi(a: number, b: number, c: number): number {\n return (a & b) ^ (~a & c);\n}\n\n/** Majority function, true if any two inputs is true. */\nexport function Maj(a: number, b: number, c: number): number {\n return (a & b) ^ (a & c) ^ (b & c);\n}\n\n/**\n * Merkle-Damgard hash construction base class.\n * Could be used to create MD5, RIPEMD, SHA1, SHA2.\n */\nexport abstract class HashMD> extends Hash {\n protected abstract process(buf: DataView, offset: number): void;\n protected abstract get(): number[];\n protected abstract set(...args: number[]): void;\n abstract destroy(): void;\n protected abstract roundClean(): void;\n\n readonly blockLen: number;\n readonly outputLen: number;\n readonly padOffset: number;\n readonly isLE: boolean;\n\n // For partial updates less than block size\n protected buffer: Uint8Array;\n protected view: DataView;\n protected finished = false;\n protected length = 0;\n protected pos = 0;\n protected destroyed = false;\n\n constructor(blockLen: number, outputLen: number, padOffset: number, isLE: boolean) {\n super();\n this.blockLen = blockLen;\n this.outputLen = outputLen;\n this.padOffset = padOffset;\n this.isLE = isLE;\n this.buffer = new Uint8Array(blockLen);\n this.view = createView(this.buffer);\n }\n update(data: Input): this {\n aexists(this);\n data = toBytes(data);\n abytes(data);\n const { view, buffer, blockLen } = this;\n const len = data.length;\n for (let pos = 0; pos < len; ) {\n const take = Math.min(blockLen - this.pos, len - pos);\n // Fast path: we have at least one block in input, cast it to view and process\n if (take === blockLen) {\n const dataView = createView(data);\n for (; blockLen <= len - pos; pos += blockLen) this.process(dataView, pos);\n continue;\n }\n buffer.set(data.subarray(pos, pos + take), this.pos);\n this.pos += take;\n pos += take;\n if (this.pos === blockLen) {\n this.process(view, 0);\n this.pos = 0;\n }\n }\n this.length += data.length;\n this.roundClean();\n return this;\n }\n digestInto(out: Uint8Array): void {\n aexists(this);\n aoutput(out, this);\n this.finished = true;\n // Padding\n // We can avoid allocation of buffer for padding completely if it\n // was previously not allocated here. But it won't change performance.\n const { buffer, view, blockLen, isLE } = this;\n let { pos } = this;\n // append the bit '1' to the message\n buffer[pos++] = 0b10000000;\n clean(this.buffer.subarray(pos));\n // we have less than padOffset left in buffer, so we cannot put length in\n // current block, need process it and pad again\n if (this.padOffset > blockLen - pos) {\n this.process(view, 0);\n pos = 0;\n }\n // Pad until full block byte with zeros\n for (let i = pos; i < blockLen; i++) buffer[i] = 0;\n // Note: sha512 requires length to be 128bit integer, but length in JS will overflow before that\n // You need to write around 2 exabytes (u64_max / 8 / (1024**6)) for this to happen.\n // So we just write lowest 64 bits of that value.\n setBigUint64(view, blockLen - 8, BigInt(this.length * 8), isLE);\n this.process(view, 0);\n const oview = createView(out);\n const len = this.outputLen;\n // NOTE: we do division by 4 later, which should be fused in single op with modulo by JIT\n if (len % 4) throw new Error('_sha2: outputLen should be aligned to 32bit');\n const outLen = len / 4;\n const state = this.get();\n if (outLen > state.length) throw new Error('_sha2: outputLen bigger than state');\n for (let i = 0; i < outLen; i++) oview.setUint32(4 * i, state[i], isLE);\n }\n digest(): Uint8Array {\n const { buffer, outputLen } = this;\n this.digestInto(buffer);\n const res = buffer.slice(0, outputLen);\n this.destroy();\n return res;\n }\n _cloneInto(to?: T): T {\n to ||= new (this.constructor as any)() as T;\n to.set(...this.get());\n const { blockLen, buffer, length, finished, destroyed, pos } = this;\n to.destroyed = destroyed;\n to.finished = finished;\n to.length = length;\n to.pos = pos;\n if (length % blockLen) to.buffer.set(buffer);\n return to;\n }\n clone(): T {\n return this._cloneInto();\n }\n}\n\n/**\n * Initial SHA-2 state: fractional parts of square roots of first 16 primes 2..53.\n * Check out `test/misc/sha2-gen-iv.js` for recomputation guide.\n */\n\n/** Initial SHA256 state. Bits 0..32 of frac part of sqrt of primes 2..19 */\nexport const SHA256_IV: Uint32Array = /* @__PURE__ */ Uint32Array.from([\n 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19,\n]);\n\n/** Initial SHA224 state. Bits 32..64 of frac part of sqrt of primes 23..53 */\nexport const SHA224_IV: Uint32Array = /* @__PURE__ */ Uint32Array.from([\n 0xc1059ed8, 0x367cd507, 0x3070dd17, 0xf70e5939, 0xffc00b31, 0x68581511, 0x64f98fa7, 0xbefa4fa4,\n]);\n\n/** Initial SHA384 state. Bits 0..64 of frac part of sqrt of primes 23..53 */\nexport const SHA384_IV: Uint32Array = /* @__PURE__ */ Uint32Array.from([\n 0xcbbb9d5d, 0xc1059ed8, 0x629a292a, 0x367cd507, 0x9159015a, 0x3070dd17, 0x152fecd8, 0xf70e5939,\n 0x67332667, 0xffc00b31, 0x8eb44a87, 0x68581511, 0xdb0c2e0d, 0x64f98fa7, 0x47b5481d, 0xbefa4fa4,\n]);\n\n/** Initial SHA512 state. Bits 0..64 of frac part of sqrt of primes 2..19 */\nexport const SHA512_IV: Uint32Array = /* @__PURE__ */ Uint32Array.from([\n 0x6a09e667, 0xf3bcc908, 0xbb67ae85, 0x84caa73b, 0x3c6ef372, 0xfe94f82b, 0xa54ff53a, 0x5f1d36f1,\n 0x510e527f, 0xade682d1, 0x9b05688c, 0x2b3e6c1f, 0x1f83d9ab, 0xfb41bd6b, 0x5be0cd19, 0x137e2179,\n]);\n", "/**\n * Internal helpers for u64. BigUint64Array is too slow as per 2025, so we implement it using Uint32Array.\n * @todo re-check https://issues.chromium.org/issues/42212588\n * @module\n */\nconst U32_MASK64 = /* @__PURE__ */ BigInt(2 ** 32 - 1);\nconst _32n = /* @__PURE__ */ BigInt(32);\n\nfunction fromBig(\n n: bigint,\n le = false\n): {\n h: number;\n l: number;\n} {\n if (le) return { h: Number(n & U32_MASK64), l: Number((n >> _32n) & U32_MASK64) };\n return { h: Number((n >> _32n) & U32_MASK64) | 0, l: Number(n & U32_MASK64) | 0 };\n}\n\nfunction split(lst: bigint[], le = false): Uint32Array[] {\n const len = lst.length;\n let Ah = new Uint32Array(len);\n let Al = new Uint32Array(len);\n for (let i = 0; i < len; i++) {\n const { h, l } = fromBig(lst[i], le);\n [Ah[i], Al[i]] = [h, l];\n }\n return [Ah, Al];\n}\n\nconst toBig = (h: number, l: number): bigint => (BigInt(h >>> 0) << _32n) | BigInt(l >>> 0);\n// for Shift in [0, 32)\nconst shrSH = (h: number, _l: number, s: number): number => h >>> s;\nconst shrSL = (h: number, l: number, s: number): number => (h << (32 - s)) | (l >>> s);\n// Right rotate for Shift in [1, 32)\nconst rotrSH = (h: number, l: number, s: number): number => (h >>> s) | (l << (32 - s));\nconst rotrSL = (h: number, l: number, s: number): number => (h << (32 - s)) | (l >>> s);\n// Right rotate for Shift in (32, 64), NOTE: 32 is special case.\nconst rotrBH = (h: number, l: number, s: number): number => (h << (64 - s)) | (l >>> (s - 32));\nconst rotrBL = (h: number, l: number, s: number): number => (h >>> (s - 32)) | (l << (64 - s));\n// Right rotate for shift===32 (just swaps l&h)\nconst rotr32H = (_h: number, l: number): number => l;\nconst rotr32L = (h: number, _l: number): number => h;\n// Left rotate for Shift in [1, 32)\nconst rotlSH = (h: number, l: number, s: number): number => (h << s) | (l >>> (32 - s));\nconst rotlSL = (h: number, l: number, s: number): number => (l << s) | (h >>> (32 - s));\n// Left rotate for Shift in (32, 64), NOTE: 32 is special case.\nconst rotlBH = (h: number, l: number, s: number): number => (l << (s - 32)) | (h >>> (64 - s));\nconst rotlBL = (h: number, l: number, s: number): number => (h << (s - 32)) | (l >>> (64 - s));\n\n// JS uses 32-bit signed integers for bitwise operations which means we cannot\n// simple take carry out of low bit sum by shift, we need to use division.\nfunction add(\n Ah: number,\n Al: number,\n Bh: number,\n Bl: number\n): {\n h: number;\n l: number;\n} {\n const l = (Al >>> 0) + (Bl >>> 0);\n return { h: (Ah + Bh + ((l / 2 ** 32) | 0)) | 0, l: l | 0 };\n}\n// Addition with more than 2 elements\nconst add3L = (Al: number, Bl: number, Cl: number): number => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0);\nconst add3H = (low: number, Ah: number, Bh: number, Ch: number): number =>\n (Ah + Bh + Ch + ((low / 2 ** 32) | 0)) | 0;\nconst add4L = (Al: number, Bl: number, Cl: number, Dl: number): number =>\n (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0);\nconst add4H = (low: number, Ah: number, Bh: number, Ch: number, Dh: number): number =>\n (Ah + Bh + Ch + Dh + ((low / 2 ** 32) | 0)) | 0;\nconst add5L = (Al: number, Bl: number, Cl: number, Dl: number, El: number): number =>\n (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0) + (El >>> 0);\nconst add5H = (low: number, Ah: number, Bh: number, Ch: number, Dh: number, Eh: number): number =>\n (Ah + Bh + Ch + Dh + Eh + ((low / 2 ** 32) | 0)) | 0;\n\n// prettier-ignore\nexport {\n add, add3H, add3L, add4H, add4L, add5H, add5L, fromBig, rotlBH, rotlBL, rotlSH, rotlSL, rotr32H, rotr32L, rotrBH, rotrBL, rotrSH, rotrSL, shrSH, shrSL, split, toBig\n};\n// prettier-ignore\nconst u64: { fromBig: typeof fromBig; split: typeof split; toBig: (h: number, l: number) => bigint; shrSH: (h: number, _l: number, s: number) => number; shrSL: (h: number, l: number, s: number) => number; rotrSH: (h: number, l: number, s: number) => number; rotrSL: (h: number, l: number, s: number) => number; rotrBH: (h: number, l: number, s: number) => number; rotrBL: (h: number, l: number, s: number) => number; rotr32H: (_h: number, l: number) => number; rotr32L: (h: number, _l: number) => number; rotlSH: (h: number, l: number, s: number) => number; rotlSL: (h: number, l: number, s: number) => number; rotlBH: (h: number, l: number, s: number) => number; rotlBL: (h: number, l: number, s: number) => number; add: typeof add; add3L: (Al: number, Bl: number, Cl: number) => number; add3H: (low: number, Ah: number, Bh: number, Ch: number) => number; add4L: (Al: number, Bl: number, Cl: number, Dl: number) => number; add4H: (low: number, Ah: number, Bh: number, Ch: number, Dh: number) => number; add5H: (low: number, Ah: number, Bh: number, Ch: number, Dh: number, Eh: number) => number; add5L: (Al: number, Bl: number, Cl: number, Dl: number, El: number) => number; } = {\n fromBig, split, toBig,\n shrSH, shrSL,\n rotrSH, rotrSL, rotrBH, rotrBL,\n rotr32H, rotr32L,\n rotlSH, rotlSL, rotlBH, rotlBL,\n add, add3L, add3H, add4L, add4H, add5H, add5L,\n};\nexport default u64;\n", "/**\n * SHA2 hash function. A.k.a. sha256, sha384, sha512, sha512_224, sha512_256.\n * SHA256 is the fastest hash implementable in JS, even faster than Blake3.\n * Check out [RFC 4634](https://datatracker.ietf.org/doc/html/rfc4634) and\n * [FIPS 180-4](https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.180-4.pdf).\n * @module\n */\nimport { Chi, HashMD, Maj, SHA224_IV, SHA256_IV, SHA384_IV, SHA512_IV } from './_md.ts';\nimport * as u64 from './_u64.ts';\nimport { type CHash, clean, createHasher, rotr } from './utils.ts';\n\n/**\n * Round constants:\n * First 32 bits of fractional parts of the cube roots of the first 64 primes 2..311)\n */\n// prettier-ignore\nconst SHA256_K = /* @__PURE__ */ Uint32Array.from([\n 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,\n 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,\n 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,\n 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,\n 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,\n 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,\n 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,\n 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2\n]);\n\n/** Reusable temporary buffer. \"W\" comes straight from spec. */\nconst SHA256_W = /* @__PURE__ */ new Uint32Array(64);\nexport class SHA256 extends HashMD {\n // We cannot use array here since array allows indexing by variable\n // which means optimizer/compiler cannot use registers.\n protected A: number = SHA256_IV[0] | 0;\n protected B: number = SHA256_IV[1] | 0;\n protected C: number = SHA256_IV[2] | 0;\n protected D: number = SHA256_IV[3] | 0;\n protected E: number = SHA256_IV[4] | 0;\n protected F: number = SHA256_IV[5] | 0;\n protected G: number = SHA256_IV[6] | 0;\n protected H: number = SHA256_IV[7] | 0;\n\n constructor(outputLen: number = 32) {\n super(64, outputLen, 8, false);\n }\n protected get(): [number, number, number, number, number, number, number, number] {\n const { A, B, C, D, E, F, G, H } = this;\n return [A, B, C, D, E, F, G, H];\n }\n // prettier-ignore\n protected set(\n A: number, B: number, C: number, D: number, E: number, F: number, G: number, H: number\n ): void {\n this.A = A | 0;\n this.B = B | 0;\n this.C = C | 0;\n this.D = D | 0;\n this.E = E | 0;\n this.F = F | 0;\n this.G = G | 0;\n this.H = H | 0;\n }\n protected process(view: DataView, offset: number): void {\n // Extend the first 16 words into the remaining 48 words w[16..63] of the message schedule array\n for (let i = 0; i < 16; i++, offset += 4) SHA256_W[i] = view.getUint32(offset, false);\n for (let i = 16; i < 64; i++) {\n const W15 = SHA256_W[i - 15];\n const W2 = SHA256_W[i - 2];\n const s0 = rotr(W15, 7) ^ rotr(W15, 18) ^ (W15 >>> 3);\n const s1 = rotr(W2, 17) ^ rotr(W2, 19) ^ (W2 >>> 10);\n SHA256_W[i] = (s1 + SHA256_W[i - 7] + s0 + SHA256_W[i - 16]) | 0;\n }\n // Compression function main loop, 64 rounds\n let { A, B, C, D, E, F, G, H } = this;\n for (let i = 0; i < 64; i++) {\n const sigma1 = rotr(E, 6) ^ rotr(E, 11) ^ rotr(E, 25);\n const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0;\n const sigma0 = rotr(A, 2) ^ rotr(A, 13) ^ rotr(A, 22);\n const T2 = (sigma0 + Maj(A, B, C)) | 0;\n H = G;\n G = F;\n F = E;\n E = (D + T1) | 0;\n D = C;\n C = B;\n B = A;\n A = (T1 + T2) | 0;\n }\n // Add the compressed chunk to the current hash value\n A = (A + this.A) | 0;\n B = (B + this.B) | 0;\n C = (C + this.C) | 0;\n D = (D + this.D) | 0;\n E = (E + this.E) | 0;\n F = (F + this.F) | 0;\n G = (G + this.G) | 0;\n H = (H + this.H) | 0;\n this.set(A, B, C, D, E, F, G, H);\n }\n protected roundClean(): void {\n clean(SHA256_W);\n }\n destroy(): void {\n this.set(0, 0, 0, 0, 0, 0, 0, 0);\n clean(this.buffer);\n }\n}\n\nexport class SHA224 extends SHA256 {\n protected A: number = SHA224_IV[0] | 0;\n protected B: number = SHA224_IV[1] | 0;\n protected C: number = SHA224_IV[2] | 0;\n protected D: number = SHA224_IV[3] | 0;\n protected E: number = SHA224_IV[4] | 0;\n protected F: number = SHA224_IV[5] | 0;\n protected G: number = SHA224_IV[6] | 0;\n protected H: number = SHA224_IV[7] | 0;\n constructor() {\n super(28);\n }\n}\n\n// SHA2-512 is slower than sha256 in js because u64 operations are slow.\n\n// Round contants\n// First 32 bits of the fractional parts of the cube roots of the first 80 primes 2..409\n// prettier-ignore\nconst K512 = /* @__PURE__ */ (() => u64.split([\n '0x428a2f98d728ae22', '0x7137449123ef65cd', '0xb5c0fbcfec4d3b2f', '0xe9b5dba58189dbbc',\n '0x3956c25bf348b538', '0x59f111f1b605d019', '0x923f82a4af194f9b', '0xab1c5ed5da6d8118',\n '0xd807aa98a3030242', '0x12835b0145706fbe', '0x243185be4ee4b28c', '0x550c7dc3d5ffb4e2',\n '0x72be5d74f27b896f', '0x80deb1fe3b1696b1', '0x9bdc06a725c71235', '0xc19bf174cf692694',\n '0xe49b69c19ef14ad2', '0xefbe4786384f25e3', '0x0fc19dc68b8cd5b5', '0x240ca1cc77ac9c65',\n '0x2de92c6f592b0275', '0x4a7484aa6ea6e483', '0x5cb0a9dcbd41fbd4', '0x76f988da831153b5',\n '0x983e5152ee66dfab', '0xa831c66d2db43210', '0xb00327c898fb213f', '0xbf597fc7beef0ee4',\n '0xc6e00bf33da88fc2', '0xd5a79147930aa725', '0x06ca6351e003826f', '0x142929670a0e6e70',\n '0x27b70a8546d22ffc', '0x2e1b21385c26c926', '0x4d2c6dfc5ac42aed', '0x53380d139d95b3df',\n '0x650a73548baf63de', '0x766a0abb3c77b2a8', '0x81c2c92e47edaee6', '0x92722c851482353b',\n '0xa2bfe8a14cf10364', '0xa81a664bbc423001', '0xc24b8b70d0f89791', '0xc76c51a30654be30',\n '0xd192e819d6ef5218', '0xd69906245565a910', '0xf40e35855771202a', '0x106aa07032bbd1b8',\n '0x19a4c116b8d2d0c8', '0x1e376c085141ab53', '0x2748774cdf8eeb99', '0x34b0bcb5e19b48a8',\n '0x391c0cb3c5c95a63', '0x4ed8aa4ae3418acb', '0x5b9cca4f7763e373', '0x682e6ff3d6b2b8a3',\n '0x748f82ee5defb2fc', '0x78a5636f43172f60', '0x84c87814a1f0ab72', '0x8cc702081a6439ec',\n '0x90befffa23631e28', '0xa4506cebde82bde9', '0xbef9a3f7b2c67915', '0xc67178f2e372532b',\n '0xca273eceea26619c', '0xd186b8c721c0c207', '0xeada7dd6cde0eb1e', '0xf57d4f7fee6ed178',\n '0x06f067aa72176fba', '0x0a637dc5a2c898a6', '0x113f9804bef90dae', '0x1b710b35131c471b',\n '0x28db77f523047d84', '0x32caab7b40c72493', '0x3c9ebe0a15c9bebc', '0x431d67c49c100d4c',\n '0x4cc5d4becb3e42b6', '0x597f299cfc657e2a', '0x5fcb6fab3ad6faec', '0x6c44198c4a475817'\n].map(n => BigInt(n))))();\nconst SHA512_Kh = /* @__PURE__ */ (() => K512[0])();\nconst SHA512_Kl = /* @__PURE__ */ (() => K512[1])();\n\n// Reusable temporary buffers\nconst SHA512_W_H = /* @__PURE__ */ new Uint32Array(80);\nconst SHA512_W_L = /* @__PURE__ */ new Uint32Array(80);\n\nexport class SHA512 extends HashMD {\n // We cannot use array here since array allows indexing by variable\n // which means optimizer/compiler cannot use registers.\n // h -- high 32 bits, l -- low 32 bits\n protected Ah: number = SHA512_IV[0] | 0;\n protected Al: number = SHA512_IV[1] | 0;\n protected Bh: number = SHA512_IV[2] | 0;\n protected Bl: number = SHA512_IV[3] | 0;\n protected Ch: number = SHA512_IV[4] | 0;\n protected Cl: number = SHA512_IV[5] | 0;\n protected Dh: number = SHA512_IV[6] | 0;\n protected Dl: number = SHA512_IV[7] | 0;\n protected Eh: number = SHA512_IV[8] | 0;\n protected El: number = SHA512_IV[9] | 0;\n protected Fh: number = SHA512_IV[10] | 0;\n protected Fl: number = SHA512_IV[11] | 0;\n protected Gh: number = SHA512_IV[12] | 0;\n protected Gl: number = SHA512_IV[13] | 0;\n protected Hh: number = SHA512_IV[14] | 0;\n protected Hl: number = SHA512_IV[15] | 0;\n\n constructor(outputLen: number = 64) {\n super(128, outputLen, 16, false);\n }\n // prettier-ignore\n protected get(): [\n number, number, number, number, number, number, number, number,\n number, number, number, number, number, number, number, number\n ] {\n const { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;\n return [Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl];\n }\n // prettier-ignore\n protected set(\n Ah: number, Al: number, Bh: number, Bl: number, Ch: number, Cl: number, Dh: number, Dl: number,\n Eh: number, El: number, Fh: number, Fl: number, Gh: number, Gl: number, Hh: number, Hl: number\n ): void {\n this.Ah = Ah | 0;\n this.Al = Al | 0;\n this.Bh = Bh | 0;\n this.Bl = Bl | 0;\n this.Ch = Ch | 0;\n this.Cl = Cl | 0;\n this.Dh = Dh | 0;\n this.Dl = Dl | 0;\n this.Eh = Eh | 0;\n this.El = El | 0;\n this.Fh = Fh | 0;\n this.Fl = Fl | 0;\n this.Gh = Gh | 0;\n this.Gl = Gl | 0;\n this.Hh = Hh | 0;\n this.Hl = Hl | 0;\n }\n protected process(view: DataView, offset: number): void {\n // Extend the first 16 words into the remaining 64 words w[16..79] of the message schedule array\n for (let i = 0; i < 16; i++, offset += 4) {\n SHA512_W_H[i] = view.getUint32(offset);\n SHA512_W_L[i] = view.getUint32((offset += 4));\n }\n for (let i = 16; i < 80; i++) {\n // s0 := (w[i-15] rightrotate 1) xor (w[i-15] rightrotate 8) xor (w[i-15] rightshift 7)\n const W15h = SHA512_W_H[i - 15] | 0;\n const W15l = SHA512_W_L[i - 15] | 0;\n const s0h = u64.rotrSH(W15h, W15l, 1) ^ u64.rotrSH(W15h, W15l, 8) ^ u64.shrSH(W15h, W15l, 7);\n const s0l = u64.rotrSL(W15h, W15l, 1) ^ u64.rotrSL(W15h, W15l, 8) ^ u64.shrSL(W15h, W15l, 7);\n // s1 := (w[i-2] rightrotate 19) xor (w[i-2] rightrotate 61) xor (w[i-2] rightshift 6)\n const W2h = SHA512_W_H[i - 2] | 0;\n const W2l = SHA512_W_L[i - 2] | 0;\n const s1h = u64.rotrSH(W2h, W2l, 19) ^ u64.rotrBH(W2h, W2l, 61) ^ u64.shrSH(W2h, W2l, 6);\n const s1l = u64.rotrSL(W2h, W2l, 19) ^ u64.rotrBL(W2h, W2l, 61) ^ u64.shrSL(W2h, W2l, 6);\n // SHA256_W[i] = s0 + s1 + SHA256_W[i - 7] + SHA256_W[i - 16];\n const SUMl = u64.add4L(s0l, s1l, SHA512_W_L[i - 7], SHA512_W_L[i - 16]);\n const SUMh = u64.add4H(SUMl, s0h, s1h, SHA512_W_H[i - 7], SHA512_W_H[i - 16]);\n SHA512_W_H[i] = SUMh | 0;\n SHA512_W_L[i] = SUMl | 0;\n }\n let { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;\n // Compression function main loop, 80 rounds\n for (let i = 0; i < 80; i++) {\n // S1 := (e rightrotate 14) xor (e rightrotate 18) xor (e rightrotate 41)\n const sigma1h = u64.rotrSH(Eh, El, 14) ^ u64.rotrSH(Eh, El, 18) ^ u64.rotrBH(Eh, El, 41);\n const sigma1l = u64.rotrSL(Eh, El, 14) ^ u64.rotrSL(Eh, El, 18) ^ u64.rotrBL(Eh, El, 41);\n //const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0;\n const CHIh = (Eh & Fh) ^ (~Eh & Gh);\n const CHIl = (El & Fl) ^ (~El & Gl);\n // T1 = H + sigma1 + Chi(E, F, G) + SHA512_K[i] + SHA512_W[i]\n // prettier-ignore\n const T1ll = u64.add5L(Hl, sigma1l, CHIl, SHA512_Kl[i], SHA512_W_L[i]);\n const T1h = u64.add5H(T1ll, Hh, sigma1h, CHIh, SHA512_Kh[i], SHA512_W_H[i]);\n const T1l = T1ll | 0;\n // S0 := (a rightrotate 28) xor (a rightrotate 34) xor (a rightrotate 39)\n const sigma0h = u64.rotrSH(Ah, Al, 28) ^ u64.rotrBH(Ah, Al, 34) ^ u64.rotrBH(Ah, Al, 39);\n const sigma0l = u64.rotrSL(Ah, Al, 28) ^ u64.rotrBL(Ah, Al, 34) ^ u64.rotrBL(Ah, Al, 39);\n const MAJh = (Ah & Bh) ^ (Ah & Ch) ^ (Bh & Ch);\n const MAJl = (Al & Bl) ^ (Al & Cl) ^ (Bl & Cl);\n Hh = Gh | 0;\n Hl = Gl | 0;\n Gh = Fh | 0;\n Gl = Fl | 0;\n Fh = Eh | 0;\n Fl = El | 0;\n ({ h: Eh, l: El } = u64.add(Dh | 0, Dl | 0, T1h | 0, T1l | 0));\n Dh = Ch | 0;\n Dl = Cl | 0;\n Ch = Bh | 0;\n Cl = Bl | 0;\n Bh = Ah | 0;\n Bl = Al | 0;\n const All = u64.add3L(T1l, sigma0l, MAJl);\n Ah = u64.add3H(All, T1h, sigma0h, MAJh);\n Al = All | 0;\n }\n // Add the compressed chunk to the current hash value\n ({ h: Ah, l: Al } = u64.add(this.Ah | 0, this.Al | 0, Ah | 0, Al | 0));\n ({ h: Bh, l: Bl } = u64.add(this.Bh | 0, this.Bl | 0, Bh | 0, Bl | 0));\n ({ h: Ch, l: Cl } = u64.add(this.Ch | 0, this.Cl | 0, Ch | 0, Cl | 0));\n ({ h: Dh, l: Dl } = u64.add(this.Dh | 0, this.Dl | 0, Dh | 0, Dl | 0));\n ({ h: Eh, l: El } = u64.add(this.Eh | 0, this.El | 0, Eh | 0, El | 0));\n ({ h: Fh, l: Fl } = u64.add(this.Fh | 0, this.Fl | 0, Fh | 0, Fl | 0));\n ({ h: Gh, l: Gl } = u64.add(this.Gh | 0, this.Gl | 0, Gh | 0, Gl | 0));\n ({ h: Hh, l: Hl } = u64.add(this.Hh | 0, this.Hl | 0, Hh | 0, Hl | 0));\n this.set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl);\n }\n protected roundClean(): void {\n clean(SHA512_W_H, SHA512_W_L);\n }\n destroy(): void {\n clean(this.buffer);\n this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);\n }\n}\n\nexport class SHA384 extends SHA512 {\n protected Ah: number = SHA384_IV[0] | 0;\n protected Al: number = SHA384_IV[1] | 0;\n protected Bh: number = SHA384_IV[2] | 0;\n protected Bl: number = SHA384_IV[3] | 0;\n protected Ch: number = SHA384_IV[4] | 0;\n protected Cl: number = SHA384_IV[5] | 0;\n protected Dh: number = SHA384_IV[6] | 0;\n protected Dl: number = SHA384_IV[7] | 0;\n protected Eh: number = SHA384_IV[8] | 0;\n protected El: number = SHA384_IV[9] | 0;\n protected Fh: number = SHA384_IV[10] | 0;\n protected Fl: number = SHA384_IV[11] | 0;\n protected Gh: number = SHA384_IV[12] | 0;\n protected Gl: number = SHA384_IV[13] | 0;\n protected Hh: number = SHA384_IV[14] | 0;\n protected Hl: number = SHA384_IV[15] | 0;\n\n constructor() {\n super(48);\n }\n}\n\n/**\n * Truncated SHA512/256 and SHA512/224.\n * SHA512_IV is XORed with 0xa5a5a5a5a5a5a5a5, then used as \"intermediary\" IV of SHA512/t.\n * Then t hashes string to produce result IV.\n * See `test/misc/sha2-gen-iv.js`.\n */\n\n/** SHA512/224 IV */\nconst T224_IV = /* @__PURE__ */ Uint32Array.from([\n 0x8c3d37c8, 0x19544da2, 0x73e19966, 0x89dcd4d6, 0x1dfab7ae, 0x32ff9c82, 0x679dd514, 0x582f9fcf,\n 0x0f6d2b69, 0x7bd44da8, 0x77e36f73, 0x04c48942, 0x3f9d85a8, 0x6a1d36c8, 0x1112e6ad, 0x91d692a1,\n]);\n\n/** SHA512/256 IV */\nconst T256_IV = /* @__PURE__ */ Uint32Array.from([\n 0x22312194, 0xfc2bf72c, 0x9f555fa3, 0xc84c64c2, 0x2393b86b, 0x6f53b151, 0x96387719, 0x5940eabd,\n 0x96283ee2, 0xa88effe3, 0xbe5e1e25, 0x53863992, 0x2b0199fc, 0x2c85b8aa, 0x0eb72ddc, 0x81c52ca2,\n]);\n\nexport class SHA512_224 extends SHA512 {\n protected Ah: number = T224_IV[0] | 0;\n protected Al: number = T224_IV[1] | 0;\n protected Bh: number = T224_IV[2] | 0;\n protected Bl: number = T224_IV[3] | 0;\n protected Ch: number = T224_IV[4] | 0;\n protected Cl: number = T224_IV[5] | 0;\n protected Dh: number = T224_IV[6] | 0;\n protected Dl: number = T224_IV[7] | 0;\n protected Eh: number = T224_IV[8] | 0;\n protected El: number = T224_IV[9] | 0;\n protected Fh: number = T224_IV[10] | 0;\n protected Fl: number = T224_IV[11] | 0;\n protected Gh: number = T224_IV[12] | 0;\n protected Gl: number = T224_IV[13] | 0;\n protected Hh: number = T224_IV[14] | 0;\n protected Hl: number = T224_IV[15] | 0;\n\n constructor() {\n super(28);\n }\n}\n\nexport class SHA512_256 extends SHA512 {\n protected Ah: number = T256_IV[0] | 0;\n protected Al: number = T256_IV[1] | 0;\n protected Bh: number = T256_IV[2] | 0;\n protected Bl: number = T256_IV[3] | 0;\n protected Ch: number = T256_IV[4] | 0;\n protected Cl: number = T256_IV[5] | 0;\n protected Dh: number = T256_IV[6] | 0;\n protected Dl: number = T256_IV[7] | 0;\n protected Eh: number = T256_IV[8] | 0;\n protected El: number = T256_IV[9] | 0;\n protected Fh: number = T256_IV[10] | 0;\n protected Fl: number = T256_IV[11] | 0;\n protected Gh: number = T256_IV[12] | 0;\n protected Gl: number = T256_IV[13] | 0;\n protected Hh: number = T256_IV[14] | 0;\n protected Hl: number = T256_IV[15] | 0;\n\n constructor() {\n super(32);\n }\n}\n\n/**\n * SHA2-256 hash function from RFC 4634.\n *\n * It is the fastest JS hash, even faster than Blake3.\n * To break sha256 using birthday attack, attackers need to try 2^128 hashes.\n * BTC network is doing 2^70 hashes/sec (2^95 hashes/year) as per 2025.\n */\nexport const sha256: CHash = /* @__PURE__ */ createHasher(() => new SHA256());\n/** SHA2-224 hash function from RFC 4634 */\nexport const sha224: CHash = /* @__PURE__ */ createHasher(() => new SHA224());\n\n/** SHA2-512 hash function from RFC 4634. */\nexport const sha512: CHash = /* @__PURE__ */ createHasher(() => new SHA512());\n/** SHA2-384 hash function from RFC 4634. */\nexport const sha384: CHash = /* @__PURE__ */ createHasher(() => new SHA384());\n\n/**\n * SHA2-512/256 \"truncated\" hash function, with improved resistance to length extension attacks.\n * See the paper on [truncated SHA512](https://eprint.iacr.org/2010/548.pdf).\n */\nexport const sha512_256: CHash = /* @__PURE__ */ createHasher(() => new SHA512_256());\n/**\n * SHA2-512/224 \"truncated\" hash function, with improved resistance to length extension attacks.\n * See the paper on [truncated SHA512](https://eprint.iacr.org/2010/548.pdf).\n */\nexport const sha512_224: CHash = /* @__PURE__ */ createHasher(() => new SHA512_224());\n", "type SimpleValue = boolean | null | undefined;\n\nexport type ResultObject = { [key: string]: ResultValue };\nexport type ResultValue =\n\t| SimpleValue\n\t| number\n\t| string\n\t| Uint8Array\n\t| Array\n\t| ResultObject;\n\ntype ResultKeyType = Extract;\nexport type ValidDecodedType = Extract;\n\nfunction isResultKeyType(value: ResultValue): value is ResultKeyType {\n\treturn typeof value === 'number' || typeof value === 'string';\n}\n\ntype DecodeResult = {\n\tvalue: T;\n\toffset: number;\n};\n\nexport function encodeCBOR(value: any) {\n\tconst buffer: Array = [];\n\tencodeItem(value, buffer);\n\treturn new Uint8Array(buffer);\n}\n\nfunction encodeItem(value: any, buffer: Array) {\n\tif (value === null) {\n\t\tbuffer.push(0xf6);\n\t} else if (value === undefined) {\n\t\tbuffer.push(0xf7);\n\t} else if (typeof value === 'boolean') {\n\t\tbuffer.push(value ? 0xf5 : 0xf4);\n\t} else if (typeof value === 'number') {\n\t\tencodeUnsigned(value, buffer);\n\t} else if (typeof value === 'string') {\n\t\tencodeString(value, buffer);\n\t} else if (Array.isArray(value)) {\n\t\tencodeArray(value, buffer);\n\t} else if (value instanceof Uint8Array) {\n\t\tencodeByteString(value, buffer);\n\t} else if (typeof value === 'object') {\n\t\tencodeObject(value, buffer);\n\t} else {\n\t\tthrow new Error('Unsupported type');\n\t}\n}\n\nfunction encodeUnsigned(value: number, buffer: Array) {\n\tif (value < 24) {\n\t\tbuffer.push(value);\n\t} else if (value < 256) {\n\t\tbuffer.push(0x18, value);\n\t} else if (value < 65536) {\n\t\tbuffer.push(0x19, value >> 8, value & 0xff);\n\t} else if (value < 4294967296) {\n\t\tbuffer.push(0x1a, value >> 24, (value >> 16) & 0xff, (value >> 8) & 0xff, value & 0xff);\n\t} else {\n\t\tthrow new Error('Unsupported integer size');\n\t}\n}\n\nfunction encodeByteString(value: Uint8Array, buffer: Array) {\n\tconst length = value.length;\n\n\tif (length < 24) {\n\t\tbuffer.push(0x40 + length);\n\t} else if (length < 256) {\n\t\tbuffer.push(0x58, length);\n\t} else if (length < 65536) {\n\t\tbuffer.push(0x59, (length >> 8) & 0xff, length & 0xff);\n\t} else if (length < 4294967296) {\n\t\tbuffer.push(\n\t\t\t0x5a,\n\t\t\t(length >> 24) & 0xff,\n\t\t\t(length >> 16) & 0xff,\n\t\t\t(length >> 8) & 0xff,\n\t\t\tlength & 0xff\n\t\t);\n\t} else {\n\t\tthrow new Error('Byte string too long to encode');\n\t}\n\n\tfor (let i = 0; i < value.length; i++) {\n\t\tbuffer.push(value[i]);\n\t}\n}\n\nfunction encodeString(value: string, buffer: Array) {\n\tconst utf8 = new TextEncoder().encode(value);\n\tconst length = utf8.length;\n\n\tif (length < 24) {\n\t\tbuffer.push(0x60 + length);\n\t} else if (length < 256) {\n\t\tbuffer.push(0x78, length);\n\t} else if (length < 65536) {\n\t\tbuffer.push(0x79, (length >> 8) & 0xff, length & 0xff);\n\t} else if (length < 4294967296) {\n\t\tbuffer.push(\n\t\t\t0x7a,\n\t\t\t(length >> 24) & 0xff,\n\t\t\t(length >> 16) & 0xff,\n\t\t\t(length >> 8) & 0xff,\n\t\t\tlength & 0xff\n\t\t);\n\t} else {\n\t\tthrow new Error('String too long to encode');\n\t}\n\n\tfor (let i = 0; i < utf8.length; i++) {\n\t\tbuffer.push(utf8[i]);\n\t}\n}\n\nfunction encodeArray(value: Array, buffer: Array) {\n\tconst length = value.length;\n\tif (length < 24) {\n\t\tbuffer.push(0x80 | length);\n\t} else if (length < 256) {\n\t\tbuffer.push(0x98, length);\n\t} else if (length < 65536) {\n\t\tbuffer.push(0x99, length >> 8, length & 0xff);\n\t} else {\n\t\tthrow new Error('Unsupported array length');\n\t}\n\n\tfor (const item of value) {\n\t\tencodeItem(item, buffer);\n\t}\n}\n\nfunction encodeObject(value: { [key: string]: any }, buffer: Array) {\n\tconst keys = Object.keys(value);\n\tencodeUnsigned(keys.length, buffer);\n\tbuffer[buffer.length - 1] |= 0xa0;\n\tfor (const key of keys) {\n\t\tencodeString(key, buffer);\n\t\tencodeItem(value[key], buffer);\n\t}\n}\n\nexport function decodeCBOR(data: Uint8Array): ResultValue {\n\tconst view = new DataView(data.buffer, data.byteOffset, data.byteLength);\n\tconst result = decodeItem(view, 0);\n\treturn result.value;\n}\n\nfunction decodeItem(view: DataView, offset: number): DecodeResult {\n\tif (offset >= view.byteLength) {\n\t\tthrow new Error('Unexpected end of data');\n\t}\n\tconst initialByte = view.getUint8(offset++);\n\tconst majorType = initialByte >> 5;\n\tconst additionalInfo = initialByte & 0x1f;\n\n\tswitch (majorType) {\n\t\tcase 0:\n\t\t\treturn decodeUnsigned(view, offset, additionalInfo);\n\t\tcase 1:\n\t\t\treturn decodeSigned(view, offset, additionalInfo);\n\t\tcase 2:\n\t\t\treturn decodeByteString(view, offset, additionalInfo);\n\t\tcase 3:\n\t\t\treturn decodeString(view, offset, additionalInfo);\n\t\tcase 4:\n\t\t\treturn decodeArray(view, offset, additionalInfo);\n\t\tcase 5:\n\t\t\treturn decodeMap(view, offset, additionalInfo);\n\t\tcase 7:\n\t\t\treturn decodeSimpleAndFloat(view, offset, additionalInfo);\n\t\tdefault:\n\t\t\tthrow new Error(`Unsupported major type: ${majorType}`);\n\t}\n}\n\nfunction decodeLength(\n\tview: DataView,\n\toffset: number,\n\tadditionalInfo: number\n): DecodeResult {\n\tif (additionalInfo < 24) return { value: additionalInfo, offset };\n\tif (additionalInfo === 24) return { value: view.getUint8(offset++), offset };\n\tif (additionalInfo === 25) {\n\t\tconst value = view.getUint16(offset, false);\n\t\toffset += 2;\n\t\treturn { value, offset };\n\t}\n\tif (additionalInfo === 26) {\n\t\tconst value = view.getUint32(offset, false);\n\t\toffset += 4;\n\t\treturn { value, offset };\n\t}\n\tif (additionalInfo === 27) {\n\t\tconst hi = view.getUint32(offset, false);\n\t\tconst lo = view.getUint32(offset + 4, false);\n\t\toffset += 8;\n\t\treturn { value: hi * 2 ** 32 + lo, offset };\n\t}\n\tthrow new Error(`Unsupported length: ${additionalInfo}`);\n}\n\nfunction decodeUnsigned(\n\tview: DataView,\n\toffset: number,\n\tadditionalInfo: number\n): DecodeResult {\n\tconst { value, offset: newOffset } = decodeLength(view, offset, additionalInfo);\n\treturn { value, offset: newOffset };\n}\n\nfunction decodeSigned(\n\tview: DataView,\n\toffset: number,\n\tadditionalInfo: number\n): DecodeResult {\n\tconst { value, offset: newOffset } = decodeLength(view, offset, additionalInfo);\n\treturn { value: -1 - value, offset: newOffset };\n}\n\nfunction decodeByteString(\n\tview: DataView,\n\toffset: number,\n\tadditionalInfo: number\n): DecodeResult {\n\tconst { value: length, offset: newOffset } = decodeLength(view, offset, additionalInfo);\n\tif (newOffset + length > view.byteLength) {\n\t\tthrow new Error('Byte string length exceeds data length');\n\t}\n\tconst value = new Uint8Array(view.buffer, view.byteOffset + newOffset, length);\n\treturn { value, offset: newOffset + length };\n}\n\nfunction decodeString(\n\tview: DataView,\n\toffset: number,\n\tadditionalInfo: number\n): DecodeResult {\n\tconst { value: length, offset: newOffset } = decodeLength(view, offset, additionalInfo);\n\tif (newOffset + length > view.byteLength) {\n\t\tthrow new Error('String length exceeds data length');\n\t}\n\tconst bytes = new Uint8Array(view.buffer, view.byteOffset + newOffset, length);\n\tconst value = new TextDecoder().decode(bytes);\n\treturn { value, offset: newOffset + length };\n}\n\nfunction decodeArray(\n\tview: DataView,\n\toffset: number,\n\tadditionalInfo: number\n): DecodeResult> {\n\tconst { value: length, offset: newOffset } = decodeLength(view, offset, additionalInfo);\n\tconst array = [];\n\tlet currentOffset = newOffset;\n\tfor (let i = 0; i < length; i++) {\n\t\tconst result = decodeItem(view, currentOffset);\n\t\tarray.push(result.value);\n\t\tcurrentOffset = result.offset;\n\t}\n\treturn { value: array, offset: currentOffset };\n}\n\nfunction decodeMap(\n\tview: DataView,\n\toffset: number,\n\tadditionalInfo: number\n): DecodeResult> {\n\tconst { value: length, offset: newOffset } = decodeLength(view, offset, additionalInfo);\n\tconst map: { [key: string]: ResultValue } = {};\n\tlet currentOffset = newOffset;\n\tfor (let i = 0; i < length; i++) {\n\t\tconst keyResult = decodeItem(view, currentOffset);\n\t\tif (!isResultKeyType(keyResult.value)) {\n\t\t\tthrow new Error('Invalid key type');\n\t\t}\n\t\tconst valueResult = decodeItem(view, keyResult.offset);\n\t\tmap[keyResult.value] = valueResult.value;\n\t\tcurrentOffset = valueResult.offset;\n\t}\n\treturn { value: map, offset: currentOffset };\n}\n\nfunction decodeFloat16(uint16: number): number {\n\tconst exponent = (uint16 & 0x7c00) >> 10;\n\tconst fraction = uint16 & 0x03ff;\n\tconst sign = uint16 & 0x8000 ? -1 : 1;\n\n\tif (exponent === 0) {\n\t\treturn sign * 2 ** -14 * (fraction / 1024);\n\t} else if (exponent === 0x1f) {\n\t\treturn fraction ? NaN : sign * Infinity;\n\t}\n\treturn sign * 2 ** (exponent - 15) * (1 + fraction / 1024);\n}\n\nfunction decodeSimpleAndFloat(\n\tview: DataView,\n\toffset: number,\n\tadditionalInfo: number\n): DecodeResult {\n\tif (additionalInfo < 24) {\n\t\tswitch (additionalInfo) {\n\t\t\tcase 20:\n\t\t\t\treturn { value: false, offset };\n\t\t\tcase 21:\n\t\t\t\treturn { value: true, offset };\n\t\t\tcase 22:\n\t\t\t\treturn { value: null, offset };\n\t\t\tcase 23:\n\t\t\t\treturn { value: undefined, offset };\n\t\t\tdefault:\n\t\t\t\tthrow new Error(`Unknown simple value: ${additionalInfo}`);\n\t\t}\n\t}\n\tif (additionalInfo === 24) return { value: view.getUint8(offset++), offset };\n\tif (additionalInfo === 25) {\n\t\tconst value = decodeFloat16(view.getUint16(offset, false));\n\t\toffset += 2;\n\t\treturn { value, offset };\n\t}\n\tif (additionalInfo === 26) {\n\t\tconst value = view.getFloat32(offset, false);\n\t\toffset += 4;\n\t\treturn { value, offset };\n\t}\n\tif (additionalInfo === 27) {\n\t\tconst value = view.getFloat64(offset, false);\n\t\toffset += 8;\n\t\treturn { value, offset };\n\t}\n\tthrow new Error(`Unknown simple or float value: ${additionalInfo}`);\n}\n", "import { encodeBase64toUint8 } from '../base64';\nimport { decodeCBOR, encodeCBOR } from '../cbor';\nimport {\n\tRawPaymentRequest,\n\tRawTransport,\n\tPaymentRequestTransport,\n\tPaymentRequestTransportType\n} from './types';\nimport { Buffer } from 'buffer';\n\nexport class PaymentRequest {\n\tconstructor(\n\t\tpublic transport: Array,\n\t\tpublic id?: string,\n\t\tpublic amount?: number,\n\t\tpublic unit?: string,\n\t\tpublic mints?: Array,\n\t\tpublic description?: string,\n\t\tpublic singleUse: boolean = false\n\t) {}\n\n\ttoEncodedRequest() {\n\t\tconst rawRequest: RawPaymentRequest = {\n\t\t\tt: this.transport.map((t: PaymentRequestTransport) => ({ t: t.type, a: t.target, g: t.tags }))\n\t\t};\n\t\tif (this.id) {\n\t\t\trawRequest.i = this.id;\n\t\t}\n\t\tif (this.amount) {\n\t\t\trawRequest.a = this.amount;\n\t\t}\n\t\tif (this.unit) {\n\t\t\trawRequest.u = this.unit;\n\t\t}\n\t\tif (this.mints) {\n\t\t\trawRequest.m = this.mints;\n\t\t}\n\t\tif (this.description) {\n\t\t\trawRequest.d = this.description;\n\t\t}\n\t\tif (this.singleUse) {\n\t\t\trawRequest.s = this.singleUse;\n\t\t}\n\n\t\tconst data = encodeCBOR(rawRequest);\n\t\tconst encodedData = Buffer.from(data).toString('base64');\n\t\treturn 'creq' + 'A' + encodedData;\n\t}\n\n\tgetTransport(type: PaymentRequestTransportType) {\n\t\treturn this.transport.find((t: PaymentRequestTransport) => t.type === type);\n\t}\n\n\tstatic fromEncodedRequest(encodedRequest: string): PaymentRequest {\n\t\tif (!encodedRequest.startsWith('creq')) {\n\t\t\tthrow new Error('unsupported pr: invalid prefix');\n\t\t}\n\t\tconst version = encodedRequest[4];\n\t\tif (version !== 'A') {\n\t\t\tthrow new Error('unsupported pr version');\n\t\t}\n\t\tconst encodedData = encodedRequest.slice(5);\n\t\tconst data = encodeBase64toUint8(encodedData);\n\t\tconst decoded = decodeCBOR(data) as RawPaymentRequest;\n\t\tconst transports = decoded.t.map((t: RawTransport) => ({ type: t.t, target: t.a, tags: t.g }));\n\t\treturn new PaymentRequest(\n\t\t\ttransports,\n\t\t\tdecoded.i,\n\t\t\tdecoded.a,\n\t\t\tdecoded.u,\n\t\t\tdecoded.m,\n\t\t\tdecoded.d,\n\t\t\tdecoded.s\n\t\t);\n\t}\n}\n", "import {\n\tencodeBase64ToJson,\n\tencodeBase64toUint8,\n\tencodeJsonToBase64,\n\tencodeUint8toBase64Url\n} from './base64.js';\nimport {\n\tDeprecatedToken,\n\tKeys,\n\tProof,\n\tToken,\n\tTokenV4Template,\n\tV4InnerToken,\n\tV4ProofTemplate\n} from './model/types/index.js';\nimport { TOKEN_PREFIX, TOKEN_VERSION } from './utils/Constants.js';\nimport { bytesToHex, hexToBytes } from '@noble/curves/abstract/utils';\nimport { sha256 } from '@noble/hashes/sha256';\nimport { decodeCBOR, encodeCBOR } from './cbor.js';\nimport { PaymentRequest } from './model/PaymentRequest.js';\n\n/**\n * Splits the amount into denominations of the provided @param keyset\n * @param value amount to split\n * @param keyset keys to look up split amounts\n * @param split? optional custom split amounts\n * @param order? optional order for split amounts (default: \"asc\")\n * @returns Array of split amounts\n * @throws Error if @param split amount is greater than @param value amount\n */\nexport function splitAmount(\n\tvalue: number,\n\tkeyset: Keys,\n\tsplit?: Array,\n\torder?: 'desc' | 'asc'\n): Array {\n\tif (split) {\n\t\tif (split.reduce((a: number, b: number) => a + b, 0) > value) {\n\t\t\tthrow new Error(\n\t\t\t\t`Split is greater than total amount: ${split.reduce(\n\t\t\t\t\t(a: number, b: number) => a + b,\n\t\t\t\t\t0\n\t\t\t\t)} > ${value}`\n\t\t\t);\n\t\t}\n\t\tsplit.forEach((amt: number) => {\n\t\t\tif (!hasCorrespondingKey(amt, keyset)) {\n\t\t\t\tthrow new Error('Provided amount preferences do not match the amounts of the mint keyset.');\n\t\t\t}\n\t\t});\n\t\tvalue =\n\t\t\tvalue -\n\t\t\tsplit.reduce((curr: number, acc: number) => {\n\t\t\t\treturn curr + acc;\n\t\t\t}, 0);\n\t} else {\n\t\tsplit = [];\n\t}\n\tconst sortedKeyAmounts = getKeysetAmounts(keyset);\n\tsortedKeyAmounts.forEach((amt: number) => {\n\t\tconst q = Math.floor(value / amt);\n\t\tfor (let i = 0; i < q; ++i) split?.push(amt);\n\t\tvalue %= amt;\n\t});\n\treturn split.sort((a, b) => (order === 'desc' ? b - a : a - b));\n}\n\n/**\n * Creates a list of amounts to keep based on the proofs we have and the proofs we want to reach.\n * @param proofsWeHave complete set of proofs stored (from current mint)\n * @param amountToKeep amount to keep\n * @param keys keys of current keyset\n * @param targetCount the target number of proofs to reach\n * @returns an array of amounts to keep\n */\nexport function getKeepAmounts(\n\tproofsWeHave: Array,\n\tamountToKeep: number,\n\tkeys: Keys,\n\ttargetCount: number\n): Array {\n\t// determines amounts we need to reach the targetCount for each amount based on the amounts of the proofs we have\n\t// it tries to select amounts so that the proofs we have and the proofs we want reach the targetCount\n\tconst amountsWeWant: Array = [];\n\tconst amountsWeHave = proofsWeHave.map((p: Proof) => p.amount);\n\tconst sortedKeyAmounts = getKeysetAmounts(keys, 'asc');\n\tsortedKeyAmounts.forEach((amt) => {\n\t\tconst countWeHave = amountsWeHave.filter((a) => a === amt).length;\n\t\tconst countWeWant = Math.max(targetCount - countWeHave, 0);\n\t\tfor (let i = 0; i < countWeWant; ++i) {\n\t\t\tif (amountsWeWant.reduce((a, b) => a + b, 0) + amt > amountToKeep) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tamountsWeWant.push(amt);\n\t\t}\n\t});\n\t// use splitAmount to fill the rest between the sum of amountsWeHave and amountToKeep\n\tconst amountDiff = amountToKeep - amountsWeWant.reduce((a, b) => a + b, 0);\n\tif (amountDiff) {\n\t\tconst remainingAmounts = splitAmount(amountDiff, keys);\n\t\tremainingAmounts.forEach((amt: number) => {\n\t\t\tamountsWeWant.push(amt);\n\t\t});\n\t}\n\tconst sortedAmountsWeWant = amountsWeWant.sort((a, b) => a - b);\n\treturn sortedAmountsWeWant;\n}\n/**\n * returns the amounts in the keyset sorted by the order specified\n * @param keyset to search in\n * @param order order to sort the amounts in\n * @returns the amounts in the keyset sorted by the order specified\n */\nexport function getKeysetAmounts(keyset: Keys, order: 'asc' | 'desc' = 'desc'): Array {\n\tif (order == 'desc') {\n\t\treturn Object.keys(keyset)\n\t\t\t.map((k: string) => parseInt(k))\n\t\t\t.sort((a: number, b: number) => b - a);\n\t}\n\treturn Object.keys(keyset)\n\t\t.map((k: string) => parseInt(k))\n\t\t.sort((a: number, b: number) => a - b);\n}\n\n/**\n * Checks if the provided amount is in the keyset.\n * @param amount amount to check\n * @param keyset to search in\n * @returns true if the amount is in the keyset, false otherwise\n */\nexport function hasCorrespondingKey(amount: number, keyset: Keys): boolean {\n\treturn amount in keyset;\n}\n\n/**\n * Converts a bytes array to a number.\n * @param bytes to convert to number\n * @returns number\n */\nexport function bytesToNumber(bytes: Uint8Array): bigint {\n\treturn hexToNumber(bytesToHex(bytes));\n}\n\n/**\n * Converts a hex string to a number.\n * @param hex to convert to number\n * @returns number\n */\nexport function hexToNumber(hex: string): bigint {\n\treturn BigInt(`0x${hex}`);\n}\n\nfunction isValidHex(str: string) {\n\treturn /^[a-f0-9]*$/i.test(str);\n}\n\n/**\n * Checks wether a proof or a list of proofs contains a non-hex id\n * @param p Proof or list of proofs\n * @returns boolean\n */\nexport function hasNonHexId(p: Proof | Array) {\n\tif (Array.isArray(p)) {\n\t\treturn p.some((proof) => !isValidHex(proof.id));\n\t}\n\treturn isValidHex(p.id);\n}\n\n//used for json serialization\nexport function bigIntStringify(_key: unknown, value: T) {\n\treturn typeof value === 'bigint' ? value.toString() : value;\n}\n\n/**\n * Helper function to encode a v3 cashu token\n * @param token to encode\n * @returns encoded token\n */\nexport function getEncodedTokenV3(token: Token): string {\n\tconst v3TokenObj: DeprecatedToken = { token: [{ mint: token.mint, proofs: token.proofs }] };\n\tif (token.unit) {\n\t\tv3TokenObj.unit = token.unit;\n\t}\n\tif (token.memo) {\n\t\tv3TokenObj.memo = token.memo;\n\t}\n\treturn TOKEN_PREFIX + TOKEN_VERSION + encodeJsonToBase64(v3TokenObj);\n}\n\n/**\n * Helper function to encode a cashu token (defaults to v4 if keyset id allows it)\n * @param token\n * @param [opts]\n */\nexport function getEncodedToken(token: Token, opts?: { version: 3 | 4 }): string {\n\tconst nonHex = hasNonHexId(token.proofs);\n\tif (nonHex || opts?.version === 3) {\n\t\tif (opts?.version === 4) {\n\t\t\tthrow new Error('can not encode to v4 token if proofs contain non-hex keyset id');\n\t\t}\n\t\treturn getEncodedTokenV3(token);\n\t}\n\treturn getEncodedTokenV4(token);\n}\n\nexport function getEncodedTokenV4(token: Token): string {\n\tconst nonHex = hasNonHexId(token.proofs);\n\tif (nonHex) {\n\t\tthrow new Error('can not encode to v4 token if proofs contain non-hex keyset id');\n\t}\n\tconst idMap: { [id: string]: Array } = {};\n\tconst mint = token.mint;\n\tfor (let i = 0; i < token.proofs.length; i++) {\n\t\tconst proof = token.proofs[i];\n\t\tif (idMap[proof.id]) {\n\t\t\tidMap[proof.id].push(proof);\n\t\t} else {\n\t\t\tidMap[proof.id] = [proof];\n\t\t}\n\t}\n\tconst tokenTemplate: TokenV4Template = {\n\t\tm: mint,\n\t\tu: token.unit || 'sat',\n\t\tt: Object.keys(idMap).map(\n\t\t\t(id: string): V4InnerToken => ({\n\t\t\t\ti: hexToBytes(id),\n\t\t\t\tp: idMap[id].map(\n\t\t\t\t\t(p: Proof): V4ProofTemplate => ({ a: p.amount, s: p.secret, c: hexToBytes(p.C) })\n\t\t\t\t)\n\t\t\t})\n\t\t)\n\t} as TokenV4Template;\n\n\tif (token.memo) {\n\t\ttokenTemplate.d = token.memo;\n\t}\n\n\tconst encodedData = encodeCBOR(tokenTemplate);\n\tconst prefix = 'cashu';\n\tconst version = 'B';\n\tconst base64Data = encodeUint8toBase64Url(encodedData);\n\treturn prefix + version + base64Data;\n}\n\n/**\n * Helper function to decode cashu tokens into object\n * @param token an encoded cashu token (cashuAey...)\n * @returns cashu token object\n */\nexport function getDecodedToken(token: string) {\n\t// remove prefixes\n\tconst uriPrefixes = ['web+cashu://', 'cashu://', 'cashu:', 'cashu'];\n\turiPrefixes.forEach((prefix: string) => {\n\t\tif (!token.startsWith(prefix)) {\n\t\t\treturn;\n\t\t}\n\t\ttoken = token.slice(prefix.length);\n\t});\n\treturn handleTokens(token);\n}\n\n/**\n * Helper function to decode different versions of cashu tokens into an object\n * @param token an encoded cashu token (cashuAey...)\n * @returns cashu Token object\n */\nexport function handleTokens(token: string): Token {\n\tconst version = token.slice(0, 1);\n\tconst encodedToken = token.slice(1);\n\tif (version === 'A') {\n\t\tconst parsedV3Token = encodeBase64ToJson(encodedToken);\n\t\tif (parsedV3Token.token.length > 1) {\n\t\t\tthrow new Error('Multi entry token are not supported');\n\t\t}\n\t\tconst entry = parsedV3Token.token[0];\n\t\tconst tokenObj: Token = {\n\t\t\tmint: entry.mint,\n\t\t\tproofs: entry.proofs,\n\t\t\tunit: parsedV3Token.unit || 'sat'\n\t\t};\n\t\tif (parsedV3Token.memo) {\n\t\t\ttokenObj.memo = parsedV3Token.memo;\n\t\t}\n\t\treturn tokenObj;\n\t} else if (version === 'B') {\n\t\tconst uInt8Token = encodeBase64toUint8(encodedToken);\n\t\tconst tokenData = decodeCBOR(uInt8Token) as TokenV4Template;\n\t\tconst proofs: Array = [];\n\t\ttokenData.t.forEach((t) =>\n\t\t\tt.p.forEach((p) => {\n\t\t\t\tproofs.push({\n\t\t\t\t\tsecret: p.s,\n\t\t\t\t\tC: bytesToHex(p.c),\n\t\t\t\t\tamount: p.a,\n\t\t\t\t\tid: bytesToHex(t.i)\n\t\t\t\t});\n\t\t\t})\n\t\t);\n\t\tconst decodedToken: Token = { mint: tokenData.m, proofs, unit: tokenData.u || 'sat' };\n\t\tif (tokenData.d) {\n\t\t\tdecodedToken.memo = tokenData.d;\n\t\t}\n\t\treturn decodedToken;\n\t}\n\tthrow new Error('Token version is not supported');\n}\n/**\n * Returns the keyset id of a set of keys\n * @param keys keys object to derive keyset id from\n * @returns\n */\nexport function deriveKeysetId(keys: Keys) {\n\tconst pubkeysConcat = Object.entries(keys)\n\t\t.sort((a: [string, string], b: [string, string]) => +a[0] - +b[0])\n\t\t.map(([, pubKey]: [unknown, string]) => hexToBytes(pubKey))\n\t\t.reduce((prev: Uint8Array, curr: Uint8Array) => mergeUInt8Arrays(prev, curr), new Uint8Array());\n\tconst hash = sha256(pubkeysConcat);\n\tconst hashHex = Buffer.from(hash).toString('hex').slice(0, 14);\n\treturn '00' + hashHex;\n}\n\nexport function mergeUInt8Arrays(a1: Uint8Array, a2: Uint8Array): Uint8Array {\n\t// sum of individual array lengths\n\tconst mergedArray = new Uint8Array(a1.length + a2.length);\n\tmergedArray.set(a1);\n\tmergedArray.set(a2, a1.length);\n\treturn mergedArray;\n}\n\nexport function sortProofsById(proofs: Array) {\n\treturn proofs.sort((a: Proof, b: Proof) => a.id.localeCompare(b.id));\n}\n\nexport function isObj(v: unknown): v is object {\n\treturn typeof v === 'object';\n}\n\nexport function checkResponse(data: { error?: string; detail?: string }) {\n\tif (!isObj(data)) return;\n\tif ('error' in data && data.error) {\n\t\tthrow new Error(data.error);\n\t}\n\tif ('detail' in data && data.detail) {\n\t\tthrow new Error(data.detail);\n\t}\n}\n\nexport function joinUrls(...parts: Array): string {\n\treturn parts.map((part: string) => part.replace(/(^\\/+|\\/+$)/g, '')).join('/');\n}\n\nexport function sanitizeUrl(url: string): string {\n\treturn url.replace(/\\/$/, '');\n}\n\nexport function sumProofs(proofs: Array) {\n\treturn proofs.reduce((acc: number, proof: Proof) => acc + proof.amount, 0);\n}\n\nexport function decodePaymentRequest(paymentRequest: string) {\n\treturn PaymentRequest.fromEncodedRequest(paymentRequest);\n}\n", "import type { MeltQuoteResponse } from '../model/types/index.js';\nimport { MeltQuoteState } from '../model/types/index.js';\n\nexport type MeltQuoteResponsePaidDeprecated = {\n\tpaid?: boolean;\n};\n\nexport function handleMeltQuoteResponseDeprecated(\n\tresponse: MeltQuoteResponse & MeltQuoteResponsePaidDeprecated\n): MeltQuoteResponse {\n\t// if the response MeltQuoteResponse has a \"paid\" flag, we monkey patch it to the state enum\n\tif (!response.state) {\n\t\tconsole.warn(\n\t\t\t\"Field 'state' not found in MeltQuoteResponse. Update NUT-05 of mint: https://github.com/cashubtc/nuts/pull/136)\"\n\t\t);\n\t\tif (typeof response.paid === 'boolean') {\n\t\t\tresponse.state = response.paid ? MeltQuoteState.PAID : MeltQuoteState.UNPAID;\n\t\t}\n\t}\n\treturn response;\n}\n", "import type { MintQuoteResponse } from '../model/types/index.js';\nimport { MintQuoteState } from '../model/types/index.js';\n\nexport type MintQuoteResponsePaidDeprecated = {\n\tpaid?: boolean;\n};\n\nexport function handleMintQuoteResponseDeprecated(\n\tresponse: MintQuoteResponse & MintQuoteResponsePaidDeprecated\n): MintQuoteResponse {\n\t// if the response MeltQuoteResponse has a \"paid\" flag, we monkey patch it to the state enum\n\tif (!response.state) {\n\t\tconsole.warn(\n\t\t\t\"Field 'state' not found in MintQuoteResponse. Update NUT-04 of mint: https://github.com/cashubtc/nuts/pull/141)\"\n\t\t);\n\t\tif (typeof response.paid === 'boolean') {\n\t\t\tresponse.state = response.paid ? MintQuoteState.PAID : MintQuoteState.UNPAID;\n\t\t}\n\t}\n\treturn response;\n}\n", "import type { MintContactInfo, GetInfoResponse } from '../model/types/index.js';\n\nexport function handleMintInfoContactFieldDeprecated(data: GetInfoResponse) {\n\t// Monkey patch old contact field [\"email\", \"me@mail.com\"] Array<[string, string]>; to new contact field [{method: \"email\", info: \"me@mail.com\"}] Array\n\t// This is to maintain backwards compatibility with older versions of the mint\n\tif (Array.isArray(data?.contact) && data?.contact.length > 0) {\n\t\tdata.contact = data.contact.map((contact: MintContactInfo) => {\n\t\t\tif (\n\t\t\t\tArray.isArray(contact) &&\n\t\t\t\tcontact.length === 2 &&\n\t\t\t\ttypeof contact[0] === 'string' &&\n\t\t\t\ttypeof contact[1] === 'string'\n\t\t\t) {\n\t\t\t\tconsole.warn(\n\t\t\t\t\t`Mint returned deprecated 'contact' field: Update NUT-06: https://github.com/cashubtc/nuts/pull/117`\n\t\t\t\t);\n\t\t\t\treturn { method: contact[0], info: contact[1] } as MintContactInfo;\n\t\t\t}\n\t\t\treturn contact;\n\t\t});\n\t}\n\treturn data;\n}\n", "import type {\n\tCheckStatePayload,\n\tCheckStateResponse,\n\tGetInfoResponse,\n\tMeltPayload,\n\tMintActiveKeys,\n\tMintAllKeysets,\n\tPostRestoreResponse,\n\tMintQuoteResponse,\n\tSerializedBlindedMessage,\n\tSwapPayload,\n\tSwapResponse,\n\tMintQuotePayload,\n\tMintPayload,\n\tMintResponse,\n\tPostRestorePayload,\n\tMeltQuotePayload,\n\tMeltQuoteResponse\n} from './model/types/index.js';\nimport { MeltQuoteState } from './model/types/index.js';\nimport request from './request.js';\nimport { isObj, joinUrls, sanitizeUrl } from './utils.js';\nimport {\n\tMeltQuoteResponsePaidDeprecated,\n\thandleMeltQuoteResponseDeprecated\n} from './legacy/nut-05.js';\nimport {\n\tMintQuoteResponsePaidDeprecated,\n\thandleMintQuoteResponseDeprecated\n} from './legacy/nut-04.js';\nimport { handleMintInfoContactFieldDeprecated } from './legacy/nut-06.js';\n/**\n * Class represents Cashu Mint API. This class contains Lower level functions that are implemented by CashuWallet.\n */\nclass CashuMint {\n\t/**\n\t * @param _mintUrl requires mint URL to create this object\n\t * @param _customRequest if passed, use custom request implementation for network communication with the mint\n\t */\n\tconstructor(private _mintUrl: string, private _customRequest?: typeof request) {\n\t\tthis._mintUrl = sanitizeUrl(_mintUrl);\n\t\tthis._customRequest = _customRequest;\n\t}\n\n\tget mintUrl() {\n\t\treturn this._mintUrl;\n\t}\n\n\t/**\n\t * fetches mints info at the /info endpoint\n\t * @param mintUrl\n\t * @param customRequest\n\t */\n\tpublic static async getInfo(\n\t\tmintUrl: string,\n\t\tcustomRequest?: typeof request\n\t): Promise {\n\t\tconst requestInstance = customRequest || request;\n\t\tconst response = await requestInstance({\n\t\t\tendpoint: joinUrls(mintUrl, '/v1/info')\n\t\t});\n\t\tconst data = handleMintInfoContactFieldDeprecated(response);\n\t\treturn data;\n\t}\n\t/**\n\t * fetches mints info at the /info endpoint\n\t */\n\tasync getInfo(): Promise {\n\t\treturn CashuMint.getInfo(this._mintUrl, this._customRequest);\n\t}\n\n\t/**\n\t * Performs a swap operation with ecash inputs and outputs.\n\t * @param mintUrl\n\t * @param swapPayload payload containing inputs and outputs\n\t * @param customRequest\n\t * @returns signed outputs\n\t */\n\tpublic static async swap(\n\t\tmintUrl: string,\n\t\tswapPayload: SwapPayload,\n\t\tcustomRequest?: typeof request\n\t): Promise {\n\t\tconst requestInstance = customRequest || request;\n\t\tconst data = await requestInstance({\n\t\t\tendpoint: joinUrls(mintUrl, '/v1/swap'),\n\t\t\tmethod: 'POST',\n\t\t\trequestBody: swapPayload\n\t\t});\n\n\t\tif (!isObj(data) || !Array.isArray(data?.signatures)) {\n\t\t\tthrow new Error(data.detail ?? 'bad response');\n\t\t}\n\n\t\treturn data;\n\t}\n\t/**\n\t * Performs a swap operation with ecash inputs and outputs.\n\t * @param swapPayload payload containing inputs and outputs\n\t * @returns signed outputs\n\t */\n\tasync swap(swapPayload: SwapPayload): Promise {\n\t\treturn CashuMint.swap(this._mintUrl, swapPayload, this._customRequest);\n\t}\n\n\t/**\n\t * Requests a new mint quote from the mint.\n\t * @param mintUrl\n\t * @param mintQuotePayload Payload for creating a new mint quote\n\t * @param customRequest\n\t * @returns the mint will create and return a new mint quote containing a payment request for the specified amount and unit\n\t */\n\tpublic static async createMintQuote(\n\t\tmintUrl: string,\n\t\tmintQuotePayload: MintQuotePayload,\n\t\tcustomRequest?: typeof request\n\t): Promise {\n\t\tconst requestInstance = customRequest || request;\n\t\tconst response = await requestInstance({\n\t\t\tendpoint: joinUrls(mintUrl, '/v1/mint/quote/bolt11'),\n\t\t\tmethod: 'POST',\n\t\t\trequestBody: mintQuotePayload\n\t\t});\n\t\tconst data = handleMintQuoteResponseDeprecated(response);\n\t\treturn data;\n\t}\n\t/**\n\t * Requests a new mint quote from the mint.\n\t * @param mintQuotePayload Payload for creating a new mint quote\n\t * @returns the mint will create and return a new mint quote containing a payment request for the specified amount and unit\n\t */\n\tasync createMintQuote(mintQuotePayload: MintQuotePayload): Promise {\n\t\treturn CashuMint.createMintQuote(this._mintUrl, mintQuotePayload, this._customRequest);\n\t}\n\n\t/**\n\t * Gets an existing mint quote from the mint.\n\t * @param mintUrl\n\t * @param quote Quote ID\n\t * @param customRequest\n\t * @returns the mint will create and return a Lightning invoice for the specified amount\n\t */\n\tpublic static async checkMintQuote(\n\t\tmintUrl: string,\n\t\tquote: string,\n\t\tcustomRequest?: typeof request\n\t): Promise {\n\t\tconst requestInstance = customRequest || request;\n\t\tconst response = await requestInstance({\n\t\t\tendpoint: joinUrls(mintUrl, '/v1/mint/quote/bolt11', quote),\n\t\t\tmethod: 'GET'\n\t\t});\n\n\t\tconst data = handleMintQuoteResponseDeprecated(response);\n\t\treturn data;\n\t}\n\t/**\n\t * Gets an existing mint quote from the mint.\n\t * @param quote Quote ID\n\t * @returns the mint will create and return a Lightning invoice for the specified amount\n\t */\n\tasync checkMintQuote(quote: string): Promise {\n\t\treturn CashuMint.checkMintQuote(this._mintUrl, quote, this._customRequest);\n\t}\n\n\t/**\n\t * Mints new tokens by requesting blind signatures on the provided outputs.\n\t * @param mintUrl\n\t * @param mintPayload Payload containing the outputs to get blind signatures on\n\t * @param customRequest\n\t * @returns serialized blinded signatures\n\t */\n\tpublic static async mint(\n\t\tmintUrl: string,\n\t\tmintPayload: MintPayload,\n\t\tcustomRequest?: typeof request\n\t) {\n\t\tconst requestInstance = customRequest || request;\n\t\tconst data = await requestInstance({\n\t\t\tendpoint: joinUrls(mintUrl, '/v1/mint/bolt11'),\n\t\t\tmethod: 'POST',\n\t\t\trequestBody: mintPayload\n\t\t});\n\n\t\tif (!isObj(data) || !Array.isArray(data?.signatures)) {\n\t\t\tthrow new Error('bad response');\n\t\t}\n\n\t\treturn data;\n\t}\n\t/**\n\t * Mints new tokens by requesting blind signatures on the provided outputs.\n\t * @param mintPayload Payload containing the outputs to get blind signatures on\n\t * @returns serialized blinded signatures\n\t */\n\tasync mint(mintPayload: MintPayload) {\n\t\treturn CashuMint.mint(this._mintUrl, mintPayload, this._customRequest);\n\t}\n\n\t/**\n\t * Requests a new melt quote from the mint.\n\t * @param mintUrl\n\t * @param MeltQuotePayload\n\t * @returns\n\t */\n\tpublic static async createMeltQuote(\n\t\tmintUrl: string,\n\t\tmeltQuotePayload: MeltQuotePayload,\n\t\tcustomRequest?: typeof request\n\t): Promise {\n\t\tconst requestInstance = customRequest || request;\n\t\tconst response = await requestInstance({\n\t\t\tendpoint: joinUrls(mintUrl, '/v1/melt/quote/bolt11'),\n\t\t\tmethod: 'POST',\n\t\t\trequestBody: meltQuotePayload\n\t\t});\n\n\t\tconst data = handleMeltQuoteResponseDeprecated(response);\n\n\t\tif (\n\t\t\t!isObj(data) ||\n\t\t\ttypeof data?.amount !== 'number' ||\n\t\t\ttypeof data?.fee_reserve !== 'number' ||\n\t\t\ttypeof data?.quote !== 'string'\n\t\t) {\n\t\t\tthrow new Error('bad response');\n\t\t}\n\t\treturn data;\n\t}\n\t/**\n\t * Requests a new melt quote from the mint.\n\t * @param MeltQuotePayload\n\t * @returns\n\t */\n\tasync createMeltQuote(meltQuotePayload: MeltQuotePayload): Promise {\n\t\treturn CashuMint.createMeltQuote(this._mintUrl, meltQuotePayload, this._customRequest);\n\t}\n\n\t/**\n\t * Gets an existing melt quote.\n\t * @param mintUrl\n\t * @param quote Quote ID\n\t * @returns\n\t */\n\tpublic static async checkMeltQuote(\n\t\tmintUrl: string,\n\t\tquote: string,\n\t\tcustomRequest?: typeof request\n\t): Promise {\n\t\tconst requestInstance = customRequest || request;\n\t\tconst response = await requestInstance({\n\t\t\tendpoint: joinUrls(mintUrl, '/v1/melt/quote/bolt11', quote),\n\t\t\tmethod: 'GET'\n\t\t});\n\n\t\tconst data = handleMeltQuoteResponseDeprecated(response);\n\n\t\tif (\n\t\t\t!isObj(data) ||\n\t\t\ttypeof data?.amount !== 'number' ||\n\t\t\ttypeof data?.fee_reserve !== 'number' ||\n\t\t\ttypeof data?.quote !== 'string' ||\n\t\t\ttypeof data?.state !== 'string' ||\n\t\t\t!Object.values(MeltQuoteState).includes(data.state)\n\t\t) {\n\t\t\tthrow new Error('bad response');\n\t\t}\n\n\t\treturn data;\n\t}\n\t/**\n\t * Gets an existing melt quote.\n\t * @param quote Quote ID\n\t * @returns\n\t */\n\tasync checkMeltQuote(quote: string): Promise {\n\t\treturn CashuMint.checkMeltQuote(this._mintUrl, quote, this._customRequest);\n\t}\n\n\t/**\n\t * Requests the mint to pay for a Bolt11 payment request by providing ecash as inputs to be spent. The inputs contain the amount and the fee_reserves for a Lightning payment. The payload can also contain blank outputs in order to receive back overpaid Lightning fees.\n\t * @param mintUrl\n\t * @param meltPayload\n\t * @param customRequest\n\t * @returns\n\t */\n\tpublic static async melt(\n\t\tmintUrl: string,\n\t\tmeltPayload: MeltPayload,\n\t\tcustomRequest?: typeof request\n\t): Promise {\n\t\tconst requestInstance = customRequest || request;\n\t\tconst response = await requestInstance({\n\t\t\tendpoint: joinUrls(mintUrl, '/v1/melt/bolt11'),\n\t\t\tmethod: 'POST',\n\t\t\trequestBody: meltPayload\n\t\t});\n\n\t\tconst data = handleMeltQuoteResponseDeprecated(response);\n\n\t\tif (\n\t\t\t!isObj(data) ||\n\t\t\ttypeof data?.state !== 'string' ||\n\t\t\t!Object.values(MeltQuoteState).includes(data.state)\n\t\t) {\n\t\t\tthrow new Error('bad response');\n\t\t}\n\n\t\treturn data;\n\t}\n\t/**\n\t * Ask mint to perform a melt operation. This pays a lightning invoice and destroys tokens matching its amount + fees\n\t * @param meltPayload\n\t * @returns\n\t */\n\tasync melt(meltPayload: MeltPayload): Promise {\n\t\treturn CashuMint.melt(this._mintUrl, meltPayload, this._customRequest);\n\t}\n\t/**\n\t * Checks if specific proofs have already been redeemed\n\t * @param mintUrl\n\t * @param checkPayload\n\t * @param customRequest\n\t * @returns redeemed and unredeemed ordered list of booleans\n\t */\n\tpublic static async check(\n\t\tmintUrl: string,\n\t\tcheckPayload: CheckStatePayload,\n\t\tcustomRequest?: typeof request\n\t): Promise {\n\t\tconst requestInstance = customRequest || request;\n\t\tconst data = await requestInstance({\n\t\t\tendpoint: joinUrls(mintUrl, '/v1/checkstate'),\n\t\t\tmethod: 'POST',\n\t\t\trequestBody: checkPayload\n\t\t});\n\n\t\tif (!isObj(data) || !Array.isArray(data?.states)) {\n\t\t\tthrow new Error('bad response');\n\t\t}\n\n\t\treturn data;\n\t}\n\n\t/**\n\t * Get the mints public keys\n\t * @param mintUrl\n\t * @param keysetId optional param to get the keys for a specific keyset. If not specified, the keys from all active keysets are fetched\n\t * @param customRequest\n\t * @returns\n\t */\n\tpublic static async getKeys(\n\t\tmintUrl: string,\n\t\tkeysetId?: string,\n\t\tcustomRequest?: typeof request\n\t): Promise {\n\t\t// backwards compatibility for base64 encoded keyset ids\n\t\tif (keysetId) {\n\t\t\t// make the keysetId url safe\n\t\t\tkeysetId = keysetId.replace(/\\//g, '_').replace(/\\+/g, '-');\n\t\t}\n\t\tconst requestInstance = customRequest || request;\n\t\tconst data = await requestInstance({\n\t\t\tendpoint: keysetId ? joinUrls(mintUrl, '/v1/keys', keysetId) : joinUrls(mintUrl, '/v1/keys')\n\t\t});\n\n\t\tif (!isObj(data) || !Array.isArray(data.keysets)) {\n\t\t\tthrow new Error('bad response');\n\t\t}\n\n\t\treturn data;\n\t}\n\t/**\n\t * Get the mints public keys\n\t * @param keysetId optional param to get the keys for a specific keyset. If not specified, the keys from all active keysets are fetched\n\t * @returns the mints public keys\n\t */\n\tasync getKeys(keysetId?: string, mintUrl?: string): Promise {\n\t\tconst allKeys = await CashuMint.getKeys(\n\t\t\tmintUrl || this._mintUrl,\n\t\t\tkeysetId,\n\t\t\tthis._customRequest\n\t\t);\n\t\treturn allKeys;\n\t}\n\t/**\n\t * Get the mints keysets in no specific order\n\t * @param mintUrl\n\t * @param customRequest\n\t * @returns all the mints past and current keysets.\n\t */\n\tpublic static async getKeySets(\n\t\tmintUrl: string,\n\t\tcustomRequest?: typeof request\n\t): Promise {\n\t\tconst requestInstance = customRequest || request;\n\t\treturn requestInstance({ endpoint: joinUrls(mintUrl, '/v1/keysets') });\n\t}\n\n\t/**\n\t * Get the mints keysets in no specific order\n\t * @returns all the mints past and current keysets.\n\t */\n\tasync getKeySets(): Promise {\n\t\treturn CashuMint.getKeySets(this._mintUrl, this._customRequest);\n\t}\n\n\t/**\n\t * Checks if specific proofs have already been redeemed\n\t * @param checkPayload\n\t * @returns redeemed and unredeemed ordered list of booleans\n\t */\n\tasync check(checkPayload: CheckStatePayload): Promise {\n\t\treturn CashuMint.check(this._mintUrl, checkPayload, this._customRequest);\n\t}\n\n\tpublic static async restore(\n\t\tmintUrl: string,\n\t\trestorePayload: PostRestorePayload,\n\t\tcustomRequest?: typeof request\n\t): Promise {\n\t\tconst requestInstance = customRequest || request;\n\t\tconst data = await requestInstance({\n\t\t\tendpoint: joinUrls(mintUrl, '/v1/restore'),\n\t\t\tmethod: 'POST',\n\t\t\trequestBody: restorePayload\n\t\t});\n\n\t\tif (!isObj(data) || !Array.isArray(data?.outputs) || !Array.isArray(data?.promises)) {\n\t\t\tthrow new Error('bad response');\n\t\t}\n\n\t\treturn data;\n\t}\n\n\tasync restore(restorePayload: {\n\t\toutputs: Array;\n\t}): Promise {\n\t\treturn CashuMint.restore(this._mintUrl, restorePayload, this._customRequest);\n\t}\n}\n\nexport { CashuMint };\n", "import { SerializedBlindedMessage } from './types/index.js';\nimport { ProjPointType } from '@noble/curves/abstract/weierstrass';\n\nclass BlindedMessage {\n\tamount: number;\n\tB_: ProjPointType;\n\tid: string;\n\tconstructor(amount: number, B_: ProjPointType, id: string) {\n\t\tthis.amount = amount;\n\t\tthis.B_ = B_;\n\t\tthis.id = id;\n\t}\n\tgetSerializedBlindedMessage(): SerializedBlindedMessage {\n\t\treturn { amount: this.amount, B_: this.B_.toHex(true), id: this.id };\n\t}\n}\nexport { BlindedMessage };\n", "import { bytesToHex, randomBytes } from '@noble/hashes/utils';\nimport { CashuMint } from './CashuMint.js';\nimport { BlindedMessage } from './model/BlindedMessage.js';\nimport {\n\ttype MeltPayload,\n\ttype MeltQuoteResponse,\n\ttype MintKeys,\n\ttype MintKeyset,\n\ttype MeltProofsResponse,\n\ttype MintPayload,\n\ttype Proof,\n\ttype MintQuotePayload,\n\ttype MeltQuotePayload,\n\ttype SendResponse,\n\ttype SerializedBlindedMessage,\n\ttype SwapPayload,\n\ttype Token,\n\tSerializedBlindedSignature,\n\tGetInfoResponse,\n\tOutputAmounts,\n\tProofState,\n\tBlindingData\n} from './model/types/index.js';\nimport { bytesToNumber, getDecodedToken, splitAmount, sumProofs, getKeepAmounts } from './utils.js';\nimport { hashToCurve, pointFromHex } from '@cashu/crypto/modules/common';\nimport {\n\tblindMessage,\n\tconstructProofFromPromise,\n\tserializeProof\n} from '@cashu/crypto/modules/client';\nimport { deriveBlindingFactor, deriveSecret } from '@cashu/crypto/modules/client/NUT09';\nimport { createP2PKsecret, getSignedProofs } from '@cashu/crypto/modules/client/NUT11';\nimport { type Proof as NUT11Proof } from '@cashu/crypto/modules/common/index';\n\n/**\n * The default number of proofs per denomination to keep in a wallet.\n */\nconst DEFAULT_DENOMINATION_TARGET = 3;\n\n/**\n * The default unit for the wallet, if not specified in constructor.\n */\nconst DEFAULT_UNIT = 'sat';\n\n/**\n * Class that represents a Cashu wallet.\n * This class should act as the entry point for this library\n */\nclass CashuWallet {\n\tprivate _keys: Map = new Map();\n\tprivate _keysetId: string | undefined;\n\tprivate _keysets: Array = [];\n\tprivate _seed: Uint8Array | undefined = undefined;\n\tprivate _unit = DEFAULT_UNIT;\n\tprivate _mintInfo: GetInfoResponse | undefined = undefined;\n\tprivate _denominationTarget = DEFAULT_DENOMINATION_TARGET;\n\n\tmint: CashuMint;\n\n\t/**\n\t * @param mint Cashu mint instance is used to make api calls\n\t * @param options.unit optionally set unit (default is 'sat')\n\t * @param options.keys public keys from the mint (will be fetched from mint if not provided)\n\t * @param options.keysets keysets from the mint (will be fetched from mint if not provided)\n\t * @param options.mintInfo mint info from the mint (will be fetched from mint if not provided)\n\t * @param options.denominationTarget target number proofs per denomination (default: see @constant DEFAULT_DENOMINATION_TARGET)\n\t * @param options.bip39seed BIP39 seed for deterministic secrets.\n\t * This can lead to poor performance, in which case the seed should be directly provided\n\t */\n\tconstructor(\n\t\tmint: CashuMint,\n\t\toptions?: {\n\t\t\tunit?: string;\n\t\t\tkeys?: Array | MintKeys;\n\t\t\tkeysets?: Array;\n\t\t\tmintInfo?: GetInfoResponse;\n\t\t\tbip39seed?: Uint8Array;\n\t\t\tdenominationTarget?: number;\n\t\t}\n\t) {\n\t\tthis.mint = mint;\n\t\tlet keys: Array = [];\n\t\tif (options?.keys && !Array.isArray(options.keys)) {\n\t\t\tkeys = [options.keys];\n\t\t} else if (options?.keys && Array.isArray(options?.keys)) {\n\t\t\tkeys = options?.keys;\n\t\t}\n\t\tif (keys) keys.forEach((key: MintKeys) => this._keys.set(key.id, key));\n\t\tif (options?.unit) this._unit = options?.unit;\n\t\tif (options?.keysets) this._keysets = options.keysets;\n\t\tif (options?.denominationTarget) {\n\t\t\tthis._denominationTarget = options.denominationTarget;\n\t\t}\n\n\t\tif (options?.bip39seed) {\n\t\t\tif (options.bip39seed instanceof Uint8Array) {\n\t\t\t\tthis._seed = options.bip39seed;\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tthrow new Error('bip39seed must be a valid UInt8Array');\n\t\t}\n\t}\n\n\tget unit(): string {\n\t\treturn this._unit;\n\t}\n\tget keys(): Map {\n\t\treturn this._keys;\n\t}\n\tget keysetId(): string {\n\t\tif (!this._keysetId) {\n\t\t\tthrow new Error('No keysetId set');\n\t\t}\n\t\treturn this._keysetId;\n\t}\n\tset keysetId(keysetId: string) {\n\t\tthis._keysetId = keysetId;\n\t}\n\tget keysets(): Array {\n\t\treturn this._keysets;\n\t}\n\tget mintInfo(): GetInfoResponse {\n\t\tif (!this._mintInfo) {\n\t\t\tthrow new Error('Mint info not loaded');\n\t\t}\n\t\treturn this._mintInfo;\n\t}\n\n\t/**\n\t * Get information about the mint\n\t * @returns mint info\n\t */\n\tasync getMintInfo(): Promise {\n\t\tthis._mintInfo = await this.mint.getInfo();\n\t\treturn this._mintInfo;\n\t}\n\n\t/**\n\t * Load mint information, keysets and keys. This function can be called if no keysets are passed in the constructor\n\t */\n\tasync loadMint() {\n\t\tawait this.getMintInfo();\n\t\tawait this.getKeySets();\n\t\tawait this.getKeys();\n\t}\n\n\t/**\n\t * Choose a keyset to activate based on the lowest input fee\n\t *\n\t * Note: this function will filter out deprecated base64 keysets\n\t *\n\t * @param keysets keysets to choose from\n\t * @returns active keyset\n\t */\n\tgetActiveKeyset(keysets: Array): MintKeyset {\n\t\tlet activeKeysets = keysets.filter((k: MintKeyset) => k.active);\n\n\t\t// we only consider keyset IDs that start with \"00\"\n\t\tactiveKeysets = activeKeysets.filter((k: MintKeyset) => k.id.startsWith('00'));\n\n\t\tconst activeKeyset = activeKeysets.sort(\n\t\t\t(a: MintKeyset, b: MintKeyset) => (a.input_fee_ppk ?? 0) - (b.input_fee_ppk ?? 0)\n\t\t)[0];\n\t\tif (!activeKeyset) {\n\t\t\tthrow new Error('No active keyset found');\n\t\t}\n\t\treturn activeKeyset;\n\t}\n\n\t/**\n\t * Get keysets from the mint with the unit of the wallet\n\t * @returns keysets with wallet's unit\n\t */\n\tasync getKeySets(): Promise> {\n\t\tconst allKeysets = await this.mint.getKeySets();\n\t\tconst unitKeysets = allKeysets.keysets.filter((k: MintKeyset) => k.unit === this._unit);\n\t\tthis._keysets = unitKeysets;\n\t\treturn this._keysets;\n\t}\n\n\t/**\n\t * Get all active keys from the mint and set the keyset with the lowest fees as the active wallet keyset.\n\t * @returns keyset\n\t */\n\tasync getAllKeys(): Promise> {\n\t\tconst keysets = await this.mint.getKeys();\n\t\tthis._keys = new Map(keysets.keysets.map((k: MintKeys) => [k.id, k]));\n\t\tthis.keysetId = this.getActiveKeyset(this._keysets).id;\n\t\treturn keysets.keysets;\n\t}\n\n\t/**\n\t * Get public keys from the mint. If keys were already fetched, it will return those.\n\t *\n\t * If `keysetId` is set, it will fetch and return that specific keyset.\n\t * Otherwise, we select an active keyset with the unit of the wallet.\n\t *\n\t * @param keysetId optional keysetId to get keys for\n\t * @param forceRefresh? if set to true, it will force refresh the keyset from the mint\n\t * @returns keyset\n\t */\n\tasync getKeys(keysetId?: string, forceRefresh?: boolean): Promise {\n\t\tif (!(this._keysets.length > 0) || forceRefresh) {\n\t\t\tawait this.getKeySets();\n\t\t}\n\t\t// no keyset id is chosen, let's choose one\n\t\tif (!keysetId) {\n\t\t\tconst localKeyset = this.getActiveKeyset(this._keysets);\n\t\t\tkeysetId = localKeyset.id;\n\t\t}\n\t\t// make sure we have keyset for this id\n\t\tif (!this._keysets.find((k: MintKeyset) => k.id === keysetId)) {\n\t\t\tawait this.getKeySets();\n\t\t\tif (!this._keysets.find((k: MintKeyset) => k.id === keysetId)) {\n\t\t\t\tthrow new Error(`could not initialize keys. No keyset with id '${keysetId}' found`);\n\t\t\t}\n\t\t}\n\n\t\t// make sure we have keys for this id\n\t\tif (!this._keys.get(keysetId)) {\n\t\t\tconst keys = await this.mint.getKeys(keysetId);\n\t\t\tthis._keys.set(keysetId, keys.keysets[0]);\n\t\t}\n\n\t\t// set and return\n\t\tthis.keysetId = keysetId;\n\t\treturn this._keys.get(keysetId) as MintKeys;\n\t}\n\n\t/**\n\t * Receive an encoded or raw Cashu token (only supports single tokens. It will only process the first token in the token array)\n\t * @param {(string|Token)} token - Cashu token, either as string or decoded\n\t * @param options.keysetId? override the keysetId derived from the current mintKeys with a custom one. This should be a keyset that was fetched from the `/keysets` endpoint\n\t * @param options.outputAmounts? optionally specify the output's amounts to keep and to send.\n\t * @param options.proofsWeHave? optionally provide all currently stored proofs of this mint. Cashu-ts will use them to derive the optimal output amounts\n\t * @param options.counter? optionally set counter to derive secret deterministically. CashuWallet class must be initialized with seed phrase to take effect\n\t * @param options.pubkey? optionally locks ecash to pubkey. Will not be deterministic, even if counter is set!\n\t * @param options.privkey? will create a signature on the @param token secrets if set\n\t * @returns New token with newly created proofs, token entries that had errors\n\t */\n\tasync receive(\n\t\ttoken: string | Token,\n\t\toptions?: {\n\t\t\tkeysetId?: string;\n\t\t\toutputAmounts?: OutputAmounts;\n\t\t\tproofsWeHave?: Array;\n\t\t\tcounter?: number;\n\t\t\tpubkey?: string;\n\t\t\tprivkey?: string;\n\t\t}\n\t): Promise> {\n\t\tif (typeof token === 'string') {\n\t\t\ttoken = getDecodedToken(token);\n\t\t}\n\t\tconst keys = await this.getKeys(options?.keysetId);\n\t\tconst amount = sumProofs(token.proofs) - this.getFeesForProofs(token.proofs);\n\t\tconst { payload, blindingData } = this.createSwapPayload(\n\t\t\tamount,\n\t\t\ttoken.proofs,\n\t\t\tkeys,\n\t\t\toptions?.outputAmounts,\n\t\t\toptions?.counter,\n\t\t\toptions?.pubkey,\n\t\t\toptions?.privkey\n\t\t);\n\t\tconst { signatures } = await this.mint.swap(payload);\n\t\tconst freshProofs = this.constructProofs(\n\t\t\tsignatures,\n\t\t\tblindingData.blindingFactors,\n\t\t\tblindingData.secrets,\n\t\t\tkeys\n\t\t);\n\t\treturn freshProofs;\n\t}\n\n\t/**\n\t * Send proofs of a given amount, by providing at least the required amount of proofs\n\t * @param amount amount to send\n\t * @param proofs array of proofs (accumulated amount of proofs must be >= than amount)\n\t * @param options.outputAmounts? optionally specify the output's amounts to keep and send.\n\t * @param options.counter? optionally set counter to derive secret deterministically. CashuWallet class must be initialized with seed phrase to take effect\n\t * @param options.proofsWeHave? optionally provide all currently stored proofs of this mint. Cashu-ts will use them to derive the optimal output amounts\n\t * @param options.pubkey? optionally locks ecash to pubkey. Will not be deterministic, even if counter is set!\n\t * @param options.privkey? will create a signature on the output secrets if set\n\t * @param options.keysetId? override the keysetId derived from the current mintKeys with a custom one. This should be a keyset that was fetched from the `/keysets` endpoint\n\t * @param options.offline? optionally send proofs offline.\n\t * @param options.includeFees? optionally include fees in the response.\n\t * @returns {SendResponse}\n\t */\n\tasync send(\n\t\tamount: number,\n\t\tproofs: Array,\n\t\toptions?: {\n\t\t\toutputAmounts?: OutputAmounts;\n\t\t\tproofsWeHave?: Array;\n\t\t\tcounter?: number;\n\t\t\tpubkey?: string;\n\t\t\tprivkey?: string;\n\t\t\tkeysetId?: string;\n\t\t\toffline?: boolean;\n\t\t\tincludeFees?: boolean;\n\t\t}\n\t): Promise {\n\t\tif (sumProofs(proofs) < amount) {\n\t\t\tthrow new Error('Not enough funds available to send');\n\t\t}\n\t\tconst { keep: keepProofsOffline, send: sendProofOffline } = this.selectProofsToSend(\n\t\t\tproofs,\n\t\t\tamount,\n\t\t\toptions?.includeFees\n\t\t);\n\t\tconst expectedFee = options?.includeFees ? this.getFeesForProofs(sendProofOffline) : 0;\n\t\tif (\n\t\t\t!options?.offline &&\n\t\t\t(sumProofs(sendProofOffline) != amount + expectedFee || // if the exact amount cannot be selected\n\t\t\t\toptions?.outputAmounts ||\n\t\t\t\toptions?.pubkey ||\n\t\t\t\toptions?.privkey ||\n\t\t\t\toptions?.keysetId) // these options require a swap\n\t\t) {\n\t\t\t// we need to swap\n\t\t\t// input selection, needs fees because of the swap\n\t\t\tconst { keep: keepProofsSelect, send: sendProofs } = this.selectProofsToSend(\n\t\t\t\tproofs,\n\t\t\t\tamount,\n\t\t\t\ttrue\n\t\t\t);\n\t\t\toptions?.proofsWeHave?.push(...keepProofsSelect);\n\n\t\t\tconst { keep, send } = await this.swap(amount, sendProofs, options);\n\t\t\tconst keepProofs = keepProofsSelect.concat(keep);\n\t\t\treturn { keep: keepProofs, send };\n\t\t}\n\n\t\tif (sumProofs(sendProofOffline) < amount + expectedFee) {\n\t\t\tthrow new Error('Not enough funds available to send');\n\t\t}\n\n\t\treturn { keep: keepProofsOffline, send: sendProofOffline };\n\t}\n\n\tselectProofsToSend(\n\t\tproofs: Array,\n\t\tamountToSend: number,\n\t\tincludeFees?: boolean\n\t): SendResponse {\n\t\tconst sortedProofs = proofs.sort((a: Proof, b: Proof) => a.amount - b.amount);\n\t\tconst smallerProofs = sortedProofs\n\t\t\t.filter((p: Proof) => p.amount <= amountToSend)\n\t\t\t.sort((a: Proof, b: Proof) => b.amount - a.amount);\n\t\tconst biggerProofs = sortedProofs\n\t\t\t.filter((p: Proof) => p.amount > amountToSend)\n\t\t\t.sort((a: Proof, b: Proof) => a.amount - b.amount);\n\t\tconst nextBigger = biggerProofs[0];\n\t\tif (!smallerProofs.length && nextBigger) {\n\t\t\treturn {\n\t\t\t\tkeep: proofs.filter((p: Proof) => p.secret !== nextBigger.secret),\n\t\t\t\tsend: [nextBigger]\n\t\t\t};\n\t\t}\n\n\t\tif (!smallerProofs.length && !nextBigger) {\n\t\t\treturn { keep: proofs, send: [] };\n\t\t}\n\n\t\tlet remainder = amountToSend;\n\t\tlet selectedProofs = [smallerProofs[0]];\n\t\tconst returnedProofs = [];\n\t\tconst feePPK = includeFees ? this.getFeesForProofs(selectedProofs) : 0;\n\t\tremainder -= selectedProofs[0].amount - feePPK / 1000;\n\t\tif (remainder > 0) {\n\t\t\tconst { keep, send } = this.selectProofsToSend(\n\t\t\t\tsmallerProofs.slice(1),\n\t\t\t\tremainder,\n\t\t\t\tincludeFees\n\t\t\t);\n\t\t\tselectedProofs.push(...send);\n\t\t\treturnedProofs.push(...keep);\n\t\t}\n\n\t\tconst selectedFeePPK = includeFees ? this.getFeesForProofs(selectedProofs) : 0;\n\t\tif (sumProofs(selectedProofs) < amountToSend + selectedFeePPK && nextBigger) {\n\t\t\tselectedProofs = [nextBigger];\n\t\t}\n\t\treturn {\n\t\t\tkeep: proofs.filter((p: Proof) => !selectedProofs.includes(p)),\n\t\t\tsend: selectedProofs\n\t\t};\n\t}\n\n\t/**\n\t * calculates the fees based on inputs (proofs)\n\t * @param proofs input proofs to calculate fees for\n\t * @returns fee amount\n\t */\n\tgetFeesForProofs(proofs: Array): number {\n\t\tif (!this._keysets.length) {\n\t\t\tthrow new Error('Could not calculate fees. No keysets found');\n\t\t}\n\t\tconst keysetIds = new Set(proofs.map((p: Proof) => p.id));\n\t\tkeysetIds.forEach((id: string) => {\n\t\t\tif (!this._keysets.find((k: MintKeyset) => k.id === id)) {\n\t\t\t\tthrow new Error(`Could not calculate fees. No keyset found with id: ${id}`);\n\t\t\t}\n\t\t});\n\n\t\tconst fees = Math.floor(\n\t\t\tMath.max(\n\t\t\t\t(proofs.reduce(\n\t\t\t\t\t(total: number, curr: Proof) =>\n\t\t\t\t\t\ttotal + (this._keysets.find((k: MintKeyset) => k.id === curr.id)?.input_fee_ppk || 0),\n\t\t\t\t\t0\n\t\t\t\t) +\n\t\t\t\t\t999) /\n\t\t\t\t\t1000,\n\t\t\t\t0\n\t\t\t)\n\t\t);\n\t\treturn fees;\n\t}\n\n\t/**\n\t * calculates the fees based on inputs for a given keyset\n\t * @param nInputs number of inputs\n\t * @param keysetId keysetId used to lookup `input_fee_ppk`\n\t * @returns fee amount\n\t */\n\tgetFeesForKeyset(nInputs: number, keysetId: string): number {\n\t\tconst fees = Math.floor(\n\t\t\tMath.max(\n\t\t\t\t(nInputs * (this._keysets.find((k: MintKeyset) => k.id === keysetId)?.input_fee_ppk || 0) +\n\t\t\t\t\t999) /\n\t\t\t\t\t1000,\n\t\t\t\t0\n\t\t\t)\n\t\t);\n\t\treturn fees;\n\t}\n\n\t/**\n\t * Splits and creates sendable tokens\n\t * if no amount is specified, the amount is implied by the cumulative amount of all proofs\n\t * if both amount and preference are set, but the preference cannot fulfill the amount, then we use the default split\n\t * @param amount amount to send while performing the optimal split (least proofs possible). can be set to undefined if preference is set\n\t * @param proofs proofs matching that amount\n\t * @param options.outputAmounts? optionally specify the output's amounts to keep and to send.\n\t * @param options.counter? optionally set counter to derive secret deterministically. CashuWallet class must be initialized with seed phrase to take effect\n\t * @param options.keysetId? override the keysetId derived from the current mintKeys with a custom one. This should be a keyset that was fetched from the `/keysets` endpoint\n\t * @param options.includeFees? include estimated fees for the receiver to receive the proofs\n\t * @param options.proofsWeHave? optionally provide all currently stored proofs of this mint. Cashu-ts will use them to derive the optimal output amounts\n\t * @param options.pubkey? optionally locks ecash to pubkey. Will not be deterministic, even if counter is set!\n\t * @param options.privkey? will create a signature on the @param proofs secrets if set\n\t * @returns promise of the change- and send-proofs\n\t */\n\tasync swap(\n\t\tamount: number,\n\t\tproofs: Array,\n\t\toptions?: {\n\t\t\toutputAmounts?: OutputAmounts;\n\t\t\tproofsWeHave?: Array;\n\t\t\tcounter?: number;\n\t\t\tpubkey?: string;\n\t\t\tprivkey?: string;\n\t\t\tkeysetId?: string;\n\t\t\tincludeFees?: boolean;\n\t\t}\n\t): Promise {\n\t\tif (!options) options = {};\n\t\tconst keyset = await this.getKeys(options.keysetId);\n\t\tconst proofsToSend = proofs;\n\t\tlet amountToSend = amount;\n\t\tconst amountAvailable = sumProofs(proofs);\n\t\tlet amountToKeep = amountAvailable - amountToSend - this.getFeesForProofs(proofsToSend);\n\t\t// send output selection\n\t\tlet sendAmounts = options?.outputAmounts?.sendAmounts || splitAmount(amountToSend, keyset.keys);\n\n\t\t// include the fees to spend the the outputs of the swap\n\t\tif (options?.includeFees) {\n\t\t\tlet outputFee = this.getFeesForKeyset(sendAmounts.length, keyset.id);\n\t\t\tlet sendAmountsFee = splitAmount(outputFee, keyset.keys);\n\t\t\twhile (\n\t\t\t\tthis.getFeesForKeyset(sendAmounts.concat(sendAmountsFee).length, keyset.id) > outputFee\n\t\t\t) {\n\t\t\t\toutputFee++;\n\t\t\t\tsendAmountsFee = splitAmount(outputFee, keyset.keys);\n\t\t\t}\n\t\t\tsendAmounts = sendAmounts.concat(sendAmountsFee);\n\t\t\tamountToSend += outputFee;\n\t\t\tamountToKeep -= outputFee;\n\t\t}\n\n\t\t// keep output selection\n\t\tlet keepAmounts;\n\t\tif (options && !options.outputAmounts?.keepAmounts && options.proofsWeHave) {\n\t\t\tkeepAmounts = getKeepAmounts(\n\t\t\t\toptions.proofsWeHave,\n\t\t\t\tamountToKeep,\n\t\t\t\tkeyset.keys,\n\t\t\t\tthis._denominationTarget\n\t\t\t);\n\t\t} else if (options.outputAmounts) {\n\t\t\tif (\n\t\t\t\toptions.outputAmounts.keepAmounts?.reduce((a: number, b: number) => a + b, 0) !=\n\t\t\t\tamountToKeep\n\t\t\t) {\n\t\t\t\tthrow new Error('Keep amounts do not match amount to keep');\n\t\t\t}\n\t\t\tkeepAmounts = options.outputAmounts.keepAmounts;\n\t\t}\n\n\t\tif (amountToSend + this.getFeesForProofs(proofsToSend) > amountAvailable) {\n\t\t\tconsole.error(\n\t\t\t\t`Not enough funds available (${amountAvailable}) for swap amountToSend: ${amountToSend} + fee: ${this.getFeesForProofs(\n\t\t\t\t\tproofsToSend\n\t\t\t\t)} | length: ${proofsToSend.length}`\n\t\t\t);\n\t\t\tthrow new Error(`Not enough funds available for swap`);\n\t\t}\n\n\t\tif (amountToSend + this.getFeesForProofs(proofsToSend) + amountToKeep != amountAvailable) {\n\t\t\tthrow new Error('Amounts do not match for swap');\n\t\t}\n\n\t\toptions.outputAmounts = {\n\t\t\tkeepAmounts: keepAmounts,\n\t\t\tsendAmounts: sendAmounts\n\t\t};\n\t\tconst { payload, blindingData } = this.createSwapPayload(\n\t\t\tamountToSend,\n\t\t\tproofsToSend,\n\t\t\tkeyset,\n\t\t\toptions?.outputAmounts,\n\t\t\toptions?.counter,\n\t\t\toptions?.pubkey,\n\t\t\toptions?.privkey\n\t\t);\n\t\tconst { signatures } = await this.mint.swap(payload);\n\t\tconst swapProofs = this.constructProofs(\n\t\t\tsignatures,\n\t\t\tblindingData.blindingFactors,\n\t\t\tblindingData.secrets,\n\t\t\tkeyset\n\t\t);\n\t\tconst splitProofsToKeep: Array = [];\n\t\tconst splitProofsToSend: Array = [];\n\t\tlet amountToKeepCounter = 0;\n\t\tswapProofs.forEach((proof: Proof) => {\n\t\t\tif (amountToKeepCounter < amountToKeep) {\n\t\t\t\tamountToKeepCounter += proof.amount;\n\t\t\t\tsplitProofsToKeep.push(proof);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tsplitProofsToSend.push(proof);\n\t\t});\n\t\treturn {\n\t\t\tkeep: splitProofsToKeep,\n\t\t\tsend: splitProofsToSend\n\t\t};\n\t}\n\n\t/**\n\t * Regenerates\n\t * @param start set starting point for count (first cycle for each keyset should usually be 0)\n\t * @param count set number of blinded messages that should be generated\n\t * @param options.keysetId set a custom keysetId to restore from. keysetIds can be loaded with `CashuMint.getKeySets()`\n\t * @returns proofs\n\t */\n\tasync restore(\n\t\tstart: number,\n\t\tcount: number,\n\t\toptions?: {\n\t\t\tkeysetId?: string;\n\t\t}\n\t): Promise<{ proofs: Array }> {\n\t\tconst keys = await this.getKeys(options?.keysetId);\n\t\tif (!this._seed) {\n\t\t\tthrow new Error('CashuWallet must be initialized with a seed to use restore');\n\t\t}\n\t\t// create blank amounts for unknown restore amounts\n\t\tconst amounts = Array(count).fill(0);\n\t\tconst { blindedMessages, blindingFactors, secrets } = this.createBlindedMessages(\n\t\t\tamounts,\n\t\t\tkeys.id,\n\t\t\tstart\n\t\t);\n\n\t\tconst { outputs, promises } = await this.mint.restore({ outputs: blindedMessages });\n\n\t\t// Collect and map the secrets and blinding factors with the blinded messages that were returned from the mint\n\t\tconst validBlindingFactors = blindingFactors.filter((_: bigint, i: number) =>\n\t\t\toutputs.map((o: SerializedBlindedMessage) => o.B_).includes(blindedMessages[i].B_)\n\t\t);\n\t\tconst validSecrets = secrets.filter((_: Uint8Array, i: number) =>\n\t\t\toutputs.map((o: SerializedBlindedMessage) => o.B_).includes(blindedMessages[i].B_)\n\t\t);\n\n\t\treturn {\n\t\t\tproofs: this.constructProofs(promises, validBlindingFactors, validSecrets, keys)\n\t\t};\n\t}\n\n\t/**\n\t * Requests a mint quote form the mint. Response returns a Lightning payment request for the requested given amount and unit.\n\t * @param amount Amount requesting for mint.\n\t * @param description optional description for the mint quote\n\t * @returns the mint will return a mint quote with a Lightning invoice for minting tokens of the specified amount and unit\n\t */\n\tasync createMintQuote(amount: number, description?: string) {\n\t\tconst mintQuotePayload: MintQuotePayload = {\n\t\t\tunit: this._unit,\n\t\t\tamount: amount,\n\t\t\tdescription: description\n\t\t};\n\t\treturn await this.mint.createMintQuote(mintQuotePayload);\n\t}\n\n\t/**\n\t * Gets an existing mint quote from the mint.\n\t * @param quote Quote ID\n\t * @returns the mint will create and return a Lightning invoice for the specified amount\n\t */\n\tasync checkMintQuote(quote: string) {\n\t\treturn await this.mint.checkMintQuote(quote);\n\t}\n\n\t/**\n\t * Mint proofs for a given mint quote\n\t * @param amount amount to request\n\t * @param quote ID of mint quote\n\t * @param options.keysetId? optionally set keysetId for blank outputs for returned change.\n\t * @param options.preference? Deprecated. Use `outputAmounts` instead. Optional preference for splitting proofs into specific amounts.\n\t * @param options.outputAmounts? optionally specify the output's amounts to keep and to send.\n\t * @param options.counter? optionally set counter to derive secret deterministically. CashuWallet class must be initialized with seed phrase to take effect\n\t * @param options.pubkey? optionally locks ecash to pubkey. Will not be deterministic, even if counter is set!\n\t * @returns proofs\n\t */\n\tasync mintProofs(\n\t\tamount: number,\n\t\tquote: string,\n\t\toptions?: {\n\t\t\tkeysetId?: string;\n\t\t\toutputAmounts?: OutputAmounts;\n\t\t\tproofsWeHave?: Array;\n\t\t\tcounter?: number;\n\t\t\tpubkey?: string;\n\t\t}\n\t): Promise<{ proofs: Array }> {\n\t\tconst keyset = await this.getKeys(options?.keysetId);\n\t\tif (!options?.outputAmounts && options?.proofsWeHave) {\n\t\t\toptions.outputAmounts = {\n\t\t\t\tkeepAmounts: getKeepAmounts(\n\t\t\t\t\toptions.proofsWeHave,\n\t\t\t\t\tamount,\n\t\t\t\t\tkeyset.keys,\n\t\t\t\t\tthis._denominationTarget\n\t\t\t\t),\n\t\t\t\tsendAmounts: []\n\t\t\t};\n\t\t}\n\n\t\tconst { blindedMessages, secrets, blindingFactors } = this.createRandomBlindedMessages(\n\t\t\tamount,\n\t\t\tkeyset,\n\t\t\toptions?.outputAmounts?.keepAmounts,\n\t\t\toptions?.counter,\n\t\t\toptions?.pubkey\n\t\t);\n\t\tconst mintPayload: MintPayload = {\n\t\t\toutputs: blindedMessages,\n\t\t\tquote: quote\n\t\t};\n\t\tconst { signatures } = await this.mint.mint(mintPayload);\n\t\treturn {\n\t\t\tproofs: this.constructProofs(signatures, blindingFactors, secrets, keyset)\n\t\t};\n\t}\n\n\t/**\n\t * Requests a melt quote from the mint. Response returns amount and fees for a given unit in order to pay a Lightning invoice.\n\t * @param invoice LN invoice that needs to get a fee estimate\n\t * @returns the mint will create and return a melt quote for the invoice with an amount and fee reserve\n\t */\n\tasync createMeltQuote(invoice: string): Promise {\n\t\tconst meltQuotePayload: MeltQuotePayload = {\n\t\t\tunit: this._unit,\n\t\t\trequest: invoice\n\t\t};\n\t\tconst meltQuote = await this.mint.createMeltQuote(meltQuotePayload);\n\t\treturn meltQuote;\n\t}\n\n\t/**\n\t * Return an existing melt quote from the mint.\n\t * @param quote ID of the melt quote\n\t * @returns the mint will return an existing melt quote\n\t */\n\tasync checkMeltQuote(quote: string): Promise {\n\t\tconst meltQuote = await this.mint.checkMeltQuote(quote);\n\t\treturn meltQuote;\n\t}\n\n\t/**\n\t * Melt proofs for a melt quote. proofsToSend must be at least amount+fee_reserve form the melt quote. This function does not perform coin selection!.\n\t * Returns melt quote and change proofs\n\t * @param meltQuote ID of the melt quote\n\t * @param proofsToSend proofs to melt\n\t * @param options.keysetId? optionally set keysetId for blank outputs for returned change.\n\t * @param options.counter? optionally set counter to derive secret deterministically. CashuWallet class must be initialized with seed phrase to take effect\n\t * @param options.privkey? optionally set a private key to unlock P2PK locked secrets\n\t * @returns\n\t */\n\tasync meltProofs(\n\t\tmeltQuote: MeltQuoteResponse,\n\t\tproofsToSend: Array,\n\t\toptions?: {\n\t\t\tkeysetId?: string;\n\t\t\tcounter?: number;\n\t\t\tprivkey?: string;\n\t\t}\n\t): Promise {\n\t\tconst keys = await this.getKeys(options?.keysetId);\n\t\tconst { blindedMessages, secrets, blindingFactors } = this.createBlankOutputs(\n\t\t\tsumProofs(proofsToSend) - meltQuote.amount,\n\t\t\tkeys.id,\n\t\t\toptions?.counter\n\t\t);\n\t\tif (options?.privkey != undefined) {\n\t\t\tproofsToSend = getSignedProofs(\n\t\t\t\tproofsToSend.map((p: Proof) => {\n\t\t\t\t\treturn {\n\t\t\t\t\t\tamount: p.amount,\n\t\t\t\t\t\tC: pointFromHex(p.C),\n\t\t\t\t\t\tid: p.id,\n\t\t\t\t\t\tsecret: new TextEncoder().encode(p.secret)\n\t\t\t\t\t};\n\t\t\t\t}),\n\t\t\t\toptions.privkey\n\t\t\t).map((p: NUT11Proof) => serializeProof(p));\n\t\t}\n\t\tconst meltPayload: MeltPayload = {\n\t\t\tquote: meltQuote.quote,\n\t\t\tinputs: proofsToSend,\n\t\t\toutputs: [...blindedMessages]\n\t\t};\n\t\tconst meltResponse = await this.mint.melt(meltPayload);\n\t\tlet change: Array = [];\n\t\tif (meltResponse.change) {\n\t\t\tchange = this.constructProofs(meltResponse.change, blindingFactors, secrets, keys);\n\t\t}\n\t\treturn {\n\t\t\tquote: meltResponse,\n\t\t\tchange: change\n\t\t};\n\t}\n\n\t/**\n\t * Creates a split payload\n\t * @param amount amount to send\n\t * @param proofsToSend proofs to split*\n\t * @param outputAmounts? optionally specify the output's amounts to keep and to send.\n\t * @param counter? optionally set counter to derive secret deterministically. CashuWallet class must be initialized with seed phrase to take effect\n\t * @param pubkey? optionally locks ecash to pubkey. Will not be deterministic, even if counter is set!\n\t * @param privkey? will create a signature on the @param proofsToSend secrets if set\n\t * @returns\n\t */\n\tprivate createSwapPayload(\n\t\tamount: number,\n\t\tproofsToSend: Array,\n\t\tkeyset: MintKeys,\n\t\toutputAmounts?: OutputAmounts,\n\t\tcounter?: number,\n\t\tpubkey?: string,\n\t\tprivkey?: string\n\t): {\n\t\tpayload: SwapPayload;\n\t\tblindingData: BlindingData;\n\t} {\n\t\tconst totalAmount = proofsToSend.reduce((total: number, curr: Proof) => total + curr.amount, 0);\n\t\tif (outputAmounts && outputAmounts.sendAmounts && !outputAmounts.keepAmounts) {\n\t\t\toutputAmounts.keepAmounts = splitAmount(\n\t\t\t\ttotalAmount - amount - this.getFeesForProofs(proofsToSend),\n\t\t\t\tkeyset.keys\n\t\t\t);\n\t\t}\n\t\tconst keepBlindedMessages = this.createRandomBlindedMessages(\n\t\t\ttotalAmount - amount - this.getFeesForProofs(proofsToSend),\n\t\t\tkeyset,\n\t\t\toutputAmounts?.keepAmounts,\n\t\t\tcounter\n\t\t);\n\t\tif (this._seed && counter) {\n\t\t\tcounter = counter + keepBlindedMessages.secrets.length;\n\t\t}\n\t\tconst sendBlindedMessages = this.createRandomBlindedMessages(\n\t\t\tamount,\n\t\t\tkeyset,\n\t\t\toutputAmounts?.sendAmounts,\n\t\t\tcounter,\n\t\t\tpubkey\n\t\t);\n\t\tif (privkey) {\n\t\t\tproofsToSend = getSignedProofs(\n\t\t\t\tproofsToSend.map((p: Proof) => {\n\t\t\t\t\treturn {\n\t\t\t\t\t\tamount: p.amount,\n\t\t\t\t\t\tC: pointFromHex(p.C),\n\t\t\t\t\t\tid: p.id,\n\t\t\t\t\t\tsecret: new TextEncoder().encode(p.secret)\n\t\t\t\t\t};\n\t\t\t\t}),\n\t\t\t\tprivkey\n\t\t\t).map((p: NUT11Proof) => serializeProof(p));\n\t\t}\n\n\t\t// join keepBlindedMessages and sendBlindedMessages\n\t\tconst blindingData: BlindingData = {\n\t\t\tblindedMessages: [\n\t\t\t\t...keepBlindedMessages.blindedMessages,\n\t\t\t\t...sendBlindedMessages.blindedMessages\n\t\t\t],\n\t\t\tsecrets: [...keepBlindedMessages.secrets, ...sendBlindedMessages.secrets],\n\t\t\tblindingFactors: [\n\t\t\t\t...keepBlindedMessages.blindingFactors,\n\t\t\t\t...sendBlindedMessages.blindingFactors\n\t\t\t]\n\t\t};\n\n\t\tconst payload = {\n\t\t\tinputs: proofsToSend,\n\t\t\toutputs: [...blindingData.blindedMessages]\n\t\t};\n\t\treturn { payload, blindingData };\n\t}\n\n\t/**\n\t * Get an array of the states of proofs from the mint (as an array of CheckStateEnum's)\n\t * @param proofs (only the `secret` field is required)\n\t * @returns\n\t */\n\tasync checkProofsStates(proofs: Array): Promise> {\n\t\tconst enc = new TextEncoder();\n\t\tconst Ys = proofs.map((p: Proof) => hashToCurve(enc.encode(p.secret)).toHex(true));\n\t\t// TODO: Replace this with a value from the info endpoint of the mint eventually\n\t\tconst BATCH_SIZE = 100;\n\t\tconst states: Array = [];\n\t\tfor (let i = 0; i < Ys.length; i += BATCH_SIZE) {\n\t\t\tconst YsSlice = Ys.slice(i, i + BATCH_SIZE);\n\t\t\tconst { states: batchStates } = await this.mint.check({\n\t\t\t\tYs: YsSlice\n\t\t\t});\n\t\t\tconst stateMap: { [y: string]: ProofState } = {};\n\t\t\tbatchStates.forEach((s) => {\n\t\t\t\tstateMap[s.Y] = s;\n\t\t\t});\n\t\t\tfor (let j = 0; j < YsSlice.length; j++) {\n\t\t\t\tconst state = stateMap[YsSlice[j]];\n\t\t\t\tif (!state) {\n\t\t\t\t\tthrow new Error('Could not find state for proof with Y: ' + YsSlice[j]);\n\t\t\t\t}\n\t\t\t\tstates.push(state);\n\t\t\t}\n\t\t}\n\t\treturn states;\n\t}\n\n\t/**\n\t * Creates blinded messages for a given amount\n\t * @param amount amount to create blinded messages for\n\t * @param split optional preference for splitting proofs into specific amounts. overrides amount param\n\t * @param keyksetId? override the keysetId derived from the current mintKeys with a custom one. This should be a keyset that was fetched from the `/keysets` endpoint\n\t * @param counter? optionally set counter to derive secret deterministically. CashuWallet class must be initialized with seed phrase to take effect\n\t * @param pubkey? optionally locks ecash to pubkey. Will not be deterministic, even if counter is set!\n\t * @returns blinded messages, secrets, rs, and amounts\n\t */\n\tprivate createRandomBlindedMessages(\n\t\tamount: number,\n\t\tkeyset: MintKeys,\n\t\tsplit?: Array,\n\t\tcounter?: number,\n\t\tpubkey?: string\n\t): BlindingData & { amounts: Array } {\n\t\tconst amounts = splitAmount(amount, keyset.keys, split);\n\t\treturn this.createBlindedMessages(amounts, keyset.id, counter, pubkey);\n\t}\n\n\t/**\n\t * Creates blinded messages for a according to @param amounts\n\t * @param amount array of amounts to create blinded messages for\n\t * @param counter? optionally set counter to derive secret deterministically. CashuWallet class must be initialized with seed phrase to take effect\n\t * @param keyksetId? override the keysetId derived from the current mintKeys with a custom one. This should be a keyset that was fetched from the `/keysets` endpoint\n\t * @param pubkey? optionally locks ecash to pubkey. Will not be deterministic, even if counter is set!\n\t * @returns blinded messages, secrets, rs, and amounts\n\t */\n\tprivate createBlindedMessages(\n\t\tamounts: Array,\n\t\tkeysetId: string,\n\t\tcounter?: number,\n\t\tpubkey?: string\n\t): BlindingData & { amounts: Array } {\n\t\t// if we atempt to create deterministic messages without a _seed, abort.\n\t\tif (counter != undefined && !this._seed) {\n\t\t\tthrow new Error(\n\t\t\t\t'Cannot create deterministic messages without seed. Instantiate CashuWallet with a bip39seed, or omit counter param.'\n\t\t\t);\n\t\t}\n\t\tconst blindedMessages: Array = [];\n\t\tconst secrets: Array = [];\n\t\tconst blindingFactors: Array = [];\n\t\tfor (let i = 0; i < amounts.length; i++) {\n\t\t\tlet deterministicR = undefined;\n\t\t\tlet secretBytes = undefined;\n\t\t\tif (pubkey) {\n\t\t\t\tsecretBytes = createP2PKsecret(pubkey);\n\t\t\t} else if (this._seed && counter != undefined) {\n\t\t\t\tsecretBytes = deriveSecret(this._seed, keysetId, counter + i);\n\t\t\t\tdeterministicR = bytesToNumber(deriveBlindingFactor(this._seed, keysetId, counter + i));\n\t\t\t} else {\n\t\t\t\tsecretBytes = randomBytes(32);\n\t\t\t}\n\t\t\tif (!pubkey) {\n\t\t\t\tconst secretHex = bytesToHex(secretBytes);\n\t\t\t\tsecretBytes = new TextEncoder().encode(secretHex);\n\t\t\t}\n\t\t\tsecrets.push(secretBytes);\n\t\t\tconst { B_, r } = blindMessage(secretBytes, deterministicR);\n\t\t\tblindingFactors.push(r);\n\t\t\tconst blindedMessage = new BlindedMessage(amounts[i], B_, keysetId);\n\t\t\tblindedMessages.push(blindedMessage.getSerializedBlindedMessage());\n\t\t}\n\t\treturn { blindedMessages, secrets, blindingFactors, amounts };\n\t}\n\n\t/**\n\t * Creates NUT-08 blank outputs (fee returns) for a given fee reserve\n\t * See: https://github.com/cashubtc/nuts/blob/main/08.md\n\t * @param amount amount to cover with blank outputs\n\t * @param keysetId mint keysetId\n\t * @param counter? optionally set counter to derive secret deterministically. CashuWallet class must be initialized with seed phrase to take effect\n\t * @returns blinded messages, secrets, and rs\n\t */\n\tprivate createBlankOutputs(amount: number, keysetId: string, counter?: number): BlindingData {\n\t\tlet count = Math.ceil(Math.log2(amount)) || 1;\n\t\t//Prevent count from being -Infinity\n\t\tif (count < 0) {\n\t\t\tcount = 0;\n\t\t}\n\t\tconst amounts = count ? Array(count).fill(1) : [];\n\t\tconst { blindedMessages, blindingFactors, secrets } = this.createBlindedMessages(\n\t\t\tamounts,\n\t\t\tkeysetId,\n\t\t\tcounter\n\t\t);\n\t\treturn { blindedMessages, secrets, blindingFactors };\n\t}\n\n\t/**\n\t * construct proofs from @params promises, @params rs, @params secrets, and @params keyset\n\t * @param promises array of serialized blinded signatures\n\t * @param rs arrays of binding factors\n\t * @param secrets array of secrets\n\t * @param keyset mint keyset\n\t * @returns array of serialized proofs\n\t */\n\tprivate constructProofs(\n\t\tpromises: Array,\n\t\trs: Array,\n\t\tsecrets: Array,\n\t\tkeyset: MintKeys\n\t): Array {\n\t\treturn promises\n\t\t\t.map((p: SerializedBlindedSignature, i: number) => {\n\t\t\t\tconst blindSignature = { id: p.id, amount: p.amount, C_: pointFromHex(p.C_) };\n\t\t\t\tconst r = rs[i];\n\t\t\t\tconst secret = secrets[i];\n\t\t\t\tconst A = pointFromHex(keyset.keys[p.amount]);\n\t\t\t\treturn constructProofFromPromise(blindSignature, r, secret, A);\n\t\t\t})\n\t\t\t.map((p: NUT11Proof) => serializeProof(p) as Proof);\n\t}\n}\n\nexport { CashuWallet };\n", "import { getDecodedToken } from \"@cashu/cashu-ts\";\nimport { Tokens } from \"../helpers/regexp.js\";\nimport { findAndReplace } from \"../nast/find-and-replace.js\";\n/** Parse cashu tokens from an ATS tree */\nexport function cashuTokens() {\n return (tree) => {\n findAndReplace(tree, [\n [\n Tokens.cashu,\n (_, $1) => {\n try {\n const token = getDecodedToken($1);\n return {\n type: \"cashu\",\n token,\n raw: $1,\n };\n }\n catch (error) { }\n return false;\n },\n ],\n ]);\n };\n}\n", "import { getEmojiTag } from \"applesauce-core/helpers/emoji\";\nimport { Tokens } from \"../helpers/regexp.js\";\nimport { findAndReplace } from \"../nast/find-and-replace.js\";\n/** Finds and creates emoji nodes in the tree */\nexport function emojis() {\n return (tree) => {\n const event = tree.event;\n if (!event)\n return;\n findAndReplace(tree, [\n [\n Tokens.emoji,\n (full, $1) => {\n try {\n const tag = getEmojiTag(event, $1);\n if (!tag)\n return false;\n return {\n type: \"emoji\",\n tag,\n raw: full,\n code: tag[1].toLowerCase(),\n url: tag[2],\n };\n }\n catch (error) { }\n return false;\n },\n ],\n ]);\n };\n}\n", "/** Creates a {@link Root} ATS node for a text note */\nexport function createEventContentTree(event, content) {\n return {\n type: \"root\",\n event: typeof event !== \"string\" ? event : undefined,\n children: [\n {\n type: \"text\",\n value: content || (typeof event === \"string\" ? event : event.content),\n },\n ],\n };\n}\n/** @deprecated use createEventContentTree instead */\nexport const createTextNoteATS = createEventContentTree;\n", "import { getHashtagTag } from \"applesauce-core/helpers/hashtag\";\nimport { Tokens } from \"../helpers/regexp.js\";\nimport { findAndReplace } from \"../nast/find-and-replace.js\";\n/** Find and create hashtag notes in provided tree */\nexport function hashtags() {\n return (tree) => {\n const event = tree.event;\n findAndReplace(tree, [\n [\n Tokens.hashtag,\n (_, $1) => {\n try {\n const tag = event && getHashtagTag(event, $1);\n // Skip if the match if no tag was found in the event\n if (!tag && event)\n return false;\n return {\n type: \"hashtag\",\n tag,\n name: $1,\n hashtag: tag?.[1].toLowerCase() || $1.toLowerCase(),\n };\n }\n catch (error) { }\n return false;\n },\n ],\n ]);\n };\n}\n", "import { convertToUrl, getURLFilename, IMAGE_EXT } from \"applesauce-core/helpers/url\";\n/** Group images into galleries in an ATS tree */\nexport function galleries(types = IMAGE_EXT) {\n return (tree) => {\n let links = [];\n const commit = (index) => {\n // only create a gallery if there are more than a single image\n if (links.length > 1) {\n const start = tree.children.indexOf(links[0]);\n const end = tree.children.indexOf(links[links.length - 1]);\n // replace all nodes with a gallery\n tree.children.splice(start, 1 + end - start, { type: \"gallery\", links: links.map((l) => l.href) });\n links = [];\n // return new cursor\n return end - 1;\n }\n else {\n links = [];\n return index;\n }\n };\n for (let i = 0; i < tree.children.length; i++) {\n const node = tree.children[i];\n try {\n if (node.type === \"link\") {\n const url = convertToUrl(node.href);\n const filename = getURLFilename(url);\n if (filename && types.some((ext) => filename.endsWith(ext))) {\n links.push(node);\n }\n else {\n i = commit(i);\n }\n }\n else if (node.type === \"text\" && links.length > 0) {\n const isEmpty = node.value === \"\\n\" || !node.value.match(/[^\\s]/g);\n if (!isEmpty)\n i = commit(i);\n }\n }\n catch (error) {\n i = commit(i);\n }\n }\n // Do one finally commit, just in case a link is the last element in the list\n commit(tree.children.length);\n };\n}\n", "import { parseBolt11 } from \"applesauce-core/helpers/bolt11\";\nimport { Tokens } from \"../helpers/regexp.js\";\nimport { findAndReplace } from \"../nast/find-and-replace.js\";\n/** Finds and creates lightning invoice nodes in the tree */\nexport function lightningInvoices() {\n return (tree) => {\n findAndReplace(tree, [\n [\n Tokens.lightning,\n (_, $1) => {\n try {\n const invoice = $1;\n const parsed = parseBolt11(invoice);\n return {\n type: \"lightning\",\n invoice,\n parsed,\n };\n }\n catch (error) { }\n return false;\n },\n ],\n ]);\n };\n}\n", "import { Tokens } from \"../helpers/regexp.js\";\nimport { findAndReplace } from \"../nast/find-and-replace.js\";\n/** Finds and creates web links in the tree */\nexport function links() {\n return (tree) => {\n findAndReplace(tree, [\n [\n Tokens.link,\n (_) => {\n try {\n return {\n type: \"link\",\n href: new URL(_).toString(),\n value: _,\n };\n }\n catch (error) { }\n return false;\n },\n ],\n ]);\n };\n}\n", "import { unified } from \"unified\";\nimport { getOrComputeCachedValue } from \"applesauce-core/helpers/cache\";\nimport { nostrMentions } from \"./mentions.js\";\nimport { cashuTokens } from \"./cashu.js\";\nimport { emojis } from \"./emoji.js\";\nimport { createEventContentTree } from \"./parser.js\";\nimport { hashtags } from \"./hashtag.js\";\nimport { galleries } from \"./gallery.js\";\nimport { lightningInvoices } from \"./lightning.js\";\nimport { eolMetadata } from \"../nast/eol-metadata.js\";\nimport { links } from \"./links.js\";\nexport const TextNoteContentSymbol = Symbol.for(\"text-note-content\");\n// default kind 1 transformers\nexport const textNoteTransformers = [\n links,\n nostrMentions,\n galleries,\n emojis,\n hashtags,\n lightningInvoices,\n cashuTokens,\n eolMetadata,\n];\n/** Parsed and process a note with custom transformers */\nexport function getParsedContent(event, content, transformers = textNoteTransformers, cacheKey = TextNoteContentSymbol) {\n // process strings\n if (typeof event === \"string\") {\n const processor = unified();\n for (const transformer of transformers) {\n processor.use(transformer);\n }\n return processor.runSync(createEventContentTree(event, content));\n }\n // no caching\n if (!cacheKey) {\n const processor = unified();\n for (const transformer of transformers) {\n processor.use(transformer);\n }\n return processor.runSync(createEventContentTree(event, content));\n }\n return getOrComputeCachedValue(event, cacheKey, () => {\n const processor = unified();\n for (const transformer of transformers) {\n processor.use(transformer);\n }\n return processor.runSync(createEventContentTree(event, content));\n });\n}\nexport function removeParsedTextContent(event) {\n // @ts-expect-error\n delete event[TextNoteContentSymbol];\n}\n"], - "mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAEA,QAAI,SAAS,OAAO,UAAU;AAC9B,QAAI,QAAQ,OAAO,UAAU;AAC7B,QAAI,iBAAiB,OAAO;AAC5B,QAAI,OAAO,OAAO;AAElB,QAAI,UAAU,SAASA,SAAQ,KAAK;AACnC,UAAI,OAAO,MAAM,YAAY,YAAY;AACxC,eAAO,MAAM,QAAQ,GAAG;AAAA,MACzB;AAEA,aAAO,MAAM,KAAK,GAAG,MAAM;AAAA,IAC5B;AAEA,QAAIC,iBAAgB,SAASA,eAAc,KAAK;AAC/C,UAAI,CAAC,OAAO,MAAM,KAAK,GAAG,MAAM,mBAAmB;AAClD,eAAO;AAAA,MACR;AAEA,UAAI,oBAAoB,OAAO,KAAK,KAAK,aAAa;AACtD,UAAI,mBAAmB,IAAI,eAAe,IAAI,YAAY,aAAa,OAAO,KAAK,IAAI,YAAY,WAAW,eAAe;AAE7H,UAAI,IAAI,eAAe,CAAC,qBAAqB,CAAC,kBAAkB;AAC/D,eAAO;AAAA,MACR;AAIA,UAAI;AACJ,WAAK,OAAO,KAAK;AAAA,MAAO;AAExB,aAAO,OAAO,QAAQ,eAAe,OAAO,KAAK,KAAK,GAAG;AAAA,IAC1D;AAGA,QAAI,cAAc,SAASC,aAAY,QAAQ,SAAS;AACvD,UAAI,kBAAkB,QAAQ,SAAS,aAAa;AACnD,uBAAe,QAAQ,QAAQ,MAAM;AAAA,UACpC,YAAY;AAAA,UACZ,cAAc;AAAA,UACd,OAAO,QAAQ;A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AC7B;AACA,WAAO,UAAU,QAAQ,uBAAuB,OAAO,OAAO,CAAC;AAAA,EACnE;AACA,SAAO,wBAAwB,OAAO,UAAU,MAAM;AAClD,UAAM,YAAY,QAAQ;AAC1B,eAAW,eAAe,cAAc;AACpC,gBAAU,IAAI,WAAW;AAAA,IAC7B;AACA,WAAO,UAAU,QAAQ,uBAAuB,OAAO,OAAO,CAAC;AAAA,EACnE,CAAC;AACL;;;AhD1CO,SAAS,mBAAmB,OAAO,YAAY,MAAM;AAExD,QAAM,kBAAc,wBAAQ,OAAO,6BAAM,iBAAgB,EAAE,GAAG,YAAY,MAAM,kBAAkB,KAAK,aAAa,EAAE,IAAI,YAAa,CAAC,6BAAM,eAAe,UAAU,CAAC;AAExK,QAAM,WAAO,wBAAQ,MAAO,QAAQ,iBAAiB,OAAO,6BAAM,SAAS,6BAAM,cAAc,6BAAM,QAAQ,IAAI,QAAY,CAAC,OAAO,6BAAM,SAAS,6BAAM,cAAc,6BAAM,QAAQ,CAAC;AACvL,MAAI,YAAY;AAChB,OAAI,6BAAM,cAAa;AACnB,gBAAY,gBAAgB,MAAM,KAAK,SAAS;AACpD,SAAO,cAAc,WAAW,WAAW;AAC/C;", - "names": ["isArray", "isPlainObject", "setProperty", "getProperty", "extend", "len", "i", "len2", "Buffer", "utf8ToBytes", "i", "asciiToBytes", "byteLength", "isBytes", "anumber", "abytes", "aexists", "aoutput", "clean", "createView", "rotr", "bytesToHex", "hexToBytes", "utf8ToBytes", "bytesToUtf8", "toBytes", "concatBytes", "createHasher", "randomBytes", "Hash", "setBigUint64", "Chi", "Maj", "_32n", "HashMD", "add", "fromBig", "split", "U32_MASK64", "_32n", "shrSH", "shrSL", "rotrSH", "rotrSL", "rotrBH", "rotrBL", "add3L", "add3H", "add4L", "add4H", "add5L", "add5H", "SHA256_K", "SHA256_W", "SHA256", "SHA224", "K512", "SHA512_Kh", "SHA512_Kl", "SHA512_W_H", "SHA512_W_L", "SHA512", "SHA384", "T224_IV", "T256_IV", "SHA512_224", "SHA512_256", "abool", "numberToHexUnpadded", "hexToNumber", "bytesToNumberBE", "bytesToNumberLE", "numberToBytesBE", "numberToBytesLE", "numberToVarBytesBE", "ensureBytes", "equalBytes", "copyBytes", "asciiToBytes", "inRange", "aInRange", "bitLen", "bitGet", "bitSet", "createHmacDrbg", "validateObject", "isHash", "memoized", "_0n", "_1n", "bitMask", "notImplemented", "map", "_0n", "_1n", "map", "_0n", "_1n", "window", "point", "wbits", "order", "_0n", "_1n", "point", "endo", "tv5", "c1", "c2", "randomBytes", "r", "s", "isObj", "is", "createHasher", "map", "_0n", "_1n", "point", "bytesToNumber", "hexToNumber", "encodeBase64toUint8", "hashToCurve", "pointFromHex", "deriveKeysetId", "blindMessage", "constructProofFromPromise", "serializeProof", "K", "isBytes", "abytes", "anumber", "wrap", "decode", "join", "normalize", "padding", "isUrl", "alphabet", "sha256", "bytesToNumber", "index", "normalize", "DerivationType", "deriveSecret", "deriveBlindingFactor", "createP2PKsecret", "getSignedProofs", "_jsx", "_Fragment", "index", "import_jsx_runtime", "content", "_jsx", "_Fragment", "import_react", "import_jsx_runtime", "import_react", "_jsx", "require", "import_react", "import_react", "import_jsx_runtime", "import_react", "_jsx", "import_react", "import_react", "import_jsx_runtime", "import_react", "_jsx", "require", "import_react", "import_jsx_runtime", "import_react", "_jsx", "import_react", "hash_sum", "import_react", "import_react", "index", "is", "index", "index", "position", "ok", "index", "point", "index", "extname", "index", "index", "index", "field", "basename", "dirname", "assertPath", "extname", "index", "extend", "file", "ok", "tree", "add", "value", "parameters", "isUint8Array", "CheckStateEnum", "MeltQuoteState", "MintQuoteState", "PaymentRequestTransportType", "HttpResponseError", "bytesToHex", "_32n", "map", "import_buffer", "PaymentRequest", "split", "order", "hexToNumber", "bytesToHex", "bytesToHex", "CashuMint", "BlindedMessage", "CashuWallet", "i", "split", "links", "index"] -} diff --git a/node_modules/.vite/deps_temp_742205d0/chunk-DC5AMYBS.js b/node_modules/.vite/deps_temp_742205d0/chunk-DC5AMYBS.js deleted file mode 100644 index 7b838028..00000000 --- a/node_modules/.vite/deps_temp_742205d0/chunk-DC5AMYBS.js +++ /dev/null @@ -1,39 +0,0 @@ -var __create = Object.create; -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __getProtoOf = Object.getPrototypeOf; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; -var __commonJS = (cb, mod) => function __require() { - return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports; -}; -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 __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( - // If the importer is in node compatibility mode or this is not an ESM - // file that has been converted to a CommonJS file using a Babel- - // compatible transform (i.e. "__esModule" has not been set), then set - // "default" to the CommonJS "module.exports" for node compatibility. - isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, - mod -)); -var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value); - -export { - __commonJS, - __export, - __toESM, - __publicField -}; -//# sourceMappingURL=chunk-DC5AMYBS.js.map diff --git a/node_modules/.vite/deps_temp_742205d0/chunk-DC5AMYBS.js.map b/node_modules/.vite/deps_temp_742205d0/chunk-DC5AMYBS.js.map deleted file mode 100644 index 98652118..00000000 --- a/node_modules/.vite/deps_temp_742205d0/chunk-DC5AMYBS.js.map +++ /dev/null @@ -1,7 +0,0 @@ -{ - "version": 3, - "sources": [], - "sourcesContent": [], - "mappings": "", - "names": [] -} diff --git a/node_modules/.vite/deps_temp_742205d0/chunk-ESJ34HX7.js b/node_modules/.vite/deps_temp_742205d0/chunk-ESJ34HX7.js deleted file mode 100644 index 1b5e5156..00000000 --- a/node_modules/.vite/deps_temp_742205d0/chunk-ESJ34HX7.js +++ /dev/null @@ -1,16111 +0,0 @@ -import { - __commonJS, - __export, - __publicField, - __toESM -} from "./chunk-DC5AMYBS.js"; - -// node_modules/hash-sum/hash-sum.js -var require_hash_sum = __commonJS({ - "node_modules/hash-sum/hash-sum.js"(exports, module) { - "use strict"; - function pad2(hash3, len) { - while (hash3.length < len) { - hash3 = "0" + hash3; - } - return hash3; - } - function fold(hash3, text) { - var i2; - var chr; - var len; - if (text.length === 0) { - return hash3; - } - for (i2 = 0, len = text.length; i2 < len; i2++) { - chr = text.charCodeAt(i2); - hash3 = (hash3 << 5) - hash3 + chr; - hash3 |= 0; - } - return hash3 < 0 ? hash3 * -2 : hash3; - } - function foldObject(hash3, o, seen) { - return Object.keys(o).sort().reduce(foldKey, hash3); - function foldKey(hash4, key) { - return foldValue(hash4, o[key], key, seen); - } - } - function foldValue(input, value, key, seen) { - var hash3 = fold(fold(fold(input, key), toString(value)), typeof value); - if (value === null) { - return fold(hash3, "null"); - } - if (value === void 0) { - return fold(hash3, "undefined"); - } - if (typeof value === "object" || typeof value === "function") { - if (seen.indexOf(value) !== -1) { - return fold(hash3, "[Circular]" + key); - } - seen.push(value); - var objHash = foldObject(hash3, value, seen); - if (!("valueOf" in value) || typeof value.valueOf !== "function") { - return objHash; - } - try { - return fold(objHash, String(value.valueOf())); - } catch (err) { - return fold(objHash, "[valueOf exception]" + (err.stack || err.message)); - } - } - return fold(hash3, value.toString()); - } - function toString(o) { - return Object.prototype.toString.call(o); - } - function sum(o) { - return pad2(foldValue(0, o, "", []).toString(16), 8); - } - module.exports = sum; - } -}); - -// node_modules/fast-deep-equal/index.js -var require_fast_deep_equal = __commonJS({ - "node_modules/fast-deep-equal/index.js"(exports, module) { - "use strict"; - module.exports = function equal2(a, b) { - if (a === b) return true; - if (a && b && typeof a == "object" && typeof b == "object") { - if (a.constructor !== b.constructor) return false; - var length, i2, keys; - if (Array.isArray(a)) { - length = a.length; - if (length != b.length) return false; - for (i2 = length; i2-- !== 0; ) - if (!equal2(a[i2], b[i2])) return false; - return true; - } - if (a.constructor === RegExp) return a.source === b.source && a.flags === b.flags; - if (a.valueOf !== Object.prototype.valueOf) return a.valueOf() === b.valueOf(); - if (a.toString !== Object.prototype.toString) return a.toString() === b.toString(); - keys = Object.keys(a); - length = keys.length; - if (length !== Object.keys(b).length) return false; - for (i2 = length; i2-- !== 0; ) - if (!Object.prototype.hasOwnProperty.call(b, keys[i2])) return false; - for (i2 = length; i2-- !== 0; ) { - var key = keys[i2]; - if (!equal2(a[key], b[key])) return false; - } - return true; - } - return a !== a && b !== b; - }; - } -}); - -// node_modules/light-bolt11-decoder/node_modules/@scure/base/lib/index.js -var require_lib = __commonJS({ - "node_modules/light-bolt11-decoder/node_modules/@scure/base/lib/index.js"(exports) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.bytes = exports.stringToBytes = exports.str = exports.bytesToString = exports.hex = exports.utf8 = exports.bech32m = exports.bech32 = exports.base58check = exports.base58xmr = exports.base58xrp = exports.base58flickr = exports.base58 = exports.base64url = exports.base64 = exports.base32crockford = exports.base32hex = exports.base32 = exports.base16 = exports.utils = exports.assertNumber = void 0; - function assertNumber2(n) { - if (!Number.isSafeInteger(n)) - throw new Error(`Wrong integer: ${n}`); - } - exports.assertNumber = assertNumber2; - function chain3(...args) { - const wrap = (a, b) => (c) => a(b(c)); - const encode = Array.from(args).reverse().reduce((acc, i2) => acc ? wrap(acc, i2.encode) : i2.encode, void 0); - const decode4 = args.reduce((acc, i2) => acc ? wrap(acc, i2.decode) : i2.decode, void 0); - return { encode, decode: decode4 }; - } - function alphabet3(alphabet4) { - 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((i2) => { - assertNumber2(i2); - if (i2 < 0 || i2 >= alphabet4.length) - throw new Error(`Digit index outside alphabet: ${i2} (alphabet: ${alphabet4.length})`); - return alphabet4[i2]; - }); - }, - 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 = alphabet4.indexOf(letter); - if (index === -1) - throw new Error(`Unknown letter: "${letter}". Allowed: ${alphabet4}`); - return index; - }); - } - }; - } - function join3(separator = "") { - if (typeof separator !== "string") - throw new Error("join separator should be string"); - return { - encode: (from2) => { - if (!Array.isArray(from2) || from2.length && typeof from2[0] !== "string") - throw new Error("join.encode input should be array of strings"); - for (let i2 of from2) - if (typeof i2 !== "string") - throw new Error(`join.encode: non-string input=${i2}`); - return from2.join(separator); - }, - decode: (to) => { - if (typeof to !== "string") - throw new Error("join.decode input should be string"); - return to.split(separator); - } - }; - } - function padding3(bits, chr = "=") { - assertNumber2(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 i2 of data) - if (typeof i2 !== "string") - throw new Error(`padding.encode: non-string input=${i2}`); - 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 i2 of input) - if (typeof i2 !== "string") - throw new Error(`padding.decode: non-string input=${i2}`); - 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 normalize3(fn) { - if (typeof fn !== "function") - throw new Error("normalize fn should be function"); - return { encode: (from2) => from2, decode: (to) => fn(to) }; - } - function convertRadix4(data, from2, to) { - if (from2 < 2) - throw new Error(`convertRadix: wrong from=${from2}, 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) => { - assertNumber2(d); - if (d < 0 || d >= from2) - throw new Error(`Wrong integer: ${d}`); - }); - while (true) { - let carry = 0; - let done = true; - for (let i2 = pos; i2 < digits.length; i2++) { - const digit = digits[i2]; - const digitBase = from2 * carry + digit; - if (!Number.isSafeInteger(digitBase) || from2 * carry / from2 !== carry || digitBase - digit !== from2 * carry) { - throw new Error("convertRadix: carry overflow"); - } - carry = digitBase % to; - digits[i2] = Math.floor(digitBase / to); - if (!Number.isSafeInteger(digits[i2]) || digits[i2] * to + carry !== digitBase) - throw new Error("convertRadix: carry overflow"); - if (!done) - continue; - else if (!digits[i2]) - pos = i2; - else - done = false; - } - res.push(carry); - if (done) - break; - } - for (let i2 = 0; i2 < data.length - 1 && data[i2] === 0; i2++) - res.push(0); - return res.reverse(); - } - var gcd3 = (a, b) => !b ? a : gcd3(b, a % b); - var radix2carry3 = (from2, to) => from2 + (to - gcd3(from2, to)); - function convertRadix23(data, from2, to, padding4) { - if (!Array.isArray(data)) - throw new Error("convertRadix2: data should be array"); - if (from2 <= 0 || from2 > 32) - throw new Error(`convertRadix2: wrong from=${from2}`); - if (to <= 0 || to > 32) - throw new Error(`convertRadix2: wrong to=${to}`); - if (radix2carry3(from2, to) > 32) { - throw new Error(`convertRadix2: carry overflow from=${from2} to=${to} carryBits=${radix2carry3(from2, to)}`); - } - let carry = 0; - let pos = 0; - const mask = 2 ** to - 1; - const res = []; - for (const n of data) { - assertNumber2(n); - if (n >= 2 ** from2) - throw new Error(`convertRadix2: invalid data word=${n} from=${from2}`); - carry = carry << from2 | n; - if (pos + from2 > 32) - throw new Error(`convertRadix2: carry overflow pos=${pos} from=${from2}`); - pos += from2; - for (; pos >= to; pos -= to) - res.push((carry >> pos - to & mask) >>> 0); - carry &= 2 ** pos - 1; - } - carry = carry << to - pos & mask; - if (!padding4 && pos >= from2) - throw new Error("Excess padding"); - if (!padding4 && carry) - throw new Error(`Non-zero padding: ${carry}`); - if (padding4 && pos > 0) - res.push(carry >>> 0); - return res; - } - function radix4(num) { - assertNumber2(num); - return { - encode: (bytes4) => { - if (!(bytes4 instanceof Uint8Array)) - throw new Error("radix.encode input should be Uint8Array"); - return convertRadix4(Array.from(bytes4), 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(convertRadix4(digits, num, 2 ** 8)); - } - }; - } - function radix23(bits, revPadding = false) { - assertNumber2(bits); - if (bits <= 0 || bits > 32) - throw new Error("radix2: bits should be in (0..32]"); - if (radix2carry3(8, bits) > 32 || radix2carry3(bits, 8) > 32) - throw new Error("radix2: carry overflow"); - return { - encode: (bytes4) => { - if (!(bytes4 instanceof Uint8Array)) - throw new Error("radix2.encode input should be Uint8Array"); - return convertRadix23(Array.from(bytes4), 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(convertRadix23(digits, bits, 8, revPadding)); - } - }; - } - function unsafeWrapper3(fn) { - if (typeof fn !== "function") - throw new Error("unsafeWrapper fn should be function"); - return function(...args) { - try { - return fn.apply(null, args); - } catch (e) { - } - }; - } - function checksum(len, fn) { - assertNumber2(len); - if (typeof fn !== "function") - throw new Error("checksum fn should be function"); - return { - encode(data) { - if (!(data instanceof Uint8Array)) - throw new Error("checksum.encode: input should be Uint8Array"); - const checksum2 = fn(data).slice(0, len); - const res = new Uint8Array(data.length + len); - res.set(data); - res.set(checksum2, data.length); - return res; - }, - decode(data) { - if (!(data instanceof Uint8Array)) - throw new Error("checksum.decode: input should be Uint8Array"); - const payload = data.slice(0, -len); - const newChecksum = fn(payload).slice(0, len); - const oldChecksum = data.slice(-len); - for (let i2 = 0; i2 < len; i2++) - if (newChecksum[i2] !== oldChecksum[i2]) - throw new Error("Invalid checksum"); - return payload; - } - }; - } - exports.utils = { alphabet: alphabet3, chain: chain3, checksum, radix: radix4, radix2: radix23, join: join3, padding: padding3 }; - exports.base16 = chain3(radix23(4), alphabet3("0123456789ABCDEF"), join3("")); - exports.base32 = chain3(radix23(5), alphabet3("ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"), padding3(5), join3("")); - exports.base32hex = chain3(radix23(5), alphabet3("0123456789ABCDEFGHIJKLMNOPQRSTUV"), padding3(5), join3("")); - exports.base32crockford = chain3(radix23(5), alphabet3("0123456789ABCDEFGHJKMNPQRSTVWXYZ"), join3(""), normalize3((s) => s.toUpperCase().replace(/O/g, "0").replace(/[IL]/g, "1"))); - exports.base64 = chain3(radix23(6), alphabet3("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"), padding3(6), join3("")); - exports.base64url = chain3(radix23(6), alphabet3("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"), padding3(6), join3("")); - var genBase583 = (abc) => chain3(radix4(58), alphabet3(abc), join3("")); - exports.base58 = genBase583("123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"); - exports.base58flickr = genBase583("123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"); - exports.base58xrp = genBase583("rpshnaf39wBUDNEGHJKLM4PQRST7VWXYZ2bcdeCg65jkm8oFqi1tuvAxyz"); - var XMR_BLOCK_LEN2 = [0, 2, 3, 5, 6, 7, 9, 10, 11]; - exports.base58xmr = { - encode(data) { - let res = ""; - for (let i2 = 0; i2 < data.length; i2 += 8) { - const block = data.subarray(i2, i2 + 8); - res += exports.base58.encode(block).padStart(XMR_BLOCK_LEN2[block.length], "1"); - } - return res; - }, - decode(str) { - let res = []; - for (let i2 = 0; i2 < str.length; i2 += 11) { - const slice = str.slice(i2, i2 + 11); - const blockLen = XMR_BLOCK_LEN2.indexOf(slice.length); - const block = exports.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 base58check = (sha2563) => chain3(checksum(4, (data) => sha2563(sha2563(data))), exports.base58); - exports.base58check = base58check; - var BECH_ALPHABET3 = chain3(alphabet3("qpzry9x8gf2tvdw0s3jn54khce6mua7l"), join3("")); - var POLYMOD_GENERATORS3 = [996825010, 642813549, 513874426, 1027748829, 705979059]; - function bech32Polymod3(pre) { - const b = pre >> 25; - let chk = (pre & 33554431) << 5; - for (let i2 = 0; i2 < POLYMOD_GENERATORS3.length; i2++) { - if ((b >> i2 & 1) === 1) - chk ^= POLYMOD_GENERATORS3[i2]; - } - return chk; - } - function bechChecksum3(prefix, words, encodingConst = 1) { - const len = prefix.length; - let chk = 1; - for (let i2 = 0; i2 < len; i2++) { - const c = prefix.charCodeAt(i2); - if (c < 33 || c > 126) - throw new Error(`Invalid prefix (${prefix})`); - chk = bech32Polymod3(chk) ^ c >> 5; - } - chk = bech32Polymod3(chk); - for (let i2 = 0; i2 < len; i2++) - chk = bech32Polymod3(chk) ^ prefix.charCodeAt(i2) & 31; - for (let v of words) - chk = bech32Polymod3(chk) ^ v; - for (let i2 = 0; i2 < 6; i2++) - chk = bech32Polymod3(chk); - chk ^= encodingConst; - return BECH_ALPHABET3.encode(convertRadix23([chk % 2 ** 30], 30, 5, false)); - } - function genBech323(encoding) { - const ENCODING_CONST = encoding === "bech32" ? 1 : 734539939; - const _words = radix23(5); - const fromWords = _words.decode; - const toWords = _words.encode; - const fromWordsUnsafe = unsafeWrapper3(fromWords); - function encode(prefix, words, limit2 = 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 (limit2 !== false && actualLength > limit2) - throw new TypeError(`Length ${actualLength} exceeds limit ${limit2}`); - prefix = prefix.toLowerCase(); - return `${prefix}1${BECH_ALPHABET3.encode(words)}${bechChecksum3(prefix, words, ENCODING_CONST)}`; - } - function decode4(str, limit2 = 90) { - if (typeof str !== "string") - throw new Error(`bech32.decode input should be string, not ${typeof str}`); - if (str.length < 8 || limit2 !== false && str.length > limit2) - throw new TypeError(`Wrong string length: ${str.length} (${str}). Expected (8..${limit2})`); - 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_ALPHABET3.decode(_words2).slice(0, -6); - const sum = bechChecksum3(prefix, words, ENCODING_CONST); - if (!_words2.endsWith(sum)) - throw new Error(`Invalid checksum in ${str}: expected "${sum}"`); - return { prefix, words }; - } - const decodeUnsafe = unsafeWrapper3(decode4); - function decodeToBytes(str) { - const { prefix, words } = decode4(str, false); - return { prefix, words, bytes: fromWords(words) }; - } - return { encode, decode: decode4, decodeToBytes, decodeUnsafe, fromWords, fromWordsUnsafe, toWords }; - } - exports.bech32 = genBech323("bech32"); - exports.bech32m = genBech323("bech32m"); - exports.utf8 = { - encode: (data) => new TextDecoder().decode(data), - decode: (str) => new TextEncoder().encode(str) - }; - exports.hex = chain3(radix23(4), alphabet3("0123456789abcdef"), join3(""), normalize3((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 CODERS2 = { - utf8: exports.utf8, - hex: exports.hex, - base16: exports.base16, - base32: exports.base32, - base64: exports.base64, - base64url: exports.base64url, - base58: exports.base58, - base58xmr: exports.base58xmr - }; - var coderTypeError2 = `Invalid encoding type. Available types: ${Object.keys(CODERS2).join(", ")}`; - var bytesToString = (type, bytes4) => { - if (typeof type !== "string" || !CODERS2.hasOwnProperty(type)) - throw new TypeError(coderTypeError2); - if (!(bytes4 instanceof Uint8Array)) - throw new TypeError("bytesToString() expects Uint8Array"); - return CODERS2[type].encode(bytes4); - }; - exports.bytesToString = bytesToString; - exports.str = exports.bytesToString; - var stringToBytes = (type, str) => { - if (!CODERS2.hasOwnProperty(type)) - throw new TypeError(coderTypeError2); - if (typeof str !== "string") - throw new TypeError("stringToBytes() expects string"); - return CODERS2[type].decode(str); - }; - exports.stringToBytes = stringToBytes; - exports.bytes = exports.stringToBytes; - } -}); - -// node_modules/light-bolt11-decoder/bolt11.js -var require_bolt11 = __commonJS({ - "node_modules/light-bolt11-decoder/bolt11.js"(exports, module) { - var { bech32: bech323, hex: hex3, utf8: utf82 } = require_lib(); - var DEFAULTNETWORK = { - // default network is bitcoin - bech32: "bc", - pubKeyHash: 0, - scriptHash: 5, - validWitnessVersions: [0] - }; - var TESTNETWORK = { - bech32: "tb", - pubKeyHash: 111, - scriptHash: 196, - validWitnessVersions: [0] - }; - var SIGNETNETWORK = { - bech32: "tbs", - pubKeyHash: 111, - scriptHash: 196, - validWitnessVersions: [0] - }; - var REGTESTNETWORK = { - bech32: "bcrt", - pubKeyHash: 111, - scriptHash: 196, - validWitnessVersions: [0] - }; - var SIMNETWORK = { - bech32: "sb", - pubKeyHash: 63, - scriptHash: 123, - validWitnessVersions: [0] - }; - var FEATUREBIT_ORDER = [ - "option_data_loss_protect", - "initial_routing_sync", - "option_upfront_shutdown_script", - "gossip_queries", - "var_onion_optin", - "gossip_queries_ex", - "option_static_remotekey", - "payment_secret", - "basic_mpp", - "option_support_large_channel" - ]; - var DIVISORS = { - m: BigInt(1e3), - u: BigInt(1e6), - n: BigInt(1e9), - p: BigInt(1e12) - }; - var MAX_MILLISATS = BigInt("2100000000000000000"); - var MILLISATS_PER_BTC = BigInt(1e11); - var TAGCODES = { - payment_hash: 1, - payment_secret: 16, - description: 13, - payee: 19, - description_hash: 23, - // commit to longer descriptions (used by lnurl-pay) - expiry: 6, - // default: 3600 (1 hour) - min_final_cltv_expiry: 24, - // default: 9 - fallback_address: 9, - route_hint: 3, - // for extra routing info (private etc.) - feature_bits: 5, - metadata: 27 - }; - var TAGNAMES = {}; - for (let i2 = 0, keys = Object.keys(TAGCODES); i2 < keys.length; i2++) { - const currentName = keys[i2]; - const currentCode = TAGCODES[keys[i2]].toString(); - TAGNAMES[currentCode] = currentName; - } - var TAGPARSERS = { - 1: (words) => hex3.encode(bech323.fromWordsUnsafe(words)), - // 256 bits - 16: (words) => hex3.encode(bech323.fromWordsUnsafe(words)), - // 256 bits - 13: (words) => utf82.encode(bech323.fromWordsUnsafe(words)), - // string variable length - 19: (words) => hex3.encode(bech323.fromWordsUnsafe(words)), - // 264 bits - 23: (words) => hex3.encode(bech323.fromWordsUnsafe(words)), - // 256 bits - 27: (words) => hex3.encode(bech323.fromWordsUnsafe(words)), - // variable - 6: wordsToIntBE, - // default: 3600 (1 hour) - 24: wordsToIntBE, - // default: 9 - 3: routingInfoParser, - // for extra routing info (private etc.) - 5: featureBitsParser - // keep feature bits as array of 5 bit words - }; - function getUnknownParser(tagCode) { - return (words) => ({ - tagCode: parseInt(tagCode), - words: bech323.encode("unknown", words, Number.MAX_SAFE_INTEGER) - }); - } - function wordsToIntBE(words) { - return words.reverse().reduce((total, item, index) => { - return total + item * Math.pow(32, index); - }, 0); - } - function routingInfoParser(words) { - const routes = []; - let pubkey, shortChannelId, feeBaseMSats, feeProportionalMillionths, cltvExpiryDelta; - let routesBuffer = bech323.fromWordsUnsafe(words); - while (routesBuffer.length > 0) { - pubkey = hex3.encode(routesBuffer.slice(0, 33)); - shortChannelId = hex3.encode(routesBuffer.slice(33, 41)); - feeBaseMSats = parseInt(hex3.encode(routesBuffer.slice(41, 45)), 16); - feeProportionalMillionths = parseInt( - hex3.encode(routesBuffer.slice(45, 49)), - 16 - ); - cltvExpiryDelta = parseInt(hex3.encode(routesBuffer.slice(49, 51)), 16); - routesBuffer = routesBuffer.slice(51); - routes.push({ - pubkey, - short_channel_id: shortChannelId, - fee_base_msat: feeBaseMSats, - fee_proportional_millionths: feeProportionalMillionths, - cltv_expiry_delta: cltvExpiryDelta - }); - } - return routes; - } - function featureBitsParser(words) { - const bools = words.slice().reverse().map((word) => [ - !!(word & 1), - !!(word & 2), - !!(word & 4), - !!(word & 8), - !!(word & 16) - ]).reduce((finalArr, itemArr) => finalArr.concat(itemArr), []); - while (bools.length < FEATUREBIT_ORDER.length * 2) { - bools.push(false); - } - const featureBits = {}; - FEATUREBIT_ORDER.forEach((featureName, index) => { - let status; - if (bools[index * 2]) { - status = "required"; - } else if (bools[index * 2 + 1]) { - status = "supported"; - } else { - status = "unsupported"; - } - featureBits[featureName] = status; - }); - const extraBits = bools.slice(FEATUREBIT_ORDER.length * 2); - featureBits.extra_bits = { - start_bit: FEATUREBIT_ORDER.length * 2, - bits: extraBits, - has_required: extraBits.reduce( - (result, bit, index) => index % 2 !== 0 ? result || false : result || bit, - false - ) - }; - return featureBits; - } - function hrpToMillisat(hrpString, outputString) { - let divisor, value; - if (hrpString.slice(-1).match(/^[munp]$/)) { - divisor = hrpString.slice(-1); - value = hrpString.slice(0, -1); - } else if (hrpString.slice(-1).match(/^[^munp0-9]$/)) { - throw new Error("Not a valid multiplier for the amount"); - } else { - value = hrpString; - } - if (!value.match(/^\d+$/)) - throw new Error("Not a valid human readable amount"); - const valueBN = BigInt(value); - const millisatoshisBN = divisor ? valueBN * MILLISATS_PER_BTC / DIVISORS[divisor] : valueBN * MILLISATS_PER_BTC; - if (divisor === "p" && !(valueBN % BigInt(10) === BigInt(0)) || millisatoshisBN > MAX_MILLISATS) { - throw new Error("Amount is outside of valid range"); - } - return outputString ? millisatoshisBN.toString() : millisatoshisBN; - } - function decode4(paymentRequest, network) { - if (typeof paymentRequest !== "string") - throw new Error("Lightning Payment Request must be string"); - if (paymentRequest.slice(0, 2).toLowerCase() !== "ln") - throw new Error("Not a proper lightning payment request"); - const sections = []; - const decoded = bech323.decode(paymentRequest, Number.MAX_SAFE_INTEGER); - paymentRequest = paymentRequest.toLowerCase(); - const prefix = decoded.prefix; - let words = decoded.words; - let letters = paymentRequest.slice(prefix.length + 1); - let sigWords = words.slice(-104); - words = words.slice(0, -104); - let prefixMatches = prefix.match(/^ln(\S+?)(\d*)([a-zA-Z]?)$/); - if (prefixMatches && !prefixMatches[2]) - prefixMatches = prefix.match(/^ln(\S+)$/); - if (!prefixMatches) { - throw new Error("Not a proper lightning payment request"); - } - sections.push({ - name: "lightning_network", - letters: "ln" - }); - const bech32Prefix = prefixMatches[1]; - let coinNetwork; - if (!network) { - switch (bech32Prefix) { - case DEFAULTNETWORK.bech32: - coinNetwork = DEFAULTNETWORK; - break; - case TESTNETWORK.bech32: - coinNetwork = TESTNETWORK; - break; - case SIGNETNETWORK.bech32: - coinNetwork = SIGNETNETWORK; - break; - case REGTESTNETWORK.bech32: - coinNetwork = REGTESTNETWORK; - break; - case SIMNETWORK.bech32: - coinNetwork = SIMNETWORK; - break; - } - } else { - if (network.bech32 === void 0 || network.pubKeyHash === void 0 || network.scriptHash === void 0 || !Array.isArray(network.validWitnessVersions)) - throw new Error("Invalid network"); - coinNetwork = network; - } - if (!coinNetwork || coinNetwork.bech32 !== bech32Prefix) { - throw new Error("Unknown coin bech32 prefix"); - } - sections.push({ - name: "coin_network", - letters: bech32Prefix, - value: coinNetwork - }); - const value = prefixMatches[2]; - let millisatoshis; - if (value) { - const divisor = prefixMatches[3]; - millisatoshis = hrpToMillisat(value + divisor, true); - sections.push({ - name: "amount", - letters: prefixMatches[2] + prefixMatches[3], - value: millisatoshis - }); - } else { - millisatoshis = null; - } - sections.push({ - name: "separator", - letters: "1" - }); - const timestamp2 = wordsToIntBE(words.slice(0, 7)); - words = words.slice(7); - sections.push({ - name: "timestamp", - letters: letters.slice(0, 7), - value: timestamp2 - }); - letters = letters.slice(7); - let tagName, parser, tagLength, tagWords; - while (words.length > 0) { - const tagCode = words[0].toString(); - tagName = TAGNAMES[tagCode] || "unknown_tag"; - parser = TAGPARSERS[tagCode] || getUnknownParser(tagCode); - words = words.slice(1); - tagLength = wordsToIntBE(words.slice(0, 2)); - words = words.slice(2); - tagWords = words.slice(0, tagLength); - words = words.slice(tagLength); - sections.push({ - name: tagName, - tag: letters[0], - letters: letters.slice(0, 1 + 2 + tagLength), - value: parser(tagWords) - // see: parsers for more comments - }); - letters = letters.slice(1 + 2 + tagLength); - } - sections.push({ - name: "signature", - letters: letters.slice(0, 104), - value: hex3.encode(bech323.fromWordsUnsafe(sigWords)) - }); - letters = letters.slice(104); - sections.push({ - name: "checksum", - letters - }); - let result = { - paymentRequest, - sections, - get expiry() { - let exp = sections.find((s) => s.name === "expiry"); - if (exp) return getValue("timestamp") + exp.value; - }, - get route_hints() { - return sections.filter((s) => s.name === "route_hint").map((s) => s.value); - } - }; - for (let name in TAGCODES) { - if (name === "route_hint") { - continue; - } - Object.defineProperty(result, name, { - get() { - return getValue(name); - } - }); - } - return result; - function getValue(name) { - let section = sections.find((s) => s.name === name); - return section ? section.value : void 0; - } - } - module.exports = { - decode: decode4, - hrpToMillisat - }; - } -}); - -// node_modules/ms/index.js -var require_ms = __commonJS({ - "node_modules/ms/index.js"(exports, module) { - var s = 1e3; - var m = s * 60; - var h = m * 60; - var d = h * 24; - var w = d * 7; - var y = d * 365.25; - module.exports = function(val, options) { - options = options || {}; - var type = typeof val; - if (type === "string" && val.length > 0) { - return parse4(val); - } else if (type === "number" && isFinite(val)) { - return options.long ? fmtLong(val) : fmtShort(val); - } - throw new Error( - "val is not a non-empty string or a valid number. val=" + JSON.stringify(val) - ); - }; - function parse4(str) { - str = String(str); - if (str.length > 100) { - return; - } - var match = /^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec( - str - ); - if (!match) { - return; - } - var n = parseFloat(match[1]); - var type = (match[2] || "ms").toLowerCase(); - switch (type) { - case "years": - case "year": - case "yrs": - case "yr": - case "y": - return n * y; - case "weeks": - case "week": - case "w": - return n * w; - case "days": - case "day": - case "d": - return n * d; - case "hours": - case "hour": - case "hrs": - case "hr": - case "h": - return n * h; - case "minutes": - case "minute": - case "mins": - case "min": - case "m": - return n * m; - case "seconds": - case "second": - case "secs": - case "sec": - case "s": - return n * s; - case "milliseconds": - case "millisecond": - case "msecs": - case "msec": - case "ms": - return n; - default: - return void 0; - } - } - function fmtShort(ms) { - var msAbs = Math.abs(ms); - if (msAbs >= d) { - return Math.round(ms / d) + "d"; - } - if (msAbs >= h) { - return Math.round(ms / h) + "h"; - } - if (msAbs >= m) { - return Math.round(ms / m) + "m"; - } - if (msAbs >= s) { - return Math.round(ms / s) + "s"; - } - return ms + "ms"; - } - function fmtLong(ms) { - var msAbs = Math.abs(ms); - if (msAbs >= d) { - return plural(ms, msAbs, d, "day"); - } - if (msAbs >= h) { - return plural(ms, msAbs, h, "hour"); - } - if (msAbs >= m) { - return plural(ms, msAbs, m, "minute"); - } - if (msAbs >= s) { - return plural(ms, msAbs, s, "second"); - } - return ms + " ms"; - } - function plural(ms, msAbs, n, name) { - var isPlural = msAbs >= n * 1.5; - return Math.round(ms / n) + " " + name + (isPlural ? "s" : ""); - } - } -}); - -// node_modules/debug/src/common.js -var require_common = __commonJS({ - "node_modules/debug/src/common.js"(exports, module) { - function setup(env) { - createDebug.debug = createDebug; - createDebug.default = createDebug; - createDebug.coerce = coerce; - createDebug.disable = disable; - createDebug.enable = enable; - createDebug.enabled = enabled; - createDebug.humanize = require_ms(); - createDebug.destroy = destroy; - Object.keys(env).forEach((key) => { - createDebug[key] = env[key]; - }); - createDebug.names = []; - createDebug.skips = []; - createDebug.formatters = {}; - function selectColor(namespace) { - let hash3 = 0; - for (let i2 = 0; i2 < namespace.length; i2++) { - hash3 = (hash3 << 5) - hash3 + namespace.charCodeAt(i2); - hash3 |= 0; - } - return createDebug.colors[Math.abs(hash3) % createDebug.colors.length]; - } - createDebug.selectColor = selectColor; - function createDebug(namespace) { - let prevTime; - let enableOverride = null; - let namespacesCache; - let enabledCache; - function debug2(...args) { - if (!debug2.enabled) { - return; - } - const self = debug2; - const curr = Number(/* @__PURE__ */ new Date()); - const ms = curr - (prevTime || curr); - self.diff = ms; - self.prev = prevTime; - self.curr = curr; - prevTime = curr; - args[0] = createDebug.coerce(args[0]); - if (typeof args[0] !== "string") { - args.unshift("%O"); - } - let index = 0; - args[0] = args[0].replace(/%([a-zA-Z%])/g, (match, format) => { - if (match === "%%") { - return "%"; - } - index++; - const formatter = createDebug.formatters[format]; - if (typeof formatter === "function") { - const val = args[index]; - match = formatter.call(self, val); - args.splice(index, 1); - index--; - } - return match; - }); - createDebug.formatArgs.call(self, args); - const logFn = self.log || createDebug.log; - logFn.apply(self, args); - } - debug2.namespace = namespace; - debug2.useColors = createDebug.useColors(); - debug2.color = createDebug.selectColor(namespace); - debug2.extend = extend; - debug2.destroy = createDebug.destroy; - Object.defineProperty(debug2, "enabled", { - enumerable: true, - configurable: false, - get: () => { - if (enableOverride !== null) { - return enableOverride; - } - if (namespacesCache !== createDebug.namespaces) { - namespacesCache = createDebug.namespaces; - enabledCache = createDebug.enabled(namespace); - } - return enabledCache; - }, - set: (v) => { - enableOverride = v; - } - }); - if (typeof createDebug.init === "function") { - createDebug.init(debug2); - } - return debug2; - } - function extend(namespace, delimiter) { - const newDebug = createDebug(this.namespace + (typeof delimiter === "undefined" ? ":" : delimiter) + namespace); - newDebug.log = this.log; - return newDebug; - } - function enable(namespaces) { - createDebug.save(namespaces); - createDebug.namespaces = namespaces; - createDebug.names = []; - createDebug.skips = []; - const split = (typeof namespaces === "string" ? namespaces : "").trim().replace(/\s+/g, ",").split(",").filter(Boolean); - for (const ns of split) { - if (ns[0] === "-") { - createDebug.skips.push(ns.slice(1)); - } else { - createDebug.names.push(ns); - } - } - } - function matchesTemplate(search, template) { - let searchIndex = 0; - let templateIndex = 0; - let starIndex = -1; - let matchIndex = 0; - while (searchIndex < search.length) { - if (templateIndex < template.length && (template[templateIndex] === search[searchIndex] || template[templateIndex] === "*")) { - if (template[templateIndex] === "*") { - starIndex = templateIndex; - matchIndex = searchIndex; - templateIndex++; - } else { - searchIndex++; - templateIndex++; - } - } else if (starIndex !== -1) { - templateIndex = starIndex + 1; - matchIndex++; - searchIndex = matchIndex; - } else { - return false; - } - } - while (templateIndex < template.length && template[templateIndex] === "*") { - templateIndex++; - } - return templateIndex === template.length; - } - function disable() { - const namespaces = [ - ...createDebug.names, - ...createDebug.skips.map((namespace) => "-" + namespace) - ].join(","); - createDebug.enable(""); - return namespaces; - } - function enabled(name) { - for (const skip2 of createDebug.skips) { - if (matchesTemplate(name, skip2)) { - return false; - } - } - for (const ns of createDebug.names) { - if (matchesTemplate(name, ns)) { - return true; - } - } - return false; - } - function coerce(val) { - if (val instanceof Error) { - return val.stack || val.message; - } - return val; - } - function destroy() { - console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."); - } - createDebug.enable(createDebug.load()); - return createDebug; - } - module.exports = setup; - } -}); - -// node_modules/debug/src/browser.js -var require_browser = __commonJS({ - "node_modules/debug/src/browser.js"(exports, module) { - exports.formatArgs = formatArgs; - exports.save = save; - exports.load = load; - exports.useColors = useColors; - exports.storage = localstorage(); - exports.destroy = /* @__PURE__ */ (() => { - let warned = false; - return () => { - if (!warned) { - warned = true; - console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."); - } - }; - })(); - exports.colors = [ - "#0000CC", - "#0000FF", - "#0033CC", - "#0033FF", - "#0066CC", - "#0066FF", - "#0099CC", - "#0099FF", - "#00CC00", - "#00CC33", - "#00CC66", - "#00CC99", - "#00CCCC", - "#00CCFF", - "#3300CC", - "#3300FF", - "#3333CC", - "#3333FF", - "#3366CC", - "#3366FF", - "#3399CC", - "#3399FF", - "#33CC00", - "#33CC33", - "#33CC66", - "#33CC99", - "#33CCCC", - "#33CCFF", - "#6600CC", - "#6600FF", - "#6633CC", - "#6633FF", - "#66CC00", - "#66CC33", - "#9900CC", - "#9900FF", - "#9933CC", - "#9933FF", - "#99CC00", - "#99CC33", - "#CC0000", - "#CC0033", - "#CC0066", - "#CC0099", - "#CC00CC", - "#CC00FF", - "#CC3300", - "#CC3333", - "#CC3366", - "#CC3399", - "#CC33CC", - "#CC33FF", - "#CC6600", - "#CC6633", - "#CC9900", - "#CC9933", - "#CCCC00", - "#CCCC33", - "#FF0000", - "#FF0033", - "#FF0066", - "#FF0099", - "#FF00CC", - "#FF00FF", - "#FF3300", - "#FF3333", - "#FF3366", - "#FF3399", - "#FF33CC", - "#FF33FF", - "#FF6600", - "#FF6633", - "#FF9900", - "#FF9933", - "#FFCC00", - "#FFCC33" - ]; - function useColors() { - if (typeof window !== "undefined" && window.process && (window.process.type === "renderer" || window.process.__nwjs)) { - return true; - } - if (typeof navigator !== "undefined" && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)) { - return false; - } - let m; - return typeof document !== "undefined" && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance || // Is firebug? http://stackoverflow.com/a/398120/376773 - typeof window !== "undefined" && window.console && (window.console.firebug || window.console.exception && window.console.table) || // Is firefox >= v31? - // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages - typeof navigator !== "undefined" && navigator.userAgent && (m = navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/)) && parseInt(m[1], 10) >= 31 || // Double check webkit in userAgent just in case we are in a worker - typeof navigator !== "undefined" && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/); - } - function formatArgs(args) { - args[0] = (this.useColors ? "%c" : "") + this.namespace + (this.useColors ? " %c" : " ") + args[0] + (this.useColors ? "%c " : " ") + "+" + module.exports.humanize(this.diff); - if (!this.useColors) { - return; - } - const c = "color: " + this.color; - args.splice(1, 0, c, "color: inherit"); - let index = 0; - let lastC = 0; - args[0].replace(/%[a-zA-Z%]/g, (match) => { - if (match === "%%") { - return; - } - index++; - if (match === "%c") { - lastC = index; - } - }); - args.splice(lastC, 0, c); - } - exports.log = console.debug || console.log || (() => { - }); - function save(namespaces) { - try { - if (namespaces) { - exports.storage.setItem("debug", namespaces); - } else { - exports.storage.removeItem("debug"); - } - } catch (error) { - } - } - function load() { - let r; - try { - r = exports.storage.getItem("debug") || exports.storage.getItem("DEBUG"); - } catch (error) { - } - if (!r && typeof process !== "undefined" && "env" in process) { - r = process.env.DEBUG; - } - return r; - } - function localstorage() { - try { - return localStorage; - } catch (error) { - } - } - module.exports = require_common()(exports); - var { formatters } = module.exports; - formatters.j = function(v) { - try { - return JSON.stringify(v); - } catch (error) { - return "[UnexpectedJSONParseError]: " + error.message; - } - }; - } -}); - -// node_modules/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 min2 = instance.outputLen; - if (out.length < min2) { - throw new Error(`digestInto() expects output buffer of length at least ${min2}`); - } -} - -// node_modules/nostr-tools/node_modules/@noble/curves/node_modules/@noble/hashes/esm/crypto.js -var crypto = typeof globalThis === "object" && "crypto" in globalThis ? globalThis.crypto : void 0; - -// node_modules/nostr-tools/node_modules/@noble/curves/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 }, (_, i2) => i2.toString(16).padStart(2, "0")); -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 pad2 = 0; - arrays.forEach((a) => { - if (!u8a(a)) - throw new Error("Uint8Array expected"); - r.set(a, pad2); - pad2 += a.length; - }); - return r; -} -var Hash = class { - // Safe version that clones internal state - clone() { - return this._cloneInto(); - } -}; -var toStr = {}.toString; -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; -} -function randomBytes(bytesLength = 32) { - if (crypto && typeof crypto.getRandomValues === "function") { - return crypto.getRandomValues(new Uint8Array(bytesLength)); - } - throw new Error("crypto.getRandomValues must be defined"); -} - -// node_modules/nostr-tools/node_modules/@noble/curves/node_modules/@noble/hashes/esm/_sha2.js -function setBigUint64(view, byteOffset, value, isLE5) { - if (typeof view.setBigUint64 === "function") - return view.setBigUint64(byteOffset, value, isLE5); - const _32n = BigInt(32); - const _u32_max = BigInt(4294967295); - const wh = Number(value >> _32n & _u32_max); - const wl = Number(value & _u32_max); - const h = isLE5 ? 4 : 0; - const l = isLE5 ? 0 : 4; - view.setUint32(byteOffset + h, wh, isLE5); - view.setUint32(byteOffset + l, wl, isLE5); -} -var SHA2 = class extends Hash { - constructor(blockLen, outputLen, padOffset, isLE5) { - super(); - this.blockLen = blockLen; - this.outputLen = outputLen; - this.padOffset = padOffset; - this.isLE = isLE5; - this.finished = false; - this.length = 0; - this.pos = 0; - this.destroyed = false; - this.buffer = new Uint8Array(blockLen); - this.view = createView(this.buffer); - } - update(data) { - exists(this); - const { view, buffer: buffer2, blockLen } = this; - data = toBytes(data); - const len = data.length; - for (let pos = 0; pos < len; ) { - const take2 = Math.min(blockLen - this.pos, len - pos); - if (take2 === blockLen) { - const dataView = createView(data); - for (; blockLen <= len - pos; pos += blockLen) - this.process(dataView, pos); - continue; - } - buffer2.set(data.subarray(pos, pos + take2), this.pos); - this.pos += take2; - pos += take2; - 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: buffer2, view, blockLen, isLE: isLE5 } = this; - let { pos } = this; - buffer2[pos++] = 128; - this.buffer.subarray(pos).fill(0); - if (this.padOffset > blockLen - pos) { - this.process(view, 0); - pos = 0; - } - for (let i2 = pos; i2 < blockLen; i2++) - buffer2[i2] = 0; - setBigUint64(view, blockLen - 8, BigInt(this.length * 8), isLE5); - this.process(view, 0); - const oview = createView(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 i2 = 0; i2 < outLen; i2++) - oview.setUint32(4 * i2, state[i2], isLE5); - } - digest() { - const { buffer: buffer2, outputLen } = this; - this.digestInto(buffer2); - const res = buffer2.slice(0, outputLen); - this.destroy(); - return res; - } - _cloneInto(to) { - to || (to = new this.constructor()); - to.set(...this.get()); - const { blockLen, buffer: buffer2, length, finished, destroyed, pos } = this; - to.length = length; - to.pos = pos; - to.finished = finished; - to.destroyed = destroyed; - if (length % blockLen) - to.buffer.set(buffer2); - return to; - } -}; - -// node_modules/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 = 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 = new Uint32Array([ - 1779033703, - 3144134277, - 1013904242, - 2773480762, - 1359893119, - 2600822924, - 528734635, - 1541459225 -]); -var SHA256_W = 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]; - } - // prettier-ignore - 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 i2 = 0; i2 < 16; i2++, offset += 4) - SHA256_W[i2] = view.getUint32(offset, false); - for (let i2 = 16; i2 < 64; i2++) { - const W15 = SHA256_W[i2 - 15]; - const W2 = SHA256_W[i2 - 2]; - const s0 = rotr(W15, 7) ^ rotr(W15, 18) ^ W15 >>> 3; - const s1 = rotr(W2, 17) ^ rotr(W2, 19) ^ W2 >>> 10; - SHA256_W[i2] = s1 + SHA256_W[i2 - 7] + s0 + SHA256_W[i2 - 16] | 0; - } - let { A, B, C, D, E, F, G, H } = this; - for (let i2 = 0; i2 < 64; i2++) { - const sigma1 = rotr(E, 6) ^ rotr(E, 11) ^ rotr(E, 25); - const T1 = H + sigma1 + Chi(E, F, G) + SHA256_K[i2] + SHA256_W[i2] | 0; - const sigma0 = rotr(A, 2) ^ rotr(A, 13) ^ rotr(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 SHA224 = class extends SHA256 { - constructor() { - super(); - this.A = 3238371032 | 0; - this.B = 914150663 | 0; - this.C = 812702999 | 0; - this.D = 4144912697 | 0; - this.E = 4290775857 | 0; - this.F = 1750603025 | 0; - this.G = 1694076839 | 0; - this.H = 3204075428 | 0; - this.outputLen = 28; - } -}; -var sha256 = wrapConstructor(() => new SHA256()); -var sha224 = wrapConstructor(() => new SHA224()); - -// node_modules/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: () => bytesToHex, - bytesToNumberBE: () => bytesToNumberBE, - bytesToNumberLE: () => bytesToNumberLE, - concatBytes: () => concatBytes2, - createHmacDrbg: () => createHmacDrbg, - ensureBytes: () => ensureBytes, - equalBytes: () => equalBytes, - hexToBytes: () => hexToBytes, - hexToNumber: () => hexToNumber, - numberToBytesBE: () => numberToBytesBE, - numberToBytesLE: () => numberToBytesLE, - numberToHexUnpadded: () => numberToHexUnpadded, - numberToVarBytesBE: () => numberToVarBytesBE, - utf8ToBytes: () => utf8ToBytes2, - validateObject: () => validateObject -}); -var _0n = BigInt(0); -var _1n = BigInt(1); -var _2n = BigInt(2); -var u8a2 = (a) => a instanceof Uint8Array; -var hexes2 = Array.from({ length: 256 }, (_, i2) => i2.toString(16).padStart(2, "0")); -function bytesToHex(bytes4) { - if (!u8a2(bytes4)) - throw new Error("Uint8Array expected"); - let hex3 = ""; - for (let i2 = 0; i2 < bytes4.length; i2++) { - hex3 += hexes2[bytes4[i2]]; - } - return hex3; -} -function numberToHexUnpadded(num) { - const hex3 = num.toString(16); - return hex3.length & 1 ? `0${hex3}` : hex3; -} -function hexToNumber(hex3) { - if (typeof hex3 !== "string") - throw new Error("hex string expected, got " + typeof hex3); - return BigInt(hex3 === "" ? "0" : `0x${hex3}`); -} -function hexToBytes(hex3) { - if (typeof hex3 !== "string") - throw new Error("hex string expected, got " + typeof hex3); - const len = hex3.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 i2 = 0; i2 < array.length; i2++) { - const j = i2 * 2; - const hexByte = hex3.slice(j, j + 2); - const byte = Number.parseInt(hexByte, 16); - if (Number.isNaN(byte) || byte < 0) - throw new Error("Invalid byte sequence"); - array[i2] = byte; - } - return array; -} -function bytesToNumberBE(bytes4) { - return hexToNumber(bytesToHex(bytes4)); -} -function bytesToNumberLE(bytes4) { - if (!u8a2(bytes4)) - throw new Error("Uint8Array expected"); - return hexToNumber(bytesToHex(Uint8Array.from(bytes4).reverse())); -} -function numberToBytesBE(n, len) { - return hexToBytes(n.toString(16).padStart(len * 2, "0")); -} -function numberToBytesLE(n, len) { - return numberToBytesBE(n, len).reverse(); -} -function numberToVarBytesBE(n) { - return hexToBytes(numberToHexUnpadded(n)); -} -function ensureBytes(title, hex3, expectedLength) { - let res; - if (typeof hex3 === "string") { - try { - res = hexToBytes(hex3); - } catch (e) { - throw new Error(`${title} must be valid hex string, got "${hex3}". Cause: ${e}`); - } - } else if (u8a2(hex3)) { - res = Uint8Array.from(hex3); - } 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 concatBytes2(...arrays) { - const r = new Uint8Array(arrays.reduce((sum, a) => sum + a.length, 0)); - let pad2 = 0; - arrays.forEach((a) => { - if (!u8a2(a)) - throw new Error("Uint8Array expected"); - r.set(a, pad2); - pad2 += a.length; - }); - return r; -} -function equalBytes(b1, b2) { - if (b1.length !== b2.length) - return false; - for (let i2 = 0; i2 < b1.length; i2++) - if (b1[i2] !== b2[i2]) - return false; - return true; -} -function utf8ToBytes2(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 i2 = 0; - const reset = () => { - v.fill(1); - k.fill(0); - i2 = 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 (i2++ >= 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 concatBytes2(...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; -} - -// node_modules/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 + result; -} -function pow(num, power, modulo) { - if (modulo <= _0n2 || power < _0n2) - throw new Error("Expected power/modulo > 0"); - if (modulo === _1n2) - return _0n2; - let res = _1n2; - while (power > _0n2) { - if (power & _1n2) - res = res * num % modulo; - num = num * num % modulo; - power >>= _1n2; - } - return res; -} -function pow2(x, power, modulo) { - let res = x; - while (power-- > _0n2) { - res *= res; - res %= modulo; - } - return res; -} -function invert(number4, modulo) { - if (number4 === _0n2 || modulo <= _0n2) { - throw new Error(`invert: expected positive integers, got n=${number4} mod=${modulo}`); - } - let a = mod(number4, modulo); - let b = modulo; - let x = _0n2, y = _1n2, u = _1n2, v = _0n2; - while (a !== _0n2) { - const q = b / a; - const r = b % a; - const m = x - u * q; - const n = y - v * q; - b = a, a = r, x = u, y = v, u = m, v = n; - } - const gcd3 = b; - if (gcd3 !== _1n2) - throw new Error("invert: does not exist"); - return mod(x, modulo); -} -function tonelliShanks(P) { - const legendreC = (P - _1n2) / _2n2; - let Q, S, Z; - for (Q = P - _1n2, S = 0; Q % _2n2 === _0n2; Q /= _2n2, S++) - ; - for (Z = _2n2; Z < P && pow(Z, legendreC, P) !== P - _1n2; Z++) - ; - if (S === 1) { - const p1div4 = (P + _1n2) / _4n; - return function tonelliFast(Fp2, n) { - const root = Fp2.pow(n, p1div4); - if (!Fp2.eql(Fp2.sqr(root), n)) - throw new Error("Cannot find square root"); - return root; - }; - } - const Q1div2 = (Q + _1n2) / _2n2; - return function tonelliSlow(Fp2, n) { - if (Fp2.pow(n, legendreC) === Fp2.neg(Fp2.ONE)) - throw new Error("Cannot find square root"); - let r = S; - let g = Fp2.pow(Fp2.mul(Fp2.ONE, Z), Q); - let x = Fp2.pow(n, Q1div2); - let b = Fp2.pow(n, Q); - while (!Fp2.eql(b, Fp2.ONE)) { - if (Fp2.eql(b, Fp2.ZERO)) - return Fp2.ZERO; - let m = 1; - for (let t2 = Fp2.sqr(b); m < r; m++) { - if (Fp2.eql(t2, Fp2.ONE)) - break; - t2 = Fp2.sqr(t2); - } - const ge2 = Fp2.pow(g, _1n2 << BigInt(r - m - 1)); - g = Fp2.sqr(ge2); - x = Fp2.mul(x, ge2); - b = Fp2.mul(b, g); - r = m; - } - return x; - }; -} -function FpSqrt(P) { - if (P % _4n === _3n) { - const p1div4 = (P + _1n2) / _4n; - return function sqrt3mod4(Fp2, n) { - const root = Fp2.pow(n, p1div4); - if (!Fp2.eql(Fp2.sqr(root), n)) - throw new Error("Cannot find square root"); - return root; - }; - } - if (P % _8n === _5n) { - const c1 = (P - _5n) / _8n; - return function sqrt5mod8(Fp2, n) { - const n2 = Fp2.mul(n, _2n2); - const v = Fp2.pow(n2, c1); - const nv = Fp2.mul(n, v); - const i2 = Fp2.mul(Fp2.mul(nv, _2n2), v); - const root = Fp2.mul(nv, Fp2.sub(i2, Fp2.ONE)); - if (!Fp2.eql(Fp2.sqr(root), n)) - throw new Error("Cannot find square root"); - return root; - }; - } - if (P % _16n === _9n) { - } - return tonelliShanks(P); -} -var FIELD_FIELDS = [ - "create", - "isValid", - "is0", - "neg", - "inv", - "sqrt", - "sqr", - "eql", - "add", - "sub", - "mul", - "pow", - "div", - "addN", - "subN", - "mulN", - "sqrN" -]; -function validateField(field) { - const initial = { - ORDER: "bigint", - MASK: "bigint", - BYTES: "isSafeInteger", - BITS: "isSafeInteger" - }; - const opts = FIELD_FIELDS.reduce((map2, val) => { - map2[val] = "function"; - return map2; - }, initial); - return validateObject(field, opts); -} -function FpPow(f, num, power) { - if (power < _0n2) - throw new Error("Expected power > 0"); - if (power === _0n2) - return f.ONE; - if (power === _1n2) - return num; - let p = f.ONE; - let d = num; - while (power > _0n2) { - if (power & _1n2) - p = f.mul(p, d); - d = f.sqr(d); - power >>= _1n2; - } - return p; -} -function FpInvertBatch(f, nums) { - const tmp = new Array(nums.length); - const lastMultiplied = nums.reduce((acc, num, i2) => { - if (f.is0(num)) - return acc; - tmp[i2] = acc; - return f.mul(acc, num); - }, f.ONE); - const inverted = f.inv(lastMultiplied); - nums.reduceRight((acc, num, i2) => { - if (f.is0(num)) - return acc; - tmp[i2] = f.mul(acc, tmp[i2]); - return f.mul(acc, num); - }, inverted); - return tmp; -} -function nLength(n, nBitLength) { - const _nBitLength = nBitLength !== void 0 ? nBitLength : n.toString(2).length; - const nByteLength = Math.ceil(_nBitLength / 8); - return { nBitLength: _nBitLength, nByteLength }; -} -function Field(ORDER, bitLen2, isLE5 = false, redef = {}) { - if (ORDER <= _0n2) - throw new Error(`Expected Field ORDER > 0, got ${ORDER}`); - const { nBitLength: BITS, nByteLength: BYTES } = nLength(ORDER, bitLen2); - if (BYTES > 2048) - throw new Error("Field lengths over 2048 bytes are not supported"); - const sqrtP = FpSqrt(ORDER); - const f = Object.freeze({ - ORDER, - BITS, - BYTES, - MASK: bitMask(BITS), - ZERO: _0n2, - ONE: _1n2, - create: (num) => mod(num, ORDER), - isValid: (num) => { - if (typeof num !== "bigint") - throw new Error(`Invalid field element: expected bigint, got ${typeof num}`); - return _0n2 <= num && num < ORDER; - }, - is0: (num) => num === _0n2, - isOdd: (num) => (num & _1n2) === _1n2, - neg: (num) => mod(-num, ORDER), - eql: (lhs, rhs) => lhs === rhs, - sqr: (num) => mod(num * num, ORDER), - add: (lhs, rhs) => mod(lhs + rhs, ORDER), - sub: (lhs, rhs) => mod(lhs - rhs, ORDER), - mul: (lhs, rhs) => mod(lhs * rhs, ORDER), - pow: (num, power) => FpPow(f, num, power), - div: (lhs, rhs) => mod(lhs * invert(rhs, ORDER), ORDER), - // Same as above, but doesn't normalize - sqrN: (num) => num * num, - addN: (lhs, rhs) => lhs + rhs, - subN: (lhs, rhs) => lhs - rhs, - mulN: (lhs, rhs) => lhs * rhs, - inv: (num) => invert(num, ORDER), - sqrt: redef.sqrt || ((n) => sqrtP(f, n)), - invertBatch: (lst) => FpInvertBatch(f, lst), - // TODO: do we really need constant cmov? - // We don't have const-time bigints anyway, so probably will be not very useful - cmov: (a, b, c) => c ? b : a, - toBytes: (num) => isLE5 ? numberToBytesLE(num, BYTES) : numberToBytesBE(num, BYTES), - fromBytes: (bytes4) => { - if (bytes4.length !== BYTES) - throw new Error(`Fp.fromBytes: expected ${BYTES}, got ${bytes4.length}`); - return isLE5 ? bytesToNumberLE(bytes4) : bytesToNumberBE(bytes4); - } - }); - return Object.freeze(f); -} -function getFieldBytesLength(fieldOrder) { - if (typeof fieldOrder !== "bigint") - throw new Error("field order must be bigint"); - const bitLength = fieldOrder.toString(2).length; - return Math.ceil(bitLength / 8); -} -function getMinHashLength(fieldOrder) { - const length = getFieldBytesLength(fieldOrder); - return length + Math.ceil(length / 2); -} -function mapHashToField(key, fieldOrder, isLE5 = false) { - const len = key.length; - const fieldLen = getFieldBytesLength(fieldOrder); - const minLen = getMinHashLength(fieldOrder); - if (len < 16 || len < minLen || len > 1024) - throw new Error(`expected ${minLen}-1024 bytes of input, got ${len}`); - const num = isLE5 ? bytesToNumberBE(key) : bytesToNumberLE(key); - const reduced = mod(num, fieldOrder - _1n2) + _1n2; - return isLE5 ? numberToBytesLE(reduced, fieldLen) : numberToBytesBE(reduced, fieldLen); -} - -// node_modules/nostr-tools/node_modules/@noble/curves/esm/abstract/curve.js -var _0n3 = BigInt(0); -var _1n3 = BigInt(1); -function wNAF(c, bits) { - const constTimeNegate = (condition, item) => { - const neg = item.negate(); - return condition ? neg : item; - }; - const opts = (W) => { - const windows = Math.ceil(bits / W) + 1; - const windowSize = 2 ** (W - 1); - return { windows, windowSize }; - }; - return { - constTimeNegate, - // non-const time multiplication ladder - unsafeLadder(elm, n) { - let p = c.ZERO; - let d = elm; - while (n > _0n3) { - if (n & _1n3) - p = p.add(d); - d = d.double(); - n >>= _1n3; - } - return p; - }, - /** - * Creates a wNAF precomputation window. Used for caching. - * Default window size is set by `utils.precompute()` and is equal to 8. - * Number of precomputed points depends on the curve size: - * 2^(𝑊−1) * (Math.ceil(𝑛 / 𝑊) + 1), where: - * - 𝑊 is the window size - * - 𝑛 is the bitlength of the curve order. - * For a 256-bit curve and window size 8, the number of precomputed points is 128 * 33 = 4224. - * @returns precomputed point tables flattened to a single array - */ - precomputeWindow(elm, W) { - const { windows, windowSize } = opts(W); - const points = []; - let p = elm; - let base = p; - for (let window3 = 0; window3 < windows; window3++) { - base = p; - points.push(base); - for (let i2 = 1; i2 < windowSize; i2++) { - base = base.add(p); - points.push(base); - } - p = base.double(); - } - return points; - }, - /** - * Implements ec multiplication using precomputed tables and w-ary non-adjacent form. - * @param W window size - * @param precomputes precomputed tables - * @param n scalar (we don't check here, but should be less than curve order) - * @returns real and fake (for const-time) points - */ - wNAF(W, precomputes, n) { - const { windows, windowSize } = opts(W); - let p = c.ZERO; - let f = c.BASE; - const mask = BigInt(2 ** W - 1); - const maxNumber = 2 ** W; - const shiftBy = BigInt(W); - for (let window3 = 0; window3 < windows; window3++) { - const offset = window3 * windowSize; - let wbits = Number(n & mask); - n >>= shiftBy; - if (wbits > windowSize) { - wbits -= maxNumber; - n += _1n3; - } - const offset1 = offset; - const offset2 = offset + Math.abs(wbits) - 1; - const cond1 = window3 % 2 !== 0; - const cond2 = wbits < 0; - if (wbits === 0) { - f = f.add(constTimeNegate(cond1, precomputes[offset1])); - } else { - p = p.add(constTimeNegate(cond2, precomputes[offset2])); - } - } - return { p, f }; - }, - wNAFCached(P, precomputesMap, n, transform) { - const W = P._WINDOW_SIZE || 1; - let comp = precomputesMap.get(P); - if (!comp) { - comp = this.precomputeWindow(P, W); - if (W !== 1) { - precomputesMap.set(P, transform(comp)); - } - } - return this.wNAF(W, comp, n); - } - }; -} -function validateBasic(curve) { - validateField(curve.Fp); - validateObject(curve, { - n: "bigint", - h: "bigint", - Gx: "field", - Gy: "field" - }, { - nBitLength: "isSafeInteger", - nByteLength: "isSafeInteger" - }); - return Object.freeze({ - ...nLength(curve.n, curve.nBitLength), - ...curve, - ...{ p: curve.Fp.ORDER } - }); -} - -// node_modules/nostr-tools/node_modules/@noble/curves/esm/abstract/weierstrass.js -function validatePointOpts(curve) { - const opts = validateBasic(curve); - validateObject(opts, { - a: "field", - b: "field" - }, { - allowedPrivateKeyLengths: "array", - wrapPrivateKey: "boolean", - isTorsionFree: "function", - clearCofactor: "function", - allowInfinityPoint: "boolean", - fromBytes: "function", - toBytes: "function" - }); - const { endo, Fp: Fp2, a } = opts; - if (endo) { - if (!Fp2.eql(a, Fp2.ZERO)) { - throw new Error("Endomorphism can only be defined for Koblitz curves that have a=0"); - } - if (typeof endo !== "object" || typeof endo.beta !== "bigint" || typeof endo.splitScalar !== "function") { - throw new Error("Expected endomorphism with beta: bigint and splitScalar: function"); - } - } - return Object.freeze({ ...opts }); -} -var { bytesToNumberBE: b2n, hexToBytes: h2b } = utils_exports; -var DER = { - // asn.1 DER encoding utils - Err: class DERErr extends Error { - constructor(m = "") { - super(m); - } - }, - _parseInt(data) { - const { Err: E } = DER; - if (data.length < 2 || data[0] !== 2) - throw new E("Invalid signature integer tag"); - const len = data[1]; - const res = data.subarray(2, len + 2); - if (!len || res.length !== len) - throw new E("Invalid signature integer: wrong length"); - if (res[0] & 128) - throw new E("Invalid signature integer: negative"); - if (res[0] === 0 && !(res[1] & 128)) - throw new E("Invalid signature integer: unnecessary leading zero"); - return { d: b2n(res), l: data.subarray(len + 2) }; - }, - toSig(hex3) { - const { Err: E } = DER; - const data = typeof hex3 === "string" ? h2b(hex3) : hex3; - if (!(data instanceof Uint8Array)) - throw new Error("ui8a expected"); - let l = data.length; - if (l < 2 || data[0] != 48) - throw new E("Invalid signature tag"); - if (data[1] !== l - 2) - throw new E("Invalid signature: incorrect length"); - const { d: r, l: sBytes } = DER._parseInt(data.subarray(2)); - const { d: s, l: rBytesLeft } = DER._parseInt(sBytes); - if (rBytesLeft.length) - throw new E("Invalid signature: left bytes after parsing"); - return { r, s }; - }, - hexFromSig(sig) { - const slice = (s2) => Number.parseInt(s2[0], 16) & 8 ? "00" + s2 : s2; - const h = (num) => { - const hex3 = num.toString(16); - return hex3.length & 1 ? `0${hex3}` : hex3; - }; - const s = slice(h(sig.s)); - const r = slice(h(sig.r)); - const shl = s.length / 2; - const rhl = r.length / 2; - const sl = h(shl); - const rl = h(rhl); - return `30${h(rhl + shl + 4)}02${rl}${r}02${sl}${s}`; - } -}; -var _0n4 = BigInt(0); -var _1n4 = BigInt(1); -var _2n3 = BigInt(2); -var _3n2 = BigInt(3); -var _4n2 = BigInt(4); -function weierstrassPoints(opts) { - const CURVE = validatePointOpts(opts); - const { Fp: Fp2 } = CURVE; - const toBytes5 = CURVE.toBytes || ((_c, point, _isCompressed) => { - const a = point.toAffine(); - return concatBytes2(Uint8Array.from([4]), Fp2.toBytes(a.x), Fp2.toBytes(a.y)); - }); - const fromBytes = CURVE.fromBytes || ((bytes4) => { - const tail = bytes4.subarray(1); - const x = Fp2.fromBytes(tail.subarray(0, Fp2.BYTES)); - const y = Fp2.fromBytes(tail.subarray(Fp2.BYTES, 2 * Fp2.BYTES)); - return { x, y }; - }); - function weierstrassEquation(x) { - const { a, b } = CURVE; - const x2 = Fp2.sqr(x); - const x3 = Fp2.mul(x2, x); - return Fp2.add(Fp2.add(x3, Fp2.mul(x, a)), b); - } - if (!Fp2.eql(Fp2.sqr(CURVE.Gy), weierstrassEquation(CURVE.Gx))) - throw new Error("bad generator point: equation left != right"); - function isWithinCurveOrder(num) { - return typeof num === "bigint" && _0n4 < num && num < CURVE.n; - } - function assertGE(num) { - if (!isWithinCurveOrder(num)) - throw new Error("Expected valid bigint: 0 < bigint < curve.n"); - } - function normPrivateKeyToScalar(key) { - const { allowedPrivateKeyLengths: lengths, nByteLength, wrapPrivateKey, n } = CURVE; - if (lengths && typeof key !== "bigint") { - if (key instanceof Uint8Array) - key = bytesToHex(key); - if (typeof key !== "string" || !lengths.includes(key.length)) - throw new Error("Invalid key"); - key = key.padStart(nByteLength * 2, "0"); - } - let num; - try { - num = typeof key === "bigint" ? key : bytesToNumberBE(ensureBytes("private key", key, nByteLength)); - } catch (error) { - throw new Error(`private key must be ${nByteLength} bytes, hex or bigint, not ${typeof key}`); - } - if (wrapPrivateKey) - num = mod(num, n); - assertGE(num); - return num; - } - const pointPrecomputes = /* @__PURE__ */ new Map(); - function assertPrjPoint(other) { - if (!(other instanceof Point2)) - throw new Error("ProjectivePoint expected"); - } - class Point2 { - constructor(px, py, pz) { - this.px = px; - this.py = py; - this.pz = pz; - if (px == null || !Fp2.isValid(px)) - throw new Error("x required"); - if (py == null || !Fp2.isValid(py)) - throw new Error("y required"); - if (pz == null || !Fp2.isValid(pz)) - throw new Error("z required"); - } - // Does not validate if the point is on-curve. - // Use fromHex instead, or call assertValidity() later. - static fromAffine(p) { - const { x, y } = p || {}; - if (!p || !Fp2.isValid(x) || !Fp2.isValid(y)) - throw new Error("invalid affine point"); - if (p instanceof Point2) - throw new Error("projective point not allowed"); - const is0 = (i2) => Fp2.eql(i2, Fp2.ZERO); - if (is0(x) && is0(y)) - return Point2.ZERO; - return new Point2(x, y, Fp2.ONE); - } - get x() { - return this.toAffine().x; - } - get y() { - return this.toAffine().y; - } - /** - * Takes a bunch of Projective Points but executes only one - * inversion on all of them. Inversion is very slow operation, - * so this improves performance massively. - * Optimization: converts a list of projective points to a list of identical points with Z=1. - */ - static normalizeZ(points) { - const toInv = Fp2.invertBatch(points.map((p) => p.pz)); - return points.map((p, i2) => p.toAffine(toInv[i2])).map(Point2.fromAffine); - } - /** - * Converts hash string or Uint8Array to Point. - * @param hex short/long ECDSA hex - */ - static fromHex(hex3) { - const P = Point2.fromAffine(fromBytes(ensureBytes("pointHex", hex3))); - P.assertValidity(); - return P; - } - // Multiplies generator point by privateKey. - static fromPrivateKey(privateKey) { - return Point2.BASE.multiply(normPrivateKeyToScalar(privateKey)); - } - // "Private method", don't use it directly - _setWindowSize(windowSize) { - this._WINDOW_SIZE = windowSize; - pointPrecomputes.delete(this); - } - // A point on curve is valid if it conforms to equation. - assertValidity() { - if (this.is0()) { - if (CURVE.allowInfinityPoint && !Fp2.is0(this.py)) - return; - throw new Error("bad point: ZERO"); - } - const { x, y } = this.toAffine(); - if (!Fp2.isValid(x) || !Fp2.isValid(y)) - throw new Error("bad point: x or y not FE"); - const left = Fp2.sqr(y); - const right = weierstrassEquation(x); - if (!Fp2.eql(left, right)) - throw new Error("bad point: equation left != right"); - if (!this.isTorsionFree()) - throw new Error("bad point: not in prime-order subgroup"); - } - hasEvenY() { - const { y } = this.toAffine(); - if (Fp2.isOdd) - return !Fp2.isOdd(y); - throw new Error("Field doesn't support isOdd"); - } - /** - * Compare one point to another. - */ - equals(other) { - assertPrjPoint(other); - const { px: X1, py: Y1, pz: Z1 } = this; - const { px: X2, py: Y2, pz: Z2 } = other; - const U1 = Fp2.eql(Fp2.mul(X1, Z2), Fp2.mul(X2, Z1)); - const U2 = Fp2.eql(Fp2.mul(Y1, Z2), Fp2.mul(Y2, Z1)); - return U1 && U2; - } - /** - * Flips point to one corresponding to (x, -y) in Affine coordinates. - */ - negate() { - return new Point2(this.px, Fp2.neg(this.py), this.pz); - } - // Renes-Costello-Batina exception-free doubling formula. - // There is 30% faster Jacobian formula, but it is not complete. - // https://eprint.iacr.org/2015/1060, algorithm 3 - // Cost: 8M + 3S + 3*a + 2*b3 + 15add. - double() { - const { a, b } = CURVE; - const b3 = Fp2.mul(b, _3n2); - const { px: X1, py: Y1, pz: Z1 } = this; - let X3 = Fp2.ZERO, Y3 = Fp2.ZERO, Z3 = Fp2.ZERO; - let t0 = Fp2.mul(X1, X1); - let t1 = Fp2.mul(Y1, Y1); - let t2 = Fp2.mul(Z1, Z1); - let t3 = Fp2.mul(X1, Y1); - t3 = Fp2.add(t3, t3); - Z3 = Fp2.mul(X1, Z1); - Z3 = Fp2.add(Z3, Z3); - X3 = Fp2.mul(a, Z3); - Y3 = Fp2.mul(b3, t2); - Y3 = Fp2.add(X3, Y3); - X3 = Fp2.sub(t1, Y3); - Y3 = Fp2.add(t1, Y3); - Y3 = Fp2.mul(X3, Y3); - X3 = Fp2.mul(t3, X3); - Z3 = Fp2.mul(b3, Z3); - t2 = Fp2.mul(a, t2); - t3 = Fp2.sub(t0, t2); - t3 = Fp2.mul(a, t3); - t3 = Fp2.add(t3, Z3); - Z3 = Fp2.add(t0, t0); - t0 = Fp2.add(Z3, t0); - t0 = Fp2.add(t0, t2); - t0 = Fp2.mul(t0, t3); - Y3 = Fp2.add(Y3, t0); - t2 = Fp2.mul(Y1, Z1); - t2 = Fp2.add(t2, t2); - t0 = Fp2.mul(t2, t3); - X3 = Fp2.sub(X3, t0); - Z3 = Fp2.mul(t2, t1); - Z3 = Fp2.add(Z3, Z3); - Z3 = Fp2.add(Z3, Z3); - return new Point2(X3, Y3, Z3); - } - // Renes-Costello-Batina exception-free addition formula. - // There is 30% faster Jacobian formula, but it is not complete. - // https://eprint.iacr.org/2015/1060, algorithm 1 - // Cost: 12M + 0S + 3*a + 3*b3 + 23add. - add(other) { - assertPrjPoint(other); - const { px: X1, py: Y1, pz: Z1 } = this; - const { px: X2, py: Y2, pz: Z2 } = other; - let X3 = Fp2.ZERO, Y3 = Fp2.ZERO, Z3 = Fp2.ZERO; - const a = CURVE.a; - const b3 = Fp2.mul(CURVE.b, _3n2); - let t0 = Fp2.mul(X1, X2); - let t1 = Fp2.mul(Y1, Y2); - let t2 = Fp2.mul(Z1, Z2); - let t3 = Fp2.add(X1, Y1); - let t4 = Fp2.add(X2, Y2); - t3 = Fp2.mul(t3, t4); - t4 = Fp2.add(t0, t1); - t3 = Fp2.sub(t3, t4); - t4 = Fp2.add(X1, Z1); - let t5 = Fp2.add(X2, Z2); - t4 = Fp2.mul(t4, t5); - t5 = Fp2.add(t0, t2); - t4 = Fp2.sub(t4, t5); - t5 = Fp2.add(Y1, Z1); - X3 = Fp2.add(Y2, Z2); - t5 = Fp2.mul(t5, X3); - X3 = Fp2.add(t1, t2); - t5 = Fp2.sub(t5, X3); - Z3 = Fp2.mul(a, t4); - X3 = Fp2.mul(b3, t2); - Z3 = Fp2.add(X3, Z3); - X3 = Fp2.sub(t1, Z3); - Z3 = Fp2.add(t1, Z3); - Y3 = Fp2.mul(X3, Z3); - t1 = Fp2.add(t0, t0); - t1 = Fp2.add(t1, t0); - t2 = Fp2.mul(a, t2); - t4 = Fp2.mul(b3, t4); - t1 = Fp2.add(t1, t2); - t2 = Fp2.sub(t0, t2); - t2 = Fp2.mul(a, t2); - t4 = Fp2.add(t4, t2); - t0 = Fp2.mul(t1, t4); - Y3 = Fp2.add(Y3, t0); - t0 = Fp2.mul(t5, t4); - X3 = Fp2.mul(t3, X3); - X3 = Fp2.sub(X3, t0); - t0 = Fp2.mul(t3, t1); - Z3 = Fp2.mul(t5, Z3); - Z3 = Fp2.add(Z3, t0); - return new Point2(X3, Y3, Z3); - } - subtract(other) { - return this.add(other.negate()); - } - is0() { - return this.equals(Point2.ZERO); - } - wNAF(n) { - return wnaf.wNAFCached(this, pointPrecomputes, n, (comp) => { - const toInv = Fp2.invertBatch(comp.map((p) => p.pz)); - return comp.map((p, i2) => p.toAffine(toInv[i2])).map(Point2.fromAffine); - }); - } - /** - * Non-constant-time multiplication. Uses double-and-add algorithm. - * It's faster, but should only be used when you don't care about - * an exposed private key e.g. sig verification, which works over *public* keys. - */ - multiplyUnsafe(n) { - const I = Point2.ZERO; - if (n === _0n4) - return I; - assertGE(n); - if (n === _1n4) - return this; - const { endo } = CURVE; - if (!endo) - return wnaf.unsafeLadder(this, n); - let { k1neg, k1, k2neg, k2 } = endo.splitScalar(n); - let k1p = I; - let k2p = I; - let d = this; - while (k1 > _0n4 || k2 > _0n4) { - if (k1 & _1n4) - k1p = k1p.add(d); - if (k2 & _1n4) - k2p = k2p.add(d); - d = d.double(); - k1 >>= _1n4; - k2 >>= _1n4; - } - if (k1neg) - k1p = k1p.negate(); - if (k2neg) - k2p = k2p.negate(); - k2p = new Point2(Fp2.mul(k2p.px, endo.beta), k2p.py, k2p.pz); - return k1p.add(k2p); - } - /** - * Constant time multiplication. - * Uses wNAF method. Windowed method may be 10% faster, - * but takes 2x longer to generate and consumes 2x memory. - * Uses precomputes when available. - * Uses endomorphism for Koblitz curves. - * @param scalar by which the point would be multiplied - * @returns New point - */ - multiply(scalar) { - assertGE(scalar); - let n = scalar; - let point, fake; - const { endo } = CURVE; - if (endo) { - const { k1neg, k1, k2neg, k2 } = endo.splitScalar(n); - let { p: k1p, f: f1p } = this.wNAF(k1); - let { p: k2p, f: f2p } = this.wNAF(k2); - k1p = wnaf.constTimeNegate(k1neg, k1p); - k2p = wnaf.constTimeNegate(k2neg, k2p); - k2p = new Point2(Fp2.mul(k2p.px, endo.beta), k2p.py, k2p.pz); - point = k1p.add(k2p); - fake = f1p.add(f2p); - } else { - const { p, f } = this.wNAF(n); - point = p; - fake = f; - } - return Point2.normalizeZ([point, fake])[0]; - } - /** - * Efficiently calculate `aP + bQ`. Unsafe, can expose private key, if used incorrectly. - * Not using Strauss-Shamir trick: precomputation tables are faster. - * The trick could be useful if both P and Q are not G (not in our case). - * @returns non-zero affine point - */ - multiplyAndAddUnsafe(Q, a, b) { - const G = Point2.BASE; - const mul3 = (P, a2) => a2 === _0n4 || a2 === _1n4 || !P.equals(G) ? P.multiplyUnsafe(a2) : P.multiply(a2); - const sum = mul3(this, a).add(mul3(Q, b)); - return sum.is0() ? void 0 : sum; - } - // Converts Projective point to affine (x, y) coordinates. - // Can accept precomputed Z^-1 - for example, from invertBatch. - // (x, y, z) ∋ (x=x/z, y=y/z) - toAffine(iz) { - const { px: x, py: y, pz: z } = this; - const is0 = this.is0(); - if (iz == null) - iz = is0 ? Fp2.ONE : Fp2.inv(z); - const ax = Fp2.mul(x, iz); - const ay = Fp2.mul(y, iz); - const zz = Fp2.mul(z, iz); - if (is0) - return { x: Fp2.ZERO, y: Fp2.ZERO }; - if (!Fp2.eql(zz, Fp2.ONE)) - throw new Error("invZ was invalid"); - return { x: ax, y: ay }; - } - isTorsionFree() { - const { h: cofactor, isTorsionFree } = CURVE; - if (cofactor === _1n4) - return true; - if (isTorsionFree) - return isTorsionFree(Point2, this); - throw new Error("isTorsionFree() has not been declared for the elliptic curve"); - } - clearCofactor() { - const { h: cofactor, clearCofactor } = CURVE; - if (cofactor === _1n4) - return this; - if (clearCofactor) - return clearCofactor(Point2, this); - return this.multiplyUnsafe(CURVE.h); - } - toRawBytes(isCompressed = true) { - this.assertValidity(); - return toBytes5(Point2, this, isCompressed); - } - toHex(isCompressed = true) { - return bytesToHex(this.toRawBytes(isCompressed)); - } - } - Point2.BASE = new Point2(CURVE.Gx, CURVE.Gy, Fp2.ONE); - Point2.ZERO = new Point2(Fp2.ZERO, Fp2.ONE, Fp2.ZERO); - const _bits = CURVE.nBitLength; - const wnaf = wNAF(Point2, CURVE.endo ? Math.ceil(_bits / 2) : _bits); - return { - CURVE, - ProjectivePoint: Point2, - normPrivateKeyToScalar, - weierstrassEquation, - isWithinCurveOrder - }; -} -function validateOpts(curve) { - const opts = validateBasic(curve); - validateObject(opts, { - hash: "hash", - hmac: "function", - randomBytes: "function" - }, { - bits2int: "function", - bits2int_modN: "function", - lowS: "boolean" - }); - return Object.freeze({ lowS: true, ...opts }); -} -function weierstrass(curveDef) { - const CURVE = validateOpts(curveDef); - const { Fp: Fp2, n: CURVE_ORDER } = CURVE; - const compressedLen = Fp2.BYTES + 1; - const uncompressedLen = 2 * Fp2.BYTES + 1; - function isValidFieldElement(num) { - return _0n4 < num && num < Fp2.ORDER; - } - function modN2(a) { - return mod(a, CURVE_ORDER); - } - function invN(a) { - return invert(a, CURVE_ORDER); - } - const { ProjectivePoint: Point2, normPrivateKeyToScalar, weierstrassEquation, isWithinCurveOrder } = weierstrassPoints({ - ...CURVE, - toBytes(_c, point, isCompressed) { - const a = point.toAffine(); - const x = Fp2.toBytes(a.x); - const cat = concatBytes2; - if (isCompressed) { - return cat(Uint8Array.from([point.hasEvenY() ? 2 : 3]), x); - } else { - return cat(Uint8Array.from([4]), x, Fp2.toBytes(a.y)); - } - }, - fromBytes(bytes4) { - const len = bytes4.length; - const head = bytes4[0]; - const tail = bytes4.subarray(1); - if (len === compressedLen && (head === 2 || head === 3)) { - const x = bytesToNumberBE(tail); - if (!isValidFieldElement(x)) - throw new Error("Point is not on curve"); - const y2 = weierstrassEquation(x); - let y = Fp2.sqrt(y2); - const isYOdd = (y & _1n4) === _1n4; - const isHeadOdd = (head & 1) === 1; - if (isHeadOdd !== isYOdd) - y = Fp2.neg(y); - return { x, y }; - } else if (len === uncompressedLen && head === 4) { - const x = Fp2.fromBytes(tail.subarray(0, Fp2.BYTES)); - const y = Fp2.fromBytes(tail.subarray(Fp2.BYTES, 2 * Fp2.BYTES)); - return { x, y }; - } else { - throw new Error(`Point of length ${len} was invalid. Expected ${compressedLen} compressed bytes or ${uncompressedLen} uncompressed bytes`); - } - } - }); - const numToNByteStr = (num) => bytesToHex(numberToBytesBE(num, CURVE.nByteLength)); - function isBiggerThanHalfOrder(number4) { - const HALF = CURVE_ORDER >> _1n4; - return number4 > HALF; - } - function normalizeS(s) { - return isBiggerThanHalfOrder(s) ? modN2(-s) : s; - } - const slcNum = (b, from2, to) => bytesToNumberBE(b.slice(from2, to)); - class Signature { - constructor(r, s, recovery) { - this.r = r; - this.s = s; - this.recovery = recovery; - this.assertValidity(); - } - // pair (bytes of r, bytes of s) - static fromCompact(hex3) { - const l = CURVE.nByteLength; - hex3 = ensureBytes("compactSignature", hex3, l * 2); - return new Signature(slcNum(hex3, 0, l), slcNum(hex3, l, 2 * l)); - } - // DER encoded ECDSA signature - // https://bitcoin.stackexchange.com/questions/57644/what-are-the-parts-of-a-bitcoin-transaction-input-script - static fromDER(hex3) { - const { r, s } = DER.toSig(ensureBytes("DER", hex3)); - return new Signature(r, s); - } - assertValidity() { - if (!isWithinCurveOrder(this.r)) - throw new Error("r must be 0 < r < CURVE.n"); - if (!isWithinCurveOrder(this.s)) - throw new Error("s must be 0 < s < CURVE.n"); - } - addRecoveryBit(recovery) { - return new Signature(this.r, this.s, recovery); - } - recoverPublicKey(msgHash) { - const { r, s, recovery: rec } = this; - const h = bits2int_modN(ensureBytes("msgHash", msgHash)); - if (rec == null || ![0, 1, 2, 3].includes(rec)) - throw new Error("recovery id invalid"); - const radj = rec === 2 || rec === 3 ? r + CURVE.n : r; - if (radj >= Fp2.ORDER) - throw new Error("recovery id 2 or 3 invalid"); - const prefix = (rec & 1) === 0 ? "02" : "03"; - const R = Point2.fromHex(prefix + numToNByteStr(radj)); - const ir = invN(radj); - const u1 = modN2(-h * ir); - const u2 = modN2(s * ir); - const Q = Point2.BASE.multiplyAndAddUnsafe(R, u1, u2); - if (!Q) - throw new Error("point at infinify"); - Q.assertValidity(); - return Q; - } - // Signatures should be low-s, to prevent malleability. - hasHighS() { - return isBiggerThanHalfOrder(this.s); - } - normalizeS() { - return this.hasHighS() ? new Signature(this.r, modN2(-this.s), this.recovery) : this; - } - // DER-encoded - toDERRawBytes() { - return hexToBytes(this.toDERHex()); - } - toDERHex() { - return DER.hexFromSig({ r: this.r, s: this.s }); - } - // padded bytes of r, then padded bytes of s - toCompactRawBytes() { - return hexToBytes(this.toCompactHex()); - } - toCompactHex() { - return numToNByteStr(this.r) + numToNByteStr(this.s); - } - } - const utils = { - isValidPrivateKey(privateKey) { - try { - normPrivateKeyToScalar(privateKey); - return true; - } catch (error) { - return false; - } - }, - normPrivateKeyToScalar, - /** - * Produces cryptographically secure private key from random of size - * (groupLen + ceil(groupLen / 2)) with modulo bias being negligible. - */ - randomPrivateKey: () => { - const length = getMinHashLength(CURVE.n); - return mapHashToField(CURVE.randomBytes(length), CURVE.n); - }, - /** - * Creates precompute table for an arbitrary EC point. Makes point "cached". - * Allows to massively speed-up `point.multiply(scalar)`. - * @returns cached point - * @example - * const fast = utils.precompute(8, ProjectivePoint.fromHex(someonesPubKey)); - * fast.multiply(privKey); // much faster ECDH now - */ - precompute(windowSize = 8, point = Point2.BASE) { - point._setWindowSize(windowSize); - point.multiply(BigInt(3)); - return point; - } - }; - function getPublicKey2(privateKey, isCompressed = true) { - return Point2.fromPrivateKey(privateKey).toRawBytes(isCompressed); - } - function isProbPub(item) { - const arr = item instanceof Uint8Array; - const str = typeof item === "string"; - const len = (arr || str) && item.length; - if (arr) - return len === compressedLen || len === uncompressedLen; - if (str) - return len === 2 * compressedLen || len === 2 * uncompressedLen; - if (item instanceof Point2) - return true; - return false; - } - function getSharedSecret(privateA, publicB, isCompressed = true) { - if (isProbPub(privateA)) - throw new Error("first arg must be private key"); - if (!isProbPub(publicB)) - throw new Error("second arg must be public key"); - const b = Point2.fromHex(publicB); - return b.multiply(normPrivateKeyToScalar(privateA)).toRawBytes(isCompressed); - } - const bits2int = CURVE.bits2int || function(bytes4) { - const num = bytesToNumberBE(bytes4); - const delta = bytes4.length * 8 - CURVE.nBitLength; - return delta > 0 ? num >> BigInt(delta) : num; - }; - const bits2int_modN = CURVE.bits2int_modN || function(bytes4) { - return modN2(bits2int(bytes4)); - }; - const ORDER_MASK = bitMask(CURVE.nBitLength); - function int2octets(num) { - if (typeof num !== "bigint") - throw new Error("bigint expected"); - if (!(_0n4 <= num && num < ORDER_MASK)) - throw new Error(`bigint expected < 2^${CURVE.nBitLength}`); - return numberToBytesBE(num, CURVE.nByteLength); - } - function prepSig(msgHash, privateKey, opts = defaultSigOpts) { - if (["recovered", "canonical"].some((k) => k in opts)) - throw new Error("sign() legacy options not supported"); - const { hash: hash3, randomBytes: randomBytes4 } = CURVE; - let { lowS, prehash, extraEntropy: ent } = opts; - if (lowS == null) - lowS = true; - msgHash = ensureBytes("msgHash", msgHash); - if (prehash) - msgHash = ensureBytes("prehashed msgHash", hash3(msgHash)); - const h1int = bits2int_modN(msgHash); - const d = normPrivateKeyToScalar(privateKey); - const seedArgs = [int2octets(d), int2octets(h1int)]; - if (ent != null) { - const e = ent === true ? randomBytes4(Fp2.BYTES) : ent; - seedArgs.push(ensureBytes("extraEntropy", e)); - } - const seed = concatBytes2(...seedArgs); - const m = h1int; - function k2sig(kBytes) { - const k = bits2int(kBytes); - if (!isWithinCurveOrder(k)) - return; - const ik = invN(k); - const q = Point2.BASE.multiply(k).toAffine(); - const r = modN2(q.x); - if (r === _0n4) - return; - const s = modN2(ik * modN2(m + r * d)); - if (s === _0n4) - return; - let recovery = (q.x === r ? 0 : 2) | Number(q.y & _1n4); - let normS = s; - if (lowS && isBiggerThanHalfOrder(s)) { - normS = normalizeS(s); - recovery ^= 1; - } - return new Signature(r, normS, recovery); - } - return { seed, k2sig }; - } - const defaultSigOpts = { lowS: CURVE.lowS, prehash: false }; - const defaultVerOpts = { lowS: CURVE.lowS, prehash: false }; - function sign(msgHash, privKey, opts = defaultSigOpts) { - const { seed, k2sig } = prepSig(msgHash, privKey, opts); - const C = CURVE; - const drbg = createHmacDrbg(C.hash.outputLen, C.nByteLength, C.hmac); - return drbg(seed, k2sig); - } - Point2.BASE._setWindowSize(8); - function verify(signature, msgHash, publicKey, opts = defaultVerOpts) { - var _a; - const sg = signature; - msgHash = ensureBytes("msgHash", msgHash); - publicKey = ensureBytes("publicKey", publicKey); - if ("strict" in opts) - throw new Error("options.strict was renamed to lowS"); - const { lowS, prehash } = opts; - let _sig = void 0; - let P; - try { - if (typeof sg === "string" || sg instanceof Uint8Array) { - try { - _sig = Signature.fromDER(sg); - } catch (derError) { - if (!(derError instanceof DER.Err)) - throw derError; - _sig = Signature.fromCompact(sg); - } - } else if (typeof sg === "object" && typeof sg.r === "bigint" && typeof sg.s === "bigint") { - const { r: r2, s: s2 } = sg; - _sig = new Signature(r2, s2); - } else { - throw new Error("PARSE"); - } - P = Point2.fromHex(publicKey); - } catch (error) { - if (error.message === "PARSE") - throw new Error(`signature must be Signature instance, Uint8Array or hex string`); - return false; - } - if (lowS && _sig.hasHighS()) - return false; - if (prehash) - msgHash = CURVE.hash(msgHash); - const { r, s } = _sig; - const h = bits2int_modN(msgHash); - const is = invN(s); - const u1 = modN2(h * is); - const u2 = modN2(r * is); - const R = (_a = Point2.BASE.multiplyAndAddUnsafe(P, u1, u2)) == null ? void 0 : _a.toAffine(); - if (!R) - return false; - const v = modN2(R.x); - return v === r; - } - return { - CURVE, - getPublicKey: getPublicKey2, - getSharedSecret, - sign, - verify, - ProjectivePoint: Point2, - Signature, - utils - }; -} -function SWUFpSqrtRatio(Fp2, Z) { - const q = Fp2.ORDER; - let l = _0n4; - for (let o = q - _1n4; o % _2n3 === _0n4; o /= _2n3) - l += _1n4; - const c1 = l; - const _2n_pow_c1_1 = _2n3 << c1 - _1n4 - _1n4; - const _2n_pow_c1 = _2n_pow_c1_1 * _2n3; - const c2 = (q - _1n4) / _2n_pow_c1; - const c3 = (c2 - _1n4) / _2n3; - const c4 = _2n_pow_c1 - _1n4; - const c5 = _2n_pow_c1_1; - const c6 = Fp2.pow(Z, c2); - const c7 = Fp2.pow(Z, (c2 + _1n4) / _2n3); - let sqrtRatio = (u, v) => { - let tv1 = c6; - let tv2 = Fp2.pow(v, c4); - let tv3 = Fp2.sqr(tv2); - tv3 = Fp2.mul(tv3, v); - let tv5 = Fp2.mul(u, tv3); - tv5 = Fp2.pow(tv5, c3); - tv5 = Fp2.mul(tv5, tv2); - tv2 = Fp2.mul(tv5, v); - tv3 = Fp2.mul(tv5, u); - let tv4 = Fp2.mul(tv3, tv2); - tv5 = Fp2.pow(tv4, c5); - let isQR = Fp2.eql(tv5, Fp2.ONE); - tv2 = Fp2.mul(tv3, c7); - tv5 = Fp2.mul(tv4, tv1); - tv3 = Fp2.cmov(tv2, tv3, isQR); - tv4 = Fp2.cmov(tv5, tv4, isQR); - for (let i2 = c1; i2 > _1n4; i2--) { - let tv52 = i2 - _2n3; - tv52 = _2n3 << tv52 - _1n4; - let tvv5 = Fp2.pow(tv4, tv52); - const e1 = Fp2.eql(tvv5, Fp2.ONE); - tv2 = Fp2.mul(tv3, tv1); - tv1 = Fp2.mul(tv1, tv1); - tvv5 = Fp2.mul(tv4, tv1); - tv3 = Fp2.cmov(tv2, tv3, e1); - tv4 = Fp2.cmov(tvv5, tv4, e1); - } - return { isValid: isQR, value: tv3 }; - }; - if (Fp2.ORDER % _4n2 === _3n2) { - const c12 = (Fp2.ORDER - _3n2) / _4n2; - const c22 = Fp2.sqrt(Fp2.neg(Z)); - sqrtRatio = (u, v) => { - let tv1 = Fp2.sqr(v); - const tv2 = Fp2.mul(u, v); - tv1 = Fp2.mul(tv1, tv2); - let y1 = Fp2.pow(tv1, c12); - y1 = Fp2.mul(y1, tv2); - const y2 = Fp2.mul(y1, c22); - const tv3 = Fp2.mul(Fp2.sqr(y1), v); - const isQR = Fp2.eql(tv3, u); - let y = Fp2.cmov(y2, y1, isQR); - return { isValid: isQR, value: y }; - }; - } - return sqrtRatio; -} -function mapToCurveSimpleSWU(Fp2, opts) { - validateField(Fp2); - if (!Fp2.isValid(opts.A) || !Fp2.isValid(opts.B) || !Fp2.isValid(opts.Z)) - throw new Error("mapToCurveSimpleSWU: invalid opts"); - const sqrtRatio = SWUFpSqrtRatio(Fp2, opts.Z); - if (!Fp2.isOdd) - throw new Error("Fp.isOdd is not implemented!"); - return (u) => { - let tv1, tv2, tv3, tv4, tv5, tv6, x, y; - tv1 = Fp2.sqr(u); - tv1 = Fp2.mul(tv1, opts.Z); - tv2 = Fp2.sqr(tv1); - tv2 = Fp2.add(tv2, tv1); - tv3 = Fp2.add(tv2, Fp2.ONE); - tv3 = Fp2.mul(tv3, opts.B); - tv4 = Fp2.cmov(opts.Z, Fp2.neg(tv2), !Fp2.eql(tv2, Fp2.ZERO)); - tv4 = Fp2.mul(tv4, opts.A); - tv2 = Fp2.sqr(tv3); - tv6 = Fp2.sqr(tv4); - tv5 = Fp2.mul(tv6, opts.A); - tv2 = Fp2.add(tv2, tv5); - tv2 = Fp2.mul(tv2, tv3); - tv6 = Fp2.mul(tv6, tv4); - tv5 = Fp2.mul(tv6, opts.B); - tv2 = Fp2.add(tv2, tv5); - x = Fp2.mul(tv1, tv3); - const { isValid: isValid2, value } = sqrtRatio(tv2, tv6); - y = Fp2.mul(tv1, u); - y = Fp2.mul(y, value); - x = Fp2.cmov(x, tv3, isValid2); - y = Fp2.cmov(y, value, isValid2); - const e1 = Fp2.isOdd(u) === Fp2.isOdd(y); - y = Fp2.cmov(Fp2.neg(y), y, e1); - x = Fp2.div(x, tv4); - return { x, y }; - }; -} - -// node_modules/nostr-tools/node_modules/@noble/curves/esm/abstract/hash-to-curve.js -function validateDST(dst) { - if (dst instanceof Uint8Array) - return dst; - if (typeof dst === "string") - return utf8ToBytes2(dst); - throw new Error("DST must be Uint8Array or string"); -} -var os2ip = bytesToNumberBE; -function i2osp(value, length) { - if (value < 0 || value >= 1 << 8 * length) { - throw new Error(`bad I2OSP call: value=${value} length=${length}`); - } - const res = Array.from({ length }).fill(0); - for (let i2 = length - 1; i2 >= 0; i2--) { - res[i2] = value & 255; - value >>>= 8; - } - return new Uint8Array(res); -} -function strxor(a, b) { - const arr = new Uint8Array(a.length); - for (let i2 = 0; i2 < a.length; i2++) { - arr[i2] = a[i2] ^ b[i2]; - } - return arr; -} -function isBytes(item) { - if (!(item instanceof Uint8Array)) - throw new Error("Uint8Array expected"); -} -function isNum(item) { - if (!Number.isSafeInteger(item)) - throw new Error("number expected"); -} -function expand_message_xmd(msg, DST, lenInBytes, H) { - isBytes(msg); - isBytes(DST); - isNum(lenInBytes); - if (DST.length > 255) - DST = H(concatBytes2(utf8ToBytes2("H2C-OVERSIZE-DST-"), DST)); - const { outputLen: b_in_bytes, blockLen: r_in_bytes } = H; - const ell = Math.ceil(lenInBytes / b_in_bytes); - if (ell > 255) - throw new Error("Invalid xmd length"); - const DST_prime = concatBytes2(DST, i2osp(DST.length, 1)); - const Z_pad = i2osp(0, r_in_bytes); - const l_i_b_str = i2osp(lenInBytes, 2); - const b = new Array(ell); - const b_0 = H(concatBytes2(Z_pad, msg, l_i_b_str, i2osp(0, 1), DST_prime)); - b[0] = H(concatBytes2(b_0, i2osp(1, 1), DST_prime)); - for (let i2 = 1; i2 <= ell; i2++) { - const args = [strxor(b_0, b[i2 - 1]), i2osp(i2 + 1, 1), DST_prime]; - b[i2] = H(concatBytes2(...args)); - } - const pseudo_random_bytes = concatBytes2(...b); - return pseudo_random_bytes.slice(0, lenInBytes); -} -function expand_message_xof(msg, DST, lenInBytes, k, H) { - isBytes(msg); - isBytes(DST); - isNum(lenInBytes); - if (DST.length > 255) { - const dkLen = Math.ceil(2 * k / 8); - DST = H.create({ dkLen }).update(utf8ToBytes2("H2C-OVERSIZE-DST-")).update(DST).digest(); - } - if (lenInBytes > 65535 || DST.length > 255) - throw new Error("expand_message_xof: invalid lenInBytes"); - return H.create({ dkLen: lenInBytes }).update(msg).update(i2osp(lenInBytes, 2)).update(DST).update(i2osp(DST.length, 1)).digest(); -} -function hash_to_field(msg, count2, options) { - validateObject(options, { - DST: "stringOrUint8Array", - p: "bigint", - m: "isSafeInteger", - k: "isSafeInteger", - hash: "hash" - }); - const { p, k, m, hash: hash3, expand: expand3, DST: _DST } = options; - isBytes(msg); - isNum(count2); - const DST = validateDST(_DST); - const log2p = p.toString(2).length; - const L = Math.ceil((log2p + k) / 8); - const len_in_bytes = count2 * m * L; - let prb; - if (expand3 === "xmd") { - prb = expand_message_xmd(msg, DST, len_in_bytes, hash3); - } else if (expand3 === "xof") { - prb = expand_message_xof(msg, DST, len_in_bytes, k, hash3); - } else if (expand3 === "_internal_pass") { - prb = msg; - } else { - throw new Error('expand must be "xmd" or "xof"'); - } - const u = new Array(count2); - for (let i2 = 0; i2 < count2; i2++) { - const e = new Array(m); - for (let j = 0; j < m; j++) { - const elm_offset = L * (j + i2 * m); - const tv = prb.subarray(elm_offset, elm_offset + L); - e[j] = mod(os2ip(tv), p); - } - u[i2] = e; - } - return u; -} -function isogenyMap(field, map2) { - const COEFF = map2.map((i2) => Array.from(i2).reverse()); - return (x, y) => { - const [xNum, xDen, yNum, yDen] = COEFF.map((val) => val.reduce((acc, i2) => field.add(field.mul(acc, x), i2))); - x = field.div(xNum, xDen); - y = field.mul(y, field.div(yNum, yDen)); - return { x, y }; - }; -} -function createHasher(Point2, mapToCurve, def) { - if (typeof mapToCurve !== "function") - throw new Error("mapToCurve() must be defined"); - return { - // Encodes byte string to elliptic curve. - // hash_to_curve from https://www.rfc-editor.org/rfc/rfc9380#section-3 - hashToCurve(msg, options) { - const u = hash_to_field(msg, 2, { ...def, DST: def.DST, ...options }); - const u0 = Point2.fromAffine(mapToCurve(u[0])); - const u1 = Point2.fromAffine(mapToCurve(u[1])); - const P = u0.add(u1).clearCofactor(); - P.assertValidity(); - return P; - }, - // Encodes byte string to elliptic curve. - // encode_to_curve from https://www.rfc-editor.org/rfc/rfc9380#section-3 - encodeToCurve(msg, options) { - const u = hash_to_field(msg, 1, { ...def, DST: def.encodeDST, ...options }); - const P = Point2.fromAffine(mapToCurve(u[0])).clearCofactor(); - P.assertValidity(); - return P; - } - }; -} - -// node_modules/nostr-tools/node_modules/@noble/curves/node_modules/@noble/hashes/esm/hmac.js -var HMAC = class extends Hash { - constructor(hash3, _key) { - super(); - this.finished = false; - this.destroyed = false; - hash(hash3); - const key = toBytes(_key); - this.iHash = hash3.create(); - if (typeof this.iHash.update !== "function") - throw new Error("Expected instance of class which extends utils.Hash"); - this.blockLen = this.iHash.blockLen; - this.outputLen = this.iHash.outputLen; - const blockLen = this.blockLen; - const pad2 = new Uint8Array(blockLen); - pad2.set(key.length > blockLen ? hash3.create().update(key).digest() : key); - for (let i2 = 0; i2 < pad2.length; i2++) - pad2[i2] ^= 54; - this.iHash.update(pad2); - this.oHash = hash3.create(); - for (let i2 = 0; i2 < pad2.length; i2++) - pad2[i2] ^= 54 ^ 92; - this.oHash.update(pad2); - pad2.fill(0); - } - update(buf) { - exists(this); - this.iHash.update(buf); - return this; - } - digestInto(out) { - exists(this); - bytes(out, this.outputLen); - this.finished = true; - this.iHash.digestInto(out); - this.oHash.update(out); - this.oHash.digestInto(out); - this.destroy(); - } - digest() { - const out = new Uint8Array(this.oHash.outputLen); - this.digestInto(out); - return out; - } - _cloneInto(to) { - to || (to = Object.create(Object.getPrototypeOf(this), {})); - const { oHash, iHash, finished, destroyed, blockLen, outputLen } = this; - to = to; - to.finished = finished; - to.destroyed = destroyed; - to.blockLen = blockLen; - to.outputLen = outputLen; - to.oHash = oHash._cloneInto(to.oHash); - to.iHash = iHash._cloneInto(to.iHash); - return to; - } - destroy() { - this.destroyed = true; - this.oHash.destroy(); - this.iHash.destroy(); - } -}; -var hmac = (hash3, key, message) => new HMAC(hash3, key).update(message).digest(); -hmac.create = (hash3, key) => new HMAC(hash3, key); - -// node_modules/nostr-tools/node_modules/@noble/curves/esm/_shortw_utils.js -function getHash(hash3) { - return { - hash: hash3, - hmac: (key, ...msgs) => hmac(hash3, key, concatBytes(...msgs)), - randomBytes - }; -} -function createCurve(curveDef, defHash) { - const create = (hash3) => weierstrass({ ...curveDef, ...getHash(hash3) }); - return Object.freeze({ ...create(defHash), create }); -} - -// node_modules/nostr-tools/node_modules/@noble/curves/esm/secp256k1.js -var secp256k1P = BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"); -var secp256k1N = BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"); -var _1n5 = BigInt(1); -var _2n4 = BigInt(2); -var divNearest = (a, b) => (a + b / _2n4) / b; -function sqrtMod(y) { - const P = secp256k1P; - const _3n3 = BigInt(3), _6n = BigInt(6), _11n = BigInt(11), _22n = BigInt(22); - const _23n = BigInt(23), _44n = BigInt(44), _88n = BigInt(88); - const b2 = y * y * y % P; - const b3 = b2 * b2 * y % P; - const b6 = pow2(b3, _3n3, P) * b3 % P; - const b9 = pow2(b6, _3n3, P) * b3 % P; - const b11 = pow2(b9, _2n4, P) * b2 % P; - const b22 = pow2(b11, _11n, P) * b11 % P; - const b44 = pow2(b22, _22n, P) * b22 % P; - const b88 = pow2(b44, _44n, P) * b44 % P; - const b176 = pow2(b88, _88n, P) * b88 % P; - const b220 = pow2(b176, _44n, P) * b44 % P; - const b223 = pow2(b220, _3n3, P) * b3 % P; - const t1 = pow2(b223, _23n, P) * b22 % P; - const t2 = pow2(t1, _6n, P) * b2 % P; - const root = pow2(t2, _2n4, P); - if (!Fp.eql(Fp.sqr(root), y)) - throw new Error("Cannot find square root"); - return root; -} -var Fp = Field(secp256k1P, void 0, void 0, { sqrt: sqrtMod }); -var secp256k1 = createCurve({ - a: BigInt(0), - b: BigInt(7), - Fp, - n: secp256k1N, - // Base point (x, y) aka generator point - Gx: BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"), - Gy: BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"), - h: BigInt(1), - lowS: true, - /** - * secp256k1 belongs to Koblitz curves: it has efficiently computable endomorphism. - * Endomorphism uses 2x less RAM, speeds up precomputation by 2x and ECDH / key recovery by 20%. - * For precomputed wNAF it trades off 1/2 init time & 1/3 ram for 20% perf hit. - * Explanation: https://gist.github.com/paulmillr/eb670806793e84df628a7c434a873066 - */ - endo: { - beta: BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"), - splitScalar: (k) => { - const n = secp256k1N; - const a1 = BigInt("0x3086d221a7d46bcde86c90e49284eb15"); - const b1 = -_1n5 * BigInt("0xe4437ed6010e88286f547fa90abfe4c3"); - const a2 = BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"); - const b2 = a1; - const POW_2_128 = BigInt("0x100000000000000000000000000000000"); - const c1 = divNearest(b2 * k, n); - const c2 = divNearest(-b1 * k, n); - let k1 = mod(k - c1 * a1 - c2 * a2, n); - let k2 = mod(-c1 * b1 - c2 * b2, n); - const k1neg = k1 > POW_2_128; - const k2neg = k2 > POW_2_128; - if (k1neg) - k1 = n - k1; - if (k2neg) - k2 = n - k2; - if (k1 > POW_2_128 || k2 > POW_2_128) { - throw new Error("splitScalar: Endomorphism failed, k=" + k); - } - return { k1neg, k1, k2neg, k2 }; - } - } -}, sha256); -var _0n5 = BigInt(0); -var fe = (x) => typeof x === "bigint" && _0n5 < x && x < secp256k1P; -var ge = (x) => typeof x === "bigint" && _0n5 < x && x < secp256k1N; -var TAGGED_HASH_PREFIXES = {}; -function taggedHash(tag, ...messages) { - let tagP = TAGGED_HASH_PREFIXES[tag]; - if (tagP === void 0) { - const tagH = sha256(Uint8Array.from(tag, (c) => c.charCodeAt(0))); - tagP = concatBytes2(tagH, tagH); - TAGGED_HASH_PREFIXES[tag] = tagP; - } - return sha256(concatBytes2(tagP, ...messages)); -} -var pointToBytes = (point) => point.toRawBytes(true).slice(1); -var numTo32b = (n) => numberToBytesBE(n, 32); -var modP = (x) => mod(x, secp256k1P); -var modN = (x) => mod(x, secp256k1N); -var Point = secp256k1.ProjectivePoint; -var GmulAdd = (Q, a, b) => Point.BASE.multiplyAndAddUnsafe(Q, a, b); -function schnorrGetExtPubKey(priv) { - let d_ = secp256k1.utils.normPrivateKeyToScalar(priv); - let p = Point.fromPrivateKey(d_); - const scalar = p.hasEvenY() ? d_ : modN(-d_); - return { scalar, bytes: pointToBytes(p) }; -} -function lift_x(x) { - if (!fe(x)) - throw new Error("bad x: need 0 < x < p"); - const xx = modP(x * x); - const c = modP(xx * x + BigInt(7)); - let y = sqrtMod(c); - if (y % _2n4 !== _0n5) - y = modP(-y); - const p = new Point(x, y, _1n5); - p.assertValidity(); - return p; -} -function challenge(...args) { - return modN(bytesToNumberBE(taggedHash("BIP0340/challenge", ...args))); -} -function schnorrGetPublicKey(privateKey) { - return schnorrGetExtPubKey(privateKey).bytes; -} -function schnorrSign(message, privateKey, auxRand = randomBytes(32)) { - const m = ensureBytes("message", message); - const { bytes: px, scalar: d } = schnorrGetExtPubKey(privateKey); - const a = ensureBytes("auxRand", auxRand, 32); - const t = numTo32b(d ^ bytesToNumberBE(taggedHash("BIP0340/aux", a))); - const rand = taggedHash("BIP0340/nonce", t, px, m); - const k_ = modN(bytesToNumberBE(rand)); - if (k_ === _0n5) - throw new Error("sign failed: k is zero"); - const { bytes: rx, scalar: k } = schnorrGetExtPubKey(k_); - const e = challenge(rx, px, m); - const sig = new Uint8Array(64); - sig.set(rx, 0); - sig.set(numTo32b(modN(k + e * d)), 32); - if (!schnorrVerify(sig, m, px)) - throw new Error("sign: Invalid signature produced"); - return sig; -} -function schnorrVerify(signature, message, publicKey) { - const sig = ensureBytes("signature", signature, 64); - const m = ensureBytes("message", message); - const pub = ensureBytes("publicKey", publicKey, 32); - try { - const P = lift_x(bytesToNumberBE(pub)); - const r = bytesToNumberBE(sig.subarray(0, 32)); - if (!fe(r)) - return false; - const s = bytesToNumberBE(sig.subarray(32, 64)); - if (!ge(s)) - return false; - const e = challenge(numTo32b(r), pointToBytes(P), m); - const R = GmulAdd(P, s, modN(-e)); - if (!R || !R.hasEvenY() || R.toAffine().x !== r) - return false; - return true; - } catch (error) { - return false; - } -} -var schnorr = (() => ({ - getPublicKey: schnorrGetPublicKey, - sign: schnorrSign, - verify: schnorrVerify, - utils: { - randomPrivateKey: secp256k1.utils.randomPrivateKey, - lift_x, - pointToBytes, - numberToBytesBE, - bytesToNumberBE, - taggedHash, - mod - } -}))(); -var isoMap = (() => isogenyMap(Fp, [ - // xNum - [ - "0x8e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38daaaaa8c7", - "0x7d3d4c80bc321d5b9f315cea7fd44c5d595d2fc0bf63b92dfff1044f17c6581", - "0x534c328d23f234e6e2a413deca25caece4506144037c40314ecbd0b53d9dd262", - "0x8e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38daaaaa88c" - ], - // xDen - [ - "0xd35771193d94918a9ca34ccbb7b640dd86cd409542f8487d9fe6b745781eb49b", - "0xedadc6f64383dc1df7c4b2d51b54225406d36b641f5e41bbc52a56612a8c6d14", - "0x0000000000000000000000000000000000000000000000000000000000000001" - // LAST 1 - ], - // yNum - [ - "0x4bda12f684bda12f684bda12f684bda12f684bda12f684bda12f684b8e38e23c", - "0xc75e0c32d5cb7c0fa9d0a54b12a0a6d5647ab046d686da6fdffc90fc201d71a3", - "0x29a6194691f91a73715209ef6512e576722830a201be2018a765e85a9ecee931", - "0x2f684bda12f684bda12f684bda12f684bda12f684bda12f684bda12f38e38d84" - ], - // yDen - [ - "0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffff93b", - "0x7a06534bb8bdb49fd5e9e6632722c2989467c1bfc8e8d978dfb425d2685c2573", - "0x6484aa716545ca2cf3a70c3fa8fe337e0a3d21162f0d6299a7bf8192bfd2a76f", - "0x0000000000000000000000000000000000000000000000000000000000000001" - // LAST 1 - ] -].map((i2) => i2.map((j) => BigInt(j)))))(); -var mapSWU = (() => mapToCurveSimpleSWU(Fp, { - A: BigInt("0x3f8731abdd661adca08a5558f0f5d272e953d363cb6f0e5d405447c01a444533"), - B: BigInt("1771"), - Z: Fp.create(BigInt("-11")) -}))(); -var htf = (() => createHasher(secp256k1.ProjectivePoint, (scalars) => { - const { x, y } = mapSWU(Fp.create(scalars[0])); - return isoMap(x, y); -}, { - DST: "secp256k1_XMD:SHA-256_SSWU_RO_", - encodeDST: "secp256k1_XMD:SHA-256_SSWU_NU_", - p: Fp.ORDER, - m: 1, - k: 128, - expand: "xmd", - hash: sha256 -}))(); -var hashToCurve = (() => htf.hashToCurve)(); -var encodeToCurve = (() => htf.encodeToCurve)(); - -// node_modules/nostr-tools/node_modules/@noble/hashes/esm/crypto.js -var crypto2 = typeof globalThis === "object" && "crypto" in globalThis ? globalThis.crypto : void 0; - -// node_modules/nostr-tools/node_modules/@noble/hashes/esm/utils.js -var u8a3 = (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"); -var hexes3 = Array.from({ length: 256 }, (v, i2) => i2.toString(16).padStart(2, "0")); -function bytesToHex2(bytes4) { - if (!u8a3(bytes4)) - throw new Error("Uint8Array expected"); - let hex3 = ""; - for (let i2 = 0; i2 < bytes4.length; i2++) { - hex3 += hexes3[bytes4[i2]]; - } - return hex3; -} -function hexToBytes2(hex3) { - if (typeof hex3 !== "string") - throw new Error("hex string expected, got " + typeof hex3); - const len = hex3.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 i2 = 0; i2 < array.length; i2++) { - const j = i2 * 2; - const hexByte = hex3.slice(j, j + 2); - const byte = Number.parseInt(hexByte, 16); - if (Number.isNaN(byte) || byte < 0) - throw new Error("Invalid byte sequence"); - array[i2] = byte; - } - return array; -} -function utf8ToBytes3(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 = utf8ToBytes3(data); - if (!u8a3(data)) - throw new Error(`expected Uint8Array, got ${typeof data}`); - return data; -} -function concatBytes3(...arrays) { - const r = new Uint8Array(arrays.reduce((sum, a) => sum + a.length, 0)); - let pad2 = 0; - arrays.forEach((a) => { - if (!u8a3(a)) - throw new Error("Uint8Array expected"); - r.set(a, pad2); - pad2 += a.length; - }); - return r; -} -var Hash2 = class { - // Safe version that clones internal state - clone() { - return this._cloneInto(); - } -}; -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 randomBytes2(bytesLength = 32) { - if (crypto2 && typeof crypto2.getRandomValues === "function") { - return crypto2.getRandomValues(new Uint8Array(bytesLength)); - } - throw new Error("crypto.getRandomValues must be defined"); -} - -// node_modules/nostr-tools/node_modules/@noble/hashes/esm/_assert.js -function number2(n) { - if (!Number.isSafeInteger(n) || n < 0) - throw new Error(`Wrong positive integer: ${n}`); -} -function bool(b) { - if (typeof b !== "boolean") - throw new Error(`Expected boolean, not ${b}`); -} -function bytes2(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 hash2(hash3) { - if (typeof hash3 !== "function" || typeof hash3.create !== "function") - throw new Error("Hash should be wrapped by utils.wrapConstructor"); - number2(hash3.outputLen); - number2(hash3.blockLen); -} -function exists2(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 output2(out, instance) { - bytes2(out); - const min2 = instance.outputLen; - if (out.length < min2) { - throw new Error(`digestInto() expects output buffer of length at least ${min2}`); - } -} -var assert = { - number: number2, - bool, - bytes: bytes2, - hash: hash2, - exists: exists2, - output: output2 -}; -var assert_default = assert; - -// node_modules/nostr-tools/node_modules/@noble/hashes/esm/_sha2.js -function setBigUint642(view, byteOffset, value, isLE5) { - if (typeof view.setBigUint64 === "function") - return view.setBigUint64(byteOffset, value, isLE5); - const _32n = BigInt(32); - const _u32_max = BigInt(4294967295); - const wh = Number(value >> _32n & _u32_max); - const wl = Number(value & _u32_max); - const h = isLE5 ? 4 : 0; - const l = isLE5 ? 0 : 4; - view.setUint32(byteOffset + h, wh, isLE5); - view.setUint32(byteOffset + l, wl, isLE5); -} -var SHA22 = class extends Hash2 { - constructor(blockLen, outputLen, padOffset, isLE5) { - super(); - this.blockLen = blockLen; - this.outputLen = outputLen; - this.padOffset = padOffset; - this.isLE = isLE5; - this.finished = false; - this.length = 0; - this.pos = 0; - this.destroyed = false; - this.buffer = new Uint8Array(blockLen); - this.view = createView2(this.buffer); - } - update(data) { - assert_default.exists(this); - const { view, buffer: buffer2, blockLen } = this; - data = toBytes2(data); - const len = data.length; - for (let pos = 0; pos < len; ) { - const take2 = Math.min(blockLen - this.pos, len - pos); - if (take2 === blockLen) { - const dataView = createView2(data); - for (; blockLen <= len - pos; pos += blockLen) - this.process(dataView, pos); - continue; - } - buffer2.set(data.subarray(pos, pos + take2), this.pos); - this.pos += take2; - pos += take2; - if (this.pos === blockLen) { - this.process(view, 0); - this.pos = 0; - } - } - this.length += data.length; - this.roundClean(); - return this; - } - digestInto(out) { - assert_default.exists(this); - assert_default.output(out, this); - this.finished = true; - const { buffer: buffer2, view, blockLen, isLE: isLE5 } = this; - let { pos } = this; - buffer2[pos++] = 128; - this.buffer.subarray(pos).fill(0); - if (this.padOffset > blockLen - pos) { - this.process(view, 0); - pos = 0; - } - for (let i2 = pos; i2 < blockLen; i2++) - buffer2[i2] = 0; - setBigUint642(view, blockLen - 8, BigInt(this.length * 8), isLE5); - 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 i2 = 0; i2 < outLen; i2++) - oview.setUint32(4 * i2, state[i2], isLE5); - } - digest() { - const { buffer: buffer2, outputLen } = this; - this.digestInto(buffer2); - const res = buffer2.slice(0, outputLen); - this.destroy(); - return res; - } - _cloneInto(to) { - to || (to = new this.constructor()); - to.set(...this.get()); - const { blockLen, buffer: buffer2, length, finished, destroyed, pos } = this; - to.length = length; - to.pos = pos; - to.finished = finished; - to.destroyed = destroyed; - if (length % blockLen) - to.buffer.set(buffer2); - return to; - } -}; - -// node_modules/nostr-tools/node_modules/@noble/hashes/esm/sha256.js -var Chi2 = (a, b, c) => a & b ^ ~a & c; -var Maj2 = (a, b, c) => a & b ^ a & c ^ b & c; -var SHA256_K2 = 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 IV2 = new Uint32Array([ - 1779033703, - 3144134277, - 1013904242, - 2773480762, - 1359893119, - 2600822924, - 528734635, - 1541459225 -]); -var SHA256_W2 = new Uint32Array(64); -var SHA2562 = class extends SHA22 { - constructor() { - super(64, 32, 8, false); - this.A = IV2[0] | 0; - this.B = IV2[1] | 0; - this.C = IV2[2] | 0; - this.D = IV2[3] | 0; - this.E = IV2[4] | 0; - this.F = IV2[5] | 0; - this.G = IV2[6] | 0; - this.H = IV2[7] | 0; - } - get() { - const { A, B, C, D, E, F, G, H } = this; - return [A, B, C, D, E, F, G, H]; - } - // prettier-ignore - 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 i2 = 0; i2 < 16; i2++, offset += 4) - SHA256_W2[i2] = view.getUint32(offset, false); - for (let i2 = 16; i2 < 64; i2++) { - const W15 = SHA256_W2[i2 - 15]; - const W2 = SHA256_W2[i2 - 2]; - const s0 = rotr2(W15, 7) ^ rotr2(W15, 18) ^ W15 >>> 3; - const s1 = rotr2(W2, 17) ^ rotr2(W2, 19) ^ W2 >>> 10; - SHA256_W2[i2] = s1 + SHA256_W2[i2 - 7] + s0 + SHA256_W2[i2 - 16] | 0; - } - let { A, B, C, D, E, F, G, H } = this; - for (let i2 = 0; i2 < 64; i2++) { - const sigma1 = rotr2(E, 6) ^ rotr2(E, 11) ^ rotr2(E, 25); - const T1 = H + sigma1 + Chi2(E, F, G) + SHA256_K2[i2] + SHA256_W2[i2] | 0; - const sigma0 = rotr2(A, 2) ^ rotr2(A, 13) ^ rotr2(A, 22); - const T2 = sigma0 + Maj2(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_W2.fill(0); - } - destroy() { - this.set(0, 0, 0, 0, 0, 0, 0, 0); - this.buffer.fill(0); - } -}; -var SHA2242 = class extends SHA2562 { - constructor() { - super(); - this.A = 3238371032 | 0; - this.B = 914150663 | 0; - this.C = 812702999 | 0; - this.D = 4144912697 | 0; - this.E = 4290775857 | 0; - this.F = 1750603025 | 0; - this.G = 1694076839 | 0; - this.H = 3204075428 | 0; - this.outputLen = 28; - } -}; -var sha2562 = wrapConstructor2(() => new SHA2562()); -var sha2242 = wrapConstructor2(() => new SHA2242()); - -// node_modules/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, i2) => acc ? wrap(acc, i2.encode) : i2.encode, void 0); - const decode4 = args.reduce((acc, i2) => acc ? wrap(acc, i2.decode) : i2.decode, void 0); - return { encode, decode: decode4 }; -} -function alphabet(alphabet3) { - 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((i2) => { - assertNumber(i2); - if (i2 < 0 || i2 >= alphabet3.length) - throw new Error(`Digit index outside alphabet: ${i2} (alphabet: ${alphabet3.length})`); - return alphabet3[i2]; - }); - }, - 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 = alphabet3.indexOf(letter); - if (index === -1) - throw new Error(`Unknown letter: "${letter}". Allowed: ${alphabet3}`); - return index; - }); - } - }; -} -function join(separator = "") { - if (typeof separator !== "string") - throw new Error("join separator should be string"); - return { - encode: (from2) => { - if (!Array.isArray(from2) || from2.length && typeof from2[0] !== "string") - throw new Error("join.encode input should be array of strings"); - for (let i2 of from2) - if (typeof i2 !== "string") - throw new Error(`join.encode: non-string input=${i2}`); - return from2.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 i2 of data) - if (typeof i2 !== "string") - throw new Error(`padding.encode: non-string input=${i2}`); - 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 i2 of input) - if (typeof i2 !== "string") - throw new Error(`padding.decode: non-string input=${i2}`); - 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: (from2) => from2, decode: (to) => fn(to) }; -} -function convertRadix(data, from2, to) { - if (from2 < 2) - throw new Error(`convertRadix: wrong from=${from2}, 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 >= from2) - throw new Error(`Wrong integer: ${d}`); - }); - while (true) { - let carry = 0; - let done = true; - for (let i2 = pos; i2 < digits.length; i2++) { - const digit = digits[i2]; - const digitBase = from2 * carry + digit; - if (!Number.isSafeInteger(digitBase) || from2 * carry / from2 !== carry || digitBase - digit !== from2 * carry) { - throw new Error("convertRadix: carry overflow"); - } - carry = digitBase % to; - digits[i2] = Math.floor(digitBase / to); - if (!Number.isSafeInteger(digits[i2]) || digits[i2] * to + carry !== digitBase) - throw new Error("convertRadix: carry overflow"); - if (!done) - continue; - else if (!digits[i2]) - pos = i2; - else - done = false; - } - res.push(carry); - if (done) - break; - } - for (let i2 = 0; i2 < data.length - 1 && data[i2] === 0; i2++) - res.push(0); - return res.reverse(); -} -var gcd = (a, b) => !b ? a : gcd(b, a % b); -var radix2carry = (from2, to) => from2 + (to - gcd(from2, to)); -function convertRadix2(data, from2, to, padding3) { - if (!Array.isArray(data)) - throw new Error("convertRadix2: data should be array"); - if (from2 <= 0 || from2 > 32) - throw new Error(`convertRadix2: wrong from=${from2}`); - if (to <= 0 || to > 32) - throw new Error(`convertRadix2: wrong to=${to}`); - if (radix2carry(from2, to) > 32) { - throw new Error(`convertRadix2: carry overflow from=${from2} to=${to} carryBits=${radix2carry(from2, to)}`); - } - let carry = 0; - let pos = 0; - const mask = 2 ** to - 1; - const res = []; - for (const n of data) { - assertNumber(n); - if (n >= 2 ** from2) - throw new Error(`convertRadix2: invalid data word=${n} from=${from2}`); - carry = carry << from2 | n; - if (pos + from2 > 32) - throw new Error(`convertRadix2: carry overflow pos=${pos} from=${from2}`); - pos += from2; - for (; pos >= to; pos -= to) - res.push((carry >> pos - to & mask) >>> 0); - carry &= 2 ** pos - 1; - } - carry = carry << to - pos & mask; - if (!padding3 && pos >= from2) - throw new Error("Excess padding"); - if (!padding3 && carry) - throw new Error(`Non-zero padding: ${carry}`); - if (padding3 && pos > 0) - res.push(carry >>> 0); - return res; -} -function radix(num) { - assertNumber(num); - return { - encode: (bytes4) => { - if (!(bytes4 instanceof Uint8Array)) - throw new Error("radix.encode input should be Uint8Array"); - return convertRadix(Array.from(bytes4), 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: (bytes4) => { - if (!(bytes4 instanceof Uint8Array)) - throw new Error("radix2.encode input should be Uint8Array"); - return convertRadix2(Array.from(bytes4), 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 i2 = 0; i2 < data.length; i2 += 8) { - const block = data.subarray(i2, i2 + 8); - res += base58.encode(block).padStart(XMR_BLOCK_LEN[block.length], "1"); - } - return res; - }, - decode(str) { - let res = []; - for (let i2 = 0; i2 < str.length; i2 += 11) { - const slice = str.slice(i2, i2 + 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 i2 = 0; i2 < POLYMOD_GENERATORS.length; i2++) { - if ((b >> i2 & 1) === 1) - chk ^= POLYMOD_GENERATORS[i2]; - } - return chk; -} -function bechChecksum(prefix, words, encodingConst = 1) { - const len = prefix.length; - let chk = 1; - for (let i2 = 0; i2 < len; i2++) { - const c = prefix.charCodeAt(i2); - if (c < 33 || c > 126) - throw new Error(`Invalid prefix (${prefix})`); - chk = bech32Polymod(chk) ^ c >> 5; - } - chk = bech32Polymod(chk); - for (let i2 = 0; i2 < len; i2++) - chk = bech32Polymod(chk) ^ prefix.charCodeAt(i2) & 31; - for (let v of words) - chk = bech32Polymod(chk) ^ v; - for (let i2 = 0; i2 < 6; i2++) - 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, limit2 = 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 (limit2 !== false && actualLength > limit2) - throw new TypeError(`Length ${actualLength} exceeds limit ${limit2}`); - prefix = prefix.toLowerCase(); - return `${prefix}1${BECH_ALPHABET.encode(words)}${bechChecksum(prefix, words, ENCODING_CONST)}`; - } - function decode4(str, limit2 = 90) { - if (typeof str !== "string") - throw new Error(`bech32.decode input should be string, not ${typeof str}`); - if (str.length < 8 || limit2 !== false && str.length > limit2) - throw new TypeError(`Wrong string length: ${str.length} (${str}). Expected (8..${limit2})`); - 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(decode4); - function decodeToBytes(str) { - const { prefix, words } = decode4(str, false); - return { prefix, words, bytes: fromWords(words) }; - } - return { encode, decode: decode4, 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(", ")}`; - -// node_modules/@noble/ciphers/esm/_assert.js -function number3(n) { - if (!Number.isSafeInteger(n) || n < 0) - throw new Error(`positive integer expected, not ${n}`); -} -function bool2(b) { - if (typeof b !== "boolean") - throw new Error(`boolean expected, not ${b}`); -} -function isBytes2(a) { - return a instanceof Uint8Array || a != null && typeof a === "object" && a.constructor.name === "Uint8Array"; -} -function bytes3(b, ...lengths) { - if (!isBytes2(b)) - throw new Error("Uint8Array expected"); - if (lengths.length > 0 && !lengths.includes(b.length)) - throw new Error(`Uint8Array expected of length ${lengths}, not of length=${b.length}`); -} -function exists3(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 output3(out, instance) { - bytes3(out); - const min2 = instance.outputLen; - if (out.length < min2) { - throw new Error(`digestInto() expects output buffer of length at least ${min2}`); - } -} - -// node_modules/@noble/ciphers/esm/utils.js -var u8 = (arr) => new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength); -var u32 = (arr) => new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4)); -var createView3 = (arr) => new DataView(arr.buffer, arr.byteOffset, arr.byteLength); -var isLE3 = new Uint8Array(new Uint32Array([287454020]).buffer)[0] === 68; -if (!isLE3) - throw new Error("Non little-endian hardware is not supported"); -var hexes4 = Array.from({ length: 256 }, (_, i2) => i2.toString(16).padStart(2, "0")); -function utf8ToBytes4(str) { - if (typeof str !== "string") - throw new Error(`string expected, got ${typeof str}`); - return new Uint8Array(new TextEncoder().encode(str)); -} -function toBytes3(data) { - if (typeof data === "string") - data = utf8ToBytes4(data); - else if (isBytes2(data)) - data = data.slice(); - else - throw new Error(`Uint8Array expected, got ${typeof data}`); - return data; -} -function checkOpts(defaults, opts) { - if (opts == null || typeof opts !== "object") - throw new Error("options must be defined"); - const merged = Object.assign(defaults, opts); - return merged; -} -function equalBytes2(a, b) { - if (a.length !== b.length) - return false; - let diff = 0; - for (let i2 = 0; i2 < a.length; i2++) - diff |= a[i2] ^ b[i2]; - return diff === 0; -} -var wrapCipher = (params, c) => { - Object.assign(c, params); - return c; -}; -function setBigUint643(view, byteOffset, value, isLE5) { - if (typeof view.setBigUint64 === "function") - return view.setBigUint64(byteOffset, value, isLE5); - const _32n = BigInt(32); - const _u32_max = BigInt(4294967295); - const wh = Number(value >> _32n & _u32_max); - const wl = Number(value & _u32_max); - const h = isLE5 ? 4 : 0; - const l = isLE5 ? 0 : 4; - view.setUint32(byteOffset + h, wh, isLE5); - view.setUint32(byteOffset + l, wl, isLE5); -} - -// node_modules/@noble/ciphers/esm/_polyval.js -var BLOCK_SIZE = 16; -var ZEROS16 = new Uint8Array(16); -var ZEROS32 = u32(ZEROS16); -var POLY = 225; -var mul2 = (s0, s1, s2, s3) => { - const hiBit = s3 & 1; - return { - s3: s2 << 31 | s3 >>> 1, - s2: s1 << 31 | s2 >>> 1, - s1: s0 << 31 | s1 >>> 1, - s0: s0 >>> 1 ^ POLY << 24 & -(hiBit & 1) - // reduce % poly - }; -}; -var swapLE = (n) => (n >>> 0 & 255) << 24 | (n >>> 8 & 255) << 16 | (n >>> 16 & 255) << 8 | n >>> 24 & 255 | 0; -function _toGHASHKey(k) { - k.reverse(); - const hiBit = k[15] & 1; - let carry = 0; - for (let i2 = 0; i2 < k.length; i2++) { - const t = k[i2]; - k[i2] = t >>> 1 | carry; - carry = (t & 1) << 7; - } - k[0] ^= -hiBit & 225; - return k; -} -var estimateWindow = (bytes4) => { - if (bytes4 > 64 * 1024) - return 8; - if (bytes4 > 1024) - return 4; - return 2; -}; -var GHASH = class { - // We select bits per window adaptively based on expectedLength - constructor(key, expectedLength) { - this.blockLen = BLOCK_SIZE; - this.outputLen = BLOCK_SIZE; - this.s0 = 0; - this.s1 = 0; - this.s2 = 0; - this.s3 = 0; - this.finished = false; - key = toBytes3(key); - bytes3(key, 16); - const kView = createView3(key); - let k0 = kView.getUint32(0, false); - let k1 = kView.getUint32(4, false); - let k2 = kView.getUint32(8, false); - let k3 = kView.getUint32(12, false); - const doubles = []; - for (let i2 = 0; i2 < 128; i2++) { - doubles.push({ s0: swapLE(k0), s1: swapLE(k1), s2: swapLE(k2), s3: swapLE(k3) }); - ({ s0: k0, s1: k1, s2: k2, s3: k3 } = mul2(k0, k1, k2, k3)); - } - const W = estimateWindow(expectedLength || 1024); - if (![1, 2, 4, 8].includes(W)) - throw new Error(`ghash: wrong window size=${W}, should be 2, 4 or 8`); - this.W = W; - const bits = 128; - const windows = bits / W; - const windowSize = this.windowSize = 2 ** W; - const items = []; - for (let w = 0; w < windows; w++) { - for (let byte = 0; byte < windowSize; byte++) { - let s0 = 0, s1 = 0, s2 = 0, s3 = 0; - for (let j = 0; j < W; j++) { - const bit = byte >>> W - j - 1 & 1; - if (!bit) - continue; - const { s0: d0, s1: d1, s2: d2, s3: d3 } = doubles[W * w + j]; - s0 ^= d0, s1 ^= d1, s2 ^= d2, s3 ^= d3; - } - items.push({ s0, s1, s2, s3 }); - } - } - this.t = items; - } - _updateBlock(s0, s1, s2, s3) { - s0 ^= this.s0, s1 ^= this.s1, s2 ^= this.s2, s3 ^= this.s3; - const { W, t, windowSize } = this; - let o0 = 0, o1 = 0, o2 = 0, o3 = 0; - const mask = (1 << W) - 1; - let w = 0; - for (const num of [s0, s1, s2, s3]) { - for (let bytePos = 0; bytePos < 4; bytePos++) { - const byte = num >>> 8 * bytePos & 255; - for (let bitPos = 8 / W - 1; bitPos >= 0; bitPos--) { - const bit = byte >>> W * bitPos & mask; - const { s0: e0, s1: e1, s2: e2, s3: e3 } = t[w * windowSize + bit]; - o0 ^= e0, o1 ^= e1, o2 ^= e2, o3 ^= e3; - w += 1; - } - } - } - this.s0 = o0; - this.s1 = o1; - this.s2 = o2; - this.s3 = o3; - } - update(data) { - data = toBytes3(data); - exists3(this); - const b32 = u32(data); - const blocks = Math.floor(data.length / BLOCK_SIZE); - const left = data.length % BLOCK_SIZE; - for (let i2 = 0; i2 < blocks; i2++) { - this._updateBlock(b32[i2 * 4 + 0], b32[i2 * 4 + 1], b32[i2 * 4 + 2], b32[i2 * 4 + 3]); - } - if (left) { - ZEROS16.set(data.subarray(blocks * BLOCK_SIZE)); - this._updateBlock(ZEROS32[0], ZEROS32[1], ZEROS32[2], ZEROS32[3]); - ZEROS32.fill(0); - } - return this; - } - destroy() { - const { t } = this; - for (const elm of t) { - elm.s0 = 0, elm.s1 = 0, elm.s2 = 0, elm.s3 = 0; - } - } - digestInto(out) { - exists3(this); - output3(out, this); - this.finished = true; - const { s0, s1, s2, s3 } = this; - const o32 = u32(out); - o32[0] = s0; - o32[1] = s1; - o32[2] = s2; - o32[3] = s3; - return out; - } - digest() { - const res = new Uint8Array(BLOCK_SIZE); - this.digestInto(res); - this.destroy(); - return res; - } -}; -var Polyval = class extends GHASH { - constructor(key, expectedLength) { - key = toBytes3(key); - const ghKey = _toGHASHKey(key.slice()); - super(ghKey, expectedLength); - ghKey.fill(0); - } - update(data) { - data = toBytes3(data); - exists3(this); - const b32 = u32(data); - const left = data.length % BLOCK_SIZE; - const blocks = Math.floor(data.length / BLOCK_SIZE); - for (let i2 = 0; i2 < blocks; i2++) { - this._updateBlock(swapLE(b32[i2 * 4 + 3]), swapLE(b32[i2 * 4 + 2]), swapLE(b32[i2 * 4 + 1]), swapLE(b32[i2 * 4 + 0])); - } - if (left) { - ZEROS16.set(data.subarray(blocks * BLOCK_SIZE)); - this._updateBlock(swapLE(ZEROS32[3]), swapLE(ZEROS32[2]), swapLE(ZEROS32[1]), swapLE(ZEROS32[0])); - ZEROS32.fill(0); - } - return this; - } - digestInto(out) { - exists3(this); - output3(out, this); - this.finished = true; - const { s0, s1, s2, s3 } = this; - const o32 = u32(out); - o32[0] = s0; - o32[1] = s1; - o32[2] = s2; - o32[3] = s3; - return out.reverse(); - } -}; -function wrapConstructorWithKey(hashCons) { - const hashC = (msg, key) => hashCons(key, msg.length).update(toBytes3(msg)).digest(); - const tmp = hashCons(new Uint8Array(16), 0); - hashC.outputLen = tmp.outputLen; - hashC.blockLen = tmp.blockLen; - hashC.create = (key, expectedLength) => hashCons(key, expectedLength); - return hashC; -} -var ghash = wrapConstructorWithKey((key, expectedLength) => new GHASH(key, expectedLength)); -var polyval = wrapConstructorWithKey((key, expectedLength) => new Polyval(key, expectedLength)); - -// node_modules/@noble/ciphers/esm/aes.js -var BLOCK_SIZE2 = 16; -var BLOCK_SIZE32 = 4; -var EMPTY_BLOCK = new Uint8Array(BLOCK_SIZE2); -var POLY2 = 283; -function mul22(n) { - return n << 1 ^ POLY2 & -(n >> 7); -} -function mul(a, b) { - let res = 0; - for (; b > 0; b >>= 1) { - res ^= a & -(b & 1); - a = mul22(a); - } - return res; -} -var sbox = (() => { - let t = new Uint8Array(256); - for (let i2 = 0, x = 1; i2 < 256; i2++, x ^= mul22(x)) - t[i2] = x; - const box = new Uint8Array(256); - box[0] = 99; - for (let i2 = 0; i2 < 255; i2++) { - let x = t[255 - i2]; - x |= x << 8; - box[t[i2]] = (x ^ x >> 4 ^ x >> 5 ^ x >> 6 ^ x >> 7 ^ 99) & 255; - } - return box; -})(); -var invSbox = sbox.map((_, j) => sbox.indexOf(j)); -var rotr32_8 = (n) => n << 24 | n >>> 8; -var rotl32_8 = (n) => n << 8 | n >>> 24; -function genTtable(sbox2, fn) { - if (sbox2.length !== 256) - throw new Error("Wrong sbox length"); - const T0 = new Uint32Array(256).map((_, j) => fn(sbox2[j])); - const T1 = T0.map(rotl32_8); - const T2 = T1.map(rotl32_8); - const T3 = T2.map(rotl32_8); - const T01 = new Uint32Array(256 * 256); - const T23 = new Uint32Array(256 * 256); - const sbox22 = new Uint16Array(256 * 256); - for (let i2 = 0; i2 < 256; i2++) { - for (let j = 0; j < 256; j++) { - const idx = i2 * 256 + j; - T01[idx] = T0[i2] ^ T1[j]; - T23[idx] = T2[i2] ^ T3[j]; - sbox22[idx] = sbox2[i2] << 8 | sbox2[j]; - } - } - return { sbox: sbox2, sbox2: sbox22, T0, T1, T2, T3, T01, T23 }; -} -var tableEncoding = genTtable(sbox, (s) => mul(s, 3) << 24 | s << 16 | s << 8 | mul(s, 2)); -var tableDecoding = genTtable(invSbox, (s) => mul(s, 11) << 24 | mul(s, 13) << 16 | mul(s, 9) << 8 | mul(s, 14)); -var xPowers = (() => { - const p = new Uint8Array(16); - for (let i2 = 0, x = 1; i2 < 16; i2++, x = mul22(x)) - p[i2] = x; - return p; -})(); -function expandKeyLE(key) { - bytes3(key); - const len = key.length; - if (![16, 24, 32].includes(len)) - throw new Error(`aes: wrong key size: should be 16, 24 or 32, got: ${len}`); - const { sbox2 } = tableEncoding; - const k32 = u32(key); - const Nk = k32.length; - const subByte = (n) => applySbox(sbox2, n, n, n, n); - const xk = new Uint32Array(len + 28); - xk.set(k32); - for (let i2 = Nk; i2 < xk.length; i2++) { - let t = xk[i2 - 1]; - if (i2 % Nk === 0) - t = subByte(rotr32_8(t)) ^ xPowers[i2 / Nk - 1]; - else if (Nk > 6 && i2 % Nk === 4) - t = subByte(t); - xk[i2] = xk[i2 - Nk] ^ t; - } - return xk; -} -function expandKeyDecLE(key) { - const encKey = expandKeyLE(key); - const xk = encKey.slice(); - const Nk = encKey.length; - const { sbox2 } = tableEncoding; - const { T0, T1, T2, T3 } = tableDecoding; - for (let i2 = 0; i2 < Nk; i2 += 4) { - for (let j = 0; j < 4; j++) - xk[i2 + j] = encKey[Nk - i2 - 4 + j]; - } - encKey.fill(0); - for (let i2 = 4; i2 < Nk - 4; i2++) { - const x = xk[i2]; - const w = applySbox(sbox2, x, x, x, x); - xk[i2] = T0[w & 255] ^ T1[w >>> 8 & 255] ^ T2[w >>> 16 & 255] ^ T3[w >>> 24]; - } - return xk; -} -function apply0123(T01, T23, s0, s1, s2, s3) { - return T01[s0 << 8 & 65280 | s1 >>> 8 & 255] ^ T23[s2 >>> 8 & 65280 | s3 >>> 24 & 255]; -} -function applySbox(sbox2, s0, s1, s2, s3) { - return sbox2[s0 & 255 | s1 & 65280] | sbox2[s2 >>> 16 & 255 | s3 >>> 16 & 65280] << 16; -} -function encrypt(xk, s0, s1, s2, s3) { - const { sbox2, T01, T23 } = tableEncoding; - let k = 0; - s0 ^= xk[k++], s1 ^= xk[k++], s2 ^= xk[k++], s3 ^= xk[k++]; - const rounds = xk.length / 4 - 2; - for (let i2 = 0; i2 < rounds; i2++) { - const t02 = xk[k++] ^ apply0123(T01, T23, s0, s1, s2, s3); - const t12 = xk[k++] ^ apply0123(T01, T23, s1, s2, s3, s0); - const t22 = xk[k++] ^ apply0123(T01, T23, s2, s3, s0, s1); - const t32 = xk[k++] ^ apply0123(T01, T23, s3, s0, s1, s2); - s0 = t02, s1 = t12, s2 = t22, s3 = t32; - } - const t0 = xk[k++] ^ applySbox(sbox2, s0, s1, s2, s3); - const t1 = xk[k++] ^ applySbox(sbox2, s1, s2, s3, s0); - const t2 = xk[k++] ^ applySbox(sbox2, s2, s3, s0, s1); - const t3 = xk[k++] ^ applySbox(sbox2, s3, s0, s1, s2); - return { s0: t0, s1: t1, s2: t2, s3: t3 }; -} -function decrypt(xk, s0, s1, s2, s3) { - const { sbox2, T01, T23 } = tableDecoding; - let k = 0; - s0 ^= xk[k++], s1 ^= xk[k++], s2 ^= xk[k++], s3 ^= xk[k++]; - const rounds = xk.length / 4 - 2; - for (let i2 = 0; i2 < rounds; i2++) { - const t02 = xk[k++] ^ apply0123(T01, T23, s0, s3, s2, s1); - const t12 = xk[k++] ^ apply0123(T01, T23, s1, s0, s3, s2); - const t22 = xk[k++] ^ apply0123(T01, T23, s2, s1, s0, s3); - const t32 = xk[k++] ^ apply0123(T01, T23, s3, s2, s1, s0); - s0 = t02, s1 = t12, s2 = t22, s3 = t32; - } - const t0 = xk[k++] ^ applySbox(sbox2, s0, s3, s2, s1); - const t1 = xk[k++] ^ applySbox(sbox2, s1, s0, s3, s2); - const t2 = xk[k++] ^ applySbox(sbox2, s2, s1, s0, s3); - const t3 = xk[k++] ^ applySbox(sbox2, s3, s2, s1, s0); - return { s0: t0, s1: t1, s2: t2, s3: t3 }; -} -function getDst(len, dst) { - if (!dst) - return new Uint8Array(len); - bytes3(dst); - if (dst.length < len) - throw new Error(`aes: wrong destination length, expected at least ${len}, got: ${dst.length}`); - return dst; -} -function ctrCounter(xk, nonce, src, dst) { - bytes3(nonce, BLOCK_SIZE2); - bytes3(src); - const srcLen = src.length; - dst = getDst(srcLen, dst); - const ctr3 = nonce; - const c32 = u32(ctr3); - let { s0, s1, s2, s3 } = encrypt(xk, c32[0], c32[1], c32[2], c32[3]); - const src32 = u32(src); - const dst32 = u32(dst); - for (let i2 = 0; i2 + 4 <= src32.length; i2 += 4) { - dst32[i2 + 0] = src32[i2 + 0] ^ s0; - dst32[i2 + 1] = src32[i2 + 1] ^ s1; - dst32[i2 + 2] = src32[i2 + 2] ^ s2; - dst32[i2 + 3] = src32[i2 + 3] ^ s3; - let carry = 1; - for (let i3 = ctr3.length - 1; i3 >= 0; i3--) { - carry = carry + (ctr3[i3] & 255) | 0; - ctr3[i3] = carry & 255; - carry >>>= 8; - } - ({ s0, s1, s2, s3 } = encrypt(xk, c32[0], c32[1], c32[2], c32[3])); - } - const start = BLOCK_SIZE2 * Math.floor(src32.length / BLOCK_SIZE32); - if (start < srcLen) { - const b32 = new Uint32Array([s0, s1, s2, s3]); - const buf = u8(b32); - for (let i2 = start, pos = 0; i2 < srcLen; i2++, pos++) - dst[i2] = src[i2] ^ buf[pos]; - } - return dst; -} -function ctr32(xk, isLE5, nonce, src, dst) { - bytes3(nonce, BLOCK_SIZE2); - bytes3(src); - dst = getDst(src.length, dst); - const ctr3 = nonce; - const c32 = u32(ctr3); - const view = createView3(ctr3); - const src32 = u32(src); - const dst32 = u32(dst); - const ctrPos = isLE5 ? 0 : 12; - const srcLen = src.length; - let ctrNum = view.getUint32(ctrPos, isLE5); - let { s0, s1, s2, s3 } = encrypt(xk, c32[0], c32[1], c32[2], c32[3]); - for (let i2 = 0; i2 + 4 <= src32.length; i2 += 4) { - dst32[i2 + 0] = src32[i2 + 0] ^ s0; - dst32[i2 + 1] = src32[i2 + 1] ^ s1; - dst32[i2 + 2] = src32[i2 + 2] ^ s2; - dst32[i2 + 3] = src32[i2 + 3] ^ s3; - ctrNum = ctrNum + 1 >>> 0; - view.setUint32(ctrPos, ctrNum, isLE5); - ({ s0, s1, s2, s3 } = encrypt(xk, c32[0], c32[1], c32[2], c32[3])); - } - const start = BLOCK_SIZE2 * Math.floor(src32.length / BLOCK_SIZE32); - if (start < srcLen) { - const b32 = new Uint32Array([s0, s1, s2, s3]); - const buf = u8(b32); - for (let i2 = start, pos = 0; i2 < srcLen; i2++, pos++) - dst[i2] = src[i2] ^ buf[pos]; - } - return dst; -} -var ctr = wrapCipher({ blockSize: 16, nonceLength: 16 }, function ctr2(key, nonce) { - bytes3(key); - bytes3(nonce, BLOCK_SIZE2); - function processCtr(buf, dst) { - const xk = expandKeyLE(key); - const n = nonce.slice(); - const out = ctrCounter(xk, n, buf, dst); - xk.fill(0); - n.fill(0); - return out; - } - return { - encrypt: (plaintext, dst) => processCtr(plaintext, dst), - decrypt: (ciphertext, dst) => processCtr(ciphertext, dst) - }; -}); -function validateBlockDecrypt(data) { - bytes3(data); - if (data.length % BLOCK_SIZE2 !== 0) { - throw new Error(`aes/(cbc-ecb).decrypt ciphertext should consist of blocks with size ${BLOCK_SIZE2}`); - } -} -function validateBlockEncrypt(plaintext, pcks5, dst) { - let outLen = plaintext.length; - const remaining = outLen % BLOCK_SIZE2; - if (!pcks5 && remaining !== 0) - throw new Error("aec/(cbc-ecb): unpadded plaintext with disabled padding"); - const b = u32(plaintext); - if (pcks5) { - let left = BLOCK_SIZE2 - remaining; - if (!left) - left = BLOCK_SIZE2; - outLen = outLen + left; - } - const out = getDst(outLen, dst); - const o = u32(out); - return { b, o, out }; -} -function validatePCKS(data, pcks5) { - if (!pcks5) - return data; - const len = data.length; - if (!len) - throw new Error(`aes/pcks5: empty ciphertext not allowed`); - const lastByte = data[len - 1]; - if (lastByte <= 0 || lastByte > 16) - throw new Error(`aes/pcks5: wrong padding byte: ${lastByte}`); - const out = data.subarray(0, -lastByte); - for (let i2 = 0; i2 < lastByte; i2++) - if (data[len - i2 - 1] !== lastByte) - throw new Error(`aes/pcks5: wrong padding`); - return out; -} -function padPCKS(left) { - const tmp = new Uint8Array(16); - const tmp32 = u32(tmp); - tmp.set(left); - const paddingByte = BLOCK_SIZE2 - left.length; - for (let i2 = BLOCK_SIZE2 - paddingByte; i2 < BLOCK_SIZE2; i2++) - tmp[i2] = paddingByte; - return tmp32; -} -var ecb = wrapCipher({ blockSize: 16 }, function ecb2(key, opts = {}) { - bytes3(key); - const pcks5 = !opts.disablePadding; - return { - encrypt: (plaintext, dst) => { - bytes3(plaintext); - const { b, o, out: _out } = validateBlockEncrypt(plaintext, pcks5, dst); - const xk = expandKeyLE(key); - let i2 = 0; - for (; i2 + 4 <= b.length; ) { - const { s0, s1, s2, s3 } = encrypt(xk, b[i2 + 0], b[i2 + 1], b[i2 + 2], b[i2 + 3]); - o[i2++] = s0, o[i2++] = s1, o[i2++] = s2, o[i2++] = s3; - } - if (pcks5) { - const tmp32 = padPCKS(plaintext.subarray(i2 * 4)); - const { s0, s1, s2, s3 } = encrypt(xk, tmp32[0], tmp32[1], tmp32[2], tmp32[3]); - o[i2++] = s0, o[i2++] = s1, o[i2++] = s2, o[i2++] = s3; - } - xk.fill(0); - return _out; - }, - decrypt: (ciphertext, dst) => { - validateBlockDecrypt(ciphertext); - const xk = expandKeyDecLE(key); - const out = getDst(ciphertext.length, dst); - const b = u32(ciphertext); - const o = u32(out); - for (let i2 = 0; i2 + 4 <= b.length; ) { - const { s0, s1, s2, s3 } = decrypt(xk, b[i2 + 0], b[i2 + 1], b[i2 + 2], b[i2 + 3]); - o[i2++] = s0, o[i2++] = s1, o[i2++] = s2, o[i2++] = s3; - } - xk.fill(0); - return validatePCKS(out, pcks5); - } - }; -}); -var cbc = wrapCipher({ blockSize: 16, nonceLength: 16 }, function cbc2(key, iv, opts = {}) { - bytes3(key); - bytes3(iv, 16); - const pcks5 = !opts.disablePadding; - return { - encrypt: (plaintext, dst) => { - const xk = expandKeyLE(key); - const { b, o, out: _out } = validateBlockEncrypt(plaintext, pcks5, dst); - const n32 = u32(iv); - let s0 = n32[0], s1 = n32[1], s2 = n32[2], s3 = n32[3]; - let i2 = 0; - for (; i2 + 4 <= b.length; ) { - s0 ^= b[i2 + 0], s1 ^= b[i2 + 1], s2 ^= b[i2 + 2], s3 ^= b[i2 + 3]; - ({ s0, s1, s2, s3 } = encrypt(xk, s0, s1, s2, s3)); - o[i2++] = s0, o[i2++] = s1, o[i2++] = s2, o[i2++] = s3; - } - if (pcks5) { - const tmp32 = padPCKS(plaintext.subarray(i2 * 4)); - s0 ^= tmp32[0], s1 ^= tmp32[1], s2 ^= tmp32[2], s3 ^= tmp32[3]; - ({ s0, s1, s2, s3 } = encrypt(xk, s0, s1, s2, s3)); - o[i2++] = s0, o[i2++] = s1, o[i2++] = s2, o[i2++] = s3; - } - xk.fill(0); - return _out; - }, - decrypt: (ciphertext, dst) => { - validateBlockDecrypt(ciphertext); - const xk = expandKeyDecLE(key); - const n32 = u32(iv); - const out = getDst(ciphertext.length, dst); - const b = u32(ciphertext); - const o = u32(out); - let s0 = n32[0], s1 = n32[1], s2 = n32[2], s3 = n32[3]; - for (let i2 = 0; i2 + 4 <= b.length; ) { - const ps0 = s0, ps1 = s1, ps2 = s2, ps3 = s3; - s0 = b[i2 + 0], s1 = b[i2 + 1], s2 = b[i2 + 2], s3 = b[i2 + 3]; - const { s0: o0, s1: o1, s2: o2, s3: o3 } = decrypt(xk, s0, s1, s2, s3); - o[i2++] = o0 ^ ps0, o[i2++] = o1 ^ ps1, o[i2++] = o2 ^ ps2, o[i2++] = o3 ^ ps3; - } - xk.fill(0); - return validatePCKS(out, pcks5); - } - }; -}); -var cfb = wrapCipher({ blockSize: 16, nonceLength: 16 }, function cfb2(key, iv) { - bytes3(key); - bytes3(iv, 16); - function processCfb(src, isEncrypt, dst) { - const xk = expandKeyLE(key); - const srcLen = src.length; - dst = getDst(srcLen, dst); - const src32 = u32(src); - const dst32 = u32(dst); - const next32 = isEncrypt ? dst32 : src32; - const n32 = u32(iv); - let s0 = n32[0], s1 = n32[1], s2 = n32[2], s3 = n32[3]; - for (let i2 = 0; i2 + 4 <= src32.length; ) { - const { s0: e0, s1: e1, s2: e2, s3: e3 } = encrypt(xk, s0, s1, s2, s3); - dst32[i2 + 0] = src32[i2 + 0] ^ e0; - dst32[i2 + 1] = src32[i2 + 1] ^ e1; - dst32[i2 + 2] = src32[i2 + 2] ^ e2; - dst32[i2 + 3] = src32[i2 + 3] ^ e3; - s0 = next32[i2++], s1 = next32[i2++], s2 = next32[i2++], s3 = next32[i2++]; - } - const start = BLOCK_SIZE2 * Math.floor(src32.length / BLOCK_SIZE32); - if (start < srcLen) { - ({ s0, s1, s2, s3 } = encrypt(xk, s0, s1, s2, s3)); - const buf = u8(new Uint32Array([s0, s1, s2, s3])); - for (let i2 = start, pos = 0; i2 < srcLen; i2++, pos++) - dst[i2] = src[i2] ^ buf[pos]; - buf.fill(0); - } - xk.fill(0); - return dst; - } - return { - encrypt: (plaintext, dst) => processCfb(plaintext, true, dst), - decrypt: (ciphertext, dst) => processCfb(ciphertext, false, dst) - }; -}); -function computeTag(fn, isLE5, key, data, AAD) { - const h = fn.create(key, data.length + ((AAD == null ? void 0 : AAD.length) || 0)); - if (AAD) - h.update(AAD); - h.update(data); - const num = new Uint8Array(16); - const view = createView3(num); - if (AAD) - setBigUint643(view, 0, BigInt(AAD.length * 8), isLE5); - setBigUint643(view, 8, BigInt(data.length * 8), isLE5); - h.update(num); - return h.digest(); -} -var gcm = wrapCipher({ blockSize: 16, nonceLength: 12, tagLength: 16 }, function gcm2(key, nonce, AAD) { - bytes3(nonce); - if (nonce.length === 0) - throw new Error("aes/gcm: empty nonce"); - const tagLength = 16; - function _computeTag(authKey, tagMask, data) { - const tag = computeTag(ghash, false, authKey, data, AAD); - for (let i2 = 0; i2 < tagMask.length; i2++) - tag[i2] ^= tagMask[i2]; - return tag; - } - function deriveKeys() { - const xk = expandKeyLE(key); - const authKey = EMPTY_BLOCK.slice(); - const counter = EMPTY_BLOCK.slice(); - ctr32(xk, false, counter, counter, authKey); - if (nonce.length === 12) { - counter.set(nonce); - } else { - const nonceLen = EMPTY_BLOCK.slice(); - const view = createView3(nonceLen); - setBigUint643(view, 8, BigInt(nonce.length * 8), false); - ghash.create(authKey).update(nonce).update(nonceLen).digestInto(counter); - } - const tagMask = ctr32(xk, false, counter, EMPTY_BLOCK); - return { xk, authKey, counter, tagMask }; - } - return { - encrypt: (plaintext) => { - bytes3(plaintext); - const { xk, authKey, counter, tagMask } = deriveKeys(); - const out = new Uint8Array(plaintext.length + tagLength); - ctr32(xk, false, counter, plaintext, out); - const tag = _computeTag(authKey, tagMask, out.subarray(0, out.length - tagLength)); - out.set(tag, plaintext.length); - xk.fill(0); - return out; - }, - decrypt: (ciphertext) => { - bytes3(ciphertext); - if (ciphertext.length < tagLength) - throw new Error(`aes/gcm: ciphertext less than tagLen (${tagLength})`); - const { xk, authKey, counter, tagMask } = deriveKeys(); - const data = ciphertext.subarray(0, -tagLength); - const passedTag = ciphertext.subarray(-tagLength); - const tag = _computeTag(authKey, tagMask, data); - if (!equalBytes2(tag, passedTag)) - throw new Error("aes/gcm: invalid ghash tag"); - const out = ctr32(xk, false, counter, data); - authKey.fill(0); - tagMask.fill(0); - xk.fill(0); - return out; - } - }; -}); -var limit = (name, min2, max2) => (value) => { - if (!Number.isSafeInteger(value) || min2 > value || value > max2) - throw new Error(`${name}: invalid value=${value}, must be [${min2}..${max2}]`); -}; -var siv = wrapCipher({ blockSize: 16, nonceLength: 12, tagLength: 16 }, function siv2(key, nonce, AAD) { - const tagLength = 16; - const AAD_LIMIT = limit("AAD", 0, 2 ** 36); - const PLAIN_LIMIT = limit("plaintext", 0, 2 ** 36); - const NONCE_LIMIT = limit("nonce", 12, 12); - const CIPHER_LIMIT = limit("ciphertext", 16, 2 ** 36 + 16); - bytes3(nonce); - NONCE_LIMIT(nonce.length); - if (AAD) { - bytes3(AAD); - AAD_LIMIT(AAD.length); - } - function deriveKeys() { - const len = key.length; - if (len !== 16 && len !== 24 && len !== 32) - throw new Error(`key length must be 16, 24 or 32 bytes, got: ${len} bytes`); - const xk = expandKeyLE(key); - const encKey = new Uint8Array(len); - const authKey = new Uint8Array(16); - const n32 = u32(nonce); - let s0 = 0, s1 = n32[0], s2 = n32[1], s3 = n32[2]; - let counter = 0; - for (const derivedKey of [authKey, encKey].map(u32)) { - const d32 = u32(derivedKey); - for (let i2 = 0; i2 < d32.length; i2 += 2) { - const { s0: o0, s1: o1 } = encrypt(xk, s0, s1, s2, s3); - d32[i2 + 0] = o0; - d32[i2 + 1] = o1; - s0 = ++counter; - } - } - xk.fill(0); - return { authKey, encKey: expandKeyLE(encKey) }; - } - function _computeTag(encKey, authKey, data) { - const tag = computeTag(polyval, true, authKey, data, AAD); - for (let i2 = 0; i2 < 12; i2++) - tag[i2] ^= nonce[i2]; - tag[15] &= 127; - const t32 = u32(tag); - let s0 = t32[0], s1 = t32[1], s2 = t32[2], s3 = t32[3]; - ({ s0, s1, s2, s3 } = encrypt(encKey, s0, s1, s2, s3)); - t32[0] = s0, t32[1] = s1, t32[2] = s2, t32[3] = s3; - return tag; - } - function processSiv(encKey, tag, input) { - let block = tag.slice(); - block[15] |= 128; - return ctr32(encKey, true, block, input); - } - return { - encrypt: (plaintext) => { - bytes3(plaintext); - PLAIN_LIMIT(plaintext.length); - const { encKey, authKey } = deriveKeys(); - const tag = _computeTag(encKey, authKey, plaintext); - const out = new Uint8Array(plaintext.length + tagLength); - out.set(tag, plaintext.length); - out.set(processSiv(encKey, tag, plaintext)); - encKey.fill(0); - authKey.fill(0); - return out; - }, - decrypt: (ciphertext) => { - bytes3(ciphertext); - CIPHER_LIMIT(ciphertext.length); - const tag = ciphertext.subarray(-tagLength); - const { encKey, authKey } = deriveKeys(); - const plaintext = processSiv(encKey, tag, ciphertext.subarray(0, -tagLength)); - const expectedTag = _computeTag(encKey, authKey, plaintext); - encKey.fill(0); - authKey.fill(0); - if (!equalBytes2(tag, expectedTag)) - throw new Error("invalid polyval tag"); - return plaintext; - } - }; -}); - -// node_modules/@noble/ciphers/esm/_poly1305.js -var u8to16 = (a, i2) => a[i2++] & 255 | (a[i2++] & 255) << 8; -var Poly1305 = class { - constructor(key) { - this.blockLen = 16; - this.outputLen = 16; - this.buffer = new Uint8Array(16); - this.r = new Uint16Array(10); - this.h = new Uint16Array(10); - this.pad = new Uint16Array(8); - this.pos = 0; - this.finished = false; - key = toBytes3(key); - bytes3(key, 32); - const t0 = u8to16(key, 0); - const t1 = u8to16(key, 2); - const t2 = u8to16(key, 4); - const t3 = u8to16(key, 6); - const t4 = u8to16(key, 8); - const t5 = u8to16(key, 10); - const t6 = u8to16(key, 12); - const t7 = u8to16(key, 14); - this.r[0] = t0 & 8191; - this.r[1] = (t0 >>> 13 | t1 << 3) & 8191; - this.r[2] = (t1 >>> 10 | t2 << 6) & 7939; - this.r[3] = (t2 >>> 7 | t3 << 9) & 8191; - this.r[4] = (t3 >>> 4 | t4 << 12) & 255; - this.r[5] = t4 >>> 1 & 8190; - this.r[6] = (t4 >>> 14 | t5 << 2) & 8191; - this.r[7] = (t5 >>> 11 | t6 << 5) & 8065; - this.r[8] = (t6 >>> 8 | t7 << 8) & 8191; - this.r[9] = t7 >>> 5 & 127; - for (let i2 = 0; i2 < 8; i2++) - this.pad[i2] = u8to16(key, 16 + 2 * i2); - } - process(data, offset, isLast = false) { - const hibit = isLast ? 0 : 1 << 11; - const { h, r } = this; - const r0 = r[0]; - const r1 = r[1]; - const r2 = r[2]; - const r3 = r[3]; - const r4 = r[4]; - const r5 = r[5]; - const r6 = r[6]; - const r7 = r[7]; - const r8 = r[8]; - const r9 = r[9]; - const t0 = u8to16(data, offset + 0); - const t1 = u8to16(data, offset + 2); - const t2 = u8to16(data, offset + 4); - const t3 = u8to16(data, offset + 6); - const t4 = u8to16(data, offset + 8); - const t5 = u8to16(data, offset + 10); - const t6 = u8to16(data, offset + 12); - const t7 = u8to16(data, offset + 14); - let h0 = h[0] + (t0 & 8191); - let h1 = h[1] + ((t0 >>> 13 | t1 << 3) & 8191); - let h2 = h[2] + ((t1 >>> 10 | t2 << 6) & 8191); - let h3 = h[3] + ((t2 >>> 7 | t3 << 9) & 8191); - let h4 = h[4] + ((t3 >>> 4 | t4 << 12) & 8191); - let h5 = h[5] + (t4 >>> 1 & 8191); - let h6 = h[6] + ((t4 >>> 14 | t5 << 2) & 8191); - let h7 = h[7] + ((t5 >>> 11 | t6 << 5) & 8191); - let h8 = h[8] + ((t6 >>> 8 | t7 << 8) & 8191); - let h9 = h[9] + (t7 >>> 5 | hibit); - let c = 0; - let d0 = c + h0 * r0 + h1 * (5 * r9) + h2 * (5 * r8) + h3 * (5 * r7) + h4 * (5 * r6); - c = d0 >>> 13; - d0 &= 8191; - d0 += h5 * (5 * r5) + h6 * (5 * r4) + h7 * (5 * r3) + h8 * (5 * r2) + h9 * (5 * r1); - c += d0 >>> 13; - d0 &= 8191; - let d1 = c + h0 * r1 + h1 * r0 + h2 * (5 * r9) + h3 * (5 * r8) + h4 * (5 * r7); - c = d1 >>> 13; - d1 &= 8191; - d1 += h5 * (5 * r6) + h6 * (5 * r5) + h7 * (5 * r4) + h8 * (5 * r3) + h9 * (5 * r2); - c += d1 >>> 13; - d1 &= 8191; - let d2 = c + h0 * r2 + h1 * r1 + h2 * r0 + h3 * (5 * r9) + h4 * (5 * r8); - c = d2 >>> 13; - d2 &= 8191; - d2 += h5 * (5 * r7) + h6 * (5 * r6) + h7 * (5 * r5) + h8 * (5 * r4) + h9 * (5 * r3); - c += d2 >>> 13; - d2 &= 8191; - let d3 = c + h0 * r3 + h1 * r2 + h2 * r1 + h3 * r0 + h4 * (5 * r9); - c = d3 >>> 13; - d3 &= 8191; - d3 += h5 * (5 * r8) + h6 * (5 * r7) + h7 * (5 * r6) + h8 * (5 * r5) + h9 * (5 * r4); - c += d3 >>> 13; - d3 &= 8191; - let d4 = c + h0 * r4 + h1 * r3 + h2 * r2 + h3 * r1 + h4 * r0; - c = d4 >>> 13; - d4 &= 8191; - d4 += h5 * (5 * r9) + h6 * (5 * r8) + h7 * (5 * r7) + h8 * (5 * r6) + h9 * (5 * r5); - c += d4 >>> 13; - d4 &= 8191; - let d5 = c + h0 * r5 + h1 * r4 + h2 * r3 + h3 * r2 + h4 * r1; - c = d5 >>> 13; - d5 &= 8191; - d5 += h5 * r0 + h6 * (5 * r9) + h7 * (5 * r8) + h8 * (5 * r7) + h9 * (5 * r6); - c += d5 >>> 13; - d5 &= 8191; - let d6 = c + h0 * r6 + h1 * r5 + h2 * r4 + h3 * r3 + h4 * r2; - c = d6 >>> 13; - d6 &= 8191; - d6 += h5 * r1 + h6 * r0 + h7 * (5 * r9) + h8 * (5 * r8) + h9 * (5 * r7); - c += d6 >>> 13; - d6 &= 8191; - let d7 = c + h0 * r7 + h1 * r6 + h2 * r5 + h3 * r4 + h4 * r3; - c = d7 >>> 13; - d7 &= 8191; - d7 += h5 * r2 + h6 * r1 + h7 * r0 + h8 * (5 * r9) + h9 * (5 * r8); - c += d7 >>> 13; - d7 &= 8191; - let d8 = c + h0 * r8 + h1 * r7 + h2 * r6 + h3 * r5 + h4 * r4; - c = d8 >>> 13; - d8 &= 8191; - d8 += h5 * r3 + h6 * r2 + h7 * r1 + h8 * r0 + h9 * (5 * r9); - c += d8 >>> 13; - d8 &= 8191; - let d9 = c + h0 * r9 + h1 * r8 + h2 * r7 + h3 * r6 + h4 * r5; - c = d9 >>> 13; - d9 &= 8191; - d9 += h5 * r4 + h6 * r3 + h7 * r2 + h8 * r1 + h9 * r0; - c += d9 >>> 13; - d9 &= 8191; - c = (c << 2) + c | 0; - c = c + d0 | 0; - d0 = c & 8191; - c = c >>> 13; - d1 += c; - h[0] = d0; - h[1] = d1; - h[2] = d2; - h[3] = d3; - h[4] = d4; - h[5] = d5; - h[6] = d6; - h[7] = d7; - h[8] = d8; - h[9] = d9; - } - finalize() { - const { h, pad: pad2 } = this; - const g = new Uint16Array(10); - let c = h[1] >>> 13; - h[1] &= 8191; - for (let i2 = 2; i2 < 10; i2++) { - h[i2] += c; - c = h[i2] >>> 13; - h[i2] &= 8191; - } - h[0] += c * 5; - c = h[0] >>> 13; - h[0] &= 8191; - h[1] += c; - c = h[1] >>> 13; - h[1] &= 8191; - h[2] += c; - g[0] = h[0] + 5; - c = g[0] >>> 13; - g[0] &= 8191; - for (let i2 = 1; i2 < 10; i2++) { - g[i2] = h[i2] + c; - c = g[i2] >>> 13; - g[i2] &= 8191; - } - g[9] -= 1 << 13; - let mask = (c ^ 1) - 1; - for (let i2 = 0; i2 < 10; i2++) - g[i2] &= mask; - mask = ~mask; - for (let i2 = 0; i2 < 10; i2++) - h[i2] = h[i2] & mask | g[i2]; - h[0] = (h[0] | h[1] << 13) & 65535; - h[1] = (h[1] >>> 3 | h[2] << 10) & 65535; - h[2] = (h[2] >>> 6 | h[3] << 7) & 65535; - h[3] = (h[3] >>> 9 | h[4] << 4) & 65535; - h[4] = (h[4] >>> 12 | h[5] << 1 | h[6] << 14) & 65535; - h[5] = (h[6] >>> 2 | h[7] << 11) & 65535; - h[6] = (h[7] >>> 5 | h[8] << 8) & 65535; - h[7] = (h[8] >>> 8 | h[9] << 5) & 65535; - let f = h[0] + pad2[0]; - h[0] = f & 65535; - for (let i2 = 1; i2 < 8; i2++) { - f = (h[i2] + pad2[i2] | 0) + (f >>> 16) | 0; - h[i2] = f & 65535; - } - } - update(data) { - exists3(this); - const { buffer: buffer2, blockLen } = this; - data = toBytes3(data); - const len = data.length; - for (let pos = 0; pos < len; ) { - const take2 = Math.min(blockLen - this.pos, len - pos); - if (take2 === blockLen) { - for (; blockLen <= len - pos; pos += blockLen) - this.process(data, pos); - continue; - } - buffer2.set(data.subarray(pos, pos + take2), this.pos); - this.pos += take2; - pos += take2; - if (this.pos === blockLen) { - this.process(buffer2, 0, false); - this.pos = 0; - } - } - return this; - } - destroy() { - this.h.fill(0); - this.r.fill(0); - this.buffer.fill(0); - this.pad.fill(0); - } - digestInto(out) { - exists3(this); - output3(out, this); - this.finished = true; - const { buffer: buffer2, h } = this; - let { pos } = this; - if (pos) { - buffer2[pos++] = 1; - for (; pos < 16; pos++) - buffer2[pos] = 0; - this.process(buffer2, 0, true); - } - this.finalize(); - let opos = 0; - for (let i2 = 0; i2 < 8; i2++) { - out[opos++] = h[i2] >>> 0; - out[opos++] = h[i2] >>> 8; - } - return out; - } - digest() { - const { buffer: buffer2, outputLen } = this; - this.digestInto(buffer2); - const res = buffer2.slice(0, outputLen); - this.destroy(); - return res; - } -}; -function wrapConstructorWithKey2(hashCons) { - const hashC = (msg, key) => hashCons(key).update(toBytes3(msg)).digest(); - const tmp = hashCons(new Uint8Array(32)); - hashC.outputLen = tmp.outputLen; - hashC.blockLen = tmp.blockLen; - hashC.create = (key) => hashCons(key); - return hashC; -} -var poly1305 = wrapConstructorWithKey2((key) => new Poly1305(key)); - -// node_modules/@noble/ciphers/esm/_arx.js -var _utf8ToBytes = (str) => Uint8Array.from(str.split("").map((c) => c.charCodeAt(0))); -var sigma16 = _utf8ToBytes("expand 16-byte k"); -var sigma32 = _utf8ToBytes("expand 32-byte k"); -var sigma16_32 = u32(sigma16); -var sigma32_32 = u32(sigma32); -var sigma = sigma32_32.slice(); -function rotl(a, b) { - return a << b | a >>> 32 - b; -} -function isAligned32(b) { - return b.byteOffset % 4 === 0; -} -var BLOCK_LEN = 64; -var BLOCK_LEN32 = 16; -var MAX_COUNTER = 2 ** 32 - 1; -var U32_EMPTY = new Uint32Array(); -function runCipher(core, sigma2, key, nonce, data, output4, counter, rounds) { - const len = data.length; - const block = new Uint8Array(BLOCK_LEN); - const b32 = u32(block); - const isAligned = isAligned32(data) && isAligned32(output4); - const d32 = isAligned ? u32(data) : U32_EMPTY; - const o32 = isAligned ? u32(output4) : U32_EMPTY; - for (let pos = 0; pos < len; counter++) { - core(sigma2, key, nonce, b32, counter, rounds); - if (counter >= MAX_COUNTER) - throw new Error("arx: counter overflow"); - const take2 = Math.min(BLOCK_LEN, len - pos); - if (isAligned && take2 === BLOCK_LEN) { - const pos32 = pos / 4; - if (pos % 4 !== 0) - throw new Error("arx: invalid block position"); - for (let j = 0, posj; j < BLOCK_LEN32; j++) { - posj = pos32 + j; - o32[posj] = d32[posj] ^ b32[j]; - } - pos += BLOCK_LEN; - continue; - } - for (let j = 0, posj; j < take2; j++) { - posj = pos + j; - output4[posj] = data[posj] ^ block[j]; - } - pos += take2; - } -} -function createCipher(core, opts) { - const { allowShortKeys, extendNonceFn, counterLength, counterRight, rounds } = checkOpts({ allowShortKeys: false, counterLength: 8, counterRight: false, rounds: 20 }, opts); - if (typeof core !== "function") - throw new Error("core must be a function"); - number3(counterLength); - number3(rounds); - bool2(counterRight); - bool2(allowShortKeys); - return (key, nonce, data, output4, counter = 0) => { - bytes3(key); - bytes3(nonce); - bytes3(data); - const len = data.length; - if (!output4) - output4 = new Uint8Array(len); - bytes3(output4); - number3(counter); - if (counter < 0 || counter >= MAX_COUNTER) - throw new Error("arx: counter overflow"); - if (output4.length < len) - throw new Error(`arx: output (${output4.length}) is shorter than data (${len})`); - const toClean = []; - let l = key.length, k, sigma2; - if (l === 32) { - k = key.slice(); - toClean.push(k); - sigma2 = sigma32_32; - } else if (l === 16 && allowShortKeys) { - k = new Uint8Array(32); - k.set(key); - k.set(key, 16); - sigma2 = sigma16_32; - toClean.push(k); - } else { - throw new Error(`arx: invalid 32-byte key, got length=${l}`); - } - if (!isAligned32(nonce)) { - nonce = nonce.slice(); - toClean.push(nonce); - } - const k32 = u32(k); - if (extendNonceFn) { - if (nonce.length !== 24) - throw new Error(`arx: extended nonce must be 24 bytes`); - extendNonceFn(sigma2, k32, u32(nonce.subarray(0, 16)), k32); - nonce = nonce.subarray(16); - } - const nonceNcLen = 16 - counterLength; - if (nonceNcLen !== nonce.length) - throw new Error(`arx: nonce must be ${nonceNcLen} or 16 bytes`); - if (nonceNcLen !== 12) { - const nc = new Uint8Array(12); - nc.set(nonce, counterRight ? 0 : 12 - nonce.length); - nonce = nc; - toClean.push(nonce); - } - const n32 = u32(nonce); - runCipher(core, sigma2, k32, n32, data, output4, counter, rounds); - while (toClean.length > 0) - toClean.pop().fill(0); - return output4; - }; -} - -// node_modules/@noble/ciphers/esm/chacha.js -function chachaCore(s, k, n, out, cnt, rounds = 20) { - let y00 = s[0], y01 = s[1], y02 = s[2], y03 = s[3], y04 = k[0], y05 = k[1], y06 = k[2], y07 = k[3], y08 = k[4], y09 = k[5], y10 = k[6], y11 = k[7], y12 = cnt, y13 = n[0], y14 = n[1], y15 = n[2]; - let x00 = y00, x01 = y01, x02 = y02, x03 = y03, x04 = y04, x05 = y05, x06 = y06, x07 = y07, x08 = y08, x09 = y09, x10 = y10, x11 = y11, x12 = y12, x13 = y13, x14 = y14, x15 = y15; - for (let r = 0; r < rounds; r += 2) { - x00 = x00 + x04 | 0; - x12 = rotl(x12 ^ x00, 16); - x08 = x08 + x12 | 0; - x04 = rotl(x04 ^ x08, 12); - x00 = x00 + x04 | 0; - x12 = rotl(x12 ^ x00, 8); - x08 = x08 + x12 | 0; - x04 = rotl(x04 ^ x08, 7); - x01 = x01 + x05 | 0; - x13 = rotl(x13 ^ x01, 16); - x09 = x09 + x13 | 0; - x05 = rotl(x05 ^ x09, 12); - x01 = x01 + x05 | 0; - x13 = rotl(x13 ^ x01, 8); - x09 = x09 + x13 | 0; - x05 = rotl(x05 ^ x09, 7); - x02 = x02 + x06 | 0; - x14 = rotl(x14 ^ x02, 16); - x10 = x10 + x14 | 0; - x06 = rotl(x06 ^ x10, 12); - x02 = x02 + x06 | 0; - x14 = rotl(x14 ^ x02, 8); - x10 = x10 + x14 | 0; - x06 = rotl(x06 ^ x10, 7); - x03 = x03 + x07 | 0; - x15 = rotl(x15 ^ x03, 16); - x11 = x11 + x15 | 0; - x07 = rotl(x07 ^ x11, 12); - x03 = x03 + x07 | 0; - x15 = rotl(x15 ^ x03, 8); - x11 = x11 + x15 | 0; - x07 = rotl(x07 ^ x11, 7); - x00 = x00 + x05 | 0; - x15 = rotl(x15 ^ x00, 16); - x10 = x10 + x15 | 0; - x05 = rotl(x05 ^ x10, 12); - x00 = x00 + x05 | 0; - x15 = rotl(x15 ^ x00, 8); - x10 = x10 + x15 | 0; - x05 = rotl(x05 ^ x10, 7); - x01 = x01 + x06 | 0; - x12 = rotl(x12 ^ x01, 16); - x11 = x11 + x12 | 0; - x06 = rotl(x06 ^ x11, 12); - x01 = x01 + x06 | 0; - x12 = rotl(x12 ^ x01, 8); - x11 = x11 + x12 | 0; - x06 = rotl(x06 ^ x11, 7); - x02 = x02 + x07 | 0; - x13 = rotl(x13 ^ x02, 16); - x08 = x08 + x13 | 0; - x07 = rotl(x07 ^ x08, 12); - x02 = x02 + x07 | 0; - x13 = rotl(x13 ^ x02, 8); - x08 = x08 + x13 | 0; - x07 = rotl(x07 ^ x08, 7); - x03 = x03 + x04 | 0; - x14 = rotl(x14 ^ x03, 16); - x09 = x09 + x14 | 0; - x04 = rotl(x04 ^ x09, 12); - x03 = x03 + x04 | 0; - x14 = rotl(x14 ^ x03, 8); - x09 = x09 + x14 | 0; - x04 = rotl(x04 ^ x09, 7); - } - let oi = 0; - out[oi++] = y00 + x00 | 0; - out[oi++] = y01 + x01 | 0; - out[oi++] = y02 + x02 | 0; - out[oi++] = y03 + x03 | 0; - out[oi++] = y04 + x04 | 0; - out[oi++] = y05 + x05 | 0; - out[oi++] = y06 + x06 | 0; - out[oi++] = y07 + x07 | 0; - out[oi++] = y08 + x08 | 0; - out[oi++] = y09 + x09 | 0; - out[oi++] = y10 + x10 | 0; - out[oi++] = y11 + x11 | 0; - out[oi++] = y12 + x12 | 0; - out[oi++] = y13 + x13 | 0; - out[oi++] = y14 + x14 | 0; - out[oi++] = y15 + x15 | 0; -} -function hchacha(s, k, i2, o32) { - let x00 = s[0], x01 = s[1], x02 = s[2], x03 = s[3], x04 = k[0], x05 = k[1], x06 = k[2], x07 = k[3], x08 = k[4], x09 = k[5], x10 = k[6], x11 = k[7], x12 = i2[0], x13 = i2[1], x14 = i2[2], x15 = i2[3]; - for (let r = 0; r < 20; r += 2) { - x00 = x00 + x04 | 0; - x12 = rotl(x12 ^ x00, 16); - x08 = x08 + x12 | 0; - x04 = rotl(x04 ^ x08, 12); - x00 = x00 + x04 | 0; - x12 = rotl(x12 ^ x00, 8); - x08 = x08 + x12 | 0; - x04 = rotl(x04 ^ x08, 7); - x01 = x01 + x05 | 0; - x13 = rotl(x13 ^ x01, 16); - x09 = x09 + x13 | 0; - x05 = rotl(x05 ^ x09, 12); - x01 = x01 + x05 | 0; - x13 = rotl(x13 ^ x01, 8); - x09 = x09 + x13 | 0; - x05 = rotl(x05 ^ x09, 7); - x02 = x02 + x06 | 0; - x14 = rotl(x14 ^ x02, 16); - x10 = x10 + x14 | 0; - x06 = rotl(x06 ^ x10, 12); - x02 = x02 + x06 | 0; - x14 = rotl(x14 ^ x02, 8); - x10 = x10 + x14 | 0; - x06 = rotl(x06 ^ x10, 7); - x03 = x03 + x07 | 0; - x15 = rotl(x15 ^ x03, 16); - x11 = x11 + x15 | 0; - x07 = rotl(x07 ^ x11, 12); - x03 = x03 + x07 | 0; - x15 = rotl(x15 ^ x03, 8); - x11 = x11 + x15 | 0; - x07 = rotl(x07 ^ x11, 7); - x00 = x00 + x05 | 0; - x15 = rotl(x15 ^ x00, 16); - x10 = x10 + x15 | 0; - x05 = rotl(x05 ^ x10, 12); - x00 = x00 + x05 | 0; - x15 = rotl(x15 ^ x00, 8); - x10 = x10 + x15 | 0; - x05 = rotl(x05 ^ x10, 7); - x01 = x01 + x06 | 0; - x12 = rotl(x12 ^ x01, 16); - x11 = x11 + x12 | 0; - x06 = rotl(x06 ^ x11, 12); - x01 = x01 + x06 | 0; - x12 = rotl(x12 ^ x01, 8); - x11 = x11 + x12 | 0; - x06 = rotl(x06 ^ x11, 7); - x02 = x02 + x07 | 0; - x13 = rotl(x13 ^ x02, 16); - x08 = x08 + x13 | 0; - x07 = rotl(x07 ^ x08, 12); - x02 = x02 + x07 | 0; - x13 = rotl(x13 ^ x02, 8); - x08 = x08 + x13 | 0; - x07 = rotl(x07 ^ x08, 7); - x03 = x03 + x04 | 0; - x14 = rotl(x14 ^ x03, 16); - x09 = x09 + x14 | 0; - x04 = rotl(x04 ^ x09, 12); - x03 = x03 + x04 | 0; - x14 = rotl(x14 ^ x03, 8); - x09 = x09 + x14 | 0; - x04 = rotl(x04 ^ x09, 7); - } - let oi = 0; - o32[oi++] = x00; - o32[oi++] = x01; - o32[oi++] = x02; - o32[oi++] = x03; - o32[oi++] = x12; - o32[oi++] = x13; - o32[oi++] = x14; - o32[oi++] = x15; -} -var chacha20orig = createCipher(chachaCore, { - counterRight: false, - counterLength: 8, - allowShortKeys: true -}); -var chacha20 = createCipher(chachaCore, { - counterRight: false, - counterLength: 4, - allowShortKeys: false -}); -var xchacha20 = createCipher(chachaCore, { - counterRight: false, - counterLength: 8, - extendNonceFn: hchacha, - allowShortKeys: false -}); -var chacha8 = createCipher(chachaCore, { - counterRight: false, - counterLength: 4, - rounds: 8 -}); -var chacha12 = createCipher(chachaCore, { - counterRight: false, - counterLength: 4, - rounds: 12 -}); -var ZEROS162 = new Uint8Array(16); -var updatePadded = (h, msg) => { - h.update(msg); - const left = msg.length % 16; - if (left) - h.update(ZEROS162.subarray(left)); -}; -var ZEROS322 = new Uint8Array(32); -function computeTag2(fn, key, nonce, data, AAD) { - const authKey = fn(key, nonce, ZEROS322); - const h = poly1305.create(authKey); - if (AAD) - updatePadded(h, AAD); - updatePadded(h, data); - const num = new Uint8Array(16); - const view = createView3(num); - setBigUint643(view, 0, BigInt(AAD ? AAD.length : 0), true); - setBigUint643(view, 8, BigInt(data.length), true); - h.update(num); - const res = h.digest(); - authKey.fill(0); - return res; -} -var _poly1305_aead = (xorStream) => (key, nonce, AAD) => { - const tagLength = 16; - bytes3(key, 32); - bytes3(nonce); - return { - encrypt: (plaintext, output4) => { - const plength = plaintext.length; - const clength = plength + tagLength; - if (output4) { - bytes3(output4, clength); - } else { - output4 = new Uint8Array(clength); - } - xorStream(key, nonce, plaintext, output4, 1); - const tag = computeTag2(xorStream, key, nonce, output4.subarray(0, -tagLength), AAD); - output4.set(tag, plength); - return output4; - }, - decrypt: (ciphertext, output4) => { - const clength = ciphertext.length; - const plength = clength - tagLength; - if (clength < tagLength) - throw new Error(`encrypted data must be at least ${tagLength} bytes`); - if (output4) { - bytes3(output4, plength); - } else { - output4 = new Uint8Array(plength); - } - const data = ciphertext.subarray(0, -tagLength); - const passedTag = ciphertext.subarray(-tagLength); - const tag = computeTag2(xorStream, key, nonce, data, AAD); - if (!equalBytes2(passedTag, tag)) - throw new Error("invalid tag"); - xorStream(key, nonce, data, output4, 1); - return output4; - } - }; -}; -var chacha20poly1305 = wrapCipher({ blockSize: 64, nonceLength: 12, tagLength: 16 }, _poly1305_aead(chacha20)); -var xchacha20poly1305 = wrapCipher({ blockSize: 64, nonceLength: 24, tagLength: 16 }, _poly1305_aead(xchacha20)); - -// node_modules/nostr-tools/node_modules/@noble/hashes/esm/hmac.js -var HMAC2 = class extends Hash2 { - constructor(hash3, _key) { - super(); - this.finished = false; - this.destroyed = false; - assert_default.hash(hash3); - const key = toBytes2(_key); - this.iHash = hash3.create(); - if (typeof this.iHash.update !== "function") - throw new Error("Expected instance of class which extends utils.Hash"); - this.blockLen = this.iHash.blockLen; - this.outputLen = this.iHash.outputLen; - const blockLen = this.blockLen; - const pad2 = new Uint8Array(blockLen); - pad2.set(key.length > blockLen ? hash3.create().update(key).digest() : key); - for (let i2 = 0; i2 < pad2.length; i2++) - pad2[i2] ^= 54; - this.iHash.update(pad2); - this.oHash = hash3.create(); - for (let i2 = 0; i2 < pad2.length; i2++) - pad2[i2] ^= 54 ^ 92; - this.oHash.update(pad2); - pad2.fill(0); - } - update(buf) { - assert_default.exists(this); - this.iHash.update(buf); - return this; - } - digestInto(out) { - assert_default.exists(this); - assert_default.bytes(out, this.outputLen); - this.finished = true; - this.iHash.digestInto(out); - this.oHash.update(out); - this.oHash.digestInto(out); - this.destroy(); - } - digest() { - const out = new Uint8Array(this.oHash.outputLen); - this.digestInto(out); - return out; - } - _cloneInto(to) { - to || (to = Object.create(Object.getPrototypeOf(this), {})); - const { oHash, iHash, finished, destroyed, blockLen, outputLen } = this; - to = to; - to.finished = finished; - to.destroyed = destroyed; - to.blockLen = blockLen; - to.outputLen = outputLen; - to.oHash = oHash._cloneInto(to.oHash); - to.iHash = iHash._cloneInto(to.iHash); - return to; - } - destroy() { - this.destroyed = true; - this.oHash.destroy(); - this.iHash.destroy(); - } -}; -var hmac2 = (hash3, key, message) => new HMAC2(hash3, key).update(message).digest(); -hmac2.create = (hash3, key) => new HMAC2(hash3, key); - -// node_modules/nostr-tools/node_modules/@noble/hashes/esm/hkdf.js -function extract(hash3, ikm, salt) { - assert_default.hash(hash3); - if (salt === void 0) - salt = new Uint8Array(hash3.outputLen); - return hmac2(hash3, toBytes2(salt), toBytes2(ikm)); -} -var HKDF_COUNTER = new Uint8Array([0]); -var EMPTY_BUFFER = new Uint8Array(); -function expand(hash3, prk, info, length = 32) { - assert_default.hash(hash3); - assert_default.number(length); - if (length > 255 * hash3.outputLen) - throw new Error("Length should be <= 255*HashLen"); - const blocks = Math.ceil(length / hash3.outputLen); - if (info === void 0) - info = EMPTY_BUFFER; - const okm = new Uint8Array(blocks * hash3.outputLen); - const HMAC3 = hmac2.create(hash3, prk); - const HMACTmp = HMAC3._cloneInto(); - const T = new Uint8Array(HMAC3.outputLen); - for (let counter = 0; counter < blocks; counter++) { - HKDF_COUNTER[0] = counter + 1; - HMACTmp.update(counter === 0 ? EMPTY_BUFFER : T).update(info).update(HKDF_COUNTER).digestInto(T); - okm.set(T, hash3.outputLen * counter); - HMAC3._cloneInto(HMACTmp); - } - HMAC3.destroy(); - HMACTmp.destroy(); - T.fill(0); - HKDF_COUNTER.fill(0); - return okm.slice(0, length); -} - -// node_modules/nostr-tools/lib/esm/index.js -var __defProp = Object.defineProperty; -var __export2 = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); -}; -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; -} -var utils_exports2 = {}; -__export2(utils_exports2, { - Queue: () => Queue, - QueueNode: () => QueueNode, - binarySearch: () => binarySearch, - bytesToHex: () => bytesToHex2, - hexToBytes: () => hexToBytes2, - insertEventIntoAscendingList: () => insertEventIntoAscendingList, - insertEventIntoDescendingList: () => insertEventIntoDescendingList, - normalizeURL: () => normalizeURL, - utf8Decoder: () => utf8Decoder, - utf8Encoder: () => utf8Encoder -}); -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); - 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}`); - } -} -function insertEventIntoDescendingList(sortedArray, event) { - const [idx, found] = binarySearch(sortedArray, (b) => { - if (event.id === b.id) - return 0; - if (event.created_at === b.created_at) - return -1; - return b.created_at - event.created_at; - }); - if (!found) { - sortedArray.splice(idx, 0, event); - } - return sortedArray; -} -function insertEventIntoAscendingList(sortedArray, event) { - const [idx, found] = binarySearch(sortedArray, (b) => { - if (event.id === b.id) - return 0; - if (event.created_at === b.created_at) - return -1; - return event.created_at - b.created_at; - }); - if (!found) { - sortedArray.splice(idx, 0, event); - } - return sortedArray; -} -function binarySearch(arr, compare) { - let start = 0; - let end = arr.length - 1; - while (start <= end) { - const mid = Math.floor((start + end) / 2); - const cmp = compare(arr[mid]); - if (cmp === 0) { - return [mid, true]; - } - if (cmp < 0) { - end = mid - 1; - } else { - start = mid + 1; - } - } - return [start, false]; -} -var QueueNode = class { - constructor(message) { - __publicField(this, "value"); - __publicField(this, "next", null); - __publicField(this, "prev", null); - this.value = message; - } -}; -var Queue = class { - constructor() { - __publicField(this, "first"); - __publicField(this, "last"); - 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; - } -}; -var JS = class { - generateSecretKey() { - return schnorr.utils.randomPrivateKey(); - } - getPublicKey(secretKey) { - return bytesToHex2(schnorr.getPublicKey(secretKey)); - } - finalizeEvent(t, secretKey) { - const event = t; - event.pubkey = bytesToHex2(schnorr.getPublicKey(secretKey)); - event.id = getEventHash(event); - event.sig = bytesToHex2(schnorr.sign(getEventHash(event), secretKey)); - event[verifiedSymbol] = true; - return event; - } - verifyEvent(event) { - if (typeof event[verifiedSymbol] === "boolean") - return event[verifiedSymbol]; - const hash3 = getEventHash(event); - if (hash3 !== event.id) { - event[verifiedSymbol] = false; - return false; - } - try { - const valid = schnorr.verify(event.sig, hash3, 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 = sha2562(utf8Encoder.encode(serializeEvent(event))); - return bytesToHex2(eventHash); -} -var i = new JS(); -var generateSecretKey = i.generateSecretKey; -var getPublicKey = i.getPublicKey; -var finalizeEvent = i.finalizeEvent; -var verifyEvent = i.verifyEvent; -var kinds_exports = {}; -__export2(kinds_exports, { - Application: () => Application, - BadgeAward: () => BadgeAward, - BadgeDefinition: () => BadgeDefinition, - BlockedRelaysList: () => BlockedRelaysList, - BookmarkList: () => BookmarkList, - Bookmarksets: () => Bookmarksets, - Calendar: () => Calendar, - CalendarEventRSVP: () => CalendarEventRSVP, - ChannelCreation: () => ChannelCreation, - ChannelHideMessage: () => ChannelHideMessage, - ChannelMessage: () => ChannelMessage, - ChannelMetadata: () => ChannelMetadata, - ChannelMuteUser: () => ChannelMuteUser, - ClassifiedListing: () => ClassifiedListing, - ClientAuth: () => ClientAuth, - CommunitiesList: () => CommunitiesList, - CommunityDefinition: () => CommunityDefinition, - CommunityPostApproval: () => CommunityPostApproval, - Contacts: () => Contacts, - CreateOrUpdateProduct: () => CreateOrUpdateProduct, - CreateOrUpdateStall: () => CreateOrUpdateStall, - Curationsets: () => Curationsets, - Date: () => Date2, - DirectMessageRelaysList: () => DirectMessageRelaysList, - DraftClassifiedListing: () => DraftClassifiedListing, - DraftLong: () => DraftLong, - Emojisets: () => Emojisets, - EncryptedDirectMessage: () => EncryptedDirectMessage, - EventDeletion: () => EventDeletion, - FileMetadata: () => FileMetadata, - FileServerPreference: () => FileServerPreference, - Followsets: () => Followsets, - GenericRepost: () => GenericRepost, - Genericlists: () => Genericlists, - GiftWrap: () => GiftWrap, - HTTPAuth: () => HTTPAuth, - Handlerinformation: () => Handlerinformation, - Handlerrecommendation: () => Handlerrecommendation, - Highlights: () => Highlights, - InterestsList: () => InterestsList, - Interestsets: () => Interestsets, - JobFeedback: () => JobFeedback, - JobRequest: () => JobRequest, - JobResult: () => JobResult, - Label: () => Label, - LightningPubRPC: () => LightningPubRPC, - LiveChatMessage: () => LiveChatMessage, - LiveEvent: () => LiveEvent, - LongFormArticle: () => LongFormArticle, - Metadata: () => Metadata, - Mutelist: () => Mutelist, - NWCWalletInfo: () => NWCWalletInfo, - NWCWalletRequest: () => NWCWalletRequest, - NWCWalletResponse: () => NWCWalletResponse, - NostrConnect: () => NostrConnect, - OpenTimestamps: () => OpenTimestamps, - Pinlist: () => Pinlist, - PrivateDirectMessage: () => PrivateDirectMessage, - ProblemTracker: () => ProblemTracker, - ProfileBadges: () => ProfileBadges, - PublicChatsList: () => PublicChatsList, - Reaction: () => Reaction, - RecommendRelay: () => RecommendRelay, - RelayList: () => RelayList, - Relaysets: () => Relaysets, - Report: () => Report, - Reporting: () => Reporting, - Repost: () => Repost, - Seal: () => Seal, - SearchRelaysList: () => SearchRelaysList, - ShortTextNote: () => ShortTextNote, - Time: () => Time, - UserEmojiList: () => UserEmojiList, - UserStatuses: () => UserStatuses, - Zap: () => Zap, - ZapGoal: () => ZapGoal, - ZapRequest: () => ZapRequest, - classifyKind: () => classifyKind, - isAddressableKind: () => isAddressableKind, - isEphemeralKind: () => isEphemeralKind, - isKind: () => isKind, - isRegularKind: () => isRegularKind, - isReplaceableKind: () => isReplaceableKind -}); -function isRegularKind(kind) { - return 1e3 <= kind && kind < 1e4 || [1, 2, 4, 5, 6, 7, 8, 16, 40, 41, 42, 43, 44].includes(kind); -} -function isReplaceableKind(kind) { - return [0, 3].includes(kind) || 1e4 <= kind && kind < 2e4; -} -function isEphemeralKind(kind) { - return 2e4 <= kind && kind < 3e4; -} -function isAddressableKind(kind) { - return 3e4 <= kind && kind < 4e4; -} -function classifyKind(kind) { - if (isRegularKind(kind)) - return "regular"; - if (isReplaceableKind(kind)) - return "replaceable"; - if (isEphemeralKind(kind)) - return "ephemeral"; - if (isAddressableKind(kind)) - return "parameterized"; - return "unknown"; -} -function isKind(event, kind) { - const kindAsArray = kind instanceof Array ? kind : [kind]; - return validateEvent(event) && kindAsArray.includes(event.kind) || false; -} -var Metadata = 0; -var ShortTextNote = 1; -var RecommendRelay = 2; -var Contacts = 3; -var EncryptedDirectMessage = 4; -var EventDeletion = 5; -var Repost = 6; -var Reaction = 7; -var BadgeAward = 8; -var Seal = 13; -var PrivateDirectMessage = 14; -var GenericRepost = 16; -var ChannelCreation = 40; -var ChannelMetadata = 41; -var ChannelMessage = 42; -var ChannelHideMessage = 43; -var ChannelMuteUser = 44; -var OpenTimestamps = 1040; -var GiftWrap = 1059; -var FileMetadata = 1063; -var LiveChatMessage = 1311; -var ProblemTracker = 1971; -var Report = 1984; -var Reporting = 1984; -var Label = 1985; -var CommunityPostApproval = 4550; -var JobRequest = 5999; -var JobResult = 6999; -var JobFeedback = 7e3; -var ZapGoal = 9041; -var ZapRequest = 9734; -var Zap = 9735; -var Highlights = 9802; -var Mutelist = 1e4; -var Pinlist = 10001; -var RelayList = 10002; -var BookmarkList = 10003; -var CommunitiesList = 10004; -var PublicChatsList = 10005; -var BlockedRelaysList = 10006; -var SearchRelaysList = 10007; -var InterestsList = 10015; -var UserEmojiList = 10030; -var DirectMessageRelaysList = 10050; -var FileServerPreference = 10096; -var NWCWalletInfo = 13194; -var LightningPubRPC = 21e3; -var ClientAuth = 22242; -var NWCWalletRequest = 23194; -var NWCWalletResponse = 23195; -var NostrConnect = 24133; -var HTTPAuth = 27235; -var Followsets = 3e4; -var Genericlists = 30001; -var Relaysets = 30002; -var Bookmarksets = 30003; -var Curationsets = 30004; -var ProfileBadges = 30008; -var BadgeDefinition = 30009; -var Interestsets = 30015; -var CreateOrUpdateStall = 30017; -var CreateOrUpdateProduct = 30018; -var LongFormArticle = 30023; -var DraftLong = 30024; -var Emojisets = 30030; -var Application = 30078; -var LiveEvent = 30311; -var UserStatuses = 30315; -var ClassifiedListing = 30402; -var DraftClassifiedListing = 30403; -var Date2 = 31922; -var Time = 31923; -var Calendar = 31924; -var CalendarEventRSVP = 31925; -var Handlerrecommendation = 31989; -var Handlerinformation = 31990; -var CommunityDefinition = 34550; -var fakejson_exports = {}; -__export2(fakejson_exports, { - getHex64: () => getHex64, - getInt: () => getInt, - getSubscriptionId: () => getSubscriptionId, - matchEventId: () => matchEventId, - matchEventKind: () => matchEventKind, - matchEventPubkey: () => matchEventPubkey -}); -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 getInt(json, field) { - let len = field.length; - let idx = json.indexOf(`"${field}":`) + len + 3; - let sliced = json.slice(idx); - let end = Math.min(sliced.indexOf(","), sliced.indexOf("}")); - return parseInt(sliced.slice(0, end), 10); -} -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); -} -function matchEventId(json, id) { - return id === getHex64(json, "id"); -} -function matchEventPubkey(json, pubkey) { - return pubkey === getHex64(json, "pubkey"); -} -function matchEventKind(json, kind) { - return kind === getInt(json, "kind"); -} -var nip42_exports = {}; -__export2(nip42_exports, { - makeAuthEvent: () => makeAuthEvent -}); -function makeAuthEvent(relayURL, challenge2) { - return { - kind: ClientAuth, - created_at: Math.floor(Date.now() / 1e3), - tags: [ - ["relay", relayURL], - ["challenge", challenge2] - ], - content: "" - }; -} -var _WebSocket; -try { - _WebSocket = WebSocket; -} catch { -} -var _WebSocket2; -try { - _WebSocket2 = WebSocket; -} catch { -} -var nip19_exports = {}; -__export2(nip19_exports, { - BECH32_REGEX: () => BECH32_REGEX, - Bech32MaxSize: () => Bech32MaxSize, - NostrTypeGuard: () => NostrTypeGuard, - decode: () => decode, - decodeNostrURI: () => decodeNostrURI, - encodeBytes: () => encodeBytes, - naddrEncode: () => naddrEncode, - neventEncode: () => neventEncode, - noteEncode: () => noteEncode, - nprofileEncode: () => nprofileEncode, - npubEncode: () => npubEncode, - nsecEncode: () => nsecEncode -}); -var NostrTypeGuard = { - isNProfile: (value) => /^nprofile1[a-z\d]+$/.test(value || ""), - isNEvent: (value) => /^nevent1[a-z\d]+$/.test(value || ""), - isNAddr: (value) => /^naddr1[a-z\d]+$/.test(value || ""), - isNSec: (value) => /^nsec1[a-z\d]{58}$/.test(value || ""), - isNPub: (value) => /^npub1[a-z\d]{58}$/.test(value || ""), - isNote: (value) => /^note1[a-z\d]+$/.test(value || ""), - isNcryptsec: (value) => /^ncryptsec1[a-z\d]+$/.test(value || "") -}; -var Bech32MaxSize = 5e3; -var BECH32_REGEX = /[\x21-\x7E]{1,83}1[023456789acdefghjklmnpqrstuvwxyz]{6,}/; -function integerToUint8Array(number4) { - const uint8Array = new Uint8Array(4); - uint8Array[0] = number4 >> 24 & 255; - uint8Array[1] = number4 >> 16 & 255; - uint8Array[2] = number4 >> 8 & 255; - uint8Array[3] = number4 & 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) { - var _a, _b, _c, _d, _e, _f, _g; - let { prefix, words } = bech32.decode(code, Bech32MaxSize); - let data = new Uint8Array(bech32.fromWords(words)); - switch (prefix) { - case "nprofile": { - let tlv = parseTLV(data); - if (!((_a = tlv[0]) == null ? void 0 : _a[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: bytesToHex2(tlv[0][0]), - relays: tlv[1] ? tlv[1].map((d) => utf8Decoder.decode(d)) : [] - } - }; - } - case "nevent": { - let tlv = parseTLV(data); - if (!((_b = tlv[0]) == null ? void 0 : _b[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: bytesToHex2(tlv[0][0]), - relays: tlv[1] ? tlv[1].map((d) => utf8Decoder.decode(d)) : [], - author: ((_c = tlv[2]) == null ? void 0 : _c[0]) ? bytesToHex2(tlv[2][0]) : void 0, - kind: ((_d = tlv[3]) == null ? void 0 : _d[0]) ? parseInt(bytesToHex2(tlv[3][0]), 16) : void 0 - } - }; - } - case "naddr": { - let tlv = parseTLV(data); - if (!((_e = tlv[0]) == null ? void 0 : _e[0])) - throw new Error("missing TLV 0 for naddr"); - if (!((_f = tlv[2]) == null ? void 0 : _f[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 (!((_g = tlv[3]) == null ? void 0 : _g[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: bytesToHex2(tlv[2][0]), - kind: parseInt(bytesToHex2(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: bytesToHex2(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 nsecEncode(key) { - return encodeBytes("nsec", key); -} -function npubEncode(hex3) { - return encodeBytes("npub", hexToBytes2(hex3)); -} -function noteEncode(hex3) { - return encodeBytes("note", hexToBytes2(hex3)); -} -function encodeBech32(prefix, data) { - let words = bech32.toWords(data); - return bech32.encode(prefix, words, Bech32MaxSize); -} -function encodeBytes(prefix, bytes4) { - return encodeBech32(prefix, bytes4); -} -function nprofileEncode(profile) { - let data = encodeTLV({ - 0: [hexToBytes2(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: [hexToBytes2(event.id)], - 1: (event.relays || []).map((url) => utf8Encoder.encode(url)), - 2: event.author ? [hexToBytes2(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: [hexToBytes2(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 concatBytes3(...entries); -} -var nip04_exports = {}; -__export2(nip04_exports, { - decrypt: () => decrypt2, - encrypt: () => encrypt2 -}); -function encrypt2(secretKey, pubkey, text) { - const privkey = secretKey instanceof Uint8Array ? bytesToHex2(secretKey) : secretKey; - const key = secp256k1.getSharedSecret(privkey, "02" + pubkey); - const normalizedKey = getNormalizedX(key); - let iv = Uint8Array.from(randomBytes2(16)); - let plaintext = utf8Encoder.encode(text); - let ciphertext = cbc(normalizedKey, iv).encrypt(plaintext); - let ctb64 = base64.encode(new Uint8Array(ciphertext)); - let ivb64 = base64.encode(new Uint8Array(iv.buffer)); - return `${ctb64}?iv=${ivb64}`; -} -function decrypt2(secretKey, pubkey, data) { - const privkey = secretKey instanceof Uint8Array ? bytesToHex2(secretKey) : secretKey; - let [ctb64, ivb64] = data.split("?iv="); - let key = secp256k1.getSharedSecret(privkey, "02" + pubkey); - let normalizedKey = getNormalizedX(key); - let iv = base64.decode(ivb64); - let ciphertext = base64.decode(ctb64); - let plaintext = cbc(normalizedKey, iv).decrypt(ciphertext); - return utf8Decoder.decode(plaintext); -} -function getNormalizedX(key) { - return key.slice(1, 33); -} -var nip05_exports = {}; -__export2(nip05_exports, { - NIP05_REGEX: () => NIP05_REGEX, - isNip05: () => isNip05, - isValid: () => isValid, - queryProfile: () => queryProfile, - searchDomain: () => searchDomain, - useFetchImplementation: () => useFetchImplementation -}); -var NIP05_REGEX = /^(?:([\w.+-]+)@)?([\w_-]+(\.[\w_-]+)+)$/; -var isNip05 = (value) => NIP05_REGEX.test(value || ""); -var _fetch; -try { - _fetch = fetch; -} catch (_) { - null; -} -function useFetchImplementation(fetchImplementation) { - _fetch = fetchImplementation; -} -async function searchDomain(domain, query = "") { - try { - const url = `https://${domain}/.well-known/nostr.json?name=${query}`; - const res = await _fetch(url, { redirect: "manual" }); - if (res.status !== 200) { - throw Error("Wrong response code"); - } - const json = await res.json(); - return json.names; - } catch (_) { - return {}; - } -} -async function queryProfile(fullname) { - var _a; - const match = fullname.match(NIP05_REGEX); - if (!match) - return null; - const [, name = "_", domain] = match; - try { - const url = `https://${domain}/.well-known/nostr.json?name=${name}`; - const res = await _fetch(url, { redirect: "manual" }); - if (res.status !== 200) { - throw Error("Wrong response code"); - } - const json = await res.json(); - const pubkey = json.names[name]; - return pubkey ? { pubkey, relays: (_a = json.relays) == null ? void 0 : _a[pubkey] } : null; - } catch (_e) { - return null; - } -} -async function isValid(pubkey, nip05) { - const res = await queryProfile(nip05); - return res ? res.pubkey === pubkey : false; -} -var nip10_exports = {}; -__export2(nip10_exports, { - parse: () => parse -}); -function parse(event) { - const result = { - reply: void 0, - root: void 0, - mentions: [], - profiles: [], - quotes: [] - }; - let maybeParent; - let maybeRoot; - for (let i2 = event.tags.length - 1; i2 >= 0; i2--) { - const tag = event.tags[i2]; - if (tag[0] === "e" && tag[1]) { - const [_, eTagEventId, eTagRelayUrl, eTagMarker, eTagAuthor] = tag; - const eventPointer = { - id: eTagEventId, - relays: eTagRelayUrl ? [eTagRelayUrl] : [], - author: eTagAuthor - }; - if (eTagMarker === "root") { - result.root = eventPointer; - continue; - } - if (eTagMarker === "reply") { - result.reply = eventPointer; - continue; - } - if (eTagMarker === "mention") { - result.mentions.push(eventPointer); - continue; - } - if (!maybeParent) { - maybeParent = eventPointer; - } else { - maybeRoot = eventPointer; - } - result.mentions.push(eventPointer); - continue; - } - if (tag[0] === "q" && tag[1]) { - const [_, eTagEventId, eTagRelayUrl] = tag; - result.quotes.push({ - id: eTagEventId, - relays: eTagRelayUrl ? [eTagRelayUrl] : [] - }); - } - if (tag[0] === "p" && tag[1]) { - result.profiles.push({ - pubkey: tag[1], - relays: tag[2] ? [tag[2]] : [] - }); - continue; - } - } - if (!result.root) { - result.root = maybeRoot || maybeParent || result.reply; - } - if (!result.reply) { - result.reply = maybeParent || result.root; - } - ; - [result.reply, result.root].forEach((ref) => { - if (!ref) - return; - let idx = result.mentions.indexOf(ref); - if (idx !== -1) { - result.mentions.splice(idx, 1); - } - if (ref.author) { - let author = result.profiles.find((p) => p.pubkey === ref.author); - if (author && author.relays) { - if (!ref.relays) { - ref.relays = []; - } - author.relays.forEach((url) => { - var _a; - if (((_a = ref.relays) == null ? void 0 : _a.indexOf(url)) === -1) - ref.relays.push(url); - }); - author.relays = ref.relays; - } - } - }); - result.mentions.forEach((ref) => { - if (ref.author) { - let author = result.profiles.find((p) => p.pubkey === ref.author); - if (author && author.relays) { - if (!ref.relays) { - ref.relays = []; - } - author.relays.forEach((url) => { - if (ref.relays.indexOf(url) === -1) - ref.relays.push(url); - }); - author.relays = ref.relays; - } - } - }); - return result; -} -var nip11_exports = {}; -__export2(nip11_exports, { - fetchRelayInformation: () => fetchRelayInformation, - useFetchImplementation: () => useFetchImplementation2 -}); -var _fetch2; -try { - _fetch2 = fetch; -} catch { -} -function useFetchImplementation2(fetchImplementation) { - _fetch2 = fetchImplementation; -} -async function fetchRelayInformation(url) { - return await (await fetch(url.replace("ws://", "http://").replace("wss://", "https://"), { - headers: { Accept: "application/nostr+json" } - })).json(); -} -var nip13_exports = {}; -__export2(nip13_exports, { - fastEventHash: () => fastEventHash, - getPow: () => getPow, - minePow: () => minePow -}); -function getPow(hex3) { - let count2 = 0; - for (let i2 = 0; i2 < 64; i2 += 8) { - const nibble = parseInt(hex3.substring(i2, i2 + 8), 16); - if (nibble === 0) { - count2 += 32; - } else { - count2 += Math.clz32(nibble); - break; - } - } - return count2; -} -function minePow(unsigned, difficulty) { - let count2 = 0; - const event = unsigned; - const tag = ["nonce", count2.toString(), difficulty.toString()]; - event.tags.push(tag); - while (true) { - const now2 = Math.floor((/* @__PURE__ */ new Date()).getTime() / 1e3); - if (now2 !== event.created_at) { - count2 = 0; - event.created_at = now2; - } - tag[1] = (++count2).toString(); - event.id = fastEventHash(event); - if (getPow(event.id) >= difficulty) { - break; - } - } - return event; -} -function fastEventHash(evt) { - return bytesToHex2( - sha2562(utf8Encoder.encode(JSON.stringify([0, evt.pubkey, evt.created_at, evt.kind, evt.tags, evt.content]))) - ); -} -var nip17_exports = {}; -__export2(nip17_exports, { - unwrapEvent: () => unwrapEvent2, - unwrapManyEvents: () => unwrapManyEvents2, - wrapEvent: () => wrapEvent2, - wrapManyEvents: () => wrapManyEvents2 -}); -var nip59_exports = {}; -__export2(nip59_exports, { - createRumor: () => createRumor, - createSeal: () => createSeal, - createWrap: () => createWrap, - unwrapEvent: () => unwrapEvent, - unwrapManyEvents: () => unwrapManyEvents, - wrapEvent: () => wrapEvent, - wrapManyEvents: () => wrapManyEvents -}); -var nip44_exports = {}; -__export2(nip44_exports, { - decrypt: () => decrypt22, - encrypt: () => encrypt22, - getConversationKey: () => getConversationKey, - v2: () => v2 -}); -var minPlaintextSize = 1; -var maxPlaintextSize = 65535; -function getConversationKey(privkeyA, pubkeyB) { - const sharedX = secp256k1.getSharedSecret(privkeyA, "02" + pubkeyB).subarray(1, 33); - return extract(sha2562, sharedX, "nip44-v2"); -} -function getMessageKeys(conversationKey, nonce) { - const keys = expand(sha2562, conversationKey, nonce, 76); - return { - chacha_key: keys.subarray(0, 32), - chacha_nonce: keys.subarray(32, 44), - hmac_key: keys.subarray(44, 76) - }; -} -function calcPaddedLen(len) { - if (!Number.isSafeInteger(len) || len < 1) - throw new Error("expected positive integer"); - if (len <= 32) - return 32; - const nextPower = 1 << Math.floor(Math.log2(len - 1)) + 1; - const chunk = nextPower <= 256 ? 32 : nextPower / 8; - return chunk * (Math.floor((len - 1) / chunk) + 1); -} -function writeU16BE(num) { - if (!Number.isSafeInteger(num) || num < minPlaintextSize || num > maxPlaintextSize) - throw new Error("invalid plaintext size: must be between 1 and 65535 bytes"); - const arr = new Uint8Array(2); - new DataView(arr.buffer).setUint16(0, num, false); - return arr; -} -function pad(plaintext) { - const unpadded = utf8Encoder.encode(plaintext); - const unpaddedLen = unpadded.length; - const prefix = writeU16BE(unpaddedLen); - const suffix = new Uint8Array(calcPaddedLen(unpaddedLen) - unpaddedLen); - return concatBytes3(prefix, unpadded, suffix); -} -function unpad(padded) { - const unpaddedLen = new DataView(padded.buffer).getUint16(0); - const unpadded = padded.subarray(2, 2 + unpaddedLen); - if (unpaddedLen < minPlaintextSize || unpaddedLen > maxPlaintextSize || unpadded.length !== unpaddedLen || padded.length !== 2 + calcPaddedLen(unpaddedLen)) - throw new Error("invalid padding"); - return utf8Decoder.decode(unpadded); -} -function hmacAad(key, message, aad) { - if (aad.length !== 32) - throw new Error("AAD associated data must be 32 bytes"); - const combined = concatBytes3(aad, message); - return hmac2(sha2562, key, combined); -} -function decodePayload(payload) { - if (typeof payload !== "string") - throw new Error("payload must be a valid string"); - const plen = payload.length; - if (plen < 132 || plen > 87472) - throw new Error("invalid payload length: " + plen); - if (payload[0] === "#") - throw new Error("unknown encryption version"); - let data; - try { - data = base64.decode(payload); - } catch (error) { - throw new Error("invalid base64: " + error.message); - } - const dlen = data.length; - if (dlen < 99 || dlen > 65603) - throw new Error("invalid data length: " + dlen); - const vers = data[0]; - if (vers !== 2) - throw new Error("unknown encryption version " + vers); - return { - nonce: data.subarray(1, 33), - ciphertext: data.subarray(33, -32), - mac: data.subarray(-32) - }; -} -function encrypt22(plaintext, conversationKey, nonce = randomBytes2(32)) { - const { chacha_key, chacha_nonce, hmac_key } = getMessageKeys(conversationKey, nonce); - const padded = pad(plaintext); - const ciphertext = chacha20(chacha_key, chacha_nonce, padded); - const mac = hmacAad(hmac_key, ciphertext, nonce); - return base64.encode(concatBytes3(new Uint8Array([2]), nonce, ciphertext, mac)); -} -function decrypt22(payload, conversationKey) { - const { nonce, ciphertext, mac } = decodePayload(payload); - const { chacha_key, chacha_nonce, hmac_key } = getMessageKeys(conversationKey, nonce); - const calculatedMac = hmacAad(hmac_key, ciphertext, nonce); - if (!equalBytes2(calculatedMac, mac)) - throw new Error("invalid MAC"); - const padded = chacha20(chacha_key, chacha_nonce, ciphertext); - return unpad(padded); -} -var v2 = { - utils: { - getConversationKey, - calcPaddedLen - }, - encrypt: encrypt22, - decrypt: decrypt22 -}; -var TWO_DAYS = 2 * 24 * 60 * 60; -var now = () => Math.round(Date.now() / 1e3); -var randomNow = () => Math.round(now() - Math.random() * TWO_DAYS); -var nip44ConversationKey = (privateKey, publicKey) => getConversationKey(privateKey, publicKey); -var nip44Encrypt = (data, privateKey, publicKey) => encrypt22(JSON.stringify(data), nip44ConversationKey(privateKey, publicKey)); -var nip44Decrypt = (data, privateKey) => JSON.parse(decrypt22(data.content, nip44ConversationKey(privateKey, data.pubkey))); -function createRumor(event, privateKey) { - const rumor = { - created_at: now(), - content: "", - tags: [], - ...event, - pubkey: getPublicKey(privateKey) - }; - rumor.id = getEventHash(rumor); - return rumor; -} -function createSeal(rumor, privateKey, recipientPublicKey) { - return finalizeEvent( - { - kind: Seal, - content: nip44Encrypt(rumor, privateKey, recipientPublicKey), - created_at: randomNow(), - tags: [] - }, - privateKey - ); -} -function createWrap(seal, recipientPublicKey) { - const randomKey = generateSecretKey(); - return finalizeEvent( - { - kind: GiftWrap, - content: nip44Encrypt(seal, randomKey, recipientPublicKey), - created_at: randomNow(), - tags: [["p", recipientPublicKey]] - }, - randomKey - ); -} -function wrapEvent(event, senderPrivateKey, recipientPublicKey) { - const rumor = createRumor(event, senderPrivateKey); - const seal = createSeal(rumor, senderPrivateKey, recipientPublicKey); - return createWrap(seal, recipientPublicKey); -} -function wrapManyEvents(event, senderPrivateKey, recipientsPublicKeys) { - if (!recipientsPublicKeys || recipientsPublicKeys.length === 0) { - throw new Error("At least one recipient is required."); - } - const senderPublicKey = getPublicKey(senderPrivateKey); - const wrappeds = [wrapEvent(event, senderPrivateKey, senderPublicKey)]; - recipientsPublicKeys.forEach((recipientPublicKey) => { - wrappeds.push(wrapEvent(event, senderPrivateKey, recipientPublicKey)); - }); - return wrappeds; -} -function unwrapEvent(wrap, recipientPrivateKey) { - const unwrappedSeal = nip44Decrypt(wrap, recipientPrivateKey); - return nip44Decrypt(unwrappedSeal, recipientPrivateKey); -} -function unwrapManyEvents(wrappedEvents, recipientPrivateKey) { - let unwrappedEvents = []; - wrappedEvents.forEach((e) => { - unwrappedEvents.push(unwrapEvent(e, recipientPrivateKey)); - }); - unwrappedEvents.sort((a, b) => a.created_at - b.created_at); - return unwrappedEvents; -} -function createEvent(recipients, message, conversationTitle, replyTo) { - const baseEvent = { - created_at: Math.ceil(Date.now() / 1e3), - kind: PrivateDirectMessage, - tags: [], - content: message - }; - const recipientsArray = Array.isArray(recipients) ? recipients : [recipients]; - recipientsArray.forEach(({ publicKey, relayUrl }) => { - baseEvent.tags.push(relayUrl ? ["p", publicKey, relayUrl] : ["p", publicKey]); - }); - if (replyTo) { - baseEvent.tags.push(["e", replyTo.eventId, replyTo.relayUrl || "", "reply"]); - } - if (conversationTitle) { - baseEvent.tags.push(["subject", conversationTitle]); - } - return baseEvent; -} -function wrapEvent2(senderPrivateKey, recipient, message, conversationTitle, replyTo) { - const event = createEvent(recipient, message, conversationTitle, replyTo); - return wrapEvent(event, senderPrivateKey, recipient.publicKey); -} -function wrapManyEvents2(senderPrivateKey, recipients, message, conversationTitle, replyTo) { - if (!recipients || recipients.length === 0) { - throw new Error("At least one recipient is required."); - } - const senderPublicKey = getPublicKey(senderPrivateKey); - return [{ publicKey: senderPublicKey }, ...recipients].map( - (recipient) => wrapEvent2(senderPrivateKey, recipient, message, conversationTitle, replyTo) - ); -} -var unwrapEvent2 = unwrapEvent; -var unwrapManyEvents2 = unwrapManyEvents; -var nip18_exports = {}; -__export2(nip18_exports, { - finishRepostEvent: () => finishRepostEvent, - getRepostedEvent: () => getRepostedEvent, - getRepostedEventPointer: () => getRepostedEventPointer -}); -function finishRepostEvent(t, reposted, relayUrl, privateKey) { - var _a; - let kind; - const tags = [...t.tags ?? [], ["e", reposted.id, relayUrl], ["p", reposted.pubkey]]; - if (reposted.kind === ShortTextNote) { - kind = Repost; - } else { - kind = GenericRepost; - tags.push(["k", String(reposted.kind)]); - } - return finalizeEvent( - { - kind, - tags, - content: t.content === "" || ((_a = reposted.tags) == null ? void 0 : _a.find((tag) => tag[0] === "-")) ? "" : JSON.stringify(reposted), - created_at: t.created_at - }, - privateKey - ); -} -function getRepostedEventPointer(event) { - if (![Repost, GenericRepost].includes(event.kind)) { - return void 0; - } - let lastETag; - let lastPTag; - for (let i2 = event.tags.length - 1; i2 >= 0 && (lastETag === void 0 || lastPTag === void 0); i2--) { - const tag = event.tags[i2]; - if (tag.length >= 2) { - if (tag[0] === "e" && lastETag === void 0) { - lastETag = tag; - } else if (tag[0] === "p" && lastPTag === void 0) { - lastPTag = tag; - } - } - } - if (lastETag === void 0) { - return void 0; - } - return { - id: lastETag[1], - relays: [lastETag[2], lastPTag == null ? void 0 : lastPTag[2]].filter((x) => typeof x === "string"), - author: lastPTag == null ? void 0 : lastPTag[1] - }; -} -function getRepostedEvent(event, { skipVerification } = {}) { - const pointer = getRepostedEventPointer(event); - if (pointer === void 0 || event.content === "") { - return void 0; - } - let repostedEvent; - try { - repostedEvent = JSON.parse(event.content); - } catch (error) { - return void 0; - } - if (repostedEvent.id !== pointer.id) { - return void 0; - } - if (!skipVerification && !verifyEvent(repostedEvent)) { - return void 0; - } - return repostedEvent; -} -var nip21_exports = {}; -__export2(nip21_exports, { - NOSTR_URI_REGEX: () => NOSTR_URI_REGEX, - parse: () => parse2, - test: () => test -}); -var NOSTR_URI_REGEX = new RegExp(`nostr:(${BECH32_REGEX.source})`); -function test(value) { - return typeof value === "string" && new RegExp(`^${NOSTR_URI_REGEX.source}$`).test(value); -} -function parse2(uri) { - const match = uri.match(new RegExp(`^${NOSTR_URI_REGEX.source}$`)); - if (!match) - throw new Error(`Invalid Nostr URI: ${uri}`); - return { - uri: match[0], - value: match[1], - decoded: decode(match[1]) - }; -} -var nip25_exports = {}; -__export2(nip25_exports, { - finishReactionEvent: () => finishReactionEvent, - getReactedEventPointer: () => getReactedEventPointer -}); -function finishReactionEvent(t, reacted, privateKey) { - const inheritedTags = reacted.tags.filter((tag) => tag.length >= 2 && (tag[0] === "e" || tag[0] === "p")); - return finalizeEvent( - { - ...t, - kind: Reaction, - tags: [...t.tags ?? [], ...inheritedTags, ["e", reacted.id], ["p", reacted.pubkey]], - content: t.content ?? "+" - }, - privateKey - ); -} -function getReactedEventPointer(event) { - if (event.kind !== Reaction) { - return void 0; - } - let lastETag; - let lastPTag; - for (let i2 = event.tags.length - 1; i2 >= 0 && (lastETag === void 0 || lastPTag === void 0); i2--) { - const tag = event.tags[i2]; - if (tag.length >= 2) { - if (tag[0] === "e" && lastETag === void 0) { - lastETag = tag; - } else if (tag[0] === "p" && lastPTag === void 0) { - lastPTag = tag; - } - } - } - if (lastETag === void 0 || lastPTag === void 0) { - return void 0; - } - return { - id: lastETag[1], - relays: [lastETag[2], lastPTag[2]].filter((x) => x !== void 0), - author: lastPTag[1] - }; -} -var nip27_exports = {}; -__export2(nip27_exports, { - parse: () => parse3 -}); -var noCharacter = /\W/m; -var noURLCharacter = /\W |\W$|$|,| /m; -function* parse3(content) { - const max2 = content.length; - let prevIndex = 0; - let index = 0; - while (index < max2) { - let u = content.indexOf(":", index); - if (u === -1) { - break; - } - if (content.substring(u - 5, u) === "nostr") { - const m = content.substring(u + 60).match(noCharacter); - const end = m ? u + 60 + m.index : max2; - try { - let pointer; - let { data, type } = decode(content.substring(u + 1, end)); - switch (type) { - case "npub": - pointer = { pubkey: data }; - break; - case "nsec": - case "note": - index = end + 1; - continue; - default: - pointer = data; - } - if (prevIndex !== u - 5) { - yield { type: "text", text: content.substring(prevIndex, u - 5) }; - } - yield { type: "reference", pointer }; - index = end; - prevIndex = index; - continue; - } catch (_err) { - index = u + 1; - continue; - } - } else if (content.substring(u - 5, u) === "https" || content.substring(u - 4, u) === "http") { - const m = content.substring(u + 4).match(noURLCharacter); - const end = m ? u + 4 + m.index : max2; - const prefixLen = content[u - 1] === "s" ? 5 : 4; - try { - let url = new URL(content.substring(u - prefixLen, end)); - if (url.hostname.indexOf(".") === -1) { - throw new Error("invalid url"); - } - if (prevIndex !== u - prefixLen) { - yield { type: "text", text: content.substring(prevIndex, u - prefixLen) }; - } - if (url.pathname.endsWith(".png") || url.pathname.endsWith(".jpg") || url.pathname.endsWith(".jpeg") || url.pathname.endsWith(".gif") || url.pathname.endsWith(".webp")) { - yield { type: "image", url: url.toString() }; - index = end; - prevIndex = index; - continue; - } - if (url.pathname.endsWith(".mp4") || url.pathname.endsWith(".avi") || url.pathname.endsWith(".webm") || url.pathname.endsWith(".mkv")) { - yield { type: "video", url: url.toString() }; - index = end; - prevIndex = index; - continue; - } - if (url.pathname.endsWith(".mp3") || url.pathname.endsWith(".aac") || url.pathname.endsWith(".ogg") || url.pathname.endsWith(".opus")) { - yield { type: "audio", url: url.toString() }; - index = end; - prevIndex = index; - continue; - } - yield { type: "url", url: url.toString() }; - index = end; - prevIndex = index; - continue; - } catch (_err) { - index = end + 1; - continue; - } - } else if (content.substring(u - 3, u) === "wss" || content.substring(u - 2, u) === "ws") { - const m = content.substring(u + 4).match(noURLCharacter); - const end = m ? u + 4 + m.index : max2; - const prefixLen = content[u - 1] === "s" ? 3 : 2; - try { - let url = new URL(content.substring(u - prefixLen, end)); - if (url.hostname.indexOf(".") === -1) { - throw new Error("invalid ws url"); - } - if (prevIndex !== u - prefixLen) { - yield { type: "text", text: content.substring(prevIndex, u - prefixLen) }; - } - yield { type: "relay", url: url.toString() }; - index = end; - prevIndex = index; - continue; - } catch (_err) { - index = end + 1; - continue; - } - } else { - index = u + 1; - continue; - } - } - if (prevIndex !== max2) { - yield { type: "text", text: content.substring(prevIndex) }; - } -} -var nip28_exports = {}; -__export2(nip28_exports, { - channelCreateEvent: () => channelCreateEvent, - channelHideMessageEvent: () => channelHideMessageEvent, - channelMessageEvent: () => channelMessageEvent, - channelMetadataEvent: () => channelMetadataEvent, - channelMuteUserEvent: () => channelMuteUserEvent -}); -var channelCreateEvent = (t, privateKey) => { - let content; - if (typeof t.content === "object") { - content = JSON.stringify(t.content); - } else if (typeof t.content === "string") { - content = t.content; - } else { - return void 0; - } - return finalizeEvent( - { - kind: ChannelCreation, - tags: [...t.tags ?? []], - content, - created_at: t.created_at - }, - privateKey - ); -}; -var channelMetadataEvent = (t, privateKey) => { - let content; - if (typeof t.content === "object") { - content = JSON.stringify(t.content); - } else if (typeof t.content === "string") { - content = t.content; - } else { - return void 0; - } - return finalizeEvent( - { - kind: ChannelMetadata, - tags: [["e", t.channel_create_event_id], ...t.tags ?? []], - content, - created_at: t.created_at - }, - privateKey - ); -}; -var channelMessageEvent = (t, privateKey) => { - const tags = [["e", t.channel_create_event_id, t.relay_url, "root"]]; - if (t.reply_to_channel_message_event_id) { - tags.push(["e", t.reply_to_channel_message_event_id, t.relay_url, "reply"]); - } - return finalizeEvent( - { - kind: ChannelMessage, - tags: [...tags, ...t.tags ?? []], - content: t.content, - created_at: t.created_at - }, - privateKey - ); -}; -var channelHideMessageEvent = (t, privateKey) => { - let content; - if (typeof t.content === "object") { - content = JSON.stringify(t.content); - } else if (typeof t.content === "string") { - content = t.content; - } else { - return void 0; - } - return finalizeEvent( - { - kind: ChannelHideMessage, - tags: [["e", t.channel_message_event_id], ...t.tags ?? []], - content, - created_at: t.created_at - }, - privateKey - ); -}; -var channelMuteUserEvent = (t, privateKey) => { - let content; - if (typeof t.content === "object") { - content = JSON.stringify(t.content); - } else if (typeof t.content === "string") { - content = t.content; - } else { - return void 0; - } - return finalizeEvent( - { - kind: ChannelMuteUser, - tags: [["p", t.pubkey_to_mute], ...t.tags ?? []], - content, - created_at: t.created_at - }, - privateKey - ); -}; -var nip30_exports = {}; -__export2(nip30_exports, { - EMOJI_SHORTCODE_REGEX: () => EMOJI_SHORTCODE_REGEX, - matchAll: () => matchAll, - regex: () => regex, - replaceAll: () => replaceAll -}); -var EMOJI_SHORTCODE_REGEX = /:(\w+):/; -var regex = () => new RegExp(`\\B${EMOJI_SHORTCODE_REGEX.source}\\B`, "g"); -function* matchAll(content) { - const matches = content.matchAll(regex()); - for (const match of matches) { - try { - const [shortcode, name] = match; - yield { - shortcode, - name, - start: match.index, - end: match.index + shortcode.length - }; - } catch (_e) { - } - } -} -function replaceAll(content, replacer) { - return content.replaceAll(regex(), (shortcode, name) => { - return replacer({ - shortcode, - name - }); - }); -} -var nip39_exports = {}; -__export2(nip39_exports, { - useFetchImplementation: () => useFetchImplementation3, - validateGithub: () => validateGithub -}); -var _fetch3; -try { - _fetch3 = fetch; -} catch { -} -function useFetchImplementation3(fetchImplementation) { - _fetch3 = fetchImplementation; -} -async function validateGithub(pubkey, username, proof) { - try { - let res = await (await _fetch3(`https://gist.github.com/${username}/${proof}/raw`)).text(); - return res === `Verifying that I control the following Nostr public key: ${pubkey}`; - } catch (_) { - return false; - } -} -var nip47_exports = {}; -__export2(nip47_exports, { - makeNwcRequestEvent: () => makeNwcRequestEvent, - parseConnectionString: () => parseConnectionString -}); -function parseConnectionString(connectionString) { - const { host, pathname, searchParams } = new URL(connectionString); - const pubkey = pathname || host; - const relay = searchParams.get("relay"); - const secret = searchParams.get("secret"); - if (!pubkey || !relay || !secret) { - throw new Error("invalid connection string"); - } - return { pubkey, relay, secret }; -} -async function makeNwcRequestEvent(pubkey, secretKey, invoice) { - const content = { - method: "pay_invoice", - params: { - invoice - } - }; - const encryptedContent = encrypt2(secretKey, pubkey, JSON.stringify(content)); - const eventTemplate = { - kind: NWCWalletRequest, - created_at: Math.round(Date.now() / 1e3), - content: encryptedContent, - tags: [["p", pubkey]] - }; - return finalizeEvent(eventTemplate, secretKey); -} -var nip54_exports = {}; -__export2(nip54_exports, { - normalizeIdentifier: () => normalizeIdentifier -}); -function normalizeIdentifier(name) { - name = name.trim().toLowerCase(); - name = name.normalize("NFKC"); - return Array.from(name).map((char) => { - if (new RegExp("\\p{Letter}", "u").test(char) || new RegExp("\\p{Number}", "u").test(char)) { - return char; - } - return "-"; - }).join(""); -} -var nip57_exports = {}; -__export2(nip57_exports, { - getSatoshisAmountFromBolt11: () => getSatoshisAmountFromBolt11, - getZapEndpoint: () => getZapEndpoint, - makeZapReceipt: () => makeZapReceipt, - makeZapRequest: () => makeZapRequest, - useFetchImplementation: () => useFetchImplementation4, - validateZapRequest: () => validateZapRequest -}); -var _fetch4; -try { - _fetch4 = fetch; -} catch { -} -function useFetchImplementation4(fetchImplementation) { - _fetch4 = fetchImplementation; -} -async function getZapEndpoint(metadata) { - try { - let lnurl = ""; - let { lud06, lud16 } = JSON.parse(metadata.content); - if (lud06) { - let { words } = bech32.decode(lud06, 1e3); - let data = bech32.fromWords(words); - lnurl = utf8Decoder.decode(data); - } else if (lud16) { - let [name, domain] = lud16.split("@"); - lnurl = new URL(`/.well-known/lnurlp/${name}`, `https://${domain}`).toString(); - } else { - return null; - } - let res = await _fetch4(lnurl); - let body = await res.json(); - if (body.allowsNostr && body.nostrPubkey) { - return body.callback; - } - } catch (err) { - } - return null; -} -function makeZapRequest({ - profile, - event, - amount, - relays, - comment = "" -}) { - if (!amount) - throw new Error("amount not given"); - if (!profile) - throw new Error("profile not given"); - let zr = { - kind: 9734, - created_at: Math.round(Date.now() / 1e3), - content: comment, - tags: [ - ["p", profile], - ["amount", amount.toString()], - ["relays", ...relays] - ] - }; - if (event && typeof event === "string") { - zr.tags.push(["e", event]); - } - if (event && typeof event === "object") { - if (isReplaceableKind(event.kind)) { - const a = ["a", `${event.kind}:${event.pubkey}:`]; - zr.tags.push(a); - } else if (isAddressableKind(event.kind)) { - let d = event.tags.find(([t, v]) => t === "d" && v); - if (!d) - throw new Error("d tag not found or is empty"); - const a = ["a", `${event.kind}:${event.pubkey}:${d[1]}`]; - zr.tags.push(a); - } - } - return zr; -} -function validateZapRequest(zapRequestString) { - let zapRequest; - try { - zapRequest = JSON.parse(zapRequestString); - } catch (err) { - return "Invalid zap request JSON."; - } - if (!validateEvent(zapRequest)) - return "Zap request is not a valid Nostr event."; - if (!verifyEvent(zapRequest)) - return "Invalid signature on zap request."; - let p = zapRequest.tags.find(([t, v]) => t === "p" && v); - if (!p) - return "Zap request doesn't have a 'p' tag."; - if (!p[1].match(/^[a-f0-9]{64}$/)) - return "Zap request 'p' tag is not valid hex."; - let e = zapRequest.tags.find(([t, v]) => t === "e" && v); - if (e && !e[1].match(/^[a-f0-9]{64}$/)) - return "Zap request 'e' tag is not valid hex."; - let relays = zapRequest.tags.find(([t, v]) => t === "relays" && v); - if (!relays) - return "Zap request doesn't have a 'relays' tag."; - return null; -} -function makeZapReceipt({ - zapRequest, - preimage, - bolt11, - paidAt -}) { - let zr = JSON.parse(zapRequest); - let tagsFromZapRequest = zr.tags.filter(([t]) => t === "e" || t === "p" || t === "a"); - let zap = { - kind: 9735, - created_at: Math.round(paidAt.getTime() / 1e3), - content: "", - tags: [...tagsFromZapRequest, ["P", zr.pubkey], ["bolt11", bolt11], ["description", zapRequest]] - }; - if (preimage) { - zap.tags.push(["preimage", preimage]); - } - return zap; -} -function getSatoshisAmountFromBolt11(bolt11) { - if (bolt11.length < 50) { - return 0; - } - bolt11 = bolt11.substring(0, 50); - const idx = bolt11.lastIndexOf("1"); - if (idx === -1) { - return 0; - } - const hrp = bolt11.substring(0, idx); - if (!hrp.startsWith("lnbc")) { - return 0; - } - const amount = hrp.substring(4); - if (amount.length < 1) { - return 0; - } - const char = amount[amount.length - 1]; - const digit = char.charCodeAt(0) - "0".charCodeAt(0); - const isDigit = digit >= 0 && digit <= 9; - let cutPoint = amount.length - 1; - if (isDigit) { - cutPoint++; - } - if (cutPoint < 1) { - return 0; - } - const num = parseInt(amount.substring(0, cutPoint)); - switch (char) { - case "m": - return num * 1e5; - case "u": - return num * 100; - case "n": - return num / 10; - case "p": - return num / 1e4; - default: - return num * 1e8; - } -} -var nip98_exports = {}; -__export2(nip98_exports, { - getToken: () => getToken, - hashPayload: () => hashPayload, - unpackEventFromToken: () => unpackEventFromToken, - validateEvent: () => validateEvent2, - validateEventKind: () => validateEventKind, - validateEventMethodTag: () => validateEventMethodTag, - validateEventPayloadTag: () => validateEventPayloadTag, - validateEventTimestamp: () => validateEventTimestamp, - validateEventUrlTag: () => validateEventUrlTag, - validateToken: () => validateToken -}); -var _authorizationScheme = "Nostr "; -async function getToken(loginUrl, httpMethod, sign, includeAuthorizationScheme = false, payload) { - const event = { - kind: HTTPAuth, - tags: [ - ["u", loginUrl], - ["method", httpMethod] - ], - created_at: Math.round((/* @__PURE__ */ new Date()).getTime() / 1e3), - content: "" - }; - if (payload) { - event.tags.push(["payload", hashPayload(payload)]); - } - const signedEvent = await sign(event); - const authorizationScheme = includeAuthorizationScheme ? _authorizationScheme : ""; - return authorizationScheme + base64.encode(utf8Encoder.encode(JSON.stringify(signedEvent))); -} -async function validateToken(token, url, method) { - const event = await unpackEventFromToken(token).catch((error) => { - throw error; - }); - const valid = await validateEvent2(event, url, method).catch((error) => { - throw error; - }); - return valid; -} -async function unpackEventFromToken(token) { - if (!token) { - throw new Error("Missing token"); - } - token = token.replace(_authorizationScheme, ""); - const eventB64 = utf8Decoder.decode(base64.decode(token)); - if (!eventB64 || eventB64.length === 0 || !eventB64.startsWith("{")) { - throw new Error("Invalid token"); - } - const event = JSON.parse(eventB64); - return event; -} -function validateEventTimestamp(event) { - if (!event.created_at) { - return false; - } - return Math.round((/* @__PURE__ */ new Date()).getTime() / 1e3) - event.created_at < 60; -} -function validateEventKind(event) { - return event.kind === HTTPAuth; -} -function validateEventUrlTag(event, url) { - const urlTag = event.tags.find((t) => t[0] === "u"); - if (!urlTag) { - return false; - } - return urlTag.length > 0 && urlTag[1] === url; -} -function validateEventMethodTag(event, method) { - const methodTag = event.tags.find((t) => t[0] === "method"); - if (!methodTag) { - return false; - } - return methodTag.length > 0 && methodTag[1].toLowerCase() === method.toLowerCase(); -} -function hashPayload(payload) { - const hash3 = sha2562(utf8Encoder.encode(JSON.stringify(payload))); - return bytesToHex2(hash3); -} -function validateEventPayloadTag(event, payload) { - const payloadTag = event.tags.find((t) => t[0] === "payload"); - if (!payloadTag) { - return false; - } - const payloadHash = hashPayload(payload); - return payloadTag.length > 0 && payloadTag[1] === payloadHash; -} -async function validateEvent2(event, url, method, body) { - if (!verifyEvent(event)) { - throw new Error("Invalid nostr event, signature invalid"); - } - if (!validateEventKind(event)) { - throw new Error("Invalid nostr event, kind invalid"); - } - if (!validateEventTimestamp(event)) { - throw new Error("Invalid nostr event, created_at timestamp invalid"); - } - if (!validateEventUrlTag(event, url)) { - throw new Error("Invalid nostr event, url tag invalid"); - } - if (!validateEventMethodTag(event, method)) { - throw new Error("Invalid nostr event, method tag invalid"); - } - if (Boolean(body) && typeof body === "object" && Object.keys(body).length > 0) { - if (!validateEventPayloadTag(event, body)) { - throw new Error("Invalid nostr event, payload tag does not match request body hash"); - } - } - return true; -} - -// node_modules/nostr-tools/lib/esm/kinds.js -var verifiedSymbol2 = Symbol("verified"); -function isReplaceableKind2(kind) { - return [0, 3].includes(kind) || 1e4 <= kind && kind < 2e4; -} -function isAddressableKind2(kind) { - return 3e4 <= kind && kind < 4e4; -} - -// node_modules/tslib/tslib.es6.mjs -var extendStatics = function(d, b) { - extendStatics = Object.setPrototypeOf || { __proto__: [] } instanceof Array && function(d2, b2) { - d2.__proto__ = b2; - } || function(d2, b2) { - for (var p in b2) if (Object.prototype.hasOwnProperty.call(b2, p)) d2[p] = b2[p]; - }; - return extendStatics(d, b); -}; -function __extends(d, b) { - if (typeof b !== "function" && b !== null) - throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); - extendStatics(d, b); - function __() { - this.constructor = d; - } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); -} -function __awaiter(thisArg, _arguments, P, generator) { - function adopt(value) { - return value instanceof P ? value : new P(function(resolve) { - resolve(value); - }); - } - return new (P || (P = Promise))(function(resolve, reject) { - function fulfilled(value) { - try { - step(generator.next(value)); - } catch (e) { - reject(e); - } - } - function rejected(value) { - try { - step(generator["throw"](value)); - } catch (e) { - reject(e); - } - } - function step(result) { - result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); - } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -} -function __generator(thisArg, body) { - var _ = { label: 0, sent: function() { - if (t[0] & 1) throw t[1]; - return t[1]; - }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype); - return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() { - return this; - }), g; - function verb(n) { - return function(v) { - return step([n, v]); - }; - } - function step(op) { - if (f) throw new TypeError("Generator is already executing."); - while (g && (g = 0, op[0] && (_ = 0)), _) try { - if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; - if (y = 0, t) op = [op[0] & 2, t.value]; - switch (op[0]) { - case 0: - case 1: - t = op; - break; - case 4: - _.label++; - return { value: op[1], done: false }; - case 5: - _.label++; - y = op[1]; - op = [0]; - continue; - case 7: - op = _.ops.pop(); - _.trys.pop(); - continue; - default: - if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { - _ = 0; - continue; - } - if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) { - _.label = op[1]; - break; - } - if (op[0] === 6 && _.label < t[1]) { - _.label = t[1]; - t = op; - break; - } - if (t && _.label < t[2]) { - _.label = t[2]; - _.ops.push(op); - break; - } - if (t[2]) _.ops.pop(); - _.trys.pop(); - continue; - } - op = body.call(thisArg, _); - } catch (e) { - op = [6, e]; - y = 0; - } finally { - f = t = 0; - } - if (op[0] & 5) throw op[1]; - return { value: op[0] ? op[1] : void 0, done: true }; - } -} -function __values(o) { - var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i2 = 0; - if (m) return m.call(o); - if (o && typeof o.length === "number") return { - next: function() { - if (o && i2 >= o.length) o = void 0; - return { value: o && o[i2++], done: !o }; - } - }; - throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); -} -function __read(o, n) { - var m = typeof Symbol === "function" && o[Symbol.iterator]; - if (!m) return o; - var i2 = m.call(o), r, ar = [], e; - try { - while ((n === void 0 || n-- > 0) && !(r = i2.next()).done) ar.push(r.value); - } catch (error) { - e = { error }; - } finally { - try { - if (r && !r.done && (m = i2["return"])) m.call(i2); - } finally { - if (e) throw e.error; - } - } - return ar; -} -function __spreadArray(to, from2, pack) { - if (pack || arguments.length === 2) for (var i2 = 0, l = from2.length, ar; i2 < l; i2++) { - if (ar || !(i2 in from2)) { - if (!ar) ar = Array.prototype.slice.call(from2, 0, i2); - ar[i2] = from2[i2]; - } - } - return to.concat(ar || Array.prototype.slice.call(from2)); -} -function __await(v) { - return this instanceof __await ? (this.v = v, this) : new __await(v); -} -function __asyncGenerator(thisArg, _arguments, generator) { - if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); - var g = generator.apply(thisArg, _arguments || []), i2, q = []; - return i2 = Object.create((typeof AsyncIterator === "function" ? AsyncIterator : Object).prototype), verb("next"), verb("throw"), verb("return", awaitReturn), i2[Symbol.asyncIterator] = function() { - return this; - }, i2; - function awaitReturn(f) { - return function(v) { - return Promise.resolve(v).then(f, reject); - }; - } - function verb(n, f) { - if (g[n]) { - i2[n] = function(v) { - return new Promise(function(a, b) { - q.push([n, v, a, b]) > 1 || resume(n, v); - }); - }; - if (f) i2[n] = f(i2[n]); - } - } - function resume(n, v) { - try { - step(g[n](v)); - } catch (e) { - settle(q[0][3], e); - } - } - function step(r) { - r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); - } - function fulfill(value) { - resume("next", value); - } - function reject(value) { - resume("throw", value); - } - function settle(f, v) { - if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); - } -} -function __asyncValues(o) { - if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); - var m = o[Symbol.asyncIterator], i2; - return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i2 = {}, verb("next"), verb("throw"), verb("return"), i2[Symbol.asyncIterator] = function() { - return this; - }, i2); - function verb(n) { - i2[n] = o[n] && function(v) { - return new Promise(function(resolve, reject) { - v = o[n](v), settle(resolve, reject, v.done, v.value); - }); - }; - } - function settle(resolve, reject, d, v) { - Promise.resolve(v).then(function(v3) { - resolve({ value: v3, done: d }); - }, reject); - } -} - -// node_modules/rxjs/dist/esm5/internal/util/isFunction.js -function isFunction(value) { - return typeof value === "function"; -} - -// node_modules/rxjs/dist/esm5/internal/util/createErrorClass.js -function createErrorClass(createImpl) { - var _super = function(instance) { - Error.call(instance); - instance.stack = new Error().stack; - }; - var ctorFunc = createImpl(_super); - ctorFunc.prototype = Object.create(Error.prototype); - ctorFunc.prototype.constructor = ctorFunc; - return ctorFunc; -} - -// node_modules/rxjs/dist/esm5/internal/util/UnsubscriptionError.js -var UnsubscriptionError = createErrorClass(function(_super) { - return function UnsubscriptionErrorImpl(errors) { - _super(this); - this.message = errors ? errors.length + " errors occurred during unsubscription:\n" + errors.map(function(err, i2) { - return i2 + 1 + ") " + err.toString(); - }).join("\n ") : ""; - this.name = "UnsubscriptionError"; - this.errors = errors; - }; -}); - -// node_modules/rxjs/dist/esm5/internal/util/arrRemove.js -function arrRemove(arr, item) { - if (arr) { - var index = arr.indexOf(item); - 0 <= index && arr.splice(index, 1); - } -} - -// node_modules/rxjs/dist/esm5/internal/Subscription.js -var Subscription = function() { - function Subscription2(initialTeardown) { - this.initialTeardown = initialTeardown; - this.closed = false; - this._parentage = null; - this._finalizers = null; - } - Subscription2.prototype.unsubscribe = function() { - var e_1, _a, e_2, _b; - var errors; - if (!this.closed) { - this.closed = true; - var _parentage = this._parentage; - if (_parentage) { - this._parentage = null; - if (Array.isArray(_parentage)) { - try { - for (var _parentage_1 = __values(_parentage), _parentage_1_1 = _parentage_1.next(); !_parentage_1_1.done; _parentage_1_1 = _parentage_1.next()) { - var parent_1 = _parentage_1_1.value; - parent_1.remove(this); - } - } catch (e_1_1) { - e_1 = { error: e_1_1 }; - } finally { - try { - if (_parentage_1_1 && !_parentage_1_1.done && (_a = _parentage_1.return)) _a.call(_parentage_1); - } finally { - if (e_1) throw e_1.error; - } - } - } else { - _parentage.remove(this); - } - } - var initialFinalizer = this.initialTeardown; - if (isFunction(initialFinalizer)) { - try { - initialFinalizer(); - } catch (e) { - errors = e instanceof UnsubscriptionError ? e.errors : [e]; - } - } - var _finalizers = this._finalizers; - if (_finalizers) { - this._finalizers = null; - try { - for (var _finalizers_1 = __values(_finalizers), _finalizers_1_1 = _finalizers_1.next(); !_finalizers_1_1.done; _finalizers_1_1 = _finalizers_1.next()) { - var finalizer = _finalizers_1_1.value; - try { - execFinalizer(finalizer); - } catch (err) { - errors = errors !== null && errors !== void 0 ? errors : []; - if (err instanceof UnsubscriptionError) { - errors = __spreadArray(__spreadArray([], __read(errors)), __read(err.errors)); - } else { - errors.push(err); - } - } - } - } catch (e_2_1) { - e_2 = { error: e_2_1 }; - } finally { - try { - if (_finalizers_1_1 && !_finalizers_1_1.done && (_b = _finalizers_1.return)) _b.call(_finalizers_1); - } finally { - if (e_2) throw e_2.error; - } - } - } - if (errors) { - throw new UnsubscriptionError(errors); - } - } - }; - Subscription2.prototype.add = function(teardown) { - var _a; - if (teardown && teardown !== this) { - if (this.closed) { - execFinalizer(teardown); - } else { - if (teardown instanceof Subscription2) { - if (teardown.closed || teardown._hasParent(this)) { - return; - } - teardown._addParent(this); - } - (this._finalizers = (_a = this._finalizers) !== null && _a !== void 0 ? _a : []).push(teardown); - } - } - }; - Subscription2.prototype._hasParent = function(parent2) { - var _parentage = this._parentage; - return _parentage === parent2 || Array.isArray(_parentage) && _parentage.includes(parent2); - }; - Subscription2.prototype._addParent = function(parent2) { - var _parentage = this._parentage; - this._parentage = Array.isArray(_parentage) ? (_parentage.push(parent2), _parentage) : _parentage ? [_parentage, parent2] : parent2; - }; - Subscription2.prototype._removeParent = function(parent2) { - var _parentage = this._parentage; - if (_parentage === parent2) { - this._parentage = null; - } else if (Array.isArray(_parentage)) { - arrRemove(_parentage, parent2); - } - }; - Subscription2.prototype.remove = function(teardown) { - var _finalizers = this._finalizers; - _finalizers && arrRemove(_finalizers, teardown); - if (teardown instanceof Subscription2) { - teardown._removeParent(this); - } - }; - Subscription2.EMPTY = function() { - var empty2 = new Subscription2(); - empty2.closed = true; - return empty2; - }(); - return Subscription2; -}(); -var EMPTY_SUBSCRIPTION = Subscription.EMPTY; -function isSubscription(value) { - return value instanceof Subscription || value && "closed" in value && isFunction(value.remove) && isFunction(value.add) && isFunction(value.unsubscribe); -} -function execFinalizer(finalizer) { - if (isFunction(finalizer)) { - finalizer(); - } else { - finalizer.unsubscribe(); - } -} - -// node_modules/rxjs/dist/esm5/internal/config.js -var config = { - onUnhandledError: null, - onStoppedNotification: null, - Promise: void 0, - useDeprecatedSynchronousErrorHandling: false, - useDeprecatedNextContext: false -}; - -// node_modules/rxjs/dist/esm5/internal/scheduler/timeoutProvider.js -var timeoutProvider = { - setTimeout: function(handler, timeout2) { - var args = []; - for (var _i = 2; _i < arguments.length; _i++) { - args[_i - 2] = arguments[_i]; - } - var delegate = timeoutProvider.delegate; - if (delegate === null || delegate === void 0 ? void 0 : delegate.setTimeout) { - return delegate.setTimeout.apply(delegate, __spreadArray([handler, timeout2], __read(args))); - } - return setTimeout.apply(void 0, __spreadArray([handler, timeout2], __read(args))); - }, - clearTimeout: function(handle) { - var delegate = timeoutProvider.delegate; - return ((delegate === null || delegate === void 0 ? void 0 : delegate.clearTimeout) || clearTimeout)(handle); - }, - delegate: void 0 -}; - -// node_modules/rxjs/dist/esm5/internal/util/reportUnhandledError.js -function reportUnhandledError(err) { - timeoutProvider.setTimeout(function() { - var onUnhandledError = config.onUnhandledError; - if (onUnhandledError) { - onUnhandledError(err); - } else { - throw err; - } - }); -} - -// node_modules/rxjs/dist/esm5/internal/util/noop.js -function noop() { -} - -// node_modules/rxjs/dist/esm5/internal/NotificationFactories.js -var COMPLETE_NOTIFICATION = function() { - return createNotification("C", void 0, void 0); -}(); -function errorNotification(error) { - return createNotification("E", void 0, error); -} -function nextNotification(value) { - return createNotification("N", value, void 0); -} -function createNotification(kind, value, error) { - return { - kind, - value, - error - }; -} - -// node_modules/rxjs/dist/esm5/internal/util/errorContext.js -var context = null; -function errorContext(cb) { - if (config.useDeprecatedSynchronousErrorHandling) { - var isRoot = !context; - if (isRoot) { - context = { errorThrown: false, error: null }; - } - cb(); - if (isRoot) { - var _a = context, errorThrown = _a.errorThrown, error = _a.error; - context = null; - if (errorThrown) { - throw error; - } - } - } else { - cb(); - } -} -function captureError(err) { - if (config.useDeprecatedSynchronousErrorHandling && context) { - context.errorThrown = true; - context.error = err; - } -} - -// node_modules/rxjs/dist/esm5/internal/Subscriber.js -var Subscriber = function(_super) { - __extends(Subscriber2, _super); - function Subscriber2(destination) { - var _this = _super.call(this) || this; - _this.isStopped = false; - if (destination) { - _this.destination = destination; - if (isSubscription(destination)) { - destination.add(_this); - } - } else { - _this.destination = EMPTY_OBSERVER; - } - return _this; - } - Subscriber2.create = function(next, error, complete) { - return new SafeSubscriber(next, error, complete); - }; - Subscriber2.prototype.next = function(value) { - if (this.isStopped) { - handleStoppedNotification(nextNotification(value), this); - } else { - this._next(value); - } - }; - Subscriber2.prototype.error = function(err) { - if (this.isStopped) { - handleStoppedNotification(errorNotification(err), this); - } else { - this.isStopped = true; - this._error(err); - } - }; - Subscriber2.prototype.complete = function() { - if (this.isStopped) { - handleStoppedNotification(COMPLETE_NOTIFICATION, this); - } else { - this.isStopped = true; - this._complete(); - } - }; - Subscriber2.prototype.unsubscribe = function() { - if (!this.closed) { - this.isStopped = true; - _super.prototype.unsubscribe.call(this); - this.destination = null; - } - }; - Subscriber2.prototype._next = function(value) { - this.destination.next(value); - }; - Subscriber2.prototype._error = function(err) { - try { - this.destination.error(err); - } finally { - this.unsubscribe(); - } - }; - Subscriber2.prototype._complete = function() { - try { - this.destination.complete(); - } finally { - this.unsubscribe(); - } - }; - return Subscriber2; -}(Subscription); -var _bind = Function.prototype.bind; -function bind(fn, thisArg) { - return _bind.call(fn, thisArg); -} -var ConsumerObserver = function() { - function ConsumerObserver2(partialObserver) { - this.partialObserver = partialObserver; - } - ConsumerObserver2.prototype.next = function(value) { - var partialObserver = this.partialObserver; - if (partialObserver.next) { - try { - partialObserver.next(value); - } catch (error) { - handleUnhandledError(error); - } - } - }; - ConsumerObserver2.prototype.error = function(err) { - var partialObserver = this.partialObserver; - if (partialObserver.error) { - try { - partialObserver.error(err); - } catch (error) { - handleUnhandledError(error); - } - } else { - handleUnhandledError(err); - } - }; - ConsumerObserver2.prototype.complete = function() { - var partialObserver = this.partialObserver; - if (partialObserver.complete) { - try { - partialObserver.complete(); - } catch (error) { - handleUnhandledError(error); - } - } - }; - return ConsumerObserver2; -}(); -var SafeSubscriber = function(_super) { - __extends(SafeSubscriber2, _super); - function SafeSubscriber2(observerOrNext, error, complete) { - var _this = _super.call(this) || this; - var partialObserver; - if (isFunction(observerOrNext) || !observerOrNext) { - partialObserver = { - next: observerOrNext !== null && observerOrNext !== void 0 ? observerOrNext : void 0, - error: error !== null && error !== void 0 ? error : void 0, - complete: complete !== null && complete !== void 0 ? complete : void 0 - }; - } else { - var context_1; - if (_this && config.useDeprecatedNextContext) { - context_1 = Object.create(observerOrNext); - context_1.unsubscribe = function() { - return _this.unsubscribe(); - }; - partialObserver = { - next: observerOrNext.next && bind(observerOrNext.next, context_1), - error: observerOrNext.error && bind(observerOrNext.error, context_1), - complete: observerOrNext.complete && bind(observerOrNext.complete, context_1) - }; - } else { - partialObserver = observerOrNext; - } - } - _this.destination = new ConsumerObserver(partialObserver); - return _this; - } - return SafeSubscriber2; -}(Subscriber); -function handleUnhandledError(error) { - if (config.useDeprecatedSynchronousErrorHandling) { - captureError(error); - } else { - reportUnhandledError(error); - } -} -function defaultErrorHandler(err) { - throw err; -} -function handleStoppedNotification(notification, subscriber) { - var onStoppedNotification = config.onStoppedNotification; - onStoppedNotification && timeoutProvider.setTimeout(function() { - return onStoppedNotification(notification, subscriber); - }); -} -var EMPTY_OBSERVER = { - closed: true, - next: noop, - error: defaultErrorHandler, - complete: noop -}; - -// node_modules/rxjs/dist/esm5/internal/symbol/observable.js -var observable = function() { - return typeof Symbol === "function" && Symbol.observable || "@@observable"; -}(); - -// node_modules/rxjs/dist/esm5/internal/util/identity.js -function identity(x) { - return x; -} - -// node_modules/rxjs/dist/esm5/internal/util/pipe.js -function pipeFromArray(fns) { - if (fns.length === 0) { - return identity; - } - if (fns.length === 1) { - return fns[0]; - } - return function piped(input) { - return fns.reduce(function(prev, fn) { - return fn(prev); - }, input); - }; -} - -// node_modules/rxjs/dist/esm5/internal/Observable.js -var Observable = function() { - function Observable2(subscribe) { - if (subscribe) { - this._subscribe = subscribe; - } - } - Observable2.prototype.lift = function(operator) { - var observable2 = new Observable2(); - observable2.source = this; - observable2.operator = operator; - return observable2; - }; - Observable2.prototype.subscribe = function(observerOrNext, error, complete) { - var _this = this; - var subscriber = isSubscriber(observerOrNext) ? observerOrNext : new SafeSubscriber(observerOrNext, error, complete); - errorContext(function() { - var _a = _this, operator = _a.operator, source = _a.source; - subscriber.add(operator ? operator.call(subscriber, source) : source ? _this._subscribe(subscriber) : _this._trySubscribe(subscriber)); - }); - return subscriber; - }; - Observable2.prototype._trySubscribe = function(sink) { - try { - return this._subscribe(sink); - } catch (err) { - sink.error(err); - } - }; - Observable2.prototype.forEach = function(next, promiseCtor) { - var _this = this; - promiseCtor = getPromiseCtor(promiseCtor); - return new promiseCtor(function(resolve, reject) { - var subscriber = new SafeSubscriber({ - next: function(value) { - try { - next(value); - } catch (err) { - reject(err); - subscriber.unsubscribe(); - } - }, - error: reject, - complete: resolve - }); - _this.subscribe(subscriber); - }); - }; - Observable2.prototype._subscribe = function(subscriber) { - var _a; - return (_a = this.source) === null || _a === void 0 ? void 0 : _a.subscribe(subscriber); - }; - Observable2.prototype[observable] = function() { - return this; - }; - Observable2.prototype.pipe = function() { - var operations = []; - for (var _i = 0; _i < arguments.length; _i++) { - operations[_i] = arguments[_i]; - } - return pipeFromArray(operations)(this); - }; - Observable2.prototype.toPromise = function(promiseCtor) { - var _this = this; - promiseCtor = getPromiseCtor(promiseCtor); - return new promiseCtor(function(resolve, reject) { - var value; - _this.subscribe(function(x) { - return value = x; - }, function(err) { - return reject(err); - }, function() { - return resolve(value); - }); - }); - }; - Observable2.create = function(subscribe) { - return new Observable2(subscribe); - }; - return Observable2; -}(); -function getPromiseCtor(promiseCtor) { - var _a; - return (_a = promiseCtor !== null && promiseCtor !== void 0 ? promiseCtor : config.Promise) !== null && _a !== void 0 ? _a : Promise; -} -function isObserver(value) { - return value && isFunction(value.next) && isFunction(value.error) && isFunction(value.complete); -} -function isSubscriber(value) { - return value && value instanceof Subscriber || isObserver(value) && isSubscription(value); -} - -// node_modules/rxjs/dist/esm5/internal/util/lift.js -function hasLift(source) { - return isFunction(source === null || source === void 0 ? void 0 : source.lift); -} -function operate(init) { - return function(source) { - if (hasLift(source)) { - return source.lift(function(liftedSource) { - try { - return init(liftedSource, this); - } catch (err) { - this.error(err); - } - }); - } - throw new TypeError("Unable to lift unknown Observable type"); - }; -} - -// node_modules/rxjs/dist/esm5/internal/operators/OperatorSubscriber.js -function createOperatorSubscriber(destination, onNext, onComplete, onError, onFinalize) { - return new OperatorSubscriber(destination, onNext, onComplete, onError, onFinalize); -} -var OperatorSubscriber = function(_super) { - __extends(OperatorSubscriber2, _super); - function OperatorSubscriber2(destination, onNext, onComplete, onError, onFinalize, shouldUnsubscribe) { - var _this = _super.call(this, destination) || this; - _this.onFinalize = onFinalize; - _this.shouldUnsubscribe = shouldUnsubscribe; - _this._next = onNext ? function(value) { - try { - onNext(value); - } catch (err) { - destination.error(err); - } - } : _super.prototype._next; - _this._error = onError ? function(err) { - try { - onError(err); - } catch (err2) { - destination.error(err2); - } finally { - this.unsubscribe(); - } - } : _super.prototype._error; - _this._complete = onComplete ? function() { - try { - onComplete(); - } catch (err) { - destination.error(err); - } finally { - this.unsubscribe(); - } - } : _super.prototype._complete; - return _this; - } - OperatorSubscriber2.prototype.unsubscribe = function() { - var _a; - if (!this.shouldUnsubscribe || this.shouldUnsubscribe()) { - var closed_1 = this.closed; - _super.prototype.unsubscribe.call(this); - !closed_1 && ((_a = this.onFinalize) === null || _a === void 0 ? void 0 : _a.call(this)); - } - }; - return OperatorSubscriber2; -}(Subscriber); - -// node_modules/rxjs/dist/esm5/internal/operators/refCount.js -function refCount() { - return operate(function(source, subscriber) { - var connection = null; - source._refCount++; - var refCounter = createOperatorSubscriber(subscriber, void 0, void 0, void 0, function() { - if (!source || source._refCount <= 0 || 0 < --source._refCount) { - connection = null; - return; - } - var sharedConnection = source._connection; - var conn = connection; - connection = null; - if (sharedConnection && (!conn || sharedConnection === conn)) { - sharedConnection.unsubscribe(); - } - subscriber.unsubscribe(); - }); - source.subscribe(refCounter); - if (!refCounter.closed) { - connection = source.connect(); - } - }); -} - -// node_modules/rxjs/dist/esm5/internal/observable/ConnectableObservable.js -var ConnectableObservable = function(_super) { - __extends(ConnectableObservable2, _super); - function ConnectableObservable2(source, subjectFactory) { - var _this = _super.call(this) || this; - _this.source = source; - _this.subjectFactory = subjectFactory; - _this._subject = null; - _this._refCount = 0; - _this._connection = null; - if (hasLift(source)) { - _this.lift = source.lift; - } - return _this; - } - ConnectableObservable2.prototype._subscribe = function(subscriber) { - return this.getSubject().subscribe(subscriber); - }; - ConnectableObservable2.prototype.getSubject = function() { - var subject = this._subject; - if (!subject || subject.isStopped) { - this._subject = this.subjectFactory(); - } - return this._subject; - }; - ConnectableObservable2.prototype._teardown = function() { - this._refCount = 0; - var _connection = this._connection; - this._subject = this._connection = null; - _connection === null || _connection === void 0 ? void 0 : _connection.unsubscribe(); - }; - ConnectableObservable2.prototype.connect = function() { - var _this = this; - var connection = this._connection; - if (!connection) { - connection = this._connection = new Subscription(); - var subject_1 = this.getSubject(); - connection.add(this.source.subscribe(createOperatorSubscriber(subject_1, void 0, function() { - _this._teardown(); - subject_1.complete(); - }, function(err) { - _this._teardown(); - subject_1.error(err); - }, function() { - return _this._teardown(); - }))); - if (connection.closed) { - this._connection = null; - connection = Subscription.EMPTY; - } - } - return connection; - }; - ConnectableObservable2.prototype.refCount = function() { - return refCount()(this); - }; - return ConnectableObservable2; -}(Observable); - -// node_modules/rxjs/dist/esm5/internal/scheduler/performanceTimestampProvider.js -var performanceTimestampProvider = { - now: function() { - return (performanceTimestampProvider.delegate || performance).now(); - }, - delegate: void 0 -}; - -// node_modules/rxjs/dist/esm5/internal/scheduler/animationFrameProvider.js -var animationFrameProvider = { - schedule: function(callback) { - var request = requestAnimationFrame; - var cancel = cancelAnimationFrame; - var delegate = animationFrameProvider.delegate; - if (delegate) { - request = delegate.requestAnimationFrame; - cancel = delegate.cancelAnimationFrame; - } - var handle = request(function(timestamp2) { - cancel = void 0; - callback(timestamp2); - }); - return new Subscription(function() { - return cancel === null || cancel === void 0 ? void 0 : cancel(handle); - }); - }, - requestAnimationFrame: function() { - var args = []; - for (var _i = 0; _i < arguments.length; _i++) { - args[_i] = arguments[_i]; - } - var delegate = animationFrameProvider.delegate; - return ((delegate === null || delegate === void 0 ? void 0 : delegate.requestAnimationFrame) || requestAnimationFrame).apply(void 0, __spreadArray([], __read(args))); - }, - cancelAnimationFrame: function() { - var args = []; - for (var _i = 0; _i < arguments.length; _i++) { - args[_i] = arguments[_i]; - } - var delegate = animationFrameProvider.delegate; - return ((delegate === null || delegate === void 0 ? void 0 : delegate.cancelAnimationFrame) || cancelAnimationFrame).apply(void 0, __spreadArray([], __read(args))); - }, - delegate: void 0 -}; - -// node_modules/rxjs/dist/esm5/internal/observable/dom/animationFrames.js -function animationFramesFactory(timestampProvider) { - return new Observable(function(subscriber) { - var provider = timestampProvider || performanceTimestampProvider; - var start = provider.now(); - var id = 0; - var run = function() { - if (!subscriber.closed) { - id = animationFrameProvider.requestAnimationFrame(function(timestamp2) { - id = 0; - var now2 = provider.now(); - subscriber.next({ - timestamp: timestampProvider ? now2 : timestamp2, - elapsed: now2 - start - }); - run(); - }); - } - }; - run(); - return function() { - if (id) { - animationFrameProvider.cancelAnimationFrame(id); - } - }; - }); -} -var DEFAULT_ANIMATION_FRAMES = animationFramesFactory(); - -// node_modules/rxjs/dist/esm5/internal/util/ObjectUnsubscribedError.js -var ObjectUnsubscribedError = createErrorClass(function(_super) { - return function ObjectUnsubscribedErrorImpl() { - _super(this); - this.name = "ObjectUnsubscribedError"; - this.message = "object unsubscribed"; - }; -}); - -// node_modules/rxjs/dist/esm5/internal/Subject.js -var Subject = function(_super) { - __extends(Subject2, _super); - function Subject2() { - var _this = _super.call(this) || this; - _this.closed = false; - _this.currentObservers = null; - _this.observers = []; - _this.isStopped = false; - _this.hasError = false; - _this.thrownError = null; - return _this; - } - Subject2.prototype.lift = function(operator) { - var subject = new AnonymousSubject(this, this); - subject.operator = operator; - return subject; - }; - Subject2.prototype._throwIfClosed = function() { - if (this.closed) { - throw new ObjectUnsubscribedError(); - } - }; - Subject2.prototype.next = function(value) { - var _this = this; - errorContext(function() { - var e_1, _a; - _this._throwIfClosed(); - if (!_this.isStopped) { - if (!_this.currentObservers) { - _this.currentObservers = Array.from(_this.observers); - } - try { - for (var _b = __values(_this.currentObservers), _c = _b.next(); !_c.done; _c = _b.next()) { - var observer = _c.value; - observer.next(value); - } - } catch (e_1_1) { - e_1 = { error: e_1_1 }; - } finally { - try { - if (_c && !_c.done && (_a = _b.return)) _a.call(_b); - } finally { - if (e_1) throw e_1.error; - } - } - } - }); - }; - Subject2.prototype.error = function(err) { - var _this = this; - errorContext(function() { - _this._throwIfClosed(); - if (!_this.isStopped) { - _this.hasError = _this.isStopped = true; - _this.thrownError = err; - var observers = _this.observers; - while (observers.length) { - observers.shift().error(err); - } - } - }); - }; - Subject2.prototype.complete = function() { - var _this = this; - errorContext(function() { - _this._throwIfClosed(); - if (!_this.isStopped) { - _this.isStopped = true; - var observers = _this.observers; - while (observers.length) { - observers.shift().complete(); - } - } - }); - }; - Subject2.prototype.unsubscribe = function() { - this.isStopped = this.closed = true; - this.observers = this.currentObservers = null; - }; - Object.defineProperty(Subject2.prototype, "observed", { - get: function() { - var _a; - return ((_a = this.observers) === null || _a === void 0 ? void 0 : _a.length) > 0; - }, - enumerable: false, - configurable: true - }); - Subject2.prototype._trySubscribe = function(subscriber) { - this._throwIfClosed(); - return _super.prototype._trySubscribe.call(this, subscriber); - }; - Subject2.prototype._subscribe = function(subscriber) { - this._throwIfClosed(); - this._checkFinalizedStatuses(subscriber); - return this._innerSubscribe(subscriber); - }; - Subject2.prototype._innerSubscribe = function(subscriber) { - var _this = this; - var _a = this, hasError = _a.hasError, isStopped = _a.isStopped, observers = _a.observers; - if (hasError || isStopped) { - return EMPTY_SUBSCRIPTION; - } - this.currentObservers = null; - observers.push(subscriber); - return new Subscription(function() { - _this.currentObservers = null; - arrRemove(observers, subscriber); - }); - }; - Subject2.prototype._checkFinalizedStatuses = function(subscriber) { - var _a = this, hasError = _a.hasError, thrownError = _a.thrownError, isStopped = _a.isStopped; - if (hasError) { - subscriber.error(thrownError); - } else if (isStopped) { - subscriber.complete(); - } - }; - Subject2.prototype.asObservable = function() { - var observable2 = new Observable(); - observable2.source = this; - return observable2; - }; - Subject2.create = function(destination, source) { - return new AnonymousSubject(destination, source); - }; - return Subject2; -}(Observable); -var AnonymousSubject = function(_super) { - __extends(AnonymousSubject2, _super); - function AnonymousSubject2(destination, source) { - var _this = _super.call(this) || this; - _this.destination = destination; - _this.source = source; - return _this; - } - AnonymousSubject2.prototype.next = function(value) { - var _a, _b; - (_b = (_a = this.destination) === null || _a === void 0 ? void 0 : _a.next) === null || _b === void 0 ? void 0 : _b.call(_a, value); - }; - AnonymousSubject2.prototype.error = function(err) { - var _a, _b; - (_b = (_a = this.destination) === null || _a === void 0 ? void 0 : _a.error) === null || _b === void 0 ? void 0 : _b.call(_a, err); - }; - AnonymousSubject2.prototype.complete = function() { - var _a, _b; - (_b = (_a = this.destination) === null || _a === void 0 ? void 0 : _a.complete) === null || _b === void 0 ? void 0 : _b.call(_a); - }; - AnonymousSubject2.prototype._subscribe = function(subscriber) { - var _a, _b; - return (_b = (_a = this.source) === null || _a === void 0 ? void 0 : _a.subscribe(subscriber)) !== null && _b !== void 0 ? _b : EMPTY_SUBSCRIPTION; - }; - return AnonymousSubject2; -}(Subject); - -// node_modules/rxjs/dist/esm5/internal/BehaviorSubject.js -var BehaviorSubject = function(_super) { - __extends(BehaviorSubject2, _super); - function BehaviorSubject2(_value) { - var _this = _super.call(this) || this; - _this._value = _value; - return _this; - } - Object.defineProperty(BehaviorSubject2.prototype, "value", { - get: function() { - return this.getValue(); - }, - enumerable: false, - configurable: true - }); - BehaviorSubject2.prototype._subscribe = function(subscriber) { - var subscription = _super.prototype._subscribe.call(this, subscriber); - !subscription.closed && subscriber.next(this._value); - return subscription; - }; - BehaviorSubject2.prototype.getValue = function() { - var _a = this, hasError = _a.hasError, thrownError = _a.thrownError, _value = _a._value; - if (hasError) { - throw thrownError; - } - this._throwIfClosed(); - return _value; - }; - BehaviorSubject2.prototype.next = function(value) { - _super.prototype.next.call(this, this._value = value); - }; - return BehaviorSubject2; -}(Subject); - -// node_modules/rxjs/dist/esm5/internal/scheduler/dateTimestampProvider.js -var dateTimestampProvider = { - now: function() { - return (dateTimestampProvider.delegate || Date).now(); - }, - delegate: void 0 -}; - -// node_modules/rxjs/dist/esm5/internal/ReplaySubject.js -var ReplaySubject = function(_super) { - __extends(ReplaySubject2, _super); - function ReplaySubject2(_bufferSize, _windowTime, _timestampProvider) { - if (_bufferSize === void 0) { - _bufferSize = Infinity; - } - if (_windowTime === void 0) { - _windowTime = Infinity; - } - if (_timestampProvider === void 0) { - _timestampProvider = dateTimestampProvider; - } - var _this = _super.call(this) || this; - _this._bufferSize = _bufferSize; - _this._windowTime = _windowTime; - _this._timestampProvider = _timestampProvider; - _this._buffer = []; - _this._infiniteTimeWindow = true; - _this._infiniteTimeWindow = _windowTime === Infinity; - _this._bufferSize = Math.max(1, _bufferSize); - _this._windowTime = Math.max(1, _windowTime); - return _this; - } - ReplaySubject2.prototype.next = function(value) { - var _a = this, isStopped = _a.isStopped, _buffer = _a._buffer, _infiniteTimeWindow = _a._infiniteTimeWindow, _timestampProvider = _a._timestampProvider, _windowTime = _a._windowTime; - if (!isStopped) { - _buffer.push(value); - !_infiniteTimeWindow && _buffer.push(_timestampProvider.now() + _windowTime); - } - this._trimBuffer(); - _super.prototype.next.call(this, value); - }; - ReplaySubject2.prototype._subscribe = function(subscriber) { - this._throwIfClosed(); - this._trimBuffer(); - var subscription = this._innerSubscribe(subscriber); - var _a = this, _infiniteTimeWindow = _a._infiniteTimeWindow, _buffer = _a._buffer; - var copy = _buffer.slice(); - for (var i2 = 0; i2 < copy.length && !subscriber.closed; i2 += _infiniteTimeWindow ? 1 : 2) { - subscriber.next(copy[i2]); - } - this._checkFinalizedStatuses(subscriber); - return subscription; - }; - ReplaySubject2.prototype._trimBuffer = function() { - var _a = this, _bufferSize = _a._bufferSize, _timestampProvider = _a._timestampProvider, _buffer = _a._buffer, _infiniteTimeWindow = _a._infiniteTimeWindow; - var adjustedBufferSize = (_infiniteTimeWindow ? 1 : 2) * _bufferSize; - _bufferSize < Infinity && adjustedBufferSize < _buffer.length && _buffer.splice(0, _buffer.length - adjustedBufferSize); - if (!_infiniteTimeWindow) { - var now2 = _timestampProvider.now(); - var last3 = 0; - for (var i2 = 1; i2 < _buffer.length && _buffer[i2] <= now2; i2 += 2) { - last3 = i2; - } - last3 && _buffer.splice(0, last3 + 1); - } - }; - return ReplaySubject2; -}(Subject); - -// node_modules/rxjs/dist/esm5/internal/AsyncSubject.js -var AsyncSubject = function(_super) { - __extends(AsyncSubject2, _super); - function AsyncSubject2() { - var _this = _super !== null && _super.apply(this, arguments) || this; - _this._value = null; - _this._hasValue = false; - _this._isComplete = false; - return _this; - } - AsyncSubject2.prototype._checkFinalizedStatuses = function(subscriber) { - var _a = this, hasError = _a.hasError, _hasValue = _a._hasValue, _value = _a._value, thrownError = _a.thrownError, isStopped = _a.isStopped, _isComplete = _a._isComplete; - if (hasError) { - subscriber.error(thrownError); - } else if (isStopped || _isComplete) { - _hasValue && subscriber.next(_value); - subscriber.complete(); - } - }; - AsyncSubject2.prototype.next = function(value) { - if (!this.isStopped) { - this._value = value; - this._hasValue = true; - } - }; - AsyncSubject2.prototype.complete = function() { - var _a = this, _hasValue = _a._hasValue, _value = _a._value, _isComplete = _a._isComplete; - if (!_isComplete) { - this._isComplete = true; - _hasValue && _super.prototype.next.call(this, _value); - _super.prototype.complete.call(this); - } - }; - return AsyncSubject2; -}(Subject); - -// node_modules/rxjs/dist/esm5/internal/scheduler/Action.js -var Action = function(_super) { - __extends(Action2, _super); - function Action2(scheduler, work) { - return _super.call(this) || this; - } - Action2.prototype.schedule = function(state, delay2) { - if (delay2 === void 0) { - delay2 = 0; - } - return this; - }; - return Action2; -}(Subscription); - -// node_modules/rxjs/dist/esm5/internal/scheduler/intervalProvider.js -var intervalProvider = { - setInterval: function(handler, timeout2) { - var args = []; - for (var _i = 2; _i < arguments.length; _i++) { - args[_i - 2] = arguments[_i]; - } - var delegate = intervalProvider.delegate; - if (delegate === null || delegate === void 0 ? void 0 : delegate.setInterval) { - return delegate.setInterval.apply(delegate, __spreadArray([handler, timeout2], __read(args))); - } - return setInterval.apply(void 0, __spreadArray([handler, timeout2], __read(args))); - }, - clearInterval: function(handle) { - var delegate = intervalProvider.delegate; - return ((delegate === null || delegate === void 0 ? void 0 : delegate.clearInterval) || clearInterval)(handle); - }, - delegate: void 0 -}; - -// node_modules/rxjs/dist/esm5/internal/scheduler/AsyncAction.js -var AsyncAction = function(_super) { - __extends(AsyncAction2, _super); - function AsyncAction2(scheduler, work) { - var _this = _super.call(this, scheduler, work) || this; - _this.scheduler = scheduler; - _this.work = work; - _this.pending = false; - return _this; - } - AsyncAction2.prototype.schedule = function(state, delay2) { - var _a; - if (delay2 === void 0) { - delay2 = 0; - } - if (this.closed) { - return this; - } - this.state = state; - var id = this.id; - var scheduler = this.scheduler; - if (id != null) { - this.id = this.recycleAsyncId(scheduler, id, delay2); - } - this.pending = true; - this.delay = delay2; - this.id = (_a = this.id) !== null && _a !== void 0 ? _a : this.requestAsyncId(scheduler, this.id, delay2); - return this; - }; - AsyncAction2.prototype.requestAsyncId = function(scheduler, _id, delay2) { - if (delay2 === void 0) { - delay2 = 0; - } - return intervalProvider.setInterval(scheduler.flush.bind(scheduler, this), delay2); - }; - AsyncAction2.prototype.recycleAsyncId = function(_scheduler, id, delay2) { - if (delay2 === void 0) { - delay2 = 0; - } - if (delay2 != null && this.delay === delay2 && this.pending === false) { - return id; - } - if (id != null) { - intervalProvider.clearInterval(id); - } - return void 0; - }; - AsyncAction2.prototype.execute = function(state, delay2) { - if (this.closed) { - return new Error("executing a cancelled action"); - } - this.pending = false; - var error = this._execute(state, delay2); - if (error) { - return error; - } else if (this.pending === false && this.id != null) { - this.id = this.recycleAsyncId(this.scheduler, this.id, null); - } - }; - AsyncAction2.prototype._execute = function(state, _delay) { - var errored = false; - var errorValue; - try { - this.work(state); - } catch (e) { - errored = true; - errorValue = e ? e : new Error("Scheduled action threw falsy error"); - } - if (errored) { - this.unsubscribe(); - return errorValue; - } - }; - AsyncAction2.prototype.unsubscribe = function() { - if (!this.closed) { - var _a = this, id = _a.id, scheduler = _a.scheduler; - var actions = scheduler.actions; - this.work = this.state = this.scheduler = null; - this.pending = false; - arrRemove(actions, this); - if (id != null) { - this.id = this.recycleAsyncId(scheduler, id, null); - } - this.delay = null; - _super.prototype.unsubscribe.call(this); - } - }; - return AsyncAction2; -}(Action); - -// node_modules/rxjs/dist/esm5/internal/util/Immediate.js -var nextHandle = 1; -var resolved; -var activeHandles = {}; -function findAndClearHandle(handle) { - if (handle in activeHandles) { - delete activeHandles[handle]; - return true; - } - return false; -} -var Immediate = { - setImmediate: function(cb) { - var handle = nextHandle++; - activeHandles[handle] = true; - if (!resolved) { - resolved = Promise.resolve(); - } - resolved.then(function() { - return findAndClearHandle(handle) && cb(); - }); - return handle; - }, - clearImmediate: function(handle) { - findAndClearHandle(handle); - } -}; - -// node_modules/rxjs/dist/esm5/internal/scheduler/immediateProvider.js -var setImmediate = Immediate.setImmediate; -var clearImmediate = Immediate.clearImmediate; -var immediateProvider = { - setImmediate: function() { - var args = []; - for (var _i = 0; _i < arguments.length; _i++) { - args[_i] = arguments[_i]; - } - var delegate = immediateProvider.delegate; - return ((delegate === null || delegate === void 0 ? void 0 : delegate.setImmediate) || setImmediate).apply(void 0, __spreadArray([], __read(args))); - }, - clearImmediate: function(handle) { - var delegate = immediateProvider.delegate; - return ((delegate === null || delegate === void 0 ? void 0 : delegate.clearImmediate) || clearImmediate)(handle); - }, - delegate: void 0 -}; - -// node_modules/rxjs/dist/esm5/internal/scheduler/AsapAction.js -var AsapAction = function(_super) { - __extends(AsapAction2, _super); - function AsapAction2(scheduler, work) { - var _this = _super.call(this, scheduler, work) || this; - _this.scheduler = scheduler; - _this.work = work; - return _this; - } - AsapAction2.prototype.requestAsyncId = function(scheduler, id, delay2) { - if (delay2 === void 0) { - delay2 = 0; - } - if (delay2 !== null && delay2 > 0) { - return _super.prototype.requestAsyncId.call(this, scheduler, id, delay2); - } - scheduler.actions.push(this); - return scheduler._scheduled || (scheduler._scheduled = immediateProvider.setImmediate(scheduler.flush.bind(scheduler, void 0))); - }; - AsapAction2.prototype.recycleAsyncId = function(scheduler, id, delay2) { - var _a; - if (delay2 === void 0) { - delay2 = 0; - } - if (delay2 != null ? delay2 > 0 : this.delay > 0) { - return _super.prototype.recycleAsyncId.call(this, scheduler, id, delay2); - } - var actions = scheduler.actions; - if (id != null && ((_a = actions[actions.length - 1]) === null || _a === void 0 ? void 0 : _a.id) !== id) { - immediateProvider.clearImmediate(id); - if (scheduler._scheduled === id) { - scheduler._scheduled = void 0; - } - } - return void 0; - }; - return AsapAction2; -}(AsyncAction); - -// node_modules/rxjs/dist/esm5/internal/Scheduler.js -var Scheduler = function() { - function Scheduler2(schedulerActionCtor, now2) { - if (now2 === void 0) { - now2 = Scheduler2.now; - } - this.schedulerActionCtor = schedulerActionCtor; - this.now = now2; - } - Scheduler2.prototype.schedule = function(work, delay2, state) { - if (delay2 === void 0) { - delay2 = 0; - } - return new this.schedulerActionCtor(this, work).schedule(state, delay2); - }; - Scheduler2.now = dateTimestampProvider.now; - return Scheduler2; -}(); - -// node_modules/rxjs/dist/esm5/internal/scheduler/AsyncScheduler.js -var AsyncScheduler = function(_super) { - __extends(AsyncScheduler2, _super); - function AsyncScheduler2(SchedulerAction, now2) { - if (now2 === void 0) { - now2 = Scheduler.now; - } - var _this = _super.call(this, SchedulerAction, now2) || this; - _this.actions = []; - _this._active = false; - return _this; - } - AsyncScheduler2.prototype.flush = function(action) { - var actions = this.actions; - if (this._active) { - actions.push(action); - return; - } - var error; - this._active = true; - do { - if (error = action.execute(action.state, action.delay)) { - break; - } - } while (action = actions.shift()); - this._active = false; - if (error) { - while (action = actions.shift()) { - action.unsubscribe(); - } - throw error; - } - }; - return AsyncScheduler2; -}(Scheduler); - -// node_modules/rxjs/dist/esm5/internal/scheduler/AsapScheduler.js -var AsapScheduler = function(_super) { - __extends(AsapScheduler2, _super); - function AsapScheduler2() { - return _super !== null && _super.apply(this, arguments) || this; - } - AsapScheduler2.prototype.flush = function(action) { - this._active = true; - var flushId = this._scheduled; - this._scheduled = void 0; - var actions = this.actions; - var error; - action = action || actions.shift(); - do { - if (error = action.execute(action.state, action.delay)) { - break; - } - } while ((action = actions[0]) && action.id === flushId && actions.shift()); - this._active = false; - if (error) { - while ((action = actions[0]) && action.id === flushId && actions.shift()) { - action.unsubscribe(); - } - throw error; - } - }; - return AsapScheduler2; -}(AsyncScheduler); - -// node_modules/rxjs/dist/esm5/internal/scheduler/asap.js -var asapScheduler = new AsapScheduler(AsapAction); - -// node_modules/rxjs/dist/esm5/internal/scheduler/async.js -var asyncScheduler = new AsyncScheduler(AsyncAction); -var async = asyncScheduler; - -// node_modules/rxjs/dist/esm5/internal/scheduler/QueueAction.js -var QueueAction = function(_super) { - __extends(QueueAction2, _super); - function QueueAction2(scheduler, work) { - var _this = _super.call(this, scheduler, work) || this; - _this.scheduler = scheduler; - _this.work = work; - return _this; - } - QueueAction2.prototype.schedule = function(state, delay2) { - if (delay2 === void 0) { - delay2 = 0; - } - if (delay2 > 0) { - return _super.prototype.schedule.call(this, state, delay2); - } - this.delay = delay2; - this.state = state; - this.scheduler.flush(this); - return this; - }; - QueueAction2.prototype.execute = function(state, delay2) { - return delay2 > 0 || this.closed ? _super.prototype.execute.call(this, state, delay2) : this._execute(state, delay2); - }; - QueueAction2.prototype.requestAsyncId = function(scheduler, id, delay2) { - if (delay2 === void 0) { - delay2 = 0; - } - if (delay2 != null && delay2 > 0 || delay2 == null && this.delay > 0) { - return _super.prototype.requestAsyncId.call(this, scheduler, id, delay2); - } - scheduler.flush(this); - return 0; - }; - return QueueAction2; -}(AsyncAction); - -// node_modules/rxjs/dist/esm5/internal/scheduler/QueueScheduler.js -var QueueScheduler = function(_super) { - __extends(QueueScheduler2, _super); - function QueueScheduler2() { - return _super !== null && _super.apply(this, arguments) || this; - } - return QueueScheduler2; -}(AsyncScheduler); - -// node_modules/rxjs/dist/esm5/internal/scheduler/queue.js -var queueScheduler = new QueueScheduler(QueueAction); - -// node_modules/rxjs/dist/esm5/internal/scheduler/AnimationFrameAction.js -var AnimationFrameAction = function(_super) { - __extends(AnimationFrameAction2, _super); - function AnimationFrameAction2(scheduler, work) { - var _this = _super.call(this, scheduler, work) || this; - _this.scheduler = scheduler; - _this.work = work; - return _this; - } - AnimationFrameAction2.prototype.requestAsyncId = function(scheduler, id, delay2) { - if (delay2 === void 0) { - delay2 = 0; - } - if (delay2 !== null && delay2 > 0) { - return _super.prototype.requestAsyncId.call(this, scheduler, id, delay2); - } - scheduler.actions.push(this); - return scheduler._scheduled || (scheduler._scheduled = animationFrameProvider.requestAnimationFrame(function() { - return scheduler.flush(void 0); - })); - }; - AnimationFrameAction2.prototype.recycleAsyncId = function(scheduler, id, delay2) { - var _a; - if (delay2 === void 0) { - delay2 = 0; - } - if (delay2 != null ? delay2 > 0 : this.delay > 0) { - return _super.prototype.recycleAsyncId.call(this, scheduler, id, delay2); - } - var actions = scheduler.actions; - if (id != null && id === scheduler._scheduled && ((_a = actions[actions.length - 1]) === null || _a === void 0 ? void 0 : _a.id) !== id) { - animationFrameProvider.cancelAnimationFrame(id); - scheduler._scheduled = void 0; - } - return void 0; - }; - return AnimationFrameAction2; -}(AsyncAction); - -// node_modules/rxjs/dist/esm5/internal/scheduler/AnimationFrameScheduler.js -var AnimationFrameScheduler = function(_super) { - __extends(AnimationFrameScheduler2, _super); - function AnimationFrameScheduler2() { - return _super !== null && _super.apply(this, arguments) || this; - } - AnimationFrameScheduler2.prototype.flush = function(action) { - this._active = true; - var flushId; - if (action) { - flushId = action.id; - } else { - flushId = this._scheduled; - this._scheduled = void 0; - } - var actions = this.actions; - var error; - action = action || actions.shift(); - do { - if (error = action.execute(action.state, action.delay)) { - break; - } - } while ((action = actions[0]) && action.id === flushId && actions.shift()); - this._active = false; - if (error) { - while ((action = actions[0]) && action.id === flushId && actions.shift()) { - action.unsubscribe(); - } - throw error; - } - }; - return AnimationFrameScheduler2; -}(AsyncScheduler); - -// node_modules/rxjs/dist/esm5/internal/scheduler/animationFrame.js -var animationFrameScheduler = new AnimationFrameScheduler(AnimationFrameAction); - -// node_modules/rxjs/dist/esm5/internal/scheduler/VirtualTimeScheduler.js -var VirtualTimeScheduler = function(_super) { - __extends(VirtualTimeScheduler2, _super); - function VirtualTimeScheduler2(schedulerActionCtor, maxFrames) { - if (schedulerActionCtor === void 0) { - schedulerActionCtor = VirtualAction; - } - if (maxFrames === void 0) { - maxFrames = Infinity; - } - var _this = _super.call(this, schedulerActionCtor, function() { - return _this.frame; - }) || this; - _this.maxFrames = maxFrames; - _this.frame = 0; - _this.index = -1; - return _this; - } - VirtualTimeScheduler2.prototype.flush = function() { - var _a = this, actions = _a.actions, maxFrames = _a.maxFrames; - var error; - var action; - while ((action = actions[0]) && action.delay <= maxFrames) { - actions.shift(); - this.frame = action.delay; - if (error = action.execute(action.state, action.delay)) { - break; - } - } - if (error) { - while (action = actions.shift()) { - action.unsubscribe(); - } - throw error; - } - }; - VirtualTimeScheduler2.frameTimeFactor = 10; - return VirtualTimeScheduler2; -}(AsyncScheduler); -var VirtualAction = function(_super) { - __extends(VirtualAction2, _super); - function VirtualAction2(scheduler, work, index) { - if (index === void 0) { - index = scheduler.index += 1; - } - var _this = _super.call(this, scheduler, work) || this; - _this.scheduler = scheduler; - _this.work = work; - _this.index = index; - _this.active = true; - _this.index = scheduler.index = index; - return _this; - } - VirtualAction2.prototype.schedule = function(state, delay2) { - if (delay2 === void 0) { - delay2 = 0; - } - if (Number.isFinite(delay2)) { - if (!this.id) { - return _super.prototype.schedule.call(this, state, delay2); - } - this.active = false; - var action = new VirtualAction2(this.scheduler, this.work); - this.add(action); - return action.schedule(state, delay2); - } else { - return Subscription.EMPTY; - } - }; - VirtualAction2.prototype.requestAsyncId = function(scheduler, id, delay2) { - if (delay2 === void 0) { - delay2 = 0; - } - this.delay = scheduler.frame + delay2; - var actions = scheduler.actions; - actions.push(this); - actions.sort(VirtualAction2.sortActions); - return 1; - }; - VirtualAction2.prototype.recycleAsyncId = function(scheduler, id, delay2) { - if (delay2 === void 0) { - delay2 = 0; - } - return void 0; - }; - VirtualAction2.prototype._execute = function(state, delay2) { - if (this.active === true) { - return _super.prototype._execute.call(this, state, delay2); - } - }; - VirtualAction2.sortActions = function(a, b) { - if (a.delay === b.delay) { - if (a.index === b.index) { - return 0; - } else if (a.index > b.index) { - return 1; - } else { - return -1; - } - } else if (a.delay > b.delay) { - return 1; - } else { - return -1; - } - }; - return VirtualAction2; -}(AsyncAction); - -// node_modules/rxjs/dist/esm5/internal/observable/empty.js -var EMPTY = new Observable(function(subscriber) { - return subscriber.complete(); -}); - -// node_modules/rxjs/dist/esm5/internal/util/isScheduler.js -function isScheduler(value) { - return value && isFunction(value.schedule); -} - -// node_modules/rxjs/dist/esm5/internal/util/args.js -function last(arr) { - return arr[arr.length - 1]; -} -function popResultSelector(args) { - return isFunction(last(args)) ? args.pop() : void 0; -} -function popScheduler(args) { - return isScheduler(last(args)) ? args.pop() : void 0; -} -function popNumber(args, defaultValue) { - return typeof last(args) === "number" ? args.pop() : defaultValue; -} - -// node_modules/rxjs/dist/esm5/internal/util/isArrayLike.js -var isArrayLike = function(x) { - return x && typeof x.length === "number" && typeof x !== "function"; -}; - -// node_modules/rxjs/dist/esm5/internal/util/isPromise.js -function isPromise(value) { - return isFunction(value === null || value === void 0 ? void 0 : value.then); -} - -// node_modules/rxjs/dist/esm5/internal/util/isInteropObservable.js -function isInteropObservable(input) { - return isFunction(input[observable]); -} - -// node_modules/rxjs/dist/esm5/internal/util/isAsyncIterable.js -function isAsyncIterable(obj) { - return Symbol.asyncIterator && isFunction(obj === null || obj === void 0 ? void 0 : obj[Symbol.asyncIterator]); -} - -// node_modules/rxjs/dist/esm5/internal/util/throwUnobservableError.js -function createInvalidObservableTypeError(input) { - return new TypeError("You provided " + (input !== null && typeof input === "object" ? "an invalid object" : "'" + input + "'") + " where a stream was expected. You can provide an Observable, Promise, ReadableStream, Array, AsyncIterable, or Iterable."); -} - -// node_modules/rxjs/dist/esm5/internal/symbol/iterator.js -function getSymbolIterator() { - if (typeof Symbol !== "function" || !Symbol.iterator) { - return "@@iterator"; - } - return Symbol.iterator; -} -var iterator = getSymbolIterator(); - -// node_modules/rxjs/dist/esm5/internal/util/isIterable.js -function isIterable(input) { - return isFunction(input === null || input === void 0 ? void 0 : input[iterator]); -} - -// node_modules/rxjs/dist/esm5/internal/util/isReadableStreamLike.js -function readableStreamLikeToAsyncGenerator(readableStream) { - return __asyncGenerator(this, arguments, function readableStreamLikeToAsyncGenerator_1() { - var reader, _a, value, done; - return __generator(this, function(_b) { - switch (_b.label) { - case 0: - reader = readableStream.getReader(); - _b.label = 1; - case 1: - _b.trys.push([1, , 9, 10]); - _b.label = 2; - case 2: - if (false) return [3, 8]; - return [4, __await(reader.read())]; - case 3: - _a = _b.sent(), value = _a.value, done = _a.done; - if (!done) return [3, 5]; - return [4, __await(void 0)]; - case 4: - return [2, _b.sent()]; - case 5: - return [4, __await(value)]; - case 6: - return [4, _b.sent()]; - case 7: - _b.sent(); - return [3, 2]; - case 8: - return [3, 10]; - case 9: - reader.releaseLock(); - return [7]; - case 10: - return [2]; - } - }); - }); -} -function isReadableStreamLike(obj) { - return isFunction(obj === null || obj === void 0 ? void 0 : obj.getReader); -} - -// node_modules/rxjs/dist/esm5/internal/observable/innerFrom.js -function innerFrom(input) { - if (input instanceof Observable) { - return input; - } - if (input != null) { - if (isInteropObservable(input)) { - return fromInteropObservable(input); - } - if (isArrayLike(input)) { - return fromArrayLike(input); - } - if (isPromise(input)) { - return fromPromise(input); - } - if (isAsyncIterable(input)) { - return fromAsyncIterable(input); - } - if (isIterable(input)) { - return fromIterable(input); - } - if (isReadableStreamLike(input)) { - return fromReadableStreamLike(input); - } - } - throw createInvalidObservableTypeError(input); -} -function fromInteropObservable(obj) { - return new Observable(function(subscriber) { - var obs = obj[observable](); - if (isFunction(obs.subscribe)) { - return obs.subscribe(subscriber); - } - throw new TypeError("Provided object does not correctly implement Symbol.observable"); - }); -} -function fromArrayLike(array) { - return new Observable(function(subscriber) { - for (var i2 = 0; i2 < array.length && !subscriber.closed; i2++) { - subscriber.next(array[i2]); - } - subscriber.complete(); - }); -} -function fromPromise(promise) { - return new Observable(function(subscriber) { - promise.then(function(value) { - if (!subscriber.closed) { - subscriber.next(value); - subscriber.complete(); - } - }, function(err) { - return subscriber.error(err); - }).then(null, reportUnhandledError); - }); -} -function fromIterable(iterable) { - return new Observable(function(subscriber) { - var e_1, _a; - try { - for (var iterable_1 = __values(iterable), iterable_1_1 = iterable_1.next(); !iterable_1_1.done; iterable_1_1 = iterable_1.next()) { - var value = iterable_1_1.value; - subscriber.next(value); - if (subscriber.closed) { - return; - } - } - } catch (e_1_1) { - e_1 = { error: e_1_1 }; - } finally { - try { - if (iterable_1_1 && !iterable_1_1.done && (_a = iterable_1.return)) _a.call(iterable_1); - } finally { - if (e_1) throw e_1.error; - } - } - subscriber.complete(); - }); -} -function fromAsyncIterable(asyncIterable) { - return new Observable(function(subscriber) { - process2(asyncIterable, subscriber).catch(function(err) { - return subscriber.error(err); - }); - }); -} -function fromReadableStreamLike(readableStream) { - return fromAsyncIterable(readableStreamLikeToAsyncGenerator(readableStream)); -} -function process2(asyncIterable, subscriber) { - var asyncIterable_1, asyncIterable_1_1; - var e_2, _a; - return __awaiter(this, void 0, void 0, function() { - var value, e_2_1; - return __generator(this, function(_b) { - switch (_b.label) { - case 0: - _b.trys.push([0, 5, 6, 11]); - asyncIterable_1 = __asyncValues(asyncIterable); - _b.label = 1; - case 1: - return [4, asyncIterable_1.next()]; - case 2: - if (!(asyncIterable_1_1 = _b.sent(), !asyncIterable_1_1.done)) return [3, 4]; - value = asyncIterable_1_1.value; - subscriber.next(value); - if (subscriber.closed) { - return [2]; - } - _b.label = 3; - case 3: - return [3, 1]; - case 4: - return [3, 11]; - case 5: - e_2_1 = _b.sent(); - e_2 = { error: e_2_1 }; - return [3, 11]; - case 6: - _b.trys.push([6, , 9, 10]); - if (!(asyncIterable_1_1 && !asyncIterable_1_1.done && (_a = asyncIterable_1.return))) return [3, 8]; - return [4, _a.call(asyncIterable_1)]; - case 7: - _b.sent(); - _b.label = 8; - case 8: - return [3, 10]; - case 9: - if (e_2) throw e_2.error; - return [7]; - case 10: - return [7]; - case 11: - subscriber.complete(); - return [2]; - } - }); - }); -} - -// node_modules/rxjs/dist/esm5/internal/util/executeSchedule.js -function executeSchedule(parentSubscription, scheduler, work, delay2, repeat2) { - if (delay2 === void 0) { - delay2 = 0; - } - if (repeat2 === void 0) { - repeat2 = false; - } - var scheduleSubscription = scheduler.schedule(function() { - work(); - if (repeat2) { - parentSubscription.add(this.schedule(null, delay2)); - } else { - this.unsubscribe(); - } - }, delay2); - parentSubscription.add(scheduleSubscription); - if (!repeat2) { - return scheduleSubscription; - } -} - -// node_modules/rxjs/dist/esm5/internal/operators/observeOn.js -function observeOn(scheduler, delay2) { - if (delay2 === void 0) { - delay2 = 0; - } - return operate(function(source, subscriber) { - source.subscribe(createOperatorSubscriber(subscriber, function(value) { - return executeSchedule(subscriber, scheduler, function() { - return subscriber.next(value); - }, delay2); - }, function() { - return executeSchedule(subscriber, scheduler, function() { - return subscriber.complete(); - }, delay2); - }, function(err) { - return executeSchedule(subscriber, scheduler, function() { - return subscriber.error(err); - }, delay2); - })); - }); -} - -// node_modules/rxjs/dist/esm5/internal/operators/subscribeOn.js -function subscribeOn(scheduler, delay2) { - if (delay2 === void 0) { - delay2 = 0; - } - return operate(function(source, subscriber) { - subscriber.add(scheduler.schedule(function() { - return source.subscribe(subscriber); - }, delay2)); - }); -} - -// node_modules/rxjs/dist/esm5/internal/scheduled/scheduleObservable.js -function scheduleObservable(input, scheduler) { - return innerFrom(input).pipe(subscribeOn(scheduler), observeOn(scheduler)); -} - -// node_modules/rxjs/dist/esm5/internal/scheduled/schedulePromise.js -function schedulePromise(input, scheduler) { - return innerFrom(input).pipe(subscribeOn(scheduler), observeOn(scheduler)); -} - -// node_modules/rxjs/dist/esm5/internal/scheduled/scheduleArray.js -function scheduleArray(input, scheduler) { - return new Observable(function(subscriber) { - var i2 = 0; - return scheduler.schedule(function() { - if (i2 === input.length) { - subscriber.complete(); - } else { - subscriber.next(input[i2++]); - if (!subscriber.closed) { - this.schedule(); - } - } - }); - }); -} - -// node_modules/rxjs/dist/esm5/internal/scheduled/scheduleIterable.js -function scheduleIterable(input, scheduler) { - return new Observable(function(subscriber) { - var iterator2; - executeSchedule(subscriber, scheduler, function() { - iterator2 = input[iterator](); - executeSchedule(subscriber, scheduler, function() { - var _a; - var value; - var done; - try { - _a = iterator2.next(), value = _a.value, done = _a.done; - } catch (err) { - subscriber.error(err); - return; - } - if (done) { - subscriber.complete(); - } else { - subscriber.next(value); - } - }, 0, true); - }); - return function() { - return isFunction(iterator2 === null || iterator2 === void 0 ? void 0 : iterator2.return) && iterator2.return(); - }; - }); -} - -// node_modules/rxjs/dist/esm5/internal/scheduled/scheduleAsyncIterable.js -function scheduleAsyncIterable(input, scheduler) { - if (!input) { - throw new Error("Iterable cannot be null"); - } - return new Observable(function(subscriber) { - executeSchedule(subscriber, scheduler, function() { - var iterator2 = input[Symbol.asyncIterator](); - executeSchedule(subscriber, scheduler, function() { - iterator2.next().then(function(result) { - if (result.done) { - subscriber.complete(); - } else { - subscriber.next(result.value); - } - }); - }, 0, true); - }); - }); -} - -// node_modules/rxjs/dist/esm5/internal/scheduled/scheduleReadableStreamLike.js -function scheduleReadableStreamLike(input, scheduler) { - return scheduleAsyncIterable(readableStreamLikeToAsyncGenerator(input), scheduler); -} - -// node_modules/rxjs/dist/esm5/internal/scheduled/scheduled.js -function scheduled(input, scheduler) { - if (input != null) { - if (isInteropObservable(input)) { - return scheduleObservable(input, scheduler); - } - if (isArrayLike(input)) { - return scheduleArray(input, scheduler); - } - if (isPromise(input)) { - return schedulePromise(input, scheduler); - } - if (isAsyncIterable(input)) { - return scheduleAsyncIterable(input, scheduler); - } - if (isIterable(input)) { - return scheduleIterable(input, scheduler); - } - if (isReadableStreamLike(input)) { - return scheduleReadableStreamLike(input, scheduler); - } - } - throw createInvalidObservableTypeError(input); -} - -// node_modules/rxjs/dist/esm5/internal/observable/from.js -function from(input, scheduler) { - return scheduler ? scheduled(input, scheduler) : innerFrom(input); -} - -// node_modules/rxjs/dist/esm5/internal/observable/of.js -function of() { - var args = []; - for (var _i = 0; _i < arguments.length; _i++) { - args[_i] = arguments[_i]; - } - var scheduler = popScheduler(args); - return from(args, scheduler); -} - -// node_modules/rxjs/dist/esm5/internal/observable/throwError.js -function throwError(errorOrErrorFactory, scheduler) { - var errorFactory = isFunction(errorOrErrorFactory) ? errorOrErrorFactory : function() { - return errorOrErrorFactory; - }; - var init = function(subscriber) { - return subscriber.error(errorFactory()); - }; - return new Observable(scheduler ? function(subscriber) { - return scheduler.schedule(init, 0, subscriber); - } : init); -} - -// node_modules/rxjs/dist/esm5/internal/Notification.js -var NotificationKind; -(function(NotificationKind2) { - NotificationKind2["NEXT"] = "N"; - NotificationKind2["ERROR"] = "E"; - NotificationKind2["COMPLETE"] = "C"; -})(NotificationKind || (NotificationKind = {})); -var Notification = function() { - function Notification2(kind, value, error) { - this.kind = kind; - this.value = value; - this.error = error; - this.hasValue = kind === "N"; - } - Notification2.prototype.observe = function(observer) { - return observeNotification(this, observer); - }; - Notification2.prototype.do = function(nextHandler, errorHandler, completeHandler) { - var _a = this, kind = _a.kind, value = _a.value, error = _a.error; - return kind === "N" ? nextHandler === null || nextHandler === void 0 ? void 0 : nextHandler(value) : kind === "E" ? errorHandler === null || errorHandler === void 0 ? void 0 : errorHandler(error) : completeHandler === null || completeHandler === void 0 ? void 0 : completeHandler(); - }; - Notification2.prototype.accept = function(nextOrObserver, error, complete) { - var _a; - return isFunction((_a = nextOrObserver) === null || _a === void 0 ? void 0 : _a.next) ? this.observe(nextOrObserver) : this.do(nextOrObserver, error, complete); - }; - Notification2.prototype.toObservable = function() { - var _a = this, kind = _a.kind, value = _a.value, error = _a.error; - var result = kind === "N" ? of(value) : kind === "E" ? throwError(function() { - return error; - }) : kind === "C" ? EMPTY : 0; - if (!result) { - throw new TypeError("Unexpected notification kind " + kind); - } - return result; - }; - Notification2.createNext = function(value) { - return new Notification2("N", value); - }; - Notification2.createError = function(err) { - return new Notification2("E", void 0, err); - }; - Notification2.createComplete = function() { - return Notification2.completeNotification; - }; - Notification2.completeNotification = new Notification2("C"); - return Notification2; -}(); -function observeNotification(notification, observer) { - var _a, _b, _c; - var _d = notification, kind = _d.kind, value = _d.value, error = _d.error; - if (typeof kind !== "string") { - throw new TypeError('Invalid notification, missing "kind"'); - } - kind === "N" ? (_a = observer.next) === null || _a === void 0 ? void 0 : _a.call(observer, value) : kind === "E" ? (_b = observer.error) === null || _b === void 0 ? void 0 : _b.call(observer, error) : (_c = observer.complete) === null || _c === void 0 ? void 0 : _c.call(observer); -} - -// node_modules/rxjs/dist/esm5/internal/util/isObservable.js -function isObservable(obj) { - return !!obj && (obj instanceof Observable || isFunction(obj.lift) && isFunction(obj.subscribe)); -} - -// node_modules/rxjs/dist/esm5/internal/util/EmptyError.js -var EmptyError = createErrorClass(function(_super) { - return function EmptyErrorImpl() { - _super(this); - this.name = "EmptyError"; - this.message = "no elements in sequence"; - }; -}); - -// node_modules/rxjs/dist/esm5/internal/lastValueFrom.js -function lastValueFrom(source, config2) { - var hasConfig = typeof config2 === "object"; - return new Promise(function(resolve, reject) { - var _hasValue = false; - var _value; - source.subscribe({ - next: function(value) { - _value = value; - _hasValue = true; - }, - error: reject, - complete: function() { - if (_hasValue) { - resolve(_value); - } else if (hasConfig) { - resolve(config2.defaultValue); - } else { - reject(new EmptyError()); - } - } - }); - }); -} - -// node_modules/rxjs/dist/esm5/internal/firstValueFrom.js -function firstValueFrom(source, config2) { - var hasConfig = typeof config2 === "object"; - return new Promise(function(resolve, reject) { - var subscriber = new SafeSubscriber({ - next: function(value) { - resolve(value); - subscriber.unsubscribe(); - }, - error: reject, - complete: function() { - if (hasConfig) { - resolve(config2.defaultValue); - } else { - reject(new EmptyError()); - } - } - }); - source.subscribe(subscriber); - }); -} - -// node_modules/rxjs/dist/esm5/internal/util/ArgumentOutOfRangeError.js -var ArgumentOutOfRangeError = createErrorClass(function(_super) { - return function ArgumentOutOfRangeErrorImpl() { - _super(this); - this.name = "ArgumentOutOfRangeError"; - this.message = "argument out of range"; - }; -}); - -// node_modules/rxjs/dist/esm5/internal/util/NotFoundError.js -var NotFoundError = createErrorClass(function(_super) { - return function NotFoundErrorImpl(message) { - _super(this); - this.name = "NotFoundError"; - this.message = message; - }; -}); - -// node_modules/rxjs/dist/esm5/internal/util/SequenceError.js -var SequenceError = createErrorClass(function(_super) { - return function SequenceErrorImpl(message) { - _super(this); - this.name = "SequenceError"; - this.message = message; - }; -}); - -// node_modules/rxjs/dist/esm5/internal/util/isDate.js -function isValidDate(value) { - return value instanceof Date && !isNaN(value); -} - -// node_modules/rxjs/dist/esm5/internal/operators/timeout.js -var TimeoutError = createErrorClass(function(_super) { - return function TimeoutErrorImpl(info) { - if (info === void 0) { - info = null; - } - _super(this); - this.message = "Timeout has occurred"; - this.name = "TimeoutError"; - this.info = info; - }; -}); -function timeout(config2, schedulerArg) { - var _a = isValidDate(config2) ? { first: config2 } : typeof config2 === "number" ? { each: config2 } : config2, first2 = _a.first, each = _a.each, _b = _a.with, _with = _b === void 0 ? timeoutErrorFactory : _b, _c = _a.scheduler, scheduler = _c === void 0 ? schedulerArg !== null && schedulerArg !== void 0 ? schedulerArg : asyncScheduler : _c, _d = _a.meta, meta = _d === void 0 ? null : _d; - if (first2 == null && each == null) { - throw new TypeError("No timeout provided."); - } - return operate(function(source, subscriber) { - var originalSourceSubscription; - var timerSubscription; - var lastValue = null; - var seen = 0; - var startTimer = function(delay2) { - timerSubscription = executeSchedule(subscriber, scheduler, function() { - try { - originalSourceSubscription.unsubscribe(); - innerFrom(_with({ - meta, - lastValue, - seen - })).subscribe(subscriber); - } catch (err) { - subscriber.error(err); - } - }, delay2); - }; - originalSourceSubscription = source.subscribe(createOperatorSubscriber(subscriber, function(value) { - timerSubscription === null || timerSubscription === void 0 ? void 0 : timerSubscription.unsubscribe(); - seen++; - subscriber.next(lastValue = value); - each > 0 && startTimer(each); - }, void 0, void 0, function() { - if (!(timerSubscription === null || timerSubscription === void 0 ? void 0 : timerSubscription.closed)) { - timerSubscription === null || timerSubscription === void 0 ? void 0 : timerSubscription.unsubscribe(); - } - lastValue = null; - })); - !seen && startTimer(first2 != null ? typeof first2 === "number" ? first2 : +first2 - scheduler.now() : each); - }); -} -function timeoutErrorFactory(info) { - throw new TimeoutError(info); -} - -// node_modules/rxjs/dist/esm5/internal/operators/map.js -function map(project, thisArg) { - return operate(function(source, subscriber) { - var index = 0; - source.subscribe(createOperatorSubscriber(subscriber, function(value) { - subscriber.next(project.call(thisArg, value, index++)); - })); - }); -} - -// node_modules/rxjs/dist/esm5/internal/util/mapOneOrManyArgs.js -var isArray = Array.isArray; -function callOrApply(fn, args) { - return isArray(args) ? fn.apply(void 0, __spreadArray([], __read(args))) : fn(args); -} -function mapOneOrManyArgs(fn) { - return map(function(args) { - return callOrApply(fn, args); - }); -} - -// node_modules/rxjs/dist/esm5/internal/util/argsArgArrayOrObject.js -var isArray2 = Array.isArray; -var getPrototypeOf = Object.getPrototypeOf; -var objectProto = Object.prototype; -var getKeys = Object.keys; -function argsArgArrayOrObject(args) { - if (args.length === 1) { - var first_1 = args[0]; - if (isArray2(first_1)) { - return { args: first_1, keys: null }; - } - if (isPOJO(first_1)) { - var keys = getKeys(first_1); - return { - args: keys.map(function(key) { - return first_1[key]; - }), - keys - }; - } - } - return { args, keys: null }; -} -function isPOJO(obj) { - return obj && typeof obj === "object" && getPrototypeOf(obj) === objectProto; -} - -// node_modules/rxjs/dist/esm5/internal/util/createObject.js -function createObject(keys, values) { - return keys.reduce(function(result, key, i2) { - return result[key] = values[i2], result; - }, {}); -} - -// node_modules/rxjs/dist/esm5/internal/observable/combineLatest.js -function combineLatest() { - var args = []; - for (var _i = 0; _i < arguments.length; _i++) { - args[_i] = arguments[_i]; - } - var scheduler = popScheduler(args); - var resultSelector = popResultSelector(args); - var _a = argsArgArrayOrObject(args), observables = _a.args, keys = _a.keys; - if (observables.length === 0) { - return from([], scheduler); - } - var result = new Observable(combineLatestInit(observables, scheduler, keys ? function(values) { - return createObject(keys, values); - } : identity)); - return resultSelector ? result.pipe(mapOneOrManyArgs(resultSelector)) : result; -} -function combineLatestInit(observables, scheduler, valueTransform) { - if (valueTransform === void 0) { - valueTransform = identity; - } - return function(subscriber) { - maybeSchedule(scheduler, function() { - var length = observables.length; - var values = new Array(length); - var active = length; - var remainingFirstValues = length; - var _loop_1 = function(i3) { - maybeSchedule(scheduler, function() { - var source = from(observables[i3], scheduler); - var hasFirstValue = false; - source.subscribe(createOperatorSubscriber(subscriber, function(value) { - values[i3] = value; - if (!hasFirstValue) { - hasFirstValue = true; - remainingFirstValues--; - } - if (!remainingFirstValues) { - subscriber.next(valueTransform(values.slice())); - } - }, function() { - if (!--active) { - subscriber.complete(); - } - })); - }, subscriber); - }; - for (var i2 = 0; i2 < length; i2++) { - _loop_1(i2); - } - }, subscriber); - }; -} -function maybeSchedule(scheduler, execute, subscription) { - if (scheduler) { - executeSchedule(subscription, scheduler, execute); - } else { - execute(); - } -} - -// node_modules/rxjs/dist/esm5/internal/operators/mergeInternals.js -function mergeInternals(source, subscriber, project, concurrent, onBeforeNext, expand3, innerSubScheduler, additionalFinalizer) { - var buffer2 = []; - var active = 0; - var index = 0; - var isComplete = false; - var checkComplete = function() { - if (isComplete && !buffer2.length && !active) { - subscriber.complete(); - } - }; - var outerNext = function(value) { - return active < concurrent ? doInnerSub(value) : buffer2.push(value); - }; - var doInnerSub = function(value) { - expand3 && subscriber.next(value); - active++; - var innerComplete = false; - innerFrom(project(value, index++)).subscribe(createOperatorSubscriber(subscriber, function(innerValue) { - onBeforeNext === null || onBeforeNext === void 0 ? void 0 : onBeforeNext(innerValue); - if (expand3) { - outerNext(innerValue); - } else { - subscriber.next(innerValue); - } - }, function() { - innerComplete = true; - }, void 0, function() { - if (innerComplete) { - try { - active--; - var _loop_1 = function() { - var bufferedValue = buffer2.shift(); - if (innerSubScheduler) { - executeSchedule(subscriber, innerSubScheduler, function() { - return doInnerSub(bufferedValue); - }); - } else { - doInnerSub(bufferedValue); - } - }; - while (buffer2.length && active < concurrent) { - _loop_1(); - } - checkComplete(); - } catch (err) { - subscriber.error(err); - } - } - })); - }; - source.subscribe(createOperatorSubscriber(subscriber, outerNext, function() { - isComplete = true; - checkComplete(); - })); - return function() { - additionalFinalizer === null || additionalFinalizer === void 0 ? void 0 : additionalFinalizer(); - }; -} - -// node_modules/rxjs/dist/esm5/internal/operators/mergeMap.js -function mergeMap(project, resultSelector, concurrent) { - if (concurrent === void 0) { - concurrent = Infinity; - } - if (isFunction(resultSelector)) { - return mergeMap(function(a, i2) { - return map(function(b, ii) { - return resultSelector(a, b, i2, ii); - })(innerFrom(project(a, i2))); - }, concurrent); - } else if (typeof resultSelector === "number") { - concurrent = resultSelector; - } - return operate(function(source, subscriber) { - return mergeInternals(source, subscriber, project, concurrent); - }); -} - -// node_modules/rxjs/dist/esm5/internal/operators/mergeAll.js -function mergeAll(concurrent) { - if (concurrent === void 0) { - concurrent = Infinity; - } - return mergeMap(identity, concurrent); -} - -// node_modules/rxjs/dist/esm5/internal/operators/concatAll.js -function concatAll() { - return mergeAll(1); -} - -// node_modules/rxjs/dist/esm5/internal/observable/concat.js -function concat() { - var args = []; - for (var _i = 0; _i < arguments.length; _i++) { - args[_i] = arguments[_i]; - } - return concatAll()(from(args, popScheduler(args))); -} - -// node_modules/rxjs/dist/esm5/internal/observable/defer.js -function defer(observableFactory) { - return new Observable(function(subscriber) { - innerFrom(observableFactory()).subscribe(subscriber); - }); -} - -// node_modules/rxjs/dist/esm5/internal/observable/timer.js -function timer(dueTime, intervalOrScheduler, scheduler) { - if (dueTime === void 0) { - dueTime = 0; - } - if (scheduler === void 0) { - scheduler = async; - } - var intervalDuration = -1; - if (intervalOrScheduler != null) { - if (isScheduler(intervalOrScheduler)) { - scheduler = intervalOrScheduler; - } else { - intervalDuration = intervalOrScheduler; - } - } - return new Observable(function(subscriber) { - var due = isValidDate(dueTime) ? +dueTime - scheduler.now() : dueTime; - if (due < 0) { - due = 0; - } - var n = 0; - return scheduler.schedule(function() { - if (!subscriber.closed) { - subscriber.next(n++); - if (0 <= intervalDuration) { - this.schedule(void 0, intervalDuration); - } else { - subscriber.complete(); - } - } - }, due); - }); -} - -// node_modules/rxjs/dist/esm5/internal/observable/merge.js -function merge() { - var args = []; - for (var _i = 0; _i < arguments.length; _i++) { - args[_i] = arguments[_i]; - } - var scheduler = popScheduler(args); - var concurrent = popNumber(args, Infinity); - var sources = args; - return !sources.length ? EMPTY : sources.length === 1 ? innerFrom(sources[0]) : mergeAll(concurrent)(from(sources, scheduler)); -} - -// node_modules/rxjs/dist/esm5/internal/observable/never.js -var NEVER = new Observable(noop); - -// node_modules/rxjs/dist/esm5/internal/util/argsOrArgArray.js -var isArray3 = Array.isArray; - -// node_modules/rxjs/dist/esm5/internal/operators/filter.js -function filter(predicate, thisArg) { - return operate(function(source, subscriber) { - var index = 0; - source.subscribe(createOperatorSubscriber(subscriber, function(value) { - return predicate.call(thisArg, value, index++) && subscriber.next(value); - })); - }); -} - -// node_modules/rxjs/dist/esm5/internal/operators/bufferTime.js -function bufferTime(bufferTimeSpan) { - var _a, _b; - var otherArgs = []; - for (var _i = 1; _i < arguments.length; _i++) { - otherArgs[_i - 1] = arguments[_i]; - } - var scheduler = (_a = popScheduler(otherArgs)) !== null && _a !== void 0 ? _a : asyncScheduler; - var bufferCreationInterval = (_b = otherArgs[0]) !== null && _b !== void 0 ? _b : null; - var maxBufferSize = otherArgs[1] || Infinity; - return operate(function(source, subscriber) { - var bufferRecords = []; - var restartOnEmit = false; - var emit = function(record) { - var buffer2 = record.buffer, subs = record.subs; - subs.unsubscribe(); - arrRemove(bufferRecords, record); - subscriber.next(buffer2); - restartOnEmit && startBuffer(); - }; - var startBuffer = function() { - if (bufferRecords) { - var subs = new Subscription(); - subscriber.add(subs); - var buffer2 = []; - var record_1 = { - buffer: buffer2, - subs - }; - bufferRecords.push(record_1); - executeSchedule(subs, scheduler, function() { - return emit(record_1); - }, bufferTimeSpan); - } - }; - if (bufferCreationInterval !== null && bufferCreationInterval >= 0) { - executeSchedule(subscriber, scheduler, startBuffer, bufferCreationInterval, true); - } else { - restartOnEmit = true; - } - startBuffer(); - var bufferTimeSubscriber = createOperatorSubscriber(subscriber, function(value) { - var e_1, _a2; - var recordsCopy = bufferRecords.slice(); - try { - for (var recordsCopy_1 = __values(recordsCopy), recordsCopy_1_1 = recordsCopy_1.next(); !recordsCopy_1_1.done; recordsCopy_1_1 = recordsCopy_1.next()) { - var record = recordsCopy_1_1.value; - var buffer2 = record.buffer; - buffer2.push(value); - maxBufferSize <= buffer2.length && emit(record); - } - } catch (e_1_1) { - e_1 = { error: e_1_1 }; - } finally { - try { - if (recordsCopy_1_1 && !recordsCopy_1_1.done && (_a2 = recordsCopy_1.return)) _a2.call(recordsCopy_1); - } finally { - if (e_1) throw e_1.error; - } - } - }, function() { - while (bufferRecords === null || bufferRecords === void 0 ? void 0 : bufferRecords.length) { - subscriber.next(bufferRecords.shift().buffer); - } - bufferTimeSubscriber === null || bufferTimeSubscriber === void 0 ? void 0 : bufferTimeSubscriber.unsubscribe(); - subscriber.complete(); - subscriber.unsubscribe(); - }, void 0, function() { - return bufferRecords = null; - }); - source.subscribe(bufferTimeSubscriber); - }); -} - -// node_modules/rxjs/dist/esm5/internal/operators/catchError.js -function catchError(selector) { - return operate(function(source, subscriber) { - var innerSub = null; - var syncUnsub = false; - var handledResult; - innerSub = source.subscribe(createOperatorSubscriber(subscriber, void 0, void 0, function(err) { - handledResult = innerFrom(selector(err, catchError(selector)(source))); - if (innerSub) { - innerSub.unsubscribe(); - innerSub = null; - handledResult.subscribe(subscriber); - } else { - syncUnsub = true; - } - })); - if (syncUnsub) { - innerSub.unsubscribe(); - innerSub = null; - handledResult.subscribe(subscriber); - } - }); -} - -// node_modules/rxjs/dist/esm5/internal/operators/scanInternals.js -function scanInternals(accumulator, seed, hasSeed, emitOnNext, emitBeforeComplete) { - return function(source, subscriber) { - var hasState = hasSeed; - var state = seed; - var index = 0; - source.subscribe(createOperatorSubscriber(subscriber, function(value) { - var i2 = index++; - state = hasState ? accumulator(state, value, i2) : (hasState = true, value); - emitOnNext && subscriber.next(state); - }, emitBeforeComplete && function() { - hasState && subscriber.next(state); - subscriber.complete(); - })); - }; -} - -// node_modules/rxjs/dist/esm5/internal/operators/take.js -function take(count2) { - return count2 <= 0 ? function() { - return EMPTY; - } : operate(function(source, subscriber) { - var seen = 0; - source.subscribe(createOperatorSubscriber(subscriber, function(value) { - if (++seen <= count2) { - subscriber.next(value); - if (count2 <= seen) { - subscriber.complete(); - } - } - })); - }); -} - -// node_modules/rxjs/dist/esm5/internal/operators/distinct.js -function distinct(keySelector, flushes) { - return operate(function(source, subscriber) { - var distinctKeys = /* @__PURE__ */ new Set(); - source.subscribe(createOperatorSubscriber(subscriber, function(value) { - var key = keySelector ? keySelector(value) : value; - if (!distinctKeys.has(key)) { - distinctKeys.add(key); - subscriber.next(value); - } - })); - flushes && innerFrom(flushes).subscribe(createOperatorSubscriber(subscriber, function() { - return distinctKeys.clear(); - }, noop)); - }); -} - -// node_modules/rxjs/dist/esm5/internal/operators/distinctUntilChanged.js -function distinctUntilChanged(comparator, keySelector) { - if (keySelector === void 0) { - keySelector = identity; - } - comparator = comparator !== null && comparator !== void 0 ? comparator : defaultCompare; - return operate(function(source, subscriber) { - var previousKey; - var first2 = true; - source.subscribe(createOperatorSubscriber(subscriber, function(value) { - var currentKey = keySelector(value); - if (first2 || !comparator(previousKey, currentKey)) { - first2 = false; - previousKey = currentKey; - subscriber.next(value); - } - })); - }); -} -function defaultCompare(a, b) { - return a === b; -} - -// node_modules/rxjs/dist/esm5/internal/operators/endWith.js -function endWith() { - var values = []; - for (var _i = 0; _i < arguments.length; _i++) { - values[_i] = arguments[_i]; - } - return function(source) { - return concat(source, of.apply(void 0, __spreadArray([], __read(values)))); - }; -} - -// node_modules/rxjs/dist/esm5/internal/operators/finalize.js -function finalize(callback) { - return operate(function(source, subscriber) { - try { - source.subscribe(subscriber); - } finally { - subscriber.add(callback); - } - }); -} - -// node_modules/rxjs/dist/esm5/internal/operators/merge.js -function merge2() { - var args = []; - for (var _i = 0; _i < arguments.length; _i++) { - args[_i] = arguments[_i]; - } - var scheduler = popScheduler(args); - var concurrent = popNumber(args, Infinity); - return operate(function(source, subscriber) { - mergeAll(concurrent)(from(__spreadArray([source], __read(args)), scheduler)).subscribe(subscriber); - }); -} - -// node_modules/rxjs/dist/esm5/internal/operators/mergeWith.js -function mergeWith() { - var otherSources = []; - for (var _i = 0; _i < arguments.length; _i++) { - otherSources[_i] = arguments[_i]; - } - return merge2.apply(void 0, __spreadArray([], __read(otherSources))); -} - -// node_modules/rxjs/dist/esm5/internal/operators/repeat.js -function repeat(countOrConfig) { - var _a; - var count2 = Infinity; - var delay2; - if (countOrConfig != null) { - if (typeof countOrConfig === "object") { - _a = countOrConfig.count, count2 = _a === void 0 ? Infinity : _a, delay2 = countOrConfig.delay; - } else { - count2 = countOrConfig; - } - } - return count2 <= 0 ? function() { - return EMPTY; - } : operate(function(source, subscriber) { - var soFar = 0; - var sourceSub; - var resubscribe = function() { - sourceSub === null || sourceSub === void 0 ? void 0 : sourceSub.unsubscribe(); - sourceSub = null; - if (delay2 != null) { - var notifier = typeof delay2 === "number" ? timer(delay2) : innerFrom(delay2(soFar)); - var notifierSubscriber_1 = createOperatorSubscriber(subscriber, function() { - notifierSubscriber_1.unsubscribe(); - subscribeToSource(); - }); - notifier.subscribe(notifierSubscriber_1); - } else { - subscribeToSource(); - } - }; - var subscribeToSource = function() { - var syncUnsub = false; - sourceSub = source.subscribe(createOperatorSubscriber(subscriber, void 0, function() { - if (++soFar < count2) { - if (sourceSub) { - resubscribe(); - } else { - syncUnsub = true; - } - } else { - subscriber.complete(); - } - })); - if (syncUnsub) { - resubscribe(); - } - }; - subscribeToSource(); - }); -} - -// node_modules/rxjs/dist/esm5/internal/operators/scan.js -function scan(accumulator, seed) { - return operate(scanInternals(accumulator, seed, arguments.length >= 2, true)); -} - -// node_modules/rxjs/dist/esm5/internal/operators/share.js -function share(options) { - if (options === void 0) { - options = {}; - } - var _a = options.connector, connector = _a === void 0 ? function() { - return new Subject(); - } : _a, _b = options.resetOnError, resetOnError = _b === void 0 ? true : _b, _c = options.resetOnComplete, resetOnComplete = _c === void 0 ? true : _c, _d = options.resetOnRefCountZero, resetOnRefCountZero = _d === void 0 ? true : _d; - return function(wrapperSource) { - var connection; - var resetConnection; - var subject; - var refCount2 = 0; - var hasCompleted = false; - var hasErrored = false; - var cancelReset = function() { - resetConnection === null || resetConnection === void 0 ? void 0 : resetConnection.unsubscribe(); - resetConnection = void 0; - }; - var reset = function() { - cancelReset(); - connection = subject = void 0; - hasCompleted = hasErrored = false; - }; - var resetAndUnsubscribe = function() { - var conn = connection; - reset(); - conn === null || conn === void 0 ? void 0 : conn.unsubscribe(); - }; - return operate(function(source, subscriber) { - refCount2++; - if (!hasErrored && !hasCompleted) { - cancelReset(); - } - var dest = subject = subject !== null && subject !== void 0 ? subject : connector(); - subscriber.add(function() { - refCount2--; - if (refCount2 === 0 && !hasErrored && !hasCompleted) { - resetConnection = handleReset(resetAndUnsubscribe, resetOnRefCountZero); - } - }); - dest.subscribe(subscriber); - if (!connection && refCount2 > 0) { - connection = new SafeSubscriber({ - next: function(value) { - return dest.next(value); - }, - error: function(err) { - hasErrored = true; - cancelReset(); - resetConnection = handleReset(reset, resetOnError, err); - dest.error(err); - }, - complete: function() { - hasCompleted = true; - cancelReset(); - resetConnection = handleReset(reset, resetOnComplete); - dest.complete(); - } - }); - innerFrom(source).subscribe(connection); - } - })(wrapperSource); - }; -} -function handleReset(reset, on) { - var args = []; - for (var _i = 2; _i < arguments.length; _i++) { - args[_i - 2] = arguments[_i]; - } - if (on === true) { - reset(); - return; - } - if (on === false) { - return; - } - var onSubscriber = new SafeSubscriber({ - next: function() { - onSubscriber.unsubscribe(); - reset(); - } - }); - return innerFrom(on.apply(void 0, __spreadArray([], __read(args)))).subscribe(onSubscriber); -} - -// node_modules/rxjs/dist/esm5/internal/operators/switchMap.js -function switchMap(project, resultSelector) { - return operate(function(source, subscriber) { - var innerSubscriber = null; - var index = 0; - var isComplete = false; - var checkComplete = function() { - return isComplete && !innerSubscriber && subscriber.complete(); - }; - source.subscribe(createOperatorSubscriber(subscriber, function(value) { - innerSubscriber === null || innerSubscriber === void 0 ? void 0 : innerSubscriber.unsubscribe(); - var innerIndex = 0; - var outerIndex = index++; - innerFrom(project(value, outerIndex)).subscribe(innerSubscriber = createOperatorSubscriber(subscriber, function(innerValue) { - return subscriber.next(resultSelector ? resultSelector(value, innerValue, outerIndex, innerIndex++) : innerValue); - }, function() { - innerSubscriber = null; - checkComplete(); - })); - }, function() { - isComplete = true; - checkComplete(); - })); - }); -} - -// node_modules/rxjs/dist/esm5/internal/operators/takeUntil.js -function takeUntil(notifier) { - return operate(function(source, subscriber) { - innerFrom(notifier).subscribe(createOperatorSubscriber(subscriber, function() { - return subscriber.complete(); - }, noop)); - !subscriber.closed && source.subscribe(subscriber); - }); -} - -// node_modules/rxjs/dist/esm5/internal/operators/tap.js -function tap(observerOrNext, error, complete) { - var tapObserver = isFunction(observerOrNext) || error || complete ? { next: observerOrNext, error, complete } : observerOrNext; - return tapObserver ? operate(function(source, subscriber) { - var _a; - (_a = tapObserver.subscribe) === null || _a === void 0 ? void 0 : _a.call(tapObserver); - var isUnsub = true; - source.subscribe(createOperatorSubscriber(subscriber, function(value) { - var _a2; - (_a2 = tapObserver.next) === null || _a2 === void 0 ? void 0 : _a2.call(tapObserver, value); - subscriber.next(value); - }, function() { - var _a2; - isUnsub = false; - (_a2 = tapObserver.complete) === null || _a2 === void 0 ? void 0 : _a2.call(tapObserver); - subscriber.complete(); - }, function(err) { - var _a2; - isUnsub = false; - (_a2 = tapObserver.error) === null || _a2 === void 0 ? void 0 : _a2.call(tapObserver, err); - subscriber.error(err); - }, function() { - var _a2, _b; - if (isUnsub) { - (_a2 = tapObserver.unsubscribe) === null || _a2 === void 0 ? void 0 : _a2.call(tapObserver); - } - (_b = tapObserver.finalize) === null || _b === void 0 ? void 0 : _b.call(tapObserver); - })); - }) : identity; -} - -// node_modules/applesauce-core/dist/event-store/event-store.js -var import_hash_sum = __toESM(require_hash_sum(), 1); - -// node_modules/applesauce-core/dist/helpers/tags.js -function isNameValueTag(tag, name) { - return tag[0] !== void 0 && tag[1] !== void 0 && (name ? tag[0] === name : true); -} -function isETag(tag) { - return isNameValueTag(tag, "e"); -} -function isPTag(tag) { - return isNameValueTag(tag, "p"); -} -function isRTag(tag) { - return isNameValueTag(tag, "r"); -} -function isDTag(tag) { - return isNameValueTag(tag, "d"); -} -function isATag(tag) { - return isNameValueTag(tag, "a"); -} -function isTTag(tag) { - return isNameValueTag(tag, "t"); -} -var processTags = (tags, ...fns) => { - return fns.reduce((step, fn) => { - const next = []; - for (const value of step) { - try { - const result = fn(value); - if (result === void 0) - continue; - next.push(result); - } catch (error) { - } - } - return next; - }, tags); -}; - -// node_modules/applesauce-core/dist/helpers/delete.js -function getDeleteIds(deleteEvent) { - return deleteEvent.tags.filter(isETag).map((t) => t[1]); -} -function getDeleteCoordinates(deleteEvent) { - return deleteEvent.tags.filter(isATag).map((t) => t[1]); -} - -// node_modules/applesauce-core/dist/helpers/cache.js -function getCachedValue(event, symbol) { - return Reflect.get(event, symbol); -} -function setCachedValue(event, symbol, value) { - Reflect.set(event, symbol, value); -} -function getOrComputeCachedValue(event, symbol, compute) { - if (Reflect.has(event, symbol)) { - return Reflect.get(event, symbol); - } else { - const value = compute(); - Reflect.set(event, symbol, value); - return value; - } -} - -// node_modules/applesauce-core/dist/helpers/event.js -var EventStoreSymbol = Symbol.for("event-store"); -var EventUIDSymbol = Symbol.for("event-uid"); -var ReplaceableAddressSymbol = Symbol.for("replaceable-address"); -var FromCacheSymbol = Symbol.for("from-cache"); -var ReplaceableIdentifierSymbol = Symbol.for("replaceable-identifier"); -function isEvent(event) { - var _a; - if (event === void 0 || event === null) - return false; - return ((_a = event.id) == null ? void 0 : _a.length) === 64 && typeof event.sig === "string" && typeof event.pubkey === "string" && event.pubkey.length === 64 && typeof event.content === "string" && Array.isArray(event.tags) && typeof event.created_at === "number" && event.created_at > 0; -} -function isReplaceable(kind) { - return isReplaceableKind2(kind) || isAddressableKind2(kind); -} -function getEventUID(event) { - let uid = Reflect.get(event, EventUIDSymbol); - if (!uid) { - if (isReplaceable(event.kind)) - uid = getReplaceableAddress(event); - else - uid = event.id; - Reflect.set(event, EventUIDSymbol, uid); - } - return uid; -} -function getReplaceableAddress(event) { - if (!isReplaceable(event.kind)) - throw new Error("Event is not replaceable or addressable"); - return getOrComputeCachedValue(event, ReplaceableAddressSymbol, () => { - const identifier = isAddressableKind2(event.kind) ? getReplaceableIdentifier(event) : void 0; - return createReplaceableAddress(event.kind, event.pubkey, identifier); - }); -} -function createReplaceableAddress(kind, pubkey, identifier) { - return kind + ":" + pubkey + ":" + (identifier ?? ""); -} -var getReplaceableUID = createReplaceableAddress; -function fakeVerifyEvent(event) { - event[verifiedSymbol] = true; - return true; -} -function markFromCache(event) { - Reflect.set(event, FromCacheSymbol, true); -} -function isFromCache(event) { - return Reflect.get(event, FromCacheSymbol) === true; -} -function getParentEventStore(event) { - return Reflect.get(event, EventStoreSymbol); -} -function notifyEventUpdate(event) { - const eventStore = getParentEventStore(event); - if (eventStore) - eventStore.update(event); -} -function getReplaceableIdentifier(event) { - return getOrComputeCachedValue(event, ReplaceableIdentifierSymbol, () => { - var _a; - return ((_a = event.tags.find((t) => t[0] === "d")) == null ? void 0 : _a[1]) ?? ""; - }); -} -function isProtectedEvent(event) { - return event.tags.some((t) => t[0] === "-"); -} - -// node_modules/applesauce-core/dist/helpers/time.js -function unixNow() { - return Math.round(Date.now() / 1e3); -} - -// node_modules/applesauce-core/dist/helpers/expiration.js -var ExpirationTimestampSymbol = Symbol("expiration-timestamp"); -function getExpirationTimestamp(event) { - return getOrComputeCachedValue(event, ExpirationTimestampSymbol, () => { - var _a; - const expiration = (_a = event.tags.find((t) => t[0] === "expiration")) == null ? void 0 : _a[1]; - return expiration ? parseInt(expiration) : void 0; - }); -} -function isExpired(event) { - const expiration = getExpirationTimestamp(event); - return expiration ? unixNow() > expiration : false; -} - -// node_modules/applesauce-core/dist/helpers/filter.js -var import_fast_deep_equal = __toESM(require_fast_deep_equal(), 1); - -// node_modules/applesauce-core/dist/helpers/encrypted-content.js -var EncryptedContentSymbol = Symbol.for("encrypted-content"); -var EventContentEncryptionMethod = { - [kinds_exports.EncryptedDirectMessage]: "nip04", - [kinds_exports.Seal]: "nip44", - [kinds_exports.GiftWrap]: "nip44" -}; -function setEncryptedContentEncryptionMethod(kind, method) { - EventContentEncryptionMethod[kind] = method; - return kind; -} -function getEncryptedContentEncryptionMethods(kind, signer, override) { - const method = override ?? EventContentEncryptionMethod[kind]; - if (!method) - throw new Error(`Event kind ${kind} does not support encrypted content`); - const encryption = signer[method]; - if (!encryption) - throw new Error(`Signer does not support ${method} encryption`); - return encryption; -} -function canHaveEncryptedContent(kind) { - return EventContentEncryptionMethod[kind] !== void 0; -} -function hasEncryptedContent(event) { - return event.content.length > 0; -} -function getEncryptedContent(event) { - return Reflect.get(event, EncryptedContentSymbol); -} -function isEncryptedContentLocked(event) { - return Reflect.has(event, EncryptedContentSymbol) === false; -} -async function unlockEncryptedContent(event, pubkey, signer) { - const encryption = getEncryptedContentEncryptionMethods(event.kind, signer); - const plaintext = await encryption.decrypt(pubkey, event.content); - setEncryptedContentCache(event, plaintext); - return plaintext; -} -function setEncryptedContentCache(event, plaintext) { - Reflect.set(event, EncryptedContentSymbol, plaintext); - if (isEvent(event)) - notifyEventUpdate(event); -} -function lockEncryptedContent(event) { - Reflect.deleteProperty(event, EncryptedContentSymbol); - if (isEvent(event)) - notifyEventUpdate(event); -} - -// node_modules/applesauce-core/dist/helpers/hidden-content.js -var HiddenContentSymbol = EncryptedContentSymbol; -var getHiddenContentEncryptionMethods = getEncryptedContentEncryptionMethods; -var HiddenContentKinds = /* @__PURE__ */ new Set([setEncryptedContentEncryptionMethod(kinds_exports.DraftLong, "nip04")]); -function setHiddenContentEncryptionMethod(kind, method) { - HiddenContentKinds.add(setEncryptedContentEncryptionMethod(kind, method)); - return kind; -} -function canHaveHiddenContent(kind) { - return canHaveEncryptedContent(kind) && HiddenContentKinds.has(kind); -} -function hasHiddenContent(event) { - return canHaveHiddenContent(event.kind) && hasEncryptedContent(event); -} -function isHiddenContentLocked(event) { - return isEncryptedContentLocked(event); -} -function getHiddenContent(event) { - if (!canHaveHiddenContent(event.kind) || isHiddenContentLocked(event)) - return void 0; - return getEncryptedContent(event); -} -async function unlockHiddenContent(event, signer, override) { - if (!canHaveHiddenContent(event.kind)) - throw new Error("Event kind does not support hidden content"); - const encryption = getEncryptedContentEncryptionMethods(event.kind, signer, override); - const plaintext = await encryption.decrypt(event.pubkey, event.content); - setHiddenContentCache(event, plaintext); - return plaintext; -} -function setHiddenContentCache(event, plaintext) { - if (!canHaveHiddenContent(event.kind)) - throw new Error("Event kind does not support hidden content"); - setEncryptedContentCache(event, plaintext); -} -function lockHiddenContent(event) { - lockEncryptedContent(event); -} - -// node_modules/applesauce-core/dist/helpers/url.js -var convertToUrl = (url) => url instanceof URL ? url : new URL(url); -var getURLFilename = (url) => { - var _a, _b; - return ((_a = url.pathname.split("/").pop()) == null ? void 0 : _a.toLocaleLowerCase()) || ((_b = url.searchParams.get("filename")) == null ? void 0 : _b.toLocaleLowerCase()); -}; -var IMAGE_EXT = [".svg", ".gif", ".png", ".jpg", ".jpeg", ".webp", ".avif"]; -var VIDEO_EXT = [".mp4", ".mkv", ".webm", ".mov"]; -var STREAM_EXT = [".m3u8"]; -var AUDIO_EXT = [".mp3", ".wav", ".ogg", ".aac", ".m4a"]; -function isImageURL(url) { - url = convertToUrl(url); - const filename = getURLFilename(url); - return !!filename && IMAGE_EXT.some((ext) => filename.endsWith(ext)); -} -function isVideoURL(url) { - url = convertToUrl(url); - const filename = getURLFilename(url); - return !!filename && VIDEO_EXT.some((ext) => filename.endsWith(ext)); -} -function isStreamURL(url) { - url = convertToUrl(url); - const filename = getURLFilename(url); - return !!filename && STREAM_EXT.some((ext) => filename.endsWith(ext)); -} -function isAudioURL(url) { - url = convertToUrl(url); - const filename = getURLFilename(url); - return !!filename && AUDIO_EXT.some((ext) => filename.endsWith(ext)); -} -function isSameURL(a, b) { - try { - a = normalizeURL2(a); - b = normalizeURL2(b); - return a === b; - } catch (error) { - return false; - } -} -function ensureProtocol(url, protocol = "https:") { - if (/^[a-zA-Z][a-zA-Z0-9+.-]+:/.test(url)) - return url; - return protocol + "//" + url; -} -function ensureWebSocketURL(url) { - const p = typeof url === "string" ? new URL(ensureProtocol(url, "wss:")) : new URL(url); - if (p.protocol === "http:") - p.protocol = "ws:"; - else if (p.protocol === "https:") - p.protocol = "wss:"; - else - p.protocol = "wss:"; - return typeof url === "string" ? p.toString() : p; -} -function ensureHttpURL(url) { - const p = typeof url === "string" ? new URL(ensureProtocol(url, "http:")) : new URL(url); - if (p.protocol === "ws:") - p.protocol = "http:"; - else if (p.protocol === "wss:") - p.protocol = "https:"; - else - p.protocol = "https:"; - return typeof url === "string" ? p.toString() : p; -} -function normalizeURL2(url) { - let p = new URL(url); - p.pathname = p.pathname.replace(/\/+/g, "/"); - if (p.port === "80" && (p.protocol === "ws:" || p.protocol === "http:") || p.port === "443" && (p.protocol === "wss:" || p.protocol === "https:")) - p.port = ""; - return typeof url === "string" ? p.toString() : p; -} - -// node_modules/applesauce-core/dist/helpers/groups.js -var GROUPS_LIST_KIND = 10009; -var GROUP_MESSAGE_KIND = 9; -function decodeGroupPointer(str) { - let [relay, id] = str.split("'"); - if (!relay) - throw new Error("Group pointer missing relay"); - if (!relay.match(/^wss?:/)) - relay = `wss://${relay}`; - relay = normalizeURL2(relay); - return { relay, id: id || "_" }; -} -function encodeGroupPointer(pointer) { - const hostname = URL.canParse(pointer.relay) ? new URL(pointer.relay).hostname : pointer.relay; - return `${hostname}'${pointer.id}`; -} -var GroupsPublicSymbol = Symbol.for("groups-public"); -var GroupsHiddenSymbol = Symbol.for("groups-hidden"); -function getGroupPointerFromHTag(tag) { - const [_, id, relay] = tag; - if (!id || !relay) - return void 0; - return { id, relay }; -} -function getGroupPointerFromGroupTag(tag) { - const [_, id, relay, name] = tag; - return { id, relay, name }; -} -function getPublicGroups(bookmark) { - return getOrComputeCachedValue(bookmark, GroupsPublicSymbol, () => processTags(bookmark.tags.filter((t) => t[0] === "group"), getGroupPointerFromGroupTag)); -} -function getHiddenGroups(bookmark) { - return getOrComputeCachedValue(bookmark, GroupsHiddenSymbol, () => { - const tags = getHiddenTags(bookmark); - return tags && processTags(bookmark.tags.filter((t) => t[0] === "group"), getGroupPointerFromGroupTag); - }); -} - -// node_modules/applesauce-core/dist/helpers/hidden-tags.js -var HiddenTagsSymbol = Symbol.for("hidden-tags"); -var HiddenTagsKinds = /* @__PURE__ */ new Set([ - // NIP-51 lists - setHiddenContentEncryptionMethod(kinds_exports.BookmarkList, "nip04"), - setHiddenContentEncryptionMethod(kinds_exports.InterestsList, "nip04"), - setHiddenContentEncryptionMethod(kinds_exports.Mutelist, "nip04"), - setHiddenContentEncryptionMethod(kinds_exports.CommunitiesList, "nip04"), - setHiddenContentEncryptionMethod(kinds_exports.PublicChatsList, "nip04"), - setHiddenContentEncryptionMethod(kinds_exports.SearchRelaysList, "nip04"), - setHiddenContentEncryptionMethod(GROUPS_LIST_KIND, "nip04"), - // NIP-51 sets - setHiddenContentEncryptionMethod(kinds_exports.Bookmarksets, "nip04"), - setHiddenContentEncryptionMethod(kinds_exports.Relaysets, "nip04"), - setHiddenContentEncryptionMethod(kinds_exports.Followsets, "nip04"), - setHiddenContentEncryptionMethod(kinds_exports.Curationsets, "nip04"), - setHiddenContentEncryptionMethod(kinds_exports.Interestsets, "nip04") -]); -function canHaveHiddenTags(kind) { - return canHaveHiddenContent(kind) && HiddenTagsKinds.has(kind); -} -function setHiddenTagsEncryptionMethod(kind, method) { - HiddenTagsKinds.add(setHiddenContentEncryptionMethod(kind, method)); - return kind; -} -function hasHiddenTags(event) { - return canHaveHiddenTags(event.kind) && hasHiddenContent(event); -} -function getHiddenTags(event) { - if (!canHaveHiddenTags(event.kind) || isHiddenTagsLocked(event)) - return void 0; - return getOrComputeCachedValue(event, HiddenTagsSymbol, () => { - const plaintext = getHiddenContent(event); - const parsed = JSON.parse(plaintext); - if (!Array.isArray(parsed)) - throw new Error("Content is not an array of tags"); - return parsed.filter((t) => Array.isArray(t)).map((t) => t.map((v) => String(v))); - }); -} -function isHiddenTagsLocked(event) { - return isHiddenContentLocked(event); -} -function getHiddenTagsEncryptionMethods(kind, signer) { - return getHiddenContentEncryptionMethods(kind, signer); -} -async function unlockHiddenTags(event, signer, override) { - if (!canHaveHiddenTags(event.kind)) - throw new Error("Event kind does not support hidden tags"); - if (isHiddenContentLocked(event)) - await unlockHiddenContent(event, signer, override); - return getHiddenTags(event); -} -function setHiddenTagsCache(event, tags) { - if (!canHaveHiddenTags(event.kind)) - throw new Error("Event kind does not support hidden tags"); - const plaintext = JSON.stringify(tags); - setHiddenContentCache(event, plaintext); -} -function lockHiddenTags(event) { - Reflect.deleteProperty(event, HiddenTagsSymbol); - lockHiddenContent(event); -} - -// node_modules/applesauce-core/dist/helpers/event-tags.js -var LETTERS = "abcdefghijklmnopqrstuvwxyz"; -var INDEXABLE_TAGS = new Set((LETTERS + LETTERS.toUpperCase()).split("")); -var EventIndexableTagsSymbol = Symbol.for("indexable-tags"); -function getTagValue(event, name) { - var _a, _b; - const hidden = getHiddenTags(event); - const hiddenValue = (_a = hidden == null ? void 0 : hidden.find((t) => t[0] === name)) == null ? void 0 : _a[1]; - if (hiddenValue) - return hiddenValue; - return (_b = event.tags.find((t) => t[0] === name)) == null ? void 0 : _b[1]; -} -function getIndexableTags(event) { - let indexable = Reflect.get(event, EventIndexableTagsSymbol); - if (!indexable) { - const tags = /* @__PURE__ */ new Set(); - for (const tag of event.tags) { - if (tag.length >= 2 && tag[0].length === 1 && INDEXABLE_TAGS.has(tag[0])) { - tags.add(tag[0] + ":" + tag[1]); - } - } - indexable = tags; - Reflect.set(event, EventIndexableTagsSymbol, tags); - } - return indexable; -} - -// node_modules/applesauce-core/dist/helpers/filter.js -function matchFilter(filter2, event) { - if (filter2.ids && filter2.ids.indexOf(event.id) === -1) { - return false; - } - if (filter2.kinds && filter2.kinds.indexOf(event.kind) === -1) { - return false; - } - if (filter2.authors && filter2.authors.indexOf(event.pubkey) === -1) { - return false; - } - for (let f in filter2) { - if (f[0] === "#") { - let tagName = f.slice(1); - let values = filter2[f]; - if (values) { - const tags = getIndexableTags(event); - if (values.some((v) => tags.has(tagName + ":" + v)) === false) - return false; - } - } - } - if (filter2.since && event.created_at < filter2.since) - return false; - if (filter2.until && event.created_at > filter2.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; -} -function mergeFilters(...filters) { - let result = {}; - for (let i2 = 0; i2 < filters.length; i2++) { - let filter2 = filters[i2]; - Object.entries(filter2).forEach(([property, values]) => { - if (values === void 0) - return; - if (property === "kinds" || property === "ids" || property === "authors" || property[0] === "#") { - result[property] = result[property] || []; - for (let v = 0; v < values.length; v++) { - let value = values[v]; - if (!result[property].includes(value)) - result[property].push(value); - } - } - }); - if (filter2.limit && (!result.limit || filter2.limit > result.limit)) - result.limit = filter2.limit; - if (filter2.until && (!result.until || filter2.until > result.until)) - result.until = filter2.until; - if (filter2.since && (!result.since || filter2.since < result.since)) - result.since = filter2.since; - } - return result; -} -function isFilterEqual(a, b) { - return (0, import_fast_deep_equal.default)(a, b); -} - -// node_modules/nostr-tools/lib/esm/nip19.js -var utf8Decoder2 = new TextDecoder("utf-8"); -var utf8Encoder2 = new TextEncoder(); -var Bech32MaxSize2 = 5e3; -function integerToUint8Array2(number4) { - const uint8Array = new Uint8Array(4); - uint8Array[0] = number4 >> 24 & 255; - uint8Array[1] = number4 >> 16 & 255; - uint8Array[2] = number4 >> 8 & 255; - uint8Array[3] = number4 & 255; - return uint8Array; -} -function decode2(code) { - var _a, _b, _c, _d, _e, _f, _g; - let { prefix, words } = bech32.decode(code, Bech32MaxSize2); - let data = new Uint8Array(bech32.fromWords(words)); - switch (prefix) { - case "nprofile": { - let tlv = parseTLV2(data); - if (!((_a = tlv[0]) == null ? void 0 : _a[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: bytesToHex2(tlv[0][0]), - relays: tlv[1] ? tlv[1].map((d) => utf8Decoder2.decode(d)) : [] - } - }; - } - case "nevent": { - let tlv = parseTLV2(data); - if (!((_b = tlv[0]) == null ? void 0 : _b[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: bytesToHex2(tlv[0][0]), - relays: tlv[1] ? tlv[1].map((d) => utf8Decoder2.decode(d)) : [], - author: ((_c = tlv[2]) == null ? void 0 : _c[0]) ? bytesToHex2(tlv[2][0]) : void 0, - kind: ((_d = tlv[3]) == null ? void 0 : _d[0]) ? parseInt(bytesToHex2(tlv[3][0]), 16) : void 0 - } - }; - } - case "naddr": { - let tlv = parseTLV2(data); - if (!((_e = tlv[0]) == null ? void 0 : _e[0])) - throw new Error("missing TLV 0 for naddr"); - if (!((_f = tlv[2]) == null ? void 0 : _f[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 (!((_g = tlv[3]) == null ? void 0 : _g[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: utf8Decoder2.decode(tlv[0][0]), - pubkey: bytesToHex2(tlv[2][0]), - kind: parseInt(bytesToHex2(tlv[3][0]), 16), - relays: tlv[1] ? tlv[1].map((d) => utf8Decoder2.decode(d)) : [] - } - }; - } - case "nsec": - return { type: prefix, data }; - case "npub": - case "note": - return { type: prefix, data: bytesToHex2(data) }; - default: - throw new Error(`unknown prefix ${prefix}`); - } -} -function parseTLV2(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 nsecEncode2(key) { - return encodeBytes2("nsec", key); -} -function npubEncode2(hex3) { - return encodeBytes2("npub", hexToBytes2(hex3)); -} -function noteEncode2(hex3) { - return encodeBytes2("note", hexToBytes2(hex3)); -} -function encodeBech322(prefix, data) { - let words = bech32.toWords(data); - return bech32.encode(prefix, words, Bech32MaxSize2); -} -function encodeBytes2(prefix, bytes4) { - return encodeBech322(prefix, bytes4); -} -function nprofileEncode2(profile) { - let data = encodeTLV2({ - 0: [hexToBytes2(profile.pubkey)], - 1: (profile.relays || []).map((url) => utf8Encoder2.encode(url)) - }); - return encodeBech322("nprofile", data); -} -function neventEncode2(event) { - let kindArray; - if (event.kind !== void 0) { - kindArray = integerToUint8Array2(event.kind); - } - let data = encodeTLV2({ - 0: [hexToBytes2(event.id)], - 1: (event.relays || []).map((url) => utf8Encoder2.encode(url)), - 2: event.author ? [hexToBytes2(event.author)] : [], - 3: kindArray ? [new Uint8Array(kindArray)] : [] - }); - return encodeBech322("nevent", data); -} -function naddrEncode2(addr) { - let kind = new ArrayBuffer(4); - new DataView(kind).setUint32(0, addr.kind, false); - let data = encodeTLV2({ - 0: [utf8Encoder2.encode(addr.identifier)], - 1: (addr.relays || []).map((url) => utf8Encoder2.encode(url)), - 2: [hexToBytes2(addr.pubkey)], - 3: [new Uint8Array(kind)] - }); - return encodeBech322("naddr", data); -} -function encodeTLV2(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 concatBytes3(...entries); -} - -// node_modules/applesauce-core/dist/helpers/relays.js -var SeenRelaysSymbol = Symbol.for("seen-relays"); -function addSeenRelay(event, relay) { - if (!event[SeenRelaysSymbol]) - event[SeenRelaysSymbol] = /* @__PURE__ */ new Set(); - event[SeenRelaysSymbol].add(relay); - return event[SeenRelaysSymbol]; -} -function getSeenRelays(event) { - return event[SeenRelaysSymbol]; -} -var WEBSOCKET_URL_CHECK = /^wss?:\/\/([-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}|localhost)\b([-a-zA-Z0-9()@:%_\+.~#?&\/\/=]*)$/; -function isSafeRelayURL(relay) { - return relay.length >= 8 && WEBSOCKET_URL_CHECK.test(relay); -} -function mergeRelaySets(...sources) { - const set = /* @__PURE__ */ new Set(); - for (const src of sources) { - if (!src) - continue; - for (const url of src) { - try { - const safe = normalizeURL2(url).toString(); - if (safe) - set.add(safe); - } catch (error) { - } - } - } - return Array.from(set); -} - -// node_modules/applesauce-core/dist/helpers/string.js -function isHex(str) { - if (str == null ? void 0 : str.match(/^[0-9a-f]+$/i)) - return true; - return false; -} -function isHexKey(key) { - var _a; - if ((_a = key == null ? void 0 : key.toLowerCase()) == null ? void 0 : _a.match(/^[0-9a-f]{64}$/)) - return true; - return false; -} -function stripInvisibleChar(str) { - return str && str.replaceAll(/[\p{Cf}\p{Zs}]/gu, ""); -} - -// node_modules/@noble/hashes/esm/crypto.js -var crypto3 = typeof globalThis === "object" && "crypto" in globalThis ? globalThis.crypto : void 0; - -// node_modules/@noble/hashes/esm/utils.js -function isBytes3(a) { - return a instanceof Uint8Array || ArrayBuffer.isView(a) && a.constructor.name === "Uint8Array"; -} -function abytes(b, ...lengths) { - if (!isBytes3(b)) - throw new Error("Uint8Array expected"); - if (lengths.length > 0 && !lengths.includes(b.length)) - throw new Error("Uint8Array expected of length " + lengths + ", got length=" + b.length); -} -function aexists(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 aoutput(out, instance) { - abytes(out); - const min2 = instance.outputLen; - if (out.length < min2) { - throw new Error("digestInto() expects output buffer of length at least " + min2); - } -} -function clean(...arrays) { - for (let i2 = 0; i2 < arrays.length; i2++) { - arrays[i2].fill(0); - } -} -function createView4(arr) { - return new DataView(arr.buffer, arr.byteOffset, arr.byteLength); -} -function rotr3(word, shift) { - return word << 32 - shift | word >>> shift; -} -var isLE4 = (() => new Uint8Array(new Uint32Array([287454020]).buffer)[0] === 68)(); -var hasHexBuiltin = (() => ( - // @ts-ignore - typeof Uint8Array.from([]).toHex === "function" && typeof Uint8Array.fromHex === "function" -))(); -var hexes5 = Array.from({ length: 256 }, (_, i2) => i2.toString(16).padStart(2, "0")); -function bytesToHex3(bytes4) { - abytes(bytes4); - if (hasHexBuiltin) - return bytes4.toHex(); - let hex3 = ""; - for (let i2 = 0; i2 < bytes4.length; i2++) { - hex3 += hexes5[bytes4[i2]]; - } - return hex3; -} -var asciis = { _0: 48, _9: 57, A: 65, F: 70, a: 97, f: 102 }; -function asciiToBase16(ch) { - if (ch >= asciis._0 && ch <= asciis._9) - return ch - asciis._0; - if (ch >= asciis.A && ch <= asciis.F) - return ch - (asciis.A - 10); - if (ch >= asciis.a && ch <= asciis.f) - return ch - (asciis.a - 10); - return; -} -function hexToBytes3(hex3) { - if (typeof hex3 !== "string") - throw new Error("hex string expected, got " + typeof hex3); - if (hasHexBuiltin) - return Uint8Array.fromHex(hex3); - const hl = hex3.length; - const al = hl / 2; - if (hl % 2) - throw new Error("hex string expected, got unpadded hex of length " + hl); - const array = new Uint8Array(al); - for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) { - const n1 = asciiToBase16(hex3.charCodeAt(hi)); - const n2 = asciiToBase16(hex3.charCodeAt(hi + 1)); - if (n1 === void 0 || n2 === void 0) { - const char = hex3[hi] + hex3[hi + 1]; - throw new Error('hex string expected, got non-hex character "' + char + '" at index ' + hi); - } - array[ai] = n1 * 16 + n2; - } - return array; -} -function utf8ToBytes5(str) { - if (typeof str !== "string") - throw new Error("string expected"); - return new Uint8Array(new TextEncoder().encode(str)); -} -function toBytes4(data) { - if (typeof data === "string") - data = utf8ToBytes5(data); - abytes(data); - return data; -} -var Hash3 = class { -}; -function createHasher2(hashCons) { - const hashC = (msg) => hashCons().update(toBytes4(msg)).digest(); - const tmp = hashCons(); - hashC.outputLen = tmp.outputLen; - hashC.blockLen = tmp.blockLen; - hashC.create = () => hashCons(); - return hashC; -} -function randomBytes3(bytesLength = 32) { - if (crypto3 && typeof crypto3.getRandomValues === "function") { - return crypto3.getRandomValues(new Uint8Array(bytesLength)); - } - if (crypto3 && typeof crypto3.randomBytes === "function") { - return Uint8Array.from(crypto3.randomBytes(bytesLength)); - } - throw new Error("crypto.getRandomValues must be defined"); -} - -// node_modules/applesauce-core/dist/helpers/pointers.js -function parseCoordinate(a, requireD = false, silent = true) { - const parts = a.split(":"); - const kind = parts[0] ? parseInt(parts[0]) : void 0; - const pubkey = parts[1]; - const d = parts[2]; - if (kind === void 0) { - if (silent) - return null; - else - throw new Error("Missing kind"); - } - if (pubkey === void 0 || pubkey === "") { - if (silent) - return null; - else - throw new Error("Missing pubkey"); - } - if (requireD && d === void 0) { - if (silent) - return null; - else - throw new Error("Missing identifier"); - } - return { - kind, - pubkey, - identifier: d - }; -} -function getPubkeyFromDecodeResult(result) { - if (!result) - return; - switch (result.type) { - case "naddr": - case "nprofile": - return result.data.pubkey; - case "npub": - return result.data; - case "nsec": - return getPublicKey(result.data); - default: - return void 0; - } -} -function encodeDecodeResult(result) { - switch (result.type) { - case "naddr": - return naddrEncode2(result.data); - case "nprofile": - return nprofileEncode2(result.data); - case "nevent": - return neventEncode2(result.data); - case "nsec": - return nsecEncode2(result.data); - case "npub": - return npubEncode2(result.data); - case "note": - return noteEncode2(result.data); - } - return ""; -} -function getEventPointerFromETag(tag) { - if (!tag[1]) - throw new Error("Missing event id in tag"); - let pointer = { id: tag[1] }; - if (tag[2] && isSafeRelayURL(tag[2])) - pointer.relays = [tag[2]]; - return pointer; -} -function getEventPointerFromQTag(tag) { - if (!tag[1]) - throw new Error("Missing event id in tag"); - let pointer = { id: tag[1] }; - if (tag[2] && isSafeRelayURL(tag[2])) - pointer.relays = [tag[2]]; - if (tag[3] && tag[3].length === 64) - pointer.author = tag[3]; - return pointer; -} -function getAddressPointerFromATag(tag) { - if (!tag[1]) - throw new Error("Missing coordinate in tag"); - const pointer = parseCoordinate(tag[1], true, false); - if (tag[2] && isSafeRelayURL(tag[2])) - pointer.relays = [tag[2]]; - return pointer; -} -function getProfilePointerFromPTag(tag) { - if (!tag[1]) - throw new Error("Missing pubkey in tag"); - if (!isHexKey(tag[1])) - throw new Error("Invalid pubkey"); - const pointer = { pubkey: tag[1] }; - if (tag[2] && isSafeRelayURL(tag[2])) - pointer.relays = [tag[2]]; - return pointer; -} -function isAddressPointer(pointer) { - return typeof pointer !== "string" && Reflect.has(pointer, "identifier") && Reflect.has(pointer, "pubkey") && Reflect.has(pointer, "kind"); -} -function isEventPointer(pointer) { - return typeof pointer !== "string" && Reflect.has(pointer, "id"); -} -function getCoordinateFromAddressPointer(pointer) { - return pointer.kind + ":" + pointer.pubkey + ":" + pointer.identifier; -} -function getAddressPointerForEvent(event, relays) { - if (!isAddressableKind2(event.kind)) - throw new Error("Cant get AddressPointer for non-replaceable event"); - const d = getReplaceableIdentifier(event); - return { - identifier: d, - kind: event.kind, - pubkey: event.pubkey, - relays - }; -} -function getEventPointerForEvent(event, relays) { - return { - id: event.id, - kind: event.kind, - author: event.pubkey, - relays - }; -} -function getPointerForEvent(event, relays) { - if (kinds_exports.isAddressableKind(event.kind)) { - return { - type: "naddr", - data: getAddressPointerForEvent(event, relays) - }; - } else { - return { - type: "nevent", - data: getEventPointerForEvent(event, relays) - }; - } -} -function addRelayHintsToPointer(pointer, relays) { - if (!relays) - return pointer; - else - return { ...pointer, relays: mergeRelaySets(relays, pointer.relays) }; -} -function normalizeToPubkey(str) { - if (isHexKey(str)) - return str.toLowerCase(); - else { - const decode4 = nip19_exports.decode(str); - const pubkey = getPubkeyFromDecodeResult(decode4); - if (!pubkey) - throw new Error(`Cant find pubkey in ${decode4.type}`); - return pubkey; - } -} -function normalizeToSecretKey(str) { - if (str instanceof Uint8Array) - return str; - else if (isHexKey(str)) - return hexToBytes3(str); - else { - const decode4 = nip19_exports.decode(str); - if (decode4.type !== "nsec") - throw new Error(`Cant get secret key from ${decode4.type}`); - return decode4.data; - } -} -function mergeEventPointers(a, b) { - if (a.id !== b.id) - throw new Error("Cant merge event pointers with different ids"); - const relays = mergeRelaySets(a.relays, b.relays); - return { id: a.id, kind: a.kind ?? b.kind, author: a.author ?? b.author, relays }; -} -function mergeAddressPointers(a, b) { - if (a.kind !== b.kind || a.pubkey !== b.pubkey || a.identifier !== b.identifier) - throw new Error("Cant merge address pointers with different kinds, pubkeys, or identifiers"); - const relays = mergeRelaySets(a.relays, b.relays); - return { ...a, relays }; -} -function mergeProfilePointers(a, b) { - if (a.pubkey !== b.pubkey) - throw new Error("Cant merge profile pointers with different pubkeys"); - const relays = mergeRelaySets(a.relays, b.relays); - return { ...a, relays }; -} - -// node_modules/applesauce-core/dist/helpers/blossom.js -var BLOSSOM_SERVER_LIST_KIND = 10063; -function areBlossomServersEqual(a, b) { - const hostnameA = new URL("/", a).toString(); - const hostnameB = new URL("/", b).toString(); - return hostnameA === hostnameB; -} -function isSha256(str) { - return !!str.match(/^[0-9a-f]{64}$/); -} -function getBlossomServersFromList(event) { - const tags = Array.isArray(event) ? event : event.tags; - return processTags(tags, (tag) => { - if (isNameValueTag(tag, "server") && URL.canParse(tag[1])) - return new URL("/", tag[1]); - else - return void 0; - }); -} -function mergeBlossomServers(...servers) { - let merged = []; - const seen = /* @__PURE__ */ new Set(); - for (const arg of servers) { - let arr = Array.isArray(arg) ? arg : [arg]; - for (const s of arr) { - if (s === null || s === void 0) - continue; - const key = new URL("/", s).toString(); - if (seen.has(key)) - continue; - seen.add(key); - merged.push(s); - } - } - return merged; -} - -// node_modules/applesauce-core/dist/models/blossom.js -function UserBlossomServersModel(user) { - if (typeof user === "string") - user = { pubkey: user }; - return (store) => store.replaceable({ kind: BLOSSOM_SERVER_LIST_KIND, pubkey: user.pubkey, relays: user.relays }).pipe(map((event) => event ? getBlossomServersFromList(event) : [])); -} - -// node_modules/nostr-tools/lib/esm/utils.js -var utf8Decoder3 = new TextDecoder("utf-8"); -var utf8Encoder3 = new TextEncoder(); -function insertEventIntoDescendingList2(sortedArray, event) { - const [idx, found] = binarySearch2(sortedArray, (b) => { - if (event.id === b.id) - return 0; - if (event.created_at === b.created_at) - return -1; - return b.created_at - event.created_at; - }); - if (!found) { - sortedArray.splice(idx, 0, event); - } - return sortedArray; -} -function binarySearch2(arr, compare) { - let start = 0; - let end = arr.length - 1; - while (start <= end) { - const mid = Math.floor((start + end) / 2); - const cmp = compare(arr[mid]); - if (cmp === 0) { - return [mid, true]; - } - if (cmp < 0) { - end = mid - 1; - } else { - start = mid + 1; - } - } - return [start, false]; -} - -// node_modules/applesauce-core/dist/helpers/index.js -var helpers_exports = {}; -__export(helpers_exports, { - AUDIO_EXT: () => AUDIO_EXT, - BLOSSOM_SERVER_LIST_KIND: () => BLOSSOM_SERVER_LIST_KIND, - BookmarkHiddenSymbol: () => BookmarkHiddenSymbol, - BookmarkPublicSymbol: () => BookmarkPublicSymbol, - CALENDAR_EVENT_RSVP_KIND: () => CALENDAR_EVENT_RSVP_KIND, - COMMENT_KIND: () => COMMENT_KIND, - CalendarEventGeohashSymbol: () => CalendarEventGeohashSymbol, - CalendarEventHashtagsSymbol: () => CalendarEventHashtagsSymbol, - CalendarEventLocationsSymbol: () => CalendarEventLocationsSymbol, - CalendarEventParticipantsSymbol: () => CalendarEventParticipantsSymbol, - CalendarEventReferencesSymbol: () => CalendarEventReferencesSymbol, - ChannelMetadataSymbol: () => ChannelMetadataSymbol, - CommentReplyPointerSymbol: () => CommentReplyPointerSymbol, - CommentRootPointerSymbol: () => CommentRootPointerSymbol, - ContactsRelaysSymbol: () => ContactsRelaysSymbol, - DATE_BASED_CALENDAR_EVENT_KIND: () => DATE_BASED_CALENDAR_EVENT_KIND, - EncryptedContentFromCacheSymbol: () => EncryptedContentFromCacheSymbol, - EncryptedContentSymbol: () => EncryptedContentSymbol, - EventContentEncryptionMethod: () => EventContentEncryptionMethod, - EventIndexableTagsSymbol: () => EventIndexableTagsSymbol, - EventStoreSymbol: () => EventStoreSymbol, - EventUIDSymbol: () => EventUIDSymbol, - ExpirationTimestampSymbol: () => ExpirationTimestampSymbol, - FAVORITE_RELAYS_KIND: () => FAVORITE_RELAYS_KIND, - FromCacheSymbol: () => FromCacheSymbol, - GROUPS_LIST_KIND: () => GROUPS_LIST_KIND, - GROUP_MESSAGE_KIND: () => GROUP_MESSAGE_KIND, - GiftWrapSymbol: () => GiftWrapSymbol, - GroupsHiddenSymbol: () => GroupsHiddenSymbol, - GroupsPublicSymbol: () => GroupsPublicSymbol, - HiddenContactsSymbol: () => HiddenContactsSymbol, - HiddenContentKinds: () => HiddenContentKinds, - HiddenContentSymbol: () => HiddenContentSymbol, - HiddenTagsKinds: () => HiddenTagsKinds, - HiddenTagsSymbol: () => HiddenTagsSymbol, - HighlightAttributionSymbol: () => HighlightAttributionSymbol, - HighlightSourceAddressPointerSymbol: () => HighlightSourceAddressPointerSymbol, - HighlightSourceEventPointerSymbol: () => HighlightSourceEventPointerSymbol, - IMAGE_EXT: () => IMAGE_EXT, - INDEXABLE_TAGS: () => INDEXABLE_TAGS, - LRU: () => LRU, - MailboxesInboxesSymbol: () => MailboxesInboxesSymbol, - MailboxesOutboxesSymbol: () => MailboxesOutboxesSymbol, - MediaAttachmentsSymbol: () => MediaAttachmentsSymbol, - MuteHiddenSymbol: () => MuteHiddenSymbol, - MutePublicSymbol: () => MutePublicSymbol, - NIP05_REGEX: () => NIP05_REGEX2, - Nip10ThreadRefsSymbol: () => Nip10ThreadRefsSymbol, - PICTURE_POST_KIND: () => PICTURE_POST_KIND, - POLL_KIND: () => POLL_KIND, - POLL_RESPONSE_KIND: () => POLL_RESPONSE_KIND, - ParsedReportSymbol: () => ParsedReportSymbol, - PollOptionsSymbol: () => PollOptionsSymbol, - ProfileContentSymbol: () => ProfileContentSymbol, - PublicContactsSymbol: () => PublicContactsSymbol, - ReactionAddressPointerSymbol: () => ReactionAddressPointerSymbol, - ReactionEventPointerSymbol: () => ReactionEventPointerSymbol, - ReplaceableAddressSymbol: () => ReplaceableAddressSymbol, - ReplaceableIdentifierSymbol: () => ReplaceableIdentifierSymbol, - ReportReason: () => ReportReason, - RumorSymbol: () => RumorSymbol, - STREAM_EXT: () => STREAM_EXT, - SealSymbol: () => SealSymbol, - SeenRelaysSymbol: () => SeenRelaysSymbol, - SharedAddressPointerSymbol: () => SharedAddressPointerSymbol, - SharedEventPointerSymbol: () => SharedEventPointerSymbol, - SharedEventSymbol: () => SharedEventSymbol, - TIME_BASED_CALENDAR_EVENT_KIND: () => TIME_BASED_CALENDAR_EVENT_KIND, - UserStatusPointerSymbol: () => UserStatusPointerSymbol, - VIDEO_EXT: () => VIDEO_EXT, - ZapAddressPointerSymbol: () => ZapAddressPointerSymbol, - ZapEventPointerSymbol: () => ZapEventPointerSymbol, - ZapInvoiceSymbol: () => ZapInvoiceSymbol, - ZapReceiverSymbol: () => ZapReceiverSymbol, - ZapRequestSymbol: () => ZapRequestSymbol, - ZapSenderSymbol: () => ZapSenderSymbol, - addRelayHintsToPointer: () => addRelayHintsToPointer, - addSeenRelay: () => addSeenRelay, - areBlossomServersEqual: () => areBlossomServersEqual, - canHaveEncryptedContent: () => canHaveEncryptedContent, - canHaveHiddenContent: () => canHaveHiddenContent, - canHaveHiddenTags: () => canHaveHiddenTags, - convertToUrl: () => convertToUrl, - createConversationIdentifier: () => createConversationIdentifier, - createHandlerAddressLink: () => createHandlerAddressLink, - createHandlerEventLink: () => createHandlerEventLink, - createHandlerLink: () => createHandlerLink, - createHandlerProfileLink: () => createHandlerProfileLink, - createMutedWordsRegExp: () => createMutedWordsRegExp, - createReplaceableAddress: () => createReplaceableAddress, - decodeGroupPointer: () => decodeGroupPointer, - decodeLNURL: () => decodeLNURL, - encodeDecodeResult: () => encodeDecodeResult, - encodeGroupPointer: () => encodeGroupPointer, - ensureHttpURL: () => ensureHttpURL, - ensureProtocol: () => ensureProtocol, - ensureWebSocketURL: () => ensureWebSocketURL, - fakeVerifyEvent: () => fakeVerifyEvent, - getAddressPointerForEvent: () => getAddressPointerForEvent, - getAddressPointerFromATag: () => getAddressPointerFromATag, - getAddressPointersFromList: () => getAddressPointersFromList, - getArticleImage: () => getArticleImage, - getArticlePublished: () => getArticlePublished, - getArticleSummary: () => getArticleSummary, - getArticleTitle: () => getArticleTitle, - getBlossomServersFromList: () => getBlossomServersFromList, - getBookmarks: () => getBookmarks, - getCachedValue: () => getCachedValue, - getCalendarAddressPointers: () => getCalendarAddressPointers, - getCalendarEventEnd: () => getCalendarEventEnd, - getCalendarEventEndTimezone: () => getCalendarEventEndTimezone, - getCalendarEventGeohash: () => getCalendarEventGeohash, - getCalendarEventHashtags: () => getCalendarEventHashtags, - getCalendarEventImage: () => getCalendarEventImage, - getCalendarEventLocations: () => getCalendarEventLocations, - getCalendarEventParticipants: () => getCalendarEventParticipants, - getCalendarEventReferences: () => getCalendarEventReferences, - getCalendarEventStart: () => getCalendarEventStart, - getCalendarEventStartTimezone: () => getCalendarEventStartTimezone, - getCalendarEventSummary: () => getCalendarEventSummary, - getCalendarEventTitle: () => getCalendarEventTitle, - getCalendarTitle: () => getCalendarTitle, - getChannelMetadataContent: () => getChannelMetadataContent, - getChannelPointer: () => getChannelPointer, - getCommentAddressPointer: () => getCommentAddressPointer, - getCommentEventPointer: () => getCommentEventPointer, - getCommentExternalPointer: () => getCommentExternalPointer, - getCommentReplyPointer: () => getCommentReplyPointer, - getCommentRootPointer: () => getCommentRootPointer, - getContacts: () => getContacts, - getContentWarning: () => getContentWarning, - getConversationIdentifierFromMessage: () => getConversationIdentifierFromMessage, - getConversationParticipants: () => getConversationParticipants, - getCoordinateFromAddressPointer: () => getCoordinateFromAddressPointer, - getDeleteCoordinates: () => getDeleteCoordinates, - getDeleteIds: () => getDeleteIds, - getDisplayName: () => getDisplayName, - getEmbededSharedEvent: () => getEmbededSharedEvent, - getEmojiFromTags: () => getEmojiFromTags, - getEmojiTag: () => getEmojiTag, - getEmojis: () => getEmojis, - getEncryptedContent: () => getEncryptedContent, - getEncryptedContentEncryptionMethods: () => getEncryptedContentEncryptionMethods, - getEventPointerForEvent: () => getEventPointerForEvent, - getEventPointerFromETag: () => getEventPointerFromETag, - getEventPointerFromQTag: () => getEventPointerFromQTag, - getEventPointerFromThreadTag: () => getEventPointerFromThreadTag, - getEventPointersFromList: () => getEventPointersFromList, - getEventUID: () => getEventUID, - getExpirationTimestamp: () => getExpirationTimestamp, - getExternalPointerFromTag: () => getExternalPointerFromTag, - getFileMetadata: () => getFileMetadata, - getFileMetadataFromImetaTag: () => getFileMetadataFromImetaTag, - getGiftWrapRumor: () => getGiftWrapRumor, - getGiftWrapSeal: () => getGiftWrapSeal, - getGroupPointerFromGroupTag: () => getGroupPointerFromGroupTag, - getGroupPointerFromHTag: () => getGroupPointerFromHTag, - getHandlerDescription: () => getHandlerDescription, - getHandlerLinkTemplate: () => getHandlerLinkTemplate, - getHandlerName: () => getHandlerName, - getHandlerPicture: () => getHandlerPicture, - getHandlerSupportedKinds: () => getHandlerSupportedKinds, - getHashtagTag: () => getHashtagTag, - getHiddenBookmarks: () => getHiddenBookmarks, - getHiddenContacts: () => getHiddenContacts, - getHiddenContent: () => getHiddenContent, - getHiddenContentEncryptionMethods: () => getHiddenContentEncryptionMethods, - getHiddenGroups: () => getHiddenGroups, - getHiddenMutedThings: () => getHiddenMutedThings, - getHiddenTags: () => getHiddenTags, - getHiddenTagsEncryptionMethods: () => getHiddenTagsEncryptionMethods, - getHighlightAttributions: () => getHighlightAttributions, - getHighlightComment: () => getHighlightComment, - getHighlightContext: () => getHighlightContext, - getHighlightSourceAddressPointer: () => getHighlightSourceAddressPointer, - getHighlightSourceEventPointer: () => getHighlightSourceEventPointer, - getHighlightSourceUrl: () => getHighlightSourceUrl, - getHighlightText: () => getHighlightText, - getInboxes: () => getInboxes, - getIndexableTags: () => getIndexableTags, - getInvoice: () => getInvoice, - getLegacyMessageCorraspondant: () => getLegacyMessageCorraspondant, - getLegacyMessageParent: () => getLegacyMessageParent, - getLegacyMessageReceiver: () => getLegacyMessageReceiver, - getLegacyMessageSender: () => getLegacyMessageSender, - getListTags: () => getListTags, - getMediaAttachments: () => getMediaAttachments, - getMutedThings: () => getMutedThings, - getNip10References: () => getNip10References, - getOrComputeCachedValue: () => getOrComputeCachedValue, - getOutboxes: () => getOutboxes, - getPackName: () => getPackName, - getParentEventStore: () => getParentEventStore, - getPicturePostAttachments: () => getPicturePostAttachments, - getPointerForEvent: () => getPointerForEvent, - getPollEndsAt: () => getPollEndsAt, - getPollOptions: () => getPollOptions, - getPollQuestion: () => getPollQuestion, - getPollRelays: () => getPollRelays, - getPollResponseOptions: () => getPollResponseOptions, - getPollResponsePollId: () => getPollResponsePollId, - getPollResponseVotes: () => getPollResponseVotes, - getPollType: () => getPollType, - getProfileContent: () => getProfileContent, - getProfilePicture: () => getProfilePicture, - getProfilePointerFromPTag: () => getProfilePointerFromPTag, - getProfilePointersFromList: () => getProfilePointersFromList, - getPubkeyFromDecodeResult: () => getPubkeyFromDecodeResult, - getPublicBookmarks: () => getPublicBookmarks, - getPublicContacts: () => getPublicContacts, - getPublicGroups: () => getPublicGroups, - getPublicMutedThings: () => getPublicMutedThings, - getRSVPAddressPointer: () => getRSVPAddressPointer, - getRSVPEventPointer: () => getRSVPEventPointer, - getRSVPFreeBusy: () => getRSVPFreeBusy, - getRSVPProfilePointer: () => getRSVPProfilePointer, - getRSVPStatus: () => getRSVPStatus, - getReactionAddressPointer: () => getReactionAddressPointer, - getReactionEmoji: () => getReactionEmoji, - getReactionEventPointer: () => getReactionEventPointer, - getRelaysFromContactsEvent: () => getRelaysFromContactsEvent, - getRelaysFromList: () => getRelaysFromList, - getReplaceableAddress: () => getReplaceableAddress, - getReplaceableIdentifier: () => getReplaceableIdentifier, - getReplaceableUID: () => getReplaceableUID, - getReported: () => getReported, - getRumorGiftWraps: () => getRumorGiftWraps, - getRumorSeals: () => getRumorSeals, - getSealGiftWrap: () => getSealGiftWrap, - getSealRumor: () => getSealRumor, - getSeenRelays: () => getSeenRelays, - getSha256FromURL: () => getSha256FromURL, - getSharedAddressPointer: () => getSharedAddressPointer, - getSharedEventPointer: () => getSharedEventPointer, - getStreamChatMessageStream: () => getStreamChatMessageStream, - getStreamEndTime: () => getStreamEndTime, - getStreamGoalPointer: () => getStreamGoalPointer, - getStreamHashtags: () => getStreamHashtags, - getStreamHost: () => getStreamHost, - getStreamImage: () => getStreamImage, - getStreamMaxViewers: () => getStreamMaxViewers, - getStreamParticipants: () => getStreamParticipants, - getStreamRecording: () => getStreamRecording, - getStreamRelays: () => getStreamRelays, - getStreamStartTime: () => getStreamStartTime, - getStreamStatus: () => getStreamStatus, - getStreamStreamingURLs: () => getStreamStreamingURLs, - getStreamSummary: () => getStreamSummary, - getStreamTitle: () => getStreamTitle, - getStreamViewers: () => getStreamViewers, - getTagValue: () => getTagValue, - getURLFilename: () => getURLFilename, - getUserStatusPointer: () => getUserStatusPointer, - getWrappedMessageParent: () => getWrappedMessageParent, - getWrappedMessageReceiver: () => getWrappedMessageReceiver, - getWrappedMessageSubject: () => getWrappedMessageSubject, - getWrappedMesssageSender: () => getWrappedMesssageSender, - getZapAddressPointer: () => getZapAddressPointer, - getZapEventPointer: () => getZapEventPointer, - getZapPayment: () => getZapPayment, - getZapPreimage: () => getZapPreimage, - getZapRecipient: () => getZapRecipient, - getZapRequest: () => getZapRequest, - getZapSender: () => getZapSender, - getZapSplits: () => getZapSplits, - groupMessageEvents: () => groupMessageEvents, - hasEncryptedContent: () => hasEncryptedContent, - hasHiddenContent: () => hasHiddenContent, - hasHiddenTags: () => hasHiddenTags, - hasHighlightSource: () => hasHighlightSource, - internalGiftWrapEvents: () => internalGiftWrapEvents, - interpretThreadTags: () => interpretThreadTags, - isATag: () => isATag, - isAddressPointer: () => isAddressPointer, - isAddressPointerInList: () => isAddressPointerInList, - isAudioURL: () => isAudioURL, - isCommentAddressPointer: () => isCommentAddressPointer, - isCommentEventPointer: () => isCommentEventPointer, - isDTag: () => isDTag, - isETag: () => isETag, - isEncryptedContentFromCache: () => isEncryptedContentFromCache, - isEncryptedContentLocked: () => isEncryptedContentLocked, - isEvent: () => isEvent, - isEventInList: () => isEventInList, - isEventPointer: () => isEventPointer, - isEventPointerInList: () => isEventPointerInList, - isExpired: () => isExpired, - isFilterEqual: () => isFilterEqual, - isFromCache: () => isFromCache, - isGiftWrapLocked: () => isGiftWrapLocked, - isHex: () => isHex, - isHexKey: () => isHexKey, - isHiddenContentLocked: () => isHiddenContentLocked, - isHiddenTagsLocked: () => isHiddenTagsLocked, - isImageURL: () => isImageURL, - isLegacyMessageLocked: () => isLegacyMessageLocked, - isNIP04Encrypted: () => isNIP04Encrypted, - isNameValueTag: () => isNameValueTag, - isNip05: () => isNip052, - isPTag: () => isPTag, - isProfilePointerInList: () => isProfilePointerInList, - isProtectedEvent: () => isProtectedEvent, - isRTag: () => isRTag, - isReplaceable: () => isReplaceable, - isRumor: () => isRumor, - isSafeRelayURL: () => isSafeRelayURL, - isSameURL: () => isSameURL, - isSealLocked: () => isSealLocked, - isSha256: () => isSha256, - isStreamURL: () => isStreamURL, - isTTag: () => isTTag, - isValidList: () => isValidList, - isValidProfile: () => isValidProfile, - isValidZap: () => isValidZap, - isVideoURL: () => isVideoURL, - lockEncryptedContent: () => lockEncryptedContent, - lockGiftWrap: () => lockGiftWrap, - lockHiddenContent: () => lockHiddenContent, - lockHiddenTags: () => lockHiddenTags, - lockLegacyMessage: () => lockLegacyMessage, - markEncryptedContentFromCache: () => markEncryptedContentFromCache, - markFromCache: () => markFromCache, - matchFilter: () => matchFilter, - matchFilters: () => matchFilters, - matchMutes: () => matchMutes, - mergeAddressPointers: () => mergeAddressPointers, - mergeBlossomServers: () => mergeBlossomServers, - mergeBookmarks: () => mergeBookmarks, - mergeContacts: () => mergeContacts, - mergeEventPointers: () => mergeEventPointers, - mergeFilters: () => mergeFilters, - mergeMutes: () => mergeMutes, - mergeProfilePointers: () => mergeProfilePointers, - mergeRelaySets: () => mergeRelaySets, - normalizeToPubkey: () => normalizeToPubkey, - normalizeToSecretKey: () => normalizeToSecretKey, - normalizeURL: () => normalizeURL2, - notifyEventUpdate: () => notifyEventUpdate, - parseBolt11: () => parseBolt11, - parseBookmarkTags: () => parseBookmarkTags, - parseCoordinate: () => parseCoordinate, - parseExternalPointer: () => parseExternalPointer, - parseFileMetadataTags: () => parseFileMetadataTags, - parseLNURLOrAddress: () => parseLNURLOrAddress, - parseLightningAddress: () => parseLightningAddress, - parseMutedTags: () => parseMutedTags, - parseNIP05Address: () => parseNIP05Address, - parseSharedEvent: () => parseSharedEvent, - persistEncryptedContent: () => persistEncryptedContent, - presistEventsToCache: () => presistEventsToCache, - processTags: () => processTags, - safeParse: () => safeParse, - setCachedValue: () => setCachedValue, - setEncryptedContentCache: () => setEncryptedContentCache, - setEncryptedContentEncryptionMethod: () => setEncryptedContentEncryptionMethod, - setHiddenContentCache: () => setHiddenContentCache, - setHiddenContentEncryptionMethod: () => setHiddenContentEncryptionMethod, - setHiddenTagsCache: () => setHiddenTagsCache, - setHiddenTagsEncryptionMethod: () => setHiddenTagsEncryptionMethod, - stripInvisibleChar: () => stripInvisibleChar, - unixNow: () => unixNow, - unlockEncryptedContent: () => unlockEncryptedContent, - unlockGiftWrap: () => unlockGiftWrap, - unlockHiddenContent: () => unlockHiddenContent, - unlockHiddenTags: () => unlockHiddenTags, - unlockLegacyMessage: () => unlockLegacyMessage, - unlockSeal: () => unlockSeal -}); - -// node_modules/applesauce-core/dist/helpers/profile.js -var ProfileContentSymbol = Symbol.for("profile-content"); -function getProfileContent(event) { - return getOrComputeCachedValue(event, ProfileContentSymbol, () => { - var _a, _b; - const profile = JSON.parse(event.content); - if (profile.nip05 && typeof profile.nip05 !== "string") - profile.nip05 = String(profile.nip05); - if (profile.website && ((_a = profile.website) == null ? void 0 : _a.length) > 0 && ((_b = profile.website) == null ? void 0 : _b.startsWith("http")) === false) { - profile.website = "https://" + profile.website; - } - return profile; - }); -} -function isValidProfile(profile) { - if (!profile) - return false; - if (profile.kind !== kinds_exports.Metadata && profile.kind !== kinds_exports.Handlerinformation) - return false; - try { - getProfileContent(profile); - return true; - } catch (error) { - return false; - } -} -function getProfilePicture(metadata, fallback) { - var _a; - if (!metadata) - return fallback; - if ("pubkey" in metadata && "id" in metadata && "sig" in metadata) { - if (isValidProfile(metadata)) - metadata = getProfileContent(metadata); - else - metadata = void 0; - } - return (_a = (metadata == null ? void 0 : metadata.picture) || (metadata == null ? void 0 : metadata.image) || fallback) == null ? void 0 : _a.trim(); -} -function getDisplayName(metadata, fallback) { - var _a; - if (!metadata) - return fallback; - if ("pubkey" in metadata && "id" in metadata && "sig" in metadata) { - if (!fallback) { - const npub = npubEncode2(metadata.pubkey); - fallback = npub.slice(0, 5 + 4) + "…" + npub.slice(-4); - } - if (isValidProfile(metadata)) - metadata = getProfileContent(metadata); - else - metadata = void 0; - } - return (_a = (metadata == null ? void 0 : metadata.display_name) || (metadata == null ? void 0 : metadata.displayName) || (metadata == null ? void 0 : metadata.name) || fallback) == null ? void 0 : _a.trim(); -} - -// node_modules/applesauce-core/dist/helpers/app-handlers.js -function getHandlerSupportedKinds(handler) { - return processTags(handler.tags, (t) => t[0] === "k" && t[1] ? parseInt(t[1]) : void 0); -} -function getHandlerName(handler) { - return getDisplayName(handler); -} -function getHandlerPicture(handler, fallback) { - if (!isValidProfile(handler)) - return fallback; - return getProfilePicture(handler, fallback); -} -function getHandlerDescription(handler) { - if (!isValidProfile(handler)) - return; - return getProfileContent(handler).about; -} -function getHandlerLinkTemplate(handler, platform = "web", type) { - var _a, _b; - const tags = handler.tags.filter((t) => t[0] === platform); - if (type) - return (_a = tags.find((t) => t[2] === type)) == null ? void 0 : _a[1]; - else - return (_b = tags.find((t) => t[2] === void 0 || t[2] === "")) == null ? void 0 : _b[1]; -} -function createHandlerProfileLink(handler, pointer, platform = "web") { - var _a, _b, _c; - return ((_a = getHandlerLinkTemplate(handler, platform, "nprofile")) == null ? void 0 : _a.replace("", nprofileEncode2(pointer))) || ((_b = getHandlerLinkTemplate(handler, platform, "npub")) == null ? void 0 : _b.replace("", npubEncode2(pointer.pubkey))) || ((_c = getHandlerLinkTemplate(handler, platform)) == null ? void 0 : _c.replace("", nprofileEncode2(pointer))); -} -function createHandlerEventLink(handler, pointer, platform = "web") { - var _a, _b, _c; - return ((_a = getHandlerLinkTemplate(handler, platform, "nevent")) == null ? void 0 : _a.replace("", neventEncode2(pointer))) || ((_b = getHandlerLinkTemplate(handler, platform, "note")) == null ? void 0 : _b.replace("", noteEncode2(pointer.id))) || ((_c = getHandlerLinkTemplate(handler, platform)) == null ? void 0 : _c.replace("", neventEncode2(pointer))); -} -function createHandlerAddressLink(handler, pointer, platform = "web") { - var _a, _b; - return ((_a = getHandlerLinkTemplate(handler, platform, "naddr")) == null ? void 0 : _a.replace("", naddrEncode2(pointer))) || ((_b = getHandlerLinkTemplate(handler, platform)) == null ? void 0 : _b.replace("", naddrEncode2(pointer))); -} -function createHandlerLink(handler, pointer, platform, webFallback = true) { - let link = void 0; - if (isEventPointer(pointer)) - link = createHandlerEventLink(handler, pointer, platform); - else if (isAddressPointer(pointer)) - link = createHandlerAddressLink(handler, pointer, platform); - else - link = createHandlerProfileLink(handler, pointer, platform); - if (!link && platform && platform !== "web" && webFallback) - link = createHandlerLink(handler, pointer, "web"); - return link; -} - -// node_modules/applesauce-core/dist/helpers/article.js -function getArticleTitle(article) { - return getTagValue(article, "title"); -} -function getArticleImage(article) { - return getTagValue(article, "image"); -} -function getArticleSummary(article) { - return getTagValue(article, "summary"); -} -function getArticlePublished(article) { - const ts = getTagValue(article, "published_at"); - if (ts && !Number.isNaN(parseInt(ts))) - return parseInt(ts); - else - return article.created_at; -} - -// node_modules/applesauce-core/dist/helpers/bolt11.js -var import_light_bolt11_decoder = __toESM(require_bolt11(), 1); -function parseBolt11(paymentRequest) { - var _a, _b, _c; - const decoded = (0, import_light_bolt11_decoder.decode)(paymentRequest); - const timestamp2 = ((_a = decoded.sections.find((s) => s.name === "timestamp")) == null ? void 0 : _a.value) ?? 0; - const description = ((_b = decoded.sections.find((s) => s.name === "description")) == null ? void 0 : _b.value) ?? ""; - const amount = parseInt(((_c = decoded.sections.find((s) => s.name === "amount")) == null ? void 0 : _c.value) ?? "0"); - const paymentHash = decoded.sections.find((s) => s.name === "payment_hash"); - return { - paymentRequest: decoded.paymentRequest, - description, - amount, - timestamp: timestamp2, - expiry: timestamp2 + decoded.expiry, - paymentHash: paymentHash == null ? void 0 : paymentHash.value - }; -} - -// node_modules/applesauce-core/dist/helpers/bookmarks.js -var BookmarkPublicSymbol = Symbol.for("bookmark-public"); -var BookmarkHiddenSymbol = Symbol.for("bookmark-hidden"); -function parseBookmarkTags(tags) { - const notes = tags.filter((t) => t[0] === "e" && t[1]).map(getEventPointerFromETag); - const articles = tags.filter((t) => t[0] === "a" && t[1]).map(getAddressPointerFromATag).filter((addr) => addr.kind === kinds_exports.LongFormArticle); - const hashtags = tags.filter((t) => t[0] === "t" && t[1]).map((t) => t[1]); - const urls = tags.filter((t) => t[0] === "r" && t[1]).map((t) => t[1]); - return { notes, articles, hashtags, urls }; -} -function mergeBookmarks(...bookmarks) { - const notes = /* @__PURE__ */ new Map(); - const articles = /* @__PURE__ */ new Map(); - const hashtags = /* @__PURE__ */ new Set(); - const urls = /* @__PURE__ */ new Set(); - for (const bookmark of bookmarks) { - if (!bookmark) - continue; - for (const note of bookmark.notes) { - const existing = notes.get(note.id); - if (existing) - notes.set(note.id, mergeEventPointers(existing, note)); - else - notes.set(note.id, note); - } - for (const article of bookmark.articles) { - const coord = getCoordinateFromAddressPointer(article); - const existing = articles.get(coord); - if (existing) - articles.set(coord, mergeAddressPointers(existing, article)); - else - articles.set(coord, article); - } - for (const hashtag of bookmark.hashtags) - hashtags.add(hashtag); - for (const url of bookmark.urls) - urls.add(url); - } - return { - notes: Array.from(notes.values()), - articles: Array.from(articles.values()), - hashtags: Array.from(hashtags), - urls: Array.from(urls) - }; -} -function getBookmarks(bookmark) { - const hidden = getHiddenBookmarks(bookmark); - if (hidden) - return mergeBookmarks(hidden, getPublicBookmarks(bookmark)); - else - return getPublicBookmarks(bookmark); -} -function getPublicBookmarks(bookmark) { - return getOrComputeCachedValue(bookmark, BookmarkPublicSymbol, () => parseBookmarkTags(bookmark.tags)); -} -function getHiddenBookmarks(bookmark) { - if (isHiddenTagsLocked(bookmark)) - return void 0; - return getOrComputeCachedValue(bookmark, BookmarkHiddenSymbol, () => parseBookmarkTags(getHiddenTags(bookmark))); -} - -// node_modules/applesauce-core/dist/helpers/calendar-event.js -var DATE_BASED_CALENDAR_EVENT_KIND = 31922; -var TIME_BASED_CALENDAR_EVENT_KIND = 31923; -var CalendarEventLocationsSymbol = Symbol.for("calendar-event-locations"); -var CalendarEventParticipantsSymbol = Symbol.for("calendar-event-participants"); -var CalendarEventHashtagsSymbol = Symbol.for("calendar-event-hashtags"); -var CalendarEventReferencesSymbol = Symbol.for("calendar-event-references"); -var CalendarEventGeohashSymbol = Symbol.for("calendar-event-geohash"); -function getCalendarEventTitle(event) { - return getTagValue(event, "title") || getTagValue(event, "name"); -} -function getCalendarEventSummary(event) { - return getTagValue(event, "summary"); -} -function getCalendarEventImage(event) { - return getTagValue(event, "image"); -} -function getCalendarEventStart(event) { - const value = getTagValue(event, "start"); - if (!value) - return void 0; - if (event.kind === DATE_BASED_CALENDAR_EVENT_KIND) - return new Date(value).valueOf() / 1e3; - else if (event.kind === TIME_BASED_CALENDAR_EVENT_KIND) - return parseInt(value); - else - return void 0; -} -function getCalendarEventStartTimezone(event) { - if (event.kind === DATE_BASED_CALENDAR_EVENT_KIND) - return void 0; - return getTagValue(event, "start_tzid"); -} -function getCalendarEventEndTimezone(event) { - if (event.kind === DATE_BASED_CALENDAR_EVENT_KIND) - return void 0; - return getTagValue(event, "end_tzid"); -} -function getCalendarEventEnd(event) { - const value = getTagValue(event, "end"); - if (!value) - return void 0; - if (event.kind === DATE_BASED_CALENDAR_EVENT_KIND) - return new Date(value).valueOf() / 1e3; - else if (event.kind === TIME_BASED_CALENDAR_EVENT_KIND) - return parseInt(value); - else - return void 0; -} -function getCalendarEventLocations(event) { - if (event.kind !== DATE_BASED_CALENDAR_EVENT_KIND && event.kind !== TIME_BASED_CALENDAR_EVENT_KIND) - throw new Error("Event is not a date-based or time-based calendar event"); - return getOrComputeCachedValue(event, CalendarEventLocationsSymbol, () => { - return event.tags.filter((t) => t[0] === "location" && t[1]).map((t) => t[1]); - }); -} -function getCalendarEventGeohash(event) { - if (event.kind !== DATE_BASED_CALENDAR_EVENT_KIND && event.kind !== TIME_BASED_CALENDAR_EVENT_KIND) - throw new Error("Event is not a date-based or time-based calendar event"); - return getOrComputeCachedValue(event, CalendarEventGeohashSymbol, () => { - let hash3 = void 0; - for (const tag of event.tags) { - if (tag[0] === "g" && tag[1] && (!hash3 || tag[1].length > hash3.length)) - hash3 = tag[1]; - } - return hash3; - }); -} -function getCalendarEventParticipants(event) { - if (event.kind !== DATE_BASED_CALENDAR_EVENT_KIND && event.kind !== TIME_BASED_CALENDAR_EVENT_KIND) - throw new Error("Event is not a date-based or time-based calendar event"); - return getOrComputeCachedValue(event, CalendarEventParticipantsSymbol, () => { - return event.tags.filter(isPTag).map((tag) => ({ - ...getProfilePointerFromPTag(tag), - // Third index of tag is optional "role" - role: tag[3] || void 0 - })); - }); -} -function getCalendarEventHashtags(event) { - if (event.kind !== DATE_BASED_CALENDAR_EVENT_KIND && event.kind !== TIME_BASED_CALENDAR_EVENT_KIND) - throw new Error("Event is not a date-based or time-based calendar event"); - return getOrComputeCachedValue(event, CalendarEventHashtagsSymbol, () => { - return event.tags.filter(isTTag).map((t) => t[1]); - }); -} -function getCalendarEventReferences(event) { - if (event.kind !== DATE_BASED_CALENDAR_EVENT_KIND && event.kind !== TIME_BASED_CALENDAR_EVENT_KIND) - throw new Error("Event is not a date-based or time-based calendar event"); - return getOrComputeCachedValue(event, CalendarEventReferencesSymbol, () => { - return event.tags.filter(isRTag).map((t) => t[1]); - }); -} - -// node_modules/applesauce-core/dist/helpers/calendar-rsvp.js -var CALENDAR_EVENT_RSVP_KIND = 31925; -function getRSVPStatus(event) { - const status = getTagValue(event, "status"); - return status && ["accepted", "declined", "tentative"].includes(status) ? status : void 0; -} -function getRSVPFreeBusy(event) { - const status = getRSVPStatus(event); - if (status === "declined") - return void 0; - const fb = getTagValue(event, "fb"); - return fb && ["free", "busy"].includes(fb) ? fb : void 0; -} -function getRSVPAddressPointer(event) { - const tag = event.tags.find(isATag); - if (!tag) - return void 0; - return getAddressPointerFromATag(tag); -} -function getRSVPEventPointer(event) { - const tag = event.tags.find(isETag); - if (!tag) - return void 0; - return getEventPointerFromETag(tag); -} -function getRSVPProfilePointer(event) { - const tag = event.tags.find(isPTag); - if (!tag) - return void 0; - return getProfilePointerFromPTag(tag); -} - -// node_modules/applesauce-core/dist/helpers/calendar.js -function getCalendarTitle(event) { - return getTagValue(event, "title"); -} -function getCalendarAddressPointers(event) { - return event.tags.filter(isATag).map(getAddressPointerFromATag); -} - -// node_modules/applesauce-core/dist/helpers/channels.js -var ChannelMetadataSymbol = Symbol.for("channel-metadata"); -function parseChannelMetadataContent(channel) { - const metadata = JSON.parse(channel.content); - if (metadata.name === void 0) - throw new Error("Missing name"); - if (metadata.about === void 0) - throw new Error("Missing about"); - if (metadata.picture === void 0) - throw new Error("Missing picture"); - if (metadata.relays && !Array.isArray(metadata.relays)) - throw new Error("Invalid relays"); - return metadata; -} -function getChannelMetadataContent(channel) { - return getOrComputeCachedValue(channel, ChannelMetadataSymbol, () => { - return parseChannelMetadataContent(channel); - }); -} -function getChannelPointer(event) { - const tag = event.tags.find((t) => t[0] === "e" && t[1]); - if (!tag) - return void 0; - return tag[2] ? { id: tag[1], relays: [tag[2]] } : { id: tag[1] }; -} - -// node_modules/applesauce-core/dist/helpers/external-id.js -function parseExternalPointer(identifier) { - if (identifier.startsWith("#")) - return { kind: "#", identifier }; - if (identifier.startsWith("geo:")) - return { kind: "geo", identifier }; - if (identifier.startsWith("podcast:guid:")) - return { kind: "podcast:guid", identifier }; - if (identifier.startsWith("podcast:item:guid:")) - return { kind: "podcast:item:guid", identifier }; - if (identifier.startsWith("podcast:publisher:guid:")) - return { kind: "podcast:publisher:guid", identifier }; - if (identifier.startsWith("isan:")) - return { kind: "isan", identifier }; - if (identifier.startsWith("doi:")) - return { kind: "doi", identifier }; - throw new Error("Failed to parse external identifier"); -} -function getExternalPointerFromTag(tag) { - return parseExternalPointer(tag[1]); -} - -// node_modules/applesauce-core/dist/helpers/comment.js -var COMMENT_KIND = 1111; -var CommentRootPointerSymbol = Symbol.for("comment-root-pointer"); -var CommentReplyPointerSymbol = Symbol.for("comment-reply-pointer"); -function getCommentEventPointer(tags, root = false) { - var _a, _b; - const eTag = tags.find((t) => t[0] === (root ? "E" : "e")); - const kind = (_a = tags.find((t) => t[0] === (root ? "K" : "k"))) == null ? void 0 : _a[1]; - if (eTag) { - if (!kind) - throw new Error("Missing kind tag"); - const rootPubkey = root ? (_b = tags.find((t) => t[0] === "P")) == null ? void 0 : _b[1] : void 0; - const pointer = { - type: "event", - id: eTag[1], - kind: parseInt(kind), - pubkey: eTag[3] || rootPubkey || void 0, - relay: eTag[2] && isSafeRelayURL(eTag[2]) ? eTag[2] : void 0 - }; - return pointer; - } - return null; -} -function getCommentAddressPointer(tags, root = false) { - var _a, _b; - const aTag = tags.find((t) => t[0] === (root ? "A" : "a")); - const eTag = tags.find((t) => t[0] === (root ? "E" : "e")); - const kind = (_a = tags.find((t) => t[0] === (root ? "K" : "k"))) == null ? void 0 : _a[1]; - if (aTag) { - if (!kind) - throw new Error("Missing kind tag"); - const addressPointer = getAddressPointerFromATag(aTag); - const pointer = { - type: "address", - id: eTag == null ? void 0 : eTag[1], - pubkey: addressPointer.pubkey, - identifier: addressPointer.identifier, - kind: addressPointer.kind || parseInt(kind), - relay: ((_b = addressPointer.relays) == null ? void 0 : _b[0]) || (eTag == null ? void 0 : eTag[2]) - }; - return pointer; - } - return null; -} -function getCommentExternalPointer(tags, root = false) { - var _a; - const iTag = tags.find((t) => t[0] === (root ? "I" : "i")); - const kind = (_a = tags.find((t) => t[0] === (root ? "K" : "k"))) == null ? void 0 : _a[1]; - if (iTag) { - if (!kind) - throw new Error("Missing kind tag"); - return { - type: "external", - ...getExternalPointerFromTag(iTag) - }; - } - return null; -} -function getCommentRootPointer(comment) { - if (comment.kind !== COMMENT_KIND) - throw new Error("Event is not a comment"); - return getOrComputeCachedValue(comment, CommentRootPointerSymbol, () => { - const A = getCommentAddressPointer(comment.tags, true); - if (A) - return A; - const E = getCommentEventPointer(comment.tags, true); - if (E) - return E; - const I = getCommentExternalPointer(comment.tags, true); - if (I) - return I; - return null; - }); -} -function getCommentReplyPointer(comment) { - if (comment.kind !== COMMENT_KIND) - throw new Error("Event is not a comment"); - return getOrComputeCachedValue(comment, CommentReplyPointerSymbol, () => { - const A = getCommentAddressPointer(comment.tags, false); - if (A) - return A; - const E = getCommentEventPointer(comment.tags, false); - if (E) - return E; - const I = getCommentExternalPointer(comment.tags, false); - if (I) - return I; - return null; - }); -} -function isCommentEventPointer(pointer) { - return Reflect.has(pointer, "id") && Reflect.has(pointer, "kind") && !Reflect.has(pointer, "identifier") && typeof pointer.kind === "number"; -} -function isCommentAddressPointer(pointer) { - return Reflect.has(pointer, "identifier") && Reflect.has(pointer, "pubkey") && Reflect.has(pointer, "kind") && typeof pointer.kind === "number"; -} - -// node_modules/applesauce-core/dist/helpers/contacts.js -var ContactsRelaysSymbol = Symbol.for("contacts-relays"); -var PublicContactsSymbol = Symbol.for("public-contacts"); -var HiddenContactsSymbol = Symbol.for("hidden-contacts"); -function getRelaysFromContactsEvent(event) { - return getOrComputeCachedValue(event, ContactsRelaysSymbol, () => { - try { - const relayJson = JSON.parse(event.content); - const relays = /* @__PURE__ */ new Map(); - for (const [url, opts] of Object.entries(relayJson)) { - if (!isSafeRelayURL(url)) - continue; - if (opts.write && opts.read) - relays.set(url, "all"); - else if (opts.read) - relays.set(url, "inbox"); - else if (opts.write) - relays.set(url, "outbox"); - } - return relays; - } catch (error) { - return null; - } - }); -} -function mergeContacts(...pointers) { - const merged = /* @__PURE__ */ new Map(); - for (const arr of pointers) { - if (Array.isArray(arr)) { - for (const pointer of arr) - if (pointer) - merged.set(pointer.pubkey, pointer); - } else if (arr) { - merged.set(arr.pubkey, arr); - } - } - return Array.from(merged.values()); -} -function getContacts(event) { - return mergeContacts(getPublicContacts(event), getHiddenContacts(event)); -} -function getPublicContacts(event) { - return getOrComputeCachedValue(event, PublicContactsSymbol, () => processTags(event.tags, (t) => isPTag(t) ? t : void 0, getProfilePointerFromPTag)); -} -function getHiddenContacts(event) { - if (isHiddenTagsLocked(event)) - return void 0; - return getOrComputeCachedValue(event, HiddenContactsSymbol, () => processTags(getHiddenTags(event), (t) => isPTag(t) ? t : void 0, getProfilePointerFromPTag)); -} - -// node_modules/applesauce-core/dist/helpers/content.js -function getContentWarning(event) { - const tag = event.tags.find((t) => t[0] === "content-warning"); - if (tag) - return tag[1] || true; - else - return false; -} - -// node_modules/nostr-tools/lib/esm/nip05.js -var NIP05_REGEX2 = /^(?:([\w.+-]+)@)?([\w_-]+(\.[\w_-]+)+)$/; -var isNip052 = (value) => NIP05_REGEX2.test(value || ""); -var _fetch5; -try { - _fetch5 = fetch; -} catch (_) { - null; -} - -// node_modules/applesauce-core/dist/helpers/dns-identity.js -function parseNIP05Address(address) { - const match = address.toLowerCase().match(NIP05_REGEX2); - if (!match) - return null; - const [, name = "_", domain] = match; - return { name, domain }; -} - -// node_modules/applesauce-core/dist/helpers/emoji.js -function getEmojiTag(tags, code) { - code = code.replace(/^:|:$/g, "").toLowerCase(); - return (Array.isArray(tags) ? tags : tags.tags).find((t) => t[0] === "emoji" && t.length >= 3 && t[1].toLowerCase() === code); -} -function getEmojiFromTags(event, code) { - const tag = getEmojiTag(event, code); - if (!tag) - return void 0; - return { - shortcode: tag[1], - url: tag[2] - }; -} -function getPackName(pack) { - return getTagValue(pack, "title") || getTagValue(pack, "d"); -} -function getEmojis(pack) { - return pack.tags.filter((t) => t[0] === "emoji" && t[1] && t[2]).map((t) => ({ shortcode: t[1], url: t[2] })); -} -function getReactionEmoji(event) { - var _a; - const shortcode = (_a = /^:+(.+?):+$/g.exec(event.content.trim().toLowerCase())) == null ? void 0 : _a[1]; - if (!shortcode) - return void 0; - return getEmojiFromTags(event, shortcode); -} - -// node_modules/applesauce-core/dist/logger.js -var import_debug = __toESM(require_browser(), 1); -var logger = (0, import_debug.default)("applesauce"); - -// node_modules/applesauce-core/dist/helpers/lru.js -var LRU = class { - constructor(max2 = 0, ttl = 0, resetTtl = false) { - __publicField(this, "first", null); - __publicField(this, "items", /* @__PURE__ */ Object.create(null)); - __publicField(this, "last", null); - __publicField(this, "max"); - __publicField(this, "resetTtl"); - __publicField(this, "size"); - __publicField(this, "ttl"); - this.first = null; - this.items = /* @__PURE__ */ Object.create(null); - this.last = null; - this.max = max2; - this.resetTtl = resetTtl; - this.size = 0; - this.ttl = ttl; - } - clear() { - this.first = null; - this.items = /* @__PURE__ */ Object.create(null); - this.last = null; - this.size = 0; - return this; - } - delete(key) { - if (this.has(key)) { - const item = this.items[key]; - delete this.items[key]; - this.size--; - if (item.prev !== null) { - item.prev.next = item.next; - } - if (item.next !== null) { - item.next.prev = item.prev; - } - if (this.first === item) { - this.first = item.next; - } - if (this.last === item) { - this.last = item.prev; - } - } - return this; - } - entries(keys = this.keys()) { - return keys.map((key) => [key, this.get(key)]); - } - evict(bypass = false) { - if (bypass || this.size > 0) { - const item = this.first; - delete this.items[item.key]; - if (--this.size === 0) { - this.first = null; - this.last = null; - } else { - this.first = item.next; - this.first.prev = null; - } - } - return this; - } - expiresAt(key) { - let result; - if (this.has(key)) { - result = this.items[key].expiry; - } - return result; - } - get(key) { - let result; - if (this.has(key)) { - const item = this.items[key]; - if (this.ttl > 0 && item.expiry <= Date.now()) { - this.delete(key); - } else { - result = item.value; - this.set(key, result, true); - } - } - return result; - } - has(key) { - return key in this.items; - } - keys() { - const result = []; - let x = this.first; - while (x !== null) { - result.push(x.key); - x = x.next; - } - return result; - } - set(key, value, bypass = false, resetTtl = this.resetTtl) { - let item; - if (bypass || this.has(key)) { - item = this.items[key]; - item.value = value; - if (bypass === false && resetTtl) { - item.expiry = this.ttl > 0 ? Date.now() + this.ttl : this.ttl; - } - if (this.last !== item) { - const last3 = this.last, next = item.next, prev = item.prev; - if (this.first === item) { - this.first = item.next; - } - item.next = null; - item.prev = this.last; - last3.next = item; - if (prev !== null) { - prev.next = next; - } - if (next !== null) { - next.prev = prev; - } - } - } else { - if (this.max > 0 && this.size === this.max) { - this.evict(true); - } - item = this.items[key] = { - expiry: this.ttl > 0 ? Date.now() + this.ttl : this.ttl, - key, - prev: this.last, - next: null, - value - }; - if (++this.size === 1) { - this.first = item; - } else { - this.last.next = item; - } - } - this.last = item; - return this; - } - values(keys = this.keys()) { - return keys.map((key) => this.get(key)); - } -}; - -// node_modules/applesauce-core/dist/event-store/event-set.js -var EventSet = class { - constructor() { - __publicField(this, "log", logger.extend("EventSet")); - /** Indexes */ - __publicField(this, "kinds", /* @__PURE__ */ new Map()); - __publicField(this, "authors", /* @__PURE__ */ new Map()); - __publicField(this, "tags", new LRU()); - __publicField(this, "created_at", []); - /** LRU cache of last events touched */ - __publicField(this, "events", new LRU()); - /** A sorted array of replaceable events by address */ - __publicField(this, "replaceable", /* @__PURE__ */ new Map()); - /** A stream of events inserted into the database */ - __publicField(this, "insert$", new Subject()); - /** A stream of events that have been updated */ - __publicField(this, "update$", new Subject()); - /** A stream of events removed from the database */ - __publicField(this, "remove$", new Subject()); - /** A method thats called before a new event is inserted */ - __publicField(this, "onBeforeInsert"); - /** A weak map of events that are claimed by other things */ - __publicField(this, "claims", /* @__PURE__ */ new WeakMap()); - } - /** The number of events in the event set */ - get size() { - return this.events.size; - } - /** Moves an event to the top of the LRU cache */ - touch(event) { - this.events.set(event.id, event); - } - /** Checks if the database contains an event without touching it */ - hasEvent(id) { - return this.events.has(id); - } - /** Gets a single event based on id */ - getEvent(id) { - return this.events.get(id); - } - /** Checks if the event set has a replaceable event */ - hasReplaceable(kind, pubkey, identifier) { - const events = this.replaceable.get(createReplaceableAddress(kind, pubkey, identifier)); - return !!events && events.length > 0; - } - /** Gets the latest replaceable event */ - getReplaceable(kind, pubkey, identifier) { - const address = createReplaceableAddress(kind, pubkey, identifier); - const events = this.replaceable.get(address); - return events == null ? void 0 : events[0]; - } - /** Gets the history of a replaceable event */ - getReplaceableHistory(kind, pubkey, identifier) { - const address = createReplaceableAddress(kind, pubkey, identifier); - return this.replaceable.get(address); - } - /** Gets all events that match the filters */ - getByFilters(filters) { - return this.getEventsForFilters(Array.isArray(filters) ? filters : [filters]); - } - /** Gets a timeline of events that match the filters */ - getTimeline(filters) { - const timeline = []; - const events = this.getEventsForFilters(Array.isArray(filters) ? filters : [filters]); - for (const event of events) - insertEventIntoDescendingList2(timeline, event); - return timeline; - } - /** Inserts an event into the database and notifies all subscriptions */ - add(event) { - var _a, _b; - const id = event.id; - const current = this.events.get(id); - if (current) - return current; - if (((_a = this.onBeforeInsert) == null ? void 0 : _a.call(this, event)) === false) - return null; - this.events.set(id, event); - this.getKindIndex(event.kind).add(event); - this.getAuthorsIndex(event.pubkey).add(event); - for (const tag of getIndexableTags(event)) { - if (this.tags.has(tag)) - this.getTagIndex(tag).add(event); - } - insertEventIntoDescendingList2(this.created_at, event); - if (isReplaceable(event.kind)) { - const identifier = (_b = event.tags.find((t) => t[0] === "d")) == null ? void 0 : _b[1]; - const address = createReplaceableAddress(event.kind, event.pubkey, identifier); - let array = this.replaceable.get(address); - if (!this.replaceable.has(address)) { - array = []; - this.replaceable.set(address, array); - } - insertEventIntoDescendingList2(array, event); - } - this.insert$.next(event); - return event; - } - /** Inserts and event into the database and notifies all subscriptions that the event has updated */ - update(event) { - const inserted = this.add(event); - if (inserted) - this.update$.next(inserted); - return inserted !== null; - } - /** Removes an event from the database and notifies all subscriptions */ - remove(eventOrId) { - var _a; - let event = typeof eventOrId === "string" ? this.events.get(eventOrId) : eventOrId; - if (!event) - throw new Error("Missing event"); - const id = event.id; - if (!this.events.has(id)) - return false; - this.getAuthorsIndex(event.pubkey).delete(event); - this.getKindIndex(event.kind).delete(event); - for (const tag of getIndexableTags(event)) { - if (this.tags.has(tag)) { - this.getTagIndex(tag).delete(event); - } - } - const i2 = this.created_at.indexOf(event); - this.created_at.splice(i2, 1); - this.events.delete(id); - if (isReplaceable(event.kind)) { - const identifier = (_a = event.tags.find((t) => t[0] === "d")) == null ? void 0 : _a[1]; - const address = createReplaceableAddress(event.kind, event.pubkey, identifier); - const array = this.replaceable.get(address); - if (array && array.includes(event)) { - const idx = array.indexOf(event); - array.splice(idx, 1); - } - } - this.claims.delete(event); - this.remove$.next(event); - return true; - } - /** Sets the claim on the event and touches it */ - claim(event, claim) { - if (!this.claims.has(event)) { - this.claims.set(event, claim); - } - this.touch(event); - } - /** Checks if an event is claimed by anything */ - isClaimed(event) { - return this.claims.has(event); - } - /** Removes a claim from an event */ - removeClaim(event, claim) { - const current = this.claims.get(event); - if (current === claim) - this.claims.delete(event); - } - /** Removes all claims on an event */ - clearClaim(event) { - this.claims.delete(event); - } - /** Index helper methods */ - getKindIndex(kind) { - if (!this.kinds.has(kind)) - this.kinds.set(kind, /* @__PURE__ */ new Set()); - return this.kinds.get(kind); - } - getAuthorsIndex(author) { - if (!this.authors.has(author)) - this.authors.set(author, /* @__PURE__ */ new Set()); - return this.authors.get(author); - } - getTagIndex(tagAndValue) { - if (!this.tags.has(tagAndValue)) { - const events = /* @__PURE__ */ new Set(); - const ts = Date.now(); - for (const event of this.events.values()) { - if (getIndexableTags(event).has(tagAndValue)) { - events.add(event); - } - } - const took = Date.now() - ts; - if (took > 100) - this.log(`Built index ${tagAndValue} took ${took}ms`); - this.tags.set(tagAndValue, events); - } - return this.tags.get(tagAndValue); - } - /** Iterates over all events by author */ - *iterateAuthors(authors) { - for (const author of authors) { - const events = this.authors.get(author); - if (events) { - for (const event of events) - yield event; - } - } - } - /** Iterates over all events by indexable tag and value */ - *iterateTag(tag, values) { - for (const value of values) { - const events = this.getTagIndex(tag + ":" + value); - if (events) { - for (const event of events) - yield event; - } - } - } - /** Iterates over all events by kind */ - *iterateKinds(kinds) { - for (const kind of kinds) { - const events = this.kinds.get(kind); - if (events) { - for (const event of events) - yield event; - } - } - } - /** Iterates over all events by time */ - *iterateTime(since, until) { - let untilIndex = 0; - let sinceIndex = this.created_at.length - 1; - let start = until ? binarySearch2(this.created_at, (mid) => { - return mid.created_at - until; - }) : void 0; - if (start) - untilIndex = start[0]; - const end = since ? binarySearch2(this.created_at, (mid) => { - return mid.created_at - since; - }) : void 0; - if (end) - sinceIndex = end[0]; - for (let i2 = untilIndex; i2 < sinceIndex; i2++) { - yield this.created_at[i2]; - } - } - /** Iterates over all events by id */ - *iterateIds(ids) { - for (const id of ids) { - if (this.events.has(id)) - yield this.events.get(id); - } - } - /** Returns all events that match the filter */ - getEventsForFilter(filter2) { - if (filter2.search) - return /* @__PURE__ */ new Set(); - let first2 = true; - let events = /* @__PURE__ */ new Set(); - const and = (iterable) => { - const set = iterable instanceof Set ? iterable : new Set(iterable); - if (first2) { - events = set; - first2 = false; - } else { - for (const event of events) { - if (!set.has(event)) - events.delete(event); - } - } - return events; - }; - if (filter2.ids) - and(this.iterateIds(filter2.ids)); - let time = null; - if (filter2.since !== void 0) { - time = Array.from(this.iterateTime(filter2.since, filter2.until)); - and(time); - } - for (const t of INDEXABLE_TAGS) { - const key = `#${t}`; - const values = filter2[key]; - if (values == null ? void 0 : values.length) - and(this.iterateTag(t, values)); - } - if (filter2.authors) - and(this.iterateAuthors(filter2.authors)); - if (filter2.kinds) - and(this.iterateKinds(filter2.kinds)); - if (filter2.since === void 0 && filter2.until !== void 0) { - time = Array.from(this.iterateTime(filter2.since, filter2.until)); - and(time); - } - if (filter2.limit && time) { - const limited = /* @__PURE__ */ new Set(); - for (const event of time) { - if (limited.size >= filter2.limit) - break; - if (events.has(event)) - limited.add(event); - } - return limited; - } - return events; - } - /** Returns all events that match the filters */ - getEventsForFilters(filters) { - if (filters.length === 0) - throw new Error("No Filters"); - let events = /* @__PURE__ */ new Set(); - for (const filter2 of filters) { - const filtered = this.getEventsForFilter(filter2); - for (const event of filtered) - events.add(event); - } - return events; - } - /** Remove the oldest events that are not claimed */ - prune(limit2 = 1e3) { - let removed = 0; - let cursor = this.events.first; - while (cursor) { - const event = cursor.value; - if (!this.isClaimed(event)) { - this.remove(event); - removed++; - if (removed >= limit2) - break; - } - cursor = cursor.next; - } - return removed; - } - /** Resets the event set */ - reset() { - this.events.clear(); - this.kinds.clear(); - this.authors.clear(); - this.tags.clear(); - this.created_at = []; - this.replaceable.clear(); - this.claims = /* @__PURE__ */ new WeakMap(); - } -}; - -// node_modules/applesauce-core/dist/helpers/gift-wraps.js -var internalGiftWrapEvents = new EventSet(); -var SealSymbol = Symbol.for("seal"); -var RumorSymbol = Symbol.for("rumor"); -var GiftWrapSymbol = Symbol.for("gift-wrap"); -function addParentSealReference(rumor, seal) { - const parents = Reflect.get(rumor, SealSymbol); - if (!parents) - Reflect.set(rumor, SealSymbol, /* @__PURE__ */ new Set([seal])); - else - parents.add(seal); -} -function removeParentSealReference(rumor, seal) { - const parents = Reflect.get(rumor, SealSymbol); - if (parents) - parents.delete(seal); -} -function isRumor(event) { - var _a; - if (event === void 0 || event === null) - return false; - return ((_a = event.id) == null ? void 0 : _a.length) === 64 && !("sig" in event) && typeof event.pubkey === "string" && event.pubkey.length === 64 && typeof event.content === "string" && Array.isArray(event.tags) && typeof event.created_at === "number" && event.created_at > 0; -} -function getSealGiftWrap(seal) { - return Reflect.get(seal, GiftWrapSymbol); -} -function getRumorSeals(rumor) { - let set = Reflect.get(rumor, SealSymbol); - if (!set) { - set = /* @__PURE__ */ new Set(); - Reflect.set(rumor, SealSymbol, set); - } - return Array.from(set); -} -function getRumorGiftWraps(rumor) { - const giftWraps = /* @__PURE__ */ new Set(); - const seals = getRumorSeals(rumor); - for (const seal of seals) { - const upstream = getSealGiftWrap(seal); - if (upstream) - giftWraps.add(upstream); - } - return Array.from(giftWraps); -} -function isSealLocked(seal) { - return isEncryptedContentLocked(seal); -} -function getSealRumor(seal) { - const cached = Reflect.get(seal, RumorSymbol); - if (cached) - return cached; - const plaintext = getEncryptedContent(seal); - if (!plaintext) - return void 0; - let rumor = JSON.parse(plaintext); - const existing = internalGiftWrapEvents.getEvent(rumor.id); - if (existing) - rumor = existing; - else - internalGiftWrapEvents.add(rumor); - addParentSealReference(rumor, seal); - Reflect.set(seal, RumorSymbol, rumor); - return rumor; -} -function getGiftWrapSeal(gift) { - const cached = Reflect.get(gift, SealSymbol); - if (cached) - return cached; - const plaintext = getEncryptedContent(gift); - if (!plaintext) - return void 0; - let seal = JSON.parse(plaintext); - const existing = internalGiftWrapEvents.getEvent(seal.id); - if (existing) { - seal = existing; - } else { - verifyEvent(seal); - internalGiftWrapEvents.add(seal); - Reflect.set(seal, GiftWrapSymbol, gift); - } - Reflect.set(gift, SealSymbol, seal); - return seal; -} -function getGiftWrapRumor(gift) { - const seal = getGiftWrapSeal(gift); - if (!seal) - return void 0; - return getSealRumor(seal); -} -function isGiftWrapLocked(gift) { - if (isEncryptedContentLocked(gift)) - return true; - else { - const seal = getGiftWrapSeal(gift); - if (!seal || isSealLocked(seal)) - return true; - else - return false; - } -} -async function unlockSeal(seal, signer) { - if (isEncryptedContentLocked(seal)) - await unlockEncryptedContent(seal, seal.pubkey, signer); - const rumor = getSealRumor(seal); - if (!rumor) - throw new Error("Failed to read rumor in gift wrap"); - if (rumor.pubkey !== seal.pubkey) - throw new Error("Seal author does not match rumor author"); - return rumor; -} -async function unlockGiftWrap(gift, signer) { - if (isEncryptedContentLocked(gift)) - await unlockEncryptedContent(gift, gift.pubkey, signer); - const seal = getGiftWrapSeal(gift); - if (!seal) - throw new Error("Failed to read seal in gift wrap"); - const rumor = await unlockSeal(seal, signer); - notifyEventUpdate(gift); - return rumor; -} -function lockGiftWrap(gift) { - const seal = getGiftWrapSeal(gift); - if (seal) { - const rumor = getSealRumor(seal); - if (rumor) - removeParentSealReference(rumor, seal); - Reflect.deleteProperty(seal, GiftWrapSymbol); - Reflect.deleteProperty(seal, RumorSymbol); - lockEncryptedContent(seal); - } - Reflect.deleteProperty(gift, SealSymbol); - lockEncryptedContent(gift); -} - -// node_modules/applesauce-core/dist/helpers/encrypted-content-cache.js -var EncryptedContentFromCacheSymbol = Symbol.for("encrypted-content-from-cache"); -function markEncryptedContentFromCache(event) { - Reflect.set(event, EncryptedContentFromCacheSymbol, true); -} -function isEncryptedContentFromCache(event) { - return Reflect.has(event, EncryptedContentFromCacheSymbol); -} -var log = logger.extend("EncryptedContentCache"); -function persistEncryptedContent(eventStore, storage, fallback) { - const storage$ = isObservable(storage) ? storage : of(storage); - const getItem = async (storage2, event) => { - return await storage2.getItem(event.id) || (fallback ? await fallback(event) : null); - }; - const restore = eventStore.insert$.pipe( - // Look for events that support encrypted content and are locked - filter((e) => canHaveEncryptedContent(e.kind) && isEncryptedContentLocked(e)), - // Get the encrypted content from storage - mergeMap((event) => ( - // Wait for storage to be available - storage$.pipe(switchMap((storage2) => combineLatest([of(event), getItem(storage2, event)])), catchError((error) => { - log(`Failed to restore encrypted content for ${event.id}`, error); - return EMPTY; - })) - )) - ).subscribe(async ([event, content]) => { - if (!content) - return; - markEncryptedContentFromCache(event); - setEncryptedContentCache(event, content); - log(`Restored encrypted content for ${event.id}`); - }); - const restoreSeals = eventStore.update$.pipe( - // Look for gift wraps that are unlocked - filter((e) => e.kind === kinds_exports.GiftWrap && !isEncryptedContentLocked(e)), - // Get the seal event - map((gift) => getGiftWrapSeal(gift)), - // Look for gift wraps with locked seals - filter((seal) => seal !== void 0 && isEncryptedContentLocked(seal)), - // Only attempt to unlock seals once - distinct((seal) => seal.id), - // Get encrypted content from storage - mergeMap((seal) => ( - // Wait for storage to be available - storage$.pipe(switchMap((storage2) => combineLatest([of(seal), getItem(storage2, seal)])), catchError((error) => { - log(`Failed to restore encrypted content for ${seal.id}`, error); - return EMPTY; - })) - )) - ).subscribe(async ([seal, content]) => { - if (!seal || !content) - return; - markEncryptedContentFromCache(seal); - setEncryptedContentCache(seal, content); - getSealRumor(seal); - const gift = getSealGiftWrap(seal); - if (gift) - notifyEventUpdate(gift); - log(`Restored encrypted content for ${seal.id}`); - }); - const persist = combineLatest([merge(eventStore.update$, eventStore.insert$), storage$]).pipe( - // Look for events that support encrypted content and are unlocked and not from the cache - filter(([event]) => canHaveEncryptedContent(event.kind) && !isEncryptedContentLocked(event) && !isEncryptedContentFromCache(event)), - // Only persist the encrypted content once - distinct(([event]) => event.id) - ).subscribe(async ([event, storage2]) => { - try { - const content = getEncryptedContent(event); - if (content) { - await storage2.setItem(event.id, content); - log(`Persisted encrypted content for ${event.id}`); - } - } catch (error) { - log(`Failed to persist encrypted content for ${event.id}`, error); - } - }); - const persistSeals = combineLatest([merge(eventStore.update$, eventStore.insert$), storage$]).pipe( - // Look for gift wraps that are unlocked - filter(([event]) => event.kind === kinds_exports.GiftWrap && !isEncryptedContentLocked(event)), - // Get the seal event - map(([gift, storage2]) => [getGiftWrapSeal(gift), storage2]), - // Make sure the seal is defined - filter(([seal]) => seal !== void 0), - // Make sure seal is unlocked and not from cache - filter(([seal]) => !isEncryptedContentLocked(seal) && !isEncryptedContentFromCache(seal)), - // Only persist the seal once - distinct(([seal]) => seal.id) - ).subscribe(async ([seal, storage2]) => { - if (!seal) - return; - try { - const content = getEncryptedContent(seal); - if (content) { - await storage2.setItem(seal.id, content); - log(`Persisted encrypted content for ${seal.id}`); - } - } catch (error) { - log(`Failed to persist encrypted content for ${seal.id}`, error); - } - }); - return () => { - restore.unsubscribe(); - persist.unsubscribe(); - restoreSeals.unsubscribe(); - persistSeals.unsubscribe(); - }; -} - -// node_modules/applesauce-core/dist/helpers/encryption.js -function isNIP04Encrypted(ciphertext) { - const l = ciphertext.length; - if (l < 28) - return false; - return ciphertext[l - 28] == "?" && ciphertext[l - 27] == "i" && ciphertext[l - 26] == "v" && ciphertext[l - 25] == "="; -} - -// node_modules/applesauce-core/dist/helpers/event-cache.js -var log2 = logger.extend("event-cache"); -function presistEventsToCache(eventStore, write, opts) { - const time = (opts == null ? void 0 : opts.batchTime) ?? 5e3; - const sub = eventStore.insert$.pipe( - // Only select events that are not from the cache - filter((e) => !isFromCache(e)), - // Buffer events for 5 seconds - (opts == null ? void 0 : opts.maxBatchSize) ? bufferTime(time, void 0, (opts == null ? void 0 : opts.maxBatchSize) ?? 100) : bufferTime(time), - // Only select buffers with events - filter((b) => b.length > 0) - ).subscribe((events) => { - write(events).then(() => log2(`Saved ${events.length} events to cache`)).catch((e) => log2(`Failed to save ${events.length} events to cache`, e)); - }); - return () => sub.unsubscribe(); -} - -// node_modules/applesauce-core/dist/helpers/file-metadata.js -function parseFileMetadataTags(tags) { - const fields = {}; - let fallback = void 0; - for (const [name, value] of tags) { - switch (name) { - case "fallback": - fallback = fallback ? [...fallback, value] : [value]; - break; - default: - fields[name] = value; - break; - } - } - if (!fields.url) - throw new Error("Missing required url in file metadata"); - const metadata = { url: fields.url, fallback }; - if (fields.size) - metadata.size = parseInt(fields.size); - if (fields.m) - metadata.type = fields.m; - if (fields.x) - metadata.sha256 = fields.x; - if (fields.ox) - metadata.originalSha256 = fields.ox; - if (fields.dim) - metadata.dimensions = fields.dim; - if (fields.magnet) - metadata.magnet = fields.magnet; - if (fields.i) - metadata.infohash = fields.i; - if (fields.thumb) - metadata.thumbnail = fields.thumb; - if (fields.image) - metadata.image = fields.image; - if (fields.summary) - metadata.summary = fields.summary; - if (fields.alt) - metadata.alt = fields.alt; - if (fields.blurhash) - metadata.blurhash = fields.blurhash; - return metadata; -} -function getFileMetadataFromImetaTag(tag) { - const parts = tag.slice(1); - const tags = []; - for (const part of parts) { - const match = part.match(/^(.+?)\s(.+)$/); - if (match) { - const [_, name, value] = match; - tags.push([name, value]); - } - } - return parseFileMetadataTags(tags); -} -var MediaAttachmentsSymbol = Symbol.for("media-attachments"); -function getMediaAttachments(event) { - return getOrComputeCachedValue(event, MediaAttachmentsSymbol, () => { - return event.tags.filter((t) => t[0] === "imeta").map((tag) => { - try { - return getFileMetadataFromImetaTag(tag); - } catch (error) { - return void 0; - } - }).filter((a) => !!a); - }); -} -function getFileMetadata(file) { - return parseFileMetadataTags(file.tags); -} -function getSha256FromURL(url) { - if (typeof url === "string") - url = new URL(url); - const hashes = Array.from(url.pathname.matchAll(/[0-9a-f]{64}/gi)); - if (hashes.length > 0) - return hashes[hashes.length - 1][0]; - return; -} - -// node_modules/applesauce-core/dist/helpers/hashtag.js -function getHashtagTag(event, hashtag) { - hashtag = stripInvisibleChar(hashtag.replace(/^#/, "").toLocaleLowerCase()); - return event.tags.filter((t) => t[0] === "t" && t[1]).find((t) => stripInvisibleChar(t[1].toLowerCase()) === hashtag); -} - -// node_modules/applesauce-core/dist/helpers/highlight.js -var HighlightSourceEventPointerSymbol = Symbol.for("highlight-source-event-pointer"); -var HighlightSourceAddressPointerSymbol = Symbol.for("highlight-source-address-pointer"); -var HighlightAttributionSymbol = Symbol.for("highlight-attribution"); -function getHighlightText(event) { - return event.content; -} -function getHighlightSourceEventPointer(event) { - return getOrComputeCachedValue(event, HighlightSourceEventPointerSymbol, () => { - const eTag = event.tags.find(isETag); - return eTag ? getEventPointerFromETag(eTag) : void 0; - }); -} -function getHighlightSourceAddressPointer(event) { - return getOrComputeCachedValue(event, HighlightSourceAddressPointerSymbol, () => { - const aTag = event.tags.find(isATag); - return aTag ? getAddressPointerFromATag(aTag) : void 0; - }); -} -function getHighlightSourceUrl(event) { - return getTagValue(event, "r"); -} -function getHighlightAttributions(event) { - return getOrComputeCachedValue(event, HighlightAttributionSymbol, () => { - const attributions = []; - const pTags = event.tags.filter(isPTag); - for (const pTag of pTags) { - const pointer = getProfilePointerFromPTag(pTag); - const role = pTag[3] || "other"; - const entry = { ...pointer, role }; - attributions.push(entry); - } - return attributions; - }); -} -function getHighlightContext(event) { - return getTagValue(event, "context"); -} -function getHighlightComment(event) { - return getTagValue(event, "comment"); -} -function hasHighlightSource(event) { - return !!(getHighlightSourceEventPointer(event) || getHighlightSourceAddressPointer(event) || getHighlightSourceUrl(event)); -} - -// node_modules/applesauce-core/dist/helpers/json.js -function safeParse(str) { - try { - return JSON.parse(str); - } catch (error) { - return void 0; - } -} - -// node_modules/applesauce-core/dist/helpers/legacy-messages.js -function isLegacyMessageLocked(event) { - return isEncryptedContentLocked(event); -} -function getLegacyMessageCorraspondant(message, self) { - const corraspondant = message.pubkey === self ? getTagValue(message, "p") : message.pubkey; - if (!corraspondant) - throw new Error("No corraspondant found"); - return corraspondant; -} -var getLegacyMessageReceiver = getLegacyMessageCorraspondant; -function getLegacyMessageSender(message) { - return message.pubkey; -} -function getLegacyMessageParent(message) { - return getTagValue(message, "e"); -} -async function unlockLegacyMessage(message, self, signer) { - const cached = getEncryptedContent(message); - if (cached) - return cached; - const corraspondant = getLegacyMessageCorraspondant(message, self); - return await unlockEncryptedContent(message, corraspondant, signer); -} -async function lockLegacyMessage(message) { - lockEncryptedContent(message); -} - -// node_modules/applesauce-core/dist/helpers/lists.js -var FAVORITE_RELAYS_KIND = 10012; -function getListTags(list, type) { - switch (type) { - case "public": - return list.tags; - case "hidden": - return getHiddenTags(list) ?? []; - default: - case "all": - return [...getHiddenTags(list) ?? [], ...list.tags]; - } -} -function isEventPointerInList(list, pointer, type) { - const id = typeof pointer === "string" ? pointer : pointer.id; - const tags = getListTags(list, type); - return tags.some((t) => t[0] === "e" && t[1] === id); -} -function isAddressPointerInList(list, pointer, type) { - const cord = typeof pointer === "string" ? pointer : getCoordinateFromAddressPointer(pointer); - const tags = getListTags(list, type); - return tags.some((t) => t[0] === "a" && t[1] === cord); -} -function isProfilePointerInList(list, pointer, type) { - const pubkey = typeof pointer === "string" ? pointer : pointer.pubkey; - const tags = getListTags(list, type); - return tags.some((t) => t[0] === "p" && t[1] === pubkey); -} -function isEventInList(list, event) { - return isReplaceable(event.kind) ? isAddressPointerInList(list, getAddressPointerForEvent(event)) : isEventPointerInList(list, event); -} -function getEventPointersFromList(list, type) { - return processTags(getListTags(list, type), (tag) => isETag(tag) ? tag : void 0, getEventPointerFromETag); -} -function getAddressPointersFromList(list, type) { - return processTags(getListTags(list, type), (t) => isATag(t) ? t : void 0, getAddressPointerFromATag); -} -function getProfilePointersFromList(list, type) { - return processTags(getListTags(list, type), (t) => isPTag(t) ? t : void 0, getProfilePointerFromPTag); -} -function getRelaysFromList(list, type) { - return mergeRelaySets(processTags(getListTags(list, type), (t) => t[0] === "relay" ? t[1] : void 0)); -} -function isValidList(event) { - try { - if (isAddressableKind2(event.kind)) { - getReplaceableIdentifier(event); - return true; - } else if (isReplaceableKind2(event.kind) && event.kind >= 1e4 && event.kind < 2e4) { - return true; - } - } catch (error) { - } - return false; -} - -// node_modules/@scure/base/lib/esm/index.js -function isBytes4(a) { - return a instanceof Uint8Array || ArrayBuffer.isView(a) && a.constructor.name === "Uint8Array"; -} -function abytes2(b, ...lengths) { - if (!isBytes4(b)) - throw new Error("Uint8Array expected"); - if (lengths.length > 0 && !lengths.includes(b.length)) - throw new Error("Uint8Array expected of length " + lengths + ", got length=" + b.length); -} -function isArrayOf(isString, arr) { - if (!Array.isArray(arr)) - return false; - if (arr.length === 0) - return true; - if (isString) { - return arr.every((item) => typeof item === "string"); - } else { - return arr.every((item) => Number.isSafeInteger(item)); - } -} -function afn(input) { - if (typeof input !== "function") - throw new Error("function expected"); - return true; -} -function astr(label, input) { - if (typeof input !== "string") - throw new Error(`${label}: string expected`); - return true; -} -function anumber(n) { - if (!Number.isSafeInteger(n)) - throw new Error(`invalid integer: ${n}`); -} -function aArr(input) { - if (!Array.isArray(input)) - throw new Error("array expected"); -} -function astrArr(label, input) { - if (!isArrayOf(true, input)) - throw new Error(`${label}: array of strings expected`); -} -function anumArr(label, input) { - if (!isArrayOf(false, input)) - throw new Error(`${label}: array of numbers expected`); -} -function chain2(...args) { - const id = (a) => a; - const wrap = (a, b) => (c) => a(b(c)); - const encode = args.map((x) => x.encode).reduceRight(wrap, id); - const decode4 = args.map((x) => x.decode).reduce(wrap, id); - return { encode, decode: decode4 }; -} -function alphabet2(letters) { - const lettersA = typeof letters === "string" ? letters.split("") : letters; - const len = lettersA.length; - astrArr("alphabet", lettersA); - const indexes = new Map(lettersA.map((l, i2) => [l, i2])); - return { - encode: (digits) => { - aArr(digits); - return digits.map((i2) => { - if (!Number.isSafeInteger(i2) || i2 < 0 || i2 >= len) - throw new Error(`alphabet.encode: digit index outside alphabet "${i2}". Allowed: ${letters}`); - return lettersA[i2]; - }); - }, - decode: (input) => { - aArr(input); - return input.map((letter) => { - astr("alphabet.decode", letter); - const i2 = indexes.get(letter); - if (i2 === void 0) - throw new Error(`Unknown letter: "${letter}". Allowed: ${letters}`); - return i2; - }); - } - }; -} -function join2(separator = "") { - astr("join", separator); - return { - encode: (from2) => { - astrArr("join.decode", from2); - return from2.join(separator); - }, - decode: (to) => { - astr("join.decode", to); - return to.split(separator); - } - }; -} -function padding2(bits, chr = "=") { - anumber(bits); - astr("padding", chr); - return { - encode(data) { - astrArr("padding.encode", data); - while (data.length * bits % 8) - data.push(chr); - return data; - }, - decode(input) { - astrArr("padding.decode", input); - let end = input.length; - if (end * bits % 8) - throw new Error("padding: invalid, string should have whole number of bytes"); - for (; end > 0 && input[end - 1] === chr; end--) { - const last3 = end - 1; - const byte = last3 * bits; - if (byte % 8 === 0) - throw new Error("padding: invalid, string has too much padding"); - } - return input.slice(0, end); - } - }; -} -function normalize2(fn) { - afn(fn); - return { encode: (from2) => from2, decode: (to) => fn(to) }; -} -function convertRadix3(data, from2, to) { - if (from2 < 2) - throw new Error(`convertRadix: invalid from=${from2}, base cannot be less than 2`); - if (to < 2) - throw new Error(`convertRadix: invalid to=${to}, base cannot be less than 2`); - aArr(data); - if (!data.length) - return []; - let pos = 0; - const res = []; - const digits = Array.from(data, (d) => { - anumber(d); - if (d < 0 || d >= from2) - throw new Error(`invalid integer: ${d}`); - return d; - }); - const dlen = digits.length; - while (true) { - let carry = 0; - let done = true; - for (let i2 = pos; i2 < dlen; i2++) { - const digit = digits[i2]; - const fromCarry = from2 * carry; - const digitBase = fromCarry + digit; - if (!Number.isSafeInteger(digitBase) || fromCarry / from2 !== carry || digitBase - digit !== fromCarry) { - throw new Error("convertRadix: carry overflow"); - } - const div = digitBase / to; - carry = digitBase % to; - const rounded = Math.floor(div); - digits[i2] = rounded; - if (!Number.isSafeInteger(rounded) || rounded * to + carry !== digitBase) - throw new Error("convertRadix: carry overflow"); - if (!done) - continue; - else if (!rounded) - pos = i2; - else - done = false; - } - res.push(carry); - if (done) - break; - } - for (let i2 = 0; i2 < data.length - 1 && data[i2] === 0; i2++) - res.push(0); - return res.reverse(); -} -var gcd2 = (a, b) => b === 0 ? a : gcd2(b, a % b); -var radix2carry2 = (from2, to) => from2 + (to - gcd2(from2, to)); -var powers = (() => { - let res = []; - for (let i2 = 0; i2 < 40; i2++) - res.push(2 ** i2); - return res; -})(); -function convertRadix22(data, from2, to, padding3) { - aArr(data); - if (from2 <= 0 || from2 > 32) - throw new Error(`convertRadix2: wrong from=${from2}`); - if (to <= 0 || to > 32) - throw new Error(`convertRadix2: wrong to=${to}`); - if (radix2carry2(from2, to) > 32) { - throw new Error(`convertRadix2: carry overflow from=${from2} to=${to} carryBits=${radix2carry2(from2, to)}`); - } - let carry = 0; - let pos = 0; - const max2 = powers[from2]; - const mask = powers[to] - 1; - const res = []; - for (const n of data) { - anumber(n); - if (n >= max2) - throw new Error(`convertRadix2: invalid data word=${n} from=${from2}`); - carry = carry << from2 | n; - if (pos + from2 > 32) - throw new Error(`convertRadix2: carry overflow pos=${pos} from=${from2}`); - pos += from2; - for (; pos >= to; pos -= to) - res.push((carry >> pos - to & mask) >>> 0); - const pow3 = powers[pos]; - if (pow3 === void 0) - throw new Error("invalid carry"); - carry &= pow3 - 1; - } - carry = carry << to - pos & mask; - if (!padding3 && pos >= from2) - throw new Error("Excess padding"); - if (!padding3 && carry > 0) - throw new Error(`Non-zero padding: ${carry}`); - if (padding3 && pos > 0) - res.push(carry >>> 0); - return res; -} -function radix3(num) { - anumber(num); - const _256 = 2 ** 8; - return { - encode: (bytes4) => { - if (!isBytes4(bytes4)) - throw new Error("radix.encode input should be Uint8Array"); - return convertRadix3(Array.from(bytes4), _256, num); - }, - decode: (digits) => { - anumArr("radix.decode", digits); - return Uint8Array.from(convertRadix3(digits, num, _256)); - } - }; -} -function radix22(bits, revPadding = false) { - anumber(bits); - if (bits <= 0 || bits > 32) - throw new Error("radix2: bits should be in (0..32]"); - if (radix2carry2(8, bits) > 32 || radix2carry2(bits, 8) > 32) - throw new Error("radix2: carry overflow"); - return { - encode: (bytes4) => { - if (!isBytes4(bytes4)) - throw new Error("radix2.encode input should be Uint8Array"); - return convertRadix22(Array.from(bytes4), 8, bits, !revPadding); - }, - decode: (digits) => { - anumArr("radix2.decode", digits); - return Uint8Array.from(convertRadix22(digits, bits, 8, revPadding)); - } - }; -} -function unsafeWrapper2(fn) { - afn(fn); - return function(...args) { - try { - return fn.apply(null, args); - } catch (e) { - } - }; -} -var base162 = chain2(radix22(4), alphabet2("0123456789ABCDEF"), join2("")); -var base322 = chain2(radix22(5), alphabet2("ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"), padding2(5), join2("")); -var base32nopad = chain2(radix22(5), alphabet2("ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"), join2("")); -var base32hex2 = chain2(radix22(5), alphabet2("0123456789ABCDEFGHIJKLMNOPQRSTUV"), padding2(5), join2("")); -var base32hexnopad = chain2(radix22(5), alphabet2("0123456789ABCDEFGHIJKLMNOPQRSTUV"), join2("")); -var base32crockford2 = chain2(radix22(5), alphabet2("0123456789ABCDEFGHJKMNPQRSTVWXYZ"), join2(""), normalize2((s) => s.toUpperCase().replace(/O/g, "0").replace(/[IL]/g, "1"))); -var hasBase64Builtin = (() => typeof Uint8Array.from([]).toBase64 === "function" && typeof Uint8Array.fromBase64 === "function")(); -var decodeBase64Builtin = (s, isUrl) => { - astr("base64", s); - const re = isUrl ? /^[A-Za-z0-9=_-]+$/ : /^[A-Za-z0-9=+/]+$/; - const alphabet3 = isUrl ? "base64url" : "base64"; - if (s.length > 0 && !re.test(s)) - throw new Error("invalid base64"); - return Uint8Array.fromBase64(s, { alphabet: alphabet3, lastChunkHandling: "strict" }); -}; -var base642 = hasBase64Builtin ? { - encode(b) { - abytes2(b); - return b.toBase64(); - }, - decode(s) { - return decodeBase64Builtin(s, false); - } -} : chain2(radix22(6), alphabet2("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"), padding2(6), join2("")); -var base64nopad = chain2(radix22(6), alphabet2("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"), join2("")); -var base64url2 = hasBase64Builtin ? { - encode(b) { - abytes2(b); - return b.toBase64({ alphabet: "base64url" }); - }, - decode(s) { - return decodeBase64Builtin(s, true); - } -} : chain2(radix22(6), alphabet2("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"), padding2(6), join2("")); -var base64urlnopad = chain2(radix22(6), alphabet2("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"), join2("")); -var genBase582 = (abc) => chain2(radix3(58), alphabet2(abc), join2("")); -var base582 = genBase582("123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"); -var base58flickr2 = genBase582("123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"); -var base58xrp2 = genBase582("rpshnaf39wBUDNEGHJKLM4PQRST7VWXYZ2bcdeCg65jkm8oFqi1tuvAxyz"); -var BECH_ALPHABET2 = chain2(alphabet2("qpzry9x8gf2tvdw0s3jn54khce6mua7l"), join2("")); -var POLYMOD_GENERATORS2 = [996825010, 642813549, 513874426, 1027748829, 705979059]; -function bech32Polymod2(pre) { - const b = pre >> 25; - let chk = (pre & 33554431) << 5; - for (let i2 = 0; i2 < POLYMOD_GENERATORS2.length; i2++) { - if ((b >> i2 & 1) === 1) - chk ^= POLYMOD_GENERATORS2[i2]; - } - return chk; -} -function bechChecksum2(prefix, words, encodingConst = 1) { - const len = prefix.length; - let chk = 1; - for (let i2 = 0; i2 < len; i2++) { - const c = prefix.charCodeAt(i2); - if (c < 33 || c > 126) - throw new Error(`Invalid prefix (${prefix})`); - chk = bech32Polymod2(chk) ^ c >> 5; - } - chk = bech32Polymod2(chk); - for (let i2 = 0; i2 < len; i2++) - chk = bech32Polymod2(chk) ^ prefix.charCodeAt(i2) & 31; - for (let v of words) - chk = bech32Polymod2(chk) ^ v; - for (let i2 = 0; i2 < 6; i2++) - chk = bech32Polymod2(chk); - chk ^= encodingConst; - return BECH_ALPHABET2.encode(convertRadix22([chk % powers[30]], 30, 5, false)); -} -function genBech322(encoding) { - const ENCODING_CONST = encoding === "bech32" ? 1 : 734539939; - const _words = radix22(5); - const fromWords = _words.decode; - const toWords = _words.encode; - const fromWordsUnsafe = unsafeWrapper2(fromWords); - function encode(prefix, words, limit2 = 90) { - astr("bech32.encode prefix", prefix); - if (isBytes4(words)) - words = Array.from(words); - anumArr("bech32.encode", words); - const plen = prefix.length; - if (plen === 0) - throw new TypeError(`Invalid prefix length ${plen}`); - const actualLength = plen + 7 + words.length; - if (limit2 !== false && actualLength > limit2) - throw new TypeError(`Length ${actualLength} exceeds limit ${limit2}`); - const lowered = prefix.toLowerCase(); - const sum = bechChecksum2(lowered, words, ENCODING_CONST); - return `${lowered}1${BECH_ALPHABET2.encode(words)}${sum}`; - } - function decode4(str, limit2 = 90) { - astr("bech32.decode input", str); - const slen = str.length; - if (slen < 8 || limit2 !== false && slen > limit2) - throw new TypeError(`invalid string length: ${slen} (${str}). Expected (8..${limit2})`); - const lowered = str.toLowerCase(); - if (str !== lowered && str !== str.toUpperCase()) - throw new Error(`String must be lowercase or uppercase`); - const sepIndex = lowered.lastIndexOf("1"); - if (sepIndex === 0 || sepIndex === -1) - throw new Error(`Letter "1" must be present between prefix and data only`); - const prefix = lowered.slice(0, sepIndex); - const data = lowered.slice(sepIndex + 1); - if (data.length < 6) - throw new Error("Data must be at least 6 characters long"); - const words = BECH_ALPHABET2.decode(data).slice(0, -6); - const sum = bechChecksum2(prefix, words, ENCODING_CONST); - if (!data.endsWith(sum)) - throw new Error(`Invalid checksum in ${str}: expected "${sum}"`); - return { prefix, words }; - } - const decodeUnsafe = unsafeWrapper2(decode4); - function decodeToBytes(str) { - const { prefix, words } = decode4(str, false); - return { prefix, words, bytes: fromWords(words) }; - } - function encodeFromBytes(prefix, bytes4) { - return encode(prefix, toWords(bytes4)); - } - return { - encode, - decode: decode4, - encodeFromBytes, - decodeToBytes, - decodeUnsafe, - fromWords, - fromWordsUnsafe, - toWords - }; -} -var bech322 = genBech322("bech32"); -var bech32m2 = genBech322("bech32m"); -var hasHexBuiltin2 = (() => typeof Uint8Array.from([]).toHex === "function" && typeof Uint8Array.fromHex === "function")(); -var hexBuiltin = { - encode(data) { - abytes2(data); - return data.toHex(); - }, - decode(s) { - astr("hex", s); - return Uint8Array.fromHex(s); - } -}; -var hex2 = hasHexBuiltin2 ? hexBuiltin : chain2(radix22(4), alphabet2("0123456789abcdef"), join2(""), normalize2((s) => { - if (typeof s !== "string" || s.length % 2 !== 0) - throw new TypeError(`hex.decode: expected string, got ${typeof s} with length ${s.length}`); - return s.toLowerCase(); -})); - -// node_modules/applesauce-core/dist/helpers/lnurl.js -var decoder = new TextDecoder(); -function parseLightningAddress(address) { - let [name, domain] = address.split("@"); - if (!name || !domain) - return; - return new URL(`https://${domain}/.well-known/lnurlp/${name}`); -} -function decodeLNURL(lnurl) { - try { - const { words, prefix } = bech322.decode(lnurl); - if (prefix !== "lnurl") - return; - const str = decoder.decode(bech322.fromWords(words)); - return new URL(str); - } catch (error) { - } - return void 0; -} -function parseLNURLOrAddress(addressOrLNURL) { - if (addressOrLNURL.includes("@")) { - return parseLightningAddress(addressOrLNURL); - } - return decodeLNURL(addressOrLNURL); -} -async function getInvoice(callback) { - const { pr: payRequest } = await fetch(callback).then((res) => res.json()); - const amount = callback.searchParams.get("amount"); - if (!amount) - throw new Error("Missing amount"); - if (payRequest) { - const parsed = parseBolt11(payRequest); - if (parsed.amount !== parseInt(amount)) - throw new Error("Incorrect amount"); - return payRequest; - } else - throw new Error("Failed to get invoice"); -} - -// node_modules/applesauce-core/dist/helpers/mailboxes.js -var MailboxesInboxesSymbol = Symbol.for("mailboxes-inboxes"); -var MailboxesOutboxesSymbol = Symbol.for("mailboxes-outboxes"); -function getInboxes(event) { - return getOrComputeCachedValue(event, MailboxesInboxesSymbol, () => { - const inboxes = []; - for (const tag of event.tags) { - const [name, url, mode] = tag; - if (name === "r" && url && isSafeRelayURL(url) && !inboxes.includes(url) && (mode === "read" || mode === void 0)) { - inboxes.push(normalizeURL2(url)); - } - } - return inboxes; - }); -} -function getOutboxes(event) { - return getOrComputeCachedValue(event, MailboxesOutboxesSymbol, () => { - const outboxes = []; - for (const tag of event.tags) { - const [name, url, mode] = tag; - if (name === "r" && url && isSafeRelayURL(url) && !outboxes.includes(url) && (mode === "write" || mode === void 0)) { - outboxes.push(normalizeURL2(url)); - } - } - return outboxes; - }); -} - -// node_modules/applesauce-core/dist/helpers/messages.js -function groupMessageEvents(messages, buffer2 = 5 * 60) { - const groups = []; - for (const message of messages) { - const group = groups[groups.length - 1]; - const last3 = group == null ? void 0 : group[0]; - if (group && (last3 == null ? void 0 : last3.pubkey) === message.pubkey && Math.abs(message.created_at - last3.created_at) < buffer2) - group.push(message); - else - groups.push([message]); - } - return groups; -} -function getConversationParticipants(participants) { - let participantList; - if (typeof participants === "string") { - participantList = participants.split(":"); - } else if (Array.isArray(participants)) { - participantList = participants; - } else { - if (participants.kind !== kinds_exports.EncryptedDirectMessage && participants.kind !== kinds_exports.PrivateDirectMessage) - throw new Error("Can only get participants from direct message event (4, 14)"); - participantList = [participants.pubkey, ...participants.tags.filter(isPTag).map((t) => t[1])]; - } - return Array.from(new Set(participantList)); -} -function createConversationIdentifier(...participants) { - return Array.from(new Set(participants.flat())).sort().join(":"); -} -function getConversationIdentifierFromMessage(message) { - return createConversationIdentifier(getConversationParticipants(message)); -} - -// node_modules/applesauce-core/dist/helpers/mutes.js -var MutePublicSymbol = Symbol.for("mute-public"); -var MuteHiddenSymbol = Symbol.for("mute-hidden"); -function mergeMutes(...mutes) { - const mute = { pubkeys: /* @__PURE__ */ new Set(), threads: /* @__PURE__ */ new Set(), hashtags: /* @__PURE__ */ new Set(), words: /* @__PURE__ */ new Set() }; - for (const m of mutes) { - for (const pubkey of m.pubkeys) - mute.pubkeys.add(pubkey); - for (const thread of m.threads) - mute.threads.add(thread); - for (const hashtag of m.hashtags) - mute.hashtags.add(hashtag); - for (const word of m.words) - mute.words.add(word); - } - return mute; -} -function parseMutedTags(tags) { - const pubkeys = new Set(tags.filter(isPTag).map((t) => t[1])); - const threads = new Set(tags.filter(isETag).map((t) => t[1])); - const hashtags = new Set(tags.filter(isTTag).map((t) => t[1].toLocaleLowerCase())); - const words = new Set(tags.filter((t) => t[0] === "word" && t[1]).map((t) => t[1].toLocaleLowerCase())); - return { pubkeys, threads, hashtags, words }; -} -function getMutedThings(mute) { - const hidden = getHiddenMutedThings(mute); - const mutes = getPublicMutedThings(mute); - if (hidden) - return mergeMutes(hidden, mutes); - return mutes; -} -function getPublicMutedThings(mute) { - return getOrComputeCachedValue(mute, MutePublicSymbol, () => parseMutedTags(mute.tags)); -} -function getHiddenMutedThings(mute) { - if (isHiddenTagsLocked(mute)) - return void 0; - return getOrComputeCachedValue(mute, MuteHiddenSymbol, () => parseMutedTags(getHiddenTags(mute))); -} -function createMutedWordsRegExp(mutedWords) { - const escapedWords = mutedWords.map((word) => word.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")); - return new RegExp(`\\b(${escapedWords.join("|")})\\b`, "gi"); -} -function matchMutes(mutes, event) { - var _a; - if (mutes.pubkeys.size > 0) { - if (mutes.pubkeys.has(event.pubkey)) - return true; - } - if (mutes.hashtags.size > 0) { - const tags = getIndexableTags(event); - for (let tag of mutes.hashtags) { - if (tags.has("t:" + tag)) - return true; - } - } - if (mutes.threads.size > 0 && event.kind === kinds_exports.ShortTextNote) { - const refs = getNip10References(event); - if (((_a = refs.root) == null ? void 0 : _a.e) && mutes.threads.has(refs.root.e.id)) - return true; - } - if (mutes.words.size > 0) { - const regExp = createMutedWordsRegExp(Array.from(mutes.words)); - if (regExp.test(event.content)) - return true; - } - return false; -} - -// node_modules/applesauce-core/dist/helpers/picture-post.js -var PICTURE_POST_KIND = 20; -function getPicturePostAttachments(post) { - return getMediaAttachments(post); -} - -// node_modules/applesauce-core/dist/helpers/poll.js -var POLL_KIND = 1068; -var POLL_RESPONSE_KIND = 1018; -var PollOptionsSymbol = Symbol.for("poll-options"); -function getPollQuestion(event) { - return event.content; -} -function getPollOptions(event) { - return getOrComputeCachedValue(event, PollOptionsSymbol, () => { - return event.tags.filter((tag) => tag[0] === "option" && tag.length >= 3).map((tag) => ({ - id: tag[1], - label: tag[2] - })); - }); -} -function getPollRelays(event) { - return event.tags.filter((tag) => tag[0] === "relay" && tag.length >= 2).map((tag) => tag[1]); -} -function getPollType(event) { - const type = getTagValue(event, "polltype"); - return type === "multiplechoice" || type === "singlechoice" ? type : "singlechoice"; -} -function getPollEndsAt(event) { - const endsAt = getTagValue(event, "endsAt"); - return endsAt ? parseInt(endsAt, 10) : void 0; -} -function getPollResponsePollId(event) { - return getTagValue(event, "e"); -} -function getPollResponseOptions(event) { - return event.tags.filter((tag) => tag[0] === "response" && tag.length >= 2).map((tag) => tag[1]); -} -function getPollResponseVotes(poll, response) { - if (poll.id !== getPollResponsePollId(response)) - return; - const pollOptions = getPollOptions(poll); - const responseOptions = getPollResponseOptions(response); - const votes = responseOptions.filter((opts) => pollOptions.some((option) => option.id === opts)); - const type = getPollType(poll); - if (type === "singlechoice") - return votes.length === 1 ? [votes[0]] : void 0; - return Array.from(new Set(votes)); -} - -// node_modules/applesauce-core/dist/helpers/reactions.js -var isInteger = (str) => Number.isInteger(Number(str)); -var ReactionEventPointerSymbol = Symbol("reaction-event-pointer"); -var ReactionAddressPointerSymbol = Symbol("reaction-address-pointer"); -function getReactionEventPointer(event) { - return getOrComputeCachedValue(event, ReactionEventPointerSymbol, () => { - const eTag = event.tags.find(isETag); - if (!eTag) - return void 0; - const pointer = getEventPointerFromETag(eTag); - if (!pointer) - return void 0; - const k = getTagValue(event, "k"); - if (k && isInteger(k)) - pointer.kind = parseInt(k); - if (!pointer.author) { - const p = event.tags.find(isPTag); - if (p) { - const author = getProfilePointerFromPTag(p); - pointer.author = author.pubkey; - if (author.relays) - pointer.relays = mergeRelaySets(author.relays, pointer.relays); - } - } - return pointer; - }); -} -function getReactionAddressPointer(event) { - return getOrComputeCachedValue(event, ReactionAddressPointerSymbol, () => { - const aTag = event.tags.find(isATag); - if (!aTag) - return void 0; - const pointer = getAddressPointerFromATag(aTag); - if (!pointer) - return void 0; - const p = event.tags.find(isPTag); - if (p) { - const author = getProfilePointerFromPTag(p); - if (author.relays) - pointer.relays = mergeRelaySets(author.relays, pointer.relays); - } - return pointer; - }); -} - -// node_modules/applesauce-core/dist/helpers/reports.js -var ParsedReportSymbol = Symbol("parsed-report"); -var ReportReason; -(function(ReportReason2) { - ReportReason2["nudity"] = "nudity"; - ReportReason2["malware"] = "malware"; - ReportReason2["profanity"] = "profanity"; - ReportReason2["illegal"] = "illegal"; - ReportReason2["spam"] = "spam"; - ReportReason2["impersonation"] = "impersonation"; - ReportReason2["other"] = "other"; -})(ReportReason || (ReportReason = {})); -function getReported(report) { - return getOrComputeCachedValue(report, ParsedReportSymbol, () => { - const p = report.tags.find(isPTag); - if (!p) - throw new Error("Report missing p tag"); - const comment = report.content ? report.content.trim() : void 0; - const e = report.tags.find(isETag); - if (e) { - const blobs = report.tags.filter((t) => t[0] === "x" && t[1]).map((t) => t[1]); - return { - type: "event", - event: report, - comment, - id: e[1], - pubkey: p[1], - reason: e[2], - blobs - }; - } - return { type: "user", event: report, comment, pubkey: p[1], reason: p[2] }; - }); -} - -// node_modules/applesauce-core/dist/helpers/share.js -var SharedEventSymbol = Symbol.for("shared-event"); -var SharedEventPointerSymbol = Symbol.for("shared-event-pointer"); -var SharedAddressPointerSymbol = Symbol.for("shared-address-pointer"); -function getSharedEventPointer(event) { - return getOrComputeCachedValue(event, SharedEventPointerSymbol, () => nip18_exports.getRepostedEventPointer(event)); -} -function getSharedAddressPointer(event) { - return getOrComputeCachedValue(event, SharedAddressPointerSymbol, () => { - const a = event.tags.find(isATag); - if (!a) - return void 0; - return getAddressPointerFromATag(a); - }); -} -function getEmbededSharedEvent(event) { - return getOrComputeCachedValue(event, SharedEventSymbol, () => nip18_exports.getRepostedEvent(event)); -} -var parseSharedEvent = getEmbededSharedEvent; - -// node_modules/applesauce-core/dist/helpers/stream-chat.js -function getStreamChatMessageStream(message) { - const tag = message.tags.find(isATag); - if (!tag) - return void 0; - return getAddressPointerFromATag(tag); -} - -// node_modules/applesauce-core/dist/helpers/stream.js -function getStreamTitle(stream) { - return getTagValue(stream, "title"); -} -function getStreamSummary(stream) { - return getTagValue(stream, "summary"); -} -function getStreamImage(stream) { - return getTagValue(stream, "image"); -} -var TWO_WEEKS = 60 * 60 * 24 * 14; -function getStreamStatus(stream) { - if (stream.created_at < unixNow() - TWO_WEEKS) - return "ended"; - else - return getTagValue(stream, "status") || "ended"; -} -function getStreamHost(stream) { - let host = void 0; - for (const tag of stream.tags) { - if (isPTag(tag) && (!host || tag[3] && tag[3].toLowerCase() === "host")) { - host = getProfilePointerFromPTag(tag); - } - } - return host || { pubkey: stream.pubkey }; -} -function getStreamParticipants(stream) { - return stream.tags.filter((t) => isPTag(t) && t[3]).map((t) => ({ ...getProfilePointerFromPTag(t), role: t[3].toLowerCase() })); -} -function getStreamGoalPointer(stream) { - const goalTag = stream.tags.find((t) => t[0] === "goal"); - return goalTag && addRelayHintsToPointer(getEventPointerFromETag(goalTag), getStreamRelays(stream)); -} -function getStreamStreamingURLs(stream) { - return stream.tags.filter((t) => t[0] === "streaming").map((t) => t[1]); -} -function getStreamRecording(stream) { - return getTagValue(stream, "recording"); -} -function getStreamRelays(stream) { - for (const tag of stream.tags) { - if (tag[0] === "relays") - return mergeRelaySets(tag.slice(1)); - } - return void 0; -} -function getStreamStartTime(stream) { - const str = getTagValue(stream, "starts"); - return str ? parseInt(str) : void 0; -} -function getStreamEndTime(stream) { - const str = getTagValue(stream, "ends"); - return str ? parseInt(str) : getStreamStatus(stream) === "ended" ? stream.created_at : void 0; -} -function getStreamViewers(stream) { - const viewers = getTagValue(stream, "current_participants"); - return viewers ? parseInt(viewers) : void 0; -} -function getStreamMaxViewers(stream) { - const viewers = getTagValue(stream, "total_participants"); - return viewers ? parseInt(viewers) : void 0; -} -function getStreamHashtags(stream) { - return stream.tags.filter((t) => t[0] === "t").map((t) => t[1]); -} - -// node_modules/applesauce-core/dist/helpers/threading.js -var Nip10ThreadRefsSymbol = Symbol.for("nip10-thread-refs"); -function getEventPointerFromThreadTag(tag) { - if (!tag[1]) - throw new Error("Missing event id in tag"); - let pointer = { id: tag[1] }; - if (tag[2] && isSafeRelayURL(tag[2])) - pointer.relays = [tag[2]]; - if (tag[0] === "e" && (tag[3] === "root" || tag[3] === "reply" || tag[3] === "mention") && tag[4] && tag[4].length === 64) { - pointer.author = tag[4]; - } - return pointer; -} -function interpretThreadTags(tags) { - const eTags = tags.filter((t) => t[0] === "e" && t[1]); - const aTags = tags.filter((t) => t[0] === "a" && t[1]); - let rootETag = eTags.find((t) => t[3] === "root"); - let replyETag = eTags.find((t) => t[3] === "reply"); - let rootATag = aTags.find((t) => t[3] === "root"); - let replyATag = aTags.find((t) => t[3] === "reply"); - if (!rootETag || !replyETag) { - rootETag = replyETag = rootETag || replyETag; - } - if (!rootATag || !replyATag) { - rootATag = replyATag = rootATag || replyATag; - } - if (!rootETag && !replyETag) { - const legacyETags = eTags.filter((t) => { - if (t[3]) - return false; - return true; - }); - if (legacyETags.length >= 1) { - rootETag = legacyETags[0]; - replyETag = legacyETags[legacyETags.length - 1] ?? rootETag; - } - } - return { - root: rootETag || rootATag ? { e: rootETag, a: rootATag } : void 0, - reply: replyETag || replyATag ? { e: replyETag, a: replyATag } : void 0 - }; -} -function getNip10References(event) { - return getOrComputeCachedValue(event, Nip10ThreadRefsSymbol, () => { - const tags = interpretThreadTags(event.tags); - let root; - if (tags.root) { - try { - root = { - e: tags.root.e && getEventPointerFromThreadTag(tags.root.e), - a: tags.root.a && getAddressPointerFromATag(tags.root.a) - }; - } catch (error) { - } - } - let reply; - if (tags.reply) { - try { - reply = { - e: tags.reply.e && getEventPointerFromThreadTag(tags.reply.e), - a: tags.reply.a && getAddressPointerFromATag(tags.reply.a) - }; - } catch (error) { - } - } - return { - root, - reply - }; - }); -} - -// node_modules/applesauce-core/dist/helpers/user-status.js -var UserStatusPointerSymbol = Symbol.for("user-status-pointer"); -function getStatusPointer(status) { - const pTag = status.tags.find((t) => t[0] === "p" && t[1]); - if (pTag) - return { type: "nprofile", data: getProfilePointerFromPTag(pTag) }; - const eTag = status.tags.find((t) => t[0] === "e" && t[1]); - if (eTag) - return { type: "nevent", data: getEventPointerFromETag(eTag) }; - const aTag = status.tags.find((t) => t[0] === "a" && t[1]); - if (aTag) - return { type: "naddr", data: getAddressPointerFromATag(aTag) }; - const rTag = status.tags.find((t) => t[0] === "r" && t[1]); - if (rTag) - return { type: "url", data: rTag[1] }; - return null; -} -function getUserStatusPointer(status) { - return getOrComputeCachedValue(status, UserStatusPointerSymbol, () => getStatusPointer(status)); -} - -// node_modules/applesauce-core/dist/helpers/wrapped-messages.js -function getWrappedMessageSubject(message) { - return getTagValue(message, "subject"); -} -function getWrappedMessageParent(message) { - return getTagValue(message, "e"); -} -function getWrappedMesssageSender(message) { - return message.pubkey; -} -function getWrappedMessageReceiver(message) { - return getConversationParticipants(message).filter((p) => p !== message.pubkey)[0]; -} - -// node_modules/applesauce-core/dist/helpers/zap.js -var ZapRequestSymbol = Symbol.for("zap-request"); -var ZapSenderSymbol = Symbol.for("zap-sender"); -var ZapReceiverSymbol = Symbol.for("zap-receiver"); -var ZapInvoiceSymbol = Symbol.for("zap-bolt11"); -var ZapEventPointerSymbol = Symbol.for("zap-event-pointer"); -var ZapAddressPointerSymbol = Symbol.for("zap-address-pointer"); -function getZapSender(zap) { - return getOrComputeCachedValue(zap, ZapSenderSymbol, () => { - return getTagValue(zap, "P") || getZapRequest(zap).pubkey; - }); -} -function getZapRecipient(zap) { - return getOrComputeCachedValue(zap, ZapReceiverSymbol, () => { - const recipient = getTagValue(zap, "p"); - if (!recipient) - throw new Error("Missing recipient"); - return recipient; - }); -} -function getZapPayment(zap) { - return getOrComputeCachedValue(zap, ZapInvoiceSymbol, () => { - const bolt11 = getTagValue(zap, "bolt11"); - return bolt11 ? parseBolt11(bolt11) : void 0; - }); -} -function getZapAddressPointer(zap) { - return getOrComputeCachedValue(zap, ZapAddressPointerSymbol, () => { - const a = zap.tags.find(isATag); - return a ? getAddressPointerFromATag(a) : null; - }); -} -function getZapEventPointer(zap) { - return getOrComputeCachedValue(zap, ZapEventPointerSymbol, () => { - const e = zap.tags.find(isETag); - return e ? getEventPointerFromETag(e) : null; - }); -} -function getZapPreimage(zap) { - return getTagValue(zap, "preimage"); -} -function getZapRequest(zap) { - return getOrComputeCachedValue(zap, ZapRequestSymbol, () => { - const description = getTagValue(zap, "description"); - if (!description) - throw new Error("Missing description tag"); - const error = nip57_exports.validateZapRequest(description); - if (error) - throw new Error(error); - return JSON.parse(description); - }); -} -function isValidZap(zap) { - if (!zap) - return false; - if (zap.kind !== kinds_exports.Zap) - return false; - try { - getZapRequest(zap); - getZapRecipient(zap); - return true; - } catch (error) { - return false; - } -} -function getZapSplits(event) { - const tags = event.tags.filter((t) => t[0] === "zap" && t[1] && t[3]); - if (tags.length > 0) { - const targets = tags.map((t) => ({ pubkey: t[1], relay: t[2], weight: parseFloat(t[3]) })).filter((p) => Number.isFinite(p.weight)); - const total = targets.reduce((v, p) => v + p.weight, 0); - return targets.map((p) => ({ ...p, percent: p.weight / total })); - } - return void 0; -} - -// node_modules/applesauce-core/dist/observable/claim-events.js -function claimEvents(claims) { - return (source) => { - const seen = /* @__PURE__ */ new Set(); - return source.pipe( - // claim all events - tap((message) => { - if (message === void 0) - return; - if (Array.isArray(message)) { - for (const event of message) { - seen.add(event); - claims.claim(event, source); - } - } else { - seen.add(message); - claims.claim(message, source); - } - }), - // remove claims on cleanup - finalize(() => { - for (const e of seen) - claims.removeClaim(e, source); - }) - ); - }; -} - -// node_modules/applesauce-core/dist/observable/claim-latest.js -function claimLatest(claims) { - return (source) => { - let latest = void 0; - return source.pipe(tap((event) => { - if (latest) - claims.removeClaim(latest, source); - if (event) - claims.claim(event, source); - latest = event; - }), finalize(() => { - if (latest) - claims.removeClaim(latest, source); - })); - }; -} - -// node_modules/applesauce-core/dist/observable/with-immediate-value.js -function withImmediateValueOrDefault(defaultValue) { - return (source) => new Observable((observer) => { - let seen = false; - const sub = source.subscribe({ - next: (v) => { - seen = true; - observer.next(v); - }, - error: (err) => observer.error(err), - complete: () => observer.complete() - }); - if (!seen) - observer.next(defaultValue); - return sub; - }); -} - -// node_modules/applesauce-core/dist/models/common.js -function EventModel(pointer) { - if (typeof pointer === "string") - pointer = { id: pointer }; - return (events) => merge( - // get current event and ignore if there is none - defer(() => { - let event = events.getEvent(pointer.id); - if (event) - return of(event); - if (!events.eventLoader) - return EMPTY; - return from(events.eventLoader(pointer)).pipe(filter((e) => !!e)); - }), - // Listen for new events - events.insert$.pipe(filter((e) => e.id === pointer.id)), - // emit undefined when deleted - events.removed(pointer.id).pipe(endWith(void 0)) - ).pipe( - // claim all events - claimLatest(events), - // ignore duplicate events - distinctUntilChanged((a, b) => (a == null ? void 0 : a.id) === (b == null ? void 0 : b.id)), - // always emit undefined so the observable is synchronous - withImmediateValueOrDefault(void 0) - ); -} -function ReplaceableModel(pointer) { - return (events) => { - let current = void 0; - return merge( - // lazily get current event - defer(() => { - let event = events.getReplaceable(pointer.kind, pointer.pubkey, pointer.identifier); - if (event) - return of(event); - else if (pointer.identifier !== void 0) { - if (!events.addressableLoader) - return EMPTY; - return from(events.addressableLoader(pointer)).pipe(filter((e) => !!e)); - } else { - if (!events.replaceableLoader) - return EMPTY; - return from(events.replaceableLoader(pointer)).pipe(filter((e) => !!e)); - } - }), - // subscribe to new events - events.insert$.pipe(filter((e) => e.pubkey == pointer.pubkey && e.kind === pointer.kind && (pointer.identifier !== void 0 ? getReplaceableIdentifier(e) === pointer.identifier : true))) - ).pipe( - // only update if event is newer - distinctUntilChanged((prev, event) => { - return prev.created_at >= event.created_at; - }), - // Hacky way to extract the current event so takeUntil can access it - tap((event) => current = event), - // complete when event is removed - takeUntil(events.remove$.pipe(filter((e) => e.id === (current == null ? void 0 : current.id)))), - // emit undefined when removed - endWith(void 0), - // keep the observable hot - repeat(), - // claim latest event - claimLatest(events), - // always emit undefined so the observable is synchronous - withImmediateValueOrDefault(void 0) - ); - }; -} -function TimelineModel(filters, includeOldVersion) { - filters = Array.isArray(filters) ? filters : [filters]; - return (events) => { - const seen = /* @__PURE__ */ new Map(); - return defer(() => of(Array.from(events.getTimeline(filters)))).pipe( - // claim existing events - claimEvents(events), - // subscribe to newer events - mergeWith(events.insert$.pipe( - filter((e) => matchFilters(filters, e)), - // claim all new events - claimEvents(events) - )), - // subscribe to delete events - mergeWith(events.remove$.pipe(filter((e) => matchFilters(filters, e)), map((e) => e.id))), - // build a timeline - scan((timeline, event) => { - if (typeof event === "string") - return timeline.filter((e) => e.id !== event); - if (Array.isArray(event)) { - if (!includeOldVersion) { - for (const e of event) - if (isReplaceable(e.kind)) - seen.set(getEventUID(e), e); - } - return event; - } - let newTimeline = [...timeline]; - if (!includeOldVersion && isReplaceable(event.kind)) { - const uid = getEventUID(event); - const existing = seen.get(uid); - if (existing && event.created_at < existing.created_at) - return timeline; - seen.set(uid, event); - if (existing) - newTimeline.slice(newTimeline.indexOf(existing), 1); - } - insertEventIntoDescendingList2(newTimeline, event); - return newTimeline; - }, []), - // ignore changes that do not modify the timeline instance - distinctUntilChanged(), - // hacky hack to clear seen on unsubscribe - finalize(() => seen.clear()) - ); - }; -} -function EventsModel(ids) { - return (events) => combineLatest(Object.fromEntries(ids.map((id) => [id, events.model(EventModel, { id })]))); -} -function ReplaceableSetModel(pointers) { - return (events) => combineLatest(Object.fromEntries(pointers.map((pointer) => [ - createReplaceableAddress(pointer.kind, pointer.pubkey, pointer.identifier), - events.model(ReplaceableModel, pointer) - ]))); -} - -// node_modules/applesauce-core/dist/observable/defined.js -function defined() { - return (source) => source.pipe(filter((v) => v !== void 0 && v !== null)); -} - -// node_modules/applesauce-core/dist/observable/get-observable-value.js -function getObservableValue(observable2) { - if (observable2 instanceof BehaviorSubject) - return observable2.value; - if (Reflect.has(observable2, "value")) - return Reflect.get(observable2, "value"); - return firstValueFrom(observable2); -} - -// node_modules/applesauce-core/dist/observable/map-events-timeline.js -function mapEventsToTimeline() { - return scan((timeline, event) => insertEventIntoDescendingList2(timeline, event), []); -} - -// node_modules/applesauce-core/dist/observable/map-events-to-store.js -function mapEventsToStore(store, removeDuplicates = true) { - return (source) => source.pipe( - // Map all events to the store - // NOTE: map is used here because we want to return the single cononical version of the event so that distinct() can be used later - map((event) => store.add(event)), - // Ignore invalid events - filter((e) => e !== null), - // Remove duplicates if requested - removeDuplicates ? distinct() : identity - ); -} - -// node_modules/applesauce-core/dist/observable/simple-timeout.js -var TimeoutError2 = class extends Error { -}; -function simpleTimeout(first2, message) { - return timeout({ first: first2, with: () => throwError(() => new TimeoutError2(message ?? "Timeout")) }); -} - -// node_modules/applesauce-core/dist/observable/watch-event-updates.js -function watchEventUpdates(eventStore) { - return (source) => { - let latest; - return merge( - // Get the latest event - source.pipe(tap((value) => latest = value)), - // listen for updates - eventStore.update$.pipe(filter((e) => e.id === (latest == null ? void 0 : latest.id))) - ); - }; -} -function watchEventsUpdates(eventStore) { - return (source) => { - let latest = []; - return merge( - // Get the latest event - source.pipe(tap((value) => latest = value)), - // listen for updates - eventStore.update$.pipe( - filter((e) => latest.includes(e)), - // re-emit the array of events - map(() => latest) - ) - ); - }; -} - -// node_modules/applesauce-core/dist/models/contacts.js -function ContactsModel(user) { - if (typeof user === "string") - user = { pubkey: user }; - return (events) => events.replaceable({ kind: kinds_exports.Contacts, pubkey: user.pubkey, relays: user.relays }).pipe( - // listen for event updates (hidden tags unlocked) - watchEventUpdates(events), - // Get all contacts - map((e) => e ? getContacts(e) : []) - ); -} -function PublicContactsModel(pubkey) { - return (events) => events.replaceable(kinds_exports.Contacts, pubkey).pipe(map((e) => e && getPublicContacts(e))); -} -function HiddenContactsModel(pubkey) { - return (events) => events.replaceable(kinds_exports.Contacts, pubkey).pipe( - // listen for event updates (hidden tags unlocked) - watchEventUpdates(events), - // Get hidden contacts - map((e) => e && (getHiddenContacts(e) ?? null)) - ); -} - -// node_modules/applesauce-core/dist/models/index.js -var models_exports = {}; -__export(models_exports, { - BlockedRelaysModel: () => BlockedRelaysModel, - CalendarEventRSVPsModel: () => CalendarEventRSVPsModel, - CalendarEventsModel: () => CalendarEventsModel, - ChannelHiddenModel: () => ChannelHiddenModel, - ChannelMessagesModel: () => ChannelMessagesModel, - ChannelMetadataModel: () => ChannelMetadataModel, - ChannelMutedModel: () => ChannelMutedModel, - CommentsModel: () => CommentsModel, - ContactsModel: () => ContactsModel, - EncryptedContentModel: () => EncryptedContentModel, - EventModel: () => EventModel, - EventZapsModel: () => EventZapsModel, - EventsModel: () => EventsModel, - FavoriteRelaySetsModel: () => FavoriteRelaySetsModel, - FavoriteRelaysModel: () => FavoriteRelaysModel, - GiftWrapRumorModel: () => GiftWrapRumorModel, - GiftWrapsModel: () => GiftWrapsModel, - HiddenContactsModel: () => HiddenContactsModel, - HiddenMuteModel: () => HiddenMuteModel, - LegacyMessageReplies: () => LegacyMessageReplies, - LegacyMessageThreads: () => LegacyMessageThreads, - LegacyMessagesGroup: () => LegacyMessagesGroup, - LegacyMessagesGroups: () => LegacyMessagesGroups, - MailboxesModel: () => MailboxesModel, - MuteModel: () => MuteModel, - ProfileModel: () => ProfileModel, - PublicContactsModel: () => PublicContactsModel, - PublicMuteModel: () => PublicMuteModel, - ReactionsModel: () => ReactionsModel, - ReceivedZapsModel: () => ReceivedZapsModel, - ReplaceableModel: () => ReplaceableModel, - ReplaceableSetModel: () => ReplaceableSetModel, - RepliesModel: () => RepliesModel, - SearchRelaysModel: () => SearchRelaysModel, - SentZapsModel: () => SentZapsModel, - ThreadModel: () => ThreadModel, - TimelineModel: () => TimelineModel, - UserBlossomServersModel: () => UserBlossomServersModel, - UserBookmarkModel: () => UserBookmarkModel, - UserHiddenBookmarkModel: () => UserHiddenBookmarkModel, - UserPinnedModel: () => UserPinnedModel, - UserPublicBookmarkModel: () => UserPublicBookmarkModel, - WrappedMessageReplies: () => WrappedMessageReplies, - WrappedMessageThreads: () => WrappedMessageThreads, - WrappedMessagesGroup: () => WrappedMessagesGroup, - WrappedMessagesGroups: () => WrappedMessagesGroups, - WrappedMessagesModel: () => WrappedMessagesModel -}); - -// node_modules/applesauce-core/dist/models/bookmarks.js -function UserBookmarkModel(pubkey) { - return (events) => events.replaceable(kinds_exports.Mutelist, pubkey).pipe( - // listen for event updates (hidden tags unlocked) - watchEventUpdates(events), - // Get all bookmarks - map((event) => event && getBookmarks(event)) - ); -} -function UserPublicBookmarkModel(pubkey) { - return (events) => events.replaceable(kinds_exports.Mutelist, pubkey).pipe(map((event) => event && getPublicBookmarks(event))); -} -function UserHiddenBookmarkModel(pubkey) { - return (events) => events.replaceable(kinds_exports.Mutelist, pubkey).pipe( - // listen for event updates (hidden tags unlocked) - watchEventUpdates(events), - // Get hidden bookmarks - map((event) => event && (getHiddenBookmarks(event) ?? null)) - ); -} - -// node_modules/applesauce-core/dist/models/calendar.js -function CalendarEventsModel(calendar) { - return (events) => combineLatest(getCalendarAddressPointers(calendar).map((p) => events.replaceable(p.kind, p.pubkey, p.identifier).pipe(defined()))); -} -function CalendarEventRSVPsModel(event) { - return (events) => { - return events.timeline({ kinds: [CALENDAR_EVENT_RSVP_KIND], "#a": [getReplaceableAddress(event)] }); - }; -} - -// node_modules/applesauce-core/dist/models/channels.js -function ChannelHiddenModel(channel, authors = []) { - return (events) => { - const hidden = /* @__PURE__ */ new Map(); - return events.filters([{ kinds: [kinds_exports.ChannelHideMessage], "#e": [channel.id], authors: [channel.pubkey, ...authors] }]).pipe(map((event) => { - var _a; - const reason = (_a = safeParse(event.content)) == null ? void 0 : _a.reason; - for (const tag of event.tags) { - if (tag[0] === "e" && tag[1]) - hidden.set(tag[1], reason ?? ""); - } - return hidden; - })); - }; -} -function ChannelMessagesModel(channel) { - return (events) => events.timeline([{ kinds: [kinds_exports.ChannelMessage], "#e": [channel.id] }]); -} -function ChannelMetadataModel(channel) { - return (events) => { - const filters = [ - { ids: [channel.id] }, - { kinds: [kinds_exports.ChannelMetadata], "#e": [channel.id], authors: [channel.pubkey] } - ]; - let latest = channel; - return events.filters(filters).pipe(map((event) => { - try { - if (event.pubkey === latest.pubkey && event.created_at > latest.created_at) { - latest = event; - } - return getChannelMetadataContent(latest); - } catch (error) { - return void 0; - } - })); - }; -} -function ChannelMutedModel(channel, authors = []) { - return (events) => { - const muted = /* @__PURE__ */ new Map(); - return events.filters([{ kinds: [kinds_exports.ChannelMuteUser], "#e": [channel.id], authors: [channel.pubkey, ...authors] }]).pipe(map((event) => { - var _a; - const reason = (_a = safeParse(event.content)) == null ? void 0 : _a.reason; - for (const tag of event.tags) { - if (tag[0] === "p" && tag[1]) - muted.set(tag[1], reason ?? ""); - } - return muted; - })); - }; -} - -// node_modules/applesauce-core/dist/models/comments.js -function CommentsModel(parent2) { - return (events) => { - const filters = [{ kinds: [COMMENT_KIND], "#e": [parent2.id] }]; - if (isAddressableKind2(parent2.kind)) - filters.push({ kinds: [COMMENT_KIND], "#a": [getReplaceableAddress(parent2)] }); - return events.timeline(filters); - }; -} - -// node_modules/applesauce-core/dist/models/encrypted-content.js -function EncryptedContentModel(event) { - return (events) => (typeof event === "string" ? events.event(event) : of(event)).pipe( - // Listen for updates to the event - watchEventUpdates(events), - // Get the encrypted content - map((event2) => event2 && getEncryptedContent(event2)) - ); -} - -// node_modules/applesauce-core/dist/models/gift-wrap.js -function GiftWrapsModel(pubkey, locked) { - return (store) => store.timeline({ kinds: [kinds_exports.GiftWrap], "#p": [pubkey] }).pipe( - // Update the timeline when events are updated - watchEventsUpdates(store), - // If lock is specified filter on locked status - locked !== void 0 ? map((events) => events.filter((e) => isGiftWrapLocked(e) === locked)) : identity - ); -} -function GiftWrapRumorModel(gift) { - return (events) => (typeof gift === "string" ? events.event(gift) : of(gift)).pipe( - // Listen for updates to the event - watchEventUpdates(events), - // Get the rumor event - map((event) => event && getGiftWrapRumor(event)) - ); -} - -// node_modules/applesauce-core/dist/models/legacy-messages.js -function LegacyMessagesGroups(self) { - return (store) => store.timeline({ kinds: [kinds_exports.EncryptedDirectMessage], "#p": [self] }).pipe(map((messages) => { - const groups = {}; - for (const message of messages) { - const id = getConversationIdentifierFromMessage(message); - if (!groups[id] || groups[id].created_at < message.created_at) - groups[id] = message; - } - return Object.values(groups).map((message) => ({ - id: getConversationIdentifierFromMessage(message), - participants: getConversationParticipants(message), - lastMessage: message - })); - })); -} -function LegacyMessagesGroup(self, corraspondant) { - return (store) => store.timeline([ - { - kinds: [kinds_exports.EncryptedDirectMessage], - "#p": [self], - authors: [corraspondant] - }, - { - kinds: [kinds_exports.EncryptedDirectMessage], - "#p": [corraspondant], - authors: [self] - } - ]); -} -function LegacyMessageThreads(self, corraspondant) { - return (store) => store.model(LegacyMessagesGroup, self, corraspondant).pipe(map((messages) => messages.filter((message) => ( - // Only select messages that are not replies - !getLegacyMessageParent(message) && // Check if message has any replies - store.getByFilters({ "#e": [message.id], kinds: [kinds_exports.EncryptedDirectMessage] }).size > 0 - )))); -} -function LegacyMessageReplies(self, message) { - const corraspondant = getLegacyMessageCorraspondant(message, self); - return (store) => store.timeline([ - { - kinds: [kinds_exports.EncryptedDirectMessage], - "#p": [self], - authors: [corraspondant], - "#e": [message.id] - }, - { - kinds: [kinds_exports.EncryptedDirectMessage], - "#p": [corraspondant], - authors: [self], - "#e": [message.id] - } - ]); -} - -// node_modules/applesauce-core/dist/models/mailboxes.js -function MailboxesModel(user) { - if (typeof user === "string") - user = { pubkey: user }; - return (events) => events.replaceable({ kind: kinds_exports.RelayList, pubkey: user.pubkey, relays: user.relays }).pipe(map((event) => event && { - inboxes: getInboxes(event), - outboxes: getOutboxes(event) - })); -} - -// node_modules/applesauce-core/dist/models/mutes.js -function MuteModel(user) { - if (typeof user === "string") - user = { pubkey: user }; - return (events) => events.replaceable({ kind: kinds_exports.Mutelist, pubkey: user.pubkey, relays: user.relays }).pipe( - // listen for event updates (hidden tags unlocked) - watchEventUpdates(events), - // Get all muted things - map((event) => event && getMutedThings(event)) - ); -} -function PublicMuteModel(pubkey) { - return (events) => events.replaceable(kinds_exports.Mutelist, pubkey).pipe(map((event) => event && getPublicMutedThings(event))); -} -function HiddenMuteModel(pubkey) { - return (events) => events.replaceable(kinds_exports.Mutelist, pubkey).pipe( - // listen for event updates (hidden tags unlocked) - watchEventUpdates(events), - // Get hidden muted things - map((event) => event && getHiddenMutedThings(event)) - ); -} - -// node_modules/applesauce-core/dist/models/pins.js -function UserPinnedModel(pubkey) { - return (events) => events.replaceable(kinds_exports.Pinlist, pubkey).pipe(map((event) => event && processTags(event.tags.filter(isETag), getEventPointerFromETag))); -} - -// node_modules/applesauce-core/dist/models/profile.js -function ProfileModel(user) { - if (typeof user === "string") - user = { pubkey: user }; - return (events) => events.replaceable({ kind: kinds_exports.Metadata, pubkey: user.pubkey, relays: user.relays }).pipe( - // Filter out invalid profile events - filter(isValidProfile), - // Parse the profile event into a ProfileContent - map((event) => event && getProfileContent(event)), - // Ensure the model is synchronous - withImmediateValueOrDefault(void 0) - ); -} - -// node_modules/applesauce-core/dist/models/reactions.js -function ReactionsModel(event) { - return (events) => events.timeline(isReplaceable(event.kind) ? [ - { kinds: [kinds_exports.Reaction], "#e": [event.id] }, - { kinds: [kinds_exports.Reaction], "#a": [getEventUID(event)] } - ] : [ - { - kinds: [kinds_exports.Reaction], - "#e": [event.id] - } - ]); -} - -// node_modules/applesauce-core/dist/models/relays.js -function FavoriteRelaysModel(pubkey, type) { - return (events) => { - return events.replaceable(FAVORITE_RELAYS_KIND, pubkey).pipe(type !== "public" ? watchEventUpdates(events) : map(identity), map((e) => e && getRelaysFromList(e, type))); - }; -} -function FavoriteRelaySetsModel(pubkey, type) { - return (events) => { - return events.replaceable(FAVORITE_RELAYS_KIND, pubkey).pipe(type !== "public" ? watchEventUpdates(events) : map(identity), map((e) => e && getAddressPointersFromList(e, type))); - }; -} -function SearchRelaysModel(pubkey, type) { - return (events) => { - return events.replaceable(kinds_exports.SearchRelaysList, pubkey).pipe(type !== "public" ? watchEventUpdates(events) : map(identity), map((e) => e && getRelaysFromList(e, type))); - }; -} -function BlockedRelaysModel(pubkey, type) { - return (events) => { - return events.replaceable(kinds_exports.BlockedRelaysList, pubkey).pipe(type !== "public" ? watchEventUpdates(events) : map(identity), map((e) => e && getRelaysFromList(e, type))); - }; -} - -// node_modules/applesauce-core/dist/models/thread.js -var defaultOptions = { - kinds: [kinds_exports.ShortTextNote] -}; -function ThreadModel(root, opts) { - const parentReferences = /* @__PURE__ */ new Map(); - const items = /* @__PURE__ */ new Map(); - const { kinds } = { ...defaultOptions, ...opts }; - let rootUID = ""; - const rootFilter = {}; - const replyFilter = { kinds }; - if (isAddressPointer(root)) { - rootUID = getCoordinateFromAddressPointer(root); - rootFilter.kinds = [root.kind]; - rootFilter.authors = [root.pubkey]; - rootFilter["#d"] = [root.identifier]; - replyFilter["#a"] = [rootUID]; - } else if (typeof root === "string") { - rootUID = root; - rootFilter.ids = [root]; - replyFilter["#e"] = [root]; - } else { - rootUID = root.id; - rootFilter.ids = [root.id]; - replyFilter["#e"] = [root.id]; - } - return (events) => events.filters([rootFilter, replyFilter]).pipe(map((event) => { - var _a, _b; - if (!items.has(getEventUID(event))) { - const refs = getNip10References(event); - const replies = parentReferences.get(getEventUID(event)) || /* @__PURE__ */ new Set(); - const item = { event, refs, replies }; - for (const child of replies) { - child.parent = item; - } - if (((_a = refs.reply) == null ? void 0 : _a.e) || ((_b = refs.reply) == null ? void 0 : _b.a)) { - let uid = refs.reply.e ? refs.reply.e.id : getCoordinateFromAddressPointer(refs.reply.a); - item.parent = items.get(uid); - if (item.parent) { - item.parent.replies.add(item); - } else { - let set = parentReferences.get(uid); - if (!set) { - set = /* @__PURE__ */ new Set(); - parentReferences.set(uid, set); - } - set.add(item); - } - } - items.set(getEventUID(event), item); - } - return { root: items.get(rootUID), all: items }; - })); -} -function RepliesModel(event, overrideKinds) { - return (events) => { - const kinds = overrideKinds || event.kind === 1 ? [1, COMMENT_KIND] : [COMMENT_KIND]; - const filter2 = { kinds }; - if (isEvent(parent) || isEventPointer(event)) - filter2["#e"] = [event.id]; - const address = isAddressableKind2(event.kind) ? createReplaceableAddress(event.kind, event.pubkey, getTagValue(event, "d")) : void 0; - if (address) { - filter2["#a"] = [address]; - } - return events.timeline(filter2).pipe(map((events2) => { - return events2.filter((e) => { - var _a, _b, _c, _d; - const refs = interpretThreadTags(e.tags); - return ((_b = (_a = refs.reply) == null ? void 0 : _a.e) == null ? void 0 : _b[1]) === event.id || ((_d = (_c = refs.reply) == null ? void 0 : _c.a) == null ? void 0 : _d[1]) === address; - }); - })); - }; -} - -// node_modules/applesauce-core/dist/models/wrapped-messages.js -function WrappedMessagesModel(self) { - return (store) => store.timeline({ kinds: [kinds_exports.GiftWrap], "#p": [self] }).pipe( - // Watch for updates to the gift wraps - watchEventsUpdates(store), - // Get rumors and filter out locked - map((rumors) => rumors.map((gift) => getGiftWrapRumor(gift)).filter((e) => !!e).filter((e) => e.kind === kinds_exports.PrivateDirectMessage).sort((a, b) => b.created_at - a.created_at)) - ); -} -function WrappedMessagesGroups(self) { - return (store) => store.model(WrappedMessagesModel, self).pipe(map((messages) => { - const groups = {}; - for (const message of messages) { - const id = getConversationIdentifierFromMessage(message); - if (!groups[id] || groups[id].created_at < message.created_at) - groups[id] = message; - } - return Object.values(groups).map((message) => ({ - id: getConversationIdentifierFromMessage(message), - participants: getConversationParticipants(message), - lastMessage: message - })); - })); -} -function WrappedMessagesGroup(self, participants) { - const identifier = createConversationIdentifier(self, participants); - return (store) => store.model(WrappedMessagesModel, self).pipe( - // Only select direct messages for this conversation - map((rumors) => rumors.filter((rumor) => rumor.kind === kinds_exports.PrivateDirectMessage && // Only select message for this conversation (the identifier from the message will include "self") - getConversationIdentifierFromMessage(rumor) === identifier)) - ); -} -function WrappedMessageThreads(self, participants) { - return (store) => store.model(WrappedMessagesGroup, self, participants).pipe( - // Filter down messages to only include root messages that have replies - map((rumors) => rumors.filter((rumor) => ( - // Only select root messages - !getWrappedMessageParent(rumor) && // Check if message has any replies - rumors.some((r) => getWrappedMessageParent(r) === rumor.id) - ))) - ); -} -function WrappedMessageReplies(self, message) { - const conversation = getConversationIdentifierFromMessage(message); - return (store) => store.model(WrappedMessagesGroup, self, conversation).pipe( - // Only select replies to this message - map((rumors) => rumors.filter((rumor) => getWrappedMessageParent(rumor) === message.id)) - ); -} - -// node_modules/applesauce-core/dist/models/zaps.js -function EventZapsModel(id) { - return (events) => { - if (isAddressPointer(id)) { - return events.timeline([{ kinds: [kinds_exports.Zap], "#a": [getCoordinateFromAddressPointer(id)] }]).pipe(map((events2) => events2.filter(isValidZap))); - } else { - id = typeof id === "string" ? id : id.id; - return events.timeline([{ kinds: [kinds_exports.Zap], "#e": [id] }]).pipe(map((events2) => events2.filter(isValidZap))); - } - }; -} -function SentZapsModel(pubkey) { - return (events) => events.timeline([{ kinds: [kinds_exports.Zap], authors: [pubkey] }]); -} -function ReceivedZapsModel(pubkey) { - return (events) => events.timeline([{ kinds: [kinds_exports.Zap], "#a": [pubkey] }]); -} - -// node_modules/applesauce-core/dist/event-store/event-store.js -var EventStore = class _EventStore { - constructor() { - __publicField(this, "database"); - /** Enable this to keep old versions of replaceable events */ - __publicField(this, "keepOldVersions", false); - /** Enable this to keep expired events */ - __publicField(this, "keepExpired", false); - /** - * A method used to verify new events before added them - * @returns true if the event is valid, false if it should be ignored - */ - __publicField(this, "verifyEvent"); - /** A stream of new events added to the store */ - __publicField(this, "insert$"); - /** A stream of events that have been updated */ - __publicField(this, "update$"); - /** A stream of events that have been removed */ - __publicField(this, "remove$"); - /** - * A method that will be called when an event isn't found in the store - * @experimental - */ - __publicField(this, "eventLoader"); - /** - * A method that will be called when a replaceable event isn't found in the store - * @experimental - */ - __publicField(this, "replaceableLoader"); - /** - * A method that will be called when an addressable event isn't found in the store - * @experimental - */ - __publicField(this, "addressableLoader"); - // delete state - __publicField(this, "deletedIds", /* @__PURE__ */ new Set()); - __publicField(this, "deletedCoords", /* @__PURE__ */ new Map()); - __publicField(this, "expirations", /* @__PURE__ */ new Map()); - __publicField(this, "expirationTimeout", null); - __publicField(this, "nextExpirationCheck", null); - /** A directory of all active models */ - __publicField(this, "models", /* @__PURE__ */ new Map()); - /** How long a model should be kept "warm" while nothing is subscribed to it */ - __publicField(this, "modelKeepWarm", 6e4); - this.database = new EventSet(); - this.database.onBeforeInsert = (event) => { - if (this.verifyEvent && this.verifyEvent(event) === false) - return false; - else - return true; - }; - this.database.insert$.subscribe((event) => { - Reflect.set(event, EventStoreSymbol, this); - }); - this.database.remove$.subscribe((event) => { - Reflect.deleteProperty(event, EventStoreSymbol); - }); - this.insert$ = this.database.insert$; - this.update$ = this.database.update$; - this.remove$ = this.database.remove$; - } - checkDeleted(event) { - var _a; - if (typeof event === "string") - return this.deletedIds.has(event); - else { - if (this.deletedIds.has(event.id)) - return true; - if (isAddressableKind2(event.kind)) { - const identifier = (_a = event.tags.find((t) => t[0] === "d")) == null ? void 0 : _a[1]; - const deleted = this.deletedCoords.get(createReplaceableAddress(event.kind, event.pubkey, identifier)); - if (deleted) - return deleted > event.created_at; - } - } - return false; - } - /** Adds an event to the expiration map */ - addExpiration(event) { - const expiration = getExpirationTimestamp(event); - if (expiration && Number.isFinite(expiration)) - this.expirations.set(event.id, expiration); - } - handleExpiringEvent(event) { - const expiration = getExpirationTimestamp(event); - if (!expiration) - return; - this.expirations.set(event.id, expiration); - if (this.expirationTimeout && this.nextExpirationCheck && this.nextExpirationCheck < expiration) - return; - if (this.expirationTimeout) - clearTimeout(this.expirationTimeout); - const timeout2 = expiration - unixNow(); - this.expirationTimeout = setTimeout(this.pruneExpired.bind(this), timeout2 * 1e3 + 10); - this.nextExpirationCheck = expiration; - } - /** Remove expired events from the store */ - pruneExpired() { - const now2 = unixNow(); - for (const [id, expiration] of this.expirations) { - if (expiration <= now2) { - this.expirations.delete(id); - this.remove(id); - } - } - if (this.expirationTimeout) - clearTimeout(this.expirationTimeout); - this.nextExpirationCheck = null; - this.expirationTimeout = null; - } - // handling delete events - handleDeleteEvent(deleteEvent) { - const ids = getDeleteIds(deleteEvent); - for (const id of ids) { - this.deletedIds.add(id); - const event = this.database.getEvent(id); - if (event) - this.database.remove(event); - } - const coords = getDeleteCoordinates(deleteEvent); - for (const coord of coords) { - this.deletedCoords.set(coord, Math.max(this.deletedCoords.get(coord) ?? 0, deleteEvent.created_at)); - const parsed = parseCoordinate(coord); - if (!parsed) - continue; - const events = this.database.getReplaceableHistory(parsed.kind, parsed.pubkey, parsed.identifier) ?? []; - for (const event of events) { - if (event.created_at < deleteEvent.created_at) - this.database.remove(event); - } - } - } - /** Copies important metadata from and identical event to another */ - static mergeDuplicateEvent(source, dest) { - const relays = getSeenRelays(source); - if (relays) { - for (const relay of relays) - addSeenRelay(dest, relay); - } - const fromCache = Reflect.get(source, FromCacheSymbol); - if (fromCache && !Reflect.get(dest, FromCacheSymbol)) - Reflect.set(dest, FromCacheSymbol, fromCache); - } - /** - * Adds an event to the store and update subscriptions - * @returns The existing event or the event that was added, if it was ignored returns null - */ - add(event, fromRelay) { - var _a; - if (event.kind === kinds_exports.EventDeletion) - this.handleDeleteEvent(event); - if (this.checkDeleted(event)) - return event; - const expiration = getExpirationTimestamp(event); - if (this.keepExpired === false && expiration && expiration <= unixNow()) - return null; - const identifier = isReplaceable(event.kind) ? (_a = event.tags.find((t) => t[0] === "d")) == null ? void 0 : _a[1] : void 0; - if (!this.keepOldVersions && isReplaceable(event.kind)) { - const existing = this.database.getReplaceableHistory(event.kind, event.pubkey, identifier); - if (existing && existing.length > 0 && existing[0].created_at >= event.created_at) { - _EventStore.mergeDuplicateEvent(event, existing[0]); - return existing[0]; - } - } else if (this.database.hasEvent(event.id)) { - const existing = this.database.getEvent(event.id); - if (existing) { - _EventStore.mergeDuplicateEvent(event, existing); - return existing; - } - } - const inserted = this.database.add(event); - if (inserted === null) - return null; - if (event !== inserted) - _EventStore.mergeDuplicateEvent(event, inserted); - if (fromRelay) - addSeenRelay(inserted, fromRelay); - if (!this.keepOldVersions && isReplaceable(event.kind)) { - const existing = this.database.getReplaceableHistory(event.kind, event.pubkey, identifier); - if (existing) { - const older = Array.from(existing).filter((e) => e.created_at < event.created_at); - for (const old of older) - this.database.remove(old); - if (existing.length !== older.length) - return existing[0]; - } - } - if (this.keepExpired === false && expiration) - this.handleExpiringEvent(inserted); - return inserted; - } - /** Removes an event from the database and updates subscriptions */ - remove(event) { - return this.database.remove(event); - } - /** Add an event to the store and notifies all subscribes it has updated */ - update(event) { - return this.database.update(event); - } - /** Removes any event that is not being used by a subscription */ - prune(max2) { - return this.database.prune(max2); - } - /** Check if the store has an event by id */ - hasEvent(id) { - return this.database.hasEvent(id); - } - /** Get an event by id from the store */ - getEvent(id) { - return this.database.getEvent(id); - } - /** Check if the store has a replaceable event */ - hasReplaceable(kind, pubkey, d) { - return this.database.hasReplaceable(kind, pubkey, d); - } - /** Gets the latest version of a replaceable event */ - getReplaceable(kind, pubkey, identifier) { - return this.database.getReplaceable(kind, pubkey, identifier); - } - /** Returns all versions of a replaceable event */ - getReplaceableHistory(kind, pubkey, identifier) { - return this.database.getReplaceableHistory(kind, pubkey, identifier); - } - /** Get all events matching a filter */ - getByFilters(filters) { - return this.database.getByFilters(filters); - } - /** Returns a timeline of events that match filters */ - getTimeline(filters) { - return this.database.getTimeline(filters); - } - /** Sets the claim on the event and touches it */ - claim(event, claim) { - this.database.claim(event, claim); - } - /** Checks if an event is claimed by anything */ - isClaimed(event) { - return this.database.isClaimed(event); - } - /** Removes a claim from an event */ - removeClaim(event, claim) { - this.database.removeClaim(event, claim); - } - /** Removes all claims on an event */ - clearClaim(event) { - this.database.clearClaim(event); - } - /** Get or create a model on the event store */ - model(constructor, ...args) { - let models = this.models.get(constructor); - if (!models) { - models = /* @__PURE__ */ new Map(); - this.models.set(constructor, models); - } - const key = constructor.getKey ? constructor.getKey(...args) : (0, import_hash_sum.default)(args); - let model = models.get(key); - if (!model) { - const cleanup = () => { - if (models.get(key) === model) - models.delete(key); - }; - model = constructor(...args)(this).pipe( - // remove the model when its unsubscribed - finalize(cleanup), - // only subscribe to models once for all subscriptions - share({ - connector: () => new ReplaySubject(1), - resetOnComplete: () => timer(this.modelKeepWarm), - resetOnRefCountZero: () => timer(this.modelKeepWarm) - }) - ); - models.set(key, model); - } - return model; - } - /** - * Creates an observable that streams all events that match the filter - * @param filters - * @param [onlyNew=false] Only subscribe to new events - */ - filters(filters, onlyNew = false) { - filters = Array.isArray(filters) ? filters : [filters]; - return merge( - // merge existing events - onlyNew ? EMPTY : from(this.getByFilters(filters)), - // subscribe to future events - this.insert$.pipe(filter((e) => matchFilters(filters, e))) - ); - } - /** Returns an observable that completes when an event is removed */ - removed(id) { - const deleted = this.checkDeleted(id); - if (deleted) - return EMPTY; - return this.remove$.pipe( - // listen for removed events - filter((e) => e.id === id), - // complete as soon as we find a matching removed event - take(1), - // switch to empty - mergeMap(() => EMPTY) - ); - } - /** Creates an observable that emits when event is updated */ - updated(event) { - return this.database.update$.pipe(filter((e) => e.id === event || e === event)); - } - // Helper methods for creating models - /** Creates a {@link EventModel} */ - event(pointer) { - if (typeof pointer === "string") - pointer = { id: pointer }; - return this.model(EventModel, pointer); - } - replaceable(...args) { - let pointer; - if (args.length === 1) { - pointer = args[0]; - } else if (args.length === 3 || args.length === 2) { - let [kind, pubkey, identifier] = args; - pointer = { kind, pubkey, identifier }; - } - if (!pointer) - throw new Error("Invalid arguments, expected address pointer or kind, pubkey, identifier"); - return this.model(ReplaceableModel, pointer); - } - /** Subscribe to an addressable event by pointer */ - addressable(pointer) { - return this.model(ReplaceableModel, pointer); - } - /** Creates a {@link TimelineModel} */ - timeline(filters, includeOldVersion = false) { - return this.model(TimelineModel, filters, includeOldVersion); - } - /** Subscribe to a users profile */ - profile(user) { - return this.model(ProfileModel, user); - } - /** Subscribe to a users contacts */ - contacts(user) { - if (typeof user === "string") - user = { pubkey: user }; - return this.model(ContactsModel, user); - } - /** Subscribe to a users mutes */ - mutes(user) { - if (typeof user === "string") - user = { pubkey: user }; - return this.model(MuteModel, user); - } - /** Subscribe to a users NIP-65 mailboxes */ - mailboxes(user) { - if (typeof user === "string") - user = { pubkey: user }; - return this.model(MailboxesModel, user); - } - /** Subscribe to a users blossom servers */ - blossomServers(user) { - if (typeof user === "string") - user = { pubkey: user }; - return this.model(UserBlossomServersModel, user); - } - /** Subscribe to an event's reactions */ - reactions(event) { - return this.model(ReactionsModel, event); - } - /** Subscribe to a thread */ - thread(root) { - return this.model(ThreadModel, root); - } - /** Subscribe to a event's comments */ - comments(event) { - return this.model(CommentsModel, event); - } - /** @deprecated use multiple {@link EventModel} instead */ - events(ids) { - return this.model(EventsModel, ids); - } - /** @deprecated use multiple {@link ReplaceableModel} instead */ - replaceableSet(pointers) { - return this.model(ReplaceableSetModel, pointers); - } -}; - -export { - Subject, - BehaviorSubject, - of, - isObservable, - lastValueFrom, - firstValueFrom, - map, - NEVER, - catchError, - distinctUntilChanged, - finalize, - switchMap, - require_hash_sum, - getOrComputeCachedValue, - convertToUrl, - getURLFilename, - IMAGE_EXT, - decode2 as decode, - abytes, - aexists, - aoutput, - clean, - createView4 as createView, - rotr3 as rotr, - bytesToHex3 as bytesToHex, - toBytes4 as toBytes, - Hash3 as Hash, - createHasher2 as createHasher, - randomBytes3 as randomBytes, - parseBolt11, - getEmojiTag, - logger, - EventSet, - getHashtagTag, - helpers_exports, - withImmediateValueOrDefault, - defined, - getObservableValue, - mapEventsToTimeline, - mapEventsToStore, - TimeoutError2 as TimeoutError, - simpleTimeout, - watchEventUpdates, - watchEventsUpdates, - models_exports, - EventStore -}; -/*! Bundled license information: - -@scure/base/lib/index.js: - (*! scure-base - MIT License (c) 2022 Paul Miller (paulmillr.com) *) - -@noble/hashes/esm/utils.js: - (*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) *) - -@noble/curves/esm/abstract/utils.js: - (*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) *) - -@noble/curves/esm/abstract/modular.js: - (*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) *) - -@noble/curves/esm/abstract/curve.js: - (*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) *) - -@noble/curves/esm/abstract/weierstrass.js: - (*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) *) - -@noble/curves/esm/_shortw_utils.js: - (*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) *) - -@noble/curves/esm/secp256k1.js: - (*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) *) - -@noble/hashes/esm/utils.js: - (*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) *) - -@scure/base/lib/esm/index.js: - (*! scure-base - MIT License (c) 2022 Paul Miller (paulmillr.com) *) - -@noble/ciphers/esm/utils.js: - (*! noble-ciphers - MIT License (c) 2023 Paul Miller (paulmillr.com) *) - -@noble/hashes/esm/utils.js: - (*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) *) - -@scure/base/lib/esm/index.js: - (*! scure-base - MIT License (c) 2022 Paul Miller (paulmillr.com) *) -*/ -//# sourceMappingURL=chunk-ESJ34HX7.js.map diff --git a/node_modules/.vite/deps_temp_742205d0/chunk-ESJ34HX7.js.map b/node_modules/.vite/deps_temp_742205d0/chunk-ESJ34HX7.js.map deleted file mode 100644 index 54ad313e..00000000 --- a/node_modules/.vite/deps_temp_742205d0/chunk-ESJ34HX7.js.map +++ /dev/null @@ -1,7 +0,0 @@ -{ - "version": 3, - "sources": ["../../hash-sum/hash-sum.js", "../../fast-deep-equal/index.js", "../../light-bolt11-decoder/node_modules/@scure/base/lib/index.js", "../../light-bolt11-decoder/bolt11.js", "../../ms/index.js", "../../debug/src/common.js", "../../debug/src/browser.js", "../../nostr-tools/node_modules/@noble/curves/node_modules/@noble/hashes/src/_assert.ts", "../../nostr-tools/node_modules/@noble/curves/node_modules/@noble/hashes/src/crypto.ts", "../../nostr-tools/node_modules/@noble/curves/node_modules/@noble/hashes/src/utils.ts", "../../nostr-tools/node_modules/@noble/curves/node_modules/@noble/hashes/src/_sha2.ts", "../../nostr-tools/node_modules/@noble/curves/node_modules/@noble/hashes/src/sha256.ts", "../../nostr-tools/node_modules/@noble/curves/src/abstract/utils.ts", "../../nostr-tools/node_modules/@noble/curves/src/abstract/modular.ts", "../../nostr-tools/node_modules/@noble/curves/src/abstract/curve.ts", "../../nostr-tools/node_modules/@noble/curves/src/abstract/weierstrass.ts", "../../nostr-tools/node_modules/@noble/curves/src/abstract/hash-to-curve.ts", "../../nostr-tools/node_modules/@noble/curves/node_modules/@noble/hashes/src/hmac.ts", "../../nostr-tools/node_modules/@noble/curves/src/_shortw_utils.ts", "../../nostr-tools/node_modules/@noble/curves/src/secp256k1.ts", "../../nostr-tools/node_modules/@noble/hashes/src/crypto.ts", "../../nostr-tools/node_modules/@noble/hashes/src/utils.ts", "../../nostr-tools/node_modules/@noble/hashes/src/_assert.ts", "../../nostr-tools/node_modules/@noble/hashes/src/_sha2.ts", "../../nostr-tools/node_modules/@noble/hashes/src/sha256.ts", "../../nostr-tools/node_modules/@scure/base/lib/esm/index.js", "../../@noble/ciphers/src/_assert.ts", "../../@noble/ciphers/src/utils.ts", "../../@noble/ciphers/src/_polyval.ts", "../../@noble/ciphers/src/aes.ts", "../../@noble/ciphers/src/_poly1305.ts", "../../@noble/ciphers/src/_arx.ts", "../../@noble/ciphers/src/chacha.ts", "../../nostr-tools/node_modules/@noble/hashes/src/hmac.ts", "../../nostr-tools/node_modules/@noble/hashes/src/hkdf.ts", "../../nostr-tools/lib/esm/index.js", "../../nostr-tools/lib/esm/kinds.js", "../../tslib/tslib.es6.mjs", "../../rxjs/src/internal/util/isFunction.ts", "../../rxjs/src/internal/util/createErrorClass.ts", "../../rxjs/src/internal/util/UnsubscriptionError.ts", "../../rxjs/src/internal/util/arrRemove.ts", "../../rxjs/src/internal/Subscription.ts", "../../rxjs/src/internal/config.ts", "../../rxjs/src/internal/scheduler/timeoutProvider.ts", "../../rxjs/src/internal/util/reportUnhandledError.ts", "../../rxjs/src/internal/util/noop.ts", "../../rxjs/src/internal/NotificationFactories.ts", "../../rxjs/src/internal/util/errorContext.ts", "../../rxjs/src/internal/Subscriber.ts", "../../rxjs/src/internal/symbol/observable.ts", "../../rxjs/src/internal/util/identity.ts", "../../rxjs/src/internal/util/pipe.ts", "../../rxjs/src/internal/Observable.ts", "../../rxjs/src/internal/util/lift.ts", "../../rxjs/src/internal/operators/OperatorSubscriber.ts", "../../rxjs/src/internal/operators/refCount.ts", "../../rxjs/src/internal/observable/ConnectableObservable.ts", "../../rxjs/src/internal/scheduler/performanceTimestampProvider.ts", "../../rxjs/src/internal/scheduler/animationFrameProvider.ts", "../../rxjs/src/internal/observable/dom/animationFrames.ts", "../../rxjs/src/internal/util/ObjectUnsubscribedError.ts", "../../rxjs/src/internal/Subject.ts", "../../rxjs/src/internal/BehaviorSubject.ts", "../../rxjs/src/internal/scheduler/dateTimestampProvider.ts", "../../rxjs/src/internal/ReplaySubject.ts", "../../rxjs/src/internal/AsyncSubject.ts", "../../rxjs/src/internal/scheduler/Action.ts", "../../rxjs/src/internal/scheduler/intervalProvider.ts", "../../rxjs/src/internal/scheduler/AsyncAction.ts", "../../rxjs/src/internal/util/Immediate.ts", "../../rxjs/src/internal/scheduler/immediateProvider.ts", "../../rxjs/src/internal/scheduler/AsapAction.ts", "../../rxjs/src/internal/Scheduler.ts", "../../rxjs/src/internal/scheduler/AsyncScheduler.ts", "../../rxjs/src/internal/scheduler/AsapScheduler.ts", "../../rxjs/src/internal/scheduler/asap.ts", "../../rxjs/src/internal/scheduler/async.ts", "../../rxjs/src/internal/scheduler/QueueAction.ts", "../../rxjs/src/internal/scheduler/QueueScheduler.ts", "../../rxjs/src/internal/scheduler/queue.ts", "../../rxjs/src/internal/scheduler/AnimationFrameAction.ts", "../../rxjs/src/internal/scheduler/AnimationFrameScheduler.ts", "../../rxjs/src/internal/scheduler/animationFrame.ts", "../../rxjs/src/internal/scheduler/VirtualTimeScheduler.ts", "../../rxjs/src/internal/observable/empty.ts", "../../rxjs/src/internal/util/isScheduler.ts", "../../rxjs/src/internal/util/args.ts", "../../rxjs/src/internal/util/isArrayLike.ts", "../../rxjs/src/internal/util/isPromise.ts", "../../rxjs/src/internal/util/isInteropObservable.ts", "../../rxjs/src/internal/util/isAsyncIterable.ts", "../../rxjs/src/internal/util/throwUnobservableError.ts", "../../rxjs/src/internal/symbol/iterator.ts", "../../rxjs/src/internal/util/isIterable.ts", "../../rxjs/src/internal/util/isReadableStreamLike.ts", "../../rxjs/src/internal/observable/innerFrom.ts", "../../rxjs/src/internal/util/executeSchedule.ts", "../../rxjs/src/internal/operators/observeOn.ts", "../../rxjs/src/internal/operators/subscribeOn.ts", "../../rxjs/src/internal/scheduled/scheduleObservable.ts", "../../rxjs/src/internal/scheduled/schedulePromise.ts", "../../rxjs/src/internal/scheduled/scheduleArray.ts", "../../rxjs/src/internal/scheduled/scheduleIterable.ts", "../../rxjs/src/internal/scheduled/scheduleAsyncIterable.ts", "../../rxjs/src/internal/scheduled/scheduleReadableStreamLike.ts", "../../rxjs/src/internal/scheduled/scheduled.ts", "../../rxjs/src/internal/observable/from.ts", "../../rxjs/src/internal/observable/of.ts", "../../rxjs/src/internal/observable/throwError.ts", "../../rxjs/src/internal/Notification.ts", "../../rxjs/src/internal/util/isObservable.ts", "../../rxjs/src/internal/util/EmptyError.ts", "../../rxjs/src/internal/lastValueFrom.ts", "../../rxjs/src/internal/firstValueFrom.ts", "../../rxjs/src/internal/util/ArgumentOutOfRangeError.ts", "../../rxjs/src/internal/util/NotFoundError.ts", "../../rxjs/src/internal/util/SequenceError.ts", "../../rxjs/src/internal/util/isDate.ts", "../../rxjs/src/internal/operators/timeout.ts", "../../rxjs/src/internal/operators/map.ts", "../../rxjs/src/internal/util/mapOneOrManyArgs.ts", "../../rxjs/src/internal/util/argsArgArrayOrObject.ts", "../../rxjs/src/internal/util/createObject.ts", "../../rxjs/src/internal/observable/combineLatest.ts", "../../rxjs/src/internal/operators/mergeInternals.ts", "../../rxjs/src/internal/operators/mergeMap.ts", "../../rxjs/src/internal/operators/mergeAll.ts", "../../rxjs/src/internal/operators/concatAll.ts", "../../rxjs/src/internal/observable/concat.ts", "../../rxjs/src/internal/observable/defer.ts", "../../rxjs/src/internal/observable/timer.ts", "../../rxjs/src/internal/observable/merge.ts", "../../rxjs/src/internal/observable/never.ts", "../../rxjs/src/internal/util/argsOrArgArray.ts", "../../rxjs/src/internal/operators/filter.ts", "../../rxjs/src/internal/operators/bufferTime.ts", "../../rxjs/src/internal/operators/catchError.ts", "../../rxjs/src/internal/operators/scanInternals.ts", "../../rxjs/src/internal/operators/take.ts", "../../rxjs/src/internal/operators/distinct.ts", "../../rxjs/src/internal/operators/distinctUntilChanged.ts", "../../rxjs/src/internal/operators/endWith.ts", "../../rxjs/src/internal/operators/finalize.ts", "../../rxjs/src/internal/operators/merge.ts", "../../rxjs/src/internal/operators/mergeWith.ts", "../../rxjs/src/internal/operators/repeat.ts", "../../rxjs/src/internal/operators/scan.ts", "../../rxjs/src/internal/operators/share.ts", "../../rxjs/src/internal/operators/switchMap.ts", "../../rxjs/src/internal/operators/takeUntil.ts", "../../rxjs/src/internal/operators/tap.ts", "../../applesauce-core/dist/event-store/event-store.js", "../../applesauce-core/dist/helpers/tags.js", "../../applesauce-core/dist/helpers/delete.js", "../../applesauce-core/dist/helpers/cache.js", "../../applesauce-core/dist/helpers/event.js", "../../applesauce-core/dist/helpers/time.js", "../../applesauce-core/dist/helpers/expiration.js", "../../applesauce-core/dist/helpers/filter.js", "../../applesauce-core/dist/helpers/encrypted-content.js", "../../applesauce-core/dist/helpers/hidden-content.js", "../../applesauce-core/dist/helpers/url.js", "../../applesauce-core/dist/helpers/groups.js", "../../applesauce-core/dist/helpers/hidden-tags.js", "../../applesauce-core/dist/helpers/event-tags.js", "../../nostr-tools/lib/esm/nip19.js", "../../applesauce-core/dist/helpers/relays.js", "../../applesauce-core/dist/helpers/string.js", "../../@noble/hashes/src/crypto.ts", "../../@noble/hashes/src/utils.ts", "../../applesauce-core/dist/helpers/pointers.js", "../../applesauce-core/dist/helpers/blossom.js", "../../applesauce-core/dist/models/blossom.js", "../../nostr-tools/lib/esm/utils.js", "../../applesauce-core/dist/helpers/index.js", "../../applesauce-core/dist/helpers/profile.js", "../../applesauce-core/dist/helpers/app-handlers.js", "../../applesauce-core/dist/helpers/article.js", "../../applesauce-core/dist/helpers/bolt11.js", "../../applesauce-core/dist/helpers/bookmarks.js", "../../applesauce-core/dist/helpers/calendar-event.js", "../../applesauce-core/dist/helpers/calendar-rsvp.js", "../../applesauce-core/dist/helpers/calendar.js", "../../applesauce-core/dist/helpers/channels.js", "../../applesauce-core/dist/helpers/external-id.js", "../../applesauce-core/dist/helpers/comment.js", "../../applesauce-core/dist/helpers/contacts.js", "../../applesauce-core/dist/helpers/content.js", "../../nostr-tools/lib/esm/nip05.js", "../../applesauce-core/dist/helpers/dns-identity.js", "../../applesauce-core/dist/helpers/emoji.js", "../../applesauce-core/dist/logger.js", "../../applesauce-core/dist/helpers/lru.js", "../../applesauce-core/dist/event-store/event-set.js", "../../applesauce-core/dist/helpers/gift-wraps.js", "../../applesauce-core/dist/helpers/encrypted-content-cache.js", "../../applesauce-core/dist/helpers/encryption.js", "../../applesauce-core/dist/helpers/event-cache.js", "../../applesauce-core/dist/helpers/file-metadata.js", "../../applesauce-core/dist/helpers/hashtag.js", "../../applesauce-core/dist/helpers/highlight.js", "../../applesauce-core/dist/helpers/json.js", "../../applesauce-core/dist/helpers/legacy-messages.js", "../../applesauce-core/dist/helpers/lists.js", "../../@scure/base/index.ts", "../../applesauce-core/dist/helpers/lnurl.js", "../../applesauce-core/dist/helpers/mailboxes.js", "../../applesauce-core/dist/helpers/messages.js", "../../applesauce-core/dist/helpers/mutes.js", "../../applesauce-core/dist/helpers/picture-post.js", "../../applesauce-core/dist/helpers/poll.js", "../../applesauce-core/dist/helpers/reactions.js", "../../applesauce-core/dist/helpers/reports.js", "../../applesauce-core/dist/helpers/share.js", "../../applesauce-core/dist/helpers/stream-chat.js", "../../applesauce-core/dist/helpers/stream.js", "../../applesauce-core/dist/helpers/threading.js", "../../applesauce-core/dist/helpers/user-status.js", "../../applesauce-core/dist/helpers/wrapped-messages.js", "../../applesauce-core/dist/helpers/zap.js", "../../applesauce-core/dist/observable/claim-events.js", "../../applesauce-core/dist/observable/claim-latest.js", "../../applesauce-core/dist/observable/with-immediate-value.js", "../../applesauce-core/dist/models/common.js", "../../applesauce-core/dist/observable/defined.js", "../../applesauce-core/dist/observable/get-observable-value.js", "../../applesauce-core/dist/observable/map-events-timeline.js", "../../applesauce-core/dist/observable/map-events-to-store.js", "../../applesauce-core/dist/observable/simple-timeout.js", "../../applesauce-core/dist/observable/watch-event-updates.js", "../../applesauce-core/dist/models/contacts.js", "../../applesauce-core/dist/models/index.js", "../../applesauce-core/dist/models/bookmarks.js", "../../applesauce-core/dist/models/calendar.js", "../../applesauce-core/dist/models/channels.js", "../../applesauce-core/dist/models/comments.js", "../../applesauce-core/dist/models/encrypted-content.js", "../../applesauce-core/dist/models/gift-wrap.js", "../../applesauce-core/dist/models/legacy-messages.js", "../../applesauce-core/dist/models/mailboxes.js", "../../applesauce-core/dist/models/mutes.js", "../../applesauce-core/dist/models/pins.js", "../../applesauce-core/dist/models/profile.js", "../../applesauce-core/dist/models/reactions.js", "../../applesauce-core/dist/models/relays.js", "../../applesauce-core/dist/models/thread.js", "../../applesauce-core/dist/models/wrapped-messages.js", "../../applesauce-core/dist/models/zaps.js"], - "sourcesContent": ["'use strict';\n\nfunction pad (hash, len) {\n while (hash.length < len) {\n hash = '0' + hash;\n }\n return hash;\n}\n\nfunction fold (hash, text) {\n var i;\n var chr;\n var len;\n if (text.length === 0) {\n return hash;\n }\n for (i = 0, len = text.length; i < len; i++) {\n chr = text.charCodeAt(i);\n hash = ((hash << 5) - hash) + chr;\n hash |= 0;\n }\n return hash < 0 ? hash * -2 : hash;\n}\n\nfunction foldObject (hash, o, seen) {\n return Object.keys(o).sort().reduce(foldKey, hash);\n function foldKey (hash, key) {\n return foldValue(hash, o[key], key, seen);\n }\n}\n\nfunction foldValue (input, value, key, seen) {\n var hash = fold(fold(fold(input, key), toString(value)), typeof value);\n if (value === null) {\n return fold(hash, 'null');\n }\n if (value === undefined) {\n return fold(hash, 'undefined');\n }\n if (typeof value === 'object' || typeof value === 'function') {\n if (seen.indexOf(value) !== -1) {\n return fold(hash, '[Circular]' + key);\n }\n seen.push(value);\n\n var objHash = foldObject(hash, value, seen)\n\n if (!('valueOf' in value) || typeof value.valueOf !== 'function') {\n return objHash;\n }\n\n try {\n return fold(objHash, String(value.valueOf()))\n } catch (err) {\n return fold(objHash, '[valueOf exception]' + (err.stack || err.message))\n }\n }\n return fold(hash, value.toString());\n}\n\nfunction toString (o) {\n return Object.prototype.toString.call(o);\n}\n\nfunction sum (o) {\n return pad(foldValue(0, o, '', []).toString(16), 8);\n}\n\nmodule.exports = sum;\n", "'use strict';\n\n// do not edit .js files directly - edit src/index.jst\n\n\n\nmodule.exports = function equal(a, b) {\n if (a === b) return true;\n\n if (a && b && typeof a == 'object' && typeof b == 'object') {\n if (a.constructor !== b.constructor) return false;\n\n var length, i, keys;\n if (Array.isArray(a)) {\n length = a.length;\n if (length != b.length) return false;\n for (i = length; i-- !== 0;)\n if (!equal(a[i], b[i])) return false;\n return true;\n }\n\n\n\n if (a.constructor === RegExp) return a.source === b.source && a.flags === b.flags;\n if (a.valueOf !== Object.prototype.valueOf) return a.valueOf() === b.valueOf();\n if (a.toString !== Object.prototype.toString) return a.toString() === b.toString();\n\n keys = Object.keys(a);\n length = keys.length;\n if (length !== Object.keys(b).length) return false;\n\n for (i = length; i-- !== 0;)\n if (!Object.prototype.hasOwnProperty.call(b, keys[i])) return false;\n\n for (i = length; i-- !== 0;) {\n var key = keys[i];\n\n if (!equal(a[key], b[key])) return false;\n }\n\n return true;\n }\n\n // true if both NaN, false otherwise\n return a!==a && b!==b;\n};\n", "\"use strict\";\n/*! scure-base - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.bytes = exports.stringToBytes = exports.str = exports.bytesToString = exports.hex = exports.utf8 = exports.bech32m = exports.bech32 = exports.base58check = exports.base58xmr = exports.base58xrp = exports.base58flickr = exports.base58 = exports.base64url = exports.base64 = exports.base32crockford = exports.base32hex = exports.base32 = exports.base16 = exports.utils = exports.assertNumber = void 0;\nfunction assertNumber(n) {\n if (!Number.isSafeInteger(n))\n throw new Error(`Wrong integer: ${n}`);\n}\nexports.assertNumber = assertNumber;\nfunction chain(...args) {\n const wrap = (a, b) => (c) => a(b(c));\n const encode = Array.from(args)\n .reverse()\n .reduce((acc, i) => (acc ? wrap(acc, i.encode) : i.encode), undefined);\n const decode = args.reduce((acc, i) => (acc ? wrap(acc, i.decode) : i.decode), undefined);\n return { encode, decode };\n}\nfunction alphabet(alphabet) {\n return {\n encode: (digits) => {\n if (!Array.isArray(digits) || (digits.length && typeof digits[0] !== 'number'))\n throw new Error('alphabet.encode input should be an array of numbers');\n return digits.map((i) => {\n assertNumber(i);\n if (i < 0 || i >= alphabet.length)\n throw new Error(`Digit index outside alphabet: ${i} (alphabet: ${alphabet.length})`);\n return alphabet[i];\n });\n },\n decode: (input) => {\n if (!Array.isArray(input) || (input.length && typeof input[0] !== 'string'))\n throw new Error('alphabet.decode input should be array of strings');\n return input.map((letter) => {\n if (typeof letter !== 'string')\n throw new Error(`alphabet.decode: not string element=${letter}`);\n const index = alphabet.indexOf(letter);\n if (index === -1)\n throw new Error(`Unknown letter: \"${letter}\". Allowed: ${alphabet}`);\n return index;\n });\n },\n };\n}\nfunction join(separator = '') {\n if (typeof separator !== 'string')\n throw new Error('join separator should be string');\n return {\n encode: (from) => {\n if (!Array.isArray(from) || (from.length && typeof from[0] !== 'string'))\n throw new Error('join.encode input should be array of strings');\n for (let i of from)\n if (typeof i !== 'string')\n throw new Error(`join.encode: non-string input=${i}`);\n return from.join(separator);\n },\n decode: (to) => {\n if (typeof to !== 'string')\n throw new Error('join.decode input should be string');\n return to.split(separator);\n },\n };\n}\nfunction padding(bits, chr = '=') {\n assertNumber(bits);\n if (typeof chr !== 'string')\n throw new Error('padding chr should be string');\n return {\n encode(data) {\n if (!Array.isArray(data) || (data.length && typeof data[0] !== 'string'))\n throw new Error('padding.encode input should be array of strings');\n for (let i of data)\n if (typeof i !== 'string')\n throw new Error(`padding.encode: non-string input=${i}`);\n while ((data.length * bits) % 8)\n data.push(chr);\n return data;\n },\n decode(input) {\n if (!Array.isArray(input) || (input.length && typeof input[0] !== 'string'))\n throw new Error('padding.encode input should be array of strings');\n for (let i of input)\n if (typeof i !== 'string')\n throw new Error(`padding.decode: non-string input=${i}`);\n let end = input.length;\n if ((end * bits) % 8)\n throw new Error('Invalid padding: string should have whole number of bytes');\n for (; end > 0 && input[end - 1] === chr; end--) {\n if (!(((end - 1) * bits) % 8))\n throw new Error('Invalid padding: string has too much padding');\n }\n return input.slice(0, end);\n },\n };\n}\nfunction normalize(fn) {\n if (typeof fn !== 'function')\n throw new Error('normalize fn should be function');\n return { encode: (from) => from, decode: (to) => fn(to) };\n}\nfunction convertRadix(data, from, to) {\n if (from < 2)\n throw new Error(`convertRadix: wrong from=${from}, base cannot be less than 2`);\n if (to < 2)\n throw new Error(`convertRadix: wrong to=${to}, base cannot be less than 2`);\n if (!Array.isArray(data))\n throw new Error('convertRadix: data should be array');\n if (!data.length)\n return [];\n let pos = 0;\n const res = [];\n const digits = Array.from(data);\n digits.forEach((d) => {\n assertNumber(d);\n if (d < 0 || d >= from)\n throw new Error(`Wrong integer: ${d}`);\n });\n while (true) {\n let carry = 0;\n let done = true;\n for (let i = pos; i < digits.length; i++) {\n const digit = digits[i];\n const digitBase = from * carry + digit;\n if (!Number.isSafeInteger(digitBase) ||\n (from * carry) / from !== carry ||\n digitBase - digit !== from * carry) {\n throw new Error('convertRadix: carry overflow');\n }\n carry = digitBase % to;\n digits[i] = Math.floor(digitBase / to);\n if (!Number.isSafeInteger(digits[i]) || digits[i] * to + carry !== digitBase)\n throw new Error('convertRadix: carry overflow');\n if (!done)\n continue;\n else if (!digits[i])\n pos = i;\n else\n done = false;\n }\n res.push(carry);\n if (done)\n break;\n }\n for (let i = 0; i < data.length - 1 && data[i] === 0; i++)\n res.push(0);\n return res.reverse();\n}\nconst gcd = (a, b) => (!b ? a : gcd(b, a % b));\nconst radix2carry = (from, to) => from + (to - gcd(from, to));\nfunction convertRadix2(data, from, to, padding) {\n if (!Array.isArray(data))\n throw new Error('convertRadix2: data should be array');\n if (from <= 0 || from > 32)\n throw new Error(`convertRadix2: wrong from=${from}`);\n if (to <= 0 || to > 32)\n throw new Error(`convertRadix2: wrong to=${to}`);\n if (radix2carry(from, to) > 32) {\n throw new Error(`convertRadix2: carry overflow from=${from} to=${to} carryBits=${radix2carry(from, to)}`);\n }\n let carry = 0;\n let pos = 0;\n const mask = 2 ** to - 1;\n const res = [];\n for (const n of data) {\n assertNumber(n);\n if (n >= 2 ** from)\n throw new Error(`convertRadix2: invalid data word=${n} from=${from}`);\n carry = (carry << from) | n;\n if (pos + from > 32)\n throw new Error(`convertRadix2: carry overflow pos=${pos} from=${from}`);\n pos += from;\n for (; pos >= to; pos -= to)\n res.push(((carry >> (pos - to)) & mask) >>> 0);\n carry &= 2 ** pos - 1;\n }\n carry = (carry << (to - pos)) & mask;\n if (!padding && pos >= from)\n throw new Error('Excess padding');\n if (!padding && carry)\n throw new Error(`Non-zero padding: ${carry}`);\n if (padding && pos > 0)\n res.push(carry >>> 0);\n return res;\n}\nfunction radix(num) {\n assertNumber(num);\n return {\n encode: (bytes) => {\n if (!(bytes instanceof Uint8Array))\n throw new Error('radix.encode input should be Uint8Array');\n return convertRadix(Array.from(bytes), 2 ** 8, num);\n },\n decode: (digits) => {\n if (!Array.isArray(digits) || (digits.length && typeof digits[0] !== 'number'))\n throw new Error('radix.decode input should be array of strings');\n return Uint8Array.from(convertRadix(digits, num, 2 ** 8));\n },\n };\n}\nfunction radix2(bits, revPadding = false) {\n assertNumber(bits);\n if (bits <= 0 || bits > 32)\n throw new Error('radix2: bits should be in (0..32]');\n if (radix2carry(8, bits) > 32 || radix2carry(bits, 8) > 32)\n throw new Error('radix2: carry overflow');\n return {\n encode: (bytes) => {\n if (!(bytes instanceof Uint8Array))\n throw new Error('radix2.encode input should be Uint8Array');\n return convertRadix2(Array.from(bytes), 8, bits, !revPadding);\n },\n decode: (digits) => {\n if (!Array.isArray(digits) || (digits.length && typeof digits[0] !== 'number'))\n throw new Error('radix2.decode input should be array of strings');\n return Uint8Array.from(convertRadix2(digits, bits, 8, revPadding));\n },\n };\n}\nfunction unsafeWrapper(fn) {\n if (typeof fn !== 'function')\n throw new Error('unsafeWrapper fn should be function');\n return function (...args) {\n try {\n return fn.apply(null, args);\n }\n catch (e) { }\n };\n}\nfunction checksum(len, fn) {\n assertNumber(len);\n if (typeof fn !== 'function')\n throw new Error('checksum fn should be function');\n return {\n encode(data) {\n if (!(data instanceof Uint8Array))\n throw new Error('checksum.encode: input should be Uint8Array');\n const checksum = fn(data).slice(0, len);\n const res = new Uint8Array(data.length + len);\n res.set(data);\n res.set(checksum, data.length);\n return res;\n },\n decode(data) {\n if (!(data instanceof Uint8Array))\n throw new Error('checksum.decode: input should be Uint8Array');\n const payload = data.slice(0, -len);\n const newChecksum = fn(payload).slice(0, len);\n const oldChecksum = data.slice(-len);\n for (let i = 0; i < len; i++)\n if (newChecksum[i] !== oldChecksum[i])\n throw new Error('Invalid checksum');\n return payload;\n },\n };\n}\nexports.utils = { alphabet, chain, checksum, radix, radix2, join, padding };\nexports.base16 = chain(radix2(4), alphabet('0123456789ABCDEF'), join(''));\nexports.base32 = chain(radix2(5), alphabet('ABCDEFGHIJKLMNOPQRSTUVWXYZ234567'), padding(5), join(''));\nexports.base32hex = chain(radix2(5), alphabet('0123456789ABCDEFGHIJKLMNOPQRSTUV'), padding(5), join(''));\nexports.base32crockford = chain(radix2(5), alphabet('0123456789ABCDEFGHJKMNPQRSTVWXYZ'), join(''), normalize((s) => s.toUpperCase().replace(/O/g, '0').replace(/[IL]/g, '1')));\nexports.base64 = chain(radix2(6), alphabet('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'), padding(6), join(''));\nexports.base64url = chain(radix2(6), alphabet('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_'), padding(6), join(''));\nconst genBase58 = (abc) => chain(radix(58), alphabet(abc), join(''));\nexports.base58 = genBase58('123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz');\nexports.base58flickr = genBase58('123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ');\nexports.base58xrp = genBase58('rpshnaf39wBUDNEGHJKLM4PQRST7VWXYZ2bcdeCg65jkm8oFqi1tuvAxyz');\nconst XMR_BLOCK_LEN = [0, 2, 3, 5, 6, 7, 9, 10, 11];\nexports.base58xmr = {\n encode(data) {\n let res = '';\n for (let i = 0; i < data.length; i += 8) {\n const block = data.subarray(i, i + 8);\n res += exports.base58.encode(block).padStart(XMR_BLOCK_LEN[block.length], '1');\n }\n return res;\n },\n decode(str) {\n let res = [];\n for (let i = 0; i < str.length; i += 11) {\n const slice = str.slice(i, i + 11);\n const blockLen = XMR_BLOCK_LEN.indexOf(slice.length);\n const block = exports.base58.decode(slice);\n for (let j = 0; j < block.length - blockLen; j++) {\n if (block[j] !== 0)\n throw new Error('base58xmr: wrong padding');\n }\n res = res.concat(Array.from(block.slice(block.length - blockLen)));\n }\n return Uint8Array.from(res);\n },\n};\nconst base58check = (sha256) => chain(checksum(4, (data) => sha256(sha256(data))), exports.base58);\nexports.base58check = base58check;\nconst BECH_ALPHABET = chain(alphabet('qpzry9x8gf2tvdw0s3jn54khce6mua7l'), join(''));\nconst POLYMOD_GENERATORS = [0x3b6a57b2, 0x26508e6d, 0x1ea119fa, 0x3d4233dd, 0x2a1462b3];\nfunction bech32Polymod(pre) {\n const b = pre >> 25;\n let chk = (pre & 0x1ffffff) << 5;\n for (let i = 0; i < POLYMOD_GENERATORS.length; i++) {\n if (((b >> i) & 1) === 1)\n chk ^= POLYMOD_GENERATORS[i];\n }\n return chk;\n}\nfunction bechChecksum(prefix, words, encodingConst = 1) {\n const len = prefix.length;\n let chk = 1;\n for (let i = 0; i < len; i++) {\n const c = prefix.charCodeAt(i);\n if (c < 33 || c > 126)\n throw new Error(`Invalid prefix (${prefix})`);\n chk = bech32Polymod(chk) ^ (c >> 5);\n }\n chk = bech32Polymod(chk);\n for (let i = 0; i < len; i++)\n chk = bech32Polymod(chk) ^ (prefix.charCodeAt(i) & 0x1f);\n for (let v of words)\n chk = bech32Polymod(chk) ^ v;\n for (let i = 0; i < 6; i++)\n chk = bech32Polymod(chk);\n chk ^= encodingConst;\n return BECH_ALPHABET.encode(convertRadix2([chk % 2 ** 30], 30, 5, false));\n}\nfunction genBech32(encoding) {\n const ENCODING_CONST = encoding === 'bech32' ? 1 : 0x2bc830a3;\n const _words = radix2(5);\n const fromWords = _words.decode;\n const toWords = _words.encode;\n const fromWordsUnsafe = unsafeWrapper(fromWords);\n function encode(prefix, words, limit = 90) {\n if (typeof prefix !== 'string')\n throw new Error(`bech32.encode prefix should be string, not ${typeof prefix}`);\n if (!Array.isArray(words) || (words.length && typeof words[0] !== 'number'))\n throw new Error(`bech32.encode words should be array of numbers, not ${typeof words}`);\n const actualLength = prefix.length + 7 + words.length;\n if (limit !== false && actualLength > limit)\n throw new TypeError(`Length ${actualLength} exceeds limit ${limit}`);\n prefix = prefix.toLowerCase();\n return `${prefix}1${BECH_ALPHABET.encode(words)}${bechChecksum(prefix, words, ENCODING_CONST)}`;\n }\n function decode(str, limit = 90) {\n if (typeof str !== 'string')\n throw new Error(`bech32.decode input should be string, not ${typeof str}`);\n if (str.length < 8 || (limit !== false && str.length > limit))\n throw new TypeError(`Wrong string length: ${str.length} (${str}). Expected (8..${limit})`);\n const lowered = str.toLowerCase();\n if (str !== lowered && str !== str.toUpperCase())\n throw new Error(`String must be lowercase or uppercase`);\n str = lowered;\n const sepIndex = str.lastIndexOf('1');\n if (sepIndex === 0 || sepIndex === -1)\n throw new Error(`Letter \"1\" must be present between prefix and data only`);\n const prefix = str.slice(0, sepIndex);\n const _words = str.slice(sepIndex + 1);\n if (_words.length < 6)\n throw new Error('Data must be at least 6 characters long');\n const words = BECH_ALPHABET.decode(_words).slice(0, -6);\n const sum = bechChecksum(prefix, words, ENCODING_CONST);\n if (!_words.endsWith(sum))\n throw new Error(`Invalid checksum in ${str}: expected \"${sum}\"`);\n return { prefix, words };\n }\n const decodeUnsafe = unsafeWrapper(decode);\n function decodeToBytes(str) {\n const { prefix, words } = decode(str, false);\n return { prefix, words, bytes: fromWords(words) };\n }\n return { encode, decode, decodeToBytes, decodeUnsafe, fromWords, fromWordsUnsafe, toWords };\n}\nexports.bech32 = genBech32('bech32');\nexports.bech32m = genBech32('bech32m');\nexports.utf8 = {\n encode: (data) => new TextDecoder().decode(data),\n decode: (str) => new TextEncoder().encode(str),\n};\nexports.hex = chain(radix2(4), alphabet('0123456789abcdef'), join(''), normalize((s) => {\n if (typeof s !== 'string' || s.length % 2)\n throw new TypeError(`hex.decode: expected string, got ${typeof s} with length ${s.length}`);\n return s.toLowerCase();\n}));\nconst CODERS = {\n utf8: exports.utf8, hex: exports.hex, base16: exports.base16, base32: exports.base32, base64: exports.base64, base64url: exports.base64url, base58: exports.base58, base58xmr: exports.base58xmr\n};\nconst coderTypeError = `Invalid encoding type. Available types: ${Object.keys(CODERS).join(', ')}`;\nconst bytesToString = (type, bytes) => {\n if (typeof type !== 'string' || !CODERS.hasOwnProperty(type))\n throw new TypeError(coderTypeError);\n if (!(bytes instanceof Uint8Array))\n throw new TypeError('bytesToString() expects Uint8Array');\n return CODERS[type].encode(bytes);\n};\nexports.bytesToString = bytesToString;\nexports.str = exports.bytesToString;\nconst stringToBytes = (type, str) => {\n if (!CODERS.hasOwnProperty(type))\n throw new TypeError(coderTypeError);\n if (typeof str !== 'string')\n throw new TypeError('stringToBytes() expects string');\n return CODERS[type].decode(str);\n};\nexports.stringToBytes = stringToBytes;\nexports.bytes = exports.stringToBytes;\n", "const {bech32, hex, utf8} = require('@scure/base')\n\n// defaults for encode; default timestamp is current time at call\nconst DEFAULTNETWORK = {\n // default network is bitcoin\n bech32: 'bc',\n pubKeyHash: 0x00,\n scriptHash: 0x05,\n validWitnessVersions: [0]\n}\nconst TESTNETWORK = {\n bech32: 'tb',\n pubKeyHash: 0x6f,\n scriptHash: 0xc4,\n validWitnessVersions: [0]\n}\nconst SIGNETNETWORK = {\n bech32: 'tbs',\n pubKeyHash: 0x6f,\n scriptHash: 0xc4,\n validWitnessVersions: [0]\n}\nconst REGTESTNETWORK = {\n bech32: 'bcrt',\n pubKeyHash: 0x6f,\n scriptHash: 0xc4,\n validWitnessVersions: [0]\n}\nconst SIMNETWORK = {\n bech32: 'sb',\n pubKeyHash: 0x3f,\n scriptHash: 0x7b,\n validWitnessVersions: [0]\n}\n\nconst FEATUREBIT_ORDER = [\n 'option_data_loss_protect',\n 'initial_routing_sync',\n 'option_upfront_shutdown_script',\n 'gossip_queries',\n 'var_onion_optin',\n 'gossip_queries_ex',\n 'option_static_remotekey',\n 'payment_secret',\n 'basic_mpp',\n 'option_support_large_channel'\n]\n\nconst DIVISORS = {\n m: BigInt(1e3),\n u: BigInt(1e6),\n n: BigInt(1e9),\n p: BigInt(1e12)\n}\n\nconst MAX_MILLISATS = BigInt('2100000000000000000')\n\nconst MILLISATS_PER_BTC = BigInt(1e11)\n\nconst TAGCODES = {\n payment_hash: 1,\n payment_secret: 16,\n description: 13,\n payee: 19,\n description_hash: 23, // commit to longer descriptions (used by lnurl-pay)\n expiry: 6, // default: 3600 (1 hour)\n min_final_cltv_expiry: 24, // default: 9\n fallback_address: 9,\n route_hint: 3, // for extra routing info (private etc.)\n feature_bits: 5,\n metadata: 27\n}\n\n// reverse the keys and values of TAGCODES and insert into TAGNAMES\nconst TAGNAMES = {}\nfor (let i = 0, keys = Object.keys(TAGCODES); i < keys.length; i++) {\n const currentName = keys[i]\n const currentCode = TAGCODES[keys[i]].toString()\n TAGNAMES[currentCode] = currentName\n}\n\nconst TAGPARSERS = {\n 1: words => hex.encode(bech32.fromWordsUnsafe(words)), // 256 bits\n 16: words => hex.encode(bech32.fromWordsUnsafe(words)), // 256 bits\n 13: words => utf8.encode(bech32.fromWordsUnsafe(words)), // string variable length\n 19: words => hex.encode(bech32.fromWordsUnsafe(words)), // 264 bits\n 23: words => hex.encode(bech32.fromWordsUnsafe(words)), // 256 bits\n 27: words => hex.encode(bech32.fromWordsUnsafe(words)), // variable\n 6: wordsToIntBE, // default: 3600 (1 hour)\n 24: wordsToIntBE, // default: 9\n 3: routingInfoParser, // for extra routing info (private etc.)\n 5: featureBitsParser // keep feature bits as array of 5 bit words\n}\n\nfunction getUnknownParser(tagCode) {\n return words => ({\n tagCode: parseInt(tagCode),\n words: bech32.encode('unknown', words, Number.MAX_SAFE_INTEGER)\n })\n}\n\nfunction wordsToIntBE(words) {\n return words.reverse().reduce((total, item, index) => {\n return total + item * Math.pow(32, index)\n }, 0)\n}\n\n// first convert from words to buffer, trimming padding where necessary\n// parse in 51 byte chunks. See encoder for details.\nfunction routingInfoParser(words) {\n const routes = []\n let pubkey,\n shortChannelId,\n feeBaseMSats,\n feeProportionalMillionths,\n cltvExpiryDelta\n let routesBuffer = bech32.fromWordsUnsafe(words)\n while (routesBuffer.length > 0) {\n pubkey = hex.encode(routesBuffer.slice(0, 33)) // 33 bytes\n shortChannelId = hex.encode(routesBuffer.slice(33, 41)) // 8 bytes\n feeBaseMSats = parseInt(hex.encode(routesBuffer.slice(41, 45)), 16) // 4 bytes\n feeProportionalMillionths = parseInt(\n hex.encode(routesBuffer.slice(45, 49)),\n 16\n ) // 4 bytes\n cltvExpiryDelta = parseInt(hex.encode(routesBuffer.slice(49, 51)), 16) // 2 bytes\n\n routesBuffer = routesBuffer.slice(51)\n\n routes.push({\n pubkey,\n short_channel_id: shortChannelId,\n fee_base_msat: feeBaseMSats,\n fee_proportional_millionths: feeProportionalMillionths,\n cltv_expiry_delta: cltvExpiryDelta\n })\n }\n return routes\n}\n\nfunction featureBitsParser(words) {\n const bools = words\n .slice()\n .reverse()\n .map(word => [\n !!(word & 0b1),\n !!(word & 0b10),\n !!(word & 0b100),\n !!(word & 0b1000),\n !!(word & 0b10000)\n ])\n .reduce((finalArr, itemArr) => finalArr.concat(itemArr), [])\n while (bools.length < FEATUREBIT_ORDER.length * 2) {\n bools.push(false)\n }\n\n const featureBits = {}\n\n FEATUREBIT_ORDER.forEach((featureName, index) => {\n let status\n if (bools[index * 2]) {\n status = 'required'\n } else if (bools[index * 2 + 1]) {\n status = 'supported'\n } else {\n status = 'unsupported'\n }\n featureBits[featureName] = status\n })\n\n const extraBits = bools.slice(FEATUREBIT_ORDER.length * 2)\n featureBits.extra_bits = {\n start_bit: FEATUREBIT_ORDER.length * 2,\n bits: extraBits,\n has_required: extraBits.reduce(\n (result, bit, index) =>\n index % 2 !== 0 ? result || false : result || bit,\n false\n )\n }\n\n return featureBits\n}\n\nfunction hrpToMillisat(hrpString, outputString) {\n let divisor, value\n if (hrpString.slice(-1).match(/^[munp]$/)) {\n divisor = hrpString.slice(-1)\n value = hrpString.slice(0, -1)\n } else if (hrpString.slice(-1).match(/^[^munp0-9]$/)) {\n throw new Error('Not a valid multiplier for the amount')\n } else {\n value = hrpString\n }\n\n if (!value.match(/^\\d+$/))\n throw new Error('Not a valid human readable amount')\n\n const valueBN = BigInt(value)\n\n const millisatoshisBN = divisor\n ? (valueBN * MILLISATS_PER_BTC) / DIVISORS[divisor]\n : valueBN * MILLISATS_PER_BTC\n\n if (\n (divisor === 'p' && !(valueBN % BigInt(10) === BigInt(0))) ||\n millisatoshisBN > MAX_MILLISATS\n ) {\n throw new Error('Amount is outside of valid range')\n }\n\n return outputString ? millisatoshisBN.toString() : millisatoshisBN\n}\n\n// decode will only have extra comments that aren't covered in encode comments.\n// also if anything is hard to read I'll comment.\nfunction decode(paymentRequest, network) {\n if (typeof paymentRequest !== 'string')\n throw new Error('Lightning Payment Request must be string')\n if (paymentRequest.slice(0, 2).toLowerCase() !== 'ln')\n throw new Error('Not a proper lightning payment request')\n\n const sections = []\n const decoded = bech32.decode(paymentRequest, Number.MAX_SAFE_INTEGER)\n paymentRequest = paymentRequest.toLowerCase()\n const prefix = decoded.prefix\n let words = decoded.words\n let letters = paymentRequest.slice(prefix.length + 1)\n let sigWords = words.slice(-104)\n words = words.slice(0, -104)\n\n // Without reverse lookups, can't say that the multipier at the end must\n // have a number before it, so instead we parse, and if the second group\n // doesn't have anything, there's a good chance the last letter of the\n // coin type got captured by the third group, so just re-regex without\n // the number.\n let prefixMatches = prefix.match(/^ln(\\S+?)(\\d*)([a-zA-Z]?)$/)\n if (prefixMatches && !prefixMatches[2])\n prefixMatches = prefix.match(/^ln(\\S+)$/)\n if (!prefixMatches) {\n throw new Error('Not a proper lightning payment request')\n }\n\n // \"ln\" section\n sections.push({\n name: 'lightning_network',\n letters: 'ln'\n })\n\n // \"bc\" section\n const bech32Prefix = prefixMatches[1]\n let coinNetwork\n if (!network) {\n switch (bech32Prefix) {\n case DEFAULTNETWORK.bech32:\n coinNetwork = DEFAULTNETWORK\n break\n case TESTNETWORK.bech32:\n coinNetwork = TESTNETWORK\n break\n case SIGNETNETWORK.bech32:\n coinNetwork = SIGNETNETWORK\n break\n case REGTESTNETWORK.bech32:\n coinNetwork = REGTESTNETWORK\n break\n case SIMNETWORK.bech32:\n coinNetwork = SIMNETWORK\n break\n }\n } else {\n if (\n network.bech32 === undefined ||\n network.pubKeyHash === undefined ||\n network.scriptHash === undefined ||\n !Array.isArray(network.validWitnessVersions)\n )\n throw new Error('Invalid network')\n coinNetwork = network\n }\n if (!coinNetwork || coinNetwork.bech32 !== bech32Prefix) {\n throw new Error('Unknown coin bech32 prefix')\n }\n sections.push({\n name: 'coin_network',\n letters: bech32Prefix,\n value: coinNetwork\n })\n\n // amount section\n const value = prefixMatches[2]\n let millisatoshis\n if (value) {\n const divisor = prefixMatches[3]\n millisatoshis = hrpToMillisat(value + divisor, true)\n sections.push({\n name: 'amount',\n letters: prefixMatches[2] + prefixMatches[3],\n value: millisatoshis\n })\n } else {\n millisatoshis = null\n }\n\n // \"1\" separator\n sections.push({\n name: 'separator',\n letters: '1'\n })\n\n // timestamp\n const timestamp = wordsToIntBE(words.slice(0, 7))\n words = words.slice(7) // trim off the left 7 words\n sections.push({\n name: 'timestamp',\n letters: letters.slice(0, 7),\n value: timestamp\n })\n letters = letters.slice(7)\n\n let tagName, parser, tagLength, tagWords\n // we have no tag count to go on, so just keep hacking off words\n // until we have none.\n while (words.length > 0) {\n const tagCode = words[0].toString()\n tagName = TAGNAMES[tagCode] || 'unknown_tag'\n parser = TAGPARSERS[tagCode] || getUnknownParser(tagCode)\n words = words.slice(1)\n\n tagLength = wordsToIntBE(words.slice(0, 2))\n words = words.slice(2)\n\n tagWords = words.slice(0, tagLength)\n words = words.slice(tagLength)\n\n sections.push({\n name: tagName,\n tag: letters[0],\n letters: letters.slice(0, 1 + 2 + tagLength),\n value: parser(tagWords) // see: parsers for more comments\n })\n letters = letters.slice(1 + 2 + tagLength)\n }\n\n // signature\n sections.push({\n name: 'signature',\n letters: letters.slice(0, 104),\n value: hex.encode(bech32.fromWordsUnsafe(sigWords))\n })\n letters = letters.slice(104)\n\n // checksum\n sections.push({\n name: 'checksum',\n letters: letters\n })\n\n let result = {\n paymentRequest,\n sections,\n\n get expiry() {\n let exp = sections.find(s => s.name === 'expiry')\n if (exp) return getValue('timestamp') + exp.value\n },\n\n get route_hints() {\n return sections.filter(s => s.name === 'route_hint').map(s => s.value)\n }\n }\n\n for (let name in TAGCODES) {\n if (name === 'route_hint') {\n // route hints can be multiple, so this won't work for them\n continue\n }\n\n Object.defineProperty(result, name, {\n get() {\n return getValue(name)\n }\n })\n }\n\n return result\n\n function getValue(name) {\n let section = sections.find(s => s.name === name)\n return section ? section.value : undefined\n }\n}\n\nmodule.exports = {\n decode,\n hrpToMillisat\n}\n", "/**\n * Helpers.\n */\n\nvar s = 1000;\nvar m = s * 60;\nvar h = m * 60;\nvar d = h * 24;\nvar w = d * 7;\nvar y = d * 365.25;\n\n/**\n * Parse or format the given `val`.\n *\n * Options:\n *\n * - `long` verbose formatting [false]\n *\n * @param {String|Number} val\n * @param {Object} [options]\n * @throws {Error} throw an error if val is not a non-empty string or a number\n * @return {String|Number}\n * @api public\n */\n\nmodule.exports = function (val, options) {\n options = options || {};\n var type = typeof val;\n if (type === 'string' && val.length > 0) {\n return parse(val);\n } else if (type === 'number' && isFinite(val)) {\n return options.long ? fmtLong(val) : fmtShort(val);\n }\n throw new Error(\n 'val is not a non-empty string or a valid number. val=' +\n JSON.stringify(val)\n );\n};\n\n/**\n * Parse the given `str` and return milliseconds.\n *\n * @param {String} str\n * @return {Number}\n * @api private\n */\n\nfunction parse(str) {\n str = String(str);\n if (str.length > 100) {\n return;\n }\n var match = /^(-?(?:\\d+)?\\.?\\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(\n str\n );\n if (!match) {\n return;\n }\n var n = parseFloat(match[1]);\n var type = (match[2] || 'ms').toLowerCase();\n switch (type) {\n case 'years':\n case 'year':\n case 'yrs':\n case 'yr':\n case 'y':\n return n * y;\n case 'weeks':\n case 'week':\n case 'w':\n return n * w;\n case 'days':\n case 'day':\n case 'd':\n return n * d;\n case 'hours':\n case 'hour':\n case 'hrs':\n case 'hr':\n case 'h':\n return n * h;\n case 'minutes':\n case 'minute':\n case 'mins':\n case 'min':\n case 'm':\n return n * m;\n case 'seconds':\n case 'second':\n case 'secs':\n case 'sec':\n case 's':\n return n * s;\n case 'milliseconds':\n case 'millisecond':\n case 'msecs':\n case 'msec':\n case 'ms':\n return n;\n default:\n return undefined;\n }\n}\n\n/**\n * Short format for `ms`.\n *\n * @param {Number} ms\n * @return {String}\n * @api private\n */\n\nfunction fmtShort(ms) {\n var msAbs = Math.abs(ms);\n if (msAbs >= d) {\n return Math.round(ms / d) + 'd';\n }\n if (msAbs >= h) {\n return Math.round(ms / h) + 'h';\n }\n if (msAbs >= m) {\n return Math.round(ms / m) + 'm';\n }\n if (msAbs >= s) {\n return Math.round(ms / s) + 's';\n }\n return ms + 'ms';\n}\n\n/**\n * Long format for `ms`.\n *\n * @param {Number} ms\n * @return {String}\n * @api private\n */\n\nfunction fmtLong(ms) {\n var msAbs = Math.abs(ms);\n if (msAbs >= d) {\n return plural(ms, msAbs, d, 'day');\n }\n if (msAbs >= h) {\n return plural(ms, msAbs, h, 'hour');\n }\n if (msAbs >= m) {\n return plural(ms, msAbs, m, 'minute');\n }\n if (msAbs >= s) {\n return plural(ms, msAbs, s, 'second');\n }\n return ms + ' ms';\n}\n\n/**\n * Pluralization helper.\n */\n\nfunction plural(ms, msAbs, n, name) {\n var isPlural = msAbs >= n * 1.5;\n return Math.round(ms / n) + ' ' + name + (isPlural ? 's' : '');\n}\n", "\n/**\n * This is the common logic for both the Node.js and web browser\n * implementations of `debug()`.\n */\n\nfunction setup(env) {\n\tcreateDebug.debug = createDebug;\n\tcreateDebug.default = createDebug;\n\tcreateDebug.coerce = coerce;\n\tcreateDebug.disable = disable;\n\tcreateDebug.enable = enable;\n\tcreateDebug.enabled = enabled;\n\tcreateDebug.humanize = require('ms');\n\tcreateDebug.destroy = destroy;\n\n\tObject.keys(env).forEach(key => {\n\t\tcreateDebug[key] = env[key];\n\t});\n\n\t/**\n\t* The currently active debug mode names, and names to skip.\n\t*/\n\n\tcreateDebug.names = [];\n\tcreateDebug.skips = [];\n\n\t/**\n\t* Map of special \"%n\" handling functions, for the debug \"format\" argument.\n\t*\n\t* Valid key names are a single, lower or upper-case letter, i.e. \"n\" and \"N\".\n\t*/\n\tcreateDebug.formatters = {};\n\n\t/**\n\t* Selects a color for a debug namespace\n\t* @param {String} namespace The namespace string for the debug instance to be colored\n\t* @return {Number|String} An ANSI color code for the given namespace\n\t* @api private\n\t*/\n\tfunction selectColor(namespace) {\n\t\tlet hash = 0;\n\n\t\tfor (let i = 0; i < namespace.length; i++) {\n\t\t\thash = ((hash << 5) - hash) + namespace.charCodeAt(i);\n\t\t\thash |= 0; // Convert to 32bit integer\n\t\t}\n\n\t\treturn createDebug.colors[Math.abs(hash) % createDebug.colors.length];\n\t}\n\tcreateDebug.selectColor = selectColor;\n\n\t/**\n\t* Create a debugger with the given `namespace`.\n\t*\n\t* @param {String} namespace\n\t* @return {Function}\n\t* @api public\n\t*/\n\tfunction createDebug(namespace) {\n\t\tlet prevTime;\n\t\tlet enableOverride = null;\n\t\tlet namespacesCache;\n\t\tlet enabledCache;\n\n\t\tfunction debug(...args) {\n\t\t\t// Disabled?\n\t\t\tif (!debug.enabled) {\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tconst self = debug;\n\n\t\t\t// Set `diff` timestamp\n\t\t\tconst curr = Number(new Date());\n\t\t\tconst ms = curr - (prevTime || curr);\n\t\t\tself.diff = ms;\n\t\t\tself.prev = prevTime;\n\t\t\tself.curr = curr;\n\t\t\tprevTime = curr;\n\n\t\t\targs[0] = createDebug.coerce(args[0]);\n\n\t\t\tif (typeof args[0] !== 'string') {\n\t\t\t\t// Anything else let's inspect with %O\n\t\t\t\targs.unshift('%O');\n\t\t\t}\n\n\t\t\t// Apply any `formatters` transformations\n\t\t\tlet index = 0;\n\t\t\targs[0] = args[0].replace(/%([a-zA-Z%])/g, (match, format) => {\n\t\t\t\t// If we encounter an escaped % then don't increase the array index\n\t\t\t\tif (match === '%%') {\n\t\t\t\t\treturn '%';\n\t\t\t\t}\n\t\t\t\tindex++;\n\t\t\t\tconst formatter = createDebug.formatters[format];\n\t\t\t\tif (typeof formatter === 'function') {\n\t\t\t\t\tconst val = args[index];\n\t\t\t\t\tmatch = formatter.call(self, val);\n\n\t\t\t\t\t// Now we need to remove `args[index]` since it's inlined in the `format`\n\t\t\t\t\targs.splice(index, 1);\n\t\t\t\t\tindex--;\n\t\t\t\t}\n\t\t\t\treturn match;\n\t\t\t});\n\n\t\t\t// Apply env-specific formatting (colors, etc.)\n\t\t\tcreateDebug.formatArgs.call(self, args);\n\n\t\t\tconst logFn = self.log || createDebug.log;\n\t\t\tlogFn.apply(self, args);\n\t\t}\n\n\t\tdebug.namespace = namespace;\n\t\tdebug.useColors = createDebug.useColors();\n\t\tdebug.color = createDebug.selectColor(namespace);\n\t\tdebug.extend = extend;\n\t\tdebug.destroy = createDebug.destroy; // XXX Temporary. Will be removed in the next major release.\n\n\t\tObject.defineProperty(debug, 'enabled', {\n\t\t\tenumerable: true,\n\t\t\tconfigurable: false,\n\t\t\tget: () => {\n\t\t\t\tif (enableOverride !== null) {\n\t\t\t\t\treturn enableOverride;\n\t\t\t\t}\n\t\t\t\tif (namespacesCache !== createDebug.namespaces) {\n\t\t\t\t\tnamespacesCache = createDebug.namespaces;\n\t\t\t\t\tenabledCache = createDebug.enabled(namespace);\n\t\t\t\t}\n\n\t\t\t\treturn enabledCache;\n\t\t\t},\n\t\t\tset: v => {\n\t\t\t\tenableOverride = v;\n\t\t\t}\n\t\t});\n\n\t\t// Env-specific initialization logic for debug instances\n\t\tif (typeof createDebug.init === 'function') {\n\t\t\tcreateDebug.init(debug);\n\t\t}\n\n\t\treturn debug;\n\t}\n\n\tfunction extend(namespace, delimiter) {\n\t\tconst newDebug = createDebug(this.namespace + (typeof delimiter === 'undefined' ? ':' : delimiter) + namespace);\n\t\tnewDebug.log = this.log;\n\t\treturn newDebug;\n\t}\n\n\t/**\n\t* Enables a debug mode by namespaces. This can include modes\n\t* separated by a colon and wildcards.\n\t*\n\t* @param {String} namespaces\n\t* @api public\n\t*/\n\tfunction enable(namespaces) {\n\t\tcreateDebug.save(namespaces);\n\t\tcreateDebug.namespaces = namespaces;\n\n\t\tcreateDebug.names = [];\n\t\tcreateDebug.skips = [];\n\n\t\tconst split = (typeof namespaces === 'string' ? namespaces : '')\n\t\t\t.trim()\n\t\t\t.replace(/\\s+/g, ',')\n\t\t\t.split(',')\n\t\t\t.filter(Boolean);\n\n\t\tfor (const ns of split) {\n\t\t\tif (ns[0] === '-') {\n\t\t\t\tcreateDebug.skips.push(ns.slice(1));\n\t\t\t} else {\n\t\t\t\tcreateDebug.names.push(ns);\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Checks if the given string matches a namespace template, honoring\n\t * asterisks as wildcards.\n\t *\n\t * @param {String} search\n\t * @param {String} template\n\t * @return {Boolean}\n\t */\n\tfunction matchesTemplate(search, template) {\n\t\tlet searchIndex = 0;\n\t\tlet templateIndex = 0;\n\t\tlet starIndex = -1;\n\t\tlet matchIndex = 0;\n\n\t\twhile (searchIndex < search.length) {\n\t\t\tif (templateIndex < template.length && (template[templateIndex] === search[searchIndex] || template[templateIndex] === '*')) {\n\t\t\t\t// Match character or proceed with wildcard\n\t\t\t\tif (template[templateIndex] === '*') {\n\t\t\t\t\tstarIndex = templateIndex;\n\t\t\t\t\tmatchIndex = searchIndex;\n\t\t\t\t\ttemplateIndex++; // Skip the '*'\n\t\t\t\t} else {\n\t\t\t\t\tsearchIndex++;\n\t\t\t\t\ttemplateIndex++;\n\t\t\t\t}\n\t\t\t} else if (starIndex !== -1) { // eslint-disable-line no-negated-condition\n\t\t\t\t// Backtrack to the last '*' and try to match more characters\n\t\t\t\ttemplateIndex = starIndex + 1;\n\t\t\t\tmatchIndex++;\n\t\t\t\tsearchIndex = matchIndex;\n\t\t\t} else {\n\t\t\t\treturn false; // No match\n\t\t\t}\n\t\t}\n\n\t\t// Handle trailing '*' in template\n\t\twhile (templateIndex < template.length && template[templateIndex] === '*') {\n\t\t\ttemplateIndex++;\n\t\t}\n\n\t\treturn templateIndex === template.length;\n\t}\n\n\t/**\n\t* Disable debug output.\n\t*\n\t* @return {String} namespaces\n\t* @api public\n\t*/\n\tfunction disable() {\n\t\tconst namespaces = [\n\t\t\t...createDebug.names,\n\t\t\t...createDebug.skips.map(namespace => '-' + namespace)\n\t\t].join(',');\n\t\tcreateDebug.enable('');\n\t\treturn namespaces;\n\t}\n\n\t/**\n\t* Returns true if the given mode name is enabled, false otherwise.\n\t*\n\t* @param {String} name\n\t* @return {Boolean}\n\t* @api public\n\t*/\n\tfunction enabled(name) {\n\t\tfor (const skip of createDebug.skips) {\n\t\t\tif (matchesTemplate(name, skip)) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\n\t\tfor (const ns of createDebug.names) {\n\t\t\tif (matchesTemplate(name, ns)) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\n\t\treturn false;\n\t}\n\n\t/**\n\t* Coerce `val`.\n\t*\n\t* @param {Mixed} val\n\t* @return {Mixed}\n\t* @api private\n\t*/\n\tfunction coerce(val) {\n\t\tif (val instanceof Error) {\n\t\t\treturn val.stack || val.message;\n\t\t}\n\t\treturn val;\n\t}\n\n\t/**\n\t* XXX DO NOT USE. This is a temporary stub function.\n\t* XXX It WILL be removed in the next major release.\n\t*/\n\tfunction destroy() {\n\t\tconsole.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.');\n\t}\n\n\tcreateDebug.enable(createDebug.load());\n\n\treturn createDebug;\n}\n\nmodule.exports = setup;\n", "/* eslint-env browser */\n\n/**\n * This is the web browser implementation of `debug()`.\n */\n\nexports.formatArgs = formatArgs;\nexports.save = save;\nexports.load = load;\nexports.useColors = useColors;\nexports.storage = localstorage();\nexports.destroy = (() => {\n\tlet warned = false;\n\n\treturn () => {\n\t\tif (!warned) {\n\t\t\twarned = true;\n\t\t\tconsole.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.');\n\t\t}\n\t};\n})();\n\n/**\n * Colors.\n */\n\nexports.colors = [\n\t'#0000CC',\n\t'#0000FF',\n\t'#0033CC',\n\t'#0033FF',\n\t'#0066CC',\n\t'#0066FF',\n\t'#0099CC',\n\t'#0099FF',\n\t'#00CC00',\n\t'#00CC33',\n\t'#00CC66',\n\t'#00CC99',\n\t'#00CCCC',\n\t'#00CCFF',\n\t'#3300CC',\n\t'#3300FF',\n\t'#3333CC',\n\t'#3333FF',\n\t'#3366CC',\n\t'#3366FF',\n\t'#3399CC',\n\t'#3399FF',\n\t'#33CC00',\n\t'#33CC33',\n\t'#33CC66',\n\t'#33CC99',\n\t'#33CCCC',\n\t'#33CCFF',\n\t'#6600CC',\n\t'#6600FF',\n\t'#6633CC',\n\t'#6633FF',\n\t'#66CC00',\n\t'#66CC33',\n\t'#9900CC',\n\t'#9900FF',\n\t'#9933CC',\n\t'#9933FF',\n\t'#99CC00',\n\t'#99CC33',\n\t'#CC0000',\n\t'#CC0033',\n\t'#CC0066',\n\t'#CC0099',\n\t'#CC00CC',\n\t'#CC00FF',\n\t'#CC3300',\n\t'#CC3333',\n\t'#CC3366',\n\t'#CC3399',\n\t'#CC33CC',\n\t'#CC33FF',\n\t'#CC6600',\n\t'#CC6633',\n\t'#CC9900',\n\t'#CC9933',\n\t'#CCCC00',\n\t'#CCCC33',\n\t'#FF0000',\n\t'#FF0033',\n\t'#FF0066',\n\t'#FF0099',\n\t'#FF00CC',\n\t'#FF00FF',\n\t'#FF3300',\n\t'#FF3333',\n\t'#FF3366',\n\t'#FF3399',\n\t'#FF33CC',\n\t'#FF33FF',\n\t'#FF6600',\n\t'#FF6633',\n\t'#FF9900',\n\t'#FF9933',\n\t'#FFCC00',\n\t'#FFCC33'\n];\n\n/**\n * Currently only WebKit-based Web Inspectors, Firefox >= v31,\n * and the Firebug extension (any Firefox version) are known\n * to support \"%c\" CSS customizations.\n *\n * TODO: add a `localStorage` variable to explicitly enable/disable colors\n */\n\n// eslint-disable-next-line complexity\nfunction useColors() {\n\t// NB: In an Electron preload script, document will be defined but not fully\n\t// initialized. Since we know we're in Chrome, we'll just detect this case\n\t// explicitly\n\tif (typeof window !== 'undefined' && window.process && (window.process.type === 'renderer' || window.process.__nwjs)) {\n\t\treturn true;\n\t}\n\n\t// Internet Explorer and Edge do not support colors.\n\tif (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\\/(\\d+)/)) {\n\t\treturn false;\n\t}\n\n\tlet m;\n\n\t// Is webkit? http://stackoverflow.com/a/16459606/376773\n\t// document is undefined in react-native: https://github.com/facebook/react-native/pull/1632\n\t// eslint-disable-next-line no-return-assign\n\treturn (typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance) ||\n\t\t// Is firebug? http://stackoverflow.com/a/398120/376773\n\t\t(typeof window !== 'undefined' && window.console && (window.console.firebug || (window.console.exception && window.console.table))) ||\n\t\t// Is firefox >= v31?\n\t\t// https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages\n\t\t(typeof navigator !== 'undefined' && navigator.userAgent && (m = navigator.userAgent.toLowerCase().match(/firefox\\/(\\d+)/)) && parseInt(m[1], 10) >= 31) ||\n\t\t// Double check webkit in userAgent just in case we are in a worker\n\t\t(typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\\/(\\d+)/));\n}\n\n/**\n * Colorize log arguments if enabled.\n *\n * @api public\n */\n\nfunction formatArgs(args) {\n\targs[0] = (this.useColors ? '%c' : '') +\n\t\tthis.namespace +\n\t\t(this.useColors ? ' %c' : ' ') +\n\t\targs[0] +\n\t\t(this.useColors ? '%c ' : ' ') +\n\t\t'+' + module.exports.humanize(this.diff);\n\n\tif (!this.useColors) {\n\t\treturn;\n\t}\n\n\tconst c = 'color: ' + this.color;\n\targs.splice(1, 0, c, 'color: inherit');\n\n\t// The final \"%c\" is somewhat tricky, because there could be other\n\t// arguments passed either before or after the %c, so we need to\n\t// figure out the correct index to insert the CSS into\n\tlet index = 0;\n\tlet lastC = 0;\n\targs[0].replace(/%[a-zA-Z%]/g, match => {\n\t\tif (match === '%%') {\n\t\t\treturn;\n\t\t}\n\t\tindex++;\n\t\tif (match === '%c') {\n\t\t\t// We only are interested in the *last* %c\n\t\t\t// (the user may have provided their own)\n\t\t\tlastC = index;\n\t\t}\n\t});\n\n\targs.splice(lastC, 0, c);\n}\n\n/**\n * Invokes `console.debug()` when available.\n * No-op when `console.debug` is not a \"function\".\n * If `console.debug` is not available, falls back\n * to `console.log`.\n *\n * @api public\n */\nexports.log = console.debug || console.log || (() => {});\n\n/**\n * Save `namespaces`.\n *\n * @param {String} namespaces\n * @api private\n */\nfunction save(namespaces) {\n\ttry {\n\t\tif (namespaces) {\n\t\t\texports.storage.setItem('debug', namespaces);\n\t\t} else {\n\t\t\texports.storage.removeItem('debug');\n\t\t}\n\t} catch (error) {\n\t\t// Swallow\n\t\t// XXX (@Qix-) should we be logging these?\n\t}\n}\n\n/**\n * Load `namespaces`.\n *\n * @return {String} returns the previously persisted debug modes\n * @api private\n */\nfunction load() {\n\tlet r;\n\ttry {\n\t\tr = exports.storage.getItem('debug') || exports.storage.getItem('DEBUG') ;\n\t} catch (error) {\n\t\t// Swallow\n\t\t// XXX (@Qix-) should we be logging these?\n\t}\n\n\t// If debug isn't set in LS, and we're in Electron, try to load $DEBUG\n\tif (!r && typeof process !== 'undefined' && 'env' in process) {\n\t\tr = process.env.DEBUG;\n\t}\n\n\treturn r;\n}\n\n/**\n * Localstorage attempts to return the localstorage.\n *\n * This is necessary because safari throws\n * when a user disables cookies/localstorage\n * and you attempt to access it.\n *\n * @return {LocalStorage}\n * @api private\n */\n\nfunction localstorage() {\n\ttry {\n\t\t// TVMLKit (Apple TV JS Runtime) does not have a window object, just localStorage in the global context\n\t\t// The Browser also has localStorage in the global context.\n\t\treturn localStorage;\n\t} catch (error) {\n\t\t// Swallow\n\t\t// XXX (@Qix-) should we be logging these?\n\t}\n}\n\nmodule.exports = require('./common')(exports);\n\nconst {formatters} = module.exports;\n\n/**\n * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default.\n */\n\nformatters.j = function (v) {\n\ttry {\n\t\treturn JSON.stringify(v);\n\t} catch (error) {\n\t\treturn '[UnexpectedJSONParseError]: ' + error.message;\n\t}\n};\n", "function number(n: number) {\n if (!Number.isSafeInteger(n) || n < 0) throw new Error(`Wrong positive integer: ${n}`);\n}\n\nfunction bool(b: boolean) {\n if (typeof b !== 'boolean') throw new Error(`Expected boolean, not ${b}`);\n}\n\nfunction bytes(b: Uint8Array | undefined, ...lengths: number[]) {\n if (!(b instanceof Uint8Array)) throw new Error('Expected Uint8Array');\n if (lengths.length > 0 && !lengths.includes(b.length))\n throw new Error(`Expected Uint8Array of length ${lengths}, not of length=${b.length}`);\n}\n\ntype Hash = {\n (data: Uint8Array): Uint8Array;\n blockLen: number;\n outputLen: number;\n create: any;\n};\nfunction hash(hash: Hash) {\n if (typeof hash !== 'function' || typeof hash.create !== 'function')\n throw new Error('Hash should be wrapped by utils.wrapConstructor');\n number(hash.outputLen);\n number(hash.blockLen);\n}\n\nfunction exists(instance: any, checkFinished = true) {\n if (instance.destroyed) throw new Error('Hash instance has been destroyed');\n if (checkFinished && instance.finished) throw new Error('Hash#digest() has already been called');\n}\nfunction output(out: any, instance: any) {\n bytes(out);\n const min = instance.outputLen;\n if (out.length < min) {\n throw new Error(`digestInto() expects output buffer of length at least ${min}`);\n }\n}\n\nexport { number, bool, bytes, hash, exists, output };\n\nconst assert = { number, bool, bytes, hash, exists, output };\nexport default assert;\n", "// We use WebCrypto aka globalThis.crypto, which exists in browsers and node.js 16+.\n// See utils.ts for details.\ndeclare const globalThis: Record | undefined;\nexport const crypto =\n typeof globalThis === 'object' && 'crypto' in globalThis ? globalThis.crypto : undefined;\n", "/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */\n\n// We use WebCrypto aka globalThis.crypto, which exists in browsers and node.js 16+.\n// node.js versions earlier than v19 don't declare it in global scope.\n// For node.js, package.json#exports field mapping rewrites import\n// from `crypto` to `cryptoNode`, which imports native module.\n// Makes the utils un-importable in browsers without a bundler.\n// Once node.js 18 is deprecated, we can just drop the import.\nimport { crypto } from '@noble/hashes/crypto';\n\n// prettier-ignore\nexport type TypedArray = Int8Array | Uint8ClampedArray | Uint8Array |\n Uint16Array | Int16Array | Uint32Array | Int32Array;\n\nconst u8a = (a: any): a is Uint8Array => a instanceof Uint8Array;\n// Cast array to different type\nexport const u8 = (arr: TypedArray) => new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength);\nexport const u32 = (arr: TypedArray) =>\n new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4));\n\n// Cast array to view\nexport const createView = (arr: TypedArray) =>\n new DataView(arr.buffer, arr.byteOffset, arr.byteLength);\n\n// The rotate right (circular right shift) operation for uint32\nexport const rotr = (word: number, shift: number) => (word << (32 - shift)) | (word >>> shift);\n\n// big-endian hardware is rare. Just in case someone still decides to run hashes:\n// early-throw an error because we don't support BE yet.\nexport const isLE = new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44;\nif (!isLE) throw new Error('Non little-endian hardware is not supported');\n\nconst hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) =>\n i.toString(16).padStart(2, '0')\n);\n/**\n * @example bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])) // 'cafe0123'\n */\nexport function bytesToHex(bytes: Uint8Array): string {\n if (!u8a(bytes)) throw new Error('Uint8Array expected');\n // pre-caching improves the speed 6x\n let hex = '';\n for (let i = 0; i < bytes.length; i++) {\n hex += hexes[bytes[i]];\n }\n return hex;\n}\n\n/**\n * @example hexToBytes('cafe0123') // Uint8Array.from([0xca, 0xfe, 0x01, 0x23])\n */\nexport function hexToBytes(hex: string): Uint8Array {\n if (typeof hex !== 'string') throw new Error('hex string expected, got ' + typeof hex);\n const len = hex.length;\n if (len % 2) throw new Error('padded hex string expected, got unpadded hex of length ' + len);\n const array = new Uint8Array(len / 2);\n for (let i = 0; i < array.length; i++) {\n const j = i * 2;\n const hexByte = hex.slice(j, j + 2);\n const byte = Number.parseInt(hexByte, 16);\n if (Number.isNaN(byte) || byte < 0) throw new Error('Invalid byte sequence');\n array[i] = byte;\n }\n return array;\n}\n\n// There is no setImmediate in browser and setTimeout is slow.\n// call of async fn will return Promise, which will be fullfiled only on\n// next scheduler queue processing step and this is exactly what we need.\nexport const nextTick = async () => {};\n\n// Returns control to thread each 'tick' ms to avoid blocking\nexport async function asyncLoop(iters: number, tick: number, cb: (i: number) => void) {\n let ts = Date.now();\n for (let i = 0; i < iters; i++) {\n cb(i);\n // Date.now() is not monotonic, so in case if clock goes backwards we return return control too\n const diff = Date.now() - ts;\n if (diff >= 0 && diff < tick) continue;\n await nextTick();\n ts += diff;\n }\n}\n\n// Global symbols in both browsers and Node.js since v11\n// See https://github.com/microsoft/TypeScript/issues/31535\ndeclare const TextEncoder: any;\n\n/**\n * @example utf8ToBytes('abc') // new Uint8Array([97, 98, 99])\n */\nexport function utf8ToBytes(str: string): Uint8Array {\n if (typeof str !== 'string') throw new Error(`utf8ToBytes expected string, got ${typeof str}`);\n return new Uint8Array(new TextEncoder().encode(str)); // https://bugzil.la/1681809\n}\n\nexport type Input = Uint8Array | string;\n/**\n * Normalizes (non-hex) string or Uint8Array to Uint8Array.\n * Warning: when Uint8Array is passed, it would NOT get copied.\n * Keep in mind for future mutable operations.\n */\nexport function toBytes(data: Input): Uint8Array {\n if (typeof data === 'string') data = utf8ToBytes(data);\n if (!u8a(data)) throw new Error(`expected Uint8Array, got ${typeof data}`);\n return data;\n}\n\n/**\n * Copies several Uint8Arrays into one.\n */\nexport function concatBytes(...arrays: Uint8Array[]): Uint8Array {\n const r = new Uint8Array(arrays.reduce((sum, a) => sum + a.length, 0));\n let pad = 0; // walk through each item, ensure they have proper type\n arrays.forEach((a) => {\n if (!u8a(a)) throw new Error('Uint8Array expected');\n r.set(a, pad);\n pad += a.length;\n });\n return r;\n}\n\n// For runtime check if class implements interface\nexport abstract class Hash> {\n abstract blockLen: number; // Bytes per block\n abstract outputLen: number; // Bytes in output\n abstract update(buf: Input): this;\n // Writes digest into buf\n abstract digestInto(buf: Uint8Array): void;\n abstract digest(): Uint8Array;\n /**\n * Resets internal state. Makes Hash instance unusable.\n * Reset is impossible for keyed hashes if key is consumed into state. If digest is not consumed\n * by user, they will need to manually call `destroy()` when zeroing is necessary.\n */\n abstract destroy(): void;\n /**\n * Clones hash instance. Unsafe: doesn't check whether `to` is valid. Can be used as `clone()`\n * when no options are passed.\n * Reasons to use `_cloneInto` instead of clone: 1) performance 2) reuse instance => all internal\n * buffers are overwritten => causes buffer overwrite which is used for digest in some cases.\n * There are no guarantees for clean-up because it's impossible in JS.\n */\n abstract _cloneInto(to?: T): T;\n // Safe version that clones internal state\n clone(): T {\n return this._cloneInto();\n }\n}\n\n/**\n * XOF: streaming API to read digest in chunks.\n * Same as 'squeeze' in keccak/k12 and 'seek' in blake3, but more generic name.\n * When hash used in XOF mode it is up to user to call '.destroy' afterwards, since we cannot\n * destroy state, next call can require more bytes.\n */\nexport type HashXOF> = Hash & {\n xof(bytes: number): Uint8Array; // Read 'bytes' bytes from digest stream\n xofInto(buf: Uint8Array): Uint8Array; // read buf.length bytes from digest stream into buf\n};\n\nconst toStr = {}.toString;\ntype EmptyObj = {};\nexport function checkOpts(\n defaults: T1,\n opts?: T2\n): T1 & T2 {\n if (opts !== undefined && toStr.call(opts) !== '[object Object]')\n throw new Error('Options should be object or undefined');\n const merged = Object.assign(defaults, opts);\n return merged as T1 & T2;\n}\n\nexport type CHash = ReturnType;\n\nexport function wrapConstructor>(hashCons: () => Hash) {\n const hashC = (msg: Input): Uint8Array => hashCons().update(toBytes(msg)).digest();\n const tmp = hashCons();\n hashC.outputLen = tmp.outputLen;\n hashC.blockLen = tmp.blockLen;\n hashC.create = () => hashCons();\n return hashC;\n}\n\nexport function wrapConstructorWithOpts, T extends Object>(\n hashCons: (opts?: T) => Hash\n) {\n const hashC = (msg: Input, opts?: T): Uint8Array => hashCons(opts).update(toBytes(msg)).digest();\n const tmp = hashCons({} as T);\n hashC.outputLen = tmp.outputLen;\n hashC.blockLen = tmp.blockLen;\n hashC.create = (opts: T) => hashCons(opts);\n return hashC;\n}\n\nexport function wrapXOFConstructorWithOpts, T extends Object>(\n hashCons: (opts?: T) => HashXOF\n) {\n const hashC = (msg: Input, opts?: T): Uint8Array => hashCons(opts).update(toBytes(msg)).digest();\n const tmp = hashCons({} as T);\n hashC.outputLen = tmp.outputLen;\n hashC.blockLen = tmp.blockLen;\n hashC.create = (opts: T) => hashCons(opts);\n return hashC;\n}\n\n/**\n * Secure PRNG. Uses `crypto.getRandomValues`, which defers to OS.\n */\nexport function randomBytes(bytesLength = 32): Uint8Array {\n if (crypto && typeof crypto.getRandomValues === 'function') {\n return crypto.getRandomValues(new Uint8Array(bytesLength));\n }\n throw new Error('crypto.getRandomValues must be defined');\n}\n", "import { exists, output } from './_assert.js';\nimport { Hash, createView, Input, toBytes } from './utils.js';\n\n// Polyfill for Safari 14\nfunction setBigUint64(view: DataView, byteOffset: number, value: bigint, isLE: boolean): void {\n if (typeof view.setBigUint64 === 'function') return view.setBigUint64(byteOffset, value, isLE);\n const _32n = BigInt(32);\n const _u32_max = BigInt(0xffffffff);\n const wh = Number((value >> _32n) & _u32_max);\n const wl = Number(value & _u32_max);\n const h = isLE ? 4 : 0;\n const l = isLE ? 0 : 4;\n view.setUint32(byteOffset + h, wh, isLE);\n view.setUint32(byteOffset + l, wl, isLE);\n}\n\n// Base SHA2 class (RFC 6234)\nexport abstract class SHA2> extends Hash {\n protected abstract process(buf: DataView, offset: number): void;\n protected abstract get(): number[];\n protected abstract set(...args: number[]): void;\n abstract destroy(): void;\n protected abstract roundClean(): void;\n // For partial updates less than block size\n protected buffer: Uint8Array;\n protected view: DataView;\n protected finished = false;\n protected length = 0;\n protected pos = 0;\n protected destroyed = false;\n\n constructor(\n readonly blockLen: number,\n public outputLen: number,\n readonly padOffset: number,\n readonly isLE: boolean\n ) {\n super();\n this.buffer = new Uint8Array(blockLen);\n this.view = createView(this.buffer);\n }\n update(data: Input): this {\n exists(this);\n const { view, buffer, blockLen } = this;\n data = toBytes(data);\n const len = data.length;\n for (let pos = 0; pos < len; ) {\n const take = Math.min(blockLen - this.pos, len - pos);\n // Fast path: we have at least one block in input, cast it to view and process\n if (take === blockLen) {\n const dataView = createView(data);\n for (; blockLen <= len - pos; pos += blockLen) this.process(dataView, pos);\n continue;\n }\n buffer.set(data.subarray(pos, pos + take), this.pos);\n this.pos += take;\n pos += take;\n if (this.pos === blockLen) {\n this.process(view, 0);\n this.pos = 0;\n }\n }\n this.length += data.length;\n this.roundClean();\n return this;\n }\n digestInto(out: Uint8Array) {\n exists(this);\n output(out, this);\n this.finished = true;\n // Padding\n // We can avoid allocation of buffer for padding completely if it\n // was previously not allocated here. But it won't change performance.\n const { buffer, view, blockLen, isLE } = this;\n let { pos } = this;\n // append the bit '1' to the message\n buffer[pos++] = 0b10000000;\n this.buffer.subarray(pos).fill(0);\n // we have less than padOffset left in buffer, so we cannot put length in current block, need process it and pad again\n if (this.padOffset > blockLen - pos) {\n this.process(view, 0);\n pos = 0;\n }\n // Pad until full block byte with zeros\n for (let i = pos; i < blockLen; i++) buffer[i] = 0;\n // Note: sha512 requires length to be 128bit integer, but length in JS will overflow before that\n // You need to write around 2 exabytes (u64_max / 8 / (1024**6)) for this to happen.\n // So we just write lowest 64 bits of that value.\n setBigUint64(view, blockLen - 8, BigInt(this.length * 8), isLE);\n this.process(view, 0);\n const oview = createView(out);\n const len = this.outputLen;\n // NOTE: we do division by 4 later, which should be fused in single op with modulo by JIT\n if (len % 4) throw new Error('_sha2: outputLen should be aligned to 32bit');\n const outLen = len / 4;\n const state = this.get();\n if (outLen > state.length) throw new Error('_sha2: outputLen bigger than state');\n for (let i = 0; i < outLen; i++) oview.setUint32(4 * i, state[i], isLE);\n }\n digest() {\n const { buffer, outputLen } = this;\n this.digestInto(buffer);\n const res = buffer.slice(0, outputLen);\n this.destroy();\n return res;\n }\n _cloneInto(to?: T): T {\n to ||= new (this.constructor as any)() as T;\n to.set(...this.get());\n const { blockLen, buffer, length, finished, destroyed, pos } = this;\n to.length = length;\n to.pos = pos;\n to.finished = finished;\n to.destroyed = destroyed;\n if (length % blockLen) to.buffer.set(buffer);\n return to;\n }\n}\n", "import { SHA2 } from './_sha2.js';\nimport { rotr, wrapConstructor } from './utils.js';\n\n// SHA2-256 need to try 2^128 hashes to execute birthday attack.\n// BTC network is doing 2^67 hashes/sec as per early 2023.\n\n// Choice: a ? b : c\nconst Chi = (a: number, b: number, c: number) => (a & b) ^ (~a & c);\n// Majority function, true if any two inpust is true\nconst Maj = (a: number, b: number, c: number) => (a & b) ^ (a & c) ^ (b & c);\n\n// Round constants:\n// first 32 bits of the fractional parts of the cube roots of the first 64 primes 2..311)\n// prettier-ignore\nconst SHA256_K = /* @__PURE__ */new Uint32Array([\n 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,\n 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,\n 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,\n 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,\n 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,\n 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,\n 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,\n 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2\n]);\n\n// Initial state (first 32 bits of the fractional parts of the square roots of the first 8 primes 2..19):\n// prettier-ignore\nconst IV = /* @__PURE__ */new Uint32Array([\n 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19\n]);\n\n// Temporary buffer, not used to store anything between runs\n// Named this way because it matches specification.\nconst SHA256_W = /* @__PURE__ */ new Uint32Array(64);\nclass SHA256 extends SHA2 {\n // We cannot use array here since array allows indexing by variable\n // which means optimizer/compiler cannot use registers.\n A = IV[0] | 0;\n B = IV[1] | 0;\n C = IV[2] | 0;\n D = IV[3] | 0;\n E = IV[4] | 0;\n F = IV[5] | 0;\n G = IV[6] | 0;\n H = IV[7] | 0;\n\n constructor() {\n super(64, 32, 8, false);\n }\n protected get(): [number, number, number, number, number, number, number, number] {\n const { A, B, C, D, E, F, G, H } = this;\n return [A, B, C, D, E, F, G, H];\n }\n // prettier-ignore\n protected set(\n A: number, B: number, C: number, D: number, E: number, F: number, G: number, H: number\n ) {\n this.A = A | 0;\n this.B = B | 0;\n this.C = C | 0;\n this.D = D | 0;\n this.E = E | 0;\n this.F = F | 0;\n this.G = G | 0;\n this.H = H | 0;\n }\n protected process(view: DataView, offset: number): void {\n // Extend the first 16 words into the remaining 48 words w[16..63] of the message schedule array\n for (let i = 0; i < 16; i++, offset += 4) SHA256_W[i] = view.getUint32(offset, false);\n for (let i = 16; i < 64; i++) {\n const W15 = SHA256_W[i - 15];\n const W2 = SHA256_W[i - 2];\n const s0 = rotr(W15, 7) ^ rotr(W15, 18) ^ (W15 >>> 3);\n const s1 = rotr(W2, 17) ^ rotr(W2, 19) ^ (W2 >>> 10);\n SHA256_W[i] = (s1 + SHA256_W[i - 7] + s0 + SHA256_W[i - 16]) | 0;\n }\n // Compression function main loop, 64 rounds\n let { A, B, C, D, E, F, G, H } = this;\n for (let i = 0; i < 64; i++) {\n const sigma1 = rotr(E, 6) ^ rotr(E, 11) ^ rotr(E, 25);\n const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0;\n const sigma0 = rotr(A, 2) ^ rotr(A, 13) ^ rotr(A, 22);\n const T2 = (sigma0 + Maj(A, B, C)) | 0;\n H = G;\n G = F;\n F = E;\n E = (D + T1) | 0;\n D = C;\n C = B;\n B = A;\n A = (T1 + T2) | 0;\n }\n // Add the compressed chunk to the current hash value\n A = (A + this.A) | 0;\n B = (B + this.B) | 0;\n C = (C + this.C) | 0;\n D = (D + this.D) | 0;\n E = (E + this.E) | 0;\n F = (F + this.F) | 0;\n G = (G + this.G) | 0;\n H = (H + this.H) | 0;\n this.set(A, B, C, D, E, F, G, H);\n }\n protected roundClean() {\n SHA256_W.fill(0);\n }\n destroy() {\n this.set(0, 0, 0, 0, 0, 0, 0, 0);\n this.buffer.fill(0);\n }\n}\n// Constants from https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.180-4.pdf\nclass SHA224 extends SHA256 {\n A = 0xc1059ed8 | 0;\n B = 0x367cd507 | 0;\n C = 0x3070dd17 | 0;\n D = 0xf70e5939 | 0;\n E = 0xffc00b31 | 0;\n F = 0x68581511 | 0;\n G = 0x64f98fa7 | 0;\n H = 0xbefa4fa4 | 0;\n constructor() {\n super();\n this.outputLen = 28;\n }\n}\n\n/**\n * SHA2-256 hash function\n * @param message - data that would be hashed\n */\nexport const sha256 = /* @__PURE__ */ wrapConstructor(() => new SHA256());\nexport const sha224 = /* @__PURE__ */ wrapConstructor(() => new SHA224());\n", "/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\n// 100 lines of code in the file are duplicated from noble-hashes (utils).\n// This is OK: `abstract` directory does not use noble-hashes.\n// User may opt-in into using different hashing library. This way, noble-hashes\n// won't be included into their bundle.\nconst _0n = BigInt(0);\nconst _1n = BigInt(1);\nconst _2n = BigInt(2);\nconst u8a = (a: any): a is Uint8Array => a instanceof Uint8Array;\nexport type Hex = Uint8Array | string; // hex strings are accepted for simplicity\nexport type PrivKey = Hex | bigint; // bigints are accepted to ease learning curve\nexport type CHash = {\n (message: Uint8Array | string): Uint8Array;\n blockLen: number;\n outputLen: number;\n create(opts?: { dkLen?: number }): any; // For shake\n};\nexport type FHash = (message: Uint8Array | string) => Uint8Array;\n\nconst hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) =>\n i.toString(16).padStart(2, '0')\n);\n/**\n * @example bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])) // 'cafe0123'\n */\nexport function bytesToHex(bytes: Uint8Array): string {\n if (!u8a(bytes)) throw new Error('Uint8Array expected');\n // pre-caching improves the speed 6x\n let hex = '';\n for (let i = 0; i < bytes.length; i++) {\n hex += hexes[bytes[i]];\n }\n return hex;\n}\n\nexport function numberToHexUnpadded(num: number | bigint): string {\n const hex = num.toString(16);\n return hex.length & 1 ? `0${hex}` : hex;\n}\n\nexport function hexToNumber(hex: string): bigint {\n if (typeof hex !== 'string') throw new Error('hex string expected, got ' + typeof hex);\n // Big Endian\n return BigInt(hex === '' ? '0' : `0x${hex}`);\n}\n\n/**\n * @example hexToBytes('cafe0123') // Uint8Array.from([0xca, 0xfe, 0x01, 0x23])\n */\nexport function hexToBytes(hex: string): Uint8Array {\n if (typeof hex !== 'string') throw new Error('hex string expected, got ' + typeof hex);\n const len = hex.length;\n if (len % 2) throw new Error('padded hex string expected, got unpadded hex of length ' + len);\n const array = new Uint8Array(len / 2);\n for (let i = 0; i < array.length; i++) {\n const j = i * 2;\n const hexByte = hex.slice(j, j + 2);\n const byte = Number.parseInt(hexByte, 16);\n if (Number.isNaN(byte) || byte < 0) throw new Error('Invalid byte sequence');\n array[i] = byte;\n }\n return array;\n}\n\n// BE: Big Endian, LE: Little Endian\nexport function bytesToNumberBE(bytes: Uint8Array): bigint {\n return hexToNumber(bytesToHex(bytes));\n}\nexport function bytesToNumberLE(bytes: Uint8Array): bigint {\n if (!u8a(bytes)) throw new Error('Uint8Array expected');\n return hexToNumber(bytesToHex(Uint8Array.from(bytes).reverse()));\n}\n\nexport function numberToBytesBE(n: number | bigint, len: number): Uint8Array {\n return hexToBytes(n.toString(16).padStart(len * 2, '0'));\n}\nexport function numberToBytesLE(n: number | bigint, len: number): Uint8Array {\n return numberToBytesBE(n, len).reverse();\n}\n// Unpadded, rarely used\nexport function numberToVarBytesBE(n: number | bigint): Uint8Array {\n return hexToBytes(numberToHexUnpadded(n));\n}\n\n/**\n * Takes hex string or Uint8Array, converts to Uint8Array.\n * Validates output length.\n * Will throw error for other types.\n * @param title descriptive title for an error e.g. 'private key'\n * @param hex hex string or Uint8Array\n * @param expectedLength optional, will compare to result array's length\n * @returns\n */\nexport function ensureBytes(title: string, hex: Hex, expectedLength?: number): Uint8Array {\n let res: Uint8Array;\n if (typeof hex === 'string') {\n try {\n res = hexToBytes(hex);\n } catch (e) {\n throw new Error(`${title} must be valid hex string, got \"${hex}\". Cause: ${e}`);\n }\n } else if (u8a(hex)) {\n // Uint8Array.from() instead of hash.slice() because node.js Buffer\n // is instance of Uint8Array, and its slice() creates **mutable** copy\n res = Uint8Array.from(hex);\n } else {\n throw new Error(`${title} must be hex string or Uint8Array`);\n }\n const len = res.length;\n if (typeof expectedLength === 'number' && len !== expectedLength)\n throw new Error(`${title} expected ${expectedLength} bytes, got ${len}`);\n return res;\n}\n\n/**\n * Copies several Uint8Arrays into one.\n */\nexport function concatBytes(...arrays: Uint8Array[]): Uint8Array {\n const r = new Uint8Array(arrays.reduce((sum, a) => sum + a.length, 0));\n let pad = 0; // walk through each item, ensure they have proper type\n arrays.forEach((a) => {\n if (!u8a(a)) throw new Error('Uint8Array expected');\n r.set(a, pad);\n pad += a.length;\n });\n return r;\n}\n\nexport function equalBytes(b1: Uint8Array, b2: Uint8Array) {\n // We don't care about timing attacks here\n if (b1.length !== b2.length) return false;\n for (let i = 0; i < b1.length; i++) if (b1[i] !== b2[i]) return false;\n return true;\n}\n\n// Global symbols in both browsers and Node.js since v11\n// See https://github.com/microsoft/TypeScript/issues/31535\ndeclare const TextEncoder: any;\n\n/**\n * @example utf8ToBytes('abc') // new Uint8Array([97, 98, 99])\n */\nexport function utf8ToBytes(str: string): Uint8Array {\n if (typeof str !== 'string') throw new Error(`utf8ToBytes expected string, got ${typeof str}`);\n return new Uint8Array(new TextEncoder().encode(str)); // https://bugzil.la/1681809\n}\n\n// Bit operations\n\n/**\n * Calculates amount of bits in a bigint.\n * Same as `n.toString(2).length`\n */\nexport function bitLen(n: bigint) {\n let len;\n for (len = 0; n > _0n; n >>= _1n, len += 1);\n return len;\n}\n\n/**\n * Gets single bit at position.\n * NOTE: first bit position is 0 (same as arrays)\n * Same as `!!+Array.from(n.toString(2)).reverse()[pos]`\n */\nexport function bitGet(n: bigint, pos: number) {\n return (n >> BigInt(pos)) & _1n;\n}\n\n/**\n * Sets single bit at position.\n */\nexport const bitSet = (n: bigint, pos: number, value: boolean) => {\n return n | ((value ? _1n : _0n) << BigInt(pos));\n};\n\n/**\n * Calculate mask for N bits. Not using ** operator with bigints because of old engines.\n * Same as BigInt(`0b${Array(i).fill('1').join('')}`)\n */\nexport const bitMask = (n: number) => (_2n << BigInt(n - 1)) - _1n;\n\n// DRBG\n\nconst u8n = (data?: any) => new Uint8Array(data); // creates Uint8Array\nconst u8fr = (arr: any) => Uint8Array.from(arr); // another shortcut\ntype Pred = (v: Uint8Array) => T | undefined;\n/**\n * Minimal HMAC-DRBG from NIST 800-90 for RFC6979 sigs.\n * @returns function that will call DRBG until 2nd arg returns something meaningful\n * @example\n * const drbg = createHmacDRBG(32, 32, hmac);\n * drbg(seed, bytesToKey); // bytesToKey must return Key or undefined\n */\nexport function createHmacDrbg(\n hashLen: number,\n qByteLen: number,\n hmacFn: (key: Uint8Array, ...messages: Uint8Array[]) => Uint8Array\n): (seed: Uint8Array, predicate: Pred) => T {\n if (typeof hashLen !== 'number' || hashLen < 2) throw new Error('hashLen must be a number');\n if (typeof qByteLen !== 'number' || qByteLen < 2) throw new Error('qByteLen must be a number');\n if (typeof hmacFn !== 'function') throw new Error('hmacFn must be a function');\n // Step B, Step C: set hashLen to 8*ceil(hlen/8)\n let v = u8n(hashLen); // Minimal non-full-spec HMAC-DRBG from NIST 800-90 for RFC6979 sigs.\n let k = u8n(hashLen); // Steps B and C of RFC6979 3.2: set hashLen, in our case always same\n let i = 0; // Iterations counter, will throw when over 1000\n const reset = () => {\n v.fill(1);\n k.fill(0);\n i = 0;\n };\n const h = (...b: Uint8Array[]) => hmacFn(k, v, ...b); // hmac(k)(v, ...values)\n const reseed = (seed = u8n()) => {\n // HMAC-DRBG reseed() function. Steps D-G\n k = h(u8fr([0x00]), seed); // k = hmac(k || v || 0x00 || seed)\n v = h(); // v = hmac(k || v)\n if (seed.length === 0) return;\n k = h(u8fr([0x01]), seed); // k = hmac(k || v || 0x01 || seed)\n v = h(); // v = hmac(k || v)\n };\n const gen = () => {\n // HMAC-DRBG generate() function\n if (i++ >= 1000) throw new Error('drbg: tried 1000 values');\n let len = 0;\n const out: Uint8Array[] = [];\n while (len < qByteLen) {\n v = h();\n const sl = v.slice();\n out.push(sl);\n len += v.length;\n }\n return concatBytes(...out);\n };\n const genUntil = (seed: Uint8Array, pred: Pred): T => {\n reset();\n reseed(seed); // Steps D-G\n let res: T | undefined = undefined; // Step H: grind until k is in [1..n-1]\n while (!(res = pred(gen()))) reseed();\n reset();\n return res;\n };\n return genUntil;\n}\n\n// Validating curves and fields\n\nconst validatorFns = {\n bigint: (val: any) => typeof val === 'bigint',\n function: (val: any) => typeof val === 'function',\n boolean: (val: any) => typeof val === 'boolean',\n string: (val: any) => typeof val === 'string',\n stringOrUint8Array: (val: any) => typeof val === 'string' || val instanceof Uint8Array,\n isSafeInteger: (val: any) => Number.isSafeInteger(val),\n array: (val: any) => Array.isArray(val),\n field: (val: any, object: any) => (object as any).Fp.isValid(val),\n hash: (val: any) => typeof val === 'function' && Number.isSafeInteger(val.outputLen),\n} as const;\ntype Validator = keyof typeof validatorFns;\ntype ValMap> = { [K in keyof T]?: Validator };\n// type Record = { [P in K]: T; }\n\nexport function validateObject>(\n object: T,\n validators: ValMap,\n optValidators: ValMap = {}\n) {\n const checkField = (fieldName: keyof T, type: Validator, isOptional: boolean) => {\n const checkVal = validatorFns[type];\n if (typeof checkVal !== 'function')\n throw new Error(`Invalid validator \"${type}\", expected function`);\n\n const val = object[fieldName as keyof typeof object];\n if (isOptional && val === undefined) return;\n if (!checkVal(val, object)) {\n throw new Error(\n `Invalid param ${String(fieldName)}=${val} (${typeof val}), expected ${type}`\n );\n }\n };\n for (const [fieldName, type] of Object.entries(validators)) checkField(fieldName, type!, false);\n for (const [fieldName, type] of Object.entries(optValidators)) checkField(fieldName, type!, true);\n return object;\n}\n// validate type tests\n// const o: { a: number; b: number; c: number } = { a: 1, b: 5, c: 6 };\n// const z0 = validateObject(o, { a: 'isSafeInteger' }, { c: 'bigint' }); // Ok!\n// // Should fail type-check\n// const z1 = validateObject(o, { a: 'tmp' }, { c: 'zz' });\n// const z2 = validateObject(o, { a: 'isSafeInteger' }, { c: 'zz' });\n// const z3 = validateObject(o, { test: 'boolean', z: 'bug' });\n// const z4 = validateObject(o, { a: 'boolean', z: 'bug' });\n", "/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\n// Utilities for modular arithmetics and finite fields\nimport {\n bitMask,\n numberToBytesBE,\n numberToBytesLE,\n bytesToNumberBE,\n bytesToNumberLE,\n ensureBytes,\n validateObject,\n} from './utils.js';\n// prettier-ignore\nconst _0n = BigInt(0), _1n = BigInt(1), _2n = BigInt(2), _3n = BigInt(3);\n// prettier-ignore\nconst _4n = BigInt(4), _5n = BigInt(5), _8n = BigInt(8);\n// prettier-ignore\nconst _9n = BigInt(9), _16n = BigInt(16);\n\n// Calculates a modulo b\nexport function mod(a: bigint, b: bigint): bigint {\n const result = a % b;\n return result >= _0n ? result : b + result;\n}\n/**\n * Efficiently raise num to power and do modular division.\n * Unsafe in some contexts: uses ladder, so can expose bigint bits.\n * @example\n * pow(2n, 6n, 11n) // 64n % 11n == 9n\n */\n// TODO: use field version && remove\nexport function pow(num: bigint, power: bigint, modulo: bigint): bigint {\n if (modulo <= _0n || power < _0n) throw new Error('Expected power/modulo > 0');\n if (modulo === _1n) return _0n;\n let res = _1n;\n while (power > _0n) {\n if (power & _1n) res = (res * num) % modulo;\n num = (num * num) % modulo;\n power >>= _1n;\n }\n return res;\n}\n\n// Does x ^ (2 ^ power) mod p. pow2(30, 4) == 30 ^ (2 ^ 4)\nexport function pow2(x: bigint, power: bigint, modulo: bigint): bigint {\n let res = x;\n while (power-- > _0n) {\n res *= res;\n res %= modulo;\n }\n return res;\n}\n\n// Inverses number over modulo\nexport function invert(number: bigint, modulo: bigint): bigint {\n if (number === _0n || modulo <= _0n) {\n throw new Error(`invert: expected positive integers, got n=${number} mod=${modulo}`);\n }\n // Euclidean GCD https://brilliant.org/wiki/extended-euclidean-algorithm/\n // Fermat's little theorem \"CT-like\" version inv(n) = n^(m-2) mod m is 30x slower.\n let a = mod(number, modulo);\n let b = modulo;\n // prettier-ignore\n let x = _0n, y = _1n, u = _1n, v = _0n;\n while (a !== _0n) {\n // JIT applies optimization if those two lines follow each other\n const q = b / a;\n const r = b % a;\n const m = x - u * q;\n const n = y - v * q;\n // prettier-ignore\n b = a, a = r, x = u, y = v, u = m, v = n;\n }\n const gcd = b;\n if (gcd !== _1n) throw new Error('invert: does not exist');\n return mod(x, modulo);\n}\n\n/**\n * Tonelli-Shanks square root search algorithm.\n * 1. https://eprint.iacr.org/2012/685.pdf (page 12)\n * 2. Square Roots from 1; 24, 51, 10 to Dan Shanks\n * Will start an infinite loop if field order P is not prime.\n * @param P field order\n * @returns function that takes field Fp (created from P) and number n\n */\nexport function tonelliShanks(P: bigint) {\n // Legendre constant: used to calculate Legendre symbol (a | p),\n // which denotes the value of a^((p-1)/2) (mod p).\n // (a | p) ≡ 1 if a is a square (mod p)\n // (a | p) ≡ -1 if a is not a square (mod p)\n // (a | p) ≡ 0 if a ≡ 0 (mod p)\n const legendreC = (P - _1n) / _2n;\n\n let Q: bigint, S: number, Z: bigint;\n // Step 1: By factoring out powers of 2 from p - 1,\n // find q and s such that p - 1 = q*(2^s) with q odd\n for (Q = P - _1n, S = 0; Q % _2n === _0n; Q /= _2n, S++);\n\n // Step 2: Select a non-square z such that (z | p) ≡ -1 and set c ≡ zq\n for (Z = _2n; Z < P && pow(Z, legendreC, P) !== P - _1n; Z++);\n\n // Fast-path\n if (S === 1) {\n const p1div4 = (P + _1n) / _4n;\n return function tonelliFast(Fp: IField, n: T) {\n const root = Fp.pow(n, p1div4);\n if (!Fp.eql(Fp.sqr(root), n)) throw new Error('Cannot find square root');\n return root;\n };\n }\n\n // Slow-path\n const Q1div2 = (Q + _1n) / _2n;\n return function tonelliSlow(Fp: IField, n: T): T {\n // Step 0: Check that n is indeed a square: (n | p) should not be ≡ -1\n if (Fp.pow(n, legendreC) === Fp.neg(Fp.ONE)) throw new Error('Cannot find square root');\n let r = S;\n // TODO: will fail at Fp2/etc\n let g = Fp.pow(Fp.mul(Fp.ONE, Z), Q); // will update both x and b\n let x = Fp.pow(n, Q1div2); // first guess at the square root\n let b = Fp.pow(n, Q); // first guess at the fudge factor\n\n while (!Fp.eql(b, Fp.ONE)) {\n if (Fp.eql(b, Fp.ZERO)) return Fp.ZERO; // https://en.wikipedia.org/wiki/Tonelli%E2%80%93Shanks_algorithm (4. If t = 0, return r = 0)\n // Find m such b^(2^m)==1\n let m = 1;\n for (let t2 = Fp.sqr(b); m < r; m++) {\n if (Fp.eql(t2, Fp.ONE)) break;\n t2 = Fp.sqr(t2); // t2 *= t2\n }\n // NOTE: r-m-1 can be bigger than 32, need to convert to bigint before shift, otherwise there will be overflow\n const ge = Fp.pow(g, _1n << BigInt(r - m - 1)); // ge = 2^(r-m-1)\n g = Fp.sqr(ge); // g = ge * ge\n x = Fp.mul(x, ge); // x *= ge\n b = Fp.mul(b, g); // b *= g\n r = m;\n }\n return x;\n };\n}\n\nexport function FpSqrt(P: bigint) {\n // NOTE: different algorithms can give different roots, it is up to user to decide which one they want.\n // For example there is FpSqrtOdd/FpSqrtEven to choice root based on oddness (used for hash-to-curve).\n\n // P ≡ 3 (mod 4)\n // √n = n^((P+1)/4)\n if (P % _4n === _3n) {\n // Not all roots possible!\n // const ORDER =\n // 0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaaabn;\n // const NUM = 72057594037927816n;\n const p1div4 = (P + _1n) / _4n;\n return function sqrt3mod4(Fp: IField, n: T) {\n const root = Fp.pow(n, p1div4);\n // Throw if root**2 != n\n if (!Fp.eql(Fp.sqr(root), n)) throw new Error('Cannot find square root');\n return root;\n };\n }\n\n // Atkin algorithm for q ≡ 5 (mod 8), https://eprint.iacr.org/2012/685.pdf (page 10)\n if (P % _8n === _5n) {\n const c1 = (P - _5n) / _8n;\n return function sqrt5mod8(Fp: IField, n: T) {\n const n2 = Fp.mul(n, _2n);\n const v = Fp.pow(n2, c1);\n const nv = Fp.mul(n, v);\n const i = Fp.mul(Fp.mul(nv, _2n), v);\n const root = Fp.mul(nv, Fp.sub(i, Fp.ONE));\n if (!Fp.eql(Fp.sqr(root), n)) throw new Error('Cannot find square root');\n return root;\n };\n }\n\n // P ≡ 9 (mod 16)\n if (P % _16n === _9n) {\n // NOTE: tonelli is too slow for bls-Fp2 calculations even on start\n // Means we cannot use sqrt for constants at all!\n //\n // const c1 = Fp.sqrt(Fp.negate(Fp.ONE)); // 1. c1 = sqrt(-1) in F, i.e., (c1^2) == -1 in F\n // const c2 = Fp.sqrt(c1); // 2. c2 = sqrt(c1) in F, i.e., (c2^2) == c1 in F\n // const c3 = Fp.sqrt(Fp.negate(c1)); // 3. c3 = sqrt(-c1) in F, i.e., (c3^2) == -c1 in F\n // const c4 = (P + _7n) / _16n; // 4. c4 = (q + 7) / 16 # Integer arithmetic\n // sqrt = (x) => {\n // let tv1 = Fp.pow(x, c4); // 1. tv1 = x^c4\n // let tv2 = Fp.mul(c1, tv1); // 2. tv2 = c1 * tv1\n // const tv3 = Fp.mul(c2, tv1); // 3. tv3 = c2 * tv1\n // let tv4 = Fp.mul(c3, tv1); // 4. tv4 = c3 * tv1\n // const e1 = Fp.equals(Fp.square(tv2), x); // 5. e1 = (tv2^2) == x\n // const e2 = Fp.equals(Fp.square(tv3), x); // 6. e2 = (tv3^2) == x\n // tv1 = Fp.cmov(tv1, tv2, e1); // 7. tv1 = CMOV(tv1, tv2, e1) # Select tv2 if (tv2^2) == x\n // tv2 = Fp.cmov(tv4, tv3, e2); // 8. tv2 = CMOV(tv4, tv3, e2) # Select tv3 if (tv3^2) == x\n // const e3 = Fp.equals(Fp.square(tv2), x); // 9. e3 = (tv2^2) == x\n // return Fp.cmov(tv1, tv2, e3); // 10. z = CMOV(tv1, tv2, e3) # Select the sqrt from tv1 and tv2\n // }\n }\n\n // Other cases: Tonelli-Shanks algorithm\n return tonelliShanks(P);\n}\n\n// Little-endian check for first LE bit (last BE bit);\nexport const isNegativeLE = (num: bigint, modulo: bigint) => (mod(num, modulo) & _1n) === _1n;\n\n// Field is not always over prime: for example, Fp2 has ORDER(q)=p^m\nexport interface IField {\n ORDER: bigint;\n BYTES: number;\n BITS: number;\n MASK: bigint;\n ZERO: T;\n ONE: T;\n // 1-arg\n create: (num: T) => T;\n isValid: (num: T) => boolean;\n is0: (num: T) => boolean;\n neg(num: T): T;\n inv(num: T): T;\n sqrt(num: T): T;\n sqr(num: T): T;\n // 2-args\n eql(lhs: T, rhs: T): boolean;\n add(lhs: T, rhs: T): T;\n sub(lhs: T, rhs: T): T;\n mul(lhs: T, rhs: T | bigint): T;\n pow(lhs: T, power: bigint): T;\n div(lhs: T, rhs: T | bigint): T;\n // N for NonNormalized (for now)\n addN(lhs: T, rhs: T): T;\n subN(lhs: T, rhs: T): T;\n mulN(lhs: T, rhs: T | bigint): T;\n sqrN(num: T): T;\n\n // Optional\n // Should be same as sgn0 function in\n // [RFC9380](https://www.rfc-editor.org/rfc/rfc9380#section-4.1).\n // NOTE: sgn0 is 'negative in LE', which is same as odd. And negative in LE is kinda strange definition anyway.\n isOdd?(num: T): boolean; // Odd instead of even since we have it for Fp2\n // legendre?(num: T): T;\n pow(lhs: T, power: bigint): T;\n invertBatch: (lst: T[]) => T[];\n toBytes(num: T): Uint8Array;\n fromBytes(bytes: Uint8Array): T;\n // If c is False, CMOV returns a, otherwise it returns b.\n cmov(a: T, b: T, c: boolean): T;\n}\n// prettier-ignore\nconst FIELD_FIELDS = [\n 'create', 'isValid', 'is0', 'neg', 'inv', 'sqrt', 'sqr',\n 'eql', 'add', 'sub', 'mul', 'pow', 'div',\n 'addN', 'subN', 'mulN', 'sqrN'\n] as const;\nexport function validateField(field: IField) {\n const initial = {\n ORDER: 'bigint',\n MASK: 'bigint',\n BYTES: 'isSafeInteger',\n BITS: 'isSafeInteger',\n } as Record;\n const opts = FIELD_FIELDS.reduce((map, val: string) => {\n map[val] = 'function';\n return map;\n }, initial);\n return validateObject(field, opts);\n}\n\n// Generic field functions\n\n/**\n * Same as `pow` but for Fp: non-constant-time.\n * Unsafe in some contexts: uses ladder, so can expose bigint bits.\n */\nexport function FpPow(f: IField, num: T, power: bigint): T {\n // Should have same speed as pow for bigints\n // TODO: benchmark!\n if (power < _0n) throw new Error('Expected power > 0');\n if (power === _0n) return f.ONE;\n if (power === _1n) return num;\n let p = f.ONE;\n let d = num;\n while (power > _0n) {\n if (power & _1n) p = f.mul(p, d);\n d = f.sqr(d);\n power >>= _1n;\n }\n return p;\n}\n\n/**\n * Efficiently invert an array of Field elements.\n * `inv(0)` will return `undefined` here: make sure to throw an error.\n */\nexport function FpInvertBatch(f: IField, nums: T[]): T[] {\n const tmp = new Array(nums.length);\n // Walk from first to last, multiply them by each other MOD p\n const lastMultiplied = nums.reduce((acc, num, i) => {\n if (f.is0(num)) return acc;\n tmp[i] = acc;\n return f.mul(acc, num);\n }, f.ONE);\n // Invert last element\n const inverted = f.inv(lastMultiplied);\n // Walk from last to first, multiply them by inverted each other MOD p\n nums.reduceRight((acc, num, i) => {\n if (f.is0(num)) return acc;\n tmp[i] = f.mul(acc, tmp[i]);\n return f.mul(acc, num);\n }, inverted);\n return tmp;\n}\n\nexport function FpDiv(f: IField, lhs: T, rhs: T | bigint): T {\n return f.mul(lhs, typeof rhs === 'bigint' ? invert(rhs, f.ORDER) : f.inv(rhs));\n}\n\n// This function returns True whenever the value x is a square in the field F.\nexport function FpIsSquare(f: IField) {\n const legendreConst = (f.ORDER - _1n) / _2n; // Integer arithmetic\n return (x: T): boolean => {\n const p = f.pow(x, legendreConst);\n return f.eql(p, f.ZERO) || f.eql(p, f.ONE);\n };\n}\n\n// CURVE.n lengths\nexport function nLength(n: bigint, nBitLength?: number) {\n // Bit size, byte size of CURVE.n\n const _nBitLength = nBitLength !== undefined ? nBitLength : n.toString(2).length;\n const nByteLength = Math.ceil(_nBitLength / 8);\n return { nBitLength: _nBitLength, nByteLength };\n}\n\ntype FpField = IField & Required, 'isOdd'>>;\n/**\n * Initializes a finite field over prime. **Non-primes are not supported.**\n * Do not init in loop: slow. Very fragile: always run a benchmark on a change.\n * Major performance optimizations:\n * * a) denormalized operations like mulN instead of mul\n * * b) same object shape: never add or remove keys\n * * c) Object.freeze\n * @param ORDER prime positive bigint\n * @param bitLen how many bits the field consumes\n * @param isLE (def: false) if encoding / decoding should be in little-endian\n * @param redef optional faster redefinitions of sqrt and other methods\n */\nexport function Field(\n ORDER: bigint,\n bitLen?: number,\n isLE = false,\n redef: Partial> = {}\n): Readonly {\n if (ORDER <= _0n) throw new Error(`Expected Field ORDER > 0, got ${ORDER}`);\n const { nBitLength: BITS, nByteLength: BYTES } = nLength(ORDER, bitLen);\n if (BYTES > 2048) throw new Error('Field lengths over 2048 bytes are not supported');\n const sqrtP = FpSqrt(ORDER);\n const f: Readonly = Object.freeze({\n ORDER,\n BITS,\n BYTES,\n MASK: bitMask(BITS),\n ZERO: _0n,\n ONE: _1n,\n create: (num) => mod(num, ORDER),\n isValid: (num) => {\n if (typeof num !== 'bigint')\n throw new Error(`Invalid field element: expected bigint, got ${typeof num}`);\n return _0n <= num && num < ORDER; // 0 is valid element, but it's not invertible\n },\n is0: (num) => num === _0n,\n isOdd: (num) => (num & _1n) === _1n,\n neg: (num) => mod(-num, ORDER),\n eql: (lhs, rhs) => lhs === rhs,\n\n sqr: (num) => mod(num * num, ORDER),\n add: (lhs, rhs) => mod(lhs + rhs, ORDER),\n sub: (lhs, rhs) => mod(lhs - rhs, ORDER),\n mul: (lhs, rhs) => mod(lhs * rhs, ORDER),\n pow: (num, power) => FpPow(f, num, power),\n div: (lhs, rhs) => mod(lhs * invert(rhs, ORDER), ORDER),\n\n // Same as above, but doesn't normalize\n sqrN: (num) => num * num,\n addN: (lhs, rhs) => lhs + rhs,\n subN: (lhs, rhs) => lhs - rhs,\n mulN: (lhs, rhs) => lhs * rhs,\n\n inv: (num) => invert(num, ORDER),\n sqrt: redef.sqrt || ((n) => sqrtP(f, n)),\n invertBatch: (lst) => FpInvertBatch(f, lst),\n // TODO: do we really need constant cmov?\n // We don't have const-time bigints anyway, so probably will be not very useful\n cmov: (a, b, c) => (c ? b : a),\n toBytes: (num) => (isLE ? numberToBytesLE(num, BYTES) : numberToBytesBE(num, BYTES)),\n fromBytes: (bytes) => {\n if (bytes.length !== BYTES)\n throw new Error(`Fp.fromBytes: expected ${BYTES}, got ${bytes.length}`);\n return isLE ? bytesToNumberLE(bytes) : bytesToNumberBE(bytes);\n },\n } as FpField);\n return Object.freeze(f);\n}\n\nexport function FpSqrtOdd(Fp: IField, elm: T) {\n if (!Fp.isOdd) throw new Error(`Field doesn't have isOdd`);\n const root = Fp.sqrt(elm);\n return Fp.isOdd(root) ? root : Fp.neg(root);\n}\n\nexport function FpSqrtEven(Fp: IField, elm: T) {\n if (!Fp.isOdd) throw new Error(`Field doesn't have isOdd`);\n const root = Fp.sqrt(elm);\n return Fp.isOdd(root) ? Fp.neg(root) : root;\n}\n\n/**\n * \"Constant-time\" private key generation utility.\n * Same as mapKeyToField, but accepts less bytes (40 instead of 48 for 32-byte field).\n * Which makes it slightly more biased, less secure.\n * @deprecated use mapKeyToField instead\n */\nexport function hashToPrivateScalar(\n hash: string | Uint8Array,\n groupOrder: bigint,\n isLE = false\n): bigint {\n hash = ensureBytes('privateHash', hash);\n const hashLen = hash.length;\n const minLen = nLength(groupOrder).nByteLength + 8;\n if (minLen < 24 || hashLen < minLen || hashLen > 1024)\n throw new Error(`hashToPrivateScalar: expected ${minLen}-1024 bytes of input, got ${hashLen}`);\n const num = isLE ? bytesToNumberLE(hash) : bytesToNumberBE(hash);\n return mod(num, groupOrder - _1n) + _1n;\n}\n\n/**\n * Returns total number of bytes consumed by the field element.\n * For example, 32 bytes for usual 256-bit weierstrass curve.\n * @param fieldOrder number of field elements, usually CURVE.n\n * @returns byte length of field\n */\nexport function getFieldBytesLength(fieldOrder: bigint): number {\n if (typeof fieldOrder !== 'bigint') throw new Error('field order must be bigint');\n const bitLength = fieldOrder.toString(2).length;\n return Math.ceil(bitLength / 8);\n}\n\n/**\n * Returns minimal amount of bytes that can be safely reduced\n * by field order.\n * Should be 2^-128 for 128-bit curve such as P256.\n * @param fieldOrder number of field elements, usually CURVE.n\n * @returns byte length of target hash\n */\nexport function getMinHashLength(fieldOrder: bigint): number {\n const length = getFieldBytesLength(fieldOrder);\n return length + Math.ceil(length / 2);\n}\n\n/**\n * \"Constant-time\" private key generation utility.\n * Can take (n + n/2) or more bytes of uniform input e.g. from CSPRNG or KDF\n * and convert them into private scalar, with the modulo bias being negligible.\n * Needs at least 48 bytes of input for 32-byte private key.\n * https://research.kudelskisecurity.com/2020/07/28/the-definitive-guide-to-modulo-bias-and-how-to-avoid-it/\n * FIPS 186-5, A.2 https://csrc.nist.gov/publications/detail/fips/186/5/final\n * RFC 9380, https://www.rfc-editor.org/rfc/rfc9380#section-5\n * @param hash hash output from SHA3 or a similar function\n * @param groupOrder size of subgroup - (e.g. secp256k1.CURVE.n)\n * @param isLE interpret hash bytes as LE num\n * @returns valid private scalar\n */\nexport function mapHashToField(key: Uint8Array, fieldOrder: bigint, isLE = false): Uint8Array {\n const len = key.length;\n const fieldLen = getFieldBytesLength(fieldOrder);\n const minLen = getMinHashLength(fieldOrder);\n // No small numbers: need to understand bias story. No huge numbers: easier to detect JS timings.\n if (len < 16 || len < minLen || len > 1024)\n throw new Error(`expected ${minLen}-1024 bytes of input, got ${len}`);\n const num = isLE ? bytesToNumberBE(key) : bytesToNumberLE(key);\n // `mod(x, 11)` can sometimes produce 0. `mod(x, 10) + 1` is the same, but no 0\n const reduced = mod(num, fieldOrder - _1n) + _1n;\n return isLE ? numberToBytesLE(reduced, fieldLen) : numberToBytesBE(reduced, fieldLen);\n}\n", "/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\n// Abelian group utilities\nimport { IField, validateField, nLength } from './modular.js';\nimport { validateObject } from './utils.js';\nconst _0n = BigInt(0);\nconst _1n = BigInt(1);\n\nexport type AffinePoint = {\n x: T;\n y: T;\n} & { z?: never; t?: never };\n\nexport interface Group> {\n double(): T;\n negate(): T;\n add(other: T): T;\n subtract(other: T): T;\n equals(other: T): boolean;\n multiply(scalar: bigint): T;\n}\n\nexport type GroupConstructor = {\n BASE: T;\n ZERO: T;\n};\nexport type Mapper = (i: T[]) => T[];\n\n// Elliptic curve multiplication of Point by scalar. Fragile.\n// Scalars should always be less than curve order: this should be checked inside of a curve itself.\n// Creates precomputation tables for fast multiplication:\n// - private scalar is split by fixed size windows of W bits\n// - every window point is collected from window's table & added to accumulator\n// - since windows are different, same point inside tables won't be accessed more than once per calc\n// - each multiplication is 'Math.ceil(CURVE_ORDER / 𝑊) + 1' point additions (fixed for any scalar)\n// - +1 window is neccessary for wNAF\n// - wNAF reduces table size: 2x less memory + 2x faster generation, but 10% slower multiplication\n// TODO: Research returning 2d JS array of windows, instead of a single window. This would allow\n// windows to be in different memory locations\nexport function wNAF>(c: GroupConstructor, bits: number) {\n const constTimeNegate = (condition: boolean, item: T): T => {\n const neg = item.negate();\n return condition ? neg : item;\n };\n const opts = (W: number) => {\n const windows = Math.ceil(bits / W) + 1; // +1, because\n const windowSize = 2 ** (W - 1); // -1 because we skip zero\n return { windows, windowSize };\n };\n return {\n constTimeNegate,\n // non-const time multiplication ladder\n unsafeLadder(elm: T, n: bigint) {\n let p = c.ZERO;\n let d: T = elm;\n while (n > _0n) {\n if (n & _1n) p = p.add(d);\n d = d.double();\n n >>= _1n;\n }\n return p;\n },\n\n /**\n * Creates a wNAF precomputation window. Used for caching.\n * Default window size is set by `utils.precompute()` and is equal to 8.\n * Number of precomputed points depends on the curve size:\n * 2^(𝑊−1) * (Math.ceil(𝑛 / 𝑊) + 1), where:\n * - 𝑊 is the window size\n * - 𝑛 is the bitlength of the curve order.\n * For a 256-bit curve and window size 8, the number of precomputed points is 128 * 33 = 4224.\n * @returns precomputed point tables flattened to a single array\n */\n precomputeWindow(elm: T, W: number): Group[] {\n const { windows, windowSize } = opts(W);\n const points: T[] = [];\n let p: T = elm;\n let base = p;\n for (let window = 0; window < windows; window++) {\n base = p;\n points.push(base);\n // =1, because we skip zero\n for (let i = 1; i < windowSize; i++) {\n base = base.add(p);\n points.push(base);\n }\n p = base.double();\n }\n return points;\n },\n\n /**\n * Implements ec multiplication using precomputed tables and w-ary non-adjacent form.\n * @param W window size\n * @param precomputes precomputed tables\n * @param n scalar (we don't check here, but should be less than curve order)\n * @returns real and fake (for const-time) points\n */\n wNAF(W: number, precomputes: T[], n: bigint): { p: T; f: T } {\n // TODO: maybe check that scalar is less than group order? wNAF behavious is undefined otherwise\n // But need to carefully remove other checks before wNAF. ORDER == bits here\n const { windows, windowSize } = opts(W);\n\n let p = c.ZERO;\n let f = c.BASE;\n\n const mask = BigInt(2 ** W - 1); // Create mask with W ones: 0b1111 for W=4 etc.\n const maxNumber = 2 ** W;\n const shiftBy = BigInt(W);\n\n for (let window = 0; window < windows; window++) {\n const offset = window * windowSize;\n // Extract W bits.\n let wbits = Number(n & mask);\n\n // Shift number by W bits.\n n >>= shiftBy;\n\n // If the bits are bigger than max size, we'll split those.\n // +224 => 256 - 32\n if (wbits > windowSize) {\n wbits -= maxNumber;\n n += _1n;\n }\n\n // This code was first written with assumption that 'f' and 'p' will never be infinity point:\n // since each addition is multiplied by 2 ** W, it cannot cancel each other. However,\n // there is negate now: it is possible that negated element from low value\n // would be the same as high element, which will create carry into next window.\n // It's not obvious how this can fail, but still worth investigating later.\n\n // Check if we're onto Zero point.\n // Add random point inside current window to f.\n const offset1 = offset;\n const offset2 = offset + Math.abs(wbits) - 1; // -1 because we skip zero\n const cond1 = window % 2 !== 0;\n const cond2 = wbits < 0;\n if (wbits === 0) {\n // The most important part for const-time getPublicKey\n f = f.add(constTimeNegate(cond1, precomputes[offset1]));\n } else {\n p = p.add(constTimeNegate(cond2, precomputes[offset2]));\n }\n }\n // JIT-compiler should not eliminate f here, since it will later be used in normalizeZ()\n // Even if the variable is still unused, there are some checks which will\n // throw an exception, so compiler needs to prove they won't happen, which is hard.\n // At this point there is a way to F be infinity-point even if p is not,\n // which makes it less const-time: around 1 bigint multiply.\n return { p, f };\n },\n\n wNAFCached(P: T, precomputesMap: Map, n: bigint, transform: Mapper): { p: T; f: T } {\n // @ts-ignore\n const W: number = P._WINDOW_SIZE || 1;\n // Calculate precomputes on a first run, reuse them after\n let comp = precomputesMap.get(P);\n if (!comp) {\n comp = this.precomputeWindow(P, W) as T[];\n if (W !== 1) {\n precomputesMap.set(P, transform(comp));\n }\n }\n return this.wNAF(W, comp, n);\n },\n };\n}\n\n// Generic BasicCurve interface: works even for polynomial fields (BLS): P, n, h would be ok.\n// Though generator can be different (Fp2 / Fp6 for BLS).\nexport type BasicCurve = {\n Fp: IField; // Field over which we'll do calculations (Fp)\n n: bigint; // Curve order, total count of valid points in the field\n nBitLength?: number; // bit length of curve order\n nByteLength?: number; // byte length of curve order\n h: bigint; // cofactor. we can assign default=1, but users will just ignore it w/o validation\n hEff?: bigint; // Number to multiply to clear cofactor\n Gx: T; // base point X coordinate\n Gy: T; // base point Y coordinate\n allowInfinityPoint?: boolean; // bls12-381 requires it. ZERO point is valid, but invalid pubkey\n};\n\nexport function validateBasic(curve: BasicCurve & T) {\n validateField(curve.Fp);\n validateObject(\n curve,\n {\n n: 'bigint',\n h: 'bigint',\n Gx: 'field',\n Gy: 'field',\n },\n {\n nBitLength: 'isSafeInteger',\n nByteLength: 'isSafeInteger',\n }\n );\n // Set defaults\n return Object.freeze({\n ...nLength(curve.n, curve.nBitLength),\n ...curve,\n ...{ p: curve.Fp.ORDER },\n } as const);\n}\n", "/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\n// Short Weierstrass curve. The formula is: y² = x³ + ax + b\nimport * as mod from './modular.js';\nimport * as ut from './utils.js';\nimport { CHash, Hex, PrivKey, ensureBytes } from './utils.js';\nimport { Group, GroupConstructor, wNAF, BasicCurve, validateBasic, AffinePoint } from './curve.js';\n\nexport type { AffinePoint };\ntype HmacFnSync = (key: Uint8Array, ...messages: Uint8Array[]) => Uint8Array;\ntype EndomorphismOpts = {\n beta: bigint;\n splitScalar: (k: bigint) => { k1neg: boolean; k1: bigint; k2neg: boolean; k2: bigint };\n};\nexport type BasicWCurve = BasicCurve & {\n // Params: a, b\n a: T;\n b: T;\n\n // Optional params\n allowedPrivateKeyLengths?: readonly number[]; // for P521\n wrapPrivateKey?: boolean; // bls12-381 requires mod(n) instead of rejecting keys >= n\n endo?: EndomorphismOpts; // Endomorphism options for Koblitz curves\n // When a cofactor != 1, there can be an effective methods to:\n // 1. Determine whether a point is torsion-free\n isTorsionFree?: (c: ProjConstructor, point: ProjPointType) => boolean;\n // 2. Clear torsion component\n clearCofactor?: (c: ProjConstructor, point: ProjPointType) => ProjPointType;\n};\n\ntype Entropy = Hex | true;\nexport type SignOpts = { lowS?: boolean; extraEntropy?: Entropy; prehash?: boolean };\nexport type VerOpts = { lowS?: boolean; prehash?: boolean };\n\n/**\n * ### Design rationale for types\n *\n * * Interaction between classes from different curves should fail:\n * `k256.Point.BASE.add(p256.Point.BASE)`\n * * For this purpose we want to use `instanceof` operator, which is fast and works during runtime\n * * Different calls of `curve()` would return different classes -\n * `curve(params) !== curve(params)`: if somebody decided to monkey-patch their curve,\n * it won't affect others\n *\n * TypeScript can't infer types for classes created inside a function. Classes is one instance of nominative types in TypeScript and interfaces only check for shape, so it's hard to create unique type for every function call.\n *\n * We can use generic types via some param, like curve opts, but that would:\n * 1. Enable interaction between `curve(params)` and `curve(params)` (curves of same params)\n * which is hard to debug.\n * 2. Params can be generic and we can't enforce them to be constant value:\n * if somebody creates curve from non-constant params,\n * it would be allowed to interact with other curves with non-constant params\n *\n * TODO: https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-7.html#unique-symbol\n */\n\n// Instance for 3d XYZ points\nexport interface ProjPointType extends Group> {\n readonly px: T;\n readonly py: T;\n readonly pz: T;\n get x(): T;\n get y(): T;\n multiply(scalar: bigint): ProjPointType;\n toAffine(iz?: T): AffinePoint;\n isTorsionFree(): boolean;\n clearCofactor(): ProjPointType;\n assertValidity(): void;\n hasEvenY(): boolean;\n toRawBytes(isCompressed?: boolean): Uint8Array;\n toHex(isCompressed?: boolean): string;\n\n multiplyUnsafe(scalar: bigint): ProjPointType;\n multiplyAndAddUnsafe(Q: ProjPointType, a: bigint, b: bigint): ProjPointType | undefined;\n _setWindowSize(windowSize: number): void;\n}\n// Static methods for 3d XYZ points\nexport interface ProjConstructor extends GroupConstructor> {\n new (x: T, y: T, z: T): ProjPointType;\n fromAffine(p: AffinePoint): ProjPointType;\n fromHex(hex: Hex): ProjPointType;\n fromPrivateKey(privateKey: PrivKey): ProjPointType;\n normalizeZ(points: ProjPointType[]): ProjPointType[];\n}\n\nexport type CurvePointsType = BasicWCurve & {\n // Bytes\n fromBytes?: (bytes: Uint8Array) => AffinePoint;\n toBytes?: (c: ProjConstructor, point: ProjPointType, isCompressed: boolean) => Uint8Array;\n};\n\nfunction validatePointOpts(curve: CurvePointsType) {\n const opts = validateBasic(curve);\n ut.validateObject(\n opts,\n {\n a: 'field',\n b: 'field',\n },\n {\n allowedPrivateKeyLengths: 'array',\n wrapPrivateKey: 'boolean',\n isTorsionFree: 'function',\n clearCofactor: 'function',\n allowInfinityPoint: 'boolean',\n fromBytes: 'function',\n toBytes: 'function',\n }\n );\n const { endo, Fp, a } = opts;\n if (endo) {\n if (!Fp.eql(a, Fp.ZERO)) {\n throw new Error('Endomorphism can only be defined for Koblitz curves that have a=0');\n }\n if (\n typeof endo !== 'object' ||\n typeof endo.beta !== 'bigint' ||\n typeof endo.splitScalar !== 'function'\n ) {\n throw new Error('Expected endomorphism with beta: bigint and splitScalar: function');\n }\n }\n return Object.freeze({ ...opts } as const);\n}\n\nexport type CurvePointsRes = {\n ProjectivePoint: ProjConstructor;\n normPrivateKeyToScalar: (key: PrivKey) => bigint;\n weierstrassEquation: (x: T) => T;\n isWithinCurveOrder: (num: bigint) => boolean;\n};\n\n// ASN.1 DER encoding utilities\nconst { bytesToNumberBE: b2n, hexToBytes: h2b } = ut;\nexport const DER = {\n // asn.1 DER encoding utils\n Err: class DERErr extends Error {\n constructor(m = '') {\n super(m);\n }\n },\n _parseInt(data: Uint8Array): { d: bigint; l: Uint8Array } {\n const { Err: E } = DER;\n if (data.length < 2 || data[0] !== 0x02) throw new E('Invalid signature integer tag');\n const len = data[1];\n const res = data.subarray(2, len + 2);\n if (!len || res.length !== len) throw new E('Invalid signature integer: wrong length');\n // https://crypto.stackexchange.com/a/57734 Leftmost bit of first byte is 'negative' flag,\n // since we always use positive integers here. It must always be empty:\n // - add zero byte if exists\n // - if next byte doesn't have a flag, leading zero is not allowed (minimal encoding)\n if (res[0] & 0b10000000) throw new E('Invalid signature integer: negative');\n if (res[0] === 0x00 && !(res[1] & 0b10000000))\n throw new E('Invalid signature integer: unnecessary leading zero');\n return { d: b2n(res), l: data.subarray(len + 2) }; // d is data, l is left\n },\n toSig(hex: string | Uint8Array): { r: bigint; s: bigint } {\n // parse DER signature\n const { Err: E } = DER;\n const data = typeof hex === 'string' ? h2b(hex) : hex;\n if (!(data instanceof Uint8Array)) throw new Error('ui8a expected');\n let l = data.length;\n if (l < 2 || data[0] != 0x30) throw new E('Invalid signature tag');\n if (data[1] !== l - 2) throw new E('Invalid signature: incorrect length');\n const { d: r, l: sBytes } = DER._parseInt(data.subarray(2));\n const { d: s, l: rBytesLeft } = DER._parseInt(sBytes);\n if (rBytesLeft.length) throw new E('Invalid signature: left bytes after parsing');\n return { r, s };\n },\n hexFromSig(sig: { r: bigint; s: bigint }): string {\n // Add leading zero if first byte has negative bit enabled. More details in '_parseInt'\n const slice = (s: string): string => (Number.parseInt(s[0], 16) & 0b1000 ? '00' + s : s);\n const h = (num: number | bigint) => {\n const hex = num.toString(16);\n return hex.length & 1 ? `0${hex}` : hex;\n };\n const s = slice(h(sig.s));\n const r = slice(h(sig.r));\n const shl = s.length / 2;\n const rhl = r.length / 2;\n const sl = h(shl);\n const rl = h(rhl);\n return `30${h(rhl + shl + 4)}02${rl}${r}02${sl}${s}`;\n },\n};\n\n// Be friendly to bad ECMAScript parsers by not using bigint literals\n// prettier-ignore\nconst _0n = BigInt(0), _1n = BigInt(1), _2n = BigInt(2), _3n = BigInt(3), _4n = BigInt(4);\n\nexport function weierstrassPoints(opts: CurvePointsType) {\n const CURVE = validatePointOpts(opts);\n const { Fp } = CURVE; // All curves has same field / group length as for now, but they can differ\n\n const toBytes =\n CURVE.toBytes ||\n ((_c: ProjConstructor, point: ProjPointType, _isCompressed: boolean) => {\n const a = point.toAffine();\n return ut.concatBytes(Uint8Array.from([0x04]), Fp.toBytes(a.x), Fp.toBytes(a.y));\n });\n const fromBytes =\n CURVE.fromBytes ||\n ((bytes: Uint8Array) => {\n // const head = bytes[0];\n const tail = bytes.subarray(1);\n // if (head !== 0x04) throw new Error('Only non-compressed encoding is supported');\n const x = Fp.fromBytes(tail.subarray(0, Fp.BYTES));\n const y = Fp.fromBytes(tail.subarray(Fp.BYTES, 2 * Fp.BYTES));\n return { x, y };\n });\n\n /**\n * y² = x³ + ax + b: Short weierstrass curve formula\n * @returns y²\n */\n function weierstrassEquation(x: T): T {\n const { a, b } = CURVE;\n const x2 = Fp.sqr(x); // x * x\n const x3 = Fp.mul(x2, x); // x2 * x\n return Fp.add(Fp.add(x3, Fp.mul(x, a)), b); // x3 + a * x + b\n }\n // Validate whether the passed curve params are valid.\n // We check if curve equation works for generator point.\n // `assertValidity()` won't work: `isTorsionFree()` is not available at this point in bls12-381.\n // ProjectivePoint class has not been initialized yet.\n if (!Fp.eql(Fp.sqr(CURVE.Gy), weierstrassEquation(CURVE.Gx)))\n throw new Error('bad generator point: equation left != right');\n\n // Valid group elements reside in range 1..n-1\n function isWithinCurveOrder(num: bigint): boolean {\n return typeof num === 'bigint' && _0n < num && num < CURVE.n;\n }\n function assertGE(num: bigint) {\n if (!isWithinCurveOrder(num)) throw new Error('Expected valid bigint: 0 < bigint < curve.n');\n }\n // Validates if priv key is valid and converts it to bigint.\n // Supports options allowedPrivateKeyLengths and wrapPrivateKey.\n function normPrivateKeyToScalar(key: PrivKey): bigint {\n const { allowedPrivateKeyLengths: lengths, nByteLength, wrapPrivateKey, n } = CURVE;\n if (lengths && typeof key !== 'bigint') {\n if (key instanceof Uint8Array) key = ut.bytesToHex(key);\n // Normalize to hex string, pad. E.g. P521 would norm 130-132 char hex to 132-char bytes\n if (typeof key !== 'string' || !lengths.includes(key.length)) throw new Error('Invalid key');\n key = key.padStart(nByteLength * 2, '0');\n }\n let num: bigint;\n try {\n num =\n typeof key === 'bigint'\n ? key\n : ut.bytesToNumberBE(ensureBytes('private key', key, nByteLength));\n } catch (error) {\n throw new Error(`private key must be ${nByteLength} bytes, hex or bigint, not ${typeof key}`);\n }\n if (wrapPrivateKey) num = mod.mod(num, n); // disabled by default, enabled for BLS\n assertGE(num); // num in range [1..N-1]\n return num;\n }\n\n const pointPrecomputes = new Map();\n function assertPrjPoint(other: unknown) {\n if (!(other instanceof Point)) throw new Error('ProjectivePoint expected');\n }\n /**\n * Projective Point works in 3d / projective (homogeneous) coordinates: (x, y, z) ∋ (x=x/z, y=y/z)\n * Default Point works in 2d / affine coordinates: (x, y)\n * We're doing calculations in projective, because its operations don't require costly inversion.\n */\n class Point implements ProjPointType {\n static readonly BASE = new Point(CURVE.Gx, CURVE.Gy, Fp.ONE);\n static readonly ZERO = new Point(Fp.ZERO, Fp.ONE, Fp.ZERO);\n\n constructor(readonly px: T, readonly py: T, readonly pz: T) {\n if (px == null || !Fp.isValid(px)) throw new Error('x required');\n if (py == null || !Fp.isValid(py)) throw new Error('y required');\n if (pz == null || !Fp.isValid(pz)) throw new Error('z required');\n }\n\n // Does not validate if the point is on-curve.\n // Use fromHex instead, or call assertValidity() later.\n static fromAffine(p: AffinePoint): Point {\n const { x, y } = p || {};\n if (!p || !Fp.isValid(x) || !Fp.isValid(y)) throw new Error('invalid affine point');\n if (p instanceof Point) throw new Error('projective point not allowed');\n const is0 = (i: T) => Fp.eql(i, Fp.ZERO);\n // fromAffine(x:0, y:0) would produce (x:0, y:0, z:1), but we need (x:0, y:1, z:0)\n if (is0(x) && is0(y)) return Point.ZERO;\n return new Point(x, y, Fp.ONE);\n }\n\n get x(): T {\n return this.toAffine().x;\n }\n get y(): T {\n return this.toAffine().y;\n }\n\n /**\n * Takes a bunch of Projective Points but executes only one\n * inversion on all of them. Inversion is very slow operation,\n * so this improves performance massively.\n * Optimization: converts a list of projective points to a list of identical points with Z=1.\n */\n static normalizeZ(points: Point[]): Point[] {\n const toInv = Fp.invertBatch(points.map((p) => p.pz));\n return points.map((p, i) => p.toAffine(toInv[i])).map(Point.fromAffine);\n }\n\n /**\n * Converts hash string or Uint8Array to Point.\n * @param hex short/long ECDSA hex\n */\n static fromHex(hex: Hex): Point {\n const P = Point.fromAffine(fromBytes(ensureBytes('pointHex', hex)));\n P.assertValidity();\n return P;\n }\n\n // Multiplies generator point by privateKey.\n static fromPrivateKey(privateKey: PrivKey) {\n return Point.BASE.multiply(normPrivateKeyToScalar(privateKey));\n }\n\n // We calculate precomputes for elliptic curve point multiplication\n // using windowed method. This specifies window size and\n // stores precomputed values. Usually only base point would be precomputed.\n _WINDOW_SIZE?: number;\n\n // \"Private method\", don't use it directly\n _setWindowSize(windowSize: number) {\n this._WINDOW_SIZE = windowSize;\n pointPrecomputes.delete(this);\n }\n\n // A point on curve is valid if it conforms to equation.\n assertValidity(): void {\n if (this.is0()) {\n // (0, 1, 0) aka ZERO is invalid in most contexts.\n // In BLS, ZERO can be serialized, so we allow it.\n // (0, 0, 0) is wrong representation of ZERO and is always invalid.\n if (CURVE.allowInfinityPoint && !Fp.is0(this.py)) return;\n throw new Error('bad point: ZERO');\n }\n // Some 3rd-party test vectors require different wording between here & `fromCompressedHex`\n const { x, y } = this.toAffine();\n // Check if x, y are valid field elements\n if (!Fp.isValid(x) || !Fp.isValid(y)) throw new Error('bad point: x or y not FE');\n const left = Fp.sqr(y); // y²\n const right = weierstrassEquation(x); // x³ + ax + b\n if (!Fp.eql(left, right)) throw new Error('bad point: equation left != right');\n if (!this.isTorsionFree()) throw new Error('bad point: not in prime-order subgroup');\n }\n hasEvenY(): boolean {\n const { y } = this.toAffine();\n if (Fp.isOdd) return !Fp.isOdd(y);\n throw new Error(\"Field doesn't support isOdd\");\n }\n\n /**\n * Compare one point to another.\n */\n equals(other: Point): boolean {\n assertPrjPoint(other);\n const { px: X1, py: Y1, pz: Z1 } = this;\n const { px: X2, py: Y2, pz: Z2 } = other;\n const U1 = Fp.eql(Fp.mul(X1, Z2), Fp.mul(X2, Z1));\n const U2 = Fp.eql(Fp.mul(Y1, Z2), Fp.mul(Y2, Z1));\n return U1 && U2;\n }\n\n /**\n * Flips point to one corresponding to (x, -y) in Affine coordinates.\n */\n negate(): Point {\n return new Point(this.px, Fp.neg(this.py), this.pz);\n }\n\n // Renes-Costello-Batina exception-free doubling formula.\n // There is 30% faster Jacobian formula, but it is not complete.\n // https://eprint.iacr.org/2015/1060, algorithm 3\n // Cost: 8M + 3S + 3*a + 2*b3 + 15add.\n double() {\n const { a, b } = CURVE;\n const b3 = Fp.mul(b, _3n);\n const { px: X1, py: Y1, pz: Z1 } = this;\n let X3 = Fp.ZERO, Y3 = Fp.ZERO, Z3 = Fp.ZERO; // prettier-ignore\n let t0 = Fp.mul(X1, X1); // step 1\n let t1 = Fp.mul(Y1, Y1);\n let t2 = Fp.mul(Z1, Z1);\n let t3 = Fp.mul(X1, Y1);\n t3 = Fp.add(t3, t3); // step 5\n Z3 = Fp.mul(X1, Z1);\n Z3 = Fp.add(Z3, Z3);\n X3 = Fp.mul(a, Z3);\n Y3 = Fp.mul(b3, t2);\n Y3 = Fp.add(X3, Y3); // step 10\n X3 = Fp.sub(t1, Y3);\n Y3 = Fp.add(t1, Y3);\n Y3 = Fp.mul(X3, Y3);\n X3 = Fp.mul(t3, X3);\n Z3 = Fp.mul(b3, Z3); // step 15\n t2 = Fp.mul(a, t2);\n t3 = Fp.sub(t0, t2);\n t3 = Fp.mul(a, t3);\n t3 = Fp.add(t3, Z3);\n Z3 = Fp.add(t0, t0); // step 20\n t0 = Fp.add(Z3, t0);\n t0 = Fp.add(t0, t2);\n t0 = Fp.mul(t0, t3);\n Y3 = Fp.add(Y3, t0);\n t2 = Fp.mul(Y1, Z1); // step 25\n t2 = Fp.add(t2, t2);\n t0 = Fp.mul(t2, t3);\n X3 = Fp.sub(X3, t0);\n Z3 = Fp.mul(t2, t1);\n Z3 = Fp.add(Z3, Z3); // step 30\n Z3 = Fp.add(Z3, Z3);\n return new Point(X3, Y3, Z3);\n }\n\n // Renes-Costello-Batina exception-free addition formula.\n // There is 30% faster Jacobian formula, but it is not complete.\n // https://eprint.iacr.org/2015/1060, algorithm 1\n // Cost: 12M + 0S + 3*a + 3*b3 + 23add.\n add(other: Point): Point {\n assertPrjPoint(other);\n const { px: X1, py: Y1, pz: Z1 } = this;\n const { px: X2, py: Y2, pz: Z2 } = other;\n let X3 = Fp.ZERO, Y3 = Fp.ZERO, Z3 = Fp.ZERO; // prettier-ignore\n const a = CURVE.a;\n const b3 = Fp.mul(CURVE.b, _3n);\n let t0 = Fp.mul(X1, X2); // step 1\n let t1 = Fp.mul(Y1, Y2);\n let t2 = Fp.mul(Z1, Z2);\n let t3 = Fp.add(X1, Y1);\n let t4 = Fp.add(X2, Y2); // step 5\n t3 = Fp.mul(t3, t4);\n t4 = Fp.add(t0, t1);\n t3 = Fp.sub(t3, t4);\n t4 = Fp.add(X1, Z1);\n let t5 = Fp.add(X2, Z2); // step 10\n t4 = Fp.mul(t4, t5);\n t5 = Fp.add(t0, t2);\n t4 = Fp.sub(t4, t5);\n t5 = Fp.add(Y1, Z1);\n X3 = Fp.add(Y2, Z2); // step 15\n t5 = Fp.mul(t5, X3);\n X3 = Fp.add(t1, t2);\n t5 = Fp.sub(t5, X3);\n Z3 = Fp.mul(a, t4);\n X3 = Fp.mul(b3, t2); // step 20\n Z3 = Fp.add(X3, Z3);\n X3 = Fp.sub(t1, Z3);\n Z3 = Fp.add(t1, Z3);\n Y3 = Fp.mul(X3, Z3);\n t1 = Fp.add(t0, t0); // step 25\n t1 = Fp.add(t1, t0);\n t2 = Fp.mul(a, t2);\n t4 = Fp.mul(b3, t4);\n t1 = Fp.add(t1, t2);\n t2 = Fp.sub(t0, t2); // step 30\n t2 = Fp.mul(a, t2);\n t4 = Fp.add(t4, t2);\n t0 = Fp.mul(t1, t4);\n Y3 = Fp.add(Y3, t0);\n t0 = Fp.mul(t5, t4); // step 35\n X3 = Fp.mul(t3, X3);\n X3 = Fp.sub(X3, t0);\n t0 = Fp.mul(t3, t1);\n Z3 = Fp.mul(t5, Z3);\n Z3 = Fp.add(Z3, t0); // step 40\n return new Point(X3, Y3, Z3);\n }\n\n subtract(other: Point) {\n return this.add(other.negate());\n }\n\n private is0() {\n return this.equals(Point.ZERO);\n }\n private wNAF(n: bigint): { p: Point; f: Point } {\n return wnaf.wNAFCached(this, pointPrecomputes, n, (comp: Point[]) => {\n const toInv = Fp.invertBatch(comp.map((p) => p.pz));\n return comp.map((p, i) => p.toAffine(toInv[i])).map(Point.fromAffine);\n });\n }\n\n /**\n * Non-constant-time multiplication. Uses double-and-add algorithm.\n * It's faster, but should only be used when you don't care about\n * an exposed private key e.g. sig verification, which works over *public* keys.\n */\n multiplyUnsafe(n: bigint): Point {\n const I = Point.ZERO;\n if (n === _0n) return I;\n assertGE(n); // Will throw on 0\n if (n === _1n) return this;\n const { endo } = CURVE;\n if (!endo) return wnaf.unsafeLadder(this, n);\n\n // Apply endomorphism\n let { k1neg, k1, k2neg, k2 } = endo.splitScalar(n);\n let k1p = I;\n let k2p = I;\n let d: Point = this;\n while (k1 > _0n || k2 > _0n) {\n if (k1 & _1n) k1p = k1p.add(d);\n if (k2 & _1n) k2p = k2p.add(d);\n d = d.double();\n k1 >>= _1n;\n k2 >>= _1n;\n }\n if (k1neg) k1p = k1p.negate();\n if (k2neg) k2p = k2p.negate();\n k2p = new Point(Fp.mul(k2p.px, endo.beta), k2p.py, k2p.pz);\n return k1p.add(k2p);\n }\n\n /**\n * Constant time multiplication.\n * Uses wNAF method. Windowed method may be 10% faster,\n * but takes 2x longer to generate and consumes 2x memory.\n * Uses precomputes when available.\n * Uses endomorphism for Koblitz curves.\n * @param scalar by which the point would be multiplied\n * @returns New point\n */\n multiply(scalar: bigint): Point {\n assertGE(scalar);\n let n = scalar;\n let point: Point, fake: Point; // Fake point is used to const-time mult\n const { endo } = CURVE;\n if (endo) {\n const { k1neg, k1, k2neg, k2 } = endo.splitScalar(n);\n let { p: k1p, f: f1p } = this.wNAF(k1);\n let { p: k2p, f: f2p } = this.wNAF(k2);\n k1p = wnaf.constTimeNegate(k1neg, k1p);\n k2p = wnaf.constTimeNegate(k2neg, k2p);\n k2p = new Point(Fp.mul(k2p.px, endo.beta), k2p.py, k2p.pz);\n point = k1p.add(k2p);\n fake = f1p.add(f2p);\n } else {\n const { p, f } = this.wNAF(n);\n point = p;\n fake = f;\n }\n // Normalize `z` for both points, but return only real one\n return Point.normalizeZ([point, fake])[0];\n }\n\n /**\n * Efficiently calculate `aP + bQ`. Unsafe, can expose private key, if used incorrectly.\n * Not using Strauss-Shamir trick: precomputation tables are faster.\n * The trick could be useful if both P and Q are not G (not in our case).\n * @returns non-zero affine point\n */\n multiplyAndAddUnsafe(Q: Point, a: bigint, b: bigint): Point | undefined {\n const G = Point.BASE; // No Strauss-Shamir trick: we have 10% faster G precomputes\n const mul = (\n P: Point,\n a: bigint // Select faster multiply() method\n ) => (a === _0n || a === _1n || !P.equals(G) ? P.multiplyUnsafe(a) : P.multiply(a));\n const sum = mul(this, a).add(mul(Q, b));\n return sum.is0() ? undefined : sum;\n }\n\n // Converts Projective point to affine (x, y) coordinates.\n // Can accept precomputed Z^-1 - for example, from invertBatch.\n // (x, y, z) ∋ (x=x/z, y=y/z)\n toAffine(iz?: T): AffinePoint {\n const { px: x, py: y, pz: z } = this;\n const is0 = this.is0();\n // If invZ was 0, we return zero point. However we still want to execute\n // all operations, so we replace invZ with a random number, 1.\n if (iz == null) iz = is0 ? Fp.ONE : Fp.inv(z);\n const ax = Fp.mul(x, iz);\n const ay = Fp.mul(y, iz);\n const zz = Fp.mul(z, iz);\n if (is0) return { x: Fp.ZERO, y: Fp.ZERO };\n if (!Fp.eql(zz, Fp.ONE)) throw new Error('invZ was invalid');\n return { x: ax, y: ay };\n }\n isTorsionFree(): boolean {\n const { h: cofactor, isTorsionFree } = CURVE;\n if (cofactor === _1n) return true; // No subgroups, always torsion-free\n if (isTorsionFree) return isTorsionFree(Point, this);\n throw new Error('isTorsionFree() has not been declared for the elliptic curve');\n }\n clearCofactor(): Point {\n const { h: cofactor, clearCofactor } = CURVE;\n if (cofactor === _1n) return this; // Fast-path\n if (clearCofactor) return clearCofactor(Point, this) as Point;\n return this.multiplyUnsafe(CURVE.h);\n }\n\n toRawBytes(isCompressed = true): Uint8Array {\n this.assertValidity();\n return toBytes(Point, this, isCompressed);\n }\n\n toHex(isCompressed = true): string {\n return ut.bytesToHex(this.toRawBytes(isCompressed));\n }\n }\n const _bits = CURVE.nBitLength;\n const wnaf = wNAF(Point, CURVE.endo ? Math.ceil(_bits / 2) : _bits);\n // Validate if generator point is on curve\n return {\n CURVE,\n ProjectivePoint: Point as ProjConstructor,\n normPrivateKeyToScalar,\n weierstrassEquation,\n isWithinCurveOrder,\n };\n}\n\n// Instance\nexport interface SignatureType {\n readonly r: bigint;\n readonly s: bigint;\n readonly recovery?: number;\n assertValidity(): void;\n addRecoveryBit(recovery: number): RecoveredSignatureType;\n hasHighS(): boolean;\n normalizeS(): SignatureType;\n recoverPublicKey(msgHash: Hex): ProjPointType;\n toCompactRawBytes(): Uint8Array;\n toCompactHex(): string;\n // DER-encoded\n toDERRawBytes(isCompressed?: boolean): Uint8Array;\n toDERHex(isCompressed?: boolean): string;\n}\nexport type RecoveredSignatureType = SignatureType & {\n readonly recovery: number;\n};\n// Static methods\nexport type SignatureConstructor = {\n new (r: bigint, s: bigint): SignatureType;\n fromCompact(hex: Hex): SignatureType;\n fromDER(hex: Hex): SignatureType;\n};\ntype SignatureLike = { r: bigint; s: bigint };\n\nexport type PubKey = Hex | ProjPointType;\n\nexport type CurveType = BasicWCurve & {\n hash: CHash; // CHash not FHash because we need outputLen for DRBG\n hmac: HmacFnSync;\n randomBytes: (bytesLength?: number) => Uint8Array;\n lowS?: boolean;\n bits2int?: (bytes: Uint8Array) => bigint;\n bits2int_modN?: (bytes: Uint8Array) => bigint;\n};\n\nfunction validateOpts(curve: CurveType) {\n const opts = validateBasic(curve);\n ut.validateObject(\n opts,\n {\n hash: 'hash',\n hmac: 'function',\n randomBytes: 'function',\n },\n {\n bits2int: 'function',\n bits2int_modN: 'function',\n lowS: 'boolean',\n }\n );\n return Object.freeze({ lowS: true, ...opts } as const);\n}\n\nexport type CurveFn = {\n CURVE: ReturnType;\n getPublicKey: (privateKey: PrivKey, isCompressed?: boolean) => Uint8Array;\n getSharedSecret: (privateA: PrivKey, publicB: Hex, isCompressed?: boolean) => Uint8Array;\n sign: (msgHash: Hex, privKey: PrivKey, opts?: SignOpts) => RecoveredSignatureType;\n verify: (signature: Hex | SignatureLike, msgHash: Hex, publicKey: Hex, opts?: VerOpts) => boolean;\n ProjectivePoint: ProjConstructor;\n Signature: SignatureConstructor;\n utils: {\n normPrivateKeyToScalar: (key: PrivKey) => bigint;\n isValidPrivateKey(privateKey: PrivKey): boolean;\n randomPrivateKey: () => Uint8Array;\n precompute: (windowSize?: number, point?: ProjPointType) => ProjPointType;\n };\n};\n\nexport function weierstrass(curveDef: CurveType): CurveFn {\n const CURVE = validateOpts(curveDef) as ReturnType;\n const { Fp, n: CURVE_ORDER } = CURVE;\n const compressedLen = Fp.BYTES + 1; // e.g. 33 for 32\n const uncompressedLen = 2 * Fp.BYTES + 1; // e.g. 65 for 32\n\n function isValidFieldElement(num: bigint): boolean {\n return _0n < num && num < Fp.ORDER; // 0 is banned since it's not invertible FE\n }\n function modN(a: bigint) {\n return mod.mod(a, CURVE_ORDER);\n }\n function invN(a: bigint) {\n return mod.invert(a, CURVE_ORDER);\n }\n\n const {\n ProjectivePoint: Point,\n normPrivateKeyToScalar,\n weierstrassEquation,\n isWithinCurveOrder,\n } = weierstrassPoints({\n ...CURVE,\n toBytes(_c, point, isCompressed: boolean): Uint8Array {\n const a = point.toAffine();\n const x = Fp.toBytes(a.x);\n const cat = ut.concatBytes;\n if (isCompressed) {\n return cat(Uint8Array.from([point.hasEvenY() ? 0x02 : 0x03]), x);\n } else {\n return cat(Uint8Array.from([0x04]), x, Fp.toBytes(a.y));\n }\n },\n fromBytes(bytes: Uint8Array) {\n const len = bytes.length;\n const head = bytes[0];\n const tail = bytes.subarray(1);\n // this.assertValidity() is done inside of fromHex\n if (len === compressedLen && (head === 0x02 || head === 0x03)) {\n const x = ut.bytesToNumberBE(tail);\n if (!isValidFieldElement(x)) throw new Error('Point is not on curve');\n const y2 = weierstrassEquation(x); // y² = x³ + ax + b\n let y = Fp.sqrt(y2); // y = y² ^ (p+1)/4\n const isYOdd = (y & _1n) === _1n;\n // ECDSA\n const isHeadOdd = (head & 1) === 1;\n if (isHeadOdd !== isYOdd) y = Fp.neg(y);\n return { x, y };\n } else if (len === uncompressedLen && head === 0x04) {\n const x = Fp.fromBytes(tail.subarray(0, Fp.BYTES));\n const y = Fp.fromBytes(tail.subarray(Fp.BYTES, 2 * Fp.BYTES));\n return { x, y };\n } else {\n throw new Error(\n `Point of length ${len} was invalid. Expected ${compressedLen} compressed bytes or ${uncompressedLen} uncompressed bytes`\n );\n }\n },\n });\n const numToNByteStr = (num: bigint): string =>\n ut.bytesToHex(ut.numberToBytesBE(num, CURVE.nByteLength));\n\n function isBiggerThanHalfOrder(number: bigint) {\n const HALF = CURVE_ORDER >> _1n;\n return number > HALF;\n }\n\n function normalizeS(s: bigint) {\n return isBiggerThanHalfOrder(s) ? modN(-s) : s;\n }\n // slice bytes num\n const slcNum = (b: Uint8Array, from: number, to: number) => ut.bytesToNumberBE(b.slice(from, to));\n\n /**\n * ECDSA signature with its (r, s) properties. Supports DER & compact representations.\n */\n class Signature implements SignatureType {\n constructor(readonly r: bigint, readonly s: bigint, readonly recovery?: number) {\n this.assertValidity();\n }\n\n // pair (bytes of r, bytes of s)\n static fromCompact(hex: Hex) {\n const l = CURVE.nByteLength;\n hex = ensureBytes('compactSignature', hex, l * 2);\n return new Signature(slcNum(hex, 0, l), slcNum(hex, l, 2 * l));\n }\n\n // DER encoded ECDSA signature\n // https://bitcoin.stackexchange.com/questions/57644/what-are-the-parts-of-a-bitcoin-transaction-input-script\n static fromDER(hex: Hex) {\n const { r, s } = DER.toSig(ensureBytes('DER', hex));\n return new Signature(r, s);\n }\n\n assertValidity(): void {\n // can use assertGE here\n if (!isWithinCurveOrder(this.r)) throw new Error('r must be 0 < r < CURVE.n');\n if (!isWithinCurveOrder(this.s)) throw new Error('s must be 0 < s < CURVE.n');\n }\n\n addRecoveryBit(recovery: number): RecoveredSignature {\n return new Signature(this.r, this.s, recovery) as RecoveredSignature;\n }\n\n recoverPublicKey(msgHash: Hex): typeof Point.BASE {\n const { r, s, recovery: rec } = this;\n const h = bits2int_modN(ensureBytes('msgHash', msgHash)); // Truncate hash\n if (rec == null || ![0, 1, 2, 3].includes(rec)) throw new Error('recovery id invalid');\n const radj = rec === 2 || rec === 3 ? r + CURVE.n : r;\n if (radj >= Fp.ORDER) throw new Error('recovery id 2 or 3 invalid');\n const prefix = (rec & 1) === 0 ? '02' : '03';\n const R = Point.fromHex(prefix + numToNByteStr(radj));\n const ir = invN(radj); // r^-1\n const u1 = modN(-h * ir); // -hr^-1\n const u2 = modN(s * ir); // sr^-1\n const Q = Point.BASE.multiplyAndAddUnsafe(R, u1, u2); // (sr^-1)R-(hr^-1)G = -(hr^-1)G + (sr^-1)\n if (!Q) throw new Error('point at infinify'); // unsafe is fine: no priv data leaked\n Q.assertValidity();\n return Q;\n }\n\n // Signatures should be low-s, to prevent malleability.\n hasHighS(): boolean {\n return isBiggerThanHalfOrder(this.s);\n }\n\n normalizeS() {\n return this.hasHighS() ? new Signature(this.r, modN(-this.s), this.recovery) : this;\n }\n\n // DER-encoded\n toDERRawBytes() {\n return ut.hexToBytes(this.toDERHex());\n }\n toDERHex() {\n return DER.hexFromSig({ r: this.r, s: this.s });\n }\n\n // padded bytes of r, then padded bytes of s\n toCompactRawBytes() {\n return ut.hexToBytes(this.toCompactHex());\n }\n toCompactHex() {\n return numToNByteStr(this.r) + numToNByteStr(this.s);\n }\n }\n type RecoveredSignature = Signature & { recovery: number };\n\n const utils = {\n isValidPrivateKey(privateKey: PrivKey) {\n try {\n normPrivateKeyToScalar(privateKey);\n return true;\n } catch (error) {\n return false;\n }\n },\n normPrivateKeyToScalar: normPrivateKeyToScalar,\n\n /**\n * Produces cryptographically secure private key from random of size\n * (groupLen + ceil(groupLen / 2)) with modulo bias being negligible.\n */\n randomPrivateKey: (): Uint8Array => {\n const length = mod.getMinHashLength(CURVE.n);\n return mod.mapHashToField(CURVE.randomBytes(length), CURVE.n);\n },\n\n /**\n * Creates precompute table for an arbitrary EC point. Makes point \"cached\".\n * Allows to massively speed-up `point.multiply(scalar)`.\n * @returns cached point\n * @example\n * const fast = utils.precompute(8, ProjectivePoint.fromHex(someonesPubKey));\n * fast.multiply(privKey); // much faster ECDH now\n */\n precompute(windowSize = 8, point = Point.BASE): typeof Point.BASE {\n point._setWindowSize(windowSize);\n point.multiply(BigInt(3)); // 3 is arbitrary, just need any number here\n return point;\n },\n };\n\n /**\n * Computes public key for a private key. Checks for validity of the private key.\n * @param privateKey private key\n * @param isCompressed whether to return compact (default), or full key\n * @returns Public key, full when isCompressed=false; short when isCompressed=true\n */\n function getPublicKey(privateKey: PrivKey, isCompressed = true): Uint8Array {\n return Point.fromPrivateKey(privateKey).toRawBytes(isCompressed);\n }\n\n /**\n * Quick and dirty check for item being public key. Does not validate hex, or being on-curve.\n */\n function isProbPub(item: PrivKey | PubKey): boolean {\n const arr = item instanceof Uint8Array;\n const str = typeof item === 'string';\n const len = (arr || str) && (item as Hex).length;\n if (arr) return len === compressedLen || len === uncompressedLen;\n if (str) return len === 2 * compressedLen || len === 2 * uncompressedLen;\n if (item instanceof Point) return true;\n return false;\n }\n\n /**\n * ECDH (Elliptic Curve Diffie Hellman).\n * Computes shared public key from private key and public key.\n * Checks: 1) private key validity 2) shared key is on-curve.\n * Does NOT hash the result.\n * @param privateA private key\n * @param publicB different public key\n * @param isCompressed whether to return compact (default), or full key\n * @returns shared public key\n */\n function getSharedSecret(privateA: PrivKey, publicB: Hex, isCompressed = true): Uint8Array {\n if (isProbPub(privateA)) throw new Error('first arg must be private key');\n if (!isProbPub(publicB)) throw new Error('second arg must be public key');\n const b = Point.fromHex(publicB); // check for being on-curve\n return b.multiply(normPrivateKeyToScalar(privateA)).toRawBytes(isCompressed);\n }\n\n // RFC6979: ensure ECDSA msg is X bytes and < N. RFC suggests optional truncating via bits2octets.\n // FIPS 186-4 4.6 suggests the leftmost min(nBitLen, outLen) bits, which matches bits2int.\n // bits2int can produce res>N, we can do mod(res, N) since the bitLen is the same.\n // int2octets can't be used; pads small msgs with 0: unacceptatble for trunc as per RFC vectors\n const bits2int =\n CURVE.bits2int ||\n function (bytes: Uint8Array): bigint {\n // For curves with nBitLength % 8 !== 0: bits2octets(bits2octets(m)) !== bits2octets(m)\n // for some cases, since bytes.length * 8 is not actual bitLength.\n const num = ut.bytesToNumberBE(bytes); // check for == u8 done here\n const delta = bytes.length * 8 - CURVE.nBitLength; // truncate to nBitLength leftmost bits\n return delta > 0 ? num >> BigInt(delta) : num;\n };\n const bits2int_modN =\n CURVE.bits2int_modN ||\n function (bytes: Uint8Array): bigint {\n return modN(bits2int(bytes)); // can't use bytesToNumberBE here\n };\n // NOTE: pads output with zero as per spec\n const ORDER_MASK = ut.bitMask(CURVE.nBitLength);\n /**\n * Converts to bytes. Checks if num in `[0..ORDER_MASK-1]` e.g.: `[0..2^256-1]`.\n */\n function int2octets(num: bigint): Uint8Array {\n if (typeof num !== 'bigint') throw new Error('bigint expected');\n if (!(_0n <= num && num < ORDER_MASK))\n throw new Error(`bigint expected < 2^${CURVE.nBitLength}`);\n // works with order, can have different size than numToField!\n return ut.numberToBytesBE(num, CURVE.nByteLength);\n }\n\n // Steps A, D of RFC6979 3.2\n // Creates RFC6979 seed; converts msg/privKey to numbers.\n // Used only in sign, not in verify.\n // NOTE: we cannot assume here that msgHash has same amount of bytes as curve order, this will be wrong at least for P521.\n // Also it can be bigger for P224 + SHA256\n function prepSig(msgHash: Hex, privateKey: PrivKey, opts = defaultSigOpts) {\n if (['recovered', 'canonical'].some((k) => k in opts))\n throw new Error('sign() legacy options not supported');\n const { hash, randomBytes } = CURVE;\n let { lowS, prehash, extraEntropy: ent } = opts; // generates low-s sigs by default\n if (lowS == null) lowS = true; // RFC6979 3.2: we skip step A, because we already provide hash\n msgHash = ensureBytes('msgHash', msgHash);\n if (prehash) msgHash = ensureBytes('prehashed msgHash', hash(msgHash));\n\n // We can't later call bits2octets, since nested bits2int is broken for curves\n // with nBitLength % 8 !== 0. Because of that, we unwrap it here as int2octets call.\n // const bits2octets = (bits) => int2octets(bits2int_modN(bits))\n const h1int = bits2int_modN(msgHash);\n const d = normPrivateKeyToScalar(privateKey); // validate private key, convert to bigint\n const seedArgs = [int2octets(d), int2octets(h1int)];\n // extraEntropy. RFC6979 3.6: additional k' (optional).\n if (ent != null) {\n // K = HMAC_K(V || 0x00 || int2octets(x) || bits2octets(h1) || k')\n const e = ent === true ? randomBytes(Fp.BYTES) : ent; // generate random bytes OR pass as-is\n seedArgs.push(ensureBytes('extraEntropy', e)); // check for being bytes\n }\n const seed = ut.concatBytes(...seedArgs); // Step D of RFC6979 3.2\n const m = h1int; // NOTE: no need to call bits2int second time here, it is inside truncateHash!\n // Converts signature params into point w r/s, checks result for validity.\n function k2sig(kBytes: Uint8Array): RecoveredSignature | undefined {\n // RFC 6979 Section 3.2, step 3: k = bits2int(T)\n const k = bits2int(kBytes); // Cannot use fields methods, since it is group element\n if (!isWithinCurveOrder(k)) return; // Important: all mod() calls here must be done over N\n const ik = invN(k); // k^-1 mod n\n const q = Point.BASE.multiply(k).toAffine(); // q = Gk\n const r = modN(q.x); // r = q.x mod n\n if (r === _0n) return;\n // Can use scalar blinding b^-1(bm + bdr) where b ∈ [1,q−1] according to\n // https://tches.iacr.org/index.php/TCHES/article/view/7337/6509. We've decided against it:\n // a) dependency on CSPRNG b) 15% slowdown c) doesn't really help since bigints are not CT\n const s = modN(ik * modN(m + r * d)); // Not using blinding here\n if (s === _0n) return;\n let recovery = (q.x === r ? 0 : 2) | Number(q.y & _1n); // recovery bit (2 or 3, when q.x > n)\n let normS = s;\n if (lowS && isBiggerThanHalfOrder(s)) {\n normS = normalizeS(s); // if lowS was passed, ensure s is always\n recovery ^= 1; // // in the bottom half of N\n }\n return new Signature(r, normS, recovery) as RecoveredSignature; // use normS, not s\n }\n return { seed, k2sig };\n }\n const defaultSigOpts: SignOpts = { lowS: CURVE.lowS, prehash: false };\n const defaultVerOpts: VerOpts = { lowS: CURVE.lowS, prehash: false };\n\n /**\n * Signs message hash with a private key.\n * ```\n * sign(m, d, k) where\n * (x, y) = G × k\n * r = x mod n\n * s = (m + dr)/k mod n\n * ```\n * @param msgHash NOT message. msg needs to be hashed to `msgHash`, or use `prehash`.\n * @param privKey private key\n * @param opts lowS for non-malleable sigs. extraEntropy for mixing randomness into k. prehash will hash first arg.\n * @returns signature with recovery param\n */\n function sign(msgHash: Hex, privKey: PrivKey, opts = defaultSigOpts): RecoveredSignature {\n const { seed, k2sig } = prepSig(msgHash, privKey, opts); // Steps A, D of RFC6979 3.2.\n const C = CURVE;\n const drbg = ut.createHmacDrbg(C.hash.outputLen, C.nByteLength, C.hmac);\n return drbg(seed, k2sig); // Steps B, C, D, E, F, G\n }\n\n // Enable precomputes. Slows down first publicKey computation by 20ms.\n Point.BASE._setWindowSize(8);\n // utils.precompute(8, ProjectivePoint.BASE)\n\n /**\n * Verifies a signature against message hash and public key.\n * Rejects lowS signatures by default: to override,\n * specify option `{lowS: false}`. Implements section 4.1.4 from https://www.secg.org/sec1-v2.pdf:\n *\n * ```\n * verify(r, s, h, P) where\n * U1 = hs^-1 mod n\n * U2 = rs^-1 mod n\n * R = U1⋅G - U2⋅P\n * mod(R.x, n) == r\n * ```\n */\n function verify(\n signature: Hex | SignatureLike,\n msgHash: Hex,\n publicKey: Hex,\n opts = defaultVerOpts\n ): boolean {\n const sg = signature;\n msgHash = ensureBytes('msgHash', msgHash);\n publicKey = ensureBytes('publicKey', publicKey);\n if ('strict' in opts) throw new Error('options.strict was renamed to lowS');\n const { lowS, prehash } = opts;\n\n let _sig: Signature | undefined = undefined;\n let P: ProjPointType;\n try {\n if (typeof sg === 'string' || sg instanceof Uint8Array) {\n // Signature can be represented in 2 ways: compact (2*nByteLength) & DER (variable-length).\n // Since DER can also be 2*nByteLength bytes, we check for it first.\n try {\n _sig = Signature.fromDER(sg);\n } catch (derError) {\n if (!(derError instanceof DER.Err)) throw derError;\n _sig = Signature.fromCompact(sg);\n }\n } else if (typeof sg === 'object' && typeof sg.r === 'bigint' && typeof sg.s === 'bigint') {\n const { r, s } = sg;\n _sig = new Signature(r, s);\n } else {\n throw new Error('PARSE');\n }\n P = Point.fromHex(publicKey);\n } catch (error) {\n if ((error as Error).message === 'PARSE')\n throw new Error(`signature must be Signature instance, Uint8Array or hex string`);\n return false;\n }\n if (lowS && _sig.hasHighS()) return false;\n if (prehash) msgHash = CURVE.hash(msgHash);\n const { r, s } = _sig;\n const h = bits2int_modN(msgHash); // Cannot use fields methods, since it is group element\n const is = invN(s); // s^-1\n const u1 = modN(h * is); // u1 = hs^-1 mod n\n const u2 = modN(r * is); // u2 = rs^-1 mod n\n const R = Point.BASE.multiplyAndAddUnsafe(P, u1, u2)?.toAffine(); // R = u1⋅G + u2⋅P\n if (!R) return false;\n const v = modN(R.x);\n return v === r;\n }\n return {\n CURVE,\n getPublicKey,\n getSharedSecret,\n sign,\n verify,\n ProjectivePoint: Point,\n Signature,\n utils,\n };\n}\n\n/**\n * Implementation of the Shallue and van de Woestijne method for any weierstrass curve.\n * TODO: check if there is a way to merge this with uvRatio in Edwards; move to modular.\n * b = True and y = sqrt(u / v) if (u / v) is square in F, and\n * b = False and y = sqrt(Z * (u / v)) otherwise.\n * @param Fp\n * @param Z\n * @returns\n */\nexport function SWUFpSqrtRatio(Fp: mod.IField, Z: T) {\n // Generic implementation\n const q = Fp.ORDER;\n let l = _0n;\n for (let o = q - _1n; o % _2n === _0n; o /= _2n) l += _1n;\n const c1 = l; // 1. c1, the largest integer such that 2^c1 divides q - 1.\n // We need 2n ** c1 and 2n ** (c1-1). We can't use **; but we can use <<.\n // 2n ** c1 == 2n << (c1-1)\n const _2n_pow_c1_1 = _2n << (c1 - _1n - _1n);\n const _2n_pow_c1 = _2n_pow_c1_1 * _2n;\n const c2 = (q - _1n) / _2n_pow_c1; // 2. c2 = (q - 1) / (2^c1) # Integer arithmetic\n const c3 = (c2 - _1n) / _2n; // 3. c3 = (c2 - 1) / 2 # Integer arithmetic\n const c4 = _2n_pow_c1 - _1n; // 4. c4 = 2^c1 - 1 # Integer arithmetic\n const c5 = _2n_pow_c1_1; // 5. c5 = 2^(c1 - 1) # Integer arithmetic\n const c6 = Fp.pow(Z, c2); // 6. c6 = Z^c2\n const c7 = Fp.pow(Z, (c2 + _1n) / _2n); // 7. c7 = Z^((c2 + 1) / 2)\n let sqrtRatio = (u: T, v: T): { isValid: boolean; value: T } => {\n let tv1 = c6; // 1. tv1 = c6\n let tv2 = Fp.pow(v, c4); // 2. tv2 = v^c4\n let tv3 = Fp.sqr(tv2); // 3. tv3 = tv2^2\n tv3 = Fp.mul(tv3, v); // 4. tv3 = tv3 * v\n let tv5 = Fp.mul(u, tv3); // 5. tv5 = u * tv3\n tv5 = Fp.pow(tv5, c3); // 6. tv5 = tv5^c3\n tv5 = Fp.mul(tv5, tv2); // 7. tv5 = tv5 * tv2\n tv2 = Fp.mul(tv5, v); // 8. tv2 = tv5 * v\n tv3 = Fp.mul(tv5, u); // 9. tv3 = tv5 * u\n let tv4 = Fp.mul(tv3, tv2); // 10. tv4 = tv3 * tv2\n tv5 = Fp.pow(tv4, c5); // 11. tv5 = tv4^c5\n let isQR = Fp.eql(tv5, Fp.ONE); // 12. isQR = tv5 == 1\n tv2 = Fp.mul(tv3, c7); // 13. tv2 = tv3 * c7\n tv5 = Fp.mul(tv4, tv1); // 14. tv5 = tv4 * tv1\n tv3 = Fp.cmov(tv2, tv3, isQR); // 15. tv3 = CMOV(tv2, tv3, isQR)\n tv4 = Fp.cmov(tv5, tv4, isQR); // 16. tv4 = CMOV(tv5, tv4, isQR)\n // 17. for i in (c1, c1 - 1, ..., 2):\n for (let i = c1; i > _1n; i--) {\n let tv5 = i - _2n; // 18. tv5 = i - 2\n tv5 = _2n << (tv5 - _1n); // 19. tv5 = 2^tv5\n let tvv5 = Fp.pow(tv4, tv5); // 20. tv5 = tv4^tv5\n const e1 = Fp.eql(tvv5, Fp.ONE); // 21. e1 = tv5 == 1\n tv2 = Fp.mul(tv3, tv1); // 22. tv2 = tv3 * tv1\n tv1 = Fp.mul(tv1, tv1); // 23. tv1 = tv1 * tv1\n tvv5 = Fp.mul(tv4, tv1); // 24. tv5 = tv4 * tv1\n tv3 = Fp.cmov(tv2, tv3, e1); // 25. tv3 = CMOV(tv2, tv3, e1)\n tv4 = Fp.cmov(tvv5, tv4, e1); // 26. tv4 = CMOV(tv5, tv4, e1)\n }\n return { isValid: isQR, value: tv3 };\n };\n if (Fp.ORDER % _4n === _3n) {\n // sqrt_ratio_3mod4(u, v)\n const c1 = (Fp.ORDER - _3n) / _4n; // 1. c1 = (q - 3) / 4 # Integer arithmetic\n const c2 = Fp.sqrt(Fp.neg(Z)); // 2. c2 = sqrt(-Z)\n sqrtRatio = (u: T, v: T) => {\n let tv1 = Fp.sqr(v); // 1. tv1 = v^2\n const tv2 = Fp.mul(u, v); // 2. tv2 = u * v\n tv1 = Fp.mul(tv1, tv2); // 3. tv1 = tv1 * tv2\n let y1 = Fp.pow(tv1, c1); // 4. y1 = tv1^c1\n y1 = Fp.mul(y1, tv2); // 5. y1 = y1 * tv2\n const y2 = Fp.mul(y1, c2); // 6. y2 = y1 * c2\n const tv3 = Fp.mul(Fp.sqr(y1), v); // 7. tv3 = y1^2; 8. tv3 = tv3 * v\n const isQR = Fp.eql(tv3, u); // 9. isQR = tv3 == u\n let y = Fp.cmov(y2, y1, isQR); // 10. y = CMOV(y2, y1, isQR)\n return { isValid: isQR, value: y }; // 11. return (isQR, y) isQR ? y : y*c2\n };\n }\n // No curves uses that\n // if (Fp.ORDER % _8n === _5n) // sqrt_ratio_5mod8\n return sqrtRatio;\n}\n/**\n * Simplified Shallue-van de Woestijne-Ulas Method\n * https://www.rfc-editor.org/rfc/rfc9380#section-6.6.2\n */\nexport function mapToCurveSimpleSWU(\n Fp: mod.IField,\n opts: {\n A: T;\n B: T;\n Z: T;\n }\n) {\n mod.validateField(Fp);\n if (!Fp.isValid(opts.A) || !Fp.isValid(opts.B) || !Fp.isValid(opts.Z))\n throw new Error('mapToCurveSimpleSWU: invalid opts');\n const sqrtRatio = SWUFpSqrtRatio(Fp, opts.Z);\n if (!Fp.isOdd) throw new Error('Fp.isOdd is not implemented!');\n // Input: u, an element of F.\n // Output: (x, y), a point on E.\n return (u: T): { x: T; y: T } => {\n // prettier-ignore\n let tv1, tv2, tv3, tv4, tv5, tv6, x, y;\n tv1 = Fp.sqr(u); // 1. tv1 = u^2\n tv1 = Fp.mul(tv1, opts.Z); // 2. tv1 = Z * tv1\n tv2 = Fp.sqr(tv1); // 3. tv2 = tv1^2\n tv2 = Fp.add(tv2, tv1); // 4. tv2 = tv2 + tv1\n tv3 = Fp.add(tv2, Fp.ONE); // 5. tv3 = tv2 + 1\n tv3 = Fp.mul(tv3, opts.B); // 6. tv3 = B * tv3\n tv4 = Fp.cmov(opts.Z, Fp.neg(tv2), !Fp.eql(tv2, Fp.ZERO)); // 7. tv4 = CMOV(Z, -tv2, tv2 != 0)\n tv4 = Fp.mul(tv4, opts.A); // 8. tv4 = A * tv4\n tv2 = Fp.sqr(tv3); // 9. tv2 = tv3^2\n tv6 = Fp.sqr(tv4); // 10. tv6 = tv4^2\n tv5 = Fp.mul(tv6, opts.A); // 11. tv5 = A * tv6\n tv2 = Fp.add(tv2, tv5); // 12. tv2 = tv2 + tv5\n tv2 = Fp.mul(tv2, tv3); // 13. tv2 = tv2 * tv3\n tv6 = Fp.mul(tv6, tv4); // 14. tv6 = tv6 * tv4\n tv5 = Fp.mul(tv6, opts.B); // 15. tv5 = B * tv6\n tv2 = Fp.add(tv2, tv5); // 16. tv2 = tv2 + tv5\n x = Fp.mul(tv1, tv3); // 17. x = tv1 * tv3\n const { isValid, value } = sqrtRatio(tv2, tv6); // 18. (is_gx1_square, y1) = sqrt_ratio(tv2, tv6)\n y = Fp.mul(tv1, u); // 19. y = tv1 * u -> Z * u^3 * y1\n y = Fp.mul(y, value); // 20. y = y * y1\n x = Fp.cmov(x, tv3, isValid); // 21. x = CMOV(x, tv3, is_gx1_square)\n y = Fp.cmov(y, value, isValid); // 22. y = CMOV(y, y1, is_gx1_square)\n const e1 = Fp.isOdd!(u) === Fp.isOdd!(y); // 23. e1 = sgn0(u) == sgn0(y)\n y = Fp.cmov(Fp.neg(y), y, e1); // 24. y = CMOV(-y, y, e1)\n x = Fp.div(x, tv4); // 25. x = x / tv4\n return { x, y };\n };\n}\n", "/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport type { Group, GroupConstructor, AffinePoint } from './curve.js';\nimport { mod, IField } from './modular.js';\nimport { bytesToNumberBE, CHash, concatBytes, utf8ToBytes, validateObject } from './utils.js';\n\n/**\n * * `DST` is a domain separation tag, defined in section 2.2.5\n * * `p` characteristic of F, where F is a finite field of characteristic p and order q = p^m\n * * `m` is extension degree (1 for prime fields)\n * * `k` is the target security target in bits (e.g. 128), from section 5.1\n * * `expand` is `xmd` (SHA2, SHA3, BLAKE) or `xof` (SHAKE, BLAKE-XOF)\n * * `hash` conforming to `utils.CHash` interface, with `outputLen` / `blockLen` props\n */\ntype UnicodeOrBytes = string | Uint8Array;\nexport type Opts = {\n DST: UnicodeOrBytes;\n p: bigint;\n m: number;\n k: number;\n expand: 'xmd' | 'xof';\n hash: CHash;\n};\n\nfunction validateDST(dst: UnicodeOrBytes): Uint8Array {\n if (dst instanceof Uint8Array) return dst;\n if (typeof dst === 'string') return utf8ToBytes(dst);\n throw new Error('DST must be Uint8Array or string');\n}\n\n// Octet Stream to Integer. \"spec\" implementation of os2ip is 2.5x slower vs bytesToNumberBE.\nconst os2ip = bytesToNumberBE;\n\n// Integer to Octet Stream (numberToBytesBE)\nfunction i2osp(value: number, length: number): Uint8Array {\n if (value < 0 || value >= 1 << (8 * length)) {\n throw new Error(`bad I2OSP call: value=${value} length=${length}`);\n }\n const res = Array.from({ length }).fill(0) as number[];\n for (let i = length - 1; i >= 0; i--) {\n res[i] = value & 0xff;\n value >>>= 8;\n }\n return new Uint8Array(res);\n}\n\nfunction strxor(a: Uint8Array, b: Uint8Array): Uint8Array {\n const arr = new Uint8Array(a.length);\n for (let i = 0; i < a.length; i++) {\n arr[i] = a[i] ^ b[i];\n }\n return arr;\n}\n\nfunction isBytes(item: unknown): void {\n if (!(item instanceof Uint8Array)) throw new Error('Uint8Array expected');\n}\nfunction isNum(item: unknown): void {\n if (!Number.isSafeInteger(item)) throw new Error('number expected');\n}\n\n// Produces a uniformly random byte string using a cryptographic hash function H that outputs b bits\n// https://www.rfc-editor.org/rfc/rfc9380#section-5.3.1\nexport function expand_message_xmd(\n msg: Uint8Array,\n DST: Uint8Array,\n lenInBytes: number,\n H: CHash\n): Uint8Array {\n isBytes(msg);\n isBytes(DST);\n isNum(lenInBytes);\n // https://www.rfc-editor.org/rfc/rfc9380#section-5.3.3\n if (DST.length > 255) DST = H(concatBytes(utf8ToBytes('H2C-OVERSIZE-DST-'), DST));\n const { outputLen: b_in_bytes, blockLen: r_in_bytes } = H;\n const ell = Math.ceil(lenInBytes / b_in_bytes);\n if (ell > 255) throw new Error('Invalid xmd length');\n const DST_prime = concatBytes(DST, i2osp(DST.length, 1));\n const Z_pad = i2osp(0, r_in_bytes);\n const l_i_b_str = i2osp(lenInBytes, 2); // len_in_bytes_str\n const b = new Array(ell);\n const b_0 = H(concatBytes(Z_pad, msg, l_i_b_str, i2osp(0, 1), DST_prime));\n b[0] = H(concatBytes(b_0, i2osp(1, 1), DST_prime));\n for (let i = 1; i <= ell; i++) {\n const args = [strxor(b_0, b[i - 1]), i2osp(i + 1, 1), DST_prime];\n b[i] = H(concatBytes(...args));\n }\n const pseudo_random_bytes = concatBytes(...b);\n return pseudo_random_bytes.slice(0, lenInBytes);\n}\n\n// Produces a uniformly random byte string using an extendable-output function (XOF) H.\n// 1. The collision resistance of H MUST be at least k bits.\n// 2. H MUST be an XOF that has been proved indifferentiable from\n// a random oracle under a reasonable cryptographic assumption.\n// https://www.rfc-editor.org/rfc/rfc9380#section-5.3.2\nexport function expand_message_xof(\n msg: Uint8Array,\n DST: Uint8Array,\n lenInBytes: number,\n k: number,\n H: CHash\n): Uint8Array {\n isBytes(msg);\n isBytes(DST);\n isNum(lenInBytes);\n // https://www.rfc-editor.org/rfc/rfc9380#section-5.3.3\n // DST = H('H2C-OVERSIZE-DST-' || a_very_long_DST, Math.ceil((lenInBytes * k) / 8));\n if (DST.length > 255) {\n const dkLen = Math.ceil((2 * k) / 8);\n DST = H.create({ dkLen }).update(utf8ToBytes('H2C-OVERSIZE-DST-')).update(DST).digest();\n }\n if (lenInBytes > 65535 || DST.length > 255)\n throw new Error('expand_message_xof: invalid lenInBytes');\n return (\n H.create({ dkLen: lenInBytes })\n .update(msg)\n .update(i2osp(lenInBytes, 2))\n // 2. DST_prime = DST || I2OSP(len(DST), 1)\n .update(DST)\n .update(i2osp(DST.length, 1))\n .digest()\n );\n}\n\n/**\n * Hashes arbitrary-length byte strings to a list of one or more elements of a finite field F\n * https://www.rfc-editor.org/rfc/rfc9380#section-5.2\n * @param msg a byte string containing the message to hash\n * @param count the number of elements of F to output\n * @param options `{DST: string, p: bigint, m: number, k: number, expand: 'xmd' | 'xof', hash: H}`, see above\n * @returns [u_0, ..., u_(count - 1)], a list of field elements.\n */\nexport function hash_to_field(msg: Uint8Array, count: number, options: Opts): bigint[][] {\n validateObject(options, {\n DST: 'stringOrUint8Array',\n p: 'bigint',\n m: 'isSafeInteger',\n k: 'isSafeInteger',\n hash: 'hash',\n });\n const { p, k, m, hash, expand, DST: _DST } = options;\n isBytes(msg);\n isNum(count);\n const DST = validateDST(_DST);\n const log2p = p.toString(2).length;\n const L = Math.ceil((log2p + k) / 8); // section 5.1 of ietf draft link above\n const len_in_bytes = count * m * L;\n let prb; // pseudo_random_bytes\n if (expand === 'xmd') {\n prb = expand_message_xmd(msg, DST, len_in_bytes, hash);\n } else if (expand === 'xof') {\n prb = expand_message_xof(msg, DST, len_in_bytes, k, hash);\n } else if (expand === '_internal_pass') {\n // for internal tests only\n prb = msg;\n } else {\n throw new Error('expand must be \"xmd\" or \"xof\"');\n }\n const u = new Array(count);\n for (let i = 0; i < count; i++) {\n const e = new Array(m);\n for (let j = 0; j < m; j++) {\n const elm_offset = L * (j + i * m);\n const tv = prb.subarray(elm_offset, elm_offset + L);\n e[j] = mod(os2ip(tv), p);\n }\n u[i] = e;\n }\n return u;\n}\n\nexport function isogenyMap>(field: F, map: [T[], T[], T[], T[]]) {\n // Make same order as in spec\n const COEFF = map.map((i) => Array.from(i).reverse());\n return (x: T, y: T) => {\n const [xNum, xDen, yNum, yDen] = COEFF.map((val) =>\n val.reduce((acc, i) => field.add(field.mul(acc, x), i))\n );\n x = field.div(xNum, xDen); // xNum / xDen\n y = field.mul(y, field.div(yNum, yDen)); // y * (yNum / yDev)\n return { x, y };\n };\n}\n\nexport interface H2CPoint extends Group> {\n add(rhs: H2CPoint): H2CPoint;\n toAffine(iz?: bigint): AffinePoint;\n clearCofactor(): H2CPoint;\n assertValidity(): void;\n}\n\nexport interface H2CPointConstructor extends GroupConstructor> {\n fromAffine(ap: AffinePoint): H2CPoint;\n}\n\nexport type MapToCurve = (scalar: bigint[]) => AffinePoint;\n\n// Separated from initialization opts, so users won't accidentally change per-curve parameters\n// (changing DST is ok!)\nexport type htfBasicOpts = { DST: UnicodeOrBytes };\n\nexport function createHasher(\n Point: H2CPointConstructor,\n mapToCurve: MapToCurve,\n def: Opts & { encodeDST?: UnicodeOrBytes }\n) {\n if (typeof mapToCurve !== 'function') throw new Error('mapToCurve() must be defined');\n return {\n // Encodes byte string to elliptic curve.\n // hash_to_curve from https://www.rfc-editor.org/rfc/rfc9380#section-3\n hashToCurve(msg: Uint8Array, options?: htfBasicOpts) {\n const u = hash_to_field(msg, 2, { ...def, DST: def.DST, ...options } as Opts);\n const u0 = Point.fromAffine(mapToCurve(u[0]));\n const u1 = Point.fromAffine(mapToCurve(u[1]));\n const P = u0.add(u1).clearCofactor();\n P.assertValidity();\n return P;\n },\n\n // Encodes byte string to elliptic curve.\n // encode_to_curve from https://www.rfc-editor.org/rfc/rfc9380#section-3\n encodeToCurve(msg: Uint8Array, options?: htfBasicOpts) {\n const u = hash_to_field(msg, 1, { ...def, DST: def.encodeDST, ...options } as Opts);\n const P = Point.fromAffine(mapToCurve(u[0])).clearCofactor();\n P.assertValidity();\n return P;\n },\n };\n}\n", "import { hash as assertHash, bytes as assertBytes, exists as assertExists } from './_assert.js';\nimport { Hash, CHash, Input, toBytes } from './utils.js';\n// HMAC (RFC 2104)\nexport class HMAC> extends Hash> {\n oHash: T;\n iHash: T;\n blockLen: number;\n outputLen: number;\n private finished = false;\n private destroyed = false;\n\n constructor(hash: CHash, _key: Input) {\n super();\n assertHash(hash);\n const key = toBytes(_key);\n this.iHash = hash.create() as T;\n if (typeof this.iHash.update !== 'function')\n throw new Error('Expected instance of class which extends utils.Hash');\n this.blockLen = this.iHash.blockLen;\n this.outputLen = this.iHash.outputLen;\n const blockLen = this.blockLen;\n const pad = new Uint8Array(blockLen);\n // blockLen can be bigger than outputLen\n pad.set(key.length > blockLen ? hash.create().update(key).digest() : key);\n for (let i = 0; i < pad.length; i++) pad[i] ^= 0x36;\n this.iHash.update(pad);\n // By doing update (processing of first block) of outer hash here we can re-use it between multiple calls via clone\n this.oHash = hash.create() as T;\n // Undo internal XOR && apply outer XOR\n for (let i = 0; i < pad.length; i++) pad[i] ^= 0x36 ^ 0x5c;\n this.oHash.update(pad);\n pad.fill(0);\n }\n update(buf: Input) {\n assertExists(this);\n this.iHash.update(buf);\n return this;\n }\n digestInto(out: Uint8Array) {\n assertExists(this);\n assertBytes(out, this.outputLen);\n this.finished = true;\n this.iHash.digestInto(out);\n this.oHash.update(out);\n this.oHash.digestInto(out);\n this.destroy();\n }\n digest() {\n const out = new Uint8Array(this.oHash.outputLen);\n this.digestInto(out);\n return out;\n }\n _cloneInto(to?: HMAC): HMAC {\n // Create new instance without calling constructor since key already in state and we don't know it.\n to ||= Object.create(Object.getPrototypeOf(this), {});\n const { oHash, iHash, finished, destroyed, blockLen, outputLen } = this;\n to = to as this;\n to.finished = finished;\n to.destroyed = destroyed;\n to.blockLen = blockLen;\n to.outputLen = outputLen;\n to.oHash = oHash._cloneInto(to.oHash);\n to.iHash = iHash._cloneInto(to.iHash);\n return to;\n }\n destroy() {\n this.destroyed = true;\n this.oHash.destroy();\n this.iHash.destroy();\n }\n}\n\n/**\n * HMAC: RFC2104 message authentication code.\n * @param hash - function that would be used e.g. sha256\n * @param key - message key\n * @param message - message data\n */\nexport const hmac = (hash: CHash, key: Input, message: Input): Uint8Array =>\n new HMAC(hash, key).update(message).digest();\nhmac.create = (hash: CHash, key: Input) => new HMAC(hash, key);\n", "/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { hmac } from '@noble/hashes/hmac';\nimport { concatBytes, randomBytes } from '@noble/hashes/utils';\nimport { weierstrass, CurveType } from './abstract/weierstrass.js';\nimport { CHash } from './abstract/utils.js';\n\n// connects noble-curves to noble-hashes\nexport function getHash(hash: CHash) {\n return {\n hash,\n hmac: (key: Uint8Array, ...msgs: Uint8Array[]) => hmac(hash, key, concatBytes(...msgs)),\n randomBytes,\n };\n}\n// Same API as @noble/hashes, with ability to create curve with custom hash\ntype CurveDef = Readonly>;\nexport function createCurve(curveDef: CurveDef, defHash: CHash) {\n const create = (hash: CHash) => weierstrass({ ...curveDef, ...getHash(hash) });\n return Object.freeze({ ...create(defHash), create });\n}\n", "/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { sha256 } from '@noble/hashes/sha256';\nimport { randomBytes } from '@noble/hashes/utils';\nimport { Field, mod, pow2 } from './abstract/modular.js';\nimport { ProjPointType as PointType, mapToCurveSimpleSWU } from './abstract/weierstrass.js';\nimport type { Hex, PrivKey } from './abstract/utils.js';\nimport { bytesToNumberBE, concatBytes, ensureBytes, numberToBytesBE } from './abstract/utils.js';\nimport { createHasher, isogenyMap } from './abstract/hash-to-curve.js';\nimport { createCurve } from './_shortw_utils.js';\n\nconst secp256k1P = BigInt('0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f');\nconst secp256k1N = BigInt('0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141');\nconst _1n = BigInt(1);\nconst _2n = BigInt(2);\nconst divNearest = (a: bigint, b: bigint) => (a + b / _2n) / b;\n\n/**\n * √n = n^((p+1)/4) for fields p = 3 mod 4. We unwrap the loop and multiply bit-by-bit.\n * (P+1n/4n).toString(2) would produce bits [223x 1, 0, 22x 1, 4x 0, 11, 00]\n */\nfunction sqrtMod(y: bigint): bigint {\n const P = secp256k1P;\n // prettier-ignore\n const _3n = BigInt(3), _6n = BigInt(6), _11n = BigInt(11), _22n = BigInt(22);\n // prettier-ignore\n const _23n = BigInt(23), _44n = BigInt(44), _88n = BigInt(88);\n const b2 = (y * y * y) % P; // x^3, 11\n const b3 = (b2 * b2 * y) % P; // x^7\n const b6 = (pow2(b3, _3n, P) * b3) % P;\n const b9 = (pow2(b6, _3n, P) * b3) % P;\n const b11 = (pow2(b9, _2n, P) * b2) % P;\n const b22 = (pow2(b11, _11n, P) * b11) % P;\n const b44 = (pow2(b22, _22n, P) * b22) % P;\n const b88 = (pow2(b44, _44n, P) * b44) % P;\n const b176 = (pow2(b88, _88n, P) * b88) % P;\n const b220 = (pow2(b176, _44n, P) * b44) % P;\n const b223 = (pow2(b220, _3n, P) * b3) % P;\n const t1 = (pow2(b223, _23n, P) * b22) % P;\n const t2 = (pow2(t1, _6n, P) * b2) % P;\n const root = pow2(t2, _2n, P);\n if (!Fp.eql(Fp.sqr(root), y)) throw new Error('Cannot find square root');\n return root;\n}\n\nconst Fp = Field(secp256k1P, undefined, undefined, { sqrt: sqrtMod });\n\nexport const secp256k1 = createCurve(\n {\n a: BigInt(0), // equation params: a, b\n b: BigInt(7), // Seem to be rigid: bitcointalk.org/index.php?topic=289795.msg3183975#msg3183975\n Fp, // Field's prime: 2n**256n - 2n**32n - 2n**9n - 2n**8n - 2n**7n - 2n**6n - 2n**4n - 1n\n n: secp256k1N, // Curve order, total count of valid points in the field\n // Base point (x, y) aka generator point\n Gx: BigInt('55066263022277343669578718895168534326250603453777594175500187360389116729240'),\n Gy: BigInt('32670510020758816978083085130507043184471273380659243275938904335757337482424'),\n h: BigInt(1), // Cofactor\n lowS: true, // Allow only low-S signatures by default in sign() and verify()\n /**\n * secp256k1 belongs to Koblitz curves: it has efficiently computable endomorphism.\n * Endomorphism uses 2x less RAM, speeds up precomputation by 2x and ECDH / key recovery by 20%.\n * For precomputed wNAF it trades off 1/2 init time & 1/3 ram for 20% perf hit.\n * Explanation: https://gist.github.com/paulmillr/eb670806793e84df628a7c434a873066\n */\n endo: {\n beta: BigInt('0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee'),\n splitScalar: (k: bigint) => {\n const n = secp256k1N;\n const a1 = BigInt('0x3086d221a7d46bcde86c90e49284eb15');\n const b1 = -_1n * BigInt('0xe4437ed6010e88286f547fa90abfe4c3');\n const a2 = BigInt('0x114ca50f7a8e2f3f657c1108d9d44cfd8');\n const b2 = a1;\n const POW_2_128 = BigInt('0x100000000000000000000000000000000'); // (2n**128n).toString(16)\n\n const c1 = divNearest(b2 * k, n);\n const c2 = divNearest(-b1 * k, n);\n let k1 = mod(k - c1 * a1 - c2 * a2, n);\n let k2 = mod(-c1 * b1 - c2 * b2, n);\n const k1neg = k1 > POW_2_128;\n const k2neg = k2 > POW_2_128;\n if (k1neg) k1 = n - k1;\n if (k2neg) k2 = n - k2;\n if (k1 > POW_2_128 || k2 > POW_2_128) {\n throw new Error('splitScalar: Endomorphism failed, k=' + k);\n }\n return { k1neg, k1, k2neg, k2 };\n },\n },\n },\n sha256\n);\n\n// Schnorr signatures are superior to ECDSA from above. Below is Schnorr-specific BIP0340 code.\n// https://github.com/bitcoin/bips/blob/master/bip-0340.mediawiki\nconst _0n = BigInt(0);\nconst fe = (x: bigint) => typeof x === 'bigint' && _0n < x && x < secp256k1P;\nconst ge = (x: bigint) => typeof x === 'bigint' && _0n < x && x < secp256k1N;\n/** An object mapping tags to their tagged hash prefix of [SHA256(tag) | SHA256(tag)] */\nconst TAGGED_HASH_PREFIXES: { [tag: string]: Uint8Array } = {};\nfunction taggedHash(tag: string, ...messages: Uint8Array[]): Uint8Array {\n let tagP = TAGGED_HASH_PREFIXES[tag];\n if (tagP === undefined) {\n const tagH = sha256(Uint8Array.from(tag, (c) => c.charCodeAt(0)));\n tagP = concatBytes(tagH, tagH);\n TAGGED_HASH_PREFIXES[tag] = tagP;\n }\n return sha256(concatBytes(tagP, ...messages));\n}\n\n// ECDSA compact points are 33-byte. Schnorr is 32: we strip first byte 0x02 or 0x03\nconst pointToBytes = (point: PointType) => point.toRawBytes(true).slice(1);\nconst numTo32b = (n: bigint) => numberToBytesBE(n, 32);\nconst modP = (x: bigint) => mod(x, secp256k1P);\nconst modN = (x: bigint) => mod(x, secp256k1N);\nconst Point = secp256k1.ProjectivePoint;\nconst GmulAdd = (Q: PointType, a: bigint, b: bigint) =>\n Point.BASE.multiplyAndAddUnsafe(Q, a, b);\n\n// Calculate point, scalar and bytes\nfunction schnorrGetExtPubKey(priv: PrivKey) {\n let d_ = secp256k1.utils.normPrivateKeyToScalar(priv); // same method executed in fromPrivateKey\n let p = Point.fromPrivateKey(d_); // P = d'⋅G; 0 < d' < n check is done inside\n const scalar = p.hasEvenY() ? d_ : modN(-d_);\n return { scalar: scalar, bytes: pointToBytes(p) };\n}\n/**\n * lift_x from BIP340. Convert 32-byte x coordinate to elliptic curve point.\n * @returns valid point checked for being on-curve\n */\nfunction lift_x(x: bigint): PointType {\n if (!fe(x)) throw new Error('bad x: need 0 < x < p'); // Fail if x ≥ p.\n const xx = modP(x * x);\n const c = modP(xx * x + BigInt(7)); // Let c = x³ + 7 mod p.\n let y = sqrtMod(c); // Let y = c^(p+1)/4 mod p.\n if (y % _2n !== _0n) y = modP(-y); // Return the unique point P such that x(P) = x and\n const p = new Point(x, y, _1n); // y(P) = y if y mod 2 = 0 or y(P) = p-y otherwise.\n p.assertValidity();\n return p;\n}\n/**\n * Create tagged hash, convert it to bigint, reduce modulo-n.\n */\nfunction challenge(...args: Uint8Array[]): bigint {\n return modN(bytesToNumberBE(taggedHash('BIP0340/challenge', ...args)));\n}\n\n/**\n * Schnorr public key is just `x` coordinate of Point as per BIP340.\n */\nfunction schnorrGetPublicKey(privateKey: Hex): Uint8Array {\n return schnorrGetExtPubKey(privateKey).bytes; // d'=int(sk). Fail if d'=0 or d'≥n. Ret bytes(d'⋅G)\n}\n\n/**\n * Creates Schnorr signature as per BIP340. Verifies itself before returning anything.\n * auxRand is optional and is not the sole source of k generation: bad CSPRNG won't be dangerous.\n */\nfunction schnorrSign(\n message: Hex,\n privateKey: PrivKey,\n auxRand: Hex = randomBytes(32)\n): Uint8Array {\n const m = ensureBytes('message', message);\n const { bytes: px, scalar: d } = schnorrGetExtPubKey(privateKey); // checks for isWithinCurveOrder\n const a = ensureBytes('auxRand', auxRand, 32); // Auxiliary random data a: a 32-byte array\n const t = numTo32b(d ^ bytesToNumberBE(taggedHash('BIP0340/aux', a))); // Let t be the byte-wise xor of bytes(d) and hash/aux(a)\n const rand = taggedHash('BIP0340/nonce', t, px, m); // Let rand = hash/nonce(t || bytes(P) || m)\n const k_ = modN(bytesToNumberBE(rand)); // Let k' = int(rand) mod n\n if (k_ === _0n) throw new Error('sign failed: k is zero'); // Fail if k' = 0.\n const { bytes: rx, scalar: k } = schnorrGetExtPubKey(k_); // Let R = k'⋅G.\n const e = challenge(rx, px, m); // Let e = int(hash/challenge(bytes(R) || bytes(P) || m)) mod n.\n const sig = new Uint8Array(64); // Let sig = bytes(R) || bytes((k + ed) mod n).\n sig.set(rx, 0);\n sig.set(numTo32b(modN(k + e * d)), 32);\n // If Verify(bytes(P), m, sig) (see below) returns failure, abort\n if (!schnorrVerify(sig, m, px)) throw new Error('sign: Invalid signature produced');\n return sig;\n}\n\n/**\n * Verifies Schnorr signature.\n * Will swallow errors & return false except for initial type validation of arguments.\n */\nfunction schnorrVerify(signature: Hex, message: Hex, publicKey: Hex): boolean {\n const sig = ensureBytes('signature', signature, 64);\n const m = ensureBytes('message', message);\n const pub = ensureBytes('publicKey', publicKey, 32);\n try {\n const P = lift_x(bytesToNumberBE(pub)); // P = lift_x(int(pk)); fail if that fails\n const r = bytesToNumberBE(sig.subarray(0, 32)); // Let r = int(sig[0:32]); fail if r ≥ p.\n if (!fe(r)) return false;\n const s = bytesToNumberBE(sig.subarray(32, 64)); // Let s = int(sig[32:64]); fail if s ≥ n.\n if (!ge(s)) return false;\n const e = challenge(numTo32b(r), pointToBytes(P), m); // int(challenge(bytes(r)||bytes(P)||m))%n\n const R = GmulAdd(P, s, modN(-e)); // R = s⋅G - e⋅P\n if (!R || !R.hasEvenY() || R.toAffine().x !== r) return false; // -eP == (n-e)P\n return true; // Fail if is_infinite(R) / not has_even_y(R) / x(R) ≠ r.\n } catch (error) {\n return false;\n }\n}\n\nexport const schnorr = /* @__PURE__ */ (() => ({\n getPublicKey: schnorrGetPublicKey,\n sign: schnorrSign,\n verify: schnorrVerify,\n utils: {\n randomPrivateKey: secp256k1.utils.randomPrivateKey,\n lift_x,\n pointToBytes,\n numberToBytesBE,\n bytesToNumberBE,\n taggedHash,\n mod,\n },\n}))();\n\nconst isoMap = /* @__PURE__ */ (() =>\n isogenyMap(\n Fp,\n [\n // xNum\n [\n '0x8e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38daaaaa8c7',\n '0x7d3d4c80bc321d5b9f315cea7fd44c5d595d2fc0bf63b92dfff1044f17c6581',\n '0x534c328d23f234e6e2a413deca25caece4506144037c40314ecbd0b53d9dd262',\n '0x8e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38daaaaa88c',\n ],\n // xDen\n [\n '0xd35771193d94918a9ca34ccbb7b640dd86cd409542f8487d9fe6b745781eb49b',\n '0xedadc6f64383dc1df7c4b2d51b54225406d36b641f5e41bbc52a56612a8c6d14',\n '0x0000000000000000000000000000000000000000000000000000000000000001', // LAST 1\n ],\n // yNum\n [\n '0x4bda12f684bda12f684bda12f684bda12f684bda12f684bda12f684b8e38e23c',\n '0xc75e0c32d5cb7c0fa9d0a54b12a0a6d5647ab046d686da6fdffc90fc201d71a3',\n '0x29a6194691f91a73715209ef6512e576722830a201be2018a765e85a9ecee931',\n '0x2f684bda12f684bda12f684bda12f684bda12f684bda12f684bda12f38e38d84',\n ],\n // yDen\n [\n '0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffff93b',\n '0x7a06534bb8bdb49fd5e9e6632722c2989467c1bfc8e8d978dfb425d2685c2573',\n '0x6484aa716545ca2cf3a70c3fa8fe337e0a3d21162f0d6299a7bf8192bfd2a76f',\n '0x0000000000000000000000000000000000000000000000000000000000000001', // LAST 1\n ],\n ].map((i) => i.map((j) => BigInt(j))) as [bigint[], bigint[], bigint[], bigint[]]\n ))();\nconst mapSWU = /* @__PURE__ */ (() =>\n mapToCurveSimpleSWU(Fp, {\n A: BigInt('0x3f8731abdd661adca08a5558f0f5d272e953d363cb6f0e5d405447c01a444533'),\n B: BigInt('1771'),\n Z: Fp.create(BigInt('-11')),\n }))();\nconst htf = /* @__PURE__ */ (() =>\n createHasher(\n secp256k1.ProjectivePoint,\n (scalars: bigint[]) => {\n const { x, y } = mapSWU(Fp.create(scalars[0]));\n return isoMap(x, y);\n },\n {\n DST: 'secp256k1_XMD:SHA-256_SSWU_RO_',\n encodeDST: 'secp256k1_XMD:SHA-256_SSWU_NU_',\n p: Fp.ORDER,\n m: 1,\n k: 128,\n expand: 'xmd',\n hash: sha256,\n }\n ))();\nexport const hashToCurve = /* @__PURE__ */ (() => htf.hashToCurve)();\nexport const encodeToCurve = /* @__PURE__ */ (() => htf.encodeToCurve)();\n", "// We use WebCrypto aka globalThis.crypto, which exists in browsers and node.js 16+.\n// See utils.ts for details.\ndeclare const globalThis: Record | undefined;\nexport const crypto =\n typeof globalThis === 'object' && 'crypto' in globalThis ? globalThis.crypto : undefined;\n", "/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */\n\n// We use WebCrypto aka globalThis.crypto, which exists in browsers and node.js 16+.\n// node.js versions earlier than v19 don't declare it in global scope.\n// For node.js, package.json#exports field mapping rewrites import\n// from `crypto` to `cryptoNode`, which imports native module.\n// Makes the utils un-importable in browsers without a bundler.\n// Once node.js 18 is deprecated, we can just drop the import.\nimport { crypto } from '@noble/hashes/crypto';\n\n// prettier-ignore\nexport type TypedArray = Int8Array | Uint8ClampedArray | Uint8Array |\n Uint16Array | Int16Array | Uint32Array | Int32Array;\n\nconst u8a = (a: any): a is Uint8Array => a instanceof Uint8Array;\n// Cast array to different type\nexport const u8 = (arr: TypedArray) => new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength);\nexport const u32 = (arr: TypedArray) =>\n new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4));\n\n// Cast array to view\nexport const createView = (arr: TypedArray) =>\n new DataView(arr.buffer, arr.byteOffset, arr.byteLength);\n\n// The rotate right (circular right shift) operation for uint32\nexport const rotr = (word: number, shift: number) => (word << (32 - shift)) | (word >>> shift);\n\n// big-endian hardware is rare. Just in case someone still decides to run hashes:\n// early-throw an error because we don't support BE yet.\nexport const isLE = new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44;\nif (!isLE) throw new Error('Non little-endian hardware is not supported');\n\nconst hexes = Array.from({ length: 256 }, (v, i) => i.toString(16).padStart(2, '0'));\n/**\n * @example bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])) // 'cafe0123'\n */\nexport function bytesToHex(bytes: Uint8Array): string {\n if (!u8a(bytes)) throw new Error('Uint8Array expected');\n // pre-caching improves the speed 6x\n let hex = '';\n for (let i = 0; i < bytes.length; i++) {\n hex += hexes[bytes[i]];\n }\n return hex;\n}\n\n/**\n * @example hexToBytes('cafe0123') // Uint8Array.from([0xca, 0xfe, 0x01, 0x23])\n */\nexport function hexToBytes(hex: string): Uint8Array {\n if (typeof hex !== 'string') throw new Error('hex string expected, got ' + typeof hex);\n const len = hex.length;\n if (len % 2) throw new Error('padded hex string expected, got unpadded hex of length ' + len);\n const array = new Uint8Array(len / 2);\n for (let i = 0; i < array.length; i++) {\n const j = i * 2;\n const hexByte = hex.slice(j, j + 2);\n const byte = Number.parseInt(hexByte, 16);\n if (Number.isNaN(byte) || byte < 0) throw new Error('Invalid byte sequence');\n array[i] = byte;\n }\n return array;\n}\n\n// There is no setImmediate in browser and setTimeout is slow.\n// call of async fn will return Promise, which will be fullfiled only on\n// next scheduler queue processing step and this is exactly what we need.\nexport const nextTick = async () => {};\n\n// Returns control to thread each 'tick' ms to avoid blocking\nexport async function asyncLoop(iters: number, tick: number, cb: (i: number) => void) {\n let ts = Date.now();\n for (let i = 0; i < iters; i++) {\n cb(i);\n // Date.now() is not monotonic, so in case if clock goes backwards we return return control too\n const diff = Date.now() - ts;\n if (diff >= 0 && diff < tick) continue;\n await nextTick();\n ts += diff;\n }\n}\n\n// Global symbols in both browsers and Node.js since v11\n// See https://github.com/microsoft/TypeScript/issues/31535\ndeclare const TextEncoder: any;\n\n/**\n * @example utf8ToBytes('abc') // new Uint8Array([97, 98, 99])\n */\nexport function utf8ToBytes(str: string): Uint8Array {\n if (typeof str !== 'string') throw new Error(`utf8ToBytes expected string, got ${typeof str}`);\n return new Uint8Array(new TextEncoder().encode(str)); // https://bugzil.la/1681809\n}\n\nexport type Input = Uint8Array | string;\n/**\n * Normalizes (non-hex) string or Uint8Array to Uint8Array.\n * Warning: when Uint8Array is passed, it would NOT get copied.\n * Keep in mind for future mutable operations.\n */\nexport function toBytes(data: Input): Uint8Array {\n if (typeof data === 'string') data = utf8ToBytes(data);\n if (!u8a(data)) throw new Error(`expected Uint8Array, got ${typeof data}`);\n return data;\n}\n\n/**\n * Copies several Uint8Arrays into one.\n */\nexport function concatBytes(...arrays: Uint8Array[]): Uint8Array {\n const r = new Uint8Array(arrays.reduce((sum, a) => sum + a.length, 0));\n let pad = 0; // walk through each item, ensure they have proper type\n arrays.forEach((a) => {\n if (!u8a(a)) throw new Error('Uint8Array expected');\n r.set(a, pad);\n pad += a.length;\n });\n return r;\n}\n\n// For runtime check if class implements interface\nexport abstract class Hash> {\n abstract blockLen: number; // Bytes per block\n abstract outputLen: number; // Bytes in output\n abstract update(buf: Input): this;\n // Writes digest into buf\n abstract digestInto(buf: Uint8Array): void;\n abstract digest(): Uint8Array;\n /**\n * Resets internal state. Makes Hash instance unusable.\n * Reset is impossible for keyed hashes if key is consumed into state. If digest is not consumed\n * by user, they will need to manually call `destroy()` when zeroing is necessary.\n */\n abstract destroy(): void;\n /**\n * Clones hash instance. Unsafe: doesn't check whether `to` is valid. Can be used as `clone()`\n * when no options are passed.\n * Reasons to use `_cloneInto` instead of clone: 1) performance 2) reuse instance => all internal\n * buffers are overwritten => causes buffer overwrite which is used for digest in some cases.\n * There are no guarantees for clean-up because it's impossible in JS.\n */\n abstract _cloneInto(to?: T): T;\n // Safe version that clones internal state\n clone(): T {\n return this._cloneInto();\n }\n}\n\n/**\n * XOF: streaming API to read digest in chunks.\n * Same as 'squeeze' in keccak/k12 and 'seek' in blake3, but more generic name.\n * When hash used in XOF mode it is up to user to call '.destroy' afterwards, since we cannot\n * destroy state, next call can require more bytes.\n */\nexport type HashXOF> = Hash & {\n xof(bytes: number): Uint8Array; // Read 'bytes' bytes from digest stream\n xofInto(buf: Uint8Array): Uint8Array; // read buf.length bytes from digest stream into buf\n};\n\n// Check if object doens't have custom constructor (like Uint8Array/Array)\nconst isPlainObject = (obj: any) =>\n Object.prototype.toString.call(obj) === '[object Object]' && obj.constructor === Object;\n\ntype EmptyObj = {};\nexport function checkOpts(\n defaults: T1,\n opts?: T2\n): T1 & T2 {\n if (opts !== undefined && (typeof opts !== 'object' || !isPlainObject(opts)))\n throw new Error('Options should be object or undefined');\n const merged = Object.assign(defaults, opts);\n return merged as T1 & T2;\n}\n\nexport type CHash = ReturnType;\n\nexport function wrapConstructor>(hashCons: () => Hash) {\n const hashC = (msg: Input): Uint8Array => hashCons().update(toBytes(msg)).digest();\n const tmp = hashCons();\n hashC.outputLen = tmp.outputLen;\n hashC.blockLen = tmp.blockLen;\n hashC.create = () => hashCons();\n return hashC;\n}\n\nexport function wrapConstructorWithOpts, T extends Object>(\n hashCons: (opts?: T) => Hash\n) {\n const hashC = (msg: Input, opts?: T): Uint8Array => hashCons(opts).update(toBytes(msg)).digest();\n const tmp = hashCons({} as T);\n hashC.outputLen = tmp.outputLen;\n hashC.blockLen = tmp.blockLen;\n hashC.create = (opts: T) => hashCons(opts);\n return hashC;\n}\n\nexport function wrapXOFConstructorWithOpts, T extends Object>(\n hashCons: (opts?: T) => HashXOF\n) {\n const hashC = (msg: Input, opts?: T): Uint8Array => hashCons(opts).update(toBytes(msg)).digest();\n const tmp = hashCons({} as T);\n hashC.outputLen = tmp.outputLen;\n hashC.blockLen = tmp.blockLen;\n hashC.create = (opts: T) => hashCons(opts);\n return hashC;\n}\n\n/**\n * Secure PRNG. Uses `crypto.getRandomValues`, which defers to OS.\n */\nexport function randomBytes(bytesLength = 32): Uint8Array {\n if (crypto && typeof crypto.getRandomValues === 'function') {\n return crypto.getRandomValues(new Uint8Array(bytesLength));\n }\n throw new Error('crypto.getRandomValues must be defined');\n}\n", "export function number(n: number) {\n if (!Number.isSafeInteger(n) || n < 0) throw new Error(`Wrong positive integer: ${n}`);\n}\n\nexport function bool(b: boolean) {\n if (typeof b !== 'boolean') throw new Error(`Expected boolean, not ${b}`);\n}\n\nexport function bytes(b: Uint8Array | undefined, ...lengths: number[]) {\n if (!(b instanceof Uint8Array)) throw new Error('Expected Uint8Array');\n if (lengths.length > 0 && !lengths.includes(b.length))\n throw new Error(`Expected Uint8Array of length ${lengths}, not of length=${b.length}`);\n}\n\ntype Hash = {\n (data: Uint8Array): Uint8Array;\n blockLen: number;\n outputLen: number;\n create: any;\n};\nexport function hash(hash: Hash) {\n if (typeof hash !== 'function' || typeof hash.create !== 'function')\n throw new Error('Hash should be wrapped by utils.wrapConstructor');\n number(hash.outputLen);\n number(hash.blockLen);\n}\n\nexport function exists(instance: any, checkFinished = true) {\n if (instance.destroyed) throw new Error('Hash instance has been destroyed');\n if (checkFinished && instance.finished) throw new Error('Hash#digest() has already been called');\n}\nexport function output(out: any, instance: any) {\n bytes(out);\n const min = instance.outputLen;\n if (out.length < min) {\n throw new Error(`digestInto() expects output buffer of length at least ${min}`);\n }\n}\n\nconst assert = {\n number,\n bool,\n bytes,\n hash,\n exists,\n output,\n};\n\nexport default assert;\n", "import assert from './_assert.js';\nimport { Hash, createView, Input, toBytes } from './utils.js';\n\n// Polyfill for Safari 14\nfunction setBigUint64(view: DataView, byteOffset: number, value: bigint, isLE: boolean): void {\n if (typeof view.setBigUint64 === 'function') return view.setBigUint64(byteOffset, value, isLE);\n const _32n = BigInt(32);\n const _u32_max = BigInt(0xffffffff);\n const wh = Number((value >> _32n) & _u32_max);\n const wl = Number(value & _u32_max);\n const h = isLE ? 4 : 0;\n const l = isLE ? 0 : 4;\n view.setUint32(byteOffset + h, wh, isLE);\n view.setUint32(byteOffset + l, wl, isLE);\n}\n\n// Base SHA2 class (RFC 6234)\nexport abstract class SHA2> extends Hash {\n protected abstract process(buf: DataView, offset: number): void;\n protected abstract get(): number[];\n protected abstract set(...args: number[]): void;\n abstract destroy(): void;\n protected abstract roundClean(): void;\n // For partial updates less than block size\n protected buffer: Uint8Array;\n protected view: DataView;\n protected finished = false;\n protected length = 0;\n protected pos = 0;\n protected destroyed = false;\n\n constructor(\n readonly blockLen: number,\n public outputLen: number,\n readonly padOffset: number,\n readonly isLE: boolean\n ) {\n super();\n this.buffer = new Uint8Array(blockLen);\n this.view = createView(this.buffer);\n }\n update(data: Input): this {\n assert.exists(this);\n const { view, buffer, blockLen } = this;\n data = toBytes(data);\n const len = data.length;\n for (let pos = 0; pos < len; ) {\n const take = Math.min(blockLen - this.pos, len - pos);\n // Fast path: we have at least one block in input, cast it to view and process\n if (take === blockLen) {\n const dataView = createView(data);\n for (; blockLen <= len - pos; pos += blockLen) this.process(dataView, pos);\n continue;\n }\n buffer.set(data.subarray(pos, pos + take), this.pos);\n this.pos += take;\n pos += take;\n if (this.pos === blockLen) {\n this.process(view, 0);\n this.pos = 0;\n }\n }\n this.length += data.length;\n this.roundClean();\n return this;\n }\n digestInto(out: Uint8Array) {\n assert.exists(this);\n assert.output(out, this);\n this.finished = true;\n // Padding\n // We can avoid allocation of buffer for padding completely if it\n // was previously not allocated here. But it won't change performance.\n const { buffer, view, blockLen, isLE } = this;\n let { pos } = this;\n // append the bit '1' to the message\n buffer[pos++] = 0b10000000;\n this.buffer.subarray(pos).fill(0);\n // we have less than padOffset left in buffer, so we cannot put length in current block, need process it and pad again\n if (this.padOffset > blockLen - pos) {\n this.process(view, 0);\n pos = 0;\n }\n // Pad until full block byte with zeros\n for (let i = pos; i < blockLen; i++) buffer[i] = 0;\n // Note: sha512 requires length to be 128bit integer, but length in JS will overflow before that\n // You need to write around 2 exabytes (u64_max / 8 / (1024**6)) for this to happen.\n // So we just write lowest 64 bits of that value.\n setBigUint64(view, blockLen - 8, BigInt(this.length * 8), isLE);\n this.process(view, 0);\n const oview = createView(out);\n const len = this.outputLen;\n // NOTE: we do division by 4 later, which should be fused in single op with modulo by JIT\n if (len % 4) throw new Error('_sha2: outputLen should be aligned to 32bit');\n const outLen = len / 4;\n const state = this.get();\n if (outLen > state.length) throw new Error('_sha2: outputLen bigger than state');\n for (let i = 0; i < outLen; i++) oview.setUint32(4 * i, state[i], isLE);\n }\n digest() {\n const { buffer, outputLen } = this;\n this.digestInto(buffer);\n const res = buffer.slice(0, outputLen);\n this.destroy();\n return res;\n }\n _cloneInto(to?: T): T {\n to ||= new (this.constructor as any)() as T;\n to.set(...this.get());\n const { blockLen, buffer, length, finished, destroyed, pos } = this;\n to.length = length;\n to.pos = pos;\n to.finished = finished;\n to.destroyed = destroyed;\n if (length % blockLen) to.buffer.set(buffer);\n return to;\n }\n}\n", "import { SHA2 } from './_sha2.js';\nimport { rotr, wrapConstructor } from './utils.js';\n\n// Choice: a ? b : c\nconst Chi = (a: number, b: number, c: number) => (a & b) ^ (~a & c);\n// Majority function, true if any two inpust is true\nconst Maj = (a: number, b: number, c: number) => (a & b) ^ (a & c) ^ (b & c);\n\n// Round constants:\n// first 32 bits of the fractional parts of the cube roots of the first 64 primes 2..311)\n// prettier-ignore\nconst SHA256_K = new Uint32Array([\n 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,\n 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,\n 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,\n 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,\n 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,\n 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,\n 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,\n 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2\n]);\n\n// Initial state (first 32 bits of the fractional parts of the square roots of the first 8 primes 2..19):\n// prettier-ignore\nconst IV = new Uint32Array([\n 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19\n]);\n\n// Temporary buffer, not used to store anything between runs\n// Named this way because it matches specification.\nconst SHA256_W = new Uint32Array(64);\nclass SHA256 extends SHA2 {\n // We cannot use array here since array allows indexing by variable\n // which means optimizer/compiler cannot use registers.\n A = IV[0] | 0;\n B = IV[1] | 0;\n C = IV[2] | 0;\n D = IV[3] | 0;\n E = IV[4] | 0;\n F = IV[5] | 0;\n G = IV[6] | 0;\n H = IV[7] | 0;\n\n constructor() {\n super(64, 32, 8, false);\n }\n protected get(): [number, number, number, number, number, number, number, number] {\n const { A, B, C, D, E, F, G, H } = this;\n return [A, B, C, D, E, F, G, H];\n }\n // prettier-ignore\n protected set(\n A: number, B: number, C: number, D: number, E: number, F: number, G: number, H: number\n ) {\n this.A = A | 0;\n this.B = B | 0;\n this.C = C | 0;\n this.D = D | 0;\n this.E = E | 0;\n this.F = F | 0;\n this.G = G | 0;\n this.H = H | 0;\n }\n protected process(view: DataView, offset: number): void {\n // Extend the first 16 words into the remaining 48 words w[16..63] of the message schedule array\n for (let i = 0; i < 16; i++, offset += 4) SHA256_W[i] = view.getUint32(offset, false);\n for (let i = 16; i < 64; i++) {\n const W15 = SHA256_W[i - 15];\n const W2 = SHA256_W[i - 2];\n const s0 = rotr(W15, 7) ^ rotr(W15, 18) ^ (W15 >>> 3);\n const s1 = rotr(W2, 17) ^ rotr(W2, 19) ^ (W2 >>> 10);\n SHA256_W[i] = (s1 + SHA256_W[i - 7] + s0 + SHA256_W[i - 16]) | 0;\n }\n // Compression function main loop, 64 rounds\n let { A, B, C, D, E, F, G, H } = this;\n for (let i = 0; i < 64; i++) {\n const sigma1 = rotr(E, 6) ^ rotr(E, 11) ^ rotr(E, 25);\n const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0;\n const sigma0 = rotr(A, 2) ^ rotr(A, 13) ^ rotr(A, 22);\n const T2 = (sigma0 + Maj(A, B, C)) | 0;\n H = G;\n G = F;\n F = E;\n E = (D + T1) | 0;\n D = C;\n C = B;\n B = A;\n A = (T1 + T2) | 0;\n }\n // Add the compressed chunk to the current hash value\n A = (A + this.A) | 0;\n B = (B + this.B) | 0;\n C = (C + this.C) | 0;\n D = (D + this.D) | 0;\n E = (E + this.E) | 0;\n F = (F + this.F) | 0;\n G = (G + this.G) | 0;\n H = (H + this.H) | 0;\n this.set(A, B, C, D, E, F, G, H);\n }\n protected roundClean() {\n SHA256_W.fill(0);\n }\n destroy() {\n this.set(0, 0, 0, 0, 0, 0, 0, 0);\n this.buffer.fill(0);\n }\n}\n// Constants from https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.180-4.pdf\nclass SHA224 extends SHA256 {\n A = 0xc1059ed8 | 0;\n B = 0x367cd507 | 0;\n C = 0x3070dd17 | 0;\n D = 0xf70e5939 | 0;\n E = 0xffc00b31 | 0;\n F = 0x68581511 | 0;\n G = 0x64f98fa7 | 0;\n H = 0xbefa4fa4 | 0;\n constructor() {\n super();\n this.outputLen = 28;\n }\n}\n\n/**\n * SHA2-256 hash function\n * @param message - data that would be hashed\n */\nexport const sha256 = wrapConstructor(() => new SHA256());\nexport const sha224 = wrapConstructor(() => new SHA224());\n", "/*! scure-base - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nexport function assertNumber(n) {\n if (!Number.isSafeInteger(n))\n throw new Error(`Wrong integer: ${n}`);\n}\nfunction chain(...args) {\n const wrap = (a, b) => (c) => a(b(c));\n const encode = Array.from(args)\n .reverse()\n .reduce((acc, i) => (acc ? wrap(acc, i.encode) : i.encode), undefined);\n const decode = args.reduce((acc, i) => (acc ? wrap(acc, i.decode) : i.decode), undefined);\n return { encode, decode };\n}\nfunction alphabet(alphabet) {\n return {\n encode: (digits) => {\n if (!Array.isArray(digits) || (digits.length && typeof digits[0] !== 'number'))\n throw new Error('alphabet.encode input should be an array of numbers');\n return digits.map((i) => {\n assertNumber(i);\n if (i < 0 || i >= alphabet.length)\n throw new Error(`Digit index outside alphabet: ${i} (alphabet: ${alphabet.length})`);\n return alphabet[i];\n });\n },\n decode: (input) => {\n if (!Array.isArray(input) || (input.length && typeof input[0] !== 'string'))\n throw new Error('alphabet.decode input should be array of strings');\n return input.map((letter) => {\n if (typeof letter !== 'string')\n throw new Error(`alphabet.decode: not string element=${letter}`);\n const index = alphabet.indexOf(letter);\n if (index === -1)\n throw new Error(`Unknown letter: \"${letter}\". Allowed: ${alphabet}`);\n return index;\n });\n },\n };\n}\nfunction join(separator = '') {\n if (typeof separator !== 'string')\n throw new Error('join separator should be string');\n return {\n encode: (from) => {\n if (!Array.isArray(from) || (from.length && typeof from[0] !== 'string'))\n throw new Error('join.encode input should be array of strings');\n for (let i of from)\n if (typeof i !== 'string')\n throw new Error(`join.encode: non-string input=${i}`);\n return from.join(separator);\n },\n decode: (to) => {\n if (typeof to !== 'string')\n throw new Error('join.decode input should be string');\n return to.split(separator);\n },\n };\n}\nfunction padding(bits, chr = '=') {\n assertNumber(bits);\n if (typeof chr !== 'string')\n throw new Error('padding chr should be string');\n return {\n encode(data) {\n if (!Array.isArray(data) || (data.length && typeof data[0] !== 'string'))\n throw new Error('padding.encode input should be array of strings');\n for (let i of data)\n if (typeof i !== 'string')\n throw new Error(`padding.encode: non-string input=${i}`);\n while ((data.length * bits) % 8)\n data.push(chr);\n return data;\n },\n decode(input) {\n if (!Array.isArray(input) || (input.length && typeof input[0] !== 'string'))\n throw new Error('padding.encode input should be array of strings');\n for (let i of input)\n if (typeof i !== 'string')\n throw new Error(`padding.decode: non-string input=${i}`);\n let end = input.length;\n if ((end * bits) % 8)\n throw new Error('Invalid padding: string should have whole number of bytes');\n for (; end > 0 && input[end - 1] === chr; end--) {\n if (!(((end - 1) * bits) % 8))\n throw new Error('Invalid padding: string has too much padding');\n }\n return input.slice(0, end);\n },\n };\n}\nfunction normalize(fn) {\n if (typeof fn !== 'function')\n throw new Error('normalize fn should be function');\n return { encode: (from) => from, decode: (to) => fn(to) };\n}\nfunction convertRadix(data, from, to) {\n if (from < 2)\n throw new Error(`convertRadix: wrong from=${from}, base cannot be less than 2`);\n if (to < 2)\n throw new Error(`convertRadix: wrong to=${to}, base cannot be less than 2`);\n if (!Array.isArray(data))\n throw new Error('convertRadix: data should be array');\n if (!data.length)\n return [];\n let pos = 0;\n const res = [];\n const digits = Array.from(data);\n digits.forEach((d) => {\n assertNumber(d);\n if (d < 0 || d >= from)\n throw new Error(`Wrong integer: ${d}`);\n });\n while (true) {\n let carry = 0;\n let done = true;\n for (let i = pos; i < digits.length; i++) {\n const digit = digits[i];\n const digitBase = from * carry + digit;\n if (!Number.isSafeInteger(digitBase) ||\n (from * carry) / from !== carry ||\n digitBase - digit !== from * carry) {\n throw new Error('convertRadix: carry overflow');\n }\n carry = digitBase % to;\n digits[i] = Math.floor(digitBase / to);\n if (!Number.isSafeInteger(digits[i]) || digits[i] * to + carry !== digitBase)\n throw new Error('convertRadix: carry overflow');\n if (!done)\n continue;\n else if (!digits[i])\n pos = i;\n else\n done = false;\n }\n res.push(carry);\n if (done)\n break;\n }\n for (let i = 0; i < data.length - 1 && data[i] === 0; i++)\n res.push(0);\n return res.reverse();\n}\nconst gcd = (a, b) => (!b ? a : gcd(b, a % b));\nconst radix2carry = (from, to) => from + (to - gcd(from, to));\nfunction convertRadix2(data, from, to, padding) {\n if (!Array.isArray(data))\n throw new Error('convertRadix2: data should be array');\n if (from <= 0 || from > 32)\n throw new Error(`convertRadix2: wrong from=${from}`);\n if (to <= 0 || to > 32)\n throw new Error(`convertRadix2: wrong to=${to}`);\n if (radix2carry(from, to) > 32) {\n throw new Error(`convertRadix2: carry overflow from=${from} to=${to} carryBits=${radix2carry(from, to)}`);\n }\n let carry = 0;\n let pos = 0;\n const mask = 2 ** to - 1;\n const res = [];\n for (const n of data) {\n assertNumber(n);\n if (n >= 2 ** from)\n throw new Error(`convertRadix2: invalid data word=${n} from=${from}`);\n carry = (carry << from) | n;\n if (pos + from > 32)\n throw new Error(`convertRadix2: carry overflow pos=${pos} from=${from}`);\n pos += from;\n for (; pos >= to; pos -= to)\n res.push(((carry >> (pos - to)) & mask) >>> 0);\n carry &= 2 ** pos - 1;\n }\n carry = (carry << (to - pos)) & mask;\n if (!padding && pos >= from)\n throw new Error('Excess padding');\n if (!padding && carry)\n throw new Error(`Non-zero padding: ${carry}`);\n if (padding && pos > 0)\n res.push(carry >>> 0);\n return res;\n}\nfunction radix(num) {\n assertNumber(num);\n return {\n encode: (bytes) => {\n if (!(bytes instanceof Uint8Array))\n throw new Error('radix.encode input should be Uint8Array');\n return convertRadix(Array.from(bytes), 2 ** 8, num);\n },\n decode: (digits) => {\n if (!Array.isArray(digits) || (digits.length && typeof digits[0] !== 'number'))\n throw new Error('radix.decode input should be array of strings');\n return Uint8Array.from(convertRadix(digits, num, 2 ** 8));\n },\n };\n}\nfunction radix2(bits, revPadding = false) {\n assertNumber(bits);\n if (bits <= 0 || bits > 32)\n throw new Error('radix2: bits should be in (0..32]');\n if (radix2carry(8, bits) > 32 || radix2carry(bits, 8) > 32)\n throw new Error('radix2: carry overflow');\n return {\n encode: (bytes) => {\n if (!(bytes instanceof Uint8Array))\n throw new Error('radix2.encode input should be Uint8Array');\n return convertRadix2(Array.from(bytes), 8, bits, !revPadding);\n },\n decode: (digits) => {\n if (!Array.isArray(digits) || (digits.length && typeof digits[0] !== 'number'))\n throw new Error('radix2.decode input should be array of strings');\n return Uint8Array.from(convertRadix2(digits, bits, 8, revPadding));\n },\n };\n}\nfunction unsafeWrapper(fn) {\n if (typeof fn !== 'function')\n throw new Error('unsafeWrapper fn should be function');\n return function (...args) {\n try {\n return fn.apply(null, args);\n }\n catch (e) { }\n };\n}\nfunction checksum(len, fn) {\n assertNumber(len);\n if (typeof fn !== 'function')\n throw new Error('checksum fn should be function');\n return {\n encode(data) {\n if (!(data instanceof Uint8Array))\n throw new Error('checksum.encode: input should be Uint8Array');\n const checksum = fn(data).slice(0, len);\n const res = new Uint8Array(data.length + len);\n res.set(data);\n res.set(checksum, data.length);\n return res;\n },\n decode(data) {\n if (!(data instanceof Uint8Array))\n throw new Error('checksum.decode: input should be Uint8Array');\n const payload = data.slice(0, -len);\n const newChecksum = fn(payload).slice(0, len);\n const oldChecksum = data.slice(-len);\n for (let i = 0; i < len; i++)\n if (newChecksum[i] !== oldChecksum[i])\n throw new Error('Invalid checksum');\n return payload;\n },\n };\n}\nexport const utils = { alphabet, chain, checksum, radix, radix2, join, padding };\nexport const base16 = chain(radix2(4), alphabet('0123456789ABCDEF'), join(''));\nexport const base32 = chain(radix2(5), alphabet('ABCDEFGHIJKLMNOPQRSTUVWXYZ234567'), padding(5), join(''));\nexport const base32hex = chain(radix2(5), alphabet('0123456789ABCDEFGHIJKLMNOPQRSTUV'), padding(5), join(''));\nexport const base32crockford = chain(radix2(5), alphabet('0123456789ABCDEFGHJKMNPQRSTVWXYZ'), join(''), normalize((s) => s.toUpperCase().replace(/O/g, '0').replace(/[IL]/g, '1')));\nexport const base64 = chain(radix2(6), alphabet('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'), padding(6), join(''));\nexport const base64url = chain(radix2(6), alphabet('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_'), padding(6), join(''));\nconst genBase58 = (abc) => chain(radix(58), alphabet(abc), join(''));\nexport const base58 = genBase58('123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz');\nexport const base58flickr = genBase58('123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ');\nexport const base58xrp = genBase58('rpshnaf39wBUDNEGHJKLM4PQRST7VWXYZ2bcdeCg65jkm8oFqi1tuvAxyz');\nconst XMR_BLOCK_LEN = [0, 2, 3, 5, 6, 7, 9, 10, 11];\nexport const base58xmr = {\n encode(data) {\n let res = '';\n for (let i = 0; i < data.length; i += 8) {\n const block = data.subarray(i, i + 8);\n res += base58.encode(block).padStart(XMR_BLOCK_LEN[block.length], '1');\n }\n return res;\n },\n decode(str) {\n let res = [];\n for (let i = 0; i < str.length; i += 11) {\n const slice = str.slice(i, i + 11);\n const blockLen = XMR_BLOCK_LEN.indexOf(slice.length);\n const block = base58.decode(slice);\n for (let j = 0; j < block.length - blockLen; j++) {\n if (block[j] !== 0)\n throw new Error('base58xmr: wrong padding');\n }\n res = res.concat(Array.from(block.slice(block.length - blockLen)));\n }\n return Uint8Array.from(res);\n },\n};\nexport const base58check = (sha256) => chain(checksum(4, (data) => sha256(sha256(data))), base58);\nconst BECH_ALPHABET = chain(alphabet('qpzry9x8gf2tvdw0s3jn54khce6mua7l'), join(''));\nconst POLYMOD_GENERATORS = [0x3b6a57b2, 0x26508e6d, 0x1ea119fa, 0x3d4233dd, 0x2a1462b3];\nfunction bech32Polymod(pre) {\n const b = pre >> 25;\n let chk = (pre & 0x1ffffff) << 5;\n for (let i = 0; i < POLYMOD_GENERATORS.length; i++) {\n if (((b >> i) & 1) === 1)\n chk ^= POLYMOD_GENERATORS[i];\n }\n return chk;\n}\nfunction bechChecksum(prefix, words, encodingConst = 1) {\n const len = prefix.length;\n let chk = 1;\n for (let i = 0; i < len; i++) {\n const c = prefix.charCodeAt(i);\n if (c < 33 || c > 126)\n throw new Error(`Invalid prefix (${prefix})`);\n chk = bech32Polymod(chk) ^ (c >> 5);\n }\n chk = bech32Polymod(chk);\n for (let i = 0; i < len; i++)\n chk = bech32Polymod(chk) ^ (prefix.charCodeAt(i) & 0x1f);\n for (let v of words)\n chk = bech32Polymod(chk) ^ v;\n for (let i = 0; i < 6; i++)\n chk = bech32Polymod(chk);\n chk ^= encodingConst;\n return BECH_ALPHABET.encode(convertRadix2([chk % 2 ** 30], 30, 5, false));\n}\nfunction genBech32(encoding) {\n const ENCODING_CONST = encoding === 'bech32' ? 1 : 0x2bc830a3;\n const _words = radix2(5);\n const fromWords = _words.decode;\n const toWords = _words.encode;\n const fromWordsUnsafe = unsafeWrapper(fromWords);\n function encode(prefix, words, limit = 90) {\n if (typeof prefix !== 'string')\n throw new Error(`bech32.encode prefix should be string, not ${typeof prefix}`);\n if (!Array.isArray(words) || (words.length && typeof words[0] !== 'number'))\n throw new Error(`bech32.encode words should be array of numbers, not ${typeof words}`);\n const actualLength = prefix.length + 7 + words.length;\n if (limit !== false && actualLength > limit)\n throw new TypeError(`Length ${actualLength} exceeds limit ${limit}`);\n prefix = prefix.toLowerCase();\n return `${prefix}1${BECH_ALPHABET.encode(words)}${bechChecksum(prefix, words, ENCODING_CONST)}`;\n }\n function decode(str, limit = 90) {\n if (typeof str !== 'string')\n throw new Error(`bech32.decode input should be string, not ${typeof str}`);\n if (str.length < 8 || (limit !== false && str.length > limit))\n throw new TypeError(`Wrong string length: ${str.length} (${str}). Expected (8..${limit})`);\n const lowered = str.toLowerCase();\n if (str !== lowered && str !== str.toUpperCase())\n throw new Error(`String must be lowercase or uppercase`);\n str = lowered;\n const sepIndex = str.lastIndexOf('1');\n if (sepIndex === 0 || sepIndex === -1)\n throw new Error(`Letter \"1\" must be present between prefix and data only`);\n const prefix = str.slice(0, sepIndex);\n const _words = str.slice(sepIndex + 1);\n if (_words.length < 6)\n throw new Error('Data must be at least 6 characters long');\n const words = BECH_ALPHABET.decode(_words).slice(0, -6);\n const sum = bechChecksum(prefix, words, ENCODING_CONST);\n if (!_words.endsWith(sum))\n throw new Error(`Invalid checksum in ${str}: expected \"${sum}\"`);\n return { prefix, words };\n }\n const decodeUnsafe = unsafeWrapper(decode);\n function decodeToBytes(str) {\n const { prefix, words } = decode(str, false);\n return { prefix, words, bytes: fromWords(words) };\n }\n return { encode, decode, decodeToBytes, decodeUnsafe, fromWords, fromWordsUnsafe, toWords };\n}\nexport const bech32 = genBech32('bech32');\nexport const bech32m = genBech32('bech32m');\nexport const utf8 = {\n encode: (data) => new TextDecoder().decode(data),\n decode: (str) => new TextEncoder().encode(str),\n};\nexport const hex = chain(radix2(4), alphabet('0123456789abcdef'), join(''), normalize((s) => {\n if (typeof s !== 'string' || s.length % 2)\n throw new TypeError(`hex.decode: expected string, got ${typeof s} with length ${s.length}`);\n return s.toLowerCase();\n}));\nconst CODERS = {\n utf8, hex, base16, base32, base64, base64url, base58, base58xmr\n};\nconst coderTypeError = `Invalid encoding type. Available types: ${Object.keys(CODERS).join(', ')}`;\nexport const bytesToString = (type, bytes) => {\n if (typeof type !== 'string' || !CODERS.hasOwnProperty(type))\n throw new TypeError(coderTypeError);\n if (!(bytes instanceof Uint8Array))\n throw new TypeError('bytesToString() expects Uint8Array');\n return CODERS[type].encode(bytes);\n};\nexport const str = bytesToString;\nexport const stringToBytes = (type, str) => {\n if (!CODERS.hasOwnProperty(type))\n throw new TypeError(coderTypeError);\n if (typeof str !== 'string')\n throw new TypeError('stringToBytes() expects string');\n return CODERS[type].decode(str);\n};\nexport const bytes = stringToBytes;\n", "function number(n: number) {\n if (!Number.isSafeInteger(n) || n < 0) throw new Error(`positive integer expected, not ${n}`);\n}\n\nfunction bool(b: boolean) {\n if (typeof b !== 'boolean') throw new Error(`boolean expected, not ${b}`);\n}\n\nexport function isBytes(a: unknown): a is Uint8Array {\n return (\n a instanceof Uint8Array ||\n (a != null && typeof a === 'object' && a.constructor.name === 'Uint8Array')\n );\n}\n\nfunction bytes(b: Uint8Array | undefined, ...lengths: number[]) {\n if (!isBytes(b)) throw new Error('Uint8Array expected');\n if (lengths.length > 0 && !lengths.includes(b.length))\n throw new Error(`Uint8Array expected of length ${lengths}, not of length=${b.length}`);\n}\n\nexport type Hash = {\n (data: Uint8Array): Uint8Array;\n blockLen: number;\n outputLen: number;\n create: any;\n};\nfunction hash(hash: Hash) {\n if (typeof hash !== 'function' || typeof hash.create !== 'function')\n throw new Error('hash must be wrapped by utils.wrapConstructor');\n number(hash.outputLen);\n number(hash.blockLen);\n}\n\nfunction exists(instance: any, checkFinished = true) {\n if (instance.destroyed) throw new Error('Hash instance has been destroyed');\n if (checkFinished && instance.finished) throw new Error('Hash#digest() has already been called');\n}\n\nfunction output(out: any, instance: any) {\n bytes(out);\n const min = instance.outputLen;\n if (out.length < min) {\n throw new Error(`digestInto() expects output buffer of length at least ${min}`);\n }\n}\n\nexport { number, bool, bytes, hash, exists, output };\nconst assert = { number, bool, bytes, hash, exists, output };\nexport default assert;\n", "/*! noble-ciphers - MIT License (c) 2023 Paul Miller (paulmillr.com) */\nimport { bytes as abytes, isBytes } from './_assert.js';\n// prettier-ignore\nexport type TypedArray = Int8Array | Uint8ClampedArray | Uint8Array |\n Uint16Array | Int16Array | Uint32Array | Int32Array;\n\n// Cast array to different type\nexport const u8 = (arr: TypedArray) => new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength);\nexport const u16 = (arr: TypedArray) =>\n new Uint16Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 2));\nexport const u32 = (arr: TypedArray) =>\n new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4));\n\n// Cast array to view\nexport const createView = (arr: TypedArray) =>\n new DataView(arr.buffer, arr.byteOffset, arr.byteLength);\n\n// big-endian hardware is rare. Just in case someone still decides to run ciphers:\n// early-throw an error because we don't support BE yet.\nexport const isLE = new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44;\nif (!isLE) throw new Error('Non little-endian hardware is not supported');\n\n// Array where index 0xf0 (240) is mapped to string 'f0'\nconst hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) =>\n i.toString(16).padStart(2, '0')\n);\n/**\n * @example bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])) // 'cafe0123'\n */\nexport function bytesToHex(bytes: Uint8Array): string {\n abytes(bytes);\n // pre-caching improves the speed 6x\n let hex = '';\n for (let i = 0; i < bytes.length; i++) {\n hex += hexes[bytes[i]];\n }\n return hex;\n}\n\n// We use optimized technique to convert hex string to byte array\nconst asciis = { _0: 48, _9: 57, _A: 65, _F: 70, _a: 97, _f: 102 } as const;\nfunction asciiToBase16(char: number): number | undefined {\n if (char >= asciis._0 && char <= asciis._9) return char - asciis._0;\n if (char >= asciis._A && char <= asciis._F) return char - (asciis._A - 10);\n if (char >= asciis._a && char <= asciis._f) return char - (asciis._a - 10);\n return;\n}\n\n/**\n * @example hexToBytes('cafe0123') // Uint8Array.from([0xca, 0xfe, 0x01, 0x23])\n */\nexport function hexToBytes(hex: string): Uint8Array {\n if (typeof hex !== 'string') throw new Error('hex string expected, got ' + typeof hex);\n const hl = hex.length;\n const al = hl / 2;\n if (hl % 2) throw new Error('padded hex string expected, got unpadded hex of length ' + hl);\n const array = new Uint8Array(al);\n for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {\n const n1 = asciiToBase16(hex.charCodeAt(hi));\n const n2 = asciiToBase16(hex.charCodeAt(hi + 1));\n if (n1 === undefined || n2 === undefined) {\n const char = hex[hi] + hex[hi + 1];\n throw new Error('hex string expected, got non-hex character \"' + char + '\" at index ' + hi);\n }\n array[ai] = n1 * 16 + n2;\n }\n return array;\n}\n\nexport function hexToNumber(hex: string): bigint {\n if (typeof hex !== 'string') throw new Error('hex string expected, got ' + typeof hex);\n // Big Endian\n return BigInt(hex === '' ? '0' : `0x${hex}`);\n}\n\n// BE: Big Endian, LE: Little Endian\nexport function bytesToNumberBE(bytes: Uint8Array): bigint {\n return hexToNumber(bytesToHex(bytes));\n}\n\nexport function numberToBytesBE(n: number | bigint, len: number): Uint8Array {\n return hexToBytes(n.toString(16).padStart(len * 2, '0'));\n}\n\n// There is no setImmediate in browser and setTimeout is slow.\n// call of async fn will return Promise, which will be fullfiled only on\n// next scheduler queue processing step and this is exactly what we need.\nexport const nextTick = async () => {};\n\n// Returns control to thread each 'tick' ms to avoid blocking\nexport async function asyncLoop(iters: number, tick: number, cb: (i: number) => void) {\n let ts = Date.now();\n for (let i = 0; i < iters; i++) {\n cb(i);\n // Date.now() is not monotonic, so in case if clock goes backwards we return return control too\n const diff = Date.now() - ts;\n if (diff >= 0 && diff < tick) continue;\n await nextTick();\n ts += diff;\n }\n}\n\n// Global symbols in both browsers and Node.js since v11\n// See https://github.com/microsoft/TypeScript/issues/31535\ndeclare const TextEncoder: any;\ndeclare const TextDecoder: any;\n\n/**\n * @example utf8ToBytes('abc') // new Uint8Array([97, 98, 99])\n */\nexport function utf8ToBytes(str: string): Uint8Array {\n if (typeof str !== 'string') throw new Error(`string expected, got ${typeof str}`);\n return new Uint8Array(new TextEncoder().encode(str)); // https://bugzil.la/1681809\n}\n\n/**\n * @example bytesToUtf8(new Uint8Array([97, 98, 99])) // 'abc'\n */\nexport function bytesToUtf8(bytes: Uint8Array): string {\n return new TextDecoder().decode(bytes);\n}\n\nexport type Input = Uint8Array | string;\n/**\n * Normalizes (non-hex) string or Uint8Array to Uint8Array.\n * Warning: when Uint8Array is passed, it would NOT get copied.\n * Keep in mind for future mutable operations.\n */\nexport function toBytes(data: Input): Uint8Array {\n if (typeof data === 'string') data = utf8ToBytes(data);\n else if (isBytes(data)) data = data.slice();\n else throw new Error(`Uint8Array expected, got ${typeof data}`);\n return data;\n}\n\n/**\n * Copies several Uint8Arrays into one.\n */\nexport function concatBytes(...arrays: Uint8Array[]): Uint8Array {\n let sum = 0;\n for (let i = 0; i < arrays.length; i++) {\n const a = arrays[i];\n abytes(a);\n sum += a.length;\n }\n const res = new Uint8Array(sum);\n for (let i = 0, pad = 0; i < arrays.length; i++) {\n const a = arrays[i];\n res.set(a, pad);\n pad += a.length;\n }\n return res;\n}\n\ntype EmptyObj = {};\nexport function checkOpts(\n defaults: T1,\n opts: T2\n): T1 & T2 {\n if (opts == null || typeof opts !== 'object') throw new Error('options must be defined');\n const merged = Object.assign(defaults, opts);\n return merged as T1 & T2;\n}\n\n// Compares 2 u8a-s in kinda constant time\nexport function equalBytes(a: Uint8Array, b: Uint8Array) {\n if (a.length !== b.length) return false;\n let diff = 0;\n for (let i = 0; i < a.length; i++) diff |= a[i] ^ b[i];\n return diff === 0;\n}\n\n// For runtime check if class implements interface\nexport abstract class Hash> {\n abstract blockLen: number; // Bytes per block\n abstract outputLen: number; // Bytes in output\n abstract update(buf: Input): this;\n // Writes digest into buf\n abstract digestInto(buf: Uint8Array): void;\n abstract digest(): Uint8Array;\n /**\n * Resets internal state. Makes Hash instance unusable.\n * Reset is impossible for keyed hashes if key is consumed into state. If digest is not consumed\n * by user, they will need to manually call `destroy()` when zeroing is necessary.\n */\n abstract destroy(): void;\n}\n\n// This will allow to re-use with composable things like packed & base encoders\n// Also, we probably can make tags composable\nexport type Cipher = {\n encrypt(plaintext: Uint8Array): Uint8Array;\n decrypt(ciphertext: Uint8Array): Uint8Array;\n};\n\nexport type AsyncCipher = {\n encrypt(plaintext: Uint8Array): Promise;\n decrypt(ciphertext: Uint8Array): Promise;\n};\n\nexport type CipherWithOutput = Cipher & {\n encrypt(plaintext: Uint8Array, output?: Uint8Array): Uint8Array;\n decrypt(ciphertext: Uint8Array, output?: Uint8Array): Uint8Array;\n};\n\n// Params is outside return type, so it is accessible before calling constructor\n// If function support multiple nonceLength's, we return best one\nexport type CipherParams = { blockSize: number; nonceLength?: number; tagLength?: number };\nexport type CipherCons = (key: Uint8Array, ...args: T) => Cipher;\n/**\n * @__NO_SIDE_EFFECTS__\n */\nexport const wrapCipher = , P extends CipherParams>(\n params: P,\n c: C\n): C & P => {\n Object.assign(c, params);\n return c as C & P;\n};\n\nexport type XorStream = (\n key: Uint8Array,\n nonce: Uint8Array,\n data: Uint8Array,\n output?: Uint8Array,\n counter?: number\n) => Uint8Array;\n\n// Polyfill for Safari 14\nexport function setBigUint64(\n view: DataView,\n byteOffset: number,\n value: bigint,\n isLE: boolean\n): void {\n if (typeof view.setBigUint64 === 'function') return view.setBigUint64(byteOffset, value, isLE);\n const _32n = BigInt(32);\n const _u32_max = BigInt(0xffffffff);\n const wh = Number((value >> _32n) & _u32_max);\n const wl = Number(value & _u32_max);\n const h = isLE ? 4 : 0;\n const l = isLE ? 0 : 4;\n view.setUint32(byteOffset + h, wh, isLE);\n view.setUint32(byteOffset + l, wl, isLE);\n}\n\nexport function u64Lengths(ciphertext: Uint8Array, AAD?: Uint8Array) {\n const num = new Uint8Array(16);\n const view = createView(num);\n setBigUint64(view, 0, BigInt(AAD ? AAD.length : 0), true);\n setBigUint64(view, 8, BigInt(ciphertext.length), true);\n return num;\n}\n", "import { createView, toBytes, Input, Hash, u32 } from './utils.js';\nimport { bytes as abytes, exists as aexists, output as aoutput } from './_assert.js';\n\n// GHash from AES-GCM and its little-endian \"mirror image\" Polyval from AES-SIV.\n// Implemented in terms of GHash with conversion function for keys\n// GCM GHASH from NIST SP800-38d, SIV from RFC 8452.\n// https://nvlpubs.nist.gov/nistpubs/Legacy/SP/nistspecialpublication800-38d.pdf\n\n// GHASH modulo: x^128 + x^7 + x^2 + x + 1\n// POLYVAL modulo: x^128 + x^127 + x^126 + x^121 + 1\n\nconst BLOCK_SIZE = 16;\n// TODO: rewrite\n// temporary padding buffer\nconst ZEROS16 = /* @__PURE__ */ new Uint8Array(16);\nconst ZEROS32 = u32(ZEROS16);\nconst POLY = 0xe1; // v = 2*v % POLY\n\n// v = 2*v % POLY\n// NOTE: because x + x = 0 (add/sub is same), mul2(x) != x+x\n// We can multiply any number using montgomery ladder and this function (works as double, add is simple xor)\nconst mul2 = (s0: number, s1: number, s2: number, s3: number) => {\n const hiBit = s3 & 1;\n return {\n s3: (s2 << 31) | (s3 >>> 1),\n s2: (s1 << 31) | (s2 >>> 1),\n s1: (s0 << 31) | (s1 >>> 1),\n s0: (s0 >>> 1) ^ ((POLY << 24) & -(hiBit & 1)), // reduce % poly\n };\n};\n\nconst swapLE = (n: number) =>\n (((n >>> 0) & 0xff) << 24) |\n (((n >>> 8) & 0xff) << 16) |\n (((n >>> 16) & 0xff) << 8) |\n ((n >>> 24) & 0xff) |\n 0;\n\n/**\n * `mulX_POLYVAL(ByteReverse(H))` from spec\n * @param k mutated in place\n */\nexport function _toGHASHKey(k: Uint8Array): Uint8Array {\n k.reverse();\n const hiBit = k[15] & 1;\n // k >>= 1\n let carry = 0;\n for (let i = 0; i < k.length; i++) {\n const t = k[i];\n k[i] = (t >>> 1) | carry;\n carry = (t & 1) << 7;\n }\n k[0] ^= -hiBit & 0xe1; // if (hiBit) n ^= 0xe1000000000000000000000000000000;\n return k;\n}\n\ntype Value = { s0: number; s1: number; s2: number; s3: number };\n\nconst estimateWindow = (bytes: number) => {\n if (bytes > 64 * 1024) return 8;\n if (bytes > 1024) return 4;\n return 2;\n};\n\nclass GHASH implements Hash {\n readonly blockLen = BLOCK_SIZE;\n readonly outputLen = BLOCK_SIZE;\n protected s0 = 0;\n protected s1 = 0;\n protected s2 = 0;\n protected s3 = 0;\n protected finished = false;\n protected t: Value[];\n private W: number;\n private windowSize: number;\n // We select bits per window adaptively based on expectedLength\n constructor(key: Input, expectedLength?: number) {\n key = toBytes(key);\n abytes(key, 16);\n const kView = createView(key);\n let k0 = kView.getUint32(0, false);\n let k1 = kView.getUint32(4, false);\n let k2 = kView.getUint32(8, false);\n let k3 = kView.getUint32(12, false);\n // generate table of doubled keys (half of montgomery ladder)\n const doubles: Value[] = [];\n for (let i = 0; i < 128; i++) {\n doubles.push({ s0: swapLE(k0), s1: swapLE(k1), s2: swapLE(k2), s3: swapLE(k3) });\n ({ s0: k0, s1: k1, s2: k2, s3: k3 } = mul2(k0, k1, k2, k3));\n }\n const W = estimateWindow(expectedLength || 1024);\n if (![1, 2, 4, 8].includes(W))\n throw new Error(`ghash: wrong window size=${W}, should be 2, 4 or 8`);\n this.W = W;\n const bits = 128; // always 128 bits;\n const windows = bits / W;\n const windowSize = (this.windowSize = 2 ** W);\n const items: Value[] = [];\n // Create precompute table for window of W bits\n for (let w = 0; w < windows; w++) {\n // truth table: 00, 01, 10, 11\n for (let byte = 0; byte < windowSize; byte++) {\n // prettier-ignore\n let s0 = 0, s1 = 0, s2 = 0, s3 = 0;\n for (let j = 0; j < W; j++) {\n const bit = (byte >>> (W - j - 1)) & 1;\n if (!bit) continue;\n const { s0: d0, s1: d1, s2: d2, s3: d3 } = doubles[W * w + j];\n (s0 ^= d0), (s1 ^= d1), (s2 ^= d2), (s3 ^= d3);\n }\n items.push({ s0, s1, s2, s3 });\n }\n }\n this.t = items;\n }\n protected _updateBlock(s0: number, s1: number, s2: number, s3: number) {\n (s0 ^= this.s0), (s1 ^= this.s1), (s2 ^= this.s2), (s3 ^= this.s3);\n const { W, t, windowSize } = this;\n // prettier-ignore\n let o0 = 0, o1 = 0, o2 = 0, o3 = 0;\n const mask = (1 << W) - 1; // 2**W will kill performance.\n let w = 0;\n for (const num of [s0, s1, s2, s3]) {\n for (let bytePos = 0; bytePos < 4; bytePos++) {\n const byte = (num >>> (8 * bytePos)) & 0xff;\n for (let bitPos = 8 / W - 1; bitPos >= 0; bitPos--) {\n const bit = (byte >>> (W * bitPos)) & mask;\n const { s0: e0, s1: e1, s2: e2, s3: e3 } = t[w * windowSize + bit];\n (o0 ^= e0), (o1 ^= e1), (o2 ^= e2), (o3 ^= e3);\n w += 1;\n }\n }\n }\n this.s0 = o0;\n this.s1 = o1;\n this.s2 = o2;\n this.s3 = o3;\n }\n update(data: Input): this {\n data = toBytes(data);\n aexists(this);\n const b32 = u32(data);\n const blocks = Math.floor(data.length / BLOCK_SIZE);\n const left = data.length % BLOCK_SIZE;\n for (let i = 0; i < blocks; i++) {\n this._updateBlock(b32[i * 4 + 0], b32[i * 4 + 1], b32[i * 4 + 2], b32[i * 4 + 3]);\n }\n if (left) {\n ZEROS16.set(data.subarray(blocks * BLOCK_SIZE));\n this._updateBlock(ZEROS32[0], ZEROS32[1], ZEROS32[2], ZEROS32[3]);\n ZEROS32.fill(0); // clean tmp buffer\n }\n return this;\n }\n destroy() {\n const { t } = this;\n // clean precompute table\n for (const elm of t) {\n (elm.s0 = 0), (elm.s1 = 0), (elm.s2 = 0), (elm.s3 = 0);\n }\n }\n digestInto(out: Uint8Array) {\n aexists(this);\n aoutput(out, this);\n this.finished = true;\n const { s0, s1, s2, s3 } = this;\n const o32 = u32(out);\n o32[0] = s0;\n o32[1] = s1;\n o32[2] = s2;\n o32[3] = s3;\n return out;\n }\n digest(): Uint8Array {\n const res = new Uint8Array(BLOCK_SIZE);\n this.digestInto(res);\n this.destroy();\n return res;\n }\n}\n\nclass Polyval extends GHASH {\n constructor(key: Input, expectedLength?: number) {\n key = toBytes(key);\n const ghKey = _toGHASHKey(key.slice());\n super(ghKey, expectedLength);\n ghKey.fill(0);\n }\n update(data: Input): this {\n data = toBytes(data);\n aexists(this);\n const b32 = u32(data);\n const left = data.length % BLOCK_SIZE;\n const blocks = Math.floor(data.length / BLOCK_SIZE);\n for (let i = 0; i < blocks; i++) {\n this._updateBlock(\n swapLE(b32[i * 4 + 3]),\n swapLE(b32[i * 4 + 2]),\n swapLE(b32[i * 4 + 1]),\n swapLE(b32[i * 4 + 0])\n );\n }\n if (left) {\n ZEROS16.set(data.subarray(blocks * BLOCK_SIZE));\n this._updateBlock(\n swapLE(ZEROS32[3]),\n swapLE(ZEROS32[2]),\n swapLE(ZEROS32[1]),\n swapLE(ZEROS32[0])\n );\n ZEROS32.fill(0); // clean tmp buffer\n }\n return this;\n }\n digestInto(out: Uint8Array) {\n aexists(this);\n aoutput(out, this);\n this.finished = true;\n // tmp ugly hack\n const { s0, s1, s2, s3 } = this;\n const o32 = u32(out);\n o32[0] = s0;\n o32[1] = s1;\n o32[2] = s2;\n o32[3] = s3;\n return out.reverse();\n }\n}\n\nexport type CHash = ReturnType;\nfunction wrapConstructorWithKey>(\n hashCons: (key: Input, expectedLength?: number) => Hash\n) {\n const hashC = (msg: Input, key: Input): Uint8Array =>\n hashCons(key, msg.length).update(toBytes(msg)).digest();\n const tmp = hashCons(new Uint8Array(16), 0);\n hashC.outputLen = tmp.outputLen;\n hashC.blockLen = tmp.blockLen;\n hashC.create = (key: Input, expectedLength?: number) => hashCons(key, expectedLength);\n return hashC;\n}\n\nexport const ghash = wrapConstructorWithKey(\n (key, expectedLength) => new GHASH(key, expectedLength)\n);\nexport const polyval = wrapConstructorWithKey(\n (key, expectedLength) => new Polyval(key, expectedLength)\n);\n", "// prettier-ignore\nimport {\n wrapCipher, Cipher, CipherWithOutput,\n createView, setBigUint64, equalBytes, u32, u8,\n} from './utils.js';\nimport { ghash, polyval } from './_polyval.js';\nimport { bytes as abytes } from './_assert.js';\n\n/*\nAES (Advanced Encryption Standard) aka Rijndael block cipher.\n\nData is split into 128-bit blocks. Encrypted in 10/12/14 rounds (128/192/256 bits). In every round:\n1. **S-box**, table substitution\n2. **Shift rows**, cyclic shift left of all rows of data array\n3. **Mix columns**, multiplying every column by fixed polynomial\n4. **Add round key**, round_key xor i-th column of array\n\nResources:\n- FIPS-197 https://csrc.nist.gov/files/pubs/fips/197/final/docs/fips-197.pdf\n- Original proposal: https://csrc.nist.gov/csrc/media/projects/cryptographic-standards-and-guidelines/documents/aes-development/rijndael-ammended.pdf\n*/\n\nconst BLOCK_SIZE = 16;\nconst BLOCK_SIZE32 = 4;\nconst EMPTY_BLOCK = new Uint8Array(BLOCK_SIZE);\nconst POLY = 0x11b; // 1 + x + x**3 + x**4 + x**8\n\n// TODO: remove multiplication, binary ops only\nfunction mul2(n: number) {\n return (n << 1) ^ (POLY & -(n >> 7));\n}\n\nfunction mul(a: number, b: number) {\n let res = 0;\n for (; b > 0; b >>= 1) {\n // Montgomery ladder\n res ^= a & -(b & 1); // if (b&1) res ^=a (but const-time).\n a = mul2(a); // a = 2*a\n }\n return res;\n}\n\n// AES S-box is generated using finite field inversion,\n// an affine transform, and xor of a constant 0x63.\nconst sbox = /* @__PURE__ */ (() => {\n let t = new Uint8Array(256);\n for (let i = 0, x = 1; i < 256; i++, x ^= mul2(x)) t[i] = x;\n const box = new Uint8Array(256);\n box[0] = 0x63; // first elm\n for (let i = 0; i < 255; i++) {\n let x = t[255 - i];\n x |= x << 8;\n box[t[i]] = (x ^ (x >> 4) ^ (x >> 5) ^ (x >> 6) ^ (x >> 7) ^ 0x63) & 0xff;\n }\n return box;\n})();\n\n// Inverted S-box\nconst invSbox = /* @__PURE__ */ sbox.map((_, j) => sbox.indexOf(j));\n\n// Rotate u32 by 8\nconst rotr32_8 = (n: number) => (n << 24) | (n >>> 8);\nconst rotl32_8 = (n: number) => (n << 8) | (n >>> 24);\n\n// T-table is optimization suggested in 5.2 of original proposal (missed from FIPS-197). Changes:\n// - LE instead of BE\n// - bigger tables: T0 and T1 are merged into T01 table and T2 & T3 into T23;\n// so index is u16, instead of u8. This speeds up things, unexpectedly\nfunction genTtable(sbox: Uint8Array, fn: (n: number) => number) {\n if (sbox.length !== 256) throw new Error('Wrong sbox length');\n const T0 = new Uint32Array(256).map((_, j) => fn(sbox[j]));\n const T1 = T0.map(rotl32_8);\n const T2 = T1.map(rotl32_8);\n const T3 = T2.map(rotl32_8);\n const T01 = new Uint32Array(256 * 256);\n const T23 = new Uint32Array(256 * 256);\n const sbox2 = new Uint16Array(256 * 256);\n for (let i = 0; i < 256; i++) {\n for (let j = 0; j < 256; j++) {\n const idx = i * 256 + j;\n T01[idx] = T0[i] ^ T1[j];\n T23[idx] = T2[i] ^ T3[j];\n sbox2[idx] = (sbox[i] << 8) | sbox[j];\n }\n }\n return { sbox, sbox2, T0, T1, T2, T3, T01, T23 };\n}\n\nconst tableEncoding = /* @__PURE__ */ genTtable(\n sbox,\n (s: number) => (mul(s, 3) << 24) | (s << 16) | (s << 8) | mul(s, 2)\n);\nconst tableDecoding = /* @__PURE__ */ genTtable(\n invSbox,\n (s) => (mul(s, 11) << 24) | (mul(s, 13) << 16) | (mul(s, 9) << 8) | mul(s, 14)\n);\n\nconst xPowers = /* @__PURE__ */ (() => {\n const p = new Uint8Array(16);\n for (let i = 0, x = 1; i < 16; i++, x = mul2(x)) p[i] = x;\n return p;\n})();\n\nexport function expandKeyLE(key: Uint8Array): Uint32Array {\n abytes(key);\n const len = key.length;\n if (![16, 24, 32].includes(len))\n throw new Error(`aes: wrong key size: should be 16, 24 or 32, got: ${len}`);\n const { sbox2 } = tableEncoding;\n const k32 = u32(key);\n const Nk = k32.length;\n const subByte = (n: number) => applySbox(sbox2, n, n, n, n);\n const xk = new Uint32Array(len + 28); // expanded key\n xk.set(k32);\n // 4.3.1 Key expansion\n for (let i = Nk; i < xk.length; i++) {\n let t = xk[i - 1];\n if (i % Nk === 0) t = subByte(rotr32_8(t)) ^ xPowers[i / Nk - 1];\n else if (Nk > 6 && i % Nk === 4) t = subByte(t);\n xk[i] = xk[i - Nk] ^ t;\n }\n return xk;\n}\n\nexport function expandKeyDecLE(key: Uint8Array): Uint32Array {\n const encKey = expandKeyLE(key);\n const xk = encKey.slice();\n const Nk = encKey.length;\n const { sbox2 } = tableEncoding;\n const { T0, T1, T2, T3 } = tableDecoding;\n // Inverse key by chunks of 4 (rounds)\n for (let i = 0; i < Nk; i += 4) {\n for (let j = 0; j < 4; j++) xk[i + j] = encKey[Nk - i - 4 + j];\n }\n encKey.fill(0);\n // apply InvMixColumn except first & last round\n for (let i = 4; i < Nk - 4; i++) {\n const x = xk[i];\n const w = applySbox(sbox2, x, x, x, x);\n xk[i] = T0[w & 0xff] ^ T1[(w >>> 8) & 0xff] ^ T2[(w >>> 16) & 0xff] ^ T3[w >>> 24];\n }\n return xk;\n}\n\n// Apply tables\nfunction apply0123(\n T01: Uint32Array,\n T23: Uint32Array,\n s0: number,\n s1: number,\n s2: number,\n s3: number\n) {\n return (\n T01[((s0 << 8) & 0xff00) | ((s1 >>> 8) & 0xff)] ^\n T23[((s2 >>> 8) & 0xff00) | ((s3 >>> 24) & 0xff)]\n );\n}\n\nfunction applySbox(sbox2: Uint16Array, s0: number, s1: number, s2: number, s3: number) {\n return (\n sbox2[(s0 & 0xff) | (s1 & 0xff00)] |\n (sbox2[((s2 >>> 16) & 0xff) | ((s3 >>> 16) & 0xff00)] << 16)\n );\n}\n\nfunction encrypt(xk: Uint32Array, s0: number, s1: number, s2: number, s3: number) {\n const { sbox2, T01, T23 } = tableEncoding;\n let k = 0;\n (s0 ^= xk[k++]), (s1 ^= xk[k++]), (s2 ^= xk[k++]), (s3 ^= xk[k++]);\n const rounds = xk.length / 4 - 2;\n for (let i = 0; i < rounds; i++) {\n const t0 = xk[k++] ^ apply0123(T01, T23, s0, s1, s2, s3);\n const t1 = xk[k++] ^ apply0123(T01, T23, s1, s2, s3, s0);\n const t2 = xk[k++] ^ apply0123(T01, T23, s2, s3, s0, s1);\n const t3 = xk[k++] ^ apply0123(T01, T23, s3, s0, s1, s2);\n (s0 = t0), (s1 = t1), (s2 = t2), (s3 = t3);\n }\n // last round (without mixcolumns, so using SBOX2 table)\n const t0 = xk[k++] ^ applySbox(sbox2, s0, s1, s2, s3);\n const t1 = xk[k++] ^ applySbox(sbox2, s1, s2, s3, s0);\n const t2 = xk[k++] ^ applySbox(sbox2, s2, s3, s0, s1);\n const t3 = xk[k++] ^ applySbox(sbox2, s3, s0, s1, s2);\n return { s0: t0, s1: t1, s2: t2, s3: t3 };\n}\n\nfunction decrypt(xk: Uint32Array, s0: number, s1: number, s2: number, s3: number) {\n const { sbox2, T01, T23 } = tableDecoding;\n let k = 0;\n (s0 ^= xk[k++]), (s1 ^= xk[k++]), (s2 ^= xk[k++]), (s3 ^= xk[k++]);\n const rounds = xk.length / 4 - 2;\n for (let i = 0; i < rounds; i++) {\n const t0 = xk[k++] ^ apply0123(T01, T23, s0, s3, s2, s1);\n const t1 = xk[k++] ^ apply0123(T01, T23, s1, s0, s3, s2);\n const t2 = xk[k++] ^ apply0123(T01, T23, s2, s1, s0, s3);\n const t3 = xk[k++] ^ apply0123(T01, T23, s3, s2, s1, s0);\n (s0 = t0), (s1 = t1), (s2 = t2), (s3 = t3);\n }\n // Last round\n const t0 = xk[k++] ^ applySbox(sbox2, s0, s3, s2, s1);\n const t1 = xk[k++] ^ applySbox(sbox2, s1, s0, s3, s2);\n const t2 = xk[k++] ^ applySbox(sbox2, s2, s1, s0, s3);\n const t3 = xk[k++] ^ applySbox(sbox2, s3, s2, s1, s0);\n return { s0: t0, s1: t1, s2: t2, s3: t3 };\n}\n\nfunction getDst(len: number, dst?: Uint8Array) {\n if (!dst) return new Uint8Array(len);\n abytes(dst);\n if (dst.length < len)\n throw new Error(`aes: wrong destination length, expected at least ${len}, got: ${dst.length}`);\n return dst;\n}\n\n// TODO: investigate merging with ctr32\nfunction ctrCounter(xk: Uint32Array, nonce: Uint8Array, src: Uint8Array, dst?: Uint8Array) {\n abytes(nonce, BLOCK_SIZE);\n abytes(src);\n const srcLen = src.length;\n dst = getDst(srcLen, dst);\n const ctr = nonce;\n const c32 = u32(ctr);\n // Fill block (empty, ctr=0)\n let { s0, s1, s2, s3 } = encrypt(xk, c32[0], c32[1], c32[2], c32[3]);\n const src32 = u32(src);\n const dst32 = u32(dst);\n // process blocks\n for (let i = 0; i + 4 <= src32.length; i += 4) {\n dst32[i + 0] = src32[i + 0] ^ s0;\n dst32[i + 1] = src32[i + 1] ^ s1;\n dst32[i + 2] = src32[i + 2] ^ s2;\n dst32[i + 3] = src32[i + 3] ^ s3;\n // Full 128 bit counter with wrap around\n let carry = 1;\n for (let i = ctr.length - 1; i >= 0; i--) {\n carry = (carry + (ctr[i] & 0xff)) | 0;\n ctr[i] = carry & 0xff;\n carry >>>= 8;\n }\n ({ s0, s1, s2, s3 } = encrypt(xk, c32[0], c32[1], c32[2], c32[3]));\n }\n // leftovers (less than block)\n // It's possible to handle > u32 fast, but is it worth it?\n const start = BLOCK_SIZE * Math.floor(src32.length / BLOCK_SIZE32);\n if (start < srcLen) {\n const b32 = new Uint32Array([s0, s1, s2, s3]);\n const buf = u8(b32);\n for (let i = start, pos = 0; i < srcLen; i++, pos++) dst[i] = src[i] ^ buf[pos];\n }\n return dst;\n}\n\n// AES CTR with overflowing 32 bit counter\n// It's possible to do 32le significantly simpler (and probably faster) by using u32.\n// But, we need both, and perf bottleneck is in ghash anyway.\nfunction ctr32(\n xk: Uint32Array,\n isLE: boolean,\n nonce: Uint8Array,\n src: Uint8Array,\n dst?: Uint8Array\n) {\n abytes(nonce, BLOCK_SIZE);\n abytes(src);\n dst = getDst(src.length, dst);\n const ctr = nonce; // write new value to nonce, so it can be re-used\n const c32 = u32(ctr);\n const view = createView(ctr);\n const src32 = u32(src);\n const dst32 = u32(dst);\n const ctrPos = isLE ? 0 : 12;\n const srcLen = src.length;\n // Fill block (empty, ctr=0)\n let ctrNum = view.getUint32(ctrPos, isLE); // read current counter value\n let { s0, s1, s2, s3 } = encrypt(xk, c32[0], c32[1], c32[2], c32[3]);\n // process blocks\n for (let i = 0; i + 4 <= src32.length; i += 4) {\n dst32[i + 0] = src32[i + 0] ^ s0;\n dst32[i + 1] = src32[i + 1] ^ s1;\n dst32[i + 2] = src32[i + 2] ^ s2;\n dst32[i + 3] = src32[i + 3] ^ s3;\n ctrNum = (ctrNum + 1) >>> 0; // u32 wrap\n view.setUint32(ctrPos, ctrNum, isLE);\n ({ s0, s1, s2, s3 } = encrypt(xk, c32[0], c32[1], c32[2], c32[3]));\n }\n // leftovers (less than a block)\n const start = BLOCK_SIZE * Math.floor(src32.length / BLOCK_SIZE32);\n if (start < srcLen) {\n const b32 = new Uint32Array([s0, s1, s2, s3]);\n const buf = u8(b32);\n for (let i = start, pos = 0; i < srcLen; i++, pos++) dst[i] = src[i] ^ buf[pos];\n }\n return dst;\n}\n\n/**\n * CTR: counter mode. Creates stream cipher.\n * Requires good IV. Parallelizable. OK, but no MAC.\n */\nexport const ctr = wrapCipher(\n { blockSize: 16, nonceLength: 16 },\n function ctr(key: Uint8Array, nonce: Uint8Array): CipherWithOutput {\n abytes(key);\n abytes(nonce, BLOCK_SIZE);\n function processCtr(buf: Uint8Array, dst?: Uint8Array) {\n const xk = expandKeyLE(key);\n const n = nonce.slice();\n const out = ctrCounter(xk, n, buf, dst);\n xk.fill(0);\n n.fill(0);\n return out;\n }\n return {\n encrypt: (plaintext: Uint8Array, dst?: Uint8Array) => processCtr(plaintext, dst),\n decrypt: (ciphertext: Uint8Array, dst?: Uint8Array) => processCtr(ciphertext, dst),\n };\n }\n);\n\nfunction validateBlockDecrypt(data: Uint8Array) {\n abytes(data);\n if (data.length % BLOCK_SIZE !== 0) {\n throw new Error(\n `aes/(cbc-ecb).decrypt ciphertext should consist of blocks with size ${BLOCK_SIZE}`\n );\n }\n}\n\nfunction validateBlockEncrypt(plaintext: Uint8Array, pcks5: boolean, dst?: Uint8Array) {\n let outLen = plaintext.length;\n const remaining = outLen % BLOCK_SIZE;\n if (!pcks5 && remaining !== 0)\n throw new Error('aec/(cbc-ecb): unpadded plaintext with disabled padding');\n const b = u32(plaintext);\n if (pcks5) {\n let left = BLOCK_SIZE - remaining;\n if (!left) left = BLOCK_SIZE; // if no bytes left, create empty padding block\n outLen = outLen + left;\n }\n const out = getDst(outLen, dst);\n const o = u32(out);\n return { b, o, out };\n}\n\nfunction validatePCKS(data: Uint8Array, pcks5: boolean) {\n if (!pcks5) return data;\n const len = data.length;\n if (!len) throw new Error(`aes/pcks5: empty ciphertext not allowed`);\n const lastByte = data[len - 1];\n if (lastByte <= 0 || lastByte > 16) throw new Error(`aes/pcks5: wrong padding byte: ${lastByte}`);\n const out = data.subarray(0, -lastByte);\n for (let i = 0; i < lastByte; i++)\n if (data[len - i - 1] !== lastByte) throw new Error(`aes/pcks5: wrong padding`);\n return out;\n}\n\nfunction padPCKS(left: Uint8Array) {\n const tmp = new Uint8Array(16);\n const tmp32 = u32(tmp);\n tmp.set(left);\n const paddingByte = BLOCK_SIZE - left.length;\n for (let i = BLOCK_SIZE - paddingByte; i < BLOCK_SIZE; i++) tmp[i] = paddingByte;\n return tmp32;\n}\n\nexport type BlockOpts = { disablePadding?: boolean };\n\n/**\n * ECB: Electronic CodeBook. Simple deterministic replacement.\n * Dangerous: always map x to y. See [AES Penguin](https://words.filippo.io/the-ecb-penguin/).\n */\nexport const ecb = wrapCipher(\n { blockSize: 16 },\n function ecb(key: Uint8Array, opts: BlockOpts = {}): CipherWithOutput {\n abytes(key);\n const pcks5 = !opts.disablePadding;\n return {\n encrypt: (plaintext: Uint8Array, dst?: Uint8Array) => {\n abytes(plaintext);\n const { b, o, out: _out } = validateBlockEncrypt(plaintext, pcks5, dst);\n const xk = expandKeyLE(key);\n let i = 0;\n for (; i + 4 <= b.length; ) {\n const { s0, s1, s2, s3 } = encrypt(xk, b[i + 0], b[i + 1], b[i + 2], b[i + 3]);\n (o[i++] = s0), (o[i++] = s1), (o[i++] = s2), (o[i++] = s3);\n }\n if (pcks5) {\n const tmp32 = padPCKS(plaintext.subarray(i * 4));\n const { s0, s1, s2, s3 } = encrypt(xk, tmp32[0], tmp32[1], tmp32[2], tmp32[3]);\n (o[i++] = s0), (o[i++] = s1), (o[i++] = s2), (o[i++] = s3);\n }\n xk.fill(0);\n return _out;\n },\n decrypt: (ciphertext: Uint8Array, dst?: Uint8Array) => {\n validateBlockDecrypt(ciphertext);\n const xk = expandKeyDecLE(key);\n const out = getDst(ciphertext.length, dst);\n const b = u32(ciphertext);\n const o = u32(out);\n for (let i = 0; i + 4 <= b.length; ) {\n const { s0, s1, s2, s3 } = decrypt(xk, b[i + 0], b[i + 1], b[i + 2], b[i + 3]);\n (o[i++] = s0), (o[i++] = s1), (o[i++] = s2), (o[i++] = s3);\n }\n xk.fill(0);\n return validatePCKS(out, pcks5);\n },\n };\n }\n);\n\n/**\n * CBC: Cipher-Block-Chaining. Key is previous round’s block.\n * Fragile: needs proper padding. Unauthenticated: needs MAC.\n */\nexport const cbc = wrapCipher(\n { blockSize: 16, nonceLength: 16 },\n function cbc(key: Uint8Array, iv: Uint8Array, opts: BlockOpts = {}): CipherWithOutput {\n abytes(key);\n abytes(iv, 16);\n const pcks5 = !opts.disablePadding;\n return {\n encrypt: (plaintext: Uint8Array, dst?: Uint8Array) => {\n const xk = expandKeyLE(key);\n const { b, o, out: _out } = validateBlockEncrypt(plaintext, pcks5, dst);\n const n32 = u32(iv);\n // prettier-ignore\n let s0 = n32[0], s1 = n32[1], s2 = n32[2], s3 = n32[3];\n let i = 0;\n for (; i + 4 <= b.length; ) {\n (s0 ^= b[i + 0]), (s1 ^= b[i + 1]), (s2 ^= b[i + 2]), (s3 ^= b[i + 3]);\n ({ s0, s1, s2, s3 } = encrypt(xk, s0, s1, s2, s3));\n (o[i++] = s0), (o[i++] = s1), (o[i++] = s2), (o[i++] = s3);\n }\n if (pcks5) {\n const tmp32 = padPCKS(plaintext.subarray(i * 4));\n (s0 ^= tmp32[0]), (s1 ^= tmp32[1]), (s2 ^= tmp32[2]), (s3 ^= tmp32[3]);\n ({ s0, s1, s2, s3 } = encrypt(xk, s0, s1, s2, s3));\n (o[i++] = s0), (o[i++] = s1), (o[i++] = s2), (o[i++] = s3);\n }\n xk.fill(0);\n return _out;\n },\n decrypt: (ciphertext: Uint8Array, dst?: Uint8Array) => {\n validateBlockDecrypt(ciphertext);\n const xk = expandKeyDecLE(key);\n const n32 = u32(iv);\n const out = getDst(ciphertext.length, dst);\n const b = u32(ciphertext);\n const o = u32(out);\n // prettier-ignore\n let s0 = n32[0], s1 = n32[1], s2 = n32[2], s3 = n32[3];\n for (let i = 0; i + 4 <= b.length; ) {\n // prettier-ignore\n const ps0 = s0, ps1 = s1, ps2 = s2, ps3 = s3;\n (s0 = b[i + 0]), (s1 = b[i + 1]), (s2 = b[i + 2]), (s3 = b[i + 3]);\n const { s0: o0, s1: o1, s2: o2, s3: o3 } = decrypt(xk, s0, s1, s2, s3);\n (o[i++] = o0 ^ ps0), (o[i++] = o1 ^ ps1), (o[i++] = o2 ^ ps2), (o[i++] = o3 ^ ps3);\n }\n xk.fill(0);\n return validatePCKS(out, pcks5);\n },\n };\n }\n);\n\n/**\n * CFB: Cipher Feedback Mode. The input for the block cipher is the previous cipher output.\n * Unauthenticated: needs MAC.\n */\nexport const cfb = wrapCipher(\n { blockSize: 16, nonceLength: 16 },\n function cfb(key: Uint8Array, iv: Uint8Array): CipherWithOutput {\n abytes(key);\n abytes(iv, 16);\n function processCfb(src: Uint8Array, isEncrypt: boolean, dst?: Uint8Array) {\n const xk = expandKeyLE(key);\n const srcLen = src.length;\n dst = getDst(srcLen, dst);\n const src32 = u32(src);\n const dst32 = u32(dst);\n const next32 = isEncrypt ? dst32 : src32;\n const n32 = u32(iv);\n // prettier-ignore\n let s0 = n32[0], s1 = n32[1], s2 = n32[2], s3 = n32[3];\n for (let i = 0; i + 4 <= src32.length; ) {\n const { s0: e0, s1: e1, s2: e2, s3: e3 } = encrypt(xk, s0, s1, s2, s3);\n dst32[i + 0] = src32[i + 0] ^ e0;\n dst32[i + 1] = src32[i + 1] ^ e1;\n dst32[i + 2] = src32[i + 2] ^ e2;\n dst32[i + 3] = src32[i + 3] ^ e3;\n (s0 = next32[i++]), (s1 = next32[i++]), (s2 = next32[i++]), (s3 = next32[i++]);\n }\n // leftovers (less than block)\n const start = BLOCK_SIZE * Math.floor(src32.length / BLOCK_SIZE32);\n if (start < srcLen) {\n ({ s0, s1, s2, s3 } = encrypt(xk, s0, s1, s2, s3));\n const buf = u8(new Uint32Array([s0, s1, s2, s3]));\n for (let i = start, pos = 0; i < srcLen; i++, pos++) dst[i] = src[i] ^ buf[pos];\n buf.fill(0);\n }\n xk.fill(0);\n return dst;\n }\n return {\n encrypt: (plaintext: Uint8Array, dst?: Uint8Array) => processCfb(plaintext, true, dst),\n decrypt: (ciphertext: Uint8Array, dst?: Uint8Array) => processCfb(ciphertext, false, dst),\n };\n }\n);\n\n// TODO: merge with chacha, however gcm has bitLen while chacha has byteLen\nfunction computeTag(\n fn: typeof ghash,\n isLE: boolean,\n key: Uint8Array,\n data: Uint8Array,\n AAD?: Uint8Array\n) {\n const h = fn.create(key, data.length + (AAD?.length || 0));\n if (AAD) h.update(AAD);\n h.update(data);\n const num = new Uint8Array(16);\n const view = createView(num);\n if (AAD) setBigUint64(view, 0, BigInt(AAD.length * 8), isLE);\n setBigUint64(view, 8, BigInt(data.length * 8), isLE);\n h.update(num);\n return h.digest();\n}\n\n/**\n * GCM: Galois/Counter Mode.\n * Good, modern version of CTR, parallel, with MAC.\n * Be careful: MACs can be forged.\n */\nexport const gcm = wrapCipher(\n { blockSize: 16, nonceLength: 12, tagLength: 16 },\n function gcm(key: Uint8Array, nonce: Uint8Array, AAD?: Uint8Array): Cipher {\n abytes(nonce);\n // Nonce can be pretty much anything (even 1 byte). But smaller nonces less secure.\n if (nonce.length === 0) throw new Error('aes/gcm: empty nonce');\n const tagLength = 16;\n function _computeTag(authKey: Uint8Array, tagMask: Uint8Array, data: Uint8Array) {\n const tag = computeTag(ghash, false, authKey, data, AAD);\n for (let i = 0; i < tagMask.length; i++) tag[i] ^= tagMask[i];\n return tag;\n }\n function deriveKeys() {\n const xk = expandKeyLE(key);\n const authKey = EMPTY_BLOCK.slice();\n const counter = EMPTY_BLOCK.slice();\n ctr32(xk, false, counter, counter, authKey);\n if (nonce.length === 12) {\n counter.set(nonce);\n } else {\n // Spec (NIST 800-38d) supports variable size nonce.\n // Not supported for now, but can be useful.\n const nonceLen = EMPTY_BLOCK.slice();\n const view = createView(nonceLen);\n setBigUint64(view, 8, BigInt(nonce.length * 8), false);\n // ghash(nonce || u64be(0) || u64be(nonceLen*8))\n ghash.create(authKey).update(nonce).update(nonceLen).digestInto(counter);\n }\n const tagMask = ctr32(xk, false, counter, EMPTY_BLOCK);\n return { xk, authKey, counter, tagMask };\n }\n return {\n encrypt: (plaintext: Uint8Array) => {\n abytes(plaintext);\n const { xk, authKey, counter, tagMask } = deriveKeys();\n const out = new Uint8Array(plaintext.length + tagLength);\n ctr32(xk, false, counter, plaintext, out);\n const tag = _computeTag(authKey, tagMask, out.subarray(0, out.length - tagLength));\n out.set(tag, plaintext.length);\n xk.fill(0);\n return out;\n },\n decrypt: (ciphertext: Uint8Array) => {\n abytes(ciphertext);\n if (ciphertext.length < tagLength)\n throw new Error(`aes/gcm: ciphertext less than tagLen (${tagLength})`);\n const { xk, authKey, counter, tagMask } = deriveKeys();\n const data = ciphertext.subarray(0, -tagLength);\n const passedTag = ciphertext.subarray(-tagLength);\n const tag = _computeTag(authKey, tagMask, data);\n if (!equalBytes(tag, passedTag)) throw new Error('aes/gcm: invalid ghash tag');\n const out = ctr32(xk, false, counter, data);\n authKey.fill(0);\n tagMask.fill(0);\n xk.fill(0);\n return out;\n },\n };\n }\n);\n\nconst limit = (name: string, min: number, max: number) => (value: number) => {\n if (!Number.isSafeInteger(value) || min > value || value > max)\n throw new Error(`${name}: invalid value=${value}, must be [${min}..${max}]`);\n};\n\n/**\n * AES-GCM-SIV: classic AES-GCM with nonce-misuse resistance.\n * Guarantees that, when a nonce is repeated, the only security loss is that identical\n * plaintexts will produce identical ciphertexts.\n * RFC 8452, https://datatracker.ietf.org/doc/html/rfc8452\n */\nexport const siv = wrapCipher(\n { blockSize: 16, nonceLength: 12, tagLength: 16 },\n function siv(key: Uint8Array, nonce: Uint8Array, AAD?: Uint8Array): Cipher {\n const tagLength = 16;\n // From RFC 8452: Section 6\n const AAD_LIMIT = limit('AAD', 0, 2 ** 36);\n const PLAIN_LIMIT = limit('plaintext', 0, 2 ** 36);\n const NONCE_LIMIT = limit('nonce', 12, 12);\n const CIPHER_LIMIT = limit('ciphertext', 16, 2 ** 36 + 16);\n abytes(nonce);\n NONCE_LIMIT(nonce.length);\n if (AAD) {\n abytes(AAD);\n AAD_LIMIT(AAD.length);\n }\n function deriveKeys() {\n const len = key.length;\n if (len !== 16 && len !== 24 && len !== 32)\n throw new Error(`key length must be 16, 24 or 32 bytes, got: ${len} bytes`);\n const xk = expandKeyLE(key);\n const encKey = new Uint8Array(len);\n const authKey = new Uint8Array(16);\n const n32 = u32(nonce);\n // prettier-ignore\n let s0 = 0, s1 = n32[0], s2 = n32[1], s3 = n32[2];\n let counter = 0;\n for (const derivedKey of [authKey, encKey].map(u32)) {\n const d32 = u32(derivedKey);\n for (let i = 0; i < d32.length; i += 2) {\n // aes(u32le(0) || nonce)[:8] || aes(u32le(1) || nonce)[:8] ...\n const { s0: o0, s1: o1 } = encrypt(xk, s0, s1, s2, s3);\n d32[i + 0] = o0;\n d32[i + 1] = o1;\n s0 = ++counter; // increment counter inside state\n }\n }\n xk.fill(0);\n return { authKey, encKey: expandKeyLE(encKey) };\n }\n function _computeTag(encKey: Uint32Array, authKey: Uint8Array, data: Uint8Array) {\n const tag = computeTag(polyval, true, authKey, data, AAD);\n // Compute the expected tag by XORing S_s and the nonce, clearing the\n // most significant bit of the last byte and encrypting with the\n // message-encryption key.\n for (let i = 0; i < 12; i++) tag[i] ^= nonce[i];\n tag[15] &= 0x7f; // Clear the highest bit\n // encrypt tag as block\n const t32 = u32(tag);\n // prettier-ignore\n let s0 = t32[0], s1 = t32[1], s2 = t32[2], s3 = t32[3];\n ({ s0, s1, s2, s3 } = encrypt(encKey, s0, s1, s2, s3));\n (t32[0] = s0), (t32[1] = s1), (t32[2] = s2), (t32[3] = s3);\n return tag;\n }\n // actual decrypt/encrypt of message.\n function processSiv(encKey: Uint32Array, tag: Uint8Array, input: Uint8Array) {\n let block = tag.slice();\n block[15] |= 0x80; // Force highest bit\n return ctr32(encKey, true, block, input);\n }\n return {\n encrypt: (plaintext: Uint8Array) => {\n abytes(plaintext);\n PLAIN_LIMIT(plaintext.length);\n const { encKey, authKey } = deriveKeys();\n const tag = _computeTag(encKey, authKey, plaintext);\n const out = new Uint8Array(plaintext.length + tagLength);\n out.set(tag, plaintext.length);\n out.set(processSiv(encKey, tag, plaintext));\n encKey.fill(0);\n authKey.fill(0);\n return out;\n },\n decrypt: (ciphertext: Uint8Array) => {\n abytes(ciphertext);\n CIPHER_LIMIT(ciphertext.length);\n const tag = ciphertext.subarray(-tagLength);\n const { encKey, authKey } = deriveKeys();\n const plaintext = processSiv(encKey, tag, ciphertext.subarray(0, -tagLength));\n const expectedTag = _computeTag(encKey, authKey, plaintext);\n encKey.fill(0);\n authKey.fill(0);\n if (!equalBytes(tag, expectedTag)) throw new Error('invalid polyval tag');\n return plaintext;\n },\n };\n }\n);\n\nfunction isBytes32(a: unknown): a is Uint8Array {\n return (\n a != null &&\n typeof a === 'object' &&\n (a instanceof Uint32Array || a.constructor.name === 'Uint32Array')\n );\n}\n\nfunction encryptBlock(xk: Uint32Array, block: Uint8Array) {\n abytes(block, 16);\n if (!isBytes32(xk)) throw new Error('_encryptBlock accepts result of expandKeyLE');\n const b32 = u32(block);\n let { s0, s1, s2, s3 } = encrypt(xk, b32[0], b32[1], b32[2], b32[3]);\n (b32[0] = s0), (b32[1] = s1), (b32[2] = s2), (b32[3] = s3);\n return block;\n}\n\nfunction decryptBlock(xk: Uint32Array, block: Uint8Array) {\n abytes(block, 16);\n if (!isBytes32(xk)) throw new Error('_decryptBlock accepts result of expandKeyLE');\n const b32 = u32(block);\n let { s0, s1, s2, s3 } = decrypt(xk, b32[0], b32[1], b32[2], b32[3]);\n (b32[0] = s0), (b32[1] = s1), (b32[2] = s2), (b32[3] = s3);\n return block;\n}\n\n// Highly unsafe private functions for implementing new modes or ciphers based on AES\n// Can change at any time, no API guarantees\nexport const unsafe = {\n expandKeyLE,\n expandKeyDecLE,\n encrypt,\n decrypt,\n encryptBlock,\n decryptBlock,\n ctrCounter,\n ctr32,\n};\n", "import { exists as aexists, bytes as abytes, output as aoutput } from './_assert.js';\nimport { Input, toBytes, Hash } from './utils.js';\n\n// Poly1305 is a fast and parallel secret-key message-authentication code.\n// https://cr.yp.to/mac.html, https://cr.yp.to/mac/poly1305-20050329.pdf\n// https://datatracker.ietf.org/doc/html/rfc8439\n\n// Based on Public Domain poly1305-donna https://github.com/floodyberry/poly1305-donna\nconst u8to16 = (a: Uint8Array, i: number) => (a[i++] & 0xff) | ((a[i++] & 0xff) << 8);\nclass Poly1305 implements Hash {\n readonly blockLen = 16;\n readonly outputLen = 16;\n private buffer = new Uint8Array(16);\n private r = new Uint16Array(10);\n private h = new Uint16Array(10);\n private pad = new Uint16Array(8);\n private pos = 0;\n protected finished = false;\n\n constructor(key: Input) {\n key = toBytes(key);\n abytes(key, 32);\n const t0 = u8to16(key, 0);\n const t1 = u8to16(key, 2);\n const t2 = u8to16(key, 4);\n const t3 = u8to16(key, 6);\n const t4 = u8to16(key, 8);\n const t5 = u8to16(key, 10);\n const t6 = u8to16(key, 12);\n const t7 = u8to16(key, 14);\n\n // https://github.com/floodyberry/poly1305-donna/blob/e6ad6e091d30d7f4ec2d4f978be1fcfcbce72781/poly1305-donna-16.h#L47\n this.r[0] = t0 & 0x1fff;\n this.r[1] = ((t0 >>> 13) | (t1 << 3)) & 0x1fff;\n this.r[2] = ((t1 >>> 10) | (t2 << 6)) & 0x1f03;\n this.r[3] = ((t2 >>> 7) | (t3 << 9)) & 0x1fff;\n this.r[4] = ((t3 >>> 4) | (t4 << 12)) & 0x00ff;\n this.r[5] = (t4 >>> 1) & 0x1ffe;\n this.r[6] = ((t4 >>> 14) | (t5 << 2)) & 0x1fff;\n this.r[7] = ((t5 >>> 11) | (t6 << 5)) & 0x1f81;\n this.r[8] = ((t6 >>> 8) | (t7 << 8)) & 0x1fff;\n this.r[9] = (t7 >>> 5) & 0x007f;\n for (let i = 0; i < 8; i++) this.pad[i] = u8to16(key, 16 + 2 * i);\n }\n\n private process(data: Uint8Array, offset: number, isLast = false) {\n const hibit = isLast ? 0 : 1 << 11;\n const { h, r } = this;\n const r0 = r[0];\n const r1 = r[1];\n const r2 = r[2];\n const r3 = r[3];\n const r4 = r[4];\n const r5 = r[5];\n const r6 = r[6];\n const r7 = r[7];\n const r8 = r[8];\n const r9 = r[9];\n\n const t0 = u8to16(data, offset + 0);\n const t1 = u8to16(data, offset + 2);\n const t2 = u8to16(data, offset + 4);\n const t3 = u8to16(data, offset + 6);\n const t4 = u8to16(data, offset + 8);\n const t5 = u8to16(data, offset + 10);\n const t6 = u8to16(data, offset + 12);\n const t7 = u8to16(data, offset + 14);\n\n let h0 = h[0] + (t0 & 0x1fff);\n let h1 = h[1] + (((t0 >>> 13) | (t1 << 3)) & 0x1fff);\n let h2 = h[2] + (((t1 >>> 10) | (t2 << 6)) & 0x1fff);\n let h3 = h[3] + (((t2 >>> 7) | (t3 << 9)) & 0x1fff);\n let h4 = h[4] + (((t3 >>> 4) | (t4 << 12)) & 0x1fff);\n let h5 = h[5] + ((t4 >>> 1) & 0x1fff);\n let h6 = h[6] + (((t4 >>> 14) | (t5 << 2)) & 0x1fff);\n let h7 = h[7] + (((t5 >>> 11) | (t6 << 5)) & 0x1fff);\n let h8 = h[8] + (((t6 >>> 8) | (t7 << 8)) & 0x1fff);\n let h9 = h[9] + ((t7 >>> 5) | hibit);\n\n let c = 0;\n\n let d0 = c + h0 * r0 + h1 * (5 * r9) + h2 * (5 * r8) + h3 * (5 * r7) + h4 * (5 * r6);\n c = d0 >>> 13;\n d0 &= 0x1fff;\n d0 += h5 * (5 * r5) + h6 * (5 * r4) + h7 * (5 * r3) + h8 * (5 * r2) + h9 * (5 * r1);\n c += d0 >>> 13;\n d0 &= 0x1fff;\n\n let d1 = c + h0 * r1 + h1 * r0 + h2 * (5 * r9) + h3 * (5 * r8) + h4 * (5 * r7);\n c = d1 >>> 13;\n d1 &= 0x1fff;\n d1 += h5 * (5 * r6) + h6 * (5 * r5) + h7 * (5 * r4) + h8 * (5 * r3) + h9 * (5 * r2);\n c += d1 >>> 13;\n d1 &= 0x1fff;\n\n let d2 = c + h0 * r2 + h1 * r1 + h2 * r0 + h3 * (5 * r9) + h4 * (5 * r8);\n c = d2 >>> 13;\n d2 &= 0x1fff;\n d2 += h5 * (5 * r7) + h6 * (5 * r6) + h7 * (5 * r5) + h8 * (5 * r4) + h9 * (5 * r3);\n c += d2 >>> 13;\n d2 &= 0x1fff;\n\n let d3 = c + h0 * r3 + h1 * r2 + h2 * r1 + h3 * r0 + h4 * (5 * r9);\n c = d3 >>> 13;\n d3 &= 0x1fff;\n d3 += h5 * (5 * r8) + h6 * (5 * r7) + h7 * (5 * r6) + h8 * (5 * r5) + h9 * (5 * r4);\n c += d3 >>> 13;\n d3 &= 0x1fff;\n\n let d4 = c + h0 * r4 + h1 * r3 + h2 * r2 + h3 * r1 + h4 * r0;\n c = d4 >>> 13;\n d4 &= 0x1fff;\n d4 += h5 * (5 * r9) + h6 * (5 * r8) + h7 * (5 * r7) + h8 * (5 * r6) + h9 * (5 * r5);\n c += d4 >>> 13;\n d4 &= 0x1fff;\n\n let d5 = c + h0 * r5 + h1 * r4 + h2 * r3 + h3 * r2 + h4 * r1;\n c = d5 >>> 13;\n d5 &= 0x1fff;\n d5 += h5 * r0 + h6 * (5 * r9) + h7 * (5 * r8) + h8 * (5 * r7) + h9 * (5 * r6);\n c += d5 >>> 13;\n d5 &= 0x1fff;\n\n let d6 = c + h0 * r6 + h1 * r5 + h2 * r4 + h3 * r3 + h4 * r2;\n c = d6 >>> 13;\n d6 &= 0x1fff;\n d6 += h5 * r1 + h6 * r0 + h7 * (5 * r9) + h8 * (5 * r8) + h9 * (5 * r7);\n c += d6 >>> 13;\n d6 &= 0x1fff;\n\n let d7 = c + h0 * r7 + h1 * r6 + h2 * r5 + h3 * r4 + h4 * r3;\n c = d7 >>> 13;\n d7 &= 0x1fff;\n d7 += h5 * r2 + h6 * r1 + h7 * r0 + h8 * (5 * r9) + h9 * (5 * r8);\n c += d7 >>> 13;\n d7 &= 0x1fff;\n\n let d8 = c + h0 * r8 + h1 * r7 + h2 * r6 + h3 * r5 + h4 * r4;\n c = d8 >>> 13;\n d8 &= 0x1fff;\n d8 += h5 * r3 + h6 * r2 + h7 * r1 + h8 * r0 + h9 * (5 * r9);\n c += d8 >>> 13;\n d8 &= 0x1fff;\n\n let d9 = c + h0 * r9 + h1 * r8 + h2 * r7 + h3 * r6 + h4 * r5;\n c = d9 >>> 13;\n d9 &= 0x1fff;\n d9 += h5 * r4 + h6 * r3 + h7 * r2 + h8 * r1 + h9 * r0;\n c += d9 >>> 13;\n d9 &= 0x1fff;\n\n c = ((c << 2) + c) | 0;\n c = (c + d0) | 0;\n d0 = c & 0x1fff;\n c = c >>> 13;\n d1 += c;\n\n h[0] = d0;\n h[1] = d1;\n h[2] = d2;\n h[3] = d3;\n h[4] = d4;\n h[5] = d5;\n h[6] = d6;\n h[7] = d7;\n h[8] = d8;\n h[9] = d9;\n }\n\n private finalize() {\n const { h, pad } = this;\n const g = new Uint16Array(10);\n let c = h[1] >>> 13;\n h[1] &= 0x1fff;\n for (let i = 2; i < 10; i++) {\n h[i] += c;\n c = h[i] >>> 13;\n h[i] &= 0x1fff;\n }\n h[0] += c * 5;\n c = h[0] >>> 13;\n h[0] &= 0x1fff;\n h[1] += c;\n c = h[1] >>> 13;\n h[1] &= 0x1fff;\n h[2] += c;\n\n g[0] = h[0] + 5;\n c = g[0] >>> 13;\n g[0] &= 0x1fff;\n for (let i = 1; i < 10; i++) {\n g[i] = h[i] + c;\n c = g[i] >>> 13;\n g[i] &= 0x1fff;\n }\n g[9] -= 1 << 13;\n\n let mask = (c ^ 1) - 1;\n for (let i = 0; i < 10; i++) g[i] &= mask;\n mask = ~mask;\n for (let i = 0; i < 10; i++) h[i] = (h[i] & mask) | g[i];\n h[0] = (h[0] | (h[1] << 13)) & 0xffff;\n h[1] = ((h[1] >>> 3) | (h[2] << 10)) & 0xffff;\n h[2] = ((h[2] >>> 6) | (h[3] << 7)) & 0xffff;\n h[3] = ((h[3] >>> 9) | (h[4] << 4)) & 0xffff;\n h[4] = ((h[4] >>> 12) | (h[5] << 1) | (h[6] << 14)) & 0xffff;\n h[5] = ((h[6] >>> 2) | (h[7] << 11)) & 0xffff;\n h[6] = ((h[7] >>> 5) | (h[8] << 8)) & 0xffff;\n h[7] = ((h[8] >>> 8) | (h[9] << 5)) & 0xffff;\n\n let f = h[0] + pad[0];\n h[0] = f & 0xffff;\n for (let i = 1; i < 8; i++) {\n f = (((h[i] + pad[i]) | 0) + (f >>> 16)) | 0;\n h[i] = f & 0xffff;\n }\n }\n update(data: Input): this {\n aexists(this);\n const { buffer, blockLen } = this;\n data = toBytes(data);\n const len = data.length;\n\n for (let pos = 0; pos < len; ) {\n const take = Math.min(blockLen - this.pos, len - pos);\n // Fast path: we have at least one block in input\n if (take === blockLen) {\n for (; blockLen <= len - pos; pos += blockLen) this.process(data, pos);\n continue;\n }\n buffer.set(data.subarray(pos, pos + take), this.pos);\n this.pos += take;\n pos += take;\n if (this.pos === blockLen) {\n this.process(buffer, 0, false);\n this.pos = 0;\n }\n }\n return this;\n }\n destroy() {\n this.h.fill(0);\n this.r.fill(0);\n this.buffer.fill(0);\n this.pad.fill(0);\n }\n digestInto(out: Uint8Array) {\n aexists(this);\n aoutput(out, this);\n this.finished = true;\n const { buffer, h } = this;\n let { pos } = this;\n if (pos) {\n buffer[pos++] = 1;\n // buffer.subarray(pos).fill(0);\n for (; pos < 16; pos++) buffer[pos] = 0;\n this.process(buffer, 0, true);\n }\n this.finalize();\n let opos = 0;\n for (let i = 0; i < 8; i++) {\n out[opos++] = h[i] >>> 0;\n out[opos++] = h[i] >>> 8;\n }\n return out;\n }\n digest(): Uint8Array {\n const { buffer, outputLen } = this;\n this.digestInto(buffer);\n const res = buffer.slice(0, outputLen);\n this.destroy();\n return res;\n }\n}\n\nexport type CHash = ReturnType;\nexport function wrapConstructorWithKey>(hashCons: (key: Input) => Hash) {\n const hashC = (msg: Input, key: Input): Uint8Array => hashCons(key).update(toBytes(msg)).digest();\n const tmp = hashCons(new Uint8Array(32));\n hashC.outputLen = tmp.outputLen;\n hashC.blockLen = tmp.blockLen;\n hashC.create = (key: Input) => hashCons(key);\n return hashC;\n}\n\nexport const poly1305 = wrapConstructorWithKey((key) => new Poly1305(key));\n", "// Basic utils for ARX (add-rotate-xor) salsa and chacha ciphers.\nimport { number as anumber, bytes as abytes, bool as abool } from './_assert.js';\nimport { XorStream, checkOpts, u32 } from './utils.js';\n\n/*\nRFC8439 requires multi-step cipher stream, where\nauthKey starts with counter: 0, actual msg with counter: 1.\n\nFor this, we need a way to re-use nonce / counter:\n\n const counter = new Uint8Array(4);\n chacha(..., counter, ...); // counter is now 1\n chacha(..., counter, ...); // counter is now 2\n\nThis is complicated:\n\n- 32-bit counters are enough, no need for 64-bit: max ArrayBuffer size in JS is 4GB\n- Original papers don't allow mutating counters\n- Counter overflow is undefined [^1]\n- Idea A: allow providing (nonce | counter) instead of just nonce, re-use it\n- Caveat: Cannot be re-used through all cases:\n- * chacha has (counter | nonce)\n- * xchacha has (nonce16 | counter | nonce16)\n- Idea B: separate nonce / counter and provide separate API for counter re-use\n- Caveat: there are different counter sizes depending on an algorithm.\n- salsa & chacha also differ in structures of key & sigma:\n salsa20: s[0] | k(4) | s[1] | nonce(2) | ctr(2) | s[2] | k(4) | s[3]\n chacha: s(4) | k(8) | ctr(1) | nonce(3)\n chacha20orig: s(4) | k(8) | ctr(2) | nonce(2)\n- Idea C: helper method such as `setSalsaState(key, nonce, sigma, data)`\n- Caveat: we can't re-use counter array\n\nxchacha [^2] uses the subkey and remaining 8 byte nonce with ChaCha20 as normal\n(prefixed by 4 NUL bytes, since [RFC8439] specifies a 12-byte nonce).\n\n[^1]: https://mailarchive.ietf.org/arch/msg/cfrg/gsOnTJzcbgG6OqD8Sc0GO5aR_tU/\n[^2]: https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-xchacha#appendix-A.2\n*/\n\n// We can't make top-level var depend on utils.utf8ToBytes\n// because it's not present in all envs. Creating a similar fn here\nconst _utf8ToBytes = (str: string) => Uint8Array.from(str.split('').map((c) => c.charCodeAt(0)));\nconst sigma16 = _utf8ToBytes('expand 16-byte k');\nconst sigma32 = _utf8ToBytes('expand 32-byte k');\nconst sigma16_32 = u32(sigma16);\nconst sigma32_32 = u32(sigma32);\nexport const sigma = sigma32_32.slice();\n\nexport function rotl(a: number, b: number): number {\n return (a << b) | (a >>> (32 - b));\n}\n\nexport type CipherCoreFn = (\n sigma: Uint32Array,\n key: Uint32Array,\n nonce: Uint32Array,\n output: Uint32Array,\n counter: number,\n rounds?: number\n) => void;\n\nexport type ExtendNonceFn = (\n sigma: Uint32Array,\n key: Uint32Array,\n input: Uint32Array,\n output: Uint32Array\n) => void;\n\nexport type CipherOpts = {\n allowShortKeys?: boolean; // Original salsa / chacha allow 16-byte keys\n extendNonceFn?: ExtendNonceFn;\n counterLength?: number;\n counterRight?: boolean; // right: nonce|counter; left: counter|nonce\n rounds?: number;\n};\n\n// Is byte array aligned to 4 byte offset (u32)?\nfunction isAligned32(b: Uint8Array) {\n return b.byteOffset % 4 === 0;\n}\n\n// Salsa and Chacha block length is always 512-bit\nconst BLOCK_LEN = 64;\nconst BLOCK_LEN32 = 16;\n\n// new Uint32Array([2**32]) // => Uint32Array(1) [ 0 ]\n// new Uint32Array([2**32-1]) // => Uint32Array(1) [ 4294967295 ]\nconst MAX_COUNTER = 2 ** 32 - 1;\n\nconst U32_EMPTY = new Uint32Array();\nfunction runCipher(\n core: CipherCoreFn,\n sigma: Uint32Array,\n key: Uint32Array,\n nonce: Uint32Array,\n data: Uint8Array,\n output: Uint8Array,\n counter: number,\n rounds: number\n): void {\n const len = data.length;\n const block = new Uint8Array(BLOCK_LEN);\n const b32 = u32(block);\n // Make sure that buffers aligned to 4 bytes\n const isAligned = isAligned32(data) && isAligned32(output);\n const d32 = isAligned ? u32(data) : U32_EMPTY;\n const o32 = isAligned ? u32(output) : U32_EMPTY;\n for (let pos = 0; pos < len; counter++) {\n core(sigma, key, nonce, b32, counter, rounds);\n if (counter >= MAX_COUNTER) throw new Error('arx: counter overflow');\n const take = Math.min(BLOCK_LEN, len - pos);\n // aligned to 4 bytes\n if (isAligned && take === BLOCK_LEN) {\n const pos32 = pos / 4;\n if (pos % 4 !== 0) throw new Error('arx: invalid block position');\n for (let j = 0, posj: number; j < BLOCK_LEN32; j++) {\n posj = pos32 + j;\n o32[posj] = d32[posj] ^ b32[j];\n }\n pos += BLOCK_LEN;\n continue;\n }\n for (let j = 0, posj; j < take; j++) {\n posj = pos + j;\n output[posj] = data[posj] ^ block[j];\n }\n pos += take;\n }\n}\n\nexport function createCipher(core: CipherCoreFn, opts: CipherOpts): XorStream {\n const { allowShortKeys, extendNonceFn, counterLength, counterRight, rounds } = checkOpts(\n { allowShortKeys: false, counterLength: 8, counterRight: false, rounds: 20 },\n opts\n );\n if (typeof core !== 'function') throw new Error('core must be a function');\n anumber(counterLength);\n anumber(rounds);\n abool(counterRight);\n abool(allowShortKeys);\n return (\n key: Uint8Array,\n nonce: Uint8Array,\n data: Uint8Array,\n output?: Uint8Array,\n counter = 0\n ): Uint8Array => {\n abytes(key);\n abytes(nonce);\n abytes(data);\n const len = data.length;\n if (!output) output = new Uint8Array(len);\n abytes(output);\n anumber(counter);\n if (counter < 0 || counter >= MAX_COUNTER) throw new Error('arx: counter overflow');\n if (output.length < len)\n throw new Error(`arx: output (${output.length}) is shorter than data (${len})`);\n const toClean = [];\n\n // Key & sigma\n // key=16 -> sigma16, k=key|key\n // key=32 -> sigma32, k=key\n let l = key.length,\n k: Uint8Array,\n sigma: Uint32Array;\n if (l === 32) {\n k = key.slice();\n toClean.push(k);\n sigma = sigma32_32;\n } else if (l === 16 && allowShortKeys) {\n k = new Uint8Array(32);\n k.set(key);\n k.set(key, 16);\n sigma = sigma16_32;\n toClean.push(k);\n } else {\n throw new Error(`arx: invalid 32-byte key, got length=${l}`);\n }\n\n // Nonce\n // salsa20: 8 (8-byte counter)\n // chacha20orig: 8 (8-byte counter)\n // chacha20: 12 (4-byte counter)\n // xsalsa20: 24 (16 -> hsalsa, 8 -> old nonce)\n // xchacha20: 24 (16 -> hchacha, 8 -> old nonce)\n // Align nonce to 4 bytes\n if (!isAligned32(nonce)) {\n nonce = nonce.slice();\n toClean.push(nonce);\n }\n\n const k32 = u32(k);\n // hsalsa & hchacha: handle extended nonce\n if (extendNonceFn) {\n if (nonce.length !== 24) throw new Error(`arx: extended nonce must be 24 bytes`);\n extendNonceFn(sigma, k32, u32(nonce.subarray(0, 16)), k32);\n nonce = nonce.subarray(16);\n }\n\n // Handle nonce counter\n const nonceNcLen = 16 - counterLength;\n if (nonceNcLen !== nonce.length)\n throw new Error(`arx: nonce must be ${nonceNcLen} or 16 bytes`);\n\n // Pad counter when nonce is 64 bit\n if (nonceNcLen !== 12) {\n const nc = new Uint8Array(12);\n nc.set(nonce, counterRight ? 0 : 12 - nonce.length);\n nonce = nc;\n toClean.push(nonce);\n }\n const n32 = u32(nonce);\n runCipher(core, sigma, k32, n32, data, output, counter, rounds);\n while (toClean.length > 0) toClean.pop()!.fill(0);\n return output;\n };\n}\n", "// prettier-ignore\nimport {\n wrapCipher, CipherWithOutput, XorStream, createView, equalBytes, setBigUint64,\n} from './utils.js';\nimport { poly1305 } from './_poly1305.js';\nimport { createCipher, rotl } from './_arx.js';\nimport { bytes as abytes } from './_assert.js';\n\n// ChaCha20 stream cipher was released in 2008. ChaCha aims to increase\n// the diffusion per round, but had slightly less cryptanalysis.\n// https://cr.yp.to/chacha.html, http://cr.yp.to/chacha/chacha-20080128.pdf\n\n/**\n * ChaCha core function.\n */\n// prettier-ignore\nfunction chachaCore(\n s: Uint32Array, k: Uint32Array, n: Uint32Array, out: Uint32Array, cnt: number, rounds = 20\n): void {\n let y00 = s[0], y01 = s[1], y02 = s[2], y03 = s[3], // \"expa\" \"nd 3\" \"2-by\" \"te k\"\n y04 = k[0], y05 = k[1], y06 = k[2], y07 = k[3], // Key Key Key Key\n y08 = k[4], y09 = k[5], y10 = k[6], y11 = k[7], // Key Key Key Key\n y12 = cnt, y13 = n[0], y14 = n[1], y15 = n[2]; // Counter Counter\tNonce Nonce\n // Save state to temporary variables\n let x00 = y00, x01 = y01, x02 = y02, x03 = y03,\n x04 = y04, x05 = y05, x06 = y06, x07 = y07,\n x08 = y08, x09 = y09, x10 = y10, x11 = y11,\n x12 = y12, x13 = y13, x14 = y14, x15 = y15;\n for (let r = 0; r < rounds; r += 2) {\n x00 = (x00 + x04) | 0; x12 = rotl(x12 ^ x00, 16);\n x08 = (x08 + x12) | 0; x04 = rotl(x04 ^ x08, 12);\n x00 = (x00 + x04) | 0; x12 = rotl(x12 ^ x00, 8);\n x08 = (x08 + x12) | 0; x04 = rotl(x04 ^ x08, 7);\n\n x01 = (x01 + x05) | 0; x13 = rotl(x13 ^ x01, 16);\n x09 = (x09 + x13) | 0; x05 = rotl(x05 ^ x09, 12);\n x01 = (x01 + x05) | 0; x13 = rotl(x13 ^ x01, 8);\n x09 = (x09 + x13) | 0; x05 = rotl(x05 ^ x09, 7);\n\n x02 = (x02 + x06) | 0; x14 = rotl(x14 ^ x02, 16);\n x10 = (x10 + x14) | 0; x06 = rotl(x06 ^ x10, 12);\n x02 = (x02 + x06) | 0; x14 = rotl(x14 ^x02, 8);\n x10 = (x10 + x14) | 0; x06 = rotl(x06 ^ x10, 7);\n\n x03 = (x03 + x07) | 0; x15 = rotl(x15 ^ x03, 16);\n x11 = (x11 + x15) | 0; x07 = rotl(x07 ^ x11, 12);\n x03 = (x03 + x07) | 0; x15 = rotl(x15 ^ x03, 8)\n x11 = (x11 + x15) | 0; x07 = rotl(x07 ^ x11, 7);\n\n x00 = (x00 + x05) | 0; x15 = rotl(x15 ^ x00, 16);\n x10 = (x10 + x15) | 0; x05 = rotl(x05 ^ x10, 12);\n x00 = (x00 + x05) | 0; x15 = rotl(x15 ^ x00, 8);\n x10 = (x10 + x15) | 0; x05 = rotl(x05 ^ x10, 7);\n\n x01 = (x01 + x06) | 0; x12 = rotl(x12 ^ x01, 16);\n x11 = (x11 + x12) | 0; x06 = rotl(x06 ^ x11, 12);\n x01 = (x01 + x06) | 0; x12 = rotl(x12 ^ x01, 8);\n x11 = (x11 + x12) | 0; x06 = rotl(x06 ^ x11, 7);\n\n x02 = (x02 + x07) | 0; x13 = rotl(x13 ^ x02, 16);\n x08 = (x08 + x13) | 0; x07 = rotl(x07 ^ x08, 12);\n x02 = (x02 + x07) | 0; x13 = rotl(x13 ^ x02, 8);\n x08 = (x08 + x13) | 0; x07 = rotl(x07 ^ x08, 7);\n\n x03 = (x03 + x04) | 0; x14 = rotl(x14 ^ x03, 16)\n x09 = (x09 + x14) | 0; x04 = rotl(x04 ^ x09, 12);\n x03 = (x03 + x04) | 0; x14 = rotl(x14 ^ x03, 8);\n x09 = (x09 + x14) | 0; x04 = rotl(x04 ^ x09, 7);\n }\n // Write output\n let oi = 0;\n out[oi++] = (y00 + x00) | 0; out[oi++] = (y01 + x01) | 0;\n out[oi++] = (y02 + x02) | 0; out[oi++] = (y03 + x03) | 0;\n out[oi++] = (y04 + x04) | 0; out[oi++] = (y05 + x05) | 0;\n out[oi++] = (y06 + x06) | 0; out[oi++] = (y07 + x07) | 0;\n out[oi++] = (y08 + x08) | 0; out[oi++] = (y09 + x09) | 0;\n out[oi++] = (y10 + x10) | 0; out[oi++] = (y11 + x11) | 0;\n out[oi++] = (y12 + x12) | 0; out[oi++] = (y13 + x13) | 0;\n out[oi++] = (y14 + x14) | 0; out[oi++] = (y15 + x15) | 0;\n}\n/**\n * hchacha helper method, used primarily in xchacha, to hash\n * key and nonce into key' and nonce'.\n * Same as chachaCore, but there doesn't seem to be a way to move the block\n * out without 25% performance hit.\n */\n// prettier-ignore\nexport function hchacha(\n s: Uint32Array, k: Uint32Array, i: Uint32Array, o32: Uint32Array\n) {\n let x00 = s[0], x01 = s[1], x02 = s[2], x03 = s[3],\n x04 = k[0], x05 = k[1], x06 = k[2], x07 = k[3],\n x08 = k[4], x09 = k[5], x10 = k[6], x11 = k[7],\n x12 = i[0], x13 = i[1], x14 = i[2], x15 = i[3];\n for (let r = 0; r < 20; r += 2) {\n x00 = (x00 + x04) | 0; x12 = rotl(x12 ^ x00, 16);\n x08 = (x08 + x12) | 0; x04 = rotl(x04 ^ x08, 12);\n x00 = (x00 + x04) | 0; x12 = rotl(x12 ^ x00, 8);\n x08 = (x08 + x12) | 0; x04 = rotl(x04 ^ x08, 7);\n\n x01 = (x01 + x05) | 0; x13 = rotl(x13 ^ x01, 16);\n x09 = (x09 + x13) | 0; x05 = rotl(x05 ^ x09, 12);\n x01 = (x01 + x05) | 0; x13 = rotl(x13 ^ x01, 8);\n x09 = (x09 + x13) | 0; x05 = rotl(x05 ^ x09, 7);\n\n x02 = (x02 + x06) | 0; x14 = rotl(x14 ^ x02, 16);\n x10 = (x10 + x14) | 0; x06 = rotl(x06 ^ x10, 12);\n x02 = (x02 + x06) | 0; x14 = rotl(x14 ^ x02, 8);\n x10 = (x10 + x14) | 0; x06 = rotl(x06 ^ x10, 7);\n\n x03 = (x03 + x07) | 0; x15 = rotl(x15 ^ x03, 16);\n x11 = (x11 + x15) | 0; x07 = rotl(x07 ^ x11, 12);\n x03 = (x03 + x07) | 0; x15 = rotl(x15 ^ x03, 8)\n x11 = (x11 + x15) | 0; x07 = rotl(x07 ^ x11, 7);\n\n x00 = (x00 + x05) | 0; x15 = rotl(x15 ^ x00, 16);\n x10 = (x10 + x15) | 0; x05 = rotl(x05 ^ x10, 12);\n x00 = (x00 + x05) | 0; x15 = rotl(x15 ^ x00, 8);\n x10 = (x10 + x15) | 0; x05 = rotl(x05 ^ x10, 7);\n\n x01 = (x01 + x06) | 0; x12 = rotl(x12 ^ x01, 16);\n x11 = (x11 + x12) | 0; x06 = rotl(x06 ^ x11, 12);\n x01 = (x01 + x06) | 0; x12 = rotl(x12 ^ x01, 8);\n x11 = (x11 + x12) | 0; x06 = rotl(x06 ^ x11, 7);\n\n x02 = (x02 + x07) | 0; x13 = rotl(x13 ^ x02, 16);\n x08 = (x08 + x13) | 0; x07 = rotl(x07 ^ x08, 12);\n x02 = (x02 + x07) | 0; x13 = rotl(x13 ^ x02, 8);\n x08 = (x08 + x13) | 0; x07 = rotl(x07 ^ x08, 7);\n\n x03 = (x03 + x04) | 0; x14 = rotl(x14 ^ x03, 16)\n x09 = (x09 + x14) | 0; x04 = rotl(x04 ^ x09, 12);\n x03 = (x03 + x04) | 0; x14 = rotl(x14 ^ x03, 8);\n x09 = (x09 + x14) | 0; x04 = rotl(x04 ^ x09, 7);\n }\n let oi = 0;\n o32[oi++] = x00; o32[oi++] = x01;\n o32[oi++] = x02; o32[oi++] = x03;\n o32[oi++] = x12; o32[oi++] = x13;\n o32[oi++] = x14; o32[oi++] = x15;\n}\n/**\n * Original, non-RFC chacha20 from DJB. 8-byte nonce, 8-byte counter.\n */\nexport const chacha20orig = /* @__PURE__ */ createCipher(chachaCore, {\n counterRight: false,\n counterLength: 8,\n allowShortKeys: true,\n});\n/**\n * ChaCha stream cipher. Conforms to RFC 8439 (IETF, TLS). 12-byte nonce, 4-byte counter.\n * With 12-byte nonce, it's not safe to use fill it with random (CSPRNG), due to collision chance.\n */\nexport const chacha20 = /* @__PURE__ */ createCipher(chachaCore, {\n counterRight: false,\n counterLength: 4,\n allowShortKeys: false,\n});\n\n/**\n * XChaCha eXtended-nonce ChaCha. 24-byte nonce.\n * With 24-byte nonce, it's safe to use fill it with random (CSPRNG).\n * https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-xchacha\n */\nexport const xchacha20 = /* @__PURE__ */ createCipher(chachaCore, {\n counterRight: false,\n counterLength: 8,\n extendNonceFn: hchacha,\n allowShortKeys: false,\n});\n\n/**\n * Reduced 8-round chacha, described in original paper.\n */\nexport const chacha8 = /* @__PURE__ */ createCipher(chachaCore, {\n counterRight: false,\n counterLength: 4,\n rounds: 8,\n});\n\n/**\n * Reduced 12-round chacha, described in original paper.\n */\nexport const chacha12 = /* @__PURE__ */ createCipher(chachaCore, {\n counterRight: false,\n counterLength: 4,\n rounds: 12,\n});\n\nconst ZEROS16 = /* @__PURE__ */ new Uint8Array(16);\n// Pad to digest size with zeros\nconst updatePadded = (h: ReturnType, msg: Uint8Array) => {\n h.update(msg);\n const left = msg.length % 16;\n if (left) h.update(ZEROS16.subarray(left));\n};\n\nconst ZEROS32 = /* @__PURE__ */ new Uint8Array(32);\nfunction computeTag(\n fn: XorStream,\n key: Uint8Array,\n nonce: Uint8Array,\n data: Uint8Array,\n AAD?: Uint8Array\n): Uint8Array {\n const authKey = fn(key, nonce, ZEROS32);\n const h = poly1305.create(authKey);\n if (AAD) updatePadded(h, AAD);\n updatePadded(h, data);\n const num = new Uint8Array(16);\n const view = createView(num);\n setBigUint64(view, 0, BigInt(AAD ? AAD.length : 0), true);\n setBigUint64(view, 8, BigInt(data.length), true);\n h.update(num);\n const res = h.digest();\n authKey.fill(0);\n return res;\n}\n\n/**\n * AEAD algorithm from RFC 8439.\n * Salsa20 and chacha (RFC 8439) use poly1305 differently.\n * We could have composed them similar to:\n * https://github.com/paulmillr/scure-base/blob/b266c73dde977b1dd7ef40ef7a23cc15aab526b3/index.ts#L250\n * But it's hard because of authKey:\n * In salsa20, authKey changes position in salsa stream.\n * In chacha, authKey can't be computed inside computeTag, it modifies the counter.\n */\nexport const _poly1305_aead =\n (xorStream: XorStream) =>\n (key: Uint8Array, nonce: Uint8Array, AAD?: Uint8Array): CipherWithOutput => {\n const tagLength = 16;\n abytes(key, 32);\n abytes(nonce);\n return {\n encrypt: (plaintext: Uint8Array, output?: Uint8Array) => {\n const plength = plaintext.length;\n const clength = plength + tagLength;\n if (output) {\n abytes(output, clength);\n } else {\n output = new Uint8Array(clength);\n }\n xorStream(key, nonce, plaintext, output, 1);\n const tag = computeTag(xorStream, key, nonce, output.subarray(0, -tagLength), AAD);\n output.set(tag, plength); // append tag\n return output;\n },\n decrypt: (ciphertext: Uint8Array, output?: Uint8Array) => {\n const clength = ciphertext.length;\n const plength = clength - tagLength;\n if (clength < tagLength)\n throw new Error(`encrypted data must be at least ${tagLength} bytes`);\n if (output) {\n abytes(output, plength);\n } else {\n output = new Uint8Array(plength);\n }\n const data = ciphertext.subarray(0, -tagLength);\n const passedTag = ciphertext.subarray(-tagLength);\n const tag = computeTag(xorStream, key, nonce, data, AAD);\n if (!equalBytes(passedTag, tag)) throw new Error('invalid tag');\n xorStream(key, nonce, data, output, 1);\n return output;\n },\n };\n };\n\n/**\n * ChaCha20-Poly1305 from RFC 8439.\n * With 12-byte nonce, it's not safe to use fill it with random (CSPRNG), due to collision chance.\n */\nexport const chacha20poly1305 = /* @__PURE__ */ wrapCipher(\n { blockSize: 64, nonceLength: 12, tagLength: 16 },\n _poly1305_aead(chacha20)\n);\n/**\n * XChaCha20-Poly1305 extended-nonce chacha.\n * https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-xchacha\n * With 24-byte nonce, it's safe to use fill it with random (CSPRNG).\n */\nexport const xchacha20poly1305 = /* @__PURE__ */ wrapCipher(\n { blockSize: 64, nonceLength: 24, tagLength: 16 },\n _poly1305_aead(xchacha20)\n);\n", "import assert from './_assert.js';\nimport { Hash, CHash, Input, toBytes } from './utils.js';\n// HMAC (RFC 2104)\nexport class HMAC> extends Hash> {\n oHash: T;\n iHash: T;\n blockLen: number;\n outputLen: number;\n private finished = false;\n private destroyed = false;\n\n constructor(hash: CHash, _key: Input) {\n super();\n assert.hash(hash);\n const key = toBytes(_key);\n this.iHash = hash.create() as T;\n if (typeof this.iHash.update !== 'function')\n throw new Error('Expected instance of class which extends utils.Hash');\n this.blockLen = this.iHash.blockLen;\n this.outputLen = this.iHash.outputLen;\n const blockLen = this.blockLen;\n const pad = new Uint8Array(blockLen);\n // blockLen can be bigger than outputLen\n pad.set(key.length > blockLen ? hash.create().update(key).digest() : key);\n for (let i = 0; i < pad.length; i++) pad[i] ^= 0x36;\n this.iHash.update(pad);\n // By doing update (processing of first block) of outer hash here we can re-use it between multiple calls via clone\n this.oHash = hash.create() as T;\n // Undo internal XOR && apply outer XOR\n for (let i = 0; i < pad.length; i++) pad[i] ^= 0x36 ^ 0x5c;\n this.oHash.update(pad);\n pad.fill(0);\n }\n update(buf: Input) {\n assert.exists(this);\n this.iHash.update(buf);\n return this;\n }\n digestInto(out: Uint8Array) {\n assert.exists(this);\n assert.bytes(out, this.outputLen);\n this.finished = true;\n this.iHash.digestInto(out);\n this.oHash.update(out);\n this.oHash.digestInto(out);\n this.destroy();\n }\n digest() {\n const out = new Uint8Array(this.oHash.outputLen);\n this.digestInto(out);\n return out;\n }\n _cloneInto(to?: HMAC): HMAC {\n // Create new instance without calling constructor since key already in state and we don't know it.\n to ||= Object.create(Object.getPrototypeOf(this), {});\n const { oHash, iHash, finished, destroyed, blockLen, outputLen } = this;\n to = to as this;\n to.finished = finished;\n to.destroyed = destroyed;\n to.blockLen = blockLen;\n to.outputLen = outputLen;\n to.oHash = oHash._cloneInto(to.oHash);\n to.iHash = iHash._cloneInto(to.iHash);\n return to;\n }\n destroy() {\n this.destroyed = true;\n this.oHash.destroy();\n this.iHash.destroy();\n }\n}\n\n/**\n * HMAC: RFC2104 message authentication code.\n * @param hash - function that would be used e.g. sha256\n * @param key - message key\n * @param message - message data\n */\nexport const hmac = (hash: CHash, key: Input, message: Input): Uint8Array =>\n new HMAC(hash, key).update(message).digest();\nhmac.create = (hash: CHash, key: Input) => new HMAC(hash, key);\n", "import assert from './_assert.js';\nimport { CHash, Input, toBytes } from './utils.js';\nimport { hmac } from './hmac.js';\n\n// HKDF (RFC 5869)\n// https://soatok.blog/2021/11/17/understanding-hkdf/\n\n/**\n * HKDF-Extract(IKM, salt) -> PRK\n * Arguments position differs from spec (IKM is first one, since it is not optional)\n * @param hash\n * @param ikm\n * @param salt\n * @returns\n */\nexport function extract(hash: CHash, ikm: Input, salt?: Input) {\n assert.hash(hash);\n // NOTE: some libraries treat zero-length array as 'not provided';\n // we don't, since we have undefined as 'not provided'\n // https://github.com/RustCrypto/KDFs/issues/15\n if (salt === undefined) salt = new Uint8Array(hash.outputLen); // if not provided, it is set to a string of HashLen zeros\n return hmac(hash, toBytes(salt), toBytes(ikm));\n}\n\n// HKDF-Expand(PRK, info, L) -> OKM\nconst HKDF_COUNTER = new Uint8Array([0]);\nconst EMPTY_BUFFER = new Uint8Array();\n\n/**\n * HKDF-expand from the spec.\n * @param prk - a pseudorandom key of at least HashLen octets (usually, the output from the extract step)\n * @param info - optional context and application specific information (can be a zero-length string)\n * @param length - length of output keying material in octets\n */\nexport function expand(hash: CHash, prk: Input, info?: Input, length: number = 32) {\n assert.hash(hash);\n assert.number(length);\n if (length > 255 * hash.outputLen) throw new Error('Length should be <= 255*HashLen');\n const blocks = Math.ceil(length / hash.outputLen);\n if (info === undefined) info = EMPTY_BUFFER;\n // first L(ength) octets of T\n const okm = new Uint8Array(blocks * hash.outputLen);\n // Re-use HMAC instance between blocks\n const HMAC = hmac.create(hash, prk);\n const HMACTmp = HMAC._cloneInto();\n const T = new Uint8Array(HMAC.outputLen);\n for (let counter = 0; counter < blocks; counter++) {\n HKDF_COUNTER[0] = counter + 1;\n // T(0) = empty string (zero length)\n // T(N) = HMAC-Hash(PRK, T(N-1) | info | N)\n HMACTmp.update(counter === 0 ? EMPTY_BUFFER : T)\n .update(info)\n .update(HKDF_COUNTER)\n .digestInto(T);\n okm.set(T, hash.outputLen * counter);\n HMAC._cloneInto(HMACTmp);\n }\n HMAC.destroy();\n HMACTmp.destroy();\n T.fill(0);\n HKDF_COUNTER.fill(0);\n return okm.slice(0, length);\n}\n\n/**\n * HKDF (RFC 5869): extract + expand in one step.\n * @param hash - hash function that would be used (e.g. sha256)\n * @param ikm - input keying material, the initial key\n * @param salt - optional salt value (a non-secret random value)\n * @param info - optional context and application specific information\n * @param length - length of output keying material in octets\n */\nexport const hkdf = (\n hash: CHash,\n ikm: Input,\n salt: Input | undefined,\n info: Input | undefined,\n length: number\n) => expand(hash, extract(hash, ikm, salt), info, length);\n", "var __defProp = Object.defineProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\n\n// pure.ts\nimport { schnorr } from \"@noble/curves/secp256k1\";\nimport { bytesToHex as bytesToHex2 } from \"@noble/hashes/utils\";\n\n// core.ts\nvar verifiedSymbol = Symbol(\"verified\");\nvar isRecord = (obj) => obj instanceof Object;\nfunction validateEvent(event) {\n if (!isRecord(event))\n return false;\n if (typeof event.kind !== \"number\")\n return false;\n if (typeof event.content !== \"string\")\n return false;\n if (typeof event.created_at !== \"number\")\n return false;\n if (typeof event.pubkey !== \"string\")\n return false;\n if (!event.pubkey.match(/^[a-f0-9]{64}$/))\n return false;\n if (!Array.isArray(event.tags))\n return false;\n for (let i2 = 0; i2 < event.tags.length; i2++) {\n let tag = event.tags[i2];\n if (!Array.isArray(tag))\n return false;\n for (let j = 0; j < tag.length; j++) {\n if (typeof tag[j] !== \"string\")\n return false;\n }\n }\n return true;\n}\nfunction sortEvents(events) {\n return events.sort((a, b) => {\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\n// pure.ts\nimport { sha256 } from \"@noble/hashes/sha256\";\n\n// utils.ts\nvar utils_exports = {};\n__export(utils_exports, {\n Queue: () => Queue,\n QueueNode: () => QueueNode,\n binarySearch: () => binarySearch,\n bytesToHex: () => bytesToHex,\n hexToBytes: () => hexToBytes,\n insertEventIntoAscendingList: () => insertEventIntoAscendingList,\n insertEventIntoDescendingList: () => insertEventIntoDescendingList,\n normalizeURL: () => normalizeURL,\n utf8Decoder: () => utf8Decoder,\n utf8Encoder: () => utf8Encoder\n});\nimport { bytesToHex, hexToBytes } from \"@noble/hashes/utils\";\nvar utf8Decoder = new TextDecoder(\"utf-8\");\nvar utf8Encoder = new TextEncoder();\nfunction normalizeURL(url) {\n try {\n if (url.indexOf(\"://\") === -1)\n url = \"wss://\" + url;\n let p = new URL(url);\n p.pathname = p.pathname.replace(/\\/+/g, \"/\");\n if (p.pathname.endsWith(\"/\"))\n p.pathname = p.pathname.slice(0, -1);\n if (p.port === \"80\" && p.protocol === \"ws:\" || p.port === \"443\" && p.protocol === \"wss:\")\n 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}\nfunction insertEventIntoDescendingList(sortedArray, event) {\n const [idx, found] = binarySearch(sortedArray, (b) => {\n if (event.id === b.id)\n return 0;\n if (event.created_at === b.created_at)\n 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}\nfunction insertEventIntoAscendingList(sortedArray, event) {\n const [idx, found] = binarySearch(sortedArray, (b) => {\n if (event.id === b.id)\n return 0;\n if (event.created_at === b.created_at)\n 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}\nfunction binarySearch(arr, compare) {\n let start = 0;\n let end = arr.length - 1;\n while (start <= end) {\n const mid = Math.floor((start + end) / 2);\n const cmp = compare(arr[mid]);\n if (cmp === 0) {\n return [mid, true];\n }\n if (cmp < 0) {\n end = mid - 1;\n } else {\n start = mid + 1;\n }\n }\n return [start, false];\n}\nvar QueueNode = class {\n value;\n next = null;\n prev = null;\n constructor(message) {\n this.value = message;\n }\n};\nvar Queue = class {\n first;\n last;\n constructor() {\n this.first = null;\n this.last = null;\n }\n enqueue(value) {\n const newNode = new QueueNode(value);\n if (!this.last) {\n this.first = newNode;\n this.last = newNode;\n } else if (this.last === this.first) {\n this.last = newNode;\n this.last.prev = this.first;\n this.first.next = newNode;\n } else {\n newNode.prev = this.last;\n this.last.next = newNode;\n this.last = newNode;\n }\n return true;\n }\n dequeue() {\n if (!this.first)\n return null;\n if (this.first === this.last) {\n const target2 = this.first;\n this.first = null;\n this.last = null;\n return target2.value;\n }\n const target = this.first;\n this.first = target.next;\n if (this.first) {\n this.first.prev = null;\n }\n return target.value;\n }\n};\n\n// pure.ts\nvar JS = class {\n generateSecretKey() {\n return schnorr.utils.randomPrivateKey();\n }\n getPublicKey(secretKey) {\n return bytesToHex2(schnorr.getPublicKey(secretKey));\n }\n finalizeEvent(t, secretKey) {\n const event = t;\n event.pubkey = bytesToHex2(schnorr.getPublicKey(secretKey));\n event.id = getEventHash(event);\n event.sig = bytesToHex2(schnorr.sign(getEventHash(event), secretKey));\n event[verifiedSymbol] = true;\n return event;\n }\n verifyEvent(event) {\n if (typeof event[verifiedSymbol] === \"boolean\")\n return event[verifiedSymbol];\n const hash = getEventHash(event);\n if (hash !== event.id) {\n event[verifiedSymbol] = false;\n return false;\n }\n try {\n const valid = schnorr.verify(event.sig, hash, event.pubkey);\n event[verifiedSymbol] = valid;\n return valid;\n } catch (err) {\n event[verifiedSymbol] = false;\n return false;\n }\n }\n};\nfunction serializeEvent(evt) {\n if (!validateEvent(evt))\n throw new Error(\"can't serialize event with wrong or missing properties\");\n return JSON.stringify([0, evt.pubkey, evt.created_at, evt.kind, evt.tags, evt.content]);\n}\nfunction getEventHash(event) {\n let eventHash = sha256(utf8Encoder.encode(serializeEvent(event)));\n return bytesToHex2(eventHash);\n}\nvar i = new JS();\nvar generateSecretKey = i.generateSecretKey;\nvar getPublicKey = i.getPublicKey;\nvar finalizeEvent = i.finalizeEvent;\nvar verifyEvent = i.verifyEvent;\n\n// kinds.ts\nvar kinds_exports = {};\n__export(kinds_exports, {\n Application: () => Application,\n BadgeAward: () => BadgeAward,\n BadgeDefinition: () => BadgeDefinition,\n BlockedRelaysList: () => BlockedRelaysList,\n BookmarkList: () => BookmarkList,\n Bookmarksets: () => Bookmarksets,\n Calendar: () => Calendar,\n CalendarEventRSVP: () => CalendarEventRSVP,\n ChannelCreation: () => ChannelCreation,\n ChannelHideMessage: () => ChannelHideMessage,\n ChannelMessage: () => ChannelMessage,\n ChannelMetadata: () => ChannelMetadata,\n ChannelMuteUser: () => ChannelMuteUser,\n ClassifiedListing: () => ClassifiedListing,\n ClientAuth: () => ClientAuth,\n CommunitiesList: () => CommunitiesList,\n CommunityDefinition: () => CommunityDefinition,\n CommunityPostApproval: () => CommunityPostApproval,\n Contacts: () => Contacts,\n CreateOrUpdateProduct: () => CreateOrUpdateProduct,\n CreateOrUpdateStall: () => CreateOrUpdateStall,\n Curationsets: () => Curationsets,\n Date: () => Date2,\n DirectMessageRelaysList: () => DirectMessageRelaysList,\n DraftClassifiedListing: () => DraftClassifiedListing,\n DraftLong: () => DraftLong,\n Emojisets: () => Emojisets,\n EncryptedDirectMessage: () => EncryptedDirectMessage,\n EventDeletion: () => EventDeletion,\n FileMetadata: () => FileMetadata,\n FileServerPreference: () => FileServerPreference,\n Followsets: () => Followsets,\n GenericRepost: () => GenericRepost,\n Genericlists: () => Genericlists,\n GiftWrap: () => GiftWrap,\n HTTPAuth: () => HTTPAuth,\n Handlerinformation: () => Handlerinformation,\n Handlerrecommendation: () => Handlerrecommendation,\n Highlights: () => Highlights,\n InterestsList: () => InterestsList,\n Interestsets: () => Interestsets,\n JobFeedback: () => JobFeedback,\n JobRequest: () => JobRequest,\n JobResult: () => JobResult,\n Label: () => Label,\n LightningPubRPC: () => LightningPubRPC,\n LiveChatMessage: () => LiveChatMessage,\n LiveEvent: () => LiveEvent,\n LongFormArticle: () => LongFormArticle,\n Metadata: () => Metadata,\n Mutelist: () => Mutelist,\n NWCWalletInfo: () => NWCWalletInfo,\n NWCWalletRequest: () => NWCWalletRequest,\n NWCWalletResponse: () => NWCWalletResponse,\n NostrConnect: () => NostrConnect,\n OpenTimestamps: () => OpenTimestamps,\n Pinlist: () => Pinlist,\n PrivateDirectMessage: () => PrivateDirectMessage,\n ProblemTracker: () => ProblemTracker,\n ProfileBadges: () => ProfileBadges,\n PublicChatsList: () => PublicChatsList,\n Reaction: () => Reaction,\n RecommendRelay: () => RecommendRelay,\n RelayList: () => RelayList,\n Relaysets: () => Relaysets,\n Report: () => Report,\n Reporting: () => Reporting,\n Repost: () => Repost,\n Seal: () => Seal,\n SearchRelaysList: () => SearchRelaysList,\n ShortTextNote: () => ShortTextNote,\n Time: () => Time,\n UserEmojiList: () => UserEmojiList,\n UserStatuses: () => UserStatuses,\n Zap: () => Zap,\n ZapGoal: () => ZapGoal,\n ZapRequest: () => ZapRequest,\n classifyKind: () => classifyKind,\n isAddressableKind: () => isAddressableKind,\n isEphemeralKind: () => isEphemeralKind,\n isKind: () => isKind,\n isRegularKind: () => isRegularKind,\n isReplaceableKind: () => isReplaceableKind\n});\nfunction isRegularKind(kind) {\n return 1e3 <= kind && kind < 1e4 || [1, 2, 4, 5, 6, 7, 8, 16, 40, 41, 42, 43, 44].includes(kind);\n}\nfunction isReplaceableKind(kind) {\n return [0, 3].includes(kind) || 1e4 <= kind && kind < 2e4;\n}\nfunction isEphemeralKind(kind) {\n return 2e4 <= kind && kind < 3e4;\n}\nfunction isAddressableKind(kind) {\n return 3e4 <= kind && kind < 4e4;\n}\nfunction classifyKind(kind) {\n if (isRegularKind(kind))\n return \"regular\";\n if (isReplaceableKind(kind))\n return \"replaceable\";\n if (isEphemeralKind(kind))\n return \"ephemeral\";\n if (isAddressableKind(kind))\n return \"parameterized\";\n return \"unknown\";\n}\nfunction isKind(event, kind) {\n const kindAsArray = kind instanceof Array ? kind : [kind];\n return validateEvent(event) && kindAsArray.includes(event.kind) || false;\n}\nvar Metadata = 0;\nvar ShortTextNote = 1;\nvar RecommendRelay = 2;\nvar Contacts = 3;\nvar EncryptedDirectMessage = 4;\nvar EventDeletion = 5;\nvar Repost = 6;\nvar Reaction = 7;\nvar BadgeAward = 8;\nvar Seal = 13;\nvar PrivateDirectMessage = 14;\nvar GenericRepost = 16;\nvar ChannelCreation = 40;\nvar ChannelMetadata = 41;\nvar ChannelMessage = 42;\nvar ChannelHideMessage = 43;\nvar ChannelMuteUser = 44;\nvar OpenTimestamps = 1040;\nvar GiftWrap = 1059;\nvar FileMetadata = 1063;\nvar LiveChatMessage = 1311;\nvar ProblemTracker = 1971;\nvar Report = 1984;\nvar Reporting = 1984;\nvar Label = 1985;\nvar CommunityPostApproval = 4550;\nvar JobRequest = 5999;\nvar JobResult = 6999;\nvar JobFeedback = 7e3;\nvar ZapGoal = 9041;\nvar ZapRequest = 9734;\nvar Zap = 9735;\nvar Highlights = 9802;\nvar Mutelist = 1e4;\nvar Pinlist = 10001;\nvar RelayList = 10002;\nvar BookmarkList = 10003;\nvar CommunitiesList = 10004;\nvar PublicChatsList = 10005;\nvar BlockedRelaysList = 10006;\nvar SearchRelaysList = 10007;\nvar InterestsList = 10015;\nvar UserEmojiList = 10030;\nvar DirectMessageRelaysList = 10050;\nvar FileServerPreference = 10096;\nvar NWCWalletInfo = 13194;\nvar LightningPubRPC = 21e3;\nvar ClientAuth = 22242;\nvar NWCWalletRequest = 23194;\nvar NWCWalletResponse = 23195;\nvar NostrConnect = 24133;\nvar HTTPAuth = 27235;\nvar Followsets = 3e4;\nvar Genericlists = 30001;\nvar Relaysets = 30002;\nvar Bookmarksets = 30003;\nvar Curationsets = 30004;\nvar ProfileBadges = 30008;\nvar BadgeDefinition = 30009;\nvar Interestsets = 30015;\nvar CreateOrUpdateStall = 30017;\nvar CreateOrUpdateProduct = 30018;\nvar LongFormArticle = 30023;\nvar DraftLong = 30024;\nvar Emojisets = 30030;\nvar Application = 30078;\nvar LiveEvent = 30311;\nvar UserStatuses = 30315;\nvar ClassifiedListing = 30402;\nvar DraftClassifiedListing = 30403;\nvar Date2 = 31922;\nvar Time = 31923;\nvar Calendar = 31924;\nvar CalendarEventRSVP = 31925;\nvar Handlerrecommendation = 31989;\nvar Handlerinformation = 31990;\nvar CommunityDefinition = 34550;\n\n// filter.ts\nfunction matchFilter(filter, event) {\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 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))\n return false;\n }\n }\n if (filter.since && event.created_at < filter.since)\n return false;\n if (filter.until && event.created_at > filter.until)\n return false;\n return true;\n}\nfunction matchFilters(filters, event) {\n for (let i2 = 0; i2 < filters.length; i2++) {\n if (matchFilter(filters[i2], event)) {\n return true;\n }\n }\n return false;\n}\nfunction mergeFilters(...filters) {\n let result = {};\n for (let i2 = 0; i2 < filters.length; i2++) {\n let filter = filters[i2];\n Object.entries(filter).forEach(([property, values]) => {\n if (property === \"kinds\" || property === \"ids\" || property === \"authors\" || property[0] === \"#\") {\n result[property] = result[property] || [];\n for (let v = 0; v < values.length; v++) {\n let value = values[v];\n if (!result[property].includes(value))\n result[property].push(value);\n }\n }\n });\n if (filter.limit && (!result.limit || filter.limit > result.limit))\n result.limit = filter.limit;\n if (filter.until && (!result.until || filter.until > result.until))\n result.until = filter.until;\n if (filter.since && (!result.since || filter.since < result.since))\n result.since = filter.since;\n }\n return result;\n}\nfunction getFilterLimit(filter) {\n if (filter.ids && !filter.ids.length)\n return 0;\n if (filter.kinds && !filter.kinds.length)\n return 0;\n if (filter.authors && !filter.authors.length)\n return 0;\n for (const [key, value] of Object.entries(filter)) {\n if (key[0] === \"#\" && Array.isArray(value) && !value.length)\n return 0;\n }\n return Math.min(\n Math.max(0, filter.limit ?? Infinity),\n filter.ids?.length ?? Infinity,\n filter.authors?.length && filter.kinds?.every((kind) => isReplaceableKind(kind)) ? filter.authors.length * filter.kinds.length : Infinity,\n filter.authors?.length && filter.kinds?.every((kind) => isAddressableKind(kind)) && filter[\"#d\"]?.length ? filter.authors.length * filter.kinds.length * filter[\"#d\"].length : Infinity\n );\n}\n\n// fakejson.ts\nvar fakejson_exports = {};\n__export(fakejson_exports, {\n getHex64: () => getHex64,\n getInt: () => getInt,\n getSubscriptionId: () => getSubscriptionId,\n matchEventId: () => matchEventId,\n matchEventKind: () => matchEventKind,\n matchEventPubkey: () => matchEventPubkey\n});\nfunction getHex64(json, field) {\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}\nfunction getInt(json, field) {\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}\nfunction getSubscriptionId(json) {\n let idx = json.slice(0, 22).indexOf(`\"EVENT\"`);\n if (idx === -1)\n return null;\n let pstart = json.slice(idx + 7 + 1).indexOf(`\"`);\n if (pstart === -1)\n return null;\n let start = idx + 7 + 1 + pstart;\n let pend = json.slice(start + 1, 80).indexOf(`\"`);\n if (pend === -1)\n return null;\n let end = start + 1 + pend;\n return json.slice(start + 1, end);\n}\nfunction matchEventId(json, id) {\n return id === getHex64(json, \"id\");\n}\nfunction matchEventPubkey(json, pubkey) {\n return pubkey === getHex64(json, \"pubkey\");\n}\nfunction matchEventKind(json, kind) {\n return kind === getInt(json, \"kind\");\n}\n\n// nip42.ts\nvar nip42_exports = {};\n__export(nip42_exports, {\n makeAuthEvent: () => makeAuthEvent\n});\nfunction makeAuthEvent(relayURL, challenge) {\n return {\n kind: ClientAuth,\n created_at: Math.floor(Date.now() / 1e3),\n tags: [\n [\"relay\", relayURL],\n [\"challenge\", challenge]\n ],\n content: \"\"\n };\n}\n\n// helpers.ts\nasync function yieldThread() {\n return new Promise((resolve) => {\n const ch = new MessageChannel();\n const handler = () => {\n ch.port1.removeEventListener(\"message\", handler);\n resolve();\n };\n ch.port1.addEventListener(\"message\", handler);\n ch.port2.postMessage(0);\n ch.port1.start();\n });\n}\nvar alwaysTrue = (t) => {\n t[verifiedSymbol] = true;\n return true;\n};\n\n// abstract-relay.ts\nvar SendingOnClosedConnection = class extends Error {\n constructor(message, relay) {\n super(`Tried to send message '${message} on a closed connection to ${relay}.`);\n this.name = \"SendingOnClosedConnection\";\n }\n};\nvar AbstractRelay = class {\n url;\n _connected = false;\n onclose = null;\n onnotice = (msg) => console.debug(`NOTICE from ${this.url}: ${msg}`);\n baseEoseTimeout = 4400;\n connectionTimeout = 4400;\n publishTimeout = 4400;\n openSubs = /* @__PURE__ */ new Map();\n connectionTimeoutHandle;\n connectionPromise;\n openCountRequests = /* @__PURE__ */ new Map();\n openEventPublishes = /* @__PURE__ */ new Map();\n ws;\n incomingMessageQueue = new Queue();\n queueRunning = false;\n challenge;\n authPromise;\n serial = 0;\n verifyEvent;\n _WebSocket;\n constructor(url, opts) {\n this.url = normalizeURL(url);\n this.verifyEvent = opts.verifyEvent;\n this._WebSocket = opts.websocketImplementation || WebSocket;\n }\n static async connect(url, opts) {\n const relay = new AbstractRelay(url, opts);\n await relay.connect();\n return relay;\n }\n closeAllSubscriptions(reason) {\n for (let [_, sub] of this.openSubs) {\n sub.close(reason);\n }\n this.openSubs.clear();\n for (let [_, ep] of this.openEventPublishes) {\n ep.reject(new Error(reason));\n }\n this.openEventPublishes.clear();\n for (let [_, cr] of this.openCountRequests) {\n cr.reject(new Error(reason));\n }\n this.openCountRequests.clear();\n }\n get connected() {\n return this._connected;\n }\n async connect() {\n if (this.connectionPromise)\n return this.connectionPromise;\n this.challenge = void 0;\n this.authPromise = void 0;\n this.connectionPromise = new Promise((resolve, reject) => {\n this.connectionTimeoutHandle = setTimeout(() => {\n reject(\"connection timed out\");\n this.connectionPromise = void 0;\n this.onclose?.();\n this.closeAllSubscriptions(\"relay connection timed out\");\n }, this.connectionTimeout);\n try {\n this.ws = new this._WebSocket(this.url);\n } catch (err) {\n clearTimeout(this.connectionTimeoutHandle);\n reject(err);\n return;\n }\n this.ws.onopen = () => {\n clearTimeout(this.connectionTimeoutHandle);\n this._connected = true;\n if (this.ws && this.ws.ping) {\n this.pingpong();\n }\n resolve();\n };\n this.ws.onerror = (ev) => {\n clearTimeout(this.connectionTimeoutHandle);\n reject(ev.message || \"websocket error\");\n if (this._connected) {\n this._connected = false;\n this.connectionPromise = void 0;\n this.onclose?.();\n this.closeAllSubscriptions(\"relay connection errored\");\n }\n };\n this.ws.onclose = (ev) => {\n clearTimeout(this.connectionTimeoutHandle);\n reject(ev.message || \"websocket closed\");\n if (this._connected) {\n this._connected = false;\n this.connectionPromise = void 0;\n this.onclose?.();\n this.closeAllSubscriptions(\"relay connection closed\");\n }\n };\n this.ws.onmessage = this._onmessage.bind(this);\n });\n return this.connectionPromise;\n }\n async receivePong() {\n return new Promise((res, err) => {\n ;\n this.ws && this.ws.on && this.ws.on(\"pong\", () => res(true)) || err(\"ws can't listen for pong\");\n });\n }\n async pingpong() {\n if (this.ws?.readyState == 1) {\n this.ws && this.ws.ping && this.ws.ping();\n const result = await Promise.any([\n this.receivePong(),\n new Promise((res) => setTimeout(() => res(false), 1e4))\n ]);\n console.error(\"pingpong result\", result);\n if (result) {\n setTimeout(() => this.pingpong(), 1e4);\n } else {\n this.ws && this.ws.close();\n }\n }\n }\n async runQueue() {\n this.queueRunning = true;\n while (true) {\n if (false === this.handleNext()) {\n break;\n }\n await yieldThread();\n }\n this.queueRunning = false;\n }\n handleNext() {\n const json = this.incomingMessageQueue.dequeue();\n if (!json) {\n return false;\n }\n const subid = getSubscriptionId(json);\n if (subid) {\n const so = this.openSubs.get(subid);\n if (!so) {\n return;\n }\n const id = getHex64(json, \"id\");\n const alreadyHave = so.alreadyHaveEvent?.(id);\n so.receivedEvent?.(this, id);\n if (alreadyHave) {\n return;\n }\n }\n try {\n let data = JSON.parse(json);\n switch (data[0]) {\n case \"EVENT\": {\n const so = this.openSubs.get(data[1]);\n const event = data[2];\n if (this.verifyEvent(event) && matchFilters(so.filters, event)) {\n so.onevent(event);\n }\n return;\n }\n case \"COUNT\": {\n const id = data[1];\n const payload = data[2];\n const cr = this.openCountRequests.get(id);\n if (cr) {\n cr.resolve(payload.count);\n this.openCountRequests.delete(id);\n }\n return;\n }\n case \"EOSE\": {\n const so = this.openSubs.get(data[1]);\n if (!so)\n return;\n so.receivedEose();\n return;\n }\n case \"OK\": {\n const id = data[1];\n const ok = data[2];\n const reason = data[3];\n const ep = this.openEventPublishes.get(id);\n if (ep) {\n clearTimeout(ep.timeout);\n if (ok)\n ep.resolve(reason);\n else\n ep.reject(new Error(reason));\n this.openEventPublishes.delete(id);\n }\n return;\n }\n case \"CLOSED\": {\n const id = data[1];\n const so = this.openSubs.get(id);\n if (!so)\n return;\n so.closed = true;\n so.close(data[2]);\n return;\n }\n case \"NOTICE\":\n this.onnotice(data[1]);\n return;\n case \"AUTH\": {\n this.challenge = data[1];\n return;\n }\n }\n } catch (err) {\n return;\n }\n }\n async send(message) {\n if (!this.connectionPromise)\n throw new SendingOnClosedConnection(message, this.url);\n this.connectionPromise.then(() => {\n this.ws?.send(message);\n });\n }\n async auth(signAuthEvent) {\n const challenge = this.challenge;\n if (!challenge)\n throw new Error(\"can't perform auth, no challenge was received\");\n if (this.authPromise)\n return this.authPromise;\n this.authPromise = new Promise(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);\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 async publish(event) {\n const ret = new Promise((resolve, reject) => {\n const timeout = setTimeout(() => {\n const ep = this.openEventPublishes.get(event.id);\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 this.send('[\"EVENT\",' + JSON.stringify(event) + \"]\");\n return ret;\n }\n async count(filters, params) {\n this.serial++;\n const id = params?.id || \"count:\" + this.serial;\n const ret = new Promise((resolve, reject) => {\n this.openCountRequests.set(id, { resolve, reject });\n });\n this.send('[\"COUNT\",\"' + id + '\",' + JSON.stringify(filters).substring(1));\n return ret;\n }\n subscribe(filters, params) {\n const subscription = this.prepareSubscription(filters, params);\n subscription.fire();\n return subscription;\n }\n prepareSubscription(filters, params) {\n this.serial++;\n const id = params.id || (params.label ? params.label + \":\" : \"sub:\") + this.serial;\n const subscription = new Subscription(this, id, filters, params);\n this.openSubs.set(id, subscription);\n return subscription;\n }\n close() {\n this.closeAllSubscriptions(\"relay connection closed by us\");\n this._connected = false;\n this.ws?.close();\n this.onclose?.();\n }\n _onmessage(ev) {\n this.incomingMessageQueue.enqueue(ev.data);\n if (!this.queueRunning) {\n this.runQueue();\n }\n }\n};\nvar Subscription = class {\n relay;\n id;\n closed = false;\n eosed = false;\n filters;\n alreadyHaveEvent;\n receivedEvent;\n onevent;\n oneose;\n onclose;\n eoseTimeout;\n eoseTimeoutHandle;\n constructor(relay, id, filters, params) {\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 this.oneose = params.oneose;\n this.onclose = params.onclose;\n this.onevent = params.onevent || ((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 fire() {\n this.relay.send('[\"REQ\",\"' + this.id + '\",' + JSON.stringify(this.filters).substring(1));\n this.eoseTimeoutHandle = setTimeout(this.receivedEose.bind(this), this.eoseTimeout);\n }\n receivedEose() {\n if (this.eosed)\n return;\n clearTimeout(this.eoseTimeoutHandle);\n this.eosed = true;\n this.oneose?.();\n }\n close(reason = \"closed by caller\") {\n if (!this.closed && this.relay.connected) {\n try {\n this.relay.send('[\"CLOSE\",' + JSON.stringify(this.id) + \"]\");\n } catch (err) {\n if (err instanceof SendingOnClosedConnection) {\n } else {\n throw err;\n }\n }\n this.closed = true;\n }\n this.relay.openSubs.delete(this.id);\n this.onclose?.(reason);\n }\n};\n\n// relay.ts\nvar _WebSocket;\ntry {\n _WebSocket = WebSocket;\n} catch {\n}\nvar Relay = class extends AbstractRelay {\n constructor(url) {\n super(url, { verifyEvent, websocketImplementation: _WebSocket });\n }\n static async connect(url) {\n const relay = new Relay(url);\n await relay.connect();\n return relay;\n }\n};\n\n// abstract-pool.ts\nvar AbstractSimplePool = class {\n relays = /* @__PURE__ */ new Map();\n seenOn = /* @__PURE__ */ new Map();\n trackRelays = false;\n verifyEvent;\n trustedRelayURLs = /* @__PURE__ */ new Set();\n _WebSocket;\n constructor(opts) {\n this.verifyEvent = opts.verifyEvent;\n this._WebSocket = opts.websocketImplementation;\n }\n async ensureRelay(url, params) {\n url = normalizeURL(url);\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 });\n relay.onclose = () => {\n this.relays.delete(url);\n };\n if (params?.connectionTimeout)\n relay.connectionTimeout = params.connectionTimeout;\n this.relays.set(url, relay);\n }\n await relay.connect();\n return relay;\n }\n close(relays) {\n relays.map(normalizeURL).forEach((url) => {\n this.relays.get(url)?.close();\n this.relays.delete(url);\n });\n }\n subscribe(relays, filter, params) {\n params.onauth = params.onauth || params.doauth;\n return this.subscribeMap(\n relays.map((url) => ({ url, filter })),\n params\n );\n }\n subscribeMany(relays, filters, params) {\n params.onauth = params.onauth || params.doauth;\n return this.subscribeMap(\n relays.flatMap((url) => filters.map((filter) => ({ url, filter }))),\n params\n );\n }\n subscribeMap(requests, params) {\n params.onauth = params.onauth || params.doauth;\n if (this.trackRelays) {\n params.receivedEvent = (relay, id) => {\n let set = this.seenOn.get(id);\n if (!set) {\n set = /* @__PURE__ */ new Set();\n this.seenOn.set(id, set);\n }\n set.add(relay);\n };\n }\n const _knownIds = /* @__PURE__ */ new Set();\n const subs = [];\n const eosesReceived = [];\n let handleEose = (i2) => {\n if (eosesReceived[i2])\n return;\n eosesReceived[i2] = true;\n if (eosesReceived.filter((a) => a).length === requests.length) {\n params.oneose?.();\n handleEose = () => {\n };\n }\n };\n const closesReceived = [];\n let handleClose = (i2, reason) => {\n if (closesReceived[i2])\n return;\n handleEose(i2);\n closesReceived[i2] = reason;\n if (closesReceived.filter((a) => a).length === requests.length) {\n params.onclose?.(closesReceived);\n handleClose = () => {\n };\n }\n };\n const localAlreadyHaveEventHandler = (id) => {\n if (params.alreadyHaveEvent?.(id)) {\n return true;\n }\n const have = _knownIds.has(id);\n _knownIds.add(id);\n return have;\n };\n const allOpened = Promise.all(\n requests.map(async ({ url, filter }, i2) => {\n url = normalizeURL(url);\n let relay;\n try {\n relay = await this.ensureRelay(url, {\n connectionTimeout: params.maxWait ? Math.max(params.maxWait * 0.8, params.maxWait - 1e3) : void 0\n });\n } catch (err) {\n handleClose(i2, err?.message || String(err));\n return;\n }\n let subscription = relay.subscribe([filter], {\n ...params,\n oneose: () => handleEose(i2),\n onclose: (reason) => {\n if (reason.startsWith(\"auth-required: \") && params.onauth) {\n relay.auth(params.onauth).then(() => {\n relay.subscribe([filter], {\n ...params,\n oneose: () => handleEose(i2),\n onclose: (reason2) => {\n handleClose(i2, reason2);\n },\n alreadyHaveEvent: localAlreadyHaveEventHandler,\n eoseTimeout: params.maxWait\n });\n }).catch((err) => {\n handleClose(i2, `auth was required and attempted, but failed with: ${err}`);\n });\n } else {\n handleClose(i2, reason);\n }\n },\n alreadyHaveEvent: localAlreadyHaveEventHandler,\n eoseTimeout: params.maxWait\n });\n subs.push(subscription);\n })\n );\n return {\n async close(reason) {\n await allOpened;\n subs.forEach((sub) => {\n sub.close(reason);\n });\n }\n };\n }\n subscribeEose(relays, filter, params) {\n params.onauth = params.onauth || params.doauth;\n const subcloser = this.subscribe(relays, filter, {\n ...params,\n oneose() {\n subcloser.close(\"closed automatically on eose\");\n }\n });\n return subcloser;\n }\n subscribeManyEose(relays, filters, params) {\n params.onauth = params.onauth || params.doauth;\n const subcloser = this.subscribeMany(relays, filters, {\n ...params,\n oneose() {\n subcloser.close(\"closed automatically on eose\");\n }\n });\n return subcloser;\n }\n async querySync(relays, filter, params) {\n return new Promise(async (resolve) => {\n const events = [];\n this.subscribeEose(relays, filter, {\n ...params,\n onevent(event) {\n events.push(event);\n },\n onclose(_) {\n resolve(events);\n }\n });\n });\n }\n async get(relays, filter, params) {\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 publish(relays, event, options) {\n return relays.map(normalizeURL).map(async (url, i2, arr) => {\n if (arr.indexOf(url) !== i2) {\n return Promise.reject(\"duplicate url\");\n }\n let r = await this.ensureRelay(url);\n return r.publish(event).catch(async (err) => {\n if (err instanceof Error && err.message.startsWith(\"auth-required: \") && options?.onauth) {\n await r.auth(options.onauth);\n return r.publish(event);\n }\n throw err;\n }).then((reason) => {\n if (this.trackRelays) {\n let set = this.seenOn.get(event.id);\n if (!set) {\n set = /* @__PURE__ */ new Set();\n this.seenOn.set(event.id, set);\n }\n set.add(r);\n }\n return reason;\n });\n });\n }\n listConnectionStatus() {\n const map = /* @__PURE__ */ new Map();\n this.relays.forEach((relay, url) => map.set(url, relay.connected));\n return map;\n }\n destroy() {\n this.relays.forEach((conn) => conn.close());\n this.relays = /* @__PURE__ */ new Map();\n }\n};\n\n// pool.ts\nvar _WebSocket2;\ntry {\n _WebSocket2 = WebSocket;\n} catch {\n}\nvar SimplePool = class extends AbstractSimplePool {\n constructor() {\n super({ verifyEvent, websocketImplementation: _WebSocket2 });\n }\n};\n\n// nip19.ts\nvar nip19_exports = {};\n__export(nip19_exports, {\n BECH32_REGEX: () => BECH32_REGEX,\n Bech32MaxSize: () => Bech32MaxSize,\n NostrTypeGuard: () => NostrTypeGuard,\n decode: () => decode,\n decodeNostrURI: () => decodeNostrURI,\n encodeBytes: () => encodeBytes,\n naddrEncode: () => naddrEncode,\n neventEncode: () => neventEncode,\n noteEncode: () => noteEncode,\n nprofileEncode: () => nprofileEncode,\n npubEncode: () => npubEncode,\n nsecEncode: () => nsecEncode\n});\nimport { bytesToHex as bytesToHex3, concatBytes, hexToBytes as hexToBytes2 } from \"@noble/hashes/utils\";\nimport { bech32 } from \"@scure/base\";\nvar NostrTypeGuard = {\n isNProfile: (value) => /^nprofile1[a-z\\d]+$/.test(value || \"\"),\n isNEvent: (value) => /^nevent1[a-z\\d]+$/.test(value || \"\"),\n isNAddr: (value) => /^naddr1[a-z\\d]+$/.test(value || \"\"),\n isNSec: (value) => /^nsec1[a-z\\d]{58}$/.test(value || \"\"),\n isNPub: (value) => /^npub1[a-z\\d]{58}$/.test(value || \"\"),\n isNote: (value) => /^note1[a-z\\d]+$/.test(value || \"\"),\n isNcryptsec: (value) => /^ncryptsec1[a-z\\d]+$/.test(value || \"\")\n};\nvar Bech32MaxSize = 5e3;\nvar BECH32_REGEX = /[\\x21-\\x7E]{1,83}1[023456789acdefghjklmnpqrstuvwxyz]{6,}/;\nfunction integerToUint8Array(number) {\n const uint8Array = new Uint8Array(4);\n uint8Array[0] = number >> 24 & 255;\n uint8Array[1] = number >> 16 & 255;\n uint8Array[2] = number >> 8 & 255;\n uint8Array[3] = number & 255;\n return uint8Array;\n}\nfunction decodeNostrURI(nip19code) {\n try {\n if (nip19code.startsWith(\"nostr:\"))\n nip19code = nip19code.substring(6);\n return decode(nip19code);\n } catch (_err) {\n return { type: \"invalid\", data: null };\n }\n}\nfunction decode(code) {\n let { prefix, words } = bech32.decode(code, Bech32MaxSize);\n let data = new Uint8Array(bech32.fromWords(words));\n switch (prefix) {\n case \"nprofile\": {\n let tlv = parseTLV(data);\n if (!tlv[0]?.[0])\n throw new Error(\"missing TLV 0 for nprofile\");\n if (tlv[0][0].length !== 32)\n throw new Error(\"TLV 0 should be 32 bytes\");\n return {\n type: \"nprofile\",\n data: {\n pubkey: bytesToHex3(tlv[0][0]),\n relays: tlv[1] ? tlv[1].map((d) => utf8Decoder.decode(d)) : []\n }\n };\n }\n case \"nevent\": {\n let tlv = parseTLV(data);\n if (!tlv[0]?.[0])\n throw new Error(\"missing TLV 0 for nevent\");\n if (tlv[0][0].length !== 32)\n throw new Error(\"TLV 0 should be 32 bytes\");\n if (tlv[2] && tlv[2][0].length !== 32)\n throw new Error(\"TLV 2 should be 32 bytes\");\n if (tlv[3] && tlv[3][0].length !== 4)\n throw new Error(\"TLV 3 should be 4 bytes\");\n return {\n type: \"nevent\",\n data: {\n id: bytesToHex3(tlv[0][0]),\n relays: tlv[1] ? tlv[1].map((d) => utf8Decoder.decode(d)) : [],\n author: tlv[2]?.[0] ? bytesToHex3(tlv[2][0]) : void 0,\n kind: tlv[3]?.[0] ? parseInt(bytesToHex3(tlv[3][0]), 16) : void 0\n }\n };\n }\n case \"naddr\": {\n let tlv = parseTLV(data);\n if (!tlv[0]?.[0])\n throw new Error(\"missing TLV 0 for naddr\");\n if (!tlv[2]?.[0])\n throw new Error(\"missing TLV 2 for naddr\");\n if (tlv[2][0].length !== 32)\n throw new Error(\"TLV 2 should be 32 bytes\");\n if (!tlv[3]?.[0])\n throw new Error(\"missing TLV 3 for naddr\");\n if (tlv[3][0].length !== 4)\n throw new Error(\"TLV 3 should be 4 bytes\");\n return {\n type: \"naddr\",\n data: {\n identifier: utf8Decoder.decode(tlv[0][0]),\n pubkey: bytesToHex3(tlv[2][0]),\n kind: parseInt(bytesToHex3(tlv[3][0]), 16),\n relays: tlv[1] ? tlv[1].map((d) => utf8Decoder.decode(d)) : []\n }\n };\n }\n case \"nsec\":\n return { type: prefix, data };\n case \"npub\":\n case \"note\":\n return { type: prefix, data: bytesToHex3(data) };\n default:\n throw new Error(`unknown prefix ${prefix}`);\n }\n}\nfunction parseTLV(data) {\n let result = {};\n let rest = data;\n while (rest.length > 0) {\n let t = rest[0];\n let l = rest[1];\n let v = rest.slice(2, 2 + l);\n rest = rest.slice(2 + l);\n if (v.length < l)\n throw new Error(`not enough data to read on TLV ${t}`);\n result[t] = result[t] || [];\n result[t].push(v);\n }\n return result;\n}\nfunction nsecEncode(key) {\n return encodeBytes(\"nsec\", key);\n}\nfunction npubEncode(hex) {\n return encodeBytes(\"npub\", hexToBytes2(hex));\n}\nfunction noteEncode(hex) {\n return encodeBytes(\"note\", hexToBytes2(hex));\n}\nfunction encodeBech32(prefix, data) {\n let words = bech32.toWords(data);\n return bech32.encode(prefix, words, Bech32MaxSize);\n}\nfunction encodeBytes(prefix, bytes) {\n return encodeBech32(prefix, bytes);\n}\nfunction nprofileEncode(profile) {\n let data = encodeTLV({\n 0: [hexToBytes2(profile.pubkey)],\n 1: (profile.relays || []).map((url) => utf8Encoder.encode(url))\n });\n return encodeBech32(\"nprofile\", data);\n}\nfunction neventEncode(event) {\n let kindArray;\n if (event.kind !== void 0) {\n kindArray = integerToUint8Array(event.kind);\n }\n let data = encodeTLV({\n 0: [hexToBytes2(event.id)],\n 1: (event.relays || []).map((url) => utf8Encoder.encode(url)),\n 2: event.author ? [hexToBytes2(event.author)] : [],\n 3: kindArray ? [new Uint8Array(kindArray)] : []\n });\n return encodeBech32(\"nevent\", data);\n}\nfunction naddrEncode(addr) {\n let kind = new ArrayBuffer(4);\n new DataView(kind).setUint32(0, addr.kind, false);\n let data = encodeTLV({\n 0: [utf8Encoder.encode(addr.identifier)],\n 1: (addr.relays || []).map((url) => utf8Encoder.encode(url)),\n 2: [hexToBytes2(addr.pubkey)],\n 3: [new Uint8Array(kind)]\n });\n return encodeBech32(\"naddr\", data);\n}\nfunction encodeTLV(tlv) {\n let entries = [];\n Object.entries(tlv).reverse().forEach(([t, vs]) => {\n vs.forEach((v) => {\n let entry = new Uint8Array(v.length + 2);\n entry.set([parseInt(t)], 0);\n entry.set([v.length], 1);\n entry.set(v, 2);\n entries.push(entry);\n });\n });\n return concatBytes(...entries);\n}\n\n// references.ts\nvar mentionRegex = /\\bnostr:((note|npub|naddr|nevent|nprofile)1\\w+)\\b|#\\[(\\d+)\\]/g;\nfunction parseReferences(evt) {\n let references = [];\n for (let ref of evt.content.matchAll(mentionRegex)) {\n if (ref[2]) {\n try {\n let { type, data } = decode(ref[1]);\n switch (type) {\n case \"npub\": {\n references.push({\n text: ref[0],\n profile: { pubkey: data, relays: [] }\n });\n break;\n }\n case \"nprofile\": {\n references.push({\n text: ref[0],\n profile: data\n });\n break;\n }\n case \"note\": {\n references.push({\n text: ref[0],\n event: { id: data, relays: [] }\n });\n break;\n }\n case \"nevent\": {\n references.push({\n text: ref[0],\n event: data\n });\n break;\n }\n case \"naddr\": {\n references.push({\n text: ref[0],\n address: data\n });\n break;\n }\n }\n } catch (err) {\n }\n } else if (ref[3]) {\n let idx = parseInt(ref[3], 10);\n let tag = evt.tags[idx];\n if (!tag)\n continue;\n switch (tag[0]) {\n case \"p\": {\n references.push({\n text: ref[0],\n profile: { pubkey: tag[1], relays: tag[2] ? [tag[2]] : [] }\n });\n break;\n }\n case \"e\": {\n references.push({\n text: ref[0],\n event: { id: tag[1], relays: tag[2] ? [tag[2]] : [] }\n });\n break;\n }\n case \"a\": {\n try {\n let [kind, pubkey, identifier] = tag[1].split(\":\");\n references.push({\n text: ref[0],\n address: {\n identifier,\n pubkey,\n kind: parseInt(kind, 10),\n relays: tag[2] ? [tag[2]] : []\n }\n });\n } catch (err) {\n }\n break;\n }\n }\n }\n }\n return references;\n}\n\n// nip04.ts\nvar nip04_exports = {};\n__export(nip04_exports, {\n decrypt: () => decrypt,\n encrypt: () => encrypt\n});\nimport { bytesToHex as bytesToHex4, randomBytes } from \"@noble/hashes/utils\";\nimport { secp256k1 } from \"@noble/curves/secp256k1\";\nimport { cbc } from \"@noble/ciphers/aes\";\nimport { base64 } from \"@scure/base\";\nfunction encrypt(secretKey, pubkey, text) {\n const privkey = secretKey instanceof Uint8Array ? bytesToHex4(secretKey) : secretKey;\n const key = secp256k1.getSharedSecret(privkey, \"02\" + pubkey);\n const normalizedKey = getNormalizedX(key);\n let iv = Uint8Array.from(randomBytes(16));\n let plaintext = utf8Encoder.encode(text);\n let ciphertext = cbc(normalizedKey, iv).encrypt(plaintext);\n let ctb64 = base64.encode(new Uint8Array(ciphertext));\n let ivb64 = base64.encode(new Uint8Array(iv.buffer));\n return `${ctb64}?iv=${ivb64}`;\n}\nfunction decrypt(secretKey, pubkey, data) {\n const privkey = secretKey instanceof Uint8Array ? bytesToHex4(secretKey) : secretKey;\n let [ctb64, ivb64] = data.split(\"?iv=\");\n let key = secp256k1.getSharedSecret(privkey, \"02\" + pubkey);\n let normalizedKey = getNormalizedX(key);\n let iv = base64.decode(ivb64);\n let ciphertext = base64.decode(ctb64);\n let plaintext = cbc(normalizedKey, iv).decrypt(ciphertext);\n return utf8Decoder.decode(plaintext);\n}\nfunction getNormalizedX(key) {\n return key.slice(1, 33);\n}\n\n// nip05.ts\nvar nip05_exports = {};\n__export(nip05_exports, {\n NIP05_REGEX: () => NIP05_REGEX,\n isNip05: () => isNip05,\n isValid: () => isValid,\n queryProfile: () => queryProfile,\n searchDomain: () => searchDomain,\n useFetchImplementation: () => useFetchImplementation\n});\nvar NIP05_REGEX = /^(?:([\\w.+-]+)@)?([\\w_-]+(\\.[\\w_-]+)+)$/;\nvar isNip05 = (value) => NIP05_REGEX.test(value || \"\");\nvar _fetch;\ntry {\n _fetch = fetch;\n} catch (_) {\n null;\n}\nfunction useFetchImplementation(fetchImplementation) {\n _fetch = fetchImplementation;\n}\nasync function searchDomain(domain, query = \"\") {\n try {\n const url = `https://${domain}/.well-known/nostr.json?name=${query}`;\n const res = await _fetch(url, { redirect: \"manual\" });\n if (res.status !== 200) {\n throw Error(\"Wrong response code\");\n }\n const json = await res.json();\n return json.names;\n } catch (_) {\n return {};\n }\n}\nasync function queryProfile(fullname) {\n const match = fullname.match(NIP05_REGEX);\n if (!match)\n return null;\n const [, name = \"_\", domain] = match;\n try {\n const url = `https://${domain}/.well-known/nostr.json?name=${name}`;\n const res = await _fetch(url, { redirect: \"manual\" });\n if (res.status !== 200) {\n throw Error(\"Wrong response code\");\n }\n const json = await res.json();\n const pubkey = json.names[name];\n return pubkey ? { pubkey, relays: json.relays?.[pubkey] } : null;\n } catch (_e) {\n return null;\n }\n}\nasync function isValid(pubkey, nip05) {\n const res = await queryProfile(nip05);\n return res ? res.pubkey === pubkey : false;\n}\n\n// nip10.ts\nvar nip10_exports = {};\n__export(nip10_exports, {\n parse: () => parse\n});\nfunction parse(event) {\n const result = {\n reply: void 0,\n root: void 0,\n mentions: [],\n profiles: [],\n quotes: []\n };\n let maybeParent;\n let maybeRoot;\n for (let i2 = event.tags.length - 1; i2 >= 0; i2--) {\n const tag = event.tags[i2];\n if (tag[0] === \"e\" && tag[1]) {\n const [_, eTagEventId, eTagRelayUrl, eTagMarker, eTagAuthor] = tag;\n const eventPointer = {\n id: eTagEventId,\n relays: eTagRelayUrl ? [eTagRelayUrl] : [],\n author: eTagAuthor\n };\n if (eTagMarker === \"root\") {\n result.root = eventPointer;\n continue;\n }\n if (eTagMarker === \"reply\") {\n result.reply = eventPointer;\n continue;\n }\n if (eTagMarker === \"mention\") {\n result.mentions.push(eventPointer);\n continue;\n }\n if (!maybeParent) {\n maybeParent = eventPointer;\n } else {\n maybeRoot = eventPointer;\n }\n result.mentions.push(eventPointer);\n continue;\n }\n if (tag[0] === \"q\" && tag[1]) {\n const [_, eTagEventId, eTagRelayUrl] = tag;\n result.quotes.push({\n id: eTagEventId,\n relays: eTagRelayUrl ? [eTagRelayUrl] : []\n });\n }\n if (tag[0] === \"p\" && tag[1]) {\n result.profiles.push({\n pubkey: tag[1],\n relays: tag[2] ? [tag[2]] : []\n });\n continue;\n }\n }\n if (!result.root) {\n result.root = maybeRoot || maybeParent || result.reply;\n }\n if (!result.reply) {\n result.reply = maybeParent || result.root;\n }\n ;\n [result.reply, result.root].forEach((ref) => {\n if (!ref)\n return;\n let idx = result.mentions.indexOf(ref);\n if (idx !== -1) {\n result.mentions.splice(idx, 1);\n }\n if (ref.author) {\n let author = result.profiles.find((p) => p.pubkey === ref.author);\n if (author && author.relays) {\n if (!ref.relays) {\n ref.relays = [];\n }\n author.relays.forEach((url) => {\n if (ref.relays?.indexOf(url) === -1)\n ref.relays.push(url);\n });\n author.relays = ref.relays;\n }\n }\n });\n result.mentions.forEach((ref) => {\n if (ref.author) {\n let author = result.profiles.find((p) => p.pubkey === ref.author);\n if (author && author.relays) {\n if (!ref.relays) {\n ref.relays = [];\n }\n author.relays.forEach((url) => {\n if (ref.relays.indexOf(url) === -1)\n ref.relays.push(url);\n });\n author.relays = ref.relays;\n }\n }\n });\n return result;\n}\n\n// nip11.ts\nvar nip11_exports = {};\n__export(nip11_exports, {\n fetchRelayInformation: () => fetchRelayInformation,\n useFetchImplementation: () => useFetchImplementation2\n});\nvar _fetch2;\ntry {\n _fetch2 = fetch;\n} catch {\n}\nfunction useFetchImplementation2(fetchImplementation) {\n _fetch2 = fetchImplementation;\n}\nasync function fetchRelayInformation(url) {\n return await (await fetch(url.replace(\"ws://\", \"http://\").replace(\"wss://\", \"https://\"), {\n headers: { Accept: \"application/nostr+json\" }\n })).json();\n}\n\n// nip13.ts\nvar nip13_exports = {};\n__export(nip13_exports, {\n fastEventHash: () => fastEventHash,\n getPow: () => getPow,\n minePow: () => minePow\n});\nimport { bytesToHex as bytesToHex5 } from \"@noble/hashes/utils\";\nimport { sha256 as sha2562 } from \"@noble/hashes/sha256\";\nfunction getPow(hex) {\n let count = 0;\n for (let i2 = 0; i2 < 64; i2 += 8) {\n const nibble = parseInt(hex.substring(i2, i2 + 8), 16);\n if (nibble === 0) {\n count += 32;\n } else {\n count += Math.clz32(nibble);\n break;\n }\n }\n return count;\n}\nfunction minePow(unsigned, difficulty) {\n let count = 0;\n const event = unsigned;\n const tag = [\"nonce\", count.toString(), difficulty.toString()];\n event.tags.push(tag);\n while (true) {\n const now2 = Math.floor(new Date().getTime() / 1e3);\n if (now2 !== event.created_at) {\n count = 0;\n event.created_at = now2;\n }\n tag[1] = (++count).toString();\n event.id = fastEventHash(event);\n if (getPow(event.id) >= difficulty) {\n break;\n }\n }\n return event;\n}\nfunction fastEventHash(evt) {\n return bytesToHex5(\n sha2562(utf8Encoder.encode(JSON.stringify([0, evt.pubkey, evt.created_at, evt.kind, evt.tags, evt.content])))\n );\n}\n\n// nip17.ts\nvar nip17_exports = {};\n__export(nip17_exports, {\n unwrapEvent: () => unwrapEvent2,\n unwrapManyEvents: () => unwrapManyEvents2,\n wrapEvent: () => wrapEvent2,\n wrapManyEvents: () => wrapManyEvents2\n});\n\n// nip59.ts\nvar nip59_exports = {};\n__export(nip59_exports, {\n createRumor: () => createRumor,\n createSeal: () => createSeal,\n createWrap: () => createWrap,\n unwrapEvent: () => unwrapEvent,\n unwrapManyEvents: () => unwrapManyEvents,\n wrapEvent: () => wrapEvent,\n wrapManyEvents: () => wrapManyEvents\n});\n\n// nip44.ts\nvar nip44_exports = {};\n__export(nip44_exports, {\n decrypt: () => decrypt2,\n encrypt: () => encrypt2,\n getConversationKey: () => getConversationKey,\n v2: () => v2\n});\nimport { chacha20 } from \"@noble/ciphers/chacha\";\nimport { equalBytes } from \"@noble/ciphers/utils\";\nimport { secp256k1 as secp256k12 } from \"@noble/curves/secp256k1\";\nimport { extract as hkdf_extract, expand as hkdf_expand } from \"@noble/hashes/hkdf\";\nimport { hmac } from \"@noble/hashes/hmac\";\nimport { sha256 as sha2563 } from \"@noble/hashes/sha256\";\nimport { concatBytes as concatBytes2, randomBytes as randomBytes2 } from \"@noble/hashes/utils\";\nimport { base64 as base642 } from \"@scure/base\";\nvar minPlaintextSize = 1;\nvar maxPlaintextSize = 65535;\nfunction getConversationKey(privkeyA, pubkeyB) {\n const sharedX = secp256k12.getSharedSecret(privkeyA, \"02\" + pubkeyB).subarray(1, 33);\n return hkdf_extract(sha2563, sharedX, \"nip44-v2\");\n}\nfunction getMessageKeys(conversationKey, nonce) {\n const keys = hkdf_expand(sha2563, conversationKey, nonce, 76);\n return {\n chacha_key: keys.subarray(0, 32),\n chacha_nonce: keys.subarray(32, 44),\n hmac_key: keys.subarray(44, 76)\n };\n}\nfunction calcPaddedLen(len) {\n if (!Number.isSafeInteger(len) || len < 1)\n throw new Error(\"expected positive integer\");\n if (len <= 32)\n return 32;\n const nextPower = 1 << Math.floor(Math.log2(len - 1)) + 1;\n const chunk = nextPower <= 256 ? 32 : nextPower / 8;\n return chunk * (Math.floor((len - 1) / chunk) + 1);\n}\nfunction writeU16BE(num) {\n if (!Number.isSafeInteger(num) || num < minPlaintextSize || num > maxPlaintextSize)\n throw new Error(\"invalid plaintext size: must be between 1 and 65535 bytes\");\n const arr = new Uint8Array(2);\n new DataView(arr.buffer).setUint16(0, num, false);\n return arr;\n}\nfunction pad(plaintext) {\n const unpadded = utf8Encoder.encode(plaintext);\n const unpaddedLen = unpadded.length;\n const prefix = writeU16BE(unpaddedLen);\n const suffix = new Uint8Array(calcPaddedLen(unpaddedLen) - unpaddedLen);\n return concatBytes2(prefix, unpadded, suffix);\n}\nfunction unpad(padded) {\n const unpaddedLen = new DataView(padded.buffer).getUint16(0);\n const unpadded = padded.subarray(2, 2 + unpaddedLen);\n if (unpaddedLen < minPlaintextSize || unpaddedLen > maxPlaintextSize || unpadded.length !== unpaddedLen || padded.length !== 2 + calcPaddedLen(unpaddedLen))\n throw new Error(\"invalid padding\");\n return utf8Decoder.decode(unpadded);\n}\nfunction hmacAad(key, message, aad) {\n if (aad.length !== 32)\n throw new Error(\"AAD associated data must be 32 bytes\");\n const combined = concatBytes2(aad, message);\n return hmac(sha2563, key, combined);\n}\nfunction decodePayload(payload) {\n if (typeof payload !== \"string\")\n throw new Error(\"payload must be a valid string\");\n const plen = payload.length;\n if (plen < 132 || plen > 87472)\n throw new Error(\"invalid payload length: \" + plen);\n if (payload[0] === \"#\")\n throw new Error(\"unknown encryption version\");\n let data;\n try {\n data = base642.decode(payload);\n } catch (error) {\n throw new Error(\"invalid base64: \" + error.message);\n }\n const dlen = data.length;\n if (dlen < 99 || dlen > 65603)\n throw new Error(\"invalid data length: \" + dlen);\n const vers = data[0];\n if (vers !== 2)\n throw new Error(\"unknown encryption version \" + vers);\n return {\n nonce: data.subarray(1, 33),\n ciphertext: data.subarray(33, -32),\n mac: data.subarray(-32)\n };\n}\nfunction encrypt2(plaintext, conversationKey, nonce = randomBytes2(32)) {\n const { chacha_key, chacha_nonce, hmac_key } = getMessageKeys(conversationKey, nonce);\n const padded = pad(plaintext);\n const ciphertext = chacha20(chacha_key, chacha_nonce, padded);\n const mac = hmacAad(hmac_key, ciphertext, nonce);\n return base642.encode(concatBytes2(new Uint8Array([2]), nonce, ciphertext, mac));\n}\nfunction decrypt2(payload, conversationKey) {\n const { nonce, ciphertext, mac } = decodePayload(payload);\n const { chacha_key, chacha_nonce, hmac_key } = getMessageKeys(conversationKey, nonce);\n const calculatedMac = hmacAad(hmac_key, ciphertext, nonce);\n if (!equalBytes(calculatedMac, mac))\n throw new Error(\"invalid MAC\");\n const padded = chacha20(chacha_key, chacha_nonce, ciphertext);\n return unpad(padded);\n}\nvar v2 = {\n utils: {\n getConversationKey,\n calcPaddedLen\n },\n encrypt: encrypt2,\n decrypt: decrypt2\n};\n\n// nip59.ts\nvar TWO_DAYS = 2 * 24 * 60 * 60;\nvar now = () => Math.round(Date.now() / 1e3);\nvar randomNow = () => Math.round(now() - Math.random() * TWO_DAYS);\nvar nip44ConversationKey = (privateKey, publicKey) => getConversationKey(privateKey, publicKey);\nvar nip44Encrypt = (data, privateKey, publicKey) => encrypt2(JSON.stringify(data), nip44ConversationKey(privateKey, publicKey));\nvar nip44Decrypt = (data, privateKey) => JSON.parse(decrypt2(data.content, nip44ConversationKey(privateKey, data.pubkey)));\nfunction createRumor(event, privateKey) {\n const rumor = {\n created_at: now(),\n content: \"\",\n tags: [],\n ...event,\n pubkey: getPublicKey(privateKey)\n };\n rumor.id = getEventHash(rumor);\n return rumor;\n}\nfunction createSeal(rumor, privateKey, recipientPublicKey) {\n return finalizeEvent(\n {\n kind: Seal,\n content: nip44Encrypt(rumor, privateKey, recipientPublicKey),\n created_at: randomNow(),\n tags: []\n },\n privateKey\n );\n}\nfunction createWrap(seal, recipientPublicKey) {\n const randomKey = generateSecretKey();\n return finalizeEvent(\n {\n kind: GiftWrap,\n content: nip44Encrypt(seal, randomKey, recipientPublicKey),\n created_at: randomNow(),\n tags: [[\"p\", recipientPublicKey]]\n },\n randomKey\n );\n}\nfunction wrapEvent(event, senderPrivateKey, recipientPublicKey) {\n const rumor = createRumor(event, senderPrivateKey);\n const seal = createSeal(rumor, senderPrivateKey, recipientPublicKey);\n return createWrap(seal, recipientPublicKey);\n}\nfunction wrapManyEvents(event, senderPrivateKey, recipientsPublicKeys) {\n if (!recipientsPublicKeys || recipientsPublicKeys.length === 0) {\n throw new Error(\"At least one recipient is required.\");\n }\n const senderPublicKey = getPublicKey(senderPrivateKey);\n const wrappeds = [wrapEvent(event, senderPrivateKey, senderPublicKey)];\n recipientsPublicKeys.forEach((recipientPublicKey) => {\n wrappeds.push(wrapEvent(event, senderPrivateKey, recipientPublicKey));\n });\n return wrappeds;\n}\nfunction unwrapEvent(wrap, recipientPrivateKey) {\n const unwrappedSeal = nip44Decrypt(wrap, recipientPrivateKey);\n return nip44Decrypt(unwrappedSeal, recipientPrivateKey);\n}\nfunction unwrapManyEvents(wrappedEvents, recipientPrivateKey) {\n let unwrappedEvents = [];\n wrappedEvents.forEach((e) => {\n unwrappedEvents.push(unwrapEvent(e, recipientPrivateKey));\n });\n unwrappedEvents.sort((a, b) => a.created_at - b.created_at);\n return unwrappedEvents;\n}\n\n// nip17.ts\nfunction createEvent(recipients, message, conversationTitle, replyTo) {\n const baseEvent = {\n created_at: Math.ceil(Date.now() / 1e3),\n kind: PrivateDirectMessage,\n tags: [],\n content: message\n };\n const recipientsArray = Array.isArray(recipients) ? recipients : [recipients];\n recipientsArray.forEach(({ publicKey, relayUrl }) => {\n baseEvent.tags.push(relayUrl ? [\"p\", publicKey, relayUrl] : [\"p\", publicKey]);\n });\n if (replyTo) {\n baseEvent.tags.push([\"e\", replyTo.eventId, replyTo.relayUrl || \"\", \"reply\"]);\n }\n if (conversationTitle) {\n baseEvent.tags.push([\"subject\", conversationTitle]);\n }\n return baseEvent;\n}\nfunction wrapEvent2(senderPrivateKey, recipient, message, conversationTitle, replyTo) {\n const event = createEvent(recipient, message, conversationTitle, replyTo);\n return wrapEvent(event, senderPrivateKey, recipient.publicKey);\n}\nfunction wrapManyEvents2(senderPrivateKey, recipients, message, conversationTitle, replyTo) {\n if (!recipients || recipients.length === 0) {\n throw new Error(\"At least one recipient is required.\");\n }\n const senderPublicKey = getPublicKey(senderPrivateKey);\n return [{ publicKey: senderPublicKey }, ...recipients].map(\n (recipient) => wrapEvent2(senderPrivateKey, recipient, message, conversationTitle, replyTo)\n );\n}\nvar unwrapEvent2 = unwrapEvent;\nvar unwrapManyEvents2 = unwrapManyEvents;\n\n// nip18.ts\nvar nip18_exports = {};\n__export(nip18_exports, {\n finishRepostEvent: () => finishRepostEvent,\n getRepostedEvent: () => getRepostedEvent,\n getRepostedEventPointer: () => getRepostedEventPointer\n});\nfunction finishRepostEvent(t, reposted, relayUrl, privateKey) {\n let kind;\n const tags = [...t.tags ?? [], [\"e\", reposted.id, relayUrl], [\"p\", reposted.pubkey]];\n if (reposted.kind === ShortTextNote) {\n kind = Repost;\n } else {\n kind = GenericRepost;\n tags.push([\"k\", String(reposted.kind)]);\n }\n return finalizeEvent(\n {\n kind,\n tags,\n content: t.content === \"\" || reposted.tags?.find((tag) => tag[0] === \"-\") ? \"\" : JSON.stringify(reposted),\n created_at: t.created_at\n },\n privateKey\n );\n}\nfunction getRepostedEventPointer(event) {\n if (![Repost, GenericRepost].includes(event.kind)) {\n return void 0;\n }\n let lastETag;\n let lastPTag;\n for (let i2 = event.tags.length - 1; i2 >= 0 && (lastETag === void 0 || lastPTag === void 0); i2--) {\n const tag = event.tags[i2];\n if (tag.length >= 2) {\n if (tag[0] === \"e\" && lastETag === void 0) {\n lastETag = tag;\n } else if (tag[0] === \"p\" && lastPTag === void 0) {\n lastPTag = tag;\n }\n }\n }\n if (lastETag === void 0) {\n return void 0;\n }\n return {\n id: lastETag[1],\n relays: [lastETag[2], lastPTag?.[2]].filter((x) => typeof x === \"string\"),\n author: lastPTag?.[1]\n };\n}\nfunction getRepostedEvent(event, { skipVerification } = {}) {\n const pointer = getRepostedEventPointer(event);\n if (pointer === void 0 || event.content === \"\") {\n return void 0;\n }\n let repostedEvent;\n try {\n repostedEvent = JSON.parse(event.content);\n } catch (error) {\n return void 0;\n }\n if (repostedEvent.id !== pointer.id) {\n return void 0;\n }\n if (!skipVerification && !verifyEvent(repostedEvent)) {\n return void 0;\n }\n return repostedEvent;\n}\n\n// nip21.ts\nvar nip21_exports = {};\n__export(nip21_exports, {\n NOSTR_URI_REGEX: () => NOSTR_URI_REGEX,\n parse: () => parse2,\n test: () => test\n});\nvar NOSTR_URI_REGEX = new RegExp(`nostr:(${BECH32_REGEX.source})`);\nfunction test(value) {\n return typeof value === \"string\" && new RegExp(`^${NOSTR_URI_REGEX.source}$`).test(value);\n}\nfunction parse2(uri) {\n const match = uri.match(new RegExp(`^${NOSTR_URI_REGEX.source}$`));\n if (!match)\n throw new Error(`Invalid Nostr URI: ${uri}`);\n return {\n uri: match[0],\n value: match[1],\n decoded: decode(match[1])\n };\n}\n\n// nip25.ts\nvar nip25_exports = {};\n__export(nip25_exports, {\n finishReactionEvent: () => finishReactionEvent,\n getReactedEventPointer: () => getReactedEventPointer\n});\nfunction finishReactionEvent(t, reacted, privateKey) {\n const inheritedTags = reacted.tags.filter((tag) => tag.length >= 2 && (tag[0] === \"e\" || tag[0] === \"p\"));\n return finalizeEvent(\n {\n ...t,\n kind: Reaction,\n tags: [...t.tags ?? [], ...inheritedTags, [\"e\", reacted.id], [\"p\", reacted.pubkey]],\n content: t.content ?? \"+\"\n },\n privateKey\n );\n}\nfunction getReactedEventPointer(event) {\n if (event.kind !== Reaction) {\n return void 0;\n }\n let lastETag;\n let lastPTag;\n for (let i2 = event.tags.length - 1; i2 >= 0 && (lastETag === void 0 || lastPTag === void 0); i2--) {\n const tag = event.tags[i2];\n if (tag.length >= 2) {\n if (tag[0] === \"e\" && lastETag === void 0) {\n lastETag = tag;\n } else if (tag[0] === \"p\" && lastPTag === void 0) {\n lastPTag = tag;\n }\n }\n }\n if (lastETag === void 0 || lastPTag === void 0) {\n return void 0;\n }\n return {\n id: lastETag[1],\n relays: [lastETag[2], lastPTag[2]].filter((x) => x !== void 0),\n author: lastPTag[1]\n };\n}\n\n// nip27.ts\nvar nip27_exports = {};\n__export(nip27_exports, {\n parse: () => parse3\n});\nvar noCharacter = /\\W/m;\nvar noURLCharacter = /\\W |\\W$|$|,| /m;\nfunction* parse3(content) {\n const max = content.length;\n let prevIndex = 0;\n let index = 0;\n while (index < max) {\n let u = content.indexOf(\":\", index);\n if (u === -1) {\n break;\n }\n if (content.substring(u - 5, u) === \"nostr\") {\n const m = content.substring(u + 60).match(noCharacter);\n const end = m ? u + 60 + m.index : max;\n try {\n let pointer;\n let { data, type } = decode(content.substring(u + 1, end));\n switch (type) {\n case \"npub\":\n pointer = { pubkey: data };\n break;\n case \"nsec\":\n case \"note\":\n index = end + 1;\n continue;\n default:\n pointer = data;\n }\n if (prevIndex !== u - 5) {\n yield { type: \"text\", text: content.substring(prevIndex, u - 5) };\n }\n yield { type: \"reference\", pointer };\n index = end;\n prevIndex = index;\n continue;\n } catch (_err) {\n index = u + 1;\n continue;\n }\n } else if (content.substring(u - 5, u) === \"https\" || content.substring(u - 4, u) === \"http\") {\n const m = content.substring(u + 4).match(noURLCharacter);\n const end = m ? u + 4 + m.index : max;\n const prefixLen = content[u - 1] === \"s\" ? 5 : 4;\n try {\n let url = new URL(content.substring(u - prefixLen, end));\n if (url.hostname.indexOf(\".\") === -1) {\n throw new Error(\"invalid url\");\n }\n if (prevIndex !== u - prefixLen) {\n yield { type: \"text\", text: content.substring(prevIndex, u - prefixLen) };\n }\n if (url.pathname.endsWith(\".png\") || url.pathname.endsWith(\".jpg\") || url.pathname.endsWith(\".jpeg\") || url.pathname.endsWith(\".gif\") || url.pathname.endsWith(\".webp\")) {\n yield { type: \"image\", url: url.toString() };\n index = end;\n prevIndex = index;\n continue;\n }\n if (url.pathname.endsWith(\".mp4\") || url.pathname.endsWith(\".avi\") || url.pathname.endsWith(\".webm\") || url.pathname.endsWith(\".mkv\")) {\n yield { type: \"video\", url: url.toString() };\n index = end;\n prevIndex = index;\n continue;\n }\n if (url.pathname.endsWith(\".mp3\") || url.pathname.endsWith(\".aac\") || url.pathname.endsWith(\".ogg\") || url.pathname.endsWith(\".opus\")) {\n yield { type: \"audio\", url: url.toString() };\n index = end;\n prevIndex = index;\n continue;\n }\n yield { type: \"url\", url: url.toString() };\n index = end;\n prevIndex = index;\n continue;\n } catch (_err) {\n index = end + 1;\n continue;\n }\n } else if (content.substring(u - 3, u) === \"wss\" || content.substring(u - 2, u) === \"ws\") {\n const m = content.substring(u + 4).match(noURLCharacter);\n const end = m ? u + 4 + m.index : max;\n const prefixLen = content[u - 1] === \"s\" ? 3 : 2;\n try {\n let url = new URL(content.substring(u - prefixLen, end));\n if (url.hostname.indexOf(\".\") === -1) {\n throw new Error(\"invalid ws url\");\n }\n if (prevIndex !== u - prefixLen) {\n yield { type: \"text\", text: content.substring(prevIndex, u - prefixLen) };\n }\n yield { type: \"relay\", url: url.toString() };\n index = end;\n prevIndex = index;\n continue;\n } catch (_err) {\n index = end + 1;\n continue;\n }\n } else {\n index = u + 1;\n continue;\n }\n }\n if (prevIndex !== max) {\n yield { type: \"text\", text: content.substring(prevIndex) };\n }\n}\n\n// nip28.ts\nvar nip28_exports = {};\n__export(nip28_exports, {\n channelCreateEvent: () => channelCreateEvent,\n channelHideMessageEvent: () => channelHideMessageEvent,\n channelMessageEvent: () => channelMessageEvent,\n channelMetadataEvent: () => channelMetadataEvent,\n channelMuteUserEvent: () => channelMuteUserEvent\n});\nvar channelCreateEvent = (t, privateKey) => {\n let content;\n if (typeof t.content === \"object\") {\n content = JSON.stringify(t.content);\n } else if (typeof t.content === \"string\") {\n content = t.content;\n } else {\n return void 0;\n }\n return finalizeEvent(\n {\n kind: ChannelCreation,\n tags: [...t.tags ?? []],\n content,\n created_at: t.created_at\n },\n privateKey\n );\n};\nvar channelMetadataEvent = (t, privateKey) => {\n let content;\n if (typeof t.content === \"object\") {\n content = JSON.stringify(t.content);\n } else if (typeof t.content === \"string\") {\n content = t.content;\n } else {\n return void 0;\n }\n return finalizeEvent(\n {\n kind: ChannelMetadata,\n tags: [[\"e\", t.channel_create_event_id], ...t.tags ?? []],\n content,\n created_at: t.created_at\n },\n privateKey\n );\n};\nvar channelMessageEvent = (t, privateKey) => {\n const tags = [[\"e\", t.channel_create_event_id, t.relay_url, \"root\"]];\n if (t.reply_to_channel_message_event_id) {\n tags.push([\"e\", t.reply_to_channel_message_event_id, t.relay_url, \"reply\"]);\n }\n return finalizeEvent(\n {\n kind: ChannelMessage,\n tags: [...tags, ...t.tags ?? []],\n content: t.content,\n created_at: t.created_at\n },\n privateKey\n );\n};\nvar channelHideMessageEvent = (t, privateKey) => {\n let content;\n if (typeof t.content === \"object\") {\n content = JSON.stringify(t.content);\n } else if (typeof t.content === \"string\") {\n content = t.content;\n } else {\n return void 0;\n }\n return finalizeEvent(\n {\n kind: ChannelHideMessage,\n tags: [[\"e\", t.channel_message_event_id], ...t.tags ?? []],\n content,\n created_at: t.created_at\n },\n privateKey\n );\n};\nvar channelMuteUserEvent = (t, privateKey) => {\n let content;\n if (typeof t.content === \"object\") {\n content = JSON.stringify(t.content);\n } else if (typeof t.content === \"string\") {\n content = t.content;\n } else {\n return void 0;\n }\n return finalizeEvent(\n {\n kind: ChannelMuteUser,\n tags: [[\"p\", t.pubkey_to_mute], ...t.tags ?? []],\n content,\n created_at: t.created_at\n },\n privateKey\n );\n};\n\n// nip30.ts\nvar nip30_exports = {};\n__export(nip30_exports, {\n EMOJI_SHORTCODE_REGEX: () => EMOJI_SHORTCODE_REGEX,\n matchAll: () => matchAll,\n regex: () => regex,\n replaceAll: () => replaceAll\n});\nvar EMOJI_SHORTCODE_REGEX = /:(\\w+):/;\nvar regex = () => new RegExp(`\\\\B${EMOJI_SHORTCODE_REGEX.source}\\\\B`, \"g\");\nfunction* matchAll(content) {\n const matches = content.matchAll(regex());\n for (const match of matches) {\n try {\n const [shortcode, name] = match;\n yield {\n shortcode,\n name,\n start: match.index,\n end: match.index + shortcode.length\n };\n } catch (_e) {\n }\n }\n}\nfunction replaceAll(content, replacer) {\n return content.replaceAll(regex(), (shortcode, name) => {\n return replacer({\n shortcode,\n name\n });\n });\n}\n\n// nip39.ts\nvar nip39_exports = {};\n__export(nip39_exports, {\n useFetchImplementation: () => useFetchImplementation3,\n validateGithub: () => validateGithub\n});\nvar _fetch3;\ntry {\n _fetch3 = fetch;\n} catch {\n}\nfunction useFetchImplementation3(fetchImplementation) {\n _fetch3 = fetchImplementation;\n}\nasync function validateGithub(pubkey, username, proof) {\n try {\n let res = await (await _fetch3(`https://gist.github.com/${username}/${proof}/raw`)).text();\n return res === `Verifying that I control the following Nostr public key: ${pubkey}`;\n } catch (_) {\n return false;\n }\n}\n\n// nip47.ts\nvar nip47_exports = {};\n__export(nip47_exports, {\n makeNwcRequestEvent: () => makeNwcRequestEvent,\n parseConnectionString: () => parseConnectionString\n});\nfunction parseConnectionString(connectionString) {\n const { host, pathname, searchParams } = new URL(connectionString);\n const pubkey = pathname || host;\n const relay = searchParams.get(\"relay\");\n const secret = searchParams.get(\"secret\");\n if (!pubkey || !relay || !secret) {\n throw new Error(\"invalid connection string\");\n }\n return { pubkey, relay, secret };\n}\nasync function makeNwcRequestEvent(pubkey, secretKey, invoice) {\n const content = {\n method: \"pay_invoice\",\n params: {\n invoice\n }\n };\n const encryptedContent = encrypt(secretKey, pubkey, JSON.stringify(content));\n const eventTemplate = {\n kind: NWCWalletRequest,\n created_at: Math.round(Date.now() / 1e3),\n content: encryptedContent,\n tags: [[\"p\", pubkey]]\n };\n return finalizeEvent(eventTemplate, secretKey);\n}\n\n// nip54.ts\nvar nip54_exports = {};\n__export(nip54_exports, {\n normalizeIdentifier: () => normalizeIdentifier\n});\nfunction normalizeIdentifier(name) {\n name = name.trim().toLowerCase();\n name = name.normalize(\"NFKC\");\n return Array.from(name).map((char) => {\n if (/\\p{Letter}/u.test(char) || /\\p{Number}/u.test(char)) {\n return char;\n }\n return \"-\";\n }).join(\"\");\n}\n\n// nip57.ts\nvar nip57_exports = {};\n__export(nip57_exports, {\n getSatoshisAmountFromBolt11: () => getSatoshisAmountFromBolt11,\n getZapEndpoint: () => getZapEndpoint,\n makeZapReceipt: () => makeZapReceipt,\n makeZapRequest: () => makeZapRequest,\n useFetchImplementation: () => useFetchImplementation4,\n validateZapRequest: () => validateZapRequest\n});\nimport { bech32 as bech322 } from \"@scure/base\";\nvar _fetch4;\ntry {\n _fetch4 = fetch;\n} catch {\n}\nfunction useFetchImplementation4(fetchImplementation) {\n _fetch4 = fetchImplementation;\n}\nasync function getZapEndpoint(metadata) {\n try {\n let lnurl = \"\";\n let { lud06, lud16 } = JSON.parse(metadata.content);\n if (lud06) {\n let { words } = bech322.decode(lud06, 1e3);\n let data = bech322.fromWords(words);\n lnurl = utf8Decoder.decode(data);\n } else if (lud16) {\n let [name, domain] = lud16.split(\"@\");\n lnurl = new URL(`/.well-known/lnurlp/${name}`, `https://${domain}`).toString();\n } else {\n return null;\n }\n let res = await _fetch4(lnurl);\n let body = await res.json();\n if (body.allowsNostr && body.nostrPubkey) {\n return body.callback;\n }\n } catch (err) {\n }\n return null;\n}\nfunction makeZapRequest({\n profile,\n event,\n amount,\n relays,\n comment = \"\"\n}) {\n if (!amount)\n throw new Error(\"amount not given\");\n if (!profile)\n throw new Error(\"profile not given\");\n let zr = {\n kind: 9734,\n created_at: Math.round(Date.now() / 1e3),\n content: comment,\n tags: [\n [\"p\", profile],\n [\"amount\", amount.toString()],\n [\"relays\", ...relays]\n ]\n };\n if (event && typeof event === \"string\") {\n zr.tags.push([\"e\", event]);\n }\n if (event && typeof event === \"object\") {\n if (isReplaceableKind(event.kind)) {\n const a = [\"a\", `${event.kind}:${event.pubkey}:`];\n zr.tags.push(a);\n } else if (isAddressableKind(event.kind)) {\n let d = event.tags.find(([t, v]) => t === \"d\" && v);\n if (!d)\n throw new Error(\"d tag not found or is empty\");\n const a = [\"a\", `${event.kind}:${event.pubkey}:${d[1]}`];\n zr.tags.push(a);\n }\n }\n return zr;\n}\nfunction validateZapRequest(zapRequestString) {\n let zapRequest;\n try {\n zapRequest = JSON.parse(zapRequestString);\n } catch (err) {\n return \"Invalid zap request JSON.\";\n }\n if (!validateEvent(zapRequest))\n return \"Zap request is not a valid Nostr event.\";\n if (!verifyEvent(zapRequest))\n return \"Invalid signature on zap request.\";\n let p = zapRequest.tags.find(([t, v]) => t === \"p\" && v);\n if (!p)\n return \"Zap request doesn't have a 'p' tag.\";\n if (!p[1].match(/^[a-f0-9]{64}$/))\n return \"Zap request 'p' tag is not valid hex.\";\n let e = zapRequest.tags.find(([t, v]) => t === \"e\" && v);\n if (e && !e[1].match(/^[a-f0-9]{64}$/))\n return \"Zap request 'e' tag is not valid hex.\";\n let relays = zapRequest.tags.find(([t, v]) => t === \"relays\" && v);\n if (!relays)\n return \"Zap request doesn't have a 'relays' tag.\";\n return null;\n}\nfunction makeZapReceipt({\n zapRequest,\n preimage,\n bolt11,\n paidAt\n}) {\n let zr = JSON.parse(zapRequest);\n let tagsFromZapRequest = zr.tags.filter(([t]) => t === \"e\" || t === \"p\" || t === \"a\");\n let zap = {\n kind: 9735,\n created_at: Math.round(paidAt.getTime() / 1e3),\n content: \"\",\n tags: [...tagsFromZapRequest, [\"P\", zr.pubkey], [\"bolt11\", bolt11], [\"description\", zapRequest]]\n };\n if (preimage) {\n zap.tags.push([\"preimage\", preimage]);\n }\n return zap;\n}\nfunction getSatoshisAmountFromBolt11(bolt11) {\n if (bolt11.length < 50) {\n return 0;\n }\n bolt11 = bolt11.substring(0, 50);\n const idx = bolt11.lastIndexOf(\"1\");\n if (idx === -1) {\n return 0;\n }\n const hrp = bolt11.substring(0, idx);\n if (!hrp.startsWith(\"lnbc\")) {\n return 0;\n }\n const amount = hrp.substring(4);\n if (amount.length < 1) {\n return 0;\n }\n const char = amount[amount.length - 1];\n const digit = char.charCodeAt(0) - \"0\".charCodeAt(0);\n const isDigit = digit >= 0 && digit <= 9;\n let cutPoint = amount.length - 1;\n if (isDigit) {\n cutPoint++;\n }\n if (cutPoint < 1) {\n return 0;\n }\n const num = parseInt(amount.substring(0, cutPoint));\n switch (char) {\n case \"m\":\n return num * 1e5;\n case \"u\":\n return num * 100;\n case \"n\":\n return num / 10;\n case \"p\":\n return num / 1e4;\n default:\n return num * 1e8;\n }\n}\n\n// nip98.ts\nvar nip98_exports = {};\n__export(nip98_exports, {\n getToken: () => getToken,\n hashPayload: () => hashPayload,\n unpackEventFromToken: () => unpackEventFromToken,\n validateEvent: () => validateEvent2,\n validateEventKind: () => validateEventKind,\n validateEventMethodTag: () => validateEventMethodTag,\n validateEventPayloadTag: () => validateEventPayloadTag,\n validateEventTimestamp: () => validateEventTimestamp,\n validateEventUrlTag: () => validateEventUrlTag,\n validateToken: () => validateToken\n});\nimport { sha256 as sha2564 } from \"@noble/hashes/sha256\";\nimport { bytesToHex as bytesToHex6 } from \"@noble/hashes/utils\";\nimport { base64 as base643 } from \"@scure/base\";\nvar _authorizationScheme = \"Nostr \";\nasync function getToken(loginUrl, httpMethod, sign, includeAuthorizationScheme = false, payload) {\n const event = {\n kind: HTTPAuth,\n tags: [\n [\"u\", loginUrl],\n [\"method\", httpMethod]\n ],\n created_at: Math.round(new Date().getTime() / 1e3),\n content: \"\"\n };\n if (payload) {\n event.tags.push([\"payload\", hashPayload(payload)]);\n }\n const signedEvent = await sign(event);\n const authorizationScheme = includeAuthorizationScheme ? _authorizationScheme : \"\";\n return authorizationScheme + base643.encode(utf8Encoder.encode(JSON.stringify(signedEvent)));\n}\nasync function validateToken(token, url, method) {\n const event = await unpackEventFromToken(token).catch((error) => {\n throw error;\n });\n const valid = await validateEvent2(event, url, method).catch((error) => {\n throw error;\n });\n return valid;\n}\nasync function unpackEventFromToken(token) {\n if (!token) {\n throw new Error(\"Missing token\");\n }\n token = token.replace(_authorizationScheme, \"\");\n const eventB64 = utf8Decoder.decode(base643.decode(token));\n if (!eventB64 || eventB64.length === 0 || !eventB64.startsWith(\"{\")) {\n throw new Error(\"Invalid token\");\n }\n const event = JSON.parse(eventB64);\n return event;\n}\nfunction validateEventTimestamp(event) {\n if (!event.created_at) {\n return false;\n }\n return Math.round(new Date().getTime() / 1e3) - event.created_at < 60;\n}\nfunction validateEventKind(event) {\n return event.kind === HTTPAuth;\n}\nfunction validateEventUrlTag(event, url) {\n const urlTag = event.tags.find((t) => t[0] === \"u\");\n if (!urlTag) {\n return false;\n }\n return urlTag.length > 0 && urlTag[1] === url;\n}\nfunction validateEventMethodTag(event, method) {\n const methodTag = event.tags.find((t) => t[0] === \"method\");\n if (!methodTag) {\n return false;\n }\n return methodTag.length > 0 && methodTag[1].toLowerCase() === method.toLowerCase();\n}\nfunction hashPayload(payload) {\n const hash = sha2564(utf8Encoder.encode(JSON.stringify(payload)));\n return bytesToHex6(hash);\n}\nfunction validateEventPayloadTag(event, payload) {\n const payloadTag = event.tags.find((t) => t[0] === \"payload\");\n if (!payloadTag) {\n return false;\n }\n const payloadHash = hashPayload(payload);\n return payloadTag.length > 0 && payloadTag[1] === payloadHash;\n}\nasync function validateEvent2(event, url, method, body) {\n if (!verifyEvent(event)) {\n throw new Error(\"Invalid nostr event, signature invalid\");\n }\n if (!validateEventKind(event)) {\n throw new Error(\"Invalid nostr event, kind invalid\");\n }\n if (!validateEventTimestamp(event)) {\n throw new Error(\"Invalid nostr event, created_at timestamp invalid\");\n }\n if (!validateEventUrlTag(event, url)) {\n throw new Error(\"Invalid nostr event, url tag invalid\");\n }\n if (!validateEventMethodTag(event, method)) {\n throw new Error(\"Invalid nostr event, method tag invalid\");\n }\n if (Boolean(body) && typeof body === \"object\" && Object.keys(body).length > 0) {\n if (!validateEventPayloadTag(event, body)) {\n throw new Error(\"Invalid nostr event, payload tag does not match request body hash\");\n }\n }\n return true;\n}\nexport {\n Relay,\n SimplePool,\n finalizeEvent,\n fakejson_exports as fj,\n generateSecretKey,\n getEventHash,\n getFilterLimit,\n getPublicKey,\n kinds_exports as kinds,\n matchFilter,\n matchFilters,\n mergeFilters,\n nip04_exports as nip04,\n nip05_exports as nip05,\n nip10_exports as nip10,\n nip11_exports as nip11,\n nip13_exports as nip13,\n nip17_exports as nip17,\n nip18_exports as nip18,\n nip19_exports as nip19,\n nip21_exports as nip21,\n nip25_exports as nip25,\n nip27_exports as nip27,\n nip28_exports as nip28,\n nip30_exports as nip30,\n nip39_exports as nip39,\n nip42_exports as nip42,\n nip44_exports as nip44,\n nip47_exports as nip47,\n nip54_exports as nip54,\n nip57_exports as nip57,\n nip59_exports as nip59,\n nip98_exports as nip98,\n parseReferences,\n serializeEvent,\n sortEvents,\n utils_exports as utils,\n validateEvent,\n verifiedSymbol,\n verifyEvent\n};\n", "// core.ts\nvar verifiedSymbol = Symbol(\"verified\");\nvar isRecord = (obj) => obj instanceof Object;\nfunction validateEvent(event) {\n if (!isRecord(event))\n return false;\n if (typeof event.kind !== \"number\")\n return false;\n if (typeof event.content !== \"string\")\n return false;\n if (typeof event.created_at !== \"number\")\n return false;\n if (typeof event.pubkey !== \"string\")\n return false;\n if (!event.pubkey.match(/^[a-f0-9]{64}$/))\n return false;\n if (!Array.isArray(event.tags))\n return false;\n for (let i = 0; i < event.tags.length; i++) {\n let tag = event.tags[i];\n if (!Array.isArray(tag))\n return false;\n for (let j = 0; j < tag.length; j++) {\n if (typeof tag[j] !== \"string\")\n return false;\n }\n }\n return true;\n}\n\n// kinds.ts\nfunction isRegularKind(kind) {\n return 1e3 <= kind && kind < 1e4 || [1, 2, 4, 5, 6, 7, 8, 16, 40, 41, 42, 43, 44].includes(kind);\n}\nfunction isReplaceableKind(kind) {\n return [0, 3].includes(kind) || 1e4 <= kind && kind < 2e4;\n}\nfunction isEphemeralKind(kind) {\n return 2e4 <= kind && kind < 3e4;\n}\nfunction isAddressableKind(kind) {\n return 3e4 <= kind && kind < 4e4;\n}\nfunction classifyKind(kind) {\n if (isRegularKind(kind))\n return \"regular\";\n if (isReplaceableKind(kind))\n return \"replaceable\";\n if (isEphemeralKind(kind))\n return \"ephemeral\";\n if (isAddressableKind(kind))\n return \"parameterized\";\n return \"unknown\";\n}\nfunction isKind(event, kind) {\n const kindAsArray = kind instanceof Array ? kind : [kind];\n return validateEvent(event) && kindAsArray.includes(event.kind) || false;\n}\nvar Metadata = 0;\nvar ShortTextNote = 1;\nvar RecommendRelay = 2;\nvar Contacts = 3;\nvar EncryptedDirectMessage = 4;\nvar EventDeletion = 5;\nvar Repost = 6;\nvar Reaction = 7;\nvar BadgeAward = 8;\nvar Seal = 13;\nvar PrivateDirectMessage = 14;\nvar GenericRepost = 16;\nvar ChannelCreation = 40;\nvar ChannelMetadata = 41;\nvar ChannelMessage = 42;\nvar ChannelHideMessage = 43;\nvar ChannelMuteUser = 44;\nvar OpenTimestamps = 1040;\nvar GiftWrap = 1059;\nvar FileMetadata = 1063;\nvar LiveChatMessage = 1311;\nvar ProblemTracker = 1971;\nvar Report = 1984;\nvar Reporting = 1984;\nvar Label = 1985;\nvar CommunityPostApproval = 4550;\nvar JobRequest = 5999;\nvar JobResult = 6999;\nvar JobFeedback = 7e3;\nvar ZapGoal = 9041;\nvar ZapRequest = 9734;\nvar Zap = 9735;\nvar Highlights = 9802;\nvar Mutelist = 1e4;\nvar Pinlist = 10001;\nvar RelayList = 10002;\nvar BookmarkList = 10003;\nvar CommunitiesList = 10004;\nvar PublicChatsList = 10005;\nvar BlockedRelaysList = 10006;\nvar SearchRelaysList = 10007;\nvar InterestsList = 10015;\nvar UserEmojiList = 10030;\nvar DirectMessageRelaysList = 10050;\nvar FileServerPreference = 10096;\nvar NWCWalletInfo = 13194;\nvar LightningPubRPC = 21e3;\nvar ClientAuth = 22242;\nvar NWCWalletRequest = 23194;\nvar NWCWalletResponse = 23195;\nvar NostrConnect = 24133;\nvar HTTPAuth = 27235;\nvar Followsets = 3e4;\nvar Genericlists = 30001;\nvar Relaysets = 30002;\nvar Bookmarksets = 30003;\nvar Curationsets = 30004;\nvar ProfileBadges = 30008;\nvar BadgeDefinition = 30009;\nvar Interestsets = 30015;\nvar CreateOrUpdateStall = 30017;\nvar CreateOrUpdateProduct = 30018;\nvar LongFormArticle = 30023;\nvar DraftLong = 30024;\nvar Emojisets = 30030;\nvar Application = 30078;\nvar LiveEvent = 30311;\nvar UserStatuses = 30315;\nvar ClassifiedListing = 30402;\nvar DraftClassifiedListing = 30403;\nvar Date = 31922;\nvar Time = 31923;\nvar Calendar = 31924;\nvar CalendarEventRSVP = 31925;\nvar Handlerrecommendation = 31989;\nvar Handlerinformation = 31990;\nvar CommunityDefinition = 34550;\nexport {\n Application,\n BadgeAward,\n BadgeDefinition,\n BlockedRelaysList,\n BookmarkList,\n Bookmarksets,\n Calendar,\n CalendarEventRSVP,\n ChannelCreation,\n ChannelHideMessage,\n ChannelMessage,\n ChannelMetadata,\n ChannelMuteUser,\n ClassifiedListing,\n ClientAuth,\n CommunitiesList,\n CommunityDefinition,\n CommunityPostApproval,\n Contacts,\n CreateOrUpdateProduct,\n CreateOrUpdateStall,\n Curationsets,\n Date,\n DirectMessageRelaysList,\n DraftClassifiedListing,\n DraftLong,\n Emojisets,\n EncryptedDirectMessage,\n EventDeletion,\n FileMetadata,\n FileServerPreference,\n Followsets,\n GenericRepost,\n Genericlists,\n GiftWrap,\n HTTPAuth,\n Handlerinformation,\n Handlerrecommendation,\n Highlights,\n InterestsList,\n Interestsets,\n JobFeedback,\n JobRequest,\n JobResult,\n Label,\n LightningPubRPC,\n LiveChatMessage,\n LiveEvent,\n LongFormArticle,\n Metadata,\n Mutelist,\n NWCWalletInfo,\n NWCWalletRequest,\n NWCWalletResponse,\n NostrConnect,\n OpenTimestamps,\n Pinlist,\n PrivateDirectMessage,\n ProblemTracker,\n ProfileBadges,\n PublicChatsList,\n Reaction,\n RecommendRelay,\n RelayList,\n Relaysets,\n Report,\n Reporting,\n Repost,\n Seal,\n SearchRelaysList,\n ShortTextNote,\n Time,\n UserEmojiList,\n UserStatuses,\n Zap,\n ZapGoal,\n ZapRequest,\n classifyKind,\n isAddressableKind,\n isEphemeralKind,\n isKind,\n isRegularKind,\n isReplaceableKind\n};\n", "/******************************************************************************\nCopyright (c) Microsoft Corporation.\n\nPermission to use, copy, modify, and/or distribute this software for any\npurpose with or without fee is hereby granted.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH\nREGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY\nAND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,\nINDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM\nLOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR\nOTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR\nPERFORMANCE OF THIS SOFTWARE.\n***************************************************************************** */\n/* global Reflect, Promise, SuppressedError, Symbol, Iterator */\n\nvar extendStatics = function(d, b) {\n extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };\n return extendStatics(d, b);\n};\n\nexport function __extends(d, b) {\n if (typeof b !== \"function\" && b !== null)\n throw new TypeError(\"Class extends value \" + String(b) + \" is not a constructor or null\");\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n}\n\nexport var __assign = function() {\n __assign = Object.assign || function __assign(t) {\n for (var s, i = 1, n = arguments.length; i < n; i++) {\n s = arguments[i];\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];\n }\n return t;\n }\n return __assign.apply(this, arguments);\n}\n\nexport function __rest(s, e) {\n var t = {};\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\n t[p] = s[p];\n if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\n for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {\n if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))\n t[p[i]] = s[p[i]];\n }\n return t;\n}\n\nexport function __decorate(decorators, target, key, desc) {\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\n return c > 3 && r && Object.defineProperty(target, key, r), r;\n}\n\nexport function __param(paramIndex, decorator) {\n return function (target, key) { decorator(target, key, paramIndex); }\n}\n\nexport function __esDecorate(ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) {\n function accept(f) { if (f !== void 0 && typeof f !== \"function\") throw new TypeError(\"Function expected\"); return f; }\n var kind = contextIn.kind, key = kind === \"getter\" ? \"get\" : kind === \"setter\" ? \"set\" : \"value\";\n var target = !descriptorIn && ctor ? contextIn[\"static\"] ? ctor : ctor.prototype : null;\n var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {});\n var _, done = false;\n for (var i = decorators.length - 1; i >= 0; i--) {\n var context = {};\n for (var p in contextIn) context[p] = p === \"access\" ? {} : contextIn[p];\n for (var p in contextIn.access) context.access[p] = contextIn.access[p];\n context.addInitializer = function (f) { if (done) throw new TypeError(\"Cannot add initializers after decoration has completed\"); extraInitializers.push(accept(f || null)); };\n var result = (0, decorators[i])(kind === \"accessor\" ? { get: descriptor.get, set: descriptor.set } : descriptor[key], context);\n if (kind === \"accessor\") {\n if (result === void 0) continue;\n if (result === null || typeof result !== \"object\") throw new TypeError(\"Object expected\");\n if (_ = accept(result.get)) descriptor.get = _;\n if (_ = accept(result.set)) descriptor.set = _;\n if (_ = accept(result.init)) initializers.unshift(_);\n }\n else if (_ = accept(result)) {\n if (kind === \"field\") initializers.unshift(_);\n else descriptor[key] = _;\n }\n }\n if (target) Object.defineProperty(target, contextIn.name, descriptor);\n done = true;\n};\n\nexport function __runInitializers(thisArg, initializers, value) {\n var useValue = arguments.length > 2;\n for (var i = 0; i < initializers.length; i++) {\n value = useValue ? initializers[i].call(thisArg, value) : initializers[i].call(thisArg);\n }\n return useValue ? value : void 0;\n};\n\nexport function __propKey(x) {\n return typeof x === \"symbol\" ? x : \"\".concat(x);\n};\n\nexport function __setFunctionName(f, name, prefix) {\n if (typeof name === \"symbol\") name = name.description ? \"[\".concat(name.description, \"]\") : \"\";\n return Object.defineProperty(f, \"name\", { configurable: true, value: prefix ? \"\".concat(prefix, \" \", name) : name });\n};\n\nexport function __metadata(metadataKey, metadataValue) {\n if (typeof Reflect === \"object\" && typeof Reflect.metadata === \"function\") return Reflect.metadata(metadataKey, metadataValue);\n}\n\nexport function __awaiter(thisArg, _arguments, P, generator) {\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments || [])).next());\n });\n}\n\nexport function __generator(thisArg, body) {\n var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === \"function\" ? Iterator : Object).prototype);\n return g.next = verb(0), g[\"throw\"] = verb(1), g[\"return\"] = verb(2), typeof Symbol === \"function\" && (g[Symbol.iterator] = function() { return this; }), g;\n function verb(n) { return function (v) { return step([n, v]); }; }\n function step(op) {\n if (f) throw new TypeError(\"Generator is already executing.\");\n while (g && (g = 0, op[0] && (_ = 0)), _) try {\n if (f = 1, y && (t = op[0] & 2 ? y[\"return\"] : op[0] ? y[\"throw\"] || ((t = y[\"return\"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;\n if (y = 0, t) op = [op[0] & 2, t.value];\n switch (op[0]) {\n case 0: case 1: t = op; break;\n case 4: _.label++; return { value: op[1], done: false };\n case 5: _.label++; y = op[1]; op = [0]; continue;\n case 7: op = _.ops.pop(); _.trys.pop(); continue;\n default:\n if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }\n if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }\n if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }\n if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }\n if (t[2]) _.ops.pop();\n _.trys.pop(); continue;\n }\n op = body.call(thisArg, _);\n } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }\n if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };\n }\n}\n\nexport var __createBinding = Object.create ? (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n var desc = Object.getOwnPropertyDescriptor(m, k);\n if (!desc || (\"get\" in desc ? !m.__esModule : desc.writable || desc.configurable)) {\n desc = { enumerable: true, get: function() { return m[k]; } };\n }\n Object.defineProperty(o, k2, desc);\n}) : (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n o[k2] = m[k];\n});\n\nexport function __exportStar(m, o) {\n for (var p in m) if (p !== \"default\" && !Object.prototype.hasOwnProperty.call(o, p)) __createBinding(o, m, p);\n}\n\nexport function __values(o) {\n var s = typeof Symbol === \"function\" && Symbol.iterator, m = s && o[s], i = 0;\n if (m) return m.call(o);\n if (o && typeof o.length === \"number\") return {\n next: function () {\n if (o && i >= o.length) o = void 0;\n return { value: o && o[i++], done: !o };\n }\n };\n throw new TypeError(s ? \"Object is not iterable.\" : \"Symbol.iterator is not defined.\");\n}\n\nexport function __read(o, n) {\n var m = typeof Symbol === \"function\" && o[Symbol.iterator];\n if (!m) return o;\n var i = m.call(o), r, ar = [], e;\n try {\n while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);\n }\n catch (error) { e = { error: error }; }\n finally {\n try {\n if (r && !r.done && (m = i[\"return\"])) m.call(i);\n }\n finally { if (e) throw e.error; }\n }\n return ar;\n}\n\n/** @deprecated */\nexport function __spread() {\n for (var ar = [], i = 0; i < arguments.length; i++)\n ar = ar.concat(__read(arguments[i]));\n return ar;\n}\n\n/** @deprecated */\nexport function __spreadArrays() {\n for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;\n for (var r = Array(s), k = 0, i = 0; i < il; i++)\n for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)\n r[k] = a[j];\n return r;\n}\n\nexport function __spreadArray(to, from, pack) {\n if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {\n if (ar || !(i in from)) {\n if (!ar) ar = Array.prototype.slice.call(from, 0, i);\n ar[i] = from[i];\n }\n }\n return to.concat(ar || Array.prototype.slice.call(from));\n}\n\nexport function __await(v) {\n return this instanceof __await ? (this.v = v, this) : new __await(v);\n}\n\nexport function __asyncGenerator(thisArg, _arguments, generator) {\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\n var g = generator.apply(thisArg, _arguments || []), i, q = [];\n return i = Object.create((typeof AsyncIterator === \"function\" ? AsyncIterator : Object).prototype), verb(\"next\"), verb(\"throw\"), verb(\"return\", awaitReturn), i[Symbol.asyncIterator] = function () { return this; }, i;\n function awaitReturn(f) { return function (v) { return Promise.resolve(v).then(f, reject); }; }\n function verb(n, f) { if (g[n]) { i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; if (f) i[n] = f(i[n]); } }\n function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }\n function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }\n function fulfill(value) { resume(\"next\", value); }\n function reject(value) { resume(\"throw\", value); }\n function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }\n}\n\nexport function __asyncDelegator(o) {\n var i, p;\n return i = {}, verb(\"next\"), verb(\"throw\", function (e) { throw e; }), verb(\"return\"), i[Symbol.iterator] = function () { return this; }, i;\n function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: false } : f ? f(v) : v; } : f; }\n}\n\nexport function __asyncValues(o) {\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\n var m = o[Symbol.asyncIterator], i;\n return m ? m.call(o) : (o = typeof __values === \"function\" ? __values(o) : o[Symbol.iterator](), i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i);\n function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }\n function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }\n}\n\nexport function __makeTemplateObject(cooked, raw) {\n if (Object.defineProperty) { Object.defineProperty(cooked, \"raw\", { value: raw }); } else { cooked.raw = raw; }\n return cooked;\n};\n\nvar __setModuleDefault = Object.create ? (function(o, v) {\n Object.defineProperty(o, \"default\", { enumerable: true, value: v });\n}) : function(o, v) {\n o[\"default\"] = v;\n};\n\nvar ownKeys = function(o) {\n ownKeys = Object.getOwnPropertyNames || function (o) {\n var ar = [];\n for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;\n return ar;\n };\n return ownKeys(o);\n};\n\nexport function __importStar(mod) {\n if (mod && mod.__esModule) return mod;\n var result = {};\n if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== \"default\") __createBinding(result, mod, k[i]);\n __setModuleDefault(result, mod);\n return result;\n}\n\nexport function __importDefault(mod) {\n return (mod && mod.__esModule) ? mod : { default: mod };\n}\n\nexport function __classPrivateFieldGet(receiver, state, kind, f) {\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a getter\");\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot read private member from an object whose class did not declare it\");\n return kind === \"m\" ? f : kind === \"a\" ? f.call(receiver) : f ? f.value : state.get(receiver);\n}\n\nexport function __classPrivateFieldSet(receiver, state, value, kind, f) {\n if (kind === \"m\") throw new TypeError(\"Private method is not writable\");\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a setter\");\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot write private member to an object whose class did not declare it\");\n return (kind === \"a\" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;\n}\n\nexport function __classPrivateFieldIn(state, receiver) {\n if (receiver === null || (typeof receiver !== \"object\" && typeof receiver !== \"function\")) throw new TypeError(\"Cannot use 'in' operator on non-object\");\n return typeof state === \"function\" ? receiver === state : state.has(receiver);\n}\n\nexport function __addDisposableResource(env, value, async) {\n if (value !== null && value !== void 0) {\n if (typeof value !== \"object\" && typeof value !== \"function\") throw new TypeError(\"Object expected.\");\n var dispose, inner;\n if (async) {\n if (!Symbol.asyncDispose) throw new TypeError(\"Symbol.asyncDispose is not defined.\");\n dispose = value[Symbol.asyncDispose];\n }\n if (dispose === void 0) {\n if (!Symbol.dispose) throw new TypeError(\"Symbol.dispose is not defined.\");\n dispose = value[Symbol.dispose];\n if (async) inner = dispose;\n }\n if (typeof dispose !== \"function\") throw new TypeError(\"Object not disposable.\");\n if (inner) dispose = function() { try { inner.call(this); } catch (e) { return Promise.reject(e); } };\n env.stack.push({ value: value, dispose: dispose, async: async });\n }\n else if (async) {\n env.stack.push({ async: true });\n }\n return value;\n}\n\nvar _SuppressedError = typeof SuppressedError === \"function\" ? SuppressedError : function (error, suppressed, message) {\n var e = new Error(message);\n return e.name = \"SuppressedError\", e.error = error, e.suppressed = suppressed, e;\n};\n\nexport function __disposeResources(env) {\n function fail(e) {\n env.error = env.hasError ? new _SuppressedError(e, env.error, \"An error was suppressed during disposal.\") : e;\n env.hasError = true;\n }\n var r, s = 0;\n function next() {\n while (r = env.stack.pop()) {\n try {\n if (!r.async && s === 1) return s = 0, env.stack.push(r), Promise.resolve().then(next);\n if (r.dispose) {\n var result = r.dispose.call(r.value);\n if (r.async) return s |= 2, Promise.resolve(result).then(next, function(e) { fail(e); return next(); });\n }\n else s |= 1;\n }\n catch (e) {\n fail(e);\n }\n }\n if (s === 1) return env.hasError ? Promise.reject(env.error) : Promise.resolve();\n if (env.hasError) throw env.error;\n }\n return next();\n}\n\nexport function __rewriteRelativeImportExtension(path, preserveJsx) {\n if (typeof path === \"string\" && /^\\.\\.?\\//.test(path)) {\n return path.replace(/\\.(tsx)$|((?:\\.d)?)((?:\\.[^./]+?)?)\\.([cm]?)ts$/i, function (m, tsx, d, ext, cm) {\n return tsx ? preserveJsx ? \".jsx\" : \".js\" : d && (!ext || !cm) ? m : (d + ext + \".\" + cm.toLowerCase() + \"js\");\n });\n }\n return path;\n}\n\nexport default {\n __extends,\n __assign,\n __rest,\n __decorate,\n __param,\n __esDecorate,\n __runInitializers,\n __propKey,\n __setFunctionName,\n __metadata,\n __awaiter,\n __generator,\n __createBinding,\n __exportStar,\n __values,\n __read,\n __spread,\n __spreadArrays,\n __spreadArray,\n __await,\n __asyncGenerator,\n __asyncDelegator,\n __asyncValues,\n __makeTemplateObject,\n __importStar,\n __importDefault,\n __classPrivateFieldGet,\n __classPrivateFieldSet,\n __classPrivateFieldIn,\n __addDisposableResource,\n __disposeResources,\n __rewriteRelativeImportExtension,\n};\n", "/**\n * Returns true if the object is a function.\n * @param value The value to check\n */\nexport function isFunction(value: any): value is (...args: any[]) => any {\n return typeof value === 'function';\n}\n", "/**\n * Used to create Error subclasses until the community moves away from ES5.\n *\n * This is because compiling from TypeScript down to ES5 has issues with subclassing Errors\n * as well as other built-in types: https://github.com/Microsoft/TypeScript/issues/12123\n *\n * @param createImpl A factory function to create the actual constructor implementation. The returned\n * function should be a named function that calls `_super` internally.\n */\nexport function createErrorClass(createImpl: (_super: any) => any): T {\n const _super = (instance: any) => {\n Error.call(instance);\n instance.stack = new Error().stack;\n };\n\n const ctorFunc = createImpl(_super);\n ctorFunc.prototype = Object.create(Error.prototype);\n ctorFunc.prototype.constructor = ctorFunc;\n return ctorFunc;\n}\n", "import { createErrorClass } from './createErrorClass';\n\nexport interface UnsubscriptionError extends Error {\n readonly errors: any[];\n}\n\nexport interface UnsubscriptionErrorCtor {\n /**\n * @deprecated Internal implementation detail. Do not construct error instances.\n * Cannot be tagged as internal: https://github.com/ReactiveX/rxjs/issues/6269\n */\n new (errors: any[]): UnsubscriptionError;\n}\n\n/**\n * An error thrown when one or more errors have occurred during the\n * `unsubscribe` of a {@link Subscription}.\n */\nexport const UnsubscriptionError: UnsubscriptionErrorCtor = createErrorClass(\n (_super) =>\n function UnsubscriptionErrorImpl(this: any, errors: (Error | string)[]) {\n _super(this);\n this.message = errors\n ? `${errors.length} errors occurred during unsubscription:\n${errors.map((err, i) => `${i + 1}) ${err.toString()}`).join('\\n ')}`\n : '';\n this.name = 'UnsubscriptionError';\n this.errors = errors;\n }\n);\n", "/**\n * Removes an item from an array, mutating it.\n * @param arr The array to remove the item from\n * @param item The item to remove\n */\nexport function arrRemove(arr: T[] | undefined | null, item: T) {\n if (arr) {\n const index = arr.indexOf(item);\n 0 <= index && arr.splice(index, 1);\n }\n}\n", "import { isFunction } from './util/isFunction';\nimport { UnsubscriptionError } from './util/UnsubscriptionError';\nimport { SubscriptionLike, TeardownLogic, Unsubscribable } from './types';\nimport { arrRemove } from './util/arrRemove';\n\n/**\n * Represents a disposable resource, such as the execution of an Observable. A\n * Subscription has one important method, `unsubscribe`, that takes no argument\n * and just disposes the resource held by the subscription.\n *\n * Additionally, subscriptions may be grouped together through the `add()`\n * method, which will attach a child Subscription to the current Subscription.\n * When a Subscription is unsubscribed, all its children (and its grandchildren)\n * will be unsubscribed as well.\n */\nexport class Subscription implements SubscriptionLike {\n public static EMPTY = (() => {\n const empty = new Subscription();\n empty.closed = true;\n return empty;\n })();\n\n /**\n * A flag to indicate whether this Subscription has already been unsubscribed.\n */\n public closed = false;\n\n private _parentage: Subscription[] | Subscription | null = null;\n\n /**\n * The list of registered finalizers to execute upon unsubscription. Adding and removing from this\n * list occurs in the {@link #add} and {@link #remove} methods.\n */\n private _finalizers: Exclude[] | null = null;\n\n /**\n * @param initialTeardown A function executed first as part of the finalization\n * process that is kicked off when {@link #unsubscribe} is called.\n */\n constructor(private initialTeardown?: () => void) {}\n\n /**\n * Disposes the resources held by the subscription. May, for instance, cancel\n * an ongoing Observable execution or cancel any other type of work that\n * started when the Subscription was created.\n */\n unsubscribe(): void {\n let errors: any[] | undefined;\n\n if (!this.closed) {\n this.closed = true;\n\n // Remove this from it's parents.\n const { _parentage } = this;\n if (_parentage) {\n this._parentage = null;\n if (Array.isArray(_parentage)) {\n for (const parent of _parentage) {\n parent.remove(this);\n }\n } else {\n _parentage.remove(this);\n }\n }\n\n const { initialTeardown: initialFinalizer } = this;\n if (isFunction(initialFinalizer)) {\n try {\n initialFinalizer();\n } catch (e) {\n errors = e instanceof UnsubscriptionError ? e.errors : [e];\n }\n }\n\n const { _finalizers } = this;\n if (_finalizers) {\n this._finalizers = null;\n for (const finalizer of _finalizers) {\n try {\n execFinalizer(finalizer);\n } catch (err) {\n errors = errors ?? [];\n if (err instanceof UnsubscriptionError) {\n errors = [...errors, ...err.errors];\n } else {\n errors.push(err);\n }\n }\n }\n }\n\n if (errors) {\n throw new UnsubscriptionError(errors);\n }\n }\n }\n\n /**\n * Adds a finalizer to this subscription, so that finalization will be unsubscribed/called\n * when this subscription is unsubscribed. If this subscription is already {@link #closed},\n * because it has already been unsubscribed, then whatever finalizer is passed to it\n * will automatically be executed (unless the finalizer itself is also a closed subscription).\n *\n * Closed Subscriptions cannot be added as finalizers to any subscription. Adding a closed\n * subscription to a any subscription will result in no operation. (A noop).\n *\n * Adding a subscription to itself, or adding `null` or `undefined` will not perform any\n * operation at all. (A noop).\n *\n * `Subscription` instances that are added to this instance will automatically remove themselves\n * if they are unsubscribed. Functions and {@link Unsubscribable} objects that you wish to remove\n * will need to be removed manually with {@link #remove}\n *\n * @param teardown The finalization logic to add to this subscription.\n */\n add(teardown: TeardownLogic): void {\n // Only add the finalizer if it's not undefined\n // and don't add a subscription to itself.\n if (teardown && teardown !== this) {\n if (this.closed) {\n // If this subscription is already closed,\n // execute whatever finalizer is handed to it automatically.\n execFinalizer(teardown);\n } else {\n if (teardown instanceof Subscription) {\n // We don't add closed subscriptions, and we don't add the same subscription\n // twice. Subscription unsubscribe is idempotent.\n if (teardown.closed || teardown._hasParent(this)) {\n return;\n }\n teardown._addParent(this);\n }\n (this._finalizers = this._finalizers ?? []).push(teardown);\n }\n }\n }\n\n /**\n * Checks to see if a this subscription already has a particular parent.\n * This will signal that this subscription has already been added to the parent in question.\n * @param parent the parent to check for\n */\n private _hasParent(parent: Subscription) {\n const { _parentage } = this;\n return _parentage === parent || (Array.isArray(_parentage) && _parentage.includes(parent));\n }\n\n /**\n * Adds a parent to this subscription so it can be removed from the parent if it\n * unsubscribes on it's own.\n *\n * NOTE: THIS ASSUMES THAT {@link _hasParent} HAS ALREADY BEEN CHECKED.\n * @param parent The parent subscription to add\n */\n private _addParent(parent: Subscription) {\n const { _parentage } = this;\n this._parentage = Array.isArray(_parentage) ? (_parentage.push(parent), _parentage) : _parentage ? [_parentage, parent] : parent;\n }\n\n /**\n * Called on a child when it is removed via {@link #remove}.\n * @param parent The parent to remove\n */\n private _removeParent(parent: Subscription) {\n const { _parentage } = this;\n if (_parentage === parent) {\n this._parentage = null;\n } else if (Array.isArray(_parentage)) {\n arrRemove(_parentage, parent);\n }\n }\n\n /**\n * Removes a finalizer from this subscription that was previously added with the {@link #add} method.\n *\n * Note that `Subscription` instances, when unsubscribed, will automatically remove themselves\n * from every other `Subscription` they have been added to. This means that using the `remove` method\n * is not a common thing and should be used thoughtfully.\n *\n * If you add the same finalizer instance of a function or an unsubscribable object to a `Subscription` instance\n * more than once, you will need to call `remove` the same number of times to remove all instances.\n *\n * All finalizer instances are removed to free up memory upon unsubscription.\n *\n * @param teardown The finalizer to remove from this subscription\n */\n remove(teardown: Exclude): void {\n const { _finalizers } = this;\n _finalizers && arrRemove(_finalizers, teardown);\n\n if (teardown instanceof Subscription) {\n teardown._removeParent(this);\n }\n }\n}\n\nexport const EMPTY_SUBSCRIPTION = Subscription.EMPTY;\n\nexport function isSubscription(value: any): value is Subscription {\n return (\n value instanceof Subscription ||\n (value && 'closed' in value && isFunction(value.remove) && isFunction(value.add) && isFunction(value.unsubscribe))\n );\n}\n\nfunction execFinalizer(finalizer: Unsubscribable | (() => void)) {\n if (isFunction(finalizer)) {\n finalizer();\n } else {\n finalizer.unsubscribe();\n }\n}\n", "import { Subscriber } from './Subscriber';\nimport { ObservableNotification } from './types';\n\n/**\n * The {@link GlobalConfig} object for RxJS. It is used to configure things\n * like how to react on unhandled errors.\n */\nexport const config: GlobalConfig = {\n onUnhandledError: null,\n onStoppedNotification: null,\n Promise: undefined,\n useDeprecatedSynchronousErrorHandling: false,\n useDeprecatedNextContext: false,\n};\n\n/**\n * The global configuration object for RxJS, used to configure things\n * like how to react on unhandled errors. Accessible via {@link config}\n * object.\n */\nexport interface GlobalConfig {\n /**\n * A registration point for unhandled errors from RxJS. These are errors that\n * cannot were not handled by consuming code in the usual subscription path. For\n * example, if you have this configured, and you subscribe to an observable without\n * providing an error handler, errors from that subscription will end up here. This\n * will _always_ be called asynchronously on another job in the runtime. This is because\n * we do not want errors thrown in this user-configured handler to interfere with the\n * behavior of the library.\n */\n onUnhandledError: ((err: any) => void) | null;\n\n /**\n * A registration point for notifications that cannot be sent to subscribers because they\n * have completed, errored or have been explicitly unsubscribed. By default, next, complete\n * and error notifications sent to stopped subscribers are noops. However, sometimes callers\n * might want a different behavior. For example, with sources that attempt to report errors\n * to stopped subscribers, a caller can configure RxJS to throw an unhandled error instead.\n * This will _always_ be called asynchronously on another job in the runtime. This is because\n * we do not want errors thrown in this user-configured handler to interfere with the\n * behavior of the library.\n */\n onStoppedNotification: ((notification: ObservableNotification, subscriber: Subscriber) => void) | null;\n\n /**\n * The promise constructor used by default for {@link Observable#toPromise toPromise} and {@link Observable#forEach forEach}\n * methods.\n *\n * @deprecated As of version 8, RxJS will no longer support this sort of injection of a\n * Promise constructor. If you need a Promise implementation other than native promises,\n * please polyfill/patch Promise as you see appropriate. Will be removed in v8.\n */\n Promise?: PromiseConstructorLike;\n\n /**\n * If true, turns on synchronous error rethrowing, which is a deprecated behavior\n * in v6 and higher. This behavior enables bad patterns like wrapping a subscribe\n * call in a try/catch block. It also enables producer interference, a nasty bug\n * where a multicast can be broken for all observers by a downstream consumer with\n * an unhandled error. DO NOT USE THIS FLAG UNLESS IT'S NEEDED TO BUY TIME\n * FOR MIGRATION REASONS.\n *\n * @deprecated As of version 8, RxJS will no longer support synchronous throwing\n * of unhandled errors. All errors will be thrown on a separate call stack to prevent bad\n * behaviors described above. Will be removed in v8.\n */\n useDeprecatedSynchronousErrorHandling: boolean;\n\n /**\n * If true, enables an as-of-yet undocumented feature from v5: The ability to access\n * `unsubscribe()` via `this` context in `next` functions created in observers passed\n * to `subscribe`.\n *\n * This is being removed because the performance was severely problematic, and it could also cause\n * issues when types other than POJOs are passed to subscribe as subscribers, as they will likely have\n * their `this` context overwritten.\n *\n * @deprecated As of version 8, RxJS will no longer support altering the\n * context of next functions provided as part of an observer to Subscribe. Instead,\n * you will have access to a subscription or a signal or token that will allow you to do things like\n * unsubscribe and test closed status. Will be removed in v8.\n */\n useDeprecatedNextContext: boolean;\n}\n", "import type { TimerHandle } from './timerHandle';\ntype SetTimeoutFunction = (handler: () => void, timeout?: number, ...args: any[]) => TimerHandle;\ntype ClearTimeoutFunction = (handle: TimerHandle) => void;\n\ninterface TimeoutProvider {\n setTimeout: SetTimeoutFunction;\n clearTimeout: ClearTimeoutFunction;\n delegate:\n | {\n setTimeout: SetTimeoutFunction;\n clearTimeout: ClearTimeoutFunction;\n }\n | undefined;\n}\n\nexport const timeoutProvider: TimeoutProvider = {\n // When accessing the delegate, use the variable rather than `this` so that\n // the functions can be called without being bound to the provider.\n setTimeout(handler: () => void, timeout?: number, ...args) {\n const { delegate } = timeoutProvider;\n if (delegate?.setTimeout) {\n return delegate.setTimeout(handler, timeout, ...args);\n }\n return setTimeout(handler, timeout, ...args);\n },\n clearTimeout(handle) {\n const { delegate } = timeoutProvider;\n return (delegate?.clearTimeout || clearTimeout)(handle as any);\n },\n delegate: undefined,\n};\n", "import { config } from '../config';\nimport { timeoutProvider } from '../scheduler/timeoutProvider';\n\n/**\n * Handles an error on another job either with the user-configured {@link onUnhandledError},\n * or by throwing it on that new job so it can be picked up by `window.onerror`, `process.on('error')`, etc.\n *\n * This should be called whenever there is an error that is out-of-band with the subscription\n * or when an error hits a terminal boundary of the subscription and no error handler was provided.\n *\n * @param err the error to report\n */\nexport function reportUnhandledError(err: any) {\n timeoutProvider.setTimeout(() => {\n const { onUnhandledError } = config;\n if (onUnhandledError) {\n // Execute the user-configured error handler.\n onUnhandledError(err);\n } else {\n // Throw so it is picked up by the runtime's uncaught error mechanism.\n throw err;\n }\n });\n}\n", "/* tslint:disable:no-empty */\nexport function noop() { }\n", "import { CompleteNotification, NextNotification, ErrorNotification } from './types';\n\n/**\n * A completion object optimized for memory use and created to be the\n * same \"shape\" as other notifications in v8.\n * @internal\n */\nexport const COMPLETE_NOTIFICATION = (() => createNotification('C', undefined, undefined) as CompleteNotification)();\n\n/**\n * Internal use only. Creates an optimized error notification that is the same \"shape\"\n * as other notifications.\n * @internal\n */\nexport function errorNotification(error: any): ErrorNotification {\n return createNotification('E', undefined, error) as any;\n}\n\n/**\n * Internal use only. Creates an optimized next notification that is the same \"shape\"\n * as other notifications.\n * @internal\n */\nexport function nextNotification(value: T) {\n return createNotification('N', value, undefined) as NextNotification;\n}\n\n/**\n * Ensures that all notifications created internally have the same \"shape\" in v8.\n *\n * TODO: This is only exported to support a crazy legacy test in `groupBy`.\n * @internal\n */\nexport function createNotification(kind: 'N' | 'E' | 'C', value: any, error: any) {\n return {\n kind,\n value,\n error,\n };\n}\n", "import { config } from '../config';\n\nlet context: { errorThrown: boolean; error: any } | null = null;\n\n/**\n * Handles dealing with errors for super-gross mode. Creates a context, in which\n * any synchronously thrown errors will be passed to {@link captureError}. Which\n * will record the error such that it will be rethrown after the call back is complete.\n * TODO: Remove in v8\n * @param cb An immediately executed function.\n */\nexport function errorContext(cb: () => void) {\n if (config.useDeprecatedSynchronousErrorHandling) {\n const isRoot = !context;\n if (isRoot) {\n context = { errorThrown: false, error: null };\n }\n cb();\n if (isRoot) {\n const { errorThrown, error } = context!;\n context = null;\n if (errorThrown) {\n throw error;\n }\n }\n } else {\n // This is the general non-deprecated path for everyone that\n // isn't crazy enough to use super-gross mode (useDeprecatedSynchronousErrorHandling)\n cb();\n }\n}\n\n/**\n * Captures errors only in super-gross mode.\n * @param err the error to capture\n */\nexport function captureError(err: any) {\n if (config.useDeprecatedSynchronousErrorHandling && context) {\n context.errorThrown = true;\n context.error = err;\n }\n}\n", "import { isFunction } from './util/isFunction';\nimport { Observer, ObservableNotification } from './types';\nimport { isSubscription, Subscription } from './Subscription';\nimport { config } from './config';\nimport { reportUnhandledError } from './util/reportUnhandledError';\nimport { noop } from './util/noop';\nimport { nextNotification, errorNotification, COMPLETE_NOTIFICATION } from './NotificationFactories';\nimport { timeoutProvider } from './scheduler/timeoutProvider';\nimport { captureError } from './util/errorContext';\n\n/**\n * Implements the {@link Observer} interface and extends the\n * {@link Subscription} class. While the {@link Observer} is the public API for\n * consuming the values of an {@link Observable}, all Observers get converted to\n * a Subscriber, in order to provide Subscription-like capabilities such as\n * `unsubscribe`. Subscriber is a common type in RxJS, and crucial for\n * implementing operators, but it is rarely used as a public API.\n */\nexport class Subscriber extends Subscription implements Observer {\n /**\n * A static factory for a Subscriber, given a (potentially partial) definition\n * of an Observer.\n * @param next The `next` callback of an Observer.\n * @param error The `error` callback of an\n * Observer.\n * @param complete The `complete` callback of an\n * Observer.\n * @return A Subscriber wrapping the (partially defined)\n * Observer represented by the given arguments.\n * @deprecated Do not use. Will be removed in v8. There is no replacement for this\n * method, and there is no reason to be creating instances of `Subscriber` directly.\n * If you have a specific use case, please file an issue.\n */\n static create(next?: (x?: T) => void, error?: (e?: any) => void, complete?: () => void): Subscriber {\n return new SafeSubscriber(next, error, complete);\n }\n\n /** @deprecated Internal implementation detail, do not use directly. Will be made internal in v8. */\n protected isStopped: boolean = false;\n /** @deprecated Internal implementation detail, do not use directly. Will be made internal in v8. */\n protected destination: Subscriber | Observer; // this `any` is the escape hatch to erase extra type param (e.g. R)\n\n /**\n * @deprecated Internal implementation detail, do not use directly. Will be made internal in v8.\n * There is no reason to directly create an instance of Subscriber. This type is exported for typings reasons.\n */\n constructor(destination?: Subscriber | Observer) {\n super();\n if (destination) {\n this.destination = destination;\n // Automatically chain subscriptions together here.\n // if destination is a Subscription, then it is a Subscriber.\n if (isSubscription(destination)) {\n destination.add(this);\n }\n } else {\n this.destination = EMPTY_OBSERVER;\n }\n }\n\n /**\n * The {@link Observer} callback to receive notifications of type `next` from\n * the Observable, with a value. The Observable may call this method 0 or more\n * times.\n * @param value The `next` value.\n */\n next(value: T): void {\n if (this.isStopped) {\n handleStoppedNotification(nextNotification(value), this);\n } else {\n this._next(value!);\n }\n }\n\n /**\n * The {@link Observer} callback to receive notifications of type `error` from\n * the Observable, with an attached `Error`. Notifies the Observer that\n * the Observable has experienced an error condition.\n * @param err The `error` exception.\n */\n error(err?: any): void {\n if (this.isStopped) {\n handleStoppedNotification(errorNotification(err), this);\n } else {\n this.isStopped = true;\n this._error(err);\n }\n }\n\n /**\n * The {@link Observer} callback to receive a valueless notification of type\n * `complete` from the Observable. Notifies the Observer that the Observable\n * has finished sending push-based notifications.\n */\n complete(): void {\n if (this.isStopped) {\n handleStoppedNotification(COMPLETE_NOTIFICATION, this);\n } else {\n this.isStopped = true;\n this._complete();\n }\n }\n\n unsubscribe(): void {\n if (!this.closed) {\n this.isStopped = true;\n super.unsubscribe();\n this.destination = null!;\n }\n }\n\n protected _next(value: T): void {\n this.destination.next(value);\n }\n\n protected _error(err: any): void {\n try {\n this.destination.error(err);\n } finally {\n this.unsubscribe();\n }\n }\n\n protected _complete(): void {\n try {\n this.destination.complete();\n } finally {\n this.unsubscribe();\n }\n }\n}\n\n/**\n * This bind is captured here because we want to be able to have\n * compatibility with monoid libraries that tend to use a method named\n * `bind`. In particular, a library called Monio requires this.\n */\nconst _bind = Function.prototype.bind;\n\nfunction bind any>(fn: Fn, thisArg: any): Fn {\n return _bind.call(fn, thisArg);\n}\n\n/**\n * Internal optimization only, DO NOT EXPOSE.\n * @internal\n */\nclass ConsumerObserver implements Observer {\n constructor(private partialObserver: Partial>) {}\n\n next(value: T): void {\n const { partialObserver } = this;\n if (partialObserver.next) {\n try {\n partialObserver.next(value);\n } catch (error) {\n handleUnhandledError(error);\n }\n }\n }\n\n error(err: any): void {\n const { partialObserver } = this;\n if (partialObserver.error) {\n try {\n partialObserver.error(err);\n } catch (error) {\n handleUnhandledError(error);\n }\n } else {\n handleUnhandledError(err);\n }\n }\n\n complete(): void {\n const { partialObserver } = this;\n if (partialObserver.complete) {\n try {\n partialObserver.complete();\n } catch (error) {\n handleUnhandledError(error);\n }\n }\n }\n}\n\nexport class SafeSubscriber extends Subscriber {\n constructor(\n observerOrNext?: Partial> | ((value: T) => void) | null,\n error?: ((e?: any) => void) | null,\n complete?: (() => void) | null\n ) {\n super();\n\n let partialObserver: Partial>;\n if (isFunction(observerOrNext) || !observerOrNext) {\n // The first argument is a function, not an observer. The next\n // two arguments *could* be observers, or they could be empty.\n partialObserver = {\n next: (observerOrNext ?? undefined) as ((value: T) => void) | undefined,\n error: error ?? undefined,\n complete: complete ?? undefined,\n };\n } else {\n // The first argument is a partial observer.\n let context: any;\n if (this && config.useDeprecatedNextContext) {\n // This is a deprecated path that made `this.unsubscribe()` available in\n // next handler functions passed to subscribe. This only exists behind a flag\n // now, as it is *very* slow.\n context = Object.create(observerOrNext);\n context.unsubscribe = () => this.unsubscribe();\n partialObserver = {\n next: observerOrNext.next && bind(observerOrNext.next, context),\n error: observerOrNext.error && bind(observerOrNext.error, context),\n complete: observerOrNext.complete && bind(observerOrNext.complete, context),\n };\n } else {\n // The \"normal\" path. Just use the partial observer directly.\n partialObserver = observerOrNext;\n }\n }\n\n // Wrap the partial observer to ensure it's a full observer, and\n // make sure proper error handling is accounted for.\n this.destination = new ConsumerObserver(partialObserver);\n }\n}\n\nfunction handleUnhandledError(error: any) {\n if (config.useDeprecatedSynchronousErrorHandling) {\n captureError(error);\n } else {\n // Ideal path, we report this as an unhandled error,\n // which is thrown on a new call stack.\n reportUnhandledError(error);\n }\n}\n\n/**\n * An error handler used when no error handler was supplied\n * to the SafeSubscriber -- meaning no error handler was supplied\n * do the `subscribe` call on our observable.\n * @param err The error to handle\n */\nfunction defaultErrorHandler(err: any) {\n throw err;\n}\n\n/**\n * A handler for notifications that cannot be sent to a stopped subscriber.\n * @param notification The notification being sent.\n * @param subscriber The stopped subscriber.\n */\nfunction handleStoppedNotification(notification: ObservableNotification, subscriber: Subscriber) {\n const { onStoppedNotification } = config;\n onStoppedNotification && timeoutProvider.setTimeout(() => onStoppedNotification(notification, subscriber));\n}\n\n/**\n * The observer used as a stub for subscriptions where the user did not\n * pass any arguments to `subscribe`. Comes with the default error handling\n * behavior.\n */\nexport const EMPTY_OBSERVER: Readonly> & { closed: true } = {\n closed: true,\n next: noop,\n error: defaultErrorHandler,\n complete: noop,\n};\n", "/**\n * Symbol.observable or a string \"@@observable\". Used for interop\n *\n * @deprecated We will no longer be exporting this symbol in upcoming versions of RxJS.\n * Instead polyfill and use Symbol.observable directly *or* use https://www.npmjs.com/package/symbol-observable\n */\nexport const observable: string | symbol = (() => (typeof Symbol === 'function' && Symbol.observable) || '@@observable')();\n", "/**\n * This function takes one parameter and just returns it. Simply put,\n * this is like `(x: T): T => x`.\n *\n * ## Examples\n *\n * This is useful in some cases when using things like `mergeMap`\n *\n * ```ts\n * import { interval, take, map, range, mergeMap, identity } from 'rxjs';\n *\n * const source$ = interval(1000).pipe(take(5));\n *\n * const result$ = source$.pipe(\n * map(i => range(i)),\n * mergeMap(identity) // same as mergeMap(x => x)\n * );\n *\n * result$.subscribe({\n * next: console.log\n * });\n * ```\n *\n * Or when you want to selectively apply an operator\n *\n * ```ts\n * import { interval, take, identity } from 'rxjs';\n *\n * const shouldLimit = () => Math.random() < 0.5;\n *\n * const source$ = interval(1000);\n *\n * const result$ = source$.pipe(shouldLimit() ? take(5) : identity);\n *\n * result$.subscribe({\n * next: console.log\n * });\n * ```\n *\n * @param x Any value that is returned by this function\n * @returns The value passed as the first parameter to this function\n */\nexport function identity(x: T): T {\n return x;\n}\n", "import { identity } from './identity';\nimport { UnaryFunction } from '../types';\n\nexport function pipe(): typeof identity;\nexport function pipe(fn1: UnaryFunction): UnaryFunction;\nexport function pipe(fn1: UnaryFunction, fn2: UnaryFunction): UnaryFunction;\nexport function pipe(fn1: UnaryFunction, fn2: UnaryFunction, fn3: UnaryFunction): UnaryFunction;\nexport function pipe(\n fn1: UnaryFunction,\n fn2: UnaryFunction,\n fn3: UnaryFunction,\n fn4: UnaryFunction\n): UnaryFunction;\nexport function pipe(\n fn1: UnaryFunction,\n fn2: UnaryFunction,\n fn3: UnaryFunction,\n fn4: UnaryFunction,\n fn5: UnaryFunction\n): UnaryFunction;\nexport function pipe(\n fn1: UnaryFunction,\n fn2: UnaryFunction,\n fn3: UnaryFunction,\n fn4: UnaryFunction,\n fn5: UnaryFunction,\n fn6: UnaryFunction\n): UnaryFunction;\nexport function pipe(\n fn1: UnaryFunction,\n fn2: UnaryFunction,\n fn3: UnaryFunction,\n fn4: UnaryFunction,\n fn5: UnaryFunction,\n fn6: UnaryFunction,\n fn7: UnaryFunction\n): UnaryFunction;\nexport function pipe(\n fn1: UnaryFunction,\n fn2: UnaryFunction,\n fn3: UnaryFunction,\n fn4: UnaryFunction,\n fn5: UnaryFunction,\n fn6: UnaryFunction,\n fn7: UnaryFunction,\n fn8: UnaryFunction\n): UnaryFunction;\nexport function pipe(\n fn1: UnaryFunction,\n fn2: UnaryFunction,\n fn3: UnaryFunction,\n fn4: UnaryFunction,\n fn5: UnaryFunction,\n fn6: UnaryFunction,\n fn7: UnaryFunction,\n fn8: UnaryFunction,\n fn9: UnaryFunction\n): UnaryFunction;\nexport function pipe(\n fn1: UnaryFunction,\n fn2: UnaryFunction,\n fn3: UnaryFunction,\n fn4: UnaryFunction,\n fn5: UnaryFunction,\n fn6: UnaryFunction,\n fn7: UnaryFunction,\n fn8: UnaryFunction,\n fn9: UnaryFunction,\n ...fns: UnaryFunction[]\n): UnaryFunction;\n\n/**\n * pipe() can be called on one or more functions, each of which can take one argument (\"UnaryFunction\")\n * and uses it to return a value.\n * It returns a function that takes one argument, passes it to the first UnaryFunction, and then\n * passes the result to the next one, passes that result to the next one, and so on. \n */\nexport function pipe(...fns: Array>): UnaryFunction {\n return pipeFromArray(fns);\n}\n\n/** @internal */\nexport function pipeFromArray(fns: Array>): UnaryFunction {\n if (fns.length === 0) {\n return identity as UnaryFunction;\n }\n\n if (fns.length === 1) {\n return fns[0];\n }\n\n return function piped(input: T): R {\n return fns.reduce((prev: any, fn: UnaryFunction) => fn(prev), input as any);\n };\n}\n", "import { Operator } from './Operator';\nimport { SafeSubscriber, Subscriber } from './Subscriber';\nimport { isSubscription, Subscription } from './Subscription';\nimport { TeardownLogic, OperatorFunction, Subscribable, Observer } from './types';\nimport { observable as Symbol_observable } from './symbol/observable';\nimport { pipeFromArray } from './util/pipe';\nimport { config } from './config';\nimport { isFunction } from './util/isFunction';\nimport { errorContext } from './util/errorContext';\n\n/**\n * A representation of any set of values over any amount of time. This is the most basic building block\n * of RxJS.\n */\nexport class Observable implements Subscribable {\n /**\n * @deprecated Internal implementation detail, do not use directly. Will be made internal in v8.\n */\n source: Observable | undefined;\n\n /**\n * @deprecated Internal implementation detail, do not use directly. Will be made internal in v8.\n */\n operator: Operator | undefined;\n\n /**\n * @param subscribe The function that is called when the Observable is\n * initially subscribed to. This function is given a Subscriber, to which new values\n * can be `next`ed, or an `error` method can be called to raise an error, or\n * `complete` can be called to notify of a successful completion.\n */\n constructor(subscribe?: (this: Observable, subscriber: Subscriber) => TeardownLogic) {\n if (subscribe) {\n this._subscribe = subscribe;\n }\n }\n\n // HACK: Since TypeScript inherits static properties too, we have to\n // fight against TypeScript here so Subject can have a different static create signature\n /**\n * Creates a new Observable by calling the Observable constructor\n * @param subscribe the subscriber function to be passed to the Observable constructor\n * @return A new observable.\n * @deprecated Use `new Observable()` instead. Will be removed in v8.\n */\n static create: (...args: any[]) => any = (subscribe?: (subscriber: Subscriber) => TeardownLogic) => {\n return new Observable(subscribe);\n };\n\n /**\n * Creates a new Observable, with this Observable instance as the source, and the passed\n * operator defined as the new observable's operator.\n * @param operator the operator defining the operation to take on the observable\n * @return A new observable with the Operator applied.\n * @deprecated Internal implementation detail, do not use directly. Will be made internal in v8.\n * If you have implemented an operator using `lift`, it is recommended that you create an\n * operator by simply returning `new Observable()` directly. See \"Creating new operators from\n * scratch\" section here: https://rxjs.dev/guide/operators\n */\n lift(operator?: Operator): Observable {\n const observable = new Observable();\n observable.source = this;\n observable.operator = operator;\n return observable;\n }\n\n subscribe(observerOrNext?: Partial> | ((value: T) => void)): Subscription;\n /** @deprecated Instead of passing separate callback arguments, use an observer argument. Signatures taking separate callback arguments will be removed in v8. Details: https://rxjs.dev/deprecations/subscribe-arguments */\n subscribe(next?: ((value: T) => void) | null, error?: ((error: any) => void) | null, complete?: (() => void) | null): Subscription;\n /**\n * Invokes an execution of an Observable and registers Observer handlers for notifications it will emit.\n *\n * Use it when you have all these Observables, but still nothing is happening.\n *\n * `subscribe` is not a regular operator, but a method that calls Observable's internal `subscribe` function. It\n * might be for example a function that you passed to Observable's constructor, but most of the time it is\n * a library implementation, which defines what will be emitted by an Observable, and when it be will emitted. This means\n * that calling `subscribe` is actually the moment when Observable starts its work, not when it is created, as it is often\n * the thought.\n *\n * Apart from starting the execution of an Observable, this method allows you to listen for values\n * that an Observable emits, as well as for when it completes or errors. You can achieve this in two\n * of the following ways.\n *\n * The first way is creating an object that implements {@link Observer} interface. It should have methods\n * defined by that interface, but note that it should be just a regular JavaScript object, which you can create\n * yourself in any way you want (ES6 class, classic function constructor, object literal etc.). In particular, do\n * not attempt to use any RxJS implementation details to create Observers - you don't need them. Remember also\n * that your object does not have to implement all methods. If you find yourself creating a method that doesn't\n * do anything, you can simply omit it. Note however, if the `error` method is not provided and an error happens,\n * it will be thrown asynchronously. Errors thrown asynchronously cannot be caught using `try`/`catch`. Instead,\n * use the {@link onUnhandledError} configuration option or use a runtime handler (like `window.onerror` or\n * `process.on('error)`) to be notified of unhandled errors. Because of this, it's recommended that you provide\n * an `error` method to avoid missing thrown errors.\n *\n * The second way is to give up on Observer object altogether and simply provide callback functions in place of its methods.\n * This means you can provide three functions as arguments to `subscribe`, where the first function is equivalent\n * of a `next` method, the second of an `error` method and the third of a `complete` method. Just as in case of an Observer,\n * if you do not need to listen for something, you can omit a function by passing `undefined` or `null`,\n * since `subscribe` recognizes these functions by where they were placed in function call. When it comes\n * to the `error` function, as with an Observer, if not provided, errors emitted by an Observable will be thrown asynchronously.\n *\n * You can, however, subscribe with no parameters at all. This may be the case where you're not interested in terminal events\n * and you also handled emissions internally by using operators (e.g. using `tap`).\n *\n * Whichever style of calling `subscribe` you use, in both cases it returns a Subscription object.\n * This object allows you to call `unsubscribe` on it, which in turn will stop the work that an Observable does and will clean\n * up all resources that an Observable used. Note that cancelling a subscription will not call `complete` callback\n * provided to `subscribe` function, which is reserved for a regular completion signal that comes from an Observable.\n *\n * Remember that callbacks provided to `subscribe` are not guaranteed to be called asynchronously.\n * It is an Observable itself that decides when these functions will be called. For example {@link of}\n * by default emits all its values synchronously. Always check documentation for how given Observable\n * will behave when subscribed and if its default behavior can be modified with a `scheduler`.\n *\n * #### Examples\n *\n * Subscribe with an {@link guide/observer Observer}\n *\n * ```ts\n * import { of } from 'rxjs';\n *\n * const sumObserver = {\n * sum: 0,\n * next(value) {\n * console.log('Adding: ' + value);\n * this.sum = this.sum + value;\n * },\n * error() {\n * // We actually could just remove this method,\n * // since we do not really care about errors right now.\n * },\n * complete() {\n * console.log('Sum equals: ' + this.sum);\n * }\n * };\n *\n * of(1, 2, 3) // Synchronously emits 1, 2, 3 and then completes.\n * .subscribe(sumObserver);\n *\n * // Logs:\n * // 'Adding: 1'\n * // 'Adding: 2'\n * // 'Adding: 3'\n * // 'Sum equals: 6'\n * ```\n *\n * Subscribe with functions ({@link deprecations/subscribe-arguments deprecated})\n *\n * ```ts\n * import { of } from 'rxjs'\n *\n * let sum = 0;\n *\n * of(1, 2, 3).subscribe(\n * value => {\n * console.log('Adding: ' + value);\n * sum = sum + value;\n * },\n * undefined,\n * () => console.log('Sum equals: ' + sum)\n * );\n *\n * // Logs:\n * // 'Adding: 1'\n * // 'Adding: 2'\n * // 'Adding: 3'\n * // 'Sum equals: 6'\n * ```\n *\n * Cancel a subscription\n *\n * ```ts\n * import { interval } from 'rxjs';\n *\n * const subscription = interval(1000).subscribe({\n * next(num) {\n * console.log(num)\n * },\n * complete() {\n * // Will not be called, even when cancelling subscription.\n * console.log('completed!');\n * }\n * });\n *\n * setTimeout(() => {\n * subscription.unsubscribe();\n * console.log('unsubscribed!');\n * }, 2500);\n *\n * // Logs:\n * // 0 after 1s\n * // 1 after 2s\n * // 'unsubscribed!' after 2.5s\n * ```\n *\n * @param observerOrNext Either an {@link Observer} with some or all callback methods,\n * or the `next` handler that is called for each value emitted from the subscribed Observable.\n * @param error A handler for a terminal event resulting from an error. If no error handler is provided,\n * the error will be thrown asynchronously as unhandled.\n * @param complete A handler for a terminal event resulting from successful completion.\n * @return A subscription reference to the registered handlers.\n */\n subscribe(\n observerOrNext?: Partial> | ((value: T) => void) | null,\n error?: ((error: any) => void) | null,\n complete?: (() => void) | null\n ): Subscription {\n const subscriber = isSubscriber(observerOrNext) ? observerOrNext : new SafeSubscriber(observerOrNext, error, complete);\n\n errorContext(() => {\n const { operator, source } = this;\n subscriber.add(\n operator\n ? // We're dealing with a subscription in the\n // operator chain to one of our lifted operators.\n operator.call(subscriber, source)\n : source\n ? // If `source` has a value, but `operator` does not, something that\n // had intimate knowledge of our API, like our `Subject`, must have\n // set it. We're going to just call `_subscribe` directly.\n this._subscribe(subscriber)\n : // In all other cases, we're likely wrapping a user-provided initializer\n // function, so we need to catch errors and handle them appropriately.\n this._trySubscribe(subscriber)\n );\n });\n\n return subscriber;\n }\n\n /** @internal */\n protected _trySubscribe(sink: Subscriber): TeardownLogic {\n try {\n return this._subscribe(sink);\n } catch (err) {\n // We don't need to return anything in this case,\n // because it's just going to try to `add()` to a subscription\n // above.\n sink.error(err);\n }\n }\n\n /**\n * Used as a NON-CANCELLABLE means of subscribing to an observable, for use with\n * APIs that expect promises, like `async/await`. You cannot unsubscribe from this.\n *\n * **WARNING**: Only use this with observables you *know* will complete. If the source\n * observable does not complete, you will end up with a promise that is hung up, and\n * potentially all of the state of an async function hanging out in memory. To avoid\n * this situation, look into adding something like {@link timeout}, {@link take},\n * {@link takeWhile}, or {@link takeUntil} amongst others.\n *\n * #### Example\n *\n * ```ts\n * import { interval, take } from 'rxjs';\n *\n * const source$ = interval(1000).pipe(take(4));\n *\n * async function getTotal() {\n * let total = 0;\n *\n * await source$.forEach(value => {\n * total += value;\n * console.log('observable -> ' + value);\n * });\n *\n * return total;\n * }\n *\n * getTotal().then(\n * total => console.log('Total: ' + total)\n * );\n *\n * // Expected:\n * // 'observable -> 0'\n * // 'observable -> 1'\n * // 'observable -> 2'\n * // 'observable -> 3'\n * // 'Total: 6'\n * ```\n *\n * @param next A handler for each value emitted by the observable.\n * @return A promise that either resolves on observable completion or\n * rejects with the handled error.\n */\n forEach(next: (value: T) => void): Promise;\n\n /**\n * @param next a handler for each value emitted by the observable\n * @param promiseCtor a constructor function used to instantiate the Promise\n * @return a promise that either resolves on observable completion or\n * rejects with the handled error\n * @deprecated Passing a Promise constructor will no longer be available\n * in upcoming versions of RxJS. This is because it adds weight to the library, for very\n * little benefit. If you need this functionality, it is recommended that you either\n * polyfill Promise, or you create an adapter to convert the returned native promise\n * to whatever promise implementation you wanted. Will be removed in v8.\n */\n forEach(next: (value: T) => void, promiseCtor: PromiseConstructorLike): Promise;\n\n forEach(next: (value: T) => void, promiseCtor?: PromiseConstructorLike): Promise {\n promiseCtor = getPromiseCtor(promiseCtor);\n\n return new promiseCtor((resolve, reject) => {\n const subscriber = new SafeSubscriber({\n next: (value) => {\n try {\n next(value);\n } catch (err) {\n reject(err);\n subscriber.unsubscribe();\n }\n },\n error: reject,\n complete: resolve,\n });\n this.subscribe(subscriber);\n }) as Promise;\n }\n\n /** @internal */\n protected _subscribe(subscriber: Subscriber): TeardownLogic {\n return this.source?.subscribe(subscriber);\n }\n\n /**\n * An interop point defined by the es7-observable spec https://github.com/zenparsing/es-observable\n * @return This instance of the observable.\n */\n [Symbol_observable]() {\n return this;\n }\n\n /* tslint:disable:max-line-length */\n pipe(): Observable;\n pipe(op1: OperatorFunction): Observable;\n pipe(op1: OperatorFunction, op2: OperatorFunction): Observable;\n pipe(op1: OperatorFunction, op2: OperatorFunction, op3: OperatorFunction): Observable;\n pipe(\n op1: OperatorFunction,\n op2: OperatorFunction,\n op3: OperatorFunction,\n op4: OperatorFunction\n ): Observable;\n pipe(\n op1: OperatorFunction,\n op2: OperatorFunction,\n op3: OperatorFunction,\n op4: OperatorFunction,\n op5: OperatorFunction\n ): Observable;\n pipe(\n op1: OperatorFunction,\n op2: OperatorFunction,\n op3: OperatorFunction,\n op4: OperatorFunction,\n op5: OperatorFunction,\n op6: OperatorFunction\n ): Observable;\n pipe(\n op1: OperatorFunction,\n op2: OperatorFunction,\n op3: OperatorFunction,\n op4: OperatorFunction,\n op5: OperatorFunction,\n op6: OperatorFunction,\n op7: OperatorFunction\n ): Observable;\n pipe(\n op1: OperatorFunction,\n op2: OperatorFunction,\n op3: OperatorFunction,\n op4: OperatorFunction,\n op5: OperatorFunction,\n op6: OperatorFunction,\n op7: OperatorFunction,\n op8: OperatorFunction\n ): Observable;\n pipe(\n op1: OperatorFunction,\n op2: OperatorFunction,\n op3: OperatorFunction,\n op4: OperatorFunction,\n op5: OperatorFunction,\n op6: OperatorFunction,\n op7: OperatorFunction,\n op8: OperatorFunction,\n op9: OperatorFunction\n ): Observable;\n pipe(\n op1: OperatorFunction,\n op2: OperatorFunction,\n op3: OperatorFunction,\n op4: OperatorFunction,\n op5: OperatorFunction,\n op6: OperatorFunction,\n op7: OperatorFunction,\n op8: OperatorFunction,\n op9: OperatorFunction,\n ...operations: OperatorFunction[]\n ): Observable;\n /* tslint:enable:max-line-length */\n\n /**\n * Used to stitch together functional operators into a chain.\n *\n * ## Example\n *\n * ```ts\n * import { interval, filter, map, scan } from 'rxjs';\n *\n * interval(1000)\n * .pipe(\n * filter(x => x % 2 === 0),\n * map(x => x + x),\n * scan((acc, x) => acc + x)\n * )\n * .subscribe(x => console.log(x));\n * ```\n *\n * @return The Observable result of all the operators having been called\n * in the order they were passed in.\n */\n pipe(...operations: OperatorFunction[]): Observable {\n return pipeFromArray(operations)(this);\n }\n\n /* tslint:disable:max-line-length */\n /** @deprecated Replaced with {@link firstValueFrom} and {@link lastValueFrom}. Will be removed in v8. Details: https://rxjs.dev/deprecations/to-promise */\n toPromise(): Promise;\n /** @deprecated Replaced with {@link firstValueFrom} and {@link lastValueFrom}. Will be removed in v8. Details: https://rxjs.dev/deprecations/to-promise */\n toPromise(PromiseCtor: typeof Promise): Promise;\n /** @deprecated Replaced with {@link firstValueFrom} and {@link lastValueFrom}. Will be removed in v8. Details: https://rxjs.dev/deprecations/to-promise */\n toPromise(PromiseCtor: PromiseConstructorLike): Promise;\n /* tslint:enable:max-line-length */\n\n /**\n * Subscribe to this Observable and get a Promise resolving on\n * `complete` with the last emission (if any).\n *\n * **WARNING**: Only use this with observables you *know* will complete. If the source\n * observable does not complete, you will end up with a promise that is hung up, and\n * potentially all of the state of an async function hanging out in memory. To avoid\n * this situation, look into adding something like {@link timeout}, {@link take},\n * {@link takeWhile}, or {@link takeUntil} amongst others.\n *\n * @param [promiseCtor] a constructor function used to instantiate\n * the Promise\n * @return A Promise that resolves with the last value emit, or\n * rejects on an error. If there were no emissions, Promise\n * resolves with undefined.\n * @deprecated Replaced with {@link firstValueFrom} and {@link lastValueFrom}. Will be removed in v8. Details: https://rxjs.dev/deprecations/to-promise\n */\n toPromise(promiseCtor?: PromiseConstructorLike): Promise {\n promiseCtor = getPromiseCtor(promiseCtor);\n\n return new promiseCtor((resolve, reject) => {\n let value: T | undefined;\n this.subscribe(\n (x: T) => (value = x),\n (err: any) => reject(err),\n () => resolve(value)\n );\n }) as Promise;\n }\n}\n\n/**\n * Decides between a passed promise constructor from consuming code,\n * A default configured promise constructor, and the native promise\n * constructor and returns it. If nothing can be found, it will throw\n * an error.\n * @param promiseCtor The optional promise constructor to passed by consuming code\n */\nfunction getPromiseCtor(promiseCtor: PromiseConstructorLike | undefined) {\n return promiseCtor ?? config.Promise ?? Promise;\n}\n\nfunction isObserver(value: any): value is Observer {\n return value && isFunction(value.next) && isFunction(value.error) && isFunction(value.complete);\n}\n\nfunction isSubscriber(value: any): value is Subscriber {\n return (value && value instanceof Subscriber) || (isObserver(value) && isSubscription(value));\n}\n", "import { Observable } from '../Observable';\nimport { Subscriber } from '../Subscriber';\nimport { OperatorFunction } from '../types';\nimport { isFunction } from './isFunction';\n\n/**\n * Used to determine if an object is an Observable with a lift function.\n */\nexport function hasLift(source: any): source is { lift: InstanceType['lift'] } {\n return isFunction(source?.lift);\n}\n\n/**\n * Creates an `OperatorFunction`. Used to define operators throughout the library in a concise way.\n * @param init The logic to connect the liftedSource to the subscriber at the moment of subscription.\n */\nexport function operate(\n init: (liftedSource: Observable, subscriber: Subscriber) => (() => void) | void\n): OperatorFunction {\n return (source: Observable) => {\n if (hasLift(source)) {\n return source.lift(function (this: Subscriber, liftedSource: Observable) {\n try {\n return init(liftedSource, this);\n } catch (err) {\n this.error(err);\n }\n });\n }\n throw new TypeError('Unable to lift unknown Observable type');\n };\n}\n", "import { Subscriber } from '../Subscriber';\n\n/**\n * Creates an instance of an `OperatorSubscriber`.\n * @param destination The downstream subscriber.\n * @param onNext Handles next values, only called if this subscriber is not stopped or closed. Any\n * error that occurs in this function is caught and sent to the `error` method of this subscriber.\n * @param onError Handles errors from the subscription, any errors that occur in this handler are caught\n * and send to the `destination` error handler.\n * @param onComplete Handles completion notification from the subscription. Any errors that occur in\n * this handler are sent to the `destination` error handler.\n * @param onFinalize Additional teardown logic here. This will only be called on teardown if the\n * subscriber itself is not already closed. This is called after all other teardown logic is executed.\n */\nexport function createOperatorSubscriber(\n destination: Subscriber,\n onNext?: (value: T) => void,\n onComplete?: () => void,\n onError?: (err: any) => void,\n onFinalize?: () => void\n): Subscriber {\n return new OperatorSubscriber(destination, onNext, onComplete, onError, onFinalize);\n}\n\n/**\n * A generic helper for allowing operators to be created with a Subscriber and\n * use closures to capture necessary state from the operator function itself.\n */\nexport class OperatorSubscriber extends Subscriber {\n /**\n * Creates an instance of an `OperatorSubscriber`.\n * @param destination The downstream subscriber.\n * @param onNext Handles next values, only called if this subscriber is not stopped or closed. Any\n * error that occurs in this function is caught and sent to the `error` method of this subscriber.\n * @param onError Handles errors from the subscription, any errors that occur in this handler are caught\n * and send to the `destination` error handler.\n * @param onComplete Handles completion notification from the subscription. Any errors that occur in\n * this handler are sent to the `destination` error handler.\n * @param onFinalize Additional finalization logic here. This will only be called on finalization if the\n * subscriber itself is not already closed. This is called after all other finalization logic is executed.\n * @param shouldUnsubscribe An optional check to see if an unsubscribe call should truly unsubscribe.\n * NOTE: This currently **ONLY** exists to support the strange behavior of {@link groupBy}, where unsubscription\n * to the resulting observable does not actually disconnect from the source if there are active subscriptions\n * to any grouped observable. (DO NOT EXPOSE OR USE EXTERNALLY!!!)\n */\n constructor(\n destination: Subscriber,\n onNext?: (value: T) => void,\n onComplete?: () => void,\n onError?: (err: any) => void,\n private onFinalize?: () => void,\n private shouldUnsubscribe?: () => boolean\n ) {\n // It's important - for performance reasons - that all of this class's\n // members are initialized and that they are always initialized in the same\n // order. This will ensure that all OperatorSubscriber instances have the\n // same hidden class in V8. This, in turn, will help keep the number of\n // hidden classes involved in property accesses within the base class as\n // low as possible. If the number of hidden classes involved exceeds four,\n // the property accesses will become megamorphic and performance penalties\n // will be incurred - i.e. inline caches won't be used.\n //\n // The reasons for ensuring all instances have the same hidden class are\n // further discussed in this blog post from Benedikt Meurer:\n // https://benediktmeurer.de/2018/03/23/impact-of-polymorphism-on-component-based-frameworks-like-react/\n super(destination);\n this._next = onNext\n ? function (this: OperatorSubscriber, value: T) {\n try {\n onNext(value);\n } catch (err) {\n destination.error(err);\n }\n }\n : super._next;\n this._error = onError\n ? function (this: OperatorSubscriber, err: any) {\n try {\n onError(err);\n } catch (err) {\n // Send any errors that occur down stream.\n destination.error(err);\n } finally {\n // Ensure finalization.\n this.unsubscribe();\n }\n }\n : super._error;\n this._complete = onComplete\n ? function (this: OperatorSubscriber) {\n try {\n onComplete();\n } catch (err) {\n // Send any errors that occur down stream.\n destination.error(err);\n } finally {\n // Ensure finalization.\n this.unsubscribe();\n }\n }\n : super._complete;\n }\n\n unsubscribe() {\n if (!this.shouldUnsubscribe || this.shouldUnsubscribe()) {\n const { closed } = this;\n super.unsubscribe();\n // Execute additional teardown if we have any and we didn't already do so.\n !closed && this.onFinalize?.();\n }\n }\n}\n", "import { ConnectableObservable } from '../observable/ConnectableObservable';\nimport { Subscription } from '../Subscription';\nimport { MonoTypeOperatorFunction } from '../types';\nimport { operate } from '../util/lift';\nimport { createOperatorSubscriber } from './OperatorSubscriber';\n\n/**\n * Make a {@link ConnectableObservable} behave like a ordinary observable and automates the way\n * you can connect to it.\n *\n * Internally it counts the subscriptions to the observable and subscribes (only once) to the source if\n * the number of subscriptions is larger than 0. If the number of subscriptions is smaller than 1, it\n * unsubscribes from the source. This way you can make sure that everything before the *published*\n * refCount has only a single subscription independently of the number of subscribers to the target\n * observable.\n *\n * Note that using the {@link share} operator is exactly the same as using the `multicast(() => new Subject())` operator\n * (making the observable hot) and the *refCount* operator in a sequence.\n *\n * ![](refCount.png)\n *\n * ## Example\n *\n * In the following example there are two intervals turned into connectable observables\n * by using the *publish* operator. The first one uses the *refCount* operator, the\n * second one does not use it. You will notice that a connectable observable does nothing\n * until you call its connect function.\n *\n * ```ts\n * import { interval, tap, publish, refCount } from 'rxjs';\n *\n * // Turn the interval observable into a ConnectableObservable (hot)\n * const refCountInterval = interval(400).pipe(\n * tap(num => console.log(`refCount ${ num }`)),\n * publish(),\n * refCount()\n * );\n *\n * const publishedInterval = interval(400).pipe(\n * tap(num => console.log(`publish ${ num }`)),\n * publish()\n * );\n *\n * refCountInterval.subscribe();\n * refCountInterval.subscribe();\n * // 'refCount 0' -----> 'refCount 1' -----> etc\n * // All subscriptions will receive the same value and the tap (and\n * // every other operator) before the `publish` operator will be executed\n * // only once per event independently of the number of subscriptions.\n *\n * publishedInterval.subscribe();\n * // Nothing happens until you call .connect() on the observable.\n * ```\n *\n * @return A function that returns an Observable that automates the connection\n * to ConnectableObservable.\n * @see {@link ConnectableObservable}\n * @see {@link share}\n * @see {@link publish}\n * @deprecated Replaced with the {@link share} operator. How `share` is used\n * will depend on the connectable observable you created just prior to the\n * `refCount` operator.\n * Details: https://rxjs.dev/deprecations/multicasting\n */\nexport function refCount(): MonoTypeOperatorFunction {\n return operate((source, subscriber) => {\n let connection: Subscription | null = null;\n\n (source as any)._refCount++;\n\n const refCounter = createOperatorSubscriber(subscriber, undefined, undefined, undefined, () => {\n if (!source || (source as any)._refCount <= 0 || 0 < --(source as any)._refCount) {\n connection = null;\n return;\n }\n\n ///\n // Compare the local RefCountSubscriber's connection Subscription to the\n // connection Subscription on the shared ConnectableObservable. In cases\n // where the ConnectableObservable source synchronously emits values, and\n // the RefCountSubscriber's downstream Observers synchronously unsubscribe,\n // execution continues to here before the RefCountOperator has a chance to\n // supply the RefCountSubscriber with the shared connection Subscription.\n // For example:\n // ```\n // range(0, 10).pipe(\n // publish(),\n // refCount(),\n // take(5),\n // )\n // .subscribe();\n // ```\n // In order to account for this case, RefCountSubscriber should only dispose\n // the ConnectableObservable's shared connection Subscription if the\n // connection Subscription exists, *and* either:\n // a. RefCountSubscriber doesn't have a reference to the shared connection\n // Subscription yet, or,\n // b. RefCountSubscriber's connection Subscription reference is identical\n // to the shared connection Subscription\n ///\n\n const sharedConnection = (source as any)._connection;\n const conn = connection;\n connection = null;\n\n if (sharedConnection && (!conn || sharedConnection === conn)) {\n sharedConnection.unsubscribe();\n }\n\n subscriber.unsubscribe();\n });\n\n source.subscribe(refCounter);\n\n if (!refCounter.closed) {\n connection = (source as ConnectableObservable).connect();\n }\n });\n}\n", "import { Subject } from '../Subject';\nimport { Observable } from '../Observable';\nimport { Subscriber } from '../Subscriber';\nimport { Subscription } from '../Subscription';\nimport { refCount as higherOrderRefCount } from '../operators/refCount';\nimport { createOperatorSubscriber } from '../operators/OperatorSubscriber';\nimport { hasLift } from '../util/lift';\n\n/**\n * @class ConnectableObservable\n * @deprecated Will be removed in v8. Use {@link connectable} to create a connectable observable.\n * If you are using the `refCount` method of `ConnectableObservable`, use the {@link share} operator\n * instead.\n * Details: https://rxjs.dev/deprecations/multicasting\n */\nexport class ConnectableObservable extends Observable {\n protected _subject: Subject | null = null;\n protected _refCount: number = 0;\n protected _connection: Subscription | null = null;\n\n /**\n * @param source The source observable\n * @param subjectFactory The factory that creates the subject used internally.\n * @deprecated Will be removed in v8. Use {@link connectable} to create a connectable observable.\n * `new ConnectableObservable(source, factory)` is equivalent to\n * `connectable(source, { connector: factory })`.\n * When the `refCount()` method is needed, the {@link share} operator should be used instead:\n * `new ConnectableObservable(source, factory).refCount()` is equivalent to\n * `source.pipe(share({ connector: factory }))`.\n * Details: https://rxjs.dev/deprecations/multicasting\n */\n constructor(public source: Observable, protected subjectFactory: () => Subject) {\n super();\n // If we have lift, monkey patch that here. This is done so custom observable\n // types will compose through multicast. Otherwise the resulting observable would\n // simply be an instance of `ConnectableObservable`.\n if (hasLift(source)) {\n this.lift = source.lift;\n }\n }\n\n /** @internal */\n protected _subscribe(subscriber: Subscriber) {\n return this.getSubject().subscribe(subscriber);\n }\n\n protected getSubject(): Subject {\n const subject = this._subject;\n if (!subject || subject.isStopped) {\n this._subject = this.subjectFactory();\n }\n return this._subject!;\n }\n\n protected _teardown() {\n this._refCount = 0;\n const { _connection } = this;\n this._subject = this._connection = null;\n _connection?.unsubscribe();\n }\n\n /**\n * @deprecated {@link ConnectableObservable} will be removed in v8. Use {@link connectable} instead.\n * Details: https://rxjs.dev/deprecations/multicasting\n */\n connect(): Subscription {\n let connection = this._connection;\n if (!connection) {\n connection = this._connection = new Subscription();\n const subject = this.getSubject();\n connection.add(\n this.source.subscribe(\n createOperatorSubscriber(\n subject as any,\n undefined,\n () => {\n this._teardown();\n subject.complete();\n },\n (err) => {\n this._teardown();\n subject.error(err);\n },\n () => this._teardown()\n )\n )\n );\n\n if (connection.closed) {\n this._connection = null;\n connection = Subscription.EMPTY;\n }\n }\n return connection;\n }\n\n /**\n * @deprecated {@link ConnectableObservable} will be removed in v8. Use the {@link share} operator instead.\n * Details: https://rxjs.dev/deprecations/multicasting\n */\n refCount(): Observable {\n return higherOrderRefCount()(this) as Observable;\n }\n}\n", "import { TimestampProvider } from '../types';\n\ninterface PerformanceTimestampProvider extends TimestampProvider {\n delegate: TimestampProvider | undefined;\n}\n\nexport const performanceTimestampProvider: PerformanceTimestampProvider = {\n now() {\n // Use the variable rather than `this` so that the function can be called\n // without being bound to the provider.\n return (performanceTimestampProvider.delegate || performance).now();\n },\n delegate: undefined,\n};\n", "import { Subscription } from '../Subscription';\n\ninterface AnimationFrameProvider {\n schedule(callback: FrameRequestCallback): Subscription;\n requestAnimationFrame: typeof requestAnimationFrame;\n cancelAnimationFrame: typeof cancelAnimationFrame;\n delegate:\n | {\n requestAnimationFrame: typeof requestAnimationFrame;\n cancelAnimationFrame: typeof cancelAnimationFrame;\n }\n | undefined;\n}\n\nexport const animationFrameProvider: AnimationFrameProvider = {\n // When accessing the delegate, use the variable rather than `this` so that\n // the functions can be called without being bound to the provider.\n schedule(callback) {\n let request = requestAnimationFrame;\n let cancel: typeof cancelAnimationFrame | undefined = cancelAnimationFrame;\n const { delegate } = animationFrameProvider;\n if (delegate) {\n request = delegate.requestAnimationFrame;\n cancel = delegate.cancelAnimationFrame;\n }\n const handle = request((timestamp) => {\n // Clear the cancel function. The request has been fulfilled, so\n // attempting to cancel the request upon unsubscription would be\n // pointless.\n cancel = undefined;\n callback(timestamp);\n });\n return new Subscription(() => cancel?.(handle));\n },\n requestAnimationFrame(...args) {\n const { delegate } = animationFrameProvider;\n return (delegate?.requestAnimationFrame || requestAnimationFrame)(...args);\n },\n cancelAnimationFrame(...args) {\n const { delegate } = animationFrameProvider;\n return (delegate?.cancelAnimationFrame || cancelAnimationFrame)(...args);\n },\n delegate: undefined,\n};\n", "import { Observable } from '../../Observable';\nimport { TimestampProvider } from '../../types';\nimport { performanceTimestampProvider } from '../../scheduler/performanceTimestampProvider';\nimport { animationFrameProvider } from '../../scheduler/animationFrameProvider';\n\n/**\n * An observable of animation frames\n *\n * Emits the amount of time elapsed since subscription and the timestamp on each animation frame.\n * Defaults to milliseconds provided to the requestAnimationFrame's callback. Does not end on its own.\n *\n * Every subscription will start a separate animation loop. Since animation frames are always scheduled\n * by the browser to occur directly before a repaint, scheduling more than one animation frame synchronously\n * should not be much different or have more overhead than looping over an array of events during\n * a single animation frame. However, if for some reason the developer would like to ensure the\n * execution of animation-related handlers are all executed during the same task by the engine,\n * the `share` operator can be used.\n *\n * This is useful for setting up animations with RxJS.\n *\n * ## Examples\n *\n * Tweening a div to move it on the screen\n *\n * ```ts\n * import { animationFrames, map, takeWhile, endWith } from 'rxjs';\n *\n * function tween(start: number, end: number, duration: number) {\n * const diff = end - start;\n * return animationFrames().pipe(\n * // Figure out what percentage of time has passed\n * map(({ elapsed }) => elapsed / duration),\n * // Take the vector while less than 100%\n * takeWhile(v => v < 1),\n * // Finish with 100%\n * endWith(1),\n * // Calculate the distance traveled between start and end\n * map(v => v * diff + start)\n * );\n * }\n *\n * // Setup a div for us to move around\n * const div = document.createElement('div');\n * document.body.appendChild(div);\n * div.style.position = 'absolute';\n * div.style.width = '40px';\n * div.style.height = '40px';\n * div.style.backgroundColor = 'lime';\n * div.style.transform = 'translate3d(10px, 0, 0)';\n *\n * tween(10, 200, 4000).subscribe(x => {\n * div.style.transform = `translate3d(${ x }px, 0, 0)`;\n * });\n * ```\n *\n * Providing a custom timestamp provider\n *\n * ```ts\n * import { animationFrames, TimestampProvider } from 'rxjs';\n *\n * // A custom timestamp provider\n * let now = 0;\n * const customTSProvider: TimestampProvider = {\n * now() { return now++; }\n * };\n *\n * const source$ = animationFrames(customTSProvider);\n *\n * // Log increasing numbers 0...1...2... on every animation frame.\n * source$.subscribe(({ elapsed }) => console.log(elapsed));\n * ```\n *\n * @param timestampProvider An object with a `now` method that provides a numeric timestamp\n */\nexport function animationFrames(timestampProvider?: TimestampProvider) {\n return timestampProvider ? animationFramesFactory(timestampProvider) : DEFAULT_ANIMATION_FRAMES;\n}\n\n/**\n * Does the work of creating the observable for `animationFrames`.\n * @param timestampProvider The timestamp provider to use to create the observable\n */\nfunction animationFramesFactory(timestampProvider?: TimestampProvider) {\n return new Observable<{ timestamp: number; elapsed: number }>((subscriber) => {\n // If no timestamp provider is specified, use performance.now() - as it\n // will return timestamps 'compatible' with those passed to the run\n // callback and won't be affected by NTP adjustments, etc.\n const provider = timestampProvider || performanceTimestampProvider;\n\n // Capture the start time upon subscription, as the run callback can remain\n // queued for a considerable period of time and the elapsed time should\n // represent the time elapsed since subscription - not the time since the\n // first rendered animation frame.\n const start = provider.now();\n\n let id = 0;\n const run = () => {\n if (!subscriber.closed) {\n id = animationFrameProvider.requestAnimationFrame((timestamp: DOMHighResTimeStamp | number) => {\n id = 0;\n // Use the provider's timestamp to calculate the elapsed time. Note that\n // this means - if the caller hasn't passed a provider - that\n // performance.now() will be used instead of the timestamp that was\n // passed to the run callback. The reason for this is that the timestamp\n // passed to the callback can be earlier than the start time, as it\n // represents the time at which the browser decided it would render any\n // queued frames - and that time can be earlier the captured start time.\n const now = provider.now();\n subscriber.next({\n timestamp: timestampProvider ? now : timestamp,\n elapsed: now - start,\n });\n run();\n });\n }\n };\n\n run();\n\n return () => {\n if (id) {\n animationFrameProvider.cancelAnimationFrame(id);\n }\n };\n });\n}\n\n/**\n * In the common case, where the timestamp provided by the rAF API is used,\n * we use this shared observable to reduce overhead.\n */\nconst DEFAULT_ANIMATION_FRAMES = animationFramesFactory();\n", "import { createErrorClass } from './createErrorClass';\n\nexport interface ObjectUnsubscribedError extends Error {}\n\nexport interface ObjectUnsubscribedErrorCtor {\n /**\n * @deprecated Internal implementation detail. Do not construct error instances.\n * Cannot be tagged as internal: https://github.com/ReactiveX/rxjs/issues/6269\n */\n new (): ObjectUnsubscribedError;\n}\n\n/**\n * An error thrown when an action is invalid because the object has been\n * unsubscribed.\n *\n * @see {@link Subject}\n * @see {@link BehaviorSubject}\n *\n * @class ObjectUnsubscribedError\n */\nexport const ObjectUnsubscribedError: ObjectUnsubscribedErrorCtor = createErrorClass(\n (_super) =>\n function ObjectUnsubscribedErrorImpl(this: any) {\n _super(this);\n this.name = 'ObjectUnsubscribedError';\n this.message = 'object unsubscribed';\n }\n);\n", "import { Operator } from './Operator';\nimport { Observable } from './Observable';\nimport { Subscriber } from './Subscriber';\nimport { Subscription, EMPTY_SUBSCRIPTION } from './Subscription';\nimport { Observer, SubscriptionLike, TeardownLogic } from './types';\nimport { ObjectUnsubscribedError } from './util/ObjectUnsubscribedError';\nimport { arrRemove } from './util/arrRemove';\nimport { errorContext } from './util/errorContext';\n\n/**\n * A Subject is a special type of Observable that allows values to be\n * multicasted to many Observers. Subjects are like EventEmitters.\n *\n * Every Subject is an Observable and an Observer. You can subscribe to a\n * Subject, and you can call next to feed values as well as error and complete.\n */\nexport class Subject extends Observable implements SubscriptionLike {\n closed = false;\n\n private currentObservers: Observer[] | null = null;\n\n /** @deprecated Internal implementation detail, do not use directly. Will be made internal in v8. */\n observers: Observer[] = [];\n /** @deprecated Internal implementation detail, do not use directly. Will be made internal in v8. */\n isStopped = false;\n /** @deprecated Internal implementation detail, do not use directly. Will be made internal in v8. */\n hasError = false;\n /** @deprecated Internal implementation detail, do not use directly. Will be made internal in v8. */\n thrownError: any = null;\n\n /**\n * Creates a \"subject\" by basically gluing an observer to an observable.\n *\n * @deprecated Recommended you do not use. Will be removed at some point in the future. Plans for replacement still under discussion.\n */\n static create: (...args: any[]) => any = (destination: Observer, source: Observable): AnonymousSubject => {\n return new AnonymousSubject(destination, source);\n };\n\n constructor() {\n // NOTE: This must be here to obscure Observable's constructor.\n super();\n }\n\n /** @deprecated Internal implementation detail, do not use directly. Will be made internal in v8. */\n lift(operator: Operator): Observable {\n const subject = new AnonymousSubject(this, this);\n subject.operator = operator as any;\n return subject as any;\n }\n\n /** @internal */\n protected _throwIfClosed() {\n if (this.closed) {\n throw new ObjectUnsubscribedError();\n }\n }\n\n next(value: T) {\n errorContext(() => {\n this._throwIfClosed();\n if (!this.isStopped) {\n if (!this.currentObservers) {\n this.currentObservers = Array.from(this.observers);\n }\n for (const observer of this.currentObservers) {\n observer.next(value);\n }\n }\n });\n }\n\n error(err: any) {\n errorContext(() => {\n this._throwIfClosed();\n if (!this.isStopped) {\n this.hasError = this.isStopped = true;\n this.thrownError = err;\n const { observers } = this;\n while (observers.length) {\n observers.shift()!.error(err);\n }\n }\n });\n }\n\n complete() {\n errorContext(() => {\n this._throwIfClosed();\n if (!this.isStopped) {\n this.isStopped = true;\n const { observers } = this;\n while (observers.length) {\n observers.shift()!.complete();\n }\n }\n });\n }\n\n unsubscribe() {\n this.isStopped = this.closed = true;\n this.observers = this.currentObservers = null!;\n }\n\n get observed() {\n return this.observers?.length > 0;\n }\n\n /** @internal */\n protected _trySubscribe(subscriber: Subscriber): TeardownLogic {\n this._throwIfClosed();\n return super._trySubscribe(subscriber);\n }\n\n /** @internal */\n protected _subscribe(subscriber: Subscriber): Subscription {\n this._throwIfClosed();\n this._checkFinalizedStatuses(subscriber);\n return this._innerSubscribe(subscriber);\n }\n\n /** @internal */\n protected _innerSubscribe(subscriber: Subscriber) {\n const { hasError, isStopped, observers } = this;\n if (hasError || isStopped) {\n return EMPTY_SUBSCRIPTION;\n }\n this.currentObservers = null;\n observers.push(subscriber);\n return new Subscription(() => {\n this.currentObservers = null;\n arrRemove(observers, subscriber);\n });\n }\n\n /** @internal */\n protected _checkFinalizedStatuses(subscriber: Subscriber) {\n const { hasError, thrownError, isStopped } = this;\n if (hasError) {\n subscriber.error(thrownError);\n } else if (isStopped) {\n subscriber.complete();\n }\n }\n\n /**\n * Creates a new Observable with this Subject as the source. You can do this\n * to create custom Observer-side logic of the Subject and conceal it from\n * code that uses the Observable.\n * @return Observable that this Subject casts to.\n */\n asObservable(): Observable {\n const observable: any = new Observable();\n observable.source = this;\n return observable;\n }\n}\n\nexport class AnonymousSubject extends Subject {\n constructor(\n /** @deprecated Internal implementation detail, do not use directly. Will be made internal in v8. */\n public destination?: Observer,\n source?: Observable\n ) {\n super();\n this.source = source;\n }\n\n next(value: T) {\n this.destination?.next?.(value);\n }\n\n error(err: any) {\n this.destination?.error?.(err);\n }\n\n complete() {\n this.destination?.complete?.();\n }\n\n /** @internal */\n protected _subscribe(subscriber: Subscriber): Subscription {\n return this.source?.subscribe(subscriber) ?? EMPTY_SUBSCRIPTION;\n }\n}\n", "import { Subject } from './Subject';\nimport { Subscriber } from './Subscriber';\nimport { Subscription } from './Subscription';\n\n/**\n * A variant of Subject that requires an initial value and emits its current\n * value whenever it is subscribed to.\n */\nexport class BehaviorSubject extends Subject {\n constructor(private _value: T) {\n super();\n }\n\n get value(): T {\n return this.getValue();\n }\n\n /** @internal */\n protected _subscribe(subscriber: Subscriber): Subscription {\n const subscription = super._subscribe(subscriber);\n !subscription.closed && subscriber.next(this._value);\n return subscription;\n }\n\n getValue(): T {\n const { hasError, thrownError, _value } = this;\n if (hasError) {\n throw thrownError;\n }\n this._throwIfClosed();\n return _value;\n }\n\n next(value: T): void {\n super.next((this._value = value));\n }\n}\n", "import { TimestampProvider } from '../types';\n\ninterface DateTimestampProvider extends TimestampProvider {\n delegate: TimestampProvider | undefined;\n}\n\nexport const dateTimestampProvider: DateTimestampProvider = {\n now() {\n // Use the variable rather than `this` so that the function can be called\n // without being bound to the provider.\n return (dateTimestampProvider.delegate || Date).now();\n },\n delegate: undefined,\n};\n", "import { Subject } from './Subject';\nimport { TimestampProvider } from './types';\nimport { Subscriber } from './Subscriber';\nimport { Subscription } from './Subscription';\nimport { dateTimestampProvider } from './scheduler/dateTimestampProvider';\n\n/**\n * A variant of {@link Subject} that \"replays\" old values to new subscribers by emitting them when they first subscribe.\n *\n * `ReplaySubject` has an internal buffer that will store a specified number of values that it has observed. Like `Subject`,\n * `ReplaySubject` \"observes\" values by having them passed to its `next` method. When it observes a value, it will store that\n * value for a time determined by the configuration of the `ReplaySubject`, as passed to its constructor.\n *\n * When a new subscriber subscribes to the `ReplaySubject` instance, it will synchronously emit all values in its buffer in\n * a First-In-First-Out (FIFO) manner. The `ReplaySubject` will also complete, if it has observed completion; and it will\n * error if it has observed an error.\n *\n * There are two main configuration items to be concerned with:\n *\n * 1. `bufferSize` - This will determine how many items are stored in the buffer, defaults to infinite.\n * 2. `windowTime` - The amount of time to hold a value in the buffer before removing it from the buffer.\n *\n * Both configurations may exist simultaneously. So if you would like to buffer a maximum of 3 values, as long as the values\n * are less than 2 seconds old, you could do so with a `new ReplaySubject(3, 2000)`.\n *\n * ### Differences with BehaviorSubject\n *\n * `BehaviorSubject` is similar to `new ReplaySubject(1)`, with a couple of exceptions:\n *\n * 1. `BehaviorSubject` comes \"primed\" with a single value upon construction.\n * 2. `ReplaySubject` will replay values, even after observing an error, where `BehaviorSubject` will not.\n *\n * @see {@link Subject}\n * @see {@link BehaviorSubject}\n * @see {@link shareReplay}\n */\nexport class ReplaySubject extends Subject {\n private _buffer: (T | number)[] = [];\n private _infiniteTimeWindow = true;\n\n /**\n * @param _bufferSize The size of the buffer to replay on subscription\n * @param _windowTime The amount of time the buffered items will stay buffered\n * @param _timestampProvider An object with a `now()` method that provides the current timestamp. This is used to\n * calculate the amount of time something has been buffered.\n */\n constructor(\n private _bufferSize = Infinity,\n private _windowTime = Infinity,\n private _timestampProvider: TimestampProvider = dateTimestampProvider\n ) {\n super();\n this._infiniteTimeWindow = _windowTime === Infinity;\n this._bufferSize = Math.max(1, _bufferSize);\n this._windowTime = Math.max(1, _windowTime);\n }\n\n next(value: T): void {\n const { isStopped, _buffer, _infiniteTimeWindow, _timestampProvider, _windowTime } = this;\n if (!isStopped) {\n _buffer.push(value);\n !_infiniteTimeWindow && _buffer.push(_timestampProvider.now() + _windowTime);\n }\n this._trimBuffer();\n super.next(value);\n }\n\n /** @internal */\n protected _subscribe(subscriber: Subscriber): Subscription {\n this._throwIfClosed();\n this._trimBuffer();\n\n const subscription = this._innerSubscribe(subscriber);\n\n const { _infiniteTimeWindow, _buffer } = this;\n // We use a copy here, so reentrant code does not mutate our array while we're\n // emitting it to a new subscriber.\n const copy = _buffer.slice();\n for (let i = 0; i < copy.length && !subscriber.closed; i += _infiniteTimeWindow ? 1 : 2) {\n subscriber.next(copy[i] as T);\n }\n\n this._checkFinalizedStatuses(subscriber);\n\n return subscription;\n }\n\n private _trimBuffer() {\n const { _bufferSize, _timestampProvider, _buffer, _infiniteTimeWindow } = this;\n // If we don't have an infinite buffer size, and we're over the length,\n // use splice to truncate the old buffer values off. Note that we have to\n // double the size for instances where we're not using an infinite time window\n // because we're storing the values and the timestamps in the same array.\n const adjustedBufferSize = (_infiniteTimeWindow ? 1 : 2) * _bufferSize;\n _bufferSize < Infinity && adjustedBufferSize < _buffer.length && _buffer.splice(0, _buffer.length - adjustedBufferSize);\n\n // Now, if we're not in an infinite time window, remove all values where the time is\n // older than what is allowed.\n if (!_infiniteTimeWindow) {\n const now = _timestampProvider.now();\n let last = 0;\n // Search the array for the first timestamp that isn't expired and\n // truncate the buffer up to that point.\n for (let i = 1; i < _buffer.length && (_buffer[i] as number) <= now; i += 2) {\n last = i;\n }\n last && _buffer.splice(0, last + 1);\n }\n }\n}\n", "import { Subject } from './Subject';\nimport { Subscriber } from './Subscriber';\n\n/**\n * A variant of Subject that only emits a value when it completes. It will emit\n * its latest value to all its observers on completion.\n */\nexport class AsyncSubject extends Subject {\n private _value: T | null = null;\n private _hasValue = false;\n private _isComplete = false;\n\n /** @internal */\n protected _checkFinalizedStatuses(subscriber: Subscriber) {\n const { hasError, _hasValue, _value, thrownError, isStopped, _isComplete } = this;\n if (hasError) {\n subscriber.error(thrownError);\n } else if (isStopped || _isComplete) {\n _hasValue && subscriber.next(_value!);\n subscriber.complete();\n }\n }\n\n next(value: T): void {\n if (!this.isStopped) {\n this._value = value;\n this._hasValue = true;\n }\n }\n\n complete(): void {\n const { _hasValue, _value, _isComplete } = this;\n if (!_isComplete) {\n this._isComplete = true;\n _hasValue && super.next(_value!);\n super.complete();\n }\n }\n}\n", "import { Scheduler } from '../Scheduler';\nimport { Subscription } from '../Subscription';\nimport { SchedulerAction } from '../types';\n\n/**\n * A unit of work to be executed in a `scheduler`. An action is typically\n * created from within a {@link SchedulerLike} and an RxJS user does not need to concern\n * themselves about creating and manipulating an Action.\n *\n * ```ts\n * class Action extends Subscription {\n * new (scheduler: Scheduler, work: (state?: T) => void);\n * schedule(state?: T, delay: number = 0): Subscription;\n * }\n * ```\n */\nexport class Action extends Subscription {\n constructor(scheduler: Scheduler, work: (this: SchedulerAction, state?: T) => void) {\n super();\n }\n /**\n * Schedules this action on its parent {@link SchedulerLike} for execution. May be passed\n * some context object, `state`. May happen at some point in the future,\n * according to the `delay` parameter, if specified.\n * @param state Some contextual data that the `work` function uses when called by the\n * Scheduler.\n * @param delay Time to wait before executing the work, where the time unit is implicit\n * and defined by the Scheduler.\n * @return A subscription in order to be able to unsubscribe the scheduled work.\n */\n public schedule(state?: T, delay: number = 0): Subscription {\n return this;\n }\n}\n", "import type { TimerHandle } from './timerHandle';\ntype SetIntervalFunction = (handler: () => void, timeout?: number, ...args: any[]) => TimerHandle;\ntype ClearIntervalFunction = (handle: TimerHandle) => void;\n\ninterface IntervalProvider {\n setInterval: SetIntervalFunction;\n clearInterval: ClearIntervalFunction;\n delegate:\n | {\n setInterval: SetIntervalFunction;\n clearInterval: ClearIntervalFunction;\n }\n | undefined;\n}\n\nexport const intervalProvider: IntervalProvider = {\n // When accessing the delegate, use the variable rather than `this` so that\n // the functions can be called without being bound to the provider.\n setInterval(handler: () => void, timeout?: number, ...args) {\n const { delegate } = intervalProvider;\n if (delegate?.setInterval) {\n return delegate.setInterval(handler, timeout, ...args);\n }\n return setInterval(handler, timeout, ...args);\n },\n clearInterval(handle) {\n const { delegate } = intervalProvider;\n return (delegate?.clearInterval || clearInterval)(handle as any);\n },\n delegate: undefined,\n};\n", "import { Action } from './Action';\nimport { SchedulerAction } from '../types';\nimport { Subscription } from '../Subscription';\nimport { AsyncScheduler } from './AsyncScheduler';\nimport { intervalProvider } from './intervalProvider';\nimport { arrRemove } from '../util/arrRemove';\nimport { TimerHandle } from './timerHandle';\n\nexport class AsyncAction extends Action {\n public id: TimerHandle | undefined;\n public state?: T;\n // @ts-ignore: Property has no initializer and is not definitely assigned\n public delay: number;\n protected pending: boolean = false;\n\n constructor(protected scheduler: AsyncScheduler, protected work: (this: SchedulerAction, state?: T) => void) {\n super(scheduler, work);\n }\n\n public schedule(state?: T, delay: number = 0): Subscription {\n if (this.closed) {\n return this;\n }\n\n // Always replace the current state with the new state.\n this.state = state;\n\n const id = this.id;\n const scheduler = this.scheduler;\n\n //\n // Important implementation note:\n //\n // Actions only execute once by default, unless rescheduled from within the\n // scheduled callback. This allows us to implement single and repeat\n // actions via the same code path, without adding API surface area, as well\n // as mimic traditional recursion but across asynchronous boundaries.\n //\n // However, JS runtimes and timers distinguish between intervals achieved by\n // serial `setTimeout` calls vs. a single `setInterval` call. An interval of\n // serial `setTimeout` calls can be individually delayed, which delays\n // scheduling the next `setTimeout`, and so on. `setInterval` attempts to\n // guarantee the interval callback will be invoked more precisely to the\n // interval period, regardless of load.\n //\n // Therefore, we use `setInterval` to schedule single and repeat actions.\n // If the action reschedules itself with the same delay, the interval is not\n // canceled. If the action doesn't reschedule, or reschedules with a\n // different delay, the interval will be canceled after scheduled callback\n // execution.\n //\n if (id != null) {\n this.id = this.recycleAsyncId(scheduler, id, delay);\n }\n\n // Set the pending flag indicating that this action has been scheduled, or\n // has recursively rescheduled itself.\n this.pending = true;\n\n this.delay = delay;\n // If this action has already an async Id, don't request a new one.\n this.id = this.id ?? this.requestAsyncId(scheduler, this.id, delay);\n\n return this;\n }\n\n protected requestAsyncId(scheduler: AsyncScheduler, _id?: TimerHandle, delay: number = 0): TimerHandle {\n return intervalProvider.setInterval(scheduler.flush.bind(scheduler, this), delay);\n }\n\n protected recycleAsyncId(_scheduler: AsyncScheduler, id?: TimerHandle, delay: number | null = 0): TimerHandle | undefined {\n // If this action is rescheduled with the same delay time, don't clear the interval id.\n if (delay != null && this.delay === delay && this.pending === false) {\n return id;\n }\n // Otherwise, if the action's delay time is different from the current delay,\n // or the action has been rescheduled before it's executed, clear the interval id\n if (id != null) {\n intervalProvider.clearInterval(id);\n }\n\n return undefined;\n }\n\n /**\n * Immediately executes this action and the `work` it contains.\n */\n public execute(state: T, delay: number): any {\n if (this.closed) {\n return new Error('executing a cancelled action');\n }\n\n this.pending = false;\n const error = this._execute(state, delay);\n if (error) {\n return error;\n } else if (this.pending === false && this.id != null) {\n // Dequeue if the action didn't reschedule itself. Don't call\n // unsubscribe(), because the action could reschedule later.\n // For example:\n // ```\n // scheduler.schedule(function doWork(counter) {\n // /* ... I'm a busy worker bee ... */\n // var originalAction = this;\n // /* wait 100ms before rescheduling the action */\n // setTimeout(function () {\n // originalAction.schedule(counter + 1);\n // }, 100);\n // }, 1000);\n // ```\n this.id = this.recycleAsyncId(this.scheduler, this.id, null);\n }\n }\n\n protected _execute(state: T, _delay: number): any {\n let errored: boolean = false;\n let errorValue: any;\n try {\n this.work(state);\n } catch (e) {\n errored = true;\n // HACK: Since code elsewhere is relying on the \"truthiness\" of the\n // return here, we can't have it return \"\" or 0 or false.\n // TODO: Clean this up when we refactor schedulers mid-version-8 or so.\n errorValue = e ? e : new Error('Scheduled action threw falsy error');\n }\n if (errored) {\n this.unsubscribe();\n return errorValue;\n }\n }\n\n unsubscribe() {\n if (!this.closed) {\n const { id, scheduler } = this;\n const { actions } = scheduler;\n\n this.work = this.state = this.scheduler = null!;\n this.pending = false;\n\n arrRemove(actions, this);\n if (id != null) {\n this.id = this.recycleAsyncId(scheduler, id, null);\n }\n\n this.delay = null!;\n super.unsubscribe();\n }\n }\n}\n", "let nextHandle = 1;\n// The promise needs to be created lazily otherwise it won't be patched by Zones\nlet resolved: Promise;\nconst activeHandles: { [key: number]: any } = {};\n\n/**\n * Finds the handle in the list of active handles, and removes it.\n * Returns `true` if found, `false` otherwise. Used both to clear\n * Immediate scheduled tasks, and to identify if a task should be scheduled.\n */\nfunction findAndClearHandle(handle: number): boolean {\n if (handle in activeHandles) {\n delete activeHandles[handle];\n return true;\n }\n return false;\n}\n\n/**\n * Helper functions to schedule and unschedule microtasks.\n */\nexport const Immediate = {\n setImmediate(cb: () => void): number {\n const handle = nextHandle++;\n activeHandles[handle] = true;\n if (!resolved) {\n resolved = Promise.resolve();\n }\n resolved.then(() => findAndClearHandle(handle) && cb());\n return handle;\n },\n\n clearImmediate(handle: number): void {\n findAndClearHandle(handle);\n },\n};\n\n/**\n * Used for internal testing purposes only. Do not export from library.\n */\nexport const TestTools = {\n pending() {\n return Object.keys(activeHandles).length;\n }\n};\n", "import { Immediate } from '../util/Immediate';\nimport type { TimerHandle } from './timerHandle';\nconst { setImmediate, clearImmediate } = Immediate;\n\ntype SetImmediateFunction = (handler: () => void, ...args: any[]) => TimerHandle;\ntype ClearImmediateFunction = (handle: TimerHandle) => void;\n\ninterface ImmediateProvider {\n setImmediate: SetImmediateFunction;\n clearImmediate: ClearImmediateFunction;\n delegate:\n | {\n setImmediate: SetImmediateFunction;\n clearImmediate: ClearImmediateFunction;\n }\n | undefined;\n}\n\nexport const immediateProvider: ImmediateProvider = {\n // When accessing the delegate, use the variable rather than `this` so that\n // the functions can be called without being bound to the provider.\n setImmediate(...args) {\n const { delegate } = immediateProvider;\n return (delegate?.setImmediate || setImmediate)(...args);\n },\n clearImmediate(handle) {\n const { delegate } = immediateProvider;\n return (delegate?.clearImmediate || clearImmediate)(handle as any);\n },\n delegate: undefined,\n};\n", "import { AsyncAction } from './AsyncAction';\nimport { AsapScheduler } from './AsapScheduler';\nimport { SchedulerAction } from '../types';\nimport { immediateProvider } from './immediateProvider';\nimport { TimerHandle } from './timerHandle';\n\nexport class AsapAction extends AsyncAction {\n constructor(protected scheduler: AsapScheduler, protected work: (this: SchedulerAction, state?: T) => void) {\n super(scheduler, work);\n }\n\n protected requestAsyncId(scheduler: AsapScheduler, id?: TimerHandle, delay: number = 0): TimerHandle {\n // If delay is greater than 0, request as an async action.\n if (delay !== null && delay > 0) {\n return super.requestAsyncId(scheduler, id, delay);\n }\n // Push the action to the end of the scheduler queue.\n scheduler.actions.push(this);\n // If a microtask has already been scheduled, don't schedule another\n // one. If a microtask hasn't been scheduled yet, schedule one now. Return\n // the current scheduled microtask id.\n return scheduler._scheduled || (scheduler._scheduled = immediateProvider.setImmediate(scheduler.flush.bind(scheduler, undefined)));\n }\n\n protected recycleAsyncId(scheduler: AsapScheduler, id?: TimerHandle, delay: number = 0): TimerHandle | undefined {\n // If delay exists and is greater than 0, or if the delay is null (the\n // action wasn't rescheduled) but was originally scheduled as an async\n // action, then recycle as an async action.\n if (delay != null ? delay > 0 : this.delay > 0) {\n return super.recycleAsyncId(scheduler, id, delay);\n }\n // If the scheduler queue has no remaining actions with the same async id,\n // cancel the requested microtask and set the scheduled flag to undefined\n // so the next AsapAction will request its own.\n const { actions } = scheduler;\n if (id != null && actions[actions.length - 1]?.id !== id) {\n immediateProvider.clearImmediate(id);\n if (scheduler._scheduled === id) {\n scheduler._scheduled = undefined;\n }\n }\n // Return undefined so the action knows to request a new async id if it's rescheduled.\n return undefined;\n }\n}\n", "import { Action } from './scheduler/Action';\nimport { Subscription } from './Subscription';\nimport { SchedulerLike, SchedulerAction } from './types';\nimport { dateTimestampProvider } from './scheduler/dateTimestampProvider';\n\n/**\n * An execution context and a data structure to order tasks and schedule their\n * execution. Provides a notion of (potentially virtual) time, through the\n * `now()` getter method.\n *\n * Each unit of work in a Scheduler is called an `Action`.\n *\n * ```ts\n * class Scheduler {\n * now(): number;\n * schedule(work, delay?, state?): Subscription;\n * }\n * ```\n *\n * @deprecated Scheduler is an internal implementation detail of RxJS, and\n * should not be used directly. Rather, create your own class and implement\n * {@link SchedulerLike}. Will be made internal in v8.\n */\nexport class Scheduler implements SchedulerLike {\n public static now: () => number = dateTimestampProvider.now;\n\n constructor(private schedulerActionCtor: typeof Action, now: () => number = Scheduler.now) {\n this.now = now;\n }\n\n /**\n * A getter method that returns a number representing the current time\n * (at the time this function was called) according to the scheduler's own\n * internal clock.\n * @return A number that represents the current time. May or may not\n * have a relation to wall-clock time. May or may not refer to a time unit\n * (e.g. milliseconds).\n */\n public now: () => number;\n\n /**\n * Schedules a function, `work`, for execution. May happen at some point in\n * the future, according to the `delay` parameter, if specified. May be passed\n * some context object, `state`, which will be passed to the `work` function.\n *\n * The given arguments will be processed an stored as an Action object in a\n * queue of actions.\n *\n * @param work A function representing a task, or some unit of work to be\n * executed by the Scheduler.\n * @param delay Time to wait before executing the work, where the time unit is\n * implicit and defined by the Scheduler itself.\n * @param state Some contextual data that the `work` function uses when called\n * by the Scheduler.\n * @return A subscription in order to be able to unsubscribe the scheduled work.\n */\n public schedule(work: (this: SchedulerAction, state?: T) => void, delay: number = 0, state?: T): Subscription {\n return new this.schedulerActionCtor(this, work).schedule(state, delay);\n }\n}\n", "import { Scheduler } from '../Scheduler';\nimport { Action } from './Action';\nimport { AsyncAction } from './AsyncAction';\nimport { TimerHandle } from './timerHandle';\n\nexport class AsyncScheduler extends Scheduler {\n public actions: Array> = [];\n /**\n * A flag to indicate whether the Scheduler is currently executing a batch of\n * queued actions.\n * @internal\n */\n public _active: boolean = false;\n /**\n * An internal ID used to track the latest asynchronous task such as those\n * coming from `setTimeout`, `setInterval`, `requestAnimationFrame`, and\n * others.\n * @internal\n */\n public _scheduled: TimerHandle | undefined;\n\n constructor(SchedulerAction: typeof Action, now: () => number = Scheduler.now) {\n super(SchedulerAction, now);\n }\n\n public flush(action: AsyncAction): void {\n const { actions } = this;\n\n if (this._active) {\n actions.push(action);\n return;\n }\n\n let error: any;\n this._active = true;\n\n do {\n if ((error = action.execute(action.state, action.delay))) {\n break;\n }\n } while ((action = actions.shift()!)); // exhaust the scheduler queue\n\n this._active = false;\n\n if (error) {\n while ((action = actions.shift()!)) {\n action.unsubscribe();\n }\n throw error;\n }\n }\n}\n", "import { AsyncAction } from './AsyncAction';\nimport { AsyncScheduler } from './AsyncScheduler';\n\nexport class AsapScheduler extends AsyncScheduler {\n public flush(action?: AsyncAction): void {\n this._active = true;\n // The async id that effects a call to flush is stored in _scheduled.\n // Before executing an action, it's necessary to check the action's async\n // id to determine whether it's supposed to be executed in the current\n // flush.\n // Previous implementations of this method used a count to determine this,\n // but that was unsound, as actions that are unsubscribed - i.e. cancelled -\n // are removed from the actions array and that can shift actions that are\n // scheduled to be executed in a subsequent flush into positions at which\n // they are executed within the current flush.\n const flushId = this._scheduled;\n this._scheduled = undefined;\n\n const { actions } = this;\n let error: any;\n action = action || actions.shift()!;\n\n do {\n if ((error = action.execute(action.state, action.delay))) {\n break;\n }\n } while ((action = actions[0]) && action.id === flushId && actions.shift());\n\n this._active = false;\n\n if (error) {\n while ((action = actions[0]) && action.id === flushId && actions.shift()) {\n action.unsubscribe();\n }\n throw error;\n }\n }\n}\n", "import { AsapAction } from './AsapAction';\nimport { AsapScheduler } from './AsapScheduler';\n\n/**\n *\n * Asap Scheduler\n *\n * Perform task as fast as it can be performed asynchronously\n *\n * `asap` scheduler behaves the same as {@link asyncScheduler} scheduler when you use it to delay task\n * in time. If however you set delay to `0`, `asap` will wait for current synchronously executing\n * code to end and then it will try to execute given task as fast as possible.\n *\n * `asap` scheduler will do its best to minimize time between end of currently executing code\n * and start of scheduled task. This makes it best candidate for performing so called \"deferring\".\n * Traditionally this was achieved by calling `setTimeout(deferredTask, 0)`, but that technique involves\n * some (although minimal) unwanted delay.\n *\n * Note that using `asap` scheduler does not necessarily mean that your task will be first to process\n * after currently executing code. In particular, if some task was also scheduled with `asap` before,\n * that task will execute first. That being said, if you need to schedule task asynchronously, but\n * as soon as possible, `asap` scheduler is your best bet.\n *\n * ## Example\n * Compare async and asap scheduler<\n * ```ts\n * import { asapScheduler, asyncScheduler } from 'rxjs';\n *\n * asyncScheduler.schedule(() => console.log('async')); // scheduling 'async' first...\n * asapScheduler.schedule(() => console.log('asap'));\n *\n * // Logs:\n * // \"asap\"\n * // \"async\"\n * // ... but 'asap' goes first!\n * ```\n */\n\nexport const asapScheduler = new AsapScheduler(AsapAction);\n\n/**\n * @deprecated Renamed to {@link asapScheduler}. Will be removed in v8.\n */\nexport const asap = asapScheduler;\n", "import { AsyncAction } from './AsyncAction';\nimport { AsyncScheduler } from './AsyncScheduler';\n\n/**\n *\n * Async Scheduler\n *\n * Schedule task as if you used setTimeout(task, duration)\n *\n * `async` scheduler schedules tasks asynchronously, by putting them on the JavaScript\n * event loop queue. It is best used to delay tasks in time or to schedule tasks repeating\n * in intervals.\n *\n * If you just want to \"defer\" task, that is to perform it right after currently\n * executing synchronous code ends (commonly achieved by `setTimeout(deferredTask, 0)`),\n * better choice will be the {@link asapScheduler} scheduler.\n *\n * ## Examples\n * Use async scheduler to delay task\n * ```ts\n * import { asyncScheduler } from 'rxjs';\n *\n * const task = () => console.log('it works!');\n *\n * asyncScheduler.schedule(task, 2000);\n *\n * // After 2 seconds logs:\n * // \"it works!\"\n * ```\n *\n * Use async scheduler to repeat task in intervals\n * ```ts\n * import { asyncScheduler } from 'rxjs';\n *\n * function task(state) {\n * console.log(state);\n * this.schedule(state + 1, 1000); // `this` references currently executing Action,\n * // which we reschedule with new state and delay\n * }\n *\n * asyncScheduler.schedule(task, 3000, 0);\n *\n * // Logs:\n * // 0 after 3s\n * // 1 after 4s\n * // 2 after 5s\n * // 3 after 6s\n * ```\n */\n\nexport const asyncScheduler = new AsyncScheduler(AsyncAction);\n\n/**\n * @deprecated Renamed to {@link asyncScheduler}. Will be removed in v8.\n */\nexport const async = asyncScheduler;\n", "import { AsyncAction } from './AsyncAction';\nimport { Subscription } from '../Subscription';\nimport { QueueScheduler } from './QueueScheduler';\nimport { SchedulerAction } from '../types';\nimport { TimerHandle } from './timerHandle';\n\nexport class QueueAction extends AsyncAction {\n constructor(protected scheduler: QueueScheduler, protected work: (this: SchedulerAction, state?: T) => void) {\n super(scheduler, work);\n }\n\n public schedule(state?: T, delay: number = 0): Subscription {\n if (delay > 0) {\n return super.schedule(state, delay);\n }\n this.delay = delay;\n this.state = state;\n this.scheduler.flush(this);\n return this;\n }\n\n public execute(state: T, delay: number): any {\n return delay > 0 || this.closed ? super.execute(state, delay) : this._execute(state, delay);\n }\n\n protected requestAsyncId(scheduler: QueueScheduler, id?: TimerHandle, delay: number = 0): TimerHandle {\n // If delay exists and is greater than 0, or if the delay is null (the\n // action wasn't rescheduled) but was originally scheduled as an async\n // action, then recycle as an async action.\n\n if ((delay != null && delay > 0) || (delay == null && this.delay > 0)) {\n return super.requestAsyncId(scheduler, id, delay);\n }\n\n // Otherwise flush the scheduler starting with this action.\n scheduler.flush(this);\n\n // HACK: In the past, this was returning `void`. However, `void` isn't a valid\n // `TimerHandle`, and generally the return value here isn't really used. So the\n // compromise is to return `0` which is both \"falsy\" and a valid `TimerHandle`,\n // as opposed to refactoring every other instanceo of `requestAsyncId`.\n return 0;\n }\n}\n", "import { AsyncScheduler } from './AsyncScheduler';\n\nexport class QueueScheduler extends AsyncScheduler {\n}\n", "import { QueueAction } from './QueueAction';\nimport { QueueScheduler } from './QueueScheduler';\n\n/**\n *\n * Queue Scheduler\n *\n * Put every next task on a queue, instead of executing it immediately\n *\n * `queue` scheduler, when used with delay, behaves the same as {@link asyncScheduler} scheduler.\n *\n * When used without delay, it schedules given task synchronously - executes it right when\n * it is scheduled. However when called recursively, that is when inside the scheduled task,\n * another task is scheduled with queue scheduler, instead of executing immediately as well,\n * that task will be put on a queue and wait for current one to finish.\n *\n * This means that when you execute task with `queue` scheduler, you are sure it will end\n * before any other task scheduled with that scheduler will start.\n *\n * ## Examples\n * Schedule recursively first, then do something\n * ```ts\n * import { queueScheduler } from 'rxjs';\n *\n * queueScheduler.schedule(() => {\n * queueScheduler.schedule(() => console.log('second')); // will not happen now, but will be put on a queue\n *\n * console.log('first');\n * });\n *\n * // Logs:\n * // \"first\"\n * // \"second\"\n * ```\n *\n * Reschedule itself recursively\n * ```ts\n * import { queueScheduler } from 'rxjs';\n *\n * queueScheduler.schedule(function(state) {\n * if (state !== 0) {\n * console.log('before', state);\n * this.schedule(state - 1); // `this` references currently executing Action,\n * // which we reschedule with new state\n * console.log('after', state);\n * }\n * }, 0, 3);\n *\n * // In scheduler that runs recursively, you would expect:\n * // \"before\", 3\n * // \"before\", 2\n * // \"before\", 1\n * // \"after\", 1\n * // \"after\", 2\n * // \"after\", 3\n *\n * // But with queue it logs:\n * // \"before\", 3\n * // \"after\", 3\n * // \"before\", 2\n * // \"after\", 2\n * // \"before\", 1\n * // \"after\", 1\n * ```\n */\n\nexport const queueScheduler = new QueueScheduler(QueueAction);\n\n/**\n * @deprecated Renamed to {@link queueScheduler}. Will be removed in v8.\n */\nexport const queue = queueScheduler;\n", "import { AsyncAction } from './AsyncAction';\nimport { AnimationFrameScheduler } from './AnimationFrameScheduler';\nimport { SchedulerAction } from '../types';\nimport { animationFrameProvider } from './animationFrameProvider';\nimport { TimerHandle } from './timerHandle';\n\nexport class AnimationFrameAction extends AsyncAction {\n constructor(protected scheduler: AnimationFrameScheduler, protected work: (this: SchedulerAction, state?: T) => void) {\n super(scheduler, work);\n }\n\n protected requestAsyncId(scheduler: AnimationFrameScheduler, id?: TimerHandle, delay: number = 0): TimerHandle {\n // If delay is greater than 0, request as an async action.\n if (delay !== null && delay > 0) {\n return super.requestAsyncId(scheduler, id, delay);\n }\n // Push the action to the end of the scheduler queue.\n scheduler.actions.push(this);\n // If an animation frame has already been requested, don't request another\n // one. If an animation frame hasn't been requested yet, request one. Return\n // the current animation frame request id.\n return scheduler._scheduled || (scheduler._scheduled = animationFrameProvider.requestAnimationFrame(() => scheduler.flush(undefined)));\n }\n\n protected recycleAsyncId(scheduler: AnimationFrameScheduler, id?: TimerHandle, delay: number = 0): TimerHandle | undefined {\n // If delay exists and is greater than 0, or if the delay is null (the\n // action wasn't rescheduled) but was originally scheduled as an async\n // action, then recycle as an async action.\n if (delay != null ? delay > 0 : this.delay > 0) {\n return super.recycleAsyncId(scheduler, id, delay);\n }\n // If the scheduler queue has no remaining actions with the same async id,\n // cancel the requested animation frame and set the scheduled flag to\n // undefined so the next AnimationFrameAction will request its own.\n const { actions } = scheduler;\n if (id != null && id === scheduler._scheduled && actions[actions.length - 1]?.id !== id) {\n animationFrameProvider.cancelAnimationFrame(id as number);\n scheduler._scheduled = undefined;\n }\n // Return undefined so the action knows to request a new async id if it's rescheduled.\n return undefined;\n }\n}\n", "import { AsyncAction } from './AsyncAction';\nimport { AsyncScheduler } from './AsyncScheduler';\n\nexport class AnimationFrameScheduler extends AsyncScheduler {\n public flush(action?: AsyncAction): void {\n this._active = true;\n // The async id that effects a call to flush is stored in _scheduled.\n // Before executing an action, it's necessary to check the action's async\n // id to determine whether it's supposed to be executed in the current\n // flush.\n // Previous implementations of this method used a count to determine this,\n // but that was unsound, as actions that are unsubscribed - i.e. cancelled -\n // are removed from the actions array and that can shift actions that are\n // scheduled to be executed in a subsequent flush into positions at which\n // they are executed within the current flush.\n let flushId;\n if (action) {\n flushId = action.id;\n } else {\n flushId = this._scheduled;\n this._scheduled = undefined;\n }\n\n const { actions } = this;\n let error: any;\n action = action || actions.shift()!;\n\n do {\n if ((error = action.execute(action.state, action.delay))) {\n break;\n }\n } while ((action = actions[0]) && action.id === flushId && actions.shift());\n\n this._active = false;\n\n if (error) {\n while ((action = actions[0]) && action.id === flushId && actions.shift()) {\n action.unsubscribe();\n }\n throw error;\n }\n }\n}\n", "import { AnimationFrameAction } from './AnimationFrameAction';\nimport { AnimationFrameScheduler } from './AnimationFrameScheduler';\n\n/**\n *\n * Animation Frame Scheduler\n *\n * Perform task when `window.requestAnimationFrame` would fire\n *\n * When `animationFrame` scheduler is used with delay, it will fall back to {@link asyncScheduler} scheduler\n * behaviour.\n *\n * Without delay, `animationFrame` scheduler can be used to create smooth browser animations.\n * It makes sure scheduled task will happen just before next browser content repaint,\n * thus performing animations as efficiently as possible.\n *\n * ## Example\n * Schedule div height animation\n * ```ts\n * // html:

\n * import { animationFrameScheduler } from 'rxjs';\n *\n * const div = document.querySelector('div');\n *\n * animationFrameScheduler.schedule(function(height) {\n * div.style.height = height + \"px\";\n *\n * this.schedule(height + 1); // `this` references currently executing Action,\n * // which we reschedule with new state\n * }, 0, 0);\n *\n * // You will see a div element growing in height\n * ```\n */\n\nexport const animationFrameScheduler = new AnimationFrameScheduler(AnimationFrameAction);\n\n/**\n * @deprecated Renamed to {@link animationFrameScheduler}. Will be removed in v8.\n */\nexport const animationFrame = animationFrameScheduler;\n", "import { AsyncAction } from './AsyncAction';\nimport { Subscription } from '../Subscription';\nimport { AsyncScheduler } from './AsyncScheduler';\nimport { SchedulerAction } from '../types';\nimport { TimerHandle } from './timerHandle';\n\nexport class VirtualTimeScheduler extends AsyncScheduler {\n /** @deprecated Not used in VirtualTimeScheduler directly. Will be removed in v8. */\n static frameTimeFactor = 10;\n\n /**\n * The current frame for the state of the virtual scheduler instance. The difference\n * between two \"frames\" is synonymous with the passage of \"virtual time units\". So if\n * you record `scheduler.frame` to be `1`, then later, observe `scheduler.frame` to be at `11`,\n * that means `10` virtual time units have passed.\n */\n public frame: number = 0;\n\n /**\n * Used internally to examine the current virtual action index being processed.\n * @deprecated Internal implementation detail, do not use directly. Will be made internal in v8.\n */\n public index: number = -1;\n\n /**\n * This creates an instance of a `VirtualTimeScheduler`. Experts only. The signature of\n * this constructor is likely to change in the long run.\n *\n * @param schedulerActionCtor The type of Action to initialize when initializing actions during scheduling.\n * @param maxFrames The maximum number of frames to process before stopping. Used to prevent endless flush cycles.\n */\n constructor(schedulerActionCtor: typeof AsyncAction = VirtualAction as any, public maxFrames: number = Infinity) {\n super(schedulerActionCtor, () => this.frame);\n }\n\n /**\n * Prompt the Scheduler to execute all of its queued actions, therefore\n * clearing its queue.\n */\n public flush(): void {\n const { actions, maxFrames } = this;\n let error: any;\n let action: AsyncAction | undefined;\n\n while ((action = actions[0]) && action.delay <= maxFrames) {\n actions.shift();\n this.frame = action.delay;\n\n if ((error = action.execute(action.state, action.delay))) {\n break;\n }\n }\n\n if (error) {\n while ((action = actions.shift())) {\n action.unsubscribe();\n }\n throw error;\n }\n }\n}\n\nexport class VirtualAction extends AsyncAction {\n protected active: boolean = true;\n\n constructor(\n protected scheduler: VirtualTimeScheduler,\n protected work: (this: SchedulerAction, state?: T) => void,\n protected index: number = (scheduler.index += 1)\n ) {\n super(scheduler, work);\n this.index = scheduler.index = index;\n }\n\n public schedule(state?: T, delay: number = 0): Subscription {\n if (Number.isFinite(delay)) {\n if (!this.id) {\n return super.schedule(state, delay);\n }\n this.active = false;\n // If an action is rescheduled, we save allocations by mutating its state,\n // pushing it to the end of the scheduler queue, and recycling the action.\n // But since the VirtualTimeScheduler is used for testing, VirtualActions\n // must be immutable so they can be inspected later.\n const action = new VirtualAction(this.scheduler, this.work);\n this.add(action);\n return action.schedule(state, delay);\n } else {\n // If someone schedules something with Infinity, it'll never happen. So we\n // don't even schedule it.\n return Subscription.EMPTY;\n }\n }\n\n protected requestAsyncId(scheduler: VirtualTimeScheduler, id?: any, delay: number = 0): TimerHandle {\n this.delay = scheduler.frame + delay;\n const { actions } = scheduler;\n actions.push(this);\n (actions as Array>).sort(VirtualAction.sortActions);\n return 1;\n }\n\n protected recycleAsyncId(scheduler: VirtualTimeScheduler, id?: any, delay: number = 0): TimerHandle | undefined {\n return undefined;\n }\n\n protected _execute(state: T, delay: number): any {\n if (this.active === true) {\n return super._execute(state, delay);\n }\n }\n\n private static sortActions(a: VirtualAction, b: VirtualAction) {\n if (a.delay === b.delay) {\n if (a.index === b.index) {\n return 0;\n } else if (a.index > b.index) {\n return 1;\n } else {\n return -1;\n }\n } else if (a.delay > b.delay) {\n return 1;\n } else {\n return -1;\n }\n }\n}\n", "import { Observable } from '../Observable';\nimport { SchedulerLike } from '../types';\n\n/**\n * A simple Observable that emits no items to the Observer and immediately\n * emits a complete notification.\n *\n * Just emits 'complete', and nothing else.\n *\n * ![](empty.png)\n *\n * A simple Observable that only emits the complete notification. It can be used\n * for composing with other Observables, such as in a {@link mergeMap}.\n *\n * ## Examples\n *\n * Log complete notification\n *\n * ```ts\n * import { EMPTY } from 'rxjs';\n *\n * EMPTY.subscribe({\n * next: () => console.log('Next'),\n * complete: () => console.log('Complete!')\n * });\n *\n * // Outputs\n * // Complete!\n * ```\n *\n * Emit the number 7, then complete\n *\n * ```ts\n * import { EMPTY, startWith } from 'rxjs';\n *\n * const result = EMPTY.pipe(startWith(7));\n * result.subscribe(x => console.log(x));\n *\n * // Outputs\n * // 7\n * ```\n *\n * Map and flatten only odd numbers to the sequence `'a'`, `'b'`, `'c'`\n *\n * ```ts\n * import { interval, mergeMap, of, EMPTY } from 'rxjs';\n *\n * const interval$ = interval(1000);\n * const result = interval$.pipe(\n * mergeMap(x => x % 2 === 1 ? of('a', 'b', 'c') : EMPTY),\n * );\n * result.subscribe(x => console.log(x));\n *\n * // Results in the following to the console:\n * // x is equal to the count on the interval, e.g. (0, 1, 2, 3, ...)\n * // x will occur every 1000ms\n * // if x % 2 is equal to 1, print a, b, c (each on its own)\n * // if x % 2 is not equal to 1, nothing will be output\n * ```\n *\n * @see {@link Observable}\n * @see {@link NEVER}\n * @see {@link of}\n * @see {@link throwError}\n */\nexport const EMPTY = new Observable((subscriber) => subscriber.complete());\n\n/**\n * @param scheduler A {@link SchedulerLike} to use for scheduling\n * the emission of the complete notification.\n * @deprecated Replaced with the {@link EMPTY} constant or {@link scheduled} (e.g. `scheduled([], scheduler)`). Will be removed in v8.\n */\nexport function empty(scheduler?: SchedulerLike) {\n return scheduler ? emptyScheduled(scheduler) : EMPTY;\n}\n\nfunction emptyScheduled(scheduler: SchedulerLike) {\n return new Observable((subscriber) => scheduler.schedule(() => subscriber.complete()));\n}\n", "import { SchedulerLike } from '../types';\nimport { isFunction } from './isFunction';\n\nexport function isScheduler(value: any): value is SchedulerLike {\n return value && isFunction(value.schedule);\n}\n", "import { SchedulerLike } from '../types';\nimport { isFunction } from './isFunction';\nimport { isScheduler } from './isScheduler';\n\nfunction last(arr: T[]): T | undefined {\n return arr[arr.length - 1];\n}\n\nexport function popResultSelector(args: any[]): ((...args: unknown[]) => unknown) | undefined {\n return isFunction(last(args)) ? args.pop() : undefined;\n}\n\nexport function popScheduler(args: any[]): SchedulerLike | undefined {\n return isScheduler(last(args)) ? args.pop() : undefined;\n}\n\nexport function popNumber(args: any[], defaultValue: number): number {\n return typeof last(args) === 'number' ? args.pop()! : defaultValue;\n}\n", "export const isArrayLike = ((x: any): x is ArrayLike => x && typeof x.length === 'number' && typeof x !== 'function');", "import { isFunction } from \"./isFunction\";\n\n/**\n * Tests to see if the object is \"thennable\".\n * @param value the object to test\n */\nexport function isPromise(value: any): value is PromiseLike {\n return isFunction(value?.then);\n}\n", "import { InteropObservable } from '../types';\nimport { observable as Symbol_observable } from '../symbol/observable';\nimport { isFunction } from './isFunction';\n\n/** Identifies an input as being Observable (but not necessary an Rx Observable) */\nexport function isInteropObservable(input: any): input is InteropObservable {\n return isFunction(input[Symbol_observable]);\n}\n", "import { isFunction } from './isFunction';\n\nexport function isAsyncIterable(obj: any): obj is AsyncIterable {\n return Symbol.asyncIterator && isFunction(obj?.[Symbol.asyncIterator]);\n}\n", "/**\n * Creates the TypeError to throw if an invalid object is passed to `from` or `scheduled`.\n * @param input The object that was passed.\n */\nexport function createInvalidObservableTypeError(input: any) {\n // TODO: We should create error codes that can be looked up, so this can be less verbose.\n return new TypeError(\n `You provided ${\n input !== null && typeof input === 'object' ? 'an invalid object' : `'${input}'`\n } where a stream was expected. You can provide an Observable, Promise, ReadableStream, Array, AsyncIterable, or Iterable.`\n );\n}\n", "export function getSymbolIterator(): symbol {\n if (typeof Symbol !== 'function' || !Symbol.iterator) {\n return '@@iterator' as any;\n }\n\n return Symbol.iterator;\n}\n\nexport const iterator = getSymbolIterator();\n", "import { iterator as Symbol_iterator } from '../symbol/iterator';\nimport { isFunction } from './isFunction';\n\n/** Identifies an input as being an Iterable */\nexport function isIterable(input: any): input is Iterable {\n return isFunction(input?.[Symbol_iterator]);\n}\n", "import { ReadableStreamLike } from '../types';\nimport { isFunction } from './isFunction';\n\nexport async function* readableStreamLikeToAsyncGenerator(readableStream: ReadableStreamLike): AsyncGenerator {\n const reader = readableStream.getReader();\n try {\n while (true) {\n const { value, done } = await reader.read();\n if (done) {\n return;\n }\n yield value!;\n }\n } finally {\n reader.releaseLock();\n }\n}\n\nexport function isReadableStreamLike(obj: any): obj is ReadableStreamLike {\n // We don't want to use instanceof checks because they would return\n // false for instances from another Realm, like an