@abraca/dabra 0.1.0

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.
@@ -0,0 +1,3199 @@
1
+ import * as Y from "yjs";
2
+ import { retry } from "@lifeomic/attempt";
3
+ import * as ed from "@noble/ed25519";
4
+
5
+ //#region node_modules/lib0/math.js
6
+ /**
7
+ * Common Math expressions.
8
+ *
9
+ * @module math
10
+ */
11
+ const floor = Math.floor;
12
+ /**
13
+ * @function
14
+ * @param {number} a
15
+ * @param {number} b
16
+ * @return {number} The smaller element of a and b
17
+ */
18
+ const min = (a, b) => a < b ? a : b;
19
+ /**
20
+ * @function
21
+ * @param {number} a
22
+ * @param {number} b
23
+ * @return {number} The bigger element of a and b
24
+ */
25
+ const max = (a, b) => a > b ? a : b;
26
+ const isNaN$1 = Number.isNaN;
27
+
28
+ //#endregion
29
+ //#region node_modules/lib0/binary.js
30
+ const BIT7 = 64;
31
+ const BIT8 = 128;
32
+ const BIT18 = 1 << 17;
33
+ const BIT19 = 1 << 18;
34
+ const BIT20 = 1 << 19;
35
+ const BIT21 = 1 << 20;
36
+ const BIT22 = 1 << 21;
37
+ const BIT23 = 1 << 22;
38
+ const BIT24 = 1 << 23;
39
+ const BIT25 = 1 << 24;
40
+ const BIT26 = 1 << 25;
41
+ const BIT27 = 1 << 26;
42
+ const BIT28 = 1 << 27;
43
+ const BIT29 = 1 << 28;
44
+ const BIT30 = 1 << 29;
45
+ const BIT31 = 1 << 30;
46
+ const BIT32 = 1 << 31;
47
+ const BITS6 = 63;
48
+ const BITS7 = 127;
49
+ const BITS17 = BIT18 - 1;
50
+ const BITS18 = BIT19 - 1;
51
+ const BITS19 = BIT20 - 1;
52
+ const BITS20 = BIT21 - 1;
53
+ const BITS21 = BIT22 - 1;
54
+ const BITS22 = BIT23 - 1;
55
+ const BITS23 = BIT24 - 1;
56
+ const BITS24 = BIT25 - 1;
57
+ const BITS25 = BIT26 - 1;
58
+ const BITS26 = BIT27 - 1;
59
+ const BITS27 = BIT28 - 1;
60
+ const BITS28 = BIT29 - 1;
61
+ const BITS29 = BIT30 - 1;
62
+ const BITS30 = BIT31 - 1;
63
+ /**
64
+ * @type {number}
65
+ */
66
+ const BITS31 = 2147483647;
67
+ /**
68
+ * @type {number}
69
+ */
70
+ const BITS32 = 4294967295;
71
+
72
+ //#endregion
73
+ //#region node_modules/lib0/number.js
74
+ /**
75
+ * Utility helpers for working with numbers.
76
+ *
77
+ * @module number
78
+ */
79
+ const MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER;
80
+ const MIN_SAFE_INTEGER = Number.MIN_SAFE_INTEGER;
81
+ const LOWEST_INT32 = 1 << 31;
82
+ const HIGHEST_INT32 = BITS31;
83
+ const HIGHEST_UINT32 = BITS32;
84
+ /* c8 ignore next */
85
+ const isInteger = Number.isInteger || ((num) => typeof num === "number" && isFinite(num) && floor(num) === num);
86
+ const isNaN = Number.isNaN;
87
+ const parseInt = Number.parseInt;
88
+
89
+ //#endregion
90
+ //#region node_modules/lib0/set.js
91
+ /**
92
+ * Utility module to work with sets.
93
+ *
94
+ * @module set
95
+ */
96
+ const create$2 = () => /* @__PURE__ */ new Set();
97
+
98
+ //#endregion
99
+ //#region node_modules/lib0/array.js
100
+ /**
101
+ * Transforms something array-like to an actual Array.
102
+ *
103
+ * @function
104
+ * @template T
105
+ * @param {ArrayLike<T>|Iterable<T>} arraylike
106
+ * @return {T}
107
+ */
108
+ const from = Array.from;
109
+ const isArray$1 = Array.isArray;
110
+
111
+ //#endregion
112
+ //#region node_modules/lib0/string.js
113
+ /**
114
+ * Utility module to work with strings.
115
+ *
116
+ * @module string
117
+ */
118
+ const fromCharCode = String.fromCharCode;
119
+ const fromCodePoint = String.fromCodePoint;
120
+ /**
121
+ * The largest utf16 character.
122
+ * Corresponds to Uint8Array([255, 255]) or charcodeof(2x2^8)
123
+ */
124
+ const MAX_UTF16_CHARACTER = fromCharCode(65535);
125
+ /**
126
+ * @param {string} str
127
+ * @return {Uint8Array<ArrayBuffer>}
128
+ */
129
+ const _encodeUtf8Polyfill = (str) => {
130
+ const encodedString = unescape(encodeURIComponent(str));
131
+ const len = encodedString.length;
132
+ const buf = new Uint8Array(len);
133
+ for (let i = 0; i < len; i++) buf[i] = encodedString.codePointAt(i);
134
+ return buf;
135
+ };
136
+ /* c8 ignore next */
137
+ const utf8TextEncoder = typeof TextEncoder !== "undefined" ? new TextEncoder() : null;
138
+ /**
139
+ * @param {string} str
140
+ * @return {Uint8Array<ArrayBuffer>}
141
+ */
142
+ const _encodeUtf8Native = (str) => utf8TextEncoder.encode(str);
143
+ /**
144
+ * @param {string} str
145
+ * @return {Uint8Array}
146
+ */
147
+ /* c8 ignore next */
148
+ const encodeUtf8 = utf8TextEncoder ? _encodeUtf8Native : _encodeUtf8Polyfill;
149
+ /* c8 ignore next */
150
+ let utf8TextDecoder = typeof TextDecoder === "undefined" ? null : new TextDecoder("utf-8", {
151
+ fatal: true,
152
+ ignoreBOM: true
153
+ });
154
+ /* c8 ignore start */
155
+ if (utf8TextDecoder && utf8TextDecoder.decode(new Uint8Array()).length === 1)
156
+ /* c8 ignore next */
157
+ utf8TextDecoder = null;
158
+
159
+ //#endregion
160
+ //#region node_modules/lib0/encoding.js
161
+ /**
162
+ * Efficient schema-less binary encoding with support for variable length encoding.
163
+ *
164
+ * Use [lib0/encoding] with [lib0/decoding]. Every encoding function has a corresponding decoding function.
165
+ *
166
+ * Encodes numbers in little-endian order (least to most significant byte order)
167
+ * and is compatible with Golang's binary encoding (https://golang.org/pkg/encoding/binary/)
168
+ * which is also used in Protocol Buffers.
169
+ *
170
+ * ```js
171
+ * // encoding step
172
+ * const encoder = encoding.createEncoder()
173
+ * encoding.writeVarUint(encoder, 256)
174
+ * encoding.writeVarString(encoder, 'Hello world!')
175
+ * const buf = encoding.toUint8Array(encoder)
176
+ * ```
177
+ *
178
+ * ```js
179
+ * // decoding step
180
+ * const decoder = decoding.createDecoder(buf)
181
+ * decoding.readVarUint(decoder) // => 256
182
+ * decoding.readVarString(decoder) // => 'Hello world!'
183
+ * decoding.hasContent(decoder) // => false - all data is read
184
+ * ```
185
+ *
186
+ * @module encoding
187
+ */
188
+ /**
189
+ * A BinaryEncoder handles the encoding to an Uint8Array.
190
+ */
191
+ var Encoder = class {
192
+ constructor() {
193
+ this.cpos = 0;
194
+ this.cbuf = new Uint8Array(100);
195
+ /**
196
+ * @type {Array<Uint8Array>}
197
+ */
198
+ this.bufs = [];
199
+ }
200
+ };
201
+ /**
202
+ * @function
203
+ * @return {Encoder}
204
+ */
205
+ const createEncoder = () => new Encoder();
206
+ /**
207
+ * The current length of the encoded data.
208
+ *
209
+ * @function
210
+ * @param {Encoder} encoder
211
+ * @return {number}
212
+ */
213
+ const length = (encoder) => {
214
+ let len = encoder.cpos;
215
+ for (let i = 0; i < encoder.bufs.length; i++) len += encoder.bufs[i].length;
216
+ return len;
217
+ };
218
+ /**
219
+ * Transform to Uint8Array.
220
+ *
221
+ * @function
222
+ * @param {Encoder} encoder
223
+ * @return {Uint8Array<ArrayBuffer>} The created ArrayBuffer.
224
+ */
225
+ const toUint8Array = (encoder) => {
226
+ const uint8arr = new Uint8Array(length(encoder));
227
+ let curPos = 0;
228
+ for (let i = 0; i < encoder.bufs.length; i++) {
229
+ const d = encoder.bufs[i];
230
+ uint8arr.set(d, curPos);
231
+ curPos += d.length;
232
+ }
233
+ uint8arr.set(new Uint8Array(encoder.cbuf.buffer, 0, encoder.cpos), curPos);
234
+ return uint8arr;
235
+ };
236
+ /**
237
+ * Write one byte to the encoder.
238
+ *
239
+ * @function
240
+ * @param {Encoder} encoder
241
+ * @param {number} num The byte that is to be encoded.
242
+ */
243
+ const write = (encoder, num) => {
244
+ const bufferLen = encoder.cbuf.length;
245
+ if (encoder.cpos === bufferLen) {
246
+ encoder.bufs.push(encoder.cbuf);
247
+ encoder.cbuf = new Uint8Array(bufferLen * 2);
248
+ encoder.cpos = 0;
249
+ }
250
+ encoder.cbuf[encoder.cpos++] = num;
251
+ };
252
+ /**
253
+ * Write a variable length unsigned integer. Max encodable integer is 2^53.
254
+ *
255
+ * @function
256
+ * @param {Encoder} encoder
257
+ * @param {number} num The number that is to be encoded.
258
+ */
259
+ const writeVarUint = (encoder, num) => {
260
+ while (num > BITS7) {
261
+ write(encoder, BIT8 | BITS7 & num);
262
+ num = floor(num / 128);
263
+ }
264
+ write(encoder, BITS7 & num);
265
+ };
266
+ /**
267
+ * A cache to store strings temporarily
268
+ */
269
+ const _strBuffer = new Uint8Array(3e4);
270
+ const _maxStrBSize = _strBuffer.length / 3;
271
+ /**
272
+ * Write a variable length string.
273
+ *
274
+ * @function
275
+ * @param {Encoder} encoder
276
+ * @param {String} str The string that is to be encoded.
277
+ */
278
+ const _writeVarStringNative = (encoder, str) => {
279
+ if (str.length < _maxStrBSize) {
280
+ /* c8 ignore next */
281
+ const written = utf8TextEncoder.encodeInto(str, _strBuffer).written || 0;
282
+ writeVarUint(encoder, written);
283
+ for (let i = 0; i < written; i++) write(encoder, _strBuffer[i]);
284
+ } else writeVarUint8Array(encoder, encodeUtf8(str));
285
+ };
286
+ /**
287
+ * Write a variable length string.
288
+ *
289
+ * @function
290
+ * @param {Encoder} encoder
291
+ * @param {String} str The string that is to be encoded.
292
+ */
293
+ const _writeVarStringPolyfill = (encoder, str) => {
294
+ const encodedString = unescape(encodeURIComponent(str));
295
+ const len = encodedString.length;
296
+ writeVarUint(encoder, len);
297
+ for (let i = 0; i < len; i++) write(encoder, encodedString.codePointAt(i));
298
+ };
299
+ /**
300
+ * Write a variable length string.
301
+ *
302
+ * @function
303
+ * @param {Encoder} encoder
304
+ * @param {String} str The string that is to be encoded.
305
+ */
306
+ /* c8 ignore next */
307
+ const writeVarString = utf8TextEncoder && utf8TextEncoder.encodeInto ? _writeVarStringNative : _writeVarStringPolyfill;
308
+ /**
309
+ * Append fixed-length Uint8Array to the encoder.
310
+ *
311
+ * @function
312
+ * @param {Encoder} encoder
313
+ * @param {Uint8Array} uint8Array
314
+ */
315
+ const writeUint8Array = (encoder, uint8Array) => {
316
+ const bufferLen = encoder.cbuf.length;
317
+ const cpos = encoder.cpos;
318
+ const leftCopyLen = min(bufferLen - cpos, uint8Array.length);
319
+ const rightCopyLen = uint8Array.length - leftCopyLen;
320
+ encoder.cbuf.set(uint8Array.subarray(0, leftCopyLen), cpos);
321
+ encoder.cpos += leftCopyLen;
322
+ if (rightCopyLen > 0) {
323
+ encoder.bufs.push(encoder.cbuf);
324
+ encoder.cbuf = new Uint8Array(max(bufferLen * 2, rightCopyLen));
325
+ encoder.cbuf.set(uint8Array.subarray(leftCopyLen));
326
+ encoder.cpos = rightCopyLen;
327
+ }
328
+ };
329
+ /**
330
+ * Append an Uint8Array to Encoder.
331
+ *
332
+ * @function
333
+ * @param {Encoder} encoder
334
+ * @param {Uint8Array} uint8Array
335
+ */
336
+ const writeVarUint8Array = (encoder, uint8Array) => {
337
+ writeVarUint(encoder, uint8Array.byteLength);
338
+ writeUint8Array(encoder, uint8Array);
339
+ };
340
+
341
+ //#endregion
342
+ //#region node_modules/lib0/error.js
343
+ /**
344
+ * Error helpers.
345
+ *
346
+ * @module error
347
+ */
348
+ /**
349
+ * @param {string} s
350
+ * @return {Error}
351
+ */
352
+ /* c8 ignore next */
353
+ const create$1 = (s) => new Error(s);
354
+
355
+ //#endregion
356
+ //#region node_modules/lib0/decoding.js
357
+ /**
358
+ * Efficient schema-less binary decoding with support for variable length encoding.
359
+ *
360
+ * Use [lib0/decoding] with [lib0/encoding]. Every encoding function has a corresponding decoding function.
361
+ *
362
+ * Encodes numbers in little-endian order (least to most significant byte order)
363
+ * and is compatible with Golang's binary encoding (https://golang.org/pkg/encoding/binary/)
364
+ * which is also used in Protocol Buffers.
365
+ *
366
+ * ```js
367
+ * // encoding step
368
+ * const encoder = encoding.createEncoder()
369
+ * encoding.writeVarUint(encoder, 256)
370
+ * encoding.writeVarString(encoder, 'Hello world!')
371
+ * const buf = encoding.toUint8Array(encoder)
372
+ * ```
373
+ *
374
+ * ```js
375
+ * // decoding step
376
+ * const decoder = decoding.createDecoder(buf)
377
+ * decoding.readVarUint(decoder) // => 256
378
+ * decoding.readVarString(decoder) // => 'Hello world!'
379
+ * decoding.hasContent(decoder) // => false - all data is read
380
+ * ```
381
+ *
382
+ * @module decoding
383
+ */
384
+ const errorUnexpectedEndOfArray = create$1("Unexpected end of array");
385
+ const errorIntegerOutOfRange = create$1("Integer out of Range");
386
+ /**
387
+ * A Decoder handles the decoding of an Uint8Array.
388
+ * @template {ArrayBufferLike} [Buf=ArrayBufferLike]
389
+ */
390
+ var Decoder = class {
391
+ /**
392
+ * @param {Uint8Array<Buf>} uint8Array Binary data to decode
393
+ */
394
+ constructor(uint8Array) {
395
+ /**
396
+ * Decoding target.
397
+ *
398
+ * @type {Uint8Array<Buf>}
399
+ */
400
+ this.arr = uint8Array;
401
+ /**
402
+ * Current decoding position.
403
+ *
404
+ * @type {number}
405
+ */
406
+ this.pos = 0;
407
+ }
408
+ };
409
+ /**
410
+ * @function
411
+ * @template {ArrayBufferLike} Buf
412
+ * @param {Uint8Array<Buf>} uint8Array
413
+ * @return {Decoder<Buf>}
414
+ */
415
+ const createDecoder = (uint8Array) => new Decoder(uint8Array);
416
+ /**
417
+ * Create an Uint8Array view of the next `len` bytes and advance the position by `len`.
418
+ *
419
+ * Important: The Uint8Array still points to the underlying ArrayBuffer. Make sure to discard the result as soon as possible to prevent any memory leaks.
420
+ * Use `buffer.copyUint8Array` to copy the result into a new Uint8Array.
421
+ *
422
+ * @function
423
+ * @template {ArrayBufferLike} Buf
424
+ * @param {Decoder<Buf>} decoder The decoder instance
425
+ * @param {number} len The length of bytes to read
426
+ * @return {Uint8Array<Buf>}
427
+ */
428
+ const readUint8Array = (decoder, len) => {
429
+ const view = new Uint8Array(decoder.arr.buffer, decoder.pos + decoder.arr.byteOffset, len);
430
+ decoder.pos += len;
431
+ return view;
432
+ };
433
+ /**
434
+ * Read variable length Uint8Array.
435
+ *
436
+ * Important: The Uint8Array still points to the underlying ArrayBuffer. Make sure to discard the result as soon as possible to prevent any memory leaks.
437
+ * Use `buffer.copyUint8Array` to copy the result into a new Uint8Array.
438
+ *
439
+ * @function
440
+ * @template {ArrayBufferLike} Buf
441
+ * @param {Decoder<Buf>} decoder
442
+ * @return {Uint8Array<Buf>}
443
+ */
444
+ const readVarUint8Array = (decoder) => readUint8Array(decoder, readVarUint(decoder));
445
+ /**
446
+ * Read one byte as unsigned integer.
447
+ * @function
448
+ * @param {Decoder} decoder The decoder instance
449
+ * @return {number} Unsigned 8-bit integer
450
+ */
451
+ const readUint8 = (decoder) => decoder.arr[decoder.pos++];
452
+ /**
453
+ * Read unsigned integer (32bit) with variable length.
454
+ * 1/8th of the storage is used as encoding overhead.
455
+ * * numbers < 2^7 is stored in one bytlength
456
+ * * numbers < 2^14 is stored in two bylength
457
+ *
458
+ * @function
459
+ * @param {Decoder} decoder
460
+ * @return {number} An unsigned integer.length
461
+ */
462
+ const readVarUint = (decoder) => {
463
+ let num = 0;
464
+ let mult = 1;
465
+ const len = decoder.arr.length;
466
+ while (decoder.pos < len) {
467
+ const r = decoder.arr[decoder.pos++];
468
+ num = num + (r & BITS7) * mult;
469
+ mult *= 128;
470
+ if (r < BIT8) return num;
471
+ /* c8 ignore start */
472
+ if (num > MAX_SAFE_INTEGER) throw errorIntegerOutOfRange;
473
+ }
474
+ throw errorUnexpectedEndOfArray;
475
+ };
476
+ /**
477
+ * Read signed integer (32bit) with variable length.
478
+ * 1/8th of the storage is used as encoding overhead.
479
+ * * numbers < 2^7 is stored in one bytlength
480
+ * * numbers < 2^14 is stored in two bylength
481
+ * @todo This should probably create the inverse ~num if number is negative - but this would be a breaking change.
482
+ *
483
+ * @function
484
+ * @param {Decoder} decoder
485
+ * @return {number} An unsigned integer.length
486
+ */
487
+ const readVarInt = (decoder) => {
488
+ let r = decoder.arr[decoder.pos++];
489
+ let num = r & BITS6;
490
+ let mult = 64;
491
+ const sign = (r & BIT7) > 0 ? -1 : 1;
492
+ if ((r & BIT8) === 0) return sign * num;
493
+ const len = decoder.arr.length;
494
+ while (decoder.pos < len) {
495
+ r = decoder.arr[decoder.pos++];
496
+ num = num + (r & BITS7) * mult;
497
+ mult *= 128;
498
+ if (r < BIT8) return sign * num;
499
+ /* c8 ignore start */
500
+ if (num > MAX_SAFE_INTEGER) throw errorIntegerOutOfRange;
501
+ }
502
+ throw errorUnexpectedEndOfArray;
503
+ };
504
+ /**
505
+ * We don't test this function anymore as we use native decoding/encoding by default now.
506
+ * Better not modify this anymore..
507
+ *
508
+ * Transforming utf8 to a string is pretty expensive. The code performs 10x better
509
+ * when String.fromCodePoint is fed with all characters as arguments.
510
+ * But most environments have a maximum number of arguments per functions.
511
+ * For effiency reasons we apply a maximum of 10000 characters at once.
512
+ *
513
+ * @function
514
+ * @param {Decoder} decoder
515
+ * @return {String} The read String.
516
+ */
517
+ /* c8 ignore start */
518
+ const _readVarStringPolyfill = (decoder) => {
519
+ let remainingLen = readVarUint(decoder);
520
+ if (remainingLen === 0) return "";
521
+ else {
522
+ let encodedString = String.fromCodePoint(readUint8(decoder));
523
+ if (--remainingLen < 100) while (remainingLen--) encodedString += String.fromCodePoint(readUint8(decoder));
524
+ else while (remainingLen > 0) {
525
+ const nextLen = remainingLen < 1e4 ? remainingLen : 1e4;
526
+ const bytes = decoder.arr.subarray(decoder.pos, decoder.pos + nextLen);
527
+ decoder.pos += nextLen;
528
+ encodedString += String.fromCodePoint.apply(null, bytes);
529
+ remainingLen -= nextLen;
530
+ }
531
+ return decodeURIComponent(escape(encodedString));
532
+ }
533
+ };
534
+ /* c8 ignore stop */
535
+ /**
536
+ * @function
537
+ * @param {Decoder} decoder
538
+ * @return {String} The read String
539
+ */
540
+ const _readVarStringNative = (decoder) => utf8TextDecoder.decode(readVarUint8Array(decoder));
541
+ /**
542
+ * Read string of variable length
543
+ * * varUint is used to store the length of the string
544
+ *
545
+ * @function
546
+ * @param {Decoder} decoder
547
+ * @return {String} The read String
548
+ *
549
+ */
550
+ /* c8 ignore next */
551
+ const readVarString = utf8TextDecoder ? _readVarStringNative : _readVarStringPolyfill;
552
+ /**
553
+ * Look ahead and read varString without incrementing position
554
+ *
555
+ * @function
556
+ * @param {Decoder} decoder
557
+ * @return {string}
558
+ */
559
+ const peekVarString = (decoder) => {
560
+ const pos = decoder.pos;
561
+ const s = readVarString(decoder);
562
+ decoder.pos = pos;
563
+ return s;
564
+ };
565
+
566
+ //#endregion
567
+ //#region packages/common/src/auth.ts
568
+ let AuthMessageType = /* @__PURE__ */ function(AuthMessageType) {
569
+ AuthMessageType[AuthMessageType["Token"] = 0] = "Token";
570
+ AuthMessageType[AuthMessageType["PermissionDenied"] = 1] = "PermissionDenied";
571
+ AuthMessageType[AuthMessageType["Authenticated"] = 2] = "Authenticated";
572
+ return AuthMessageType;
573
+ }({});
574
+ const writeAuthentication = (encoder, auth) => {
575
+ writeVarUint(encoder, AuthMessageType.Token);
576
+ writeVarString(encoder, auth);
577
+ };
578
+ const readAuthMessage = (decoder, sendToken, permissionDeniedHandler, authenticatedHandler) => {
579
+ switch (readVarUint(decoder)) {
580
+ case AuthMessageType.Token:
581
+ sendToken();
582
+ break;
583
+ case AuthMessageType.PermissionDenied:
584
+ permissionDeniedHandler(readVarString(decoder));
585
+ break;
586
+ case AuthMessageType.Authenticated:
587
+ authenticatedHandler(readVarString(decoder));
588
+ break;
589
+ default:
590
+ }
591
+ };
592
+
593
+ //#endregion
594
+ //#region packages/common/src/awarenessStatesToArray.ts
595
+ const awarenessStatesToArray = (states) => {
596
+ return Array.from(states.entries()).map(([key, value]) => {
597
+ return {
598
+ clientId: key,
599
+ ...value
600
+ };
601
+ });
602
+ };
603
+
604
+ //#endregion
605
+ //#region packages/common/src/types.ts
606
+ /**
607
+ * State of the WebSocket connection.
608
+ * https://developer.mozilla.org/de/docs/Web/API/WebSocket/readyState
609
+ */
610
+ let WsReadyStates = /* @__PURE__ */ function(WsReadyStates) {
611
+ WsReadyStates[WsReadyStates["Connecting"] = 0] = "Connecting";
612
+ WsReadyStates[WsReadyStates["Open"] = 1] = "Open";
613
+ WsReadyStates[WsReadyStates["Closing"] = 2] = "Closing";
614
+ WsReadyStates[WsReadyStates["Closed"] = 3] = "Closed";
615
+ return WsReadyStates;
616
+ }({});
617
+
618
+ //#endregion
619
+ //#region node_modules/lib0/time.js
620
+ /**
621
+ * Return current unix time.
622
+ *
623
+ * @return {number}
624
+ */
625
+ const getUnixTime = Date.now;
626
+
627
+ //#endregion
628
+ //#region node_modules/lib0/map.js
629
+ /**
630
+ * Utility module to work with key-value stores.
631
+ *
632
+ * @module map
633
+ */
634
+ /**
635
+ * @template K
636
+ * @template V
637
+ * @typedef {Map<K,V>} GlobalMap
638
+ */
639
+ /**
640
+ * Creates a new Map instance.
641
+ *
642
+ * @function
643
+ * @return {Map<any, any>}
644
+ *
645
+ * @function
646
+ */
647
+ const create = () => /* @__PURE__ */ new Map();
648
+ /**
649
+ * Get map property. Create T if property is undefined and set T on map.
650
+ *
651
+ * ```js
652
+ * const listeners = map.setIfUndefined(events, 'eventName', set.create)
653
+ * listeners.add(listener)
654
+ * ```
655
+ *
656
+ * @function
657
+ * @template {Map<any, any>} MAP
658
+ * @template {MAP extends Map<any,infer V> ? function():V : unknown} CF
659
+ * @param {MAP} map
660
+ * @param {MAP extends Map<infer K,any> ? K : unknown} key
661
+ * @param {CF} createT
662
+ * @return {ReturnType<CF>}
663
+ */
664
+ const setIfUndefined = (map, key, createT) => {
665
+ let set = map.get(key);
666
+ if (set === void 0) map.set(key, set = createT());
667
+ return set;
668
+ };
669
+
670
+ //#endregion
671
+ //#region node_modules/lib0/observable.js
672
+ /**
673
+ * Observable class prototype.
674
+ *
675
+ * @module observable
676
+ */
677
+ /* c8 ignore start */
678
+ /**
679
+ * Handles named events.
680
+ *
681
+ * @deprecated
682
+ * @template N
683
+ */
684
+ var Observable = class {
685
+ constructor() {
686
+ /**
687
+ * Some desc.
688
+ * @type {Map<N, any>}
689
+ */
690
+ this._observers = create();
691
+ }
692
+ /**
693
+ * @param {N} name
694
+ * @param {function} f
695
+ */
696
+ on(name, f) {
697
+ setIfUndefined(this._observers, name, create$2).add(f);
698
+ }
699
+ /**
700
+ * @param {N} name
701
+ * @param {function} f
702
+ */
703
+ once(name, f) {
704
+ /**
705
+ * @param {...any} args
706
+ */
707
+ const _f = (...args) => {
708
+ this.off(name, _f);
709
+ f(...args);
710
+ };
711
+ this.on(name, _f);
712
+ }
713
+ /**
714
+ * @param {N} name
715
+ * @param {function} f
716
+ */
717
+ off(name, f) {
718
+ const observers = this._observers.get(name);
719
+ if (observers !== void 0) {
720
+ observers.delete(f);
721
+ if (observers.size === 0) this._observers.delete(name);
722
+ }
723
+ }
724
+ /**
725
+ * Emit a named event. All registered event listeners that listen to the
726
+ * specified name will receive the event.
727
+ *
728
+ * @todo This should catch exceptions
729
+ *
730
+ * @param {N} name The event name.
731
+ * @param {Array<any>} args The arguments that are applied to the event listener.
732
+ */
733
+ emit(name, args) {
734
+ return from((this._observers.get(name) || create()).values()).forEach((f) => f(...args));
735
+ }
736
+ destroy() {
737
+ this._observers = create();
738
+ }
739
+ };
740
+ /* c8 ignore end */
741
+
742
+ //#endregion
743
+ //#region node_modules/lib0/trait/equality.js
744
+ const EqualityTraitSymbol = Symbol("Equality");
745
+
746
+ //#endregion
747
+ //#region node_modules/lib0/object.js
748
+ /**
749
+ * @param {Object<string,any>} obj
750
+ */
751
+ const keys = Object.keys;
752
+ /**
753
+ * @param {Object<string,any>} obj
754
+ * @return {number}
755
+ */
756
+ const size = (obj) => keys(obj).length;
757
+ /**
758
+ * Calls `Object.prototype.hasOwnProperty`.
759
+ *
760
+ * @param {any} obj
761
+ * @param {string|number|symbol} key
762
+ * @return {boolean}
763
+ */
764
+ const hasProperty = (obj, key) => Object.prototype.hasOwnProperty.call(obj, key);
765
+
766
+ //#endregion
767
+ //#region node_modules/lib0/function.js
768
+ /**
769
+ * Common functions and function call helpers.
770
+ *
771
+ * @module function
772
+ */
773
+ /* c8 ignore start */
774
+ /**
775
+ * @param {any} a
776
+ * @param {any} b
777
+ * @return {boolean}
778
+ */
779
+ const equalityDeep = (a, b) => {
780
+ if (a === b) return true;
781
+ if (a == null || b == null || a.constructor !== b.constructor && (a.constructor || Object) !== (b.constructor || Object)) return false;
782
+ if (a[EqualityTraitSymbol] != null) return a[EqualityTraitSymbol](b);
783
+ switch (a.constructor) {
784
+ case ArrayBuffer:
785
+ a = new Uint8Array(a);
786
+ b = new Uint8Array(b);
787
+ case Uint8Array:
788
+ if (a.byteLength !== b.byteLength) return false;
789
+ for (let i = 0; i < a.length; i++) if (a[i] !== b[i]) return false;
790
+ break;
791
+ case Set:
792
+ if (a.size !== b.size) return false;
793
+ for (const value of a) if (!b.has(value)) return false;
794
+ break;
795
+ case Map:
796
+ if (a.size !== b.size) return false;
797
+ for (const key of a.keys()) if (!b.has(key) || !equalityDeep(a.get(key), b.get(key))) return false;
798
+ break;
799
+ case void 0:
800
+ case Object:
801
+ if (size(a) !== size(b)) return false;
802
+ for (const key in a) if (!hasProperty(a, key) || !equalityDeep(a[key], b[key])) return false;
803
+ break;
804
+ case Array:
805
+ if (a.length !== b.length) return false;
806
+ for (let i = 0; i < a.length; i++) if (!equalityDeep(a[i], b[i])) return false;
807
+ break;
808
+ default: return false;
809
+ }
810
+ return true;
811
+ };
812
+ /* c8 ignore stop */
813
+ const isArray = isArray$1;
814
+
815
+ //#endregion
816
+ //#region node_modules/y-protocols/awareness.js
817
+ /**
818
+ * @module awareness-protocol
819
+ */
820
+ const outdatedTimeout = 3e4;
821
+ /**
822
+ * @typedef {Object} MetaClientState
823
+ * @property {number} MetaClientState.clock
824
+ * @property {number} MetaClientState.lastUpdated unix timestamp
825
+ */
826
+ /**
827
+ * The Awareness class implements a simple shared state protocol that can be used for non-persistent data like awareness information
828
+ * (cursor, username, status, ..). Each client can update its own local state and listen to state changes of
829
+ * remote clients. Every client may set a state of a remote peer to `null` to mark the client as offline.
830
+ *
831
+ * Each client is identified by a unique client id (something we borrow from `doc.clientID`). A client can override
832
+ * its own state by propagating a message with an increasing timestamp (`clock`). If such a message is received, it is
833
+ * applied if the known state of that client is older than the new state (`clock < newClock`). If a client thinks that
834
+ * a remote client is offline, it may propagate a message with
835
+ * `{ clock: currentClientClock, state: null, client: remoteClient }`. If such a
836
+ * message is received, and the known clock of that client equals the received clock, it will override the state with `null`.
837
+ *
838
+ * Before a client disconnects, it should propagate a `null` state with an updated clock.
839
+ *
840
+ * Awareness states must be updated every 30 seconds. Otherwise the Awareness instance will delete the client state.
841
+ *
842
+ * @extends {Observable<string>}
843
+ */
844
+ var Awareness = class extends Observable {
845
+ /**
846
+ * @param {Y.Doc} doc
847
+ */
848
+ constructor(doc) {
849
+ super();
850
+ this.doc = doc;
851
+ /**
852
+ * @type {number}
853
+ */
854
+ this.clientID = doc.clientID;
855
+ /**
856
+ * Maps from client id to client state
857
+ * @type {Map<number, Object<string, any>>}
858
+ */
859
+ this.states = /* @__PURE__ */ new Map();
860
+ /**
861
+ * @type {Map<number, MetaClientState>}
862
+ */
863
+ this.meta = /* @__PURE__ */ new Map();
864
+ this._checkInterval = setInterval(() => {
865
+ const now = getUnixTime();
866
+ if (this.getLocalState() !== null && outdatedTimeout / 2 <= now - this.meta.get(this.clientID).lastUpdated) this.setLocalState(this.getLocalState());
867
+ /**
868
+ * @type {Array<number>}
869
+ */
870
+ const remove = [];
871
+ this.meta.forEach((meta, clientid) => {
872
+ if (clientid !== this.clientID && outdatedTimeout <= now - meta.lastUpdated && this.states.has(clientid)) remove.push(clientid);
873
+ });
874
+ if (remove.length > 0) removeAwarenessStates(this, remove, "timeout");
875
+ }, floor(outdatedTimeout / 10));
876
+ doc.on("destroy", () => {
877
+ this.destroy();
878
+ });
879
+ this.setLocalState({});
880
+ }
881
+ destroy() {
882
+ this.emit("destroy", [this]);
883
+ this.setLocalState(null);
884
+ super.destroy();
885
+ clearInterval(this._checkInterval);
886
+ }
887
+ /**
888
+ * @return {Object<string,any>|null}
889
+ */
890
+ getLocalState() {
891
+ return this.states.get(this.clientID) || null;
892
+ }
893
+ /**
894
+ * @param {Object<string,any>|null} state
895
+ */
896
+ setLocalState(state) {
897
+ const clientID = this.clientID;
898
+ const currLocalMeta = this.meta.get(clientID);
899
+ const clock = currLocalMeta === void 0 ? 0 : currLocalMeta.clock + 1;
900
+ const prevState = this.states.get(clientID);
901
+ if (state === null) this.states.delete(clientID);
902
+ else this.states.set(clientID, state);
903
+ this.meta.set(clientID, {
904
+ clock,
905
+ lastUpdated: getUnixTime()
906
+ });
907
+ const added = [];
908
+ const updated = [];
909
+ const filteredUpdated = [];
910
+ const removed = [];
911
+ if (state === null) removed.push(clientID);
912
+ else if (prevState == null) {
913
+ if (state != null) added.push(clientID);
914
+ } else {
915
+ updated.push(clientID);
916
+ if (!equalityDeep(prevState, state)) filteredUpdated.push(clientID);
917
+ }
918
+ if (added.length > 0 || filteredUpdated.length > 0 || removed.length > 0) this.emit("change", [{
919
+ added,
920
+ updated: filteredUpdated,
921
+ removed
922
+ }, "local"]);
923
+ this.emit("update", [{
924
+ added,
925
+ updated,
926
+ removed
927
+ }, "local"]);
928
+ }
929
+ /**
930
+ * @param {string} field
931
+ * @param {any} value
932
+ */
933
+ setLocalStateField(field, value) {
934
+ const state = this.getLocalState();
935
+ if (state !== null) this.setLocalState({
936
+ ...state,
937
+ [field]: value
938
+ });
939
+ }
940
+ /**
941
+ * @return {Map<number,Object<string,any>>}
942
+ */
943
+ getStates() {
944
+ return this.states;
945
+ }
946
+ };
947
+ /**
948
+ * Mark (remote) clients as inactive and remove them from the list of active peers.
949
+ * This change will be propagated to remote clients.
950
+ *
951
+ * @param {Awareness} awareness
952
+ * @param {Array<number>} clients
953
+ * @param {any} origin
954
+ */
955
+ const removeAwarenessStates = (awareness, clients, origin) => {
956
+ const removed = [];
957
+ for (let i = 0; i < clients.length; i++) {
958
+ const clientID = clients[i];
959
+ if (awareness.states.has(clientID)) {
960
+ awareness.states.delete(clientID);
961
+ if (clientID === awareness.clientID) {
962
+ const curMeta = awareness.meta.get(clientID);
963
+ awareness.meta.set(clientID, {
964
+ clock: curMeta.clock + 1,
965
+ lastUpdated: getUnixTime()
966
+ });
967
+ }
968
+ removed.push(clientID);
969
+ }
970
+ }
971
+ if (removed.length > 0) {
972
+ awareness.emit("change", [{
973
+ added: [],
974
+ updated: [],
975
+ removed
976
+ }, origin]);
977
+ awareness.emit("update", [{
978
+ added: [],
979
+ updated: [],
980
+ removed
981
+ }, origin]);
982
+ }
983
+ };
984
+ /**
985
+ * @param {Awareness} awareness
986
+ * @param {Array<number>} clients
987
+ * @return {Uint8Array}
988
+ */
989
+ const encodeAwarenessUpdate = (awareness, clients, states = awareness.states) => {
990
+ const len = clients.length;
991
+ const encoder = createEncoder();
992
+ writeVarUint(encoder, len);
993
+ for (let i = 0; i < len; i++) {
994
+ const clientID = clients[i];
995
+ const state = states.get(clientID) || null;
996
+ const clock = awareness.meta.get(clientID).clock;
997
+ writeVarUint(encoder, clientID);
998
+ writeVarUint(encoder, clock);
999
+ writeVarString(encoder, JSON.stringify(state));
1000
+ }
1001
+ return toUint8Array(encoder);
1002
+ };
1003
+ /**
1004
+ * @param {Awareness} awareness
1005
+ * @param {Uint8Array} update
1006
+ * @param {any} origin This will be added to the emitted change event
1007
+ */
1008
+ const applyAwarenessUpdate = (awareness, update, origin) => {
1009
+ const decoder = createDecoder(update);
1010
+ const timestamp = getUnixTime();
1011
+ const added = [];
1012
+ const updated = [];
1013
+ const filteredUpdated = [];
1014
+ const removed = [];
1015
+ const len = readVarUint(decoder);
1016
+ for (let i = 0; i < len; i++) {
1017
+ const clientID = readVarUint(decoder);
1018
+ let clock = readVarUint(decoder);
1019
+ const state = JSON.parse(readVarString(decoder));
1020
+ const clientMeta = awareness.meta.get(clientID);
1021
+ const prevState = awareness.states.get(clientID);
1022
+ const currClock = clientMeta === void 0 ? 0 : clientMeta.clock;
1023
+ if (currClock < clock || currClock === clock && state === null && awareness.states.has(clientID)) {
1024
+ if (state === null) if (clientID === awareness.clientID && awareness.getLocalState() != null) clock++;
1025
+ else awareness.states.delete(clientID);
1026
+ else awareness.states.set(clientID, state);
1027
+ awareness.meta.set(clientID, {
1028
+ clock,
1029
+ lastUpdated: timestamp
1030
+ });
1031
+ if (clientMeta === void 0 && state !== null) added.push(clientID);
1032
+ else if (clientMeta !== void 0 && state === null) removed.push(clientID);
1033
+ else if (state !== null) {
1034
+ if (!equalityDeep(state, prevState)) filteredUpdated.push(clientID);
1035
+ updated.push(clientID);
1036
+ }
1037
+ }
1038
+ }
1039
+ if (added.length > 0 || filteredUpdated.length > 0 || removed.length > 0) awareness.emit("change", [{
1040
+ added,
1041
+ updated: filteredUpdated,
1042
+ removed
1043
+ }, origin]);
1044
+ if (added.length > 0 || updated.length > 0 || removed.length > 0) awareness.emit("update", [{
1045
+ added,
1046
+ updated,
1047
+ removed
1048
+ }, origin]);
1049
+ };
1050
+
1051
+ //#endregion
1052
+ //#region packages/provider/src/EventEmitter.ts
1053
+ var EventEmitter = class {
1054
+ constructor() {
1055
+ this.callbacks = {};
1056
+ }
1057
+ on(event, fn) {
1058
+ if (!this.callbacks[event]) this.callbacks[event] = [];
1059
+ this.callbacks[event].push(fn);
1060
+ return this;
1061
+ }
1062
+ emit(event, ...args) {
1063
+ const callbacks = this.callbacks[event];
1064
+ if (callbacks) callbacks.forEach((callback) => callback.apply(this, args));
1065
+ return this;
1066
+ }
1067
+ off(event, fn) {
1068
+ const callbacks = this.callbacks[event];
1069
+ if (callbacks) if (fn) this.callbacks[event] = callbacks.filter((callback) => callback !== fn);
1070
+ else delete this.callbacks[event];
1071
+ return this;
1072
+ }
1073
+ removeAllListeners() {
1074
+ this.callbacks = {};
1075
+ }
1076
+ };
1077
+
1078
+ //#endregion
1079
+ //#region packages/provider/src/IncomingMessage.ts
1080
+ var IncomingMessage = class {
1081
+ constructor(data) {
1082
+ this.data = data;
1083
+ this.encoder = createEncoder();
1084
+ this.decoder = createDecoder(new Uint8Array(this.data));
1085
+ }
1086
+ peekVarString() {
1087
+ return peekVarString(this.decoder);
1088
+ }
1089
+ readVarUint() {
1090
+ return readVarUint(this.decoder);
1091
+ }
1092
+ readVarString() {
1093
+ return readVarString(this.decoder);
1094
+ }
1095
+ readVarUint8Array() {
1096
+ return readVarUint8Array(this.decoder);
1097
+ }
1098
+ writeVarUint(type) {
1099
+ return writeVarUint(this.encoder, type);
1100
+ }
1101
+ writeVarString(string) {
1102
+ return writeVarString(this.encoder, string);
1103
+ }
1104
+ writeVarUint8Array(data) {
1105
+ return writeVarUint8Array(this.encoder, data);
1106
+ }
1107
+ length() {
1108
+ return length(this.encoder);
1109
+ }
1110
+ };
1111
+
1112
+ //#endregion
1113
+ //#region packages/provider/src/types.ts
1114
+ let MessageType = /* @__PURE__ */ function(MessageType) {
1115
+ MessageType[MessageType["Sync"] = 0] = "Sync";
1116
+ MessageType[MessageType["Awareness"] = 1] = "Awareness";
1117
+ MessageType[MessageType["Auth"] = 2] = "Auth";
1118
+ MessageType[MessageType["QueryAwareness"] = 3] = "QueryAwareness";
1119
+ MessageType[MessageType["Subdoc"] = 4] = "Subdoc";
1120
+ MessageType[MessageType["Stateless"] = 5] = "Stateless";
1121
+ MessageType[MessageType["CLOSE"] = 7] = "CLOSE";
1122
+ MessageType[MessageType["SyncStatus"] = 8] = "SyncStatus";
1123
+ return MessageType;
1124
+ }({});
1125
+ let WebSocketStatus = /* @__PURE__ */ function(WebSocketStatus) {
1126
+ WebSocketStatus["Connecting"] = "connecting";
1127
+ WebSocketStatus["Connected"] = "connected";
1128
+ WebSocketStatus["Disconnected"] = "disconnected";
1129
+ return WebSocketStatus;
1130
+ }({});
1131
+
1132
+ //#endregion
1133
+ //#region packages/provider/src/OutgoingMessage.ts
1134
+ var OutgoingMessage = class {
1135
+ constructor() {
1136
+ this.encoder = createEncoder();
1137
+ }
1138
+ get(args) {
1139
+ return args.encoder;
1140
+ }
1141
+ toUint8Array() {
1142
+ return toUint8Array(this.encoder);
1143
+ }
1144
+ };
1145
+
1146
+ //#endregion
1147
+ //#region packages/provider/src/OutgoingMessages/CloseMessage.ts
1148
+ var CloseMessage = class extends OutgoingMessage {
1149
+ constructor(..._args) {
1150
+ super(..._args);
1151
+ this.type = MessageType.CLOSE;
1152
+ this.description = "Ask the server to close the connection";
1153
+ }
1154
+ get(args) {
1155
+ writeVarString(this.encoder, args.documentName);
1156
+ writeVarUint(this.encoder, this.type);
1157
+ return this.encoder;
1158
+ }
1159
+ };
1160
+
1161
+ //#endregion
1162
+ //#region packages/provider/src/HocuspocusProviderWebsocket.ts
1163
+ var HocuspocusProviderWebsocket = class extends EventEmitter {
1164
+ constructor(configuration) {
1165
+ super();
1166
+ this.messageQueue = [];
1167
+ this.configuration = {
1168
+ url: "",
1169
+ autoConnect: true,
1170
+ preserveTrailingSlash: false,
1171
+ document: void 0,
1172
+ WebSocketPolyfill: void 0,
1173
+ messageReconnectTimeout: 3e4,
1174
+ delay: 1e3,
1175
+ initialDelay: 0,
1176
+ factor: 2,
1177
+ maxAttempts: 0,
1178
+ minDelay: 1e3,
1179
+ maxDelay: 3e4,
1180
+ jitter: true,
1181
+ timeout: 0,
1182
+ onOpen: () => null,
1183
+ onConnect: () => null,
1184
+ onMessage: () => null,
1185
+ onOutgoingMessage: () => null,
1186
+ onStatus: () => null,
1187
+ onDisconnect: () => null,
1188
+ onClose: () => null,
1189
+ onDestroy: () => null,
1190
+ onAwarenessUpdate: () => null,
1191
+ onAwarenessChange: () => null,
1192
+ handleTimeout: null,
1193
+ providerMap: /* @__PURE__ */ new Map()
1194
+ };
1195
+ this.webSocket = null;
1196
+ this.webSocketHandlers = {};
1197
+ this.shouldConnect = true;
1198
+ this.status = WebSocketStatus.Disconnected;
1199
+ this.lastMessageReceived = 0;
1200
+ this.identifier = 0;
1201
+ this.intervals = { connectionChecker: null };
1202
+ this.connectionAttempt = null;
1203
+ this.receivedOnOpenPayload = void 0;
1204
+ this.closeTries = 0;
1205
+ this.setConfiguration(configuration);
1206
+ this.configuration.WebSocketPolyfill = configuration.WebSocketPolyfill ? configuration.WebSocketPolyfill : WebSocket;
1207
+ this.on("open", this.configuration.onOpen);
1208
+ this.on("open", this.onOpen.bind(this));
1209
+ this.on("connect", this.configuration.onConnect);
1210
+ this.on("message", this.configuration.onMessage);
1211
+ this.on("outgoingMessage", this.configuration.onOutgoingMessage);
1212
+ this.on("status", this.configuration.onStatus);
1213
+ this.on("disconnect", this.configuration.onDisconnect);
1214
+ this.on("close", this.configuration.onClose);
1215
+ this.on("destroy", this.configuration.onDestroy);
1216
+ this.on("awarenessUpdate", this.configuration.onAwarenessUpdate);
1217
+ this.on("awarenessChange", this.configuration.onAwarenessChange);
1218
+ this.on("close", this.onClose.bind(this));
1219
+ this.on("message", this.onMessage.bind(this));
1220
+ this.intervals.connectionChecker = setInterval(this.checkConnection.bind(this), this.configuration.messageReconnectTimeout / 10);
1221
+ if (this.shouldConnect) this.connect();
1222
+ }
1223
+ async onOpen(event) {
1224
+ this.status = WebSocketStatus.Connected;
1225
+ this.emit("status", { status: WebSocketStatus.Connected });
1226
+ this.cancelWebsocketRetry = void 0;
1227
+ this.receivedOnOpenPayload = event;
1228
+ }
1229
+ attach(provider) {
1230
+ this.configuration.providerMap.set(provider.configuration.name, provider);
1231
+ if (this.status === WebSocketStatus.Disconnected && this.shouldConnect) this.connect();
1232
+ if (this.receivedOnOpenPayload && this.status === WebSocketStatus.Connected) provider.onOpen(this.receivedOnOpenPayload);
1233
+ }
1234
+ detach(provider) {
1235
+ if (this.configuration.providerMap.has(provider.configuration.name)) {
1236
+ provider.send(CloseMessage, { documentName: provider.configuration.name });
1237
+ this.configuration.providerMap.delete(provider.configuration.name);
1238
+ }
1239
+ }
1240
+ setConfiguration(configuration = {}) {
1241
+ this.configuration = {
1242
+ ...this.configuration,
1243
+ ...configuration
1244
+ };
1245
+ if (!this.configuration.autoConnect) this.shouldConnect = false;
1246
+ }
1247
+ async connect() {
1248
+ if (this.status === WebSocketStatus.Connected) return;
1249
+ if (this.cancelWebsocketRetry) {
1250
+ this.cancelWebsocketRetry();
1251
+ this.cancelWebsocketRetry = void 0;
1252
+ }
1253
+ this.receivedOnOpenPayload = void 0;
1254
+ this.shouldConnect = true;
1255
+ const abortableRetry = () => {
1256
+ let cancelAttempt = false;
1257
+ return {
1258
+ retryPromise: retry(this.createWebSocketConnection.bind(this), {
1259
+ delay: this.configuration.delay,
1260
+ initialDelay: this.configuration.initialDelay,
1261
+ factor: this.configuration.factor,
1262
+ maxAttempts: this.configuration.maxAttempts,
1263
+ minDelay: this.configuration.minDelay,
1264
+ maxDelay: this.configuration.maxDelay,
1265
+ jitter: this.configuration.jitter,
1266
+ timeout: this.configuration.timeout,
1267
+ handleTimeout: this.configuration.handleTimeout,
1268
+ beforeAttempt: (context) => {
1269
+ if (!this.shouldConnect || cancelAttempt) context.abort();
1270
+ }
1271
+ }).catch((error) => {
1272
+ if (error && error.code !== "ATTEMPT_ABORTED") throw error;
1273
+ }),
1274
+ cancelFunc: () => {
1275
+ cancelAttempt = true;
1276
+ }
1277
+ };
1278
+ };
1279
+ const { retryPromise, cancelFunc } = abortableRetry();
1280
+ this.cancelWebsocketRetry = cancelFunc;
1281
+ return retryPromise;
1282
+ }
1283
+ attachWebSocketListeners(ws, reject) {
1284
+ const { identifier } = ws;
1285
+ const onMessageHandler = (payload) => this.emit("message", payload);
1286
+ const onCloseHandler = (payload) => this.emit("close", { event: payload });
1287
+ const onOpenHandler = (payload) => this.emit("open", payload);
1288
+ const onErrorHandler = (err) => {
1289
+ reject(err);
1290
+ };
1291
+ this.webSocketHandlers[identifier] = {
1292
+ message: onMessageHandler,
1293
+ close: onCloseHandler,
1294
+ open: onOpenHandler,
1295
+ error: onErrorHandler
1296
+ };
1297
+ const handlers = this.webSocketHandlers[ws.identifier];
1298
+ Object.keys(handlers).forEach((name) => {
1299
+ ws.addEventListener(name, handlers[name]);
1300
+ });
1301
+ }
1302
+ cleanupWebSocket() {
1303
+ if (!this.webSocket) return;
1304
+ const { identifier } = this.webSocket;
1305
+ const handlers = this.webSocketHandlers[identifier];
1306
+ Object.keys(handlers).forEach((name) => {
1307
+ this.webSocket?.removeEventListener(name, handlers[name]);
1308
+ delete this.webSocketHandlers[identifier];
1309
+ });
1310
+ try {
1311
+ if (this.webSocket.readyState !== 0 && this.webSocket.readyState !== 3) this.webSocket.close();
1312
+ } catch (e) {}
1313
+ this.webSocket = null;
1314
+ }
1315
+ createWebSocketConnection() {
1316
+ return new Promise((resolve, reject) => {
1317
+ if (this.webSocket) {
1318
+ this.messageQueue = [];
1319
+ this.cleanupWebSocket();
1320
+ }
1321
+ this.lastMessageReceived = 0;
1322
+ this.identifier += 1;
1323
+ const ws = new this.configuration.WebSocketPolyfill(this.url);
1324
+ ws.binaryType = "arraybuffer";
1325
+ ws.identifier = this.identifier;
1326
+ this.attachWebSocketListeners(ws, reject);
1327
+ this.webSocket = ws;
1328
+ this.status = WebSocketStatus.Connecting;
1329
+ this.emit("status", { status: WebSocketStatus.Connecting });
1330
+ this.connectionAttempt = {
1331
+ resolve,
1332
+ reject
1333
+ };
1334
+ });
1335
+ }
1336
+ onMessage(event) {
1337
+ this.resolveConnectionAttempt();
1338
+ this.lastMessageReceived = getUnixTime();
1339
+ const documentName = new IncomingMessage(event.data).peekVarString();
1340
+ this.configuration.providerMap.get(documentName)?.onMessage(event);
1341
+ }
1342
+ resolveConnectionAttempt() {
1343
+ if (this.connectionAttempt) {
1344
+ this.connectionAttempt.resolve();
1345
+ this.connectionAttempt = null;
1346
+ this.status = WebSocketStatus.Connected;
1347
+ this.emit("status", { status: WebSocketStatus.Connected });
1348
+ this.emit("connect");
1349
+ this.messageQueue.forEach((message) => this.send(message));
1350
+ this.messageQueue = [];
1351
+ }
1352
+ }
1353
+ stopConnectionAttempt() {
1354
+ this.connectionAttempt = null;
1355
+ }
1356
+ rejectConnectionAttempt() {
1357
+ this.connectionAttempt?.reject();
1358
+ this.connectionAttempt = null;
1359
+ }
1360
+ checkConnection() {
1361
+ if (this.status !== WebSocketStatus.Connected) return;
1362
+ if (!this.lastMessageReceived) return;
1363
+ if (this.configuration.messageReconnectTimeout >= getUnixTime() - this.lastMessageReceived) return;
1364
+ this.closeTries += 1;
1365
+ if (this.closeTries > 2) {
1366
+ this.onClose({ event: {
1367
+ code: 4408,
1368
+ reason: "forced"
1369
+ } });
1370
+ this.closeTries = 0;
1371
+ } else {
1372
+ this.webSocket?.close();
1373
+ this.messageQueue = [];
1374
+ }
1375
+ }
1376
+ get serverUrl() {
1377
+ if (this.configuration.preserveTrailingSlash) return this.configuration.url;
1378
+ let url = this.configuration.url;
1379
+ while (url[url.length - 1] === "/") url = url.slice(0, url.length - 1);
1380
+ return url;
1381
+ }
1382
+ get url() {
1383
+ return this.serverUrl;
1384
+ }
1385
+ disconnect() {
1386
+ this.shouldConnect = false;
1387
+ if (this.webSocket === null) return;
1388
+ try {
1389
+ this.webSocket.close();
1390
+ this.messageQueue = [];
1391
+ } catch (e) {
1392
+ console.error(e);
1393
+ }
1394
+ }
1395
+ send(message) {
1396
+ if (this.webSocket?.readyState === WsReadyStates.Open) this.webSocket.send(message);
1397
+ else this.messageQueue.push(message);
1398
+ }
1399
+ onClose({ event }) {
1400
+ this.closeTries = 0;
1401
+ this.cleanupWebSocket();
1402
+ if (this.connectionAttempt) this.rejectConnectionAttempt();
1403
+ this.status = WebSocketStatus.Disconnected;
1404
+ this.emit("status", { status: WebSocketStatus.Disconnected });
1405
+ this.emit("disconnect", { event });
1406
+ if (!this.cancelWebsocketRetry && this.shouldConnect) setTimeout(() => {
1407
+ this.connect();
1408
+ }, this.configuration.delay);
1409
+ }
1410
+ destroy() {
1411
+ this.emit("destroy");
1412
+ clearInterval(this.intervals.connectionChecker);
1413
+ this.stopConnectionAttempt();
1414
+ this.disconnect();
1415
+ this.removeAllListeners();
1416
+ this.cleanupWebSocket();
1417
+ }
1418
+ };
1419
+
1420
+ //#endregion
1421
+ //#region node_modules/y-protocols/sync.js
1422
+ /**
1423
+ * @module sync-protocol
1424
+ */
1425
+ /**
1426
+ * @typedef {Map<number, number>} StateMap
1427
+ */
1428
+ /**
1429
+ * Core Yjs defines two message types:
1430
+ * • YjsSyncStep1: Includes the State Set of the sending client. When received, the client should reply with YjsSyncStep2.
1431
+ * • YjsSyncStep2: Includes all missing structs and the complete delete set. When received, the client is assured that it
1432
+ * received all information from the remote client.
1433
+ *
1434
+ * In a peer-to-peer network, you may want to introduce a SyncDone message type. Both parties should initiate the connection
1435
+ * with SyncStep1. When a client received SyncStep2, it should reply with SyncDone. When the local client received both
1436
+ * SyncStep2 and SyncDone, it is assured that it is synced to the remote client.
1437
+ *
1438
+ * In a client-server model, you want to handle this differently: The client should initiate the connection with SyncStep1.
1439
+ * When the server receives SyncStep1, it should reply with SyncStep2 immediately followed by SyncStep1. The client replies
1440
+ * with SyncStep2 when it receives SyncStep1. Optionally the server may send a SyncDone after it received SyncStep2, so the
1441
+ * client knows that the sync is finished. There are two reasons for this more elaborated sync model: 1. This protocol can
1442
+ * easily be implemented on top of http and websockets. 2. The server should only reply to requests, and not initiate them.
1443
+ * Therefore it is necessary that the client initiates the sync.
1444
+ *
1445
+ * Construction of a message:
1446
+ * [messageType : varUint, message definition..]
1447
+ *
1448
+ * Note: A message does not include information about the room name. This must to be handled by the upper layer protocol!
1449
+ *
1450
+ * stringify[messageType] stringifies a message definition (messageType is already read from the bufffer)
1451
+ */
1452
+ const messageYjsSyncStep1 = 0;
1453
+ const messageYjsSyncStep2 = 1;
1454
+ const messageYjsUpdate = 2;
1455
+ /**
1456
+ * Create a sync step 1 message based on the state of the current shared document.
1457
+ *
1458
+ * @param {encoding.Encoder} encoder
1459
+ * @param {Y.Doc} doc
1460
+ */
1461
+ const writeSyncStep1 = (encoder, doc) => {
1462
+ writeVarUint(encoder, messageYjsSyncStep1);
1463
+ const sv = Y.encodeStateVector(doc);
1464
+ writeVarUint8Array(encoder, sv);
1465
+ };
1466
+ /**
1467
+ * @param {encoding.Encoder} encoder
1468
+ * @param {Y.Doc} doc
1469
+ * @param {Uint8Array} [encodedStateVector]
1470
+ */
1471
+ const writeSyncStep2 = (encoder, doc, encodedStateVector) => {
1472
+ writeVarUint(encoder, messageYjsSyncStep2);
1473
+ writeVarUint8Array(encoder, Y.encodeStateAsUpdate(doc, encodedStateVector));
1474
+ };
1475
+ /**
1476
+ * Read SyncStep1 message and reply with SyncStep2.
1477
+ *
1478
+ * @param {decoding.Decoder} decoder The reply to the received message
1479
+ * @param {encoding.Encoder} encoder The received message
1480
+ * @param {Y.Doc} doc
1481
+ */
1482
+ const readSyncStep1 = (decoder, encoder, doc) => writeSyncStep2(encoder, doc, readVarUint8Array(decoder));
1483
+ /**
1484
+ * Read and apply Structs and then DeleteStore to a y instance.
1485
+ *
1486
+ * @param {decoding.Decoder} decoder
1487
+ * @param {Y.Doc} doc
1488
+ * @param {any} transactionOrigin
1489
+ * @param {(error:Error)=>any} [errorHandler]
1490
+ */
1491
+ const readSyncStep2 = (decoder, doc, transactionOrigin, errorHandler) => {
1492
+ try {
1493
+ Y.applyUpdate(doc, readVarUint8Array(decoder), transactionOrigin);
1494
+ } catch (error) {
1495
+ if (errorHandler != null) errorHandler(error);
1496
+ console.error("Caught error while handling a Yjs update", error);
1497
+ }
1498
+ };
1499
+ /**
1500
+ * @param {encoding.Encoder} encoder
1501
+ * @param {Uint8Array} update
1502
+ */
1503
+ const writeUpdate = (encoder, update) => {
1504
+ writeVarUint(encoder, messageYjsUpdate);
1505
+ writeVarUint8Array(encoder, update);
1506
+ };
1507
+ /**
1508
+ * Read and apply Structs and then DeleteStore to a y instance.
1509
+ *
1510
+ * @param {decoding.Decoder} decoder
1511
+ * @param {Y.Doc} doc
1512
+ * @param {any} transactionOrigin
1513
+ * @param {(error:Error)=>any} [errorHandler]
1514
+ */
1515
+ const readUpdate = readSyncStep2;
1516
+ /**
1517
+ * @param {decoding.Decoder} decoder A message received from another client
1518
+ * @param {encoding.Encoder} encoder The reply message. Does not need to be sent if empty.
1519
+ * @param {Y.Doc} doc
1520
+ * @param {any} transactionOrigin
1521
+ * @param {(error:Error)=>any} [errorHandler] Optional error handler that catches errors when reading Yjs messages.
1522
+ */
1523
+ const readSyncMessage = (decoder, encoder, doc, transactionOrigin, errorHandler) => {
1524
+ const messageType = readVarUint(decoder);
1525
+ switch (messageType) {
1526
+ case messageYjsSyncStep1:
1527
+ readSyncStep1(decoder, encoder, doc);
1528
+ break;
1529
+ case messageYjsSyncStep2:
1530
+ readSyncStep2(decoder, doc, transactionOrigin, errorHandler);
1531
+ break;
1532
+ case messageYjsUpdate:
1533
+ readUpdate(decoder, doc, transactionOrigin, errorHandler);
1534
+ break;
1535
+ default: throw new Error("Unknown message type");
1536
+ }
1537
+ return messageType;
1538
+ };
1539
+
1540
+ //#endregion
1541
+ //#region packages/provider/src/MessageReceiver.ts
1542
+ var MessageReceiver = class {
1543
+ constructor(message) {
1544
+ this.message = message;
1545
+ }
1546
+ apply(provider, emitSynced) {
1547
+ const { message } = this;
1548
+ const type = message.readVarUint();
1549
+ const emptyMessageLength = message.length();
1550
+ switch (type) {
1551
+ case MessageType.Sync:
1552
+ this.applySyncMessage(provider, emitSynced);
1553
+ break;
1554
+ case MessageType.Awareness:
1555
+ this.applyAwarenessMessage(provider);
1556
+ break;
1557
+ case MessageType.Auth:
1558
+ this.applyAuthMessage(provider);
1559
+ break;
1560
+ case MessageType.QueryAwareness:
1561
+ this.applyQueryAwarenessMessage(provider);
1562
+ break;
1563
+ case MessageType.Stateless:
1564
+ provider.receiveStateless(readVarString(message.decoder));
1565
+ break;
1566
+ case MessageType.SyncStatus:
1567
+ this.applySyncStatusMessage(provider, readVarInt(message.decoder) === 1);
1568
+ break;
1569
+ case MessageType.CLOSE:
1570
+ const event = {
1571
+ code: 1e3,
1572
+ reason: readVarString(message.decoder),
1573
+ target: provider.configuration.websocketProvider.webSocket,
1574
+ type: "close"
1575
+ };
1576
+ provider.onClose();
1577
+ provider.configuration.onClose({ event });
1578
+ provider.forwardClose({ event });
1579
+ break;
1580
+ default: throw new Error(`Can’t apply message of unknown type: ${type}`);
1581
+ }
1582
+ if (message.length() > emptyMessageLength + 1) provider.send(OutgoingMessage, { encoder: message.encoder });
1583
+ }
1584
+ applySyncMessage(provider, emitSynced) {
1585
+ const { message } = this;
1586
+ message.writeVarUint(MessageType.Sync);
1587
+ const syncMessageType = readSyncMessage(message.decoder, message.encoder, provider.document, provider);
1588
+ if (emitSynced && syncMessageType === messageYjsSyncStep2) provider.synced = true;
1589
+ }
1590
+ applySyncStatusMessage(provider, applied) {
1591
+ if (applied) provider.decrementUnsyncedChanges();
1592
+ }
1593
+ applyAwarenessMessage(provider) {
1594
+ if (!provider.awareness) return;
1595
+ const { message } = this;
1596
+ applyAwarenessUpdate(provider.awareness, message.readVarUint8Array(), provider);
1597
+ }
1598
+ applyAuthMessage(provider) {
1599
+ const { message } = this;
1600
+ readAuthMessage(message.decoder, provider.sendToken.bind(provider), provider.permissionDeniedHandler.bind(provider), provider.authenticatedHandler.bind(provider));
1601
+ }
1602
+ applyQueryAwarenessMessage(provider) {
1603
+ if (!provider.awareness) return;
1604
+ const { message } = this;
1605
+ message.writeVarUint(MessageType.Awareness);
1606
+ message.writeVarUint8Array(encodeAwarenessUpdate(provider.awareness, Array.from(provider.awareness.getStates().keys())));
1607
+ }
1608
+ };
1609
+
1610
+ //#endregion
1611
+ //#region packages/provider/src/MessageSender.ts
1612
+ var MessageSender = class {
1613
+ constructor(Message, args = {}) {
1614
+ this.message = new Message();
1615
+ this.encoder = this.message.get(args);
1616
+ }
1617
+ create() {
1618
+ return toUint8Array(this.encoder);
1619
+ }
1620
+ send(webSocket) {
1621
+ webSocket?.send(this.create());
1622
+ }
1623
+ };
1624
+
1625
+ //#endregion
1626
+ //#region packages/provider/src/OutgoingMessages/AuthenticationMessage.ts
1627
+ var AuthenticationMessage = class extends OutgoingMessage {
1628
+ constructor(..._args) {
1629
+ super(..._args);
1630
+ this.type = MessageType.Auth;
1631
+ this.description = "Authentication";
1632
+ }
1633
+ get(args) {
1634
+ if (typeof args.token === "undefined") throw new Error("The authentication message requires `token` as an argument.");
1635
+ writeVarString(this.encoder, args.documentName);
1636
+ writeVarUint(this.encoder, this.type);
1637
+ writeAuthentication(this.encoder, args.token);
1638
+ return this.encoder;
1639
+ }
1640
+ };
1641
+
1642
+ //#endregion
1643
+ //#region packages/provider/src/OutgoingMessages/AwarenessMessage.ts
1644
+ var AwarenessMessage = class extends OutgoingMessage {
1645
+ constructor(..._args) {
1646
+ super(..._args);
1647
+ this.type = MessageType.Awareness;
1648
+ this.description = "Awareness states update";
1649
+ }
1650
+ get(args) {
1651
+ if (typeof args.awareness === "undefined") throw new Error("The awareness message requires awareness as an argument");
1652
+ if (typeof args.clients === "undefined") throw new Error("The awareness message requires clients as an argument");
1653
+ writeVarString(this.encoder, args.documentName);
1654
+ writeVarUint(this.encoder, this.type);
1655
+ let awarenessUpdate;
1656
+ if (args.states === void 0) awarenessUpdate = encodeAwarenessUpdate(args.awareness, args.clients);
1657
+ else awarenessUpdate = encodeAwarenessUpdate(args.awareness, args.clients, args.states);
1658
+ writeVarUint8Array(this.encoder, awarenessUpdate);
1659
+ return this.encoder;
1660
+ }
1661
+ };
1662
+
1663
+ //#endregion
1664
+ //#region packages/provider/src/OutgoingMessages/StatelessMessage.ts
1665
+ var StatelessMessage = class extends OutgoingMessage {
1666
+ constructor(..._args) {
1667
+ super(..._args);
1668
+ this.type = MessageType.Stateless;
1669
+ this.description = "A stateless message";
1670
+ }
1671
+ get(args) {
1672
+ writeVarString(this.encoder, args.documentName);
1673
+ writeVarUint(this.encoder, this.type);
1674
+ writeVarString(this.encoder, args.payload ?? "");
1675
+ return this.encoder;
1676
+ }
1677
+ };
1678
+
1679
+ //#endregion
1680
+ //#region packages/provider/src/OutgoingMessages/SyncStepOneMessage.ts
1681
+ var SyncStepOneMessage = class extends OutgoingMessage {
1682
+ constructor(..._args) {
1683
+ super(..._args);
1684
+ this.type = MessageType.Sync;
1685
+ this.description = "First sync step";
1686
+ }
1687
+ get(args) {
1688
+ if (typeof args.document === "undefined") throw new Error("The sync step one message requires document as an argument");
1689
+ writeVarString(this.encoder, args.documentName);
1690
+ writeVarUint(this.encoder, this.type);
1691
+ writeSyncStep1(this.encoder, args.document);
1692
+ return this.encoder;
1693
+ }
1694
+ };
1695
+
1696
+ //#endregion
1697
+ //#region packages/provider/src/OutgoingMessages/UpdateMessage.ts
1698
+ var UpdateMessage = class extends OutgoingMessage {
1699
+ constructor(..._args) {
1700
+ super(..._args);
1701
+ this.type = MessageType.Sync;
1702
+ this.description = "A document update";
1703
+ }
1704
+ get(args) {
1705
+ writeVarString(this.encoder, args.documentName);
1706
+ writeVarUint(this.encoder, this.type);
1707
+ writeUpdate(this.encoder, args.update);
1708
+ return this.encoder;
1709
+ }
1710
+ };
1711
+
1712
+ //#endregion
1713
+ //#region packages/provider/src/HocuspocusProvider.ts
1714
+ var AwarenessError = class extends Error {
1715
+ constructor(..._args) {
1716
+ super(..._args);
1717
+ this.code = 1001;
1718
+ }
1719
+ };
1720
+ var HocuspocusProvider = class extends EventEmitter {
1721
+ constructor(configuration) {
1722
+ super();
1723
+ this.configuration = {
1724
+ name: "",
1725
+ document: void 0,
1726
+ awareness: void 0,
1727
+ token: null,
1728
+ forceSyncInterval: false,
1729
+ onAuthenticated: () => null,
1730
+ onAuthenticationFailed: () => null,
1731
+ onOpen: () => null,
1732
+ onConnect: () => null,
1733
+ onMessage: () => null,
1734
+ onOutgoingMessage: () => null,
1735
+ onSynced: () => null,
1736
+ onStatus: () => null,
1737
+ onDisconnect: () => null,
1738
+ onClose: () => null,
1739
+ onDestroy: () => null,
1740
+ onAwarenessUpdate: () => null,
1741
+ onAwarenessChange: () => null,
1742
+ onStateless: () => null,
1743
+ onUnsyncedChanges: () => null
1744
+ };
1745
+ this.isSynced = false;
1746
+ this.unsyncedChanges = 0;
1747
+ this.isAuthenticated = false;
1748
+ this.authorizedScope = void 0;
1749
+ this.manageSocket = false;
1750
+ this._isAttached = false;
1751
+ this.intervals = { forceSync: null };
1752
+ this.boundDocumentUpdateHandler = this.documentUpdateHandler.bind(this);
1753
+ this.boundAwarenessUpdateHandler = this.awarenessUpdateHandler.bind(this);
1754
+ this.boundPageHide = this.pageHide.bind(this);
1755
+ this.boundOnOpen = this.onOpen.bind(this);
1756
+ this.boundOnClose = this.onClose.bind(this);
1757
+ this.forwardConnect = () => this.emit("connect");
1758
+ this.forwardStatus = (e) => this.emit("status", e);
1759
+ this.forwardClose = (e) => this.emit("close", e);
1760
+ this.forwardDisconnect = (e) => this.emit("disconnect", e);
1761
+ this.forwardDestroy = () => this.emit("destroy");
1762
+ this.setConfiguration(configuration);
1763
+ this.configuration.document = configuration.document ? configuration.document : new Y.Doc();
1764
+ this.configuration.awareness = configuration.awareness !== void 0 ? configuration.awareness : new Awareness(this.document);
1765
+ this.on("open", this.configuration.onOpen);
1766
+ this.on("message", this.configuration.onMessage);
1767
+ this.on("outgoingMessage", this.configuration.onOutgoingMessage);
1768
+ this.on("synced", this.configuration.onSynced);
1769
+ this.on("destroy", this.configuration.onDestroy);
1770
+ this.on("awarenessUpdate", this.configuration.onAwarenessUpdate);
1771
+ this.on("awarenessChange", this.configuration.onAwarenessChange);
1772
+ this.on("stateless", this.configuration.onStateless);
1773
+ this.on("unsyncedChanges", this.configuration.onUnsyncedChanges);
1774
+ this.on("authenticated", this.configuration.onAuthenticated);
1775
+ this.on("authenticationFailed", this.configuration.onAuthenticationFailed);
1776
+ this.awareness?.on("update", () => {
1777
+ this.emit("awarenessUpdate", { states: awarenessStatesToArray(this.awareness.getStates()) });
1778
+ });
1779
+ this.awareness?.on("change", () => {
1780
+ this.emit("awarenessChange", { states: awarenessStatesToArray(this.awareness.getStates()) });
1781
+ });
1782
+ this.document.on("update", this.boundDocumentUpdateHandler);
1783
+ this.awareness?.on("update", this.boundAwarenessUpdateHandler);
1784
+ this.registerEventListeners();
1785
+ if (this.configuration.forceSyncInterval && typeof this.configuration.forceSyncInterval === "number") this.intervals.forceSync = setInterval(this.forceSync.bind(this), this.configuration.forceSyncInterval);
1786
+ if (this.manageSocket) this.attach();
1787
+ }
1788
+ setConfiguration(configuration = {}) {
1789
+ if (!configuration.websocketProvider) {
1790
+ this.manageSocket = true;
1791
+ this.configuration.websocketProvider = new HocuspocusProviderWebsocket(configuration);
1792
+ }
1793
+ this.configuration = {
1794
+ ...this.configuration,
1795
+ ...configuration
1796
+ };
1797
+ }
1798
+ get document() {
1799
+ return this.configuration.document;
1800
+ }
1801
+ get isAttached() {
1802
+ return this._isAttached;
1803
+ }
1804
+ get awareness() {
1805
+ return this.configuration.awareness;
1806
+ }
1807
+ get hasUnsyncedChanges() {
1808
+ return this.unsyncedChanges > 0;
1809
+ }
1810
+ resetUnsyncedChanges() {
1811
+ this.unsyncedChanges = 1;
1812
+ this.emit("unsyncedChanges", { number: this.unsyncedChanges });
1813
+ }
1814
+ incrementUnsyncedChanges() {
1815
+ this.unsyncedChanges += 1;
1816
+ this.emit("unsyncedChanges", { number: this.unsyncedChanges });
1817
+ }
1818
+ decrementUnsyncedChanges() {
1819
+ if (this.unsyncedChanges > 0) this.unsyncedChanges -= 1;
1820
+ if (this.unsyncedChanges === 0) this.synced = true;
1821
+ this.emit("unsyncedChanges", { number: this.unsyncedChanges });
1822
+ }
1823
+ forceSync() {
1824
+ this.resetUnsyncedChanges();
1825
+ this.send(SyncStepOneMessage, {
1826
+ document: this.document,
1827
+ documentName: this.configuration.name
1828
+ });
1829
+ }
1830
+ pageHide() {
1831
+ if (this.awareness) removeAwarenessStates(this.awareness, [this.document.clientID], "page hide");
1832
+ }
1833
+ registerEventListeners() {
1834
+ if (typeof window === "undefined" || !("addEventListener" in window)) return;
1835
+ window.addEventListener("pagehide", this.boundPageHide);
1836
+ }
1837
+ sendStateless(payload) {
1838
+ this.send(StatelessMessage, {
1839
+ documentName: this.configuration.name,
1840
+ payload
1841
+ });
1842
+ }
1843
+ async sendToken() {
1844
+ let token;
1845
+ try {
1846
+ token = await this.getToken();
1847
+ } catch (error) {
1848
+ this.permissionDeniedHandler(`Failed to get token during sendToken(): ${error}`);
1849
+ return;
1850
+ }
1851
+ this.send(AuthenticationMessage, {
1852
+ token: token ?? "",
1853
+ documentName: this.configuration.name
1854
+ });
1855
+ }
1856
+ documentUpdateHandler(update, origin) {
1857
+ if (origin === this) return;
1858
+ this.incrementUnsyncedChanges();
1859
+ this.send(UpdateMessage, {
1860
+ update,
1861
+ documentName: this.configuration.name
1862
+ });
1863
+ }
1864
+ awarenessUpdateHandler({ added, updated, removed }, origin) {
1865
+ const changedClients = added.concat(updated).concat(removed);
1866
+ this.send(AwarenessMessage, {
1867
+ awareness: this.awareness,
1868
+ clients: changedClients,
1869
+ documentName: this.configuration.name
1870
+ });
1871
+ }
1872
+ /**
1873
+ * Indicates whether a first handshake with the server has been established
1874
+ *
1875
+ * Note: this does not mean all updates from the client have been persisted to the backend. For this,
1876
+ * use `hasUnsyncedChanges`.
1877
+ */
1878
+ get synced() {
1879
+ return this.isSynced;
1880
+ }
1881
+ set synced(state) {
1882
+ if (this.isSynced === state) return;
1883
+ this.isSynced = state;
1884
+ if (state) this.emit("synced", { state });
1885
+ }
1886
+ receiveStateless(payload) {
1887
+ this.emit("stateless", { payload });
1888
+ }
1889
+ async connect() {
1890
+ if (this.manageSocket) return this.configuration.websocketProvider.connect();
1891
+ console.warn("HocuspocusProvider::connect() is deprecated and does not do anything. Please connect/disconnect on the websocketProvider, or attach/deattach providers.");
1892
+ }
1893
+ disconnect() {
1894
+ if (this.manageSocket) return this.configuration.websocketProvider.disconnect();
1895
+ console.warn("HocuspocusProvider::disconnect() is deprecated and does not do anything. Please connect/disconnect on the websocketProvider, or attach/deattach providers.");
1896
+ }
1897
+ async onOpen(event) {
1898
+ this.isAuthenticated = false;
1899
+ this.emit("open", { event });
1900
+ await this.sendToken();
1901
+ this.startSync();
1902
+ }
1903
+ async getToken() {
1904
+ if (typeof this.configuration.token === "function") return await this.configuration.token();
1905
+ return this.configuration.token;
1906
+ }
1907
+ startSync() {
1908
+ this.resetUnsyncedChanges();
1909
+ this.send(SyncStepOneMessage, {
1910
+ document: this.document,
1911
+ documentName: this.configuration.name
1912
+ });
1913
+ if (this.awareness && this.awareness.getLocalState() !== null) this.send(AwarenessMessage, {
1914
+ awareness: this.awareness,
1915
+ clients: [this.document.clientID],
1916
+ documentName: this.configuration.name
1917
+ });
1918
+ }
1919
+ send(message, args) {
1920
+ if (!this._isAttached) return;
1921
+ const messageSender = new MessageSender(message, args);
1922
+ this.emit("outgoingMessage", { message: messageSender.message });
1923
+ messageSender.send(this.configuration.websocketProvider);
1924
+ }
1925
+ onMessage(event) {
1926
+ const message = new IncomingMessage(event.data);
1927
+ const documentName = message.readVarString();
1928
+ message.writeVarString(documentName);
1929
+ this.emit("message", {
1930
+ event,
1931
+ message: new IncomingMessage(event.data)
1932
+ });
1933
+ new MessageReceiver(message).apply(this, true);
1934
+ }
1935
+ onClose() {
1936
+ this.isAuthenticated = false;
1937
+ this.synced = false;
1938
+ if (this.awareness) removeAwarenessStates(this.awareness, Array.from(this.awareness.getStates().keys()).filter((client) => client !== this.document.clientID), this);
1939
+ }
1940
+ destroy() {
1941
+ this.emit("destroy");
1942
+ if (this.intervals.forceSync) clearInterval(this.intervals.forceSync);
1943
+ if (this.awareness) {
1944
+ removeAwarenessStates(this.awareness, [this.document.clientID], "provider destroy");
1945
+ this.awareness.off("update", this.boundAwarenessUpdateHandler);
1946
+ this.awareness.destroy();
1947
+ }
1948
+ this.document.off("update", this.boundDocumentUpdateHandler);
1949
+ this.removeAllListeners();
1950
+ this.detach();
1951
+ if (this.manageSocket) this.configuration.websocketProvider.destroy();
1952
+ if (typeof window === "undefined" || !("removeEventListener" in window)) return;
1953
+ window.removeEventListener("pagehide", this.boundPageHide);
1954
+ }
1955
+ detach() {
1956
+ this.configuration.websocketProvider.off("connect", this.configuration.onConnect);
1957
+ this.configuration.websocketProvider.off("connect", this.forwardConnect);
1958
+ this.configuration.websocketProvider.off("status", this.forwardStatus);
1959
+ this.configuration.websocketProvider.off("status", this.configuration.onStatus);
1960
+ this.configuration.websocketProvider.off("open", this.boundOnOpen);
1961
+ this.configuration.websocketProvider.off("close", this.boundOnClose);
1962
+ this.configuration.websocketProvider.off("close", this.configuration.onClose);
1963
+ this.configuration.websocketProvider.off("close", this.forwardClose);
1964
+ this.configuration.websocketProvider.off("disconnect", this.configuration.onDisconnect);
1965
+ this.configuration.websocketProvider.off("disconnect", this.forwardDisconnect);
1966
+ this.configuration.websocketProvider.off("destroy", this.configuration.onDestroy);
1967
+ this.configuration.websocketProvider.off("destroy", this.forwardDestroy);
1968
+ this.configuration.websocketProvider.detach(this);
1969
+ this._isAttached = false;
1970
+ }
1971
+ attach() {
1972
+ if (this._isAttached) return;
1973
+ this.configuration.websocketProvider.on("connect", this.configuration.onConnect);
1974
+ this.configuration.websocketProvider.on("connect", this.forwardConnect);
1975
+ this.configuration.websocketProvider.on("status", this.configuration.onStatus);
1976
+ this.configuration.websocketProvider.on("status", this.forwardStatus);
1977
+ this.configuration.websocketProvider.on("open", this.boundOnOpen);
1978
+ this.configuration.websocketProvider.on("close", this.boundOnClose);
1979
+ this.configuration.websocketProvider.on("close", this.configuration.onClose);
1980
+ this.configuration.websocketProvider.on("close", this.forwardClose);
1981
+ this.configuration.websocketProvider.on("disconnect", this.configuration.onDisconnect);
1982
+ this.configuration.websocketProvider.on("disconnect", this.forwardDisconnect);
1983
+ this.configuration.websocketProvider.on("destroy", this.configuration.onDestroy);
1984
+ this.configuration.websocketProvider.on("destroy", this.forwardDestroy);
1985
+ this.configuration.websocketProvider.attach(this);
1986
+ this._isAttached = true;
1987
+ }
1988
+ permissionDeniedHandler(reason) {
1989
+ this.emit("authenticationFailed", { reason });
1990
+ this.isAuthenticated = false;
1991
+ }
1992
+ authenticatedHandler(scope) {
1993
+ this.isAuthenticated = true;
1994
+ this.authorizedScope = scope;
1995
+ this.emit("authenticated", { scope });
1996
+ }
1997
+ setAwarenessField(key, value) {
1998
+ if (!this.awareness) throw new AwarenessError(`Cannot set awareness field "${key}" to ${JSON.stringify(value)}. You have disabled Awareness for this provider by explicitly passing awareness: null in the provider configuration.`);
1999
+ this.awareness.setLocalStateField(key, value);
2000
+ }
2001
+ };
2002
+
2003
+ //#endregion
2004
+ //#region packages/provider/src/OfflineStore.ts
2005
+ const DB_VERSION = 1;
2006
+ function idbAvailable() {
2007
+ return typeof globalThis !== "undefined" && "indexedDB" in globalThis;
2008
+ }
2009
+ function openDb$1(docId) {
2010
+ return new Promise((resolve, reject) => {
2011
+ const req = globalThis.indexedDB.open(`abracadabra:${docId}`, DB_VERSION);
2012
+ req.onupgradeneeded = (event) => {
2013
+ const db = event.target.result;
2014
+ if (!db.objectStoreNames.contains("updates")) db.createObjectStore("updates", { autoIncrement: true });
2015
+ if (!db.objectStoreNames.contains("meta")) db.createObjectStore("meta");
2016
+ if (!db.objectStoreNames.contains("subdoc_queue")) db.createObjectStore("subdoc_queue", { keyPath: "childId" });
2017
+ };
2018
+ req.onsuccess = () => resolve(req.result);
2019
+ req.onerror = () => reject(req.error);
2020
+ });
2021
+ }
2022
+ function txPromise(store, request) {
2023
+ return new Promise((resolve, reject) => {
2024
+ request.onsuccess = () => resolve(request.result);
2025
+ request.onerror = () => reject(request.error);
2026
+ });
2027
+ }
2028
+ var OfflineStore = class {
2029
+ constructor(docId) {
2030
+ this.db = null;
2031
+ this.docId = docId;
2032
+ }
2033
+ async getDb() {
2034
+ if (!idbAvailable()) return null;
2035
+ if (!this.db) this.db = await openDb$1(this.docId).catch(() => null);
2036
+ return this.db;
2037
+ }
2038
+ async persistUpdate(update) {
2039
+ const db = await this.getDb();
2040
+ if (!db) return;
2041
+ const store = db.transaction("updates", "readwrite").objectStore("updates");
2042
+ await txPromise(store, store.add(update));
2043
+ }
2044
+ async getPendingUpdates() {
2045
+ const db = await this.getDb();
2046
+ if (!db) return [];
2047
+ return new Promise((resolve, reject) => {
2048
+ const req = db.transaction("updates", "readonly").objectStore("updates").getAll();
2049
+ req.onsuccess = () => resolve(req.result);
2050
+ req.onerror = () => reject(req.error);
2051
+ });
2052
+ }
2053
+ async clearPendingUpdates() {
2054
+ const db = await this.getDb();
2055
+ if (!db) return;
2056
+ const tx = db.transaction("updates", "readwrite");
2057
+ await txPromise(tx.objectStore("updates"), tx.objectStore("updates").clear());
2058
+ }
2059
+ async getStateVector() {
2060
+ const db = await this.getDb();
2061
+ if (!db) return null;
2062
+ const tx = db.transaction("meta", "readonly");
2063
+ return await txPromise(tx.objectStore("meta"), tx.objectStore("meta").get("sv")) ?? null;
2064
+ }
2065
+ async saveStateVector(sv) {
2066
+ const db = await this.getDb();
2067
+ if (!db) return;
2068
+ const tx = db.transaction("meta", "readwrite");
2069
+ await txPromise(tx.objectStore("meta"), tx.objectStore("meta").put(sv, "sv"));
2070
+ }
2071
+ async getPermissionSnapshot() {
2072
+ const db = await this.getDb();
2073
+ if (!db) return null;
2074
+ const tx = db.transaction("meta", "readonly");
2075
+ return await txPromise(tx.objectStore("meta"), tx.objectStore("meta").get("role")) ?? null;
2076
+ }
2077
+ async savePermissionSnapshot(role) {
2078
+ const db = await this.getDb();
2079
+ if (!db) return;
2080
+ const tx = db.transaction("meta", "readwrite");
2081
+ await txPromise(tx.objectStore("meta"), tx.objectStore("meta").put(role, "role"));
2082
+ }
2083
+ async queueSubdoc(entry) {
2084
+ const db = await this.getDb();
2085
+ if (!db) return;
2086
+ const tx = db.transaction("subdoc_queue", "readwrite");
2087
+ await txPromise(tx.objectStore("subdoc_queue"), tx.objectStore("subdoc_queue").put(entry));
2088
+ }
2089
+ async getPendingSubdocs() {
2090
+ const db = await this.getDb();
2091
+ if (!db) return [];
2092
+ return new Promise((resolve, reject) => {
2093
+ const req = db.transaction("subdoc_queue", "readonly").objectStore("subdoc_queue").getAll();
2094
+ req.onsuccess = () => resolve(req.result);
2095
+ req.onerror = () => reject(req.error);
2096
+ });
2097
+ }
2098
+ async removeSubdocFromQueue(childId) {
2099
+ const db = await this.getDb();
2100
+ if (!db) return;
2101
+ const tx = db.transaction("subdoc_queue", "readwrite");
2102
+ await txPromise(tx.objectStore("subdoc_queue"), tx.objectStore("subdoc_queue").delete(childId));
2103
+ }
2104
+ destroy() {
2105
+ this.db?.close();
2106
+ this.db = null;
2107
+ }
2108
+ };
2109
+
2110
+ //#endregion
2111
+ //#region packages/provider/src/OutgoingMessages/SubdocMessage.ts
2112
+ /**
2113
+ * Registers a new subdocument with the Abracadabra server.
2114
+ *
2115
+ * Wire format (consumed by handle_subdoc in sync.rs):
2116
+ * [ParentDocName: VarString] [MSG_SUBDOC(4): VarUint] [childDocumentName: VarString]
2117
+ *
2118
+ * The server responds with a MSG_STATELESS JSON frame:
2119
+ * { type: "subdoc_registered", child_id, parent_id }
2120
+ * which AbracadabraProvider intercepts in receiveStateless().
2121
+ */
2122
+ var SubdocMessage = class extends OutgoingMessage {
2123
+ constructor(..._args) {
2124
+ super(..._args);
2125
+ this.type = MessageType.Subdoc;
2126
+ this.description = "SubdocRegistration";
2127
+ }
2128
+ get(args) {
2129
+ if (!args.documentName) throw new Error("SubdocMessage requires `documentName` (parent id).");
2130
+ if (!args.childDocumentName) throw new Error("SubdocMessage requires `childDocumentName`.");
2131
+ writeVarString(this.encoder, args.documentName);
2132
+ writeVarUint(this.encoder, this.type);
2133
+ writeVarString(this.encoder, args.childDocumentName);
2134
+ return this.encoder;
2135
+ }
2136
+ };
2137
+
2138
+ //#endregion
2139
+ //#region packages/provider/src/AbracadabraProvider.ts
2140
+ /**
2141
+ * AbracadabraProvider extends HocuspocusProvider with:
2142
+ *
2143
+ * 1. Subdocument lifecycle – intercepts Y.Doc subdoc events and syncs them
2144
+ * with the server via MSG_SUBDOC (4) frames. Child documents get their
2145
+ * own AbracadabraProvider instances sharing the same WebSocket connection.
2146
+ *
2147
+ * 2. Offline-first – persists CRDT updates to IndexedDB so they survive
2148
+ * page reloads and network outages. On reconnect, pending updates are
2149
+ * flushed before resuming normal sync.
2150
+ *
2151
+ * 3. Permission snapshotting – stores the resolved role locally so the UI
2152
+ * can gate write operations without a network round-trip. Role is
2153
+ * refreshed from the server on every reconnect.
2154
+ */
2155
+ var AbracadabraProvider = class AbracadabraProvider extends HocuspocusProvider {
2156
+ constructor(configuration) {
2157
+ super(configuration);
2158
+ this.effectiveRole = null;
2159
+ this.childProviders = /* @__PURE__ */ new Map();
2160
+ this.boundHandleYSubdocsChange = this.handleYSubdocsChange.bind(this);
2161
+ this.abracadabraConfig = configuration;
2162
+ this.subdocLoading = configuration.subdocLoading ?? "lazy";
2163
+ this.offlineStore = configuration.disableOfflineStore ? null : new OfflineStore(configuration.name);
2164
+ this.on("subdocRegistered", configuration.onSubdocRegistered ?? (() => null));
2165
+ this.on("subdocLoaded", configuration.onSubdocLoaded ?? (() => null));
2166
+ this.document.on("subdocs", this.boundHandleYSubdocsChange);
2167
+ this.on("synced", () => this.flushPendingUpdates());
2168
+ this.restorePermissionSnapshot();
2169
+ }
2170
+ authenticatedHandler(scope) {
2171
+ super.authenticatedHandler(scope);
2172
+ this.effectiveRole = scope === "read-write" ? "editor" : "viewer";
2173
+ this.offlineStore?.savePermissionSnapshot(this.effectiveRole);
2174
+ }
2175
+ /**
2176
+ * Override sendToken to send an identity declaration instead of a JWT
2177
+ * when cryptoIdentity is configured.
2178
+ */
2179
+ async sendToken() {
2180
+ const { cryptoIdentity } = this.abracadabraConfig;
2181
+ if (cryptoIdentity) {
2182
+ const id = typeof cryptoIdentity === "function" ? await cryptoIdentity() : cryptoIdentity;
2183
+ const json = JSON.stringify({
2184
+ type: "identity",
2185
+ username: id.username,
2186
+ publicKey: id.publicKey
2187
+ });
2188
+ this.send(AuthenticationMessage, {
2189
+ token: json,
2190
+ documentName: this.configuration.name
2191
+ });
2192
+ } else await super.sendToken();
2193
+ }
2194
+ /** Handle an auth_challenge message from the server. */
2195
+ async handleAuthChallenge(challenge, expiresAt) {
2196
+ const { signChallenge, cryptoIdentity } = this.abracadabraConfig;
2197
+ if (!signChallenge || !cryptoIdentity) {
2198
+ this.permissionDeniedHandler("No signChallenge callback configured");
2199
+ return;
2200
+ }
2201
+ if (Date.now() > expiresAt * 1e3) {
2202
+ this.permissionDeniedHandler("Challenge expired");
2203
+ return;
2204
+ }
2205
+ const id = typeof cryptoIdentity === "function" ? await cryptoIdentity() : cryptoIdentity;
2206
+ const signature = await signChallenge(challenge);
2207
+ const proof = JSON.stringify({
2208
+ type: "proof",
2209
+ username: id.username,
2210
+ publicKey: id.publicKey,
2211
+ signature,
2212
+ challenge
2213
+ });
2214
+ this.send(AuthenticationMessage, {
2215
+ token: proof,
2216
+ documentName: this.configuration.name
2217
+ });
2218
+ }
2219
+ async restorePermissionSnapshot() {
2220
+ if (!this.offlineStore) return;
2221
+ const role = await this.offlineStore.getPermissionSnapshot();
2222
+ if (role && !this.effectiveRole) this.effectiveRole = role;
2223
+ }
2224
+ get canWrite() {
2225
+ return this.effectiveRole === "owner" || this.effectiveRole === "editor";
2226
+ }
2227
+ /**
2228
+ * Called when a MSG_STATELESS frame arrives from the server.
2229
+ * Abracadabra uses stateless frames to deliver subdoc confirmations
2230
+ * ({ type: "subdoc_registered", child_id, parent_id }).
2231
+ */
2232
+ receiveStateless(payload) {
2233
+ let parsed;
2234
+ try {
2235
+ parsed = JSON.parse(payload);
2236
+ } catch {
2237
+ super.receiveStateless(payload);
2238
+ return;
2239
+ }
2240
+ const msg = parsed;
2241
+ if (msg.type === "auth_challenge" && msg.challenge && msg.expiresAt) {
2242
+ this.handleAuthChallenge(msg.challenge, msg.expiresAt).catch(() => null);
2243
+ return;
2244
+ }
2245
+ if (msg.type === "subdoc_registered" && msg.child_id && msg.parent_id) {
2246
+ const event = {
2247
+ childId: msg.child_id,
2248
+ parentId: msg.parent_id
2249
+ };
2250
+ this.emit("subdocRegistered", event);
2251
+ this.offlineStore?.removeSubdocFromQueue(msg.child_id);
2252
+ if (this.subdocLoading === "eager") this.loadChild(msg.child_id);
2253
+ return;
2254
+ }
2255
+ super.receiveStateless(payload);
2256
+ }
2257
+ /**
2258
+ * Y.Doc emits 'subdocs' whenever subdocuments are added, removed, or loaded.
2259
+ * We intercept additions to register them with the Abracadabra server.
2260
+ */
2261
+ handleYSubdocsChange({ added, removed }) {
2262
+ for (const subdoc of added) this.registerSubdoc(subdoc);
2263
+ for (const subdoc of removed) this.unloadChild(subdoc.guid);
2264
+ }
2265
+ /**
2266
+ * Send a subdoc registration frame to the server.
2267
+ * If offline the event is queued in IndexedDB and replayed on reconnect.
2268
+ */
2269
+ registerSubdoc(subdoc) {
2270
+ const childId = subdoc.guid;
2271
+ if (this.isConnected) this.send(SubdocMessage, {
2272
+ documentName: this.configuration.name,
2273
+ childDocumentName: childId
2274
+ });
2275
+ else this.offlineStore?.queueSubdoc({
2276
+ childId,
2277
+ parentId: this.configuration.name,
2278
+ createdAt: Date.now()
2279
+ });
2280
+ }
2281
+ /**
2282
+ * Create (or return cached) a child AbracadabraProvider for a given
2283
+ * child document id. The child shares the parent's WebSocket connection.
2284
+ */
2285
+ async loadChild(childId) {
2286
+ if (this.childProviders.has(childId)) return this.childProviders.get(childId);
2287
+ const childDoc = new Y.Doc({ guid: childId });
2288
+ const parentWsp = this.configuration.websocketProvider;
2289
+ const childProvider = new AbracadabraProvider({
2290
+ name: childId,
2291
+ document: childDoc,
2292
+ url: parentWsp.configuration.url,
2293
+ WebSocketPolyfill: parentWsp.configuration.WebSocketPolyfill,
2294
+ token: this.configuration.token,
2295
+ subdocLoading: this.subdocLoading,
2296
+ disableOfflineStore: this.abracadabraConfig.disableOfflineStore
2297
+ });
2298
+ this.childProviders.set(childId, childProvider);
2299
+ this.emit("subdocLoaded", {
2300
+ childId,
2301
+ provider: childProvider
2302
+ });
2303
+ return childProvider;
2304
+ }
2305
+ unloadChild(childId) {
2306
+ const provider = this.childProviders.get(childId);
2307
+ if (provider) {
2308
+ provider.destroy();
2309
+ this.childProviders.delete(childId);
2310
+ }
2311
+ }
2312
+ /** Return all currently-loaded child providers. */
2313
+ get children() {
2314
+ return this.childProviders;
2315
+ }
2316
+ /**
2317
+ * Override to persist every local update to IndexedDB before sending it
2318
+ * over the wire, ensuring no work is lost during connection outages.
2319
+ */
2320
+ documentUpdateHandler(update, origin) {
2321
+ if (origin === this) return;
2322
+ this.offlineStore?.persistUpdate(update).catch(() => null);
2323
+ super.documentUpdateHandler(update, origin);
2324
+ }
2325
+ /**
2326
+ * After reconnect + sync, flush any updates that were generated while
2327
+ * offline, then flush any queued subdoc registrations.
2328
+ */
2329
+ async flushPendingUpdates() {
2330
+ if (!this.offlineStore) return;
2331
+ const updates = await this.offlineStore.getPendingUpdates();
2332
+ if (updates.length > 0) {
2333
+ for (const update of updates) this.send(UpdateMessage, {
2334
+ update,
2335
+ documentName: this.configuration.name
2336
+ });
2337
+ await this.offlineStore.clearPendingUpdates();
2338
+ }
2339
+ const pendingSubdocs = await this.offlineStore.getPendingSubdocs();
2340
+ for (const { childId } of pendingSubdocs) this.send(SubdocMessage, {
2341
+ documentName: this.configuration.name,
2342
+ childDocumentName: childId
2343
+ });
2344
+ }
2345
+ get isConnected() {
2346
+ return this.configuration.websocketProvider.status === "connected";
2347
+ }
2348
+ destroy() {
2349
+ this.document.off("subdocs", this.boundHandleYSubdocsChange);
2350
+ for (const provider of this.childProviders.values()) provider.destroy();
2351
+ this.childProviders.clear();
2352
+ this.offlineStore?.destroy();
2353
+ this.offlineStore = null;
2354
+ super.destroy();
2355
+ }
2356
+ };
2357
+
2358
+ //#endregion
2359
+ //#region node_modules/@noble/hashes/esm/utils.js
2360
+ /** Checks if something is Uint8Array. Be careful: nodejs Buffer will return true. */
2361
+ function isBytes(a) {
2362
+ return a instanceof Uint8Array || ArrayBuffer.isView(a) && a.constructor.name === "Uint8Array";
2363
+ }
2364
+ /** Asserts something is positive integer. */
2365
+ function anumber(n) {
2366
+ if (!Number.isSafeInteger(n) || n < 0) throw new Error("positive integer expected, got " + n);
2367
+ }
2368
+ /** Asserts something is Uint8Array. */
2369
+ function abytes(b, ...lengths) {
2370
+ if (!isBytes(b)) throw new Error("Uint8Array expected");
2371
+ if (lengths.length > 0 && !lengths.includes(b.length)) throw new Error("Uint8Array expected of length " + lengths + ", got length=" + b.length);
2372
+ }
2373
+ /** Asserts something is hash */
2374
+ function ahash(h) {
2375
+ if (typeof h !== "function" || typeof h.create !== "function") throw new Error("Hash should be wrapped by utils.createHasher");
2376
+ anumber(h.outputLen);
2377
+ anumber(h.blockLen);
2378
+ }
2379
+ /** Asserts a hash instance has not been destroyed / finished */
2380
+ function aexists(instance, checkFinished = true) {
2381
+ if (instance.destroyed) throw new Error("Hash instance has been destroyed");
2382
+ if (checkFinished && instance.finished) throw new Error("Hash#digest() has already been called");
2383
+ }
2384
+ /** Asserts output is properly-sized byte array */
2385
+ function aoutput(out, instance) {
2386
+ abytes(out);
2387
+ const min = instance.outputLen;
2388
+ if (out.length < min) throw new Error("digestInto() expects output buffer of length at least " + min);
2389
+ }
2390
+ /** Zeroize a byte array. Warning: JS provides no guarantees. */
2391
+ function clean(...arrays) {
2392
+ for (let i = 0; i < arrays.length; i++) arrays[i].fill(0);
2393
+ }
2394
+ /** Create DataView of an array for easy byte-level manipulation. */
2395
+ function createView(arr) {
2396
+ return new DataView(arr.buffer, arr.byteOffset, arr.byteLength);
2397
+ }
2398
+ /** The rotate right (circular right shift) operation for uint32 */
2399
+ function rotr(word, shift) {
2400
+ return word << 32 - shift | word >>> shift;
2401
+ }
2402
+ /** Is current platform little-endian? Most are. Big-Endian platform: IBM */
2403
+ const isLE = new Uint8Array(new Uint32Array([287454020]).buffer)[0] === 68;
2404
+ const hasHexBuiltin = typeof Uint8Array.from([]).toHex === "function" && typeof Uint8Array.fromHex === "function";
2405
+ /**
2406
+ * Converts string to bytes using UTF8 encoding.
2407
+ * @example utf8ToBytes('abc') // Uint8Array.from([97, 98, 99])
2408
+ */
2409
+ function utf8ToBytes(str) {
2410
+ if (typeof str !== "string") throw new Error("string expected");
2411
+ return new Uint8Array(new TextEncoder().encode(str));
2412
+ }
2413
+ /**
2414
+ * Normalizes (non-hex) string or Uint8Array to Uint8Array.
2415
+ * Warning: when Uint8Array is passed, it would NOT get copied.
2416
+ * Keep in mind for future mutable operations.
2417
+ */
2418
+ function toBytes(data) {
2419
+ if (typeof data === "string") data = utf8ToBytes(data);
2420
+ abytes(data);
2421
+ return data;
2422
+ }
2423
+ /** For runtime check if class implements interface */
2424
+ var Hash = class {};
2425
+ /** Wraps hash function, creating an interface on top of it */
2426
+ function createHasher(hashCons) {
2427
+ const hashC = (msg) => hashCons().update(toBytes(msg)).digest();
2428
+ const tmp = hashCons();
2429
+ hashC.outputLen = tmp.outputLen;
2430
+ hashC.blockLen = tmp.blockLen;
2431
+ hashC.create = () => hashCons();
2432
+ return hashC;
2433
+ }
2434
+
2435
+ //#endregion
2436
+ //#region node_modules/@noble/hashes/esm/hmac.js
2437
+ /**
2438
+ * HMAC: RFC2104 message authentication code.
2439
+ * @module
2440
+ */
2441
+ var HMAC = class extends Hash {
2442
+ constructor(hash, _key) {
2443
+ super();
2444
+ this.finished = false;
2445
+ this.destroyed = false;
2446
+ ahash(hash);
2447
+ const key = toBytes(_key);
2448
+ this.iHash = hash.create();
2449
+ if (typeof this.iHash.update !== "function") throw new Error("Expected instance of class which extends utils.Hash");
2450
+ this.blockLen = this.iHash.blockLen;
2451
+ this.outputLen = this.iHash.outputLen;
2452
+ const blockLen = this.blockLen;
2453
+ const pad = new Uint8Array(blockLen);
2454
+ pad.set(key.length > blockLen ? hash.create().update(key).digest() : key);
2455
+ for (let i = 0; i < pad.length; i++) pad[i] ^= 54;
2456
+ this.iHash.update(pad);
2457
+ this.oHash = hash.create();
2458
+ for (let i = 0; i < pad.length; i++) pad[i] ^= 106;
2459
+ this.oHash.update(pad);
2460
+ clean(pad);
2461
+ }
2462
+ update(buf) {
2463
+ aexists(this);
2464
+ this.iHash.update(buf);
2465
+ return this;
2466
+ }
2467
+ digestInto(out) {
2468
+ aexists(this);
2469
+ abytes(out, this.outputLen);
2470
+ this.finished = true;
2471
+ this.iHash.digestInto(out);
2472
+ this.oHash.update(out);
2473
+ this.oHash.digestInto(out);
2474
+ this.destroy();
2475
+ }
2476
+ digest() {
2477
+ const out = new Uint8Array(this.oHash.outputLen);
2478
+ this.digestInto(out);
2479
+ return out;
2480
+ }
2481
+ _cloneInto(to) {
2482
+ to || (to = Object.create(Object.getPrototypeOf(this), {}));
2483
+ const { oHash, iHash, finished, destroyed, blockLen, outputLen } = this;
2484
+ to = to;
2485
+ to.finished = finished;
2486
+ to.destroyed = destroyed;
2487
+ to.blockLen = blockLen;
2488
+ to.outputLen = outputLen;
2489
+ to.oHash = oHash._cloneInto(to.oHash);
2490
+ to.iHash = iHash._cloneInto(to.iHash);
2491
+ return to;
2492
+ }
2493
+ clone() {
2494
+ return this._cloneInto();
2495
+ }
2496
+ destroy() {
2497
+ this.destroyed = true;
2498
+ this.oHash.destroy();
2499
+ this.iHash.destroy();
2500
+ }
2501
+ };
2502
+ /**
2503
+ * HMAC: RFC2104 message authentication code.
2504
+ * @param hash - function that would be used e.g. sha256
2505
+ * @param key - message key
2506
+ * @param message - message data
2507
+ * @example
2508
+ * import { hmac } from '@noble/hashes/hmac';
2509
+ * import { sha256 } from '@noble/hashes/sha2';
2510
+ * const mac1 = hmac(sha256, 'key', 'message');
2511
+ */
2512
+ const hmac = (hash, key, message) => new HMAC(hash, key).update(message).digest();
2513
+ hmac.create = (hash, key) => new HMAC(hash, key);
2514
+
2515
+ //#endregion
2516
+ //#region node_modules/@noble/hashes/esm/hkdf.js
2517
+ /**
2518
+ * HKDF (RFC 5869): extract + expand in one step.
2519
+ * See https://soatok.blog/2021/11/17/understanding-hkdf/.
2520
+ * @module
2521
+ */
2522
+ /**
2523
+ * HKDF-extract from spec. Less important part. `HKDF-Extract(IKM, salt) -> PRK`
2524
+ * Arguments position differs from spec (IKM is first one, since it is not optional)
2525
+ * @param hash - hash function that would be used (e.g. sha256)
2526
+ * @param ikm - input keying material, the initial key
2527
+ * @param salt - optional salt value (a non-secret random value)
2528
+ */
2529
+ function extract(hash, ikm, salt) {
2530
+ ahash(hash);
2531
+ if (salt === void 0) salt = new Uint8Array(hash.outputLen);
2532
+ return hmac(hash, toBytes(salt), toBytes(ikm));
2533
+ }
2534
+ const HKDF_COUNTER = /* @__PURE__ */ Uint8Array.from([0]);
2535
+ const EMPTY_BUFFER = /* @__PURE__ */ Uint8Array.of();
2536
+ /**
2537
+ * HKDF-expand from the spec. The most important part. `HKDF-Expand(PRK, info, L) -> OKM`
2538
+ * @param hash - hash function that would be used (e.g. sha256)
2539
+ * @param prk - a pseudorandom key of at least HashLen octets (usually, the output from the extract step)
2540
+ * @param info - optional context and application specific information (can be a zero-length string)
2541
+ * @param length - length of output keying material in bytes
2542
+ */
2543
+ function expand(hash, prk, info, length = 32) {
2544
+ ahash(hash);
2545
+ anumber(length);
2546
+ const olen = hash.outputLen;
2547
+ if (length > 255 * olen) throw new Error("Length should be <= 255*HashLen");
2548
+ const blocks = Math.ceil(length / olen);
2549
+ if (info === void 0) info = EMPTY_BUFFER;
2550
+ const okm = new Uint8Array(blocks * olen);
2551
+ const HMAC = hmac.create(hash, prk);
2552
+ const HMACTmp = HMAC._cloneInto();
2553
+ const T = new Uint8Array(HMAC.outputLen);
2554
+ for (let counter = 0; counter < blocks; counter++) {
2555
+ HKDF_COUNTER[0] = counter + 1;
2556
+ HMACTmp.update(counter === 0 ? EMPTY_BUFFER : T).update(info).update(HKDF_COUNTER).digestInto(T);
2557
+ okm.set(T, olen * counter);
2558
+ HMAC._cloneInto(HMACTmp);
2559
+ }
2560
+ HMAC.destroy();
2561
+ HMACTmp.destroy();
2562
+ clean(T, HKDF_COUNTER);
2563
+ return okm.slice(0, length);
2564
+ }
2565
+ /**
2566
+ * HKDF (RFC 5869): derive keys from an initial input.
2567
+ * Combines hkdf_extract + hkdf_expand in one step
2568
+ * @param hash - hash function that would be used (e.g. sha256)
2569
+ * @param ikm - input keying material, the initial key
2570
+ * @param salt - optional salt value (a non-secret random value)
2571
+ * @param info - optional context and application specific information (can be a zero-length string)
2572
+ * @param length - length of output keying material in bytes
2573
+ * @example
2574
+ * import { hkdf } from '@noble/hashes/hkdf';
2575
+ * import { sha256 } from '@noble/hashes/sha2';
2576
+ * import { randomBytes } from '@noble/hashes/utils';
2577
+ * const inputKey = randomBytes(32);
2578
+ * const salt = randomBytes(32);
2579
+ * const info = 'application-key';
2580
+ * const hk1 = hkdf(sha256, inputKey, salt, info, 32);
2581
+ */
2582
+ const hkdf = (hash, ikm, salt, info, length) => expand(hash, extract(hash, ikm, salt), info, length);
2583
+
2584
+ //#endregion
2585
+ //#region node_modules/@noble/hashes/esm/_md.js
2586
+ /**
2587
+ * Internal Merkle-Damgard hash utils.
2588
+ * @module
2589
+ */
2590
+ /** Polyfill for Safari 14. https://caniuse.com/mdn-javascript_builtins_dataview_setbiguint64 */
2591
+ function setBigUint64(view, byteOffset, value, isLE) {
2592
+ if (typeof view.setBigUint64 === "function") return view.setBigUint64(byteOffset, value, isLE);
2593
+ const _32n = BigInt(32);
2594
+ const _u32_max = BigInt(4294967295);
2595
+ const wh = Number(value >> _32n & _u32_max);
2596
+ const wl = Number(value & _u32_max);
2597
+ const h = isLE ? 4 : 0;
2598
+ const l = isLE ? 0 : 4;
2599
+ view.setUint32(byteOffset + h, wh, isLE);
2600
+ view.setUint32(byteOffset + l, wl, isLE);
2601
+ }
2602
+ /** Choice: a ? b : c */
2603
+ function Chi(a, b, c) {
2604
+ return a & b ^ ~a & c;
2605
+ }
2606
+ /** Majority function, true if any two inputs is true. */
2607
+ function Maj(a, b, c) {
2608
+ return a & b ^ a & c ^ b & c;
2609
+ }
2610
+ /**
2611
+ * Merkle-Damgard hash construction base class.
2612
+ * Could be used to create MD5, RIPEMD, SHA1, SHA2.
2613
+ */
2614
+ var HashMD = class extends Hash {
2615
+ constructor(blockLen, outputLen, padOffset, isLE) {
2616
+ super();
2617
+ this.finished = false;
2618
+ this.length = 0;
2619
+ this.pos = 0;
2620
+ this.destroyed = false;
2621
+ this.blockLen = blockLen;
2622
+ this.outputLen = outputLen;
2623
+ this.padOffset = padOffset;
2624
+ this.isLE = isLE;
2625
+ this.buffer = new Uint8Array(blockLen);
2626
+ this.view = createView(this.buffer);
2627
+ }
2628
+ update(data) {
2629
+ aexists(this);
2630
+ data = toBytes(data);
2631
+ abytes(data);
2632
+ const { view, buffer, blockLen } = this;
2633
+ const len = data.length;
2634
+ for (let pos = 0; pos < len;) {
2635
+ const take = Math.min(blockLen - this.pos, len - pos);
2636
+ if (take === blockLen) {
2637
+ const dataView = createView(data);
2638
+ for (; blockLen <= len - pos; pos += blockLen) this.process(dataView, pos);
2639
+ continue;
2640
+ }
2641
+ buffer.set(data.subarray(pos, pos + take), this.pos);
2642
+ this.pos += take;
2643
+ pos += take;
2644
+ if (this.pos === blockLen) {
2645
+ this.process(view, 0);
2646
+ this.pos = 0;
2647
+ }
2648
+ }
2649
+ this.length += data.length;
2650
+ this.roundClean();
2651
+ return this;
2652
+ }
2653
+ digestInto(out) {
2654
+ aexists(this);
2655
+ aoutput(out, this);
2656
+ this.finished = true;
2657
+ const { buffer, view, blockLen, isLE } = this;
2658
+ let { pos } = this;
2659
+ buffer[pos++] = 128;
2660
+ clean(this.buffer.subarray(pos));
2661
+ if (this.padOffset > blockLen - pos) {
2662
+ this.process(view, 0);
2663
+ pos = 0;
2664
+ }
2665
+ for (let i = pos; i < blockLen; i++) buffer[i] = 0;
2666
+ setBigUint64(view, blockLen - 8, BigInt(this.length * 8), isLE);
2667
+ this.process(view, 0);
2668
+ const oview = createView(out);
2669
+ const len = this.outputLen;
2670
+ if (len % 4) throw new Error("_sha2: outputLen should be aligned to 32bit");
2671
+ const outLen = len / 4;
2672
+ const state = this.get();
2673
+ if (outLen > state.length) throw new Error("_sha2: outputLen bigger than state");
2674
+ for (let i = 0; i < outLen; i++) oview.setUint32(4 * i, state[i], isLE);
2675
+ }
2676
+ digest() {
2677
+ const { buffer, outputLen } = this;
2678
+ this.digestInto(buffer);
2679
+ const res = buffer.slice(0, outputLen);
2680
+ this.destroy();
2681
+ return res;
2682
+ }
2683
+ _cloneInto(to) {
2684
+ to || (to = new this.constructor());
2685
+ to.set(...this.get());
2686
+ const { blockLen, buffer, length, finished, destroyed, pos } = this;
2687
+ to.destroyed = destroyed;
2688
+ to.finished = finished;
2689
+ to.length = length;
2690
+ to.pos = pos;
2691
+ if (length % blockLen) to.buffer.set(buffer);
2692
+ return to;
2693
+ }
2694
+ clone() {
2695
+ return this._cloneInto();
2696
+ }
2697
+ };
2698
+ /**
2699
+ * Initial SHA-2 state: fractional parts of square roots of first 16 primes 2..53.
2700
+ * Check out `test/misc/sha2-gen-iv.js` for recomputation guide.
2701
+ */
2702
+ /** Initial SHA256 state. Bits 0..32 of frac part of sqrt of primes 2..19 */
2703
+ const SHA256_IV = /* @__PURE__ */ Uint32Array.from([
2704
+ 1779033703,
2705
+ 3144134277,
2706
+ 1013904242,
2707
+ 2773480762,
2708
+ 1359893119,
2709
+ 2600822924,
2710
+ 528734635,
2711
+ 1541459225
2712
+ ]);
2713
+
2714
+ //#endregion
2715
+ //#region node_modules/@noble/hashes/esm/_u64.js
2716
+ /**
2717
+ * Internal helpers for u64. BigUint64Array is too slow as per 2025, so we implement it using Uint32Array.
2718
+ * @todo re-check https://issues.chromium.org/issues/42212588
2719
+ * @module
2720
+ */
2721
+ const U32_MASK64 = /* @__PURE__ */ BigInt(2 ** 32 - 1);
2722
+ const _32n = /* @__PURE__ */ BigInt(32);
2723
+ function fromBig(n, le = false) {
2724
+ if (le) return {
2725
+ h: Number(n & U32_MASK64),
2726
+ l: Number(n >> _32n & U32_MASK64)
2727
+ };
2728
+ return {
2729
+ h: Number(n >> _32n & U32_MASK64) | 0,
2730
+ l: Number(n & U32_MASK64) | 0
2731
+ };
2732
+ }
2733
+ function split(lst, le = false) {
2734
+ const len = lst.length;
2735
+ let Ah = new Uint32Array(len);
2736
+ let Al = new Uint32Array(len);
2737
+ for (let i = 0; i < len; i++) {
2738
+ const { h, l } = fromBig(lst[i], le);
2739
+ [Ah[i], Al[i]] = [h, l];
2740
+ }
2741
+ return [Ah, Al];
2742
+ }
2743
+
2744
+ //#endregion
2745
+ //#region node_modules/@noble/hashes/esm/sha2.js
2746
+ /**
2747
+ * SHA2 hash function. A.k.a. sha256, sha384, sha512, sha512_224, sha512_256.
2748
+ * SHA256 is the fastest hash implementable in JS, even faster than Blake3.
2749
+ * Check out [RFC 4634](https://datatracker.ietf.org/doc/html/rfc4634) and
2750
+ * [FIPS 180-4](https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.180-4.pdf).
2751
+ * @module
2752
+ */
2753
+ /**
2754
+ * Round constants:
2755
+ * First 32 bits of fractional parts of the cube roots of the first 64 primes 2..311)
2756
+ */
2757
+ const SHA256_K = /* @__PURE__ */ Uint32Array.from([
2758
+ 1116352408,
2759
+ 1899447441,
2760
+ 3049323471,
2761
+ 3921009573,
2762
+ 961987163,
2763
+ 1508970993,
2764
+ 2453635748,
2765
+ 2870763221,
2766
+ 3624381080,
2767
+ 310598401,
2768
+ 607225278,
2769
+ 1426881987,
2770
+ 1925078388,
2771
+ 2162078206,
2772
+ 2614888103,
2773
+ 3248222580,
2774
+ 3835390401,
2775
+ 4022224774,
2776
+ 264347078,
2777
+ 604807628,
2778
+ 770255983,
2779
+ 1249150122,
2780
+ 1555081692,
2781
+ 1996064986,
2782
+ 2554220882,
2783
+ 2821834349,
2784
+ 2952996808,
2785
+ 3210313671,
2786
+ 3336571891,
2787
+ 3584528711,
2788
+ 113926993,
2789
+ 338241895,
2790
+ 666307205,
2791
+ 773529912,
2792
+ 1294757372,
2793
+ 1396182291,
2794
+ 1695183700,
2795
+ 1986661051,
2796
+ 2177026350,
2797
+ 2456956037,
2798
+ 2730485921,
2799
+ 2820302411,
2800
+ 3259730800,
2801
+ 3345764771,
2802
+ 3516065817,
2803
+ 3600352804,
2804
+ 4094571909,
2805
+ 275423344,
2806
+ 430227734,
2807
+ 506948616,
2808
+ 659060556,
2809
+ 883997877,
2810
+ 958139571,
2811
+ 1322822218,
2812
+ 1537002063,
2813
+ 1747873779,
2814
+ 1955562222,
2815
+ 2024104815,
2816
+ 2227730452,
2817
+ 2361852424,
2818
+ 2428436474,
2819
+ 2756734187,
2820
+ 3204031479,
2821
+ 3329325298
2822
+ ]);
2823
+ /** Reusable temporary buffer. "W" comes straight from spec. */
2824
+ const SHA256_W = /* @__PURE__ */ new Uint32Array(64);
2825
+ var SHA256 = class extends HashMD {
2826
+ constructor(outputLen = 32) {
2827
+ super(64, outputLen, 8, false);
2828
+ this.A = SHA256_IV[0] | 0;
2829
+ this.B = SHA256_IV[1] | 0;
2830
+ this.C = SHA256_IV[2] | 0;
2831
+ this.D = SHA256_IV[3] | 0;
2832
+ this.E = SHA256_IV[4] | 0;
2833
+ this.F = SHA256_IV[5] | 0;
2834
+ this.G = SHA256_IV[6] | 0;
2835
+ this.H = SHA256_IV[7] | 0;
2836
+ }
2837
+ get() {
2838
+ const { A, B, C, D, E, F, G, H } = this;
2839
+ return [
2840
+ A,
2841
+ B,
2842
+ C,
2843
+ D,
2844
+ E,
2845
+ F,
2846
+ G,
2847
+ H
2848
+ ];
2849
+ }
2850
+ set(A, B, C, D, E, F, G, H) {
2851
+ this.A = A | 0;
2852
+ this.B = B | 0;
2853
+ this.C = C | 0;
2854
+ this.D = D | 0;
2855
+ this.E = E | 0;
2856
+ this.F = F | 0;
2857
+ this.G = G | 0;
2858
+ this.H = H | 0;
2859
+ }
2860
+ process(view, offset) {
2861
+ for (let i = 0; i < 16; i++, offset += 4) SHA256_W[i] = view.getUint32(offset, false);
2862
+ for (let i = 16; i < 64; i++) {
2863
+ const W15 = SHA256_W[i - 15];
2864
+ const W2 = SHA256_W[i - 2];
2865
+ const s0 = rotr(W15, 7) ^ rotr(W15, 18) ^ W15 >>> 3;
2866
+ SHA256_W[i] = (rotr(W2, 17) ^ rotr(W2, 19) ^ W2 >>> 10) + SHA256_W[i - 7] + s0 + SHA256_W[i - 16] | 0;
2867
+ }
2868
+ let { A, B, C, D, E, F, G, H } = this;
2869
+ for (let i = 0; i < 64; i++) {
2870
+ const sigma1 = rotr(E, 6) ^ rotr(E, 11) ^ rotr(E, 25);
2871
+ const T1 = H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i] | 0;
2872
+ const T2 = (rotr(A, 2) ^ rotr(A, 13) ^ rotr(A, 22)) + Maj(A, B, C) | 0;
2873
+ H = G;
2874
+ G = F;
2875
+ F = E;
2876
+ E = D + T1 | 0;
2877
+ D = C;
2878
+ C = B;
2879
+ B = A;
2880
+ A = T1 + T2 | 0;
2881
+ }
2882
+ A = A + this.A | 0;
2883
+ B = B + this.B | 0;
2884
+ C = C + this.C | 0;
2885
+ D = D + this.D | 0;
2886
+ E = E + this.E | 0;
2887
+ F = F + this.F | 0;
2888
+ G = G + this.G | 0;
2889
+ H = H + this.H | 0;
2890
+ this.set(A, B, C, D, E, F, G, H);
2891
+ }
2892
+ roundClean() {
2893
+ clean(SHA256_W);
2894
+ }
2895
+ destroy() {
2896
+ this.set(0, 0, 0, 0, 0, 0, 0, 0);
2897
+ clean(this.buffer);
2898
+ }
2899
+ };
2900
+ const K512 = split([
2901
+ "0x428a2f98d728ae22",
2902
+ "0x7137449123ef65cd",
2903
+ "0xb5c0fbcfec4d3b2f",
2904
+ "0xe9b5dba58189dbbc",
2905
+ "0x3956c25bf348b538",
2906
+ "0x59f111f1b605d019",
2907
+ "0x923f82a4af194f9b",
2908
+ "0xab1c5ed5da6d8118",
2909
+ "0xd807aa98a3030242",
2910
+ "0x12835b0145706fbe",
2911
+ "0x243185be4ee4b28c",
2912
+ "0x550c7dc3d5ffb4e2",
2913
+ "0x72be5d74f27b896f",
2914
+ "0x80deb1fe3b1696b1",
2915
+ "0x9bdc06a725c71235",
2916
+ "0xc19bf174cf692694",
2917
+ "0xe49b69c19ef14ad2",
2918
+ "0xefbe4786384f25e3",
2919
+ "0x0fc19dc68b8cd5b5",
2920
+ "0x240ca1cc77ac9c65",
2921
+ "0x2de92c6f592b0275",
2922
+ "0x4a7484aa6ea6e483",
2923
+ "0x5cb0a9dcbd41fbd4",
2924
+ "0x76f988da831153b5",
2925
+ "0x983e5152ee66dfab",
2926
+ "0xa831c66d2db43210",
2927
+ "0xb00327c898fb213f",
2928
+ "0xbf597fc7beef0ee4",
2929
+ "0xc6e00bf33da88fc2",
2930
+ "0xd5a79147930aa725",
2931
+ "0x06ca6351e003826f",
2932
+ "0x142929670a0e6e70",
2933
+ "0x27b70a8546d22ffc",
2934
+ "0x2e1b21385c26c926",
2935
+ "0x4d2c6dfc5ac42aed",
2936
+ "0x53380d139d95b3df",
2937
+ "0x650a73548baf63de",
2938
+ "0x766a0abb3c77b2a8",
2939
+ "0x81c2c92e47edaee6",
2940
+ "0x92722c851482353b",
2941
+ "0xa2bfe8a14cf10364",
2942
+ "0xa81a664bbc423001",
2943
+ "0xc24b8b70d0f89791",
2944
+ "0xc76c51a30654be30",
2945
+ "0xd192e819d6ef5218",
2946
+ "0xd69906245565a910",
2947
+ "0xf40e35855771202a",
2948
+ "0x106aa07032bbd1b8",
2949
+ "0x19a4c116b8d2d0c8",
2950
+ "0x1e376c085141ab53",
2951
+ "0x2748774cdf8eeb99",
2952
+ "0x34b0bcb5e19b48a8",
2953
+ "0x391c0cb3c5c95a63",
2954
+ "0x4ed8aa4ae3418acb",
2955
+ "0x5b9cca4f7763e373",
2956
+ "0x682e6ff3d6b2b8a3",
2957
+ "0x748f82ee5defb2fc",
2958
+ "0x78a5636f43172f60",
2959
+ "0x84c87814a1f0ab72",
2960
+ "0x8cc702081a6439ec",
2961
+ "0x90befffa23631e28",
2962
+ "0xa4506cebde82bde9",
2963
+ "0xbef9a3f7b2c67915",
2964
+ "0xc67178f2e372532b",
2965
+ "0xca273eceea26619c",
2966
+ "0xd186b8c721c0c207",
2967
+ "0xeada7dd6cde0eb1e",
2968
+ "0xf57d4f7fee6ed178",
2969
+ "0x06f067aa72176fba",
2970
+ "0x0a637dc5a2c898a6",
2971
+ "0x113f9804bef90dae",
2972
+ "0x1b710b35131c471b",
2973
+ "0x28db77f523047d84",
2974
+ "0x32caab7b40c72493",
2975
+ "0x3c9ebe0a15c9bebc",
2976
+ "0x431d67c49c100d4c",
2977
+ "0x4cc5d4becb3e42b6",
2978
+ "0x597f299cfc657e2a",
2979
+ "0x5fcb6fab3ad6faec",
2980
+ "0x6c44198c4a475817"
2981
+ ].map((n) => BigInt(n)));
2982
+ const SHA512_Kh = K512[0];
2983
+ const SHA512_Kl = K512[1];
2984
+ /**
2985
+ * SHA2-256 hash function from RFC 4634.
2986
+ *
2987
+ * It is the fastest JS hash, even faster than Blake3.
2988
+ * To break sha256 using birthday attack, attackers need to try 2^128 hashes.
2989
+ * BTC network is doing 2^70 hashes/sec (2^95 hashes/year) as per 2025.
2990
+ */
2991
+ const sha256$1 = /* @__PURE__ */ createHasher(() => new SHA256());
2992
+
2993
+ //#endregion
2994
+ //#region node_modules/@noble/hashes/esm/sha256.js
2995
+ /**
2996
+ * SHA2-256 a.k.a. sha256. In JS, it is the fastest hash, even faster than Blake3.
2997
+ *
2998
+ * To break sha256 using birthday attack, attackers need to try 2^128 hashes.
2999
+ * BTC network is doing 2^70 hashes/sec (2^95 hashes/year) as per 2025.
3000
+ *
3001
+ * Check out [FIPS 180-4](https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.180-4.pdf).
3002
+ * @module
3003
+ * @deprecated
3004
+ */
3005
+ /** @deprecated Use import from `noble/hashes/sha2` module */
3006
+ const sha256 = sha256$1;
3007
+
3008
+ //#endregion
3009
+ //#region packages/provider/src/CryptoIdentityKeystore.ts
3010
+ /**
3011
+ * CryptoIdentityKeystore
3012
+ *
3013
+ * Per-device Ed25519 keypair, private key protected by WebAuthn PRF + AES-256-GCM.
3014
+ * Stored in IndexedDB under "abracadabra:identity" / "identity" / key "current".
3015
+ *
3016
+ * No private key is ever shared between devices. Each device generates its own
3017
+ * keypair, encrypts the private key with the PRF output from its own WebAuthn
3018
+ * credential, and stores the ciphertext in IndexedDB.
3019
+ *
3020
+ * Dependencies: @noble/ed25519, @noble/hashes (for HKDF)
3021
+ */
3022
+ function toBase64url(bytes) {
3023
+ return btoa(String.fromCharCode(...bytes)).replace(/\+/g, "-").replace(/\//g, "_").replace(/=/g, "");
3024
+ }
3025
+ function fromBase64url(b64) {
3026
+ const padded = b64.replace(/-/g, "+").replace(/_/g, "/");
3027
+ const padLen = (4 - padded.length % 4) % 4;
3028
+ const padded2 = padded + "=".repeat(padLen);
3029
+ return Uint8Array.from(atob(padded2), (c) => c.charCodeAt(0));
3030
+ }
3031
+ const DB_NAME = "abracadabra:identity";
3032
+ const STORE_NAME = "identity";
3033
+ const RECORD_KEY = "current";
3034
+ const HKDF_INFO = new TextEncoder().encode("abracadabra-identity-v1");
3035
+ function openDb() {
3036
+ return new Promise((resolve, reject) => {
3037
+ const req = indexedDB.open(DB_NAME, 1);
3038
+ req.onupgradeneeded = () => {
3039
+ req.result.createObjectStore(STORE_NAME);
3040
+ };
3041
+ req.onsuccess = () => resolve(req.result);
3042
+ req.onerror = () => reject(req.error);
3043
+ });
3044
+ }
3045
+ async function dbGet(db) {
3046
+ return new Promise((resolve, reject) => {
3047
+ const req = db.transaction(STORE_NAME, "readonly").objectStore(STORE_NAME).get(RECORD_KEY);
3048
+ req.onsuccess = () => resolve(req.result);
3049
+ req.onerror = () => reject(req.error);
3050
+ });
3051
+ }
3052
+ async function dbPut(db, value) {
3053
+ return new Promise((resolve, reject) => {
3054
+ const req = db.transaction(STORE_NAME, "readwrite").objectStore(STORE_NAME).put(value, RECORD_KEY);
3055
+ req.onsuccess = () => resolve();
3056
+ req.onerror = () => reject(req.error);
3057
+ });
3058
+ }
3059
+ async function dbDelete(db) {
3060
+ return new Promise((resolve, reject) => {
3061
+ const req = db.transaction(STORE_NAME, "readwrite").objectStore(STORE_NAME).delete(RECORD_KEY);
3062
+ req.onsuccess = () => resolve();
3063
+ req.onerror = () => reject(req.error);
3064
+ });
3065
+ }
3066
+ async function deriveAesKey(prfOutput, salt) {
3067
+ const keyBytes = hkdf(sha256, new Uint8Array(prfOutput), salt, HKDF_INFO, 32);
3068
+ return crypto.subtle.importKey("raw", keyBytes, { name: "AES-GCM" }, false, ["encrypt", "decrypt"]);
3069
+ }
3070
+ var CryptoIdentityKeystore = class {
3071
+ /**
3072
+ * One-time setup for a device: generates an Ed25519 keypair, creates a
3073
+ * WebAuthn credential with PRF extension, encrypts the private key, and
3074
+ * stores everything in IndexedDB.
3075
+ *
3076
+ * Returns the base64url-encoded public key. The caller must register this
3077
+ * key with the server via POST /auth/register (first device) or
3078
+ * POST /auth/keys (additional device).
3079
+ *
3080
+ * @param username - The user's account name.
3081
+ * @param rpId - WebAuthn relying party ID (e.g. "example.com").
3082
+ * @param rpName - Human-readable relying party name.
3083
+ */
3084
+ async register(username, rpId, rpName) {
3085
+ const privateKey = ed.utils.randomPrivateKey();
3086
+ const publicKey = await ed.getPublicKeyAsync(privateKey);
3087
+ const salt = crypto.getRandomValues(new Uint8Array(32));
3088
+ const credential = await navigator.credentials.create({ publicKey: {
3089
+ challenge: crypto.getRandomValues(new Uint8Array(32)),
3090
+ rp: {
3091
+ id: rpId,
3092
+ name: rpName
3093
+ },
3094
+ user: {
3095
+ id: new TextEncoder().encode(username),
3096
+ name: username,
3097
+ displayName: username
3098
+ },
3099
+ pubKeyCredParams: [{
3100
+ alg: -7,
3101
+ type: "public-key"
3102
+ }, {
3103
+ alg: -257,
3104
+ type: "public-key"
3105
+ }],
3106
+ authenticatorSelection: { userVerification: "required" },
3107
+ extensions: { prf: { eval: { first: salt.buffer } } }
3108
+ } });
3109
+ if (!credential) throw new Error("WebAuthn credential creation failed");
3110
+ const prfOutput = credential.getClientExtensionResults()?.prf?.results?.first;
3111
+ if (!prfOutput) throw new Error("WebAuthn PRF extension not available on this authenticator. A PRF-capable authenticator (e.g. platform authenticator with PRF support) is required.");
3112
+ const aesKey = await deriveAesKey(prfOutput, salt);
3113
+ const iv = crypto.getRandomValues(new Uint8Array(12));
3114
+ const encryptedPrivateKey = await crypto.subtle.encrypt({
3115
+ name: "AES-GCM",
3116
+ iv
3117
+ }, aesKey, privateKey);
3118
+ const db = await openDb();
3119
+ await dbPut(db, {
3120
+ username,
3121
+ publicKey: toBase64url(publicKey),
3122
+ encryptedPrivateKey,
3123
+ iv,
3124
+ salt,
3125
+ credentialId: credential.rawId
3126
+ });
3127
+ db.close();
3128
+ return toBase64url(publicKey);
3129
+ }
3130
+ /**
3131
+ * Sign a base64url-encoded challenge using the stored Ed25519 private key.
3132
+ *
3133
+ * This triggers a WebAuthn assertion (biometric / PIN prompt) to unlock the
3134
+ * private key via PRF → HKDF → AES-GCM decryption. The private key is
3135
+ * wiped from memory after signing.
3136
+ *
3137
+ * @param challengeB64 - base64url-encoded challenge bytes from the server.
3138
+ * @returns base64url-encoded Ed25519 signature (64 bytes).
3139
+ */
3140
+ async sign(challengeB64) {
3141
+ const db = await openDb();
3142
+ const stored = await dbGet(db);
3143
+ db.close();
3144
+ if (!stored) throw new Error("No identity stored. Call register() first.");
3145
+ const assertion = await navigator.credentials.get({ publicKey: {
3146
+ challenge: crypto.getRandomValues(new Uint8Array(32)),
3147
+ allowCredentials: [{
3148
+ id: stored.credentialId,
3149
+ type: "public-key"
3150
+ }],
3151
+ userVerification: "required",
3152
+ extensions: { prf: { eval: { first: stored.salt.buffer } } }
3153
+ } });
3154
+ if (!assertion) throw new Error("WebAuthn assertion failed");
3155
+ const prfOutput = assertion.getClientExtensionResults()?.prf?.results?.first;
3156
+ if (!prfOutput) throw new Error("PRF output not available from authenticator");
3157
+ const aesKey = await deriveAesKey(prfOutput, stored.salt);
3158
+ const privateKeyBytes = await crypto.subtle.decrypt({
3159
+ name: "AES-GCM",
3160
+ iv: stored.iv
3161
+ }, aesKey, stored.encryptedPrivateKey);
3162
+ const privateKey = new Uint8Array(privateKeyBytes);
3163
+ const challengeBytes = fromBase64url(challengeB64);
3164
+ const signature = await ed.signAsync(challengeBytes, privateKey);
3165
+ privateKey.fill(0);
3166
+ return toBase64url(signature);
3167
+ }
3168
+ /** Returns the stored base64url public key, or null if no identity exists. */
3169
+ async getPublicKey() {
3170
+ const db = await openDb();
3171
+ const stored = await dbGet(db);
3172
+ db.close();
3173
+ return stored?.publicKey ?? null;
3174
+ }
3175
+ /** Returns the stored username, or null if no identity exists. */
3176
+ async getUsername() {
3177
+ const db = await openDb();
3178
+ const stored = await dbGet(db);
3179
+ db.close();
3180
+ return stored?.username ?? null;
3181
+ }
3182
+ /** Returns true if an identity is stored in IndexedDB. */
3183
+ async hasIdentity() {
3184
+ const db = await openDb();
3185
+ const stored = await dbGet(db);
3186
+ db.close();
3187
+ return stored !== void 0;
3188
+ }
3189
+ /** Remove the stored identity from IndexedDB. */
3190
+ async clear() {
3191
+ const db = await openDb();
3192
+ await dbDelete(db);
3193
+ db.close();
3194
+ }
3195
+ };
3196
+
3197
+ //#endregion
3198
+ export { AbracadabraProvider, AwarenessError, CryptoIdentityKeystore, HocuspocusProvider, HocuspocusProviderWebsocket, MessageType, OfflineStore, SubdocMessage, WebSocketStatus };
3199
+ //# sourceMappingURL=hocuspocus-provider.esm.js.map