@automerge/automerge-repo-react-hooks 2.5.0-alpha.2 → 2.5.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,1242 +1,2150 @@
1
- import ke, { createContext as Oe, useContext as Fe, useRef as qe, useState as X, useEffect as z, useCallback as Le } from "react";
2
- function Ue(e) {
3
- let t = "pending", n, H;
4
- const y = e.then(
5
- (w) => {
6
- t = "success", n = w;
1
+ import require$$0, { createContext, useContext, useRef, useState, useEffect, useCallback } from 'react';
2
+
3
+ function wrapPromise(promise) {
4
+ let status = "pending";
5
+ let result;
6
+ let error;
7
+ const suspender = promise.then(
8
+ (data) => {
9
+ status = "success";
10
+ result = data;
7
11
  },
8
- (w) => {
9
- t = "error", H = w;
12
+ (err) => {
13
+ status = "error";
14
+ error = err;
10
15
  }
11
16
  );
12
17
  return {
13
- promise: e,
18
+ promise,
14
19
  read() {
15
- switch (t) {
20
+ switch (status) {
16
21
  case "pending":
17
- throw y;
22
+ throw suspender;
18
23
  case "error":
19
- throw H;
24
+ throw error;
20
25
  case "success":
21
- return n;
26
+ return result;
22
27
  }
23
28
  }
24
29
  };
25
30
  }
26
- const Ge = Oe(null);
27
- function Ve() {
28
- const e = Fe(Ge);
29
- if (!e) throw new Error("Repo was not found on RepoContext.");
30
- return e;
31
+
32
+ const RepoContext = createContext(null);
33
+ function useRepo() {
34
+ const repo = useContext(RepoContext);
35
+ if (!repo) throw new Error("Repo was not found on RepoContext.");
36
+ return repo;
31
37
  }
32
- const Pe = /^(?:[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;
33
- function de(e) {
34
- return typeof e == "string" && Pe.test(e);
38
+
39
+ 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;
40
+
41
+ function validate(uuid) {
42
+ return typeof uuid === 'string' && REGEX.test(uuid);
35
43
  }
36
- function je(e) {
37
- if (!de(e))
38
- throw TypeError("Invalid UUID");
39
- let t;
40
- const n = new Uint8Array(16);
41
- return n[0] = (t = parseInt(e.slice(0, 8), 16)) >>> 24, n[1] = t >>> 16 & 255, n[2] = t >>> 8 & 255, n[3] = t & 255, n[4] = (t = parseInt(e.slice(9, 13), 16)) >>> 8, n[5] = t & 255, n[6] = (t = parseInt(e.slice(14, 18), 16)) >>> 8, n[7] = t & 255, n[8] = (t = parseInt(e.slice(19, 23), 16)) >>> 8, n[9] = t & 255, n[10] = (t = parseInt(e.slice(24, 36), 16)) / 1099511627776 & 255, n[11] = t / 4294967296 & 255, n[12] = t >>> 24 & 255, n[13] = t >>> 16 & 255, n[14] = t >>> 8 & 255, n[15] = t & 255, n;
44
+
45
+ function parse(uuid) {
46
+ if (!validate(uuid)) {
47
+ throw TypeError('Invalid UUID');
48
+ }
49
+
50
+ let v;
51
+ const arr = new Uint8Array(16); // Parse ########-....-....-....-............
52
+
53
+ arr[0] = (v = parseInt(uuid.slice(0, 8), 16)) >>> 24;
54
+ arr[1] = v >>> 16 & 0xff;
55
+ arr[2] = v >>> 8 & 0xff;
56
+ arr[3] = v & 0xff; // Parse ........-####-....-....-............
57
+
58
+ arr[4] = (v = parseInt(uuid.slice(9, 13), 16)) >>> 8;
59
+ arr[5] = v & 0xff; // Parse ........-....-####-....-............
60
+
61
+ arr[6] = (v = parseInt(uuid.slice(14, 18), 16)) >>> 8;
62
+ arr[7] = v & 0xff; // Parse ........-....-....-####-............
63
+
64
+ arr[8] = (v = parseInt(uuid.slice(19, 23), 16)) >>> 8;
65
+ arr[9] = v & 0xff; // Parse ........-....-....-....-############
66
+ // (Use "/" to avoid 32-bit truncation when bit-shifting high-order bytes)
67
+
68
+ arr[10] = (v = parseInt(uuid.slice(24, 36), 16)) / 0x10000000000 & 0xff;
69
+ arr[11] = v / 0x100000000 & 0xff;
70
+ arr[12] = v >>> 24 & 0xff;
71
+ arr[13] = v >>> 16 & 0xff;
72
+ arr[14] = v >>> 8 & 0xff;
73
+ arr[15] = v & 0xff;
74
+ return arr;
42
75
  }
43
- function be(e) {
44
- return e && e.__esModule && Object.prototype.hasOwnProperty.call(e, "default") ? e.default : e;
76
+
77
+ function getDefaultExportFromCjs (x) {
78
+ return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
45
79
  }
46
- var $ = {}, T = {}, P = {}, se = {}, J = {}, pe;
47
- function We() {
48
- return pe || (pe = 1, Object.defineProperty(J, "__esModule", { value: !0 }), J.crypto = void 0, J.crypto = typeof globalThis == "object" && "crypto" in globalThis ? globalThis.crypto : void 0), J;
80
+
81
+ var sha256 = {};
82
+
83
+ var sha2 = {};
84
+
85
+ var _md = {};
86
+
87
+ var utils = {};
88
+
89
+ var crypto = {};
90
+
91
+ var hasRequiredCrypto;
92
+
93
+ function requireCrypto () {
94
+ if (hasRequiredCrypto) return crypto;
95
+ hasRequiredCrypto = 1;
96
+ Object.defineProperty(crypto, "__esModule", { value: true });
97
+ crypto.crypto = void 0;
98
+ crypto.crypto = typeof globalThis === 'object' && 'crypto' in globalThis ? globalThis.crypto : undefined;
99
+
100
+ return crypto;
49
101
  }
50
- var He;
51
- function Ce() {
52
- return He || (He = 1, function(e) {
53
- /*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */
54
- Object.defineProperty(e, "__esModule", { value: !0 }), e.wrapXOFConstructorWithOpts = e.wrapConstructorWithOpts = e.wrapConstructor = e.Hash = e.nextTick = e.swap32IfBE = e.byteSwapIfBE = e.swap8IfBE = e.isLE = void 0, e.isBytes = n, e.anumber = H, e.abytes = y, e.ahash = w, e.aexists = a, e.aoutput = c, e.u8 = s, e.u32 = o, e.clean = i, e.createView = h, e.rotr = m, e.rotl = B, e.byteSwap = f, e.byteSwap32 = g, e.bytesToHex = M, e.hexToBytes = A, e.asyncLoop = L, e.utf8ToBytes = E, e.bytesToUtf8 = u, e.toBytes = l, e.kdfInputToBytes = b, e.concatBytes = C, e.checkOpts = S, e.createHasher = O, e.createOptHasher = F, e.createXOFer = q, e.randomBytes = j;
55
- const t = /* @__PURE__ */ We();
56
- function n(r) {
57
- return r instanceof Uint8Array || ArrayBuffer.isView(r) && r.constructor.name === "Uint8Array";
58
- }
59
- function H(r) {
60
- if (!Number.isSafeInteger(r) || r < 0)
61
- throw new Error("positive integer expected, got " + r);
62
- }
63
- function y(r, ...p) {
64
- if (!n(r))
65
- throw new Error("Uint8Array expected");
66
- if (p.length > 0 && !p.includes(r.length))
67
- throw new Error("Uint8Array expected of length " + p + ", got length=" + r.length);
68
- }
69
- function w(r) {
70
- if (typeof r != "function" || typeof r.create != "function")
71
- throw new Error("Hash should be wrapped by utils.createHasher");
72
- H(r.outputLen), H(r.blockLen);
73
- }
74
- function a(r, p = !0) {
75
- if (r.destroyed)
76
- throw new Error("Hash instance has been destroyed");
77
- if (p && r.finished)
78
- throw new Error("Hash#digest() has already been called");
79
- }
80
- function c(r, p) {
81
- y(r);
82
- const v = p.outputLen;
83
- if (r.length < v)
84
- throw new Error("digestInto() expects output buffer of length at least " + v);
85
- }
86
- function s(r) {
87
- return new Uint8Array(r.buffer, r.byteOffset, r.byteLength);
88
- }
89
- function o(r) {
90
- return new Uint32Array(r.buffer, r.byteOffset, Math.floor(r.byteLength / 4));
91
- }
92
- function i(...r) {
93
- for (let p = 0; p < r.length; p++)
94
- r[p].fill(0);
95
- }
96
- function h(r) {
97
- return new DataView(r.buffer, r.byteOffset, r.byteLength);
98
- }
99
- function m(r, p) {
100
- return r << 32 - p | r >>> p;
101
- }
102
- function B(r, p) {
103
- return r << p | r >>> 32 - p >>> 0;
104
- }
105
- e.isLE = new Uint8Array(new Uint32Array([287454020]).buffer)[0] === 68;
106
- function f(r) {
107
- return r << 24 & 4278190080 | r << 8 & 16711680 | r >>> 8 & 65280 | r >>> 24 & 255;
108
- }
109
- e.swap8IfBE = e.isLE ? (r) => r : (r) => f(r), e.byteSwapIfBE = e.swap8IfBE;
110
- function g(r) {
111
- for (let p = 0; p < r.length; p++)
112
- r[p] = f(r[p]);
113
- return r;
114
- }
115
- e.swap32IfBE = e.isLE ? (r) => r : g;
116
- const d = /* @ts-ignore */ typeof Uint8Array.from([]).toHex == "function" && typeof Uint8Array.fromHex == "function", V = /* @__PURE__ */ Array.from({ length: 256 }, (r, p) => p.toString(16).padStart(2, "0"));
117
- function M(r) {
118
- if (y(r), d)
119
- return r.toHex();
120
- let p = "";
121
- for (let v = 0; v < r.length; v++)
122
- p += V[r[v]];
123
- return p;
124
- }
125
- const x = { _0: 48, _9: 57, A: 65, F: 70, a: 97, f: 102 };
126
- function R(r) {
127
- if (r >= x._0 && r <= x._9)
128
- return r - x._0;
129
- if (r >= x.A && r <= x.F)
130
- return r - (x.A - 10);
131
- if (r >= x.a && r <= x.f)
132
- return r - (x.a - 10);
133
- }
134
- function A(r) {
135
- if (typeof r != "string")
136
- throw new Error("hex string expected, got " + typeof r);
137
- if (d)
138
- return Uint8Array.fromHex(r);
139
- const p = r.length, v = p / 2;
140
- if (p % 2)
141
- throw new Error("hex string expected, got unpadded hex of length " + p);
142
- const D = new Uint8Array(v);
143
- for (let k = 0, G = 0; k < v; k++, G += 2) {
144
- const K = R(r.charCodeAt(G)), W = R(r.charCodeAt(G + 1));
145
- if (K === void 0 || W === void 0) {
146
- const N = r[G] + r[G + 1];
147
- throw new Error('hex string expected, got non-hex character "' + N + '" at index ' + G);
148
- }
149
- D[k] = K * 16 + W;
150
- }
151
- return D;
152
- }
153
- const I = async () => {
154
- };
155
- e.nextTick = I;
156
- async function L(r, p, v) {
157
- let D = Date.now();
158
- for (let k = 0; k < r; k++) {
159
- v(k);
160
- const G = Date.now() - D;
161
- G >= 0 && G < p || (await (0, e.nextTick)(), D += G);
162
- }
163
- }
164
- function E(r) {
165
- if (typeof r != "string")
166
- throw new Error("string expected");
167
- return new Uint8Array(new TextEncoder().encode(r));
168
- }
169
- function u(r) {
170
- return new TextDecoder().decode(r);
171
- }
172
- function l(r) {
173
- return typeof r == "string" && (r = E(r)), y(r), r;
174
- }
175
- function b(r) {
176
- return typeof r == "string" && (r = E(r)), y(r), r;
177
- }
178
- function C(...r) {
179
- let p = 0;
180
- for (let D = 0; D < r.length; D++) {
181
- const k = r[D];
182
- y(k), p += k.length;
183
- }
184
- const v = new Uint8Array(p);
185
- for (let D = 0, k = 0; D < r.length; D++) {
186
- const G = r[D];
187
- v.set(G, k), k += G.length;
188
- }
189
- return v;
190
- }
191
- function S(r, p) {
192
- if (p !== void 0 && {}.toString.call(p) !== "[object Object]")
193
- throw new Error("options should be object or undefined");
194
- return Object.assign(r, p);
195
- }
196
- class U {
197
- }
198
- e.Hash = U;
199
- function O(r) {
200
- const p = (D) => r().update(l(D)).digest(), v = r();
201
- return p.outputLen = v.outputLen, p.blockLen = v.blockLen, p.create = () => r(), p;
202
- }
203
- function F(r) {
204
- const p = (D, k) => r(k).update(l(D)).digest(), v = r({});
205
- return p.outputLen = v.outputLen, p.blockLen = v.blockLen, p.create = (D) => r(D), p;
206
- }
207
- function q(r) {
208
- const p = (D, k) => r(k).update(l(D)).digest(), v = r({});
209
- return p.outputLen = v.outputLen, p.blockLen = v.blockLen, p.create = (D) => r(D), p;
210
- }
211
- e.wrapConstructor = O, e.wrapConstructorWithOpts = F, e.wrapXOFConstructorWithOpts = q;
212
- function j(r = 32) {
213
- if (t.crypto && typeof t.crypto.getRandomValues == "function")
214
- return t.crypto.getRandomValues(new Uint8Array(r));
215
- if (t.crypto && typeof t.crypto.randomBytes == "function")
216
- return Uint8Array.from(t.crypto.randomBytes(r));
217
- throw new Error("crypto.getRandomValues must be defined");
218
- }
219
- }(se)), se;
102
+
103
+ var hasRequiredUtils;
104
+
105
+ function requireUtils () {
106
+ if (hasRequiredUtils) return utils;
107
+ hasRequiredUtils = 1;
108
+ (function (exports) {
109
+ /**
110
+ * Utilities for hex, bytes, CSPRNG.
111
+ * @module
112
+ */
113
+ /*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */
114
+ Object.defineProperty(exports, "__esModule", { value: true });
115
+ exports.wrapXOFConstructorWithOpts = exports.wrapConstructorWithOpts = exports.wrapConstructor = exports.Hash = exports.nextTick = exports.swap32IfBE = exports.byteSwapIfBE = exports.swap8IfBE = exports.isLE = void 0;
116
+ exports.isBytes = isBytes;
117
+ exports.anumber = anumber;
118
+ exports.abytes = abytes;
119
+ exports.ahash = ahash;
120
+ exports.aexists = aexists;
121
+ exports.aoutput = aoutput;
122
+ exports.u8 = u8;
123
+ exports.u32 = u32;
124
+ exports.clean = clean;
125
+ exports.createView = createView;
126
+ exports.rotr = rotr;
127
+ exports.rotl = rotl;
128
+ exports.byteSwap = byteSwap;
129
+ exports.byteSwap32 = byteSwap32;
130
+ exports.bytesToHex = bytesToHex;
131
+ exports.hexToBytes = hexToBytes;
132
+ exports.asyncLoop = asyncLoop;
133
+ exports.utf8ToBytes = utf8ToBytes;
134
+ exports.bytesToUtf8 = bytesToUtf8;
135
+ exports.toBytes = toBytes;
136
+ exports.kdfInputToBytes = kdfInputToBytes;
137
+ exports.concatBytes = concatBytes;
138
+ exports.checkOpts = checkOpts;
139
+ exports.createHasher = createHasher;
140
+ exports.createOptHasher = createOptHasher;
141
+ exports.createXOFer = createXOFer;
142
+ exports.randomBytes = randomBytes;
143
+ // We use WebCrypto aka globalThis.crypto, which exists in browsers and node.js 16+.
144
+ // node.js versions earlier than v19 don't declare it in global scope.
145
+ // For node.js, package.json#exports field mapping rewrites import
146
+ // from `crypto` to `cryptoNode`, which imports native module.
147
+ // Makes the utils un-importable in browsers without a bundler.
148
+ // Once node.js 18 is deprecated (2025-04-30), we can just drop the import.
149
+ const crypto_1 = /*@__PURE__*/ requireCrypto();
150
+ /** Checks if something is Uint8Array. Be careful: nodejs Buffer will return true. */
151
+ function isBytes(a) {
152
+ return a instanceof Uint8Array || (ArrayBuffer.isView(a) && a.constructor.name === 'Uint8Array');
153
+ }
154
+ /** Asserts something is positive integer. */
155
+ function anumber(n) {
156
+ if (!Number.isSafeInteger(n) || n < 0)
157
+ throw new Error('positive integer expected, got ' + n);
158
+ }
159
+ /** Asserts something is Uint8Array. */
160
+ function abytes(b, ...lengths) {
161
+ if (!isBytes(b))
162
+ throw new Error('Uint8Array expected');
163
+ if (lengths.length > 0 && !lengths.includes(b.length))
164
+ throw new Error('Uint8Array expected of length ' + lengths + ', got length=' + b.length);
165
+ }
166
+ /** Asserts something is hash */
167
+ function ahash(h) {
168
+ if (typeof h !== 'function' || typeof h.create !== 'function')
169
+ throw new Error('Hash should be wrapped by utils.createHasher');
170
+ anumber(h.outputLen);
171
+ anumber(h.blockLen);
172
+ }
173
+ /** Asserts a hash instance has not been destroyed / finished */
174
+ function aexists(instance, checkFinished = true) {
175
+ if (instance.destroyed)
176
+ throw new Error('Hash instance has been destroyed');
177
+ if (checkFinished && instance.finished)
178
+ throw new Error('Hash#digest() has already been called');
179
+ }
180
+ /** Asserts output is properly-sized byte array */
181
+ function aoutput(out, instance) {
182
+ abytes(out);
183
+ const min = instance.outputLen;
184
+ if (out.length < min) {
185
+ throw new Error('digestInto() expects output buffer of length at least ' + min);
186
+ }
187
+ }
188
+ /** Cast u8 / u16 / u32 to u8. */
189
+ function u8(arr) {
190
+ return new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength);
191
+ }
192
+ /** Cast u8 / u16 / u32 to u32. */
193
+ function u32(arr) {
194
+ return new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4));
195
+ }
196
+ /** Zeroize a byte array. Warning: JS provides no guarantees. */
197
+ function clean(...arrays) {
198
+ for (let i = 0; i < arrays.length; i++) {
199
+ arrays[i].fill(0);
200
+ }
201
+ }
202
+ /** Create DataView of an array for easy byte-level manipulation. */
203
+ function createView(arr) {
204
+ return new DataView(arr.buffer, arr.byteOffset, arr.byteLength);
205
+ }
206
+ /** The rotate right (circular right shift) operation for uint32 */
207
+ function rotr(word, shift) {
208
+ return (word << (32 - shift)) | (word >>> shift);
209
+ }
210
+ /** The rotate left (circular left shift) operation for uint32 */
211
+ function rotl(word, shift) {
212
+ return (word << shift) | ((word >>> (32 - shift)) >>> 0);
213
+ }
214
+ /** Is current platform little-endian? Most are. Big-Endian platform: IBM */
215
+ exports.isLE = (() => new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44)();
216
+ /** The byte swap operation for uint32 */
217
+ function byteSwap(word) {
218
+ return (((word << 24) & 0xff000000) |
219
+ ((word << 8) & 0xff0000) |
220
+ ((word >>> 8) & 0xff00) |
221
+ ((word >>> 24) & 0xff));
222
+ }
223
+ /** Conditionally byte swap if on a big-endian platform */
224
+ exports.swap8IfBE = exports.isLE
225
+ ? (n) => n
226
+ : (n) => byteSwap(n);
227
+ /** @deprecated */
228
+ exports.byteSwapIfBE = exports.swap8IfBE;
229
+ /** In place byte swap for Uint32Array */
230
+ function byteSwap32(arr) {
231
+ for (let i = 0; i < arr.length; i++) {
232
+ arr[i] = byteSwap(arr[i]);
233
+ }
234
+ return arr;
235
+ }
236
+ exports.swap32IfBE = exports.isLE
237
+ ? (u) => u
238
+ : byteSwap32;
239
+ // Built-in hex conversion https://caniuse.com/mdn-javascript_builtins_uint8array_fromhex
240
+ const hasHexBuiltin = /* @__PURE__ */ (() =>
241
+ // @ts-ignore
242
+ typeof Uint8Array.from([]).toHex === 'function' && typeof Uint8Array.fromHex === 'function')();
243
+ // Array where index 0xf0 (240) is mapped to string 'f0'
244
+ const hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, '0'));
245
+ /**
246
+ * Convert byte array to hex string. Uses built-in function, when available.
247
+ * @example bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])) // 'cafe0123'
248
+ */
249
+ function bytesToHex(bytes) {
250
+ abytes(bytes);
251
+ // @ts-ignore
252
+ if (hasHexBuiltin)
253
+ return bytes.toHex();
254
+ // pre-caching improves the speed 6x
255
+ let hex = '';
256
+ for (let i = 0; i < bytes.length; i++) {
257
+ hex += hexes[bytes[i]];
258
+ }
259
+ return hex;
260
+ }
261
+ // We use optimized technique to convert hex string to byte array
262
+ const asciis = { _0: 48, _9: 57, A: 65, F: 70, a: 97, f: 102 };
263
+ function asciiToBase16(ch) {
264
+ if (ch >= asciis._0 && ch <= asciis._9)
265
+ return ch - asciis._0; // '2' => 50-48
266
+ if (ch >= asciis.A && ch <= asciis.F)
267
+ return ch - (asciis.A - 10); // 'B' => 66-(65-10)
268
+ if (ch >= asciis.a && ch <= asciis.f)
269
+ return ch - (asciis.a - 10); // 'b' => 98-(97-10)
270
+ return;
271
+ }
272
+ /**
273
+ * Convert hex string to byte array. Uses built-in function, when available.
274
+ * @example hexToBytes('cafe0123') // Uint8Array.from([0xca, 0xfe, 0x01, 0x23])
275
+ */
276
+ function hexToBytes(hex) {
277
+ if (typeof hex !== 'string')
278
+ throw new Error('hex string expected, got ' + typeof hex);
279
+ // @ts-ignore
280
+ if (hasHexBuiltin)
281
+ return Uint8Array.fromHex(hex);
282
+ const hl = hex.length;
283
+ const al = hl / 2;
284
+ if (hl % 2)
285
+ throw new Error('hex string expected, got unpadded hex of length ' + hl);
286
+ const array = new Uint8Array(al);
287
+ for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {
288
+ const n1 = asciiToBase16(hex.charCodeAt(hi));
289
+ const n2 = asciiToBase16(hex.charCodeAt(hi + 1));
290
+ if (n1 === undefined || n2 === undefined) {
291
+ const char = hex[hi] + hex[hi + 1];
292
+ throw new Error('hex string expected, got non-hex character "' + char + '" at index ' + hi);
293
+ }
294
+ array[ai] = n1 * 16 + n2; // multiply first octet, e.g. 'a3' => 10*16+3 => 160 + 3 => 163
295
+ }
296
+ return array;
297
+ }
298
+ /**
299
+ * There is no setImmediate in browser and setTimeout is slow.
300
+ * Call of async fn will return Promise, which will be fullfiled only on
301
+ * next scheduler queue processing step and this is exactly what we need.
302
+ */
303
+ const nextTick = async () => { };
304
+ exports.nextTick = nextTick;
305
+ /** Returns control to thread each 'tick' ms to avoid blocking. */
306
+ async function asyncLoop(iters, tick, cb) {
307
+ let ts = Date.now();
308
+ for (let i = 0; i < iters; i++) {
309
+ cb(i);
310
+ // Date.now() is not monotonic, so in case if clock goes backwards we return return control too
311
+ const diff = Date.now() - ts;
312
+ if (diff >= 0 && diff < tick)
313
+ continue;
314
+ await (0, exports.nextTick)();
315
+ ts += diff;
316
+ }
317
+ }
318
+ /**
319
+ * Converts string to bytes using UTF8 encoding.
320
+ * @example utf8ToBytes('abc') // Uint8Array.from([97, 98, 99])
321
+ */
322
+ function utf8ToBytes(str) {
323
+ if (typeof str !== 'string')
324
+ throw new Error('string expected');
325
+ return new Uint8Array(new TextEncoder().encode(str)); // https://bugzil.la/1681809
326
+ }
327
+ /**
328
+ * Converts bytes to string using UTF8 encoding.
329
+ * @example bytesToUtf8(Uint8Array.from([97, 98, 99])) // 'abc'
330
+ */
331
+ function bytesToUtf8(bytes) {
332
+ return new TextDecoder().decode(bytes);
333
+ }
334
+ /**
335
+ * Normalizes (non-hex) string or Uint8Array to Uint8Array.
336
+ * Warning: when Uint8Array is passed, it would NOT get copied.
337
+ * Keep in mind for future mutable operations.
338
+ */
339
+ function toBytes(data) {
340
+ if (typeof data === 'string')
341
+ data = utf8ToBytes(data);
342
+ abytes(data);
343
+ return data;
344
+ }
345
+ /**
346
+ * Helper for KDFs: consumes uint8array or string.
347
+ * When string is passed, does utf8 decoding, using TextDecoder.
348
+ */
349
+ function kdfInputToBytes(data) {
350
+ if (typeof data === 'string')
351
+ data = utf8ToBytes(data);
352
+ abytes(data);
353
+ return data;
354
+ }
355
+ /** Copies several Uint8Arrays into one. */
356
+ function concatBytes(...arrays) {
357
+ let sum = 0;
358
+ for (let i = 0; i < arrays.length; i++) {
359
+ const a = arrays[i];
360
+ abytes(a);
361
+ sum += a.length;
362
+ }
363
+ const res = new Uint8Array(sum);
364
+ for (let i = 0, pad = 0; i < arrays.length; i++) {
365
+ const a = arrays[i];
366
+ res.set(a, pad);
367
+ pad += a.length;
368
+ }
369
+ return res;
370
+ }
371
+ function checkOpts(defaults, opts) {
372
+ if (opts !== undefined && {}.toString.call(opts) !== '[object Object]')
373
+ throw new Error('options should be object or undefined');
374
+ const merged = Object.assign(defaults, opts);
375
+ return merged;
376
+ }
377
+ /** For runtime check if class implements interface */
378
+ class Hash {
379
+ }
380
+ exports.Hash = Hash;
381
+ /** Wraps hash function, creating an interface on top of it */
382
+ function createHasher(hashCons) {
383
+ const hashC = (msg) => hashCons().update(toBytes(msg)).digest();
384
+ const tmp = hashCons();
385
+ hashC.outputLen = tmp.outputLen;
386
+ hashC.blockLen = tmp.blockLen;
387
+ hashC.create = () => hashCons();
388
+ return hashC;
389
+ }
390
+ function createOptHasher(hashCons) {
391
+ const hashC = (msg, opts) => hashCons(opts).update(toBytes(msg)).digest();
392
+ const tmp = hashCons({});
393
+ hashC.outputLen = tmp.outputLen;
394
+ hashC.blockLen = tmp.blockLen;
395
+ hashC.create = (opts) => hashCons(opts);
396
+ return hashC;
397
+ }
398
+ function createXOFer(hashCons) {
399
+ const hashC = (msg, opts) => hashCons(opts).update(toBytes(msg)).digest();
400
+ const tmp = hashCons({});
401
+ hashC.outputLen = tmp.outputLen;
402
+ hashC.blockLen = tmp.blockLen;
403
+ hashC.create = (opts) => hashCons(opts);
404
+ return hashC;
405
+ }
406
+ exports.wrapConstructor = createHasher;
407
+ exports.wrapConstructorWithOpts = createOptHasher;
408
+ exports.wrapXOFConstructorWithOpts = createXOFer;
409
+ /** Cryptographically secure PRNG. Uses internal OS-level `crypto.getRandomValues`. */
410
+ function randomBytes(bytesLength = 32) {
411
+ if (crypto_1.crypto && typeof crypto_1.crypto.getRandomValues === 'function') {
412
+ return crypto_1.crypto.getRandomValues(new Uint8Array(bytesLength));
413
+ }
414
+ // Legacy Node.js compatibility
415
+ if (crypto_1.crypto && typeof crypto_1.crypto.randomBytes === 'function') {
416
+ return Uint8Array.from(crypto_1.crypto.randomBytes(bytesLength));
417
+ }
418
+ throw new Error('crypto.getRandomValues must be defined');
419
+ }
420
+
421
+ } (utils));
422
+ return utils;
220
423
  }
221
- var ye;
222
- function Ne() {
223
- if (ye) return P;
224
- ye = 1, Object.defineProperty(P, "__esModule", { value: !0 }), P.SHA512_IV = P.SHA384_IV = P.SHA224_IV = P.SHA256_IV = P.HashMD = void 0, P.setBigUint64 = t, P.Chi = n, P.Maj = H;
225
- const e = /* @__PURE__ */ Ce();
226
- function t(w, a, c, s) {
227
- if (typeof w.setBigUint64 == "function")
228
- return w.setBigUint64(a, c, s);
229
- const o = BigInt(32), i = BigInt(4294967295), h = Number(c >> o & i), m = Number(c & i), B = s ? 4 : 0, f = s ? 0 : 4;
230
- w.setUint32(a + B, h, s), w.setUint32(a + f, m, s);
231
- }
232
- function n(w, a, c) {
233
- return w & a ^ ~w & c;
234
- }
235
- function H(w, a, c) {
236
- return w & a ^ w & c ^ a & c;
237
- }
238
- class y extends e.Hash {
239
- constructor(a, c, s, o) {
240
- super(), this.finished = !1, this.length = 0, this.pos = 0, this.destroyed = !1, this.blockLen = a, this.outputLen = c, this.padOffset = s, this.isLE = o, this.buffer = new Uint8Array(a), this.view = (0, e.createView)(this.buffer);
241
- }
242
- update(a) {
243
- (0, e.aexists)(this), a = (0, e.toBytes)(a), (0, e.abytes)(a);
244
- const { view: c, buffer: s, blockLen: o } = this, i = a.length;
245
- for (let h = 0; h < i; ) {
246
- const m = Math.min(o - this.pos, i - h);
247
- if (m === o) {
248
- const B = (0, e.createView)(a);
249
- for (; o <= i - h; h += o)
250
- this.process(B, h);
251
- continue;
252
- }
253
- s.set(a.subarray(h, h + m), this.pos), this.pos += m, h += m, this.pos === o && (this.process(c, 0), this.pos = 0);
254
- }
255
- return this.length += a.length, this.roundClean(), this;
256
- }
257
- digestInto(a) {
258
- (0, e.aexists)(this), (0, e.aoutput)(a, this), this.finished = !0;
259
- const { buffer: c, view: s, blockLen: o, isLE: i } = this;
260
- let { pos: h } = this;
261
- c[h++] = 128, (0, e.clean)(this.buffer.subarray(h)), this.padOffset > o - h && (this.process(s, 0), h = 0);
262
- for (let d = h; d < o; d++)
263
- c[d] = 0;
264
- t(s, o - 8, BigInt(this.length * 8), i), this.process(s, 0);
265
- const m = (0, e.createView)(a), B = this.outputLen;
266
- if (B % 4)
267
- throw new Error("_sha2: outputLen should be aligned to 32bit");
268
- const f = B / 4, g = this.get();
269
- if (f > g.length)
270
- throw new Error("_sha2: outputLen bigger than state");
271
- for (let d = 0; d < f; d++)
272
- m.setUint32(4 * d, g[d], i);
273
- }
274
- digest() {
275
- const { buffer: a, outputLen: c } = this;
276
- this.digestInto(a);
277
- const s = a.slice(0, c);
278
- return this.destroy(), s;
279
- }
280
- _cloneInto(a) {
281
- a || (a = new this.constructor()), a.set(...this.get());
282
- const { blockLen: c, buffer: s, length: o, finished: i, destroyed: h, pos: m } = this;
283
- return a.destroyed = h, a.finished = i, a.length = o, a.pos = m, o % c && a.buffer.set(s), a;
284
- }
285
- clone() {
286
- return this._cloneInto();
287
- }
288
- }
289
- return P.HashMD = y, P.SHA256_IV = Uint32Array.from([
290
- 1779033703,
291
- 3144134277,
292
- 1013904242,
293
- 2773480762,
294
- 1359893119,
295
- 2600822924,
296
- 528734635,
297
- 1541459225
298
- ]), P.SHA224_IV = Uint32Array.from([
299
- 3238371032,
300
- 914150663,
301
- 812702999,
302
- 4144912697,
303
- 4290775857,
304
- 1750603025,
305
- 1694076839,
306
- 3204075428
307
- ]), P.SHA384_IV = Uint32Array.from([
308
- 3418070365,
309
- 3238371032,
310
- 1654270250,
311
- 914150663,
312
- 2438529370,
313
- 812702999,
314
- 355462360,
315
- 4144912697,
316
- 1731405415,
317
- 4290775857,
318
- 2394180231,
319
- 1750603025,
320
- 3675008525,
321
- 1694076839,
322
- 1203062813,
323
- 3204075428
324
- ]), P.SHA512_IV = Uint32Array.from([
325
- 1779033703,
326
- 4089235720,
327
- 3144134277,
328
- 2227873595,
329
- 1013904242,
330
- 4271175723,
331
- 2773480762,
332
- 1595750129,
333
- 1359893119,
334
- 2917565137,
335
- 2600822924,
336
- 725511199,
337
- 528734635,
338
- 4215389547,
339
- 1541459225,
340
- 327033209
341
- ]), P;
424
+
425
+ var hasRequired_md;
426
+
427
+ function require_md () {
428
+ if (hasRequired_md) return _md;
429
+ hasRequired_md = 1;
430
+ Object.defineProperty(_md, "__esModule", { value: true });
431
+ _md.SHA512_IV = _md.SHA384_IV = _md.SHA224_IV = _md.SHA256_IV = _md.HashMD = void 0;
432
+ _md.setBigUint64 = setBigUint64;
433
+ _md.Chi = Chi;
434
+ _md.Maj = Maj;
435
+ /**
436
+ * Internal Merkle-Damgard hash utils.
437
+ * @module
438
+ */
439
+ const utils_ts_1 = /*@__PURE__*/ requireUtils();
440
+ /** Polyfill for Safari 14. https://caniuse.com/mdn-javascript_builtins_dataview_setbiguint64 */
441
+ function setBigUint64(view, byteOffset, value, isLE) {
442
+ if (typeof view.setBigUint64 === 'function')
443
+ return view.setBigUint64(byteOffset, value, isLE);
444
+ const _32n = BigInt(32);
445
+ const _u32_max = BigInt(0xffffffff);
446
+ const wh = Number((value >> _32n) & _u32_max);
447
+ const wl = Number(value & _u32_max);
448
+ const h = isLE ? 4 : 0;
449
+ const l = isLE ? 0 : 4;
450
+ view.setUint32(byteOffset + h, wh, isLE);
451
+ view.setUint32(byteOffset + l, wl, isLE);
452
+ }
453
+ /** Choice: a ? b : c */
454
+ function Chi(a, b, c) {
455
+ return (a & b) ^ (~a & c);
456
+ }
457
+ /** Majority function, true if any two inputs is true. */
458
+ function Maj(a, b, c) {
459
+ return (a & b) ^ (a & c) ^ (b & c);
460
+ }
461
+ /**
462
+ * Merkle-Damgard hash construction base class.
463
+ * Could be used to create MD5, RIPEMD, SHA1, SHA2.
464
+ */
465
+ class HashMD extends utils_ts_1.Hash {
466
+ constructor(blockLen, outputLen, padOffset, isLE) {
467
+ super();
468
+ this.finished = false;
469
+ this.length = 0;
470
+ this.pos = 0;
471
+ this.destroyed = false;
472
+ this.blockLen = blockLen;
473
+ this.outputLen = outputLen;
474
+ this.padOffset = padOffset;
475
+ this.isLE = isLE;
476
+ this.buffer = new Uint8Array(blockLen);
477
+ this.view = (0, utils_ts_1.createView)(this.buffer);
478
+ }
479
+ update(data) {
480
+ (0, utils_ts_1.aexists)(this);
481
+ data = (0, utils_ts_1.toBytes)(data);
482
+ (0, utils_ts_1.abytes)(data);
483
+ const { view, buffer, blockLen } = this;
484
+ const len = data.length;
485
+ for (let pos = 0; pos < len;) {
486
+ const take = Math.min(blockLen - this.pos, len - pos);
487
+ // Fast path: we have at least one block in input, cast it to view and process
488
+ if (take === blockLen) {
489
+ const dataView = (0, utils_ts_1.createView)(data);
490
+ for (; blockLen <= len - pos; pos += blockLen)
491
+ this.process(dataView, pos);
492
+ continue;
493
+ }
494
+ buffer.set(data.subarray(pos, pos + take), this.pos);
495
+ this.pos += take;
496
+ pos += take;
497
+ if (this.pos === blockLen) {
498
+ this.process(view, 0);
499
+ this.pos = 0;
500
+ }
501
+ }
502
+ this.length += data.length;
503
+ this.roundClean();
504
+ return this;
505
+ }
506
+ digestInto(out) {
507
+ (0, utils_ts_1.aexists)(this);
508
+ (0, utils_ts_1.aoutput)(out, this);
509
+ this.finished = true;
510
+ // Padding
511
+ // We can avoid allocation of buffer for padding completely if it
512
+ // was previously not allocated here. But it won't change performance.
513
+ const { buffer, view, blockLen, isLE } = this;
514
+ let { pos } = this;
515
+ // append the bit '1' to the message
516
+ buffer[pos++] = 0b10000000;
517
+ (0, utils_ts_1.clean)(this.buffer.subarray(pos));
518
+ // we have less than padOffset left in buffer, so we cannot put length in
519
+ // current block, need process it and pad again
520
+ if (this.padOffset > blockLen - pos) {
521
+ this.process(view, 0);
522
+ pos = 0;
523
+ }
524
+ // Pad until full block byte with zeros
525
+ for (let i = pos; i < blockLen; i++)
526
+ buffer[i] = 0;
527
+ // Note: sha512 requires length to be 128bit integer, but length in JS will overflow before that
528
+ // You need to write around 2 exabytes (u64_max / 8 / (1024**6)) for this to happen.
529
+ // So we just write lowest 64 bits of that value.
530
+ setBigUint64(view, blockLen - 8, BigInt(this.length * 8), isLE);
531
+ this.process(view, 0);
532
+ const oview = (0, utils_ts_1.createView)(out);
533
+ const len = this.outputLen;
534
+ // NOTE: we do division by 4 later, which should be fused in single op with modulo by JIT
535
+ if (len % 4)
536
+ throw new Error('_sha2: outputLen should be aligned to 32bit');
537
+ const outLen = len / 4;
538
+ const state = this.get();
539
+ if (outLen > state.length)
540
+ throw new Error('_sha2: outputLen bigger than state');
541
+ for (let i = 0; i < outLen; i++)
542
+ oview.setUint32(4 * i, state[i], isLE);
543
+ }
544
+ digest() {
545
+ const { buffer, outputLen } = this;
546
+ this.digestInto(buffer);
547
+ const res = buffer.slice(0, outputLen);
548
+ this.destroy();
549
+ return res;
550
+ }
551
+ _cloneInto(to) {
552
+ to || (to = new this.constructor());
553
+ to.set(...this.get());
554
+ const { blockLen, buffer, length, finished, destroyed, pos } = this;
555
+ to.destroyed = destroyed;
556
+ to.finished = finished;
557
+ to.length = length;
558
+ to.pos = pos;
559
+ if (length % blockLen)
560
+ to.buffer.set(buffer);
561
+ return to;
562
+ }
563
+ clone() {
564
+ return this._cloneInto();
565
+ }
566
+ }
567
+ _md.HashMD = HashMD;
568
+ /**
569
+ * Initial SHA-2 state: fractional parts of square roots of first 16 primes 2..53.
570
+ * Check out `test/misc/sha2-gen-iv.js` for recomputation guide.
571
+ */
572
+ /** Initial SHA256 state. Bits 0..32 of frac part of sqrt of primes 2..19 */
573
+ _md.SHA256_IV = Uint32Array.from([
574
+ 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19,
575
+ ]);
576
+ /** Initial SHA224 state. Bits 32..64 of frac part of sqrt of primes 23..53 */
577
+ _md.SHA224_IV = Uint32Array.from([
578
+ 0xc1059ed8, 0x367cd507, 0x3070dd17, 0xf70e5939, 0xffc00b31, 0x68581511, 0x64f98fa7, 0xbefa4fa4,
579
+ ]);
580
+ /** Initial SHA384 state. Bits 0..64 of frac part of sqrt of primes 23..53 */
581
+ _md.SHA384_IV = Uint32Array.from([
582
+ 0xcbbb9d5d, 0xc1059ed8, 0x629a292a, 0x367cd507, 0x9159015a, 0x3070dd17, 0x152fecd8, 0xf70e5939,
583
+ 0x67332667, 0xffc00b31, 0x8eb44a87, 0x68581511, 0xdb0c2e0d, 0x64f98fa7, 0x47b5481d, 0xbefa4fa4,
584
+ ]);
585
+ /** Initial SHA512 state. Bits 0..64 of frac part of sqrt of primes 2..19 */
586
+ _md.SHA512_IV = Uint32Array.from([
587
+ 0x6a09e667, 0xf3bcc908, 0xbb67ae85, 0x84caa73b, 0x3c6ef372, 0xfe94f82b, 0xa54ff53a, 0x5f1d36f1,
588
+ 0x510e527f, 0xade682d1, 0x9b05688c, 0x2b3e6c1f, 0x1f83d9ab, 0xfb41bd6b, 0x5be0cd19, 0x137e2179,
589
+ ]);
590
+
591
+ return _md;
342
592
  }
343
- var _ = {}, Ae;
344
- function $e() {
345
- if (Ae) return _;
346
- Ae = 1, Object.defineProperty(_, "__esModule", { value: !0 }), _.toBig = _.shrSL = _.shrSH = _.rotrSL = _.rotrSH = _.rotrBL = _.rotrBH = _.rotr32L = _.rotr32H = _.rotlSL = _.rotlSH = _.rotlBL = _.rotlBH = _.add5L = _.add5H = _.add4L = _.add4H = _.add3L = _.add3H = void 0, _.add = V, _.fromBig = n, _.split = H;
347
- const e = /* @__PURE__ */ BigInt(2 ** 32 - 1), t = /* @__PURE__ */ BigInt(32);
348
- function n(u, l = !1) {
349
- return l ? { h: Number(u & e), l: Number(u >> t & e) } : { h: Number(u >> t & e) | 0, l: Number(u & e) | 0 };
350
- }
351
- function H(u, l = !1) {
352
- const b = u.length;
353
- let C = new Uint32Array(b), S = new Uint32Array(b);
354
- for (let U = 0; U < b; U++) {
355
- const { h: O, l: F } = n(u[U], l);
356
- [C[U], S[U]] = [O, F];
357
- }
358
- return [C, S];
359
- }
360
- const y = (u, l) => BigInt(u >>> 0) << t | BigInt(l >>> 0);
361
- _.toBig = y;
362
- const w = (u, l, b) => u >>> b;
363
- _.shrSH = w;
364
- const a = (u, l, b) => u << 32 - b | l >>> b;
365
- _.shrSL = a;
366
- const c = (u, l, b) => u >>> b | l << 32 - b;
367
- _.rotrSH = c;
368
- const s = (u, l, b) => u << 32 - b | l >>> b;
369
- _.rotrSL = s;
370
- const o = (u, l, b) => u << 64 - b | l >>> b - 32;
371
- _.rotrBH = o;
372
- const i = (u, l, b) => u >>> b - 32 | l << 64 - b;
373
- _.rotrBL = i;
374
- const h = (u, l) => l;
375
- _.rotr32H = h;
376
- const m = (u, l) => u;
377
- _.rotr32L = m;
378
- const B = (u, l, b) => u << b | l >>> 32 - b;
379
- _.rotlSH = B;
380
- const f = (u, l, b) => l << b | u >>> 32 - b;
381
- _.rotlSL = f;
382
- const g = (u, l, b) => l << b - 32 | u >>> 64 - b;
383
- _.rotlBH = g;
384
- const d = (u, l, b) => u << b - 32 | l >>> 64 - b;
385
- _.rotlBL = d;
386
- function V(u, l, b, C) {
387
- const S = (l >>> 0) + (C >>> 0);
388
- return { h: u + b + (S / 2 ** 32 | 0) | 0, l: S | 0 };
389
- }
390
- const M = (u, l, b) => (u >>> 0) + (l >>> 0) + (b >>> 0);
391
- _.add3L = M;
392
- const x = (u, l, b, C) => l + b + C + (u / 2 ** 32 | 0) | 0;
393
- _.add3H = x;
394
- const R = (u, l, b, C) => (u >>> 0) + (l >>> 0) + (b >>> 0) + (C >>> 0);
395
- _.add4L = R;
396
- const A = (u, l, b, C, S) => l + b + C + S + (u / 2 ** 32 | 0) | 0;
397
- _.add4H = A;
398
- const I = (u, l, b, C, S) => (u >>> 0) + (l >>> 0) + (b >>> 0) + (C >>> 0) + (S >>> 0);
399
- _.add5L = I;
400
- const L = (u, l, b, C, S, U) => l + b + C + S + U + (u / 2 ** 32 | 0) | 0;
401
- _.add5H = L;
402
- const E = {
403
- fromBig: n,
404
- split: H,
405
- toBig: y,
406
- shrSH: w,
407
- shrSL: a,
408
- rotrSH: c,
409
- rotrSL: s,
410
- rotrBH: o,
411
- rotrBL: i,
412
- rotr32H: h,
413
- rotr32L: m,
414
- rotlSH: B,
415
- rotlSL: f,
416
- rotlBH: g,
417
- rotlBL: d,
418
- add: V,
419
- add3L: M,
420
- add3H: x,
421
- add4L: R,
422
- add4H: A,
423
- add5H: L,
424
- add5L: I
425
- };
426
- return _.default = E, _;
593
+
594
+ var _u64 = {};
595
+
596
+ var hasRequired_u64;
597
+
598
+ function require_u64 () {
599
+ if (hasRequired_u64) return _u64;
600
+ hasRequired_u64 = 1;
601
+ Object.defineProperty(_u64, "__esModule", { value: true });
602
+ _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;
603
+ _u64.add = add;
604
+ _u64.fromBig = fromBig;
605
+ _u64.split = split;
606
+ /**
607
+ * Internal helpers for u64. BigUint64Array is too slow as per 2025, so we implement it using Uint32Array.
608
+ * @todo re-check https://issues.chromium.org/issues/42212588
609
+ * @module
610
+ */
611
+ const U32_MASK64 = /* @__PURE__ */ BigInt(2 ** 32 - 1);
612
+ const _32n = /* @__PURE__ */ BigInt(32);
613
+ function fromBig(n, le = false) {
614
+ if (le)
615
+ return { h: Number(n & U32_MASK64), l: Number((n >> _32n) & U32_MASK64) };
616
+ return { h: Number((n >> _32n) & U32_MASK64) | 0, l: Number(n & U32_MASK64) | 0 };
617
+ }
618
+ function split(lst, le = false) {
619
+ const len = lst.length;
620
+ let Ah = new Uint32Array(len);
621
+ let Al = new Uint32Array(len);
622
+ for (let i = 0; i < len; i++) {
623
+ const { h, l } = fromBig(lst[i], le);
624
+ [Ah[i], Al[i]] = [h, l];
625
+ }
626
+ return [Ah, Al];
627
+ }
628
+ const toBig = (h, l) => (BigInt(h >>> 0) << _32n) | BigInt(l >>> 0);
629
+ _u64.toBig = toBig;
630
+ // for Shift in [0, 32)
631
+ const shrSH = (h, _l, s) => h >>> s;
632
+ _u64.shrSH = shrSH;
633
+ const shrSL = (h, l, s) => (h << (32 - s)) | (l >>> s);
634
+ _u64.shrSL = shrSL;
635
+ // Right rotate for Shift in [1, 32)
636
+ const rotrSH = (h, l, s) => (h >>> s) | (l << (32 - s));
637
+ _u64.rotrSH = rotrSH;
638
+ const rotrSL = (h, l, s) => (h << (32 - s)) | (l >>> s);
639
+ _u64.rotrSL = rotrSL;
640
+ // Right rotate for Shift in (32, 64), NOTE: 32 is special case.
641
+ const rotrBH = (h, l, s) => (h << (64 - s)) | (l >>> (s - 32));
642
+ _u64.rotrBH = rotrBH;
643
+ const rotrBL = (h, l, s) => (h >>> (s - 32)) | (l << (64 - s));
644
+ _u64.rotrBL = rotrBL;
645
+ // Right rotate for shift===32 (just swaps l&h)
646
+ const rotr32H = (_h, l) => l;
647
+ _u64.rotr32H = rotr32H;
648
+ const rotr32L = (h, _l) => h;
649
+ _u64.rotr32L = rotr32L;
650
+ // Left rotate for Shift in [1, 32)
651
+ const rotlSH = (h, l, s) => (h << s) | (l >>> (32 - s));
652
+ _u64.rotlSH = rotlSH;
653
+ const rotlSL = (h, l, s) => (l << s) | (h >>> (32 - s));
654
+ _u64.rotlSL = rotlSL;
655
+ // Left rotate for Shift in (32, 64), NOTE: 32 is special case.
656
+ const rotlBH = (h, l, s) => (l << (s - 32)) | (h >>> (64 - s));
657
+ _u64.rotlBH = rotlBH;
658
+ const rotlBL = (h, l, s) => (h << (s - 32)) | (l >>> (64 - s));
659
+ _u64.rotlBL = rotlBL;
660
+ // JS uses 32-bit signed integers for bitwise operations which means we cannot
661
+ // simple take carry out of low bit sum by shift, we need to use division.
662
+ function add(Ah, Al, Bh, Bl) {
663
+ const l = (Al >>> 0) + (Bl >>> 0);
664
+ return { h: (Ah + Bh + ((l / 2 ** 32) | 0)) | 0, l: l | 0 };
665
+ }
666
+ // Addition with more than 2 elements
667
+ const add3L = (Al, Bl, Cl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0);
668
+ _u64.add3L = add3L;
669
+ const add3H = (low, Ah, Bh, Ch) => (Ah + Bh + Ch + ((low / 2 ** 32) | 0)) | 0;
670
+ _u64.add3H = add3H;
671
+ const add4L = (Al, Bl, Cl, Dl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0);
672
+ _u64.add4L = add4L;
673
+ const add4H = (low, Ah, Bh, Ch, Dh) => (Ah + Bh + Ch + Dh + ((low / 2 ** 32) | 0)) | 0;
674
+ _u64.add4H = add4H;
675
+ const add5L = (Al, Bl, Cl, Dl, El) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0) + (El >>> 0);
676
+ _u64.add5L = add5L;
677
+ const add5H = (low, Ah, Bh, Ch, Dh, Eh) => (Ah + Bh + Ch + Dh + Eh + ((low / 2 ** 32) | 0)) | 0;
678
+ _u64.add5H = add5H;
679
+ // prettier-ignore
680
+ const u64 = {
681
+ fromBig, split, toBig,
682
+ shrSH, shrSL,
683
+ rotrSH, rotrSL, rotrBH, rotrBL,
684
+ rotr32H, rotr32L,
685
+ rotlSH, rotlSL, rotlBH, rotlBL,
686
+ add, add3L, add3H, add4L, add4H, add5H, add5L,
687
+ };
688
+ _u64.default = u64;
689
+
690
+ return _u64;
427
691
  }
428
- var we;
429
- function ze() {
430
- if (we) return T;
431
- we = 1, Object.defineProperty(T, "__esModule", { value: !0 }), T.sha512_224 = T.sha512_256 = T.sha384 = T.sha512 = T.sha224 = T.sha256 = T.SHA512_256 = T.SHA512_224 = T.SHA384 = T.SHA512 = T.SHA224 = T.SHA256 = void 0;
432
- const e = /* @__PURE__ */ Ne(), t = /* @__PURE__ */ $e(), n = /* @__PURE__ */ Ce(), H = /* @__PURE__ */ Uint32Array.from([
433
- 1116352408,
434
- 1899447441,
435
- 3049323471,
436
- 3921009573,
437
- 961987163,
438
- 1508970993,
439
- 2453635748,
440
- 2870763221,
441
- 3624381080,
442
- 310598401,
443
- 607225278,
444
- 1426881987,
445
- 1925078388,
446
- 2162078206,
447
- 2614888103,
448
- 3248222580,
449
- 3835390401,
450
- 4022224774,
451
- 264347078,
452
- 604807628,
453
- 770255983,
454
- 1249150122,
455
- 1555081692,
456
- 1996064986,
457
- 2554220882,
458
- 2821834349,
459
- 2952996808,
460
- 3210313671,
461
- 3336571891,
462
- 3584528711,
463
- 113926993,
464
- 338241895,
465
- 666307205,
466
- 773529912,
467
- 1294757372,
468
- 1396182291,
469
- 1695183700,
470
- 1986661051,
471
- 2177026350,
472
- 2456956037,
473
- 2730485921,
474
- 2820302411,
475
- 3259730800,
476
- 3345764771,
477
- 3516065817,
478
- 3600352804,
479
- 4094571909,
480
- 275423344,
481
- 430227734,
482
- 506948616,
483
- 659060556,
484
- 883997877,
485
- 958139571,
486
- 1322822218,
487
- 1537002063,
488
- 1747873779,
489
- 1955562222,
490
- 2024104815,
491
- 2227730452,
492
- 2361852424,
493
- 2428436474,
494
- 2756734187,
495
- 3204031479,
496
- 3329325298
497
- ]), y = /* @__PURE__ */ new Uint32Array(64);
498
- class w extends e.HashMD {
499
- constructor(x = 32) {
500
- super(64, x, 8, !1), this.A = e.SHA256_IV[0] | 0, this.B = e.SHA256_IV[1] | 0, this.C = e.SHA256_IV[2] | 0, this.D = e.SHA256_IV[3] | 0, this.E = e.SHA256_IV[4] | 0, this.F = e.SHA256_IV[5] | 0, this.G = e.SHA256_IV[6] | 0, this.H = e.SHA256_IV[7] | 0;
501
- }
502
- get() {
503
- const { A: x, B: R, C: A, D: I, E: L, F: E, G: u, H: l } = this;
504
- return [x, R, A, I, L, E, u, l];
505
- }
506
- // prettier-ignore
507
- set(x, R, A, I, L, E, u, l) {
508
- this.A = x | 0, this.B = R | 0, this.C = A | 0, this.D = I | 0, this.E = L | 0, this.F = E | 0, this.G = u | 0, this.H = l | 0;
509
- }
510
- process(x, R) {
511
- for (let S = 0; S < 16; S++, R += 4)
512
- y[S] = x.getUint32(R, !1);
513
- for (let S = 16; S < 64; S++) {
514
- const U = y[S - 15], O = y[S - 2], F = (0, n.rotr)(U, 7) ^ (0, n.rotr)(U, 18) ^ U >>> 3, q = (0, n.rotr)(O, 17) ^ (0, n.rotr)(O, 19) ^ O >>> 10;
515
- y[S] = q + y[S - 7] + F + y[S - 16] | 0;
516
- }
517
- let { A, B: I, C: L, D: E, E: u, F: l, G: b, H: C } = this;
518
- for (let S = 0; S < 64; S++) {
519
- const U = (0, n.rotr)(u, 6) ^ (0, n.rotr)(u, 11) ^ (0, n.rotr)(u, 25), O = C + U + (0, e.Chi)(u, l, b) + H[S] + y[S] | 0, q = ((0, n.rotr)(A, 2) ^ (0, n.rotr)(A, 13) ^ (0, n.rotr)(A, 22)) + (0, e.Maj)(A, I, L) | 0;
520
- C = b, b = l, l = u, u = E + O | 0, E = L, L = I, I = A, A = O + q | 0;
521
- }
522
- A = A + this.A | 0, I = I + this.B | 0, L = L + this.C | 0, E = E + this.D | 0, u = u + this.E | 0, l = l + this.F | 0, b = b + this.G | 0, C = C + this.H | 0, this.set(A, I, L, E, u, l, b, C);
523
- }
524
- roundClean() {
525
- (0, n.clean)(y);
526
- }
527
- destroy() {
528
- this.set(0, 0, 0, 0, 0, 0, 0, 0), (0, n.clean)(this.buffer);
529
- }
530
- }
531
- T.SHA256 = w;
532
- class a extends w {
533
- constructor() {
534
- super(28), this.A = e.SHA224_IV[0] | 0, this.B = e.SHA224_IV[1] | 0, this.C = e.SHA224_IV[2] | 0, this.D = e.SHA224_IV[3] | 0, this.E = e.SHA224_IV[4] | 0, this.F = e.SHA224_IV[5] | 0, this.G = e.SHA224_IV[6] | 0, this.H = e.SHA224_IV[7] | 0;
535
- }
536
- }
537
- T.SHA224 = a;
538
- const c = t.split([
539
- "0x428a2f98d728ae22",
540
- "0x7137449123ef65cd",
541
- "0xb5c0fbcfec4d3b2f",
542
- "0xe9b5dba58189dbbc",
543
- "0x3956c25bf348b538",
544
- "0x59f111f1b605d019",
545
- "0x923f82a4af194f9b",
546
- "0xab1c5ed5da6d8118",
547
- "0xd807aa98a3030242",
548
- "0x12835b0145706fbe",
549
- "0x243185be4ee4b28c",
550
- "0x550c7dc3d5ffb4e2",
551
- "0x72be5d74f27b896f",
552
- "0x80deb1fe3b1696b1",
553
- "0x9bdc06a725c71235",
554
- "0xc19bf174cf692694",
555
- "0xe49b69c19ef14ad2",
556
- "0xefbe4786384f25e3",
557
- "0x0fc19dc68b8cd5b5",
558
- "0x240ca1cc77ac9c65",
559
- "0x2de92c6f592b0275",
560
- "0x4a7484aa6ea6e483",
561
- "0x5cb0a9dcbd41fbd4",
562
- "0x76f988da831153b5",
563
- "0x983e5152ee66dfab",
564
- "0xa831c66d2db43210",
565
- "0xb00327c898fb213f",
566
- "0xbf597fc7beef0ee4",
567
- "0xc6e00bf33da88fc2",
568
- "0xd5a79147930aa725",
569
- "0x06ca6351e003826f",
570
- "0x142929670a0e6e70",
571
- "0x27b70a8546d22ffc",
572
- "0x2e1b21385c26c926",
573
- "0x4d2c6dfc5ac42aed",
574
- "0x53380d139d95b3df",
575
- "0x650a73548baf63de",
576
- "0x766a0abb3c77b2a8",
577
- "0x81c2c92e47edaee6",
578
- "0x92722c851482353b",
579
- "0xa2bfe8a14cf10364",
580
- "0xa81a664bbc423001",
581
- "0xc24b8b70d0f89791",
582
- "0xc76c51a30654be30",
583
- "0xd192e819d6ef5218",
584
- "0xd69906245565a910",
585
- "0xf40e35855771202a",
586
- "0x106aa07032bbd1b8",
587
- "0x19a4c116b8d2d0c8",
588
- "0x1e376c085141ab53",
589
- "0x2748774cdf8eeb99",
590
- "0x34b0bcb5e19b48a8",
591
- "0x391c0cb3c5c95a63",
592
- "0x4ed8aa4ae3418acb",
593
- "0x5b9cca4f7763e373",
594
- "0x682e6ff3d6b2b8a3",
595
- "0x748f82ee5defb2fc",
596
- "0x78a5636f43172f60",
597
- "0x84c87814a1f0ab72",
598
- "0x8cc702081a6439ec",
599
- "0x90befffa23631e28",
600
- "0xa4506cebde82bde9",
601
- "0xbef9a3f7b2c67915",
602
- "0xc67178f2e372532b",
603
- "0xca273eceea26619c",
604
- "0xd186b8c721c0c207",
605
- "0xeada7dd6cde0eb1e",
606
- "0xf57d4f7fee6ed178",
607
- "0x06f067aa72176fba",
608
- "0x0a637dc5a2c898a6",
609
- "0x113f9804bef90dae",
610
- "0x1b710b35131c471b",
611
- "0x28db77f523047d84",
612
- "0x32caab7b40c72493",
613
- "0x3c9ebe0a15c9bebc",
614
- "0x431d67c49c100d4c",
615
- "0x4cc5d4becb3e42b6",
616
- "0x597f299cfc657e2a",
617
- "0x5fcb6fab3ad6faec",
618
- "0x6c44198c4a475817"
619
- ].map((M) => BigInt(M))), s = c[0], o = c[1], i = /* @__PURE__ */ new Uint32Array(80), h = /* @__PURE__ */ new Uint32Array(80);
620
- class m extends e.HashMD {
621
- constructor(x = 64) {
622
- super(128, x, 16, !1), this.Ah = e.SHA512_IV[0] | 0, this.Al = e.SHA512_IV[1] | 0, this.Bh = e.SHA512_IV[2] | 0, this.Bl = e.SHA512_IV[3] | 0, this.Ch = e.SHA512_IV[4] | 0, this.Cl = e.SHA512_IV[5] | 0, this.Dh = e.SHA512_IV[6] | 0, this.Dl = e.SHA512_IV[7] | 0, this.Eh = e.SHA512_IV[8] | 0, this.El = e.SHA512_IV[9] | 0, this.Fh = e.SHA512_IV[10] | 0, this.Fl = e.SHA512_IV[11] | 0, this.Gh = e.SHA512_IV[12] | 0, this.Gl = e.SHA512_IV[13] | 0, this.Hh = e.SHA512_IV[14] | 0, this.Hl = e.SHA512_IV[15] | 0;
623
- }
624
- // prettier-ignore
625
- get() {
626
- const { Ah: x, Al: R, Bh: A, Bl: I, Ch: L, Cl: E, Dh: u, Dl: l, Eh: b, El: C, Fh: S, Fl: U, Gh: O, Gl: F, Hh: q, Hl: j } = this;
627
- return [x, R, A, I, L, E, u, l, b, C, S, U, O, F, q, j];
628
- }
629
- // prettier-ignore
630
- set(x, R, A, I, L, E, u, l, b, C, S, U, O, F, q, j) {
631
- this.Ah = x | 0, this.Al = R | 0, this.Bh = A | 0, this.Bl = I | 0, this.Ch = L | 0, this.Cl = E | 0, this.Dh = u | 0, this.Dl = l | 0, this.Eh = b | 0, this.El = C | 0, this.Fh = S | 0, this.Fl = U | 0, this.Gh = O | 0, this.Gl = F | 0, this.Hh = q | 0, this.Hl = j | 0;
632
- }
633
- process(x, R) {
634
- for (let v = 0; v < 16; v++, R += 4)
635
- i[v] = x.getUint32(R), h[v] = x.getUint32(R += 4);
636
- for (let v = 16; v < 80; v++) {
637
- const D = i[v - 15] | 0, k = h[v - 15] | 0, G = t.rotrSH(D, k, 1) ^ t.rotrSH(D, k, 8) ^ t.shrSH(D, k, 7), K = t.rotrSL(D, k, 1) ^ t.rotrSL(D, k, 8) ^ t.shrSL(D, k, 7), W = i[v - 2] | 0, N = h[v - 2] | 0, Y = t.rotrSH(W, N, 19) ^ t.rotrBH(W, N, 61) ^ t.shrSH(W, N, 6), re = t.rotrSL(W, N, 19) ^ t.rotrBL(W, N, 61) ^ t.shrSL(W, N, 6), Z = t.add4L(K, re, h[v - 7], h[v - 16]), ne = t.add4H(Z, G, Y, i[v - 7], i[v - 16]);
638
- i[v] = ne | 0, h[v] = Z | 0;
639
- }
640
- let { Ah: A, Al: I, Bh: L, Bl: E, Ch: u, Cl: l, Dh: b, Dl: C, Eh: S, El: U, Fh: O, Fl: F, Gh: q, Gl: j, Hh: r, Hl: p } = this;
641
- for (let v = 0; v < 80; v++) {
642
- const D = t.rotrSH(S, U, 14) ^ t.rotrSH(S, U, 18) ^ t.rotrBH(S, U, 41), k = t.rotrSL(S, U, 14) ^ t.rotrSL(S, U, 18) ^ t.rotrBL(S, U, 41), G = S & O ^ ~S & q, K = U & F ^ ~U & j, W = t.add5L(p, k, K, o[v], h[v]), N = t.add5H(W, r, D, G, s[v], i[v]), Y = W | 0, re = t.rotrSH(A, I, 28) ^ t.rotrBH(A, I, 34) ^ t.rotrBH(A, I, 39), Z = t.rotrSL(A, I, 28) ^ t.rotrBL(A, I, 34) ^ t.rotrBL(A, I, 39), ne = A & L ^ A & u ^ L & u, Te = I & E ^ I & l ^ E & l;
643
- r = q | 0, p = j | 0, q = O | 0, j = F | 0, O = S | 0, F = U | 0, { h: S, l: U } = t.add(b | 0, C | 0, N | 0, Y | 0), b = u | 0, C = l | 0, u = L | 0, l = E | 0, L = A | 0, E = I | 0;
644
- const xe = t.add3L(Y, Z, Te);
645
- A = t.add3H(xe, N, re, ne), I = xe | 0;
646
- }
647
- ({ h: A, l: I } = t.add(this.Ah | 0, this.Al | 0, A | 0, I | 0)), { h: L, l: E } = t.add(this.Bh | 0, this.Bl | 0, L | 0, E | 0), { h: u, l } = t.add(this.Ch | 0, this.Cl | 0, u | 0, l | 0), { h: b, l: C } = t.add(this.Dh | 0, this.Dl | 0, b | 0, C | 0), { h: S, l: U } = t.add(this.Eh | 0, this.El | 0, S | 0, U | 0), { h: O, l: F } = t.add(this.Fh | 0, this.Fl | 0, O | 0, F | 0), { h: q, l: j } = t.add(this.Gh | 0, this.Gl | 0, q | 0, j | 0), { h: r, l: p } = t.add(this.Hh | 0, this.Hl | 0, r | 0, p | 0), this.set(A, I, L, E, u, l, b, C, S, U, O, F, q, j, r, p);
648
- }
649
- roundClean() {
650
- (0, n.clean)(i, h);
651
- }
652
- destroy() {
653
- (0, n.clean)(this.buffer), this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
654
- }
655
- }
656
- T.SHA512 = m;
657
- class B extends m {
658
- constructor() {
659
- super(48), this.Ah = e.SHA384_IV[0] | 0, this.Al = e.SHA384_IV[1] | 0, this.Bh = e.SHA384_IV[2] | 0, this.Bl = e.SHA384_IV[3] | 0, this.Ch = e.SHA384_IV[4] | 0, this.Cl = e.SHA384_IV[5] | 0, this.Dh = e.SHA384_IV[6] | 0, this.Dl = e.SHA384_IV[7] | 0, this.Eh = e.SHA384_IV[8] | 0, this.El = e.SHA384_IV[9] | 0, this.Fh = e.SHA384_IV[10] | 0, this.Fl = e.SHA384_IV[11] | 0, this.Gh = e.SHA384_IV[12] | 0, this.Gl = e.SHA384_IV[13] | 0, this.Hh = e.SHA384_IV[14] | 0, this.Hl = e.SHA384_IV[15] | 0;
660
- }
661
- }
662
- T.SHA384 = B;
663
- const f = /* @__PURE__ */ Uint32Array.from([
664
- 2352822216,
665
- 424955298,
666
- 1944164710,
667
- 2312950998,
668
- 502970286,
669
- 855612546,
670
- 1738396948,
671
- 1479516111,
672
- 258812777,
673
- 2077511080,
674
- 2011393907,
675
- 79989058,
676
- 1067287976,
677
- 1780299464,
678
- 286451373,
679
- 2446758561
680
- ]), g = /* @__PURE__ */ Uint32Array.from([
681
- 573645204,
682
- 4230739756,
683
- 2673172387,
684
- 3360449730,
685
- 596883563,
686
- 1867755857,
687
- 2520282905,
688
- 1497426621,
689
- 2519219938,
690
- 2827943907,
691
- 3193839141,
692
- 1401305490,
693
- 721525244,
694
- 746961066,
695
- 246885852,
696
- 2177182882
697
- ]);
698
- class d extends m {
699
- constructor() {
700
- super(28), this.Ah = f[0] | 0, this.Al = f[1] | 0, this.Bh = f[2] | 0, this.Bl = f[3] | 0, this.Ch = f[4] | 0, this.Cl = f[5] | 0, this.Dh = f[6] | 0, this.Dl = f[7] | 0, this.Eh = f[8] | 0, this.El = f[9] | 0, this.Fh = f[10] | 0, this.Fl = f[11] | 0, this.Gh = f[12] | 0, this.Gl = f[13] | 0, this.Hh = f[14] | 0, this.Hl = f[15] | 0;
701
- }
702
- }
703
- T.SHA512_224 = d;
704
- class V extends m {
705
- constructor() {
706
- super(32), this.Ah = g[0] | 0, this.Al = g[1] | 0, this.Bh = g[2] | 0, this.Bl = g[3] | 0, this.Ch = g[4] | 0, this.Cl = g[5] | 0, this.Dh = g[6] | 0, this.Dl = g[7] | 0, this.Eh = g[8] | 0, this.El = g[9] | 0, this.Fh = g[10] | 0, this.Fl = g[11] | 0, this.Gh = g[12] | 0, this.Gl = g[13] | 0, this.Hh = g[14] | 0, this.Hl = g[15] | 0;
707
- }
708
- }
709
- return T.SHA512_256 = V, T.sha256 = (0, n.createHasher)(() => new w()), T.sha224 = (0, n.createHasher)(() => new a()), T.sha512 = (0, n.createHasher)(() => new m()), T.sha384 = (0, n.createHasher)(() => new B()), T.sha512_256 = (0, n.createHasher)(() => new V()), T.sha512_224 = (0, n.createHasher)(() => new d()), T;
692
+
693
+ var hasRequiredSha2;
694
+
695
+ function requireSha2 () {
696
+ if (hasRequiredSha2) return sha2;
697
+ hasRequiredSha2 = 1;
698
+ Object.defineProperty(sha2, "__esModule", { value: true });
699
+ 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;
700
+ /**
701
+ * SHA2 hash function. A.k.a. sha256, sha384, sha512, sha512_224, sha512_256.
702
+ * SHA256 is the fastest hash implementable in JS, even faster than Blake3.
703
+ * Check out [RFC 4634](https://datatracker.ietf.org/doc/html/rfc4634) and
704
+ * [FIPS 180-4](https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.180-4.pdf).
705
+ * @module
706
+ */
707
+ const _md_ts_1 = /*@__PURE__*/ require_md();
708
+ const u64 = /*@__PURE__*/ require_u64();
709
+ const utils_ts_1 = /*@__PURE__*/ requireUtils();
710
+ /**
711
+ * Round constants:
712
+ * First 32 bits of fractional parts of the cube roots of the first 64 primes 2..311)
713
+ */
714
+ // prettier-ignore
715
+ const SHA256_K = /* @__PURE__ */ Uint32Array.from([
716
+ 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
717
+ 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
718
+ 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
719
+ 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,
720
+ 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
721
+ 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
722
+ 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
723
+ 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2
724
+ ]);
725
+ /** Reusable temporary buffer. "W" comes straight from spec. */
726
+ const SHA256_W = /* @__PURE__ */ new Uint32Array(64);
727
+ class SHA256 extends _md_ts_1.HashMD {
728
+ constructor(outputLen = 32) {
729
+ super(64, outputLen, 8, false);
730
+ // We cannot use array here since array allows indexing by variable
731
+ // which means optimizer/compiler cannot use registers.
732
+ this.A = _md_ts_1.SHA256_IV[0] | 0;
733
+ this.B = _md_ts_1.SHA256_IV[1] | 0;
734
+ this.C = _md_ts_1.SHA256_IV[2] | 0;
735
+ this.D = _md_ts_1.SHA256_IV[3] | 0;
736
+ this.E = _md_ts_1.SHA256_IV[4] | 0;
737
+ this.F = _md_ts_1.SHA256_IV[5] | 0;
738
+ this.G = _md_ts_1.SHA256_IV[6] | 0;
739
+ this.H = _md_ts_1.SHA256_IV[7] | 0;
740
+ }
741
+ get() {
742
+ const { A, B, C, D, E, F, G, H } = this;
743
+ return [A, B, C, D, E, F, G, H];
744
+ }
745
+ // prettier-ignore
746
+ set(A, B, C, D, E, F, G, H) {
747
+ this.A = A | 0;
748
+ this.B = B | 0;
749
+ this.C = C | 0;
750
+ this.D = D | 0;
751
+ this.E = E | 0;
752
+ this.F = F | 0;
753
+ this.G = G | 0;
754
+ this.H = H | 0;
755
+ }
756
+ process(view, offset) {
757
+ // Extend the first 16 words into the remaining 48 words w[16..63] of the message schedule array
758
+ for (let i = 0; i < 16; i++, offset += 4)
759
+ SHA256_W[i] = view.getUint32(offset, false);
760
+ for (let i = 16; i < 64; i++) {
761
+ const W15 = SHA256_W[i - 15];
762
+ const W2 = SHA256_W[i - 2];
763
+ const s0 = (0, utils_ts_1.rotr)(W15, 7) ^ (0, utils_ts_1.rotr)(W15, 18) ^ (W15 >>> 3);
764
+ const s1 = (0, utils_ts_1.rotr)(W2, 17) ^ (0, utils_ts_1.rotr)(W2, 19) ^ (W2 >>> 10);
765
+ SHA256_W[i] = (s1 + SHA256_W[i - 7] + s0 + SHA256_W[i - 16]) | 0;
766
+ }
767
+ // Compression function main loop, 64 rounds
768
+ let { A, B, C, D, E, F, G, H } = this;
769
+ for (let i = 0; i < 64; i++) {
770
+ const sigma1 = (0, utils_ts_1.rotr)(E, 6) ^ (0, utils_ts_1.rotr)(E, 11) ^ (0, utils_ts_1.rotr)(E, 25);
771
+ const T1 = (H + sigma1 + (0, _md_ts_1.Chi)(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0;
772
+ const sigma0 = (0, utils_ts_1.rotr)(A, 2) ^ (0, utils_ts_1.rotr)(A, 13) ^ (0, utils_ts_1.rotr)(A, 22);
773
+ const T2 = (sigma0 + (0, _md_ts_1.Maj)(A, B, C)) | 0;
774
+ H = G;
775
+ G = F;
776
+ F = E;
777
+ E = (D + T1) | 0;
778
+ D = C;
779
+ C = B;
780
+ B = A;
781
+ A = (T1 + T2) | 0;
782
+ }
783
+ // Add the compressed chunk to the current hash value
784
+ A = (A + this.A) | 0;
785
+ B = (B + this.B) | 0;
786
+ C = (C + this.C) | 0;
787
+ D = (D + this.D) | 0;
788
+ E = (E + this.E) | 0;
789
+ F = (F + this.F) | 0;
790
+ G = (G + this.G) | 0;
791
+ H = (H + this.H) | 0;
792
+ this.set(A, B, C, D, E, F, G, H);
793
+ }
794
+ roundClean() {
795
+ (0, utils_ts_1.clean)(SHA256_W);
796
+ }
797
+ destroy() {
798
+ this.set(0, 0, 0, 0, 0, 0, 0, 0);
799
+ (0, utils_ts_1.clean)(this.buffer);
800
+ }
801
+ }
802
+ sha2.SHA256 = SHA256;
803
+ class SHA224 extends SHA256 {
804
+ constructor() {
805
+ super(28);
806
+ this.A = _md_ts_1.SHA224_IV[0] | 0;
807
+ this.B = _md_ts_1.SHA224_IV[1] | 0;
808
+ this.C = _md_ts_1.SHA224_IV[2] | 0;
809
+ this.D = _md_ts_1.SHA224_IV[3] | 0;
810
+ this.E = _md_ts_1.SHA224_IV[4] | 0;
811
+ this.F = _md_ts_1.SHA224_IV[5] | 0;
812
+ this.G = _md_ts_1.SHA224_IV[6] | 0;
813
+ this.H = _md_ts_1.SHA224_IV[7] | 0;
814
+ }
815
+ }
816
+ sha2.SHA224 = SHA224;
817
+ // SHA2-512 is slower than sha256 in js because u64 operations are slow.
818
+ // Round contants
819
+ // First 32 bits of the fractional parts of the cube roots of the first 80 primes 2..409
820
+ // prettier-ignore
821
+ const K512 = /* @__PURE__ */ (() => u64.split([
822
+ '0x428a2f98d728ae22', '0x7137449123ef65cd', '0xb5c0fbcfec4d3b2f', '0xe9b5dba58189dbbc',
823
+ '0x3956c25bf348b538', '0x59f111f1b605d019', '0x923f82a4af194f9b', '0xab1c5ed5da6d8118',
824
+ '0xd807aa98a3030242', '0x12835b0145706fbe', '0x243185be4ee4b28c', '0x550c7dc3d5ffb4e2',
825
+ '0x72be5d74f27b896f', '0x80deb1fe3b1696b1', '0x9bdc06a725c71235', '0xc19bf174cf692694',
826
+ '0xe49b69c19ef14ad2', '0xefbe4786384f25e3', '0x0fc19dc68b8cd5b5', '0x240ca1cc77ac9c65',
827
+ '0x2de92c6f592b0275', '0x4a7484aa6ea6e483', '0x5cb0a9dcbd41fbd4', '0x76f988da831153b5',
828
+ '0x983e5152ee66dfab', '0xa831c66d2db43210', '0xb00327c898fb213f', '0xbf597fc7beef0ee4',
829
+ '0xc6e00bf33da88fc2', '0xd5a79147930aa725', '0x06ca6351e003826f', '0x142929670a0e6e70',
830
+ '0x27b70a8546d22ffc', '0x2e1b21385c26c926', '0x4d2c6dfc5ac42aed', '0x53380d139d95b3df',
831
+ '0x650a73548baf63de', '0x766a0abb3c77b2a8', '0x81c2c92e47edaee6', '0x92722c851482353b',
832
+ '0xa2bfe8a14cf10364', '0xa81a664bbc423001', '0xc24b8b70d0f89791', '0xc76c51a30654be30',
833
+ '0xd192e819d6ef5218', '0xd69906245565a910', '0xf40e35855771202a', '0x106aa07032bbd1b8',
834
+ '0x19a4c116b8d2d0c8', '0x1e376c085141ab53', '0x2748774cdf8eeb99', '0x34b0bcb5e19b48a8',
835
+ '0x391c0cb3c5c95a63', '0x4ed8aa4ae3418acb', '0x5b9cca4f7763e373', '0x682e6ff3d6b2b8a3',
836
+ '0x748f82ee5defb2fc', '0x78a5636f43172f60', '0x84c87814a1f0ab72', '0x8cc702081a6439ec',
837
+ '0x90befffa23631e28', '0xa4506cebde82bde9', '0xbef9a3f7b2c67915', '0xc67178f2e372532b',
838
+ '0xca273eceea26619c', '0xd186b8c721c0c207', '0xeada7dd6cde0eb1e', '0xf57d4f7fee6ed178',
839
+ '0x06f067aa72176fba', '0x0a637dc5a2c898a6', '0x113f9804bef90dae', '0x1b710b35131c471b',
840
+ '0x28db77f523047d84', '0x32caab7b40c72493', '0x3c9ebe0a15c9bebc', '0x431d67c49c100d4c',
841
+ '0x4cc5d4becb3e42b6', '0x597f299cfc657e2a', '0x5fcb6fab3ad6faec', '0x6c44198c4a475817'
842
+ ].map(n => BigInt(n))))();
843
+ const SHA512_Kh = /* @__PURE__ */ (() => K512[0])();
844
+ const SHA512_Kl = /* @__PURE__ */ (() => K512[1])();
845
+ // Reusable temporary buffers
846
+ const SHA512_W_H = /* @__PURE__ */ new Uint32Array(80);
847
+ const SHA512_W_L = /* @__PURE__ */ new Uint32Array(80);
848
+ class SHA512 extends _md_ts_1.HashMD {
849
+ constructor(outputLen = 64) {
850
+ super(128, outputLen, 16, false);
851
+ // We cannot use array here since array allows indexing by variable
852
+ // which means optimizer/compiler cannot use registers.
853
+ // h -- high 32 bits, l -- low 32 bits
854
+ this.Ah = _md_ts_1.SHA512_IV[0] | 0;
855
+ this.Al = _md_ts_1.SHA512_IV[1] | 0;
856
+ this.Bh = _md_ts_1.SHA512_IV[2] | 0;
857
+ this.Bl = _md_ts_1.SHA512_IV[3] | 0;
858
+ this.Ch = _md_ts_1.SHA512_IV[4] | 0;
859
+ this.Cl = _md_ts_1.SHA512_IV[5] | 0;
860
+ this.Dh = _md_ts_1.SHA512_IV[6] | 0;
861
+ this.Dl = _md_ts_1.SHA512_IV[7] | 0;
862
+ this.Eh = _md_ts_1.SHA512_IV[8] | 0;
863
+ this.El = _md_ts_1.SHA512_IV[9] | 0;
864
+ this.Fh = _md_ts_1.SHA512_IV[10] | 0;
865
+ this.Fl = _md_ts_1.SHA512_IV[11] | 0;
866
+ this.Gh = _md_ts_1.SHA512_IV[12] | 0;
867
+ this.Gl = _md_ts_1.SHA512_IV[13] | 0;
868
+ this.Hh = _md_ts_1.SHA512_IV[14] | 0;
869
+ this.Hl = _md_ts_1.SHA512_IV[15] | 0;
870
+ }
871
+ // prettier-ignore
872
+ get() {
873
+ const { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;
874
+ return [Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl];
875
+ }
876
+ // prettier-ignore
877
+ set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl) {
878
+ this.Ah = Ah | 0;
879
+ this.Al = Al | 0;
880
+ this.Bh = Bh | 0;
881
+ this.Bl = Bl | 0;
882
+ this.Ch = Ch | 0;
883
+ this.Cl = Cl | 0;
884
+ this.Dh = Dh | 0;
885
+ this.Dl = Dl | 0;
886
+ this.Eh = Eh | 0;
887
+ this.El = El | 0;
888
+ this.Fh = Fh | 0;
889
+ this.Fl = Fl | 0;
890
+ this.Gh = Gh | 0;
891
+ this.Gl = Gl | 0;
892
+ this.Hh = Hh | 0;
893
+ this.Hl = Hl | 0;
894
+ }
895
+ process(view, offset) {
896
+ // Extend the first 16 words into the remaining 64 words w[16..79] of the message schedule array
897
+ for (let i = 0; i < 16; i++, offset += 4) {
898
+ SHA512_W_H[i] = view.getUint32(offset);
899
+ SHA512_W_L[i] = view.getUint32((offset += 4));
900
+ }
901
+ for (let i = 16; i < 80; i++) {
902
+ // s0 := (w[i-15] rightrotate 1) xor (w[i-15] rightrotate 8) xor (w[i-15] rightshift 7)
903
+ const W15h = SHA512_W_H[i - 15] | 0;
904
+ const W15l = SHA512_W_L[i - 15] | 0;
905
+ const s0h = u64.rotrSH(W15h, W15l, 1) ^ u64.rotrSH(W15h, W15l, 8) ^ u64.shrSH(W15h, W15l, 7);
906
+ const s0l = u64.rotrSL(W15h, W15l, 1) ^ u64.rotrSL(W15h, W15l, 8) ^ u64.shrSL(W15h, W15l, 7);
907
+ // s1 := (w[i-2] rightrotate 19) xor (w[i-2] rightrotate 61) xor (w[i-2] rightshift 6)
908
+ const W2h = SHA512_W_H[i - 2] | 0;
909
+ const W2l = SHA512_W_L[i - 2] | 0;
910
+ const s1h = u64.rotrSH(W2h, W2l, 19) ^ u64.rotrBH(W2h, W2l, 61) ^ u64.shrSH(W2h, W2l, 6);
911
+ const s1l = u64.rotrSL(W2h, W2l, 19) ^ u64.rotrBL(W2h, W2l, 61) ^ u64.shrSL(W2h, W2l, 6);
912
+ // SHA256_W[i] = s0 + s1 + SHA256_W[i - 7] + SHA256_W[i - 16];
913
+ const SUMl = u64.add4L(s0l, s1l, SHA512_W_L[i - 7], SHA512_W_L[i - 16]);
914
+ const SUMh = u64.add4H(SUMl, s0h, s1h, SHA512_W_H[i - 7], SHA512_W_H[i - 16]);
915
+ SHA512_W_H[i] = SUMh | 0;
916
+ SHA512_W_L[i] = SUMl | 0;
917
+ }
918
+ let { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;
919
+ // Compression function main loop, 80 rounds
920
+ for (let i = 0; i < 80; i++) {
921
+ // S1 := (e rightrotate 14) xor (e rightrotate 18) xor (e rightrotate 41)
922
+ const sigma1h = u64.rotrSH(Eh, El, 14) ^ u64.rotrSH(Eh, El, 18) ^ u64.rotrBH(Eh, El, 41);
923
+ const sigma1l = u64.rotrSL(Eh, El, 14) ^ u64.rotrSL(Eh, El, 18) ^ u64.rotrBL(Eh, El, 41);
924
+ //const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0;
925
+ const CHIh = (Eh & Fh) ^ (~Eh & Gh);
926
+ const CHIl = (El & Fl) ^ (~El & Gl);
927
+ // T1 = H + sigma1 + Chi(E, F, G) + SHA512_K[i] + SHA512_W[i]
928
+ // prettier-ignore
929
+ const T1ll = u64.add5L(Hl, sigma1l, CHIl, SHA512_Kl[i], SHA512_W_L[i]);
930
+ const T1h = u64.add5H(T1ll, Hh, sigma1h, CHIh, SHA512_Kh[i], SHA512_W_H[i]);
931
+ const T1l = T1ll | 0;
932
+ // S0 := (a rightrotate 28) xor (a rightrotate 34) xor (a rightrotate 39)
933
+ const sigma0h = u64.rotrSH(Ah, Al, 28) ^ u64.rotrBH(Ah, Al, 34) ^ u64.rotrBH(Ah, Al, 39);
934
+ const sigma0l = u64.rotrSL(Ah, Al, 28) ^ u64.rotrBL(Ah, Al, 34) ^ u64.rotrBL(Ah, Al, 39);
935
+ const MAJh = (Ah & Bh) ^ (Ah & Ch) ^ (Bh & Ch);
936
+ const MAJl = (Al & Bl) ^ (Al & Cl) ^ (Bl & Cl);
937
+ Hh = Gh | 0;
938
+ Hl = Gl | 0;
939
+ Gh = Fh | 0;
940
+ Gl = Fl | 0;
941
+ Fh = Eh | 0;
942
+ Fl = El | 0;
943
+ ({ h: Eh, l: El } = u64.add(Dh | 0, Dl | 0, T1h | 0, T1l | 0));
944
+ Dh = Ch | 0;
945
+ Dl = Cl | 0;
946
+ Ch = Bh | 0;
947
+ Cl = Bl | 0;
948
+ Bh = Ah | 0;
949
+ Bl = Al | 0;
950
+ const All = u64.add3L(T1l, sigma0l, MAJl);
951
+ Ah = u64.add3H(All, T1h, sigma0h, MAJh);
952
+ Al = All | 0;
953
+ }
954
+ // Add the compressed chunk to the current hash value
955
+ ({ h: Ah, l: Al } = u64.add(this.Ah | 0, this.Al | 0, Ah | 0, Al | 0));
956
+ ({ h: Bh, l: Bl } = u64.add(this.Bh | 0, this.Bl | 0, Bh | 0, Bl | 0));
957
+ ({ h: Ch, l: Cl } = u64.add(this.Ch | 0, this.Cl | 0, Ch | 0, Cl | 0));
958
+ ({ h: Dh, l: Dl } = u64.add(this.Dh | 0, this.Dl | 0, Dh | 0, Dl | 0));
959
+ ({ h: Eh, l: El } = u64.add(this.Eh | 0, this.El | 0, Eh | 0, El | 0));
960
+ ({ h: Fh, l: Fl } = u64.add(this.Fh | 0, this.Fl | 0, Fh | 0, Fl | 0));
961
+ ({ h: Gh, l: Gl } = u64.add(this.Gh | 0, this.Gl | 0, Gh | 0, Gl | 0));
962
+ ({ h: Hh, l: Hl } = u64.add(this.Hh | 0, this.Hl | 0, Hh | 0, Hl | 0));
963
+ this.set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl);
964
+ }
965
+ roundClean() {
966
+ (0, utils_ts_1.clean)(SHA512_W_H, SHA512_W_L);
967
+ }
968
+ destroy() {
969
+ (0, utils_ts_1.clean)(this.buffer);
970
+ this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
971
+ }
972
+ }
973
+ sha2.SHA512 = SHA512;
974
+ class SHA384 extends SHA512 {
975
+ constructor() {
976
+ super(48);
977
+ this.Ah = _md_ts_1.SHA384_IV[0] | 0;
978
+ this.Al = _md_ts_1.SHA384_IV[1] | 0;
979
+ this.Bh = _md_ts_1.SHA384_IV[2] | 0;
980
+ this.Bl = _md_ts_1.SHA384_IV[3] | 0;
981
+ this.Ch = _md_ts_1.SHA384_IV[4] | 0;
982
+ this.Cl = _md_ts_1.SHA384_IV[5] | 0;
983
+ this.Dh = _md_ts_1.SHA384_IV[6] | 0;
984
+ this.Dl = _md_ts_1.SHA384_IV[7] | 0;
985
+ this.Eh = _md_ts_1.SHA384_IV[8] | 0;
986
+ this.El = _md_ts_1.SHA384_IV[9] | 0;
987
+ this.Fh = _md_ts_1.SHA384_IV[10] | 0;
988
+ this.Fl = _md_ts_1.SHA384_IV[11] | 0;
989
+ this.Gh = _md_ts_1.SHA384_IV[12] | 0;
990
+ this.Gl = _md_ts_1.SHA384_IV[13] | 0;
991
+ this.Hh = _md_ts_1.SHA384_IV[14] | 0;
992
+ this.Hl = _md_ts_1.SHA384_IV[15] | 0;
993
+ }
994
+ }
995
+ sha2.SHA384 = SHA384;
996
+ /**
997
+ * Truncated SHA512/256 and SHA512/224.
998
+ * SHA512_IV is XORed with 0xa5a5a5a5a5a5a5a5, then used as "intermediary" IV of SHA512/t.
999
+ * Then t hashes string to produce result IV.
1000
+ * See `test/misc/sha2-gen-iv.js`.
1001
+ */
1002
+ /** SHA512/224 IV */
1003
+ const T224_IV = /* @__PURE__ */ Uint32Array.from([
1004
+ 0x8c3d37c8, 0x19544da2, 0x73e19966, 0x89dcd4d6, 0x1dfab7ae, 0x32ff9c82, 0x679dd514, 0x582f9fcf,
1005
+ 0x0f6d2b69, 0x7bd44da8, 0x77e36f73, 0x04c48942, 0x3f9d85a8, 0x6a1d36c8, 0x1112e6ad, 0x91d692a1,
1006
+ ]);
1007
+ /** SHA512/256 IV */
1008
+ const T256_IV = /* @__PURE__ */ Uint32Array.from([
1009
+ 0x22312194, 0xfc2bf72c, 0x9f555fa3, 0xc84c64c2, 0x2393b86b, 0x6f53b151, 0x96387719, 0x5940eabd,
1010
+ 0x96283ee2, 0xa88effe3, 0xbe5e1e25, 0x53863992, 0x2b0199fc, 0x2c85b8aa, 0x0eb72ddc, 0x81c52ca2,
1011
+ ]);
1012
+ class SHA512_224 extends SHA512 {
1013
+ constructor() {
1014
+ super(28);
1015
+ this.Ah = T224_IV[0] | 0;
1016
+ this.Al = T224_IV[1] | 0;
1017
+ this.Bh = T224_IV[2] | 0;
1018
+ this.Bl = T224_IV[3] | 0;
1019
+ this.Ch = T224_IV[4] | 0;
1020
+ this.Cl = T224_IV[5] | 0;
1021
+ this.Dh = T224_IV[6] | 0;
1022
+ this.Dl = T224_IV[7] | 0;
1023
+ this.Eh = T224_IV[8] | 0;
1024
+ this.El = T224_IV[9] | 0;
1025
+ this.Fh = T224_IV[10] | 0;
1026
+ this.Fl = T224_IV[11] | 0;
1027
+ this.Gh = T224_IV[12] | 0;
1028
+ this.Gl = T224_IV[13] | 0;
1029
+ this.Hh = T224_IV[14] | 0;
1030
+ this.Hl = T224_IV[15] | 0;
1031
+ }
1032
+ }
1033
+ sha2.SHA512_224 = SHA512_224;
1034
+ class SHA512_256 extends SHA512 {
1035
+ constructor() {
1036
+ super(32);
1037
+ this.Ah = T256_IV[0] | 0;
1038
+ this.Al = T256_IV[1] | 0;
1039
+ this.Bh = T256_IV[2] | 0;
1040
+ this.Bl = T256_IV[3] | 0;
1041
+ this.Ch = T256_IV[4] | 0;
1042
+ this.Cl = T256_IV[5] | 0;
1043
+ this.Dh = T256_IV[6] | 0;
1044
+ this.Dl = T256_IV[7] | 0;
1045
+ this.Eh = T256_IV[8] | 0;
1046
+ this.El = T256_IV[9] | 0;
1047
+ this.Fh = T256_IV[10] | 0;
1048
+ this.Fl = T256_IV[11] | 0;
1049
+ this.Gh = T256_IV[12] | 0;
1050
+ this.Gl = T256_IV[13] | 0;
1051
+ this.Hh = T256_IV[14] | 0;
1052
+ this.Hl = T256_IV[15] | 0;
1053
+ }
1054
+ }
1055
+ sha2.SHA512_256 = SHA512_256;
1056
+ /**
1057
+ * SHA2-256 hash function from RFC 4634.
1058
+ *
1059
+ * It is the fastest JS hash, even faster than Blake3.
1060
+ * To break sha256 using birthday attack, attackers need to try 2^128 hashes.
1061
+ * BTC network is doing 2^70 hashes/sec (2^95 hashes/year) as per 2025.
1062
+ */
1063
+ sha2.sha256 = (0, utils_ts_1.createHasher)(() => new SHA256());
1064
+ /** SHA2-224 hash function from RFC 4634 */
1065
+ sha2.sha224 = (0, utils_ts_1.createHasher)(() => new SHA224());
1066
+ /** SHA2-512 hash function from RFC 4634. */
1067
+ sha2.sha512 = (0, utils_ts_1.createHasher)(() => new SHA512());
1068
+ /** SHA2-384 hash function from RFC 4634. */
1069
+ sha2.sha384 = (0, utils_ts_1.createHasher)(() => new SHA384());
1070
+ /**
1071
+ * SHA2-512/256 "truncated" hash function, with improved resistance to length extension attacks.
1072
+ * See the paper on [truncated SHA512](https://eprint.iacr.org/2010/548.pdf).
1073
+ */
1074
+ sha2.sha512_256 = (0, utils_ts_1.createHasher)(() => new SHA512_256());
1075
+ /**
1076
+ * SHA2-512/224 "truncated" hash function, with improved resistance to length extension attacks.
1077
+ * See the paper on [truncated SHA512](https://eprint.iacr.org/2010/548.pdf).
1078
+ */
1079
+ sha2.sha512_224 = (0, utils_ts_1.createHasher)(() => new SHA512_224());
1080
+
1081
+ return sha2;
710
1082
  }
711
- var ge;
712
- function Ke() {
713
- if (ge) return $;
714
- ge = 1, Object.defineProperty($, "__esModule", { value: !0 }), $.sha224 = $.SHA224 = $.sha256 = $.SHA256 = void 0;
715
- const e = /* @__PURE__ */ ze();
716
- return $.SHA256 = e.SHA256, $.sha256 = e.sha256, $.SHA224 = e.SHA224, $.sha224 = e.sha224, $;
1083
+
1084
+ var hasRequiredSha256;
1085
+
1086
+ function requireSha256 () {
1087
+ if (hasRequiredSha256) return sha256;
1088
+ hasRequiredSha256 = 1;
1089
+ Object.defineProperty(sha256, "__esModule", { value: true });
1090
+ sha256.sha224 = sha256.SHA224 = sha256.sha256 = sha256.SHA256 = void 0;
1091
+ /**
1092
+ * SHA2-256 a.k.a. sha256. In JS, it is the fastest hash, even faster than Blake3.
1093
+ *
1094
+ * To break sha256 using birthday attack, attackers need to try 2^128 hashes.
1095
+ * BTC network is doing 2^70 hashes/sec (2^95 hashes/year) as per 2025.
1096
+ *
1097
+ * Check out [FIPS 180-4](https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.180-4.pdf).
1098
+ * @module
1099
+ * @deprecated
1100
+ */
1101
+ const sha2_ts_1 = /*@__PURE__*/ requireSha2();
1102
+ /** @deprecated Use import from `noble/hashes/sha2` module */
1103
+ sha256.SHA256 = sha2_ts_1.SHA256;
1104
+ /** @deprecated Use import from `noble/hashes/sha2` module */
1105
+ sha256.sha256 = sha2_ts_1.sha256;
1106
+ /** @deprecated Use import from `noble/hashes/sha2` module */
1107
+ sha256.SHA224 = sha2_ts_1.SHA224;
1108
+ /** @deprecated Use import from `noble/hashes/sha2` module */
1109
+ sha256.sha224 = sha2_ts_1.sha224;
1110
+
1111
+ return sha256;
717
1112
  }
718
- var oe, ve;
719
- function Xe() {
720
- if (ve) return oe;
721
- ve = 1;
722
- function e(t) {
723
- if (t.length >= 255)
724
- throw new TypeError("Alphabet too long");
725
- for (var n = new Uint8Array(256), H = 0; H < n.length; H++)
726
- n[H] = 255;
727
- for (var y = 0; y < t.length; y++) {
728
- var w = t.charAt(y), a = w.charCodeAt(0);
729
- if (n[a] !== 255)
730
- throw new TypeError(w + " is ambiguous");
731
- n[a] = y;
732
- }
733
- var c = t.length, s = t.charAt(0), o = Math.log(c) / Math.log(256), i = Math.log(256) / Math.log(c);
734
- function h(f) {
735
- if (f instanceof Uint8Array || (ArrayBuffer.isView(f) ? f = new Uint8Array(f.buffer, f.byteOffset, f.byteLength) : Array.isArray(f) && (f = Uint8Array.from(f))), !(f instanceof Uint8Array))
736
- throw new TypeError("Expected Uint8Array");
737
- if (f.length === 0)
738
- return "";
739
- for (var g = 0, d = 0, V = 0, M = f.length; V !== M && f[V] === 0; )
740
- V++, g++;
741
- for (var x = (M - V) * i + 1 >>> 0, R = new Uint8Array(x); V !== M; ) {
742
- for (var A = f[V], I = 0, L = x - 1; (A !== 0 || I < d) && L !== -1; L--, I++)
743
- A += 256 * R[L] >>> 0, R[L] = A % c >>> 0, A = A / c >>> 0;
744
- if (A !== 0)
745
- throw new Error("Non-zero carry");
746
- d = I, V++;
747
- }
748
- for (var E = x - d; E !== x && R[E] === 0; )
749
- E++;
750
- for (var u = s.repeat(g); E < x; ++E)
751
- u += t.charAt(R[E]);
752
- return u;
753
- }
754
- function m(f) {
755
- if (typeof f != "string")
756
- throw new TypeError("Expected String");
757
- if (f.length === 0)
758
- return new Uint8Array();
759
- for (var g = 0, d = 0, V = 0; f[g] === s; )
760
- d++, g++;
761
- for (var M = (f.length - g) * o + 1 >>> 0, x = new Uint8Array(M); f[g]; ) {
762
- var R = f.charCodeAt(g);
763
- if (R > 255)
764
- return;
765
- var A = n[R];
766
- if (A === 255)
767
- return;
768
- for (var I = 0, L = M - 1; (A !== 0 || I < V) && L !== -1; L--, I++)
769
- A += c * x[L] >>> 0, x[L] = A % 256 >>> 0, A = A / 256 >>> 0;
770
- if (A !== 0)
771
- throw new Error("Non-zero carry");
772
- V = I, g++;
773
- }
774
- for (var E = M - V; E !== M && x[E] === 0; )
775
- E++;
776
- for (var u = new Uint8Array(d + (M - E)), l = d; E !== M; )
777
- u[l++] = x[E++];
778
- return u;
779
- }
780
- function B(f) {
781
- var g = m(f);
782
- if (g)
783
- return g;
784
- throw new Error("Non-base" + c + " character");
785
- }
786
- return {
787
- encode: h,
788
- decodeUnsafe: m,
789
- decode: B
790
- };
791
- }
792
- return oe = e, oe;
1113
+
1114
+ var src;
1115
+ var hasRequiredSrc;
1116
+
1117
+ function requireSrc () {
1118
+ if (hasRequiredSrc) return src;
1119
+ hasRequiredSrc = 1;
1120
+ // base-x encoding / decoding
1121
+ // Copyright (c) 2018 base-x contributors
1122
+ // Copyright (c) 2014-2018 The Bitcoin Core developers (base58.cpp)
1123
+ // Distributed under the MIT software license, see the accompanying
1124
+ // file LICENSE or http://www.opensource.org/licenses/mit-license.php.
1125
+ function base (ALPHABET) {
1126
+ if (ALPHABET.length >= 255) { throw new TypeError('Alphabet too long') }
1127
+ var BASE_MAP = new Uint8Array(256);
1128
+ for (var j = 0; j < BASE_MAP.length; j++) {
1129
+ BASE_MAP[j] = 255;
1130
+ }
1131
+ for (var i = 0; i < ALPHABET.length; i++) {
1132
+ var x = ALPHABET.charAt(i);
1133
+ var xc = x.charCodeAt(0);
1134
+ if (BASE_MAP[xc] !== 255) { throw new TypeError(x + ' is ambiguous') }
1135
+ BASE_MAP[xc] = i;
1136
+ }
1137
+ var BASE = ALPHABET.length;
1138
+ var LEADER = ALPHABET.charAt(0);
1139
+ var FACTOR = Math.log(BASE) / Math.log(256); // log(BASE) / log(256), rounded up
1140
+ var iFACTOR = Math.log(256) / Math.log(BASE); // log(256) / log(BASE), rounded up
1141
+ function encode (source) {
1142
+ if (source instanceof Uint8Array) ; else if (ArrayBuffer.isView(source)) {
1143
+ source = new Uint8Array(source.buffer, source.byteOffset, source.byteLength);
1144
+ } else if (Array.isArray(source)) {
1145
+ source = Uint8Array.from(source);
1146
+ }
1147
+ if (!(source instanceof Uint8Array)) { throw new TypeError('Expected Uint8Array') }
1148
+ if (source.length === 0) { return '' }
1149
+ // Skip & count leading zeroes.
1150
+ var zeroes = 0;
1151
+ var length = 0;
1152
+ var pbegin = 0;
1153
+ var pend = source.length;
1154
+ while (pbegin !== pend && source[pbegin] === 0) {
1155
+ pbegin++;
1156
+ zeroes++;
1157
+ }
1158
+ // Allocate enough space in big-endian base58 representation.
1159
+ var size = ((pend - pbegin) * iFACTOR + 1) >>> 0;
1160
+ var b58 = new Uint8Array(size);
1161
+ // Process the bytes.
1162
+ while (pbegin !== pend) {
1163
+ var carry = source[pbegin];
1164
+ // Apply "b58 = b58 * 256 + ch".
1165
+ var i = 0;
1166
+ for (var it1 = size - 1; (carry !== 0 || i < length) && (it1 !== -1); it1--, i++) {
1167
+ carry += (256 * b58[it1]) >>> 0;
1168
+ b58[it1] = (carry % BASE) >>> 0;
1169
+ carry = (carry / BASE) >>> 0;
1170
+ }
1171
+ if (carry !== 0) { throw new Error('Non-zero carry') }
1172
+ length = i;
1173
+ pbegin++;
1174
+ }
1175
+ // Skip leading zeroes in base58 result.
1176
+ var it2 = size - length;
1177
+ while (it2 !== size && b58[it2] === 0) {
1178
+ it2++;
1179
+ }
1180
+ // Translate the result into a string.
1181
+ var str = LEADER.repeat(zeroes);
1182
+ for (; it2 < size; ++it2) { str += ALPHABET.charAt(b58[it2]); }
1183
+ return str
1184
+ }
1185
+ function decodeUnsafe (source) {
1186
+ if (typeof source !== 'string') { throw new TypeError('Expected String') }
1187
+ if (source.length === 0) { return new Uint8Array() }
1188
+ var psz = 0;
1189
+ // Skip and count leading '1's.
1190
+ var zeroes = 0;
1191
+ var length = 0;
1192
+ while (source[psz] === LEADER) {
1193
+ zeroes++;
1194
+ psz++;
1195
+ }
1196
+ // Allocate enough space in big-endian base256 representation.
1197
+ var size = (((source.length - psz) * FACTOR) + 1) >>> 0; // log(58) / log(256), rounded up.
1198
+ var b256 = new Uint8Array(size);
1199
+ // Process the characters.
1200
+ while (source[psz]) {
1201
+ // Find code of next character
1202
+ var charCode = source.charCodeAt(psz);
1203
+ // Base map can not be indexed using char code
1204
+ if (charCode > 255) { return }
1205
+ // Decode character
1206
+ var carry = BASE_MAP[charCode];
1207
+ // Invalid character
1208
+ if (carry === 255) { return }
1209
+ var i = 0;
1210
+ for (var it3 = size - 1; (carry !== 0 || i < length) && (it3 !== -1); it3--, i++) {
1211
+ carry += (BASE * b256[it3]) >>> 0;
1212
+ b256[it3] = (carry % 256) >>> 0;
1213
+ carry = (carry / 256) >>> 0;
1214
+ }
1215
+ if (carry !== 0) { throw new Error('Non-zero carry') }
1216
+ length = i;
1217
+ psz++;
1218
+ }
1219
+ // Skip leading zeroes in b256.
1220
+ var it4 = size - length;
1221
+ while (it4 !== size && b256[it4] === 0) {
1222
+ it4++;
1223
+ }
1224
+ var vch = new Uint8Array(zeroes + (size - it4));
1225
+ var j = zeroes;
1226
+ while (it4 !== size) {
1227
+ vch[j++] = b256[it4++];
1228
+ }
1229
+ return vch
1230
+ }
1231
+ function decode (string) {
1232
+ var buffer = decodeUnsafe(string);
1233
+ if (buffer) { return buffer }
1234
+ throw new Error('Non-base' + BASE + ' character')
1235
+ }
1236
+ return {
1237
+ encode: encode,
1238
+ decodeUnsafe: decodeUnsafe,
1239
+ decode: decode
1240
+ }
1241
+ }
1242
+ src = base;
1243
+ return src;
793
1244
  }
794
- var ce, Se;
795
- function Je() {
796
- return Se || (Se = 1, ce = Xe()("123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz")), ce;
1245
+
1246
+ var bs58;
1247
+ var hasRequiredBs58;
1248
+
1249
+ function requireBs58 () {
1250
+ if (hasRequiredBs58) return bs58;
1251
+ hasRequiredBs58 = 1;
1252
+ const basex = requireSrc();
1253
+ const ALPHABET = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz';
1254
+
1255
+ bs58 = basex(ALPHABET);
1256
+ return bs58;
797
1257
  }
798
- var ae, _e;
799
- function Qe() {
800
- if (_e) return ae;
801
- _e = 1;
802
- var e = Je();
803
- return ae = function(t) {
804
- function n(a) {
805
- var c = Uint8Array.from(a), s = t(c), o = c.length + 4, i = new Uint8Array(o);
806
- return i.set(c, 0), i.set(s.subarray(0, 4), c.length), e.encode(i, o);
807
- }
808
- function H(a) {
809
- var c = a.slice(0, -4), s = a.slice(-4), o = t(c);
810
- if (!(s[0] ^ o[0] | s[1] ^ o[1] | s[2] ^ o[2] | s[3] ^ o[3]))
811
- return c;
812
- }
813
- function y(a) {
814
- var c = e.decodeUnsafe(a);
815
- if (c)
816
- return H(c);
817
- }
818
- function w(a) {
819
- var c = e.decode(a), s = H(c);
820
- if (!s) throw new Error("Invalid checksum");
821
- return s;
822
- }
823
- return {
824
- encode: n,
825
- decode: w,
826
- decodeUnsafe: y
827
- };
828
- }, ae;
1258
+
1259
+ var base;
1260
+ var hasRequiredBase;
1261
+
1262
+ function requireBase () {
1263
+ if (hasRequiredBase) return base;
1264
+ hasRequiredBase = 1;
1265
+
1266
+ var base58 = requireBs58();
1267
+
1268
+ base = function (checksumFn) {
1269
+ // Encode a buffer as a base58-check encoded string
1270
+ function encode (payload) {
1271
+ var payloadU8 = Uint8Array.from(payload);
1272
+ var checksum = checksumFn(payloadU8);
1273
+ var length = payloadU8.length + 4;
1274
+ var both = new Uint8Array(length);
1275
+ both.set(payloadU8, 0);
1276
+ both.set(checksum.subarray(0, 4), payloadU8.length);
1277
+ return base58.encode(both, length)
1278
+ }
1279
+
1280
+ function decodeRaw (buffer) {
1281
+ var payload = buffer.slice(0, -4);
1282
+ var checksum = buffer.slice(-4);
1283
+ var newChecksum = checksumFn(payload);
1284
+
1285
+ if (checksum[0] ^ newChecksum[0] |
1286
+ checksum[1] ^ newChecksum[1] |
1287
+ checksum[2] ^ newChecksum[2] |
1288
+ checksum[3] ^ newChecksum[3]) return
1289
+
1290
+ return payload
1291
+ }
1292
+
1293
+ // Decode a base58-check encoded string to a buffer, no result if checksum is wrong
1294
+ function decodeUnsafe (string) {
1295
+ var buffer = base58.decodeUnsafe(string);
1296
+ if (!buffer) return
1297
+
1298
+ return decodeRaw(buffer)
1299
+ }
1300
+
1301
+ function decode (string) {
1302
+ var buffer = base58.decode(string);
1303
+ var payload = decodeRaw(buffer);
1304
+ if (!payload) throw new Error('Invalid checksum')
1305
+ return payload
1306
+ }
1307
+
1308
+ return {
1309
+ encode: encode,
1310
+ decode: decode,
1311
+ decodeUnsafe: decodeUnsafe
1312
+ }
1313
+ };
1314
+ return base;
829
1315
  }
830
- var ie, me;
831
- function Ye() {
832
- if (me) return ie;
833
- me = 1;
834
- var { sha256: e } = /* @__PURE__ */ Ke(), t = Qe();
835
- function n(H) {
836
- return e(e(H));
837
- }
838
- return ie = t(n), ie;
1316
+
1317
+ var bs58check$1;
1318
+ var hasRequiredBs58check;
1319
+
1320
+ function requireBs58check () {
1321
+ if (hasRequiredBs58check) return bs58check$1;
1322
+ hasRequiredBs58check = 1;
1323
+
1324
+ var { sha256 } = /*@__PURE__*/ requireSha256();
1325
+ var bs58checkBase = requireBase();
1326
+
1327
+ // SHA256(SHA256(buffer))
1328
+ function sha256x2 (buffer) {
1329
+ return sha256(sha256(buffer))
1330
+ }
1331
+
1332
+ bs58check$1 = bs58checkBase(sha256x2);
1333
+ return bs58check$1;
839
1334
  }
840
- var Ze = Ye();
841
- const Q = /* @__PURE__ */ be(Ze), et = (e) => Array.from(e, (t) => t.toString(16).padStart(2, "0")).join(""), ee = "automerge:", tt = (e) => {
842
- const [t, n, ...H] = e.split("#");
843
- if (H.length > 0)
844
- throw new Error("Invalid URL: contains multiple heads sections");
845
- const y = new RegExp(`^${ee}(\\w+)$`), [, w] = t.match(y) || [], a = w, c = Re(a);
846
- if (!c)
847
- throw new Error("Invalid document URL: " + e);
848
- if (n === void 0)
849
- return { binaryDocumentId: c, documentId: a };
850
- const s = n === "" ? [] : n.split("|"), o = s.map((i) => {
851
- try {
852
- return et(Q.decode(i));
853
- } catch {
854
- throw new Error(`Invalid head in URL: ${i}`);
855
- }
856
- });
857
- return { binaryDocumentId: c, hexHeads: o, documentId: a, heads: s };
858
- }, De = (e) => {
859
- if (e instanceof Uint8Array || typeof e == "string")
860
- return ee + (e instanceof Uint8Array ? Ie(e) : e);
861
- const { documentId: t, heads: n = void 0 } = e;
862
- if (t === void 0)
863
- throw new Error("Invalid documentId: " + t);
864
- const H = t instanceof Uint8Array ? Ie(t) : t;
865
- let y = `${ee}${H}`;
866
- return n !== void 0 && (n.forEach((w) => {
1335
+
1336
+ var bs58checkExports = requireBs58check();
1337
+ const bs58check = /*@__PURE__*/getDefaultExportFromCjs(bs58checkExports);
1338
+
1339
+ const uint8ArrayToHexString = (data) => {
1340
+ return Array.from(data, byte => byte.toString(16).padStart(2, "0")).join("");
1341
+ };
1342
+
1343
+ const urlPrefix = "automerge:";
1344
+ /** Given an Automerge URL, returns the DocumentId in both base58check-encoded form and binary form */
1345
+ const parseAutomergeUrl = (url) => {
1346
+ const [baseUrl, headsSection, ...rest] = url.split("#");
1347
+ if (rest.length > 0) {
1348
+ throw new Error("Invalid URL: contains multiple heads sections");
1349
+ }
1350
+ const regex = new RegExp(`^${urlPrefix}(\\w+)$`);
1351
+ const [, docMatch] = baseUrl.match(regex) || [];
1352
+ const documentId = docMatch;
1353
+ const binaryDocumentId = documentIdToBinary(documentId);
1354
+ if (!binaryDocumentId)
1355
+ throw new Error("Invalid document URL: " + url);
1356
+ if (headsSection === undefined)
1357
+ return { binaryDocumentId, documentId };
1358
+ const heads = (headsSection === "" ? [] : headsSection.split("|"));
1359
+ const hexHeads = heads.map(head => {
1360
+ try {
1361
+ return uint8ArrayToHexString(bs58check.decode(head));
1362
+ }
1363
+ catch (e) {
1364
+ throw new Error(`Invalid head in URL: ${head}`);
1365
+ }
1366
+ });
1367
+ return { binaryDocumentId, hexHeads, documentId, heads };
1368
+ };
1369
+ /**
1370
+ * Given a documentId in either binary or base58check-encoded form, returns an Automerge URL.
1371
+ * Throws on invalid input.
1372
+ */
1373
+ const stringifyAutomergeUrl = (arg) => {
1374
+ if (arg instanceof Uint8Array || typeof arg === "string") {
1375
+ return (urlPrefix +
1376
+ (arg instanceof Uint8Array
1377
+ ? binaryToDocumentId(arg)
1378
+ : arg));
1379
+ }
1380
+ const { documentId, heads = undefined } = arg;
1381
+ if (documentId === undefined)
1382
+ throw new Error("Invalid documentId: " + documentId);
1383
+ const encodedDocumentId = documentId instanceof Uint8Array
1384
+ ? binaryToDocumentId(documentId)
1385
+ : documentId;
1386
+ let url = `${urlPrefix}${encodedDocumentId}`;
1387
+ if (heads !== undefined) {
1388
+ heads.forEach(head => {
1389
+ try {
1390
+ bs58check.decode(head);
1391
+ }
1392
+ catch (e) {
1393
+ throw new Error(`Invalid head: ${head}`);
1394
+ }
1395
+ });
1396
+ url += "#" + heads.join("|");
1397
+ }
1398
+ return url;
1399
+ };
1400
+ const anyDocumentIdToAutomergeUrl = (id) => isValidAutomergeUrl(id)
1401
+ ? id
1402
+ : isValidDocumentId(id)
1403
+ ? stringifyAutomergeUrl({ documentId: id })
1404
+ : isValidUuid(id)
1405
+ ? parseLegacyUUID(id)
1406
+ : undefined;
1407
+ /**
1408
+ * Given a string, returns true if it is a valid Automerge URL. This function also acts as a type
1409
+ * discriminator in Typescript.
1410
+ */
1411
+ const isValidAutomergeUrl = (str) => {
1412
+ if (typeof str !== "string" || !str || !str.startsWith(urlPrefix))
1413
+ return false;
867
1414
  try {
868
- Q.decode(w);
869
- } catch {
870
- throw new Error(`Invalid head: ${w}`);
1415
+ const { documentId, heads } = parseAutomergeUrl(str);
1416
+ if (!isValidDocumentId(documentId))
1417
+ return false;
1418
+ if (heads &&
1419
+ !heads.every(head => {
1420
+ try {
1421
+ bs58check.decode(head);
1422
+ return true;
1423
+ }
1424
+ catch {
1425
+ return false;
1426
+ }
1427
+ }))
1428
+ return false;
1429
+ return true;
1430
+ }
1431
+ catch {
1432
+ return false;
871
1433
  }
872
- }), y += "#" + n.join("|")), y;
873
- }, rt = (e) => nt(e) ? e : Me(e) ? De({ documentId: e }) : st(e) ? ot(e) : void 0, nt = (e) => {
874
- if (typeof e != "string" || !e || !e.startsWith(ee))
875
- return !1;
876
- try {
877
- const { documentId: t, heads: n } = tt(e);
878
- return !(!Me(t) || n && !n.every((H) => {
879
- try {
880
- return Q.decode(H), !0;
881
- } catch {
882
- return !1;
883
- }
884
- }));
885
- } catch {
886
- return !1;
887
- }
888
- }, Me = (e) => typeof e != "string" ? !1 : Re(e) !== void 0, st = (e) => typeof e == "string" && de(e), Re = (e) => Q.decodeUnsafe(e), Ie = (e) => Q.encode(e), ot = (e) => {
889
- if (!de(e))
890
- return;
891
- const t = je(e);
892
- return De({ documentId: t });
893
- }, te = /* @__PURE__ */ new Map();
894
- function ct(e, { suspense: t } = { suspense: !1 }) {
895
- const n = Ve(), H = qe(), [y, w] = X();
896
- let a = (
1434
+ };
1435
+ const isValidDocumentId = (str) => {
1436
+ if (typeof str !== "string")
1437
+ return false;
1438
+ // try to decode from base58
1439
+ const binaryDocumentID = documentIdToBinary(str);
1440
+ return binaryDocumentID !== undefined;
1441
+ };
1442
+ const isValidUuid = (str) => typeof str === "string" && validate(str);
1443
+ const documentIdToBinary = (docId) => bs58check.decodeUnsafe(docId);
1444
+ const binaryToDocumentId = (docId) => bs58check.encode(docId);
1445
+ const parseLegacyUUID = (str) => {
1446
+ if (!validate(str))
1447
+ return undefined;
1448
+ const documentId = parse(str);
1449
+ return stringifyAutomergeUrl({ documentId });
1450
+ };
1451
+
1452
+ const wrapperCache = /* @__PURE__ */ new Map();
1453
+ function useDocHandle(id, { suspense } = { suspense: false }) {
1454
+ const repo = useRepo();
1455
+ const controllerRef = useRef();
1456
+ const [handle, setHandle] = useState();
1457
+ let currentHandle = (
897
1458
  // make sure the handle matches the id
898
- e && y && y.url === rt(e) ? y : void 0
1459
+ id && handle && handle.url === anyDocumentIdToAutomergeUrl(id) ? handle : void 0
899
1460
  );
900
- if (e && !a) {
901
- const s = n.findWithProgress(e);
902
- s.state === "ready" && (a = s.handle);
1461
+ if (id && !currentHandle) {
1462
+ const progress = repo.findWithProgress(id);
1463
+ if (progress.state === "ready") {
1464
+ currentHandle = progress.handle;
1465
+ }
903
1466
  }
904
- let c = e ? te.get(e) : void 0;
905
- if (!c && e) {
906
- H.current?.abort(), H.current = new AbortController();
907
- const s = n.find(e, { signal: H.current.signal });
908
- c = Ue(s), te.set(e, c);
1467
+ let wrapper = id ? wrapperCache.get(id) : void 0;
1468
+ if (!wrapper && id) {
1469
+ controllerRef.current?.abort();
1470
+ controllerRef.current = new AbortController();
1471
+ const promise = repo.find(id, { signal: controllerRef.current.signal });
1472
+ wrapper = wrapPromise(promise);
1473
+ wrapperCache.set(id, wrapper);
909
1474
  }
910
- return z(() => {
911
- a || t || !c || c.promise.then((s) => {
912
- w(s);
1475
+ useEffect(() => {
1476
+ if (currentHandle || suspense || !wrapper) {
1477
+ return;
1478
+ }
1479
+ wrapper.promise.then((handle2) => {
1480
+ setHandle(handle2);
913
1481
  }).catch(() => {
914
- w(void 0);
1482
+ setHandle(void 0);
915
1483
  });
916
- }, [a, t, c]), a || !t || !c ? a : c.read();
1484
+ }, [currentHandle, suspense, wrapper]);
1485
+ if (currentHandle || !suspense || !wrapper) {
1486
+ return currentHandle;
1487
+ }
1488
+ return wrapper.read();
917
1489
  }
918
- function pt(e, t = { suspense: !1 }) {
919
- const n = ct(e, t), [H, y] = X(() => n?.doc()), [w, a] = X();
920
- z(() => {
921
- y(n?.doc());
922
- }, [n]), z(() => {
923
- if (!n)
1490
+
1491
+ function useDocument(id, params = { suspense: false }) {
1492
+ const handle = useDocHandle(id, params);
1493
+ const [doc, setDoc] = useState(() => handle?.doc());
1494
+ const [deleteError, setDeleteError] = useState();
1495
+ useEffect(() => {
1496
+ setDoc(handle?.doc());
1497
+ }, [handle]);
1498
+ useEffect(() => {
1499
+ if (!handle) {
924
1500
  return;
925
- const s = () => y(n.doc()), o = () => {
926
- a(new Error(`Document ${e} was deleted`));
1501
+ }
1502
+ const onChange = () => setDoc(handle.doc());
1503
+ const onDelete = () => {
1504
+ setDeleteError(new Error(`Document ${id} was deleted`));
927
1505
  };
928
- return n.on("change", s), n.on("delete", o), () => {
929
- n.removeListener("change", s), n.removeListener("delete", o);
1506
+ handle.on("change", onChange);
1507
+ handle.on("delete", onDelete);
1508
+ return () => {
1509
+ handle.removeListener("change", onChange);
1510
+ handle.removeListener("delete", onDelete);
930
1511
  };
931
- }, [n, e]);
932
- const c = Le(
933
- (s, o) => {
934
- n.change(s, o);
1512
+ }, [handle, id]);
1513
+ const changeDoc = useCallback(
1514
+ (changeFn, options) => {
1515
+ handle.change(changeFn, options);
935
1516
  },
936
- [n]
1517
+ [handle]
937
1518
  );
938
- if (w)
939
- throw w;
940
- return H ? [H, c] : [void 0, () => {
941
- }];
1519
+ if (deleteError) {
1520
+ throw deleteError;
1521
+ }
1522
+ if (!doc) {
1523
+ return [void 0, () => {
1524
+ }];
1525
+ }
1526
+ return [doc, changeDoc];
942
1527
  }
943
- function at(e) {
944
- const [t, n] = X(() => new Set(e));
945
- return z(() => {
946
- const H = new Set(e);
947
- it(t, H) || n(H);
948
- }, [t, e]), t;
1528
+
1529
+ function useSet(items) {
1530
+ const [set, setSet] = useState(() => {
1531
+ return new Set(items);
1532
+ });
1533
+ useEffect(() => {
1534
+ const newSet = new Set(items);
1535
+ if (identical(set, newSet)) {
1536
+ return;
1537
+ }
1538
+ setSet(newSet);
1539
+ }, [set, items]);
1540
+ return set;
949
1541
  }
950
- function it(e, t) {
951
- return e.size === t.size && Array.from(e).every((n) => t.has(n));
1542
+ function identical(s1, s2) {
1543
+ return s1.size === s2.size && Array.from(s1).every((v) => s2.has(v));
952
1544
  }
953
- function ft(e, { suspense: t = !1 } = {}) {
954
- const n = at(e), H = Ve(), [y, w] = X(() => {
955
- const s = /* @__PURE__ */ new Map();
956
- for (const o of n.values()) {
957
- let i;
1545
+
1546
+ function useDocHandles(ids, { suspense = false } = {}) {
1547
+ const idSet = useSet(ids);
1548
+ const repo = useRepo();
1549
+ const [handleMap, setHandleMap] = useState(() => {
1550
+ const map = /* @__PURE__ */ new Map();
1551
+ for (const id of idSet.values()) {
1552
+ let progress;
958
1553
  try {
959
- i = H.findWithProgress(o);
960
- } catch {
1554
+ progress = repo.findWithProgress(id);
1555
+ } catch (e) {
961
1556
  continue;
962
1557
  }
963
- i.state === "ready" && s.set(o, i.handle);
1558
+ if (progress.state === "ready") {
1559
+ map.set(id, progress.handle);
1560
+ }
964
1561
  }
965
- return s;
966
- }), a = [], c = /* @__PURE__ */ new Map();
967
- for (const s of n.values()) {
968
- let o = y.get(s), i = te.get(s);
969
- if (!i)
1562
+ return map;
1563
+ });
1564
+ const pendingPromises = [];
1565
+ const nextHandleMap = /* @__PURE__ */ new Map();
1566
+ for (const id of idSet.values()) {
1567
+ let handle = handleMap.get(id);
1568
+ let wrapper = wrapperCache.get(id);
1569
+ if (!wrapper) {
970
1570
  try {
971
- const h = H.find(s);
972
- i = Ue(h), te.set(s, i);
973
- } catch {
1571
+ const promise = repo.find(id);
1572
+ wrapper = wrapPromise(promise);
1573
+ wrapperCache.set(id, wrapper);
1574
+ } catch (e) {
974
1575
  continue;
975
1576
  }
1577
+ }
976
1578
  try {
977
- o ??= i.read(), c.set(s, o);
978
- } catch (h) {
979
- h instanceof Promise ? a.push(i) : c.set(s, void 0);
1579
+ handle ??= wrapper.read();
1580
+ nextHandleMap.set(id, handle);
1581
+ } catch (e) {
1582
+ if (e instanceof Promise) {
1583
+ pendingPromises.push(wrapper);
1584
+ } else {
1585
+ nextHandleMap.set(id, void 0);
1586
+ }
980
1587
  }
981
1588
  }
982
- if (z(() => {
983
- a.length > 0 ? Promise.allSettled(a.map((s) => s.promise)).then(
984
- (s) => {
985
- s.forEach((o) => {
986
- if (o.status === "fulfilled") {
987
- const i = o.value;
988
- c.set(i.url, i);
989
- }
990
- }), w(c);
991
- }
992
- ) : w(c);
993
- }, [t, n]), t && a.length > 0)
994
- throw Promise.all(a.map((s) => s.promise));
995
- return y;
1589
+ useEffect(() => {
1590
+ if (pendingPromises.length > 0) {
1591
+ void Promise.allSettled(pendingPromises.map((p) => p.promise)).then(
1592
+ (handles) => {
1593
+ handles.forEach((r) => {
1594
+ if (r.status === "fulfilled") {
1595
+ const h = r.value;
1596
+ nextHandleMap.set(h.url, h);
1597
+ }
1598
+ });
1599
+ setHandleMap(nextHandleMap);
1600
+ }
1601
+ );
1602
+ } else {
1603
+ setHandleMap(nextHandleMap);
1604
+ }
1605
+ }, [suspense, idSet]);
1606
+ if (suspense && pendingPromises.length > 0) {
1607
+ throw Promise.all(pendingPromises.map((p) => p.promise));
1608
+ }
1609
+ return handleMap;
996
1610
  }
997
- function Ht(e, { suspense: t = !0 } = {}) {
998
- const n = ft(e, { suspense: t }), [H, y] = X(() => {
999
- const a = /* @__PURE__ */ new Map();
1000
- return n.forEach((c) => {
1001
- const s = c?.url;
1002
- s && a.set(s, c?.doc());
1003
- }), a;
1611
+
1612
+ function useDocuments(ids, { suspense = true } = {}) {
1613
+ const handleMap = useDocHandles(ids, { suspense });
1614
+ const [docMap, setDocMap] = useState(() => {
1615
+ const docs = /* @__PURE__ */ new Map();
1616
+ handleMap.forEach((handle) => {
1617
+ const url = handle?.url;
1618
+ if (url) {
1619
+ docs.set(url, handle?.doc());
1620
+ }
1621
+ });
1622
+ return docs;
1004
1623
  });
1005
- z(() => {
1006
- const a = /* @__PURE__ */ new Map();
1007
- return n.forEach((c, s) => {
1008
- if (c) {
1009
- const o = () => {
1010
- y((i) => {
1011
- const h = new Map(i);
1012
- return h.set(s, c.doc()), h;
1624
+ useEffect(() => {
1625
+ const listeners = /* @__PURE__ */ new Map();
1626
+ handleMap.forEach((handle, id) => {
1627
+ if (handle) {
1628
+ const onChange = () => {
1629
+ setDocMap((prev) => {
1630
+ const next = new Map(prev);
1631
+ next.set(id, handle.doc());
1632
+ return next;
1013
1633
  });
1014
1634
  };
1015
- y((i) => {
1016
- const h = new Map(i);
1017
- return h.set(s, c.doc()), h;
1018
- }), c.on("change", o), a.set(s, o);
1635
+ setDocMap((prev) => {
1636
+ const next = new Map(prev);
1637
+ next.set(id, handle.doc());
1638
+ return next;
1639
+ });
1640
+ handle.on("change", onChange);
1641
+ listeners.set(id, onChange);
1642
+ }
1643
+ });
1644
+ setDocMap((prev) => {
1645
+ const next = new Map(prev);
1646
+ for (const [id] of next) {
1647
+ if (!handleMap.has(id)) {
1648
+ next.delete(id);
1649
+ }
1019
1650
  }
1020
- }), y((c) => {
1021
- const s = new Map(c);
1022
- for (const [o] of s)
1023
- n.has(o) || s.delete(o);
1024
- return s;
1025
- }), () => {
1026
- n.forEach((c, s) => {
1027
- const o = a.get(s);
1028
- c && o && c.removeListener("change", o);
1651
+ return next;
1652
+ });
1653
+ return () => {
1654
+ handleMap.forEach((handle, id) => {
1655
+ const listener = listeners.get(id);
1656
+ if (handle && listener) {
1657
+ handle.removeListener("change", listener);
1658
+ }
1029
1659
  });
1030
1660
  };
1031
- }, [n]);
1032
- const w = Le(
1033
- (a, c, s) => {
1034
- const o = n.get(a);
1035
- o && o.change(c, s);
1661
+ }, [handleMap]);
1662
+ const changeDoc = useCallback(
1663
+ (id, changeFn, options) => {
1664
+ const handle = handleMap.get(id);
1665
+ if (handle) {
1666
+ handle.change(changeFn, options);
1667
+ }
1036
1668
  },
1037
- [n]
1669
+ [handleMap]
1038
1670
  );
1039
- return [H, w];
1671
+ return [docMap, changeDoc];
1040
1672
  }
1041
- var fe, Ee;
1042
- function ht() {
1043
- if (Ee) return fe;
1044
- Ee = 1;
1045
- var e = ke, t = function(H) {
1046
- return typeof H == "function";
1047
- }, n = function(H) {
1048
- var y = e.useState(H), w = y[0], a = y[1], c = e.useRef(w), s = e.useCallback(function(o) {
1049
- c.current = t(o) ? o(c.current) : o, a(c.current);
1050
- }, []);
1051
- return [w, s, c];
1052
- };
1053
- return fe = n, fe;
1673
+
1674
+ var dist;
1675
+ var hasRequiredDist;
1676
+
1677
+ function requireDist () {
1678
+ if (hasRequiredDist) return dist;
1679
+ hasRequiredDist = 1;
1680
+ var react_1 = require$$0;
1681
+ var isFunction = function (setStateAction) {
1682
+ return typeof setStateAction === "function";
1683
+ };
1684
+ var useStateRef = function (initialState) {
1685
+ var _a = react_1.useState(initialState), state = _a[0], setState = _a[1];
1686
+ var ref = react_1.useRef(state);
1687
+ var dispatch = react_1.useCallback(function (setStateAction) {
1688
+ ref.current = isFunction(setStateAction) ? setStateAction(ref.current) : setStateAction;
1689
+ setState(ref.current);
1690
+ }, []);
1691
+ return [state, dispatch, ref];
1692
+ };
1693
+ dist = useStateRef;
1694
+ return dist;
1054
1695
  }
1055
- var ut = ht();
1056
- const ue = /* @__PURE__ */ be(ut);
1057
- var he = { exports: {} }, Be;
1058
- function lt() {
1059
- return Be || (Be = 1, function(e) {
1060
- var t = Object.prototype.hasOwnProperty, n = "~";
1061
- function H() {
1062
- }
1063
- Object.create && (H.prototype = /* @__PURE__ */ Object.create(null), new H().__proto__ || (n = !1));
1064
- function y(s, o, i) {
1065
- this.fn = s, this.context = o, this.once = i || !1;
1066
- }
1067
- function w(s, o, i, h, m) {
1068
- if (typeof i != "function")
1069
- throw new TypeError("The listener must be a function");
1070
- var B = new y(i, h || s, m), f = n ? n + o : o;
1071
- return s._events[f] ? s._events[f].fn ? s._events[f] = [s._events[f], B] : s._events[f].push(B) : (s._events[f] = B, s._eventsCount++), s;
1072
- }
1073
- function a(s, o) {
1074
- --s._eventsCount === 0 ? s._events = new H() : delete s._events[o];
1075
- }
1076
- function c() {
1077
- this._events = new H(), this._eventsCount = 0;
1696
+
1697
+ var distExports = requireDist();
1698
+ const useStateRef = /*@__PURE__*/getDefaultExportFromCjs(distExports);
1699
+
1700
+ var eventemitter3 = {exports: {}};
1701
+
1702
+ var hasRequiredEventemitter3;
1703
+
1704
+ function requireEventemitter3 () {
1705
+ if (hasRequiredEventemitter3) return eventemitter3.exports;
1706
+ hasRequiredEventemitter3 = 1;
1707
+ (function (module) {
1708
+
1709
+ var has = Object.prototype.hasOwnProperty
1710
+ , prefix = '~';
1711
+
1712
+ /**
1713
+ * Constructor to create a storage for our `EE` objects.
1714
+ * An `Events` instance is a plain object whose properties are event names.
1715
+ *
1716
+ * @constructor
1717
+ * @private
1718
+ */
1719
+ function Events() {}
1720
+
1721
+ //
1722
+ // We try to not inherit from `Object.prototype`. In some engines creating an
1723
+ // instance in this way is faster than calling `Object.create(null)` directly.
1724
+ // If `Object.create(null)` is not supported we prefix the event names with a
1725
+ // character to make sure that the built-in object properties are not
1726
+ // overridden or used as an attack vector.
1727
+ //
1728
+ if (Object.create) {
1729
+ Events.prototype = Object.create(null);
1730
+
1731
+ //
1732
+ // This hack is needed because the `__proto__` property is still inherited in
1733
+ // some old browsers like Android 4, iPhone 5.1, Opera 11 and Safari 5.
1734
+ //
1735
+ if (!new Events().__proto__) prefix = false;
1736
+ }
1737
+
1738
+ /**
1739
+ * Representation of a single event listener.
1740
+ *
1741
+ * @param {Function} fn The listener function.
1742
+ * @param {*} context The context to invoke the listener with.
1743
+ * @param {Boolean} [once=false] Specify if the listener is a one-time listener.
1744
+ * @constructor
1745
+ * @private
1746
+ */
1747
+ function EE(fn, context, once) {
1748
+ this.fn = fn;
1749
+ this.context = context;
1750
+ this.once = once || false;
1751
+ }
1752
+
1753
+ /**
1754
+ * Add a listener for a given event.
1755
+ *
1756
+ * @param {EventEmitter} emitter Reference to the `EventEmitter` instance.
1757
+ * @param {(String|Symbol)} event The event name.
1758
+ * @param {Function} fn The listener function.
1759
+ * @param {*} context The context to invoke the listener with.
1760
+ * @param {Boolean} once Specify if the listener is a one-time listener.
1761
+ * @returns {EventEmitter}
1762
+ * @private
1763
+ */
1764
+ function addListener(emitter, event, fn, context, once) {
1765
+ if (typeof fn !== 'function') {
1766
+ throw new TypeError('The listener must be a function');
1767
+ }
1768
+
1769
+ var listener = new EE(fn, context || emitter, once)
1770
+ , evt = prefix ? prefix + event : event;
1771
+
1772
+ if (!emitter._events[evt]) emitter._events[evt] = listener, emitter._eventsCount++;
1773
+ else if (!emitter._events[evt].fn) emitter._events[evt].push(listener);
1774
+ else emitter._events[evt] = [emitter._events[evt], listener];
1775
+
1776
+ return emitter;
1777
+ }
1778
+
1779
+ /**
1780
+ * Clear event by name.
1781
+ *
1782
+ * @param {EventEmitter} emitter Reference to the `EventEmitter` instance.
1783
+ * @param {(String|Symbol)} evt The Event name.
1784
+ * @private
1785
+ */
1786
+ function clearEvent(emitter, evt) {
1787
+ if (--emitter._eventsCount === 0) emitter._events = new Events();
1788
+ else delete emitter._events[evt];
1789
+ }
1790
+
1791
+ /**
1792
+ * Minimal `EventEmitter` interface that is molded against the Node.js
1793
+ * `EventEmitter` interface.
1794
+ *
1795
+ * @constructor
1796
+ * @public
1797
+ */
1798
+ function EventEmitter() {
1799
+ this._events = new Events();
1800
+ this._eventsCount = 0;
1801
+ }
1802
+
1803
+ /**
1804
+ * Return an array listing the events for which the emitter has registered
1805
+ * listeners.
1806
+ *
1807
+ * @returns {Array}
1808
+ * @public
1809
+ */
1810
+ EventEmitter.prototype.eventNames = function eventNames() {
1811
+ var names = []
1812
+ , events
1813
+ , name;
1814
+
1815
+ if (this._eventsCount === 0) return names;
1816
+
1817
+ for (name in (events = this._events)) {
1818
+ if (has.call(events, name)) names.push(prefix ? name.slice(1) : name);
1819
+ }
1820
+
1821
+ if (Object.getOwnPropertySymbols) {
1822
+ return names.concat(Object.getOwnPropertySymbols(events));
1823
+ }
1824
+
1825
+ return names;
1826
+ };
1827
+
1828
+ /**
1829
+ * Return the listeners registered for a given event.
1830
+ *
1831
+ * @param {(String|Symbol)} event The event name.
1832
+ * @returns {Array} The registered listeners.
1833
+ * @public
1834
+ */
1835
+ EventEmitter.prototype.listeners = function listeners(event) {
1836
+ var evt = prefix ? prefix + event : event
1837
+ , handlers = this._events[evt];
1838
+
1839
+ if (!handlers) return [];
1840
+ if (handlers.fn) return [handlers.fn];
1841
+
1842
+ for (var i = 0, l = handlers.length, ee = new Array(l); i < l; i++) {
1843
+ ee[i] = handlers[i].fn;
1844
+ }
1845
+
1846
+ return ee;
1847
+ };
1848
+
1849
+ /**
1850
+ * Return the number of listeners listening to a given event.
1851
+ *
1852
+ * @param {(String|Symbol)} event The event name.
1853
+ * @returns {Number} The number of listeners.
1854
+ * @public
1855
+ */
1856
+ EventEmitter.prototype.listenerCount = function listenerCount(event) {
1857
+ var evt = prefix ? prefix + event : event
1858
+ , listeners = this._events[evt];
1859
+
1860
+ if (!listeners) return 0;
1861
+ if (listeners.fn) return 1;
1862
+ return listeners.length;
1863
+ };
1864
+
1865
+ /**
1866
+ * Calls each of the listeners registered for a given event.
1867
+ *
1868
+ * @param {(String|Symbol)} event The event name.
1869
+ * @returns {Boolean} `true` if the event had listeners, else `false`.
1870
+ * @public
1871
+ */
1872
+ EventEmitter.prototype.emit = function emit(event, a1, a2, a3, a4, a5) {
1873
+ var evt = prefix ? prefix + event : event;
1874
+
1875
+ if (!this._events[evt]) return false;
1876
+
1877
+ var listeners = this._events[evt]
1878
+ , len = arguments.length
1879
+ , args
1880
+ , i;
1881
+
1882
+ if (listeners.fn) {
1883
+ if (listeners.once) this.removeListener(event, listeners.fn, undefined, true);
1884
+
1885
+ switch (len) {
1886
+ case 1: return listeners.fn.call(listeners.context), true;
1887
+ case 2: return listeners.fn.call(listeners.context, a1), true;
1888
+ case 3: return listeners.fn.call(listeners.context, a1, a2), true;
1889
+ case 4: return listeners.fn.call(listeners.context, a1, a2, a3), true;
1890
+ case 5: return listeners.fn.call(listeners.context, a1, a2, a3, a4), true;
1891
+ case 6: return listeners.fn.call(listeners.context, a1, a2, a3, a4, a5), true;
1892
+ }
1893
+
1894
+ for (i = 1, args = new Array(len -1); i < len; i++) {
1895
+ args[i - 1] = arguments[i];
1896
+ }
1897
+
1898
+ listeners.fn.apply(listeners.context, args);
1899
+ } else {
1900
+ var length = listeners.length
1901
+ , j;
1902
+
1903
+ for (i = 0; i < length; i++) {
1904
+ if (listeners[i].once) this.removeListener(event, listeners[i].fn, undefined, true);
1905
+
1906
+ switch (len) {
1907
+ case 1: listeners[i].fn.call(listeners[i].context); break;
1908
+ case 2: listeners[i].fn.call(listeners[i].context, a1); break;
1909
+ case 3: listeners[i].fn.call(listeners[i].context, a1, a2); break;
1910
+ case 4: listeners[i].fn.call(listeners[i].context, a1, a2, a3); break;
1911
+ default:
1912
+ if (!args) for (j = 1, args = new Array(len -1); j < len; j++) {
1913
+ args[j - 1] = arguments[j];
1914
+ }
1915
+
1916
+ listeners[i].fn.apply(listeners[i].context, args);
1917
+ }
1918
+ }
1919
+ }
1920
+
1921
+ return true;
1922
+ };
1923
+
1924
+ /**
1925
+ * Add a listener for a given event.
1926
+ *
1927
+ * @param {(String|Symbol)} event The event name.
1928
+ * @param {Function} fn The listener function.
1929
+ * @param {*} [context=this] The context to invoke the listener with.
1930
+ * @returns {EventEmitter} `this`.
1931
+ * @public
1932
+ */
1933
+ EventEmitter.prototype.on = function on(event, fn, context) {
1934
+ return addListener(this, event, fn, context, false);
1935
+ };
1936
+
1937
+ /**
1938
+ * Add a one-time listener for a given event.
1939
+ *
1940
+ * @param {(String|Symbol)} event The event name.
1941
+ * @param {Function} fn The listener function.
1942
+ * @param {*} [context=this] The context to invoke the listener with.
1943
+ * @returns {EventEmitter} `this`.
1944
+ * @public
1945
+ */
1946
+ EventEmitter.prototype.once = function once(event, fn, context) {
1947
+ return addListener(this, event, fn, context, true);
1948
+ };
1949
+
1950
+ /**
1951
+ * Remove the listeners of a given event.
1952
+ *
1953
+ * @param {(String|Symbol)} event The event name.
1954
+ * @param {Function} fn Only remove the listeners that match this function.
1955
+ * @param {*} context Only remove the listeners that have this context.
1956
+ * @param {Boolean} once Only remove one-time listeners.
1957
+ * @returns {EventEmitter} `this`.
1958
+ * @public
1959
+ */
1960
+ EventEmitter.prototype.removeListener = function removeListener(event, fn, context, once) {
1961
+ var evt = prefix ? prefix + event : event;
1962
+
1963
+ if (!this._events[evt]) return this;
1964
+ if (!fn) {
1965
+ clearEvent(this, evt);
1966
+ return this;
1967
+ }
1968
+
1969
+ var listeners = this._events[evt];
1970
+
1971
+ if (listeners.fn) {
1972
+ if (
1973
+ listeners.fn === fn &&
1974
+ (!once || listeners.once) &&
1975
+ (!context || listeners.context === context)
1976
+ ) {
1977
+ clearEvent(this, evt);
1978
+ }
1979
+ } else {
1980
+ for (var i = 0, events = [], length = listeners.length; i < length; i++) {
1981
+ if (
1982
+ listeners[i].fn !== fn ||
1983
+ (once && !listeners[i].once) ||
1984
+ (context && listeners[i].context !== context)
1985
+ ) {
1986
+ events.push(listeners[i]);
1987
+ }
1988
+ }
1989
+
1990
+ //
1991
+ // Reset the array, or remove it completely if we have no more listeners.
1992
+ //
1993
+ if (events.length) this._events[evt] = events.length === 1 ? events[0] : events;
1994
+ else clearEvent(this, evt);
1995
+ }
1996
+
1997
+ return this;
1998
+ };
1999
+
2000
+ /**
2001
+ * Remove all listeners, or those of the specified event.
2002
+ *
2003
+ * @param {(String|Symbol)} [event] The event name.
2004
+ * @returns {EventEmitter} `this`.
2005
+ * @public
2006
+ */
2007
+ EventEmitter.prototype.removeAllListeners = function removeAllListeners(event) {
2008
+ var evt;
2009
+
2010
+ if (event) {
2011
+ evt = prefix ? prefix + event : event;
2012
+ if (this._events[evt]) clearEvent(this, evt);
2013
+ } else {
2014
+ this._events = new Events();
2015
+ this._eventsCount = 0;
2016
+ }
2017
+
2018
+ return this;
2019
+ };
2020
+
2021
+ //
2022
+ // Alias methods names because people roll like that.
2023
+ //
2024
+ EventEmitter.prototype.off = EventEmitter.prototype.removeListener;
2025
+ EventEmitter.prototype.addListener = EventEmitter.prototype.on;
2026
+
2027
+ //
2028
+ // Expose the prefix.
2029
+ //
2030
+ EventEmitter.prefixed = prefix;
2031
+
2032
+ //
2033
+ // Allow `EventEmitter` to be imported as module namespace.
2034
+ //
2035
+ EventEmitter.EventEmitter = EventEmitter;
2036
+
2037
+ //
2038
+ // Expose the module.
2039
+ //
2040
+ {
2041
+ module.exports = EventEmitter;
2042
+ }
2043
+ } (eventemitter3));
2044
+ return eventemitter3.exports;
2045
+ }
2046
+
2047
+ var eventemitter3Exports = requireEventemitter3();
2048
+ const EventEmitter = /*@__PURE__*/getDefaultExportFromCjs(eventemitter3Exports);
2049
+
2050
+ const peerEvents = new EventEmitter();
2051
+ const useRemoteAwareness = ({
2052
+ handle,
2053
+ localUserId,
2054
+ offlineTimeout = 3e4,
2055
+ getTime = () => (/* @__PURE__ */ new Date()).getTime()
2056
+ }) => {
2057
+ const [peerStates, setPeerStates, peerStatesRef] = useStateRef({});
2058
+ const [heartbeats, setHeartbeats, heartbeatsRef] = useStateRef({});
2059
+ useEffect(() => {
2060
+ if (!handle) {
2061
+ return;
1078
2062
  }
1079
- c.prototype.eventNames = function() {
1080
- var o = [], i, h;
1081
- if (this._eventsCount === 0) return o;
1082
- for (h in i = this._events)
1083
- t.call(i, h) && o.push(n ? h.slice(1) : h);
1084
- return Object.getOwnPropertySymbols ? o.concat(Object.getOwnPropertySymbols(i)) : o;
1085
- }, c.prototype.listeners = function(o) {
1086
- var i = n ? n + o : o, h = this._events[i];
1087
- if (!h) return [];
1088
- if (h.fn) return [h.fn];
1089
- for (var m = 0, B = h.length, f = new Array(B); m < B; m++)
1090
- f[m] = h[m].fn;
1091
- return f;
1092
- }, c.prototype.listenerCount = function(o) {
1093
- var i = n ? n + o : o, h = this._events[i];
1094
- return h ? h.fn ? 1 : h.length : 0;
1095
- }, c.prototype.emit = function(o, i, h, m, B, f) {
1096
- var g = n ? n + o : o;
1097
- if (!this._events[g]) return !1;
1098
- var d = this._events[g], V = arguments.length, M, x;
1099
- if (d.fn) {
1100
- switch (d.once && this.removeListener(o, d.fn, void 0, !0), V) {
1101
- case 1:
1102
- return d.fn.call(d.context), !0;
1103
- case 2:
1104
- return d.fn.call(d.context, i), !0;
1105
- case 3:
1106
- return d.fn.call(d.context, i, h), !0;
1107
- case 4:
1108
- return d.fn.call(d.context, i, h, m), !0;
1109
- case 5:
1110
- return d.fn.call(d.context, i, h, m, B), !0;
1111
- case 6:
1112
- return d.fn.call(d.context, i, h, m, B, f), !0;
2063
+ const handleIncomingUpdate = (event) => {
2064
+ const [userId, state] = event.message;
2065
+ if (userId === localUserId) return;
2066
+ if (!heartbeatsRef.current[userId]) peerEvents.emit("new_peer", event);
2067
+ setPeerStates({
2068
+ ...peerStatesRef.current,
2069
+ [userId]: state
2070
+ });
2071
+ setHeartbeats({
2072
+ ...heartbeatsRef.current,
2073
+ [userId]: getTime()
2074
+ });
2075
+ };
2076
+ const pruneOfflinePeers = () => {
2077
+ const peerStates2 = { ...peerStatesRef.current };
2078
+ const heartbeats2 = { ...heartbeatsRef.current };
2079
+ const time = getTime();
2080
+ let hasChanges = false;
2081
+ for (const key in heartbeats2) {
2082
+ if (time - heartbeats2[key] > offlineTimeout) {
2083
+ delete peerStates2[key];
2084
+ delete heartbeats2[key];
2085
+ hasChanges = true;
1113
2086
  }
1114
- for (x = 1, M = new Array(V - 1); x < V; x++)
1115
- M[x - 1] = arguments[x];
1116
- d.fn.apply(d.context, M);
1117
- } else {
1118
- var R = d.length, A;
1119
- for (x = 0; x < R; x++)
1120
- switch (d[x].once && this.removeListener(o, d[x].fn, void 0, !0), V) {
1121
- case 1:
1122
- d[x].fn.call(d[x].context);
1123
- break;
1124
- case 2:
1125
- d[x].fn.call(d[x].context, i);
1126
- break;
1127
- case 3:
1128
- d[x].fn.call(d[x].context, i, h);
1129
- break;
1130
- case 4:
1131
- d[x].fn.call(d[x].context, i, h, m);
1132
- break;
1133
- default:
1134
- if (!M) for (A = 1, M = new Array(V - 1); A < V; A++)
1135
- M[A - 1] = arguments[A];
1136
- d[x].fn.apply(d[x].context, M);
1137
- }
1138
2087
  }
1139
- return !0;
1140
- }, c.prototype.on = function(o, i, h) {
1141
- return w(this, o, i, h, !1);
1142
- }, c.prototype.once = function(o, i, h) {
1143
- return w(this, o, i, h, !0);
1144
- }, c.prototype.removeListener = function(o, i, h, m) {
1145
- var B = n ? n + o : o;
1146
- if (!this._events[B]) return this;
1147
- if (!i)
1148
- return a(this, B), this;
1149
- var f = this._events[B];
1150
- if (f.fn)
1151
- f.fn === i && (!m || f.once) && (!h || f.context === h) && a(this, B);
1152
- else {
1153
- for (var g = 0, d = [], V = f.length; g < V; g++)
1154
- (f[g].fn !== i || m && !f[g].once || h && f[g].context !== h) && d.push(f[g]);
1155
- d.length ? this._events[B] = d.length === 1 ? d[0] : d : a(this, B);
2088
+ if (hasChanges) {
2089
+ setPeerStates(peerStates2);
2090
+ setHeartbeats(heartbeats2);
1156
2091
  }
1157
- return this;
1158
- }, c.prototype.removeAllListeners = function(o) {
1159
- var i;
1160
- return o ? (i = n ? n + o : o, this._events[i] && a(this, i)) : (this._events = new H(), this._eventsCount = 0), this;
1161
- }, c.prototype.off = c.prototype.removeListener, c.prototype.addListener = c.prototype.on, c.prefixed = n, c.EventEmitter = c, e.exports = c;
1162
- }(he)), he.exports;
1163
- }
1164
- var dt = lt();
1165
- const bt = /* @__PURE__ */ be(dt), le = new bt(), yt = ({
1166
- handle: e,
1167
- localUserId: t,
1168
- offlineTimeout: n = 3e4,
1169
- getTime: H = () => (/* @__PURE__ */ new Date()).getTime()
1170
- }) => {
1171
- const [y, w, a] = ue({}), [c, s, o] = ue({});
1172
- return z(() => {
1173
- if (!e)
1174
- return;
1175
- const i = (B) => {
1176
- const [f, g] = B.message;
1177
- f !== t && (o.current[f] || le.emit("new_peer", B), w({
1178
- ...a.current,
1179
- [f]: g
1180
- }), s({
1181
- ...o.current,
1182
- [f]: H()
1183
- }));
1184
- }, h = () => {
1185
- const B = { ...a.current }, f = { ...o.current }, g = H();
1186
- let d = !1;
1187
- for (const V in f)
1188
- g - f[V] > n && (delete B[V], delete f[V], d = !0);
1189
- d && (w(B), s(f));
1190
2092
  };
1191
- e.on("ephemeral-message", i);
1192
- const m = setInterval(
1193
- h,
1194
- n
2093
+ handle.on("ephemeral-message", handleIncomingUpdate);
2094
+ const pruneOfflinePeersIntervalId = setInterval(
2095
+ pruneOfflinePeers,
2096
+ offlineTimeout
1195
2097
  );
1196
2098
  return () => {
1197
- e.removeListener("ephemeral-message", i), clearInterval(m);
2099
+ handle.removeListener("ephemeral-message", handleIncomingUpdate);
2100
+ clearInterval(pruneOfflinePeersIntervalId);
1198
2101
  };
1199
- }, [e, t, n, H]), [y, c];
1200
- }, At = ({
1201
- handle: e,
1202
- userId: t,
1203
- initialState: n,
1204
- heartbeatTime: H = 15e3
2102
+ }, [handle, localUserId, offlineTimeout, getTime]);
2103
+ return [peerStates, heartbeats];
2104
+ };
2105
+
2106
+ const useLocalAwareness = ({
2107
+ handle,
2108
+ userId,
2109
+ initialState,
2110
+ heartbeatTime = 15e3
1205
2111
  }) => {
1206
- const [y, w, a] = ue(n), c = (s) => {
1207
- const o = typeof s == "function" ? s(a.current) : s;
1208
- w(o), e && e.broadcast([t, o]);
2112
+ const [localState, setLocalState, localStateRef] = useStateRef(initialState);
2113
+ const setState = (stateOrUpdater) => {
2114
+ const state = typeof stateOrUpdater === "function" ? stateOrUpdater(localStateRef.current) : stateOrUpdater;
2115
+ setLocalState(state);
2116
+ if (handle) {
2117
+ handle.broadcast([userId, state]);
2118
+ }
1209
2119
  };
1210
- return z(() => {
1211
- if (!t || !e)
2120
+ useEffect(() => {
2121
+ if (!userId || !handle) {
1212
2122
  return;
1213
- const s = () => void e.broadcast([t, a.current]);
1214
- s();
1215
- const o = setInterval(s, H);
1216
- return () => void clearInterval(o);
1217
- }, [e, t, H]), z(() => {
1218
- if (!e || !t)
2123
+ }
2124
+ const heartbeat = () => void handle.broadcast([userId, localStateRef.current]);
2125
+ heartbeat();
2126
+ const heartbeatIntervalId = setInterval(heartbeat, heartbeatTime);
2127
+ return () => void clearInterval(heartbeatIntervalId);
2128
+ }, [handle, userId, heartbeatTime]);
2129
+ useEffect(() => {
2130
+ if (!handle || !userId) {
1219
2131
  return;
1220
- let s;
1221
- const o = le.on("new_peer", () => {
1222
- s = setTimeout(
1223
- () => e.broadcast([t, a.current]),
2132
+ }
2133
+ let broadcastTimeoutId;
2134
+ const newPeerEvents = peerEvents.on("new_peer", () => {
2135
+ broadcastTimeoutId = setTimeout(
2136
+ () => handle.broadcast([userId, localStateRef.current]),
1224
2137
  500
1225
2138
  // Wait for the peer to be ready
1226
2139
  );
1227
2140
  });
1228
2141
  return () => {
1229
- o.off("new_peer"), s && clearTimeout(s);
2142
+ newPeerEvents.off("new_peer");
2143
+ broadcastTimeoutId && clearTimeout(broadcastTimeoutId);
1230
2144
  };
1231
- }, [e, t, le]), [y, c];
1232
- };
1233
- export {
1234
- Ge as RepoContext,
1235
- ct as useDocHandle,
1236
- ft as useDocHandles,
1237
- pt as useDocument,
1238
- Ht as useDocuments,
1239
- At as useLocalAwareness,
1240
- yt as useRemoteAwareness,
1241
- Ve as useRepo
2145
+ }, [handle, userId, peerEvents]);
2146
+ return [localState, setState];
1242
2147
  };
2148
+
2149
+ export { RepoContext, useDocHandle, useDocHandles, useDocument, useDocuments, useLocalAwareness, useRemoteAwareness, useRepo };
2150
+ //# sourceMappingURL=index.js.map