akkounts/vendor/javascript/nostrify.js
2024-10-10 23:37:41 +02:00

11691 lines
364 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

var dl = Object.defineProperty;
var yo = (n) => {
throw TypeError(n);
};
var hl = (n, e, t) => e in n ? dl(n, e, { enumerable: !0, configurable: !0, writable: !0, value: t }) : n[e] = t;
var B = (n, e, t) => hl(n, typeof e != "symbol" ? e + "" : e, t), Bs = (n, e, t) => e.has(n) || yo("Cannot " + t);
var h = (n, e, t) => (Bs(n, e, "read from private field"), t ? t.call(n) : e.get(n)), X = (n, e, t) => e.has(n) ? yo("Cannot add the same private member more than once") : e instanceof WeakSet ? e.add(n) : e.set(n, t), q = (n, e, t, r) => (Bs(n, e, "write to private field"), r ? r.call(n, t) : e.set(n, t), t), M = (n, e, t) => (Bs(n, e, "access private method"), t);
var Ur = (n, e, t, r) => ({
set _(s) {
q(n, e, s, t);
},
get _() {
return h(n, e, r);
}
});
const _n = typeof performance == "object" && performance && typeof performance.now == "function" ? performance : Date, sa = /* @__PURE__ */ new Set(), Fs = typeof process == "object" && process ? process : {}, ia = (n, e, t, r) => {
typeof Fs.emitWarning == "function" ? Fs.emitWarning(n, e, t, r) : console.error(`[${t}] ${e}: ${n}`);
};
let Gr = globalThis.AbortController, mo = globalThis.AbortSignal;
var Jo;
if (typeof Gr > "u") {
mo = class {
constructor() {
B(this, "onabort");
B(this, "_onabort", []);
B(this, "reason");
B(this, "aborted", !1);
}
addEventListener(r, s) {
this._onabort.push(s);
}
}, Gr = class {
constructor() {
B(this, "signal", new mo());
e();
}
abort(r) {
var s, i;
if (!this.signal.aborted) {
this.signal.reason = r, this.signal.aborted = !0;
for (const o of this.signal._onabort)
o(r);
(i = (s = this.signal).onabort) == null || i.call(s, r);
}
}
};
let n = ((Jo = Fs.env) == null ? void 0 : Jo.LRU_CACHE_IGNORE_AC_WARNING) !== "1";
const e = () => {
n && (n = !1, ia("AbortController is not defined. If using lru-cache in node 14, load an AbortController polyfill from the `node-abort-controller` package. A minimal polyfill is provided for use by LRUCache.fetch(), but it should not be relied upon in other contexts (eg, passing it to other APIs that use AbortController/AbortSignal might have undesirable effects). You may disable this with LRU_CACHE_IGNORE_AC_WARNING=1 in the env.", "NO_ABORT_CONTROLLER", "ENOTSUP", e));
};
}
const fl = (n) => !sa.has(n), Kt = (n) => n && n === Math.floor(n) && n > 0 && isFinite(n), oa = (n) => Kt(n) ? n <= Math.pow(2, 8) ? Uint8Array : n <= Math.pow(2, 16) ? Uint16Array : n <= Math.pow(2, 32) ? Uint32Array : n <= Number.MAX_SAFE_INTEGER ? qr : null : null;
class qr extends Array {
constructor(e) {
super(e), this.fill(0);
}
}
var Cn;
const dn = class dn {
constructor(e, t) {
B(this, "heap");
B(this, "length");
if (!h(dn, Cn))
throw new TypeError("instantiate Stack using Stack.create(n)");
this.heap = new t(e), this.length = 0;
}
static create(e) {
const t = oa(e);
if (!t)
return [];
q(dn, Cn, !0);
const r = new dn(e, t);
return q(dn, Cn, !1), r;
}
push(e) {
this.heap[this.length++] = e;
}
pop() {
return this.heap[--this.length];
}
};
Cn = new WeakMap(), // private constructor
X(dn, Cn, !1);
let Gs = dn;
var Xo, Qo, Fe, Ue, Ge, Ye, $n, Rn, pe, Je, fe, ae, G, Oe, He, ke, me, Xe, we, Qe, et, Me, tt, Jt, Ie, R, Js, fn, Tt, Ar, je, aa, pn, Nn, Tr, Wt, Ft, Xs, Vr, Kr, oe, Qs, tr, Gt, ei;
const po = class po {
constructor(e) {
X(this, R);
// options that cannot be changed without disaster
X(this, Fe);
X(this, Ue);
X(this, Ge);
X(this, Ye);
X(this, $n);
X(this, Rn);
/**
* {@link LRUCache.OptionsBase.ttl}
*/
B(this, "ttl");
/**
* {@link LRUCache.OptionsBase.ttlResolution}
*/
B(this, "ttlResolution");
/**
* {@link LRUCache.OptionsBase.ttlAutopurge}
*/
B(this, "ttlAutopurge");
/**
* {@link LRUCache.OptionsBase.updateAgeOnGet}
*/
B(this, "updateAgeOnGet");
/**
* {@link LRUCache.OptionsBase.updateAgeOnHas}
*/
B(this, "updateAgeOnHas");
/**
* {@link LRUCache.OptionsBase.allowStale}
*/
B(this, "allowStale");
/**
* {@link LRUCache.OptionsBase.noDisposeOnSet}
*/
B(this, "noDisposeOnSet");
/**
* {@link LRUCache.OptionsBase.noUpdateTTL}
*/
B(this, "noUpdateTTL");
/**
* {@link LRUCache.OptionsBase.maxEntrySize}
*/
B(this, "maxEntrySize");
/**
* {@link LRUCache.OptionsBase.sizeCalculation}
*/
B(this, "sizeCalculation");
/**
* {@link LRUCache.OptionsBase.noDeleteOnFetchRejection}
*/
B(this, "noDeleteOnFetchRejection");
/**
* {@link LRUCache.OptionsBase.noDeleteOnStaleGet}
*/
B(this, "noDeleteOnStaleGet");
/**
* {@link LRUCache.OptionsBase.allowStaleOnFetchAbort}
*/
B(this, "allowStaleOnFetchAbort");
/**
* {@link LRUCache.OptionsBase.allowStaleOnFetchRejection}
*/
B(this, "allowStaleOnFetchRejection");
/**
* {@link LRUCache.OptionsBase.ignoreFetchAbort}
*/
B(this, "ignoreFetchAbort");
// computed properties
X(this, pe);
X(this, Je);
X(this, fe);
X(this, ae);
X(this, G);
X(this, Oe);
X(this, He);
X(this, ke);
X(this, me);
X(this, Xe);
X(this, we);
X(this, Qe);
X(this, et);
X(this, Me);
X(this, tt);
X(this, Jt);
X(this, Ie);
// conditionally set private methods related to TTL
X(this, fn, () => {
});
X(this, Tt, () => {
});
X(this, Ar, () => {
});
/* c8 ignore stop */
X(this, je, () => !1);
X(this, pn, (e) => {
});
X(this, Nn, (e, t, r) => {
});
X(this, Tr, (e, t, r, s) => {
if (r || s)
throw new TypeError("cannot set size without setting maxSize or maxEntrySize on cache");
return 0;
});
/**
* A String value that is used in the creation of the default string
* description of an object. Called by the built-in method
* `Object.prototype.toString`.
*/
B(this, Xo, "LRUCache");
const { max: t = 0, ttl: r, ttlResolution: s = 1, ttlAutopurge: i, updateAgeOnGet: o, updateAgeOnHas: a, allowStale: c, dispose: l, disposeAfter: d, noDisposeOnSet: u, noUpdateTTL: f, maxSize: m = 0, maxEntrySize: b = 0, sizeCalculation: g, fetchMethod: p, memoMethod: y, noDeleteOnFetchRejection: w, noDeleteOnStaleGet: x, allowStaleOnFetchRejection: A, allowStaleOnFetchAbort: T, ignoreFetchAbort: _ } = e;
if (t !== 0 && !Kt(t))
throw new TypeError("max option must be a nonnegative integer");
const S = t ? oa(t) : Array;
if (!S)
throw new Error("invalid max value: " + t);
if (q(this, Fe, t), q(this, Ue, m), this.maxEntrySize = b || h(this, Ue), this.sizeCalculation = g, this.sizeCalculation) {
if (!h(this, Ue) && !this.maxEntrySize)
throw new TypeError("cannot set sizeCalculation without setting maxSize or maxEntrySize");
if (typeof this.sizeCalculation != "function")
throw new TypeError("sizeCalculation set to non-function");
}
if (y !== void 0 && typeof y != "function")
throw new TypeError("memoMethod must be a function if defined");
if (q(this, Rn, y), p !== void 0 && typeof p != "function")
throw new TypeError("fetchMethod must be a function if specified");
if (q(this, $n, p), q(this, Jt, !!p), q(this, fe, /* @__PURE__ */ new Map()), q(this, ae, new Array(t).fill(void 0)), q(this, G, new Array(t).fill(void 0)), q(this, Oe, new S(t)), q(this, He, new S(t)), q(this, ke, 0), q(this, me, 0), q(this, Xe, Gs.create(t)), q(this, pe, 0), q(this, Je, 0), typeof l == "function" && q(this, Ge, l), typeof d == "function" ? (q(this, Ye, d), q(this, we, [])) : (q(this, Ye, void 0), q(this, we, void 0)), q(this, tt, !!h(this, Ge)), q(this, Ie, !!h(this, Ye)), this.noDisposeOnSet = !!u, this.noUpdateTTL = !!f, this.noDeleteOnFetchRejection = !!w, this.allowStaleOnFetchRejection = !!A, this.allowStaleOnFetchAbort = !!T, this.ignoreFetchAbort = !!_, this.maxEntrySize !== 0) {
if (h(this, Ue) !== 0 && !Kt(h(this, Ue)))
throw new TypeError("maxSize must be a positive integer if specified");
if (!Kt(this.maxEntrySize))
throw new TypeError("maxEntrySize must be a positive integer if specified");
M(this, R, aa).call(this);
}
if (this.allowStale = !!c, this.noDeleteOnStaleGet = !!x, this.updateAgeOnGet = !!o, this.updateAgeOnHas = !!a, this.ttlResolution = Kt(s) || s === 0 ? s : 1, this.ttlAutopurge = !!i, this.ttl = r || 0, this.ttl) {
if (!Kt(this.ttl))
throw new TypeError("ttl must be a positive integer if specified");
M(this, R, Js).call(this);
}
if (h(this, Fe) === 0 && this.ttl === 0 && h(this, Ue) === 0)
throw new TypeError("At least one of max, maxSize, or ttl is required");
if (!this.ttlAutopurge && !h(this, Fe) && !h(this, Ue)) {
const k = "LRU_CACHE_UNBOUNDED";
fl(k) && (sa.add(k), ia("TTL caching without ttlAutopurge, max, or maxSize can result in unbounded memory consumption.", "UnboundedCacheWarning", k, po));
}
}
/**
* Do not call this method unless you need to inspect the
* inner workings of the cache. If anything returned by this
* object is modified in any way, strange breakage may occur.
*
* These fields are private for a reason!
*
* @internal
*/
static unsafeExposeInternals(e) {
return {
// properties
starts: h(e, et),
ttls: h(e, Me),
sizes: h(e, Qe),
keyMap: h(e, fe),
keyList: h(e, ae),
valList: h(e, G),
next: h(e, Oe),
prev: h(e, He),
get head() {
return h(e, ke);
},
get tail() {
return h(e, me);
},
free: h(e, Xe),
// methods
isBackgroundFetch: (t) => {
var r;
return M(r = e, R, oe).call(r, t);
},
backgroundFetch: (t, r, s, i) => {
var o;
return M(o = e, R, Kr).call(o, t, r, s, i);
},
moveToTail: (t) => {
var r;
return M(r = e, R, tr).call(r, t);
},
indexes: (t) => {
var r;
return M(r = e, R, Wt).call(r, t);
},
rindexes: (t) => {
var r;
return M(r = e, R, Ft).call(r, t);
},
isStale: (t) => {
var r;
return h(r = e, je).call(r, t);
}
};
}
// Protected read-only members
/**
* {@link LRUCache.OptionsBase.max} (read-only)
*/
get max() {
return h(this, Fe);
}
/**
* {@link LRUCache.OptionsBase.maxSize} (read-only)
*/
get maxSize() {
return h(this, Ue);
}
/**
* The total computed size of items in the cache (read-only)
*/
get calculatedSize() {
return h(this, Je);
}
/**
* The number of items stored in the cache (read-only)
*/
get size() {
return h(this, pe);
}
/**
* {@link LRUCache.OptionsBase.fetchMethod} (read-only)
*/
get fetchMethod() {
return h(this, $n);
}
get memoMethod() {
return h(this, Rn);
}
/**
* {@link LRUCache.OptionsBase.dispose} (read-only)
*/
get dispose() {
return h(this, Ge);
}
/**
* {@link LRUCache.OptionsBase.disposeAfter} (read-only)
*/
get disposeAfter() {
return h(this, Ye);
}
/**
* Return the number of ms left in the item's TTL. If item is not in cache,
* returns `0`. Returns `Infinity` if item is in cache without a defined TTL.
*/
getRemainingTTL(e) {
return h(this, fe).has(e) ? 1 / 0 : 0;
}
/**
* Return a generator yielding `[key, value]` pairs,
* in order from most recently used to least recently used.
*/
*entries() {
for (const e of M(this, R, Wt).call(this))
h(this, G)[e] !== void 0 && h(this, ae)[e] !== void 0 && !M(this, R, oe).call(this, h(this, G)[e]) && (yield [h(this, ae)[e], h(this, G)[e]]);
}
/**
* Inverse order version of {@link LRUCache.entries}
*
* Return a generator yielding `[key, value]` pairs,
* in order from least recently used to most recently used.
*/
*rentries() {
for (const e of M(this, R, Ft).call(this))
h(this, G)[e] !== void 0 && h(this, ae)[e] !== void 0 && !M(this, R, oe).call(this, h(this, G)[e]) && (yield [h(this, ae)[e], h(this, G)[e]]);
}
/**
* Return a generator yielding the keys in the cache,
* in order from most recently used to least recently used.
*/
*keys() {
for (const e of M(this, R, Wt).call(this)) {
const t = h(this, ae)[e];
t !== void 0 && !M(this, R, oe).call(this, h(this, G)[e]) && (yield t);
}
}
/**
* Inverse order version of {@link LRUCache.keys}
*
* Return a generator yielding the keys in the cache,
* in order from least recently used to most recently used.
*/
*rkeys() {
for (const e of M(this, R, Ft).call(this)) {
const t = h(this, ae)[e];
t !== void 0 && !M(this, R, oe).call(this, h(this, G)[e]) && (yield t);
}
}
/**
* Return a generator yielding the values in the cache,
* in order from most recently used to least recently used.
*/
*values() {
for (const e of M(this, R, Wt).call(this))
h(this, G)[e] !== void 0 && !M(this, R, oe).call(this, h(this, G)[e]) && (yield h(this, G)[e]);
}
/**
* Inverse order version of {@link LRUCache.values}
*
* Return a generator yielding the values in the cache,
* in order from least recently used to most recently used.
*/
*rvalues() {
for (const e of M(this, R, Ft).call(this))
h(this, G)[e] !== void 0 && !M(this, R, oe).call(this, h(this, G)[e]) && (yield h(this, G)[e]);
}
/**
* Iterating over the cache itself yields the same results as
* {@link LRUCache.entries}
*/
[(Qo = Symbol.iterator, Xo = Symbol.toStringTag, Qo)]() {
return this.entries();
}
/**
* Find a value for which the supplied fn method returns a truthy value,
* similar to `Array.find()`. fn is called as `fn(value, key, cache)`.
*/
find(e, t = {}) {
for (const r of M(this, R, Wt).call(this)) {
const s = h(this, G)[r], i = M(this, R, oe).call(this, s) ? s.__staleWhileFetching : s;
if (i !== void 0 && e(i, h(this, ae)[r], this))
return this.get(h(this, ae)[r], t);
}
}
/**
* Call the supplied function on each item in the cache, in order from most
* recently used to least recently used.
*
* `fn` is called as `fn(value, key, cache)`.
*
* If `thisp` is provided, function will be called in the `this`-context of
* the provided object, or the cache if no `thisp` object is provided.
*
* Does not update age or recenty of use, or iterate over stale values.
*/
forEach(e, t = this) {
for (const r of M(this, R, Wt).call(this)) {
const s = h(this, G)[r], i = M(this, R, oe).call(this, s) ? s.__staleWhileFetching : s;
i !== void 0 && e.call(t, i, h(this, ae)[r], this);
}
}
/**
* The same as {@link LRUCache.forEach} but items are iterated over in
* reverse order. (ie, less recently used items are iterated over first.)
*/
rforEach(e, t = this) {
for (const r of M(this, R, Ft).call(this)) {
const s = h(this, G)[r], i = M(this, R, oe).call(this, s) ? s.__staleWhileFetching : s;
i !== void 0 && e.call(t, i, h(this, ae)[r], this);
}
}
/**
* Delete any stale entries. Returns true if anything was removed,
* false otherwise.
*/
purgeStale() {
let e = !1;
for (const t of M(this, R, Ft).call(this, { allowStale: !0 }))
h(this, je).call(this, t) && (M(this, R, Gt).call(this, h(this, ae)[t], "expire"), e = !0);
return e;
}
/**
* Get the extended info about a given entry, to get its value, size, and
* TTL info simultaneously. Returns `undefined` if the key is not present.
*
* Unlike {@link LRUCache#dump}, which is designed to be portable and survive
* serialization, the `start` value is always the current timestamp, and the
* `ttl` is a calculated remaining time to live (negative if expired).
*
* Always returns stale values, if their info is found in the cache, so be
* sure to check for expirations (ie, a negative {@link LRUCache.Entry#ttl})
* if relevant.
*/
info(e) {
const t = h(this, fe).get(e);
if (t === void 0)
return;
const r = h(this, G)[t], s = M(this, R, oe).call(this, r) ? r.__staleWhileFetching : r;
if (s === void 0)
return;
const i = { value: s };
if (h(this, Me) && h(this, et)) {
const o = h(this, Me)[t], a = h(this, et)[t];
if (o && a) {
const c = o - (_n.now() - a);
i.ttl = c, i.start = Date.now();
}
}
return h(this, Qe) && (i.size = h(this, Qe)[t]), i;
}
/**
* Return an array of [key, {@link LRUCache.Entry}] tuples which can be
* passed to {@link LRLUCache#load}.
*
* The `start` fields are calculated relative to a portable `Date.now()`
* timestamp, even if `performance.now()` is available.
*
* Stale entries are always included in the `dump`, even if
* {@link LRUCache.OptionsBase.allowStale} is false.
*
* Note: this returns an actual array, not a generator, so it can be more
* easily passed around.
*/
dump() {
const e = [];
for (const t of M(this, R, Wt).call(this, { allowStale: !0 })) {
const r = h(this, ae)[t], s = h(this, G)[t], i = M(this, R, oe).call(this, s) ? s.__staleWhileFetching : s;
if (i === void 0 || r === void 0)
continue;
const o = { value: i };
if (h(this, Me) && h(this, et)) {
o.ttl = h(this, Me)[t];
const a = _n.now() - h(this, et)[t];
o.start = Math.floor(Date.now() - a);
}
h(this, Qe) && (o.size = h(this, Qe)[t]), e.unshift([r, o]);
}
return e;
}
/**
* Reset the cache and load in the items in entries in the order listed.
*
* The shape of the resulting cache may be different if the same options are
* not used in both caches.
*
* The `start` fields are assumed to be calculated relative to a portable
* `Date.now()` timestamp, even if `performance.now()` is available.
*/
load(e) {
this.clear();
for (const [t, r] of e) {
if (r.start) {
const s = Date.now() - r.start;
r.start = _n.now() - s;
}
this.set(t, r.value, r);
}
}
/**
* Add a value to the cache.
*
* Note: if `undefined` is specified as a value, this is an alias for
* {@link LRUCache#delete}
*
* Fields on the {@link LRUCache.SetOptions} options param will override
* their corresponding values in the constructor options for the scope
* of this single `set()` operation.
*
* If `start` is provided, then that will set the effective start
* time for the TTL calculation. Note that this must be a previous
* value of `performance.now()` if supported, or a previous value of
* `Date.now()` if not.
*
* Options object may also include `size`, which will prevent
* calling the `sizeCalculation` function and just use the specified
* number if it is a positive integer, and `noDisposeOnSet` which
* will prevent calling a `dispose` function in the case of
* overwrites.
*
* If the `size` (or return value of `sizeCalculation`) for a given
* entry is greater than `maxEntrySize`, then the item will not be
* added to the cache.
*
* Will update the recency of the entry.
*
* If the value is `undefined`, then this is an alias for
* `cache.delete(key)`. `undefined` is never stored in the cache.
*/
set(e, t, r = {}) {
var f, m, b, g, p;
if (t === void 0)
return this.delete(e), this;
const { ttl: s = this.ttl, start: i, noDisposeOnSet: o = this.noDisposeOnSet, sizeCalculation: a = this.sizeCalculation, status: c } = r;
let { noUpdateTTL: l = this.noUpdateTTL } = r;
const d = h(this, Tr).call(this, e, t, r.size || 0, a);
if (this.maxEntrySize && d > this.maxEntrySize)
return c && (c.set = "miss", c.maxEntrySizeExceeded = !0), M(this, R, Gt).call(this, e, "set"), this;
let u = h(this, pe) === 0 ? void 0 : h(this, fe).get(e);
if (u === void 0)
u = h(this, pe) === 0 ? h(this, me) : h(this, Xe).length !== 0 ? h(this, Xe).pop() : h(this, pe) === h(this, Fe) ? M(this, R, Vr).call(this, !1) : h(this, pe), h(this, ae)[u] = e, h(this, G)[u] = t, h(this, fe).set(e, u), h(this, Oe)[h(this, me)] = u, h(this, He)[u] = h(this, me), q(this, me, u), Ur(this, pe)._++, h(this, Nn).call(this, u, d, c), c && (c.set = "add"), l = !1;
else {
M(this, R, tr).call(this, u);
const y = h(this, G)[u];
if (t !== y) {
if (h(this, Jt) && M(this, R, oe).call(this, y)) {
y.__abortController.abort(new Error("replaced"));
const { __staleWhileFetching: w } = y;
w !== void 0 && !o && (h(this, tt) && ((f = h(this, Ge)) == null || f.call(this, w, e, "set")), h(this, Ie) && ((m = h(this, we)) == null || m.push([w, e, "set"])));
} else o || (h(this, tt) && ((b = h(this, Ge)) == null || b.call(this, y, e, "set")), h(this, Ie) && ((g = h(this, we)) == null || g.push([y, e, "set"])));
if (h(this, pn).call(this, u), h(this, Nn).call(this, u, d, c), h(this, G)[u] = t, c) {
c.set = "replace";
const w = y && M(this, R, oe).call(this, y) ? y.__staleWhileFetching : y;
w !== void 0 && (c.oldValue = w);
}
} else c && (c.set = "update");
}
if (s !== 0 && !h(this, Me) && M(this, R, Js).call(this), h(this, Me) && (l || h(this, Ar).call(this, u, s, i), c && h(this, Tt).call(this, c, u)), !o && h(this, Ie) && h(this, we)) {
const y = h(this, we);
let w;
for (; w = y == null ? void 0 : y.shift(); )
(p = h(this, Ye)) == null || p.call(this, ...w);
}
return this;
}
/**
* Evict the least recently used item, returning its value or
* `undefined` if cache is empty.
*/
pop() {
var e;
try {
for (; h(this, pe); ) {
const t = h(this, G)[h(this, ke)];
if (M(this, R, Vr).call(this, !0), M(this, R, oe).call(this, t)) {
if (t.__staleWhileFetching)
return t.__staleWhileFetching;
} else if (t !== void 0)
return t;
}
} finally {
if (h(this, Ie) && h(this, we)) {
const t = h(this, we);
let r;
for (; r = t == null ? void 0 : t.shift(); )
(e = h(this, Ye)) == null || e.call(this, ...r);
}
}
}
/**
* Check if a key is in the cache, without updating the recency of use.
* Will return false if the item is stale, even though it is technically
* in the cache.
*
* Check if a key is in the cache, without updating the recency of
* use. Age is updated if {@link LRUCache.OptionsBase.updateAgeOnHas} is set
* to `true` in either the options or the constructor.
*
* Will return `false` if the item is stale, even though it is technically in
* the cache. The difference can be determined (if it matters) by using a
* `status` argument, and inspecting the `has` field.
*
* Will not update item age unless
* {@link LRUCache.OptionsBase.updateAgeOnHas} is set.
*/
has(e, t = {}) {
const { updateAgeOnHas: r = this.updateAgeOnHas, status: s } = t, i = h(this, fe).get(e);
if (i !== void 0) {
const o = h(this, G)[i];
if (M(this, R, oe).call(this, o) && o.__staleWhileFetching === void 0)
return !1;
if (h(this, je).call(this, i))
s && (s.has = "stale", h(this, Tt).call(this, s, i));
else return r && h(this, fn).call(this, i), s && (s.has = "hit", h(this, Tt).call(this, s, i)), !0;
} else s && (s.has = "miss");
return !1;
}
/**
* Like {@link LRUCache#get} but doesn't update recency or delete stale
* items.
*
* Returns `undefined` if the item is stale, unless
* {@link LRUCache.OptionsBase.allowStale} is set.
*/
peek(e, t = {}) {
const { allowStale: r = this.allowStale } = t, s = h(this, fe).get(e);
if (s === void 0 || !r && h(this, je).call(this, s))
return;
const i = h(this, G)[s];
return M(this, R, oe).call(this, i) ? i.__staleWhileFetching : i;
}
async fetch(e, t = {}) {
const {
// get options
allowStale: r = this.allowStale,
updateAgeOnGet: s = this.updateAgeOnGet,
noDeleteOnStaleGet: i = this.noDeleteOnStaleGet,
// set options
ttl: o = this.ttl,
noDisposeOnSet: a = this.noDisposeOnSet,
size: c = 0,
sizeCalculation: l = this.sizeCalculation,
noUpdateTTL: d = this.noUpdateTTL,
// fetch exclusive options
noDeleteOnFetchRejection: u = this.noDeleteOnFetchRejection,
allowStaleOnFetchRejection: f = this.allowStaleOnFetchRejection,
ignoreFetchAbort: m = this.ignoreFetchAbort,
allowStaleOnFetchAbort: b = this.allowStaleOnFetchAbort,
context: g,
forceRefresh: p = !1,
status: y,
signal: w
} = t;
if (!h(this, Jt))
return y && (y.fetch = "get"), this.get(e, {
allowStale: r,
updateAgeOnGet: s,
noDeleteOnStaleGet: i,
status: y
});
const x = {
allowStale: r,
updateAgeOnGet: s,
noDeleteOnStaleGet: i,
ttl: o,
noDisposeOnSet: a,
size: c,
sizeCalculation: l,
noUpdateTTL: d,
noDeleteOnFetchRejection: u,
allowStaleOnFetchRejection: f,
allowStaleOnFetchAbort: b,
ignoreFetchAbort: m,
status: y,
signal: w
};
let A = h(this, fe).get(e);
if (A === void 0) {
y && (y.fetch = "miss");
const T = M(this, R, Kr).call(this, e, A, x, g);
return T.__returned = T;
} else {
const T = h(this, G)[A];
if (M(this, R, oe).call(this, T)) {
const z = r && T.__staleWhileFetching !== void 0;
return y && (y.fetch = "inflight", z && (y.returnedStale = !0)), z ? T.__staleWhileFetching : T.__returned = T;
}
const _ = h(this, je).call(this, A);
if (!p && !_)
return y && (y.fetch = "hit"), M(this, R, tr).call(this, A), s && h(this, fn).call(this, A), y && h(this, Tt).call(this, y, A), T;
const S = M(this, R, Kr).call(this, e, A, x, g), N = S.__staleWhileFetching !== void 0 && r;
return y && (y.fetch = _ ? "stale" : "refresh", N && _ && (y.returnedStale = !0)), N ? S.__staleWhileFetching : S.__returned = S;
}
}
async forceFetch(e, t = {}) {
const r = await this.fetch(e, t);
if (r === void 0)
throw new Error("fetch() returned undefined");
return r;
}
memo(e, t = {}) {
const r = h(this, Rn);
if (!r)
throw new Error("no memoMethod provided to constructor");
const { context: s, forceRefresh: i, ...o } = t, a = this.get(e, o);
if (!i && a !== void 0)
return a;
const c = r(e, a, {
options: o,
context: s
});
return this.set(e, c, o), c;
}
/**
* Return a value from the cache. Will update the recency of the cache
* entry found.
*
* If the key is not found, get() will return `undefined`.
*/
get(e, t = {}) {
const { allowStale: r = this.allowStale, updateAgeOnGet: s = this.updateAgeOnGet, noDeleteOnStaleGet: i = this.noDeleteOnStaleGet, status: o } = t, a = h(this, fe).get(e);
if (a !== void 0) {
const c = h(this, G)[a], l = M(this, R, oe).call(this, c);
return o && h(this, Tt).call(this, o, a), h(this, je).call(this, a) ? (o && (o.get = "stale"), l ? (o && r && c.__staleWhileFetching !== void 0 && (o.returnedStale = !0), r ? c.__staleWhileFetching : void 0) : (i || M(this, R, Gt).call(this, e, "expire"), o && r && (o.returnedStale = !0), r ? c : void 0)) : (o && (o.get = "hit"), l ? c.__staleWhileFetching : (M(this, R, tr).call(this, a), s && h(this, fn).call(this, a), c));
} else o && (o.get = "miss");
}
/**
* Deletes a key out of the cache.
*
* Returns true if the key was deleted, false otherwise.
*/
delete(e) {
return M(this, R, Gt).call(this, e, "delete");
}
/**
* Clear the cache entirely, throwing away all values.
*/
clear() {
return M(this, R, ei).call(this, "delete");
}
};
Fe = new WeakMap(), Ue = new WeakMap(), Ge = new WeakMap(), Ye = new WeakMap(), $n = new WeakMap(), Rn = new WeakMap(), pe = new WeakMap(), Je = new WeakMap(), fe = new WeakMap(), ae = new WeakMap(), G = new WeakMap(), Oe = new WeakMap(), He = new WeakMap(), ke = new WeakMap(), me = new WeakMap(), Xe = new WeakMap(), we = new WeakMap(), Qe = new WeakMap(), et = new WeakMap(), Me = new WeakMap(), tt = new WeakMap(), Jt = new WeakMap(), Ie = new WeakMap(), R = new WeakSet(), Js = function() {
const e = new qr(h(this, Fe)), t = new qr(h(this, Fe));
q(this, Me, e), q(this, et, t), q(this, Ar, (i, o, a = _n.now()) => {
if (t[i] = o !== 0 ? a : 0, e[i] = o, o !== 0 && this.ttlAutopurge) {
const c = setTimeout(() => {
h(this, je).call(this, i) && M(this, R, Gt).call(this, h(this, ae)[i], "expire");
}, o + 1);
c.unref && c.unref();
}
}), q(this, fn, (i) => {
t[i] = e[i] !== 0 ? _n.now() : 0;
}), q(this, Tt, (i, o) => {
if (e[o]) {
const a = e[o], c = t[o];
if (!a || !c)
return;
i.ttl = a, i.start = c, i.now = r || s();
const l = i.now - c;
i.remainingTTL = a - l;
}
});
let r = 0;
const s = () => {
const i = _n.now();
if (this.ttlResolution > 0) {
r = i;
const o = setTimeout(() => r = 0, this.ttlResolution);
o.unref && o.unref();
}
return i;
};
this.getRemainingTTL = (i) => {
const o = h(this, fe).get(i);
if (o === void 0)
return 0;
const a = e[o], c = t[o];
if (!a || !c)
return 1 / 0;
const l = (r || s()) - c;
return a - l;
}, q(this, je, (i) => {
const o = t[i], a = e[i];
return !!a && !!o && (r || s()) - o > a;
});
}, fn = new WeakMap(), Tt = new WeakMap(), Ar = new WeakMap(), je = new WeakMap(), aa = function() {
const e = new qr(h(this, Fe));
q(this, Je, 0), q(this, Qe, e), q(this, pn, (t) => {
q(this, Je, h(this, Je) - e[t]), e[t] = 0;
}), q(this, Tr, (t, r, s, i) => {
if (M(this, R, oe).call(this, r))
return 0;
if (!Kt(s))
if (i) {
if (typeof i != "function")
throw new TypeError("sizeCalculation must be a function");
if (s = i(r, t), !Kt(s))
throw new TypeError("sizeCalculation return invalid (expect positive integer)");
} else
throw new TypeError("invalid size value (must be positive integer). When maxSize or maxEntrySize is used, sizeCalculation or size must be set.");
return s;
}), q(this, Nn, (t, r, s) => {
if (e[t] = r, h(this, Ue)) {
const i = h(this, Ue) - e[t];
for (; h(this, Je) > i; )
M(this, R, Vr).call(this, !0);
}
q(this, Je, h(this, Je) + e[t]), s && (s.entrySize = r, s.totalCalculatedSize = h(this, Je));
});
}, pn = new WeakMap(), Nn = new WeakMap(), Tr = new WeakMap(), Wt = function* ({ allowStale: e = this.allowStale } = {}) {
if (h(this, pe))
for (let t = h(this, me); !(!M(this, R, Xs).call(this, t) || ((e || !h(this, je).call(this, t)) && (yield t), t === h(this, ke))); )
t = h(this, He)[t];
}, Ft = function* ({ allowStale: e = this.allowStale } = {}) {
if (h(this, pe))
for (let t = h(this, ke); !(!M(this, R, Xs).call(this, t) || ((e || !h(this, je).call(this, t)) && (yield t), t === h(this, me))); )
t = h(this, Oe)[t];
}, Xs = function(e) {
return e !== void 0 && h(this, fe).get(h(this, ae)[e]) === e;
}, Vr = function(e) {
var i, o;
const t = h(this, ke), r = h(this, ae)[t], s = h(this, G)[t];
return h(this, Jt) && M(this, R, oe).call(this, s) ? s.__abortController.abort(new Error("evicted")) : (h(this, tt) || h(this, Ie)) && (h(this, tt) && ((i = h(this, Ge)) == null || i.call(this, s, r, "evict")), h(this, Ie) && ((o = h(this, we)) == null || o.push([s, r, "evict"]))), h(this, pn).call(this, t), e && (h(this, ae)[t] = void 0, h(this, G)[t] = void 0, h(this, Xe).push(t)), h(this, pe) === 1 ? (q(this, ke, q(this, me, 0)), h(this, Xe).length = 0) : q(this, ke, h(this, Oe)[t]), h(this, fe).delete(r), Ur(this, pe)._--, t;
}, Kr = function(e, t, r, s) {
const i = t === void 0 ? void 0 : h(this, G)[t];
if (M(this, R, oe).call(this, i))
return i;
const o = new Gr(), { signal: a } = r;
a == null || a.addEventListener("abort", () => o.abort(a.reason), {
signal: o.signal
});
const c = {
signal: o.signal,
options: r,
context: s
}, l = (g, p = !1) => {
const { aborted: y } = o.signal, w = r.ignoreFetchAbort && g !== void 0;
if (r.status && (y && !p ? (r.status.fetchAborted = !0, r.status.fetchError = o.signal.reason, w && (r.status.fetchAbortIgnored = !0)) : r.status.fetchResolved = !0), y && !w && !p)
return u(o.signal.reason);
const x = m;
return h(this, G)[t] === m && (g === void 0 ? x.__staleWhileFetching ? h(this, G)[t] = x.__staleWhileFetching : M(this, R, Gt).call(this, e, "fetch") : (r.status && (r.status.fetchUpdated = !0), this.set(e, g, c.options))), g;
}, d = (g) => (r.status && (r.status.fetchRejected = !0, r.status.fetchError = g), u(g)), u = (g) => {
const { aborted: p } = o.signal, y = p && r.allowStaleOnFetchAbort, w = y || r.allowStaleOnFetchRejection, x = w || r.noDeleteOnFetchRejection, A = m;
if (h(this, G)[t] === m && (!x || A.__staleWhileFetching === void 0 ? M(this, R, Gt).call(this, e, "fetch") : y || (h(this, G)[t] = A.__staleWhileFetching)), w)
return r.status && A.__staleWhileFetching !== void 0 && (r.status.returnedStale = !0), A.__staleWhileFetching;
if (A.__returned === A)
throw g;
}, f = (g, p) => {
var w;
const y = (w = h(this, $n)) == null ? void 0 : w.call(this, e, i, c);
y && y instanceof Promise && y.then((x) => g(x === void 0 ? void 0 : x), p), o.signal.addEventListener("abort", () => {
(!r.ignoreFetchAbort || r.allowStaleOnFetchAbort) && (g(void 0), r.allowStaleOnFetchAbort && (g = (x) => l(x, !0)));
});
};
r.status && (r.status.fetchDispatched = !0);
const m = new Promise(f).then(l, d), b = Object.assign(m, {
__abortController: o,
__staleWhileFetching: i,
__returned: void 0
});
return t === void 0 ? (this.set(e, b, { ...c.options, status: void 0 }), t = h(this, fe).get(e)) : h(this, G)[t] = b, b;
}, oe = function(e) {
if (!h(this, Jt))
return !1;
const t = e;
return !!t && t instanceof Promise && t.hasOwnProperty("__staleWhileFetching") && t.__abortController instanceof Gr;
}, Qs = function(e, t) {
h(this, He)[t] = e, h(this, Oe)[e] = t;
}, tr = function(e) {
e !== h(this, me) && (e === h(this, ke) ? q(this, ke, h(this, Oe)[e]) : M(this, R, Qs).call(this, h(this, He)[e], h(this, Oe)[e]), M(this, R, Qs).call(this, h(this, me), e), q(this, me, e));
}, Gt = function(e, t) {
var s, i, o, a;
let r = !1;
if (h(this, pe) !== 0) {
const c = h(this, fe).get(e);
if (c !== void 0)
if (r = !0, h(this, pe) === 1)
M(this, R, ei).call(this, t);
else {
h(this, pn).call(this, c);
const l = h(this, G)[c];
if (M(this, R, oe).call(this, l) ? l.__abortController.abort(new Error("deleted")) : (h(this, tt) || h(this, Ie)) && (h(this, tt) && ((s = h(this, Ge)) == null || s.call(this, l, e, t)), h(this, Ie) && ((i = h(this, we)) == null || i.push([l, e, t]))), h(this, fe).delete(e), h(this, ae)[c] = void 0, h(this, G)[c] = void 0, c === h(this, me))
q(this, me, h(this, He)[c]);
else if (c === h(this, ke))
q(this, ke, h(this, Oe)[c]);
else {
const d = h(this, He)[c];
h(this, Oe)[d] = h(this, Oe)[c];
const u = h(this, Oe)[c];
h(this, He)[u] = h(this, He)[c];
}
Ur(this, pe)._--, h(this, Xe).push(c);
}
}
if (h(this, Ie) && ((o = h(this, we)) != null && o.length)) {
const c = h(this, we);
let l;
for (; l = c == null ? void 0 : c.shift(); )
(a = h(this, Ye)) == null || a.call(this, ...l);
}
return r;
}, ei = function(e) {
var t, r, s;
for (const i of M(this, R, Ft).call(this, { allowStale: !0 })) {
const o = h(this, G)[i];
if (M(this, R, oe).call(this, o))
o.__abortController.abort(new Error("deleted"));
else {
const a = h(this, ae)[i];
h(this, tt) && ((t = h(this, Ge)) == null || t.call(this, o, a, e)), h(this, Ie) && ((r = h(this, we)) == null || r.push([o, a, e]));
}
}
if (h(this, fe).clear(), h(this, G).fill(void 0), h(this, ae).fill(void 0), h(this, Me) && h(this, et) && (h(this, Me).fill(0), h(this, et).fill(0)), h(this, Qe) && h(this, Qe).fill(0), q(this, ke, 0), q(this, me, 0), h(this, Xe).length = 0, q(this, Je, 0), q(this, pe, 0), h(this, Ie) && h(this, we)) {
const i = h(this, we);
let o;
for (; o = i == null ? void 0 : i.shift(); )
(s = h(this, Ye)) == null || s.call(this, ...o);
}
};
let Ys = po;
function wo(n) {
if (!Number.isSafeInteger(n) || n < 0)
throw new Error(`Wrong positive integer: ${n}`);
}
function ca(n, ...e) {
if (!(n instanceof Uint8Array))
throw new Error("Expected Uint8Array");
if (e.length > 0 && !e.includes(n.length))
throw new Error(`Expected Uint8Array of length ${e}, not of length=${n.length}`);
}
function pl(n) {
if (typeof n != "function" || typeof n.create != "function")
throw new Error("Hash should be wrapped by utils.wrapConstructor");
wo(n.outputLen), wo(n.blockLen);
}
function Yr(n, e = !0) {
if (n.destroyed)
throw new Error("Hash instance has been destroyed");
if (e && n.finished)
throw new Error("Hash#digest() has already been called");
}
function gl(n, e) {
ca(n);
const t = e.outputLen;
if (n.length < t)
throw new Error(`digestInto() expects output buffer of length at least ${t}`);
}
const Os = typeof globalThis == "object" && "crypto" in globalThis ? globalThis.crypto : void 0;
/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */
const la = (n) => n instanceof Uint8Array, Is = (n) => new DataView(n.buffer, n.byteOffset, n.byteLength), ot = (n, e) => n << 32 - e | n >>> e, yl = new Uint8Array(new Uint32Array([287454020]).buffer)[0] === 68;
if (!yl)
throw new Error("Non little-endian hardware is not supported");
function ml(n) {
if (typeof n != "string")
throw new Error(`utf8ToBytes expected string, got ${typeof n}`);
return new Uint8Array(new TextEncoder().encode(n));
}
function Oi(n) {
if (typeof n == "string" && (n = ml(n)), !la(n))
throw new Error(`expected Uint8Array, got ${typeof n}`);
return n;
}
function wl(...n) {
const e = new Uint8Array(n.reduce((r, s) => r + s.length, 0));
let t = 0;
return n.forEach((r) => {
if (!la(r))
throw new Error("Uint8Array expected");
e.set(r, t), t += r.length;
}), e;
}
let ua = class {
// Safe version that clones internal state
clone() {
return this._cloneInto();
}
};
function bl(n) {
const e = (r) => n().update(Oi(r)).digest(), t = n();
return e.outputLen = t.outputLen, e.blockLen = t.blockLen, e.create = () => n(), e;
}
function da(n = 32) {
if (Os && typeof Os.getRandomValues == "function")
return Os.getRandomValues(new Uint8Array(n));
throw new Error("crypto.getRandomValues must be defined");
}
function vl(n, e, t, r) {
if (typeof n.setBigUint64 == "function")
return n.setBigUint64(e, t, r);
const s = BigInt(32), i = BigInt(4294967295), o = Number(t >> s & i), a = Number(t & i), c = r ? 4 : 0, l = r ? 0 : 4;
n.setUint32(e + c, o, r), n.setUint32(e + l, a, r);
}
let xl = class extends ua {
constructor(e, t, r, s) {
super(), this.blockLen = e, this.outputLen = t, this.padOffset = r, this.isLE = s, this.finished = !1, this.length = 0, this.pos = 0, this.destroyed = !1, this.buffer = new Uint8Array(e), this.view = Is(this.buffer);
}
update(e) {
Yr(this);
const { view: t, buffer: r, blockLen: s } = this;
e = Oi(e);
const i = e.length;
for (let o = 0; o < i; ) {
const a = Math.min(s - this.pos, i - o);
if (a === s) {
const c = Is(e);
for (; s <= i - o; o += s)
this.process(c, o);
continue;
}
r.set(e.subarray(o, o + a), this.pos), this.pos += a, o += a, this.pos === s && (this.process(t, 0), this.pos = 0);
}
return this.length += e.length, this.roundClean(), this;
}
digestInto(e) {
Yr(this), gl(e, this), this.finished = !0;
const { buffer: t, view: r, blockLen: s, isLE: i } = this;
let { pos: o } = this;
t[o++] = 128, this.buffer.subarray(o).fill(0), this.padOffset > s - o && (this.process(r, 0), o = 0);
for (let u = o; u < s; u++)
t[u] = 0;
vl(r, s - 8, BigInt(this.length * 8), i), this.process(r, 0);
const a = Is(e), c = this.outputLen;
if (c % 4)
throw new Error("_sha2: outputLen should be aligned to 32bit");
const l = c / 4, d = this.get();
if (l > d.length)
throw new Error("_sha2: outputLen bigger than state");
for (let u = 0; u < l; u++)
a.setUint32(4 * u, d[u], i);
}
digest() {
const { buffer: e, outputLen: t } = this;
this.digestInto(e);
const r = e.slice(0, t);
return this.destroy(), r;
}
_cloneInto(e) {
e || (e = new this.constructor()), e.set(...this.get());
const { blockLen: t, buffer: r, length: s, finished: i, destroyed: o, pos: a } = this;
return e.length = s, e.pos = a, e.finished = i, e.destroyed = o, s % t && e.buffer.set(r), e;
}
};
const El = (n, e, t) => n & e ^ ~n & t, _l = (n, e, t) => n & e ^ n & t ^ e & t, Sl = /* @__PURE__ */ new Uint32Array([
1116352408,
1899447441,
3049323471,
3921009573,
961987163,
1508970993,
2453635748,
2870763221,
3624381080,
310598401,
607225278,
1426881987,
1925078388,
2162078206,
2614888103,
3248222580,
3835390401,
4022224774,
264347078,
604807628,
770255983,
1249150122,
1555081692,
1996064986,
2554220882,
2821834349,
2952996808,
3210313671,
3336571891,
3584528711,
113926993,
338241895,
666307205,
773529912,
1294757372,
1396182291,
1695183700,
1986661051,
2177026350,
2456956037,
2730485921,
2820302411,
3259730800,
3345764771,
3516065817,
3600352804,
4094571909,
275423344,
430227734,
506948616,
659060556,
883997877,
958139571,
1322822218,
1537002063,
1747873779,
1955562222,
2024104815,
2227730452,
2361852424,
2428436474,
2756734187,
3204031479,
3329325298
]), Mt = /* @__PURE__ */ new Uint32Array([
1779033703,
3144134277,
1013904242,
2773480762,
1359893119,
2600822924,
528734635,
1541459225
]), jt = /* @__PURE__ */ new Uint32Array(64);
let kl = class extends xl {
constructor() {
super(64, 32, 8, !1), this.A = Mt[0] | 0, this.B = Mt[1] | 0, this.C = Mt[2] | 0, this.D = Mt[3] | 0, this.E = Mt[4] | 0, this.F = Mt[5] | 0, this.G = Mt[6] | 0, this.H = Mt[7] | 0;
}
get() {
const { A: e, B: t, C: r, D: s, E: i, F: o, G: a, H: c } = this;
return [e, t, r, s, i, o, a, c];
}
// prettier-ignore
set(e, t, r, s, i, o, a, c) {
this.A = e | 0, this.B = t | 0, this.C = r | 0, this.D = s | 0, this.E = i | 0, this.F = o | 0, this.G = a | 0, this.H = c | 0;
}
process(e, t) {
for (let u = 0; u < 16; u++, t += 4)
jt[u] = e.getUint32(t, !1);
for (let u = 16; u < 64; u++) {
const f = jt[u - 15], m = jt[u - 2], b = ot(f, 7) ^ ot(f, 18) ^ f >>> 3, g = ot(m, 17) ^ ot(m, 19) ^ m >>> 10;
jt[u] = g + jt[u - 7] + b + jt[u - 16] | 0;
}
let { A: r, B: s, C: i, D: o, E: a, F: c, G: l, H: d } = this;
for (let u = 0; u < 64; u++) {
const f = ot(a, 6) ^ ot(a, 11) ^ ot(a, 25), m = d + f + El(a, c, l) + Sl[u] + jt[u] | 0, g = (ot(r, 2) ^ ot(r, 13) ^ ot(r, 22)) + _l(r, s, i) | 0;
d = l, l = c, c = a, a = o + m | 0, o = i, i = s, s = r, r = m + g | 0;
}
r = r + this.A | 0, s = s + this.B | 0, i = i + this.C | 0, o = o + this.D | 0, a = a + this.E | 0, c = c + this.F | 0, l = l + this.G | 0, d = d + this.H | 0, this.set(r, s, i, o, a, c, l, d);
}
roundClean() {
jt.fill(0);
}
destroy() {
this.set(0, 0, 0, 0, 0, 0, 0, 0), this.buffer.fill(0);
}
};
const ti = /* @__PURE__ */ bl(() => new kl());
/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
const ha = BigInt(0), ds = BigInt(1), Al = BigInt(2), hs = (n) => n instanceof Uint8Array, Tl = /* @__PURE__ */ Array.from({ length: 256 }, (n, e) => e.toString(16).padStart(2, "0"));
function Hn(n) {
if (!hs(n))
throw new Error("Uint8Array expected");
let e = "";
for (let t = 0; t < n.length; t++)
e += Tl[n[t]];
return e;
}
function fa(n) {
const e = n.toString(16);
return e.length & 1 ? `0${e}` : e;
}
function Ii(n) {
if (typeof n != "string")
throw new Error("hex string expected, got " + typeof n);
return BigInt(n === "" ? "0" : `0x${n}`);
}
function Mn(n) {
if (typeof n != "string")
throw new Error("hex string expected, got " + typeof n);
const e = n.length;
if (e % 2)
throw new Error("padded hex string expected, got unpadded hex of length " + e);
const t = new Uint8Array(e / 2);
for (let r = 0; r < t.length; r++) {
const s = r * 2, i = n.slice(s, s + 2), o = Number.parseInt(i, 16);
if (Number.isNaN(o) || o < 0)
throw new Error("Invalid byte sequence");
t[r] = o;
}
return t;
}
function Le(n) {
return Ii(Hn(n));
}
function Ci(n) {
if (!hs(n))
throw new Error("Uint8Array expected");
return Ii(Hn(Uint8Array.from(n).reverse()));
}
function en(n, e) {
return Mn(n.toString(16).padStart(e * 2, "0"));
}
function $i(n, e) {
return en(n, e).reverse();
}
function Bl(n) {
return Mn(fa(n));
}
function Ae(n, e, t) {
let r;
if (typeof e == "string")
try {
r = Mn(e);
} catch (i) {
throw new Error(`${n} must be valid hex string, got "${e}". Cause: ${i}`);
}
else if (hs(e))
r = Uint8Array.from(e);
else
throw new Error(`${n} must be hex string or Uint8Array`);
const s = r.length;
if (typeof t == "number" && s !== t)
throw new Error(`${n} expected ${t} bytes, got ${s}`);
return r;
}
function bn(...n) {
const e = new Uint8Array(n.reduce((r, s) => r + s.length, 0));
let t = 0;
return n.forEach((r) => {
if (!hs(r))
throw new Error("Uint8Array expected");
e.set(r, t), t += r.length;
}), e;
}
function Ol(n, e) {
if (n.length !== e.length)
return !1;
for (let t = 0; t < n.length; t++)
if (n[t] !== e[t])
return !1;
return !0;
}
function Il(n) {
if (typeof n != "string")
throw new Error(`utf8ToBytes expected string, got ${typeof n}`);
return new Uint8Array(new TextEncoder().encode(n));
}
function Cl(n) {
let e;
for (e = 0; n > ha; n >>= ds, e += 1)
;
return e;
}
function $l(n, e) {
return n >> BigInt(e) & ds;
}
const Rl = (n, e, t) => n | (t ? ds : ha) << BigInt(e), Ri = (n) => (Al << BigInt(n - 1)) - ds, Cs = (n) => new Uint8Array(n), bo = (n) => Uint8Array.from(n);
function pa(n, e, t) {
if (typeof n != "number" || n < 2)
throw new Error("hashLen must be a number");
if (typeof e != "number" || e < 2)
throw new Error("qByteLen must be a number");
if (typeof t != "function")
throw new Error("hmacFn must be a function");
let r = Cs(n), s = Cs(n), i = 0;
const o = () => {
r.fill(1), s.fill(0), i = 0;
}, a = (...u) => t(s, r, ...u), c = (u = Cs()) => {
s = a(bo([0]), u), r = a(), u.length !== 0 && (s = a(bo([1]), u), r = a());
}, l = () => {
if (i++ >= 1e3)
throw new Error("drbg: tried 1000 values");
let u = 0;
const f = [];
for (; u < e; ) {
r = a();
const m = r.slice();
f.push(m), u += r.length;
}
return bn(...f);
};
return (u, f) => {
o(), c(u);
let m;
for (; !(m = f(l())); )
c();
return o(), m;
};
}
const Nl = {
bigint: (n) => typeof n == "bigint",
function: (n) => typeof n == "function",
boolean: (n) => typeof n == "boolean",
string: (n) => typeof n == "string",
stringOrUint8Array: (n) => typeof n == "string" || n instanceof Uint8Array,
isSafeInteger: (n) => Number.isSafeInteger(n),
array: (n) => Array.isArray(n),
field: (n, e) => e.Fp.isValid(n),
hash: (n) => typeof n == "function" && Number.isSafeInteger(n.outputLen)
};
function Cr(n, e, t = {}) {
const r = (s, i, o) => {
const a = Nl[i];
if (typeof a != "function")
throw new Error(`Invalid validator "${i}", expected function`);
const c = n[s];
if (!(o && c === void 0) && !a(c, n))
throw new Error(`Invalid param ${String(s)}=${c} (${typeof c}), expected ${i}`);
};
for (const [s, i] of Object.entries(e))
r(s, i, !1);
for (const [s, i] of Object.entries(t))
r(s, i, !0);
return n;
}
const Ll = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
__proto__: null,
bitGet: $l,
bitLen: Cl,
bitMask: Ri,
bitSet: Rl,
bytesToHex: Hn,
bytesToNumberBE: Le,
bytesToNumberLE: Ci,
concatBytes: bn,
createHmacDrbg: pa,
ensureBytes: Ae,
equalBytes: Ol,
hexToBytes: Mn,
hexToNumber: Ii,
numberToBytesBE: en,
numberToBytesLE: $i,
numberToHexUnpadded: fa,
numberToVarBytesBE: Bl,
utf8ToBytes: Il,
validateObject: Cr
}, Symbol.toStringTag, { value: "Module" }));
/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
const xe = BigInt(0), ue = BigInt(1), cn = BigInt(2), Ul = BigInt(3), ni = BigInt(4), vo = BigInt(5), xo = BigInt(8);
BigInt(9);
BigInt(16);
function Se(n, e) {
const t = n % e;
return t >= xe ? t : e + t;
}
function Hl(n, e, t) {
if (t <= xe || e < xe)
throw new Error("Expected power/modulo > 0");
if (t === ue)
return xe;
let r = ue;
for (; e > xe; )
e & ue && (r = r * n % t), n = n * n % t, e >>= ue;
return r;
}
function De(n, e, t) {
let r = n;
for (; e-- > xe; )
r *= r, r %= t;
return r;
}
function ri(n, e) {
if (n === xe || e <= xe)
throw new Error(`invert: expected positive integers, got n=${n} mod=${e}`);
let t = Se(n, e), r = e, s = xe, i = ue;
for (; t !== xe; ) {
const a = r / t, c = r % t, l = s - i * a;
r = t, t = c, s = i, i = l;
}
if (r !== ue)
throw new Error("invert: does not exist");
return Se(s, e);
}
function Ml(n) {
const e = (n - ue) / cn;
let t, r, s;
for (t = n - ue, r = 0; t % cn === xe; t /= cn, r++)
;
for (s = cn; s < n && Hl(s, e, n) !== n - ue; s++)
;
if (r === 1) {
const o = (n + ue) / ni;
return function(c, l) {
const d = c.pow(l, o);
if (!c.eql(c.sqr(d), l))
throw new Error("Cannot find square root");
return d;
};
}
const i = (t + ue) / cn;
return function(a, c) {
if (a.pow(c, e) === a.neg(a.ONE))
throw new Error("Cannot find square root");
let l = r, d = a.pow(a.mul(a.ONE, s), t), u = a.pow(c, i), f = a.pow(c, t);
for (; !a.eql(f, a.ONE); ) {
if (a.eql(f, a.ZERO))
return a.ZERO;
let m = 1;
for (let g = a.sqr(f); m < l && !a.eql(g, a.ONE); m++)
g = a.sqr(g);
const b = a.pow(d, ue << BigInt(l - m - 1));
d = a.sqr(b), u = a.mul(u, b), f = a.mul(f, d), l = m;
}
return u;
};
}
function jl(n) {
if (n % ni === Ul) {
const e = (n + ue) / ni;
return function(r, s) {
const i = r.pow(s, e);
if (!r.eql(r.sqr(i), s))
throw new Error("Cannot find square root");
return i;
};
}
if (n % xo === vo) {
const e = (n - vo) / xo;
return function(r, s) {
const i = r.mul(s, cn), o = r.pow(i, e), a = r.mul(s, o), c = r.mul(r.mul(a, cn), o), l = r.mul(a, r.sub(c, r.ONE));
if (!r.eql(r.sqr(l), s))
throw new Error("Cannot find square root");
return l;
};
}
return Ml(n);
}
const Pl = [
"create",
"isValid",
"is0",
"neg",
"inv",
"sqrt",
"sqr",
"eql",
"add",
"sub",
"mul",
"pow",
"div",
"addN",
"subN",
"mulN",
"sqrN"
];
function Zl(n) {
const e = {
ORDER: "bigint",
MASK: "bigint",
BYTES: "isSafeInteger",
BITS: "isSafeInteger"
}, t = Pl.reduce((r, s) => (r[s] = "function", r), e);
return Cr(n, t);
}
function zl(n, e, t) {
if (t < xe)
throw new Error("Expected power > 0");
if (t === xe)
return n.ONE;
if (t === ue)
return e;
let r = n.ONE, s = e;
for (; t > xe; )
t & ue && (r = n.mul(r, s)), s = n.sqr(s), t >>= ue;
return r;
}
function Dl(n, e) {
const t = new Array(e.length), r = e.reduce((i, o, a) => n.is0(o) ? i : (t[a] = i, n.mul(i, o)), n.ONE), s = n.inv(r);
return e.reduceRight((i, o, a) => n.is0(o) ? i : (t[a] = n.mul(i, t[a]), n.mul(i, o)), s), t;
}
function ga(n, e) {
const t = e !== void 0 ? e : n.toString(2).length, r = Math.ceil(t / 8);
return { nBitLength: t, nByteLength: r };
}
function ql(n, e, t = !1, r = {}) {
if (n <= xe)
throw new Error(`Expected Field ORDER > 0, got ${n}`);
const { nBitLength: s, nByteLength: i } = ga(n, e);
if (i > 2048)
throw new Error("Field lengths over 2048 bytes are not supported");
const o = jl(n), a = Object.freeze({
ORDER: n,
BITS: s,
BYTES: i,
MASK: Ri(s),
ZERO: xe,
ONE: ue,
create: (c) => Se(c, n),
isValid: (c) => {
if (typeof c != "bigint")
throw new Error(`Invalid field element: expected bigint, got ${typeof c}`);
return xe <= c && c < n;
},
is0: (c) => c === xe,
isOdd: (c) => (c & ue) === ue,
neg: (c) => Se(-c, n),
eql: (c, l) => c === l,
sqr: (c) => Se(c * c, n),
add: (c, l) => Se(c + l, n),
sub: (c, l) => Se(c - l, n),
mul: (c, l) => Se(c * l, n),
pow: (c, l) => zl(a, c, l),
div: (c, l) => Se(c * ri(l, n), n),
// Same as above, but doesn't normalize
sqrN: (c) => c * c,
addN: (c, l) => c + l,
subN: (c, l) => c - l,
mulN: (c, l) => c * l,
inv: (c) => ri(c, n),
sqrt: r.sqrt || ((c) => o(a, c)),
invertBatch: (c) => Dl(a, c),
// TODO: do we really need constant cmov?
// We don't have const-time bigints anyway, so probably will be not very useful
cmov: (c, l, d) => d ? l : c,
toBytes: (c) => t ? $i(c, i) : en(c, i),
fromBytes: (c) => {
if (c.length !== i)
throw new Error(`Fp.fromBytes: expected ${i}, got ${c.length}`);
return t ? Ci(c) : Le(c);
}
});
return Object.freeze(a);
}
function ya(n) {
if (typeof n != "bigint")
throw new Error("field order must be bigint");
const e = n.toString(2).length;
return Math.ceil(e / 8);
}
function ma(n) {
const e = ya(n);
return e + Math.ceil(e / 2);
}
function Vl(n, e, t = !1) {
const r = n.length, s = ya(e), i = ma(e);
if (r < 16 || r < i || r > 1024)
throw new Error(`expected ${i}-1024 bytes of input, got ${r}`);
const o = t ? Le(n) : Ci(n), a = Se(o, e - ue) + ue;
return t ? $i(a, s) : en(a, s);
}
/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
const Kl = BigInt(0), $s = BigInt(1);
function Wl(n, e) {
const t = (s, i) => {
const o = i.negate();
return s ? o : i;
}, r = (s) => {
const i = Math.ceil(e / s) + 1, o = 2 ** (s - 1);
return { windows: i, windowSize: o };
};
return {
constTimeNegate: t,
// non-const time multiplication ladder
unsafeLadder(s, i) {
let o = n.ZERO, a = s;
for (; i > Kl; )
i & $s && (o = o.add(a)), a = a.double(), i >>= $s;
return o;
},
/**
* 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(s, i) {
const { windows: o, windowSize: a } = r(i), c = [];
let l = s, d = l;
for (let u = 0; u < o; u++) {
d = l, c.push(d);
for (let f = 1; f < a; f++)
d = d.add(l), c.push(d);
l = d.double();
}
return c;
},
/**
* 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(s, i, o) {
const { windows: a, windowSize: c } = r(s);
let l = n.ZERO, d = n.BASE;
const u = BigInt(2 ** s - 1), f = 2 ** s, m = BigInt(s);
for (let b = 0; b < a; b++) {
const g = b * c;
let p = Number(o & u);
o >>= m, p > c && (p -= f, o += $s);
const y = g, w = g + Math.abs(p) - 1, x = b % 2 !== 0, A = p < 0;
p === 0 ? d = d.add(t(x, i[y])) : l = l.add(t(A, i[w]));
}
return { p: l, f: d };
},
wNAFCached(s, i, o, a) {
const c = s._WINDOW_SIZE || 1;
let l = i.get(s);
return l || (l = this.precomputeWindow(s, c), c !== 1 && i.set(s, a(l))), this.wNAF(c, l, o);
}
};
}
function wa(n) {
return Zl(n.Fp), Cr(n, {
n: "bigint",
h: "bigint",
Gx: "field",
Gy: "field"
}, {
nBitLength: "isSafeInteger",
nByteLength: "isSafeInteger"
}), Object.freeze({
...ga(n.n, n.nBitLength),
...n,
p: n.Fp.ORDER
});
}
/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
function Fl(n) {
const e = wa(n);
Cr(e, {
a: "field",
b: "field"
}, {
allowedPrivateKeyLengths: "array",
wrapPrivateKey: "boolean",
isTorsionFree: "function",
clearCofactor: "function",
allowInfinityPoint: "boolean",
fromBytes: "function",
toBytes: "function"
});
const { endo: t, Fp: r, a: s } = e;
if (t) {
if (!r.eql(s, r.ZERO))
throw new Error("Endomorphism can only be defined for Koblitz curves that have a=0");
if (typeof t != "object" || typeof t.beta != "bigint" || typeof t.splitScalar != "function")
throw new Error("Expected endomorphism with beta: bigint and splitScalar: function");
}
return Object.freeze({ ...e });
}
const { bytesToNumberBE: Gl, hexToBytes: Yl } = Ll, hn = {
// asn.1 DER encoding utils
Err: class extends Error {
constructor(e = "") {
super(e);
}
},
_parseInt(n) {
const { Err: e } = hn;
if (n.length < 2 || n[0] !== 2)
throw new e("Invalid signature integer tag");
const t = n[1], r = n.subarray(2, t + 2);
if (!t || r.length !== t)
throw new e("Invalid signature integer: wrong length");
if (r[0] & 128)
throw new e("Invalid signature integer: negative");
if (r[0] === 0 && !(r[1] & 128))
throw new e("Invalid signature integer: unnecessary leading zero");
return { d: Gl(r), l: n.subarray(t + 2) };
},
toSig(n) {
const { Err: e } = hn, t = typeof n == "string" ? Yl(n) : n;
if (!(t instanceof Uint8Array))
throw new Error("ui8a expected");
let r = t.length;
if (r < 2 || t[0] != 48)
throw new e("Invalid signature tag");
if (t[1] !== r - 2)
throw new e("Invalid signature: incorrect length");
const { d: s, l: i } = hn._parseInt(t.subarray(2)), { d: o, l: a } = hn._parseInt(i);
if (a.length)
throw new e("Invalid signature: left bytes after parsing");
return { r: s, s: o };
},
hexFromSig(n) {
const e = (l) => Number.parseInt(l[0], 16) & 8 ? "00" + l : l, t = (l) => {
const d = l.toString(16);
return d.length & 1 ? `0${d}` : d;
}, r = e(t(n.s)), s = e(t(n.r)), i = r.length / 2, o = s.length / 2, a = t(i), c = t(o);
return `30${t(o + i + 4)}02${c}${s}02${a}${r}`;
}
}, Ot = BigInt(0), Ve = BigInt(1);
BigInt(2);
const Eo = BigInt(3);
BigInt(4);
function Jl(n) {
const e = Fl(n), { Fp: t } = e, r = e.toBytes || ((b, g, p) => {
const y = g.toAffine();
return bn(Uint8Array.from([4]), t.toBytes(y.x), t.toBytes(y.y));
}), s = e.fromBytes || ((b) => {
const g = b.subarray(1), p = t.fromBytes(g.subarray(0, t.BYTES)), y = t.fromBytes(g.subarray(t.BYTES, 2 * t.BYTES));
return { x: p, y };
});
function i(b) {
const { a: g, b: p } = e, y = t.sqr(b), w = t.mul(y, b);
return t.add(t.add(w, t.mul(b, g)), p);
}
if (!t.eql(t.sqr(e.Gy), i(e.Gx)))
throw new Error("bad generator point: equation left != right");
function o(b) {
return typeof b == "bigint" && Ot < b && b < e.n;
}
function a(b) {
if (!o(b))
throw new Error("Expected valid bigint: 0 < bigint < curve.n");
}
function c(b) {
const { allowedPrivateKeyLengths: g, nByteLength: p, wrapPrivateKey: y, n: w } = e;
if (g && typeof b != "bigint") {
if (b instanceof Uint8Array && (b = Hn(b)), typeof b != "string" || !g.includes(b.length))
throw new Error("Invalid key");
b = b.padStart(p * 2, "0");
}
let x;
try {
x = typeof b == "bigint" ? b : Le(Ae("private key", b, p));
} catch {
throw new Error(`private key must be ${p} bytes, hex or bigint, not ${typeof b}`);
}
return y && (x = Se(x, w)), a(x), x;
}
const l = /* @__PURE__ */ new Map();
function d(b) {
if (!(b instanceof u))
throw new Error("ProjectivePoint expected");
}
class u {
constructor(g, p, y) {
if (this.px = g, this.py = p, this.pz = y, g == null || !t.isValid(g))
throw new Error("x required");
if (p == null || !t.isValid(p))
throw new Error("y required");
if (y == null || !t.isValid(y))
throw new Error("z required");
}
// Does not validate if the point is on-curve.
// Use fromHex instead, or call assertValidity() later.
static fromAffine(g) {
const { x: p, y } = g || {};
if (!g || !t.isValid(p) || !t.isValid(y))
throw new Error("invalid affine point");
if (g instanceof u)
throw new Error("projective point not allowed");
const w = (x) => t.eql(x, t.ZERO);
return w(p) && w(y) ? u.ZERO : new u(p, y, t.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(g) {
const p = t.invertBatch(g.map((y) => y.pz));
return g.map((y, w) => y.toAffine(p[w])).map(u.fromAffine);
}
/**
* Converts hash string or Uint8Array to Point.
* @param hex short/long ECDSA hex
*/
static fromHex(g) {
const p = u.fromAffine(s(Ae("pointHex", g)));
return p.assertValidity(), p;
}
// Multiplies generator point by privateKey.
static fromPrivateKey(g) {
return u.BASE.multiply(c(g));
}
// "Private method", don't use it directly
_setWindowSize(g) {
this._WINDOW_SIZE = g, l.delete(this);
}
// A point on curve is valid if it conforms to equation.
assertValidity() {
if (this.is0()) {
if (e.allowInfinityPoint && !t.is0(this.py))
return;
throw new Error("bad point: ZERO");
}
const { x: g, y: p } = this.toAffine();
if (!t.isValid(g) || !t.isValid(p))
throw new Error("bad point: x or y not FE");
const y = t.sqr(p), w = i(g);
if (!t.eql(y, w))
throw new Error("bad point: equation left != right");
if (!this.isTorsionFree())
throw new Error("bad point: not in prime-order subgroup");
}
hasEvenY() {
const { y: g } = this.toAffine();
if (t.isOdd)
return !t.isOdd(g);
throw new Error("Field doesn't support isOdd");
}
/**
* Compare one point to another.
*/
equals(g) {
d(g);
const { px: p, py: y, pz: w } = this, { px: x, py: A, pz: T } = g, _ = t.eql(t.mul(p, T), t.mul(x, w)), S = t.eql(t.mul(y, T), t.mul(A, w));
return _ && S;
}
/**
* Flips point to one corresponding to (x, -y) in Affine coordinates.
*/
negate() {
return new u(this.px, t.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: g, b: p } = e, y = t.mul(p, Eo), { px: w, py: x, pz: A } = this;
let T = t.ZERO, _ = t.ZERO, S = t.ZERO, k = t.mul(w, w), N = t.mul(x, x), z = t.mul(A, A), L = t.mul(w, x);
return L = t.add(L, L), S = t.mul(w, A), S = t.add(S, S), T = t.mul(g, S), _ = t.mul(y, z), _ = t.add(T, _), T = t.sub(N, _), _ = t.add(N, _), _ = t.mul(T, _), T = t.mul(L, T), S = t.mul(y, S), z = t.mul(g, z), L = t.sub(k, z), L = t.mul(g, L), L = t.add(L, S), S = t.add(k, k), k = t.add(S, k), k = t.add(k, z), k = t.mul(k, L), _ = t.add(_, k), z = t.mul(x, A), z = t.add(z, z), k = t.mul(z, L), T = t.sub(T, k), S = t.mul(z, N), S = t.add(S, S), S = t.add(S, S), new u(T, _, S);
}
// 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(g) {
d(g);
const { px: p, py: y, pz: w } = this, { px: x, py: A, pz: T } = g;
let _ = t.ZERO, S = t.ZERO, k = t.ZERO;
const N = e.a, z = t.mul(e.b, Eo);
let L = t.mul(p, x), P = t.mul(y, A), F = t.mul(w, T), I = t.add(p, y), v = t.add(x, A);
I = t.mul(I, v), v = t.add(L, P), I = t.sub(I, v), v = t.add(p, w);
let E = t.add(x, T);
return v = t.mul(v, E), E = t.add(L, F), v = t.sub(v, E), E = t.add(y, w), _ = t.add(A, T), E = t.mul(E, _), _ = t.add(P, F), E = t.sub(E, _), k = t.mul(N, v), _ = t.mul(z, F), k = t.add(_, k), _ = t.sub(P, k), k = t.add(P, k), S = t.mul(_, k), P = t.add(L, L), P = t.add(P, L), F = t.mul(N, F), v = t.mul(z, v), P = t.add(P, F), F = t.sub(L, F), F = t.mul(N, F), v = t.add(v, F), L = t.mul(P, v), S = t.add(S, L), L = t.mul(E, v), _ = t.mul(I, _), _ = t.sub(_, L), L = t.mul(I, P), k = t.mul(E, k), k = t.add(k, L), new u(_, S, k);
}
subtract(g) {
return this.add(g.negate());
}
is0() {
return this.equals(u.ZERO);
}
wNAF(g) {
return m.wNAFCached(this, l, g, (p) => {
const y = t.invertBatch(p.map((w) => w.pz));
return p.map((w, x) => w.toAffine(y[x])).map(u.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(g) {
const p = u.ZERO;
if (g === Ot)
return p;
if (a(g), g === Ve)
return this;
const { endo: y } = e;
if (!y)
return m.unsafeLadder(this, g);
let { k1neg: w, k1: x, k2neg: A, k2: T } = y.splitScalar(g), _ = p, S = p, k = this;
for (; x > Ot || T > Ot; )
x & Ve && (_ = _.add(k)), T & Ve && (S = S.add(k)), k = k.double(), x >>= Ve, T >>= Ve;
return w && (_ = _.negate()), A && (S = S.negate()), S = new u(t.mul(S.px, y.beta), S.py, S.pz), _.add(S);
}
/**
* 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(g) {
a(g);
let p = g, y, w;
const { endo: x } = e;
if (x) {
const { k1neg: A, k1: T, k2neg: _, k2: S } = x.splitScalar(p);
let { p: k, f: N } = this.wNAF(T), { p: z, f: L } = this.wNAF(S);
k = m.constTimeNegate(A, k), z = m.constTimeNegate(_, z), z = new u(t.mul(z.px, x.beta), z.py, z.pz), y = k.add(z), w = N.add(L);
} else {
const { p: A, f: T } = this.wNAF(p);
y = A, w = T;
}
return u.normalizeZ([y, w])[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(g, p, y) {
const w = u.BASE, x = (T, _) => _ === Ot || _ === Ve || !T.equals(w) ? T.multiplyUnsafe(_) : T.multiply(_), A = x(this, p).add(x(g, y));
return A.is0() ? void 0 : A;
}
// 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(g) {
const { px: p, py: y, pz: w } = this, x = this.is0();
g == null && (g = x ? t.ONE : t.inv(w));
const A = t.mul(p, g), T = t.mul(y, g), _ = t.mul(w, g);
if (x)
return { x: t.ZERO, y: t.ZERO };
if (!t.eql(_, t.ONE))
throw new Error("invZ was invalid");
return { x: A, y: T };
}
isTorsionFree() {
const { h: g, isTorsionFree: p } = e;
if (g === Ve)
return !0;
if (p)
return p(u, this);
throw new Error("isTorsionFree() has not been declared for the elliptic curve");
}
clearCofactor() {
const { h: g, clearCofactor: p } = e;
return g === Ve ? this : p ? p(u, this) : this.multiplyUnsafe(e.h);
}
toRawBytes(g = !0) {
return this.assertValidity(), r(u, this, g);
}
toHex(g = !0) {
return Hn(this.toRawBytes(g));
}
}
u.BASE = new u(e.Gx, e.Gy, t.ONE), u.ZERO = new u(t.ZERO, t.ONE, t.ZERO);
const f = e.nBitLength, m = Wl(u, e.endo ? Math.ceil(f / 2) : f);
return {
CURVE: e,
ProjectivePoint: u,
normPrivateKeyToScalar: c,
weierstrassEquation: i,
isWithinCurveOrder: o
};
}
function Xl(n) {
const e = wa(n);
return Cr(e, {
hash: "hash",
hmac: "function",
randomBytes: "function"
}, {
bits2int: "function",
bits2int_modN: "function",
lowS: "boolean"
}), Object.freeze({ lowS: !0, ...e });
}
function Ql(n) {
const e = Xl(n), { Fp: t, n: r } = e, s = t.BYTES + 1, i = 2 * t.BYTES + 1;
function o(v) {
return Ot < v && v < t.ORDER;
}
function a(v) {
return Se(v, r);
}
function c(v) {
return ri(v, r);
}
const { ProjectivePoint: l, normPrivateKeyToScalar: d, weierstrassEquation: u, isWithinCurveOrder: f } = Jl({
...e,
toBytes(v, E, C) {
const j = E.toAffine(), Z = t.toBytes(j.x), W = bn;
return C ? W(Uint8Array.from([E.hasEvenY() ? 2 : 3]), Z) : W(Uint8Array.from([4]), Z, t.toBytes(j.y));
},
fromBytes(v) {
const E = v.length, C = v[0], j = v.subarray(1);
if (E === s && (C === 2 || C === 3)) {
const Z = Le(j);
if (!o(Z))
throw new Error("Point is not on curve");
const W = u(Z);
let Y = t.sqrt(W);
const te = (Y & Ve) === Ve;
return (C & 1) === 1 !== te && (Y = t.neg(Y)), { x: Z, y: Y };
} else if (E === i && C === 4) {
const Z = t.fromBytes(j.subarray(0, t.BYTES)), W = t.fromBytes(j.subarray(t.BYTES, 2 * t.BYTES));
return { x: Z, y: W };
} else
throw new Error(`Point of length ${E} was invalid. Expected ${s} compressed bytes or ${i} uncompressed bytes`);
}
}), m = (v) => Hn(en(v, e.nByteLength));
function b(v) {
const E = r >> Ve;
return v > E;
}
function g(v) {
return b(v) ? a(-v) : v;
}
const p = (v, E, C) => Le(v.slice(E, C));
class y {
constructor(E, C, j) {
this.r = E, this.s = C, this.recovery = j, this.assertValidity();
}
// pair (bytes of r, bytes of s)
static fromCompact(E) {
const C = e.nByteLength;
return E = Ae("compactSignature", E, C * 2), new y(p(E, 0, C), p(E, C, 2 * C));
}
// DER encoded ECDSA signature
// https://bitcoin.stackexchange.com/questions/57644/what-are-the-parts-of-a-bitcoin-transaction-input-script
static fromDER(E) {
const { r: C, s: j } = hn.toSig(Ae("DER", E));
return new y(C, j);
}
assertValidity() {
if (!f(this.r))
throw new Error("r must be 0 < r < CURVE.n");
if (!f(this.s))
throw new Error("s must be 0 < s < CURVE.n");
}
addRecoveryBit(E) {
return new y(this.r, this.s, E);
}
recoverPublicKey(E) {
const { r: C, s: j, recovery: Z } = this, W = S(Ae("msgHash", E));
if (Z == null || ![0, 1, 2, 3].includes(Z))
throw new Error("recovery id invalid");
const Y = Z === 2 || Z === 3 ? C + e.n : C;
if (Y >= t.ORDER)
throw new Error("recovery id 2 or 3 invalid");
const te = Z & 1 ? "03" : "02", ce = l.fromHex(te + m(Y)), _e = c(Y), Ze = a(-W * _e), Re = a(j * _e), ze = l.BASE.multiplyAndAddUnsafe(ce, Ze, Re);
if (!ze)
throw new Error("point at infinify");
return ze.assertValidity(), ze;
}
// Signatures should be low-s, to prevent malleability.
hasHighS() {
return b(this.s);
}
normalizeS() {
return this.hasHighS() ? new y(this.r, a(-this.s), this.recovery) : this;
}
// DER-encoded
toDERRawBytes() {
return Mn(this.toDERHex());
}
toDERHex() {
return hn.hexFromSig({ r: this.r, s: this.s });
}
// padded bytes of r, then padded bytes of s
toCompactRawBytes() {
return Mn(this.toCompactHex());
}
toCompactHex() {
return m(this.r) + m(this.s);
}
}
const w = {
isValidPrivateKey(v) {
try {
return d(v), !0;
} catch {
return !1;
}
},
normPrivateKeyToScalar: d,
/**
* Produces cryptographically secure private key from random of size
* (groupLen + ceil(groupLen / 2)) with modulo bias being negligible.
*/
randomPrivateKey: () => {
const v = ma(e.n);
return Vl(e.randomBytes(v), e.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(v = 8, E = l.BASE) {
return E._setWindowSize(v), E.multiply(BigInt(3)), E;
}
};
function x(v, E = !0) {
return l.fromPrivateKey(v).toRawBytes(E);
}
function A(v) {
const E = v instanceof Uint8Array, C = typeof v == "string", j = (E || C) && v.length;
return E ? j === s || j === i : C ? j === 2 * s || j === 2 * i : v instanceof l;
}
function T(v, E, C = !0) {
if (A(v))
throw new Error("first arg must be private key");
if (!A(E))
throw new Error("second arg must be public key");
return l.fromHex(E).multiply(d(v)).toRawBytes(C);
}
const _ = e.bits2int || function(v) {
const E = Le(v), C = v.length * 8 - e.nBitLength;
return C > 0 ? E >> BigInt(C) : E;
}, S = e.bits2int_modN || function(v) {
return a(_(v));
}, k = Ri(e.nBitLength);
function N(v) {
if (typeof v != "bigint")
throw new Error("bigint expected");
if (!(Ot <= v && v < k))
throw new Error(`bigint expected < 2^${e.nBitLength}`);
return en(v, e.nByteLength);
}
function z(v, E, C = L) {
if (["recovered", "canonical"].some((Ne) => Ne in C))
throw new Error("sign() legacy options not supported");
const { hash: j, randomBytes: Z } = e;
let { lowS: W, prehash: Y, extraEntropy: te } = C;
W == null && (W = !0), v = Ae("msgHash", v), Y && (v = Ae("prehashed msgHash", j(v)));
const ce = S(v), _e = d(E), Ze = [N(_e), N(ce)];
if (te != null) {
const Ne = te === !0 ? Z(t.BYTES) : te;
Ze.push(Ae("extraEntropy", Ne));
}
const Re = bn(...Ze), ze = ce;
function Ke(Ne) {
const bt = _(Ne);
if (!f(bt))
return;
const vt = c(bt), ge = l.BASE.multiply(bt).toAffine(), ye = a(ge.x);
if (ye === Ot)
return;
const xt = a(vt * a(ze + ye * _e));
if (xt === Ot)
return;
let Qn = (ge.x === ye ? 0 : 2) | Number(ge.y & Ve), go = xt;
return W && b(xt) && (go = g(xt), Qn ^= 1), new y(ye, go, Qn);
}
return { seed: Re, k2sig: Ke };
}
const L = { lowS: e.lowS, prehash: !1 }, P = { lowS: e.lowS, prehash: !1 };
function F(v, E, C = L) {
const { seed: j, k2sig: Z } = z(v, E, C), W = e;
return pa(W.hash.outputLen, W.nByteLength, W.hmac)(j, Z);
}
l.BASE._setWindowSize(8);
function I(v, E, C, j = P) {
var ge;
const Z = v;
if (E = Ae("msgHash", E), C = Ae("publicKey", C), "strict" in j)
throw new Error("options.strict was renamed to lowS");
const { lowS: W, prehash: Y } = j;
let te, ce;
try {
if (typeof Z == "string" || Z instanceof Uint8Array)
try {
te = y.fromDER(Z);
} catch (ye) {
if (!(ye instanceof hn.Err))
throw ye;
te = y.fromCompact(Z);
}
else if (typeof Z == "object" && typeof Z.r == "bigint" && typeof Z.s == "bigint") {
const { r: ye, s: xt } = Z;
te = new y(ye, xt);
} else
throw new Error("PARSE");
ce = l.fromHex(C);
} catch (ye) {
if (ye.message === "PARSE")
throw new Error("signature must be Signature instance, Uint8Array or hex string");
return !1;
}
if (W && te.hasHighS())
return !1;
Y && (E = e.hash(E));
const { r: _e, s: Ze } = te, Re = S(E), ze = c(Ze), Ke = a(Re * ze), Ne = a(_e * ze), bt = (ge = l.BASE.multiplyAndAddUnsafe(ce, Ke, Ne)) == null ? void 0 : ge.toAffine();
return bt ? a(bt.x) === _e : !1;
}
return {
CURVE: e,
getPublicKey: x,
getSharedSecret: T,
sign: F,
verify: I,
ProjectivePoint: l,
Signature: y,
utils: w
};
}
let ba = class extends ua {
constructor(e, t) {
super(), this.finished = !1, this.destroyed = !1, pl(e);
const r = Oi(t);
if (this.iHash = e.create(), 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 s = this.blockLen, i = new Uint8Array(s);
i.set(r.length > s ? e.create().update(r).digest() : r);
for (let o = 0; o < i.length; o++)
i[o] ^= 54;
this.iHash.update(i), this.oHash = e.create();
for (let o = 0; o < i.length; o++)
i[o] ^= 106;
this.oHash.update(i), i.fill(0);
}
update(e) {
return Yr(this), this.iHash.update(e), this;
}
digestInto(e) {
Yr(this), ca(e, this.outputLen), this.finished = !0, this.iHash.digestInto(e), this.oHash.update(e), this.oHash.digestInto(e), this.destroy();
}
digest() {
const e = new Uint8Array(this.oHash.outputLen);
return this.digestInto(e), e;
}
_cloneInto(e) {
e || (e = Object.create(Object.getPrototypeOf(this), {}));
const { oHash: t, iHash: r, finished: s, destroyed: i, blockLen: o, outputLen: a } = this;
return e = e, e.finished = s, e.destroyed = i, e.blockLen = o, e.outputLen = a, e.oHash = t._cloneInto(e.oHash), e.iHash = r._cloneInto(e.iHash), e;
}
destroy() {
this.destroyed = !0, this.oHash.destroy(), this.iHash.destroy();
}
};
const va = (n, e, t) => new ba(n, e).update(t).digest();
va.create = (n, e) => new ba(n, e);
/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
function eu(n) {
return {
hash: n,
hmac: (e, ...t) => va(n, e, wl(...t)),
randomBytes: da
};
}
function tu(n, e) {
const t = (r) => Ql({ ...n, ...eu(r) });
return Object.freeze({ ...t(e), create: t });
}
/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
const fs = BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"), Jr = BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"), xa = BigInt(1), Xr = BigInt(2), _o = (n, e) => (n + e / Xr) / e;
function Ea(n) {
const e = fs, t = BigInt(3), r = BigInt(6), s = BigInt(11), i = BigInt(22), o = BigInt(23), a = BigInt(44), c = BigInt(88), l = n * n * n % e, d = l * l * n % e, u = De(d, t, e) * d % e, f = De(u, t, e) * d % e, m = De(f, Xr, e) * l % e, b = De(m, s, e) * m % e, g = De(b, i, e) * b % e, p = De(g, a, e) * g % e, y = De(p, c, e) * p % e, w = De(y, a, e) * g % e, x = De(w, t, e) * d % e, A = De(x, o, e) * b % e, T = De(A, r, e) * l % e, _ = De(T, Xr, e);
if (!si.eql(si.sqr(_), n))
throw new Error("Cannot find square root");
return _;
}
const si = ql(fs, void 0, void 0, { sqrt: Ea }), Gn = tu({
a: BigInt(0),
b: BigInt(7),
Fp: si,
n: Jr,
// Base point (x, y) aka generator point
Gx: BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"),
Gy: BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"),
h: BigInt(1),
lowS: !0,
/**
* 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: (n) => {
const e = Jr, t = BigInt("0x3086d221a7d46bcde86c90e49284eb15"), r = -xa * BigInt("0xe4437ed6010e88286f547fa90abfe4c3"), s = BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"), i = t, o = BigInt("0x100000000000000000000000000000000"), a = _o(i * n, e), c = _o(-r * n, e);
let l = Se(n - a * t - c * s, e), d = Se(-a * r - c * i, e);
const u = l > o, f = d > o;
if (u && (l = e - l), f && (d = e - d), l > o || d > o)
throw new Error("splitScalar: Endomorphism failed, k=" + n);
return { k1neg: u, k1: l, k2neg: f, k2: d };
}
}
}, ti), ps = BigInt(0), _a = (n) => typeof n == "bigint" && ps < n && n < fs, nu = (n) => typeof n == "bigint" && ps < n && n < Jr, So = {};
function Qr(n, ...e) {
let t = So[n];
if (t === void 0) {
const r = ti(Uint8Array.from(n, (s) => s.charCodeAt(0)));
t = bn(r, r), So[n] = t;
}
return ti(bn(t, ...e));
}
const Ni = (n) => n.toRawBytes(!0).slice(1), ii = (n) => en(n, 32), Rs = (n) => Se(n, fs), ar = (n) => Se(n, Jr), Li = Gn.ProjectivePoint, ru = (n, e, t) => Li.BASE.multiplyAndAddUnsafe(n, e, t);
function oi(n) {
let e = Gn.utils.normPrivateKeyToScalar(n), t = Li.fromPrivateKey(e);
return { scalar: t.hasEvenY() ? e : ar(-e), bytes: Ni(t) };
}
function Sa(n) {
if (!_a(n))
throw new Error("bad x: need 0 < x < p");
const e = Rs(n * n), t = Rs(e * n + BigInt(7));
let r = Ea(t);
r % Xr !== ps && (r = Rs(-r));
const s = new Li(n, r, xa);
return s.assertValidity(), s;
}
function ka(...n) {
return ar(Le(Qr("BIP0340/challenge", ...n)));
}
function su(n) {
return oi(n).bytes;
}
function iu(n, e, t = da(32)) {
const r = Ae("message", n), { bytes: s, scalar: i } = oi(e), o = Ae("auxRand", t, 32), a = ii(i ^ Le(Qr("BIP0340/aux", o))), c = Qr("BIP0340/nonce", a, s, r), l = ar(Le(c));
if (l === ps)
throw new Error("sign failed: k is zero");
const { bytes: d, scalar: u } = oi(l), f = ka(d, s, r), m = new Uint8Array(64);
if (m.set(d, 0), m.set(ii(ar(u + f * i)), 32), !Aa(m, r, s))
throw new Error("sign: Invalid signature produced");
return m;
}
function Aa(n, e, t) {
const r = Ae("signature", n, 64), s = Ae("message", e), i = Ae("publicKey", t, 32);
try {
const o = Sa(Le(i)), a = Le(r.subarray(0, 32));
if (!_a(a))
return !1;
const c = Le(r.subarray(32, 64));
if (!nu(c))
return !1;
const l = ka(ii(a), Ni(o), s), d = ru(o, c, ar(-l));
return !(!d || !d.hasEvenY() || d.toAffine().x !== a);
} catch {
return !1;
}
}
const dt = {
getPublicKey: su,
sign: iu,
verify: Aa,
utils: {
randomPrivateKey: Gn.utils.randomPrivateKey,
lift_x: Sa,
pointToBytes: Ni,
numberToBytesBE: en,
bytesToNumberBE: Le,
taggedHash: Qr,
mod: Se
}
}, Ns = typeof globalThis == "object" && "crypto" in globalThis ? globalThis.crypto : void 0;
/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */
const Ui = (n) => n instanceof Uint8Array, Ls = (n) => new DataView(n.buffer, n.byteOffset, n.byteLength), at = (n, e) => n << 32 - e | n >>> e, ou = new Uint8Array(new Uint32Array([287454020]).buffer)[0] === 68;
if (!ou)
throw new Error("Non little-endian hardware is not supported");
const au = Array.from({ length: 256 }, (n, e) => e.toString(16).padStart(2, "0"));
function ve(n) {
if (!Ui(n))
throw new Error("Uint8Array expected");
let e = "";
for (let t = 0; t < n.length; t++)
e += au[n[t]];
return e;
}
function jn(n) {
if (typeof n != "string")
throw new Error("hex string expected, got " + typeof n);
const e = n.length;
if (e % 2)
throw new Error("padded hex string expected, got unpadded hex of length " + e);
const t = new Uint8Array(e / 2);
for (let r = 0; r < t.length; r++) {
const s = r * 2, i = n.slice(s, s + 2), o = Number.parseInt(i, 16);
if (Number.isNaN(o) || o < 0)
throw new Error("Invalid byte sequence");
t[r] = o;
}
return t;
}
function cu(n) {
if (typeof n != "string")
throw new Error(`utf8ToBytes expected string, got ${typeof n}`);
return new Uint8Array(new TextEncoder().encode(n));
}
function cr(n) {
if (typeof n == "string" && (n = cu(n)), !Ui(n))
throw new Error(`expected Uint8Array, got ${typeof n}`);
return n;
}
function gs(...n) {
const e = new Uint8Array(n.reduce((r, s) => r + s.length, 0));
let t = 0;
return n.forEach((r) => {
if (!Ui(r))
throw new Error("Uint8Array expected");
e.set(r, t), t += r.length;
}), e;
}
let Ta = class {
// Safe version that clones internal state
clone() {
return this._cloneInto();
}
};
function Ba(n) {
const e = (r) => n().update(cr(r)).digest(), t = n();
return e.outputLen = t.outputLen, e.blockLen = t.blockLen, e.create = () => n(), e;
}
function Oa(n = 32) {
if (Ns && typeof Ns.getRandomValues == "function")
return Ns.getRandomValues(new Uint8Array(n));
throw new Error("crypto.getRandomValues must be defined");
}
function ai(n) {
if (!Number.isSafeInteger(n) || n < 0)
throw new Error(`Wrong positive integer: ${n}`);
}
function lu(n) {
if (typeof n != "boolean")
throw new Error(`Expected boolean, not ${n}`);
}
function Ia(n, ...e) {
if (!(n instanceof Uint8Array))
throw new Error("Expected Uint8Array");
if (e.length > 0 && !e.includes(n.length))
throw new Error(`Expected Uint8Array of length ${e}, not of length=${n.length}`);
}
function uu(n) {
if (typeof n != "function" || typeof n.create != "function")
throw new Error("Hash should be wrapped by utils.wrapConstructor");
ai(n.outputLen), ai(n.blockLen);
}
function du(n, e = !0) {
if (n.destroyed)
throw new Error("Hash instance has been destroyed");
if (e && n.finished)
throw new Error("Hash#digest() has already been called");
}
function hu(n, e) {
Ia(n);
const t = e.outputLen;
if (n.length < t)
throw new Error(`digestInto() expects output buffer of length at least ${t}`);
}
const pt = {
number: ai,
bool: lu,
bytes: Ia,
hash: uu,
exists: du,
output: hu
};
function fu(n, e, t, r) {
if (typeof n.setBigUint64 == "function")
return n.setBigUint64(e, t, r);
const s = BigInt(32), i = BigInt(4294967295), o = Number(t >> s & i), a = Number(t & i), c = r ? 4 : 0, l = r ? 0 : 4;
n.setUint32(e + c, o, r), n.setUint32(e + l, a, r);
}
class pu extends Ta {
constructor(e, t, r, s) {
super(), this.blockLen = e, this.outputLen = t, this.padOffset = r, this.isLE = s, this.finished = !1, this.length = 0, this.pos = 0, this.destroyed = !1, this.buffer = new Uint8Array(e), this.view = Ls(this.buffer);
}
update(e) {
pt.exists(this);
const { view: t, buffer: r, blockLen: s } = this;
e = cr(e);
const i = e.length;
for (let o = 0; o < i; ) {
const a = Math.min(s - this.pos, i - o);
if (a === s) {
const c = Ls(e);
for (; s <= i - o; o += s)
this.process(c, o);
continue;
}
r.set(e.subarray(o, o + a), this.pos), this.pos += a, o += a, this.pos === s && (this.process(t, 0), this.pos = 0);
}
return this.length += e.length, this.roundClean(), this;
}
digestInto(e) {
pt.exists(this), pt.output(e, this), this.finished = !0;
const { buffer: t, view: r, blockLen: s, isLE: i } = this;
let { pos: o } = this;
t[o++] = 128, this.buffer.subarray(o).fill(0), this.padOffset > s - o && (this.process(r, 0), o = 0);
for (let u = o; u < s; u++)
t[u] = 0;
fu(r, s - 8, BigInt(this.length * 8), i), this.process(r, 0);
const a = Ls(e), c = this.outputLen;
if (c % 4)
throw new Error("_sha2: outputLen should be aligned to 32bit");
const l = c / 4, d = this.get();
if (l > d.length)
throw new Error("_sha2: outputLen bigger than state");
for (let u = 0; u < l; u++)
a.setUint32(4 * u, d[u], i);
}
digest() {
const { buffer: e, outputLen: t } = this;
this.digestInto(e);
const r = e.slice(0, t);
return this.destroy(), r;
}
_cloneInto(e) {
e || (e = new this.constructor()), e.set(...this.get());
const { blockLen: t, buffer: r, length: s, finished: i, destroyed: o, pos: a } = this;
return e.length = s, e.pos = a, e.finished = i, e.destroyed = o, s % t && e.buffer.set(r), e;
}
}
const gu = (n, e, t) => n & e ^ ~n & t, yu = (n, e, t) => n & e ^ n & t ^ e & t, mu = 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
]), Pt = new Uint32Array([
1779033703,
3144134277,
1013904242,
2773480762,
1359893119,
2600822924,
528734635,
1541459225
]), Zt = new Uint32Array(64);
let Ca = class extends pu {
constructor() {
super(64, 32, 8, !1), this.A = Pt[0] | 0, this.B = Pt[1] | 0, this.C = Pt[2] | 0, this.D = Pt[3] | 0, this.E = Pt[4] | 0, this.F = Pt[5] | 0, this.G = Pt[6] | 0, this.H = Pt[7] | 0;
}
get() {
const { A: e, B: t, C: r, D: s, E: i, F: o, G: a, H: c } = this;
return [e, t, r, s, i, o, a, c];
}
// prettier-ignore
set(e, t, r, s, i, o, a, c) {
this.A = e | 0, this.B = t | 0, this.C = r | 0, this.D = s | 0, this.E = i | 0, this.F = o | 0, this.G = a | 0, this.H = c | 0;
}
process(e, t) {
for (let u = 0; u < 16; u++, t += 4)
Zt[u] = e.getUint32(t, !1);
for (let u = 16; u < 64; u++) {
const f = Zt[u - 15], m = Zt[u - 2], b = at(f, 7) ^ at(f, 18) ^ f >>> 3, g = at(m, 17) ^ at(m, 19) ^ m >>> 10;
Zt[u] = g + Zt[u - 7] + b + Zt[u - 16] | 0;
}
let { A: r, B: s, C: i, D: o, E: a, F: c, G: l, H: d } = this;
for (let u = 0; u < 64; u++) {
const f = at(a, 6) ^ at(a, 11) ^ at(a, 25), m = d + f + gu(a, c, l) + mu[u] + Zt[u] | 0, g = (at(r, 2) ^ at(r, 13) ^ at(r, 22)) + yu(r, s, i) | 0;
d = l, l = c, c = a, a = o + m | 0, o = i, i = s, s = r, r = m + g | 0;
}
r = r + this.A | 0, s = s + this.B | 0, i = i + this.C | 0, o = o + this.D | 0, a = a + this.E | 0, c = c + this.F | 0, l = l + this.G | 0, d = d + this.H | 0, this.set(r, s, i, o, a, c, l, d);
}
roundClean() {
Zt.fill(0);
}
destroy() {
this.set(0, 0, 0, 0, 0, 0, 0, 0), this.buffer.fill(0);
}
};
class wu extends Ca {
constructor() {
super(), this.A = -1056596264, this.B = 914150663, this.C = 812702999, this.D = -150054599, this.E = -4191439, this.F = 1750603025, this.G = 1694076839, this.H = -1090891868, this.outputLen = 28;
}
}
const Yn = Ba(() => new Ca());
Ba(() => new wu());
/*! scure-base - MIT License (c) 2022 Paul Miller (paulmillr.com) */
function Jn(n) {
if (!Number.isSafeInteger(n))
throw new Error(`Wrong integer: ${n}`);
}
function Nt(...n) {
const e = (s, i) => (o) => s(i(o)), t = Array.from(n).reverse().reduce((s, i) => s ? e(s, i.encode) : i.encode, void 0), r = n.reduce((s, i) => s ? e(s, i.decode) : i.decode, void 0);
return { encode: t, decode: r };
}
function Lt(n) {
return {
encode: (e) => {
if (!Array.isArray(e) || e.length && typeof e[0] != "number")
throw new Error("alphabet.encode input should be an array of numbers");
return e.map((t) => {
if (Jn(t), t < 0 || t >= n.length)
throw new Error(`Digit index outside alphabet: ${t} (alphabet: ${n.length})`);
return n[t];
});
},
decode: (e) => {
if (!Array.isArray(e) || e.length && typeof e[0] != "string")
throw new Error("alphabet.decode input should be array of strings");
return e.map((t) => {
if (typeof t != "string")
throw new Error(`alphabet.decode: not string element=${t}`);
const r = n.indexOf(t);
if (r === -1)
throw new Error(`Unknown letter: "${t}". Allowed: ${n}`);
return r;
});
}
};
}
function Ut(n = "") {
if (typeof n != "string")
throw new Error("join separator should be string");
return {
encode: (e) => {
if (!Array.isArray(e) || e.length && typeof e[0] != "string")
throw new Error("join.encode input should be array of strings");
for (let t of e)
if (typeof t != "string")
throw new Error(`join.encode: non-string input=${t}`);
return e.join(n);
},
decode: (e) => {
if (typeof e != "string")
throw new Error("join.decode input should be string");
return e.split(n);
}
};
}
function ys(n, e = "=") {
if (Jn(n), typeof e != "string")
throw new Error("padding chr should be string");
return {
encode(t) {
if (!Array.isArray(t) || t.length && typeof t[0] != "string")
throw new Error("padding.encode input should be array of strings");
for (let r of t)
if (typeof r != "string")
throw new Error(`padding.encode: non-string input=${r}`);
for (; t.length * n % 8; )
t.push(e);
return t;
},
decode(t) {
if (!Array.isArray(t) || t.length && typeof t[0] != "string")
throw new Error("padding.encode input should be array of strings");
for (let s of t)
if (typeof s != "string")
throw new Error(`padding.decode: non-string input=${s}`);
let r = t.length;
if (r * n % 8)
throw new Error("Invalid padding: string should have whole number of bytes");
for (; r > 0 && t[r - 1] === e; r--)
if (!((r - 1) * n % 8))
throw new Error("Invalid padding: string has too much padding");
return t.slice(0, r);
}
};
}
function $a(n) {
if (typeof n != "function")
throw new Error("normalize fn should be function");
return { encode: (e) => e, decode: (e) => n(e) };
}
function ko(n, e, t) {
if (e < 2)
throw new Error(`convertRadix: wrong from=${e}, base cannot be less than 2`);
if (t < 2)
throw new Error(`convertRadix: wrong to=${t}, base cannot be less than 2`);
if (!Array.isArray(n))
throw new Error("convertRadix: data should be array");
if (!n.length)
return [];
let r = 0;
const s = [], i = Array.from(n);
for (i.forEach((o) => {
if (Jn(o), o < 0 || o >= e)
throw new Error(`Wrong integer: ${o}`);
}); ; ) {
let o = 0, a = !0;
for (let c = r; c < i.length; c++) {
const l = i[c], d = e * o + l;
if (!Number.isSafeInteger(d) || e * o / e !== o || d - l !== e * o)
throw new Error("convertRadix: carry overflow");
if (o = d % t, i[c] = Math.floor(d / t), !Number.isSafeInteger(i[c]) || i[c] * t + o !== d)
throw new Error("convertRadix: carry overflow");
if (a)
i[c] ? a = !1 : r = c;
else continue;
}
if (s.push(o), a)
break;
}
for (let o = 0; o < n.length - 1 && n[o] === 0; o++)
s.push(0);
return s.reverse();
}
const Ra = (n, e) => e ? Ra(e, n % e) : n, es = (n, e) => n + (e - Ra(n, e));
function ci(n, e, t, r) {
if (!Array.isArray(n))
throw new Error("convertRadix2: data should be array");
if (e <= 0 || e > 32)
throw new Error(`convertRadix2: wrong from=${e}`);
if (t <= 0 || t > 32)
throw new Error(`convertRadix2: wrong to=${t}`);
if (es(e, t) > 32)
throw new Error(`convertRadix2: carry overflow from=${e} to=${t} carryBits=${es(e, t)}`);
let s = 0, i = 0;
const o = 2 ** t - 1, a = [];
for (const c of n) {
if (Jn(c), c >= 2 ** e)
throw new Error(`convertRadix2: invalid data word=${c} from=${e}`);
if (s = s << e | c, i + e > 32)
throw new Error(`convertRadix2: carry overflow pos=${i} from=${e}`);
for (i += e; i >= t; i -= t)
a.push((s >> i - t & o) >>> 0);
s &= 2 ** i - 1;
}
if (s = s << t - i & o, !r && i >= e)
throw new Error("Excess padding");
if (!r && s)
throw new Error(`Non-zero padding: ${s}`);
return r && i > 0 && a.push(s >>> 0), a;
}
function bu(n) {
return Jn(n), {
encode: (e) => {
if (!(e instanceof Uint8Array))
throw new Error("radix.encode input should be Uint8Array");
return ko(Array.from(e), 2 ** 8, n);
},
decode: (e) => {
if (!Array.isArray(e) || e.length && typeof e[0] != "number")
throw new Error("radix.decode input should be array of strings");
return Uint8Array.from(ko(e, n, 2 ** 8));
}
};
}
function on(n, e = !1) {
if (Jn(n), n <= 0 || n > 32)
throw new Error("radix2: bits should be in (0..32]");
if (es(8, n) > 32 || es(n, 8) > 32)
throw new Error("radix2: carry overflow");
return {
encode: (t) => {
if (!(t instanceof Uint8Array))
throw new Error("radix2.encode input should be Uint8Array");
return ci(Array.from(t), 8, n, !e);
},
decode: (t) => {
if (!Array.isArray(t) || t.length && typeof t[0] != "number")
throw new Error("radix2.decode input should be array of strings");
return Uint8Array.from(ci(t, n, 8, e));
}
};
}
function Ao(n) {
if (typeof n != "function")
throw new Error("unsafeWrapper fn should be function");
return function(...e) {
try {
return n.apply(null, e);
} catch {
}
};
}
const vu = Nt(on(4), Lt("0123456789ABCDEF"), Ut("")), xu = Nt(on(5), Lt("ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"), ys(5), Ut(""));
Nt(on(5), Lt("0123456789ABCDEFGHIJKLMNOPQRSTUV"), ys(5), Ut(""));
Nt(on(5), Lt("0123456789ABCDEFGHJKMNPQRSTVWXYZ"), Ut(""), $a((n) => n.toUpperCase().replace(/O/g, "0").replace(/[IL]/g, "1")));
const $t = Nt(on(6), Lt("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"), ys(6), Ut("")), Eu = Nt(on(6), Lt("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"), ys(6), Ut("")), Hi = (n) => Nt(bu(58), Lt(n), Ut("")), li = Hi("123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz");
Hi("123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ");
Hi("rpshnaf39wBUDNEGHJKLM4PQRST7VWXYZ2bcdeCg65jkm8oFqi1tuvAxyz");
const To = [0, 2, 3, 5, 6, 7, 9, 10, 11], _u = {
encode(n) {
let e = "";
for (let t = 0; t < n.length; t += 8) {
const r = n.subarray(t, t + 8);
e += li.encode(r).padStart(To[r.length], "1");
}
return e;
},
decode(n) {
let e = [];
for (let t = 0; t < n.length; t += 11) {
const r = n.slice(t, t + 11), s = To.indexOf(r.length), i = li.decode(r);
for (let o = 0; o < i.length - s; o++)
if (i[o] !== 0)
throw new Error("base58xmr: wrong padding");
e = e.concat(Array.from(i.slice(i.length - s)));
}
return Uint8Array.from(e);
}
}, ui = Nt(Lt("qpzry9x8gf2tvdw0s3jn54khce6mua7l"), Ut("")), Bo = [996825010, 642813549, 513874426, 1027748829, 705979059];
function er(n) {
const e = n >> 25;
let t = (n & 33554431) << 5;
for (let r = 0; r < Bo.length; r++)
(e >> r & 1) === 1 && (t ^= Bo[r]);
return t;
}
function Oo(n, e, t = 1) {
const r = n.length;
let s = 1;
for (let i = 0; i < r; i++) {
const o = n.charCodeAt(i);
if (o < 33 || o > 126)
throw new Error(`Invalid prefix (${n})`);
s = er(s) ^ o >> 5;
}
s = er(s);
for (let i = 0; i < r; i++)
s = er(s) ^ n.charCodeAt(i) & 31;
for (let i of e)
s = er(s) ^ i;
for (let i = 0; i < 6; i++)
s = er(s);
return s ^= t, ui.encode(ci([s % 2 ** 30], 30, 5, !1));
}
function Na(n) {
const e = n === "bech32" ? 1 : 734539939, t = on(5), r = t.decode, s = t.encode, i = Ao(r);
function o(d, u, f = 90) {
if (typeof d != "string")
throw new Error(`bech32.encode prefix should be string, not ${typeof d}`);
if (!Array.isArray(u) || u.length && typeof u[0] != "number")
throw new Error(`bech32.encode words should be array of numbers, not ${typeof u}`);
const m = d.length + 7 + u.length;
if (f !== !1 && m > f)
throw new TypeError(`Length ${m} exceeds limit ${f}`);
return d = d.toLowerCase(), `${d}1${ui.encode(u)}${Oo(d, u, e)}`;
}
function a(d, u = 90) {
if (typeof d != "string")
throw new Error(`bech32.decode input should be string, not ${typeof d}`);
if (d.length < 8 || u !== !1 && d.length > u)
throw new TypeError(`Wrong string length: ${d.length} (${d}). Expected (8..${u})`);
const f = d.toLowerCase();
if (d !== f && d !== d.toUpperCase())
throw new Error("String must be lowercase or uppercase");
d = f;
const m = d.lastIndexOf("1");
if (m === 0 || m === -1)
throw new Error('Letter "1" must be present between prefix and data only');
const b = d.slice(0, m), g = d.slice(m + 1);
if (g.length < 6)
throw new Error("Data must be at least 6 characters long");
const p = ui.decode(g).slice(0, -6), y = Oo(b, p, e);
if (!g.endsWith(y))
throw new Error(`Invalid checksum in ${d}: expected "${y}"`);
return { prefix: b, words: p };
}
const c = Ao(a);
function l(d) {
const { prefix: u, words: f } = a(d, !1);
return { prefix: u, words: f, bytes: r(f) };
}
return { encode: o, decode: a, decodeToBytes: l, decodeUnsafe: c, fromWords: r, fromWordsUnsafe: i, toWords: s };
}
const Pn = Na("bech32");
Na("bech32m");
const Su = {
encode: (n) => new TextDecoder().decode(n),
decode: (n) => new TextEncoder().encode(n)
}, ku = Nt(on(4), Lt("0123456789abcdef"), Ut(""), $a((n) => {
if (typeof n != "string" || n.length % 2)
throw new TypeError(`hex.decode: expected string, got ${typeof n} with length ${n.length}`);
return n.toLowerCase();
})), Au = {
utf8: Su,
hex: ku,
base16: vu,
base32: xu,
base64: $t,
base64url: Eu,
base58: li,
base58xmr: _u
};
`${Object.keys(Au).join(", ")}`;
function Us(n) {
if (!Number.isSafeInteger(n) || n < 0)
throw new Error(`positive integer expected, not ${n}`);
}
function Io(n) {
if (typeof n != "boolean")
throw new Error(`boolean expected, not ${n}`);
}
function Tu(n) {
return n instanceof Uint8Array || n != null && typeof n == "object" && n.constructor.name === "Uint8Array";
}
function Ct(n, ...e) {
if (!Tu(n))
throw new Error("Uint8Array expected");
if (e.length > 0 && !e.includes(n.length))
throw new Error(`Uint8Array expected of length ${e}, not of length=${n.length}`);
}
/*! noble-ciphers - MIT License (c) 2023 Paul Miller (paulmillr.com) */
const Te = (n) => new Uint32Array(n.buffer, n.byteOffset, Math.floor(n.byteLength / 4)), Bu = new Uint8Array(new Uint32Array([287454020]).buffer)[0] === 68;
if (!Bu)
throw new Error("Non little-endian hardware is not supported");
function Ou(n, e) {
if (e == null || typeof e != "object")
throw new Error("options must be defined");
return Object.assign(n, e);
}
function Iu(n, e) {
if (n.length !== e.length)
return !1;
let t = 0;
for (let r = 0; r < n.length; r++)
t |= n[r] ^ e[r];
return t === 0;
}
const Cu = /* @__NO_SIDE_EFFECTS__ */ (n, e) => (Object.assign(e, n), e), Qt = 16, $u = 283;
function Mi(n) {
return n << 1 ^ $u & -(n >> 7);
}
function Tn(n, e) {
let t = 0;
for (; e > 0; e >>= 1)
t ^= n & -(e & 1), n = Mi(n);
return t;
}
const di = /* @__PURE__ */ (() => {
let n = new Uint8Array(256);
for (let t = 0, r = 1; t < 256; t++, r ^= Mi(r))
n[t] = r;
const e = new Uint8Array(256);
e[0] = 99;
for (let t = 0; t < 255; t++) {
let r = n[255 - t];
r |= r << 8, e[n[t]] = (r ^ r >> 4 ^ r >> 5 ^ r >> 6 ^ r >> 7 ^ 99) & 255;
}
return e;
})(), Ru = /* @__PURE__ */ di.map((n, e) => di.indexOf(e)), Nu = (n) => n << 24 | n >>> 8, Hs = (n) => n << 8 | n >>> 24;
function La(n, e) {
if (n.length !== 256)
throw new Error("Wrong sbox length");
const t = new Uint32Array(256).map((l, d) => e(n[d])), r = t.map(Hs), s = r.map(Hs), i = s.map(Hs), o = new Uint32Array(256 * 256), a = new Uint32Array(256 * 256), c = new Uint16Array(256 * 256);
for (let l = 0; l < 256; l++)
for (let d = 0; d < 256; d++) {
const u = l * 256 + d;
o[u] = t[l] ^ r[d], a[u] = s[l] ^ i[d], c[u] = n[l] << 8 | n[d];
}
return { sbox: n, sbox2: c, T0: t, T1: r, T2: s, T3: i, T01: o, T23: a };
}
const ji = /* @__PURE__ */ La(di, (n) => Tn(n, 3) << 24 | n << 16 | n << 8 | Tn(n, 2)), Ua = /* @__PURE__ */ La(Ru, (n) => Tn(n, 11) << 24 | Tn(n, 13) << 16 | Tn(n, 9) << 8 | Tn(n, 14)), Lu = /* @__PURE__ */ (() => {
const n = new Uint8Array(16);
for (let e = 0, t = 1; e < 16; e++, t = Mi(t))
n[e] = t;
return n;
})();
function Ha(n) {
Ct(n);
const e = n.length;
if (![16, 24, 32].includes(e))
throw new Error(`aes: wrong key size: should be 16, 24 or 32, got: ${e}`);
const { sbox2: t } = ji, r = Te(n), s = r.length, i = (a) => gt(t, a, a, a, a), o = new Uint32Array(e + 28);
o.set(r);
for (let a = s; a < o.length; a++) {
let c = o[a - 1];
a % s === 0 ? c = i(Nu(c)) ^ Lu[a / s - 1] : s > 6 && a % s === 4 && (c = i(c)), o[a] = o[a - s] ^ c;
}
return o;
}
function Uu(n) {
const e = Ha(n), t = e.slice(), r = e.length, { sbox2: s } = ji, { T0: i, T1: o, T2: a, T3: c } = Ua;
for (let l = 0; l < r; l += 4)
for (let d = 0; d < 4; d++)
t[l + d] = e[r - l - 4 + d];
e.fill(0);
for (let l = 4; l < r - 4; l++) {
const d = t[l], u = gt(s, d, d, d, d);
t[l] = i[u & 255] ^ o[u >>> 8 & 255] ^ a[u >>> 16 & 255] ^ c[u >>> 24];
}
return t;
}
function Xt(n, e, t, r, s, i) {
return n[t << 8 & 65280 | r >>> 8 & 255] ^ e[s >>> 8 & 65280 | i >>> 24 & 255];
}
function gt(n, e, t, r, s) {
return n[e & 255 | t & 65280] | n[r >>> 16 & 255 | s >>> 16 & 65280] << 16;
}
function Co(n, e, t, r, s) {
const { sbox2: i, T01: o, T23: a } = ji;
let c = 0;
e ^= n[c++], t ^= n[c++], r ^= n[c++], s ^= n[c++];
const l = n.length / 4 - 2;
for (let b = 0; b < l; b++) {
const g = n[c++] ^ Xt(o, a, e, t, r, s), p = n[c++] ^ Xt(o, a, t, r, s, e), y = n[c++] ^ Xt(o, a, r, s, e, t), w = n[c++] ^ Xt(o, a, s, e, t, r);
e = g, t = p, r = y, s = w;
}
const d = n[c++] ^ gt(i, e, t, r, s), u = n[c++] ^ gt(i, t, r, s, e), f = n[c++] ^ gt(i, r, s, e, t), m = n[c++] ^ gt(i, s, e, t, r);
return { s0: d, s1: u, s2: f, s3: m };
}
function Hu(n, e, t, r, s) {
const { sbox2: i, T01: o, T23: a } = Ua;
let c = 0;
e ^= n[c++], t ^= n[c++], r ^= n[c++], s ^= n[c++];
const l = n.length / 4 - 2;
for (let b = 0; b < l; b++) {
const g = n[c++] ^ Xt(o, a, e, s, r, t), p = n[c++] ^ Xt(o, a, t, e, s, r), y = n[c++] ^ Xt(o, a, r, t, e, s), w = n[c++] ^ Xt(o, a, s, r, t, e);
e = g, t = p, r = y, s = w;
}
const d = n[c++] ^ gt(i, e, s, r, t), u = n[c++] ^ gt(i, t, e, s, r), f = n[c++] ^ gt(i, r, t, e, s), m = n[c++] ^ gt(i, s, r, t, e);
return { s0: d, s1: u, s2: f, s3: m };
}
function Ma(n, e) {
if (!e)
return new Uint8Array(n);
if (Ct(e), e.length < n)
throw new Error(`aes: wrong destination length, expected at least ${n}, got: ${e.length}`);
return e;
}
function Mu(n) {
if (Ct(n), n.length % Qt !== 0)
throw new Error(`aes/(cbc-ecb).decrypt ciphertext should consist of blocks with size ${Qt}`);
}
function ju(n, e, t) {
let r = n.length;
const s = r % Qt;
if (!e && s !== 0)
throw new Error("aec/(cbc-ecb): unpadded plaintext with disabled padding");
const i = Te(n);
if (e) {
let c = Qt - s;
c || (c = Qt), r = r + c;
}
const o = Ma(r, t), a = Te(o);
return { b: i, o: a, out: o };
}
function Pu(n, e) {
if (!e)
return n;
const t = n.length;
if (!t)
throw new Error("aes/pcks5: empty ciphertext not allowed");
const r = n[t - 1];
if (r <= 0 || r > 16)
throw new Error(`aes/pcks5: wrong padding byte: ${r}`);
const s = n.subarray(0, -r);
for (let i = 0; i < r; i++)
if (n[t - i - 1] !== r)
throw new Error("aes/pcks5: wrong padding");
return s;
}
function Zu(n) {
const e = new Uint8Array(16), t = Te(e);
e.set(n);
const r = Qt - n.length;
for (let s = Qt - r; s < Qt; s++)
e[s] = r;
return t;
}
const ja = /* @__PURE__ */ Cu({ blockSize: 16, nonceLength: 16 }, function(e, t, r = {}) {
Ct(e), Ct(t, 16);
const s = !r.disablePadding;
return {
encrypt: (i, o) => {
const a = Ha(e), { b: c, o: l, out: d } = ju(i, s, o), u = Te(t);
let f = u[0], m = u[1], b = u[2], g = u[3], p = 0;
for (; p + 4 <= c.length; )
f ^= c[p + 0], m ^= c[p + 1], b ^= c[p + 2], g ^= c[p + 3], { s0: f, s1: m, s2: b, s3: g } = Co(a, f, m, b, g), l[p++] = f, l[p++] = m, l[p++] = b, l[p++] = g;
if (s) {
const y = Zu(i.subarray(p * 4));
f ^= y[0], m ^= y[1], b ^= y[2], g ^= y[3], { s0: f, s1: m, s2: b, s3: g } = Co(a, f, m, b, g), l[p++] = f, l[p++] = m, l[p++] = b, l[p++] = g;
}
return a.fill(0), d;
},
decrypt: (i, o) => {
Mu(i);
const a = Uu(e), c = Te(t), l = Ma(i.length, o), d = Te(i), u = Te(l);
let f = c[0], m = c[1], b = c[2], g = c[3];
for (let p = 0; p + 4 <= d.length; ) {
const y = f, w = m, x = b, A = g;
f = d[p + 0], m = d[p + 1], b = d[p + 2], g = d[p + 3];
const { s0: T, s1: _, s2: S, s3: k } = Hu(a, f, m, b, g);
u[p++] = T ^ y, u[p++] = _ ^ w, u[p++] = S ^ x, u[p++] = k ^ A;
}
return a.fill(0), Pu(l, s);
}
};
}), Pa = (n) => Uint8Array.from(n.split("").map((e) => e.charCodeAt(0))), zu = Pa("expand 16-byte k"), Du = Pa("expand 32-byte k"), qu = Te(zu), Za = Te(Du);
Za.slice();
function se(n, e) {
return n << e | n >>> 32 - e;
}
function hi(n) {
return n.byteOffset % 4 === 0;
}
const Hr = 64, Vu = 16, za = 2 ** 32 - 1, $o = new Uint32Array();
function Ku(n, e, t, r, s, i, o, a) {
const c = s.length, l = new Uint8Array(Hr), d = Te(l), u = hi(s) && hi(i), f = u ? Te(s) : $o, m = u ? Te(i) : $o;
for (let b = 0; b < c; o++) {
if (n(e, t, r, d, o, a), o >= za)
throw new Error("arx: counter overflow");
const g = Math.min(Hr, c - b);
if (u && g === Hr) {
const p = b / 4;
if (b % 4 !== 0)
throw new Error("arx: invalid block position");
for (let y = 0, w; y < Vu; y++)
w = p + y, m[w] = f[w] ^ d[y];
b += Hr;
continue;
}
for (let p = 0, y; p < g; p++)
y = b + p, i[y] = s[y] ^ l[p];
b += g;
}
}
function Wu(n, e) {
const { allowShortKeys: t, extendNonceFn: r, counterLength: s, counterRight: i, rounds: o } = Ou({ allowShortKeys: !1, counterLength: 8, counterRight: !1, rounds: 20 }, e);
if (typeof n != "function")
throw new Error("core must be a function");
return Us(s), Us(o), Io(i), Io(t), (a, c, l, d, u = 0) => {
Ct(a), Ct(c), Ct(l);
const f = l.length;
if (d || (d = new Uint8Array(f)), Ct(d), Us(u), u < 0 || u >= za)
throw new Error("arx: counter overflow");
if (d.length < f)
throw new Error(`arx: output (${d.length}) is shorter than data (${f})`);
const m = [];
let b = a.length, g, p;
if (b === 32)
g = a.slice(), m.push(g), p = Za;
else if (b === 16 && t)
g = new Uint8Array(32), g.set(a), g.set(a, 16), p = qu, m.push(g);
else
throw new Error(`arx: invalid 32-byte key, got length=${b}`);
hi(c) || (c = c.slice(), m.push(c));
const y = Te(g);
if (r) {
if (c.length !== 24)
throw new Error("arx: extended nonce must be 24 bytes");
r(p, y, Te(c.subarray(0, 16)), y), c = c.subarray(16);
}
const w = 16 - s;
if (w !== c.length)
throw new Error(`arx: nonce must be ${w} or 16 bytes`);
if (w !== 12) {
const A = new Uint8Array(12);
A.set(c, i ? 0 : 12 - c.length), c = A, m.push(c);
}
const x = Te(c);
for (Ku(n, p, y, x, l, d, u, o); m.length > 0; )
m.pop().fill(0);
return d;
};
}
function Fu(n, e, t, r, s, i = 20) {
let o = n[0], a = n[1], c = n[2], l = n[3], d = e[0], u = e[1], f = e[2], m = e[3], b = e[4], g = e[5], p = e[6], y = e[7], w = s, x = t[0], A = t[1], T = t[2], _ = o, S = a, k = c, N = l, z = d, L = u, P = f, F = m, I = b, v = g, E = p, C = y, j = w, Z = x, W = A, Y = T;
for (let ce = 0; ce < i; ce += 2)
_ = _ + z | 0, j = se(j ^ _, 16), I = I + j | 0, z = se(z ^ I, 12), _ = _ + z | 0, j = se(j ^ _, 8), I = I + j | 0, z = se(z ^ I, 7), S = S + L | 0, Z = se(Z ^ S, 16), v = v + Z | 0, L = se(L ^ v, 12), S = S + L | 0, Z = se(Z ^ S, 8), v = v + Z | 0, L = se(L ^ v, 7), k = k + P | 0, W = se(W ^ k, 16), E = E + W | 0, P = se(P ^ E, 12), k = k + P | 0, W = se(W ^ k, 8), E = E + W | 0, P = se(P ^ E, 7), N = N + F | 0, Y = se(Y ^ N, 16), C = C + Y | 0, F = se(F ^ C, 12), N = N + F | 0, Y = se(Y ^ N, 8), C = C + Y | 0, F = se(F ^ C, 7), _ = _ + L | 0, Y = se(Y ^ _, 16), E = E + Y | 0, L = se(L ^ E, 12), _ = _ + L | 0, Y = se(Y ^ _, 8), E = E + Y | 0, L = se(L ^ E, 7), S = S + P | 0, j = se(j ^ S, 16), C = C + j | 0, P = se(P ^ C, 12), S = S + P | 0, j = se(j ^ S, 8), C = C + j | 0, P = se(P ^ C, 7), k = k + F | 0, Z = se(Z ^ k, 16), I = I + Z | 0, F = se(F ^ I, 12), k = k + F | 0, Z = se(Z ^ k, 8), I = I + Z | 0, F = se(F ^ I, 7), N = N + z | 0, W = se(W ^ N, 16), v = v + W | 0, z = se(z ^ v, 12), N = N + z | 0, W = se(W ^ N, 8), v = v + W | 0, z = se(z ^ v, 7);
let te = 0;
r[te++] = o + _ | 0, r[te++] = a + S | 0, r[te++] = c + k | 0, r[te++] = l + N | 0, r[te++] = d + z | 0, r[te++] = u + L | 0, r[te++] = f + P | 0, r[te++] = m + F | 0, r[te++] = b + I | 0, r[te++] = g + v | 0, r[te++] = p + E | 0, r[te++] = y + C | 0, r[te++] = w + j | 0, r[te++] = x + Z | 0, r[te++] = A + W | 0, r[te++] = T + Y | 0;
}
const Da = /* @__PURE__ */ Wu(Fu, {
counterRight: !1,
counterLength: 4,
allowShortKeys: !1
});
let qa = class extends Ta {
constructor(e, t) {
super(), this.finished = !1, this.destroyed = !1, pt.hash(e);
const r = cr(t);
if (this.iHash = e.create(), 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 s = this.blockLen, i = new Uint8Array(s);
i.set(r.length > s ? e.create().update(r).digest() : r);
for (let o = 0; o < i.length; o++)
i[o] ^= 54;
this.iHash.update(i), this.oHash = e.create();
for (let o = 0; o < i.length; o++)
i[o] ^= 106;
this.oHash.update(i), i.fill(0);
}
update(e) {
return pt.exists(this), this.iHash.update(e), this;
}
digestInto(e) {
pt.exists(this), pt.bytes(e, this.outputLen), this.finished = !0, this.iHash.digestInto(e), this.oHash.update(e), this.oHash.digestInto(e), this.destroy();
}
digest() {
const e = new Uint8Array(this.oHash.outputLen);
return this.digestInto(e), e;
}
_cloneInto(e) {
e || (e = Object.create(Object.getPrototypeOf(this), {}));
const { oHash: t, iHash: r, finished: s, destroyed: i, blockLen: o, outputLen: a } = this;
return e = e, e.finished = s, e.destroyed = i, e.blockLen = o, e.outputLen = a, e.oHash = t._cloneInto(e.oHash), e.iHash = r._cloneInto(e.iHash), e;
}
destroy() {
this.destroyed = !0, this.oHash.destroy(), this.iHash.destroy();
}
};
const ms = (n, e, t) => new qa(n, e).update(t).digest();
ms.create = (n, e) => new qa(n, e);
function Gu(n, e, t) {
return pt.hash(n), ms(n, cr(t), cr(e));
}
const Ms = new Uint8Array([0]), Ro = new Uint8Array();
function Yu(n, e, t, r = 32) {
if (pt.hash(n), pt.number(r), r > 255 * n.outputLen)
throw new Error("Length should be <= 255*HashLen");
const s = Math.ceil(r / n.outputLen);
t === void 0 && (t = Ro);
const i = new Uint8Array(s * n.outputLen), o = ms.create(n, e), a = o._cloneInto(), c = new Uint8Array(o.outputLen);
for (let l = 0; l < s; l++)
Ms[0] = l + 1, a.update(l === 0 ? Ro : c).update(t).update(Ms).digestInto(c), i.set(c, n.outputLen * l), o._cloneInto(a);
return o.destroy(), a.destroy(), c.fill(0), Ms.fill(0), i.slice(0, r);
}
var Ju = Object.defineProperty, he = (n, e) => {
for (var t in e)
Ju(n, t, { get: e[t], enumerable: !0 });
}, Sn = Symbol("verified"), Xu = (n) => n instanceof Object;
function Va(n) {
if (!Xu(n) || typeof n.kind != "number" || typeof n.content != "string" || typeof n.created_at != "number" || typeof n.pubkey != "string" || !n.pubkey.match(/^[a-f0-9]{64}$/) || !Array.isArray(n.tags))
return !1;
for (let e = 0; e < n.tags.length; e++) {
let t = n.tags[e];
if (!Array.isArray(t))
return !1;
for (let r = 0; r < t.length; r++)
if (typeof t[r] == "object")
return !1;
}
return !0;
}
var Qu = {};
he(Qu, {
Queue: () => rd,
QueueNode: () => Ka,
binarySearch: () => Pi,
insertEventIntoAscendingList: () => nd,
insertEventIntoDescendingList: () => td,
normalizeURL: () => ed,
utf8Decoder: () => ht,
utf8Encoder: () => st
});
var ht = new TextDecoder("utf-8"), st = new TextEncoder();
function ed(n) {
n.indexOf("://") === -1 && (n = "wss://" + n);
let e = new URL(n);
return e.pathname = e.pathname.replace(/\/+/g, "/"), e.pathname.endsWith("/") && (e.pathname = e.pathname.slice(0, -1)), (e.port === "80" && e.protocol === "ws:" || e.port === "443" && e.protocol === "wss:") && (e.port = ""), e.searchParams.sort(), e.hash = "", e.toString();
}
function td(n, e) {
const [t, r] = Pi(n, (s) => e.id === s.id ? 0 : e.created_at === s.created_at ? -1 : s.created_at - e.created_at);
return r || n.splice(t, 0, e), n;
}
function nd(n, e) {
const [t, r] = Pi(n, (s) => e.id === s.id ? 0 : e.created_at === s.created_at ? -1 : e.created_at - s.created_at);
return r || n.splice(t, 0, e), n;
}
function Pi(n, e) {
let t = 0, r = n.length - 1;
for (; t <= r; ) {
const s = Math.floor((t + r) / 2), i = e(n[s]);
if (i === 0)
return [s, !0];
i < 0 ? r = s - 1 : t = s + 1;
}
return [t, !1];
}
var Ka = class {
constructor(e) {
B(this, "value");
B(this, "next", null);
B(this, "prev", null);
this.value = e;
}
}, rd = class {
constructor() {
B(this, "first");
B(this, "last");
this.first = null, this.last = null;
}
enqueue(e) {
const t = new Ka(e);
return this.last ? this.last === this.first ? (this.last = t, this.last.prev = this.first, this.first.next = t) : (t.prev = this.last, this.last.next = t, this.last = t) : (this.first = t, this.last = t), !0;
}
dequeue() {
if (!this.first)
return null;
if (this.first === this.last) {
const t = this.first;
return this.first = null, this.last = null, t.value;
}
const e = this.first;
return this.first = e.next, e.value;
}
}, sd = class {
generateSecretKey() {
return dt.utils.randomPrivateKey();
}
getPublicKey(e) {
return ve(dt.getPublicKey(e));
}
finalizeEvent(e, t) {
const r = e;
return r.pubkey = ve(dt.getPublicKey(t)), r.id = Wr(r), r.sig = ve(dt.sign(Wr(r), t)), r[Sn] = !0, r;
}
verifyEvent(e) {
if (typeof e[Sn] == "boolean")
return e[Sn];
const t = Wr(e);
if (t !== e.id)
return e[Sn] = !1, !1;
try {
const r = dt.verify(e.sig, t, e.pubkey);
return e[Sn] = r, r;
} catch {
return e[Sn] = !1, !1;
}
}
};
function id(n) {
if (!Va(n))
throw new Error("can't serialize event with wrong or missing properties");
return JSON.stringify([0, n.pubkey, n.created_at, n.kind, n.tags, n.content]);
}
function Wr(n) {
let e = Yn(st.encode(id(n)));
return ve(e);
}
var ws = new sd();
ws.generateSecretKey;
var od = ws.getPublicKey, Ht = ws.finalizeEvent, Xn = ws.verifyEvent, ad = {};
he(ad, {
Application: () => ah,
BadgeAward: () => yd,
BadgeDefinition: () => eh,
BlockedRelaysList: () => jd,
BookmarkList: () => Ud,
Bookmarksets: () => Jd,
Calendar: () => ph,
CalendarEventRSVP: () => gh,
ChannelCreation: () => Ga,
ChannelHideMessage: () => Xa,
ChannelMessage: () => Ja,
ChannelMetadata: () => Ya,
ChannelMuteUser: () => Qa,
ClassifiedListing: () => uh,
ClientAuth: () => ec,
CommunitiesList: () => Hd,
CommunityDefinition: () => wh,
CommunityPostApproval: () => kd,
Contacts: () => hd,
CreateOrUpdateProduct: () => rh,
CreateOrUpdateStall: () => nh,
Curationsets: () => Xd,
Date: () => hh,
DraftClassifiedListing: () => dh,
DraftLong: () => ih,
Emojisets: () => oh,
EncryptedDirectMessage: () => fd,
EncryptedDirectMessages: () => pd,
EventDeletion: () => gd,
FileMetadata: () => bd,
FileServerPreference: () => Dd,
Followsets: () => Fd,
GenericRepost: () => md,
Genericlists: () => Gd,
HTTPAuth: () => Vi,
Handlerinformation: () => mh,
Handlerrecommendation: () => yh,
Highlights: () => $d,
InterestsList: () => Zd,
Interestsets: () => th,
JobFeedback: () => Bd,
JobRequest: () => Ad,
JobResult: () => Td,
Label: () => Sd,
LightningPubRPC: () => Vd,
LiveChatMessage: () => vd,
LiveEvent: () => ch,
LongFormArticle: () => sh,
Metadata: () => ld,
Mutelist: () => Rd,
NWCWalletInfo: () => qd,
NWCWalletRequest: () => tc,
NWCWalletResponse: () => Kd,
NostrConnect: () => Wd,
OpenTimestamps: () => wd,
Pinlist: () => Nd,
ProblemTracker: () => xd,
ProfileBadges: () => Qd,
PublicChatsList: () => Md,
Reaction: () => qi,
RecommendRelay: () => dd,
RelayList: () => Ld,
Relaysets: () => Yd,
Report: () => Ed,
Reporting: () => _d,
Repost: () => Di,
SearchRelaysList: () => Pd,
ShortTextNote: () => ud,
Time: () => fh,
UserEmojiList: () => zd,
UserStatuses: () => lh,
Zap: () => Cd,
ZapGoal: () => Od,
ZapRequest: () => Id,
classifyKind: () => cd,
isEphemeralKind: () => Fa,
isParameterizedReplaceableKind: () => zi,
isRegularKind: () => Wa,
isReplaceableKind: () => Zi
});
function Wa(n) {
return 1e3 <= n && n < 1e4 || [1, 2, 4, 5, 6, 7, 8, 16, 40, 41, 42, 43, 44].includes(n);
}
function Zi(n) {
return [0, 3].includes(n) || 1e4 <= n && n < 2e4;
}
function Fa(n) {
return 2e4 <= n && n < 3e4;
}
function zi(n) {
return 3e4 <= n && n < 4e4;
}
function cd(n) {
return Wa(n) ? "regular" : Zi(n) ? "replaceable" : Fa(n) ? "ephemeral" : zi(n) ? "parameterized" : "unknown";
}
var ld = 0, ud = 1, dd = 2, hd = 3, fd = 4, pd = 4, gd = 5, Di = 6, qi = 7, yd = 8, md = 16, Ga = 40, Ya = 41, Ja = 42, Xa = 43, Qa = 44, wd = 1040, bd = 1063, vd = 1311, xd = 1971, Ed = 1984, _d = 1984, Sd = 1985, kd = 4550, Ad = 5999, Td = 6999, Bd = 7e3, Od = 9041, Id = 9734, Cd = 9735, $d = 9802, Rd = 1e4, Nd = 10001, Ld = 10002, Ud = 10003, Hd = 10004, Md = 10005, jd = 10006, Pd = 10007, Zd = 10015, zd = 10030, Dd = 10096, qd = 13194, Vd = 21e3, ec = 22242, tc = 23194, Kd = 23195, Wd = 24133, Vi = 27235, Fd = 3e4, Gd = 30001, Yd = 30002, Jd = 30003, Xd = 30004, Qd = 30008, eh = 30009, th = 30015, nh = 30017, rh = 30018, sh = 30023, ih = 30024, oh = 30030, ah = 30078, ch = 30311, lh = 30315, uh = 30402, dh = 30403, hh = 31922, fh = 31923, ph = 31924, gh = 31925, yh = 31989, mh = 31990, wh = 34550;
function bh(n, e) {
if (n.ids && n.ids.indexOf(e.id) === -1 || n.kinds && n.kinds.indexOf(e.kind) === -1 || n.authors && n.authors.indexOf(e.pubkey) === -1)
return !1;
for (let t in n)
if (t[0] === "#") {
let r = t.slice(1), s = n[`#${r}`];
if (s && !e.tags.find(([i, o]) => i === t.slice(1) && s.indexOf(o) !== -1))
return !1;
}
return !(n.since && e.created_at < n.since || n.until && e.created_at > n.until);
}
function fi(n, e) {
for (let t = 0; t < n.length; t++)
if (bh(n[t], e))
return !0;
return !1;
}
function nc(n) {
var e, t, r, s, i, o;
if (n.ids && !n.ids.length || n.kinds && !n.kinds.length || n.authors && !n.authors.length)
return 0;
for (const [a, c] of Object.entries(n))
if (a[0] === "#" && Array.isArray(c) && !c.length)
return 0;
return Math.min(
Math.max(0, n.limit ?? 1 / 0),
((e = n.ids) == null ? void 0 : e.length) ?? 1 / 0,
(t = n.authors) != null && t.length && ((r = n.kinds) != null && r.every((a) => Zi(a))) ? n.authors.length * n.kinds.length : 1 / 0,
(s = n.authors) != null && s.length && ((i = n.kinds) != null && i.every((a) => zi(a))) && ((o = n["#d"]) != null && o.length) ? n.authors.length * n.kinds.length * n["#d"].length : 1 / 0
);
}
var vh = {};
he(vh, {
getHex64: () => Ki,
getInt: () => rc,
getSubscriptionId: () => xh,
matchEventId: () => Eh,
matchEventKind: () => Sh,
matchEventPubkey: () => _h
});
function Ki(n, e) {
let t = e.length + 3, r = n.indexOf(`"${e}":`) + t, s = n.slice(r).indexOf('"') + r + 1;
return n.slice(s, s + 64);
}
function rc(n, e) {
let t = e.length, r = n.indexOf(`"${e}":`) + t + 3, s = n.slice(r), i = Math.min(s.indexOf(","), s.indexOf("}"));
return parseInt(s.slice(0, i), 10);
}
function xh(n) {
let e = n.slice(0, 22).indexOf('"EVENT"');
if (e === -1)
return null;
let t = n.slice(e + 7 + 1).indexOf('"');
if (t === -1)
return null;
let r = e + 7 + 1 + t, s = n.slice(r + 1, 80).indexOf('"');
if (s === -1)
return null;
let i = r + 1 + s;
return n.slice(r + 1, i);
}
function Eh(n, e) {
return e === Ki(n, "id");
}
function _h(n, e) {
return e === Ki(n, "pubkey");
}
function Sh(n, e) {
return e === rc(n, "kind");
}
var kh = {};
he(kh, {
makeAuthEvent: () => Ah
});
function Ah(n, e) {
return {
kind: ec,
created_at: Math.floor(Date.now() / 1e3),
tags: [
["relay", n],
["challenge", e]
],
content: ""
};
}
var Th;
try {
Th = WebSocket;
} catch {
}
var Bh;
try {
Bh = WebSocket;
} catch {
}
var Oh = {};
he(Oh, {
BECH32_REGEX: () => sc,
Bech32MaxSize: () => Wi,
decode: () => bs,
encodeBytes: () => vs,
naddrEncode: () => Uh,
neventEncode: () => Lh,
noteEncode: () => Rh,
nprofileEncode: () => Nh,
npubEncode: () => $h,
nrelayEncode: () => Hh,
nsecEncode: () => Ch
});
var Wi = 5e3, sc = /[\x21-\x7E]{1,83}1[023456789acdefghjklmnpqrstuvwxyz]{6,}/;
function Ih(n) {
const e = new Uint8Array(4);
return e[0] = n >> 24 & 255, e[1] = n >> 16 & 255, e[2] = n >> 8 & 255, e[3] = n & 255, e;
}
function bs(n) {
var s, i, o, a, c, l, d, u;
let { prefix: e, words: t } = Pn.decode(n, Wi), r = new Uint8Array(Pn.fromWords(t));
switch (e) {
case "nprofile": {
let f = Mr(r);
if (!((s = f[0]) != null && s[0]))
throw new Error("missing TLV 0 for nprofile");
if (f[0][0].length !== 32)
throw new Error("TLV 0 should be 32 bytes");
return {
type: "nprofile",
data: {
pubkey: ve(f[0][0]),
relays: f[1] ? f[1].map((m) => ht.decode(m)) : []
}
};
}
case "nevent": {
let f = Mr(r);
if (!((i = f[0]) != null && i[0]))
throw new Error("missing TLV 0 for nevent");
if (f[0][0].length !== 32)
throw new Error("TLV 0 should be 32 bytes");
if (f[2] && f[2][0].length !== 32)
throw new Error("TLV 2 should be 32 bytes");
if (f[3] && f[3][0].length !== 4)
throw new Error("TLV 3 should be 4 bytes");
return {
type: "nevent",
data: {
id: ve(f[0][0]),
relays: f[1] ? f[1].map((m) => ht.decode(m)) : [],
author: (o = f[2]) != null && o[0] ? ve(f[2][0]) : void 0,
kind: (a = f[3]) != null && a[0] ? parseInt(ve(f[3][0]), 16) : void 0
}
};
}
case "naddr": {
let f = Mr(r);
if (!((c = f[0]) != null && c[0]))
throw new Error("missing TLV 0 for naddr");
if (!((l = f[2]) != null && l[0]))
throw new Error("missing TLV 2 for naddr");
if (f[2][0].length !== 32)
throw new Error("TLV 2 should be 32 bytes");
if (!((d = f[3]) != null && d[0]))
throw new Error("missing TLV 3 for naddr");
if (f[3][0].length !== 4)
throw new Error("TLV 3 should be 4 bytes");
return {
type: "naddr",
data: {
identifier: ht.decode(f[0][0]),
pubkey: ve(f[2][0]),
kind: parseInt(ve(f[3][0]), 16),
relays: f[1] ? f[1].map((m) => ht.decode(m)) : []
}
};
}
case "nrelay": {
let f = Mr(r);
if (!((u = f[0]) != null && u[0]))
throw new Error("missing TLV 0 for nrelay");
return {
type: "nrelay",
data: ht.decode(f[0][0])
};
}
case "nsec":
return { type: e, data: r };
case "npub":
case "note":
return { type: e, data: ve(r) };
default:
throw new Error(`unknown prefix ${e}`);
}
}
function Mr(n) {
let e = {}, t = n;
for (; t.length > 0; ) {
let r = t[0], s = t[1], i = t.slice(2, 2 + s);
if (t = t.slice(2 + s), i.length < s)
throw new Error(`not enough data to read on TLV ${r}`);
e[r] = e[r] || [], e[r].push(i);
}
return e;
}
function Ch(n) {
return vs("nsec", n);
}
function $h(n) {
return vs("npub", jn(n));
}
function Rh(n) {
return vs("note", jn(n));
}
function $r(n, e) {
let t = Pn.toWords(e);
return Pn.encode(n, t, Wi);
}
function vs(n, e) {
return $r(n, e);
}
function Nh(n) {
let e = xs({
0: [jn(n.pubkey)],
1: (n.relays || []).map((t) => st.encode(t))
});
return $r("nprofile", e);
}
function Lh(n) {
let e;
n.kind !== void 0 && (e = Ih(n.kind));
let t = xs({
0: [jn(n.id)],
1: (n.relays || []).map((r) => st.encode(r)),
2: n.author ? [jn(n.author)] : [],
3: e ? [new Uint8Array(e)] : []
});
return $r("nevent", t);
}
function Uh(n) {
let e = new ArrayBuffer(4);
new DataView(e).setUint32(0, n.kind, !1);
let t = xs({
0: [st.encode(n.identifier)],
1: (n.relays || []).map((r) => st.encode(r)),
2: [jn(n.pubkey)],
3: [new Uint8Array(e)]
});
return $r("naddr", t);
}
function Hh(n) {
let e = xs({
0: [st.encode(n)]
});
return $r("nrelay", e);
}
function xs(n) {
let e = [];
return Object.entries(n).reverse().forEach(([t, r]) => {
r.forEach((s) => {
let i = new Uint8Array(s.length + 2);
i.set([parseInt(t)], 0), i.set([s.length], 1), i.set(s, 2), e.push(i);
});
}), gs(...e);
}
var pi = {};
he(pi, {
decrypt: () => Mh,
encrypt: () => ic
});
async function ic(n, e, t) {
const r = n instanceof Uint8Array ? ve(n) : n, s = Gn.getSharedSecret(r, "02" + e), i = oc(s);
let o = Uint8Array.from(Oa(16)), a = st.encode(t), c = ja(i, o).encrypt(a), l = $t.encode(new Uint8Array(c)), d = $t.encode(new Uint8Array(o.buffer));
return `${l}?iv=${d}`;
}
async function Mh(n, e, t) {
const r = n instanceof Uint8Array ? ve(n) : n;
let [s, i] = t.split("?iv="), o = Gn.getSharedSecret(r, "02" + e), a = oc(o), c = $t.decode(i), l = $t.decode(s), d = ja(a, c).decrypt(l);
return ht.decode(d);
}
function oc(n) {
return n.slice(1, 33);
}
var jh = {};
he(jh, {
NIP05_REGEX: () => ac,
isValid: () => zh,
queryProfile: () => cc,
searchDomain: () => Zh,
useFetchImplementation: () => Ph
});
var ac = /^(?:([\w.+-]+)@)?([\w_-]+(\.[\w_-]+)+)$/, Es;
try {
Es = fetch;
} catch {
}
function Ph(n) {
Es = n;
}
async function Zh(n, e = "") {
try {
const t = `https://${n}/.well-known/nostr.json?name=${e}`;
return (await (await Es(t, { redirect: "error" })).json()).names;
} catch {
return {};
}
}
async function cc(n) {
var i;
const e = n.match(ac);
if (!e)
return null;
const [t, r = "_", s] = e;
try {
const o = `https://${s}/.well-known/nostr.json?name=${r}`, a = await (await Es(o, { redirect: "error" })).json();
let c = a.names[r];
return c ? { pubkey: c, relays: (i = a.relays) == null ? void 0 : i[c] } : null;
} catch {
return null;
}
}
async function zh(n, e) {
let t = await cc(e);
return t ? t.pubkey === n : !1;
}
var Dh = {};
he(Dh, {
parse: () => qh
});
function qh(n) {
const e = {
reply: void 0,
root: void 0,
mentions: [],
profiles: []
}, t = [];
for (const r of n.tags)
r[0] === "e" && r[1] && t.push(r), r[0] === "p" && r[1] && e.profiles.push({
pubkey: r[1],
relays: r[2] ? [r[2]] : []
});
for (let r = 0; r < t.length; r++) {
const s = t[r], [i, o, a, c] = s, l = {
id: o,
relays: a ? [a] : []
}, d = r === 0, u = r === t.length - 1;
if (c === "root") {
e.root = l;
continue;
}
if (c === "reply") {
e.reply = l;
continue;
}
if (c === "mention") {
e.mentions.push(l);
continue;
}
if (d) {
e.root = l;
continue;
}
if (u) {
e.reply = l;
continue;
}
e.mentions.push(l);
}
return e;
}
var Vh = {};
he(Vh, {
fetchRelayInformation: () => Wh,
useFetchImplementation: () => Kh
});
var lc;
try {
lc = fetch;
} catch {
}
function Kh(n) {
lc = n;
}
async function Wh(n) {
return await (await fetch(n.replace("ws://", "http://").replace("wss://", "https://"), {
headers: { Accept: "application/nostr+json" }
})).json();
}
var Fh = {};
he(Fh, {
getPow: () => uc,
minePow: () => Gh
});
function uc(n) {
let e = 0;
for (let t = 0; t < n.length; t++) {
const r = parseInt(n[t], 16);
if (r === 0)
e += 4;
else {
e += Math.clz32(r) - 28;
break;
}
}
return e;
}
function Gh(n, e) {
let t = 0;
const r = n, s = ["nonce", t.toString(), e.toString()];
for (r.tags.push(s); ; ) {
const i = Math.floor((/* @__PURE__ */ new Date()).getTime() / 1e3);
if (i !== r.created_at && (t = 0, r.created_at = i), s[1] = (++t).toString(), r.id = Wr(r), uc(r.id) >= e)
break;
}
return r;
}
var Yh = {};
he(Yh, {
finishRepostEvent: () => Jh,
getRepostedEvent: () => Xh,
getRepostedEventPointer: () => dc
});
function Jh(n, e, t, r) {
return Ht(
{
kind: Di,
tags: [...n.tags ?? [], ["e", e.id, t], ["p", e.pubkey]],
content: n.content === "" ? "" : JSON.stringify(e),
created_at: n.created_at
},
r
);
}
function dc(n) {
if (n.kind !== Di)
return;
let e, t;
for (let r = n.tags.length - 1; r >= 0 && (e === void 0 || t === void 0); r--) {
const s = n.tags[r];
s.length >= 2 && (s[0] === "e" && e === void 0 ? e = s : s[0] === "p" && t === void 0 && (t = s));
}
if (e !== void 0)
return {
id: e[1],
relays: [e[2], t == null ? void 0 : t[2]].filter((r) => typeof r == "string"),
author: t == null ? void 0 : t[1]
};
}
function Xh(n, { skipVerification: e } = {}) {
const t = dc(n);
if (t === void 0 || n.content === "")
return;
let r;
try {
r = JSON.parse(n.content);
} catch {
return;
}
if (r.id === t.id && !(!e && !Xn(r)))
return r;
}
var Qh = {};
he(Qh, {
NOSTR_URI_REGEX: () => _s,
parse: () => tf,
test: () => ef
});
var _s = new RegExp(`nostr:(${sc.source})`);
function ef(n) {
return typeof n == "string" && new RegExp(`^${_s.source}$`).test(n);
}
function tf(n) {
const e = n.match(new RegExp(`^${_s.source}$`));
if (!e)
throw new Error(`Invalid Nostr URI: ${n}`);
return {
uri: e[0],
value: e[1],
decoded: bs(e[1])
};
}
var nf = {};
he(nf, {
finishReactionEvent: () => rf,
getReactedEventPointer: () => sf
});
function rf(n, e, t) {
const r = e.tags.filter((s) => s.length >= 2 && (s[0] === "e" || s[0] === "p"));
return Ht(
{
...n,
kind: qi,
tags: [...n.tags ?? [], ...r, ["e", e.id], ["p", e.pubkey]],
content: n.content ?? "+"
},
t
);
}
function sf(n) {
if (n.kind !== qi)
return;
let e, t;
for (let r = n.tags.length - 1; r >= 0 && (e === void 0 || t === void 0); r--) {
const s = n.tags[r];
s.length >= 2 && (s[0] === "e" && e === void 0 ? e = s : s[0] === "p" && t === void 0 && (t = s));
}
if (!(e === void 0 || t === void 0))
return {
id: e[1],
relays: [e[2], t[2]].filter((r) => r !== void 0),
author: t[1]
};
}
var of = {};
he(of, {
matchAll: () => af,
regex: () => Fi,
replaceAll: () => cf
});
var Fi = () => new RegExp(`\\b${_s.source}\\b`, "g");
function* af(n) {
const e = n.matchAll(Fi());
for (const t of e)
try {
const [r, s] = t;
yield {
uri: r,
value: s,
decoded: bs(s),
start: t.index,
end: t.index + r.length
};
} catch {
}
}
function cf(n, e) {
return n.replaceAll(Fi(), (t, r) => e({
uri: t,
value: r,
decoded: bs(r)
}));
}
var lf = {};
he(lf, {
channelCreateEvent: () => uf,
channelHideMessageEvent: () => ff,
channelMessageEvent: () => hf,
channelMetadataEvent: () => df,
channelMuteUserEvent: () => pf
});
var uf = (n, e) => {
let t;
if (typeof n.content == "object")
t = JSON.stringify(n.content);
else if (typeof n.content == "string")
t = n.content;
else
return;
return Ht(
{
kind: Ga,
tags: [...n.tags ?? []],
content: t,
created_at: n.created_at
},
e
);
}, df = (n, e) => {
let t;
if (typeof n.content == "object")
t = JSON.stringify(n.content);
else if (typeof n.content == "string")
t = n.content;
else
return;
return Ht(
{
kind: Ya,
tags: [["e", n.channel_create_event_id], ...n.tags ?? []],
content: t,
created_at: n.created_at
},
e
);
}, hf = (n, e) => {
const t = [["e", n.channel_create_event_id, n.relay_url, "root"]];
return n.reply_to_channel_message_event_id && t.push(["e", n.reply_to_channel_message_event_id, n.relay_url, "reply"]), Ht(
{
kind: Ja,
tags: [...t, ...n.tags ?? []],
content: n.content,
created_at: n.created_at
},
e
);
}, ff = (n, e) => {
let t;
if (typeof n.content == "object")
t = JSON.stringify(n.content);
else if (typeof n.content == "string")
t = n.content;
else
return;
return Ht(
{
kind: Xa,
tags: [["e", n.channel_message_event_id], ...n.tags ?? []],
content: t,
created_at: n.created_at
},
e
);
}, pf = (n, e) => {
let t;
if (typeof n.content == "object")
t = JSON.stringify(n.content);
else if (typeof n.content == "string")
t = n.content;
else
return;
return Ht(
{
kind: Qa,
tags: [["p", n.pubkey_to_mute], ...n.tags ?? []],
content: t,
created_at: n.created_at
},
e
);
}, gf = {};
he(gf, {
EMOJI_SHORTCODE_REGEX: () => hc,
matchAll: () => yf,
regex: () => Gi,
replaceAll: () => mf
});
var hc = /:(\w+):/, Gi = () => new RegExp(`\\B${hc.source}\\B`, "g");
function* yf(n) {
const e = n.matchAll(Gi());
for (const t of e)
try {
const [r, s] = t;
yield {
shortcode: r,
name: s,
start: t.index,
end: t.index + r.length
};
} catch {
}
}
function mf(n, e) {
return n.replaceAll(Gi(), (t, r) => e({
shortcode: t,
name: r
}));
}
var wf = {};
he(wf, {
useFetchImplementation: () => bf,
validateGithub: () => vf
});
var Yi;
try {
Yi = fetch;
} catch {
}
function bf(n) {
Yi = n;
}
async function vf(n, e, t) {
try {
return await (await Yi(`https://gist.github.com/${e}/${t}/raw`)).text() === `Verifying that I control the following Nostr public key: ${n}`;
} catch {
return !1;
}
}
var Fr = {};
he(Fr, {
decrypt: () => bc,
encrypt: () => wc,
getConversationKey: () => gc,
v2: () => kf
});
var fc = 1, pc = 65535;
function gc(n, e) {
const t = Gn.getSharedSecret(n, "02" + e).subarray(1, 33);
return Gu(Yn, t, "nip44-v2");
}
function yc(n, e) {
const t = Yu(Yn, n, e, 76);
return {
chacha_key: t.subarray(0, 32),
chacha_nonce: t.subarray(32, 44),
hmac_key: t.subarray(44, 76)
};
}
function Ji(n) {
if (!Number.isSafeInteger(n) || n < 1)
throw new Error("expected positive integer");
if (n <= 32)
return 32;
const e = 1 << Math.floor(Math.log2(n - 1)) + 1, t = e <= 256 ? 32 : e / 8;
return t * (Math.floor((n - 1) / t) + 1);
}
function xf(n) {
if (!Number.isSafeInteger(n) || n < fc || n > pc)
throw new Error("invalid plaintext size: must be between 1 and 65535 bytes");
const e = new Uint8Array(2);
return new DataView(e.buffer).setUint16(0, n, !1), e;
}
function Ef(n) {
const e = st.encode(n), t = e.length, r = xf(t), s = new Uint8Array(Ji(t) - t);
return gs(r, e, s);
}
function _f(n) {
const e = new DataView(n.buffer).getUint16(0), t = n.subarray(2, 2 + e);
if (e < fc || e > pc || t.length !== e || n.length !== 2 + Ji(e))
throw new Error("invalid padding");
return ht.decode(t);
}
function mc(n, e, t) {
if (t.length !== 32)
throw new Error("AAD associated data must be 32 bytes");
const r = gs(t, e);
return ms(Yn, n, r);
}
function Sf(n) {
if (typeof n != "string")
throw new Error("payload must be a valid string");
const e = n.length;
if (e < 132 || e > 87472)
throw new Error("invalid payload length: " + e);
if (n[0] === "#")
throw new Error("unknown encryption version");
let t;
try {
t = $t.decode(n);
} catch (i) {
throw new Error("invalid base64: " + i.message);
}
const r = t.length;
if (r < 99 || r > 65603)
throw new Error("invalid data length: " + r);
const s = t[0];
if (s !== 2)
throw new Error("unknown encryption version " + s);
return {
nonce: t.subarray(1, 33),
ciphertext: t.subarray(33, -32),
mac: t.subarray(-32)
};
}
function wc(n, e, t = Oa(32)) {
const { chacha_key: r, chacha_nonce: s, hmac_key: i } = yc(e, t), o = Ef(n), a = Da(r, s, o), c = mc(i, a, t);
return $t.encode(gs(new Uint8Array([2]), t, a, c));
}
function bc(n, e) {
const { nonce: t, ciphertext: r, mac: s } = Sf(n), { chacha_key: i, chacha_nonce: o, hmac_key: a } = yc(e, t), c = mc(a, r, t);
if (!Iu(c, s))
throw new Error("invalid MAC");
const l = Da(i, o, r);
return _f(l);
}
var kf = {
utils: {
getConversationKey: gc,
calcPaddedLen: Ji
},
encrypt: wc,
decrypt: bc
}, Af = {};
he(Af, {
makeNwcRequestEvent: () => Bf,
parseConnectionString: () => Tf
});
function Tf(n) {
const { pathname: e, searchParams: t } = new URL(n), r = e, s = t.get("relay"), i = t.get("secret");
if (!r || !s || !i)
throw new Error("invalid connection string");
return { pubkey: r, relay: s, secret: i };
}
async function Bf(n, e, t) {
const s = await ic(e, n, JSON.stringify({
method: "pay_invoice",
params: {
invoice: t
}
})), i = {
kind: tc,
created_at: Math.round(Date.now() / 1e3),
content: s,
tags: [["p", n]]
};
return Ht(i, e);
}
var Of = {};
he(Of, {
getZapEndpoint: () => Cf,
makeZapReceipt: () => Nf,
makeZapRequest: () => $f,
useFetchImplementation: () => If,
validateZapRequest: () => Rf
});
var Xi;
try {
Xi = fetch;
} catch {
}
function If(n) {
Xi = n;
}
async function Cf(n) {
try {
let e = "", { lud06: t, lud16: r } = JSON.parse(n.content);
if (t) {
let { words: o } = Pn.decode(t, 1e3), a = Pn.fromWords(o);
e = ht.decode(a);
} else if (r) {
let [o, a] = r.split("@");
e = new URL(`/.well-known/lnurlp/${o}`, `https://${a}`).toString();
} else
return null;
let i = await (await Xi(e)).json();
if (i.allowsNostr && i.nostrPubkey)
return i.callback;
} catch {
}
return null;
}
function $f({
profile: n,
event: e,
amount: t,
relays: r,
comment: s = ""
}) {
if (!t)
throw new Error("amount not given");
if (!n)
throw new Error("profile not given");
let i = {
kind: 9734,
created_at: Math.round(Date.now() / 1e3),
content: s,
tags: [
["p", n],
["amount", t.toString()],
["relays", ...r]
]
};
return e && i.tags.push(["e", e]), i;
}
function Rf(n) {
let e;
try {
e = JSON.parse(n);
} catch {
return "Invalid zap request JSON.";
}
if (!Va(e))
return "Zap request is not a valid Nostr event.";
if (!Xn(e))
return "Invalid signature on zap request.";
let t = e.tags.find(([i, o]) => i === "p" && o);
if (!t)
return "Zap request doesn't have a 'p' tag.";
if (!t[1].match(/^[a-f0-9]{64}$/))
return "Zap request 'p' tag is not valid hex.";
let r = e.tags.find(([i, o]) => i === "e" && o);
return r && !r[1].match(/^[a-f0-9]{64}$/) ? "Zap request 'e' tag is not valid hex." : e.tags.find(([i, o]) => i === "relays" && o) ? null : "Zap request doesn't have a 'relays' tag.";
}
function Nf({
zapRequest: n,
preimage: e,
bolt11: t,
paidAt: r
}) {
let s = JSON.parse(n), i = s.tags.filter(([a]) => a === "e" || a === "p" || a === "a"), o = {
kind: 9735,
created_at: Math.round(r.getTime() / 1e3),
content: "",
tags: [...i, ["P", s.pubkey], ["bolt11", t], ["description", n]]
};
return e && o.tags.push(["preimage", e]), o;
}
var Lf = {};
he(Lf, {
getToken: () => Uf,
hashPayload: () => Qi,
unpackEventFromToken: () => xc,
validateEvent: () => Tc,
validateEventKind: () => _c,
validateEventMethodTag: () => kc,
validateEventPayloadTag: () => Ac,
validateEventTimestamp: () => Ec,
validateEventUrlTag: () => Sc,
validateToken: () => Hf
});
var vc = "Nostr ";
async function Uf(n, e, t, r = !1, s) {
const i = {
kind: Vi,
tags: [
["u", n],
["method", e]
],
created_at: Math.round((/* @__PURE__ */ new Date()).getTime() / 1e3),
content: ""
};
s && i.tags.push(["payload", Qi(s)]);
const o = await t(i);
return (r ? vc : "") + $t.encode(st.encode(JSON.stringify(o)));
}
async function Hf(n, e, t) {
const r = await xc(n).catch((i) => {
throw i;
});
return await Tc(r, e, t).catch((i) => {
throw i;
});
}
async function xc(n) {
if (!n)
throw new Error("Missing token");
n = n.replace(vc, "");
const e = ht.decode($t.decode(n));
if (!e || e.length === 0 || !e.startsWith("{"))
throw new Error("Invalid token");
return JSON.parse(e);
}
function Ec(n) {
return n.created_at ? Math.round((/* @__PURE__ */ new Date()).getTime() / 1e3) - n.created_at < 60 : !1;
}
function _c(n) {
return n.kind === Vi;
}
function Sc(n, e) {
const t = n.tags.find((r) => r[0] === "u");
return t ? t.length > 0 && t[1] === e : !1;
}
function kc(n, e) {
const t = n.tags.find((r) => r[0] === "method");
return t ? t.length > 0 && t[1].toLowerCase() === e.toLowerCase() : !1;
}
function Qi(n) {
const e = Yn(st.encode(JSON.stringify(n)));
return ve(e);
}
function Ac(n, e) {
const t = n.tags.find((s) => s[0] === "payload");
if (!t)
return !1;
const r = Qi(e);
return t.length > 0 && t[1] === r;
}
async function Tc(n, e, t, r) {
if (!Xn(n))
throw new Error("Invalid nostr event, signature invalid");
if (!_c(n))
throw new Error("Invalid nostr event, kind invalid");
if (!Ec(n))
throw new Error("Invalid nostr event, created_at timestamp invalid");
if (!Sc(n, e))
throw new Error("Invalid nostr event, url tag invalid");
if (!kc(n, t))
throw new Error("Invalid nostr event, method tag invalid");
if (r && typeof r == "object" && Object.keys(r).length > 0 && !Ac(n, r))
throw new Error("Invalid nostr event, payload tag does not match request body hash");
return !0;
}
var Bc, Oc;
Bc = Symbol.iterator, Oc = Symbol.toStringTag;
var ea, ta, us, Ic;
const ut = class ut {
constructor(e) {
X(this, us);
B(this, "cache");
B(this, ea, "NSet");
this.cache = e ?? /* @__PURE__ */ new Map();
}
get size() {
return this.cache.size;
}
add(e) {
M(this, us, Ic).call(this, e);
for (const t of this) {
if (ut.deletes(t, e) || ut.replaces(t, e))
return this;
ut.replaces(e, t) && this.delete(t);
}
return this.cache.set(e.id, e), this;
}
clear() {
this.cache.clear();
}
delete(e) {
return this.cache.delete(e.id);
}
forEach(e, t) {
return this.cache.forEach((r, s) => e(r, r, this), t);
}
has(e) {
return this.cache.has(e.id);
}
*entries() {
for (const e of this.values())
yield [
e,
e
];
}
keys() {
return this.values();
}
*values() {
for (const e of ut.sortEvents([
...this.cache.values()
]))
yield e;
}
[(ta = Bc, ea = Oc, ta)]() {
return this.values();
}
/** Event kind is **replaceable**, which means that, for each combination of `pubkey` and `kind`, only the latest event is expected to (SHOULD) be stored by relays, older versions are expected to be discarded. */
static isReplaceable(e) {
return [
0,
3
].includes(e) || 1e4 <= e && e < 2e4;
}
/** Event kind is **parameterized replaceable**, which means that, for each combination of `pubkey`, `kind` and the `d` tag, only the latest event is expected to be stored by relays, older versions are expected to be discarded. */
static isParameterizedReplaceable(e) {
return 3e4 <= e && e < 4e4;
}
/**
* Returns true if `event` replaces `target`.
*
* Both events must be replaceable, belong to the same kind and pubkey (and `d` tag, for parameterized events), and the `event` must be newer than the `target`.
*/
static replaces(e, t) {
var i, o;
const { kind: r, pubkey: s } = e;
if (ut.isReplaceable(r))
return r === t.kind && s === t.pubkey && ut.sortEvents([
e,
t
])[0] === e;
if (ut.isParameterizedReplaceable(r)) {
const a = ((i = e.tags.find(([l]) => l === "d")) == null ? void 0 : i[1]) || "", c = ((o = t.tags.find(([l]) => l === "d")) == null ? void 0 : o[1]) || "";
return r === t.kind && s === t.pubkey && ut.sortEvents([
e,
t
])[0] === e && a === c;
}
return !1;
}
/**
* Returns true if the `event` deletes`target`.
*
* `event` must be a kind `5` event, and both events must share the same `pubkey`.
*/
static deletes(e, t) {
const { kind: r, pubkey: s, tags: i } = e;
if (r === 5 && s === t.pubkey) {
for (const [o, a] of i)
if (o === "e" && a === t.id)
return !0;
}
return !1;
}
/**
* Sort events in reverse-chronological order by the `created_at` timestamp,
* and then by the event `id` (lexicographically) in case of ties.
* This mutates the array.
*/
static sortEvents(e) {
return e.sort((t, r) => t.created_at !== r.created_at ? r.created_at - t.created_at : t.id.localeCompare(r.id));
}
union(e) {
throw new Error("Method not implemented.");
}
intersection(e) {
throw new Error("Method not implemented.");
}
difference(e) {
throw new Error("Method not implemented.");
}
symmetricDifference(e) {
throw new Error("Method not implemented.");
}
isSubsetOf(e) {
throw new Error("Method not implemented.");
}
isSupersetOf(e) {
throw new Error("Method not implemented.");
}
isDisjointFrom(e) {
throw new Error("Method not implemented.");
}
};
us = new WeakSet(), Ic = function(e) {
if (e.kind === 5) {
for (const t of e.tags)
if (t[0] === "e") {
const r = this.cache.get(t[1]);
r && r.pubkey === e.pubkey && this.delete(r);
}
}
};
let Zn = ut;
var Cc;
Cc = Symbol.toStringTag;
var na, ra;
class Mf extends (ra = Zn, na = Cc, ra) {
constructor(...t) {
super(new Ys(...t));
B(this, na, "NCache");
}
async event(t) {
this.add(t);
}
async query(t) {
const r = [];
for (const s of this)
fi(t, s) && (this.cache.get(s.id), r.push(s));
return r;
}
async remove(t) {
for (const r of this)
fi(t, r) && this.delete(r);
}
async count(t) {
return {
count: (await this.query(t)).length,
approximate: !1
};
}
}
var re;
(function(n) {
n.assertEqual = (s) => s;
function e(s) {
}
n.assertIs = e;
function t(s) {
throw new Error();
}
n.assertNever = t, n.arrayToEnum = (s) => {
const i = {};
for (const o of s)
i[o] = o;
return i;
}, n.getValidEnumValues = (s) => {
const i = n.objectKeys(s).filter((a) => typeof s[s[a]] != "number"), o = {};
for (const a of i)
o[a] = s[a];
return n.objectValues(o);
}, n.objectValues = (s) => n.objectKeys(s).map(function(i) {
return s[i];
}), n.objectKeys = typeof Object.keys == "function" ? (s) => Object.keys(s) : (s) => {
const i = [];
for (const o in s)
Object.prototype.hasOwnProperty.call(s, o) && i.push(o);
return i;
}, n.find = (s, i) => {
for (const o of s)
if (i(o))
return o;
}, n.isInteger = typeof Number.isInteger == "function" ? (s) => Number.isInteger(s) : (s) => typeof s == "number" && isFinite(s) && Math.floor(s) === s;
function r(s, i = " | ") {
return s.map((o) => typeof o == "string" ? `'${o}'` : o).join(i);
}
n.joinValues = r, n.jsonStringifyReplacer = (s, i) => typeof i == "bigint" ? i.toString() : i;
})(re || (re = {}));
var gi;
(function(n) {
n.mergeShapes = (e, t) => ({
...e,
...t
// second overwrites first
});
})(gi || (gi = {}));
const H = re.arrayToEnum([
"string",
"nan",
"number",
"integer",
"float",
"boolean",
"date",
"bigint",
"symbol",
"function",
"undefined",
"null",
"array",
"object",
"unknown",
"promise",
"void",
"never",
"map",
"set"
]), Yt = (n) => {
switch (typeof n) {
case "undefined":
return H.undefined;
case "string":
return H.string;
case "number":
return isNaN(n) ? H.nan : H.number;
case "boolean":
return H.boolean;
case "function":
return H.function;
case "bigint":
return H.bigint;
case "symbol":
return H.symbol;
case "object":
return Array.isArray(n) ? H.array : n === null ? H.null : n.then && typeof n.then == "function" && n.catch && typeof n.catch == "function" ? H.promise : typeof Map < "u" && n instanceof Map ? H.map : typeof Set < "u" && n instanceof Set ? H.set : typeof Date < "u" && n instanceof Date ? H.date : H.object;
default:
return H.unknown;
}
}, O = re.arrayToEnum([
"invalid_type",
"invalid_literal",
"custom",
"invalid_union",
"invalid_union_discriminator",
"invalid_enum_value",
"unrecognized_keys",
"invalid_arguments",
"invalid_return_type",
"invalid_date",
"invalid_string",
"too_small",
"too_big",
"invalid_intersection_types",
"not_multiple_of",
"not_finite"
]), jf = (n) => JSON.stringify(n, null, 2).replace(/"([^"]+)":/g, "$1:");
class Pe extends Error {
constructor(e) {
super(), this.issues = [], this.addIssue = (r) => {
this.issues = [...this.issues, r];
}, this.addIssues = (r = []) => {
this.issues = [...this.issues, ...r];
};
const t = new.target.prototype;
Object.setPrototypeOf ? Object.setPrototypeOf(this, t) : this.__proto__ = t, this.name = "ZodError", this.issues = e;
}
get errors() {
return this.issues;
}
format(e) {
const t = e || function(i) {
return i.message;
}, r = { _errors: [] }, s = (i) => {
for (const o of i.issues)
if (o.code === "invalid_union")
o.unionErrors.map(s);
else if (o.code === "invalid_return_type")
s(o.returnTypeError);
else if (o.code === "invalid_arguments")
s(o.argumentsError);
else if (o.path.length === 0)
r._errors.push(t(o));
else {
let a = r, c = 0;
for (; c < o.path.length; ) {
const l = o.path[c];
c === o.path.length - 1 ? (a[l] = a[l] || { _errors: [] }, a[l]._errors.push(t(o))) : a[l] = a[l] || { _errors: [] }, a = a[l], c++;
}
}
};
return s(this), r;
}
static assert(e) {
if (!(e instanceof Pe))
throw new Error(`Not a ZodError: ${e}`);
}
toString() {
return this.message;
}
get message() {
return JSON.stringify(this.issues, re.jsonStringifyReplacer, 2);
}
get isEmpty() {
return this.issues.length === 0;
}
flatten(e = (t) => t.message) {
const t = {}, r = [];
for (const s of this.issues)
s.path.length > 0 ? (t[s.path[0]] = t[s.path[0]] || [], t[s.path[0]].push(e(s))) : r.push(e(s));
return { formErrors: r, fieldErrors: t };
}
get formErrors() {
return this.flatten();
}
}
Pe.create = (n) => new Pe(n);
const zn = (n, e) => {
let t;
switch (n.code) {
case O.invalid_type:
n.received === H.undefined ? t = "Required" : t = `Expected ${n.expected}, received ${n.received}`;
break;
case O.invalid_literal:
t = `Invalid literal value, expected ${JSON.stringify(n.expected, re.jsonStringifyReplacer)}`;
break;
case O.unrecognized_keys:
t = `Unrecognized key(s) in object: ${re.joinValues(n.keys, ", ")}`;
break;
case O.invalid_union:
t = "Invalid input";
break;
case O.invalid_union_discriminator:
t = `Invalid discriminator value. Expected ${re.joinValues(n.options)}`;
break;
case O.invalid_enum_value:
t = `Invalid enum value. Expected ${re.joinValues(n.options)}, received '${n.received}'`;
break;
case O.invalid_arguments:
t = "Invalid function arguments";
break;
case O.invalid_return_type:
t = "Invalid function return type";
break;
case O.invalid_date:
t = "Invalid date";
break;
case O.invalid_string:
typeof n.validation == "object" ? "includes" in n.validation ? (t = `Invalid input: must include "${n.validation.includes}"`, typeof n.validation.position == "number" && (t = `${t} at one or more positions greater than or equal to ${n.validation.position}`)) : "startsWith" in n.validation ? t = `Invalid input: must start with "${n.validation.startsWith}"` : "endsWith" in n.validation ? t = `Invalid input: must end with "${n.validation.endsWith}"` : re.assertNever(n.validation) : n.validation !== "regex" ? t = `Invalid ${n.validation}` : t = "Invalid";
break;
case O.too_small:
n.type === "array" ? t = `Array must contain ${n.exact ? "exactly" : n.inclusive ? "at least" : "more than"} ${n.minimum} element(s)` : n.type === "string" ? t = `String must contain ${n.exact ? "exactly" : n.inclusive ? "at least" : "over"} ${n.minimum} character(s)` : n.type === "number" ? t = `Number must be ${n.exact ? "exactly equal to " : n.inclusive ? "greater than or equal to " : "greater than "}${n.minimum}` : n.type === "date" ? t = `Date must be ${n.exact ? "exactly equal to " : n.inclusive ? "greater than or equal to " : "greater than "}${new Date(Number(n.minimum))}` : t = "Invalid input";
break;
case O.too_big:
n.type === "array" ? t = `Array must contain ${n.exact ? "exactly" : n.inclusive ? "at most" : "less than"} ${n.maximum} element(s)` : n.type === "string" ? t = `String must contain ${n.exact ? "exactly" : n.inclusive ? "at most" : "under"} ${n.maximum} character(s)` : n.type === "number" ? t = `Number must be ${n.exact ? "exactly" : n.inclusive ? "less than or equal to" : "less than"} ${n.maximum}` : n.type === "bigint" ? t = `BigInt must be ${n.exact ? "exactly" : n.inclusive ? "less than or equal to" : "less than"} ${n.maximum}` : n.type === "date" ? t = `Date must be ${n.exact ? "exactly" : n.inclusive ? "smaller than or equal to" : "smaller than"} ${new Date(Number(n.maximum))}` : t = "Invalid input";
break;
case O.custom:
t = "Invalid input";
break;
case O.invalid_intersection_types:
t = "Intersection results could not be merged";
break;
case O.not_multiple_of:
t = `Number must be a multiple of ${n.multipleOf}`;
break;
case O.not_finite:
t = "Number must be finite";
break;
default:
t = e.defaultError, re.assertNever(n);
}
return { message: t };
};
let $c = zn;
function Pf(n) {
$c = n;
}
function ts() {
return $c;
}
const ns = (n) => {
const { data: e, path: t, errorMaps: r, issueData: s } = n, i = [...t, ...s.path || []], o = {
...s,
path: i
};
if (s.message !== void 0)
return {
...s,
path: i,
message: s.message
};
let a = "";
const c = r.filter((l) => !!l).slice().reverse();
for (const l of c)
a = l(o, { data: e, defaultError: a }).message;
return {
...s,
path: i,
message: a
};
}, Zf = [];
function U(n, e) {
const t = ts(), r = ns({
issueData: e,
data: n.data,
path: n.path,
errorMaps: [
n.common.contextualErrorMap,
n.schemaErrorMap,
t,
t === zn ? void 0 : zn
// then global default map
].filter((s) => !!s)
});
n.common.issues.push(r);
}
class Be {
constructor() {
this.value = "valid";
}
dirty() {
this.value === "valid" && (this.value = "dirty");
}
abort() {
this.value !== "aborted" && (this.value = "aborted");
}
static mergeArray(e, t) {
const r = [];
for (const s of t) {
if (s.status === "aborted")
return K;
s.status === "dirty" && e.dirty(), r.push(s.value);
}
return { status: e.value, value: r };
}
static async mergeObjectAsync(e, t) {
const r = [];
for (const s of t) {
const i = await s.key, o = await s.value;
r.push({
key: i,
value: o
});
}
return Be.mergeObjectSync(e, r);
}
static mergeObjectSync(e, t) {
const r = {};
for (const s of t) {
const { key: i, value: o } = s;
if (i.status === "aborted" || o.status === "aborted")
return K;
i.status === "dirty" && e.dirty(), o.status === "dirty" && e.dirty(), i.value !== "__proto__" && (typeof o.value < "u" || s.alwaysSet) && (r[i.value] = o.value);
}
return { status: e.value, value: r };
}
}
const K = Object.freeze({
status: "aborted"
}), Bn = (n) => ({ status: "dirty", value: n }), $e = (n) => ({ status: "valid", value: n }), yi = (n) => n.status === "aborted", mi = (n) => n.status === "dirty", lr = (n) => n.status === "valid", ur = (n) => typeof Promise < "u" && n instanceof Promise;
function rs(n, e, t, r) {
if (typeof e == "function" ? n !== e || !r : !e.has(n)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
return e.get(n);
}
function Rc(n, e, t, r, s) {
if (typeof e == "function" ? n !== e || !s : !e.has(n)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
return e.set(n, t), t;
}
var D;
(function(n) {
n.errToObj = (e) => typeof e == "string" ? { message: e } : e || {}, n.toString = (e) => typeof e == "string" ? e : e == null ? void 0 : e.message;
})(D || (D = {}));
var nr, rr;
class mt {
constructor(e, t, r, s) {
this._cachedPath = [], this.parent = e, this.data = t, this._path = r, this._key = s;
}
get path() {
return this._cachedPath.length || (this._key instanceof Array ? this._cachedPath.push(...this._path, ...this._key) : this._cachedPath.push(...this._path, this._key)), this._cachedPath;
}
}
const No = (n, e) => {
if (lr(e))
return { success: !0, data: e.value };
if (!n.common.issues.length)
throw new Error("Validation failed but no issues detected.");
return {
success: !1,
get error() {
if (this._error)
return this._error;
const t = new Pe(n.common.issues);
return this._error = t, this._error;
}
};
};
function J(n) {
if (!n)
return {};
const { errorMap: e, invalid_type_error: t, required_error: r, description: s } = n;
if (e && (t || r))
throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);
return e ? { errorMap: e, description: s } : { errorMap: (o, a) => {
var c, l;
const { message: d } = n;
return o.code === "invalid_enum_value" ? { message: d ?? a.defaultError } : typeof a.data > "u" ? { message: (c = d ?? r) !== null && c !== void 0 ? c : a.defaultError } : o.code !== "invalid_type" ? { message: a.defaultError } : { message: (l = d ?? t) !== null && l !== void 0 ? l : a.defaultError };
}, description: s };
}
class ee {
constructor(e) {
this.spa = this.safeParseAsync, this._def = e, this.parse = this.parse.bind(this), this.safeParse = this.safeParse.bind(this), this.parseAsync = this.parseAsync.bind(this), this.safeParseAsync = this.safeParseAsync.bind(this), this.spa = this.spa.bind(this), this.refine = this.refine.bind(this), this.refinement = this.refinement.bind(this), this.superRefine = this.superRefine.bind(this), this.optional = this.optional.bind(this), this.nullable = this.nullable.bind(this), this.nullish = this.nullish.bind(this), this.array = this.array.bind(this), this.promise = this.promise.bind(this), this.or = this.or.bind(this), this.and = this.and.bind(this), this.transform = this.transform.bind(this), this.brand = this.brand.bind(this), this.default = this.default.bind(this), this.catch = this.catch.bind(this), this.describe = this.describe.bind(this), this.pipe = this.pipe.bind(this), this.readonly = this.readonly.bind(this), this.isNullable = this.isNullable.bind(this), this.isOptional = this.isOptional.bind(this);
}
get description() {
return this._def.description;
}
_getType(e) {
return Yt(e.data);
}
_getOrReturnCtx(e, t) {
return t || {
common: e.parent.common,
data: e.data,
parsedType: Yt(e.data),
schemaErrorMap: this._def.errorMap,
path: e.path,
parent: e.parent
};
}
_processInputParams(e) {
return {
status: new Be(),
ctx: {
common: e.parent.common,
data: e.data,
parsedType: Yt(e.data),
schemaErrorMap: this._def.errorMap,
path: e.path,
parent: e.parent
}
};
}
_parseSync(e) {
const t = this._parse(e);
if (ur(t))
throw new Error("Synchronous parse encountered promise.");
return t;
}
_parseAsync(e) {
const t = this._parse(e);
return Promise.resolve(t);
}
parse(e, t) {
const r = this.safeParse(e, t);
if (r.success)
return r.data;
throw r.error;
}
safeParse(e, t) {
var r;
const s = {
common: {
issues: [],
async: (r = t == null ? void 0 : t.async) !== null && r !== void 0 ? r : !1,
contextualErrorMap: t == null ? void 0 : t.errorMap
},
path: (t == null ? void 0 : t.path) || [],
schemaErrorMap: this._def.errorMap,
parent: null,
data: e,
parsedType: Yt(e)
}, i = this._parseSync({ data: e, path: s.path, parent: s });
return No(s, i);
}
async parseAsync(e, t) {
const r = await this.safeParseAsync(e, t);
if (r.success)
return r.data;
throw r.error;
}
async safeParseAsync(e, t) {
const r = {
common: {
issues: [],
contextualErrorMap: t == null ? void 0 : t.errorMap,
async: !0
},
path: (t == null ? void 0 : t.path) || [],
schemaErrorMap: this._def.errorMap,
parent: null,
data: e,
parsedType: Yt(e)
}, s = this._parse({ data: e, path: r.path, parent: r }), i = await (ur(s) ? s : Promise.resolve(s));
return No(r, i);
}
refine(e, t) {
const r = (s) => typeof t == "string" || typeof t > "u" ? { message: t } : typeof t == "function" ? t(s) : t;
return this._refinement((s, i) => {
const o = e(s), a = () => i.addIssue({
code: O.custom,
...r(s)
});
return typeof Promise < "u" && o instanceof Promise ? o.then((c) => c ? !0 : (a(), !1)) : o ? !0 : (a(), !1);
});
}
refinement(e, t) {
return this._refinement((r, s) => e(r) ? !0 : (s.addIssue(typeof t == "function" ? t(r, s) : t), !1));
}
_refinement(e) {
return new it({
schema: this,
typeName: V.ZodEffects,
effect: { type: "refinement", refinement: e }
});
}
superRefine(e) {
return this._refinement(e);
}
optional() {
return yt.create(this, this._def);
}
nullable() {
return sn.create(this, this._def);
}
nullish() {
return this.nullable().optional();
}
array() {
return rt.create(this, this._def);
}
promise() {
return qn.create(this, this._def);
}
or(e) {
return pr.create([this, e], this._def);
}
and(e) {
return gr.create(this, e, this._def);
}
transform(e) {
return new it({
...J(this._def),
schema: this,
typeName: V.ZodEffects,
effect: { type: "transform", transform: e }
});
}
default(e) {
const t = typeof e == "function" ? e : () => e;
return new vr({
...J(this._def),
innerType: this,
defaultValue: t,
typeName: V.ZodDefault
});
}
brand() {
return new eo({
typeName: V.ZodBranded,
type: this,
...J(this._def)
});
}
catch(e) {
const t = typeof e == "function" ? e : () => e;
return new xr({
...J(this._def),
innerType: this,
catchValue: t,
typeName: V.ZodCatch
});
}
describe(e) {
const t = this.constructor;
return new t({
...this._def,
description: e
});
}
pipe(e) {
return Rr.create(this, e);
}
readonly() {
return Er.create(this);
}
isOptional() {
return this.safeParse(void 0).success;
}
isNullable() {
return this.safeParse(null).success;
}
}
const zf = /^c[^\s-]{8,}$/i, Df = /^[0-9a-z]+$/, qf = /^[0-9A-HJKMNP-TV-Z]{26}$/, Vf = /^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i, Kf = /^[a-z0-9_-]{21}$/i, Wf = /^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/, Ff = /^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i, Gf = "^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";
let js;
const Yf = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/, Jf = /^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/, Xf = /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/, Nc = "((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))", Qf = new RegExp(`^${Nc}$`);
function Lc(n) {
let e = "([01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d";
return n.precision ? e = `${e}\\.\\d{${n.precision}}` : n.precision == null && (e = `${e}(\\.\\d+)?`), e;
}
function ep(n) {
return new RegExp(`^${Lc(n)}$`);
}
function Uc(n) {
let e = `${Nc}T${Lc(n)}`;
const t = [];
return t.push(n.local ? "Z?" : "Z"), n.offset && t.push("([+-]\\d{2}:?\\d{2})"), e = `${e}(${t.join("|")})`, new RegExp(`^${e}$`);
}
function tp(n, e) {
return !!((e === "v4" || !e) && Yf.test(n) || (e === "v6" || !e) && Jf.test(n));
}
class nt extends ee {
_parse(e) {
if (this._def.coerce && (e.data = String(e.data)), this._getType(e) !== H.string) {
const i = this._getOrReturnCtx(e);
return U(i, {
code: O.invalid_type,
expected: H.string,
received: i.parsedType
}), K;
}
const r = new Be();
let s;
for (const i of this._def.checks)
if (i.kind === "min")
e.data.length < i.value && (s = this._getOrReturnCtx(e, s), U(s, {
code: O.too_small,
minimum: i.value,
type: "string",
inclusive: !0,
exact: !1,
message: i.message
}), r.dirty());
else if (i.kind === "max")
e.data.length > i.value && (s = this._getOrReturnCtx(e, s), U(s, {
code: O.too_big,
maximum: i.value,
type: "string",
inclusive: !0,
exact: !1,
message: i.message
}), r.dirty());
else if (i.kind === "length") {
const o = e.data.length > i.value, a = e.data.length < i.value;
(o || a) && (s = this._getOrReturnCtx(e, s), o ? U(s, {
code: O.too_big,
maximum: i.value,
type: "string",
inclusive: !0,
exact: !0,
message: i.message
}) : a && U(s, {
code: O.too_small,
minimum: i.value,
type: "string",
inclusive: !0,
exact: !0,
message: i.message
}), r.dirty());
} else if (i.kind === "email")
Ff.test(e.data) || (s = this._getOrReturnCtx(e, s), U(s, {
validation: "email",
code: O.invalid_string,
message: i.message
}), r.dirty());
else if (i.kind === "emoji")
js || (js = new RegExp(Gf, "u")), js.test(e.data) || (s = this._getOrReturnCtx(e, s), U(s, {
validation: "emoji",
code: O.invalid_string,
message: i.message
}), r.dirty());
else if (i.kind === "uuid")
Vf.test(e.data) || (s = this._getOrReturnCtx(e, s), U(s, {
validation: "uuid",
code: O.invalid_string,
message: i.message
}), r.dirty());
else if (i.kind === "nanoid")
Kf.test(e.data) || (s = this._getOrReturnCtx(e, s), U(s, {
validation: "nanoid",
code: O.invalid_string,
message: i.message
}), r.dirty());
else if (i.kind === "cuid")
zf.test(e.data) || (s = this._getOrReturnCtx(e, s), U(s, {
validation: "cuid",
code: O.invalid_string,
message: i.message
}), r.dirty());
else if (i.kind === "cuid2")
Df.test(e.data) || (s = this._getOrReturnCtx(e, s), U(s, {
validation: "cuid2",
code: O.invalid_string,
message: i.message
}), r.dirty());
else if (i.kind === "ulid")
qf.test(e.data) || (s = this._getOrReturnCtx(e, s), U(s, {
validation: "ulid",
code: O.invalid_string,
message: i.message
}), r.dirty());
else if (i.kind === "url")
try {
new URL(e.data);
} catch {
s = this._getOrReturnCtx(e, s), U(s, {
validation: "url",
code: O.invalid_string,
message: i.message
}), r.dirty();
}
else i.kind === "regex" ? (i.regex.lastIndex = 0, i.regex.test(e.data) || (s = this._getOrReturnCtx(e, s), U(s, {
validation: "regex",
code: O.invalid_string,
message: i.message
}), r.dirty())) : i.kind === "trim" ? e.data = e.data.trim() : i.kind === "includes" ? e.data.includes(i.value, i.position) || (s = this._getOrReturnCtx(e, s), U(s, {
code: O.invalid_string,
validation: { includes: i.value, position: i.position },
message: i.message
}), r.dirty()) : i.kind === "toLowerCase" ? e.data = e.data.toLowerCase() : i.kind === "toUpperCase" ? e.data = e.data.toUpperCase() : i.kind === "startsWith" ? e.data.startsWith(i.value) || (s = this._getOrReturnCtx(e, s), U(s, {
code: O.invalid_string,
validation: { startsWith: i.value },
message: i.message
}), r.dirty()) : i.kind === "endsWith" ? e.data.endsWith(i.value) || (s = this._getOrReturnCtx(e, s), U(s, {
code: O.invalid_string,
validation: { endsWith: i.value },
message: i.message
}), r.dirty()) : i.kind === "datetime" ? Uc(i).test(e.data) || (s = this._getOrReturnCtx(e, s), U(s, {
code: O.invalid_string,
validation: "datetime",
message: i.message
}), r.dirty()) : i.kind === "date" ? Qf.test(e.data) || (s = this._getOrReturnCtx(e, s), U(s, {
code: O.invalid_string,
validation: "date",
message: i.message
}), r.dirty()) : i.kind === "time" ? ep(i).test(e.data) || (s = this._getOrReturnCtx(e, s), U(s, {
code: O.invalid_string,
validation: "time",
message: i.message
}), r.dirty()) : i.kind === "duration" ? Wf.test(e.data) || (s = this._getOrReturnCtx(e, s), U(s, {
validation: "duration",
code: O.invalid_string,
message: i.message
}), r.dirty()) : i.kind === "ip" ? tp(e.data, i.version) || (s = this._getOrReturnCtx(e, s), U(s, {
validation: "ip",
code: O.invalid_string,
message: i.message
}), r.dirty()) : i.kind === "base64" ? Xf.test(e.data) || (s = this._getOrReturnCtx(e, s), U(s, {
validation: "base64",
code: O.invalid_string,
message: i.message
}), r.dirty()) : re.assertNever(i);
return { status: r.value, value: e.data };
}
_regex(e, t, r) {
return this.refinement((s) => e.test(s), {
validation: t,
code: O.invalid_string,
...D.errToObj(r)
});
}
_addCheck(e) {
return new nt({
...this._def,
checks: [...this._def.checks, e]
});
}
email(e) {
return this._addCheck({ kind: "email", ...D.errToObj(e) });
}
url(e) {
return this._addCheck({ kind: "url", ...D.errToObj(e) });
}
emoji(e) {
return this._addCheck({ kind: "emoji", ...D.errToObj(e) });
}
uuid(e) {
return this._addCheck({ kind: "uuid", ...D.errToObj(e) });
}
nanoid(e) {
return this._addCheck({ kind: "nanoid", ...D.errToObj(e) });
}
cuid(e) {
return this._addCheck({ kind: "cuid", ...D.errToObj(e) });
}
cuid2(e) {
return this._addCheck({ kind: "cuid2", ...D.errToObj(e) });
}
ulid(e) {
return this._addCheck({ kind: "ulid", ...D.errToObj(e) });
}
base64(e) {
return this._addCheck({ kind: "base64", ...D.errToObj(e) });
}
ip(e) {
return this._addCheck({ kind: "ip", ...D.errToObj(e) });
}
datetime(e) {
var t, r;
return typeof e == "string" ? this._addCheck({
kind: "datetime",
precision: null,
offset: !1,
local: !1,
message: e
}) : this._addCheck({
kind: "datetime",
precision: typeof (e == null ? void 0 : e.precision) > "u" ? null : e == null ? void 0 : e.precision,
offset: (t = e == null ? void 0 : e.offset) !== null && t !== void 0 ? t : !1,
local: (r = e == null ? void 0 : e.local) !== null && r !== void 0 ? r : !1,
...D.errToObj(e == null ? void 0 : e.message)
});
}
date(e) {
return this._addCheck({ kind: "date", message: e });
}
time(e) {
return typeof e == "string" ? this._addCheck({
kind: "time",
precision: null,
message: e
}) : this._addCheck({
kind: "time",
precision: typeof (e == null ? void 0 : e.precision) > "u" ? null : e == null ? void 0 : e.precision,
...D.errToObj(e == null ? void 0 : e.message)
});
}
duration(e) {
return this._addCheck({ kind: "duration", ...D.errToObj(e) });
}
regex(e, t) {
return this._addCheck({
kind: "regex",
regex: e,
...D.errToObj(t)
});
}
includes(e, t) {
return this._addCheck({
kind: "includes",
value: e,
position: t == null ? void 0 : t.position,
...D.errToObj(t == null ? void 0 : t.message)
});
}
startsWith(e, t) {
return this._addCheck({
kind: "startsWith",
value: e,
...D.errToObj(t)
});
}
endsWith(e, t) {
return this._addCheck({
kind: "endsWith",
value: e,
...D.errToObj(t)
});
}
min(e, t) {
return this._addCheck({
kind: "min",
value: e,
...D.errToObj(t)
});
}
max(e, t) {
return this._addCheck({
kind: "max",
value: e,
...D.errToObj(t)
});
}
length(e, t) {
return this._addCheck({
kind: "length",
value: e,
...D.errToObj(t)
});
}
/**
* @deprecated Use z.string().min(1) instead.
* @see {@link ZodString.min}
*/
nonempty(e) {
return this.min(1, D.errToObj(e));
}
trim() {
return new nt({
...this._def,
checks: [...this._def.checks, { kind: "trim" }]
});
}
toLowerCase() {
return new nt({
...this._def,
checks: [...this._def.checks, { kind: "toLowerCase" }]
});
}
toUpperCase() {
return new nt({
...this._def,
checks: [...this._def.checks, { kind: "toUpperCase" }]
});
}
get isDatetime() {
return !!this._def.checks.find((e) => e.kind === "datetime");
}
get isDate() {
return !!this._def.checks.find((e) => e.kind === "date");
}
get isTime() {
return !!this._def.checks.find((e) => e.kind === "time");
}
get isDuration() {
return !!this._def.checks.find((e) => e.kind === "duration");
}
get isEmail() {
return !!this._def.checks.find((e) => e.kind === "email");
}
get isURL() {
return !!this._def.checks.find((e) => e.kind === "url");
}
get isEmoji() {
return !!this._def.checks.find((e) => e.kind === "emoji");
}
get isUUID() {
return !!this._def.checks.find((e) => e.kind === "uuid");
}
get isNANOID() {
return !!this._def.checks.find((e) => e.kind === "nanoid");
}
get isCUID() {
return !!this._def.checks.find((e) => e.kind === "cuid");
}
get isCUID2() {
return !!this._def.checks.find((e) => e.kind === "cuid2");
}
get isULID() {
return !!this._def.checks.find((e) => e.kind === "ulid");
}
get isIP() {
return !!this._def.checks.find((e) => e.kind === "ip");
}
get isBase64() {
return !!this._def.checks.find((e) => e.kind === "base64");
}
get minLength() {
let e = null;
for (const t of this._def.checks)
t.kind === "min" && (e === null || t.value > e) && (e = t.value);
return e;
}
get maxLength() {
let e = null;
for (const t of this._def.checks)
t.kind === "max" && (e === null || t.value < e) && (e = t.value);
return e;
}
}
nt.create = (n) => {
var e;
return new nt({
checks: [],
typeName: V.ZodString,
coerce: (e = n == null ? void 0 : n.coerce) !== null && e !== void 0 ? e : !1,
...J(n)
});
};
function np(n, e) {
const t = (n.toString().split(".")[1] || "").length, r = (e.toString().split(".")[1] || "").length, s = t > r ? t : r, i = parseInt(n.toFixed(s).replace(".", "")), o = parseInt(e.toFixed(s).replace(".", ""));
return i % o / Math.pow(10, s);
}
class tn extends ee {
constructor() {
super(...arguments), this.min = this.gte, this.max = this.lte, this.step = this.multipleOf;
}
_parse(e) {
if (this._def.coerce && (e.data = Number(e.data)), this._getType(e) !== H.number) {
const i = this._getOrReturnCtx(e);
return U(i, {
code: O.invalid_type,
expected: H.number,
received: i.parsedType
}), K;
}
let r;
const s = new Be();
for (const i of this._def.checks)
i.kind === "int" ? re.isInteger(e.data) || (r = this._getOrReturnCtx(e, r), U(r, {
code: O.invalid_type,
expected: "integer",
received: "float",
message: i.message
}), s.dirty()) : i.kind === "min" ? (i.inclusive ? e.data < i.value : e.data <= i.value) && (r = this._getOrReturnCtx(e, r), U(r, {
code: O.too_small,
minimum: i.value,
type: "number",
inclusive: i.inclusive,
exact: !1,
message: i.message
}), s.dirty()) : i.kind === "max" ? (i.inclusive ? e.data > i.value : e.data >= i.value) && (r = this._getOrReturnCtx(e, r), U(r, {
code: O.too_big,
maximum: i.value,
type: "number",
inclusive: i.inclusive,
exact: !1,
message: i.message
}), s.dirty()) : i.kind === "multipleOf" ? np(e.data, i.value) !== 0 && (r = this._getOrReturnCtx(e, r), U(r, {
code: O.not_multiple_of,
multipleOf: i.value,
message: i.message
}), s.dirty()) : i.kind === "finite" ? Number.isFinite(e.data) || (r = this._getOrReturnCtx(e, r), U(r, {
code: O.not_finite,
message: i.message
}), s.dirty()) : re.assertNever(i);
return { status: s.value, value: e.data };
}
gte(e, t) {
return this.setLimit("min", e, !0, D.toString(t));
}
gt(e, t) {
return this.setLimit("min", e, !1, D.toString(t));
}
lte(e, t) {
return this.setLimit("max", e, !0, D.toString(t));
}
lt(e, t) {
return this.setLimit("max", e, !1, D.toString(t));
}
setLimit(e, t, r, s) {
return new tn({
...this._def,
checks: [
...this._def.checks,
{
kind: e,
value: t,
inclusive: r,
message: D.toString(s)
}
]
});
}
_addCheck(e) {
return new tn({
...this._def,
checks: [...this._def.checks, e]
});
}
int(e) {
return this._addCheck({
kind: "int",
message: D.toString(e)
});
}
positive(e) {
return this._addCheck({
kind: "min",
value: 0,
inclusive: !1,
message: D.toString(e)
});
}
negative(e) {
return this._addCheck({
kind: "max",
value: 0,
inclusive: !1,
message: D.toString(e)
});
}
nonpositive(e) {
return this._addCheck({
kind: "max",
value: 0,
inclusive: !0,
message: D.toString(e)
});
}
nonnegative(e) {
return this._addCheck({
kind: "min",
value: 0,
inclusive: !0,
message: D.toString(e)
});
}
multipleOf(e, t) {
return this._addCheck({
kind: "multipleOf",
value: e,
message: D.toString(t)
});
}
finite(e) {
return this._addCheck({
kind: "finite",
message: D.toString(e)
});
}
safe(e) {
return this._addCheck({
kind: "min",
inclusive: !0,
value: Number.MIN_SAFE_INTEGER,
message: D.toString(e)
})._addCheck({
kind: "max",
inclusive: !0,
value: Number.MAX_SAFE_INTEGER,
message: D.toString(e)
});
}
get minValue() {
let e = null;
for (const t of this._def.checks)
t.kind === "min" && (e === null || t.value > e) && (e = t.value);
return e;
}
get maxValue() {
let e = null;
for (const t of this._def.checks)
t.kind === "max" && (e === null || t.value < e) && (e = t.value);
return e;
}
get isInt() {
return !!this._def.checks.find((e) => e.kind === "int" || e.kind === "multipleOf" && re.isInteger(e.value));
}
get isFinite() {
let e = null, t = null;
for (const r of this._def.checks) {
if (r.kind === "finite" || r.kind === "int" || r.kind === "multipleOf")
return !0;
r.kind === "min" ? (t === null || r.value > t) && (t = r.value) : r.kind === "max" && (e === null || r.value < e) && (e = r.value);
}
return Number.isFinite(t) && Number.isFinite(e);
}
}
tn.create = (n) => new tn({
checks: [],
typeName: V.ZodNumber,
coerce: (n == null ? void 0 : n.coerce) || !1,
...J(n)
});
class nn extends ee {
constructor() {
super(...arguments), this.min = this.gte, this.max = this.lte;
}
_parse(e) {
if (this._def.coerce && (e.data = BigInt(e.data)), this._getType(e) !== H.bigint) {
const i = this._getOrReturnCtx(e);
return U(i, {
code: O.invalid_type,
expected: H.bigint,
received: i.parsedType
}), K;
}
let r;
const s = new Be();
for (const i of this._def.checks)
i.kind === "min" ? (i.inclusive ? e.data < i.value : e.data <= i.value) && (r = this._getOrReturnCtx(e, r), U(r, {
code: O.too_small,
type: "bigint",
minimum: i.value,
inclusive: i.inclusive,
message: i.message
}), s.dirty()) : i.kind === "max" ? (i.inclusive ? e.data > i.value : e.data >= i.value) && (r = this._getOrReturnCtx(e, r), U(r, {
code: O.too_big,
type: "bigint",
maximum: i.value,
inclusive: i.inclusive,
message: i.message
}), s.dirty()) : i.kind === "multipleOf" ? e.data % i.value !== BigInt(0) && (r = this._getOrReturnCtx(e, r), U(r, {
code: O.not_multiple_of,
multipleOf: i.value,
message: i.message
}), s.dirty()) : re.assertNever(i);
return { status: s.value, value: e.data };
}
gte(e, t) {
return this.setLimit("min", e, !0, D.toString(t));
}
gt(e, t) {
return this.setLimit("min", e, !1, D.toString(t));
}
lte(e, t) {
return this.setLimit("max", e, !0, D.toString(t));
}
lt(e, t) {
return this.setLimit("max", e, !1, D.toString(t));
}
setLimit(e, t, r, s) {
return new nn({
...this._def,
checks: [
...this._def.checks,
{
kind: e,
value: t,
inclusive: r,
message: D.toString(s)
}
]
});
}
_addCheck(e) {
return new nn({
...this._def,
checks: [...this._def.checks, e]
});
}
positive(e) {
return this._addCheck({
kind: "min",
value: BigInt(0),
inclusive: !1,
message: D.toString(e)
});
}
negative(e) {
return this._addCheck({
kind: "max",
value: BigInt(0),
inclusive: !1,
message: D.toString(e)
});
}
nonpositive(e) {
return this._addCheck({
kind: "max",
value: BigInt(0),
inclusive: !0,
message: D.toString(e)
});
}
nonnegative(e) {
return this._addCheck({
kind: "min",
value: BigInt(0),
inclusive: !0,
message: D.toString(e)
});
}
multipleOf(e, t) {
return this._addCheck({
kind: "multipleOf",
value: e,
message: D.toString(t)
});
}
get minValue() {
let e = null;
for (const t of this._def.checks)
t.kind === "min" && (e === null || t.value > e) && (e = t.value);
return e;
}
get maxValue() {
let e = null;
for (const t of this._def.checks)
t.kind === "max" && (e === null || t.value < e) && (e = t.value);
return e;
}
}
nn.create = (n) => {
var e;
return new nn({
checks: [],
typeName: V.ZodBigInt,
coerce: (e = n == null ? void 0 : n.coerce) !== null && e !== void 0 ? e : !1,
...J(n)
});
};
class dr extends ee {
_parse(e) {
if (this._def.coerce && (e.data = !!e.data), this._getType(e) !== H.boolean) {
const r = this._getOrReturnCtx(e);
return U(r, {
code: O.invalid_type,
expected: H.boolean,
received: r.parsedType
}), K;
}
return $e(e.data);
}
}
dr.create = (n) => new dr({
typeName: V.ZodBoolean,
coerce: (n == null ? void 0 : n.coerce) || !1,
...J(n)
});
class vn extends ee {
_parse(e) {
if (this._def.coerce && (e.data = new Date(e.data)), this._getType(e) !== H.date) {
const i = this._getOrReturnCtx(e);
return U(i, {
code: O.invalid_type,
expected: H.date,
received: i.parsedType
}), K;
}
if (isNaN(e.data.getTime())) {
const i = this._getOrReturnCtx(e);
return U(i, {
code: O.invalid_date
}), K;
}
const r = new Be();
let s;
for (const i of this._def.checks)
i.kind === "min" ? e.data.getTime() < i.value && (s = this._getOrReturnCtx(e, s), U(s, {
code: O.too_small,
message: i.message,
inclusive: !0,
exact: !1,
minimum: i.value,
type: "date"
}), r.dirty()) : i.kind === "max" ? e.data.getTime() > i.value && (s = this._getOrReturnCtx(e, s), U(s, {
code: O.too_big,
message: i.message,
inclusive: !0,
exact: !1,
maximum: i.value,
type: "date"
}), r.dirty()) : re.assertNever(i);
return {
status: r.value,
value: new Date(e.data.getTime())
};
}
_addCheck(e) {
return new vn({
...this._def,
checks: [...this._def.checks, e]
});
}
min(e, t) {
return this._addCheck({
kind: "min",
value: e.getTime(),
message: D.toString(t)
});
}
max(e, t) {
return this._addCheck({
kind: "max",
value: e.getTime(),
message: D.toString(t)
});
}
get minDate() {
let e = null;
for (const t of this._def.checks)
t.kind === "min" && (e === null || t.value > e) && (e = t.value);
return e != null ? new Date(e) : null;
}
get maxDate() {
let e = null;
for (const t of this._def.checks)
t.kind === "max" && (e === null || t.value < e) && (e = t.value);
return e != null ? new Date(e) : null;
}
}
vn.create = (n) => new vn({
checks: [],
coerce: (n == null ? void 0 : n.coerce) || !1,
typeName: V.ZodDate,
...J(n)
});
class ss extends ee {
_parse(e) {
if (this._getType(e) !== H.symbol) {
const r = this._getOrReturnCtx(e);
return U(r, {
code: O.invalid_type,
expected: H.symbol,
received: r.parsedType
}), K;
}
return $e(e.data);
}
}
ss.create = (n) => new ss({
typeName: V.ZodSymbol,
...J(n)
});
class hr extends ee {
_parse(e) {
if (this._getType(e) !== H.undefined) {
const r = this._getOrReturnCtx(e);
return U(r, {
code: O.invalid_type,
expected: H.undefined,
received: r.parsedType
}), K;
}
return $e(e.data);
}
}
hr.create = (n) => new hr({
typeName: V.ZodUndefined,
...J(n)
});
class fr extends ee {
_parse(e) {
if (this._getType(e) !== H.null) {
const r = this._getOrReturnCtx(e);
return U(r, {
code: O.invalid_type,
expected: H.null,
received: r.parsedType
}), K;
}
return $e(e.data);
}
}
fr.create = (n) => new fr({
typeName: V.ZodNull,
...J(n)
});
class Dn extends ee {
constructor() {
super(...arguments), this._any = !0;
}
_parse(e) {
return $e(e.data);
}
}
Dn.create = (n) => new Dn({
typeName: V.ZodAny,
...J(n)
});
class gn extends ee {
constructor() {
super(...arguments), this._unknown = !0;
}
_parse(e) {
return $e(e.data);
}
}
gn.create = (n) => new gn({
typeName: V.ZodUnknown,
...J(n)
});
class Rt extends ee {
_parse(e) {
const t = this._getOrReturnCtx(e);
return U(t, {
code: O.invalid_type,
expected: H.never,
received: t.parsedType
}), K;
}
}
Rt.create = (n) => new Rt({
typeName: V.ZodNever,
...J(n)
});
class is extends ee {
_parse(e) {
if (this._getType(e) !== H.undefined) {
const r = this._getOrReturnCtx(e);
return U(r, {
code: O.invalid_type,
expected: H.void,
received: r.parsedType
}), K;
}
return $e(e.data);
}
}
is.create = (n) => new is({
typeName: V.ZodVoid,
...J(n)
});
class rt extends ee {
_parse(e) {
const { ctx: t, status: r } = this._processInputParams(e), s = this._def;
if (t.parsedType !== H.array)
return U(t, {
code: O.invalid_type,
expected: H.array,
received: t.parsedType
}), K;
if (s.exactLength !== null) {
const o = t.data.length > s.exactLength.value, a = t.data.length < s.exactLength.value;
(o || a) && (U(t, {
code: o ? O.too_big : O.too_small,
minimum: a ? s.exactLength.value : void 0,
maximum: o ? s.exactLength.value : void 0,
type: "array",
inclusive: !0,
exact: !0,
message: s.exactLength.message
}), r.dirty());
}
if (s.minLength !== null && t.data.length < s.minLength.value && (U(t, {
code: O.too_small,
minimum: s.minLength.value,
type: "array",
inclusive: !0,
exact: !1,
message: s.minLength.message
}), r.dirty()), s.maxLength !== null && t.data.length > s.maxLength.value && (U(t, {
code: O.too_big,
maximum: s.maxLength.value,
type: "array",
inclusive: !0,
exact: !1,
message: s.maxLength.message
}), r.dirty()), t.common.async)
return Promise.all([...t.data].map((o, a) => s.type._parseAsync(new mt(t, o, t.path, a)))).then((o) => Be.mergeArray(r, o));
const i = [...t.data].map((o, a) => s.type._parseSync(new mt(t, o, t.path, a)));
return Be.mergeArray(r, i);
}
get element() {
return this._def.type;
}
min(e, t) {
return new rt({
...this._def,
minLength: { value: e, message: D.toString(t) }
});
}
max(e, t) {
return new rt({
...this._def,
maxLength: { value: e, message: D.toString(t) }
});
}
length(e, t) {
return new rt({
...this._def,
exactLength: { value: e, message: D.toString(t) }
});
}
nonempty(e) {
return this.min(1, e);
}
}
rt.create = (n, e) => new rt({
type: n,
minLength: null,
maxLength: null,
exactLength: null,
typeName: V.ZodArray,
...J(e)
});
function An(n) {
if (n instanceof le) {
const e = {};
for (const t in n.shape) {
const r = n.shape[t];
e[t] = yt.create(An(r));
}
return new le({
...n._def,
shape: () => e
});
} else return n instanceof rt ? new rt({
...n._def,
type: An(n.element)
}) : n instanceof yt ? yt.create(An(n.unwrap())) : n instanceof sn ? sn.create(An(n.unwrap())) : n instanceof wt ? wt.create(n.items.map((e) => An(e))) : n;
}
class le extends ee {
constructor() {
super(...arguments), this._cached = null, this.nonstrict = this.passthrough, this.augment = this.extend;
}
_getCached() {
if (this._cached !== null)
return this._cached;
const e = this._def.shape(), t = re.objectKeys(e);
return this._cached = { shape: e, keys: t };
}
_parse(e) {
if (this._getType(e) !== H.object) {
const l = this._getOrReturnCtx(e);
return U(l, {
code: O.invalid_type,
expected: H.object,
received: l.parsedType
}), K;
}
const { status: r, ctx: s } = this._processInputParams(e), { shape: i, keys: o } = this._getCached(), a = [];
if (!(this._def.catchall instanceof Rt && this._def.unknownKeys === "strip"))
for (const l in s.data)
o.includes(l) || a.push(l);
const c = [];
for (const l of o) {
const d = i[l], u = s.data[l];
c.push({
key: { status: "valid", value: l },
value: d._parse(new mt(s, u, s.path, l)),
alwaysSet: l in s.data
});
}
if (this._def.catchall instanceof Rt) {
const l = this._def.unknownKeys;
if (l === "passthrough")
for (const d of a)
c.push({
key: { status: "valid", value: d },
value: { status: "valid", value: s.data[d] }
});
else if (l === "strict")
a.length > 0 && (U(s, {
code: O.unrecognized_keys,
keys: a
}), r.dirty());
else if (l !== "strip") throw new Error("Internal ZodObject error: invalid unknownKeys value.");
} else {
const l = this._def.catchall;
for (const d of a) {
const u = s.data[d];
c.push({
key: { status: "valid", value: d },
value: l._parse(
new mt(s, u, s.path, d)
//, ctx.child(key), value, getParsedType(value)
),
alwaysSet: d in s.data
});
}
}
return s.common.async ? Promise.resolve().then(async () => {
const l = [];
for (const d of c) {
const u = await d.key, f = await d.value;
l.push({
key: u,
value: f,
alwaysSet: d.alwaysSet
});
}
return l;
}).then((l) => Be.mergeObjectSync(r, l)) : Be.mergeObjectSync(r, c);
}
get shape() {
return this._def.shape();
}
strict(e) {
return D.errToObj, new le({
...this._def,
unknownKeys: "strict",
...e !== void 0 ? {
errorMap: (t, r) => {
var s, i, o, a;
const c = (o = (i = (s = this._def).errorMap) === null || i === void 0 ? void 0 : i.call(s, t, r).message) !== null && o !== void 0 ? o : r.defaultError;
return t.code === "unrecognized_keys" ? {
message: (a = D.errToObj(e).message) !== null && a !== void 0 ? a : c
} : {
message: c
};
}
} : {}
});
}
strip() {
return new le({
...this._def,
unknownKeys: "strip"
});
}
passthrough() {
return new le({
...this._def,
unknownKeys: "passthrough"
});
}
// const AugmentFactory =
// <Def extends ZodObjectDef>(def: Def) =>
// <Augmentation extends ZodRawShape>(
// augmentation: Augmentation
// ): ZodObject<
// extendShape<ReturnType<Def["shape"]>, Augmentation>,
// Def["unknownKeys"],
// Def["catchall"]
// > => {
// return new ZodObject({
// ...def,
// shape: () => ({
// ...def.shape(),
// ...augmentation,
// }),
// }) as any;
// };
extend(e) {
return new le({
...this._def,
shape: () => ({
...this._def.shape(),
...e
})
});
}
/**
* Prior to zod@1.0.12 there was a bug in the
* inferred type of merged objects. Please
* upgrade if you are experiencing issues.
*/
merge(e) {
return new le({
unknownKeys: e._def.unknownKeys,
catchall: e._def.catchall,
shape: () => ({
...this._def.shape(),
...e._def.shape()
}),
typeName: V.ZodObject
});
}
// merge<
// Incoming extends AnyZodObject,
// Augmentation extends Incoming["shape"],
// NewOutput extends {
// [k in keyof Augmentation | keyof Output]: k extends keyof Augmentation
// ? Augmentation[k]["_output"]
// : k extends keyof Output
// ? Output[k]
// : never;
// },
// NewInput extends {
// [k in keyof Augmentation | keyof Input]: k extends keyof Augmentation
// ? Augmentation[k]["_input"]
// : k extends keyof Input
// ? Input[k]
// : never;
// }
// >(
// merging: Incoming
// ): ZodObject<
// extendShape<T, ReturnType<Incoming["_def"]["shape"]>>,
// Incoming["_def"]["unknownKeys"],
// Incoming["_def"]["catchall"],
// NewOutput,
// NewInput
// > {
// const merged: any = new ZodObject({
// unknownKeys: merging._def.unknownKeys,
// catchall: merging._def.catchall,
// shape: () =>
// objectUtil.mergeShapes(this._def.shape(), merging._def.shape()),
// typeName: ZodFirstPartyTypeKind.ZodObject,
// }) as any;
// return merged;
// }
setKey(e, t) {
return this.augment({ [e]: t });
}
// merge<Incoming extends AnyZodObject>(
// merging: Incoming
// ): //ZodObject<T & Incoming["_shape"], UnknownKeys, Catchall> = (merging) => {
// ZodObject<
// extendShape<T, ReturnType<Incoming["_def"]["shape"]>>,
// Incoming["_def"]["unknownKeys"],
// Incoming["_def"]["catchall"]
// > {
// // const mergedShape = objectUtil.mergeShapes(
// // this._def.shape(),
// // merging._def.shape()
// // );
// const merged: any = new ZodObject({
// unknownKeys: merging._def.unknownKeys,
// catchall: merging._def.catchall,
// shape: () =>
// objectUtil.mergeShapes(this._def.shape(), merging._def.shape()),
// typeName: ZodFirstPartyTypeKind.ZodObject,
// }) as any;
// return merged;
// }
catchall(e) {
return new le({
...this._def,
catchall: e
});
}
pick(e) {
const t = {};
return re.objectKeys(e).forEach((r) => {
e[r] && this.shape[r] && (t[r] = this.shape[r]);
}), new le({
...this._def,
shape: () => t
});
}
omit(e) {
const t = {};
return re.objectKeys(this.shape).forEach((r) => {
e[r] || (t[r] = this.shape[r]);
}), new le({
...this._def,
shape: () => t
});
}
/**
* @deprecated
*/
deepPartial() {
return An(this);
}
partial(e) {
const t = {};
return re.objectKeys(this.shape).forEach((r) => {
const s = this.shape[r];
e && !e[r] ? t[r] = s : t[r] = s.optional();
}), new le({
...this._def,
shape: () => t
});
}
required(e) {
const t = {};
return re.objectKeys(this.shape).forEach((r) => {
if (e && !e[r])
t[r] = this.shape[r];
else {
let i = this.shape[r];
for (; i instanceof yt; )
i = i._def.innerType;
t[r] = i;
}
}), new le({
...this._def,
shape: () => t
});
}
keyof() {
return Hc(re.objectKeys(this.shape));
}
}
le.create = (n, e) => new le({
shape: () => n,
unknownKeys: "strip",
catchall: Rt.create(),
typeName: V.ZodObject,
...J(e)
});
le.strictCreate = (n, e) => new le({
shape: () => n,
unknownKeys: "strict",
catchall: Rt.create(),
typeName: V.ZodObject,
...J(e)
});
le.lazycreate = (n, e) => new le({
shape: n,
unknownKeys: "strip",
catchall: Rt.create(),
typeName: V.ZodObject,
...J(e)
});
class pr extends ee {
_parse(e) {
const { ctx: t } = this._processInputParams(e), r = this._def.options;
function s(i) {
for (const a of i)
if (a.result.status === "valid")
return a.result;
for (const a of i)
if (a.result.status === "dirty")
return t.common.issues.push(...a.ctx.common.issues), a.result;
const o = i.map((a) => new Pe(a.ctx.common.issues));
return U(t, {
code: O.invalid_union,
unionErrors: o
}), K;
}
if (t.common.async)
return Promise.all(r.map(async (i) => {
const o = {
...t,
common: {
...t.common,
issues: []
},
parent: null
};
return {
result: await i._parseAsync({
data: t.data,
path: t.path,
parent: o
}),
ctx: o
};
})).then(s);
{
let i;
const o = [];
for (const c of r) {
const l = {
...t,
common: {
...t.common,
issues: []
},
parent: null
}, d = c._parseSync({
data: t.data,
path: t.path,
parent: l
});
if (d.status === "valid")
return d;
d.status === "dirty" && !i && (i = { result: d, ctx: l }), l.common.issues.length && o.push(l.common.issues);
}
if (i)
return t.common.issues.push(...i.ctx.common.issues), i.result;
const a = o.map((c) => new Pe(c));
return U(t, {
code: O.invalid_union,
unionErrors: a
}), K;
}
}
get options() {
return this._def.options;
}
}
pr.create = (n, e) => new pr({
options: n,
typeName: V.ZodUnion,
...J(e)
});
const kt = (n) => n instanceof mr ? kt(n.schema) : n instanceof it ? kt(n.innerType()) : n instanceof wr ? [n.value] : n instanceof rn ? n.options : n instanceof br ? re.objectValues(n.enum) : n instanceof vr ? kt(n._def.innerType) : n instanceof hr ? [void 0] : n instanceof fr ? [null] : n instanceof yt ? [void 0, ...kt(n.unwrap())] : n instanceof sn ? [null, ...kt(n.unwrap())] : n instanceof eo || n instanceof Er ? kt(n.unwrap()) : n instanceof xr ? kt(n._def.innerType) : [];
class Ss extends ee {
_parse(e) {
const { ctx: t } = this._processInputParams(e);
if (t.parsedType !== H.object)
return U(t, {
code: O.invalid_type,
expected: H.object,
received: t.parsedType
}), K;
const r = this.discriminator, s = t.data[r], i = this.optionsMap.get(s);
return i ? t.common.async ? i._parseAsync({
data: t.data,
path: t.path,
parent: t
}) : i._parseSync({
data: t.data,
path: t.path,
parent: t
}) : (U(t, {
code: O.invalid_union_discriminator,
options: Array.from(this.optionsMap.keys()),
path: [r]
}), K);
}
get discriminator() {
return this._def.discriminator;
}
get options() {
return this._def.options;
}
get optionsMap() {
return this._def.optionsMap;
}
/**
* The constructor of the discriminated union schema. Its behaviour is very similar to that of the normal z.union() constructor.
* However, it only allows a union of objects, all of which need to share a discriminator property. This property must
* have a different value for each object in the union.
* @param discriminator the name of the discriminator property
* @param types an array of object schemas
* @param params
*/
static create(e, t, r) {
const s = /* @__PURE__ */ new Map();
for (const i of t) {
const o = kt(i.shape[e]);
if (!o.length)
throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);
for (const a of o) {
if (s.has(a))
throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(a)}`);
s.set(a, i);
}
}
return new Ss({
typeName: V.ZodDiscriminatedUnion,
discriminator: e,
options: t,
optionsMap: s,
...J(r)
});
}
}
function wi(n, e) {
const t = Yt(n), r = Yt(e);
if (n === e)
return { valid: !0, data: n };
if (t === H.object && r === H.object) {
const s = re.objectKeys(e), i = re.objectKeys(n).filter((a) => s.indexOf(a) !== -1), o = { ...n, ...e };
for (const a of i) {
const c = wi(n[a], e[a]);
if (!c.valid)
return { valid: !1 };
o[a] = c.data;
}
return { valid: !0, data: o };
} else if (t === H.array && r === H.array) {
if (n.length !== e.length)
return { valid: !1 };
const s = [];
for (let i = 0; i < n.length; i++) {
const o = n[i], a = e[i], c = wi(o, a);
if (!c.valid)
return { valid: !1 };
s.push(c.data);
}
return { valid: !0, data: s };
} else return t === H.date && r === H.date && +n == +e ? { valid: !0, data: n } : { valid: !1 };
}
class gr extends ee {
_parse(e) {
const { status: t, ctx: r } = this._processInputParams(e), s = (i, o) => {
if (yi(i) || yi(o))
return K;
const a = wi(i.value, o.value);
return a.valid ? ((mi(i) || mi(o)) && t.dirty(), { status: t.value, value: a.data }) : (U(r, {
code: O.invalid_intersection_types
}), K);
};
return r.common.async ? Promise.all([
this._def.left._parseAsync({
data: r.data,
path: r.path,
parent: r
}),
this._def.right._parseAsync({
data: r.data,
path: r.path,
parent: r
})
]).then(([i, o]) => s(i, o)) : s(this._def.left._parseSync({
data: r.data,
path: r.path,
parent: r
}), this._def.right._parseSync({
data: r.data,
path: r.path,
parent: r
}));
}
}
gr.create = (n, e, t) => new gr({
left: n,
right: e,
typeName: V.ZodIntersection,
...J(t)
});
class wt extends ee {
_parse(e) {
const { status: t, ctx: r } = this._processInputParams(e);
if (r.parsedType !== H.array)
return U(r, {
code: O.invalid_type,
expected: H.array,
received: r.parsedType
}), K;
if (r.data.length < this._def.items.length)
return U(r, {
code: O.too_small,
minimum: this._def.items.length,
inclusive: !0,
exact: !1,
type: "array"
}), K;
!this._def.rest && r.data.length > this._def.items.length && (U(r, {
code: O.too_big,
maximum: this._def.items.length,
inclusive: !0,
exact: !1,
type: "array"
}), t.dirty());
const i = [...r.data].map((o, a) => {
const c = this._def.items[a] || this._def.rest;
return c ? c._parse(new mt(r, o, r.path, a)) : null;
}).filter((o) => !!o);
return r.common.async ? Promise.all(i).then((o) => Be.mergeArray(t, o)) : Be.mergeArray(t, i);
}
get items() {
return this._def.items;
}
rest(e) {
return new wt({
...this._def,
rest: e
});
}
}
wt.create = (n, e) => {
if (!Array.isArray(n))
throw new Error("You must pass an array of schemas to z.tuple([ ... ])");
return new wt({
items: n,
typeName: V.ZodTuple,
rest: null,
...J(e)
});
};
class yr extends ee {
get keySchema() {
return this._def.keyType;
}
get valueSchema() {
return this._def.valueType;
}
_parse(e) {
const { status: t, ctx: r } = this._processInputParams(e);
if (r.parsedType !== H.object)
return U(r, {
code: O.invalid_type,
expected: H.object,
received: r.parsedType
}), K;
const s = [], i = this._def.keyType, o = this._def.valueType;
for (const a in r.data)
s.push({
key: i._parse(new mt(r, a, r.path, a)),
value: o._parse(new mt(r, r.data[a], r.path, a)),
alwaysSet: a in r.data
});
return r.common.async ? Be.mergeObjectAsync(t, s) : Be.mergeObjectSync(t, s);
}
get element() {
return this._def.valueType;
}
static create(e, t, r) {
return t instanceof ee ? new yr({
keyType: e,
valueType: t,
typeName: V.ZodRecord,
...J(r)
}) : new yr({
keyType: nt.create(),
valueType: e,
typeName: V.ZodRecord,
...J(t)
});
}
}
class os extends ee {
get keySchema() {
return this._def.keyType;
}
get valueSchema() {
return this._def.valueType;
}
_parse(e) {
const { status: t, ctx: r } = this._processInputParams(e);
if (r.parsedType !== H.map)
return U(r, {
code: O.invalid_type,
expected: H.map,
received: r.parsedType
}), K;
const s = this._def.keyType, i = this._def.valueType, o = [...r.data.entries()].map(([a, c], l) => ({
key: s._parse(new mt(r, a, r.path, [l, "key"])),
value: i._parse(new mt(r, c, r.path, [l, "value"]))
}));
if (r.common.async) {
const a = /* @__PURE__ */ new Map();
return Promise.resolve().then(async () => {
for (const c of o) {
const l = await c.key, d = await c.value;
if (l.status === "aborted" || d.status === "aborted")
return K;
(l.status === "dirty" || d.status === "dirty") && t.dirty(), a.set(l.value, d.value);
}
return { status: t.value, value: a };
});
} else {
const a = /* @__PURE__ */ new Map();
for (const c of o) {
const l = c.key, d = c.value;
if (l.status === "aborted" || d.status === "aborted")
return K;
(l.status === "dirty" || d.status === "dirty") && t.dirty(), a.set(l.value, d.value);
}
return { status: t.value, value: a };
}
}
}
os.create = (n, e, t) => new os({
valueType: e,
keyType: n,
typeName: V.ZodMap,
...J(t)
});
class xn extends ee {
_parse(e) {
const { status: t, ctx: r } = this._processInputParams(e);
if (r.parsedType !== H.set)
return U(r, {
code: O.invalid_type,
expected: H.set,
received: r.parsedType
}), K;
const s = this._def;
s.minSize !== null && r.data.size < s.minSize.value && (U(r, {
code: O.too_small,
minimum: s.minSize.value,
type: "set",
inclusive: !0,
exact: !1,
message: s.minSize.message
}), t.dirty()), s.maxSize !== null && r.data.size > s.maxSize.value && (U(r, {
code: O.too_big,
maximum: s.maxSize.value,
type: "set",
inclusive: !0,
exact: !1,
message: s.maxSize.message
}), t.dirty());
const i = this._def.valueType;
function o(c) {
const l = /* @__PURE__ */ new Set();
for (const d of c) {
if (d.status === "aborted")
return K;
d.status === "dirty" && t.dirty(), l.add(d.value);
}
return { status: t.value, value: l };
}
const a = [...r.data.values()].map((c, l) => i._parse(new mt(r, c, r.path, l)));
return r.common.async ? Promise.all(a).then((c) => o(c)) : o(a);
}
min(e, t) {
return new xn({
...this._def,
minSize: { value: e, message: D.toString(t) }
});
}
max(e, t) {
return new xn({
...this._def,
maxSize: { value: e, message: D.toString(t) }
});
}
size(e, t) {
return this.min(e, t).max(e, t);
}
nonempty(e) {
return this.min(1, e);
}
}
xn.create = (n, e) => new xn({
valueType: n,
minSize: null,
maxSize: null,
typeName: V.ZodSet,
...J(e)
});
class In extends ee {
constructor() {
super(...arguments), this.validate = this.implement;
}
_parse(e) {
const { ctx: t } = this._processInputParams(e);
if (t.parsedType !== H.function)
return U(t, {
code: O.invalid_type,
expected: H.function,
received: t.parsedType
}), K;
function r(a, c) {
return ns({
data: a,
path: t.path,
errorMaps: [
t.common.contextualErrorMap,
t.schemaErrorMap,
ts(),
zn
].filter((l) => !!l),
issueData: {
code: O.invalid_arguments,
argumentsError: c
}
});
}
function s(a, c) {
return ns({
data: a,
path: t.path,
errorMaps: [
t.common.contextualErrorMap,
t.schemaErrorMap,
ts(),
zn
].filter((l) => !!l),
issueData: {
code: O.invalid_return_type,
returnTypeError: c
}
});
}
const i = { errorMap: t.common.contextualErrorMap }, o = t.data;
if (this._def.returns instanceof qn) {
const a = this;
return $e(async function(...c) {
const l = new Pe([]), d = await a._def.args.parseAsync(c, i).catch((m) => {
throw l.addIssue(r(c, m)), l;
}), u = await Reflect.apply(o, this, d);
return await a._def.returns._def.type.parseAsync(u, i).catch((m) => {
throw l.addIssue(s(u, m)), l;
});
});
} else {
const a = this;
return $e(function(...c) {
const l = a._def.args.safeParse(c, i);
if (!l.success)
throw new Pe([r(c, l.error)]);
const d = Reflect.apply(o, this, l.data), u = a._def.returns.safeParse(d, i);
if (!u.success)
throw new Pe([s(d, u.error)]);
return u.data;
});
}
}
parameters() {
return this._def.args;
}
returnType() {
return this._def.returns;
}
args(...e) {
return new In({
...this._def,
args: wt.create(e).rest(gn.create())
});
}
returns(e) {
return new In({
...this._def,
returns: e
});
}
implement(e) {
return this.parse(e);
}
strictImplement(e) {
return this.parse(e);
}
static create(e, t, r) {
return new In({
args: e || wt.create([]).rest(gn.create()),
returns: t || gn.create(),
typeName: V.ZodFunction,
...J(r)
});
}
}
class mr extends ee {
get schema() {
return this._def.getter();
}
_parse(e) {
const { ctx: t } = this._processInputParams(e);
return this._def.getter()._parse({ data: t.data, path: t.path, parent: t });
}
}
mr.create = (n, e) => new mr({
getter: n,
typeName: V.ZodLazy,
...J(e)
});
class wr extends ee {
_parse(e) {
if (e.data !== this._def.value) {
const t = this._getOrReturnCtx(e);
return U(t, {
received: t.data,
code: O.invalid_literal,
expected: this._def.value
}), K;
}
return { status: "valid", value: e.data };
}
get value() {
return this._def.value;
}
}
wr.create = (n, e) => new wr({
value: n,
typeName: V.ZodLiteral,
...J(e)
});
function Hc(n, e) {
return new rn({
values: n,
typeName: V.ZodEnum,
...J(e)
});
}
class rn extends ee {
constructor() {
super(...arguments), nr.set(this, void 0);
}
_parse(e) {
if (typeof e.data != "string") {
const t = this._getOrReturnCtx(e), r = this._def.values;
return U(t, {
expected: re.joinValues(r),
received: t.parsedType,
code: O.invalid_type
}), K;
}
if (rs(this, nr) || Rc(this, nr, new Set(this._def.values)), !rs(this, nr).has(e.data)) {
const t = this._getOrReturnCtx(e), r = this._def.values;
return U(t, {
received: t.data,
code: O.invalid_enum_value,
options: r
}), K;
}
return $e(e.data);
}
get options() {
return this._def.values;
}
get enum() {
const e = {};
for (const t of this._def.values)
e[t] = t;
return e;
}
get Values() {
const e = {};
for (const t of this._def.values)
e[t] = t;
return e;
}
get Enum() {
const e = {};
for (const t of this._def.values)
e[t] = t;
return e;
}
extract(e, t = this._def) {
return rn.create(e, {
...this._def,
...t
});
}
exclude(e, t = this._def) {
return rn.create(this.options.filter((r) => !e.includes(r)), {
...this._def,
...t
});
}
}
nr = /* @__PURE__ */ new WeakMap();
rn.create = Hc;
class br extends ee {
constructor() {
super(...arguments), rr.set(this, void 0);
}
_parse(e) {
const t = re.getValidEnumValues(this._def.values), r = this._getOrReturnCtx(e);
if (r.parsedType !== H.string && r.parsedType !== H.number) {
const s = re.objectValues(t);
return U(r, {
expected: re.joinValues(s),
received: r.parsedType,
code: O.invalid_type
}), K;
}
if (rs(this, rr) || Rc(this, rr, new Set(re.getValidEnumValues(this._def.values))), !rs(this, rr).has(e.data)) {
const s = re.objectValues(t);
return U(r, {
received: r.data,
code: O.invalid_enum_value,
options: s
}), K;
}
return $e(e.data);
}
get enum() {
return this._def.values;
}
}
rr = /* @__PURE__ */ new WeakMap();
br.create = (n, e) => new br({
values: n,
typeName: V.ZodNativeEnum,
...J(e)
});
class qn extends ee {
unwrap() {
return this._def.type;
}
_parse(e) {
const { ctx: t } = this._processInputParams(e);
if (t.parsedType !== H.promise && t.common.async === !1)
return U(t, {
code: O.invalid_type,
expected: H.promise,
received: t.parsedType
}), K;
const r = t.parsedType === H.promise ? t.data : Promise.resolve(t.data);
return $e(r.then((s) => this._def.type.parseAsync(s, {
path: t.path,
errorMap: t.common.contextualErrorMap
})));
}
}
qn.create = (n, e) => new qn({
type: n,
typeName: V.ZodPromise,
...J(e)
});
class it extends ee {
innerType() {
return this._def.schema;
}
sourceType() {
return this._def.schema._def.typeName === V.ZodEffects ? this._def.schema.sourceType() : this._def.schema;
}
_parse(e) {
const { status: t, ctx: r } = this._processInputParams(e), s = this._def.effect || null, i = {
addIssue: (o) => {
U(r, o), o.fatal ? t.abort() : t.dirty();
},
get path() {
return r.path;
}
};
if (i.addIssue = i.addIssue.bind(i), s.type === "preprocess") {
const o = s.transform(r.data, i);
if (r.common.async)
return Promise.resolve(o).then(async (a) => {
if (t.value === "aborted")
return K;
const c = await this._def.schema._parseAsync({
data: a,
path: r.path,
parent: r
});
return c.status === "aborted" ? K : c.status === "dirty" || t.value === "dirty" ? Bn(c.value) : c;
});
{
if (t.value === "aborted")
return K;
const a = this._def.schema._parseSync({
data: o,
path: r.path,
parent: r
});
return a.status === "aborted" ? K : a.status === "dirty" || t.value === "dirty" ? Bn(a.value) : a;
}
}
if (s.type === "refinement") {
const o = (a) => {
const c = s.refinement(a, i);
if (r.common.async)
return Promise.resolve(c);
if (c instanceof Promise)
throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");
return a;
};
if (r.common.async === !1) {
const a = this._def.schema._parseSync({
data: r.data,
path: r.path,
parent: r
});
return a.status === "aborted" ? K : (a.status === "dirty" && t.dirty(), o(a.value), { status: t.value, value: a.value });
} else
return this._def.schema._parseAsync({ data: r.data, path: r.path, parent: r }).then((a) => a.status === "aborted" ? K : (a.status === "dirty" && t.dirty(), o(a.value).then(() => ({ status: t.value, value: a.value }))));
}
if (s.type === "transform")
if (r.common.async === !1) {
const o = this._def.schema._parseSync({
data: r.data,
path: r.path,
parent: r
});
if (!lr(o))
return o;
const a = s.transform(o.value, i);
if (a instanceof Promise)
throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");
return { status: t.value, value: a };
} else
return this._def.schema._parseAsync({ data: r.data, path: r.path, parent: r }).then((o) => lr(o) ? Promise.resolve(s.transform(o.value, i)).then((a) => ({ status: t.value, value: a })) : o);
re.assertNever(s);
}
}
it.create = (n, e, t) => new it({
schema: n,
typeName: V.ZodEffects,
effect: e,
...J(t)
});
it.createWithPreprocess = (n, e, t) => new it({
schema: e,
effect: { type: "preprocess", transform: n },
typeName: V.ZodEffects,
...J(t)
});
class yt extends ee {
_parse(e) {
return this._getType(e) === H.undefined ? $e(void 0) : this._def.innerType._parse(e);
}
unwrap() {
return this._def.innerType;
}
}
yt.create = (n, e) => new yt({
innerType: n,
typeName: V.ZodOptional,
...J(e)
});
class sn extends ee {
_parse(e) {
return this._getType(e) === H.null ? $e(null) : this._def.innerType._parse(e);
}
unwrap() {
return this._def.innerType;
}
}
sn.create = (n, e) => new sn({
innerType: n,
typeName: V.ZodNullable,
...J(e)
});
class vr extends ee {
_parse(e) {
const { ctx: t } = this._processInputParams(e);
let r = t.data;
return t.parsedType === H.undefined && (r = this._def.defaultValue()), this._def.innerType._parse({
data: r,
path: t.path,
parent: t
});
}
removeDefault() {
return this._def.innerType;
}
}
vr.create = (n, e) => new vr({
innerType: n,
typeName: V.ZodDefault,
defaultValue: typeof e.default == "function" ? e.default : () => e.default,
...J(e)
});
class xr extends ee {
_parse(e) {
const { ctx: t } = this._processInputParams(e), r = {
...t,
common: {
...t.common,
issues: []
}
}, s = this._def.innerType._parse({
data: r.data,
path: r.path,
parent: {
...r
}
});
return ur(s) ? s.then((i) => ({
status: "valid",
value: i.status === "valid" ? i.value : this._def.catchValue({
get error() {
return new Pe(r.common.issues);
},
input: r.data
})
})) : {
status: "valid",
value: s.status === "valid" ? s.value : this._def.catchValue({
get error() {
return new Pe(r.common.issues);
},
input: r.data
})
};
}
removeCatch() {
return this._def.innerType;
}
}
xr.create = (n, e) => new xr({
innerType: n,
typeName: V.ZodCatch,
catchValue: typeof e.catch == "function" ? e.catch : () => e.catch,
...J(e)
});
class as extends ee {
_parse(e) {
if (this._getType(e) !== H.nan) {
const r = this._getOrReturnCtx(e);
return U(r, {
code: O.invalid_type,
expected: H.nan,
received: r.parsedType
}), K;
}
return { status: "valid", value: e.data };
}
}
as.create = (n) => new as({
typeName: V.ZodNaN,
...J(n)
});
const rp = Symbol("zod_brand");
class eo extends ee {
_parse(e) {
const { ctx: t } = this._processInputParams(e), r = t.data;
return this._def.type._parse({
data: r,
path: t.path,
parent: t
});
}
unwrap() {
return this._def.type;
}
}
class Rr extends ee {
_parse(e) {
const { status: t, ctx: r } = this._processInputParams(e);
if (r.common.async)
return (async () => {
const i = await this._def.in._parseAsync({
data: r.data,
path: r.path,
parent: r
});
return i.status === "aborted" ? K : i.status === "dirty" ? (t.dirty(), Bn(i.value)) : this._def.out._parseAsync({
data: i.value,
path: r.path,
parent: r
});
})();
{
const s = this._def.in._parseSync({
data: r.data,
path: r.path,
parent: r
});
return s.status === "aborted" ? K : s.status === "dirty" ? (t.dirty(), {
status: "dirty",
value: s.value
}) : this._def.out._parseSync({
data: s.value,
path: r.path,
parent: r
});
}
}
static create(e, t) {
return new Rr({
in: e,
out: t,
typeName: V.ZodPipeline
});
}
}
class Er extends ee {
_parse(e) {
const t = this._def.innerType._parse(e), r = (s) => (lr(s) && (s.value = Object.freeze(s.value)), s);
return ur(t) ? t.then((s) => r(s)) : r(t);
}
unwrap() {
return this._def.innerType;
}
}
Er.create = (n, e) => new Er({
innerType: n,
typeName: V.ZodReadonly,
...J(e)
});
function Mc(n, e = {}, t) {
return n ? Dn.create().superRefine((r, s) => {
var i, o;
if (!n(r)) {
const a = typeof e == "function" ? e(r) : typeof e == "string" ? { message: e } : e, c = (o = (i = a.fatal) !== null && i !== void 0 ? i : t) !== null && o !== void 0 ? o : !0, l = typeof a == "string" ? { message: a } : a;
s.addIssue({ code: "custom", ...l, fatal: c });
}
}) : Dn.create();
}
const sp = {
object: le.lazycreate
};
var V;
(function(n) {
n.ZodString = "ZodString", n.ZodNumber = "ZodNumber", n.ZodNaN = "ZodNaN", n.ZodBigInt = "ZodBigInt", n.ZodBoolean = "ZodBoolean", n.ZodDate = "ZodDate", n.ZodSymbol = "ZodSymbol", n.ZodUndefined = "ZodUndefined", n.ZodNull = "ZodNull", n.ZodAny = "ZodAny", n.ZodUnknown = "ZodUnknown", n.ZodNever = "ZodNever", n.ZodVoid = "ZodVoid", n.ZodArray = "ZodArray", n.ZodObject = "ZodObject", n.ZodUnion = "ZodUnion", n.ZodDiscriminatedUnion = "ZodDiscriminatedUnion", n.ZodIntersection = "ZodIntersection", n.ZodTuple = "ZodTuple", n.ZodRecord = "ZodRecord", n.ZodMap = "ZodMap", n.ZodSet = "ZodSet", n.ZodFunction = "ZodFunction", n.ZodLazy = "ZodLazy", n.ZodLiteral = "ZodLiteral", n.ZodEnum = "ZodEnum", n.ZodEffects = "ZodEffects", n.ZodNativeEnum = "ZodNativeEnum", n.ZodOptional = "ZodOptional", n.ZodNullable = "ZodNullable", n.ZodDefault = "ZodDefault", n.ZodCatch = "ZodCatch", n.ZodPromise = "ZodPromise", n.ZodBranded = "ZodBranded", n.ZodPipeline = "ZodPipeline", n.ZodReadonly = "ZodReadonly";
})(V || (V = {}));
const ip = (n, e = {
message: `Input not instance of ${n.name}`
}) => Mc((t) => t instanceof n, e), jc = nt.create, Pc = tn.create, op = as.create, ap = nn.create, Zc = dr.create, cp = vn.create, lp = ss.create, up = hr.create, dp = fr.create, hp = Dn.create, fp = gn.create, pp = Rt.create, gp = is.create, yp = rt.create, mp = le.create, wp = le.strictCreate, bp = pr.create, vp = Ss.create, xp = gr.create, Ep = wt.create, _p = yr.create, Sp = os.create, kp = xn.create, Ap = In.create, Tp = mr.create, Bp = wr.create, Op = rn.create, Ip = br.create, Cp = qn.create, Lo = it.create, $p = yt.create, Rp = sn.create, Np = it.createWithPreprocess, Lp = Rr.create, Up = () => jc().optional(), Hp = () => Pc().optional(), Mp = () => Zc().optional(), jp = {
string: (n) => nt.create({ ...n, coerce: !0 }),
number: (n) => tn.create({ ...n, coerce: !0 }),
boolean: (n) => dr.create({
...n,
coerce: !0
}),
bigint: (n) => nn.create({ ...n, coerce: !0 }),
date: (n) => vn.create({ ...n, coerce: !0 })
}, Pp = K;
var $ = /* @__PURE__ */ Object.freeze({
__proto__: null,
defaultErrorMap: zn,
setErrorMap: Pf,
getErrorMap: ts,
makeIssue: ns,
EMPTY_PATH: Zf,
addIssueToContext: U,
ParseStatus: Be,
INVALID: K,
DIRTY: Bn,
OK: $e,
isAborted: yi,
isDirty: mi,
isValid: lr,
isAsync: ur,
get util() {
return re;
},
get objectUtil() {
return gi;
},
ZodParsedType: H,
getParsedType: Yt,
ZodType: ee,
datetimeRegex: Uc,
ZodString: nt,
ZodNumber: tn,
ZodBigInt: nn,
ZodBoolean: dr,
ZodDate: vn,
ZodSymbol: ss,
ZodUndefined: hr,
ZodNull: fr,
ZodAny: Dn,
ZodUnknown: gn,
ZodNever: Rt,
ZodVoid: is,
ZodArray: rt,
ZodObject: le,
ZodUnion: pr,
ZodDiscriminatedUnion: Ss,
ZodIntersection: gr,
ZodTuple: wt,
ZodRecord: yr,
ZodMap: os,
ZodSet: xn,
ZodFunction: In,
ZodLazy: mr,
ZodLiteral: wr,
ZodEnum: rn,
ZodNativeEnum: br,
ZodPromise: qn,
ZodEffects: it,
ZodTransformer: it,
ZodOptional: yt,
ZodNullable: sn,
ZodDefault: vr,
ZodCatch: xr,
ZodNaN: as,
BRAND: rp,
ZodBranded: eo,
ZodPipeline: Rr,
ZodReadonly: Er,
custom: Mc,
Schema: ee,
ZodSchema: ee,
late: sp,
get ZodFirstPartyTypeKind() {
return V;
},
coerce: jp,
any: hp,
array: yp,
bigint: ap,
boolean: Zc,
date: cp,
discriminatedUnion: vp,
effect: Lo,
enum: Op,
function: Ap,
instanceof: ip,
intersection: xp,
lazy: Tp,
literal: Bp,
map: Sp,
nan: op,
nativeEnum: Ip,
never: pp,
null: dp,
nullable: Rp,
number: Pc,
object: mp,
oboolean: Mp,
onumber: Hp,
optional: $p,
ostring: Up,
pipeline: Lp,
preprocess: Np,
promise: Cp,
record: _p,
set: kp,
strictObject: wp,
string: jc,
symbol: lp,
transformer: Lo,
tuple: Ep,
undefined: up,
union: bp,
unknown: fp,
void: gp,
NEVER: Pp,
ZodIssueCode: O,
quotelessJson: jf,
ZodError: Pe
});
class ne {
/** Schema to validate Nostr hex IDs such as event IDs and pubkeys. */
static id() {
return $.string().regex(/^[0-9a-f]{64}$/);
}
/** Nostr event schema. */
static event() {
return $.object({
id: ne.id(),
kind: $.number().int().nonnegative(),
pubkey: ne.id(),
tags: $.string().array().array(),
content: $.string(),
created_at: $.number().int().nonnegative(),
sig: $.string()
});
}
/** Nostr filter schema. */
static filter() {
return $.object({
kinds: $.number().int().nonnegative().array().optional(),
ids: ne.id().array().optional(),
authors: ne.id().array().optional(),
since: $.number().int().nonnegative().optional(),
until: $.number().int().nonnegative().optional(),
limit: $.number().int().nonnegative().optional(),
search: $.string().optional()
}).passthrough().transform((e) => {
const t = [
"kinds",
"ids",
"authors",
"since",
"until",
"limit",
"search"
];
return Object.entries(e).reduce((r, [s, i]) => ((t.includes(s) || s.startsWith("#")) && (r[s] = i), r), {});
});
}
/**
* Bech32 string.
* @see https://github.com/bitcoin/bips/blob/master/bip-0173.mediawiki#bech32
*/
static bech32(e) {
return $.string().regex(/^[\x21-\x7E]{1,83}1[023456789acdefghjklmnpqrstuvwxyz]{6,}$/).refine((t) => e ? t.startsWith(`${e}1`) : !0);
}
/** NIP-01 `EVENT` message from client to relay. */
static clientEVENT() {
return $.tuple([
$.literal("EVENT"),
ne.event()
]);
}
/** NIP-01 `REQ` message from client to relay. */
static clientREQ() {
return $.tuple([
$.literal("REQ"),
$.string()
]).rest(ne.filter());
}
/** NIP-45 `COUNT` message from client to relay. */
static clientCOUNT() {
return $.tuple([
$.literal("COUNT"),
$.string()
]).rest(ne.filter());
}
/** NIP-01 `CLOSE` message from client to relay. */
static clientCLOSE() {
return $.tuple([
$.literal("CLOSE"),
$.string()
]);
}
/** NIP-42 `AUTH` message from client to relay. */
static clientAUTH() {
return $.tuple([
$.literal("AUTH"),
ne.event()
]);
}
/** NIP-01 message from client to relay. */
static clientMsg() {
return $.union([
ne.clientEVENT(),
ne.clientREQ(),
ne.clientCOUNT(),
ne.clientCLOSE(),
ne.clientAUTH()
]);
}
/** NIP-01 `EVENT` message from relay to client. */
static relayEVENT() {
return $.tuple([
$.literal("EVENT"),
$.string(),
ne.event()
]);
}
/** NIP-01 `OK` message from relay to client. */
static relayOK() {
return $.tuple([
$.literal("OK"),
ne.id(),
$.boolean(),
$.string()
]);
}
/** NIP-01 `EOSE` message from relay to client. */
static relayEOSE() {
return $.tuple([
$.literal("EOSE"),
$.string()
]);
}
/** NIP-01 `NOTICE` message from relay to client. */
static relayNOTICE() {
return $.tuple([
$.literal("NOTICE"),
$.string()
]);
}
/** NIP-01 `CLOSED` message from relay to client. */
static relayCLOSED() {
return $.tuple([
$.literal("CLOSED"),
$.string(),
$.string()
]);
}
/** NIP-42 `AUTH` message from relay to client. */
static relayAUTH() {
return $.tuple([
$.literal("AUTH"),
$.string()
]);
}
/** NIP-45 `COUNT` message from relay to client. */
static relayCOUNT() {
return $.tuple([
$.literal("COUNT"),
$.string(),
$.object({
count: $.number().int().nonnegative(),
approximate: $.boolean().optional()
})
]);
}
/** NIP-01 message from relay to client. */
static relayMsg() {
return $.union([
ne.relayEVENT(),
ne.relayOK(),
ne.relayEOSE(),
ne.relayNOTICE(),
ne.relayCLOSED(),
ne.relayAUTH(),
ne.relayCOUNT()
]);
}
/** Kind 0 content schema. */
static metadata() {
return $.object({
about: $.string().optional().catch(void 0),
banner: $.string().url().optional().catch(void 0),
bot: $.boolean().optional().catch(void 0),
display_name: $.string().optional().catch(void 0),
lud06: ne.bech32("lnurl").optional().catch(void 0),
lud16: $.string().email().optional().catch(void 0),
name: $.string().optional().catch(void 0),
nip05: $.string().email().optional().catch(void 0),
picture: $.string().url().optional().catch(void 0),
website: $.string().url().optional().catch(void 0)
}).passthrough();
}
/** NIP-46 request content schema. */
static connectRequest() {
return $.object({
id: $.string(),
method: $.string(),
params: $.string().array()
});
}
/** NIP-46 response content schema. */
static connectResponse() {
return $.object({
id: $.string(),
result: $.string(),
error: $.string().optional()
});
}
/**
* Helper schema to parse a JSON string. It should then be piped into another schema. For example:
*
* ```ts
* const event = NSchema.json().pipe(NSchema.event()).parse(data);
* ```
*/
static json() {
return $.string().transform((e, t) => {
try {
return JSON.parse(e);
} catch {
return t.addIssue({
code: $.ZodIssueCode.custom,
message: "Invalid JSON"
}), $.NEVER;
}
});
}
}
class Zp {
constructor({ relay: e, pubkey: t, signer: r, timeout: s, encryption: i = "nip04" }) {
B(this, "relay");
B(this, "pubkey");
B(this, "signer");
B(this, "timeout");
B(this, "encryption");
B(this, "nip04", {
encrypt: async (e, t) => this.cmd("nip04_encrypt", [
e,
t
]),
decrypt: async (e, t) => this.cmd("nip04_decrypt", [
e,
t
])
});
B(this, "nip44", {
encrypt: async (e, t) => this.cmd("nip44_encrypt", [
e,
t
]),
decrypt: async (e, t) => this.cmd("nip44_decrypt", [
e,
t
])
});
this.relay = e, this.pubkey = t, this.signer = r, this.timeout = s, this.encryption = i;
}
async getPublicKey() {
return this.cmd("get_public_key", []);
}
async signEvent(e) {
const t = await this.cmd("sign_event", [
JSON.stringify(e)
]);
return ne.json().pipe(ne.event()).parse(t);
}
async getRelays() {
const e = await this.cmd("get_relays", []);
return ne.json().pipe($.record($.string(), $.object({
read: $.boolean(),
write: $.boolean()
}))).parse(e);
}
/** Send a `connect` command to the relay. It should respond with `ack`. */
async connect(e) {
const t = [
this.pubkey
];
return e && t.push(e), this.cmd("connect", t);
}
/** Send a `ping` command to the signer. It should respond with `pong`. */
async ping() {
return this.cmd("ping", []);
}
/** High-level RPC method. Returns the string result, or throws on error. */
async cmd(e, t) {
const r = typeof this.timeout == "number" ? AbortSignal.timeout(this.timeout) : void 0, { result: s, error: i } = await this.send({
id: crypto.randomUUID(),
method: e,
params: t
}, {
signal: r
});
if (i)
throw new Error(i);
return s;
}
/** Low-level send method. Deals directly with connect request/response. */
async send(e, t = {}) {
const { signal: r } = t, s = await this.signer.signEvent({
kind: 24133,
content: await this.encrypt(this.pubkey, JSON.stringify(e)),
created_at: Math.floor(Date.now() / 1e3),
tags: [
[
"p",
this.pubkey
]
]
}), i = await this.signer.getPublicKey(), o = this.relay.req([
{
kinds: [
24133
],
authors: [
this.pubkey
],
"#p": [
i
]
}
], {
signal: r
});
await this.relay.event(s, {
signal: r
});
for await (const a of o) {
if (a[0] === "CLOSED") throw new Error("Subscription closed");
if (a[0] === "EVENT") {
const c = a[2], l = await this.decrypt(this.pubkey, c.content), d = ne.json().pipe(ne.connectResponse()).parse(l);
if (d.id === e.id)
return d;
}
}
throw new Error("Unreachable");
}
/** Local encrypt depending on settings. */
async encrypt(e, t) {
switch (this.encryption) {
case "nip04":
return this.signer.nip04.encrypt(e, t);
case "nip44":
return this.signer.nip44.encrypt(e, t);
}
}
/** Local decrypt depending on settings. */
async decrypt(e, t) {
switch (this.encryption) {
case "nip04":
return this.signer.nip04.decrypt(e, t);
case "nip44":
return this.signer.nip44.decrypt(e, t);
}
}
}
function or(n) {
if (!Number.isSafeInteger(n) || n < 0)
throw new Error(`positive integer expected, not ${n}`);
}
function zp(n) {
return n instanceof Uint8Array || n != null && typeof n == "object" && n.constructor.name === "Uint8Array";
}
function ft(n, ...e) {
if (!zp(n))
throw new Error("Uint8Array expected");
if (e.length > 0 && !e.includes(n.length))
throw new Error(`Uint8Array expected of length ${e}, not of length=${n.length}`);
}
function zc(n) {
if (typeof n != "function" || typeof n.create != "function")
throw new Error("Hash should be wrapped by utils.wrapConstructor");
or(n.outputLen), or(n.blockLen);
}
function cs(n, e = !0) {
if (n.destroyed)
throw new Error("Hash instance has been destroyed");
if (e && n.finished)
throw new Error("Hash#digest() has already been called");
}
function Dp(n, e) {
ft(n);
const t = e.outputLen;
if (n.length < t)
throw new Error(`digestInto() expects output buffer of length at least ${t}`);
}
const kn = typeof globalThis == "object" && "crypto" in globalThis ? globalThis.crypto : void 0;
/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */
const yn = (n) => new DataView(n.buffer, n.byteOffset, n.byteLength), ct = (n, e) => n << 32 - e | n >>> e, jr = (n, e) => n << e | n >>> 32 - e >>> 0;
new Uint8Array(new Uint32Array([287454020]).buffer)[0];
const qp = /* @__PURE__ */ Array.from({ length: 256 }, (n, e) => e.toString(16).padStart(2, "0"));
function Vp(n) {
ft(n);
let e = "";
for (let t = 0; t < n.length; t++)
e += qp[n[t]];
return e;
}
const Et = { _0: 48, _9: 57, _A: 65, _F: 70, _a: 97, _f: 102 };
function Uo(n) {
if (n >= Et._0 && n <= Et._9)
return n - Et._0;
if (n >= Et._A && n <= Et._F)
return n - (Et._A - 10);
if (n >= Et._a && n <= Et._f)
return n - (Et._a - 10);
}
function Kp(n) {
if (typeof n != "string")
throw new Error("hex string expected, got " + typeof n);
const e = n.length, t = e / 2;
if (e % 2)
throw new Error("padded hex string expected, got unpadded hex of length " + e);
const r = new Uint8Array(t);
for (let s = 0, i = 0; s < t; s++, i += 2) {
const o = Uo(n.charCodeAt(i)), a = Uo(n.charCodeAt(i + 1));
if (o === void 0 || a === void 0) {
const c = n[i] + n[i + 1];
throw new Error('hex string expected, got non-hex character "' + c + '" at index ' + i);
}
r[s] = o * 16 + a;
}
return r;
}
function Dc(n) {
if (typeof n != "string")
throw new Error(`utf8ToBytes expected string, got ${typeof n}`);
return new Uint8Array(new TextEncoder().encode(n));
}
function _r(n) {
return typeof n == "string" && (n = Dc(n)), ft(n), n;
}
function sr(...n) {
let e = 0;
for (let r = 0; r < n.length; r++) {
const s = n[r];
ft(s), e += s.length;
}
const t = new Uint8Array(e);
for (let r = 0, s = 0; r < n.length; r++) {
const i = n[r];
t.set(i, s), s += i.length;
}
return t;
}
class qc {
// Safe version that clones internal state
clone() {
return this._cloneInto();
}
}
const Wp = {}.toString;
function Fp(n, e) {
if (e !== void 0 && Wp.call(e) !== "[object Object]")
throw new Error("Options should be object or undefined");
return Object.assign(n, e);
}
function to(n) {
const e = (r) => n().update(_r(r)).digest(), t = n();
return e.outputLen = t.outputLen, e.blockLen = t.blockLen, e.create = () => n(), e;
}
function Gp(n = 32) {
if (kn && typeof kn.getRandomValues == "function")
return kn.getRandomValues(new Uint8Array(n));
if (kn && typeof kn.randomBytes == "function")
return kn.randomBytes(n);
throw new Error("crypto.getRandomValues must be defined");
}
class Vc extends qc {
constructor(e, t) {
super(), this.finished = !1, this.destroyed = !1, zc(e);
const r = _r(t);
if (this.iHash = e.create(), 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 s = this.blockLen, i = new Uint8Array(s);
i.set(r.length > s ? e.create().update(r).digest() : r);
for (let o = 0; o < i.length; o++)
i[o] ^= 54;
this.iHash.update(i), this.oHash = e.create();
for (let o = 0; o < i.length; o++)
i[o] ^= 106;
this.oHash.update(i), i.fill(0);
}
update(e) {
return cs(this), this.iHash.update(e), this;
}
digestInto(e) {
cs(this), ft(e, this.outputLen), this.finished = !0, this.iHash.digestInto(e), this.oHash.update(e), this.oHash.digestInto(e), this.destroy();
}
digest() {
const e = new Uint8Array(this.oHash.outputLen);
return this.digestInto(e), e;
}
_cloneInto(e) {
e || (e = Object.create(Object.getPrototypeOf(this), {}));
const { oHash: t, iHash: r, finished: s, destroyed: i, blockLen: o, outputLen: a } = this;
return e = e, e.finished = s, e.destroyed = i, e.blockLen = o, e.outputLen = a, e.oHash = t._cloneInto(e.oHash), e.iHash = r._cloneInto(e.iHash), e;
}
destroy() {
this.destroyed = !0, this.oHash.destroy(), this.iHash.destroy();
}
}
const Sr = (n, e, t) => new Vc(n, e).update(t).digest();
Sr.create = (n, e) => new Vc(n, e);
function Yp(n, e, t, r) {
if (typeof n.setBigUint64 == "function")
return n.setBigUint64(e, t, r);
const s = BigInt(32), i = BigInt(4294967295), o = Number(t >> s & i), a = Number(t & i), c = r ? 4 : 0, l = r ? 0 : 4;
n.setUint32(e + c, o, r), n.setUint32(e + l, a, r);
}
const Jp = (n, e, t) => n & e ^ ~n & t, Xp = (n, e, t) => n & e ^ n & t ^ e & t;
class no extends qc {
constructor(e, t, r, s) {
super(), this.blockLen = e, this.outputLen = t, this.padOffset = r, this.isLE = s, this.finished = !1, this.length = 0, this.pos = 0, this.destroyed = !1, this.buffer = new Uint8Array(e), this.view = yn(this.buffer);
}
update(e) {
cs(this);
const { view: t, buffer: r, blockLen: s } = this;
e = _r(e);
const i = e.length;
for (let o = 0; o < i; ) {
const a = Math.min(s - this.pos, i - o);
if (a === s) {
const c = yn(e);
for (; s <= i - o; o += s)
this.process(c, o);
continue;
}
r.set(e.subarray(o, o + a), this.pos), this.pos += a, o += a, this.pos === s && (this.process(t, 0), this.pos = 0);
}
return this.length += e.length, this.roundClean(), this;
}
digestInto(e) {
cs(this), Dp(e, this), this.finished = !0;
const { buffer: t, view: r, blockLen: s, isLE: i } = this;
let { pos: o } = this;
t[o++] = 128, this.buffer.subarray(o).fill(0), this.padOffset > s - o && (this.process(r, 0), o = 0);
for (let u = o; u < s; u++)
t[u] = 0;
Yp(r, s - 8, BigInt(this.length * 8), i), this.process(r, 0);
const a = yn(e), c = this.outputLen;
if (c % 4)
throw new Error("_sha2: outputLen should be aligned to 32bit");
const l = c / 4, d = this.get();
if (l > d.length)
throw new Error("_sha2: outputLen bigger than state");
for (let u = 0; u < l; u++)
a.setUint32(4 * u, d[u], i);
}
digest() {
const { buffer: e, outputLen: t } = this;
this.digestInto(e);
const r = e.slice(0, t);
return this.destroy(), r;
}
_cloneInto(e) {
e || (e = new this.constructor()), e.set(...this.get());
const { blockLen: t, buffer: r, length: s, finished: i, destroyed: o, pos: a } = this;
return e.length = s, e.pos = a, e.finished = i, e.destroyed = o, s % t && e.buffer.set(r), e;
}
}
const Qp = /* @__PURE__ */ new Uint8Array([7, 4, 13, 1, 10, 6, 15, 3, 12, 0, 9, 5, 2, 14, 11, 8]), Kc = /* @__PURE__ */ new Uint8Array(new Array(16).fill(0).map((n, e) => e)), e0 = /* @__PURE__ */ Kc.map((n) => (9 * n + 5) % 16);
let ro = [Kc], so = [e0];
for (let n = 0; n < 4; n++)
for (let e of [ro, so])
e.push(e[n].map((t) => Qp[t]));
const Wc = /* @__PURE__ */ [
[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((n) => new Uint8Array(n)), t0 = /* @__PURE__ */ ro.map((n, e) => n.map((t) => Wc[e][t])), n0 = /* @__PURE__ */ so.map((n, e) => n.map((t) => Wc[e][t])), r0 = /* @__PURE__ */ new Uint32Array([
0,
1518500249,
1859775393,
2400959708,
2840853838
]), s0 = /* @__PURE__ */ new Uint32Array([
1352829926,
1548603684,
1836072691,
2053994217,
0
]);
function Ho(n, e, t, r) {
return n === 0 ? e ^ t ^ r : n === 1 ? e & t | ~e & r : n === 2 ? (e | ~t) ^ r : n === 3 ? e & r | t & ~r : e ^ (t | ~r);
}
const Pr = /* @__PURE__ */ new Uint32Array(16);
class i0 extends no {
constructor() {
super(64, 20, 8, !0), this.h0 = 1732584193, this.h1 = -271733879, this.h2 = -1732584194, this.h3 = 271733878, this.h4 = -1009589776;
}
get() {
const { h0: e, h1: t, h2: r, h3: s, h4: i } = this;
return [e, t, r, s, i];
}
set(e, t, r, s, i) {
this.h0 = e | 0, this.h1 = t | 0, this.h2 = r | 0, this.h3 = s | 0, this.h4 = i | 0;
}
process(e, t) {
for (let m = 0; m < 16; m++, t += 4)
Pr[m] = e.getUint32(t, !0);
let r = this.h0 | 0, s = r, i = this.h1 | 0, o = i, a = this.h2 | 0, c = a, l = this.h3 | 0, d = l, u = this.h4 | 0, f = u;
for (let m = 0; m < 5; m++) {
const b = 4 - m, g = r0[m], p = s0[m], y = ro[m], w = so[m], x = t0[m], A = n0[m];
for (let T = 0; T < 16; T++) {
const _ = jr(r + Ho(m, i, a, l) + Pr[y[T]] + g, x[T]) + u | 0;
r = u, u = l, l = jr(a, 10) | 0, a = i, i = _;
}
for (let T = 0; T < 16; T++) {
const _ = jr(s + Ho(b, o, c, d) + Pr[w[T]] + p, A[T]) + f | 0;
s = f, f = d, d = jr(c, 10) | 0, c = o, o = _;
}
}
this.set(this.h1 + a + d | 0, this.h2 + l + f | 0, this.h3 + u + s | 0, this.h4 + r + o | 0, this.h0 + i + c | 0);
}
roundClean() {
Pr.fill(0);
}
destroy() {
this.destroyed = !0, this.buffer.fill(0), this.set(0, 0, 0, 0, 0);
}
}
const o0 = /* @__PURE__ */ to(() => new i0()), a0 = /* @__PURE__ */ new Uint32Array([
1116352408,
1899447441,
3049323471,
3921009573,
961987163,
1508970993,
2453635748,
2870763221,
3624381080,
310598401,
607225278,
1426881987,
1925078388,
2162078206,
2614888103,
3248222580,
3835390401,
4022224774,
264347078,
604807628,
770255983,
1249150122,
1555081692,
1996064986,
2554220882,
2821834349,
2952996808,
3210313671,
3336571891,
3584528711,
113926993,
338241895,
666307205,
773529912,
1294757372,
1396182291,
1695183700,
1986661051,
2177026350,
2456956037,
2730485921,
2820302411,
3259730800,
3345764771,
3516065817,
3600352804,
4094571909,
275423344,
430227734,
506948616,
659060556,
883997877,
958139571,
1322822218,
1537002063,
1747873779,
1955562222,
2024104815,
2227730452,
2361852424,
2428436474,
2756734187,
3204031479,
3329325298
]), zt = /* @__PURE__ */ new Uint32Array([
1779033703,
3144134277,
1013904242,
2773480762,
1359893119,
2600822924,
528734635,
1541459225
]), Dt = /* @__PURE__ */ new Uint32Array(64);
class c0 extends no {
constructor() {
super(64, 32, 8, !1), this.A = zt[0] | 0, this.B = zt[1] | 0, this.C = zt[2] | 0, this.D = zt[3] | 0, this.E = zt[4] | 0, this.F = zt[5] | 0, this.G = zt[6] | 0, this.H = zt[7] | 0;
}
get() {
const { A: e, B: t, C: r, D: s, E: i, F: o, G: a, H: c } = this;
return [e, t, r, s, i, o, a, c];
}
// prettier-ignore
set(e, t, r, s, i, o, a, c) {
this.A = e | 0, this.B = t | 0, this.C = r | 0, this.D = s | 0, this.E = i | 0, this.F = o | 0, this.G = a | 0, this.H = c | 0;
}
process(e, t) {
for (let u = 0; u < 16; u++, t += 4)
Dt[u] = e.getUint32(t, !1);
for (let u = 16; u < 64; u++) {
const f = Dt[u - 15], m = Dt[u - 2], b = ct(f, 7) ^ ct(f, 18) ^ f >>> 3, g = ct(m, 17) ^ ct(m, 19) ^ m >>> 10;
Dt[u] = g + Dt[u - 7] + b + Dt[u - 16] | 0;
}
let { A: r, B: s, C: i, D: o, E: a, F: c, G: l, H: d } = this;
for (let u = 0; u < 64; u++) {
const f = ct(a, 6) ^ ct(a, 11) ^ ct(a, 25), m = d + f + Jp(a, c, l) + a0[u] + Dt[u] | 0, g = (ct(r, 2) ^ ct(r, 13) ^ ct(r, 22)) + Xp(r, s, i) | 0;
d = l, l = c, c = a, a = o + m | 0, o = i, i = s, s = r, r = m + g | 0;
}
r = r + this.A | 0, s = s + this.B | 0, i = i + this.C | 0, o = o + this.D | 0, a = a + this.E | 0, c = c + this.F | 0, l = l + this.G | 0, d = d + this.H | 0, this.set(r, s, i, o, a, c, l, d);
}
roundClean() {
Dt.fill(0);
}
destroy() {
this.set(0, 0, 0, 0, 0, 0, 0, 0), this.buffer.fill(0);
}
}
const io = /* @__PURE__ */ to(() => new c0()), Zr = /* @__PURE__ */ BigInt(2 ** 32 - 1), bi = /* @__PURE__ */ BigInt(32);
function Fc(n, e = !1) {
return e ? { h: Number(n & Zr), l: Number(n >> bi & Zr) } : { h: Number(n >> bi & Zr) | 0, l: Number(n & Zr) | 0 };
}
function l0(n, e = !1) {
let t = new Uint32Array(n.length), r = new Uint32Array(n.length);
for (let s = 0; s < n.length; s++) {
const { h: i, l: o } = Fc(n[s], e);
[t[s], r[s]] = [i, o];
}
return [t, r];
}
const u0 = (n, e) => BigInt(n >>> 0) << bi | BigInt(e >>> 0), d0 = (n, e, t) => n >>> t, h0 = (n, e, t) => n << 32 - t | e >>> t, f0 = (n, e, t) => n >>> t | e << 32 - t, p0 = (n, e, t) => n << 32 - t | e >>> t, g0 = (n, e, t) => n << 64 - t | e >>> t - 32, y0 = (n, e, t) => n >>> t - 32 | e << 64 - t, m0 = (n, e) => e, w0 = (n, e) => n, b0 = (n, e, t) => n << t | e >>> 32 - t, v0 = (n, e, t) => e << t | n >>> 32 - t, x0 = (n, e, t) => e << t - 32 | n >>> 64 - t, E0 = (n, e, t) => n << t - 32 | e >>> 64 - t;
function _0(n, e, t, r) {
const s = (e >>> 0) + (r >>> 0);
return { h: n + t + (s / 2 ** 32 | 0) | 0, l: s | 0 };
}
const S0 = (n, e, t) => (n >>> 0) + (e >>> 0) + (t >>> 0), k0 = (n, e, t, r) => e + t + r + (n / 2 ** 32 | 0) | 0, A0 = (n, e, t, r) => (n >>> 0) + (e >>> 0) + (t >>> 0) + (r >>> 0), T0 = (n, e, t, r, s) => e + t + r + s + (n / 2 ** 32 | 0) | 0, B0 = (n, e, t, r, s) => (n >>> 0) + (e >>> 0) + (t >>> 0) + (r >>> 0) + (s >>> 0), O0 = (n, e, t, r, s, i) => e + t + r + s + i + (n / 2 ** 32 | 0) | 0, Q = {
fromBig: Fc,
split: l0,
toBig: u0,
shrSH: d0,
shrSL: h0,
rotrSH: f0,
rotrSL: p0,
rotrBH: g0,
rotrBL: y0,
rotr32H: m0,
rotr32L: w0,
rotlSH: b0,
rotlSL: v0,
rotlBH: x0,
rotlBL: E0,
add: _0,
add3L: S0,
add3H: k0,
add4L: A0,
add4H: T0,
add5H: O0,
add5L: B0
}, [I0, C0] = Q.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))), qt = /* @__PURE__ */ new Uint32Array(80), Vt = /* @__PURE__ */ new Uint32Array(80);
class $0 extends no {
constructor() {
super(128, 64, 16, !1), this.Ah = 1779033703, this.Al = -205731576, this.Bh = -1150833019, this.Bl = -2067093701, this.Ch = 1013904242, this.Cl = -23791573, this.Dh = -1521486534, this.Dl = 1595750129, this.Eh = 1359893119, this.El = -1377402159, this.Fh = -1694144372, this.Fl = 725511199, this.Gh = 528734635, this.Gl = -79577749, this.Hh = 1541459225, this.Hl = 327033209;
}
// prettier-ignore
get() {
const { Ah: e, Al: t, Bh: r, Bl: s, Ch: i, Cl: o, Dh: a, Dl: c, Eh: l, El: d, Fh: u, Fl: f, Gh: m, Gl: b, Hh: g, Hl: p } = this;
return [e, t, r, s, i, o, a, c, l, d, u, f, m, b, g, p];
}
// prettier-ignore
set(e, t, r, s, i, o, a, c, l, d, u, f, m, b, g, p) {
this.Ah = e | 0, this.Al = t | 0, this.Bh = r | 0, this.Bl = s | 0, this.Ch = i | 0, this.Cl = o | 0, this.Dh = a | 0, this.Dl = c | 0, this.Eh = l | 0, this.El = d | 0, this.Fh = u | 0, this.Fl = f | 0, this.Gh = m | 0, this.Gl = b | 0, this.Hh = g | 0, this.Hl = p | 0;
}
process(e, t) {
for (let x = 0; x < 16; x++, t += 4)
qt[x] = e.getUint32(t), Vt[x] = e.getUint32(t += 4);
for (let x = 16; x < 80; x++) {
const A = qt[x - 15] | 0, T = Vt[x - 15] | 0, _ = Q.rotrSH(A, T, 1) ^ Q.rotrSH(A, T, 8) ^ Q.shrSH(A, T, 7), S = Q.rotrSL(A, T, 1) ^ Q.rotrSL(A, T, 8) ^ Q.shrSL(A, T, 7), k = qt[x - 2] | 0, N = Vt[x - 2] | 0, z = Q.rotrSH(k, N, 19) ^ Q.rotrBH(k, N, 61) ^ Q.shrSH(k, N, 6), L = Q.rotrSL(k, N, 19) ^ Q.rotrBL(k, N, 61) ^ Q.shrSL(k, N, 6), P = Q.add4L(S, L, Vt[x - 7], Vt[x - 16]), F = Q.add4H(P, _, z, qt[x - 7], qt[x - 16]);
qt[x] = F | 0, Vt[x] = P | 0;
}
let { Ah: r, Al: s, Bh: i, Bl: o, Ch: a, Cl: c, Dh: l, Dl: d, Eh: u, El: f, Fh: m, Fl: b, Gh: g, Gl: p, Hh: y, Hl: w } = this;
for (let x = 0; x < 80; x++) {
const A = Q.rotrSH(u, f, 14) ^ Q.rotrSH(u, f, 18) ^ Q.rotrBH(u, f, 41), T = Q.rotrSL(u, f, 14) ^ Q.rotrSL(u, f, 18) ^ Q.rotrBL(u, f, 41), _ = u & m ^ ~u & g, S = f & b ^ ~f & p, k = Q.add5L(w, T, S, C0[x], Vt[x]), N = Q.add5H(k, y, A, _, I0[x], qt[x]), z = k | 0, L = Q.rotrSH(r, s, 28) ^ Q.rotrBH(r, s, 34) ^ Q.rotrBH(r, s, 39), P = Q.rotrSL(r, s, 28) ^ Q.rotrBL(r, s, 34) ^ Q.rotrBL(r, s, 39), F = r & i ^ r & a ^ i & a, I = s & o ^ s & c ^ o & c;
y = g | 0, w = p | 0, g = m | 0, p = b | 0, m = u | 0, b = f | 0, { h: u, l: f } = Q.add(l | 0, d | 0, N | 0, z | 0), l = a | 0, d = c | 0, a = i | 0, c = o | 0, i = r | 0, o = s | 0;
const v = Q.add3L(z, P, I);
r = Q.add3H(v, N, L, F), s = v | 0;
}
({ h: r, l: s } = Q.add(this.Ah | 0, this.Al | 0, r | 0, s | 0)), { h: i, l: o } = Q.add(this.Bh | 0, this.Bl | 0, i | 0, o | 0), { h: a, l: c } = Q.add(this.Ch | 0, this.Cl | 0, a | 0, c | 0), { h: l, l: d } = Q.add(this.Dh | 0, this.Dl | 0, l | 0, d | 0), { h: u, l: f } = Q.add(this.Eh | 0, this.El | 0, u | 0, f | 0), { h: m, l: b } = Q.add(this.Fh | 0, this.Fl | 0, m | 0, b | 0), { h: g, l: p } = Q.add(this.Gh | 0, this.Gl | 0, g | 0, p | 0), { h: y, l: w } = Q.add(this.Hh | 0, this.Hl | 0, y | 0, w | 0), this.set(r, s, i, o, a, c, l, d, u, f, m, b, g, p, y, w);
}
roundClean() {
qt.fill(0), Vt.fill(0);
}
destroy() {
this.buffer.fill(0), this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
}
}
const vi = /* @__PURE__ */ to(() => new $0());
/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
const oo = /* @__PURE__ */ BigInt(0), ks = /* @__PURE__ */ BigInt(1), R0 = /* @__PURE__ */ BigInt(2);
function En(n) {
return n instanceof Uint8Array || n != null && typeof n == "object" && n.constructor.name === "Uint8Array";
}
function Nr(n) {
if (!En(n))
throw new Error("Uint8Array expected");
}
function Vn(n, e) {
if (typeof e != "boolean")
throw new Error(`${n} must be valid boolean, got "${e}".`);
}
const N0 = /* @__PURE__ */ Array.from({ length: 256 }, (n, e) => e.toString(16).padStart(2, "0"));
function Kn(n) {
Nr(n);
let e = "";
for (let t = 0; t < n.length; t++)
e += N0[n[t]];
return e;
}
function On(n) {
const e = n.toString(16);
return e.length & 1 ? `0${e}` : e;
}
function ao(n) {
if (typeof n != "string")
throw new Error("hex string expected, got " + typeof n);
return BigInt(n === "" ? "0" : `0x${n}`);
}
const _t = { _0: 48, _9: 57, _A: 65, _F: 70, _a: 97, _f: 102 };
function Mo(n) {
if (n >= _t._0 && n <= _t._9)
return n - _t._0;
if (n >= _t._A && n <= _t._F)
return n - (_t._A - 10);
if (n >= _t._a && n <= _t._f)
return n - (_t._a - 10);
}
function Wn(n) {
if (typeof n != "string")
throw new Error("hex string expected, got " + typeof n);
const e = n.length, t = e / 2;
if (e % 2)
throw new Error("padded hex string expected, got unpadded hex of length " + e);
const r = new Uint8Array(t);
for (let s = 0, i = 0; s < t; s++, i += 2) {
const o = Mo(n.charCodeAt(i)), a = Mo(n.charCodeAt(i + 1));
if (o === void 0 || a === void 0) {
const c = n[i] + n[i + 1];
throw new Error('hex string expected, got non-hex character "' + c + '" at index ' + i);
}
r[s] = o * 16 + a;
}
return r;
}
function mn(n) {
return ao(Kn(n));
}
function co(n) {
return Nr(n), ao(Kn(Uint8Array.from(n).reverse()));
}
function Fn(n, e) {
return Wn(n.toString(16).padStart(e * 2, "0"));
}
function lo(n, e) {
return Fn(n, e).reverse();
}
function L0(n) {
return Wn(On(n));
}
function We(n, e, t) {
let r;
if (typeof e == "string")
try {
r = Wn(e);
} catch (i) {
throw new Error(`${n} must be valid hex string, got "${e}". Cause: ${i}`);
}
else if (En(e))
r = Uint8Array.from(e);
else
throw new Error(`${n} must be hex string or Uint8Array`);
const s = r.length;
if (typeof t == "number" && s !== t)
throw new Error(`${n} expected ${t} bytes, got ${s}`);
return r;
}
function kr(...n) {
let e = 0;
for (let r = 0; r < n.length; r++) {
const s = n[r];
Nr(s), e += s.length;
}
const t = new Uint8Array(e);
for (let r = 0, s = 0; r < n.length; r++) {
const i = n[r];
t.set(i, s), s += i.length;
}
return t;
}
function U0(n, e) {
if (n.length !== e.length)
return !1;
let t = 0;
for (let r = 0; r < n.length; r++)
t |= n[r] ^ e[r];
return t === 0;
}
function H0(n) {
if (typeof n != "string")
throw new Error(`utf8ToBytes expected string, got ${typeof n}`);
return new Uint8Array(new TextEncoder().encode(n));
}
const Ps = (n) => typeof n == "bigint" && oo <= n;
function As(n, e, t) {
return Ps(n) && Ps(e) && Ps(t) && e <= n && n < t;
}
function wn(n, e, t, r) {
if (!As(e, t, r))
throw new Error(`expected valid ${n}: ${t} <= n < ${r}, got ${typeof e} ${e}`);
}
function Gc(n) {
let e;
for (e = 0; n > oo; n >>= ks, e += 1)
;
return e;
}
function M0(n, e) {
return n >> BigInt(e) & ks;
}
function j0(n, e, t) {
return n | (t ? ks : oo) << BigInt(e);
}
const uo = (n) => (R0 << BigInt(n - 1)) - ks, Zs = (n) => new Uint8Array(n), jo = (n) => Uint8Array.from(n);
function Yc(n, e, t) {
if (typeof n != "number" || n < 2)
throw new Error("hashLen must be a number");
if (typeof e != "number" || e < 2)
throw new Error("qByteLen must be a number");
if (typeof t != "function")
throw new Error("hmacFn must be a function");
let r = Zs(n), s = Zs(n), i = 0;
const o = () => {
r.fill(1), s.fill(0), i = 0;
}, a = (...u) => t(s, r, ...u), c = (u = Zs()) => {
s = a(jo([0]), u), r = a(), u.length !== 0 && (s = a(jo([1]), u), r = a());
}, l = () => {
if (i++ >= 1e3)
throw new Error("drbg: tried 1000 values");
let u = 0;
const f = [];
for (; u < e; ) {
r = a();
const m = r.slice();
f.push(m), u += r.length;
}
return kr(...f);
};
return (u, f) => {
o(), c(u);
let m;
for (; !(m = f(l())); )
c();
return o(), m;
};
}
const P0 = {
bigint: (n) => typeof n == "bigint",
function: (n) => typeof n == "function",
boolean: (n) => typeof n == "boolean",
string: (n) => typeof n == "string",
stringOrUint8Array: (n) => typeof n == "string" || En(n),
isSafeInteger: (n) => Number.isSafeInteger(n),
array: (n) => Array.isArray(n),
field: (n, e) => e.Fp.isValid(n),
hash: (n) => typeof n == "function" && Number.isSafeInteger(n.outputLen)
};
function Lr(n, e, t = {}) {
const r = (s, i, o) => {
const a = P0[i];
if (typeof a != "function")
throw new Error(`Invalid validator "${i}", expected function`);
const c = n[s];
if (!(o && c === void 0) && !a(c, n))
throw new Error(`Invalid param ${String(s)}=${c} (${typeof c}), expected ${i}`);
};
for (const [s, i] of Object.entries(e))
r(s, i, !1);
for (const [s, i] of Object.entries(t))
r(s, i, !0);
return n;
}
const Z0 = () => {
throw new Error("not implemented");
};
function xi(n) {
const e = /* @__PURE__ */ new WeakMap();
return (t, ...r) => {
const s = e.get(t);
if (s !== void 0)
return s;
const i = n(t, ...r);
return e.set(t, i), i;
};
}
const z0 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
__proto__: null,
aInRange: wn,
abool: Vn,
abytes: Nr,
bitGet: M0,
bitLen: Gc,
bitMask: uo,
bitSet: j0,
bytesToHex: Kn,
bytesToNumberBE: mn,
bytesToNumberLE: co,
concatBytes: kr,
createHmacDrbg: Yc,
ensureBytes: We,
equalBytes: U0,
hexToBytes: Wn,
hexToNumber: ao,
inRange: As,
isBytes: En,
memoized: xi,
notImplemented: Z0,
numberToBytesBE: Fn,
numberToBytesLE: lo,
numberToHexUnpadded: On,
numberToVarBytesBE: L0,
utf8ToBytes: H0,
validateObject: Lr
}, Symbol.toStringTag, { value: "Module" }));
/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
const Ee = BigInt(0), de = BigInt(1), ln = BigInt(2), D0 = BigInt(3), Ei = BigInt(4), Po = BigInt(5), Zo = BigInt(8);
BigInt(9);
BigInt(16);
function Ce(n, e) {
const t = n % e;
return t >= Ee ? t : e + t;
}
function q0(n, e, t) {
if (t <= Ee || e < Ee)
throw new Error("Expected power/modulo > 0");
if (t === de)
return Ee;
let r = de;
for (; e > Ee; )
e & de && (r = r * n % t), n = n * n % t, e >>= de;
return r;
}
function qe(n, e, t) {
let r = n;
for (; e-- > Ee; )
r *= r, r %= t;
return r;
}
function _i(n, e) {
if (n === Ee || e <= Ee)
throw new Error(`invert: expected positive integers, got n=${n} mod=${e}`);
let t = Ce(n, e), r = e, s = Ee, i = de;
for (; t !== Ee; ) {
const a = r / t, c = r % t, l = s - i * a;
r = t, t = c, s = i, i = l;
}
if (r !== de)
throw new Error("invert: does not exist");
return Ce(s, e);
}
function V0(n) {
const e = (n - de) / ln;
let t, r, s;
for (t = n - de, r = 0; t % ln === Ee; t /= ln, r++)
;
for (s = ln; s < n && q0(s, e, n) !== n - de; s++)
;
if (r === 1) {
const o = (n + de) / Ei;
return function(c, l) {
const d = c.pow(l, o);
if (!c.eql(c.sqr(d), l))
throw new Error("Cannot find square root");
return d;
};
}
const i = (t + de) / ln;
return function(a, c) {
if (a.pow(c, e) === a.neg(a.ONE))
throw new Error("Cannot find square root");
let l = r, d = a.pow(a.mul(a.ONE, s), t), u = a.pow(c, i), f = a.pow(c, t);
for (; !a.eql(f, a.ONE); ) {
if (a.eql(f, a.ZERO))
return a.ZERO;
let m = 1;
for (let g = a.sqr(f); m < l && !a.eql(g, a.ONE); m++)
g = a.sqr(g);
const b = a.pow(d, de << BigInt(l - m - 1));
d = a.sqr(b), u = a.mul(u, b), f = a.mul(f, d), l = m;
}
return u;
};
}
function K0(n) {
if (n % Ei === D0) {
const e = (n + de) / Ei;
return function(r, s) {
const i = r.pow(s, e);
if (!r.eql(r.sqr(i), s))
throw new Error("Cannot find square root");
return i;
};
}
if (n % Zo === Po) {
const e = (n - Po) / Zo;
return function(r, s) {
const i = r.mul(s, ln), o = r.pow(i, e), a = r.mul(s, o), c = r.mul(r.mul(a, ln), o), l = r.mul(a, r.sub(c, r.ONE));
if (!r.eql(r.sqr(l), s))
throw new Error("Cannot find square root");
return l;
};
}
return V0(n);
}
const W0 = [
"create",
"isValid",
"is0",
"neg",
"inv",
"sqrt",
"sqr",
"eql",
"add",
"sub",
"mul",
"pow",
"div",
"addN",
"subN",
"mulN",
"sqrN"
];
function F0(n) {
const e = {
ORDER: "bigint",
MASK: "bigint",
BYTES: "isSafeInteger",
BITS: "isSafeInteger"
}, t = W0.reduce((r, s) => (r[s] = "function", r), e);
return Lr(n, t);
}
function G0(n, e, t) {
if (t < Ee)
throw new Error("Expected power > 0");
if (t === Ee)
return n.ONE;
if (t === de)
return e;
let r = n.ONE, s = e;
for (; t > Ee; )
t & de && (r = n.mul(r, s)), s = n.sqr(s), t >>= de;
return r;
}
function Y0(n, e) {
const t = new Array(e.length), r = e.reduce((i, o, a) => n.is0(o) ? i : (t[a] = i, n.mul(i, o)), n.ONE), s = n.inv(r);
return e.reduceRight((i, o, a) => n.is0(o) ? i : (t[a] = n.mul(i, t[a]), n.mul(i, o)), s), t;
}
function Jc(n, e) {
const t = e !== void 0 ? e : n.toString(2).length, r = Math.ceil(t / 8);
return { nBitLength: t, nByteLength: r };
}
function Xc(n, e, t = !1, r = {}) {
if (n <= Ee)
throw new Error(`Expected Field ORDER > 0, got ${n}`);
const { nBitLength: s, nByteLength: i } = Jc(n, e);
if (i > 2048)
throw new Error("Field lengths over 2048 bytes are not supported");
const o = K0(n), a = Object.freeze({
ORDER: n,
BITS: s,
BYTES: i,
MASK: uo(s),
ZERO: Ee,
ONE: de,
create: (c) => Ce(c, n),
isValid: (c) => {
if (typeof c != "bigint")
throw new Error(`Invalid field element: expected bigint, got ${typeof c}`);
return Ee <= c && c < n;
},
is0: (c) => c === Ee,
isOdd: (c) => (c & de) === de,
neg: (c) => Ce(-c, n),
eql: (c, l) => c === l,
sqr: (c) => Ce(c * c, n),
add: (c, l) => Ce(c + l, n),
sub: (c, l) => Ce(c - l, n),
mul: (c, l) => Ce(c * l, n),
pow: (c, l) => G0(a, c, l),
div: (c, l) => Ce(c * _i(l, n), n),
// Same as above, but doesn't normalize
sqrN: (c) => c * c,
addN: (c, l) => c + l,
subN: (c, l) => c - l,
mulN: (c, l) => c * l,
inv: (c) => _i(c, n),
sqrt: r.sqrt || ((c) => o(a, c)),
invertBatch: (c) => Y0(a, c),
// TODO: do we really need constant cmov?
// We don't have const-time bigints anyway, so probably will be not very useful
cmov: (c, l, d) => d ? l : c,
toBytes: (c) => t ? lo(c, i) : Fn(c, i),
fromBytes: (c) => {
if (c.length !== i)
throw new Error(`Fp.fromBytes: expected ${i}, got ${c.length}`);
return t ? co(c) : mn(c);
}
});
return Object.freeze(a);
}
function Qc(n) {
if (typeof n != "bigint")
throw new Error("field order must be bigint");
const e = n.toString(2).length;
return Math.ceil(e / 8);
}
function el(n) {
const e = Qc(n);
return e + Math.ceil(e / 2);
}
function J0(n, e, t = !1) {
const r = n.length, s = Qc(e), i = el(e);
if (r < 16 || r < i || r > 1024)
throw new Error(`expected ${i}-1024 bytes of input, got ${r}`);
const o = t ? mn(n) : co(n), a = Ce(o, e - de) + de;
return t ? lo(a, s) : Fn(a, s);
}
/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
const X0 = BigInt(0), zs = BigInt(1), Ds = /* @__PURE__ */ new WeakMap(), zo = /* @__PURE__ */ new WeakMap();
function Q0(n, e) {
const t = (i, o) => {
const a = o.negate();
return i ? a : o;
}, r = (i) => {
if (!Number.isSafeInteger(i) || i <= 0 || i > e)
throw new Error(`Wrong window size=${i}, should be [1..${e}]`);
}, s = (i) => {
r(i);
const o = Math.ceil(e / i) + 1, a = 2 ** (i - 1);
return { windows: o, windowSize: a };
};
return {
constTimeNegate: t,
// non-const time multiplication ladder
unsafeLadder(i, o) {
let a = n.ZERO, c = i;
for (; o > X0; )
o & zs && (a = a.add(c)), c = c.double(), o >>= zs;
return a;
},
/**
* 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(i, o) {
const { windows: a, windowSize: c } = s(o), l = [];
let d = i, u = d;
for (let f = 0; f < a; f++) {
u = d, l.push(u);
for (let m = 1; m < c; m++)
u = u.add(d), l.push(u);
d = u.double();
}
return l;
},
/**
* 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(i, o, a) {
const { windows: c, windowSize: l } = s(i);
let d = n.ZERO, u = n.BASE;
const f = BigInt(2 ** i - 1), m = 2 ** i, b = BigInt(i);
for (let g = 0; g < c; g++) {
const p = g * l;
let y = Number(a & f);
a >>= b, y > l && (y -= m, a += zs);
const w = p, x = p + Math.abs(y) - 1, A = g % 2 !== 0, T = y < 0;
y === 0 ? u = u.add(t(A, o[w])) : d = d.add(t(T, o[x]));
}
return { p: d, f: u };
},
wNAFCached(i, o, a) {
const c = zo.get(i) || 1;
let l = Ds.get(i);
return l || (l = this.precomputeWindow(i, c), c !== 1 && Ds.set(i, a(l))), this.wNAF(c, l, o);
},
// 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.
setWindowSize(i, o) {
r(o), zo.set(i, o), Ds.delete(i);
}
};
}
function eg(n, e, t, r) {
if (!Array.isArray(t) || !Array.isArray(r) || r.length !== t.length)
throw new Error("arrays of points and scalars must have equal length");
r.forEach((d, u) => {
if (!e.isValid(d))
throw new Error(`wrong scalar at index ${u}`);
}), t.forEach((d, u) => {
if (!(d instanceof n))
throw new Error(`wrong point at index ${u}`);
});
const s = Gc(BigInt(t.length)), i = s > 12 ? s - 3 : s > 4 ? s - 2 : s ? 2 : 1, o = (1 << i) - 1, a = new Array(o + 1).fill(n.ZERO), c = Math.floor((e.BITS - 1) / i) * i;
let l = n.ZERO;
for (let d = c; d >= 0; d -= i) {
a.fill(n.ZERO);
for (let f = 0; f < r.length; f++) {
const m = r[f], b = Number(m >> BigInt(d) & BigInt(o));
a[b] = a[b].add(t[f]);
}
let u = n.ZERO;
for (let f = a.length - 1, m = n.ZERO; f > 0; f--)
m = m.add(a[f]), u = u.add(m);
if (l = l.add(u), d !== 0)
for (let f = 0; f < i; f++)
l = l.double();
}
return l;
}
function tl(n) {
return F0(n.Fp), Lr(n, {
n: "bigint",
h: "bigint",
Gx: "field",
Gy: "field"
}, {
nBitLength: "isSafeInteger",
nByteLength: "isSafeInteger"
}), Object.freeze({
...Jc(n.n, n.nBitLength),
...n,
p: n.Fp.ORDER
});
}
/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
function Do(n) {
n.lowS !== void 0 && Vn("lowS", n.lowS), n.prehash !== void 0 && Vn("prehash", n.prehash);
}
function tg(n) {
const e = tl(n);
Lr(e, {
a: "field",
b: "field"
}, {
allowedPrivateKeyLengths: "array",
wrapPrivateKey: "boolean",
isTorsionFree: "function",
clearCofactor: "function",
allowInfinityPoint: "boolean",
fromBytes: "function",
toBytes: "function"
});
const { endo: t, Fp: r, a: s } = e;
if (t) {
if (!r.eql(s, r.ZERO))
throw new Error("Endomorphism can only be defined for Koblitz curves that have a=0");
if (typeof t != "object" || typeof t.beta != "bigint" || typeof t.splitScalar != "function")
throw new Error("Expected endomorphism with beta: bigint and splitScalar: function");
}
return Object.freeze({ ...e });
}
const { bytesToNumberBE: ng, hexToBytes: rg } = z0, At = {
// asn.1 DER encoding utils
Err: class extends Error {
constructor(e = "") {
super(e);
}
},
// Basic building block is TLV (Tag-Length-Value)
_tlv: {
encode: (n, e) => {
const { Err: t } = At;
if (n < 0 || n > 256)
throw new t("tlv.encode: wrong tag");
if (e.length & 1)
throw new t("tlv.encode: unpadded data");
const r = e.length / 2, s = On(r);
if (s.length / 2 & 128)
throw new t("tlv.encode: long form length too big");
const i = r > 127 ? On(s.length / 2 | 128) : "";
return `${On(n)}${i}${s}${e}`;
},
// v - value, l - left bytes (unparsed)
decode(n, e) {
const { Err: t } = At;
let r = 0;
if (n < 0 || n > 256)
throw new t("tlv.encode: wrong tag");
if (e.length < 2 || e[r++] !== n)
throw new t("tlv.decode: wrong tlv");
const s = e[r++], i = !!(s & 128);
let o = 0;
if (!i)
o = s;
else {
const c = s & 127;
if (!c)
throw new t("tlv.decode(long): indefinite length not supported");
if (c > 4)
throw new t("tlv.decode(long): byte length is too big");
const l = e.subarray(r, r + c);
if (l.length !== c)
throw new t("tlv.decode: length bytes not complete");
if (l[0] === 0)
throw new t("tlv.decode(long): zero leftmost byte");
for (const d of l)
o = o << 8 | d;
if (r += c, o < 128)
throw new t("tlv.decode(long): not minimal encoding");
}
const a = e.subarray(r, r + o);
if (a.length !== o)
throw new t("tlv.decode: wrong value length");
return { v: a, l: e.subarray(r + o) };
}
},
// 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(n) {
const { Err: e } = At;
if (n < It)
throw new e("integer: negative integers are not allowed");
let t = On(n);
if (Number.parseInt(t[0], 16) & 8 && (t = "00" + t), t.length & 1)
throw new e("unexpected assertion");
return t;
},
decode(n) {
const { Err: e } = At;
if (n[0] & 128)
throw new e("Invalid signature integer: negative");
if (n[0] === 0 && !(n[1] & 128))
throw new e("Invalid signature integer: unnecessary leading zero");
return ng(n);
}
},
toSig(n) {
const { Err: e, _int: t, _tlv: r } = At, s = typeof n == "string" ? rg(n) : n;
Nr(s);
const { v: i, l: o } = r.decode(48, s);
if (o.length)
throw new e("Invalid signature: left bytes after parsing");
const { v: a, l: c } = r.decode(2, i), { v: l, l: d } = r.decode(2, c);
if (d.length)
throw new e("Invalid signature: left bytes after parsing");
return { r: t.decode(a), s: t.decode(l) };
},
hexFromSig(n) {
const { _tlv: e, _int: t } = At, r = `${e.encode(2, t.encode(n.r))}${e.encode(2, t.encode(n.s))}`;
return e.encode(48, r);
}
}, It = BigInt(0), be = BigInt(1);
BigInt(2);
const qo = BigInt(3);
BigInt(4);
function sg(n) {
const e = tg(n), { Fp: t } = e, r = Xc(e.n, e.nBitLength), s = e.toBytes || ((g, p, y) => {
const w = p.toAffine();
return kr(Uint8Array.from([4]), t.toBytes(w.x), t.toBytes(w.y));
}), i = e.fromBytes || ((g) => {
const p = g.subarray(1), y = t.fromBytes(p.subarray(0, t.BYTES)), w = t.fromBytes(p.subarray(t.BYTES, 2 * t.BYTES));
return { x: y, y: w };
});
function o(g) {
const { a: p, b: y } = e, w = t.sqr(g), x = t.mul(w, g);
return t.add(t.add(x, t.mul(g, p)), y);
}
if (!t.eql(t.sqr(e.Gy), o(e.Gx)))
throw new Error("bad generator point: equation left != right");
function a(g) {
return As(g, be, e.n);
}
function c(g) {
const { allowedPrivateKeyLengths: p, nByteLength: y, wrapPrivateKey: w, n: x } = e;
if (p && typeof g != "bigint") {
if (En(g) && (g = Kn(g)), typeof g != "string" || !p.includes(g.length))
throw new Error("Invalid key");
g = g.padStart(y * 2, "0");
}
let A;
try {
A = typeof g == "bigint" ? g : mn(We("private key", g, y));
} catch {
throw new Error(`private key must be ${y} bytes, hex or bigint, not ${typeof g}`);
}
return w && (A = Ce(A, x)), wn("private key", A, be, x), A;
}
function l(g) {
if (!(g instanceof f))
throw new Error("ProjectivePoint expected");
}
const d = xi((g, p) => {
const { px: y, py: w, pz: x } = g;
if (t.eql(x, t.ONE))
return { x: y, y: w };
const A = g.is0();
p == null && (p = A ? t.ONE : t.inv(x));
const T = t.mul(y, p), _ = t.mul(w, p), S = t.mul(x, p);
if (A)
return { x: t.ZERO, y: t.ZERO };
if (!t.eql(S, t.ONE))
throw new Error("invZ was invalid");
return { x: T, y: _ };
}), u = xi((g) => {
if (g.is0()) {
if (e.allowInfinityPoint && !t.is0(g.py))
return;
throw new Error("bad point: ZERO");
}
const { x: p, y } = g.toAffine();
if (!t.isValid(p) || !t.isValid(y))
throw new Error("bad point: x or y not FE");
const w = t.sqr(y), x = o(p);
if (!t.eql(w, x))
throw new Error("bad point: equation left != right");
if (!g.isTorsionFree())
throw new Error("bad point: not in prime-order subgroup");
return !0;
});
class f {
constructor(p, y, w) {
if (this.px = p, this.py = y, this.pz = w, p == null || !t.isValid(p))
throw new Error("x required");
if (y == null || !t.isValid(y))
throw new Error("y required");
if (w == null || !t.isValid(w))
throw new Error("z required");
Object.freeze(this);
}
// Does not validate if the point is on-curve.
// Use fromHex instead, or call assertValidity() later.
static fromAffine(p) {
const { x: y, y: w } = p || {};
if (!p || !t.isValid(y) || !t.isValid(w))
throw new Error("invalid affine point");
if (p instanceof f)
throw new Error("projective point not allowed");
const x = (A) => t.eql(A, t.ZERO);
return x(y) && x(w) ? f.ZERO : new f(y, w, t.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(p) {
const y = t.invertBatch(p.map((w) => w.pz));
return p.map((w, x) => w.toAffine(y[x])).map(f.fromAffine);
}
/**
* Converts hash string or Uint8Array to Point.
* @param hex short/long ECDSA hex
*/
static fromHex(p) {
const y = f.fromAffine(i(We("pointHex", p)));
return y.assertValidity(), y;
}
// Multiplies generator point by privateKey.
static fromPrivateKey(p) {
return f.BASE.multiply(c(p));
}
// Multiscalar Multiplication
static msm(p, y) {
return eg(f, r, p, y);
}
// "Private method", don't use it directly
_setWindowSize(p) {
b.setWindowSize(this, p);
}
// A point on curve is valid if it conforms to equation.
assertValidity() {
u(this);
}
hasEvenY() {
const { y: p } = this.toAffine();
if (t.isOdd)
return !t.isOdd(p);
throw new Error("Field doesn't support isOdd");
}
/**
* Compare one point to another.
*/
equals(p) {
l(p);
const { px: y, py: w, pz: x } = this, { px: A, py: T, pz: _ } = p, S = t.eql(t.mul(y, _), t.mul(A, x)), k = t.eql(t.mul(w, _), t.mul(T, x));
return S && k;
}
/**
* Flips point to one corresponding to (x, -y) in Affine coordinates.
*/
negate() {
return new f(this.px, t.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: p, b: y } = e, w = t.mul(y, qo), { px: x, py: A, pz: T } = this;
let _ = t.ZERO, S = t.ZERO, k = t.ZERO, N = t.mul(x, x), z = t.mul(A, A), L = t.mul(T, T), P = t.mul(x, A);
return P = t.add(P, P), k = t.mul(x, T), k = t.add(k, k), _ = t.mul(p, k), S = t.mul(w, L), S = t.add(_, S), _ = t.sub(z, S), S = t.add(z, S), S = t.mul(_, S), _ = t.mul(P, _), k = t.mul(w, k), L = t.mul(p, L), P = t.sub(N, L), P = t.mul(p, P), P = t.add(P, k), k = t.add(N, N), N = t.add(k, N), N = t.add(N, L), N = t.mul(N, P), S = t.add(S, N), L = t.mul(A, T), L = t.add(L, L), N = t.mul(L, P), _ = t.sub(_, N), k = t.mul(L, z), k = t.add(k, k), k = t.add(k, k), new f(_, S, k);
}
// 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(p) {
l(p);
const { px: y, py: w, pz: x } = this, { px: A, py: T, pz: _ } = p;
let S = t.ZERO, k = t.ZERO, N = t.ZERO;
const z = e.a, L = t.mul(e.b, qo);
let P = t.mul(y, A), F = t.mul(w, T), I = t.mul(x, _), v = t.add(y, w), E = t.add(A, T);
v = t.mul(v, E), E = t.add(P, F), v = t.sub(v, E), E = t.add(y, x);
let C = t.add(A, _);
return E = t.mul(E, C), C = t.add(P, I), E = t.sub(E, C), C = t.add(w, x), S = t.add(T, _), C = t.mul(C, S), S = t.add(F, I), C = t.sub(C, S), N = t.mul(z, E), S = t.mul(L, I), N = t.add(S, N), S = t.sub(F, N), N = t.add(F, N), k = t.mul(S, N), F = t.add(P, P), F = t.add(F, P), I = t.mul(z, I), E = t.mul(L, E), F = t.add(F, I), I = t.sub(P, I), I = t.mul(z, I), E = t.add(E, I), P = t.mul(F, E), k = t.add(k, P), P = t.mul(C, E), S = t.mul(v, S), S = t.sub(S, P), P = t.mul(v, F), N = t.mul(C, N), N = t.add(N, P), new f(S, k, N);
}
subtract(p) {
return this.add(p.negate());
}
is0() {
return this.equals(f.ZERO);
}
wNAF(p) {
return b.wNAFCached(this, p, f.normalizeZ);
}
/**
* 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(p) {
wn("scalar", p, It, e.n);
const y = f.ZERO;
if (p === It)
return y;
if (p === be)
return this;
const { endo: w } = e;
if (!w)
return b.unsafeLadder(this, p);
let { k1neg: x, k1: A, k2neg: T, k2: _ } = w.splitScalar(p), S = y, k = y, N = this;
for (; A > It || _ > It; )
A & be && (S = S.add(N)), _ & be && (k = k.add(N)), N = N.double(), A >>= be, _ >>= be;
return x && (S = S.negate()), T && (k = k.negate()), k = new f(t.mul(k.px, w.beta), k.py, k.pz), S.add(k);
}
/**
* 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(p) {
const { endo: y, n: w } = e;
wn("scalar", p, be, w);
let x, A;
if (y) {
const { k1neg: T, k1: _, k2neg: S, k2: k } = y.splitScalar(p);
let { p: N, f: z } = this.wNAF(_), { p: L, f: P } = this.wNAF(k);
N = b.constTimeNegate(T, N), L = b.constTimeNegate(S, L), L = new f(t.mul(L.px, y.beta), L.py, L.pz), x = N.add(L), A = z.add(P);
} else {
const { p: T, f: _ } = this.wNAF(p);
x = T, A = _;
}
return f.normalizeZ([x, A])[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(p, y, w) {
const x = f.BASE, A = (_, S) => S === It || S === be || !_.equals(x) ? _.multiplyUnsafe(S) : _.multiply(S), T = A(this, y).add(A(p, w));
return T.is0() ? void 0 : T;
}
// 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(p) {
return d(this, p);
}
isTorsionFree() {
const { h: p, isTorsionFree: y } = e;
if (p === be)
return !0;
if (y)
return y(f, this);
throw new Error("isTorsionFree() has not been declared for the elliptic curve");
}
clearCofactor() {
const { h: p, clearCofactor: y } = e;
return p === be ? this : y ? y(f, this) : this.multiplyUnsafe(e.h);
}
toRawBytes(p = !0) {
return Vn("isCompressed", p), this.assertValidity(), s(f, this, p);
}
toHex(p = !0) {
return Vn("isCompressed", p), Kn(this.toRawBytes(p));
}
}
f.BASE = new f(e.Gx, e.Gy, t.ONE), f.ZERO = new f(t.ZERO, t.ONE, t.ZERO);
const m = e.nBitLength, b = Q0(f, e.endo ? Math.ceil(m / 2) : m);
return {
CURVE: e,
ProjectivePoint: f,
normPrivateKeyToScalar: c,
weierstrassEquation: o,
isWithinCurveOrder: a
};
}
function ig(n) {
const e = tl(n);
return Lr(e, {
hash: "hash",
hmac: "function",
randomBytes: "function"
}, {
bits2int: "function",
bits2int_modN: "function",
lowS: "boolean"
}), Object.freeze({ lowS: !0, ...e });
}
function og(n) {
const e = ig(n), { Fp: t, n: r } = e, s = t.BYTES + 1, i = 2 * t.BYTES + 1;
function o(I) {
return Ce(I, r);
}
function a(I) {
return _i(I, r);
}
const { ProjectivePoint: c, normPrivateKeyToScalar: l, weierstrassEquation: d, isWithinCurveOrder: u } = sg({
...e,
toBytes(I, v, E) {
const C = v.toAffine(), j = t.toBytes(C.x), Z = kr;
return Vn("isCompressed", E), E ? Z(Uint8Array.from([v.hasEvenY() ? 2 : 3]), j) : Z(Uint8Array.from([4]), j, t.toBytes(C.y));
},
fromBytes(I) {
const v = I.length, E = I[0], C = I.subarray(1);
if (v === s && (E === 2 || E === 3)) {
const j = mn(C);
if (!As(j, be, t.ORDER))
throw new Error("Point is not on curve");
const Z = d(j);
let W;
try {
W = t.sqrt(Z);
} catch (ce) {
const _e = ce instanceof Error ? ": " + ce.message : "";
throw new Error("Point is not on curve" + _e);
}
const Y = (W & be) === be;
return (E & 1) === 1 !== Y && (W = t.neg(W)), { x: j, y: W };
} else if (v === i && E === 4) {
const j = t.fromBytes(C.subarray(0, t.BYTES)), Z = t.fromBytes(C.subarray(t.BYTES, 2 * t.BYTES));
return { x: j, y: Z };
} else
throw new Error(`Point of length ${v} was invalid. Expected ${s} compressed bytes or ${i} uncompressed bytes`);
}
}), f = (I) => Kn(Fn(I, e.nByteLength));
function m(I) {
const v = r >> be;
return I > v;
}
function b(I) {
return m(I) ? o(-I) : I;
}
const g = (I, v, E) => mn(I.slice(v, E));
class p {
constructor(v, E, C) {
this.r = v, this.s = E, this.recovery = C, this.assertValidity();
}
// pair (bytes of r, bytes of s)
static fromCompact(v) {
const E = e.nByteLength;
return v = We("compactSignature", v, E * 2), new p(g(v, 0, E), g(v, E, 2 * E));
}
// DER encoded ECDSA signature
// https://bitcoin.stackexchange.com/questions/57644/what-are-the-parts-of-a-bitcoin-transaction-input-script
static fromDER(v) {
const { r: E, s: C } = At.toSig(We("DER", v));
return new p(E, C);
}
assertValidity() {
wn("r", this.r, be, r), wn("s", this.s, be, r);
}
addRecoveryBit(v) {
return new p(this.r, this.s, v);
}
recoverPublicKey(v) {
const { r: E, s: C, recovery: j } = this, Z = _(We("msgHash", v));
if (j == null || ![0, 1, 2, 3].includes(j))
throw new Error("recovery id invalid");
const W = j === 2 || j === 3 ? E + e.n : E;
if (W >= t.ORDER)
throw new Error("recovery id 2 or 3 invalid");
const Y = j & 1 ? "03" : "02", te = c.fromHex(Y + f(W)), ce = a(W), _e = o(-Z * ce), Ze = o(C * ce), Re = c.BASE.multiplyAndAddUnsafe(te, _e, Ze);
if (!Re)
throw new Error("point at infinify");
return Re.assertValidity(), Re;
}
// Signatures should be low-s, to prevent malleability.
hasHighS() {
return m(this.s);
}
normalizeS() {
return this.hasHighS() ? new p(this.r, o(-this.s), this.recovery) : this;
}
// DER-encoded
toDERRawBytes() {
return Wn(this.toDERHex());
}
toDERHex() {
return At.hexFromSig({ r: this.r, s: this.s });
}
// padded bytes of r, then padded bytes of s
toCompactRawBytes() {
return Wn(this.toCompactHex());
}
toCompactHex() {
return f(this.r) + f(this.s);
}
}
const y = {
isValidPrivateKey(I) {
try {
return l(I), !0;
} catch {
return !1;
}
},
normPrivateKeyToScalar: l,
/**
* Produces cryptographically secure private key from random of size
* (groupLen + ceil(groupLen / 2)) with modulo bias being negligible.
*/
randomPrivateKey: () => {
const I = el(e.n);
return J0(e.randomBytes(I), e.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(I = 8, v = c.BASE) {
return v._setWindowSize(I), v.multiply(BigInt(3)), v;
}
};
function w(I, v = !0) {
return c.fromPrivateKey(I).toRawBytes(v);
}
function x(I) {
const v = En(I), E = typeof I == "string", C = (v || E) && I.length;
return v ? C === s || C === i : E ? C === 2 * s || C === 2 * i : I instanceof c;
}
function A(I, v, E = !0) {
if (x(I))
throw new Error("first arg must be private key");
if (!x(v))
throw new Error("second arg must be public key");
return c.fromHex(v).multiply(l(I)).toRawBytes(E);
}
const T = e.bits2int || function(I) {
const v = mn(I), E = I.length * 8 - e.nBitLength;
return E > 0 ? v >> BigInt(E) : v;
}, _ = e.bits2int_modN || function(I) {
return o(T(I));
}, S = uo(e.nBitLength);
function k(I) {
return wn(`num < 2^${e.nBitLength}`, I, It, S), Fn(I, e.nByteLength);
}
function N(I, v, E = z) {
if (["recovered", "canonical"].some((Ke) => Ke in E))
throw new Error("sign() legacy options not supported");
const { hash: C, randomBytes: j } = e;
let { lowS: Z, prehash: W, extraEntropy: Y } = E;
Z == null && (Z = !0), I = We("msgHash", I), Do(E), W && (I = We("prehashed msgHash", C(I)));
const te = _(I), ce = l(v), _e = [k(ce), k(te)];
if (Y != null && Y !== !1) {
const Ke = Y === !0 ? j(t.BYTES) : Y;
_e.push(We("extraEntropy", Ke));
}
const Ze = kr(..._e), Re = te;
function ze(Ke) {
const Ne = T(Ke);
if (!u(Ne))
return;
const bt = a(Ne), vt = c.BASE.multiply(Ne).toAffine(), ge = o(vt.x);
if (ge === It)
return;
const ye = o(bt * o(Re + ge * ce));
if (ye === It)
return;
let xt = (vt.x === ge ? 0 : 2) | Number(vt.y & be), Qn = ye;
return Z && m(ye) && (Qn = b(ye), xt ^= 1), new p(ge, Qn, xt);
}
return { seed: Ze, k2sig: ze };
}
const z = { lowS: e.lowS, prehash: !1 }, L = { lowS: e.lowS, prehash: !1 };
function P(I, v, E = z) {
const { seed: C, k2sig: j } = N(I, v, E), Z = e;
return Yc(Z.hash.outputLen, Z.nByteLength, Z.hmac)(C, j);
}
c.BASE._setWindowSize(8);
function F(I, v, E, C = L) {
var vt;
const j = I;
if (v = We("msgHash", v), E = We("publicKey", E), "strict" in C)
throw new Error("options.strict was renamed to lowS");
Do(C);
const { lowS: Z, prehash: W } = C;
let Y, te;
try {
if (typeof j == "string" || En(j))
try {
Y = p.fromDER(j);
} catch (ge) {
if (!(ge instanceof At.Err))
throw ge;
Y = p.fromCompact(j);
}
else if (typeof j == "object" && typeof j.r == "bigint" && typeof j.s == "bigint") {
const { r: ge, s: ye } = j;
Y = new p(ge, ye);
} else
throw new Error("PARSE");
te = c.fromHex(E);
} catch (ge) {
if (ge.message === "PARSE")
throw new Error("signature must be Signature instance, Uint8Array or hex string");
return !1;
}
if (Z && Y.hasHighS())
return !1;
W && (v = e.hash(v));
const { r: ce, s: _e } = Y, Ze = _(v), Re = a(_e), ze = o(Ze * Re), Ke = o(ce * Re), Ne = (vt = c.BASE.multiplyAndAddUnsafe(te, ze, Ke)) == null ? void 0 : vt.toAffine();
return Ne ? o(Ne.x) === ce : !1;
}
return {
CURVE: e,
getPublicKey: w,
getSharedSecret: A,
sign: P,
verify: F,
ProjectivePoint: c,
Signature: p,
utils: y
};
}
/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
function ag(n) {
return {
hash: n,
hmac: (e, ...t) => Sr(n, e, sr(...t)),
randomBytes: Gp
};
}
function cg(n, e) {
const t = (r) => og({ ...n, ...ag(r) });
return Object.freeze({ ...t(e), create: t });
}
/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
const nl = BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"), Vo = BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"), lg = BigInt(1), Si = BigInt(2), Ko = (n, e) => (n + e / Si) / e;
function ug(n) {
const e = nl, t = BigInt(3), r = BigInt(6), s = BigInt(11), i = BigInt(22), o = BigInt(23), a = BigInt(44), c = BigInt(88), l = n * n * n % e, d = l * l * n % e, u = qe(d, t, e) * d % e, f = qe(u, t, e) * d % e, m = qe(f, Si, e) * l % e, b = qe(m, s, e) * m % e, g = qe(b, i, e) * b % e, p = qe(g, a, e) * g % e, y = qe(p, c, e) * p % e, w = qe(y, a, e) * g % e, x = qe(w, t, e) * d % e, A = qe(x, o, e) * b % e, T = qe(A, r, e) * l % e, _ = qe(T, Si, e);
if (!ki.eql(ki.sqr(_), n))
throw new Error("Cannot find square root");
return _;
}
const ki = Xc(nl, void 0, void 0, { sqrt: ug }), lt = cg({
a: BigInt(0),
// equation params: a, b
b: BigInt(7),
// Seem to be rigid: bitcointalk.org/index.php?topic=289795.msg3183975#msg3183975
Fp: ki,
// Field's prime: 2n**256n - 2n**32n - 2n**9n - 2n**8n - 2n**7n - 2n**6n - 2n**4n - 1n
n: Vo,
// Curve order, total count of valid points in the field
// Base point (x, y) aka generator point
Gx: BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"),
Gy: BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"),
h: BigInt(1),
// Cofactor
lowS: !0,
// Allow only low-S signatures by default in sign() and verify()
/**
* 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: (n) => {
const e = Vo, t = BigInt("0x3086d221a7d46bcde86c90e49284eb15"), r = -lg * BigInt("0xe4437ed6010e88286f547fa90abfe4c3"), s = BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"), i = t, o = BigInt("0x100000000000000000000000000000000"), a = Ko(i * n, e), c = Ko(-r * n, e);
let l = Ce(n - a * t - c * s, e), d = Ce(-a * r - c * i, e);
const u = l > o, f = d > o;
if (u && (l = e - l), f && (d = e - d), l > o || d > o)
throw new Error("splitScalar: Endomorphism failed, k=" + n);
return { k1neg: u, k1: l, k2neg: f, k2: d };
}
}
}, io);
BigInt(0);
lt.ProjectivePoint;
/*! scure-base - MIT License (c) 2022 Paul Miller (paulmillr.com) */
function Ai(n) {
return n instanceof Uint8Array || n != null && typeof n == "object" && n.constructor.name === "Uint8Array";
}
// @__NO_SIDE_EFFECTS__
function rl(...n) {
const e = (i) => i, t = (i, o) => (a) => i(o(a)), r = n.map((i) => i.encode).reduceRight(t, e), s = n.map((i) => i.decode).reduce(t, e);
return { encode: r, decode: s };
}
// @__NO_SIDE_EFFECTS__
function dg(n) {
return {
encode: (e) => {
if (!Array.isArray(e) || e.length && typeof e[0] != "number")
throw new Error("alphabet.encode input should be an array of numbers");
return e.map((t) => {
if (t < 0 || t >= n.length)
throw new Error(`Digit index outside alphabet: ${t} (alphabet: ${n.length})`);
return n[t];
});
},
decode: (e) => {
if (!Array.isArray(e) || e.length && typeof e[0] != "string")
throw new Error("alphabet.decode input should be array of strings");
return e.map((t) => {
if (typeof t != "string")
throw new Error(`alphabet.decode: not string element=${t}`);
const r = n.indexOf(t);
if (r === -1)
throw new Error(`Unknown letter: "${t}". Allowed: ${n}`);
return r;
});
}
};
}
// @__NO_SIDE_EFFECTS__
function hg(n = "") {
if (typeof n != "string")
throw new Error("join separator should be string");
return {
encode: (e) => {
if (!Array.isArray(e) || e.length && typeof e[0] != "string")
throw new Error("join.encode input should be array of strings");
for (let t of e)
if (typeof t != "string")
throw new Error(`join.encode: non-string input=${t}`);
return e.join(n);
},
decode: (e) => {
if (typeof e != "string")
throw new Error("join.decode input should be string");
return e.split(n);
}
};
}
// @__NO_SIDE_EFFECTS__
function Wo(n, e, t) {
if (e < 2)
throw new Error(`convertRadix: wrong from=${e}, base cannot be less than 2`);
if (t < 2)
throw new Error(`convertRadix: wrong to=${t}, base cannot be less than 2`);
if (!Array.isArray(n))
throw new Error("convertRadix: data should be array");
if (!n.length)
return [];
let r = 0;
const s = [], i = Array.from(n);
for (i.forEach((o) => {
if (o < 0 || o >= e)
throw new Error(`Wrong integer: ${o}`);
}); ; ) {
let o = 0, a = !0;
for (let c = r; c < i.length; c++) {
const l = i[c], d = e * o + l;
if (!Number.isSafeInteger(d) || e * o / e !== o || d - l !== e * o)
throw new Error("convertRadix: carry overflow");
o = d % t;
const u = Math.floor(d / t);
if (i[c] = u, !Number.isSafeInteger(u) || u * t + o !== d)
throw new Error("convertRadix: carry overflow");
if (a)
u ? a = !1 : r = c;
else continue;
}
if (s.push(o), a)
break;
}
for (let o = 0; o < n.length - 1 && n[o] === 0; o++)
s.push(0);
return s.reverse();
}
// @__NO_SIDE_EFFECTS__
function fg(n) {
return {
encode: (e) => {
if (!Ai(e))
throw new Error("radix.encode input should be Uint8Array");
return /* @__PURE__ */ Wo(Array.from(e), 2 ** 8, n);
},
decode: (e) => {
if (!Array.isArray(e) || e.length && typeof e[0] != "number")
throw new Error("radix.decode input should be array of numbers");
return Uint8Array.from(/* @__PURE__ */ Wo(e, n, 2 ** 8));
}
};
}
// @__NO_SIDE_EFFECTS__
function pg(n, e) {
if (typeof e != "function")
throw new Error("checksum fn should be function");
return {
encode(t) {
if (!Ai(t))
throw new Error("checksum.encode: input should be Uint8Array");
const r = e(t).slice(0, n), s = new Uint8Array(t.length + n);
return s.set(t), s.set(r, t.length), s;
},
decode(t) {
if (!Ai(t))
throw new Error("checksum.decode: input should be Uint8Array");
const r = t.slice(0, -n), s = e(r).slice(0, n), i = t.slice(-n);
for (let o = 0; o < n; o++)
if (s[o] !== i[o])
throw new Error("Invalid checksum");
return r;
}
};
}
const gg = (n) => /* @__PURE__ */ rl(/* @__PURE__ */ fg(58), /* @__PURE__ */ dg(n), /* @__PURE__ */ hg("")), yg = /* @__PURE__ */ gg("123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"), mg = (n) => /* @__PURE__ */ rl(/* @__PURE__ */ pg(4, (e) => n(n(e))), yg);
/*! scure-bip32 - MIT License (c) 2022 Patricio Palladino, Paul Miller (paulmillr.com) */
const zr = lt.ProjectivePoint, qs = mg(io);
function Fo(n) {
return BigInt(`0x${Vp(n)}`);
}
function wg(n) {
return Kp(n.toString(16).padStart(64, "0"));
}
const bg = Dc("Bitcoin seed"), Vs = { private: 76066276, public: 76067358 }, Ks = 2147483648, vg = (n) => o0(io(n)), xg = (n) => yn(n).getUint32(0, !1), Dr = (n) => {
if (!Number.isSafeInteger(n) || n < 0 || n > 2 ** 32 - 1)
throw new Error(`Invalid number=${n}. Should be from 0 to 2 ** 32 - 1`);
const e = new Uint8Array(4);
return yn(e).setUint32(0, n, !1), e;
};
class un {
get fingerprint() {
if (!this.pubHash)
throw new Error("No publicKey set!");
return xg(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 e = this.privateKey;
if (!e)
throw new Error("No private key");
return qs.encode(this.serialize(this.versions.private, sr(new Uint8Array([0]), e)));
}
get publicExtendedKey() {
if (!this.pubKey)
throw new Error("No public key");
return qs.encode(this.serialize(this.versions.public, this.pubKey));
}
static fromMasterSeed(e, t = Vs) {
if (ft(e), 8 * e.length < 128 || 8 * e.length > 512)
throw new Error(`HDKey: wrong seed length=${e.length}. Should be between 128 and 512 bits; 256 bits is advised)`);
const r = Sr(vi, bg, e);
return new un({
versions: t,
chainCode: r.slice(32),
privateKey: r.slice(0, 32)
});
}
static fromExtendedKey(e, t = Vs) {
const r = qs.decode(e), s = yn(r), i = s.getUint32(0, !1), o = {
versions: t,
depth: r[4],
parentFingerprint: s.getUint32(5, !1),
index: s.getUint32(9, !1),
chainCode: r.slice(13, 45)
}, a = r.slice(45), c = a[0] === 0;
if (i !== t[c ? "private" : "public"])
throw new Error("Version mismatch");
return c ? new un({ ...o, privateKey: a.slice(1) }) : new un({ ...o, publicKey: a });
}
static fromJSON(e) {
return un.fromExtendedKey(e.xpriv);
}
constructor(e) {
if (this.depth = 0, this.index = 0, this.chainCode = null, this.parentFingerprint = 0, !e || typeof e != "object")
throw new Error("HDKey.constructor must not be called directly");
if (this.versions = e.versions || Vs, this.depth = e.depth || 0, this.chainCode = e.chainCode || null, this.index = e.index || 0, this.parentFingerprint = e.parentFingerprint || 0, !this.depth && (this.parentFingerprint || this.index))
throw new Error("HDKey: zero depth with non-zero index/parent fingerprint");
if (e.publicKey && e.privateKey)
throw new Error("HDKey: publicKey and privateKey at same time.");
if (e.privateKey) {
if (!lt.utils.isValidPrivateKey(e.privateKey))
throw new Error("Invalid private key");
this.privKey = typeof e.privateKey == "bigint" ? e.privateKey : Fo(e.privateKey), this.privKeyBytes = wg(this.privKey), this.pubKey = lt.getPublicKey(e.privateKey, !0);
} else if (e.publicKey)
this.pubKey = zr.fromHex(e.publicKey).toRawBytes(!0);
else
throw new Error("HDKey: no public or private key provided");
this.pubHash = vg(this.pubKey);
}
derive(e) {
if (!/^[mM]'?/.test(e))
throw new Error('Path must start with "m" or "M"');
if (/^[mM]'?$/.test(e))
return this;
const t = e.replace(/^[mM]'?\//, "").split("/");
let r = this;
for (const s of t) {
const i = /^(\d+)('?)$/.exec(s), o = i && i[1];
if (!i || i.length !== 3 || typeof o != "string")
throw new Error(`Invalid child index: ${s}`);
let a = +o;
if (!Number.isSafeInteger(a) || a >= Ks)
throw new Error("Invalid index");
i[2] === "'" && (a += Ks), r = r.deriveChild(a);
}
return r;
}
deriveChild(e) {
if (!this.pubKey || !this.chainCode)
throw new Error("No publicKey or chainCode set");
let t = Dr(e);
if (e >= Ks) {
const a = this.privateKey;
if (!a)
throw new Error("Could not derive hardened child key");
t = sr(new Uint8Array([0]), a, t);
} else
t = sr(this.pubKey, t);
const r = Sr(vi, this.chainCode, t), s = Fo(r.slice(0, 32)), i = r.slice(32);
if (!lt.utils.isValidPrivateKey(s))
throw new Error("Tweak bigger than curve order");
const o = {
versions: this.versions,
chainCode: i,
depth: this.depth + 1,
parentFingerprint: this.fingerprint,
index: e
};
try {
if (this.privateKey) {
const a = Ce(this.privKey + s, lt.CURVE.n);
if (!lt.utils.isValidPrivateKey(a))
throw new Error("The tweak was out of range or the resulted private key is invalid");
o.privateKey = a;
} else {
const a = zr.fromHex(this.pubKey).add(zr.fromPrivateKey(s));
if (a.equals(zr.ZERO))
throw new Error("The tweak was equal to negative P, which made the result key invalid");
o.publicKey = a.toRawBytes(!0);
}
return new un(o);
} catch {
return this.deriveChild(e + 1);
}
}
sign(e) {
if (!this.privateKey)
throw new Error("No privateKey set!");
return ft(e, 32), lt.sign(e, this.privKey).toCompactRawBytes();
}
verify(e, t) {
if (ft(e, 32), ft(t, 64), !this.publicKey)
throw new Error("No publicKey set!");
let r;
try {
r = lt.Signature.fromCompact(t);
} catch {
return !1;
}
return lt.verify(r, e, this.publicKey);
}
wipePrivateData() {
return this.privKey = void 0, this.privKeyBytes && (this.privKeyBytes.fill(0), this.privKeyBytes = void 0), this;
}
toJSON() {
return {
xpriv: this.privateExtendedKey,
xpub: this.publicExtendedKey
};
}
serialize(e, t) {
if (!this.chainCode)
throw new Error("No chainCode set");
return ft(t, 33), sr(Dr(e), new Uint8Array([this.depth]), Dr(this.parentFingerprint), Dr(this.index), this.chainCode, t);
}
}
var Bt, Br, Ti;
class sl {
constructor(e) {
X(this, Br);
X(this, Bt);
B(this, "nip04", {
encrypt: async (e, t) => pi.encrypt(h(this, Bt), e, t),
decrypt: async (e, t) => pi.decrypt(h(this, Bt), e, t)
});
B(this, "nip44", {
encrypt: async (e, t) => {
const r = M(this, Br, Ti).call(this, e);
return Fr.v2.encrypt(t, r);
},
decrypt: async (e, t) => {
const r = M(this, Br, Ti).call(this, e);
return Fr.v2.decrypt(t, r);
}
});
q(this, Bt, e);
}
async getPublicKey() {
return od(h(this, Bt));
}
async signEvent(e) {
return Ht(e, h(this, Bt));
}
}
Bt = new WeakMap(), Br = new WeakSet(), Ti = function(e) {
return Fr.v2.utils.getConversationKey(h(this, Bt), e);
};
class ho extends sl {
constructor(e, t = 0) {
const r = `m/44'/1237'/${t}'/0/0`, { privateKey: s } = un.fromMasterSeed(e).derive(r);
if (!s)
throw new Error("Could not derive private key");
super(s);
}
}
var Or;
class Eg {
constructor(e) {
X(this, Or);
q(this, Or, e);
}
/** Get a signer for the given user. */
async get(e, t = 0) {
const r = await crypto.subtle.importKey("raw", h(this, Or), {
name: "HMAC",
hash: {
name: "SHA-256"
}
}, !1, [
"sign"
]), s = new TextEncoder().encode(e), i = await crypto.subtle.sign("HMAC", r, s), o = new Uint8Array(i);
return new ho(o, t);
}
}
Or = new WeakMap();
class ls {
/** NIP-05 value regex. */
static regex() {
return /^(?:([\w.+-]+)@)?([\w.-]+)$/;
}
/** `nostr.json` response schema. */
static nostrJsonSchema() {
return $.object({
names: $.record($.string().regex(/^[\w.+-]+$/), ne.id()),
relays: $.record(ne.id(), $.array($.string().url())).optional()
});
}
/** Resolve NIP-05 name to a profile pointer. */
static async lookup(e, t) {
const { fetch: r = globalThis.fetch, signal: s } = t ?? {}, i = e.match(ls.regex());
if (!i) throw new Error(`NIP-05: invalid name ${e}`);
const [o, a = "_", c] = i, l = new URL(`/.well-known/nostr.json?name=${encodeURIComponent(a)}`, `https://${c}/`), d = await r(l, {
signal: s
}), { names: u, relays: f } = ls.nostrJsonSchema().parse(await d.json()), m = u[a];
if (!m) throw new Error(`NIP-05: no match for ${e}`);
return {
pubkey: m,
relays: (f == null ? void 0 : f[m]) ?? []
};
}
}
class _g {
static parseInput(e) {
const t = /(\b\w+:[^\s"]+)|(".*?")|(\S+)/g, r = [];
let s;
for (; (s = t.exec(e)) !== null; )
if (s[1]) {
const [i, ...o] = s[1].split(":");
r.push({
key: i,
value: o.join(":")
});
} else s[2] ? r.push(s[2].replace(/"/g, "")) : s[3] && r.push(s[3]);
return r;
}
}
const Sg = new TextEncoder();
function kg(n) {
var t;
const e = typeof n;
return e !== "object" ? e : n === null ? "null" : ((t = n == null ? void 0 : n.constructor) == null ? void 0 : t.name) ?? "object";
}
function il(n) {
if (typeof n == "string")
return Sg.encode(n);
if (n instanceof Uint8Array)
return n;
if (n instanceof ArrayBuffer)
return new Uint8Array(n);
throw new TypeError(`The input must be a Uint8Array, a string, or an ArrayBuffer. Received a value of the type ${kg(n)}.`);
}
const Go = new TextEncoder().encode("0123456789abcdef");
new TextEncoder();
const Ag = new TextDecoder();
function Yo(n) {
const e = il(n), t = new Uint8Array(e.length * 2);
for (let r = 0; r < t.length; r++) {
const s = e[r];
t[r * 2] = Go[s >> 4], t[r * 2 + 1] = Go[s & 15];
}
return Ag.decode(t);
}
const St = [
"A",
"B",
"C",
"D",
"E",
"F",
"G",
"H",
"I",
"J",
"K",
"L",
"M",
"N",
"O",
"P",
"Q",
"R",
"S",
"T",
"U",
"V",
"W",
"X",
"Y",
"Z",
"a",
"b",
"c",
"d",
"e",
"f",
"g",
"h",
"i",
"j",
"k",
"l",
"m",
"n",
"o",
"p",
"q",
"r",
"s",
"t",
"u",
"v",
"w",
"x",
"y",
"z",
"0",
"1",
"2",
"3",
"4",
"5",
"6",
"7",
"8",
"9",
"+",
"/"
];
function Tg(n) {
const e = il(n);
let t = "", r;
const s = e.length;
for (r = 2; r < s; r += 3)
t += St[e[r - 2] >> 2], t += St[(e[r - 2] & 3) << 4 | e[r - 1] >> 4], t += St[(e[r - 1] & 15) << 2 | e[r] >> 6], t += St[e[r] & 63];
return r === s + 1 && (t += St[e[r - 2] >> 2], t += St[(e[r - 2] & 3) << 4], t += "=="), r === s && (t += St[e[r - 2] >> 2], t += St[(e[r - 2] & 3) << 4 | e[r - 1] >> 4], t += St[(e[r - 1] & 15) << 2], t += "="), t;
}
function Bg(n) {
const e = atob(n), t = e.length, r = new Uint8Array(t);
for (let s = 0; s < t; s++)
r[s] = e.charCodeAt(s);
return r;
}
class Og {
/** Encode an event as a base64 string. */
static encodeEvent(e) {
return Tg(JSON.stringify(e));
}
/** Decode an event from a base64 string. Validates the event's structure but does not verify its signature. */
static decodeEvent(e) {
const t = Bg(e), r = new TextDecoder().decode(t);
return ne.json().pipe(ne.event()).parse(r);
}
}
class Ig {
/** Generate an auth event template from a Request. */
static async template(e, t) {
const { validatePayload: r = [
"POST",
"PUT",
"PATCH"
].includes(e.method) } = t ?? {}, { method: s, url: i } = e, o = [
[
"method",
s
],
[
"u",
i
]
];
if (r) {
const a = await e.clone().arrayBuffer(), c = await crypto.subtle.digest("SHA-256", a);
o.push([
"payload",
Yo(c)
]);
}
return {
kind: 27235,
content: "",
tags: o,
created_at: Math.floor(Date.now() / 1e3)
};
}
/** Compare the auth event with the request, throwing a human-readable error if validation fails. */
static async verify(e, t) {
var m, b, g, p;
const { maxAge: r = 6e4, validatePayload: s = [
"POST",
"PUT",
"PATCH"
].includes(e.method), verifyEvent: i = Xn } = t ?? {}, o = e.headers.get("authorization");
if (!o)
throw new Error("Missing Nostr authorization header");
const a = (m = o.match(/^Nostr (.+)$/)) == null ? void 0 : m[1];
if (!a)
throw new Error("Missing Nostr authorization token");
const c = Og.decodeEvent(a);
if (!i(c))
throw new Error("Event signature is invalid");
const l = Date.now() - c.created_at * 1e3, d = (b = c.tags.find(([y]) => y === "u")) == null ? void 0 : b[1], u = (g = c.tags.find(([y]) => y === "method")) == null ? void 0 : g[1], f = (p = c.tags.find(([y]) => y === "payload")) == null ? void 0 : p[1];
if (c.kind !== 27235)
throw new Error("Event must be kind 27235");
if (d !== e.url)
throw new Error("Event URL does not match request URL");
if (u !== e.method)
throw new Error("Event method does not match HTTP request method");
if (l >= r)
throw new Error("Event expired");
if (s && f !== void 0) {
const y = await e.clone().arrayBuffer(), w = await crypto.subtle.digest("SHA-256", y);
if (Yo(w) !== f)
throw new Error("Event payload does not match request body");
}
return c;
}
}
class Bi {
/** Events are **regular**, which means they're all expected to be stored by relays. */
static regular(e) {
return 1e3 <= e && e < 1e4 || [
1,
2,
4,
5,
6,
7,
8,
16,
40,
41,
42,
43,
44
].includes(e);
}
/** Events are **replaceable**, which means that, for each combination of `pubkey` and `kind`, only the latest event is expected to (SHOULD) be stored by relays, older versions are expected to be discarded. */
static replaceable(e) {
return 1e4 <= e && e < 2e4 || [
0,
3
].includes(e);
}
/** Events are **ephemeral**, which means they are not expected to be stored by relays. */
static ephemeral(e) {
return 2e4 <= e && e < 3e4;
}
/** Events are **parameterized replaceable**, which means that, for each combination of `pubkey`, `kind` and the `d` tag, only the latest event is expected to be stored by relays, older versions are expected to be discarded. */
static parameterizedReplaceable(e) {
return 3e4 <= e && e < 4e4;
}
}
function Cg(n, e, t, r) {
zc(n);
const s = Fp({ dkLen: 32, asyncTick: 10 }, r), { c: i, dkLen: o, asyncTick: a } = s;
if (or(i), or(o), or(a), i < 1)
throw new Error("PBKDF2: iterations (c) should be >= 1");
const c = _r(e), l = _r(t), d = new Uint8Array(o), u = Sr.create(n, c), f = u._cloneInto().update(l);
return { c: i, dkLen: o, asyncTick: a, DK: d, PRF: u, PRFSalt: f };
}
function $g(n, e, t, r, s) {
return n.destroy(), e.destroy(), r && r.destroy(), s.fill(0), t;
}
function Rg(n, e, t, r) {
const { c: s, dkLen: i, DK: o, PRF: a, PRFSalt: c } = Cg(n, e, t, r);
let l;
const d = new Uint8Array(4), u = yn(d), f = new Uint8Array(a.outputLen);
for (let m = 1, b = 0; b < i; m++, b += a.outputLen) {
const g = o.subarray(b, b + a.outputLen);
u.setInt32(0, m, !1), (l = c._cloneInto(l)).update(d).digestInto(f), g.set(f.subarray(0, g.length));
for (let p = 1; p < s; p++) {
a._cloneInto(l).update(f).digestInto(f);
for (let y = 0; y < g.length; y++)
g[y] ^= f[y];
}
}
return $g(a, c, o, l, f);
}
/*! scure-bip39 - MIT License (c) 2022 Patricio Palladino, Paul Miller (paulmillr.com) */
function ol(n) {
if (typeof n != "string")
throw new TypeError(`Invalid mnemonic type: ${typeof n}`);
return n.normalize("NFKD");
}
function Ng(n) {
const e = ol(n), t = e.split(" ");
if (![12, 15, 18, 21, 24].includes(t.length))
throw new Error("Invalid mnemonic");
return { nfkd: e, words: t };
}
const Lg = (n) => ol(`mnemonic${n}`);
function Ug(n, e = "") {
return Rg(vi, Ng(n).nfkd, Lg(e), { c: 2048, dkLen: 64 });
}
class Hg extends ho {
constructor(e, t = {}) {
const { account: r, passphrase: s } = t, i = Ug(e, s);
super(i, r);
}
}
var al;
al = Symbol.asyncIterator;
var Ln, Un, Ir;
class fo {
constructor(e) {
X(this, Ln, []);
X(this, Un);
X(this, Ir, !1);
e != null && e.aborted ? this.abort() : e == null || e.addEventListener("abort", () => this.abort(), {
once: !0
});
}
/** Get messages as an AsyncIterable. */
async *[al]() {
for (; !h(this, Ir); ) {
if (h(this, Ln).length) {
yield h(this, Ln).shift();
continue;
}
await new Promise((e) => {
q(this, Un, e);
});
}
throw new DOMException("The signal has been aborted", "AbortError");
}
/** Push a message into the Machina instance, making it available to the consumer of `stream()`. */
push(e) {
var t;
h(this, Ln).push(e), (t = h(this, Un)) == null || t.call(this);
}
/** Stops streaming and throws an error to the consumer. */
abort() {
var e;
q(this, Ir, !0), (e = h(this, Un)) == null || e.call(this);
}
}
Ln = new WeakMap(), Un = new WeakMap(), Ir = new WeakMap();
var cl;
cl = Symbol.asyncDispose;
class Mg {
constructor(e) {
B(this, "opts");
B(this, "_relays");
this.opts = e, this._relays = /* @__PURE__ */ new Map();
}
/** Get or create a relay instance for the given URL. */
relay(e) {
const t = this._relays.get(e);
if (t)
return t;
{
const r = this.opts.open(e);
return this._relays.set(e, r), r;
}
}
get relays() {
return this._relays;
}
async *req(e, t) {
const r = new AbortController(), s = t != null && t.signal ? AbortSignal.any([
t.signal,
r.signal
]) : r.signal, i = await this.opts.reqRouter(e);
if (i.size < 1)
return;
const o = new fo(s), a = /* @__PURE__ */ new Set(), c = /* @__PURE__ */ new Set();
for (const [l, d] of i.entries()) {
const u = this.relay(l);
(async () => {
for await (const f of u.req(d, {
signal: s
}))
f[0] === "EOSE" && (a.add(l), a.size === i.size && o.push(f)), f[0] === "CLOSED" && (c.add(l), c.size === i.size && o.push(f)), f[0] === "EVENT" && o.push(f);
})().catch(() => {
});
}
try {
for await (const l of o)
yield l;
} finally {
r.abort();
}
}
async event(e, t) {
const r = await this.opts.eventRouter(e);
r.length < 1 || await Promise.any(r.map((s) => this.relay(s).event(e, t)));
}
async query(e, t) {
const r = new Zn(), s = e.reduce((o, a) => o + nc(a), 0);
if (s === 0) return [];
const i = e.reduce((o, a) => {
var c;
return o || !!((c = a.kinds) != null && c.some((l) => Bi.replaceable(l) || Bi.parameterizedReplaceable(l)));
}, !1);
try {
for await (const o of this.req(e, t)) {
if (o[0] === "EOSE") break;
if (o[0] === "EVENT" && r.add(o[2]), o[0] === "CLOSED") throw new Error("Subscription closed");
if (!i && r.size >= s)
break;
}
} catch {
}
return [
...r
];
}
/** Close all the relays in the pool. */
async close() {
await Promise.all([
...this._relays.values()
].map((e) => e.close()));
}
async [cl]() {
await this.close();
}
}
class jg {
/**
* Creates a new ExponentialBackoff.
* @param base the base of the exponentiation
* @param expMax the maximum exponent, no bound if undefined
*/
constructor(e, t) {
if (this._retries = 0, !Number.isInteger(e) || e < 0)
throw new Error("Base must be a positive integer or zero");
if (t !== void 0 && (!Number.isInteger(t) || t < 0))
throw new Error("ExpMax must be a undefined, a positive integer or zero");
this.base = e, this.expMax = t, this.i = 0;
}
get retries() {
return this._retries;
}
get current() {
return this.base * Math.pow(2, this.i);
}
next() {
return this._retries++, this.i = this.expMax === void 0 ? this.i + 1 : Math.min(this.i + 1, this.expMax), this.current;
}
reset() {
this._retries = 0, this.i = 0;
}
}
class Pg {
constructor() {
this.elements = [];
}
add(e) {
this.elements.push(e);
}
clear() {
this.elements.length = 0;
}
forEach(e) {
this.elements.forEach(e);
}
length() {
return this.elements.length;
}
isEmpty() {
return this.elements.length === 0;
}
peek() {
return this.elements[0];
}
read() {
return this.elements.shift();
}
}
var ie;
(function(n) {
n.open = "open", n.close = "close", n.error = "error", n.message = "message", n.retry = "retry", n.reconnect = "reconnect";
})(ie || (ie = {}));
class Zg {
/**
* Creates a new websocket.
*
* @param url to connect to.
* @param protocols optional protocols to use.
* @param options optional options to use.
*/
constructor(e, t, r) {
var s, i, o, a, c, l, d, u, f, m, b, g, p, y, w;
this._closedByUser = !1, this.handleOpenEvent = (x) => this.handleEvent(ie.open, x), this.handleErrorEvent = (x) => this.handleEvent(ie.error, x), this.handleCloseEvent = (x) => this.handleEvent(ie.close, x), this.handleMessageEvent = (x) => this.handleEvent(ie.message, x), this._url = e, this._protocols = t, this._options = {
buffer: r == null ? void 0 : r.buffer,
retry: {
maxRetries: (s = r == null ? void 0 : r.retry) === null || s === void 0 ? void 0 : s.maxRetries,
instantReconnect: (i = r == null ? void 0 : r.retry) === null || i === void 0 ? void 0 : i.instantReconnect,
backoff: (o = r == null ? void 0 : r.retry) === null || o === void 0 ? void 0 : o.backoff
},
listeners: {
open: [...(c = (a = r == null ? void 0 : r.listeners) === null || a === void 0 ? void 0 : a.open) !== null && c !== void 0 ? c : []],
close: [...(d = (l = r == null ? void 0 : r.listeners) === null || l === void 0 ? void 0 : l.close) !== null && d !== void 0 ? d : []],
error: [...(f = (u = r == null ? void 0 : r.listeners) === null || u === void 0 ? void 0 : u.error) !== null && f !== void 0 ? f : []],
message: [...(b = (m = r == null ? void 0 : r.listeners) === null || m === void 0 ? void 0 : m.message) !== null && b !== void 0 ? b : []],
retry: [...(p = (g = r == null ? void 0 : r.listeners) === null || g === void 0 ? void 0 : g.retry) !== null && p !== void 0 ? p : []],
reconnect: [...(w = (y = r == null ? void 0 : r.listeners) === null || y === void 0 ? void 0 : y.reconnect) !== null && w !== void 0 ? w : []]
}
}, this._underlyingWebsocket = this.tryConnect();
}
/**
* Getter for the url.
*
* @return the url.
*/
get url() {
return this._url;
}
/**
* Getter for the protocols.
*
* @return the protocols, or undefined if none were provided.
*/
get protocols() {
return this._protocols;
}
/**
* Getter for the buffer.
*
* @return the buffer, or undefined if none was provided.
*/
get buffer() {
return this._options.buffer;
}
/**
* Getter for the maxRetries.
*
* @return the maxRetries, or undefined if none was provided (no limit).
*/
get maxRetries() {
return this._options.retry.maxRetries;
}
/**
* Getter for the instantReconnect.
*
* @return the instantReconnect, or undefined if none was provided.
*/
get instantReconnect() {
return this._options.retry.instantReconnect;
}
/**
* Getter for the backoff.
*
* @return the backoff, or undefined if none was provided.
*/
get backoff() {
return this._options.retry.backoff;
}
/**
* Whether the websocket was closed by the user. A websocket is closed by the user if the close().
*
* @return true if the websocket was closed by the user, false otherwise.
*/
get closedByUser() {
return this._closedByUser;
}
/**
* Getter for the last 'open' event, e.g. the last time the websocket was connected.
*
* @return the last 'open' event, or undefined if the websocket was never connected.
*/
get lastConnection() {
return this._lastConnection;
}
/**
* Getter for the underlying websocket. This can be used to access the browser's native websocket directly.
*
* @see https://developer.mozilla.org/en-US/docs/Web/API/WebSocket
* @return the underlying websocket.
*/
get underlyingWebsocket() {
return this._underlyingWebsocket;
}
/**
* Getter for the readyState of the underlying websocket.
*
* @see https://developer.mozilla.org/en-US/docs/Web/API/WebSocket/readyState
* @return the readyState of the underlying websocket.
*/
get readyState() {
return this._underlyingWebsocket.readyState;
}
/**
* Getter for the bufferedAmount of the underlying websocket.
*
* @see https://developer.mozilla.org/en-US/docs/Web/API/WebSocket/bufferedAmount
* @return the bufferedAmount of the underlying websocket.
*/
get bufferedAmount() {
return this._underlyingWebsocket.bufferedAmount;
}
/**
* Getter for the extensions of the underlying websocket.
*
* @see https://developer.mozilla.org/en-US/docs/Web/API/WebSocket/extensions
* @return the extensions of the underlying websocket.
*/
get extensions() {
return this._underlyingWebsocket.extensions;
}
/**
* Getter for the binaryType of the underlying websocket.
*
* @see https://developer.mozilla.org/en-US/docs/Web/API/WebSocket/binaryType
* @return the binaryType of the underlying websocket.
*/
get binaryType() {
return this._underlyingWebsocket.binaryType;
}
/**
* Setter for the binaryType of the underlying websocket.
*
* @param value to set, 'blob' or 'arraybuffer'.
*/
set binaryType(e) {
this._underlyingWebsocket.binaryType = e;
}
/**
* Sends data over the websocket.
*
* If the websocket is not connected and a buffer was provided on creation, the data will be added to the buffer.
* If no buffer was provided or the websocket was closed by the user, the data will be dropped.
*
* @see https://developer.mozilla.org/en-US/docs/Web/API/WebSocket/send
* @param data to send.
*/
send(e) {
this.closedByUser || (this._underlyingWebsocket.readyState === this._underlyingWebsocket.OPEN ? this._underlyingWebsocket.send(e) : this.buffer !== void 0 && this.buffer.add(e));
}
/**
* Close the websocket. No connection-retry will be attempted after this.
*
* @see https://developer.mozilla.org/en-US/docs/Web/API/WebSocket/close
* @param code optional close code.
* @param reason optional close reason.
*/
close(e, t) {
this.cancelScheduledConnectionRetry(), this._closedByUser = !0, this._underlyingWebsocket.close(e, t);
}
/**
* Adds an event listener for the given event-type.
*
* @see https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener
* @param type of the event to add the listener for.
* @param listener to add.
* @param options to use when adding the listener.
*/
addEventListener(e, t, r) {
this._options.listeners[e].push({ listener: t, options: r });
}
/**
* Removes one or more event listener for the given event-type that match the given listener and options.
*
* @param type of the event to remove the listener for.
* @param listener to remove.
* @param options that were used when the listener was added.
*/
removeEventListener(e, t, r) {
const s = (i) => i.listener !== t || i.options !== r;
this._options.listeners[e] = this._options.listeners[e].filter(s);
}
/**
* Creates a new browser-native websocket and connects it to the given URL with the given protocols
* and adds all event listeners to the browser-native websocket.
*
* @return the created browser-native websocket which is also stored in the '_underlyingWebsocket' property.
*/
tryConnect() {
return this._underlyingWebsocket = new WebSocket(this.url, this.protocols), this._underlyingWebsocket.addEventListener(ie.open, this.handleOpenEvent), this._underlyingWebsocket.addEventListener(ie.close, this.handleCloseEvent), this._underlyingWebsocket.addEventListener(ie.error, this.handleErrorEvent), this._underlyingWebsocket.addEventListener(ie.message, this.handleMessageEvent), this._underlyingWebsocket;
}
/**
* Removes all event listeners from the browser-native websocket and closes it.
*/
clearWebsocket() {
this._underlyingWebsocket.removeEventListener(ie.open, this.handleOpenEvent), this._underlyingWebsocket.removeEventListener(ie.close, this.handleCloseEvent), this._underlyingWebsocket.removeEventListener(ie.error, this.handleErrorEvent), this._underlyingWebsocket.removeEventListener(ie.message, this.handleMessageEvent), this._underlyingWebsocket.close();
}
/**
* Dispatch an event to all listeners of the given event-type.
*
* @param type of the event to dispatch.
* @param event to dispatch.
*/
dispatchEvent(e, t) {
const r = this._options.listeners[e], s = [];
r.forEach(({ listener: i, options: o }) => {
i(this, t), (o === void 0 || o.once === void 0 || !o.once) && s.push({ listener: i, options: o });
}), this._options.listeners[e] = s;
}
/**
* Handles the given event by dispatching it to all listeners of the given event-type.
*
* @param type of the event to handle.
* @param event to handle.
*/
handleEvent(e, t) {
switch (e) {
case ie.close:
this.dispatchEvent(e, t), this.scheduleConnectionRetryIfNeeded();
break;
case ie.open:
if (this.backoff !== void 0 && this._lastConnection !== void 0) {
const r = {
retries: this.backoff.retries,
lastConnection: new Date(this._lastConnection)
}, s = new CustomEvent(ie.reconnect, {
detail: r
});
this.dispatchEvent(ie.reconnect, s), this.backoff.reset();
}
this._lastConnection = /* @__PURE__ */ new Date(), this.dispatchEvent(e, t), this.sendBufferedData();
break;
case ie.retry:
this.dispatchEvent(e, t), this.clearWebsocket(), this.tryConnect();
break;
default:
this.dispatchEvent(e, t);
break;
}
}
/**
* Sends buffered data if there is a buffer defined.
*/
sendBufferedData() {
if (this.buffer !== void 0)
for (let e = this.buffer.read(); e !== void 0; e = this.buffer.read())
this.send(e);
}
/**
* Schedules a connection-retry if there is a backoff defined and the websocket was not closed by the user.
*/
scheduleConnectionRetryIfNeeded() {
if (this.closedByUser || this.backoff === void 0)
return;
const e = (r) => {
const s = new CustomEvent(ie.retry, { detail: r });
this.handleEvent(ie.retry, s);
}, t = {
backoff: this._options.retry.instantReconnect === !0 ? 0 : this.backoff.next(),
retries: this._options.retry.instantReconnect === !0 ? 0 : this.backoff.retries,
lastConnection: this._lastConnection
};
(this._options.retry.maxRetries === void 0 || t.retries <= this._options.retry.maxRetries) && (this.retryTimeout = globalThis.setTimeout(() => e(t), t.backoff));
}
/**
* Cancels the scheduled connection-retry, if there is one.
*/
cancelScheduledConnectionRetry() {
globalThis.clearTimeout(this.retryTimeout);
}
}
class zg {
/**
* Creates a new WebsocketBuilder.
*
* @param url the url to connect to
*/
constructor(e) {
this._url = e;
}
/**
* Getter for the url.
*
* @returns the url
*/
get url() {
return this._url;
}
/**
* Adds protocols to the websocket. Subsequent calls to this method will override the previously set protocols.
*
* @param protocols the protocols to add
*/
withProtocols(e) {
return this._protocols = e, this;
}
/**
* Getter for the protocols.
*
* @returns the protocols, undefined if no protocols have been set
*/
get protocols() {
return this._protocols;
}
/**
* Sets the maximum number of retries before giving up. No limit if undefined.
*
* @param maxRetries the maximum number of retries before giving up
*/
withMaxRetries(e) {
var t;
return this._options = Object.assign(Object.assign({}, this._options), { retry: Object.assign(Object.assign({}, (t = this._options) === null || t === void 0 ? void 0 : t.retry), { maxRetries: e }) }), this;
}
/**
* Getter for the maximum number of retries before giving up.
*
* @returns the maximum number of retries before giving up, undefined if no maximum has been set
*/
get maxRetries() {
var e, t;
return (t = (e = this._options) === null || e === void 0 ? void 0 : e.retry) === null || t === void 0 ? void 0 : t.maxRetries;
}
/**
* Sets wether to reconnect immediately after a connection has been lost, ignoring the backoff strategy for the first retry.
*
* @param instantReconnect wether to reconnect immediately after a connection has been lost
*/
withInstantReconnect(e) {
var t;
return this._options = Object.assign(Object.assign({}, this._options), { retry: Object.assign(Object.assign({}, (t = this._options) === null || t === void 0 ? void 0 : t.retry), { instantReconnect: e }) }), this;
}
/**
* Getter for wether to reconnect immediately after a connection has been lost, ignoring the backoff strategy for the first retry.
*
* @returns wether to reconnect immediately after a connection has been lost, undefined if no value has been set
*/
get instantReconnect() {
var e, t;
return (t = (e = this._options) === null || e === void 0 ? void 0 : e.retry) === null || t === void 0 ? void 0 : t.instantReconnect;
}
/**
* Adds a backoff to the websocket. Subsequent calls to this method will override the previously set backoff.
*
* @param backoff the backoff to add
*/
withBackoff(e) {
var t;
return this._options = Object.assign(Object.assign({}, this._options), { retry: Object.assign(Object.assign({}, (t = this._options) === null || t === void 0 ? void 0 : t.retry), { backoff: e }) }), this;
}
/**
* Getter for the backoff.
*
* @returns the backoff, undefined if no backoff has been set
*/
get backoff() {
var e, t;
return (t = (e = this._options) === null || e === void 0 ? void 0 : e.retry) === null || t === void 0 ? void 0 : t.backoff;
}
/**
* Adds a buffer to the websocket. Subsequent calls to this method will override the previously set buffer.
*
* @param buffer the buffer to add
*/
withBuffer(e) {
return this._options = Object.assign(Object.assign({}, this._options), { buffer: e }), this;
}
/**
* Getter for the buffer.
*
* @returns the buffer, undefined if no buffer has been set
*/
get buffer() {
var e;
return (e = this._options) === null || e === void 0 ? void 0 : e.buffer;
}
/**
* Adds an 'open' event listener to the websocket. Subsequent calls to this method will add additional listeners that will be
* called in the order they were added.
*
* @param listener the listener to add
* @param options the listener options
*/
onOpen(e, t) {
return this.addListener(ie.open, e, t), this;
}
/**
* Adds an 'close' event listener to the websocket. Subsequent calls to this method will add additional listeners that will be
* called in the order they were added.
*
* @param listener the listener to add
* @param options the listener options
*/
onClose(e, t) {
return this.addListener(ie.close, e, t), this;
}
/**
* Adds an 'error' event listener to the websocket. Subsequent calls to this method will add additional listeners that will be
* called in the order they were added.
*
* @param listener the listener to add
* @param options the listener options
*/
onError(e, t) {
return this.addListener(ie.error, e, t), this;
}
/**
* Adds an 'message' event listener to the websocket. Subsequent calls to this method will add additional listeners that will be
* called in the order they were added.
*
* @param listener the listener to add
* @param options the listener options
*/
onMessage(e, t) {
return this.addListener(ie.message, e, t), this;
}
/**
* Adds an 'retry' event listener to the websocket. Subsequent calls to this method will add additional listeners that will be
* called in the order they were added.
*
* @param listener the listener to add
* @param options the listener options
*/
onRetry(e, t) {
return this.addListener(ie.retry, e, t), this;
}
/**
* Adds an 'reconnect' event listener to the websocket. Subsequent calls to this method will add additional listeners that will be
* called in the order they were added.
*
* @param listener the listener to add
* @param options the listener options
*/
onReconnect(e, t) {
return this.addListener(ie.reconnect, e, t), this;
}
/**
* Builds the websocket.
*
* @return a new websocket, with the set options
*/
build() {
return new Zg(this._url, this._protocols, this._options);
}
/**
* Adds an event listener to the options.
*
* @param event the event to add the listener to
* @param listener the listener to add
* @param options the listener options
*/
addListener(e, t, r) {
var s, i, o, a, c, l, d, u, f, m, b, g, p, y, w, x, A, T, _, S, k;
return this._options = Object.assign(Object.assign({}, this._options), { listeners: {
open: (o = (i = (s = this._options) === null || s === void 0 ? void 0 : s.listeners) === null || i === void 0 ? void 0 : i.open) !== null && o !== void 0 ? o : [],
close: (l = (c = (a = this._options) === null || a === void 0 ? void 0 : a.listeners) === null || c === void 0 ? void 0 : c.close) !== null && l !== void 0 ? l : [],
error: (f = (u = (d = this._options) === null || d === void 0 ? void 0 : d.listeners) === null || u === void 0 ? void 0 : u.error) !== null && f !== void 0 ? f : [],
message: (g = (b = (m = this._options) === null || m === void 0 ? void 0 : m.listeners) === null || b === void 0 ? void 0 : b.message) !== null && g !== void 0 ? g : [],
retry: (w = (y = (p = this._options) === null || p === void 0 ? void 0 : p.listeners) === null || y === void 0 ? void 0 : y.retry) !== null && w !== void 0 ? w : [],
reconnect: (T = (A = (x = this._options) === null || x === void 0 ? void 0 : x.listeners) === null || A === void 0 ? void 0 : A.reconnect) !== null && T !== void 0 ? T : [],
[e]: [
...(k = (S = (_ = this._options) === null || _ === void 0 ? void 0 : _.listeners) === null || S === void 0 ? void 0 : S[e]) !== null && k !== void 0 ? k : [],
{ listener: t, options: r }
]
} }), this;
}
}
var ll;
ll = Symbol.asyncDispose;
class Dg {
constructor(e, t = {}) {
B(this, "url");
B(this, "opts");
B(this, "socket");
B(this, "subs");
B(this, "closedByUser");
B(this, "idleTimer");
B(this, "ee");
this.url = e, this.opts = t, this.subs = /* @__PURE__ */ new Map(), this.closedByUser = !1, this.ee = new EventTarget(), this.socket = this.createSocket(), this.maybeStartIdleTimer();
}
get subscriptions() {
return [
...this.subs.values()
];
}
/** Create (and open) a WebSocket connection with automatic reconnect. */
createSocket() {
const { backoff: e = new jg(1e3) } = this.opts;
return new zg(this.url).withBuffer(new Pg()).withBackoff(e === !1 ? void 0 : e).onOpen(() => {
for (const t of this.subs.values())
this.send(t);
}).onClose(() => {
this.subs.size || this.socket.close();
}).onMessage((t, r) => {
const s = ne.json().pipe(ne.relayMsg()).safeParse(r.data);
s.success && this.receive(s.data);
}).build();
}
/** Handle a NIP-01 relay message. */
receive(e) {
const { auth: t, verifyEvent: r = Xn } = this.opts;
switch (e[0]) {
case "EVENT":
if (!r(e[2])) break;
this.ee.dispatchEvent(new CustomEvent(`sub:${e[1]}`, {
detail: e
}));
break;
case "EOSE":
this.ee.dispatchEvent(new CustomEvent(`sub:${e[1]}`, {
detail: e
}));
break;
case "CLOSED":
this.subs.delete(e[1]), this.maybeStartIdleTimer(), this.ee.dispatchEvent(new CustomEvent(`sub:${e[1]}`, {
detail: e
}));
break;
case "OK":
this.ee.dispatchEvent(new CustomEvent(`ok:${e[1]}`, {
detail: e
}));
break;
case "NOTICE":
this.ee.dispatchEvent(new CustomEvent("notice", {
detail: e
}));
break;
case "COUNT":
this.ee.dispatchEvent(new CustomEvent(`count:${e[1]}`, {
detail: e
}));
break;
case "AUTH":
t == null || t(e[1]).then((s) => this.send([
"AUTH",
s
])).catch(() => {
});
}
}
/** Send a NIP-01 client message to the relay. */
send(e) {
switch (this.wake(), e[0]) {
case "REQ":
this.subs.set(e[1], e);
break;
case "CLOSE":
this.subs.delete(e[1]), this.maybeStartIdleTimer();
break;
case "EVENT":
case "COUNT":
return this.socket.send(JSON.stringify(e));
}
this.socket.readyState === WebSocket.OPEN && this.socket.send(JSON.stringify(e));
}
async *req(e, t = {}) {
const { signal: r } = t, s = crypto.randomUUID(), i = this.on(`sub:${s}`, r), o = [
"REQ",
s,
...e
];
this.send(o);
try {
for await (const a of i) {
if (a[0] === "EOSE" && (yield a), a[0] === "CLOSED") break;
if (a[0] === "EVENT")
if (fi(e, a[2]))
yield a;
else
continue;
}
} finally {
this.send([
"CLOSE",
s
]);
}
}
async query(e, t) {
const r = new Zn(), s = e.reduce((i, o) => i + nc(o), 0);
if (s === 0) return [];
for await (const i of this.req(e, t)) {
if (i[0] === "EOSE") break;
if (i[0] === "EVENT" && r.add(i[2]), i[0] === "CLOSED") throw new Error("Subscription closed");
if (r.size >= s)
break;
}
return [
...r
];
}
async event(e, t) {
const r = this.once(`ok:${e.id}`, t == null ? void 0 : t.signal);
this.send([
"EVENT",
e
]);
const [, , s, i] = await r;
if (!s)
throw new Error(i);
}
async count(e, t) {
const r = crypto.randomUUID(), s = this.once(`count:${r}`, t == null ? void 0 : t.signal);
this.send([
"COUNT",
r,
...e
]);
const [, , i] = await s;
return i;
}
/** Get a stream of EE events. */
async *on(e, t) {
if (t != null && t.aborted) throw this.abortError();
const r = new fo(t), s = (i) => r.push(i.detail);
this.ee.addEventListener(e, s);
try {
for await (const i of r)
yield i;
} finally {
this.ee.removeEventListener(e, s);
}
}
/** Wait for a single EE event. */
async once(e, t) {
for await (const r of this.on(e, t))
return r;
throw new Error("Unreachable");
}
abortError() {
return new DOMException("The signal has been aborted", "AbortError");
}
/** Start the idle time if applicable. */
maybeStartIdleTimer() {
const { idleTimeout: e = 3e4 } = this.opts;
e !== !1 && (this.idleTimer || this.subs.size || this.closedByUser || (this.idleTimer = setTimeout(() => this.socket.close(), e)));
}
/** Stop the idle timer. */
stopIdleTimer() {
clearTimeout(this.idleTimer), this.idleTimer = void 0;
}
/** Make a new WebSocket, but only if it was closed by an idle timeout. */
wake() {
this.stopIdleTimer(), !this.closedByUser && this.socket.closedByUser && (this.socket = this.createSocket());
}
/**
* Close the relay connection and prevent it from reconnecting.
* After this you should dispose of the `NRelay1` instance and create a new one to connect again.
*/
async close() {
this.closedByUser = !0, this.socket.close(), this.stopIdleTimer(), this.socket.readyState !== WebSocket.CLOSED && await new Promise((e) => {
this.socket.addEventListener(ie.close, e, {
once: !0
});
});
}
async [ll]() {
await this.close();
}
}
var an = Symbol("verified"), qg = (n) => n instanceof Object;
function Vg(n) {
if (!qg(n) || typeof n.kind != "number" || typeof n.content != "string" || typeof n.created_at != "number" || typeof n.pubkey != "string" || !n.pubkey.match(/^[a-f0-9]{64}$/) || !Array.isArray(n.tags))
return !1;
for (let e = 0; e < n.tags.length; e++) {
let t = n.tags[e];
if (!Array.isArray(t))
return !1;
for (let r = 0; r < t.length; r++)
if (typeof t[r] == "object")
return !1;
}
return !0;
}
new TextDecoder("utf-8");
var Kg = new TextEncoder();
function ir(n) {
n.indexOf("://") === -1 && (n = "wss://" + n);
let e = new URL(n);
return e.pathname = e.pathname.replace(/\/+/g, "/"), e.pathname.endsWith("/") && (e.pathname = e.pathname.slice(0, -1)), (e.port === "80" && e.protocol === "ws:" || e.port === "443" && e.protocol === "wss:") && (e.port = ""), e.searchParams.sort(), e.hash = "", e.toString();
}
var Wg = class {
constructor(n) {
B(this, "value");
B(this, "next", null);
B(this, "prev", null);
this.value = n;
}
}, Fg = class {
constructor() {
B(this, "first");
B(this, "last");
this.first = null, this.last = null;
}
enqueue(n) {
const e = new Wg(n);
return this.last ? this.last === this.first ? (this.last = e, this.last.prev = this.first, this.first.next = e) : (e.prev = this.last, this.last.next = e, this.last = e) : (this.first = e, this.last = e), !0;
}
dequeue() {
if (!this.first)
return null;
if (this.first === this.last) {
const e = this.first;
return this.first = null, this.last = null, e.value;
}
const n = this.first;
return this.first = n.next, n.value;
}
}, Gg = class {
generateSecretKey() {
return dt.utils.randomPrivateKey();
}
getPublicKey(n) {
return ve(dt.getPublicKey(n));
}
finalizeEvent(n, e) {
const t = n;
return t.pubkey = ve(dt.getPublicKey(e)), t.id = Ws(t), t.sig = ve(dt.sign(Ws(t), e)), t[an] = !0, t;
}
verifyEvent(n) {
if (typeof n[an] == "boolean")
return n[an];
const e = Ws(n);
if (e !== n.id)
return n[an] = !1, !1;
try {
const t = dt.verify(n.sig, e, n.pubkey);
return n[an] = t, t;
} catch {
return n[an] = !1, !1;
}
}
};
function Yg(n) {
if (!Vg(n))
throw new Error("can't serialize event with wrong or missing properties");
return JSON.stringify([0, n.pubkey, n.created_at, n.kind, n.tags, n.content]);
}
function Ws(n) {
let e = Yn(Kg.encode(Yg(n)));
return ve(e);
}
var Ts = new Gg();
Ts.generateSecretKey;
Ts.getPublicKey;
Ts.finalizeEvent;
Ts.verifyEvent;
var Jg = 22242;
function Xg(n, e) {
if (n.ids && n.ids.indexOf(e.id) === -1 || n.kinds && n.kinds.indexOf(e.kind) === -1 || n.authors && n.authors.indexOf(e.pubkey) === -1)
return !1;
for (let t in n)
if (t[0] === "#") {
let r = t.slice(1), s = n[`#${r}`];
if (s && !e.tags.find(([i, o]) => i === t.slice(1) && s.indexOf(o) !== -1))
return !1;
}
return !(n.since && e.created_at < n.since || n.until && e.created_at > n.until);
}
function Qg(n, e) {
for (let t = 0; t < n.length; t++)
if (Xg(n[t], e))
return !0;
return !1;
}
function ey(n, e) {
let t = e.length + 3, r = n.indexOf(`"${e}":`) + t, s = n.slice(r).indexOf('"') + r + 1;
return n.slice(s, s + 64);
}
function ty(n) {
let e = n.slice(0, 22).indexOf('"EVENT"');
if (e === -1)
return null;
let t = n.slice(e + 7 + 1).indexOf('"');
if (t === -1)
return null;
let r = e + 7 + 1 + t, s = n.slice(r + 1, 80).indexOf('"');
if (s === -1)
return null;
let i = r + 1 + s;
return n.slice(r + 1, i);
}
function ny(n, e) {
return {
kind: Jg,
created_at: Math.floor(Date.now() / 1e3),
tags: [
["relay", n],
["challenge", e]
],
content: ""
};
}
async function ry() {
return new Promise((n) => {
const e = new MessageChannel(), t = () => {
e.port1.removeEventListener("message", t), n();
};
e.port1.addEventListener("message", t), e.port2.postMessage(0), e.port1.start();
});
}
var sy = (n) => (n[an] = !0, !0), ul = class {
constructor(n, e) {
B(this, "url");
B(this, "_connected", !1);
B(this, "onclose", null);
B(this, "onnotice", (n) => console.debug(`NOTICE from ${this.url}: ${n}`));
B(this, "_onauth", null);
B(this, "baseEoseTimeout", 4400);
B(this, "connectionTimeout", 4400);
B(this, "openSubs", /* @__PURE__ */ new Map());
B(this, "connectionTimeoutHandle");
B(this, "connectionPromise");
B(this, "openCountRequests", /* @__PURE__ */ new Map());
B(this, "openEventPublishes", /* @__PURE__ */ new Map());
B(this, "ws");
B(this, "incomingMessageQueue", new Fg());
B(this, "queueRunning", !1);
B(this, "challenge");
B(this, "serial", 0);
B(this, "verifyEvent");
B(this, "_WebSocket");
this.url = ir(n), this.verifyEvent = e.verifyEvent, this._WebSocket = e.websocketImplementation || WebSocket;
}
static async connect(n, e) {
const t = new ul(n, e);
return await t.connect(), t;
}
closeAllSubscriptions(n) {
for (let [e, t] of this.openSubs)
t.close(n);
this.openSubs.clear();
for (let [e, t] of this.openEventPublishes)
t.reject(new Error(n));
this.openEventPublishes.clear();
for (let [e, t] of this.openCountRequests)
t.reject(new Error(n));
this.openCountRequests.clear();
}
get connected() {
return this._connected;
}
async connect() {
return this.connectionPromise ? this.connectionPromise : (this.challenge = void 0, this.connectionPromise = new Promise((n, e) => {
this.connectionTimeoutHandle = setTimeout(() => {
var t;
e("connection timed out"), this.connectionPromise = void 0, (t = this.onclose) == null || t.call(this), this.closeAllSubscriptions("relay connection timed out");
}, this.connectionTimeout);
try {
this.ws = new this._WebSocket(this.url);
} catch (t) {
e(t);
return;
}
this.ws.onopen = () => {
clearTimeout(this.connectionTimeoutHandle), this._connected = !0, n();
}, this.ws.onerror = (t) => {
var r;
e(t.message || "websocket error"), this._connected && (this._connected = !1, this.connectionPromise = void 0, (r = this.onclose) == null || r.call(this), this.closeAllSubscriptions("relay connection errored"));
}, this.ws.onclose = async () => {
var t;
this._connected && (this._connected = !1, this.connectionPromise = void 0, (t = this.onclose) == null || t.call(this), this.closeAllSubscriptions("relay connection closed"));
}, this.ws.onmessage = this._onmessage.bind(this);
}), this.connectionPromise);
}
async runQueue() {
for (this.queueRunning = !0; this.handleNext() !== !1; )
await ry();
this.queueRunning = !1;
}
handleNext() {
var t, r, s;
const n = this.incomingMessageQueue.dequeue();
if (!n)
return !1;
const e = ty(n);
if (e) {
const i = this.openSubs.get(e);
if (!i)
return;
const o = ey(n, "id"), a = (t = i.alreadyHaveEvent) == null ? void 0 : t.call(i, o);
if ((r = i.receivedEvent) == null || r.call(i, this, o), a)
return;
}
try {
let i = JSON.parse(n);
switch (i[0]) {
case "EVENT": {
const o = this.openSubs.get(i[1]), a = i[2];
this.verifyEvent(a) && Qg(o.filters, a) && o.onevent(a);
return;
}
case "COUNT": {
const o = i[1], a = i[2], c = this.openCountRequests.get(o);
c && (c.resolve(a.count), this.openCountRequests.delete(o));
return;
}
case "EOSE": {
const o = this.openSubs.get(i[1]);
if (!o)
return;
o.receivedEose();
return;
}
case "OK": {
const o = i[1], a = i[2], c = i[3], l = this.openEventPublishes.get(o);
a ? l.resolve(c) : l.reject(new Error(c)), this.openEventPublishes.delete(o);
return;
}
case "CLOSED": {
const o = i[1], a = this.openSubs.get(o);
if (!a)
return;
a.closed = !0, a.close(i[2]);
return;
}
case "NOTICE":
this.onnotice(i[1]);
return;
case "AUTH": {
this.challenge = i[1], (s = this._onauth) == null || s.call(this, i[1]);
return;
}
}
} catch {
return;
}
}
async send(n) {
if (!this.connectionPromise)
throw new Error("sending on closed connection");
this.connectionPromise.then(() => {
var e;
(e = this.ws) == null || e.send(n);
});
}
async auth(n) {
if (!this.challenge)
throw new Error("can't perform auth, no challenge was received");
const e = await n(ny(this.url, this.challenge)), t = new Promise((r, s) => {
this.openEventPublishes.set(e.id, { resolve: r, reject: s });
});
return this.send('["AUTH",' + JSON.stringify(e) + "]"), t;
}
async publish(n) {
const e = new Promise((t, r) => {
this.openEventPublishes.set(n.id, { resolve: t, reject: r });
});
return this.send('["EVENT",' + JSON.stringify(n) + "]"), e;
}
async count(n, e) {
this.serial++;
const t = (e == null ? void 0 : e.id) || "count:" + this.serial, r = new Promise((s, i) => {
this.openCountRequests.set(t, { resolve: s, reject: i });
});
return this.send('["COUNT","' + t + '",' + JSON.stringify(n).substring(1)), r;
}
subscribe(n, e) {
const t = this.prepareSubscription(n, e);
return t.fire(), t;
}
prepareSubscription(n, e) {
this.serial++;
const t = e.id || "sub:" + this.serial, r = new iy(this, t, n, e);
return this.openSubs.set(t, r), r;
}
close() {
var n;
this.closeAllSubscriptions("relay connection closed by us"), this._connected = !1, (n = this.ws) == null || n.close();
}
_onmessage(n) {
this.incomingMessageQueue.enqueue(n.data), this.queueRunning || this.runQueue();
}
}, iy = class {
constructor(n, e, t, r) {
B(this, "relay");
B(this, "id");
B(this, "closed", !1);
B(this, "eosed", !1);
B(this, "filters");
B(this, "alreadyHaveEvent");
B(this, "receivedEvent");
B(this, "onevent");
B(this, "oneose");
B(this, "onclose");
B(this, "eoseTimeout");
B(this, "eoseTimeoutHandle");
this.relay = n, this.filters = t, this.id = e, this.alreadyHaveEvent = r.alreadyHaveEvent, this.receivedEvent = r.receivedEvent, this.eoseTimeout = r.eoseTimeout || n.baseEoseTimeout, this.oneose = r.oneose, this.onclose = r.onclose, this.onevent = r.onevent || ((s) => {
console.warn(
`onevent() callback not defined for subscription '${this.id}' in relay ${this.relay.url}. event received:`,
s
);
});
}
fire() {
this.relay.send('["REQ","' + this.id + '",' + JSON.stringify(this.filters).substring(1)), this.eoseTimeoutHandle = setTimeout(this.receivedEose.bind(this), this.eoseTimeout);
}
receivedEose() {
var n;
this.eosed || (clearTimeout(this.eoseTimeoutHandle), this.eosed = !0, (n = this.oneose) == null || n.call(this));
}
close(n = "closed by caller") {
var e;
!this.closed && this.relay.connected && (this.relay.send('["CLOSE",' + JSON.stringify(this.id) + "]"), this.closed = !0), this.relay.openSubs.delete(this.id), (e = this.onclose) == null || e.call(this, n);
}
}, oy = class {
constructor(n) {
B(this, "relays", /* @__PURE__ */ new Map());
B(this, "seenOn", /* @__PURE__ */ new Map());
B(this, "trackRelays", !1);
B(this, "verifyEvent");
B(this, "trustedRelayURLs", /* @__PURE__ */ new Set());
B(this, "_WebSocket");
this.verifyEvent = n.verifyEvent, this._WebSocket = n.websocketImplementation;
}
async ensureRelay(n, e) {
n = ir(n);
let t = this.relays.get(n);
return t || (t = new ul(n, {
verifyEvent: this.trustedRelayURLs.has(n) ? sy : this.verifyEvent,
websocketImplementation: this._WebSocket
}), e != null && e.connectionTimeout && (t.connectionTimeout = e.connectionTimeout), this.relays.set(n, t)), await t.connect(), t;
}
close(n) {
n.map(ir).forEach((e) => {
var t;
(t = this.relays.get(e)) == null || t.close();
});
}
subscribeMany(n, e, t) {
return this.subscribeManyMap(Object.fromEntries(n.map((r) => [r, e])), t);
}
subscribeManyMap(n, e) {
this.trackRelays && (e.receivedEvent = (u, f) => {
let m = this.seenOn.get(f);
m || (m = /* @__PURE__ */ new Set(), this.seenOn.set(f, m)), m.add(u);
});
const t = /* @__PURE__ */ new Set(), r = [], s = Object.keys(n).length, i = [];
let o = (u) => {
var f;
i[u] = !0, i.filter((m) => m).length === s && ((f = e.oneose) == null || f.call(e), o = () => {
});
};
const a = [];
let c = (u, f) => {
var m;
o(u), a[u] = f, a.filter((b) => b).length === s && ((m = e.onclose) == null || m.call(e, a), c = () => {
});
};
const l = (u) => {
var m;
if ((m = e.alreadyHaveEvent) != null && m.call(e, u))
return !0;
const f = t.has(u);
return t.add(u), f;
}, d = Promise.all(
Object.entries(n).map(async (u, f, m) => {
if (m.indexOf(u) !== f) {
c(f, "duplicate url");
return;
}
let [b, g] = u;
b = ir(b);
let p;
try {
p = await this.ensureRelay(b, {
connectionTimeout: e.maxWait ? Math.max(e.maxWait * 0.8, e.maxWait - 1e3) : void 0
});
} catch (w) {
c(f, (w == null ? void 0 : w.message) || String(w));
return;
}
let y = p.subscribe(g, {
...e,
oneose: () => o(f),
onclose: (w) => c(f, w),
alreadyHaveEvent: l,
eoseTimeout: e.maxWait
});
r.push(y);
})
);
return {
async close() {
await d, r.forEach((u) => {
u.close();
});
}
};
}
subscribeManyEose(n, e, t) {
const r = this.subscribeMany(n, e, {
...t,
oneose() {
r.close();
}
});
return r;
}
async querySync(n, e, t) {
return new Promise(async (r) => {
const s = [];
this.subscribeManyEose(n, [e], {
...t,
onevent(i) {
s.push(i);
},
onclose(i) {
r(s);
}
});
});
}
async get(n, e, t) {
e.limit = 1;
const r = await this.querySync(n, e, t);
return r.sort((s, i) => i.created_at - s.created_at), r[0] || null;
}
publish(n, e) {
return n.map(ir).map(async (t, r, s) => s.indexOf(t) !== r ? Promise.reject("duplicate url") : (await this.ensureRelay(t)).publish(e));
}
listConnectionStatus() {
const n = /* @__PURE__ */ new Map();
return this.relays.forEach((e, t) => n.set(t, e.connected)), n;
}
destroy() {
this.relays.forEach((n) => n.close()), this.relays = /* @__PURE__ */ new Map();
}
}, ay;
try {
ay = WebSocket;
} catch {
}
class cy {
constructor(e) {
B(this, "pool");
this.pool = new oy({
verifyEvent: (e == null ? void 0 : e.verifyEvent) ?? Xn
}), this.pool.trackRelays = (e == null ? void 0 : e.trackRelays) ?? !1, this.pool.trustedRelayURLs = (e == null ? void 0 : e.trustedRelayURLs) ?? /* @__PURE__ */ new Set();
}
get seenOn() {
const e = /* @__PURE__ */ new Map();
for (const [t, r] of this.pool.seenOn)
e.set(t, new Set([
...r
].map((s) => s.url)));
return e;
}
async *req(e, t = {}) {
var c, l;
if ((c = t.signal) != null && c.aborted) throw new DOMException("The signal has been aborted", "AbortError");
const r = crypto.randomUUID(), s = new fo(t.signal), i = this.pool.subscribeMany(t.relays ?? [], e, {
id: r,
onevent(d) {
s.push([
"EVENT",
r,
d
]);
},
oneose() {
s.push([
"EOSE",
r
]);
},
onclose(d) {
s.push([
"CLOSED",
r,
d.join(", ")
]);
}
}), o = () => {
i.close(), a();
}, a = () => {
var d;
(d = t.signal) == null || d.removeEventListener("abort", o);
};
(l = t.signal) == null || l.addEventListener("abort", o);
try {
for await (const d of s)
yield d;
} finally {
o();
}
}
// deno-lint-ignore require-await
async event(e, t = {}) {
var r;
if ((r = t.signal) != null && r.aborted)
throw new DOMException("The signal has been aborted", "AbortError");
this.pool.publish(t.relays ?? [], e);
}
async query(e, t = {}) {
const r = [];
for await (const s of this.req(e, t)) {
if (s[0] === "EOSE") break;
if (s[0] === "EVENT" && r.push(s[2]), s[0] === "CLOSED") throw new Error("Subscription closed");
}
return r;
}
/** Disconnect from the given relay URLs. */
disconnect(e) {
this.pool.close(e);
}
// deno-lint-ignore require-await
async close() {
this.pool.destroy();
}
}
const Sy = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
__proto__: null,
NCache: Mf,
NConnectSigner: Zp,
NCustodial: Eg,
NIP05: ls,
NIP50: _g,
NIP98: Ig,
NKinds: Bi,
NPhraseSigner: Hg,
NPool: Mg,
NRelay1: Dg,
NSchema: ne,
NSecSigner: sl,
NSeedSigner: ho,
NSet: Zn,
NSimplePool: cy
}, Symbol.toStringTag, { value: "Module" }));
export {
Sy as Nostrify
};
//# sourceMappingURL=nostrify.js.map