import { r as reactExports } from "../index.js"; function wrapPromise(promise) { let status = "pending"; let result; let error; const suspender = promise.then( (data) => { status = "success"; result = data; }, (err) => { status = "error"; error = err; } ); return { promise, read() { switch (status) { case "pending": throw suspender; case "error": throw error; case "success": return result; } } }; } const RepoContext = reactExports.createContext(null); function useRepo() { const repo = reactExports.useContext(RepoContext); if (!repo) throw new Error("Repo was not found on RepoContext."); return repo; } const REGEX = /^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i; function validate(uuid) { return typeof uuid === "string" && REGEX.test(uuid); } function parse(uuid) { if (!validate(uuid)) { throw TypeError("Invalid UUID"); } let v; const arr = new Uint8Array(16); arr[0] = (v = parseInt(uuid.slice(0, 8), 16)) >>> 24; arr[1] = v >>> 16 & 255; arr[2] = v >>> 8 & 255; arr[3] = v & 255; arr[4] = (v = parseInt(uuid.slice(9, 13), 16)) >>> 8; arr[5] = v & 255; arr[6] = (v = parseInt(uuid.slice(14, 18), 16)) >>> 8; arr[7] = v & 255; arr[8] = (v = parseInt(uuid.slice(19, 23), 16)) >>> 8; arr[9] = v & 255; arr[10] = (v = parseInt(uuid.slice(24, 36), 16)) / 1099511627776 & 255; arr[11] = v / 4294967296 & 255; arr[12] = v >>> 24 & 255; arr[13] = v >>> 16 & 255; arr[14] = v >>> 8 & 255; arr[15] = v & 255; return arr; } function getDefaultExportFromCjs(x) { return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, "default") ? x["default"] : x; } var sha256$2 = {}; var sha2 = {}; var _md = {}; var utils = {}; var crypto = {}; var hasRequiredCrypto; function requireCrypto() { if (hasRequiredCrypto) return crypto; hasRequiredCrypto = 1; Object.defineProperty(crypto, "__esModule", { value: true }); crypto.crypto = void 0; crypto.crypto = typeof globalThis === "object" && "crypto" in globalThis ? globalThis.crypto : void 0; return crypto; } var hasRequiredUtils; function requireUtils() { if (hasRequiredUtils) return utils; hasRequiredUtils = 1; (function(exports$1) { /*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */ Object.defineProperty(exports$1, "__esModule", { value: true }); exports$1.wrapXOFConstructorWithOpts = exports$1.wrapConstructorWithOpts = exports$1.wrapConstructor = exports$1.Hash = exports$1.nextTick = exports$1.swap32IfBE = exports$1.byteSwapIfBE = exports$1.swap8IfBE = exports$1.isLE = void 0; exports$1.isBytes = isBytes; exports$1.anumber = anumber; exports$1.abytes = abytes; exports$1.ahash = ahash; exports$1.aexists = aexists; exports$1.aoutput = aoutput; exports$1.u8 = u8; exports$1.u32 = u32; exports$1.clean = clean; exports$1.createView = createView; exports$1.rotr = rotr; exports$1.rotl = rotl; exports$1.byteSwap = byteSwap; exports$1.byteSwap32 = byteSwap32; exports$1.bytesToHex = bytesToHex; exports$1.hexToBytes = hexToBytes; exports$1.asyncLoop = asyncLoop; exports$1.utf8ToBytes = utf8ToBytes; exports$1.bytesToUtf8 = bytesToUtf8; exports$1.toBytes = toBytes; exports$1.kdfInputToBytes = kdfInputToBytes; exports$1.concatBytes = concatBytes; exports$1.checkOpts = checkOpts; exports$1.createHasher = createHasher; exports$1.createOptHasher = createOptHasher; exports$1.createXOFer = createXOFer; exports$1.randomBytes = randomBytes; const crypto_1 = /* @__PURE__ */ requireCrypto(); function isBytes(a) { return a instanceof Uint8Array || ArrayBuffer.isView(a) && a.constructor.name === "Uint8Array"; } function anumber(n) { if (!Number.isSafeInteger(n) || n < 0) throw new Error("positive integer expected, got " + n); } function abytes(b, ...lengths) { if (!isBytes(b)) throw new Error("Uint8Array expected"); if (lengths.length > 0 && !lengths.includes(b.length)) throw new Error("Uint8Array expected of length " + lengths + ", got length=" + b.length); } function ahash(h) { if (typeof h !== "function" || typeof h.create !== "function") throw new Error("Hash should be wrapped by utils.createHasher"); anumber(h.outputLen); anumber(h.blockLen); } function aexists(instance, checkFinished = true) { if (instance.destroyed) throw new Error("Hash instance has been destroyed"); if (checkFinished && instance.finished) throw new Error("Hash#digest() has already been called"); } function aoutput(out, instance) { abytes(out); const min = instance.outputLen; if (out.length < min) { throw new Error("digestInto() expects output buffer of length at least " + min); } } function u8(arr) { return new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength); } function u32(arr) { return new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4)); } function clean(...arrays) { for (let i = 0; i < arrays.length; i++) { arrays[i].fill(0); } } function createView(arr) { return new DataView(arr.buffer, arr.byteOffset, arr.byteLength); } function rotr(word, shift) { return word << 32 - shift | word >>> shift; } function rotl(word, shift) { return word << shift | word >>> 32 - shift >>> 0; } exports$1.isLE = (() => new Uint8Array(new Uint32Array([287454020]).buffer)[0] === 68)(); function byteSwap(word) { return word << 24 & 4278190080 | word << 8 & 16711680 | word >>> 8 & 65280 | word >>> 24 & 255; } exports$1.swap8IfBE = exports$1.isLE ? (n) => n : (n) => byteSwap(n); exports$1.byteSwapIfBE = exports$1.swap8IfBE; function byteSwap32(arr) { for (let i = 0; i < arr.length; i++) { arr[i] = byteSwap(arr[i]); } return arr; } exports$1.swap32IfBE = exports$1.isLE ? (u) => u : byteSwap32; const hasHexBuiltin = /* @__PURE__ */ (() => ( // @ts-ignore typeof Uint8Array.from([]).toHex === "function" && typeof Uint8Array.fromHex === "function" ))(); const hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, "0")); function bytesToHex(bytes) { abytes(bytes); if (hasHexBuiltin) return bytes.toHex(); let hex = ""; for (let i = 0; i < bytes.length; i++) { hex += hexes[bytes[i]]; } return hex; } const asciis = { _0: 48, _9: 57, A: 65, F: 70, a: 97, f: 102 }; function asciiToBase16(ch) { if (ch >= asciis._0 && ch <= asciis._9) return ch - asciis._0; if (ch >= asciis.A && ch <= asciis.F) return ch - (asciis.A - 10); if (ch >= asciis.a && ch <= asciis.f) return ch - (asciis.a - 10); return; } function hexToBytes(hex) { if (typeof hex !== "string") throw new Error("hex string expected, got " + typeof hex); if (hasHexBuiltin) return Uint8Array.fromHex(hex); const hl = hex.length; const al = hl / 2; if (hl % 2) throw new Error("hex string expected, got unpadded hex of length " + hl); const array = new Uint8Array(al); for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) { const n1 = asciiToBase16(hex.charCodeAt(hi)); const n2 = asciiToBase16(hex.charCodeAt(hi + 1)); if (n1 === void 0 || n2 === void 0) { const char = hex[hi] + hex[hi + 1]; throw new Error('hex string expected, got non-hex character "' + char + '" at index ' + hi); } array[ai] = n1 * 16 + n2; } return array; } const nextTick = async () => { }; exports$1.nextTick = nextTick; async function asyncLoop(iters, tick, cb) { let ts = Date.now(); for (let i = 0; i < iters; i++) { cb(i); const diff = Date.now() - ts; if (diff >= 0 && diff < tick) continue; await (0, exports$1.nextTick)(); ts += diff; } } function utf8ToBytes(str) { if (typeof str !== "string") throw new Error("string expected"); return new Uint8Array(new TextEncoder().encode(str)); } function bytesToUtf8(bytes) { return new TextDecoder().decode(bytes); } function toBytes(data) { if (typeof data === "string") data = utf8ToBytes(data); abytes(data); return data; } function kdfInputToBytes(data) { if (typeof data === "string") data = utf8ToBytes(data); abytes(data); return data; } function concatBytes(...arrays) { let sum = 0; for (let i = 0; i < arrays.length; i++) { const a = arrays[i]; abytes(a); sum += a.length; } const res = new Uint8Array(sum); for (let i = 0, pad = 0; i < arrays.length; i++) { const a = arrays[i]; res.set(a, pad); pad += a.length; } return res; } function checkOpts(defaults, opts) { if (opts !== void 0 && {}.toString.call(opts) !== "[object Object]") throw new Error("options should be object or undefined"); const merged = Object.assign(defaults, opts); return merged; } class Hash { } exports$1.Hash = Hash; function createHasher(hashCons) { const hashC = (msg) => hashCons().update(toBytes(msg)).digest(); const tmp = hashCons(); hashC.outputLen = tmp.outputLen; hashC.blockLen = tmp.blockLen; hashC.create = () => hashCons(); return hashC; } function createOptHasher(hashCons) { const hashC = (msg, opts) => hashCons(opts).update(toBytes(msg)).digest(); const tmp = hashCons({}); hashC.outputLen = tmp.outputLen; hashC.blockLen = tmp.blockLen; hashC.create = (opts) => hashCons(opts); return hashC; } function createXOFer(hashCons) { const hashC = (msg, opts) => hashCons(opts).update(toBytes(msg)).digest(); const tmp = hashCons({}); hashC.outputLen = tmp.outputLen; hashC.blockLen = tmp.blockLen; hashC.create = (opts) => hashCons(opts); return hashC; } exports$1.wrapConstructor = createHasher; exports$1.wrapConstructorWithOpts = createOptHasher; exports$1.wrapXOFConstructorWithOpts = createXOFer; function randomBytes(bytesLength = 32) { if (crypto_1.crypto && typeof crypto_1.crypto.getRandomValues === "function") { return crypto_1.crypto.getRandomValues(new Uint8Array(bytesLength)); } if (crypto_1.crypto && typeof crypto_1.crypto.randomBytes === "function") { return Uint8Array.from(crypto_1.crypto.randomBytes(bytesLength)); } throw new Error("crypto.getRandomValues must be defined"); } })(utils); return utils; } var hasRequired_md; function require_md() { if (hasRequired_md) return _md; hasRequired_md = 1; Object.defineProperty(_md, "__esModule", { value: true }); _md.SHA512_IV = _md.SHA384_IV = _md.SHA224_IV = _md.SHA256_IV = _md.HashMD = void 0; _md.setBigUint64 = setBigUint64; _md.Chi = Chi; _md.Maj = Maj; const utils_ts_1 = /* @__PURE__ */ requireUtils(); function setBigUint64(view, byteOffset, value, isLE) { if (typeof view.setBigUint64 === "function") return view.setBigUint64(byteOffset, value, isLE); const _32n = BigInt(32); const _u32_max = BigInt(4294967295); const wh = Number(value >> _32n & _u32_max); const wl = Number(value & _u32_max); const h = isLE ? 4 : 0; const l = isLE ? 0 : 4; view.setUint32(byteOffset + h, wh, isLE); view.setUint32(byteOffset + l, wl, isLE); } function Chi(a, b, c) { return a & b ^ ~a & c; } function Maj(a, b, c) { return a & b ^ a & c ^ b & c; } class HashMD extends utils_ts_1.Hash { constructor(blockLen, outputLen, padOffset, isLE) { super(); this.finished = false; this.length = 0; this.pos = 0; this.destroyed = false; this.blockLen = blockLen; this.outputLen = outputLen; this.padOffset = padOffset; this.isLE = isLE; this.buffer = new Uint8Array(blockLen); this.view = (0, utils_ts_1.createView)(this.buffer); } update(data) { (0, utils_ts_1.aexists)(this); data = (0, utils_ts_1.toBytes)(data); (0, utils_ts_1.abytes)(data); const { view, buffer, blockLen } = this; const len = data.length; for (let pos = 0; pos < len; ) { const take = Math.min(blockLen - this.pos, len - pos); if (take === blockLen) { const dataView2 = (0, utils_ts_1.createView)(data); for (; blockLen <= len - pos; pos += blockLen) this.process(dataView2, pos); continue; } buffer.set(data.subarray(pos, pos + take), this.pos); this.pos += take; pos += take; if (this.pos === blockLen) { this.process(view, 0); this.pos = 0; } } this.length += data.length; this.roundClean(); return this; } digestInto(out) { (0, utils_ts_1.aexists)(this); (0, utils_ts_1.aoutput)(out, this); this.finished = true; const { buffer, view, blockLen, isLE } = this; let { pos } = this; buffer[pos++] = 128; (0, utils_ts_1.clean)(this.buffer.subarray(pos)); if (this.padOffset > blockLen - pos) { this.process(view, 0); pos = 0; } for (let i = pos; i < blockLen; i++) buffer[i] = 0; setBigUint64(view, blockLen - 8, BigInt(this.length * 8), isLE); this.process(view, 0); const oview = (0, utils_ts_1.createView)(out); const len = this.outputLen; if (len % 4) throw new Error("_sha2: outputLen should be aligned to 32bit"); const outLen = len / 4; const state = this.get(); if (outLen > state.length) throw new Error("_sha2: outputLen bigger than state"); for (let i = 0; i < outLen; i++) oview.setUint32(4 * i, state[i], isLE); } digest() { const { buffer, outputLen } = this; this.digestInto(buffer); const res = buffer.slice(0, outputLen); this.destroy(); return res; } _cloneInto(to) { to || (to = new this.constructor()); to.set(...this.get()); const { blockLen, buffer, length, finished, destroyed, pos } = this; to.destroyed = destroyed; to.finished = finished; to.length = length; to.pos = pos; if (length % blockLen) to.buffer.set(buffer); return to; } clone() { return this._cloneInto(); } } _md.HashMD = HashMD; _md.SHA256_IV = Uint32Array.from([ 1779033703, 3144134277, 1013904242, 2773480762, 1359893119, 2600822924, 528734635, 1541459225 ]); _md.SHA224_IV = Uint32Array.from([ 3238371032, 914150663, 812702999, 4144912697, 4290775857, 1750603025, 1694076839, 3204075428 ]); _md.SHA384_IV = Uint32Array.from([ 3418070365, 3238371032, 1654270250, 914150663, 2438529370, 812702999, 355462360, 4144912697, 1731405415, 4290775857, 2394180231, 1750603025, 3675008525, 1694076839, 1203062813, 3204075428 ]); _md.SHA512_IV = Uint32Array.from([ 1779033703, 4089235720, 3144134277, 2227873595, 1013904242, 4271175723, 2773480762, 1595750129, 1359893119, 2917565137, 2600822924, 725511199, 528734635, 4215389547, 1541459225, 327033209 ]); return _md; } var _u64 = {}; var hasRequired_u64; function require_u64() { if (hasRequired_u64) return _u64; hasRequired_u64 = 1; Object.defineProperty(_u64, "__esModule", { value: true }); _u64.toBig = _u64.shrSL = _u64.shrSH = _u64.rotrSL = _u64.rotrSH = _u64.rotrBL = _u64.rotrBH = _u64.rotr32L = _u64.rotr32H = _u64.rotlSL = _u64.rotlSH = _u64.rotlBL = _u64.rotlBH = _u64.add5L = _u64.add5H = _u64.add4L = _u64.add4H = _u64.add3L = _u64.add3H = void 0; _u64.add = add; _u64.fromBig = fromBig; _u64.split = split; const U32_MASK64 = /* @__PURE__ */ BigInt(2 ** 32 - 1); const _32n = /* @__PURE__ */ BigInt(32); function fromBig(n, le = false) { if (le) return { h: Number(n & U32_MASK64), l: Number(n >> _32n & U32_MASK64) }; return { h: Number(n >> _32n & U32_MASK64) | 0, l: Number(n & U32_MASK64) | 0 }; } function split(lst, le = false) { const len = lst.length; let Ah = new Uint32Array(len); let Al = new Uint32Array(len); for (let i = 0; i < len; i++) { const { h, l } = fromBig(lst[i], le); [Ah[i], Al[i]] = [h, l]; } return [Ah, Al]; } const toBig = (h, l) => BigInt(h >>> 0) << _32n | BigInt(l >>> 0); _u64.toBig = toBig; const shrSH = (h, _l, s) => h >>> s; _u64.shrSH = shrSH; const shrSL = (h, l, s) => h << 32 - s | l >>> s; _u64.shrSL = shrSL; const rotrSH = (h, l, s) => h >>> s | l << 32 - s; _u64.rotrSH = rotrSH; const rotrSL = (h, l, s) => h << 32 - s | l >>> s; _u64.rotrSL = rotrSL; const rotrBH = (h, l, s) => h << 64 - s | l >>> s - 32; _u64.rotrBH = rotrBH; const rotrBL = (h, l, s) => h >>> s - 32 | l << 64 - s; _u64.rotrBL = rotrBL; const rotr32H = (_h, l) => l; _u64.rotr32H = rotr32H; const rotr32L = (h, _l) => h; _u64.rotr32L = rotr32L; const rotlSH = (h, l, s) => h << s | l >>> 32 - s; _u64.rotlSH = rotlSH; const rotlSL = (h, l, s) => l << s | h >>> 32 - s; _u64.rotlSL = rotlSL; const rotlBH = (h, l, s) => l << s - 32 | h >>> 64 - s; _u64.rotlBH = rotlBH; const rotlBL = (h, l, s) => h << s - 32 | l >>> 64 - s; _u64.rotlBL = rotlBL; function add(Ah, Al, Bh, Bl) { const l = (Al >>> 0) + (Bl >>> 0); return { h: Ah + Bh + (l / 2 ** 32 | 0) | 0, l: l | 0 }; } const add3L = (Al, Bl, Cl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0); _u64.add3L = add3L; const add3H = (low, Ah, Bh, Ch) => Ah + Bh + Ch + (low / 2 ** 32 | 0) | 0; _u64.add3H = add3H; const add4L = (Al, Bl, Cl, Dl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0); _u64.add4L = add4L; const add4H = (low, Ah, Bh, Ch, Dh) => Ah + Bh + Ch + Dh + (low / 2 ** 32 | 0) | 0; _u64.add4H = add4H; const add5L = (Al, Bl, Cl, Dl, El) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0) + (El >>> 0); _u64.add5L = add5L; const add5H = (low, Ah, Bh, Ch, Dh, Eh) => Ah + Bh + Ch + Dh + Eh + (low / 2 ** 32 | 0) | 0; _u64.add5H = add5H; const u64 = { fromBig, split, toBig, shrSH, shrSL, rotrSH, rotrSL, rotrBH, rotrBL, rotr32H, rotr32L, rotlSH, rotlSL, rotlBH, rotlBL, add, add3L, add3H, add4L, add4H, add5H, add5L }; _u64.default = u64; return _u64; } var hasRequiredSha2; function requireSha2() { if (hasRequiredSha2) return sha2; hasRequiredSha2 = 1; Object.defineProperty(sha2, "__esModule", { value: true }); sha2.sha512_224 = sha2.sha512_256 = sha2.sha384 = sha2.sha512 = sha2.sha224 = sha2.sha256 = sha2.SHA512_256 = sha2.SHA512_224 = sha2.SHA384 = sha2.SHA512 = sha2.SHA224 = sha2.SHA256 = void 0; const _md_ts_1 = /* @__PURE__ */ require_md(); const u64 = /* @__PURE__ */ require_u64(); const utils_ts_1 = /* @__PURE__ */ requireUtils(); const SHA256_K = /* @__PURE__ */ Uint32Array.from([ 1116352408, 1899447441, 3049323471, 3921009573, 961987163, 1508970993, 2453635748, 2870763221, 3624381080, 310598401, 607225278, 1426881987, 1925078388, 2162078206, 2614888103, 3248222580, 3835390401, 4022224774, 264347078, 604807628, 770255983, 1249150122, 1555081692, 1996064986, 2554220882, 2821834349, 2952996808, 3210313671, 3336571891, 3584528711, 113926993, 338241895, 666307205, 773529912, 1294757372, 1396182291, 1695183700, 1986661051, 2177026350, 2456956037, 2730485921, 2820302411, 3259730800, 3345764771, 3516065817, 3600352804, 4094571909, 275423344, 430227734, 506948616, 659060556, 883997877, 958139571, 1322822218, 1537002063, 1747873779, 1955562222, 2024104815, 2227730452, 2361852424, 2428436474, 2756734187, 3204031479, 3329325298 ]); const SHA256_W = /* @__PURE__ */ new Uint32Array(64); class SHA256 extends _md_ts_1.HashMD { constructor(outputLen = 32) { super(64, outputLen, 8, false); this.A = _md_ts_1.SHA256_IV[0] | 0; this.B = _md_ts_1.SHA256_IV[1] | 0; this.C = _md_ts_1.SHA256_IV[2] | 0; this.D = _md_ts_1.SHA256_IV[3] | 0; this.E = _md_ts_1.SHA256_IV[4] | 0; this.F = _md_ts_1.SHA256_IV[5] | 0; this.G = _md_ts_1.SHA256_IV[6] | 0; this.H = _md_ts_1.SHA256_IV[7] | 0; } get() { const { A, B, C, D, E, F, G, H } = this; return [A, B, C, D, E, F, G, H]; } // prettier-ignore set(A, B, C, D, E, F, G, H) { this.A = A | 0; this.B = B | 0; this.C = C | 0; this.D = D | 0; this.E = E | 0; this.F = F | 0; this.G = G | 0; this.H = H | 0; } process(view, offset) { for (let i = 0; i < 16; i++, offset += 4) SHA256_W[i] = view.getUint32(offset, false); for (let i = 16; i < 64; i++) { const W15 = SHA256_W[i - 15]; const W2 = SHA256_W[i - 2]; const s0 = (0, utils_ts_1.rotr)(W15, 7) ^ (0, utils_ts_1.rotr)(W15, 18) ^ W15 >>> 3; const s1 = (0, utils_ts_1.rotr)(W2, 17) ^ (0, utils_ts_1.rotr)(W2, 19) ^ W2 >>> 10; SHA256_W[i] = s1 + SHA256_W[i - 7] + s0 + SHA256_W[i - 16] | 0; } let { A, B, C, D, E, F, G, H } = this; for (let i = 0; i < 64; i++) { const sigma1 = (0, utils_ts_1.rotr)(E, 6) ^ (0, utils_ts_1.rotr)(E, 11) ^ (0, utils_ts_1.rotr)(E, 25); const T1 = H + sigma1 + (0, _md_ts_1.Chi)(E, F, G) + SHA256_K[i] + SHA256_W[i] | 0; const sigma0 = (0, utils_ts_1.rotr)(A, 2) ^ (0, utils_ts_1.rotr)(A, 13) ^ (0, utils_ts_1.rotr)(A, 22); const T2 = sigma0 + (0, _md_ts_1.Maj)(A, B, C) | 0; H = G; G = F; F = E; E = D + T1 | 0; D = C; C = B; B = A; A = T1 + T2 | 0; } A = A + this.A | 0; B = B + this.B | 0; C = C + this.C | 0; D = D + this.D | 0; E = E + this.E | 0; F = F + this.F | 0; G = G + this.G | 0; H = H + this.H | 0; this.set(A, B, C, D, E, F, G, H); } roundClean() { (0, utils_ts_1.clean)(SHA256_W); } destroy() { this.set(0, 0, 0, 0, 0, 0, 0, 0); (0, utils_ts_1.clean)(this.buffer); } } sha2.SHA256 = SHA256; class SHA224 extends SHA256 { constructor() { super(28); this.A = _md_ts_1.SHA224_IV[0] | 0; this.B = _md_ts_1.SHA224_IV[1] | 0; this.C = _md_ts_1.SHA224_IV[2] | 0; this.D = _md_ts_1.SHA224_IV[3] | 0; this.E = _md_ts_1.SHA224_IV[4] | 0; this.F = _md_ts_1.SHA224_IV[5] | 0; this.G = _md_ts_1.SHA224_IV[6] | 0; this.H = _md_ts_1.SHA224_IV[7] | 0; } } sha2.SHA224 = SHA224; const K512 = /* @__PURE__ */ (() => u64.split([ "0x428a2f98d728ae22", "0x7137449123ef65cd", "0xb5c0fbcfec4d3b2f", "0xe9b5dba58189dbbc", "0x3956c25bf348b538", "0x59f111f1b605d019", "0x923f82a4af194f9b", "0xab1c5ed5da6d8118", "0xd807aa98a3030242", "0x12835b0145706fbe", "0x243185be4ee4b28c", "0x550c7dc3d5ffb4e2", "0x72be5d74f27b896f", "0x80deb1fe3b1696b1", "0x9bdc06a725c71235", "0xc19bf174cf692694", "0xe49b69c19ef14ad2", "0xefbe4786384f25e3", "0x0fc19dc68b8cd5b5", "0x240ca1cc77ac9c65", "0x2de92c6f592b0275", "0x4a7484aa6ea6e483", "0x5cb0a9dcbd41fbd4", "0x76f988da831153b5", "0x983e5152ee66dfab", "0xa831c66d2db43210", "0xb00327c898fb213f", "0xbf597fc7beef0ee4", "0xc6e00bf33da88fc2", "0xd5a79147930aa725", "0x06ca6351e003826f", "0x142929670a0e6e70", "0x27b70a8546d22ffc", "0x2e1b21385c26c926", "0x4d2c6dfc5ac42aed", "0x53380d139d95b3df", "0x650a73548baf63de", "0x766a0abb3c77b2a8", "0x81c2c92e47edaee6", "0x92722c851482353b", "0xa2bfe8a14cf10364", "0xa81a664bbc423001", "0xc24b8b70d0f89791", "0xc76c51a30654be30", "0xd192e819d6ef5218", "0xd69906245565a910", "0xf40e35855771202a", "0x106aa07032bbd1b8", "0x19a4c116b8d2d0c8", "0x1e376c085141ab53", "0x2748774cdf8eeb99", "0x34b0bcb5e19b48a8", "0x391c0cb3c5c95a63", "0x4ed8aa4ae3418acb", "0x5b9cca4f7763e373", "0x682e6ff3d6b2b8a3", "0x748f82ee5defb2fc", "0x78a5636f43172f60", "0x84c87814a1f0ab72", "0x8cc702081a6439ec", "0x90befffa23631e28", "0xa4506cebde82bde9", "0xbef9a3f7b2c67915", "0xc67178f2e372532b", "0xca273eceea26619c", "0xd186b8c721c0c207", "0xeada7dd6cde0eb1e", "0xf57d4f7fee6ed178", "0x06f067aa72176fba", "0x0a637dc5a2c898a6", "0x113f9804bef90dae", "0x1b710b35131c471b", "0x28db77f523047d84", "0x32caab7b40c72493", "0x3c9ebe0a15c9bebc", "0x431d67c49c100d4c", "0x4cc5d4becb3e42b6", "0x597f299cfc657e2a", "0x5fcb6fab3ad6faec", "0x6c44198c4a475817" ].map((n) => BigInt(n))))(); const SHA512_Kh = /* @__PURE__ */ (() => K512[0])(); const SHA512_Kl = /* @__PURE__ */ (() => K512[1])(); const SHA512_W_H = /* @__PURE__ */ new Uint32Array(80); const SHA512_W_L = /* @__PURE__ */ new Uint32Array(80); class SHA512 extends _md_ts_1.HashMD { constructor(outputLen = 64) { super(128, outputLen, 16, false); this.Ah = _md_ts_1.SHA512_IV[0] | 0; this.Al = _md_ts_1.SHA512_IV[1] | 0; this.Bh = _md_ts_1.SHA512_IV[2] | 0; this.Bl = _md_ts_1.SHA512_IV[3] | 0; this.Ch = _md_ts_1.SHA512_IV[4] | 0; this.Cl = _md_ts_1.SHA512_IV[5] | 0; this.Dh = _md_ts_1.SHA512_IV[6] | 0; this.Dl = _md_ts_1.SHA512_IV[7] | 0; this.Eh = _md_ts_1.SHA512_IV[8] | 0; this.El = _md_ts_1.SHA512_IV[9] | 0; this.Fh = _md_ts_1.SHA512_IV[10] | 0; this.Fl = _md_ts_1.SHA512_IV[11] | 0; this.Gh = _md_ts_1.SHA512_IV[12] | 0; this.Gl = _md_ts_1.SHA512_IV[13] | 0; this.Hh = _md_ts_1.SHA512_IV[14] | 0; this.Hl = _md_ts_1.SHA512_IV[15] | 0; } // prettier-ignore get() { const { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this; return [Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl]; } // prettier-ignore set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl) { this.Ah = Ah | 0; this.Al = Al | 0; this.Bh = Bh | 0; this.Bl = Bl | 0; this.Ch = Ch | 0; this.Cl = Cl | 0; this.Dh = Dh | 0; this.Dl = Dl | 0; this.Eh = Eh | 0; this.El = El | 0; this.Fh = Fh | 0; this.Fl = Fl | 0; this.Gh = Gh | 0; this.Gl = Gl | 0; this.Hh = Hh | 0; this.Hl = Hl | 0; } process(view, offset) { for (let i = 0; i < 16; i++, offset += 4) { SHA512_W_H[i] = view.getUint32(offset); SHA512_W_L[i] = view.getUint32(offset += 4); } for (let i = 16; i < 80; i++) { const W15h = SHA512_W_H[i - 15] | 0; const W15l = SHA512_W_L[i - 15] | 0; const s0h = u64.rotrSH(W15h, W15l, 1) ^ u64.rotrSH(W15h, W15l, 8) ^ u64.shrSH(W15h, W15l, 7); const s0l = u64.rotrSL(W15h, W15l, 1) ^ u64.rotrSL(W15h, W15l, 8) ^ u64.shrSL(W15h, W15l, 7); const W2h = SHA512_W_H[i - 2] | 0; const W2l = SHA512_W_L[i - 2] | 0; const s1h = u64.rotrSH(W2h, W2l, 19) ^ u64.rotrBH(W2h, W2l, 61) ^ u64.shrSH(W2h, W2l, 6); const s1l = u64.rotrSL(W2h, W2l, 19) ^ u64.rotrBL(W2h, W2l, 61) ^ u64.shrSL(W2h, W2l, 6); const SUMl = u64.add4L(s0l, s1l, SHA512_W_L[i - 7], SHA512_W_L[i - 16]); const SUMh = u64.add4H(SUMl, s0h, s1h, SHA512_W_H[i - 7], SHA512_W_H[i - 16]); SHA512_W_H[i] = SUMh | 0; SHA512_W_L[i] = SUMl | 0; } let { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this; for (let i = 0; i < 80; i++) { const sigma1h = u64.rotrSH(Eh, El, 14) ^ u64.rotrSH(Eh, El, 18) ^ u64.rotrBH(Eh, El, 41); const sigma1l = u64.rotrSL(Eh, El, 14) ^ u64.rotrSL(Eh, El, 18) ^ u64.rotrBL(Eh, El, 41); const CHIh = Eh & Fh ^ ~Eh & Gh; const CHIl = El & Fl ^ ~El & Gl; const T1ll = u64.add5L(Hl, sigma1l, CHIl, SHA512_Kl[i], SHA512_W_L[i]); const T1h = u64.add5H(T1ll, Hh, sigma1h, CHIh, SHA512_Kh[i], SHA512_W_H[i]); const T1l = T1ll | 0; const sigma0h = u64.rotrSH(Ah, Al, 28) ^ u64.rotrBH(Ah, Al, 34) ^ u64.rotrBH(Ah, Al, 39); const sigma0l = u64.rotrSL(Ah, Al, 28) ^ u64.rotrBL(Ah, Al, 34) ^ u64.rotrBL(Ah, Al, 39); const MAJh = Ah & Bh ^ Ah & Ch ^ Bh & Ch; const MAJl = Al & Bl ^ Al & Cl ^ Bl & Cl; Hh = Gh | 0; Hl = Gl | 0; Gh = Fh | 0; Gl = Fl | 0; Fh = Eh | 0; Fl = El | 0; ({ h: Eh, l: El } = u64.add(Dh | 0, Dl | 0, T1h | 0, T1l | 0)); Dh = Ch | 0; Dl = Cl | 0; Ch = Bh | 0; Cl = Bl | 0; Bh = Ah | 0; Bl = Al | 0; const All = u64.add3L(T1l, sigma0l, MAJl); Ah = u64.add3H(All, T1h, sigma0h, MAJh); Al = All | 0; } ({ h: Ah, l: Al } = u64.add(this.Ah | 0, this.Al | 0, Ah | 0, Al | 0)); ({ h: Bh, l: Bl } = u64.add(this.Bh | 0, this.Bl | 0, Bh | 0, Bl | 0)); ({ h: Ch, l: Cl } = u64.add(this.Ch | 0, this.Cl | 0, Ch | 0, Cl | 0)); ({ h: Dh, l: Dl } = u64.add(this.Dh | 0, this.Dl | 0, Dh | 0, Dl | 0)); ({ h: Eh, l: El } = u64.add(this.Eh | 0, this.El | 0, Eh | 0, El | 0)); ({ h: Fh, l: Fl } = u64.add(this.Fh | 0, this.Fl | 0, Fh | 0, Fl | 0)); ({ h: Gh, l: Gl } = u64.add(this.Gh | 0, this.Gl | 0, Gh | 0, Gl | 0)); ({ h: Hh, l: Hl } = u64.add(this.Hh | 0, this.Hl | 0, Hh | 0, Hl | 0)); this.set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl); } roundClean() { (0, utils_ts_1.clean)(SHA512_W_H, SHA512_W_L); } destroy() { (0, utils_ts_1.clean)(this.buffer); this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0); } } sha2.SHA512 = SHA512; class SHA384 extends SHA512 { constructor() { super(48); this.Ah = _md_ts_1.SHA384_IV[0] | 0; this.Al = _md_ts_1.SHA384_IV[1] | 0; this.Bh = _md_ts_1.SHA384_IV[2] | 0; this.Bl = _md_ts_1.SHA384_IV[3] | 0; this.Ch = _md_ts_1.SHA384_IV[4] | 0; this.Cl = _md_ts_1.SHA384_IV[5] | 0; this.Dh = _md_ts_1.SHA384_IV[6] | 0; this.Dl = _md_ts_1.SHA384_IV[7] | 0; this.Eh = _md_ts_1.SHA384_IV[8] | 0; this.El = _md_ts_1.SHA384_IV[9] | 0; this.Fh = _md_ts_1.SHA384_IV[10] | 0; this.Fl = _md_ts_1.SHA384_IV[11] | 0; this.Gh = _md_ts_1.SHA384_IV[12] | 0; this.Gl = _md_ts_1.SHA384_IV[13] | 0; this.Hh = _md_ts_1.SHA384_IV[14] | 0; this.Hl = _md_ts_1.SHA384_IV[15] | 0; } } sha2.SHA384 = SHA384; const T224_IV = /* @__PURE__ */ Uint32Array.from([ 2352822216, 424955298, 1944164710, 2312950998, 502970286, 855612546, 1738396948, 1479516111, 258812777, 2077511080, 2011393907, 79989058, 1067287976, 1780299464, 286451373, 2446758561 ]); const T256_IV = /* @__PURE__ */ Uint32Array.from([ 573645204, 4230739756, 2673172387, 3360449730, 596883563, 1867755857, 2520282905, 1497426621, 2519219938, 2827943907, 3193839141, 1401305490, 721525244, 746961066, 246885852, 2177182882 ]); class SHA512_224 extends SHA512 { constructor() { super(28); this.Ah = T224_IV[0] | 0; this.Al = T224_IV[1] | 0; this.Bh = T224_IV[2] | 0; this.Bl = T224_IV[3] | 0; this.Ch = T224_IV[4] | 0; this.Cl = T224_IV[5] | 0; this.Dh = T224_IV[6] | 0; this.Dl = T224_IV[7] | 0; this.Eh = T224_IV[8] | 0; this.El = T224_IV[9] | 0; this.Fh = T224_IV[10] | 0; this.Fl = T224_IV[11] | 0; this.Gh = T224_IV[12] | 0; this.Gl = T224_IV[13] | 0; this.Hh = T224_IV[14] | 0; this.Hl = T224_IV[15] | 0; } } sha2.SHA512_224 = SHA512_224; class SHA512_256 extends SHA512 { constructor() { super(32); this.Ah = T256_IV[0] | 0; this.Al = T256_IV[1] | 0; this.Bh = T256_IV[2] | 0; this.Bl = T256_IV[3] | 0; this.Ch = T256_IV[4] | 0; this.Cl = T256_IV[5] | 0; this.Dh = T256_IV[6] | 0; this.Dl = T256_IV[7] | 0; this.Eh = T256_IV[8] | 0; this.El = T256_IV[9] | 0; this.Fh = T256_IV[10] | 0; this.Fl = T256_IV[11] | 0; this.Gh = T256_IV[12] | 0; this.Gl = T256_IV[13] | 0; this.Hh = T256_IV[14] | 0; this.Hl = T256_IV[15] | 0; } } sha2.SHA512_256 = SHA512_256; sha2.sha256 = (0, utils_ts_1.createHasher)(() => new SHA256()); sha2.sha224 = (0, utils_ts_1.createHasher)(() => new SHA224()); sha2.sha512 = (0, utils_ts_1.createHasher)(() => new SHA512()); sha2.sha384 = (0, utils_ts_1.createHasher)(() => new SHA384()); sha2.sha512_256 = (0, utils_ts_1.createHasher)(() => new SHA512_256()); sha2.sha512_224 = (0, utils_ts_1.createHasher)(() => new SHA512_224()); return sha2; } var hasRequiredSha256$1; function requireSha256$1() { if (hasRequiredSha256$1) return sha256$2; hasRequiredSha256$1 = 1; Object.defineProperty(sha256$2, "__esModule", { value: true }); sha256$2.sha224 = sha256$2.SHA224 = sha256$2.sha256 = sha256$2.SHA256 = void 0; const sha2_ts_1 = /* @__PURE__ */ requireSha2(); sha256$2.SHA256 = sha2_ts_1.SHA256; sha256$2.sha256 = sha2_ts_1.sha256; sha256$2.SHA224 = sha2_ts_1.SHA224; sha256$2.sha224 = sha2_ts_1.sha224; return sha256$2; } var src$1; var hasRequiredSrc; function requireSrc() { if (hasRequiredSrc) return src$1; hasRequiredSrc = 1; function base2(ALPHABET) { if (ALPHABET.length >= 255) { throw new TypeError("Alphabet too long"); } var BASE_MAP = new Uint8Array(256); for (var j = 0; j < BASE_MAP.length; j++) { BASE_MAP[j] = 255; } for (var i = 0; i < ALPHABET.length; i++) { var x = ALPHABET.charAt(i); var xc = x.charCodeAt(0); if (BASE_MAP[xc] !== 255) { throw new TypeError(x + " is ambiguous"); } BASE_MAP[xc] = i; } var BASE = ALPHABET.length; var LEADER = ALPHABET.charAt(0); var FACTOR = Math.log(BASE) / Math.log(256); var iFACTOR = Math.log(256) / Math.log(BASE); function encode(source) { if (source instanceof Uint8Array) ; else if (ArrayBuffer.isView(source)) { source = new Uint8Array(source.buffer, source.byteOffset, source.byteLength); } else if (Array.isArray(source)) { source = Uint8Array.from(source); } if (!(source instanceof Uint8Array)) { throw new TypeError("Expected Uint8Array"); } if (source.length === 0) { return ""; } var zeroes = 0; var length = 0; var pbegin = 0; var pend = source.length; while (pbegin !== pend && source[pbegin] === 0) { pbegin++; zeroes++; } var size = (pend - pbegin) * iFACTOR + 1 >>> 0; var b58 = new Uint8Array(size); while (pbegin !== pend) { var carry = source[pbegin]; var i2 = 0; for (var it1 = size - 1; (carry !== 0 || i2 < length) && it1 !== -1; it1--, i2++) { carry += 256 * b58[it1] >>> 0; b58[it1] = carry % BASE >>> 0; carry = carry / BASE >>> 0; } if (carry !== 0) { throw new Error("Non-zero carry"); } length = i2; pbegin++; } var it2 = size - length; while (it2 !== size && b58[it2] === 0) { it2++; } var str = LEADER.repeat(zeroes); for (; it2 < size; ++it2) { str += ALPHABET.charAt(b58[it2]); } return str; } function decodeUnsafe(source) { if (typeof source !== "string") { throw new TypeError("Expected String"); } if (source.length === 0) { return new Uint8Array(); } var psz = 0; var zeroes = 0; var length = 0; while (source[psz] === LEADER) { zeroes++; psz++; } var size = (source.length - psz) * FACTOR + 1 >>> 0; var b256 = new Uint8Array(size); while (source[psz]) { var charCode = source.charCodeAt(psz); if (charCode > 255) { return; } var carry = BASE_MAP[charCode]; if (carry === 255) { return; } var i2 = 0; for (var it3 = size - 1; (carry !== 0 || i2 < length) && it3 !== -1; it3--, i2++) { carry += BASE * b256[it3] >>> 0; b256[it3] = carry % 256 >>> 0; carry = carry / 256 >>> 0; } if (carry !== 0) { throw new Error("Non-zero carry"); } length = i2; psz++; } var it4 = size - length; while (it4 !== size && b256[it4] === 0) { it4++; } var vch = new Uint8Array(zeroes + (size - it4)); var j2 = zeroes; while (it4 !== size) { vch[j2++] = b256[it4++]; } return vch; } function decode(string) { var buffer = decodeUnsafe(string); if (buffer) { return buffer; } throw new Error("Non-base" + BASE + " character"); } return { encode, decodeUnsafe, decode }; } src$1 = base2; return src$1; } var bs58; var hasRequiredBs58; function requireBs58() { if (hasRequiredBs58) return bs58; hasRequiredBs58 = 1; const basex = requireSrc(); const ALPHABET = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"; bs58 = basex(ALPHABET); return bs58; } var base; var hasRequiredBase; function requireBase() { if (hasRequiredBase) return base; hasRequiredBase = 1; var base58 = requireBs58(); base = function(checksumFn) { function encode(payload) { var payloadU8 = Uint8Array.from(payload); var checksum = checksumFn(payloadU8); var length = payloadU8.length + 4; var both = new Uint8Array(length); both.set(payloadU8, 0); both.set(checksum.subarray(0, 4), payloadU8.length); return base58.encode(both, length); } function decodeRaw(buffer) { var payload = buffer.slice(0, -4); var checksum = buffer.slice(-4); var newChecksum = checksumFn(payload); if (checksum[0] ^ newChecksum[0] | checksum[1] ^ newChecksum[1] | checksum[2] ^ newChecksum[2] | checksum[3] ^ newChecksum[3]) return; return payload; } function decodeUnsafe(string) { var buffer = base58.decodeUnsafe(string); if (!buffer) return; return decodeRaw(buffer); } function decode(string) { var buffer = base58.decode(string); var payload = decodeRaw(buffer); if (!payload) throw new Error("Invalid checksum"); return payload; } return { encode, decode, decodeUnsafe }; }; return base; } var bs58check$1; var hasRequiredBs58check; function requireBs58check() { if (hasRequiredBs58check) return bs58check$1; hasRequiredBs58check = 1; var { sha256: sha2562 } = /* @__PURE__ */ requireSha256$1(); var bs58checkBase = requireBase(); function sha256x2(buffer) { return sha2562(sha2562(buffer)); } bs58check$1 = bs58checkBase(sha256x2); return bs58check$1; } var bs58checkExports = requireBs58check(); const bs58check = /* @__PURE__ */ getDefaultExportFromCjs(bs58checkExports); const uint8ArrayToHexString = (data) => { return Array.from(data, (byte) => byte.toString(16).padStart(2, "0")).join(""); }; const urlPrefix = "automerge:"; const parseAutomergeUrl = (url) => { const [baseUrl, headsSection, ...rest] = url.split("#"); if (rest.length > 0) { throw new Error("Invalid URL: contains multiple heads sections"); } const regex = new RegExp(`^${urlPrefix}(\\w+)$`); const [, docMatch] = baseUrl.match(regex) || []; const documentId = docMatch; const binaryDocumentId = documentIdToBinary(documentId); if (!binaryDocumentId) throw new Error("Invalid document URL: " + url); if (headsSection === void 0) return { binaryDocumentId, documentId }; const heads = headsSection === "" ? [] : headsSection.split("|"); const hexHeads = heads.map((head) => { try { return uint8ArrayToHexString(bs58check.decode(head)); } catch (e) { throw new Error(`Invalid head in URL: ${head}`); } }); return { binaryDocumentId, hexHeads, documentId, heads }; }; const stringifyAutomergeUrl = (arg) => { if (arg instanceof Uint8Array || typeof arg === "string") { return urlPrefix + (arg instanceof Uint8Array ? binaryToDocumentId(arg) : arg); } const { documentId, heads = void 0 } = arg; if (documentId === void 0) throw new Error("Invalid documentId: " + documentId); const encodedDocumentId = documentId instanceof Uint8Array ? binaryToDocumentId(documentId) : documentId; let url = `${urlPrefix}${encodedDocumentId}`; if (heads !== void 0) { heads.forEach((head) => { try { bs58check.decode(head); } catch (e) { throw new Error(`Invalid head: ${head}`); } }); url += "#" + heads.join("|"); } return url; }; const anyDocumentIdToAutomergeUrl = (id) => isValidAutomergeUrl(id) ? id : isValidDocumentId(id) ? stringifyAutomergeUrl({ documentId: id }) : isValidUuid(id) ? parseLegacyUUID(id) : void 0; const isValidAutomergeUrl = (str) => { if (typeof str !== "string" || !str || !str.startsWith(urlPrefix)) return false; try { const { documentId, heads } = parseAutomergeUrl(str); if (!isValidDocumentId(documentId)) return false; if (heads && !heads.every((head) => { try { bs58check.decode(head); return true; } catch { return false; } })) return false; return true; } catch { return false; } }; const isValidDocumentId = (str) => { if (typeof str !== "string") return false; const binaryDocumentID = documentIdToBinary(str); return binaryDocumentID !== void 0; }; const isValidUuid = (str) => typeof str === "string" && validate(str); const documentIdToBinary = (docId) => bs58check.decodeUnsafe(docId); const binaryToDocumentId = (docId) => bs58check.encode(docId); const parseLegacyUUID = (str) => { if (!validate(str)) return void 0; const documentId = parse(str); return stringifyAutomergeUrl({ documentId }); }; const wrapperCache = /* @__PURE__ */ new Map(); function useDocHandle(id, { suspense } = { suspense: false }) { var _a2; const repo = useRepo(); const controllerRef = reactExports.useRef(); const [handle, setHandle] = reactExports.useState(); let currentHandle = ( // make sure the handle matches the id id && handle && handle.url === anyDocumentIdToAutomergeUrl(id) ? handle : void 0 ); if (id && !currentHandle) { const progress = repo.findWithProgress(id); if (progress.state === "ready") { currentHandle = progress.handle; } } let wrapper = id ? wrapperCache.get(id) : void 0; if (!wrapper && id) { (_a2 = controllerRef.current) == null ? void 0 : _a2.abort(); controllerRef.current = new AbortController(); const promise = repo.find(id, { signal: controllerRef.current.signal }); wrapper = wrapPromise(promise); wrapperCache.set(id, wrapper); } reactExports.useEffect(() => { if (currentHandle || suspense || !wrapper) { return; } wrapper.promise.then((handle2) => { setHandle(handle2); }).catch(() => { setHandle(void 0); }); }, [currentHandle, suspense, wrapper]); if (currentHandle || !suspense || !wrapper) { return currentHandle; } return wrapper.read(); } function useDocument(id, params = { suspense: false }) { const handle = useDocHandle(id, params); const [doc, setDoc] = reactExports.useState(() => handle == null ? void 0 : handle.doc()); const [deleteError, setDeleteError] = reactExports.useState(); reactExports.useEffect(() => { setDoc(handle == null ? void 0 : handle.doc()); }, [handle]); reactExports.useEffect(() => { if (!handle) { return; } const onChange = () => setDoc(handle.doc()); const onDelete = () => { setDeleteError(new Error(`Document ${id} was deleted`)); }; handle.on("change", onChange); handle.on("delete", onDelete); return () => { handle.removeListener("change", onChange); handle.removeListener("delete", onDelete); }; }, [handle, id]); const changeDoc = reactExports.useCallback( (changeFn, options) => { handle.change(changeFn, options); }, [handle] ); if (deleteError) { throw deleteError; } if (!doc) { return [void 0, () => { }]; } return [doc, changeDoc]; } var eventemitter3 = { exports: {} }; var hasRequiredEventemitter3; function requireEventemitter3() { if (hasRequiredEventemitter3) return eventemitter3.exports; hasRequiredEventemitter3 = 1; (function(module) { var has = Object.prototype.hasOwnProperty, prefix = "~"; function Events() { } if (Object.create) { Events.prototype = /* @__PURE__ */ Object.create(null); if (!new Events().__proto__) prefix = false; } function EE(fn, context, once) { this.fn = fn; this.context = context; this.once = once || false; } function addListener(emitter, event, fn, context, once) { if (typeof fn !== "function") { throw new TypeError("The listener must be a function"); } var listener = new EE(fn, context || emitter, once), evt = prefix ? prefix + event : event; if (!emitter._events[evt]) emitter._events[evt] = listener, emitter._eventsCount++; else if (!emitter._events[evt].fn) emitter._events[evt].push(listener); else emitter._events[evt] = [emitter._events[evt], listener]; return emitter; } function clearEvent(emitter, evt) { if (--emitter._eventsCount === 0) emitter._events = new Events(); else delete emitter._events[evt]; } function EventEmitter2() { this._events = new Events(); this._eventsCount = 0; } EventEmitter2.prototype.eventNames = function eventNames() { var names = [], events, name; if (this._eventsCount === 0) return names; for (name in events = this._events) { if (has.call(events, name)) names.push(prefix ? name.slice(1) : name); } if (Object.getOwnPropertySymbols) { return names.concat(Object.getOwnPropertySymbols(events)); } return names; }; EventEmitter2.prototype.listeners = function listeners(event) { var evt = prefix ? prefix + event : event, handlers = this._events[evt]; if (!handlers) return []; if (handlers.fn) return [handlers.fn]; for (var i = 0, l = handlers.length, ee = new Array(l); i < l; i++) { ee[i] = handlers[i].fn; } return ee; }; EventEmitter2.prototype.listenerCount = function listenerCount(event) { var evt = prefix ? prefix + event : event, listeners = this._events[evt]; if (!listeners) return 0; if (listeners.fn) return 1; return listeners.length; }; EventEmitter2.prototype.emit = function emit(event, a1, a2, a3, a4, a5) { var evt = prefix ? prefix + event : event; if (!this._events[evt]) return false; var listeners = this._events[evt], len = arguments.length, args, i; if (listeners.fn) { if (listeners.once) this.removeListener(event, listeners.fn, void 0, true); switch (len) { case 1: return listeners.fn.call(listeners.context), true; case 2: return listeners.fn.call(listeners.context, a1), true; case 3: return listeners.fn.call(listeners.context, a1, a2), true; case 4: return listeners.fn.call(listeners.context, a1, a2, a3), true; case 5: return listeners.fn.call(listeners.context, a1, a2, a3, a4), true; case 6: return listeners.fn.call(listeners.context, a1, a2, a3, a4, a5), true; } for (i = 1, args = new Array(len - 1); i < len; i++) { args[i - 1] = arguments[i]; } listeners.fn.apply(listeners.context, args); } else { var length = listeners.length, j; for (i = 0; i < length; i++) { if (listeners[i].once) this.removeListener(event, listeners[i].fn, void 0, true); switch (len) { case 1: listeners[i].fn.call(listeners[i].context); break; case 2: listeners[i].fn.call(listeners[i].context, a1); break; case 3: listeners[i].fn.call(listeners[i].context, a1, a2); break; case 4: listeners[i].fn.call(listeners[i].context, a1, a2, a3); break; default: if (!args) for (j = 1, args = new Array(len - 1); j < len; j++) { args[j - 1] = arguments[j]; } listeners[i].fn.apply(listeners[i].context, args); } } } return true; }; EventEmitter2.prototype.on = function on(event, fn, context) { return addListener(this, event, fn, context, false); }; EventEmitter2.prototype.once = function once(event, fn, context) { return addListener(this, event, fn, context, true); }; EventEmitter2.prototype.removeListener = function removeListener(event, fn, context, once) { var evt = prefix ? prefix + event : event; if (!this._events[evt]) return this; if (!fn) { clearEvent(this, evt); return this; } var listeners = this._events[evt]; if (listeners.fn) { if (listeners.fn === fn && (!once || listeners.once) && (!context || listeners.context === context)) { clearEvent(this, evt); } } else { for (var i = 0, events = [], length = listeners.length; i < length; i++) { if (listeners[i].fn !== fn || once && !listeners[i].once || context && listeners[i].context !== context) { events.push(listeners[i]); } } if (events.length) this._events[evt] = events.length === 1 ? events[0] : events; else clearEvent(this, evt); } return this; }; EventEmitter2.prototype.removeAllListeners = function removeAllListeners(event) { var evt; if (event) { evt = prefix ? prefix + event : event; if (this._events[evt]) clearEvent(this, evt); } else { this._events = new Events(); this._eventsCount = 0; } return this; }; EventEmitter2.prototype.off = EventEmitter2.prototype.removeListener; EventEmitter2.prototype.addListener = EventEmitter2.prototype.on; EventEmitter2.prefixed = prefix; EventEmitter2.EventEmitter = EventEmitter2; { module.exports = EventEmitter2; } })(eventemitter3); return eventemitter3.exports; } var eventemitter3Exports = requireEventemitter3(); const EventEmitter = /* @__PURE__ */ getDefaultExportFromCjs(eventemitter3Exports); new EventEmitter(); const STATE = /* @__PURE__ */ Symbol.for("_am_meta"); const TRACE = /* @__PURE__ */ Symbol.for("_am_trace"); const OBJECT_ID = /* @__PURE__ */ Symbol.for("_am_objectId"); const IS_PROXY = /* @__PURE__ */ Symbol.for("_am_isProxy"); const CLEAR_CACHE = /* @__PURE__ */ Symbol.for("_am_clearCache"); const UINT = /* @__PURE__ */ Symbol.for("_am_uint"); const INT = /* @__PURE__ */ Symbol.for("_am_int"); const F64 = /* @__PURE__ */ Symbol.for("_am_f64"); const COUNTER = /* @__PURE__ */ Symbol.for("_am_counter"); const IMMUTABLE_STRING = /* @__PURE__ */ Symbol.for("_am_immutableString"); class Counter { constructor(value) { this.value = value || 0; Reflect.defineProperty(this, COUNTER, { value: true }); } /** * A peculiar JavaScript language feature from its early days: if the object * `x` has a `valueOf()` method that returns a number, you can use numerical * operators on the object `x` directly, such as `x + 1` or `x < 4`. * This method is also called when coercing a value to a string by * concatenating it with another string, as in `x + ''`. * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/valueOf */ valueOf() { return this.value; } /** * Returns the counter value as a decimal string. If `x` is a counter object, * this method is called e.g. when you do `['value: ', x].join('')` or when * you use string interpolation: `value: ${x}`. */ toString() { return this.valueOf().toString(); } /** * Returns the counter value, so that a JSON serialization of an Automerge * document represents the counter simply as an integer. */ toJSON() { return this.value; } /** * Increases the value of the counter by `delta`. If `delta` is not given, * increases the value of the counter by 1. * * Will throw an error if used outside of a change callback. */ increment(_delta) { throw new Error("Counters should not be incremented outside of a change callback"); } /** * Decreases the value of the counter by `delta`. If `delta` is not given, * decreases the value of the counter by 1. * * Will throw an error if used outside of a change callback. */ decrement(_delta) { throw new Error("Counters should not be decremented outside of a change callback"); } } class WriteableCounter extends Counter { constructor(value, context, path, objectId, key) { super(value); this.context = context; this.path = path; this.objectId = objectId; this.key = key; } /** * Increases the value of the counter by `delta`. If `delta` is not given, * increases the value of the counter by 1. */ increment(delta) { delta = typeof delta === "number" ? delta : 1; this.context.increment(this.objectId, this.key, delta); this.value += delta; return this.value; } /** * Decreases the value of the counter by `delta`. If `delta` is not given, * decreases the value of the counter by 1. */ decrement(delta) { return this.increment(typeof delta === "number" ? -delta : -1); } } function getWriteableCounter(value, context, path, objectId, key) { return new WriteableCounter(value, context, path, objectId, key); } var _a; class ImmutableString { constructor(val) { this[_a] = true; this.val = val; } /** * Returns the content of the ImmutableString object as a simple string */ toString() { return this.val; } toJSON() { return this.val; } } _a = IMMUTABLE_STRING; function parseListIndex(key) { if (typeof key === "string" && /^[0-9]+$/.test(key)) key = parseInt(key, 10); if (typeof key !== "number") { return key; } if (key < 0 || isNaN(key) || key === Infinity || key === -Infinity) { throw new RangeError("A list index must be positive, but you passed " + key); } return key; } function valueAt(target2, prop) { const { context, objectId, path } = target2; const value = context.getWithType(objectId, prop); if (value === null) { return; } const datatype = value[0]; const val = value[1]; switch (datatype) { case void 0: return; case "map": return mapProxy(context, val, [...path, prop]); case "list": return listProxy(context, val, [...path, prop]); case "text": return context.text(val); case "str": return new ImmutableString(val); case "uint": return val; case "int": return val; case "f64": return val; case "boolean": return val; case "null": return null; case "bytes": return val; case "timestamp": return val; case "counter": { const counter = getWriteableCounter(val, context, path, objectId, prop); return counter; } default: throw RangeError(`datatype ${datatype} unimplemented`); } } function import_value(value, path, context) { const type = typeof value; switch (type) { case "object": if (value == null) { return [null, "null"]; } else if (value[UINT]) { return [value.value, "uint"]; } else if (value[INT]) { return [value.value, "int"]; } else if (value[F64]) { return [value.value, "f64"]; } else if (value[COUNTER]) { return [value.value, "counter"]; } else if (value instanceof Date) { return [value.getTime(), "timestamp"]; } else if (isImmutableString(value)) { return [value.toString(), "str"]; } else if (value instanceof Uint8Array) { return [value, "bytes"]; } else if (value instanceof Array) { return [value, "list"]; } else if (Object.prototype.toString.call(value) === "[object Object]") { return [value, "map"]; } else if (isSameDocument(value, context)) { throw new RangeError("Cannot create a reference to an existing document object"); } else { throw new RangeError(`Cannot assign unknown object: ${value}`); } case "boolean": return [value, "boolean"]; case "number": if (Number.isInteger(value)) { return [value, "int"]; } else { return [value, "f64"]; } case "string": return [value, "text"]; case "undefined": throw new RangeError([ `Cannot assign undefined value at ${printPath(path)}, `, "because `undefined` is not a valid JSON data type. ", "You might consider setting the property's value to `null`, ", "or using `delete` to remove it altogether." ].join("")); default: throw new RangeError([ `Cannot assign ${type} value at ${printPath(path)}. `, `All JSON primitive datatypes (object, array, string, number, boolean, null) `, `are supported in an Automerge document; ${type} values are not. ` ].join("")); } } function isSameDocument(val, context) { var _b, _c; if (val instanceof Date) { return false; } if (val && ((_c = (_b = val[STATE]) === null || _b === void 0 ? void 0 : _b.handle) === null || _c === void 0 ? void 0 : _c.__wbg_ptr) === context.__wbg_ptr) { return true; } return false; } const MapHandler = { get(target2, key) { const { context, objectId, cache } = target2; if (key === Symbol.toStringTag) { return target2[Symbol.toStringTag]; } if (key === OBJECT_ID) return objectId; if (key === IS_PROXY) return true; if (key === TRACE) return target2.trace; if (key === STATE) return { handle: context }; if (!cache[key]) { cache[key] = valueAt(target2, key); } return cache[key]; }, set(target2, key, val) { const { context, objectId, path } = target2; target2.cache = {}; if (isSameDocument(val, context)) { throw new RangeError("Cannot create a reference to an existing document object"); } if (key === TRACE) { target2.trace = val; return true; } if (key === CLEAR_CACHE) { return true; } const [value, datatype] = import_value(val, [...path, key], context); switch (datatype) { case "list": { const list = context.putObject(objectId, key, []); const proxyList = listProxy(context, list, [...path, key]); for (let i = 0; i < value.length; i++) { proxyList[i] = value[i]; } break; } case "text": { context.putObject(objectId, key, value); break; } case "map": { const map = context.putObject(objectId, key, {}); const proxyMap = mapProxy(context, map, [...path, key]); for (const key2 in value) { proxyMap[key2] = value[key2]; } break; } default: context.put(objectId, key, value, datatype); } return true; }, deleteProperty(target2, key) { const { context, objectId } = target2; target2.cache = {}; context.delete(objectId, key); return true; }, has(target2, key) { const value = this.get(target2, key); return value !== void 0; }, getOwnPropertyDescriptor(target2, key) { const value = this.get(target2, key); if (typeof value !== "undefined") { return { configurable: true, enumerable: true, value }; } }, ownKeys(target2) { const { context, objectId } = target2; const keys = context.keys(objectId); return [...new Set(keys)]; } }; const ListHandler = { get(target2, index) { const { context, objectId } = target2; index = parseListIndex(index); if (index === Symbol.hasInstance) { return (instance) => { return Array.isArray(instance); }; } if (index === Symbol.toStringTag) { return target2[Symbol.toStringTag]; } if (index === OBJECT_ID) return objectId; if (index === IS_PROXY) return true; if (index === TRACE) return target2.trace; if (index === STATE) return { handle: context }; if (index === "length") return context.length(objectId); if (typeof index === "number") { return valueAt(target2, index); } else { return listMethods(target2)[index]; } }, set(target2, index, val) { const { context, objectId, path } = target2; index = parseListIndex(index); if (isSameDocument(val, context)) { throw new RangeError("Cannot create a reference to an existing document object"); } if (index === CLEAR_CACHE) { return true; } if (index === TRACE) { target2.trace = val; return true; } if (typeof index == "string") { throw new RangeError("list index must be a number"); } const [value, datatype] = import_value(val, [...path, index], context); switch (datatype) { case "list": { let list; if (index >= context.length(objectId)) { list = context.insertObject(objectId, index, []); } else { list = context.putObject(objectId, index, []); } const proxyList = listProxy(context, list, [...path, index]); proxyList.splice(0, 0, ...value); break; } case "text": { if (index >= context.length(objectId)) { context.insertObject(objectId, index, value); } else { context.putObject(objectId, index, value); } break; } case "map": { let map; if (index >= context.length(objectId)) { map = context.insertObject(objectId, index, {}); } else { map = context.putObject(objectId, index, {}); } const proxyMap = mapProxy(context, map, [...path, index]); for (const key in value) { proxyMap[key] = value[key]; } break; } default: if (index >= context.length(objectId)) { context.insert(objectId, index, value, datatype); } else { context.put(objectId, index, value, datatype); } } return true; }, deleteProperty(target2, index) { const { context, objectId } = target2; index = parseListIndex(index); const elem = context.get(objectId, index); if (elem != null && elem[0] == "counter") { throw new TypeError("Unsupported operation: deleting a counter from a list"); } context.delete(objectId, index); return true; }, has(target2, index) { const { context, objectId } = target2; index = parseListIndex(index); if (typeof index === "number") { return index < context.length(objectId); } return index === "length"; }, getOwnPropertyDescriptor(target2, index) { const { context, objectId } = target2; if (index === "length") return { writable: true, value: context.length(objectId) }; if (index === OBJECT_ID) return { configurable: false, enumerable: false, value: objectId }; index = parseListIndex(index); const value = valueAt(target2, index); return { configurable: true, enumerable: true, value }; }, getPrototypeOf(target2) { return Object.getPrototypeOf(target2); }, ownKeys() { const keys = []; keys.push("length"); return keys; } }; Object.assign({}, ListHandler, { get(target2, index) { const { context, objectId } = target2; index = parseListIndex(index); if (index === Symbol.hasInstance) { return (instance) => { return Array.isArray(instance); }; } if (index === Symbol.toStringTag) { return target2[Symbol.toStringTag]; } if (index === OBJECT_ID) return objectId; if (index === IS_PROXY) return true; if (index === TRACE) return target2.trace; if (index === STATE) return { handle: context }; if (index === "length") return context.length(objectId); if (typeof index === "number") { return valueAt(target2, index); } else { return textMethods(target2)[index] || listMethods(target2)[index]; } }, getPrototypeOf() { return Object.getPrototypeOf(new Text()); } }); function mapProxy(context, objectId, path) { const target2 = { context, objectId, path: path || [], cache: {} }; const proxied = {}; Object.assign(proxied, target2); const result = new Proxy(proxied, MapHandler); return result; } function listProxy(context, objectId, path) { const target2 = { context, objectId, path: path || [], cache: {} }; const proxied = []; Object.assign(proxied, target2); return new Proxy(proxied, ListHandler); } function listMethods(target2) { const { context, objectId, path } = target2; const methods = { at(index) { return valueAt(target2, index); }, deleteAt(index, numDelete) { if (typeof numDelete === "number") { context.splice(objectId, index, numDelete); } else { context.delete(objectId, index); } return this; }, fill(val, start, end) { const [value, datatype] = import_value(val, [...path, start], context); const length = context.length(objectId); start = parseListIndex(start || 0); end = parseListIndex(end || length); for (let i = start; i < Math.min(end, length); i++) { if (datatype === "list" || datatype === "map") { context.putObject(objectId, i, value); } else if (datatype === "text") { context.putObject(objectId, i, value); } else { context.put(objectId, i, value, datatype); } } return this; }, indexOf(searchElement, start = 0) { const length = context.length(objectId); for (let i = start; i < length; i++) { const valueWithType = context.getWithType(objectId, i); if (!valueWithType) { continue; } const [valType, value] = valueWithType; const isObject = ["map", "list", "text"].includes(valType); if (!isObject) { if (value === searchElement) { return i; } else { continue; } } if (valType === "text" && typeof searchElement === "string") { if (searchElement === valueAt(target2, i)) { return i; } } if (searchElement[OBJECT_ID] === value) { return i; } } return -1; }, insertAt(index, ...values) { this.splice(index, 0, ...values); return this; }, pop() { const length = context.length(objectId); if (length == 0) { return void 0; } const last = valueAt(target2, length - 1); context.delete(objectId, length - 1); return last; }, push(...values) { const len = context.length(objectId); this.splice(len, 0, ...values); return context.length(objectId); }, shift() { if (context.length(objectId) == 0) return; const first = valueAt(target2, 0); context.delete(objectId, 0); return first; }, splice(index, del, ...vals) { index = parseListIndex(index); if (typeof del !== "number") { del = context.length(objectId) - index; } del = parseListIndex(del); for (const val of vals) { if (isSameDocument(val, context)) { throw new RangeError("Cannot create a reference to an existing document object"); } } const result = []; for (let i = 0; i < del; i++) { const value = valueAt(target2, index); if (value !== void 0) { result.push(value); } context.delete(objectId, index); } const values = vals.map((val, index2) => { try { return import_value(val, [...path], context); } catch (e) { if (e instanceof RangeError) { throw new RangeError(`${e.message} (at index ${index2} in the input)`); } else { throw e; } } }); for (const [value, datatype] of values) { switch (datatype) { case "list": { const list = context.insertObject(objectId, index, []); const proxyList = listProxy(context, list, [...path, index]); proxyList.splice(0, 0, ...value); break; } case "text": { context.insertObject(objectId, index, value); break; } case "map": { const map = context.insertObject(objectId, index, {}); const proxyMap = mapProxy(context, map, [...path, index]); for (const key in value) { proxyMap[key] = value[key]; } break; } default: context.insert(objectId, index, value, datatype); } index += 1; } return result; }, unshift(...values) { this.splice(0, 0, ...values); return context.length(objectId); }, entries() { let i = 0; const iterator = { next: () => { const value = valueAt(target2, i); if (value === void 0) { return { value: void 0, done: true }; } else { return { value: [i++, value], done: false }; } }, [Symbol.iterator]() { return this; } }; return iterator; }, keys() { let i = 0; const len = context.length(objectId); const iterator = { next: () => { if (i < len) { return { value: i++, done: false }; } return { value: void 0, done: true }; }, [Symbol.iterator]() { return this; } }; return iterator; }, values() { let i = 0; const iterator = { next: () => { const value = valueAt(target2, i++); if (value === void 0) { return { value: void 0, done: true }; } else { return { value, done: false }; } }, [Symbol.iterator]() { return this; } }; return iterator; }, toArray() { const list = []; let value; do { value = valueAt(target2, list.length); if (value !== void 0) { list.push(value); } } while (value !== void 0); return list; }, map(f) { return this.toArray().map(f); }, toString() { return this.toArray().toString(); }, toLocaleString() { return this.toArray().toLocaleString(); }, forEach(f) { return this.toArray().forEach(f); }, // todo: real concat function is different concat(other) { return this.toArray().concat(other); }, every(f) { return this.toArray().every(f); }, filter(f) { return this.toArray().filter(f); }, find(f) { let index = 0; for (const v of this) { if (f(v, index)) { return v; } index += 1; } }, findIndex(f) { let index = 0; for (const v of this) { if (f(v, index)) { return index; } index += 1; } return -1; }, includes(elem) { return this.find((e) => e === elem) !== void 0; }, join(sep) { return this.toArray().join(sep); }, reduce(f, initialValue) { return this.toArray().reduce(f, initialValue); }, reduceRight(f, initialValue) { return this.toArray().reduceRight(f, initialValue); }, lastIndexOf(search, fromIndex = Infinity) { return this.toArray().lastIndexOf(search, fromIndex); }, slice(index, num) { return this.toArray().slice(index, num); }, some(f) { let index = 0; for (const v of this) { if (f(v, index)) { return true; } index += 1; } return false; }, [Symbol.iterator]: function* () { let i = 0; let value = valueAt(target2, i); while (value !== void 0) { yield value; i += 1; value = valueAt(target2, i); } } }; return methods; } function textMethods(target2) { const { context, objectId } = target2; const methods = { set(index, value) { return this[index] = value; }, get(index) { return this[index]; }, toString() { return context.text(objectId).replace(//g, ""); }, toSpans() { const spans = []; let chars = ""; const length = context.length(objectId); for (let i = 0; i < length; i++) { const value = this[i]; if (typeof value === "string") { chars += value; } else { if (chars.length > 0) { spans.push(chars); chars = ""; } spans.push(value); } } if (chars.length > 0) { spans.push(chars); } return spans; }, toJSON() { return this.toString(); }, indexOf(o, start = 0) { const text = context.text(objectId); return text.indexOf(o, start); }, insertAt(index, ...values) { if (values.every((v) => typeof v === "string")) { context.splice(objectId, index, 0, values.join("")); } else { listMethods(target2).insertAt(index, ...values); } } }; return methods; } function printPath(path) { const jsonPointerComponents = path.map((component) => { if (typeof component === "number") { return component.toString(); } else if (typeof component === "string") { return component.replace(/~/g, "~0").replace(/\//g, "~1"); } }); if (path.length === 0) { return ""; } else { return "/" + jsonPointerComponents.join("/"); } } function isImmutableString(obj) { return typeof obj === "object" && obj !== null && Object.prototype.hasOwnProperty.call(obj, IMMUTABLE_STRING); } let wasm; const cachedTextEncoder = typeof TextEncoder !== "undefined" ? new TextEncoder("utf-8") : { encode: () => { throw Error("TextEncoder not available"); } }; typeof cachedTextEncoder.encodeInto === "function" ? function(arg, view) { return cachedTextEncoder.encodeInto(arg, view); } : function(arg, view) { const buf = cachedTextEncoder.encode(arg); view.set(buf); return { read: arg.length, written: buf.length }; }; const cachedTextDecoder = typeof TextDecoder !== "undefined" ? new TextDecoder("utf-8", { ignoreBOM: true, fatal: true }) : { decode: () => { throw Error("TextDecoder not available"); } }; if (typeof TextDecoder !== "undefined") { cachedTextDecoder.decode(); } typeof FinalizationRegistry === "undefined" ? {} : new FinalizationRegistry((ptr) => wasm.__wbg_automerge_free(ptr >>> 0, 1)); typeof FinalizationRegistry === "undefined" ? {} : new FinalizationRegistry((ptr) => wasm.__wbg_syncstate_free(ptr >>> 0, 1)); var browser = { exports: {} }; var ms; var hasRequiredMs; function requireMs() { if (hasRequiredMs) return ms; hasRequiredMs = 1; var s = 1e3; var m = s * 60; var h = m * 60; var d = h * 24; var w = d * 7; var y = d * 365.25; ms = function(val, options) { options = options || {}; var type = typeof val; if (type === "string" && val.length > 0) { return parse2(val); } else if (type === "number" && isFinite(val)) { return options.long ? fmtLong(val) : fmtShort(val); } throw new Error( "val is not a non-empty string or a valid number. val=" + JSON.stringify(val) ); }; function parse2(str) { str = String(str); if (str.length > 100) { return; } var match = /^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec( str ); if (!match) { return; } var n = parseFloat(match[1]); var type = (match[2] || "ms").toLowerCase(); switch (type) { case "years": case "year": case "yrs": case "yr": case "y": return n * y; case "weeks": case "week": case "w": return n * w; case "days": case "day": case "d": return n * d; case "hours": case "hour": case "hrs": case "hr": case "h": return n * h; case "minutes": case "minute": case "mins": case "min": case "m": return n * m; case "seconds": case "second": case "secs": case "sec": case "s": return n * s; case "milliseconds": case "millisecond": case "msecs": case "msec": case "ms": return n; default: return void 0; } } function fmtShort(ms2) { var msAbs = Math.abs(ms2); if (msAbs >= d) { return Math.round(ms2 / d) + "d"; } if (msAbs >= h) { return Math.round(ms2 / h) + "h"; } if (msAbs >= m) { return Math.round(ms2 / m) + "m"; } if (msAbs >= s) { return Math.round(ms2 / s) + "s"; } return ms2 + "ms"; } function fmtLong(ms2) { var msAbs = Math.abs(ms2); if (msAbs >= d) { return plural(ms2, msAbs, d, "day"); } if (msAbs >= h) { return plural(ms2, msAbs, h, "hour"); } if (msAbs >= m) { return plural(ms2, msAbs, m, "minute"); } if (msAbs >= s) { return plural(ms2, msAbs, s, "second"); } return ms2 + " ms"; } function plural(ms2, msAbs, n, name) { var isPlural = msAbs >= n * 1.5; return Math.round(ms2 / n) + " " + name + (isPlural ? "s" : ""); } return ms; } var common; var hasRequiredCommon; function requireCommon() { if (hasRequiredCommon) return common; hasRequiredCommon = 1; function setup(env) { createDebug.debug = createDebug; createDebug.default = createDebug; createDebug.coerce = coerce; createDebug.disable = disable; createDebug.enable = enable; createDebug.enabled = enabled; createDebug.humanize = requireMs(); createDebug.destroy = destroy; Object.keys(env).forEach((key) => { createDebug[key] = env[key]; }); createDebug.names = []; createDebug.skips = []; createDebug.formatters = {}; function selectColor(namespace) { let hash = 0; for (let i = 0; i < namespace.length; i++) { hash = (hash << 5) - hash + namespace.charCodeAt(i); hash |= 0; } return createDebug.colors[Math.abs(hash) % createDebug.colors.length]; } createDebug.selectColor = selectColor; function createDebug(namespace) { let prevTime; let enableOverride = null; let namespacesCache; let enabledCache; function debug2(...args) { if (!debug2.enabled) { return; } const self = debug2; const curr = Number(/* @__PURE__ */ new Date()); const ms2 = curr - (prevTime || curr); self.diff = ms2; self.prev = prevTime; self.curr = curr; prevTime = curr; args[0] = createDebug.coerce(args[0]); if (typeof args[0] !== "string") { args.unshift("%O"); } let index = 0; args[0] = args[0].replace(/%([a-zA-Z%])/g, (match, format) => { if (match === "%%") { return "%"; } index++; const formatter = createDebug.formatters[format]; if (typeof formatter === "function") { const val = args[index]; match = formatter.call(self, val); args.splice(index, 1); index--; } return match; }); createDebug.formatArgs.call(self, args); const logFn = self.log || createDebug.log; logFn.apply(self, args); } debug2.namespace = namespace; debug2.useColors = createDebug.useColors(); debug2.color = createDebug.selectColor(namespace); debug2.extend = extend; debug2.destroy = createDebug.destroy; Object.defineProperty(debug2, "enabled", { enumerable: true, configurable: false, get: () => { if (enableOverride !== null) { return enableOverride; } if (namespacesCache !== createDebug.namespaces) { namespacesCache = createDebug.namespaces; enabledCache = createDebug.enabled(namespace); } return enabledCache; }, set: (v) => { enableOverride = v; } }); if (typeof createDebug.init === "function") { createDebug.init(debug2); } return debug2; } function extend(namespace, delimiter) { const newDebug = createDebug(this.namespace + (typeof delimiter === "undefined" ? ":" : delimiter) + namespace); newDebug.log = this.log; return newDebug; } function enable(namespaces) { createDebug.save(namespaces); createDebug.namespaces = namespaces; createDebug.names = []; createDebug.skips = []; const split = (typeof namespaces === "string" ? namespaces : "").trim().replace(/\s+/g, ",").split(",").filter(Boolean); for (const ns of split) { if (ns[0] === "-") { createDebug.skips.push(ns.slice(1)); } else { createDebug.names.push(ns); } } } function matchesTemplate(search, template) { let searchIndex = 0; let templateIndex = 0; let starIndex = -1; let matchIndex = 0; while (searchIndex < search.length) { if (templateIndex < template.length && (template[templateIndex] === search[searchIndex] || template[templateIndex] === "*")) { if (template[templateIndex] === "*") { starIndex = templateIndex; matchIndex = searchIndex; templateIndex++; } else { searchIndex++; templateIndex++; } } else if (starIndex !== -1) { templateIndex = starIndex + 1; matchIndex++; searchIndex = matchIndex; } else { return false; } } while (templateIndex < template.length && template[templateIndex] === "*") { templateIndex++; } return templateIndex === template.length; } function disable() { const namespaces = [ ...createDebug.names, ...createDebug.skips.map((namespace) => "-" + namespace) ].join(","); createDebug.enable(""); return namespaces; } function enabled(name) { for (const skip of createDebug.skips) { if (matchesTemplate(name, skip)) { return false; } } for (const ns of createDebug.names) { if (matchesTemplate(name, ns)) { return true; } } return false; } function coerce(val) { if (val instanceof Error) { return val.stack || val.message; } return val; } function destroy() { console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."); } createDebug.enable(createDebug.load()); return createDebug; } common = setup; return common; } var hasRequiredBrowser; function requireBrowser() { if (hasRequiredBrowser) return browser.exports; hasRequiredBrowser = 1; (function(module, exports$1) { exports$1.formatArgs = formatArgs; exports$1.save = save; exports$1.load = load; exports$1.useColors = useColors; exports$1.storage = localstorage(); exports$1.destroy = /* @__PURE__ */ (() => { let warned = false; return () => { if (!warned) { warned = true; console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."); } }; })(); exports$1.colors = [ "#0000CC", "#0000FF", "#0033CC", "#0033FF", "#0066CC", "#0066FF", "#0099CC", "#0099FF", "#00CC00", "#00CC33", "#00CC66", "#00CC99", "#00CCCC", "#00CCFF", "#3300CC", "#3300FF", "#3333CC", "#3333FF", "#3366CC", "#3366FF", "#3399CC", "#3399FF", "#33CC00", "#33CC33", "#33CC66", "#33CC99", "#33CCCC", "#33CCFF", "#6600CC", "#6600FF", "#6633CC", "#6633FF", "#66CC00", "#66CC33", "#9900CC", "#9900FF", "#9933CC", "#9933FF", "#99CC00", "#99CC33", "#CC0000", "#CC0033", "#CC0066", "#CC0099", "#CC00CC", "#CC00FF", "#CC3300", "#CC3333", "#CC3366", "#CC3399", "#CC33CC", "#CC33FF", "#CC6600", "#CC6633", "#CC9900", "#CC9933", "#CCCC00", "#CCCC33", "#FF0000", "#FF0033", "#FF0066", "#FF0099", "#FF00CC", "#FF00FF", "#FF3300", "#FF3333", "#FF3366", "#FF3399", "#FF33CC", "#FF33FF", "#FF6600", "#FF6633", "#FF9900", "#FF9933", "#FFCC00", "#FFCC33" ]; function useColors() { if (typeof window !== "undefined" && window.process && (window.process.type === "renderer" || window.process.__nwjs)) { return true; } if (typeof navigator !== "undefined" && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)) { return false; } let m; return typeof document !== "undefined" && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance || // Is firebug? http://stackoverflow.com/a/398120/376773 typeof window !== "undefined" && window.console && (window.console.firebug || window.console.exception && window.console.table) || // Is firefox >= v31? // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages typeof navigator !== "undefined" && navigator.userAgent && (m = navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/)) && parseInt(m[1], 10) >= 31 || // Double check webkit in userAgent just in case we are in a worker typeof navigator !== "undefined" && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/); } function formatArgs(args) { args[0] = (this.useColors ? "%c" : "") + this.namespace + (this.useColors ? " %c" : " ") + args[0] + (this.useColors ? "%c " : " ") + "+" + module.exports.humanize(this.diff); if (!this.useColors) { return; } const c = "color: " + this.color; args.splice(1, 0, c, "color: inherit"); let index = 0; let lastC = 0; args[0].replace(/%[a-zA-Z%]/g, (match) => { if (match === "%%") { return; } index++; if (match === "%c") { lastC = index; } }); args.splice(lastC, 0, c); } exports$1.log = console.debug || console.log || (() => { }); function save(namespaces) { try { if (namespaces) { exports$1.storage.setItem("debug", namespaces); } else { exports$1.storage.removeItem("debug"); } } catch (error) { } } function load() { let r; try { r = exports$1.storage.getItem("debug") || exports$1.storage.getItem("DEBUG"); } catch (error) { } if (!r && typeof process !== "undefined" && "env" in process) { r = process.env.DEBUG; } return r; } function localstorage() { try { return localStorage; } catch (error) { } } module.exports = requireCommon()(exports$1); const { formatters } = module.exports; formatters.j = function(v) { try { return JSON.stringify(v); } catch (error) { return "[UnexpectedJSONParseError]: " + error.message; } }; })(browser, browser.exports); return browser.exports; } var browserExports = requireBrowser(); const debug = /* @__PURE__ */ getDefaultExportFromCjs(browserExports); let decoder; try { decoder = new TextDecoder(); } catch (error) { } let src; let srcEnd; let position$1 = 0; const LEGACY_RECORD_INLINE_ID = 105; const RECORD_DEFINITIONS_ID = 57342; const RECORD_INLINE_ID = 57343; const BUNDLED_STRINGS_ID = 57337; const PACKED_REFERENCE_TAG_ID = 6; const STOP_CODE = {}; let maxArraySize = 11281e4; let maxMapSize = 1681e4; let currentDecoder = {}; let currentStructures; let srcString; let srcStringStart = 0; let srcStringEnd = 0; let bundledStrings$1; let referenceMap; let currentExtensions = []; let currentExtensionRanges = []; let packedValues; let dataView; let restoreMapsAsObject; let defaultOptions = { useRecords: false, mapsAsObjects: true }; let sequentialMode = false; let inlineObjectReadThreshold = 2; try { new Function(""); } catch (error) { inlineObjectReadThreshold = Infinity; } class Decoder { constructor(options) { if (options) { if ((options.keyMap || options._keyMap) && !options.useRecords) { options.useRecords = false; options.mapsAsObjects = true; } if (options.useRecords === false && options.mapsAsObjects === void 0) options.mapsAsObjects = true; if (options.getStructures) options.getShared = options.getStructures; if (options.getShared && !options.structures) (options.structures = []).uninitialized = true; if (options.keyMap) { this.mapKey = /* @__PURE__ */ new Map(); for (let [k, v] of Object.entries(options.keyMap)) this.mapKey.set(v, k); } } Object.assign(this, options); } /* decodeKey(key) { return this.keyMap ? Object.keys(this.keyMap)[Object.values(this.keyMap).indexOf(key)] || key : key } */ decodeKey(key) { return this.keyMap ? this.mapKey.get(key) || key : key; } encodeKey(key) { return this.keyMap && this.keyMap.hasOwnProperty(key) ? this.keyMap[key] : key; } encodeKeys(rec) { if (!this._keyMap) return rec; let map = /* @__PURE__ */ new Map(); for (let [k, v] of Object.entries(rec)) map.set(this._keyMap.hasOwnProperty(k) ? this._keyMap[k] : k, v); return map; } decodeKeys(map) { if (!this._keyMap || map.constructor.name != "Map") return map; if (!this._mapKey) { this._mapKey = /* @__PURE__ */ new Map(); for (let [k, v] of Object.entries(this._keyMap)) this._mapKey.set(v, k); } let res = {}; map.forEach((v, k) => res[safeKey(this._mapKey.has(k) ? this._mapKey.get(k) : k)] = v); return res; } mapDecode(source, end) { let res = this.decode(source); if (this._keyMap) { switch (res.constructor.name) { case "Array": return res.map((r) => this.decodeKeys(r)); } } return res; } decode(source, end) { if (src) { return saveState(() => { clearSource(); return this ? this.decode(source, end) : Decoder.prototype.decode.call(defaultOptions, source, end); }); } srcEnd = end > -1 ? end : source.length; position$1 = 0; srcStringEnd = 0; srcString = null; bundledStrings$1 = null; src = source; try { dataView = source.dataView || (source.dataView = new DataView(source.buffer, source.byteOffset, source.byteLength)); } catch (error) { src = null; if (source instanceof Uint8Array) throw error; throw new Error("Source must be a Uint8Array or Buffer but was a " + (source && typeof source == "object" ? source.constructor.name : typeof source)); } if (this instanceof Decoder) { currentDecoder = this; packedValues = this.sharedValues && (this.pack ? new Array(this.maxPrivatePackedValues || 16).concat(this.sharedValues) : this.sharedValues); if (this.structures) { currentStructures = this.structures; return checkedRead(); } else if (!currentStructures || currentStructures.length > 0) { currentStructures = []; } } else { currentDecoder = defaultOptions; if (!currentStructures || currentStructures.length > 0) currentStructures = []; packedValues = null; } return checkedRead(); } decodeMultiple(source, forEach) { let values, lastPosition = 0; try { let size = source.length; sequentialMode = true; let value = this ? this.decode(source, size) : defaultDecoder.decode(source, size); if (forEach) { if (forEach(value) === false) { return; } while (position$1 < size) { lastPosition = position$1; if (forEach(checkedRead()) === false) { return; } } } else { values = [value]; while (position$1 < size) { lastPosition = position$1; values.push(checkedRead()); } return values; } } catch (error) { error.lastPosition = lastPosition; error.values = values; throw error; } finally { sequentialMode = false; clearSource(); } } } function checkedRead() { try { let result = read(); if (bundledStrings$1) { if (position$1 >= bundledStrings$1.postBundlePosition) { let error = new Error("Unexpected bundle position"); error.incomplete = true; throw error; } position$1 = bundledStrings$1.postBundlePosition; bundledStrings$1 = null; } if (position$1 == srcEnd) { currentStructures = null; src = null; if (referenceMap) referenceMap = null; } else if (position$1 > srcEnd) { let error = new Error("Unexpected end of CBOR data"); error.incomplete = true; throw error; } else if (!sequentialMode) { throw new Error("Data read, but end of buffer not reached"); } return result; } catch (error) { clearSource(); if (error instanceof RangeError || error.message.startsWith("Unexpected end of buffer")) { error.incomplete = true; } throw error; } } function read() { let token = src[position$1++]; let majorType = token >> 5; token = token & 31; if (token > 23) { switch (token) { case 24: token = src[position$1++]; break; case 25: if (majorType == 7) { return getFloat16(); } token = dataView.getUint16(position$1); position$1 += 2; break; case 26: if (majorType == 7) { let value = dataView.getFloat32(position$1); if (currentDecoder.useFloat32 > 2) { let multiplier = mult10[(src[position$1] & 127) << 1 | src[position$1 + 1] >> 7]; position$1 += 4; return (multiplier * value + (value > 0 ? 0.5 : -0.5) >> 0) / multiplier; } position$1 += 4; return value; } token = dataView.getUint32(position$1); position$1 += 4; break; case 27: if (majorType == 7) { let value = dataView.getFloat64(position$1); position$1 += 8; return value; } if (majorType > 1) { if (dataView.getUint32(position$1) > 0) throw new Error("JavaScript does not support arrays, maps, or strings with length over 4294967295"); token = dataView.getUint32(position$1 + 4); } else if (currentDecoder.int64AsNumber) { token = dataView.getUint32(position$1) * 4294967296; token += dataView.getUint32(position$1 + 4); } else token = dataView.getBigUint64(position$1); position$1 += 8; break; case 31: switch (majorType) { case 2: // byte string case 3: throw new Error("Indefinite length not supported for byte or text strings"); case 4: let array = []; let value, i = 0; while ((value = read()) != STOP_CODE) { if (i >= maxArraySize) throw new Error(`Array length exceeds ${maxArraySize}`); array[i++] = value; } return majorType == 4 ? array : majorType == 3 ? array.join("") : Buffer.concat(array); case 5: let key; if (currentDecoder.mapsAsObjects) { let object = {}; let i2 = 0; if (currentDecoder.keyMap) { while ((key = read()) != STOP_CODE) { if (i2++ >= maxMapSize) throw new Error(`Property count exceeds ${maxMapSize}`); object[safeKey(currentDecoder.decodeKey(key))] = read(); } } else { while ((key = read()) != STOP_CODE) { if (i2++ >= maxMapSize) throw new Error(`Property count exceeds ${maxMapSize}`); object[safeKey(key)] = read(); } } return object; } else { if (restoreMapsAsObject) { currentDecoder.mapsAsObjects = true; restoreMapsAsObject = false; } let map = /* @__PURE__ */ new Map(); if (currentDecoder.keyMap) { let i2 = 0; while ((key = read()) != STOP_CODE) { if (i2++ >= maxMapSize) { throw new Error(`Map size exceeds ${maxMapSize}`); } map.set(currentDecoder.decodeKey(key), read()); } } else { let i2 = 0; while ((key = read()) != STOP_CODE) { if (i2++ >= maxMapSize) { throw new Error(`Map size exceeds ${maxMapSize}`); } map.set(key, read()); } } return map; } case 7: return STOP_CODE; default: throw new Error("Invalid major type for indefinite length " + majorType); } default: throw new Error("Unknown token " + token); } } switch (majorType) { case 0: return token; case 1: return ~token; case 2: return readBin(token); case 3: if (srcStringEnd >= position$1) { return srcString.slice(position$1 - srcStringStart, (position$1 += token) - srcStringStart); } if (srcStringEnd == 0 && srcEnd < 140 && token < 32) { let string = token < 16 ? shortStringInJS(token) : longStringInJS(token); if (string != null) return string; } return readFixedString(token); case 4: if (token >= maxArraySize) throw new Error(`Array length exceeds ${maxArraySize}`); let array = new Array(token); for (let i = 0; i < token; i++) array[i] = read(); return array; case 5: if (token >= maxMapSize) throw new Error(`Map size exceeds ${maxArraySize}`); if (currentDecoder.mapsAsObjects) { let object = {}; if (currentDecoder.keyMap) for (let i = 0; i < token; i++) object[safeKey(currentDecoder.decodeKey(read()))] = read(); else for (let i = 0; i < token; i++) object[safeKey(read())] = read(); return object; } else { if (restoreMapsAsObject) { currentDecoder.mapsAsObjects = true; restoreMapsAsObject = false; } let map = /* @__PURE__ */ new Map(); if (currentDecoder.keyMap) for (let i = 0; i < token; i++) map.set(currentDecoder.decodeKey(read()), read()); else for (let i = 0; i < token; i++) map.set(read(), read()); return map; } case 6: if (token >= BUNDLED_STRINGS_ID) { let structure = currentStructures[token & 8191]; if (structure) { if (!structure.read) structure.read = createStructureReader(structure); return structure.read(); } if (token < 65536) { if (token == RECORD_INLINE_ID) { let length = readJustLength(); let id = read(); let structure2 = read(); recordDefinition(id, structure2); let object = {}; if (currentDecoder.keyMap) for (let i = 2; i < length; i++) { let key = currentDecoder.decodeKey(structure2[i - 2]); object[safeKey(key)] = read(); } else for (let i = 2; i < length; i++) { let key = structure2[i - 2]; object[safeKey(key)] = read(); } return object; } else if (token == RECORD_DEFINITIONS_ID) { let length = readJustLength(); let id = read(); for (let i = 2; i < length; i++) { recordDefinition(id++, read()); } return read(); } else if (token == BUNDLED_STRINGS_ID) { return readBundleExt(); } if (currentDecoder.getShared) { loadShared(); structure = currentStructures[token & 8191]; if (structure) { if (!structure.read) structure.read = createStructureReader(structure); return structure.read(); } } } } let extension = currentExtensions[token]; if (extension) { if (extension.handlesRead) return extension(read); else return extension(read()); } else { let input = read(); for (let i = 0; i < currentExtensionRanges.length; i++) { let value = currentExtensionRanges[i](token, input); if (value !== void 0) return value; } return new Tag(input, token); } case 7: switch (token) { case 20: return false; case 21: return true; case 22: return null; case 23: return; // undefined case 31: default: let packedValue = (packedValues || getPackedValues())[token]; if (packedValue !== void 0) return packedValue; throw new Error("Unknown token " + token); } default: if (isNaN(token)) { let error = new Error("Unexpected end of CBOR data"); error.incomplete = true; throw error; } throw new Error("Unknown CBOR token " + token); } } const validName = /^[a-zA-Z_$][a-zA-Z\d_$]*$/; function createStructureReader(structure) { if (!structure) throw new Error("Structure is required in record definition"); function readObject() { let length = src[position$1++]; length = length & 31; if (length > 23) { switch (length) { case 24: length = src[position$1++]; break; case 25: length = dataView.getUint16(position$1); position$1 += 2; break; case 26: length = dataView.getUint32(position$1); position$1 += 4; break; default: throw new Error("Expected array header, but got " + src[position$1 - 1]); } } let compiledReader = this.compiledReader; while (compiledReader) { if (compiledReader.propertyCount === length) return compiledReader(read); compiledReader = compiledReader.next; } if (this.slowReads++ >= inlineObjectReadThreshold) { let array = this.length == length ? this : this.slice(0, length); compiledReader = currentDecoder.keyMap ? new Function("r", "return {" + array.map((k) => currentDecoder.decodeKey(k)).map((k) => validName.test(k) ? safeKey(k) + ":r()" : "[" + JSON.stringify(k) + "]:r()").join(",") + "}") : new Function("r", "return {" + array.map((key) => validName.test(key) ? safeKey(key) + ":r()" : "[" + JSON.stringify(key) + "]:r()").join(",") + "}"); if (this.compiledReader) compiledReader.next = this.compiledReader; compiledReader.propertyCount = length; this.compiledReader = compiledReader; return compiledReader(read); } let object = {}; if (currentDecoder.keyMap) for (let i = 0; i < length; i++) object[safeKey(currentDecoder.decodeKey(this[i]))] = read(); else for (let i = 0; i < length; i++) { object[safeKey(this[i])] = read(); } return object; } structure.slowReads = 0; return readObject; } function safeKey(key) { if (typeof key === "string") return key === "__proto__" ? "__proto_" : key; if (typeof key === "number" || typeof key === "boolean" || typeof key === "bigint") return key.toString(); if (key == null) return key + ""; throw new Error("Invalid property name type " + typeof key); } let readFixedString = readStringJS; function readStringJS(length) { let result; if (length < 16) { if (result = shortStringInJS(length)) return result; } if (length > 64 && decoder) return decoder.decode(src.subarray(position$1, position$1 += length)); const end = position$1 + length; const units = []; result = ""; while (position$1 < end) { const byte1 = src[position$1++]; if ((byte1 & 128) === 0) { units.push(byte1); } else if ((byte1 & 224) === 192) { const byte2 = src[position$1++] & 63; units.push((byte1 & 31) << 6 | byte2); } else if ((byte1 & 240) === 224) { const byte2 = src[position$1++] & 63; const byte3 = src[position$1++] & 63; units.push((byte1 & 31) << 12 | byte2 << 6 | byte3); } else if ((byte1 & 248) === 240) { const byte2 = src[position$1++] & 63; const byte3 = src[position$1++] & 63; const byte4 = src[position$1++] & 63; let unit = (byte1 & 7) << 18 | byte2 << 12 | byte3 << 6 | byte4; if (unit > 65535) { unit -= 65536; units.push(unit >>> 10 & 1023 | 55296); unit = 56320 | unit & 1023; } units.push(unit); } else { units.push(byte1); } if (units.length >= 4096) { result += fromCharCode.apply(String, units); units.length = 0; } } if (units.length > 0) { result += fromCharCode.apply(String, units); } return result; } let fromCharCode = String.fromCharCode; function longStringInJS(length) { let start = position$1; let bytes = new Array(length); for (let i = 0; i < length; i++) { const byte = src[position$1++]; if ((byte & 128) > 0) { position$1 = start; return; } bytes[i] = byte; } return fromCharCode.apply(String, bytes); } function shortStringInJS(length) { if (length < 4) { if (length < 2) { if (length === 0) return ""; else { let a = src[position$1++]; if ((a & 128) > 1) { position$1 -= 1; return; } return fromCharCode(a); } } else { let a = src[position$1++]; let b = src[position$1++]; if ((a & 128) > 0 || (b & 128) > 0) { position$1 -= 2; return; } if (length < 3) return fromCharCode(a, b); let c = src[position$1++]; if ((c & 128) > 0) { position$1 -= 3; return; } return fromCharCode(a, b, c); } } else { let a = src[position$1++]; let b = src[position$1++]; let c = src[position$1++]; let d = src[position$1++]; if ((a & 128) > 0 || (b & 128) > 0 || (c & 128) > 0 || (d & 128) > 0) { position$1 -= 4; return; } if (length < 6) { if (length === 4) return fromCharCode(a, b, c, d); else { let e = src[position$1++]; if ((e & 128) > 0) { position$1 -= 5; return; } return fromCharCode(a, b, c, d, e); } } else if (length < 8) { let e = src[position$1++]; let f = src[position$1++]; if ((e & 128) > 0 || (f & 128) > 0) { position$1 -= 6; return; } if (length < 7) return fromCharCode(a, b, c, d, e, f); let g = src[position$1++]; if ((g & 128) > 0) { position$1 -= 7; return; } return fromCharCode(a, b, c, d, e, f, g); } else { let e = src[position$1++]; let f = src[position$1++]; let g = src[position$1++]; let h = src[position$1++]; if ((e & 128) > 0 || (f & 128) > 0 || (g & 128) > 0 || (h & 128) > 0) { position$1 -= 8; return; } if (length < 10) { if (length === 8) return fromCharCode(a, b, c, d, e, f, g, h); else { let i = src[position$1++]; if ((i & 128) > 0) { position$1 -= 9; return; } return fromCharCode(a, b, c, d, e, f, g, h, i); } } else if (length < 12) { let i = src[position$1++]; let j = src[position$1++]; if ((i & 128) > 0 || (j & 128) > 0) { position$1 -= 10; return; } if (length < 11) return fromCharCode(a, b, c, d, e, f, g, h, i, j); let k = src[position$1++]; if ((k & 128) > 0) { position$1 -= 11; return; } return fromCharCode(a, b, c, d, e, f, g, h, i, j, k); } else { let i = src[position$1++]; let j = src[position$1++]; let k = src[position$1++]; let l = src[position$1++]; if ((i & 128) > 0 || (j & 128) > 0 || (k & 128) > 0 || (l & 128) > 0) { position$1 -= 12; return; } if (length < 14) { if (length === 12) return fromCharCode(a, b, c, d, e, f, g, h, i, j, k, l); else { let m = src[position$1++]; if ((m & 128) > 0) { position$1 -= 13; return; } return fromCharCode(a, b, c, d, e, f, g, h, i, j, k, l, m); } } else { let m = src[position$1++]; let n = src[position$1++]; if ((m & 128) > 0 || (n & 128) > 0) { position$1 -= 14; return; } if (length < 15) return fromCharCode(a, b, c, d, e, f, g, h, i, j, k, l, m, n); let o = src[position$1++]; if ((o & 128) > 0) { position$1 -= 15; return; } return fromCharCode(a, b, c, d, e, f, g, h, i, j, k, l, m, n, o); } } } } } function readBin(length) { return currentDecoder.copyBuffers ? ( // specifically use the copying slice (not the node one) Uint8Array.prototype.slice.call(src, position$1, position$1 += length) ) : src.subarray(position$1, position$1 += length); } let f32Array = new Float32Array(1); let u8Array = new Uint8Array(f32Array.buffer, 0, 4); function getFloat16() { let byte0 = src[position$1++]; let byte1 = src[position$1++]; let exponent = (byte0 & 127) >> 2; if (exponent === 31) { if (byte1 || byte0 & 3) return NaN; return byte0 & 128 ? -Infinity : Infinity; } if (exponent === 0) { let abs = ((byte0 & 3) << 8 | byte1) / (1 << 24); return byte0 & 128 ? -abs : abs; } u8Array[3] = byte0 & 128 | // sign bit (exponent >> 1) + 56; u8Array[2] = (byte0 & 7) << 5 | // last exponent bit and first two mantissa bits byte1 >> 3; u8Array[1] = byte1 << 5; u8Array[0] = 0; return f32Array[0]; } new Array(4096); class Tag { constructor(value, tag) { this.value = value; this.tag = tag; } } currentExtensions[0] = (dateString) => { return new Date(dateString); }; currentExtensions[1] = (epochSec) => { return new Date(Math.round(epochSec * 1e3)); }; currentExtensions[2] = (buffer) => { let value = BigInt(0); for (let i = 0, l = buffer.byteLength; i < l; i++) { value = BigInt(buffer[i]) + (value << BigInt(8)); } return value; }; currentExtensions[3] = (buffer) => { return BigInt(-1) - currentExtensions[2](buffer); }; currentExtensions[4] = (fraction) => { return +(fraction[1] + "e" + fraction[0]); }; currentExtensions[5] = (fraction) => { return fraction[1] * Math.exp(fraction[0] * Math.log(2)); }; const recordDefinition = (id, structure) => { id = id - 57344; let existingStructure = currentStructures[id]; if (existingStructure && existingStructure.isShared) { (currentStructures.restoreStructures || (currentStructures.restoreStructures = []))[id] = existingStructure; } currentStructures[id] = structure; structure.read = createStructureReader(structure); }; currentExtensions[LEGACY_RECORD_INLINE_ID] = (data) => { let length = data.length; let structure = data[1]; recordDefinition(data[0], structure); let object = {}; for (let i = 2; i < length; i++) { let key = structure[i - 2]; object[safeKey(key)] = data[i]; } return object; }; currentExtensions[14] = (value) => { if (bundledStrings$1) return bundledStrings$1[0].slice(bundledStrings$1.position0, bundledStrings$1.position0 += value); return new Tag(value, 14); }; currentExtensions[15] = (value) => { if (bundledStrings$1) return bundledStrings$1[1].slice(bundledStrings$1.position1, bundledStrings$1.position1 += value); return new Tag(value, 15); }; let glbl = { Error, RegExp }; currentExtensions[27] = (data) => { return (glbl[data[0]] || Error)(data[1], data[2]); }; const packedTable = (read2) => { if (src[position$1++] != 132) { let error = new Error("Packed values structure must be followed by a 4 element array"); if (src.length < position$1) error.incomplete = true; throw error; } let newPackedValues = read2(); if (!newPackedValues || !newPackedValues.length) { let error = new Error("Packed values structure must be followed by a 4 element array"); error.incomplete = true; throw error; } packedValues = packedValues ? newPackedValues.concat(packedValues.slice(newPackedValues.length)) : newPackedValues; packedValues.prefixes = read2(); packedValues.suffixes = read2(); return read2(); }; packedTable.handlesRead = true; currentExtensions[51] = packedTable; currentExtensions[PACKED_REFERENCE_TAG_ID] = (data) => { if (!packedValues) { if (currentDecoder.getShared) loadShared(); else return new Tag(data, PACKED_REFERENCE_TAG_ID); } if (typeof data == "number") return packedValues[16 + (data >= 0 ? 2 * data : -2 * data - 1)]; let error = new Error("No support for non-integer packed references yet"); if (data === void 0) error.incomplete = true; throw error; }; currentExtensions[28] = (read2) => { if (!referenceMap) { referenceMap = /* @__PURE__ */ new Map(); referenceMap.id = 0; } let id = referenceMap.id++; let startingPosition = position$1; let token = src[position$1]; let target2; if (token >> 5 == 4) target2 = []; else target2 = {}; let refEntry = { target: target2 }; referenceMap.set(id, refEntry); let targetProperties = read2(); if (refEntry.used) { if (Object.getPrototypeOf(target2) !== Object.getPrototypeOf(targetProperties)) { position$1 = startingPosition; target2 = targetProperties; referenceMap.set(id, { target: target2 }); targetProperties = read2(); } return Object.assign(target2, targetProperties); } refEntry.target = targetProperties; return targetProperties; }; currentExtensions[28].handlesRead = true; currentExtensions[29] = (id) => { let refEntry = referenceMap.get(id); refEntry.used = true; return refEntry.target; }; currentExtensions[258] = (array) => new Set(array); (currentExtensions[259] = (read2) => { if (currentDecoder.mapsAsObjects) { currentDecoder.mapsAsObjects = false; restoreMapsAsObject = true; } return read2(); }).handlesRead = true; function combine(a, b) { if (typeof a === "string") return a + b; if (a instanceof Array) return a.concat(b); return Object.assign({}, a, b); } function getPackedValues() { if (!packedValues) { if (currentDecoder.getShared) loadShared(); else throw new Error("No packed values available"); } return packedValues; } const SHARED_DATA_TAG_ID = 1399353956; currentExtensionRanges.push((tag, input) => { if (tag >= 225 && tag <= 255) return combine(getPackedValues().prefixes[tag - 224], input); if (tag >= 28704 && tag <= 32767) return combine(getPackedValues().prefixes[tag - 28672], input); if (tag >= 1879052288 && tag <= 2147483647) return combine(getPackedValues().prefixes[tag - 1879048192], input); if (tag >= 216 && tag <= 223) return combine(input, getPackedValues().suffixes[tag - 216]); if (tag >= 27647 && tag <= 28671) return combine(input, getPackedValues().suffixes[tag - 27639]); if (tag >= 1811940352 && tag <= 1879048191) return combine(input, getPackedValues().suffixes[tag - 1811939328]); if (tag == SHARED_DATA_TAG_ID) { return { packedValues, structures: currentStructures.slice(0), version: input }; } if (tag == 55799) return input; }); const isLittleEndianMachine$1 = new Uint8Array(new Uint16Array([1]).buffer)[0] == 1; const typedArrays = [ Uint8Array, Uint8ClampedArray, Uint16Array, Uint32Array, typeof BigUint64Array == "undefined" ? { name: "BigUint64Array" } : BigUint64Array, Int8Array, Int16Array, Int32Array, typeof BigInt64Array == "undefined" ? { name: "BigInt64Array" } : BigInt64Array, Float32Array, Float64Array ]; const typedArrayTags = [64, 68, 69, 70, 71, 72, 77, 78, 79, 85, 86]; for (let i = 0; i < typedArrays.length; i++) { registerTypedArray(typedArrays[i], typedArrayTags[i]); } function registerTypedArray(TypedArray, tag) { let dvMethod = "get" + TypedArray.name.slice(0, -5); let bytesPerElement; if (typeof TypedArray === "function") bytesPerElement = TypedArray.BYTES_PER_ELEMENT; else TypedArray = null; for (let littleEndian = 0; littleEndian < 2; littleEndian++) { if (!littleEndian && bytesPerElement == 1) continue; let sizeShift = bytesPerElement == 2 ? 1 : bytesPerElement == 4 ? 2 : bytesPerElement == 8 ? 3 : 0; currentExtensions[littleEndian ? tag : tag - 4] = bytesPerElement == 1 || littleEndian == isLittleEndianMachine$1 ? (buffer) => { if (!TypedArray) throw new Error("Could not find typed array for code " + tag); if (!currentDecoder.copyBuffers) { if (bytesPerElement === 1 || bytesPerElement === 2 && !(buffer.byteOffset & 1) || bytesPerElement === 4 && !(buffer.byteOffset & 3) || bytesPerElement === 8 && !(buffer.byteOffset & 7)) return new TypedArray(buffer.buffer, buffer.byteOffset, buffer.byteLength >> sizeShift); } return new TypedArray(Uint8Array.prototype.slice.call(buffer, 0).buffer); } : (buffer) => { if (!TypedArray) throw new Error("Could not find typed array for code " + tag); let dv = new DataView(buffer.buffer, buffer.byteOffset, buffer.byteLength); let elements = buffer.length >> sizeShift; let ta = new TypedArray(elements); let method = dv[dvMethod]; for (let i = 0; i < elements; i++) { ta[i] = method.call(dv, i << sizeShift, littleEndian); } return ta; }; } } function readBundleExt() { let length = readJustLength(); let bundlePosition = position$1 + read(); for (let i = 2; i < length; i++) { let bundleLength = readJustLength(); position$1 += bundleLength; } let dataPosition = position$1; position$1 = bundlePosition; bundledStrings$1 = [readStringJS(readJustLength()), readStringJS(readJustLength())]; bundledStrings$1.position0 = 0; bundledStrings$1.position1 = 0; bundledStrings$1.postBundlePosition = position$1; position$1 = dataPosition; return read(); } function readJustLength() { let token = src[position$1++] & 31; if (token > 23) { switch (token) { case 24: token = src[position$1++]; break; case 25: token = dataView.getUint16(position$1); position$1 += 2; break; case 26: token = dataView.getUint32(position$1); position$1 += 4; break; } } return token; } function loadShared() { if (currentDecoder.getShared) { let sharedData = saveState(() => { src = null; return currentDecoder.getShared(); }) || {}; let updatedStructures = sharedData.structures || []; currentDecoder.sharedVersion = sharedData.version; packedValues = currentDecoder.sharedValues = sharedData.packedValues; if (currentStructures === true) currentDecoder.structures = currentStructures = updatedStructures; else currentStructures.splice.apply(currentStructures, [0, updatedStructures.length].concat(updatedStructures)); } } function saveState(callback) { let savedSrcEnd = srcEnd; let savedPosition = position$1; let savedSrcStringStart = srcStringStart; let savedSrcStringEnd = srcStringEnd; let savedSrcString = srcString; let savedReferenceMap = referenceMap; let savedBundledStrings = bundledStrings$1; let savedSrc = new Uint8Array(src.slice(0, srcEnd)); let savedStructures = currentStructures; let savedDecoder = currentDecoder; let savedSequentialMode = sequentialMode; let value = callback(); srcEnd = savedSrcEnd; position$1 = savedPosition; srcStringStart = savedSrcStringStart; srcStringEnd = savedSrcStringEnd; srcString = savedSrcString; referenceMap = savedReferenceMap; bundledStrings$1 = savedBundledStrings; src = savedSrc; sequentialMode = savedSequentialMode; currentStructures = savedStructures; currentDecoder = savedDecoder; dataView = new DataView(src.buffer, src.byteOffset, src.byteLength); return value; } function clearSource() { src = null; referenceMap = null; currentStructures = null; } const mult10 = new Array(147); for (let i = 0; i < 256; i++) { mult10[i] = +("1e" + Math.floor(45.15 - i * 0.30103)); } let defaultDecoder = new Decoder({ useRecords: false }); defaultDecoder.decode; defaultDecoder.decodeMultiple; let textEncoder; try { textEncoder = new TextEncoder(); } catch (error) { } let extensions, extensionClasses; const Buffer$1 = typeof globalThis === "object" && globalThis.Buffer; const hasNodeBuffer = typeof Buffer$1 !== "undefined"; const ByteArrayAllocate = hasNodeBuffer ? Buffer$1.allocUnsafeSlow : Uint8Array; const ByteArray = hasNodeBuffer ? Buffer$1 : Uint8Array; const MAX_STRUCTURES = 256; const MAX_BUFFER_SIZE = hasNodeBuffer ? 4294967296 : 2144337920; let throwOnIterable; let target; let targetView; let position = 0; let safeEnd; let bundledStrings = null; const MAX_BUNDLE_SIZE = 61440; const hasNonLatin = /[\u0080-\uFFFF]/; const RECORD_SYMBOL = /* @__PURE__ */ Symbol("record-id"); class Encoder extends Decoder { constructor(options) { super(options); this.offset = 0; let start; let sharedStructures; let hasSharedUpdate; let structures; let referenceMap2; options = options || {}; let encodeUtf8 = ByteArray.prototype.utf8Write ? function(string, position2, maxBytes) { return target.utf8Write(string, position2, maxBytes); } : textEncoder && textEncoder.encodeInto ? function(string, position2) { return textEncoder.encodeInto(string, target.subarray(position2)).written; } : false; let encoder = this; let hasSharedStructures = options.structures || options.saveStructures; let maxSharedStructures = options.maxSharedStructures; if (maxSharedStructures == null) maxSharedStructures = hasSharedStructures ? 128 : 0; if (maxSharedStructures > 8190) throw new Error("Maximum maxSharedStructure is 8190"); let isSequential = options.sequential; if (isSequential) { maxSharedStructures = 0; } if (!this.structures) this.structures = []; if (this.saveStructures) this.saveShared = this.saveStructures; let samplingPackedValues, packedObjectMap2, sharedValues = options.sharedValues; let sharedPackedObjectMap2; if (sharedValues) { sharedPackedObjectMap2 = /* @__PURE__ */ Object.create(null); for (let i = 0, l = sharedValues.length; i < l; i++) { sharedPackedObjectMap2[sharedValues[i]] = i; } } let recordIdsToRemove = []; let transitionsCount = 0; let serializationsSinceTransitionRebuild = 0; this.mapEncode = function(value, encodeOptions) { if (this._keyMap && !this._mapped) { switch (value.constructor.name) { case "Array": value = value.map((r) => this.encodeKeys(r)); break; } } return this.encode(value, encodeOptions); }; this.encode = function(value, encodeOptions) { if (!target) { target = new ByteArrayAllocate(8192); targetView = new DataView(target.buffer, 0, 8192); position = 0; } safeEnd = target.length - 10; if (safeEnd - position < 2048) { target = new ByteArrayAllocate(target.length); targetView = new DataView(target.buffer, 0, target.length); safeEnd = target.length - 10; position = 0; } else if (encodeOptions === REUSE_BUFFER_MODE) position = position + 7 & 2147483640; start = position; if (encoder.useSelfDescribedHeader) { targetView.setUint32(position, 3654940416); position += 3; } referenceMap2 = encoder.structuredClone ? /* @__PURE__ */ new Map() : null; if (encoder.bundleStrings && typeof value !== "string") { bundledStrings = []; bundledStrings.size = Infinity; } else bundledStrings = null; sharedStructures = encoder.structures; if (sharedStructures) { if (sharedStructures.uninitialized) { let sharedData = encoder.getShared() || {}; encoder.structures = sharedStructures = sharedData.structures || []; encoder.sharedVersion = sharedData.version; let sharedValues2 = encoder.sharedValues = sharedData.packedValues; if (sharedValues2) { sharedPackedObjectMap2 = {}; for (let i = 0, l = sharedValues2.length; i < l; i++) sharedPackedObjectMap2[sharedValues2[i]] = i; } } let sharedStructuresLength = sharedStructures.length; if (sharedStructuresLength > maxSharedStructures && !isSequential) sharedStructuresLength = maxSharedStructures; if (!sharedStructures.transitions) { sharedStructures.transitions = /* @__PURE__ */ Object.create(null); for (let i = 0; i < sharedStructuresLength; i++) { let keys = sharedStructures[i]; if (!keys) continue; let nextTransition, transition = sharedStructures.transitions; for (let j = 0, l = keys.length; j < l; j++) { if (transition[RECORD_SYMBOL] === void 0) transition[RECORD_SYMBOL] = i; let key = keys[j]; nextTransition = transition[key]; if (!nextTransition) { nextTransition = transition[key] = /* @__PURE__ */ Object.create(null); } transition = nextTransition; } transition[RECORD_SYMBOL] = i | 1048576; } } if (!isSequential) sharedStructures.nextId = sharedStructuresLength; } if (hasSharedUpdate) hasSharedUpdate = false; structures = sharedStructures || []; packedObjectMap2 = sharedPackedObjectMap2; if (options.pack) { let packedValues2 = /* @__PURE__ */ new Map(); packedValues2.values = []; packedValues2.encoder = encoder; packedValues2.maxValues = options.maxPrivatePackedValues || (sharedPackedObjectMap2 ? 16 : Infinity); packedValues2.objectMap = sharedPackedObjectMap2 || false; packedValues2.samplingPackedValues = samplingPackedValues; findRepetitiveStrings(value, packedValues2); if (packedValues2.values.length > 0) { target[position++] = 216; target[position++] = 51; writeArrayHeader(4); let valuesArray = packedValues2.values; encode(valuesArray); writeArrayHeader(0); writeArrayHeader(0); packedObjectMap2 = Object.create(sharedPackedObjectMap2 || null); for (let i = 0, l = valuesArray.length; i < l; i++) { packedObjectMap2[valuesArray[i]] = i; } } } throwOnIterable = encodeOptions & THROW_ON_ITERABLE; try { if (throwOnIterable) return; encode(value); if (bundledStrings) { writeBundles(start, encode); } encoder.offset = position; if (referenceMap2 && referenceMap2.idsToInsert) { position += referenceMap2.idsToInsert.length * 2; if (position > safeEnd) makeRoom(position); encoder.offset = position; let serialized = insertIds(target.subarray(start, position), referenceMap2.idsToInsert); referenceMap2 = null; return serialized; } if (encodeOptions & REUSE_BUFFER_MODE) { target.start = start; target.end = position; return target; } return target.subarray(start, position); } finally { if (sharedStructures) { if (serializationsSinceTransitionRebuild < 10) serializationsSinceTransitionRebuild++; if (sharedStructures.length > maxSharedStructures) sharedStructures.length = maxSharedStructures; if (transitionsCount > 1e4) { sharedStructures.transitions = null; serializationsSinceTransitionRebuild = 0; transitionsCount = 0; if (recordIdsToRemove.length > 0) recordIdsToRemove = []; } else if (recordIdsToRemove.length > 0 && !isSequential) { for (let i = 0, l = recordIdsToRemove.length; i < l; i++) { recordIdsToRemove[i][RECORD_SYMBOL] = void 0; } recordIdsToRemove = []; } } if (hasSharedUpdate && encoder.saveShared) { if (encoder.structures.length > maxSharedStructures) { encoder.structures = encoder.structures.slice(0, maxSharedStructures); } let returnBuffer = target.subarray(start, position); if (encoder.updateSharedData() === false) return encoder.encode(value); return returnBuffer; } if (encodeOptions & RESET_BUFFER_MODE) position = start; } }; this.findCommonStringsToPack = () => { samplingPackedValues = /* @__PURE__ */ new Map(); if (!sharedPackedObjectMap2) sharedPackedObjectMap2 = /* @__PURE__ */ Object.create(null); return (options2) => { let threshold = options2 && options2.threshold || 4; let position2 = this.pack ? options2.maxPrivatePackedValues || 16 : 0; if (!sharedValues) sharedValues = this.sharedValues = []; for (let [key, status] of samplingPackedValues) { if (status.count > threshold) { sharedPackedObjectMap2[key] = position2++; sharedValues.push(key); hasSharedUpdate = true; } } while (this.saveShared && this.updateSharedData() === false) { } samplingPackedValues = null; }; }; const encode = (value) => { if (position > safeEnd) target = makeRoom(position); var type = typeof value; var length; if (type === "string") { if (packedObjectMap2) { let packedPosition = packedObjectMap2[value]; if (packedPosition >= 0) { if (packedPosition < 16) target[position++] = packedPosition + 224; else { target[position++] = 198; if (packedPosition & 1) encode(15 - packedPosition >> 1); else encode(packedPosition - 16 >> 1); } return; } else if (samplingPackedValues && !options.pack) { let status = samplingPackedValues.get(value); if (status) status.count++; else samplingPackedValues.set(value, { count: 1 }); } } let strLength = value.length; if (bundledStrings && strLength >= 4 && strLength < 1024) { if ((bundledStrings.size += strLength) > MAX_BUNDLE_SIZE) { let extStart; let maxBytes2 = (bundledStrings[0] ? bundledStrings[0].length * 3 + bundledStrings[1].length : 0) + 10; if (position + maxBytes2 > safeEnd) target = makeRoom(position + maxBytes2); target[position++] = 217; target[position++] = 223; target[position++] = 249; target[position++] = bundledStrings.position ? 132 : 130; target[position++] = 26; extStart = position - start; position += 4; if (bundledStrings.position) { writeBundles(start, encode); } bundledStrings = ["", ""]; bundledStrings.size = 0; bundledStrings.position = extStart; } let twoByte = hasNonLatin.test(value); bundledStrings[twoByte ? 0 : 1] += value; target[position++] = twoByte ? 206 : 207; encode(strLength); return; } let headerSize; if (strLength < 32) { headerSize = 1; } else if (strLength < 256) { headerSize = 2; } else if (strLength < 65536) { headerSize = 3; } else { headerSize = 5; } let maxBytes = strLength * 3; if (position + maxBytes > safeEnd) target = makeRoom(position + maxBytes); if (strLength < 64 || !encodeUtf8) { let i, c1, c2, strPosition = position + headerSize; for (i = 0; i < strLength; i++) { c1 = value.charCodeAt(i); if (c1 < 128) { target[strPosition++] = c1; } else if (c1 < 2048) { target[strPosition++] = c1 >> 6 | 192; target[strPosition++] = c1 & 63 | 128; } else if ((c1 & 64512) === 55296 && ((c2 = value.charCodeAt(i + 1)) & 64512) === 56320) { c1 = 65536 + ((c1 & 1023) << 10) + (c2 & 1023); i++; target[strPosition++] = c1 >> 18 | 240; target[strPosition++] = c1 >> 12 & 63 | 128; target[strPosition++] = c1 >> 6 & 63 | 128; target[strPosition++] = c1 & 63 | 128; } else { target[strPosition++] = c1 >> 12 | 224; target[strPosition++] = c1 >> 6 & 63 | 128; target[strPosition++] = c1 & 63 | 128; } } length = strPosition - position - headerSize; } else { length = encodeUtf8(value, position + headerSize, maxBytes); } if (length < 24) { target[position++] = 96 | length; } else if (length < 256) { if (headerSize < 2) { target.copyWithin(position + 2, position + 1, position + 1 + length); } target[position++] = 120; target[position++] = length; } else if (length < 65536) { if (headerSize < 3) { target.copyWithin(position + 3, position + 2, position + 2 + length); } target[position++] = 121; target[position++] = length >> 8; target[position++] = length & 255; } else { if (headerSize < 5) { target.copyWithin(position + 5, position + 3, position + 3 + length); } target[position++] = 122; targetView.setUint32(position, length); position += 4; } position += length; } else if (type === "number") { if (!this.alwaysUseFloat && value >>> 0 === value) { if (value < 24) { target[position++] = value; } else if (value < 256) { target[position++] = 24; target[position++] = value; } else if (value < 65536) { target[position++] = 25; target[position++] = value >> 8; target[position++] = value & 255; } else { target[position++] = 26; targetView.setUint32(position, value); position += 4; } } else if (!this.alwaysUseFloat && value >> 0 === value) { if (value >= -24) { target[position++] = 31 - value; } else if (value >= -256) { target[position++] = 56; target[position++] = ~value; } else if (value >= -65536) { target[position++] = 57; targetView.setUint16(position, ~value); position += 2; } else { target[position++] = 58; targetView.setUint32(position, ~value); position += 4; } } else { let useFloat32; if ((useFloat32 = this.useFloat32) > 0 && value < 4294967296 && value >= -2147483648) { target[position++] = 250; targetView.setFloat32(position, value); let xShifted; if (useFloat32 < 4 || // this checks for rounding of numbers that were encoded in 32-bit float to nearest significant decimal digit that could be preserved (xShifted = value * mult10[(target[position] & 127) << 1 | target[position + 1] >> 7]) >> 0 === xShifted) { position += 4; return; } else position--; } target[position++] = 251; targetView.setFloat64(position, value); position += 8; } } else if (type === "object") { if (!value) target[position++] = 246; else { if (referenceMap2) { let referee = referenceMap2.get(value); if (referee) { target[position++] = 216; target[position++] = 29; target[position++] = 25; if (!referee.references) { let idsToInsert = referenceMap2.idsToInsert || (referenceMap2.idsToInsert = []); referee.references = []; idsToInsert.push(referee); } referee.references.push(position - start); position += 2; return; } else referenceMap2.set(value, { offset: position - start }); } let constructor = value.constructor; if (constructor === Object) { writeObject(value); } else if (constructor === Array) { length = value.length; if (length < 24) { target[position++] = 128 | length; } else { writeArrayHeader(length); } for (let i = 0; i < length; i++) { encode(value[i]); } } else if (constructor === Map) { if (this.mapsAsObjects ? this.useTag259ForMaps !== false : this.useTag259ForMaps) { target[position++] = 217; target[position++] = 1; target[position++] = 3; } length = value.size; if (length < 24) { target[position++] = 160 | length; } else if (length < 256) { target[position++] = 184; target[position++] = length; } else if (length < 65536) { target[position++] = 185; target[position++] = length >> 8; target[position++] = length & 255; } else { target[position++] = 186; targetView.setUint32(position, length); position += 4; } if (encoder.keyMap) { for (let [key, entryValue] of value) { encode(encoder.encodeKey(key)); encode(entryValue); } } else { for (let [key, entryValue] of value) { encode(key); encode(entryValue); } } } else { for (let i = 0, l = extensions.length; i < l; i++) { let extensionClass = extensionClasses[i]; if (value instanceof extensionClass) { let extension = extensions[i]; let tag = extension.tag; if (tag == void 0) tag = extension.getTag && extension.getTag.call(this, value); if (tag < 24) { target[position++] = 192 | tag; } else if (tag < 256) { target[position++] = 216; target[position++] = tag; } else if (tag < 65536) { target[position++] = 217; target[position++] = tag >> 8; target[position++] = tag & 255; } else if (tag > -1) { target[position++] = 218; targetView.setUint32(position, tag); position += 4; } extension.encode.call(this, value, encode, makeRoom); return; } } if (value[Symbol.iterator]) { if (throwOnIterable) { let error = new Error("Iterable should be serialized as iterator"); error.iteratorNotHandled = true; throw error; } target[position++] = 159; for (let entry of value) { encode(entry); } target[position++] = 255; return; } if (value[Symbol.asyncIterator] || isBlob(value)) { let error = new Error("Iterable/blob should be serialized as iterator"); error.iteratorNotHandled = true; throw error; } if (this.useToJSON && value.toJSON) { const json = value.toJSON(); if (json !== value) return encode(json); } writeObject(value); } } } else if (type === "boolean") { target[position++] = value ? 245 : 244; } else if (type === "bigint") { if (value < BigInt(1) << BigInt(64) && value >= 0) { target[position++] = 27; targetView.setBigUint64(position, value); } else if (value > -(BigInt(1) << BigInt(64)) && value < 0) { target[position++] = 59; targetView.setBigUint64(position, -value - BigInt(1)); } else { if (this.largeBigIntToFloat) { target[position++] = 251; targetView.setFloat64(position, Number(value)); } else { if (value >= BigInt(0)) target[position++] = 194; else { target[position++] = 195; value = BigInt(-1) - value; } let bytes = []; while (value) { bytes.push(Number(value & BigInt(255))); value >>= BigInt(8); } writeBuffer(new Uint8Array(bytes.reverse()), makeRoom); return; } } position += 8; } else if (type === "undefined") { target[position++] = 247; } else { throw new Error("Unknown type: " + type); } }; const writeObject = this.useRecords === false ? this.variableMapSize ? (object) => { let keys = Object.keys(object); let vals = Object.values(object); let length = keys.length; if (length < 24) { target[position++] = 160 | length; } else if (length < 256) { target[position++] = 184; target[position++] = length; } else if (length < 65536) { target[position++] = 185; target[position++] = length >> 8; target[position++] = length & 255; } else { target[position++] = 186; targetView.setUint32(position, length); position += 4; } if (encoder.keyMap) { for (let i = 0; i < length; i++) { encode(encoder.encodeKey(keys[i])); encode(vals[i]); } } else { for (let i = 0; i < length; i++) { encode(keys[i]); encode(vals[i]); } } } : (object) => { target[position++] = 185; let objectOffset = position - start; position += 2; let size = 0; if (encoder.keyMap) { for (let key in object) if (typeof object.hasOwnProperty !== "function" || object.hasOwnProperty(key)) { encode(encoder.encodeKey(key)); encode(object[key]); size++; } } else { for (let key in object) if (typeof object.hasOwnProperty !== "function" || object.hasOwnProperty(key)) { encode(key); encode(object[key]); size++; } } target[objectOffset++ + start] = size >> 8; target[objectOffset + start] = size & 255; } : (object, skipValues) => { let nextTransition, transition = structures.transitions || (structures.transitions = /* @__PURE__ */ Object.create(null)); let newTransitions = 0; let length = 0; let parentRecordId; let keys; if (this.keyMap) { keys = Object.keys(object).map((k) => this.encodeKey(k)); length = keys.length; for (let i = 0; i < length; i++) { let key = keys[i]; nextTransition = transition[key]; if (!nextTransition) { nextTransition = transition[key] = /* @__PURE__ */ Object.create(null); newTransitions++; } transition = nextTransition; } } else { for (let key in object) if (typeof object.hasOwnProperty !== "function" || object.hasOwnProperty(key)) { nextTransition = transition[key]; if (!nextTransition) { if (transition[RECORD_SYMBOL] & 1048576) { parentRecordId = transition[RECORD_SYMBOL] & 65535; } nextTransition = transition[key] = /* @__PURE__ */ Object.create(null); newTransitions++; } transition = nextTransition; length++; } } let recordId = transition[RECORD_SYMBOL]; if (recordId !== void 0) { recordId &= 65535; target[position++] = 217; target[position++] = recordId >> 8 | 224; target[position++] = recordId & 255; } else { if (!keys) keys = transition.__keys__ || (transition.__keys__ = Object.keys(object)); if (parentRecordId === void 0) { recordId = structures.nextId++; if (!recordId) { recordId = 0; structures.nextId = 1; } if (recordId >= MAX_STRUCTURES) { structures.nextId = (recordId = maxSharedStructures) + 1; } } else { recordId = parentRecordId; } structures[recordId] = keys; if (recordId < maxSharedStructures) { target[position++] = 217; target[position++] = recordId >> 8 | 224; target[position++] = recordId & 255; transition = structures.transitions; for (let i = 0; i < length; i++) { if (transition[RECORD_SYMBOL] === void 0 || transition[RECORD_SYMBOL] & 1048576) transition[RECORD_SYMBOL] = recordId; transition = transition[keys[i]]; } transition[RECORD_SYMBOL] = recordId | 1048576; hasSharedUpdate = true; } else { transition[RECORD_SYMBOL] = recordId; targetView.setUint32(position, 3655335680); position += 3; if (newTransitions) transitionsCount += serializationsSinceTransitionRebuild * newTransitions; if (recordIdsToRemove.length >= MAX_STRUCTURES - maxSharedStructures) recordIdsToRemove.shift()[RECORD_SYMBOL] = void 0; recordIdsToRemove.push(transition); writeArrayHeader(length + 2); encode(57344 + recordId); encode(keys); if (skipValues) return; for (let key in object) if (typeof object.hasOwnProperty !== "function" || object.hasOwnProperty(key)) encode(object[key]); return; } } if (length < 24) { target[position++] = 128 | length; } else { writeArrayHeader(length); } if (skipValues) return; for (let key in object) if (typeof object.hasOwnProperty !== "function" || object.hasOwnProperty(key)) encode(object[key]); }; const makeRoom = (end) => { let newSize; if (end > 16777216) { if (end - start > MAX_BUFFER_SIZE) throw new Error("Encoded buffer would be larger than maximum buffer size"); newSize = Math.min( MAX_BUFFER_SIZE, Math.round(Math.max((end - start) * (end > 67108864 ? 1.25 : 2), 4194304) / 4096) * 4096 ); } else newSize = (Math.max(end - start << 2, target.length - 1) >> 12) + 1 << 12; let newBuffer = new ByteArrayAllocate(newSize); targetView = new DataView(newBuffer.buffer, 0, newSize); if (target.copy) target.copy(newBuffer, 0, start, end); else newBuffer.set(target.slice(start, end)); position -= start; start = 0; safeEnd = newBuffer.length - 10; return target = newBuffer; }; let chunkThreshold = 100; let continuedChunkThreshold = 1e3; this.encodeAsIterable = function(value, options2) { return startEncoding(value, options2, encodeObjectAsIterable); }; this.encodeAsAsyncIterable = function(value, options2) { return startEncoding(value, options2, encodeObjectAsAsyncIterable); }; function* encodeObjectAsIterable(object, iterateProperties, finalIterable) { let constructor = object.constructor; if (constructor === Object) { let useRecords = encoder.useRecords !== false; if (useRecords) writeObject(object, true); else writeEntityLength(Object.keys(object).length, 160); for (let key in object) { let value = object[key]; if (!useRecords) encode(key); if (value && typeof value === "object") { if (iterateProperties[key]) yield* encodeObjectAsIterable(value, iterateProperties[key]); else yield* tryEncode(value, iterateProperties, key); } else encode(value); } } else if (constructor === Array) { let length = object.length; writeArrayHeader(length); for (let i = 0; i < length; i++) { let value = object[i]; if (value && (typeof value === "object" || position - start > chunkThreshold)) { if (iterateProperties.element) yield* encodeObjectAsIterable(value, iterateProperties.element); else yield* tryEncode(value, iterateProperties, "element"); } else encode(value); } } else if (object[Symbol.iterator] && !object.buffer) { target[position++] = 159; for (let value of object) { if (value && (typeof value === "object" || position - start > chunkThreshold)) { if (iterateProperties.element) yield* encodeObjectAsIterable(value, iterateProperties.element); else yield* tryEncode(value, iterateProperties, "element"); } else encode(value); } target[position++] = 255; } else if (isBlob(object)) { writeEntityLength(object.size, 64); yield target.subarray(start, position); yield object; restartEncoding(); } else if (object[Symbol.asyncIterator]) { target[position++] = 159; yield target.subarray(start, position); yield object; restartEncoding(); target[position++] = 255; } else { encode(object); } if (finalIterable && position > start) yield target.subarray(start, position); else if (position - start > chunkThreshold) { yield target.subarray(start, position); restartEncoding(); } } function* tryEncode(value, iterateProperties, key) { let restart = position - start; try { encode(value); if (position - start > chunkThreshold) { yield target.subarray(start, position); restartEncoding(); } } catch (error) { if (error.iteratorNotHandled) { iterateProperties[key] = {}; position = start + restart; yield* encodeObjectAsIterable.call(this, value, iterateProperties[key]); } else throw error; } } function restartEncoding() { chunkThreshold = continuedChunkThreshold; encoder.encode(null, THROW_ON_ITERABLE); } function startEncoding(value, options2, encodeIterable) { if (options2 && options2.chunkThreshold) chunkThreshold = continuedChunkThreshold = options2.chunkThreshold; else chunkThreshold = 100; if (value && typeof value === "object") { encoder.encode(null, THROW_ON_ITERABLE); return encodeIterable(value, encoder.iterateProperties || (encoder.iterateProperties = {}), true); } return [encoder.encode(value)]; } async function* encodeObjectAsAsyncIterable(value, iterateProperties) { for (let encodedValue of encodeObjectAsIterable(value, iterateProperties, true)) { let constructor = encodedValue.constructor; if (constructor === ByteArray || constructor === Uint8Array) yield encodedValue; else if (isBlob(encodedValue)) { let reader = encodedValue.stream().getReader(); let next; while (!(next = await reader.read()).done) { yield next.value; } } else if (encodedValue[Symbol.asyncIterator]) { for await (let asyncValue of encodedValue) { restartEncoding(); if (asyncValue) yield* encodeObjectAsAsyncIterable(asyncValue, iterateProperties.async || (iterateProperties.async = {})); else yield encoder.encode(asyncValue); } } else { yield encodedValue; } } } } useBuffer(buffer) { target = buffer; targetView = new DataView(target.buffer, target.byteOffset, target.byteLength); position = 0; } clearSharedData() { if (this.structures) this.structures = []; if (this.sharedValues) this.sharedValues = void 0; } updateSharedData() { let lastVersion = this.sharedVersion || 0; this.sharedVersion = lastVersion + 1; let structuresCopy = this.structures.slice(0); let sharedData = new SharedData(structuresCopy, this.sharedValues, this.sharedVersion); let saveResults = this.saveShared( sharedData, (existingShared) => (existingShared && existingShared.version || 0) == lastVersion ); if (saveResults === false) { sharedData = this.getShared() || {}; this.structures = sharedData.structures || []; this.sharedValues = sharedData.packedValues; this.sharedVersion = sharedData.version; this.structures.nextId = this.structures.length; } else { structuresCopy.forEach((structure, i) => this.structures[i] = structure); } return saveResults; } } function writeEntityLength(length, majorValue) { if (length < 24) target[position++] = majorValue | length; else if (length < 256) { target[position++] = majorValue | 24; target[position++] = length; } else if (length < 65536) { target[position++] = majorValue | 25; target[position++] = length >> 8; target[position++] = length & 255; } else { target[position++] = majorValue | 26; targetView.setUint32(position, length); position += 4; } } class SharedData { constructor(structures, values, version) { this.structures = structures; this.packedValues = values; this.version = version; } } function writeArrayHeader(length) { if (length < 24) target[position++] = 128 | length; else if (length < 256) { target[position++] = 152; target[position++] = length; } else if (length < 65536) { target[position++] = 153; target[position++] = length >> 8; target[position++] = length & 255; } else { target[position++] = 154; targetView.setUint32(position, length); position += 4; } } const BlobConstructor = typeof Blob === "undefined" ? function() { } : Blob; function isBlob(object) { if (object instanceof BlobConstructor) return true; let tag = object[Symbol.toStringTag]; return tag === "Blob" || tag === "File"; } function findRepetitiveStrings(value, packedValues2) { switch (typeof value) { case "string": if (value.length > 3) { if (packedValues2.objectMap[value] > -1 || packedValues2.values.length >= packedValues2.maxValues) return; let packedStatus = packedValues2.get(value); if (packedStatus) { if (++packedStatus.count == 2) { packedValues2.values.push(value); } } else { packedValues2.set(value, { count: 1 }); if (packedValues2.samplingPackedValues) { let status = packedValues2.samplingPackedValues.get(value); if (status) status.count++; else packedValues2.samplingPackedValues.set(value, { count: 1 }); } } } break; case "object": if (value) { if (value instanceof Array) { for (let i = 0, l = value.length; i < l; i++) { findRepetitiveStrings(value[i], packedValues2); } } else { let includeKeys = !packedValues2.encoder.useRecords; for (var key in value) { if (value.hasOwnProperty(key)) { if (includeKeys) findRepetitiveStrings(key, packedValues2); findRepetitiveStrings(value[key], packedValues2); } } } } break; case "function": console.log(value); } } const isLittleEndianMachine = new Uint8Array(new Uint16Array([1]).buffer)[0] == 1; extensionClasses = [ Date, Set, Error, RegExp, Tag, ArrayBuffer, Uint8Array, Uint8ClampedArray, Uint16Array, Uint32Array, typeof BigUint64Array == "undefined" ? function() { } : BigUint64Array, Int8Array, Int16Array, Int32Array, typeof BigInt64Array == "undefined" ? function() { } : BigInt64Array, Float32Array, Float64Array, SharedData ]; extensions = [ { // Date tag: 1, encode(date, encode) { let seconds = date.getTime() / 1e3; if ((this.useTimestamp32 || date.getMilliseconds() === 0) && seconds >= 0 && seconds < 4294967296) { target[position++] = 26; targetView.setUint32(position, seconds); position += 4; } else { target[position++] = 251; targetView.setFloat64(position, seconds); position += 8; } } }, { // Set tag: 258, // https://github.com/input-output-hk/cbor-sets-spec/blob/master/CBOR_SETS.md encode(set, encode) { let array = Array.from(set); encode(array); } }, { // Error tag: 27, // http://cbor.schmorp.de/generic-object encode(error, encode) { encode([error.name, error.message]); } }, { // RegExp tag: 27, // http://cbor.schmorp.de/generic-object encode(regex, encode) { encode(["RegExp", regex.source, regex.flags]); } }, { // Tag getTag(tag) { return tag.tag; }, encode(tag, encode) { encode(tag.value); } }, { // ArrayBuffer encode(arrayBuffer, encode, makeRoom) { writeBuffer(arrayBuffer, makeRoom); } }, { // Uint8Array getTag(typedArray) { if (typedArray.constructor === Uint8Array) { if (this.tagUint8Array || hasNodeBuffer && this.tagUint8Array !== false) return 64; } }, encode(typedArray, encode, makeRoom) { writeBuffer(typedArray, makeRoom); } }, typedArrayEncoder(68, 1), typedArrayEncoder(69, 2), typedArrayEncoder(70, 4), typedArrayEncoder(71, 8), typedArrayEncoder(72, 1), typedArrayEncoder(77, 2), typedArrayEncoder(78, 4), typedArrayEncoder(79, 8), typedArrayEncoder(85, 4), typedArrayEncoder(86, 8), { encode(sharedData, encode) { let packedValues2 = sharedData.packedValues || []; let sharedStructures = sharedData.structures || []; if (packedValues2.values.length > 0) { target[position++] = 216; target[position++] = 51; writeArrayHeader(4); let valuesArray = packedValues2.values; encode(valuesArray); writeArrayHeader(0); writeArrayHeader(0); packedObjectMap = Object.create(sharedPackedObjectMap || null); for (let i = 0, l = valuesArray.length; i < l; i++) { packedObjectMap[valuesArray[i]] = i; } } if (sharedStructures) { targetView.setUint32(position, 3655335424); position += 3; let definitions = sharedStructures.slice(0); definitions.unshift(57344); definitions.push(new Tag(sharedData.version, 1399353956)); encode(definitions); } else encode(new Tag(sharedData.version, 1399353956)); } } ]; function typedArrayEncoder(tag, size) { if (!isLittleEndianMachine && size > 1) tag -= 4; return { tag, encode: function writeExtBuffer(typedArray, encode) { let length = typedArray.byteLength; let offset = typedArray.byteOffset || 0; let buffer = typedArray.buffer || typedArray; encode(hasNodeBuffer ? Buffer$1.from(buffer, offset, length) : new Uint8Array(buffer, offset, length)); } }; } function writeBuffer(buffer, makeRoom) { let length = buffer.byteLength; if (length < 24) { target[position++] = 64 + length; } else if (length < 256) { target[position++] = 88; target[position++] = length; } else if (length < 65536) { target[position++] = 89; target[position++] = length >> 8; target[position++] = length & 255; } else { target[position++] = 90; targetView.setUint32(position, length); position += 4; } if (position + length >= target.length) { makeRoom(position + length); } target.set(buffer.buffer ? buffer : new Uint8Array(buffer), position); position += length; } function insertIds(serialized, idsToInsert) { let nextId; let distanceToMove = idsToInsert.length * 2; let lastEnd = serialized.length - distanceToMove; idsToInsert.sort((a, b) => a.offset > b.offset ? 1 : -1); for (let id = 0; id < idsToInsert.length; id++) { let referee = idsToInsert[id]; referee.id = id; for (let position2 of referee.references) { serialized[position2++] = id >> 8; serialized[position2] = id & 255; } } while (nextId = idsToInsert.pop()) { let offset = nextId.offset; serialized.copyWithin(offset + distanceToMove, offset, lastEnd); distanceToMove -= 2; let position2 = offset + distanceToMove; serialized[position2++] = 216; serialized[position2++] = 28; lastEnd = offset; } return serialized; } function writeBundles(start, encode) { targetView.setUint32(bundledStrings.position + start, position - bundledStrings.position - start + 1); let writeStrings = bundledStrings; bundledStrings = null; encode(writeStrings[0]); encode(writeStrings[1]); } let defaultEncoder = new Encoder({ useRecords: false }); defaultEncoder.encode; defaultEncoder.encodeAsIterable; defaultEncoder.encodeAsAsyncIterable; const REUSE_BUFFER_MODE = 512; const RESET_BUFFER_MODE = 1024; const THROW_ON_ITERABLE = 2048; new FinalizationRegistry((cleanup) => cleanup()); var sha256$1 = { exports: {} }; var sha256 = sha256$1.exports; var hasRequiredSha256; function requireSha256() { if (hasRequiredSha256) return sha256$1.exports; hasRequiredSha256 = 1; (function(module) { (function(root, factory) { var exports$1 = {}; factory(exports$1); var sha2562 = exports$1["default"]; for (var k in exports$1) { sha2562[k] = exports$1[k]; } { module.exports = sha2562; } })(sha256, function(exports$1) { exports$1.__esModule = true; exports$1.digestLength = 32; exports$1.blockSize = 64; var K = new Uint32Array([ 1116352408, 1899447441, 3049323471, 3921009573, 961987163, 1508970993, 2453635748, 2870763221, 3624381080, 310598401, 607225278, 1426881987, 1925078388, 2162078206, 2614888103, 3248222580, 3835390401, 4022224774, 264347078, 604807628, 770255983, 1249150122, 1555081692, 1996064986, 2554220882, 2821834349, 2952996808, 3210313671, 3336571891, 3584528711, 113926993, 338241895, 666307205, 773529912, 1294757372, 1396182291, 1695183700, 1986661051, 2177026350, 2456956037, 2730485921, 2820302411, 3259730800, 3345764771, 3516065817, 3600352804, 4094571909, 275423344, 430227734, 506948616, 659060556, 883997877, 958139571, 1322822218, 1537002063, 1747873779, 1955562222, 2024104815, 2227730452, 2361852424, 2428436474, 2756734187, 3204031479, 3329325298 ]); function hashBlocks(w, v, p, pos, len) { var a, b, c, d, e, f, g, h, u, i, j, t1, t2; while (len >= 64) { a = v[0]; b = v[1]; c = v[2]; d = v[3]; e = v[4]; f = v[5]; g = v[6]; h = v[7]; for (i = 0; i < 16; i++) { j = pos + i * 4; w[i] = (p[j] & 255) << 24 | (p[j + 1] & 255) << 16 | (p[j + 2] & 255) << 8 | p[j + 3] & 255; } for (i = 16; i < 64; i++) { u = w[i - 2]; t1 = (u >>> 17 | u << 32 - 17) ^ (u >>> 19 | u << 32 - 19) ^ u >>> 10; u = w[i - 15]; t2 = (u >>> 7 | u << 32 - 7) ^ (u >>> 18 | u << 32 - 18) ^ u >>> 3; w[i] = (t1 + w[i - 7] | 0) + (t2 + w[i - 16] | 0); } for (i = 0; i < 64; i++) { t1 = (((e >>> 6 | e << 32 - 6) ^ (e >>> 11 | e << 32 - 11) ^ (e >>> 25 | e << 32 - 25)) + (e & f ^ ~e & g) | 0) + (h + (K[i] + w[i] | 0) | 0) | 0; t2 = ((a >>> 2 | a << 32 - 2) ^ (a >>> 13 | a << 32 - 13) ^ (a >>> 22 | a << 32 - 22)) + (a & b ^ a & c ^ b & c) | 0; h = g; g = f; f = e; e = d + t1 | 0; d = c; c = b; b = a; a = t1 + t2 | 0; } v[0] += a; v[1] += b; v[2] += c; v[3] += d; v[4] += e; v[5] += f; v[6] += g; v[7] += h; pos += 64; len -= 64; } return pos; } var Hash = ( /** @class */ (function() { function Hash2() { this.digestLength = exports$1.digestLength; this.blockSize = exports$1.blockSize; this.state = new Int32Array(8); this.temp = new Int32Array(64); this.buffer = new Uint8Array(128); this.bufferLength = 0; this.bytesHashed = 0; this.finished = false; this.reset(); } Hash2.prototype.reset = function() { this.state[0] = 1779033703; this.state[1] = 3144134277; this.state[2] = 1013904242; this.state[3] = 2773480762; this.state[4] = 1359893119; this.state[5] = 2600822924; this.state[6] = 528734635; this.state[7] = 1541459225; this.bufferLength = 0; this.bytesHashed = 0; this.finished = false; return this; }; Hash2.prototype.clean = function() { for (var i = 0; i < this.buffer.length; i++) { this.buffer[i] = 0; } for (var i = 0; i < this.temp.length; i++) { this.temp[i] = 0; } this.reset(); }; Hash2.prototype.update = function(data, dataLength) { if (dataLength === void 0) { dataLength = data.length; } if (this.finished) { throw new Error("SHA256: can't update because hash was finished."); } var dataPos = 0; this.bytesHashed += dataLength; if (this.bufferLength > 0) { while (this.bufferLength < 64 && dataLength > 0) { this.buffer[this.bufferLength++] = data[dataPos++]; dataLength--; } if (this.bufferLength === 64) { hashBlocks(this.temp, this.state, this.buffer, 0, 64); this.bufferLength = 0; } } if (dataLength >= 64) { dataPos = hashBlocks(this.temp, this.state, data, dataPos, dataLength); dataLength %= 64; } while (dataLength > 0) { this.buffer[this.bufferLength++] = data[dataPos++]; dataLength--; } return this; }; Hash2.prototype.finish = function(out) { if (!this.finished) { var bytesHashed = this.bytesHashed; var left = this.bufferLength; var bitLenHi = bytesHashed / 536870912 | 0; var bitLenLo = bytesHashed << 3; var padLength = bytesHashed % 64 < 56 ? 64 : 128; this.buffer[left] = 128; for (var i = left + 1; i < padLength - 8; i++) { this.buffer[i] = 0; } this.buffer[padLength - 8] = bitLenHi >>> 24 & 255; this.buffer[padLength - 7] = bitLenHi >>> 16 & 255; this.buffer[padLength - 6] = bitLenHi >>> 8 & 255; this.buffer[padLength - 5] = bitLenHi >>> 0 & 255; this.buffer[padLength - 4] = bitLenLo >>> 24 & 255; this.buffer[padLength - 3] = bitLenLo >>> 16 & 255; this.buffer[padLength - 2] = bitLenLo >>> 8 & 255; this.buffer[padLength - 1] = bitLenLo >>> 0 & 255; hashBlocks(this.temp, this.state, this.buffer, 0, padLength); this.finished = true; } for (var i = 0; i < 8; i++) { out[i * 4 + 0] = this.state[i] >>> 24 & 255; out[i * 4 + 1] = this.state[i] >>> 16 & 255; out[i * 4 + 2] = this.state[i] >>> 8 & 255; out[i * 4 + 3] = this.state[i] >>> 0 & 255; } return this; }; Hash2.prototype.digest = function() { var out = new Uint8Array(this.digestLength); this.finish(out); return out; }; Hash2.prototype._saveState = function(out) { for (var i = 0; i < this.state.length; i++) { out[i] = this.state[i]; } }; Hash2.prototype._restoreState = function(from, bytesHashed) { for (var i = 0; i < this.state.length; i++) { this.state[i] = from[i]; } this.bytesHashed = bytesHashed; this.finished = false; this.bufferLength = 0; }; return Hash2; })() ); exports$1.Hash = Hash; var HMAC = ( /** @class */ (function() { function HMAC2(key) { this.inner = new Hash(); this.outer = new Hash(); this.blockSize = this.inner.blockSize; this.digestLength = this.inner.digestLength; var pad = new Uint8Array(this.blockSize); if (key.length > this.blockSize) { new Hash().update(key).finish(pad).clean(); } else { for (var i = 0; i < key.length; i++) { pad[i] = key[i]; } } for (var i = 0; i < pad.length; i++) { pad[i] ^= 54; } this.inner.update(pad); for (var i = 0; i < pad.length; i++) { pad[i] ^= 54 ^ 92; } this.outer.update(pad); this.istate = new Uint32Array(8); this.ostate = new Uint32Array(8); this.inner._saveState(this.istate); this.outer._saveState(this.ostate); for (var i = 0; i < pad.length; i++) { pad[i] = 0; } } HMAC2.prototype.reset = function() { this.inner._restoreState(this.istate, this.inner.blockSize); this.outer._restoreState(this.ostate, this.outer.blockSize); return this; }; HMAC2.prototype.clean = function() { for (var i = 0; i < this.istate.length; i++) { this.ostate[i] = this.istate[i] = 0; } this.inner.clean(); this.outer.clean(); }; HMAC2.prototype.update = function(data) { this.inner.update(data); return this; }; HMAC2.prototype.finish = function(out) { if (this.outer.finished) { this.outer.finish(out); } else { this.inner.finish(out); this.outer.update(out, this.digestLength).finish(out); } return this; }; HMAC2.prototype.digest = function() { var out = new Uint8Array(this.digestLength); this.finish(out); return out; }; return HMAC2; })() ); exports$1.HMAC = HMAC; function hash(data) { var h = new Hash().update(data); var digest = h.digest(); h.clean(); return digest; } exports$1.hash = hash; exports$1["default"] = hash; function hmac(key, data) { var h = new HMAC(key).update(data); var digest = h.digest(); h.clean(); return digest; } exports$1.hmac = hmac; function fillBuffer(buffer, hmac2, info, counter) { var num = counter[0]; if (num === 0) { throw new Error("hkdf: cannot expand more"); } hmac2.reset(); if (num > 1) { hmac2.update(buffer); } if (info) { hmac2.update(info); } hmac2.update(counter); hmac2.finish(buffer); counter[0]++; } var hkdfSalt = new Uint8Array(exports$1.digestLength); function hkdf(key, salt, info, length) { if (salt === void 0) { salt = hkdfSalt; } if (length === void 0) { length = 32; } var counter = new Uint8Array([1]); var okm = hmac(salt, key); var hmac_ = new HMAC(okm); var buffer = new Uint8Array(hmac_.digestLength); var bufpos = buffer.length; var out = new Uint8Array(length); for (var i = 0; i < length; i++) { if (bufpos === buffer.length) { fillBuffer(buffer, hmac_, info, counter); bufpos = 0; } out[i] = buffer[bufpos++]; } hmac_.clean(); buffer.fill(0); counter.fill(0); return out; } exports$1.hkdf = hkdf; function pbkdf2(password, salt, iterations, dkLen) { var prf = new HMAC(password); var len = prf.digestLength; var ctr = new Uint8Array(4); var t = new Uint8Array(len); var u = new Uint8Array(len); var dk = new Uint8Array(dkLen); for (var i = 0; i * len < dkLen; i++) { var c = i + 1; ctr[0] = c >>> 24 & 255; ctr[1] = c >>> 16 & 255; ctr[2] = c >>> 8 & 255; ctr[3] = c >>> 0 & 255; prf.reset(); prf.update(salt); prf.update(ctr); prf.finish(u); for (var j = 0; j < len; j++) { t[j] = u[j]; } for (var j = 2; j <= iterations; j++) { prf.reset(); prf.update(u).finish(u); for (var k = 0; k < len; k++) { t[k] ^= u[k]; } } for (var j = 0; j < len && i * len + j < dkLen; j++) { dk[i * len + j] = t[j]; } } for (var i = 0; i < len; i++) { t[i] = u[i] = 0; } for (var i = 0; i < 4; i++) { ctr[i] = 0; } prf.clean(); return dk; } exports$1.pbkdf2 = pbkdf2; }); })(sha256$1); return sha256$1.exports; } requireSha256(); debug("automerge-repo:collectionsync"); export { RepoContext as R, useDocument as a, useRepo as u };