@yorozu/utils 0.1.4 → 0.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (74) hide show
  1. package/LICENSE +21 -0
  2. package/arrays/index.d.ts +4 -0
  3. package/arrays/typed/compare.d.ts +3 -0
  4. package/arrays/typed/find.d.ts +10 -0
  5. package/arrays/typed/index.d.ts +4 -0
  6. package/arrays/typed/misc.d.ts +10 -0
  7. package/arrays/typed/types.d.ts +2 -0
  8. package/arrays/u8/concat.d.ts +3 -0
  9. package/arrays/u8/index.d.ts +6 -0
  10. package/arrays/u8/misc.d.ts +3 -0
  11. package/arrays/u8/pool.d.ts +15 -0
  12. package/arrays/u8/reverse.d.ts +2 -0
  13. package/arrays/u8/swap.d.ts +4 -0
  14. package/arrays/u8/xor.d.ts +2 -0
  15. package/async/async-interval.d.ts +16 -0
  16. package/async/async-lock.d.ts +10 -0
  17. package/async/async-queue.d.ts +22 -0
  18. package/async/async-resource.d.ts +41 -0
  19. package/async/condition-variable.d.ts +6 -0
  20. package/async/deferred.d.ts +25 -0
  21. package/async/emitter.d.ts +15 -0
  22. package/async/index.d.ts +11 -0
  23. package/async/pool.d.ts +19 -0
  24. package/async/sleep.d.ts +1 -0
  25. package/async/timers.d.ts +8 -0
  26. package/bigint/bytes.d.ts +2 -0
  27. package/bigint/index.d.ts +2 -0
  28. package/bigint/math.d.ts +10 -0
  29. package/compress/bits.d.ts +5 -0
  30. package/compress/checksum.d.ts +15 -0
  31. package/compress/compress.d.ts +3 -0
  32. package/compress/decompress.d.ts +4 -0
  33. package/compress/deflate.d.ts +22 -0
  34. package/compress/detect.d.ts +2 -0
  35. package/compress/errors.d.ts +24 -0
  36. package/compress/gzip.d.ts +31 -0
  37. package/compress/huffman.d.ts +6 -0
  38. package/compress/index.d.ts +5 -0
  39. package/compress/inflate.d.ts +21 -0
  40. package/compress/types.d.ts +14 -0
  41. package/compress/zlib.d.ts +30 -0
  42. package/encoding/base64.d.ts +6 -0
  43. package/encoding/hex.d.ts +4 -0
  44. package/encoding/index.d.ts +4 -0
  45. package/encoding/utf8.d.ts +3 -0
  46. package/index.d.ts +9 -0
  47. package/index.js +3154 -0
  48. package/iterate/enumerate.d.ts +1 -0
  49. package/iterate/index.d.ts +1 -0
  50. package/misc/assert.d.ts +7 -0
  51. package/misc/composer.d.ts +4 -0
  52. package/misc/guards.d.ts +12 -0
  53. package/misc/index.d.ts +6 -0
  54. package/misc/noop.d.ts +1 -0
  55. package/misc/objects.d.ts +18 -0
  56. package/misc/string.d.ts +4 -0
  57. package/package.json +15 -17
  58. package/structures/_iterator.d.ts +2 -0
  59. package/structures/custom-map.d.ts +21 -0
  60. package/structures/custom-set.d.ts +25 -0
  61. package/structures/deque.d.ts +34 -0
  62. package/structures/index.d.ts +5 -0
  63. package/structures/lru-map.d.ts +15 -0
  64. package/structures/lru-set.d.ts +12 -0
  65. package/types/brand.d.ts +5 -0
  66. package/types/equal.d.ts +1 -0
  67. package/types/error.d.ts +6 -0
  68. package/types/index.d.ts +5 -0
  69. package/types/misc.d.ts +11 -0
  70. package/types/unions.d.ts +3 -0
  71. package/lib/index.cjs +0 -2044
  72. package/lib/index.d.cts +0 -468
  73. package/lib/index.d.ts +0 -468
  74. package/lib/index.js +0 -1958
package/index.js ADDED
@@ -0,0 +1,3154 @@
1
+ //#region \0rolldown/runtime.js
2
+ var __defProp = Object.defineProperty;
3
+ var __exportAll = (all, no_symbols) => {
4
+ let target = {};
5
+ for (var name in all) __defProp(target, name, {
6
+ get: all[name],
7
+ enumerable: true
8
+ });
9
+ if (!no_symbols) __defProp(target, Symbol.toStringTag, { value: "Module" });
10
+ return target;
11
+ };
12
+ //#endregion
13
+ //#region src/arrays/typed/compare.ts
14
+ function compare(a, b) {
15
+ if (a.length < b.length) return -1;
16
+ if (a.length > b.length) return 1;
17
+ for (let i = 0; i < a.length; i++) {
18
+ if (a[i] < b[i]) return -1;
19
+ if (a[i] > b[i]) return 1;
20
+ }
21
+ return 0;
22
+ }
23
+ function equal(a, b) {
24
+ return compare(a, b) === 0;
25
+ }
26
+ //#endregion
27
+ //#region src/arrays/typed/find.ts
28
+ function indexOf(haystack, needle, start = 0) {
29
+ let length = haystack.length;
30
+ if (start < 0) {
31
+ start += length;
32
+ if (start < 0) start = 0;
33
+ }
34
+ for (let i = start; i < length; i++) if (haystack[i] === needle) return i;
35
+ return -1;
36
+ }
37
+ function lastIndexOf(haystack, needle, start = haystack.length - 1) {
38
+ let length = haystack.length;
39
+ if (start < 0) {
40
+ start += length;
41
+ if (start < 0) return -1;
42
+ } else if (start >= length) start = length - 1;
43
+ for (let i = start; i >= 0; i--) if (haystack[i] === needle) return i;
44
+ return -1;
45
+ }
46
+ function indexOfArray(haystack, needle, start = 0) {
47
+ if (needle.length === 0) return start;
48
+ if (needle.length === 1) return indexOf(haystack, needle[0], start);
49
+ let max = haystack.length - needle.length;
50
+ for (let i = start; i <= max; i++) if (haystack[i] === needle[0]) {
51
+ let j = 1;
52
+ for (; j < needle.length; j++) if (haystack[i + j] !== needle[j]) break;
53
+ if (j === needle.length) return i;
54
+ }
55
+ return -1;
56
+ }
57
+ function lastIndexOfArray(haystack, needle, start = haystack.length - 1) {
58
+ if (needle.length === 0) return start;
59
+ if (needle.length === 1) return lastIndexOf(haystack, needle[0], start);
60
+ let maxStart = haystack.length - needle.length;
61
+ let effectiveStart = start > maxStart ? maxStart : start;
62
+ for (let i = effectiveStart; i >= 0; i--) {
63
+ let j = 0;
64
+ for (; j < needle.length; j++) if (haystack[i + j] !== needle[j]) break;
65
+ if (j === needle.length) return i;
66
+ }
67
+ return -1;
68
+ }
69
+ function includes(haystack, needle) {
70
+ for (let i = 0; i < haystack.length; i++) {
71
+ let value = haystack[i];
72
+ if (value === needle || Number.isNaN(value) && Number.isNaN(needle)) return true;
73
+ }
74
+ return false;
75
+ }
76
+ function includesArray(haystack, needle) {
77
+ return indexOfArray(haystack, needle) !== -1;
78
+ }
79
+ //#endregion
80
+ //#region src/arrays/typed/misc.ts
81
+ function toDataView(buf) {
82
+ return new DataView(buf.buffer, buf.byteOffset, buf.byteLength);
83
+ }
84
+ function view(ctor, buf) {
85
+ let byteLength = buf.byteLength;
86
+ let bytesPerElement = ctor.BYTES_PER_ELEMENT;
87
+ if (byteLength % bytesPerElement !== 0) throw new RangeError(`byteLength (${byteLength}) is not a multiple of ${bytesPerElement} for ${ctor.name}`);
88
+ let length = byteLength / bytesPerElement;
89
+ return new ctor(buf.buffer, buf.byteOffset, length);
90
+ }
91
+ function getPlatformByteOrder() {
92
+ if (getPlatformByteOrder._cachedByteOrder === null) {
93
+ let buffer = /* @__PURE__ */ new ArrayBuffer(2);
94
+ new DataView(buffer).setUint16(0, 4660, true);
95
+ getPlatformByteOrder._cachedByteOrder = new Uint16Array(buffer)[0] === 4660;
96
+ }
97
+ return getPlatformByteOrder._cachedByteOrder ? "little" : "big";
98
+ }
99
+ getPlatformByteOrder._cachedByteOrder = null;
100
+ //#endregion
101
+ //#region src/arrays/typed/index.ts
102
+ var typed_exports = /* @__PURE__ */ __exportAll({
103
+ compare: () => compare,
104
+ equal: () => equal,
105
+ getPlatformByteOrder: () => getPlatformByteOrder,
106
+ includes: () => includes,
107
+ includesArray: () => includesArray,
108
+ indexOf: () => indexOf,
109
+ indexOfArray: () => indexOfArray,
110
+ lastIndexOf: () => lastIndexOf,
111
+ lastIndexOfArray: () => lastIndexOfArray,
112
+ toDataView: () => toDataView,
113
+ view: () => view
114
+ });
115
+ //#endregion
116
+ //#region src/arrays/u8/misc.ts
117
+ var empty$1 = new Uint8Array(0);
118
+ function clone(buf) {
119
+ return new Uint8Array(buf);
120
+ }
121
+ function readNthBit(byte, bit) {
122
+ return (byte & 1 << bit) >> bit;
123
+ }
124
+ //#endregion
125
+ //#region src/arrays/u8/pool.ts
126
+ var BufferPool = class {
127
+ size;
128
+ maxAllocSize;
129
+ _pool;
130
+ _offset = 0;
131
+ constructor(size = 16 * 1024) {
132
+ this.size = size;
133
+ this.maxAllocSize = size >>> 1;
134
+ this._reallocate();
135
+ }
136
+ get _remaining() {
137
+ return this.size - this._offset;
138
+ }
139
+ allocate(size) {
140
+ if (!Number.isInteger(size) || size < 0) throw new RangeError(`Invalid allocation size: ${size}.`);
141
+ if (size === 0) return empty$1;
142
+ if (size > this.maxAllocSize) return new Uint8Array(size);
143
+ if (size > this._remaining) this._reallocate();
144
+ let start = this._offset;
145
+ this._offset += size;
146
+ this._align();
147
+ return new Uint8Array(this._pool, start, size);
148
+ }
149
+ reset() {
150
+ this._reallocate();
151
+ }
152
+ _reallocate() {
153
+ this._pool = new ArrayBuffer(this.size);
154
+ this._offset = 0;
155
+ }
156
+ _align() {
157
+ let misalignment = this._offset & 7;
158
+ if (misalignment !== 0) this._offset += 8 - misalignment;
159
+ }
160
+ };
161
+ var defaultPool = new BufferPool(16 * 1024);
162
+ function setDefaultPool(size) {
163
+ defaultPool = new BufferPool(size);
164
+ }
165
+ function allocate(size) {
166
+ return defaultPool.allocate(size);
167
+ }
168
+ function allocateWith(init) {
169
+ let buf = allocate(init.length);
170
+ buf.set(init);
171
+ return buf;
172
+ }
173
+ //#endregion
174
+ //#region src/arrays/u8/concat.ts
175
+ function concat(bufs) {
176
+ if (bufs.length === 0) return allocate(0);
177
+ if (bufs.length === 1) return bufs[0];
178
+ if (typeof Buffer !== "undefined") {
179
+ let buf = Buffer.concat(bufs);
180
+ return new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength);
181
+ }
182
+ let length = 0;
183
+ for (let i = 0; i < bufs.length; i++) length += bufs[i].length;
184
+ let ret = allocate(length);
185
+ let offset = 0;
186
+ for (let i = 0; i < bufs.length; i++) {
187
+ ret.set(bufs[i], offset);
188
+ offset += bufs[i].length;
189
+ }
190
+ return ret;
191
+ }
192
+ function concat2(a, b) {
193
+ let ret = allocate(a.length + b.length);
194
+ ret.set(a);
195
+ ret.set(b, a.length);
196
+ return ret;
197
+ }
198
+ function concat3(a, b, c) {
199
+ let ret = allocate(a.length + b.length + c.length);
200
+ ret.set(a);
201
+ ret.set(b, a.length);
202
+ ret.set(c, a.length + b.length);
203
+ return ret;
204
+ }
205
+ //#endregion
206
+ //#region src/arrays/u8/reverse.ts
207
+ function reverse(buffer) {
208
+ if (buffer.length < 2) return;
209
+ let left = 0;
210
+ let right = buffer.length - 1;
211
+ while (left < right) {
212
+ let tmp = buffer[left];
213
+ buffer[left] = buffer[right];
214
+ buffer[right] = tmp;
215
+ left++;
216
+ right--;
217
+ }
218
+ }
219
+ function toReversed(buffer) {
220
+ let len = buffer.length;
221
+ if (len === 0) return allocate(0);
222
+ if (len === 1) {
223
+ let result = allocate(1);
224
+ result[0] = buffer[0];
225
+ return result;
226
+ }
227
+ let result = allocate(len);
228
+ let last = len - 1;
229
+ for (let i = 0; i < len; i++) result[i] = buffer[last - i];
230
+ return result;
231
+ }
232
+ //#endregion
233
+ //#region src/arrays/u8/swap.ts
234
+ function swap16(buf) {
235
+ if (buf.length % 2 !== 0) throw new RangeError(`Buffer length must be a multiple of 2`);
236
+ for (let i = 0; i < buf.length; i += 2) {
237
+ let tmp = buf[i];
238
+ buf[i] = buf[i + 1];
239
+ buf[i + 1] = tmp;
240
+ }
241
+ }
242
+ function swap32(buf) {
243
+ if (buf.length % 4 !== 0) throw new RangeError(`Buffer length must be a multiple of 4`);
244
+ for (let i = 0; i < buf.length; i += 4) {
245
+ let tmp = buf[i];
246
+ buf[i] = buf[i + 3];
247
+ buf[i + 3] = tmp;
248
+ tmp = buf[i + 1];
249
+ buf[i + 1] = buf[i + 2];
250
+ buf[i + 2] = tmp;
251
+ }
252
+ }
253
+ function swap64(buf) {
254
+ if (buf.length % 8 !== 0) throw new RangeError(`Buffer length must be a multiple of 8`);
255
+ for (let i = 0; i < buf.length; i += 8) {
256
+ let tmp = buf[i];
257
+ buf[i] = buf[i + 7];
258
+ buf[i + 7] = tmp;
259
+ tmp = buf[i + 1];
260
+ buf[i + 1] = buf[i + 6];
261
+ buf[i + 6] = tmp;
262
+ tmp = buf[i + 2];
263
+ buf[i + 2] = buf[i + 5];
264
+ buf[i + 5] = tmp;
265
+ tmp = buf[i + 3];
266
+ buf[i + 3] = buf[i + 4];
267
+ buf[i + 4] = tmp;
268
+ }
269
+ }
270
+ function swapNibbles(buf) {
271
+ for (let i = 0; i < buf.length; i++) buf[i] = (buf[i] & 240) >> 4 | (buf[i] & 15) << 4;
272
+ }
273
+ //#endregion
274
+ //#region src/arrays/u8/xor.ts
275
+ function xor(data, key) {
276
+ if (key.length < data.length) throw new RangeError(`Key must be at least as long as data (key=${key.length}, data=${data.length})`);
277
+ let ret = allocate(data.length);
278
+ for (let i = 0; i < data.length; i++) ret[i] = data[i] ^ key[i];
279
+ return ret;
280
+ }
281
+ function xorInPlace(data, key) {
282
+ if (key.length < data.length) throw new RangeError(`Key must be at least as long as data (key=${key.length}, data=${data.length})`);
283
+ for (let i = 0; i < data.length; i++) data[i] ^= key[i];
284
+ }
285
+ //#endregion
286
+ //#region src/arrays/u8/index.ts
287
+ var u8_exports = /* @__PURE__ */ __exportAll({
288
+ BufferPool: () => BufferPool,
289
+ allocate: () => allocate,
290
+ allocateWith: () => allocateWith,
291
+ clone: () => clone,
292
+ concat: () => concat,
293
+ concat2: () => concat2,
294
+ concat3: () => concat3,
295
+ empty: () => empty$1,
296
+ readNthBit: () => readNthBit,
297
+ reverse: () => reverse,
298
+ setDefaultPool: () => setDefaultPool,
299
+ swap16: () => swap16,
300
+ swap32: () => swap32,
301
+ swap64: () => swap64,
302
+ swapNibbles: () => swapNibbles,
303
+ toReversed: () => toReversed,
304
+ xor: () => xor,
305
+ xorInPlace: () => xorInPlace
306
+ });
307
+ //#endregion
308
+ //#region src/bigint/math.ts
309
+ function bitLength(n) {
310
+ if (n === 0n) return 0;
311
+ if (n < 0n) n = -n;
312
+ let hex = n.toString(16);
313
+ let len = hex.length;
314
+ let leadingDigit = parseInt(hex[0], 16);
315
+ return (len - 1) * 4 + (32 - Math.clz32(leadingDigit));
316
+ }
317
+ function twoMultiplicity(n) {
318
+ if (n === 0n) return 0n;
319
+ let m = 0n;
320
+ let pow = 1n;
321
+ while (true) {
322
+ if ((n & pow) !== 0n) return m;
323
+ m += 1n;
324
+ pow <<= 1n;
325
+ }
326
+ }
327
+ function min2(a, b) {
328
+ return a < b ? a : b;
329
+ }
330
+ function min(...args) {
331
+ let m = args[0];
332
+ for (let i = 1; i < args.length; i++) if (args[i] < m) m = args[i];
333
+ return m;
334
+ }
335
+ function max2(a, b) {
336
+ return a > b ? a : b;
337
+ }
338
+ function max(...args) {
339
+ let m = args[0];
340
+ for (let i = 1; i < args.length; i++) if (args[i] > m) m = args[i];
341
+ return m;
342
+ }
343
+ function abs(a) {
344
+ return a < 0n ? -a : a;
345
+ }
346
+ function euclideanGcd(a, b) {
347
+ while (b !== 0n) {
348
+ let t = b;
349
+ b = a % b;
350
+ a = t;
351
+ }
352
+ return a < 0n ? -a : a;
353
+ }
354
+ function modPowBinary(base, exp, mod) {
355
+ if (exp < 0n) throw new RangeError("Negative exponent is not supported.");
356
+ if (mod === 1n) return 0n;
357
+ base %= mod;
358
+ if (base < 0n) base += mod;
359
+ let result = 1n;
360
+ while (exp > 0n) {
361
+ if (exp % 2n === 1n) result = result * base % mod;
362
+ exp >>= 1n;
363
+ base = base ** 2n % mod;
364
+ }
365
+ return result;
366
+ }
367
+ function modInv(a, n) {
368
+ let [g, x] = eGcd(toZn(a, n), n);
369
+ if (g !== 1n) throw new RangeError(`${a.toString()} does not have inverse modulo ${n.toString()}`);
370
+ else return toZn(x, n);
371
+ }
372
+ function eGcd(a, b) {
373
+ let x = 0n;
374
+ let y = 1n;
375
+ let u = 1n;
376
+ let v = 0n;
377
+ while (a !== 0n) {
378
+ let q = b / a;
379
+ let r = b % a;
380
+ let m = x - u * q;
381
+ let n = y - v * q;
382
+ b = a;
383
+ a = r;
384
+ x = u;
385
+ y = v;
386
+ u = m;
387
+ v = n;
388
+ }
389
+ return [
390
+ b,
391
+ x,
392
+ y
393
+ ];
394
+ }
395
+ function toZn(a, n) {
396
+ if (typeof a === "number") a = BigInt(a);
397
+ if (typeof n === "number") n = BigInt(n);
398
+ if (n <= 0n) throw new RangeError("n must be greater than 0.");
399
+ let aZn = a % n;
400
+ return aZn < 0n ? aZn + n : aZn;
401
+ }
402
+ //#endregion
403
+ //#region src/bigint/bytes.ts
404
+ function toBytes(value, length = 0, le = false) {
405
+ let bits = bitLength(value < 0n ? ~value : value) + (value < 0n ? 1 : 0);
406
+ let bytes = Math.ceil(bits / 8);
407
+ if (length !== 0 && bytes > length) throw new RangeError(`Value out of bounds: ${bytes.toString()}, ${length.toString()}.`);
408
+ if (length === 0) length = bytes;
409
+ let buf = new ArrayBuffer(length);
410
+ let arr = new Uint8Array(buf);
411
+ let unaligned = length % 8;
412
+ let dv = new DataView(buf, 0, length - unaligned);
413
+ for (let i = 0; i < dv.byteLength; i += 8) {
414
+ dv.setBigUint64(i, value & 18446744073709551615n, true);
415
+ value >>= 64n;
416
+ }
417
+ if (unaligned > 0) for (let i = length - unaligned; i < length; i++) {
418
+ arr[i] = Number(value & 255n);
419
+ value >>= 8n;
420
+ }
421
+ if (!le) arr.reverse();
422
+ return arr;
423
+ }
424
+ function fromBytes(buffer, le = false) {
425
+ if (le) buffer = toReversed(buffer);
426
+ let unaligned = buffer.length % 8;
427
+ let dv = new DataView(buffer.buffer, buffer.byteOffset, buffer.byteLength - unaligned);
428
+ let res = 0n;
429
+ for (let i = 0; i < dv.byteLength; i += 8) res = res << 64n | BigInt(dv.getBigUint64(i, false));
430
+ if (unaligned > 0) for (let i = buffer.length - unaligned; i < buffer.length; i++) res = res << 8n | BigInt(buffer[i]);
431
+ return res;
432
+ }
433
+ //#endregion
434
+ //#region src/encoding/utf8.ts
435
+ var utf8_exports = /* @__PURE__ */ __exportAll({
436
+ decoder: () => decoder,
437
+ encodedLength: () => encodedLength$2,
438
+ encoder: () => encoder
439
+ });
440
+ var encoder = new TextEncoder();
441
+ var decoder = new TextDecoder();
442
+ function encodedLength$2(data) {
443
+ if (typeof Buffer !== "undefined") return Buffer.byteLength(data, "utf8");
444
+ let length = data.length;
445
+ for (let i = length - 1; i >= 0; i--) {
446
+ let code = data.charCodeAt(i);
447
+ if (code > 127 && code <= 2047) length++;
448
+ else if (code > 2047 && code <= 65535) length += 2;
449
+ if (code >= 56320 && code <= 57343 && i > 0) {
450
+ let prev = data.charCodeAt(i - 1);
451
+ if (prev >= 55296 && prev <= 56319) i--;
452
+ }
453
+ }
454
+ return length;
455
+ }
456
+ //#endregion
457
+ //#region src/encoding/base64.ts
458
+ var base64_exports = /* @__PURE__ */ __exportAll({
459
+ decode: () => decode$1,
460
+ decodedLength: () => decodedLength$1,
461
+ encode: () => encode$1,
462
+ encodeLookup: () => encodeLookup,
463
+ encodedLength: () => encodedLength$1,
464
+ lookup: () => lookup
465
+ });
466
+ var alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
467
+ var lookup = /* @__PURE__ */ new Map();
468
+ var encodeLookup = /* @__PURE__ */ new Map();
469
+ for (let i = 0; i < 64; i++) {
470
+ const charCode = alphabet.charCodeAt(i);
471
+ lookup.set(charCode, i);
472
+ encodeLookup.set(i, charCode);
473
+ }
474
+ lookup.set("=".charCodeAt(0), 0);
475
+ lookup.set("-".charCodeAt(0), 62);
476
+ lookup.set("_".charCodeAt(0), 63);
477
+ var HasToBase64 = typeof Uint8Array.prototype.toBase64 === "function";
478
+ function decode$1(data, url = false) {
479
+ if (typeof Uint8Array.fromBase64 === "function") return Uint8Array.fromBase64(data, { alphabet: url ? "base64url" : "base64" });
480
+ data = data.replace(/=+$/g, "");
481
+ let n = data.length;
482
+ let rem = n % 4;
483
+ let k = rem && rem - 1;
484
+ let m = (n >> 2) * 3 + k;
485
+ let encoded = allocate(n + 3);
486
+ encoder.encodeInto(`${data}===`, encoded);
487
+ for (let i = 0, j = 0; i < n; i += 4, j += 3) {
488
+ let a = lookup.get(encoded[i]);
489
+ let b = lookup.get(encoded[i + 1]);
490
+ let c = lookup.get(encoded[i + 2]);
491
+ let d = lookup.get(encoded[i + 3]);
492
+ if (a === void 0 || b === void 0 || c === void 0 || d === void 0) throw new TypeError("Invalid base64 string.", { cause: { data } });
493
+ let x = (a << 18) + (b << 12) + (c << 6) + d;
494
+ encoded[j] = x >> 16;
495
+ encoded[j + 1] = x >> 8 & 255;
496
+ encoded[j + 2] = x & 255;
497
+ }
498
+ return new Uint8Array(encoded.buffer, encoded.byteOffset, m);
499
+ }
500
+ var ToBase64Options = {
501
+ alphabet: "base64",
502
+ omitPadding: false
503
+ };
504
+ var ToBase64UrlOptions = {
505
+ alphabet: "base64url",
506
+ omitPadding: true
507
+ };
508
+ function encode$1(bytes, url = false) {
509
+ if (typeof Buffer !== "undefined") return Buffer.from(bytes).toString(url ? "base64url" : "base64");
510
+ if (HasToBase64) return bytes.toBase64(url ? ToBase64UrlOptions : ToBase64Options);
511
+ let m = bytes.length;
512
+ let k = m % 3;
513
+ let n = Math.floor(m / 3) * 4 + (k && k + 1);
514
+ let encoded = allocate(Math.ceil(m / 3) * 4);
515
+ for (let i = 0, j = 0; j < m; i += 4, j += 3) {
516
+ let y = (bytes[j] << 16) + (bytes[j + 1] << 8) + (bytes[j + 2] | 0);
517
+ encoded[i] = encodeLookup.get(y >> 18);
518
+ encoded[i + 1] = encodeLookup.get(y >> 12 & 63);
519
+ encoded[i + 2] = encodeLookup.get(y >> 6 & 63);
520
+ encoded[i + 3] = encodeLookup.get(y & 63);
521
+ }
522
+ let base64 = decoder.decode(new Uint8Array(encoded.buffer, encoded.byteOffset, n));
523
+ if (url) base64 = base64.replace(/\+/g, "-").replace(/\//g, "_");
524
+ else {
525
+ if (k === 1) base64 += "==";
526
+ if (k === 2) base64 += "=";
527
+ }
528
+ return base64;
529
+ }
530
+ function encodedLength$1(n) {
531
+ return Math.ceil(n / 3) * 4;
532
+ }
533
+ function decodedLength$1(n) {
534
+ let rem = n % 4;
535
+ return (n >> 2) * 3 + (rem && rem - 1);
536
+ }
537
+ //#endregion
538
+ //#region src/encoding/hex.ts
539
+ var hex_exports = /* @__PURE__ */ __exportAll({
540
+ decode: () => decode,
541
+ decodedLength: () => decodedLength,
542
+ encode: () => encode,
543
+ encodedLength: () => encodedLength
544
+ });
545
+ var hexSliceLookupTable = (function() {
546
+ const alphabet = "0123456789abcdef";
547
+ const table = Array.from({ length: 256 });
548
+ for (let i = 0; i < 16; ++i) {
549
+ const i16 = i * 16;
550
+ for (let j = 0; j < 16; ++j) table[i16 + j] = alphabet[i] + alphabet[j];
551
+ }
552
+ return table;
553
+ })();
554
+ var hexCharValueTable = {
555
+ 0: 0,
556
+ 1: 1,
557
+ 2: 2,
558
+ 3: 3,
559
+ 4: 4,
560
+ 5: 5,
561
+ 6: 6,
562
+ 7: 7,
563
+ 8: 8,
564
+ 9: 9,
565
+ a: 10,
566
+ b: 11,
567
+ c: 12,
568
+ d: 13,
569
+ e: 14,
570
+ f: 15,
571
+ A: 10,
572
+ B: 11,
573
+ C: 12,
574
+ D: 13,
575
+ E: 14,
576
+ F: 15
577
+ };
578
+ var HasToHex = typeof Uint8Array.prototype.toHex === "function";
579
+ function encode(buf) {
580
+ if (typeof Buffer !== "undefined") return Buffer.from(buf).toString("hex");
581
+ if (HasToHex) return buf.toHex();
582
+ let out = "";
583
+ for (let i = 0; i < buf.byteLength; ++i) out += hexSliceLookupTable[buf[i]];
584
+ return out;
585
+ }
586
+ function decode(data) {
587
+ if (typeof Uint8Array.fromHex === "function") return Uint8Array.fromHex(data);
588
+ if (data.length % 2 !== 0) throw new TypeError("Invalid hex string.", { cause: { data } });
589
+ let buf = allocate(data.length / 2);
590
+ for (let i = 0; i < buf.length; ++i) {
591
+ let a = hexCharValueTable[data[i * 2]];
592
+ let b = hexCharValueTable[data[i * 2 + 1]];
593
+ if (a === void 0 || b === void 0) throw new TypeError("Invalid hex string.", { cause: { data } });
594
+ buf[i] = a << 4 | b;
595
+ }
596
+ return buf;
597
+ }
598
+ function encodedLength(n) {
599
+ return n * 2;
600
+ }
601
+ function decodedLength(n) {
602
+ return Math.ceil(n / 2);
603
+ }
604
+ //#endregion
605
+ //#region src/iterate/enumerate.ts
606
+ function enumerate(iterable) {
607
+ const iterator = iterable[Symbol.iterator]();
608
+ let idx = 0;
609
+ return {
610
+ [Symbol.iterator]() {
611
+ return this;
612
+ },
613
+ next() {
614
+ let res = iterator.next();
615
+ if (res.done) return res;
616
+ return {
617
+ done: false,
618
+ value: [idx++, res.value]
619
+ };
620
+ }
621
+ };
622
+ }
623
+ //#endregion
624
+ //#region src/misc/assert.ts
625
+ function assert(condition, message) {
626
+ if (!condition) throw new Error(typeof message === "string" ? message : "Assertion failed.", { cause: message });
627
+ }
628
+ function assertHashKey(obj, key) {
629
+ if (!(key in obj)) throw new Error(`Key ${JSON.stringify(key)} not found in object.`, { cause: {
630
+ obj,
631
+ key
632
+ } });
633
+ }
634
+ function unsafeCastType(value) {}
635
+ function assertNotNull(value) {
636
+ if (value == null) throw new Error(`Value is ${value}.`);
637
+ }
638
+ function asNonNull(value) {
639
+ assertNotNull(value);
640
+ return value;
641
+ }
642
+ function assertMatches(str, regex) {
643
+ let match = str.match(regex);
644
+ if (!match) throw new Error(`${JSON.stringify(str)} does not match ${regex}.`, { cause: {
645
+ str,
646
+ regex
647
+ } });
648
+ return match;
649
+ }
650
+ //#endregion
651
+ //#region src/misc/composer.ts
652
+ function composeMiddlewares(middlewares, final) {
653
+ middlewares = middlewares.slice();
654
+ if (final == null) return function(context, next) {
655
+ function dispatch(i, ctx) {
656
+ if (i > middlewares.length) throw new Error("next() called after end");
657
+ return (middlewares[i] ?? next)(ctx, dispatch.bind(null, i + 1));
658
+ }
659
+ return dispatch(0, context);
660
+ };
661
+ middlewares.push(final);
662
+ function dispatch(i, ctx) {
663
+ let fn = middlewares[i];
664
+ return fn(ctx, boundDispatches[i + 1]);
665
+ }
666
+ let boundDispatches = [];
667
+ for (let i = 0; i < middlewares.length; i++) boundDispatches.push(dispatch.bind(null, i));
668
+ return function(context) {
669
+ return boundDispatches[0](context);
670
+ };
671
+ }
672
+ //#endregion
673
+ //#region src/misc/guards.ts
674
+ var isNotUndefined = (val) => val !== void 0;
675
+ var isNotNull = (val) => val !== null;
676
+ var isBoolean = (val) => typeof val === "boolean";
677
+ var isTruthy = (val) => Boolean(val);
678
+ var isFalsy = (val) => !val;
679
+ var isFunction = (val) => typeof val === "function";
680
+ var isNumber = (val) => typeof val === "number";
681
+ var isString = (val) => typeof val === "string";
682
+ var isSymbol = (val) => typeof val === "symbol";
683
+ var isBigInt = (val) => typeof val === "bigint";
684
+ var isObject = (val) => typeof val === "object" && val !== null;
685
+ //#endregion
686
+ //#region src/misc/noop.ts
687
+ function noop() {}
688
+ //#endregion
689
+ //#region src/misc/objects.ts
690
+ function objectKeys(obj) {
691
+ return Object.keys(obj);
692
+ }
693
+ function objectEntries(obj) {
694
+ return Object.entries(obj);
695
+ }
696
+ function clearUndefinedInPlace(obj) {
697
+ for (const key in obj) {
698
+ if (!Object.hasOwn(obj, key)) continue;
699
+ if (obj[key] === void 0) delete obj[key];
700
+ }
701
+ }
702
+ function deepMerge(into, from, options = {}) {
703
+ if (!Array.isArray(from)) from = [from];
704
+ if (from.length === 0) return into;
705
+ const { undefined: undefinedStrategy = "ignore", properties: propertiesStrategy = "replace", arrays: arraysStrategy = "replace", objects: objectsStrategy = "merge" } = options;
706
+ for (let i = 0; i < from.length; i++) {
707
+ const source = from[i];
708
+ for (const key in source) {
709
+ if (!Object.hasOwn(source, key)) continue;
710
+ const value = source[key];
711
+ const existing = into[key];
712
+ if (value === void 0) {
713
+ if (undefinedStrategy === "replace") into[key] = void 0;
714
+ continue;
715
+ }
716
+ if (Array.isArray(value)) {
717
+ if (arraysStrategy === "merge" && Array.isArray(existing)) existing.push(...value);
718
+ else if (arraysStrategy === "ignore" && existing !== void 0) {} else into[key] = [...value];
719
+ continue;
720
+ }
721
+ if (typeof value === "object" && value !== null) {
722
+ if (value instanceof Date || value instanceof Map || value instanceof Set || value instanceof RegExp) {
723
+ if (propertiesStrategy === "ignore" && existing !== void 0) {} else into[key] = value;
724
+ continue;
725
+ }
726
+ if (objectsStrategy === "merge" && typeof existing === "object" && existing !== null) into[key] = deepMerge(existing, value, options);
727
+ else if (objectsStrategy === "ignore" && existing !== void 0) {} else into[key] = { ...value };
728
+ continue;
729
+ }
730
+ if (propertiesStrategy === "ignore" && existing !== void 0) {} else into[key] = value;
731
+ }
732
+ }
733
+ return into;
734
+ }
735
+ //#endregion
736
+ //#region src/misc/string.ts
737
+ function splitOnce(str, separator) {
738
+ let idx = str.indexOf(separator);
739
+ if (idx === -1) throw new RangeError(`Separator not found: ${separator}.`, { cause: {
740
+ str,
741
+ separator
742
+ } });
743
+ return [str.slice(0, idx), str.slice(idx + separator.length)];
744
+ }
745
+ function assertStartsWith(str, prefix) {
746
+ if (!str.startsWith(prefix)) throw new TypeError(`String does not starts with ${prefix}.`, { cause: {
747
+ str,
748
+ prefix
749
+ } });
750
+ }
751
+ function assertEndsWith(str, suffix) {
752
+ if (!str.endsWith(suffix)) throw new TypeError(`String does not ends with ${suffix}.`, { cause: {
753
+ str,
754
+ suffix
755
+ } });
756
+ }
757
+ //#endregion
758
+ //#region src/async/timers.ts
759
+ var timers_exports = /* @__PURE__ */ __exportAll({
760
+ clearInterval: () => clearIntervalWrap,
761
+ clearTimeout: () => clearTimeoutWrap,
762
+ setInterval: () => setIntervalWrap,
763
+ setTimeout: () => setTimeoutWrap
764
+ });
765
+ var setTimeoutWrap = ((...args) => setTimeout(...args));
766
+ var setIntervalWrap = ((...args) => setInterval(...args));
767
+ var clearTimeoutWrap = ((...args) => clearTimeout(...args));
768
+ var clearIntervalWrap = ((...args) => clearInterval(...args));
769
+ //#endregion
770
+ //#region src/async/async-interval.ts
771
+ var AsyncInterval = class {
772
+ _handler;
773
+ _interval;
774
+ _timer;
775
+ _onError = noop;
776
+ _stopped = true;
777
+ _generation = 0;
778
+ _abortController = new AbortController();
779
+ constructor(handler, interval) {
780
+ this._handler = handler;
781
+ this._interval = interval;
782
+ }
783
+ start(after = this._interval) {
784
+ this.stop();
785
+ this._stopped = false;
786
+ let generation = this._generation;
787
+ this._timer = setTimeoutWrap(() => this._onTimeout(generation), after);
788
+ }
789
+ startNow() {
790
+ this.stop();
791
+ this._stopped = false;
792
+ this._onTimeout(this._generation);
793
+ }
794
+ stop() {
795
+ this._generation++;
796
+ this._abortController.abort();
797
+ this._abortController = new AbortController();
798
+ if (this._timer != null) {
799
+ clearTimeoutWrap(this._timer);
800
+ this._timer = void 0;
801
+ }
802
+ this._stopped = true;
803
+ }
804
+ onError(handler) {
805
+ this._onError = handler;
806
+ }
807
+ _onTimeout = (generation) => {
808
+ this._timer = void 0;
809
+ (async () => {
810
+ try {
811
+ await this._handler(this._abortController.signal);
812
+ } catch (err) {
813
+ this._onError(err);
814
+ }
815
+ if (this._stopped || generation !== this._generation) return;
816
+ this._timer = setTimeoutWrap(() => this._onTimeout(generation), this._interval);
817
+ })();
818
+ };
819
+ };
820
+ //#endregion
821
+ //#region src/structures/_iterator.ts
822
+ var _hasIteratorFrom = null;
823
+ function maybeWrapIterator(iter) {
824
+ if (_hasIteratorFrom === null) _hasIteratorFrom = typeof globalThis.Iterator !== "undefined" && "from" in globalThis.Iterator;
825
+ if (_hasIteratorFrom) return globalThis.Iterator.from(iter);
826
+ return iter;
827
+ }
828
+ //#endregion
829
+ //#region src/structures/custom-map.ts
830
+ var CustomMap = class {
831
+ clear;
832
+ _map;
833
+ _mapperTo;
834
+ _mapperFrom;
835
+ constructor(externalToInternal, internalToExternal) {
836
+ this._mapperTo = externalToInternal;
837
+ this._mapperFrom = internalToExternal;
838
+ this.clear = (this._map = /* @__PURE__ */ new Map()).clear.bind(this._map);
839
+ }
840
+ get size() {
841
+ return this._map.size;
842
+ }
843
+ get [Symbol.toStringTag]() {
844
+ return this._map[Symbol.toStringTag];
845
+ }
846
+ getInternalMap() {
847
+ return this._map;
848
+ }
849
+ delete(key) {
850
+ return this._map.delete(this._mapperTo(key));
851
+ }
852
+ forEach(cb, thisArg) {
853
+ return this._map.forEach((value, key) => {
854
+ cb.call(thisArg, value, this._mapperFrom(key), this);
855
+ });
856
+ }
857
+ get(key) {
858
+ return this._map.get(this._mapperTo(key));
859
+ }
860
+ has(key) {
861
+ return this._map.has(this._mapperTo(key));
862
+ }
863
+ set(key, value) {
864
+ this._map.set(this._mapperTo(key), value);
865
+ return this;
866
+ }
867
+ getOrInsert(key, value) {
868
+ if (this._map.getOrInsert) return this._map.getOrInsert(this._mapperTo(key), value);
869
+ let k = this._mapperTo(key);
870
+ if (!this._map.has(k)) this._map.set(k, value);
871
+ return this._map.get(k);
872
+ }
873
+ getOrInsertComputed(key, callback) {
874
+ if (this._map.getOrInsertComputed) return this._map.getOrInsertComputed(this._mapperTo(key), (k) => callback(this._mapperFrom(k)));
875
+ let k = this._mapperTo(key);
876
+ if (!this._map.has(k)) this._map.set(k, callback(key));
877
+ return this._map.get(k);
878
+ }
879
+ entries() {
880
+ let inner = this._map.entries();
881
+ const iterator = {
882
+ [Symbol.iterator]: () => iterator,
883
+ next: () => {
884
+ let { done, value } = inner.next();
885
+ if (done) return {
886
+ done,
887
+ value
888
+ };
889
+ return {
890
+ done,
891
+ value: [this._mapperFrom(value[0]), value[1]]
892
+ };
893
+ }
894
+ };
895
+ return maybeWrapIterator(iterator);
896
+ }
897
+ keys() {
898
+ let inner = this._map.keys();
899
+ const iterator = {
900
+ [Symbol.iterator]: () => iterator,
901
+ next: () => {
902
+ let { done, value } = inner.next();
903
+ if (done) return {
904
+ done,
905
+ value
906
+ };
907
+ return {
908
+ done,
909
+ value: this._mapperFrom(value)
910
+ };
911
+ }
912
+ };
913
+ return maybeWrapIterator(iterator);
914
+ }
915
+ values() {
916
+ let inner = this._map.values();
917
+ const iterator = {
918
+ [Symbol.iterator]: () => iterator,
919
+ next: () => {
920
+ let { done, value } = inner.next();
921
+ if (done) return {
922
+ done,
923
+ value
924
+ };
925
+ return {
926
+ done,
927
+ value
928
+ };
929
+ }
930
+ };
931
+ return maybeWrapIterator(iterator);
932
+ }
933
+ [Symbol.iterator]() {
934
+ return this.entries();
935
+ }
936
+ };
937
+ //#endregion
938
+ //#region src/structures/custom-set.ts
939
+ var CustomSet = class CustomSet {
940
+ clear;
941
+ _set;
942
+ _mapperTo;
943
+ _mapperFrom;
944
+ constructor(externalToInternal, internalToExternal) {
945
+ this._mapperTo = externalToInternal;
946
+ this._mapperFrom = internalToExternal;
947
+ let set = this._set = /* @__PURE__ */ new Set();
948
+ this.clear = set.clear.bind(set);
949
+ }
950
+ get size() {
951
+ return this._set.size;
952
+ }
953
+ get [Symbol.toStringTag]() {
954
+ return this._set[Symbol.toStringTag];
955
+ }
956
+ add(value) {
957
+ this._set.add(this._mapperTo(value));
958
+ return this;
959
+ }
960
+ delete(value) {
961
+ return this._set.delete(this._mapperTo(value));
962
+ }
963
+ forEach(cb, thisArg) {
964
+ this._set.forEach((value) => {
965
+ let mapped = this._mapperFrom(value);
966
+ cb.call(thisArg, mapped, mapped, this);
967
+ });
968
+ }
969
+ has(value) {
970
+ return this._set.has(this._mapperTo(value));
971
+ }
972
+ entries() {
973
+ let inner = this._set.entries();
974
+ const iterator = {
975
+ [Symbol.iterator]: () => iterator,
976
+ next: () => {
977
+ let { done, value } = inner.next();
978
+ if (done) return {
979
+ done,
980
+ value
981
+ };
982
+ let mapped = this._mapperFrom(value[0]);
983
+ return {
984
+ done,
985
+ value: [mapped, mapped]
986
+ };
987
+ }
988
+ };
989
+ return maybeWrapIterator(iterator);
990
+ }
991
+ keys() {
992
+ let inner = this._set.keys();
993
+ const iterator = {
994
+ [Symbol.iterator]: () => iterator,
995
+ next: () => {
996
+ let { done, value } = inner.next();
997
+ if (done) return {
998
+ done,
999
+ value
1000
+ };
1001
+ return {
1002
+ done,
1003
+ value: this._mapperFrom(value)
1004
+ };
1005
+ }
1006
+ };
1007
+ return maybeWrapIterator(iterator);
1008
+ }
1009
+ values() {
1010
+ return this.keys();
1011
+ }
1012
+ union(other) {
1013
+ let newSet = new CustomSet((k) => this._mapperTo(k), (k) => this._mapperFrom(k));
1014
+ this._set.forEach((v) => newSet.add(this._mapperFrom(v)));
1015
+ other.forEach((v) => newSet.add(v));
1016
+ return newSet;
1017
+ }
1018
+ intersection(other) {
1019
+ let newSet = new CustomSet((k) => this._mapperTo(k), (k) => this._mapperFrom(k));
1020
+ this._set.forEach((v) => {
1021
+ let ext = this._mapperFrom(v);
1022
+ if (other.has(ext)) newSet.add(ext);
1023
+ });
1024
+ return newSet;
1025
+ }
1026
+ difference(other) {
1027
+ let newSet = new CustomSet(this._mapperTo, this._mapperFrom);
1028
+ this._set.forEach((v) => {
1029
+ let ext = this._mapperFrom(v);
1030
+ if (!other.has(ext)) newSet.add(ext);
1031
+ });
1032
+ return newSet;
1033
+ }
1034
+ symmetricDifference(other) {
1035
+ let newSet = new CustomSet((k) => this._mapperTo(k), (k) => this._mapperFrom(k));
1036
+ this._set.forEach((v) => {
1037
+ let ext = this._mapperFrom(v);
1038
+ if (!other.has(ext)) newSet.add(ext);
1039
+ });
1040
+ other.forEach((v) => {
1041
+ if (!this.has(v)) newSet.add(v);
1042
+ });
1043
+ return newSet;
1044
+ }
1045
+ isSubsetOf(other) {
1046
+ for (let v of this._set) if (!other.has(this._mapperFrom(v))) return false;
1047
+ return true;
1048
+ }
1049
+ isSupersetOf(other) {
1050
+ for (let v of other) if (!this.has(v)) return false;
1051
+ return true;
1052
+ }
1053
+ isDisjointFrom(other) {
1054
+ for (let v of other) if (this.has(v)) return false;
1055
+ return true;
1056
+ }
1057
+ [Symbol.iterator]() {
1058
+ return this.keys();
1059
+ }
1060
+ getInternalSet() {
1061
+ return this._set;
1062
+ }
1063
+ };
1064
+ //#endregion
1065
+ //#region src/structures/deque.ts
1066
+ var Log2 = Math.log(2);
1067
+ function _nextPowerOf2(n) {
1068
+ if (n <= 4) return 4;
1069
+ return 1 << Math.ceil(Math.log(n) / Log2);
1070
+ }
1071
+ var Deque = class {
1072
+ _list;
1073
+ _head = 0;
1074
+ _tail = 0;
1075
+ _capacityMask = 3;
1076
+ _capacity;
1077
+ _size = 0;
1078
+ constructor(array, options = {}) {
1079
+ this._capacity = options.capacity;
1080
+ if (array) this._fromArray(array);
1081
+ else this._list = new Array(4);
1082
+ }
1083
+ get length() {
1084
+ return this._size;
1085
+ }
1086
+ isEmpty() {
1087
+ return this._size === 0;
1088
+ }
1089
+ at(index) {
1090
+ let i = index;
1091
+ if (i !== (i | 0)) return void 0;
1092
+ let len = this._size;
1093
+ if (i >= len || i < -len) return void 0;
1094
+ if (i < 0) i += len;
1095
+ return this._list[this._head + i & this._capacityMask];
1096
+ }
1097
+ peekFront() {
1098
+ return this.isEmpty() ? void 0 : this._list[this._head];
1099
+ }
1100
+ peekBack() {
1101
+ return this.isEmpty() ? void 0 : this._list[this._tail - 1 + this._list.length & this._capacityMask];
1102
+ }
1103
+ pushFront(item) {
1104
+ if (this._size === this._list.length) this._growArray();
1105
+ this._head = this._head - 1 + this._list.length & this._capacityMask;
1106
+ this._list[this._head] = item;
1107
+ this._size++;
1108
+ if (this._capacity !== void 0 && this._size > this._capacity) this.popBack();
1109
+ return this._size;
1110
+ }
1111
+ pushBack(item) {
1112
+ if (this._size === this._list.length) this._growArray();
1113
+ this._list[this._tail] = item;
1114
+ this._tail = this._tail + 1 & this._capacityMask;
1115
+ this._size++;
1116
+ if (this._capacity !== void 0 && this._size > this._capacity) this.popFront();
1117
+ return this._size;
1118
+ }
1119
+ popFront() {
1120
+ if (this.isEmpty()) return void 0;
1121
+ let item = this._list[this._head];
1122
+ this._list[this._head] = void 0;
1123
+ this._head = this._head + 1 & this._capacityMask;
1124
+ this._size--;
1125
+ if (this._size <= this._list.length / 4 && this._list.length > 4) this._shrinkArray();
1126
+ return item;
1127
+ }
1128
+ popBack() {
1129
+ if (this.isEmpty()) return void 0;
1130
+ this._tail = this._tail - 1 + this._list.length & this._capacityMask;
1131
+ let item = this._list[this._tail];
1132
+ this._list[this._tail] = void 0;
1133
+ this._size--;
1134
+ if (this._size <= this._list.length / 4 && this._list.length > 4) this._shrinkArray();
1135
+ return item;
1136
+ }
1137
+ removeOne(idx) {
1138
+ let len = this._size;
1139
+ if (idx >= len || idx < -len) return void 0;
1140
+ if (idx < 0) idx += len;
1141
+ let realIdx = this._head + idx & this._capacityMask;
1142
+ let item = this._list[realIdx];
1143
+ this._remove(realIdx);
1144
+ return item;
1145
+ }
1146
+ removeBy(predicate) {
1147
+ for (let pos = 0; pos < this._size; pos++) {
1148
+ let i = this._head + pos & this._capacityMask;
1149
+ let item = this._list[i];
1150
+ if (item !== void 0 && predicate(item)) {
1151
+ this._remove(i);
1152
+ return;
1153
+ }
1154
+ }
1155
+ }
1156
+ clear() {
1157
+ this._list = new Array(this._list.length);
1158
+ this._head = 0;
1159
+ this._tail = 0;
1160
+ this._size = 0;
1161
+ }
1162
+ indexOf(item) {
1163
+ for (let pos = 0; pos < this._size; pos++) if (this._list[this._head + pos & this._capacityMask] === item) return pos;
1164
+ return -1;
1165
+ }
1166
+ findIndex(predicate) {
1167
+ for (let pos = 0; pos < this._size; pos++) if (predicate(this._list[this._head + pos & this._capacityMask])) return pos;
1168
+ return -1;
1169
+ }
1170
+ find(predicate) {
1171
+ for (let pos = 0; pos < this._size; pos++) {
1172
+ let item = this._list[this._head + pos & this._capacityMask];
1173
+ if (item !== void 0 && predicate(item)) return item;
1174
+ }
1175
+ }
1176
+ includes(item) {
1177
+ return this.indexOf(item) !== -1;
1178
+ }
1179
+ toArray() {
1180
+ let arr = new Array(this._size);
1181
+ for (let k = 0; k < this._size; k++) arr[k] = this._list[this._head + k & this._capacityMask];
1182
+ return arr;
1183
+ }
1184
+ [Symbol.iterator]() {
1185
+ let pos = 0;
1186
+ return { next: () => {
1187
+ if (pos >= this._size) return {
1188
+ done: true,
1189
+ value: void 0
1190
+ };
1191
+ let value = this._list[this._head + pos & this._capacityMask];
1192
+ pos++;
1193
+ return {
1194
+ done: false,
1195
+ value
1196
+ };
1197
+ } };
1198
+ }
1199
+ _fromArray(array) {
1200
+ let start = 0;
1201
+ let length = array.length;
1202
+ if (this._capacity !== void 0 && length > this._capacity) {
1203
+ start = length - this._capacity;
1204
+ length = this._capacity;
1205
+ }
1206
+ let capacity = _nextPowerOf2(length);
1207
+ this._list = new Array(capacity);
1208
+ this._capacityMask = capacity - 1;
1209
+ this._head = 0;
1210
+ this._tail = length & this._capacityMask;
1211
+ this._size = length;
1212
+ for (let i = 0; i < length; i++) this._list[i] = array[start + i];
1213
+ }
1214
+ _growArray() {
1215
+ let oldMask = this._capacityMask;
1216
+ let oldList = this._list;
1217
+ let oldHead = this._head;
1218
+ let size = this._size;
1219
+ let newList = new Array(oldList.length << 1);
1220
+ for (let i = 0; i < size; i++) newList[i] = oldList[oldHead + i & oldMask];
1221
+ this._list = newList;
1222
+ this._head = 0;
1223
+ this._tail = size;
1224
+ this._capacityMask = newList.length - 1;
1225
+ }
1226
+ _shrinkArray() {
1227
+ if (this._list.length <= 4) return;
1228
+ let oldMask = this._capacityMask;
1229
+ let oldList = this._list;
1230
+ let oldHead = this._head;
1231
+ let size = this._size;
1232
+ let newList = new Array(oldList.length >>> 1);
1233
+ for (let i = 0; i < size; i++) newList[i] = oldList[oldHead + i & oldMask];
1234
+ this._list = newList;
1235
+ this._head = 0;
1236
+ this._tail = size;
1237
+ this._capacityMask = newList.length - 1;
1238
+ }
1239
+ _remove(idx) {
1240
+ let mask = this._capacityMask;
1241
+ let len = this._list.length;
1242
+ let distFromHead = idx - this._head & mask;
1243
+ if (distFromHead < this._size - distFromHead) {
1244
+ let i = idx;
1245
+ while (i !== this._head) {
1246
+ let prev = i - 1 + len & mask;
1247
+ this._list[i] = this._list[prev];
1248
+ i = prev;
1249
+ }
1250
+ this._list[this._head] = void 0;
1251
+ this._head = this._head + 1 & mask;
1252
+ } else {
1253
+ let i = idx;
1254
+ let last = this._tail - 1 + len & mask;
1255
+ while (i !== last) {
1256
+ let next = i + 1 & mask;
1257
+ this._list[i] = this._list[next];
1258
+ i = next;
1259
+ }
1260
+ this._list[last] = void 0;
1261
+ this._tail = last;
1262
+ }
1263
+ this._size--;
1264
+ if (this._size <= this._list.length / 4 && this._list.length > 4) this._shrinkArray();
1265
+ }
1266
+ };
1267
+ //#endregion
1268
+ //#region src/structures/lru-map.ts
1269
+ var LruMap = class {
1270
+ _capacity;
1271
+ _map;
1272
+ constructor(capacity, MapImpl = Map) {
1273
+ this._capacity = capacity;
1274
+ this._map = new MapImpl();
1275
+ }
1276
+ get size() {
1277
+ return this._map.size;
1278
+ }
1279
+ get(key) {
1280
+ if (!this._map.has(key)) return void 0;
1281
+ let value = this._map.get(key);
1282
+ this._map.delete(key);
1283
+ this._map.set(key, value);
1284
+ return value;
1285
+ }
1286
+ has(key) {
1287
+ return this._map.has(key);
1288
+ }
1289
+ set(key, value) {
1290
+ if (this._map.has(key)) this._map.delete(key);
1291
+ this._map.set(key, value);
1292
+ if (this._map.size > this._capacity) {
1293
+ let oldest = this._map.keys().next();
1294
+ if (!oldest.done) this._map.delete(oldest.value);
1295
+ }
1296
+ }
1297
+ delete(key) {
1298
+ this._map.delete(key);
1299
+ }
1300
+ clear() {
1301
+ this._map.clear();
1302
+ }
1303
+ *[Symbol.iterator]() {
1304
+ yield* this._map;
1305
+ }
1306
+ entries() {
1307
+ return this._map.entries();
1308
+ }
1309
+ keys() {
1310
+ return this._map.keys();
1311
+ }
1312
+ values() {
1313
+ return this._map.values();
1314
+ }
1315
+ };
1316
+ //#endregion
1317
+ //#region src/structures/lru-set.ts
1318
+ var LruSet = class {
1319
+ _capacity;
1320
+ _set;
1321
+ constructor(capacity, SetImpl = Set) {
1322
+ this._capacity = capacity;
1323
+ this._set = new SetImpl();
1324
+ }
1325
+ get size() {
1326
+ return this._set.size;
1327
+ }
1328
+ add(value) {
1329
+ if (this._set.has(value)) this._set.delete(value);
1330
+ this._set.add(value);
1331
+ if (this._set.size > this._capacity) {
1332
+ let oldest = this._set.keys().next();
1333
+ if (!oldest.done) this._set.delete(oldest.value);
1334
+ }
1335
+ }
1336
+ has(value) {
1337
+ return this._set.has(value);
1338
+ }
1339
+ delete(value) {
1340
+ return this._set.delete(value);
1341
+ }
1342
+ clear() {
1343
+ this._set.clear();
1344
+ }
1345
+ *[Symbol.iterator]() {
1346
+ yield* this._set;
1347
+ }
1348
+ toArray() {
1349
+ return Array.from(this._set);
1350
+ }
1351
+ };
1352
+ //#endregion
1353
+ //#region src/async/async-lock.ts
1354
+ var AsyncLock = class {
1355
+ _queue = new Deque();
1356
+ async acquire() {
1357
+ let info;
1358
+ while (info = this._queue.peekFront()) await info[0];
1359
+ let unlock;
1360
+ const promise = new Promise((resolve) => {
1361
+ unlock = resolve;
1362
+ });
1363
+ this._queue.pushBack([promise, unlock]);
1364
+ }
1365
+ release() {
1366
+ const front = this._queue.popFront();
1367
+ if (!front) throw new Error("Nothing to release.", { cause: this._queue });
1368
+ front[1]();
1369
+ }
1370
+ with(func) {
1371
+ return (async () => {
1372
+ await this.acquire();
1373
+ try {
1374
+ return await func();
1375
+ } finally {
1376
+ this.release();
1377
+ }
1378
+ })();
1379
+ }
1380
+ };
1381
+ //#endregion
1382
+ //#region src/async/deferred.ts
1383
+ var Deferred = class {
1384
+ resolve;
1385
+ reject;
1386
+ promise;
1387
+ constructor() {
1388
+ this.promise = new Promise((resolve, reject) => {
1389
+ this.resolve = resolve;
1390
+ this.reject = reject;
1391
+ });
1392
+ }
1393
+ };
1394
+ var DeferredTracked = class {
1395
+ promise;
1396
+ status;
1397
+ _resolve;
1398
+ _reject;
1399
+ constructor() {
1400
+ this.status = { type: "pending" };
1401
+ this.promise = new Promise((resolve, reject) => {
1402
+ this._resolve = resolve;
1403
+ this._reject = reject;
1404
+ });
1405
+ }
1406
+ get result() {
1407
+ if (this.status.type === "fulfilled") return this.status.value;
1408
+ }
1409
+ get error() {
1410
+ if (this.status.type === "rejected") return this.status.reason;
1411
+ }
1412
+ resolve(value) {
1413
+ if (this.status.type !== "pending") return;
1414
+ this.status = {
1415
+ type: "fulfilled",
1416
+ value
1417
+ };
1418
+ this._resolve(value);
1419
+ }
1420
+ reject(reason) {
1421
+ if (this.status.type !== "pending") return;
1422
+ this.status = {
1423
+ type: "rejected",
1424
+ reason
1425
+ };
1426
+ this._reject(reason);
1427
+ }
1428
+ };
1429
+ //#endregion
1430
+ //#region src/async/async-queue.ts
1431
+ var AsyncQueue = class {
1432
+ queue;
1433
+ maxSize;
1434
+ _consumerWaiters = new Deque();
1435
+ _producerWaiters = new Deque();
1436
+ _ended = false;
1437
+ constructor(from, maxSize) {
1438
+ if (maxSize !== void 0 && maxSize < 1) throw new Error("maxSize must be at least 1");
1439
+ this.maxSize = maxSize;
1440
+ if (from) if (from instanceof Deque) this.queue = from;
1441
+ else this.queue = new Deque(from);
1442
+ else this.queue = new Deque();
1443
+ if (maxSize !== void 0 && this.queue.length > maxSize) throw new Error("Initial queue length exceeds maxSize");
1444
+ }
1445
+ get length() {
1446
+ return this.queue.length;
1447
+ }
1448
+ get isFull() {
1449
+ return this.maxSize !== void 0 && this.queue.length >= this.maxSize;
1450
+ }
1451
+ get remainingCapacity() {
1452
+ return this.maxSize !== void 0 ? this.maxSize - this.queue.length : Infinity;
1453
+ }
1454
+ get ended() {
1455
+ return this._ended;
1456
+ }
1457
+ async enqueue(item) {
1458
+ if (this._ended) throw new Error("Cannot enqueue after .end() has been called");
1459
+ while (true) {
1460
+ if (this._consumerWaiters.length > 0) {
1461
+ this._consumerWaiters.popFront().resolve(item);
1462
+ return;
1463
+ }
1464
+ if (!this.isFull) {
1465
+ this.queue.pushBack(item);
1466
+ return;
1467
+ }
1468
+ let waiter = new Deferred();
1469
+ this._producerWaiters.pushBack(waiter);
1470
+ await waiter.promise;
1471
+ if (this._ended) throw new Error("Queue was ended while waiting to enqueue.");
1472
+ }
1473
+ }
1474
+ tryEnqueue(item) {
1475
+ if (this._ended || this.isFull) return false;
1476
+ if (this._consumerWaiters.length > 0) {
1477
+ this._consumerWaiters.popFront().resolve(item);
1478
+ return true;
1479
+ }
1480
+ this.queue.pushBack(item);
1481
+ return true;
1482
+ }
1483
+ end() {
1484
+ if (this._ended) throw new Error(".end() has already been called.");
1485
+ this._ended = true;
1486
+ for (let waiter of this._consumerWaiters) waiter.resolve(void 0);
1487
+ this._consumerWaiters.clear();
1488
+ let err = /* @__PURE__ */ new Error("Queue has been ended.");
1489
+ for (let waiter of this._producerWaiters) waiter.reject(err);
1490
+ this._producerWaiters.clear();
1491
+ }
1492
+ peek() {
1493
+ return this.queue.peekFront();
1494
+ }
1495
+ next() {
1496
+ if (this.queue.length === 0) return void 0;
1497
+ let item = this.queue.popFront();
1498
+ this._wakeProducerIfNeeded();
1499
+ return item;
1500
+ }
1501
+ async nextOrWait() {
1502
+ if (this.queue.length > 0) {
1503
+ let item = this.queue.popFront();
1504
+ this._wakeProducerIfNeeded();
1505
+ return item;
1506
+ }
1507
+ if (this._ended) return;
1508
+ let waiter = new Deferred();
1509
+ this._consumerWaiters.pushBack(waiter);
1510
+ return waiter.promise;
1511
+ }
1512
+ [Symbol.asyncIterator]() {
1513
+ let iterator = {
1514
+ [Symbol.asyncIterator]: () => iterator,
1515
+ next: async () => {
1516
+ let item = await this.nextOrWait();
1517
+ if (item === void 0) return {
1518
+ done: true,
1519
+ value: void 0
1520
+ };
1521
+ return {
1522
+ value: item,
1523
+ done: false
1524
+ };
1525
+ }
1526
+ };
1527
+ return iterator;
1528
+ }
1529
+ _wakeProducerIfNeeded() {
1530
+ if (this._producerWaiters.length > 0 && !this.isFull) this._producerWaiters.popFront().resolve();
1531
+ }
1532
+ };
1533
+ //#endregion
1534
+ //#region src/async/emitter.ts
1535
+ var Emitter = class {
1536
+ _listeners = [];
1537
+ _emit = noop;
1538
+ get length() {
1539
+ return this._listeners.length;
1540
+ }
1541
+ add(listener) {
1542
+ this._listeners.push(listener);
1543
+ this._updateEmit();
1544
+ }
1545
+ forwardTo(emitter) {
1546
+ this.add(emitter.emit.bind(emitter));
1547
+ }
1548
+ remove(listener) {
1549
+ let idx = this._listeners.indexOf(listener);
1550
+ if (idx === -1) return;
1551
+ this._listeners.splice(idx, 1);
1552
+ this._updateEmit();
1553
+ }
1554
+ emit(value) {
1555
+ this._emit(value);
1556
+ }
1557
+ once(listener) {
1558
+ const once = (value) => {
1559
+ this.remove(once);
1560
+ listener(value);
1561
+ };
1562
+ this.add(once);
1563
+ }
1564
+ listeners() {
1565
+ return this._listeners;
1566
+ }
1567
+ clear() {
1568
+ this._listeners.length = 0;
1569
+ this._emit = noop;
1570
+ }
1571
+ _emitFew = (value) => {
1572
+ let listeners = this._listeners.slice();
1573
+ let len = listeners.length;
1574
+ listeners[0](value);
1575
+ len > 1 && listeners[1](value);
1576
+ len > 2 && listeners[2](value);
1577
+ len > 3 && listeners[3](value);
1578
+ len > 4 && listeners[4](value);
1579
+ };
1580
+ _emitAll = (value) => {
1581
+ let listeners = this._listeners.slice();
1582
+ for (let i = 0; i < listeners.length; i++) listeners[i](value);
1583
+ };
1584
+ _updateEmit = () => {
1585
+ let len = this._listeners.length;
1586
+ if (len === 0) this._emit = noop;
1587
+ else if (len <= 5) this._emit = this._emitFew;
1588
+ else this._emit = this._emitAll;
1589
+ };
1590
+ };
1591
+ //#endregion
1592
+ //#region src/async/async-resource.ts
1593
+ var AsyncResource = class {
1594
+ onUpdated = new Emitter();
1595
+ _abort;
1596
+ _ctx;
1597
+ _updating;
1598
+ _timeout;
1599
+ _destroyed = false;
1600
+ constructor(options) {
1601
+ this.options = options;
1602
+ this._ctx = {
1603
+ current: null,
1604
+ currentFetchedAt: 0,
1605
+ currentExpiresAt: 0,
1606
+ isBackground: false,
1607
+ abort: null
1608
+ };
1609
+ }
1610
+ get isStale() {
1611
+ return this._ctx.current === null || this._ctx.currentExpiresAt <= performance.now();
1612
+ }
1613
+ setData(data, expiresIn) {
1614
+ if (this._destroyed) return;
1615
+ let now = performance.now();
1616
+ this._ctx.current = data;
1617
+ this._ctx.currentExpiresAt = now + expiresIn;
1618
+ this._ctx.currentFetchedAt = now;
1619
+ this.onUpdated.emit(this._ctx);
1620
+ if (this.options.autoReload) {
1621
+ this._clearTimer();
1622
+ this._timeout = setTimeoutWrap(() => {
1623
+ if (this._destroyed) return;
1624
+ this._ctx.isBackground = true;
1625
+ this.update(true).catch(noop);
1626
+ }, expiresIn + (this.options.autoReloadAfter ?? this.options.authReloadAfter ?? 0));
1627
+ }
1628
+ }
1629
+ async update(force = false) {
1630
+ if (this._destroyed) return;
1631
+ if (this._updating) {
1632
+ await this._updating.promise;
1633
+ return;
1634
+ }
1635
+ if (!force && !this.isStale) return;
1636
+ this._abort?.abort();
1637
+ this._abort = new AbortController();
1638
+ this._ctx.abort = this._abort.signal;
1639
+ this._updating = new Deferred();
1640
+ let result;
1641
+ try {
1642
+ result = await this.options.fetcher(this._ctx);
1643
+ } catch (err) {
1644
+ if (err instanceof Error && err.name === "AbortError") {
1645
+ this._updating?.resolve();
1646
+ this._updating = void 0;
1647
+ this._ctx.abort = null;
1648
+ return;
1649
+ }
1650
+ if (this.options.onError) this.options.onError(err, this._ctx);
1651
+ else console.error(err);
1652
+ this._updating?.resolve();
1653
+ this._updating = void 0;
1654
+ this._ctx.abort = null;
1655
+ return;
1656
+ }
1657
+ this._updating?.resolve();
1658
+ this._updating = void 0;
1659
+ this._ctx.abort = null;
1660
+ if (!this._destroyed) this.setData(result.data, result.expiresIn);
1661
+ }
1662
+ async get() {
1663
+ if (this._destroyed) return null;
1664
+ if (this.options.swr === true && this._ctx.current !== null) {
1665
+ let validator = this.options.swrValidator;
1666
+ if (!validator || validator(this._ctx)) {
1667
+ this._ctx.isBackground = true;
1668
+ this.update(true).catch(noop);
1669
+ return this._ctx.current;
1670
+ }
1671
+ }
1672
+ this._ctx.isBackground = false;
1673
+ await this.update();
1674
+ return this._ctx.current;
1675
+ }
1676
+ getCached() {
1677
+ return this._ctx.current;
1678
+ }
1679
+ destroy() {
1680
+ if (this._destroyed) return;
1681
+ this._destroyed = true;
1682
+ this._clearTimer();
1683
+ this._abort?.abort();
1684
+ this.onUpdated.clear();
1685
+ this._updating?.resolve();
1686
+ this._updating = void 0;
1687
+ }
1688
+ _clearTimer() {
1689
+ if (this._timeout) {
1690
+ clearTimeoutWrap(this._timeout);
1691
+ this._timeout = void 0;
1692
+ }
1693
+ }
1694
+ };
1695
+ //#endregion
1696
+ //#region src/async/condition-variable.ts
1697
+ var ConditionVariable = class {
1698
+ _resolvers = [];
1699
+ wait() {
1700
+ return new Promise((resolve) => {
1701
+ this._resolvers.push(resolve);
1702
+ });
1703
+ }
1704
+ notify() {
1705
+ let resolvers = this._resolvers;
1706
+ this._resolvers = [];
1707
+ for (let resolve of resolvers) resolve();
1708
+ }
1709
+ };
1710
+ //#endregion
1711
+ //#region src/async/pool.ts
1712
+ var ErrorInfo = class {
1713
+ constructor(item, index, error) {
1714
+ this.item = item;
1715
+ this.index = index;
1716
+ this.error = error;
1717
+ }
1718
+ };
1719
+ var AggregateError = class extends Error {
1720
+ constructor(errors) {
1721
+ super(`AggregateError: ${errors.length} errors`);
1722
+ this.errors = errors;
1723
+ }
1724
+ };
1725
+ async function asyncPool(iterable, executor, options = {}) {
1726
+ let { limit = 16, signal, onErrorStrategy } = options;
1727
+ if (limit <= 0) throw new RangeError(`Pool limit must be a positive integer.`);
1728
+ if (signal?.aborted) throw signal.reason;
1729
+ let iterator = iterable[Symbol.asyncIterator]?.() ?? iterable[Symbol.iterator]?.();
1730
+ if (!iterator) throw new TypeError(`iterable must be iterable`);
1731
+ let idx = 0;
1732
+ let errors = [];
1733
+ let abortController = new AbortController();
1734
+ let abortSignal = signal ? AbortSignal.any([signal, abortController.signal]) : abortController.signal;
1735
+ async function worker() {
1736
+ while (true) {
1737
+ if (abortSignal.aborted) return;
1738
+ let result;
1739
+ try {
1740
+ result = await iterator.next();
1741
+ } catch (e) {
1742
+ abortController.abort(e);
1743
+ return;
1744
+ }
1745
+ if (result.done) return;
1746
+ if (abortSignal.aborted) return;
1747
+ let item = result.value;
1748
+ let thisIdx = idx++;
1749
+ try {
1750
+ await executor(item, thisIdx);
1751
+ } catch (err) {
1752
+ let action = onErrorStrategy?.(item, thisIdx, err) ?? "throw";
1753
+ if (action instanceof Promise) action = await action;
1754
+ if (action === "ignore") continue;
1755
+ if (action === "collect") {
1756
+ errors.push(new ErrorInfo(item, thisIdx, err));
1757
+ continue;
1758
+ }
1759
+ abortController.abort(err);
1760
+ return;
1761
+ }
1762
+ }
1763
+ }
1764
+ await Promise.all(Array.from({ length: limit }, worker));
1765
+ if (abortSignal.aborted) throw abortSignal.reason;
1766
+ if (errors.length > 0) throw new AggregateError(errors);
1767
+ }
1768
+ async function parallelMap(iterable, executor, options = {}) {
1769
+ let result = [];
1770
+ if (Array.isArray(iterable)) result.length = iterable.length;
1771
+ await asyncPool(iterable, async (item, index) => {
1772
+ result[index] = await executor(item, index);
1773
+ }, options);
1774
+ return result;
1775
+ }
1776
+ //#endregion
1777
+ //#region src/async/sleep.ts
1778
+ function sleep(ms, signal) {
1779
+ if (ms < 0) throw new RangeError("sleep: ms must be a non-negative number");
1780
+ return new Promise((resolve, reject) => {
1781
+ if (signal?.aborted) {
1782
+ reject(signal.reason ?? new DOMException("The operation was aborted.", "AbortError"));
1783
+ return;
1784
+ }
1785
+ let onAbort = () => {
1786
+ clearTimeout(timeoutId);
1787
+ reject(signal.reason ?? new DOMException("The operation was aborted.", "AbortError"));
1788
+ };
1789
+ let timeoutId = setTimeout(() => {
1790
+ signal?.removeEventListener("abort", onAbort);
1791
+ resolve();
1792
+ }, ms);
1793
+ signal?.addEventListener("abort", onAbort, { once: true });
1794
+ });
1795
+ }
1796
+ //#endregion
1797
+ //#region src/types/error.ts
1798
+ function unknownToError(err) {
1799
+ if (err instanceof Error) return err;
1800
+ if (typeof err === "string") return new Error(err);
1801
+ let error = "";
1802
+ try {
1803
+ error = JSON.stringify(err);
1804
+ } catch (_) {}
1805
+ return new Error(error, { cause: err });
1806
+ }
1807
+ var NotImplementedError = class extends Error {
1808
+ constructor(message, options = {}) {
1809
+ super(`Not implemented${message != null ? `: ${message}` : ""}`, options);
1810
+ }
1811
+ };
1812
+ function throwNotImplemented(message, options) {
1813
+ throw new NotImplementedError(message, options);
1814
+ }
1815
+ function throwUnreachable() {
1816
+ throw new Error("Unreachable");
1817
+ }
1818
+ //#endregion
1819
+ //#region src/compress/checksum.ts
1820
+ var crcTable = new Int32Array(256);
1821
+ for (let i = 0; i < 256; i++) {
1822
+ let c = i;
1823
+ for (let k = 0; k < 8; k++) c = (c & 1 ? -306674912 : 0) ^ c >>> 1;
1824
+ crcTable[i] = c;
1825
+ }
1826
+ var Crc32 = class {
1827
+ _c;
1828
+ constructor(seed = 0) {
1829
+ this._c = ~seed;
1830
+ }
1831
+ update(data) {
1832
+ let c = this._c;
1833
+ for (let i = 0; i < data.length; i++) c = crcTable[c & 255 ^ data[i]] ^ c >>> 8;
1834
+ this._c = c;
1835
+ return this;
1836
+ }
1837
+ digest() {
1838
+ return ~this._c >>> 0;
1839
+ }
1840
+ };
1841
+ function crc32(data, seed = 0) {
1842
+ return new Crc32(seed).update(data).digest();
1843
+ }
1844
+ var Adler32 = class {
1845
+ _a;
1846
+ _b;
1847
+ constructor(seed = 1) {
1848
+ this._a = seed & 65535;
1849
+ this._b = seed >>> 16 & 65535;
1850
+ }
1851
+ update(data) {
1852
+ let a = this._a;
1853
+ let b = this._b;
1854
+ let i = 0;
1855
+ let n = data.length;
1856
+ while (i < n) {
1857
+ let end = Math.min(i + 2654, n);
1858
+ for (; i < end; i++) {
1859
+ a += data[i];
1860
+ b += a;
1861
+ }
1862
+ a %= 65521;
1863
+ b %= 65521;
1864
+ }
1865
+ this._a = a;
1866
+ this._b = b;
1867
+ return this;
1868
+ }
1869
+ digest() {
1870
+ return (this._b << 16 | this._a) >>> 0;
1871
+ }
1872
+ };
1873
+ function adler32(data, seed = 1) {
1874
+ return new Adler32(seed).update(data).digest();
1875
+ }
1876
+ //#endregion
1877
+ //#region src/compress/bits.ts
1878
+ function readBits(data, bitPos, mask) {
1879
+ let offset = bitPos / 8 | 0;
1880
+ return (data[offset] | data[offset + 1] << 8) >> (bitPos & 7) & mask;
1881
+ }
1882
+ function readBits16(data, bitPos) {
1883
+ let offset = bitPos / 8 | 0;
1884
+ return (data[offset] | data[offset + 1] << 8 | data[offset + 2] << 16) >> (bitPos & 7);
1885
+ }
1886
+ function writeBits(data, bitPos, value) {
1887
+ value <<= bitPos & 7;
1888
+ let offset = bitPos / 8 | 0;
1889
+ data[offset] |= value;
1890
+ data[offset + 1] |= value >> 8;
1891
+ }
1892
+ function writeBits16(data, bitPos, value) {
1893
+ value <<= bitPos & 7;
1894
+ let offset = bitPos / 8 | 0;
1895
+ data[offset] |= value;
1896
+ data[offset + 1] |= value >> 8;
1897
+ data[offset + 2] |= value >> 16;
1898
+ }
1899
+ function byteCeil(bitPos) {
1900
+ return (bitPos + 7) / 8 | 0;
1901
+ }
1902
+ //#endregion
1903
+ //#region src/compress/errors.ts
1904
+ var FlateError = class extends Error {
1905
+ constructor(message, options) {
1906
+ super(message, options);
1907
+ this.name = new.target.name;
1908
+ }
1909
+ };
1910
+ var UnexpectedEofError = class extends FlateError {
1911
+ constructor(options) {
1912
+ super("Unexpected end of DEFLATE stream.", options);
1913
+ }
1914
+ };
1915
+ var InvalidBlockTypeError = class extends FlateError {
1916
+ constructor(options) {
1917
+ super("Invalid DEFLATE block type.", options);
1918
+ }
1919
+ };
1920
+ var InvalidLengthLiteralError = class extends FlateError {
1921
+ constructor(options) {
1922
+ super("Invalid DEFLATE length or literal symbol.", options);
1923
+ }
1924
+ };
1925
+ var InvalidDistanceError = class extends FlateError {
1926
+ constructor(options) {
1927
+ super("Invalid DEFLATE distance.", options);
1928
+ }
1929
+ };
1930
+ var InvalidHeaderError = class extends FlateError {
1931
+ constructor(message = "Invalid compressed stream header.", options) {
1932
+ super(message, options);
1933
+ }
1934
+ };
1935
+ var StreamFinishedError = class extends FlateError {
1936
+ constructor(options) {
1937
+ super("Stream already finished.", options);
1938
+ }
1939
+ };
1940
+ var ChecksumMismatchError = class extends FlateError {
1941
+ constructor(options) {
1942
+ super("Checksum mismatch.", options);
1943
+ }
1944
+ };
1945
+ //#endregion
1946
+ //#region src/compress/tables.ts
1947
+ var fixedLengthExtraBits = new Uint8Array([
1948
+ 0,
1949
+ 0,
1950
+ 0,
1951
+ 0,
1952
+ 0,
1953
+ 0,
1954
+ 0,
1955
+ 0,
1956
+ 1,
1957
+ 1,
1958
+ 1,
1959
+ 1,
1960
+ 2,
1961
+ 2,
1962
+ 2,
1963
+ 2,
1964
+ 3,
1965
+ 3,
1966
+ 3,
1967
+ 3,
1968
+ 4,
1969
+ 4,
1970
+ 4,
1971
+ 4,
1972
+ 5,
1973
+ 5,
1974
+ 5,
1975
+ 5,
1976
+ 0,
1977
+ 0,
1978
+ 0
1979
+ ]);
1980
+ var fixedDistanceExtraBits = new Uint8Array([
1981
+ 0,
1982
+ 0,
1983
+ 0,
1984
+ 0,
1985
+ 1,
1986
+ 1,
1987
+ 2,
1988
+ 2,
1989
+ 3,
1990
+ 3,
1991
+ 4,
1992
+ 4,
1993
+ 5,
1994
+ 5,
1995
+ 6,
1996
+ 6,
1997
+ 7,
1998
+ 7,
1999
+ 8,
2000
+ 8,
2001
+ 9,
2002
+ 9,
2003
+ 10,
2004
+ 10,
2005
+ 11,
2006
+ 11,
2007
+ 12,
2008
+ 12,
2009
+ 13,
2010
+ 13,
2011
+ 0,
2012
+ 0
2013
+ ]);
2014
+ var codeLengthOrder = new Uint8Array([
2015
+ 16,
2016
+ 17,
2017
+ 18,
2018
+ 0,
2019
+ 8,
2020
+ 7,
2021
+ 9,
2022
+ 6,
2023
+ 10,
2024
+ 5,
2025
+ 11,
2026
+ 4,
2027
+ 12,
2028
+ 3,
2029
+ 13,
2030
+ 2,
2031
+ 14,
2032
+ 1,
2033
+ 15
2034
+ ]);
2035
+ function basesFromExtra(extraBits, start) {
2036
+ let bases = new Uint16Array(31);
2037
+ for (let i = 0; i < 31; i++) {
2038
+ start += 1 << (i === 0 ? 0 : extraBits[i - 1]);
2039
+ bases[i] = start;
2040
+ }
2041
+ let reverse = new Int32Array(bases[30]);
2042
+ for (let i = 1; i < 30; i++) for (let value = bases[i]; value < bases[i + 1]; value++) reverse[value] = value - bases[i] << 5 | i;
2043
+ return {
2044
+ bases,
2045
+ reverse
2046
+ };
2047
+ }
2048
+ var lengthTables = basesFromExtra(fixedLengthExtraBits, 2);
2049
+ lengthTables.bases[28] = 258;
2050
+ lengthTables.reverse[258] = 28;
2051
+ var lengthBase = lengthTables.bases;
2052
+ var lengthReverse = lengthTables.reverse;
2053
+ var distanceTables = basesFromExtra(fixedDistanceExtraBits, 0);
2054
+ var distanceBase = distanceTables.bases;
2055
+ var distanceReverse = distanceTables.reverse;
2056
+ var reverseBits15 = new Uint16Array(32768);
2057
+ for (let i = 0; i < 32768; i++) {
2058
+ let x = (i & 43690) >> 1 | (i & 21845) << 1;
2059
+ x = (x & 52428) >> 2 | (x & 13107) << 2;
2060
+ x = (x & 61680) >> 4 | (x & 3855) << 4;
2061
+ reverseBits15[i] = ((x & 65280) >> 8 | (x & 255) << 8) >> 1;
2062
+ }
2063
+ var fixedLiteralLengths = new Uint8Array(288);
2064
+ for (let i = 0; i < 144; i++) fixedLiteralLengths[i] = 8;
2065
+ for (let i = 144; i < 256; i++) fixedLiteralLengths[i] = 9;
2066
+ for (let i = 256; i < 280; i++) fixedLiteralLengths[i] = 7;
2067
+ for (let i = 280; i < 288; i++) fixedLiteralLengths[i] = 8;
2068
+ var fixedDistanceLengths = new Uint8Array(32);
2069
+ fixedDistanceLengths.fill(5);
2070
+ //#endregion
2071
+ //#region src/compress/huffman.ts
2072
+ function buildEncodeMap(lengths, maxBits) {
2073
+ return buildCodeMap(lengths, maxBits, false);
2074
+ }
2075
+ function buildDecodeMap(lengths, maxBits) {
2076
+ return buildCodeMap(lengths, maxBits, true);
2077
+ }
2078
+ function buildCodeMap(lengths, maxBits, decode) {
2079
+ let count = new Uint16Array(maxBits);
2080
+ for (let i = 0; i < lengths.length; i++) if (lengths[i]) count[lengths[i] - 1]++;
2081
+ let nextCode = new Uint16Array(maxBits);
2082
+ for (let i = 1; i < maxBits; i++) nextCode[i] = nextCode[i - 1] + count[i - 1] << 1;
2083
+ if (decode) {
2084
+ let map = new Uint16Array(1 << maxBits);
2085
+ let drop = 15 - maxBits;
2086
+ for (let symbol = 0; symbol < lengths.length; symbol++) {
2087
+ let bits = lengths[symbol];
2088
+ if (!bits) continue;
2089
+ let packed = symbol << 4 | bits;
2090
+ let pad = maxBits - bits;
2091
+ let value = nextCode[bits - 1]++ << pad;
2092
+ let last = value | (1 << pad) - 1;
2093
+ for (; value <= last; value++) map[reverseBits15[value] >> drop] = packed;
2094
+ }
2095
+ return map;
2096
+ }
2097
+ let map = new Uint16Array(lengths.length);
2098
+ for (let symbol = 0; symbol < lengths.length; symbol++) {
2099
+ let bits = lengths[symbol];
2100
+ if (bits) map[symbol] = reverseBits15[nextCode[bits - 1]++] >> 15 - bits;
2101
+ }
2102
+ return map;
2103
+ }
2104
+ function buildLengthLimitedTree(freqs, maxBits) {
2105
+ let nodes = [];
2106
+ for (let i = 0; i < freqs.length; i++) if (freqs[i]) nodes.push({
2107
+ symbol: i,
2108
+ freq: freqs[i]
2109
+ });
2110
+ let n = nodes.length;
2111
+ let leaves = nodes.slice();
2112
+ if (!n) return {
2113
+ lengths: new Uint8Array(0),
2114
+ maxBits: 0
2115
+ };
2116
+ if (n === 1) {
2117
+ let lengths = new Uint8Array(nodes[0].symbol + 1);
2118
+ lengths[nodes[0].symbol] = 1;
2119
+ return {
2120
+ lengths,
2121
+ maxBits: 1
2122
+ };
2123
+ }
2124
+ nodes.sort((a, b) => a.freq - b.freq);
2125
+ nodes.push({
2126
+ symbol: -1,
2127
+ freq: 25001
2128
+ });
2129
+ let left = nodes[0];
2130
+ let right = nodes[1];
2131
+ let lookbehind = 0;
2132
+ let write = 1;
2133
+ let lookahead = 2;
2134
+ nodes[0] = {
2135
+ symbol: -1,
2136
+ freq: left.freq + right.freq,
2137
+ left,
2138
+ right
2139
+ };
2140
+ while (write !== n - 1) {
2141
+ left = nodes[nodes[lookbehind].freq < nodes[lookahead].freq ? lookbehind++ : lookahead++];
2142
+ right = nodes[lookbehind !== write && nodes[lookbehind].freq < nodes[lookahead].freq ? lookbehind++ : lookahead++];
2143
+ nodes[write++] = {
2144
+ symbol: -1,
2145
+ freq: left.freq + right.freq,
2146
+ left,
2147
+ right
2148
+ };
2149
+ }
2150
+ let maxSymbol = leaves[0].symbol;
2151
+ for (let i = 1; i < n; i++) if (leaves[i].symbol > maxSymbol) maxSymbol = leaves[i].symbol;
2152
+ let bitLengths = new Uint16Array(maxSymbol + 1);
2153
+ let treeBits = assignLengths(nodes[write - 1], bitLengths, 0);
2154
+ if (treeBits > maxBits) {
2155
+ let debt = 0;
2156
+ let overflow = treeBits - maxBits;
2157
+ let cost = 1 << overflow;
2158
+ leaves.sort((a, b) => bitLengths[b.symbol] - bitLengths[a.symbol] || a.freq - b.freq);
2159
+ let i = 0;
2160
+ for (; i < n; i++) {
2161
+ let symbol = leaves[i].symbol;
2162
+ if (bitLengths[symbol] > maxBits) {
2163
+ debt += cost - (1 << treeBits - bitLengths[symbol]);
2164
+ bitLengths[symbol] = maxBits;
2165
+ } else break;
2166
+ }
2167
+ debt >>= overflow;
2168
+ while (debt > 0) {
2169
+ let symbol = leaves[i].symbol;
2170
+ if (bitLengths[symbol] < maxBits) debt -= 1 << maxBits - bitLengths[symbol]++ - 1;
2171
+ else i++;
2172
+ }
2173
+ for (; i >= 0 && debt; i--) {
2174
+ let symbol = leaves[i].symbol;
2175
+ if (bitLengths[symbol] === maxBits) {
2176
+ bitLengths[symbol]--;
2177
+ debt++;
2178
+ }
2179
+ }
2180
+ treeBits = maxBits;
2181
+ }
2182
+ return {
2183
+ lengths: new Uint8Array(bitLengths),
2184
+ maxBits: treeBits
2185
+ };
2186
+ }
2187
+ function assignLengths(node, lengths, depth) {
2188
+ if (node.symbol === -1) return Math.max(assignLengths(node.left, lengths, depth + 1), assignLengths(node.right, lengths, depth + 1));
2189
+ lengths[node.symbol] = depth;
2190
+ return depth;
2191
+ }
2192
+ //#endregion
2193
+ //#region src/compress/deflate.ts
2194
+ var levelOptions = new Int32Array([
2195
+ 65540,
2196
+ 131080,
2197
+ 131088,
2198
+ 131104,
2199
+ 262176,
2200
+ 1048704,
2201
+ 1048832,
2202
+ 2114560,
2203
+ 2117632
2204
+ ]);
2205
+ var empty = empty$1;
2206
+ var fixedLiteralEncode = /* @__PURE__ */ buildEncodeMap(fixedLiteralLengths, 9);
2207
+ var fixedDistanceEncode = /* @__PURE__ */ buildEncodeMap(fixedDistanceLengths, 5);
2208
+ function copySlice$1(buffer, start, end) {
2209
+ if (start < 0) start = 0;
2210
+ if (end == null || end > buffer.length) end = buffer.length;
2211
+ return new Uint8Array(buffer.subarray(start, end));
2212
+ }
2213
+ function encodedSize(freqs, lengths) {
2214
+ let bits = 0;
2215
+ for (let i = 0; i < lengths.length; i++) bits += freqs[i] * lengths[i];
2216
+ return bits;
2217
+ }
2218
+ function runLengthCodeLengths(lengths) {
2219
+ let end = lengths.length;
2220
+ while (end && !lengths[--end]);
2221
+ let packed = new Uint16Array(++end);
2222
+ let count = 0;
2223
+ let value = lengths[0];
2224
+ let run = 1;
2225
+ let write = (code) => {
2226
+ packed[count++] = code;
2227
+ };
2228
+ for (let i = 1; i <= end; i++) if (lengths[i] === value && i !== end) run++;
2229
+ else {
2230
+ if (!value && run > 2) {
2231
+ for (; run > 138; run -= 138) write(32754);
2232
+ if (run > 2) {
2233
+ write(run > 10 ? run - 11 << 5 | 28690 : run - 3 << 5 | 12305);
2234
+ run = 0;
2235
+ }
2236
+ } else if (run > 3) {
2237
+ write(value);
2238
+ run--;
2239
+ for (; run > 6; run -= 6) write(8304);
2240
+ if (run > 2) {
2241
+ write(run - 3 << 5 | 8208);
2242
+ run = 0;
2243
+ }
2244
+ }
2245
+ while (run--) write(value);
2246
+ run = 1;
2247
+ value = lengths[i];
2248
+ }
2249
+ return {
2250
+ codes: packed.subarray(0, count),
2251
+ used: end
2252
+ };
2253
+ }
2254
+ function writeStoredBlock(out, bitPos, data) {
2255
+ let length = data.length;
2256
+ let offset = byteCeil(bitPos + 2);
2257
+ out[offset] = length & 255;
2258
+ out[offset + 1] = length >> 8;
2259
+ out[offset + 2] = out[offset] ^ 255;
2260
+ out[offset + 3] = out[offset + 1] ^ 255;
2261
+ out.set(data, offset + 4);
2262
+ return (offset + 4 + length) * 8;
2263
+ }
2264
+ function writeBlock(data, out, final, symbols, literalFreq, distanceFreq, extraBits, symbolCount, blockStart, blockLength, bitPos) {
2265
+ writeBits(out, bitPos++, final);
2266
+ literalFreq[256]++;
2267
+ let literalTree = buildLengthLimitedTree(literalFreq, 15);
2268
+ let distanceTree = buildLengthLimitedTree(distanceFreq, 15);
2269
+ let literalRuns = runLengthCodeLengths(literalTree.lengths);
2270
+ let distanceRuns = runLengthCodeLengths(distanceTree.lengths);
2271
+ let codeLengthFreq = new Uint16Array(19);
2272
+ for (let i = 0; i < literalRuns.codes.length; i++) codeLengthFreq[literalRuns.codes[i] & 31]++;
2273
+ for (let i = 0; i < distanceRuns.codes.length; i++) codeLengthFreq[distanceRuns.codes[i] & 31]++;
2274
+ let codeLengthTree = buildLengthLimitedTree(codeLengthFreq, 7);
2275
+ let codeLengthCount = 19;
2276
+ while (codeLengthCount > 4 && !codeLengthTree.lengths[codeLengthOrder[codeLengthCount - 1]]) codeLengthCount--;
2277
+ let storedBits = blockLength + 5 << 3;
2278
+ let fixedBits = encodedSize(literalFreq, fixedLiteralLengths) + encodedSize(distanceFreq, fixedDistanceLengths) + extraBits;
2279
+ let dynamicBits = encodedSize(literalFreq, literalTree.lengths) + encodedSize(distanceFreq, distanceTree.lengths) + extraBits + 14 + 3 * codeLengthCount + encodedSize(codeLengthFreq, codeLengthTree.lengths) + 2 * codeLengthFreq[16] + 3 * codeLengthFreq[17] + 7 * codeLengthFreq[18];
2280
+ if (blockStart >= 0 && storedBits <= fixedBits && storedBits <= dynamicBits) return writeStoredBlock(out, bitPos, data.subarray(blockStart, blockStart + blockLength));
2281
+ let literalMap;
2282
+ let literalLengths;
2283
+ let distanceMap;
2284
+ let distanceLengths;
2285
+ writeBits(out, bitPos, 1 + (dynamicBits < fixedBits ? 1 : 0));
2286
+ bitPos += 2;
2287
+ if (dynamicBits < fixedBits) {
2288
+ literalMap = buildEncodeMap(literalTree.lengths, literalTree.maxBits);
2289
+ literalLengths = literalTree.lengths;
2290
+ distanceMap = buildEncodeMap(distanceTree.lengths, distanceTree.maxBits);
2291
+ distanceLengths = distanceTree.lengths;
2292
+ let codeLengthMap = buildEncodeMap(codeLengthTree.lengths, codeLengthTree.maxBits);
2293
+ writeBits(out, bitPos, literalRuns.used - 257);
2294
+ writeBits(out, bitPos + 5, distanceRuns.used - 1);
2295
+ writeBits(out, bitPos + 10, codeLengthCount - 4);
2296
+ bitPos += 14;
2297
+ for (let i = 0; i < codeLengthCount; i++) writeBits(out, bitPos + 3 * i, codeLengthTree.lengths[codeLengthOrder[i]]);
2298
+ bitPos += 3 * codeLengthCount;
2299
+ let runs = [literalRuns.codes, distanceRuns.codes];
2300
+ for (let set = 0; set < 2; set++) {
2301
+ let codes = runs[set];
2302
+ for (let i = 0; i < codes.length; i++) {
2303
+ let symbol = codes[i] & 31;
2304
+ writeBits(out, bitPos, codeLengthMap[symbol]);
2305
+ bitPos += codeLengthTree.lengths[symbol];
2306
+ if (symbol > 15) {
2307
+ writeBits(out, bitPos, codes[i] >> 5 & 127);
2308
+ bitPos += codes[i] >> 12;
2309
+ }
2310
+ }
2311
+ }
2312
+ } else {
2313
+ literalMap = fixedLiteralEncode;
2314
+ literalLengths = fixedLiteralLengths;
2315
+ distanceMap = fixedDistanceEncode;
2316
+ distanceLengths = fixedDistanceLengths;
2317
+ }
2318
+ for (let i = 0; i < symbolCount; i++) {
2319
+ let symbol = symbols[i];
2320
+ if (symbol > 255) {
2321
+ let lengthIndex = symbol >> 18 & 31;
2322
+ writeBits16(out, bitPos, literalMap[lengthIndex + 257]);
2323
+ bitPos += literalLengths[lengthIndex + 257];
2324
+ if (lengthIndex > 7) {
2325
+ writeBits(out, bitPos, symbol >> 23 & 31);
2326
+ bitPos += fixedLengthExtraBits[lengthIndex];
2327
+ }
2328
+ let distanceIndex = symbol & 31;
2329
+ writeBits16(out, bitPos, distanceMap[distanceIndex]);
2330
+ bitPos += distanceLengths[distanceIndex];
2331
+ if (distanceIndex > 3) {
2332
+ writeBits16(out, bitPos, symbol >> 5 & 8191);
2333
+ bitPos += fixedDistanceExtraBits[distanceIndex];
2334
+ }
2335
+ } else {
2336
+ writeBits16(out, bitPos, literalMap[symbol]);
2337
+ bitPos += literalLengths[symbol];
2338
+ }
2339
+ }
2340
+ writeBits16(out, bitPos, literalMap[256]);
2341
+ return bitPos + literalLengths[256];
2342
+ }
2343
+ function deflateRaw(data, level, hashBits, pre, post, state) {
2344
+ let size = state.end || data.length;
2345
+ let out = new Uint8Array(pre + size + 5 * (1 + Math.ceil(size / 7e3)) + post);
2346
+ let dest = out.subarray(pre, out.length - post);
2347
+ let last = state.last;
2348
+ let pos = (state.remainder || 0) & 7;
2349
+ if (level) {
2350
+ if (pos) dest[0] = state.remainder >> 3;
2351
+ let opt = levelOptions[level - 1];
2352
+ let nice = opt >> 13;
2353
+ let chain = opt & 8191;
2354
+ let mask = (1 << hashBits) - 1;
2355
+ let prev = state.prev || new Uint16Array(32768);
2356
+ let head = state.head || new Uint16Array(mask + 1);
2357
+ let shift1 = Math.ceil(hashBits / 3);
2358
+ let shift2 = 2 * shift1;
2359
+ let hashAt = (i) => (data[i] ^ data[i + 1] << shift1 ^ data[i + 2] << shift2) & mask;
2360
+ let symbols = new Int32Array(25e3);
2361
+ let literalFreq = new Uint16Array(288);
2362
+ let distanceFreq = new Uint16Array(32);
2363
+ let matches = 0;
2364
+ let extraBits = 0;
2365
+ let i = state.index || 0;
2366
+ let symbolCount = 0;
2367
+ let wait = state.wait || 0;
2368
+ let blockStart = 0;
2369
+ for (; i + 2 < size; i++) {
2370
+ let hv = hashAt(i);
2371
+ let imod = i & 32767;
2372
+ let previous = head[hv];
2373
+ prev[imod] = previous;
2374
+ head[hv] = imod;
2375
+ if (wait <= i) {
2376
+ let remaining = size - i;
2377
+ if ((matches > 7e3 || symbolCount > 24576) && (remaining > 423 || !last)) {
2378
+ pos = writeBlock(data, dest, 0, symbols, literalFreq, distanceFreq, extraBits, symbolCount, blockStart, i - blockStart, pos);
2379
+ symbolCount = matches = extraBits = 0;
2380
+ blockStart = i;
2381
+ literalFreq.fill(0);
2382
+ distanceFreq.fill(0);
2383
+ }
2384
+ let bestLen = 2;
2385
+ let bestDist = 0;
2386
+ let tries = chain;
2387
+ let dist = imod - previous & 32767;
2388
+ if (remaining > 2 && hv === hashAt(i - dist)) {
2389
+ let niceLen = Math.min(nice, remaining) - 1;
2390
+ let maxDist = Math.min(32767, i);
2391
+ let maxLen = Math.min(258, remaining);
2392
+ while (dist <= maxDist && --tries && imod !== previous) {
2393
+ if (data[i + bestLen] === data[i + bestLen - dist]) {
2394
+ let len = 0;
2395
+ for (; len < maxLen && data[i + len] === data[i + len - dist]; len++);
2396
+ if (len > bestLen) {
2397
+ bestLen = len;
2398
+ bestDist = dist;
2399
+ if (len > niceLen) break;
2400
+ let search = Math.min(dist, len - 2);
2401
+ let rarest = 0;
2402
+ for (let j = 0; j < search; j++) {
2403
+ let ti = i - dist + j & 32767;
2404
+ let candidate = ti - prev[ti] & 32767;
2405
+ if (candidate > rarest) {
2406
+ rarest = candidate;
2407
+ previous = ti;
2408
+ }
2409
+ }
2410
+ }
2411
+ }
2412
+ imod = previous;
2413
+ previous = prev[imod];
2414
+ dist += imod - previous & 32767;
2415
+ }
2416
+ }
2417
+ if (bestDist) {
2418
+ symbols[symbolCount++] = 268435456 | lengthReverse[bestLen] << 18 | distanceReverse[bestDist];
2419
+ let lengthIndex = lengthReverse[bestLen] & 31;
2420
+ let distanceIndex = distanceReverse[bestDist] & 31;
2421
+ extraBits += fixedLengthExtraBits[lengthIndex] + fixedDistanceExtraBits[distanceIndex];
2422
+ literalFreq[257 + lengthIndex]++;
2423
+ distanceFreq[distanceIndex]++;
2424
+ wait = i + bestLen;
2425
+ matches++;
2426
+ } else {
2427
+ symbols[symbolCount++] = data[i];
2428
+ literalFreq[data[i]]++;
2429
+ }
2430
+ }
2431
+ }
2432
+ for (i = Math.max(i, wait); i < size; i++) {
2433
+ symbols[symbolCount++] = data[i];
2434
+ literalFreq[data[i]]++;
2435
+ }
2436
+ pos = writeBlock(data, dest, last, symbols, literalFreq, distanceFreq, extraBits, symbolCount, blockStart, i - blockStart, pos);
2437
+ if (!last) {
2438
+ state.remainder = pos & 7 | dest[pos / 8 | 0] << 3;
2439
+ pos -= 7;
2440
+ state.head = head;
2441
+ state.prev = prev;
2442
+ state.index = i;
2443
+ state.wait = wait;
2444
+ }
2445
+ } else {
2446
+ for (let i = state.wait || 0; i < size + last; i += 65535) {
2447
+ let end = i + 65535;
2448
+ if (end >= size) {
2449
+ dest[pos / 8 | 0] = last;
2450
+ end = size;
2451
+ }
2452
+ pos = writeStoredBlock(dest, pos + 1, data.subarray(i, end));
2453
+ }
2454
+ state.index = size;
2455
+ }
2456
+ return copySlice$1(out, 0, pre + byteCeil(pos) + post);
2457
+ }
2458
+ function defaultHashBits(length, last) {
2459
+ if (!last) return 20;
2460
+ return Math.ceil(Math.max(8, Math.min(13, Math.log(Math.max(length, 1)))) * 1.5);
2461
+ }
2462
+ function deflateWithOptions(data, options, pre, post, state) {
2463
+ if (!state) {
2464
+ state = { last: 1 };
2465
+ if (options.dictionary) {
2466
+ let dict = options.dictionary.subarray(-32768);
2467
+ let prefixed = new Uint8Array(dict.length + data.length);
2468
+ prefixed.set(dict);
2469
+ prefixed.set(data, dict.length);
2470
+ data = prefixed;
2471
+ state.wait = dict.length;
2472
+ }
2473
+ }
2474
+ let level = options.level == null ? 6 : options.level;
2475
+ let hashBits = options.mem == null ? defaultHashBits(data.length, state.last) : 12 + options.mem;
2476
+ return deflateRaw(data, level, hashBits, pre, post, state);
2477
+ }
2478
+ function compress$2(data, options = {}) {
2479
+ return deflateWithOptions(data, options, 0, 0);
2480
+ }
2481
+ var Compressor$2 = class {
2482
+ _options;
2483
+ _state;
2484
+ _buffer;
2485
+ _done = false;
2486
+ constructor(options = {}) {
2487
+ this._options = options;
2488
+ this._state = {
2489
+ last: 0,
2490
+ index: 32768,
2491
+ wait: 32768,
2492
+ end: 32768
2493
+ };
2494
+ this._buffer = new Uint8Array(98304);
2495
+ if (options.dictionary) {
2496
+ let dict = options.dictionary.subarray(-32768);
2497
+ this._buffer.set(dict, 32768 - dict.length);
2498
+ this._state.index = 32768 - dict.length;
2499
+ }
2500
+ }
2501
+ _emit(final) {
2502
+ return deflateWithOptions(this._buffer, this._options, 0, 0, this._state);
2503
+ }
2504
+ push(chunk, final) {
2505
+ if (this._done) throw new StreamFinishedError();
2506
+ let endLen = chunk.length + this._state.end;
2507
+ if (endLen > this._buffer.length) {
2508
+ if (endLen > 2 * this._buffer.length - 32768) {
2509
+ let next = new Uint8Array(endLen & -32768);
2510
+ next.set(this._buffer.subarray(0, this._state.end));
2511
+ this._buffer = next;
2512
+ }
2513
+ let split = this._buffer.length - this._state.end;
2514
+ this._buffer.set(chunk.subarray(0, split), this._state.end);
2515
+ this._state.end = this._buffer.length;
2516
+ let first = this._emit(false);
2517
+ this._buffer.set(this._buffer.subarray(-32768));
2518
+ this._buffer.set(chunk.subarray(split), 32768);
2519
+ this._state.end = chunk.length - split + 32768;
2520
+ this._state.index = 32766;
2521
+ this._state.wait = 32768;
2522
+ this._state.last = final ? 1 : 0;
2523
+ let rest = new Uint8Array(0);
2524
+ if (this._state.end > this._state.wait + 8191 || final) {
2525
+ rest = this._emit(!!final);
2526
+ this._state.wait = this._state.index;
2527
+ this._state.index -= 2;
2528
+ }
2529
+ if (final) {
2530
+ this._done = true;
2531
+ this._buffer = empty;
2532
+ this._state = { last: 1 };
2533
+ }
2534
+ if (!rest.length) return first;
2535
+ let joined = new Uint8Array(first.length + rest.length);
2536
+ joined.set(first);
2537
+ joined.set(rest, first.length);
2538
+ return joined;
2539
+ }
2540
+ this._buffer.set(chunk, this._state.end);
2541
+ this._state.end += chunk.length;
2542
+ this._state.last = final ? 1 : 0;
2543
+ let out = empty$1;
2544
+ if (this._state.end > this._state.wait + 8191 || final) {
2545
+ out = this._emit(!!final);
2546
+ this._state.wait = this._state.index;
2547
+ this._state.index -= 2;
2548
+ }
2549
+ if (final) {
2550
+ this._done = true;
2551
+ this._buffer = empty;
2552
+ this._state = { last: 1 };
2553
+ }
2554
+ return out;
2555
+ }
2556
+ flush(sync) {
2557
+ if (this._done) throw new StreamFinishedError();
2558
+ let out = this._emit(false);
2559
+ this._state.wait = this._state.index;
2560
+ this._state.index -= 2;
2561
+ if (!sync) return out;
2562
+ let block = new Uint8Array(6);
2563
+ block[0] = this._state.remainder >> 3;
2564
+ let end = writeStoredBlock(block, this._state.remainder, empty);
2565
+ this._state.remainder = 0;
2566
+ let trailer = block.subarray(0, end >> 3);
2567
+ if (!out.length) return new Uint8Array(trailer);
2568
+ let joined = new Uint8Array(out.length + trailer.length);
2569
+ joined.set(out);
2570
+ joined.set(trailer, out.length);
2571
+ return joined;
2572
+ }
2573
+ };
2574
+ //#endregion
2575
+ //#region src/compress/inflate.ts
2576
+ var fixedLengthMap = /* @__PURE__ */ buildDecodeMap(fixedLiteralLengths, 9);
2577
+ var fixedDistanceMap = /* @__PURE__ */ buildDecodeMap(fixedDistanceLengths, 5);
2578
+ function copySlice(buffer, start, end) {
2579
+ if (start < 0) start = 0;
2580
+ if (end == null || end > buffer.length) end = buffer.length;
2581
+ return new Uint8Array(buffer.subarray(start, end));
2582
+ }
2583
+ function maxValue(values) {
2584
+ let max = values[0];
2585
+ for (let i = 1; i < values.length; i++) if (values[i] > max) max = values[i];
2586
+ return max;
2587
+ }
2588
+ function inflateRaw(data, state, buf, dictionary) {
2589
+ let sourceLength = data.length;
2590
+ let dictLength = dictionary ? dictionary.length : 0;
2591
+ if (!sourceLength || state.final && !state.lengthMap) return buf || empty$1;
2592
+ let noBuf = !buf;
2593
+ let resize = noBuf || state.mode !== 2;
2594
+ let throwOnEof = state.mode !== 0;
2595
+ if (noBuf) buf = new Uint8Array(sourceLength * 3);
2596
+ let ensure = (need) => {
2597
+ if (need <= buf.length) return;
2598
+ let next = new Uint8Array(Math.max(buf.length * 2, need));
2599
+ next.set(buf);
2600
+ buf = next;
2601
+ };
2602
+ let final = state.final || 0;
2603
+ let pos = state.bitPos || 0;
2604
+ let written = state.outputLength || 0;
2605
+ let lengthMap = state.lengthMap;
2606
+ let distanceMap = state.distanceMap;
2607
+ let lengthBits = state.lengthBits;
2608
+ let distanceBits = state.distanceBits;
2609
+ let totalBits = sourceLength * 8;
2610
+ do {
2611
+ if (!lengthMap) {
2612
+ final = readBits(data, pos, 1);
2613
+ let type = readBits(data, pos + 1, 3);
2614
+ pos += 3;
2615
+ if (!type) {
2616
+ let start = byteCeil(pos) + 4;
2617
+ let length = data[start - 4] | data[start - 3] << 8;
2618
+ let end = start + length;
2619
+ if (end > sourceLength) {
2620
+ if (throwOnEof) throw new UnexpectedEofError();
2621
+ break;
2622
+ }
2623
+ if (resize) ensure(written + length);
2624
+ let room = buf.length - written;
2625
+ if (room > 0) buf.set(data.subarray(start, start + Math.min(length, room)), written);
2626
+ state.outputLength = written += length;
2627
+ state.bitPos = pos = end * 8;
2628
+ state.final = final;
2629
+ continue;
2630
+ } else if (type === 1) {
2631
+ lengthMap = fixedLengthMap;
2632
+ distanceMap = fixedDistanceMap;
2633
+ lengthBits = 9;
2634
+ distanceBits = 5;
2635
+ } else if (type === 2) {
2636
+ let literalCount = readBits(data, pos, 31) + 257;
2637
+ let distanceCount = readBits(data, pos + 5, 31) + 1;
2638
+ let codeLengthCount = readBits(data, pos + 10, 15) + 4;
2639
+ let totalCodes = literalCount + distanceCount;
2640
+ pos += 14;
2641
+ let lengths = new Uint8Array(totalCodes);
2642
+ let codeLengthTree = new Uint8Array(19);
2643
+ for (let i = 0; i < codeLengthCount; i++) codeLengthTree[codeLengthOrder[i]] = readBits(data, pos + i * 3, 7);
2644
+ pos += codeLengthCount * 3;
2645
+ let codeLengthBits = maxValue(codeLengthTree);
2646
+ let codeLengthMask = (1 << codeLengthBits) - 1;
2647
+ let codeLengthMap = buildDecodeMap(codeLengthTree, codeLengthBits);
2648
+ for (let i = 0; i < totalCodes;) {
2649
+ let entry = codeLengthMap[readBits(data, pos, codeLengthMask)];
2650
+ pos += entry & 15;
2651
+ let symbol = entry >> 4;
2652
+ if (symbol < 16) lengths[i++] = symbol;
2653
+ else {
2654
+ let fill = 0;
2655
+ let count = 0;
2656
+ if (symbol === 16) {
2657
+ count = 3 + readBits(data, pos, 3);
2658
+ pos += 2;
2659
+ fill = lengths[i - 1];
2660
+ } else if (symbol === 17) {
2661
+ count = 3 + readBits(data, pos, 7);
2662
+ pos += 3;
2663
+ } else if (symbol === 18) {
2664
+ count = 11 + readBits(data, pos, 127);
2665
+ pos += 7;
2666
+ }
2667
+ while (count--) lengths[i++] = fill;
2668
+ }
2669
+ }
2670
+ let literalLengths = lengths.subarray(0, literalCount);
2671
+ let distanceLengths = lengths.subarray(literalCount);
2672
+ lengthBits = maxValue(literalLengths);
2673
+ distanceBits = maxValue(distanceLengths);
2674
+ lengthMap = buildDecodeMap(literalLengths, lengthBits);
2675
+ distanceMap = buildDecodeMap(distanceLengths, distanceBits);
2676
+ } else throw new InvalidBlockTypeError();
2677
+ if (pos > totalBits) {
2678
+ if (throwOnEof) throw new UnexpectedEofError();
2679
+ break;
2680
+ }
2681
+ }
2682
+ if (resize) ensure(written + 131072);
2683
+ let lengthMask = (1 << lengthBits) - 1;
2684
+ let distanceMask = (1 << distanceBits) - 1;
2685
+ let lastPos = pos;
2686
+ for (;; lastPos = pos) {
2687
+ let entry = lengthMap[readBits16(data, pos) & lengthMask];
2688
+ let symbol = entry >> 4;
2689
+ pos += entry & 15;
2690
+ if (pos > totalBits) {
2691
+ if (throwOnEof) throw new UnexpectedEofError();
2692
+ break;
2693
+ }
2694
+ if (!entry) throw new InvalidLengthLiteralError();
2695
+ if (symbol < 256) {
2696
+ if (written < buf.length) buf[written] = symbol;
2697
+ written++;
2698
+ } else if (symbol === 256) {
2699
+ lastPos = pos;
2700
+ lengthMap = void 0;
2701
+ break;
2702
+ } else {
2703
+ let add = symbol - 254;
2704
+ if (symbol > 264) {
2705
+ let index = symbol - 257;
2706
+ let extra = fixedLengthExtraBits[index];
2707
+ add = readBits(data, pos, (1 << extra) - 1) + lengthBase[index];
2708
+ pos += extra;
2709
+ }
2710
+ let distEntry = distanceMap[readBits16(data, pos) & distanceMask];
2711
+ let distSymbol = distEntry >> 4;
2712
+ if (!distEntry) throw new InvalidDistanceError();
2713
+ pos += distEntry & 15;
2714
+ let distance = distanceBase[distSymbol];
2715
+ if (distSymbol > 3) {
2716
+ let extra = fixedDistanceExtraBits[distSymbol];
2717
+ distance += readBits16(data, pos) & (1 << extra) - 1;
2718
+ pos += extra;
2719
+ }
2720
+ if (pos > totalBits) {
2721
+ if (throwOnEof) throw new UnexpectedEofError();
2722
+ break;
2723
+ }
2724
+ if (resize) ensure(written + 131072);
2725
+ let end = written + add;
2726
+ if (written < distance) {
2727
+ let shift = dictLength - distance;
2728
+ let dictEnd = Math.min(distance, end);
2729
+ if (shift + written < 0) throw new InvalidDistanceError();
2730
+ for (; written < dictEnd; written++) if (written < buf.length) buf[written] = dictionary[shift + written];
2731
+ }
2732
+ for (; written < end; written++) if (written < buf.length) buf[written] = buf[written - distance];
2733
+ }
2734
+ }
2735
+ state.lengthMap = lengthMap;
2736
+ state.bitPos = lastPos;
2737
+ state.outputLength = written;
2738
+ state.final = final;
2739
+ if (lengthMap) {
2740
+ final = 1;
2741
+ state.lengthBits = lengthBits;
2742
+ state.distanceMap = distanceMap;
2743
+ state.distanceBits = distanceBits;
2744
+ }
2745
+ } while (!final);
2746
+ let length = Math.min(written, buf.length);
2747
+ if (length === buf.length) return buf;
2748
+ return noBuf ? copySlice(buf, 0, length) : buf.subarray(0, length);
2749
+ }
2750
+ function decompress$3(data, options) {
2751
+ return inflateRaw(data, { mode: 2 }, options?.out, options?.dictionary);
2752
+ }
2753
+ var Decompressor$2 = class {
2754
+ _state;
2755
+ _window;
2756
+ _pending;
2757
+ _done = false;
2758
+ constructor(options) {
2759
+ let dict = options?.dictionary?.subarray(-32768);
2760
+ this._state = {
2761
+ mode: 0,
2762
+ outputLength: dict ? dict.length : 0
2763
+ };
2764
+ this._window = new Uint8Array(32768);
2765
+ this._pending = empty$1;
2766
+ if (dict) this._window.set(dict);
2767
+ }
2768
+ push(chunk, final) {
2769
+ if (this._done) throw new StreamFinishedError();
2770
+ if (!this._pending.length) this._pending = chunk;
2771
+ else if (chunk.length) {
2772
+ let next = new Uint8Array(this._pending.length + chunk.length);
2773
+ next.set(this._pending);
2774
+ next.set(chunk, this._pending.length);
2775
+ this._pending = next;
2776
+ }
2777
+ this._done = !!final;
2778
+ this._state.mode = this._done ? 1 : 0;
2779
+ let start = this._state.outputLength || 0;
2780
+ let out = inflateRaw(this._pending, this._state, this._window);
2781
+ let produced = copySlice(out, start, this._state.outputLength);
2782
+ this._window = copySlice(out, (this._state.outputLength || 0) - 32768);
2783
+ this._state.outputLength = this._window.length;
2784
+ this._pending = copySlice(this._pending, (this._state.bitPos || 0) / 8 | 0);
2785
+ this._state.bitPos = (this._state.bitPos || 0) & 7;
2786
+ return produced.length ? produced : empty$1;
2787
+ }
2788
+ };
2789
+ //#endregion
2790
+ //#region src/compress/gzip.ts
2791
+ function writeU32LE(buf, offset, value) {
2792
+ buf[offset] = value;
2793
+ buf[offset + 1] = value >>> 8;
2794
+ buf[offset + 2] = value >>> 16;
2795
+ buf[offset + 3] = value >>> 24;
2796
+ }
2797
+ function readU32LE(buf, offset) {
2798
+ return (buf[offset] | buf[offset + 1] << 8 | buf[offset + 2] << 16 | buf[offset + 3] << 24) >>> 0;
2799
+ }
2800
+ function gzipHeaderSize(options) {
2801
+ return 10 + (options.filename ? options.filename.length + 1 : 0);
2802
+ }
2803
+ function writeGzipHeader(out, options) {
2804
+ out[0] = 31;
2805
+ out[1] = 139;
2806
+ out[2] = 8;
2807
+ let level = options.level ?? 6;
2808
+ out[8] = level < 2 ? 4 : level === 9 ? 2 : 0;
2809
+ out[9] = 3;
2810
+ if (options.mtime !== 0) writeU32LE(out, 4, Math.floor((options.mtime != null ? new Date(options.mtime).getTime() : Date.now()) / 1e3) >>> 0);
2811
+ if (options.filename) {
2812
+ out[3] = 8;
2813
+ for (let i = 0; i < options.filename.length; i++) out[10 + i] = options.filename.charCodeAt(i);
2814
+ out[10 + options.filename.length] = 0;
2815
+ }
2816
+ }
2817
+ function gzipHeaderLength(data) {
2818
+ if (data.length < 10) throw new UnexpectedEofError();
2819
+ if (data[0] !== 31 || data[1] !== 139 || data[2] !== 8) throw new InvalidHeaderError("Invalid gzip header.");
2820
+ let flags = data[3];
2821
+ let offset = 10;
2822
+ if (flags & 4) {
2823
+ if (offset + 2 > data.length) throw new UnexpectedEofError();
2824
+ offset += (data[offset] | data[offset + 1] << 8) + 2;
2825
+ }
2826
+ let strings = (flags >> 3 & 1) + (flags >> 4 & 1);
2827
+ while (strings) {
2828
+ if (offset >= data.length) throw new UnexpectedEofError();
2829
+ if (!data[offset++]) strings--;
2830
+ }
2831
+ if (flags & 2) offset += 2;
2832
+ if (offset > data.length) throw new UnexpectedEofError();
2833
+ return offset;
2834
+ }
2835
+ function concatParts(parts) {
2836
+ if (parts.length === 0) return empty$1;
2837
+ if (parts.length === 1) return parts[0];
2838
+ let out = new Uint8Array(parts.reduce((n, p) => n + p.length, 0));
2839
+ let offset = 0;
2840
+ for (let part of parts) {
2841
+ out.set(part, offset);
2842
+ offset += part.length;
2843
+ }
2844
+ return out;
2845
+ }
2846
+ function verifyFooter(footer, data, check) {
2847
+ if (!check) return;
2848
+ if (readU32LE(footer, 0) !== crc32(data) || readU32LE(footer, 4) !== data.length >>> 0) throw new ChecksumMismatchError();
2849
+ }
2850
+ function compress$1(data, options = {}) {
2851
+ let out = deflateWithOptions(data, options, gzipHeaderSize(options), 8);
2852
+ writeGzipHeader(out, options);
2853
+ writeU32LE(out, out.length - 8, crc32(data));
2854
+ writeU32LE(out, out.length - 4, data.length >>> 0);
2855
+ return out;
2856
+ }
2857
+ function decompress$2(data, options) {
2858
+ let parts = [];
2859
+ let offset = 0;
2860
+ while (offset < data.length) {
2861
+ let header = gzipHeaderLength(data.subarray(offset));
2862
+ offset += header;
2863
+ let state = { mode: 2 };
2864
+ let payload = inflateRaw(data.subarray(offset), state);
2865
+ parts.push(payload);
2866
+ offset += byteCeil(state.bitPos || 0);
2867
+ if (offset + 8 > data.length) throw new UnexpectedEofError();
2868
+ verifyFooter(data.subarray(offset, offset + 8), payload, options?.check !== false);
2869
+ offset += 8;
2870
+ }
2871
+ return concatParts(parts);
2872
+ }
2873
+ var Compressor$1 = class {
2874
+ _inner;
2875
+ _options;
2876
+ _crc = new Crc32();
2877
+ _length = 0;
2878
+ _header = false;
2879
+ _done = false;
2880
+ constructor(options = {}) {
2881
+ this._options = options;
2882
+ this._inner = new Compressor$2(options);
2883
+ }
2884
+ _wrap(raw, final) {
2885
+ let header = 0;
2886
+ if (!this._header) {
2887
+ header = gzipHeaderSize(this._options);
2888
+ this._header = true;
2889
+ }
2890
+ let footer = final ? 8 : 0;
2891
+ if (!header && !footer) return raw;
2892
+ let out = new Uint8Array(header + raw.length + footer);
2893
+ if (header) writeGzipHeader(out, this._options);
2894
+ out.set(raw, header);
2895
+ if (footer) {
2896
+ writeU32LE(out, header + raw.length, this._crc.digest());
2897
+ writeU32LE(out, header + raw.length + 4, this._length >>> 0);
2898
+ }
2899
+ return out;
2900
+ }
2901
+ push(chunk, final) {
2902
+ if (this._done) throw new StreamFinishedError();
2903
+ this._crc.update(chunk);
2904
+ this._length += chunk.length;
2905
+ this._done = !!final;
2906
+ return this._wrap(this._inner.push(chunk, final), !!final);
2907
+ }
2908
+ flush(sync) {
2909
+ if (this._done) throw new StreamFinishedError();
2910
+ return this._wrap(this._inner.flush(sync), false);
2911
+ }
2912
+ };
2913
+ var Decompressor$1 = class {
2914
+ _pending = empty$1;
2915
+ _needHeader = true;
2916
+ _state = { mode: 0 };
2917
+ _window = new Uint8Array(32768);
2918
+ _crc = new Crc32();
2919
+ _length = 0;
2920
+ _check;
2921
+ _done = false;
2922
+ constructor(options) {
2923
+ this._check = options?.check !== false;
2924
+ }
2925
+ push(chunk, final) {
2926
+ if (this._done) throw new StreamFinishedError();
2927
+ if (!this._pending.length) this._pending = chunk;
2928
+ else if (chunk.length) {
2929
+ let next = new Uint8Array(this._pending.length + chunk.length);
2930
+ next.set(this._pending);
2931
+ next.set(chunk, this._pending.length);
2932
+ this._pending = next;
2933
+ }
2934
+ let parts = [];
2935
+ for (;;) {
2936
+ if (this._needHeader) {
2937
+ if (!this._pending.length) break;
2938
+ if (this._pending.length < 10 && !final) break;
2939
+ let header = gzipHeaderLength(this._pending);
2940
+ this._pending = this._pending.subarray(header);
2941
+ this._needHeader = false;
2942
+ this._state = { mode: 0 };
2943
+ this._window = new Uint8Array(32768);
2944
+ this._crc = new Crc32();
2945
+ this._length = 0;
2946
+ }
2947
+ this._state.mode = 0;
2948
+ let start = this._state.outputLength || 0;
2949
+ let out = inflateRaw(this._pending, this._state, this._window);
2950
+ let produced = out.subarray(start, Math.min(this._state.outputLength || 0, out.length));
2951
+ if (produced.length) {
2952
+ this._crc.update(produced);
2953
+ this._length += produced.length;
2954
+ parts.push(new Uint8Array(produced));
2955
+ }
2956
+ if (this._state.final && !this._state.lengthMap) {
2957
+ this._pending = this._pending.subarray(byteCeil(this._state.bitPos || 0));
2958
+ this._state.bitPos = 0;
2959
+ } else {
2960
+ this._pending = this._pending.subarray((this._state.bitPos || 0) / 8 | 0);
2961
+ this._state.bitPos = (this._state.bitPos || 0) & 7;
2962
+ }
2963
+ this._window = new Uint8Array(out.subarray(Math.max(0, (this._state.outputLength || 0) - 32768)));
2964
+ this._state.outputLength = this._window.length;
2965
+ if (this._state.final && !this._state.lengthMap) {
2966
+ if (this._pending.length < 8) {
2967
+ if (!final) break;
2968
+ throw new UnexpectedEofError();
2969
+ }
2970
+ if (this._check) {
2971
+ if (readU32LE(this._pending, 0) !== this._crc.digest() || readU32LE(this._pending, 4) !== this._length >>> 0) throw new ChecksumMismatchError();
2972
+ }
2973
+ this._pending = this._pending.subarray(8);
2974
+ this._needHeader = true;
2975
+ continue;
2976
+ }
2977
+ break;
2978
+ }
2979
+ if (final) this._done = true;
2980
+ return concatParts(parts);
2981
+ }
2982
+ };
2983
+ //#endregion
2984
+ //#region src/compress/zlib.ts
2985
+ function writeU32BE(buf, offset, value) {
2986
+ buf[offset] = value >>> 24;
2987
+ buf[offset + 1] = value >>> 16;
2988
+ buf[offset + 2] = value >>> 8;
2989
+ buf[offset + 3] = value;
2990
+ }
2991
+ function readU32BE(buf, offset) {
2992
+ return (buf[offset] << 24 | buf[offset + 1] << 16 | buf[offset + 2] << 8 | buf[offset + 3]) >>> 0;
2993
+ }
2994
+ function zlibHeaderSize(options) {
2995
+ return options.dictionary ? 6 : 2;
2996
+ }
2997
+ function writeZlibHeader(out, options) {
2998
+ let level = options.level ?? 6;
2999
+ let flevel = level === 0 ? 0 : level < 6 ? 1 : level === 9 ? 3 : 2;
3000
+ out[0] = 120;
3001
+ out[1] = flevel << 6 | (options.dictionary ? 32 : 0);
3002
+ out[1] += 31 - (out[0] << 8 | out[1]) % 31;
3003
+ if (options.dictionary) writeU32BE(out, 2, adler32(options.dictionary));
3004
+ }
3005
+ function zlibHeaderLength(data, dictionary) {
3006
+ if (data.length < 2) throw new UnexpectedEofError();
3007
+ if ((data[0] & 15) !== 8 || data[0] >> 4 > 7 || (data[0] << 8 | data[1]) % 31 !== 0) throw new InvalidHeaderError("Invalid zlib header.");
3008
+ let hasDict = data[1] >> 5 & 1;
3009
+ if (hasDict && !dictionary) throw new InvalidHeaderError("zlib stream requires a dictionary.");
3010
+ if (!hasDict && dictionary) throw new InvalidHeaderError("zlib stream has no dictionary.");
3011
+ let size = hasDict ? 6 : 2;
3012
+ if (data.length < size) throw new UnexpectedEofError();
3013
+ return size;
3014
+ }
3015
+ function compress(data, options = {}) {
3016
+ let out = deflateWithOptions(data, options, zlibHeaderSize(options), 4);
3017
+ writeZlibHeader(out, options);
3018
+ writeU32BE(out, out.length - 4, adler32(data));
3019
+ return out;
3020
+ }
3021
+ function decompress$1(data, options) {
3022
+ let header = zlibHeaderLength(data, options?.dictionary);
3023
+ let state = { mode: 2 };
3024
+ let payload = inflateRaw(data.subarray(header), state, options?.out, options?.dictionary);
3025
+ let trailer = header + byteCeil(state.bitPos || 0);
3026
+ if (options?.check !== false) {
3027
+ if (trailer + 4 > data.length) throw new UnexpectedEofError();
3028
+ if (readU32BE(data, trailer) !== adler32(payload)) throw new ChecksumMismatchError();
3029
+ }
3030
+ return payload;
3031
+ }
3032
+ var Compressor = class {
3033
+ _inner;
3034
+ _options;
3035
+ _sum = new Adler32();
3036
+ _header = false;
3037
+ _done = false;
3038
+ constructor(options = {}) {
3039
+ this._options = options;
3040
+ this._inner = new Compressor$2(options);
3041
+ }
3042
+ _wrap(raw, final) {
3043
+ let header = 0;
3044
+ if (!this._header) {
3045
+ header = zlibHeaderSize(this._options);
3046
+ this._header = true;
3047
+ }
3048
+ let footer = final ? 4 : 0;
3049
+ if (!header && !footer) return raw;
3050
+ let out = new Uint8Array(header + raw.length + footer);
3051
+ if (header) writeZlibHeader(out, this._options);
3052
+ out.set(raw, header);
3053
+ if (footer) writeU32BE(out, header + raw.length, this._sum.digest());
3054
+ return out;
3055
+ }
3056
+ push(chunk, final) {
3057
+ if (this._done) throw new StreamFinishedError();
3058
+ this._sum.update(chunk);
3059
+ this._done = !!final;
3060
+ return this._wrap(this._inner.push(chunk, final), !!final);
3061
+ }
3062
+ flush(sync) {
3063
+ if (this._done) throw new StreamFinishedError();
3064
+ return this._wrap(this._inner.flush(sync), false);
3065
+ }
3066
+ };
3067
+ var Decompressor = class {
3068
+ _pending = empty$1;
3069
+ _header = false;
3070
+ _state = { mode: 0 };
3071
+ _window = new Uint8Array(32768);
3072
+ _sum = new Adler32();
3073
+ _dictionary;
3074
+ _check;
3075
+ _done = false;
3076
+ constructor(options) {
3077
+ this._dictionary = options?.dictionary;
3078
+ this._check = options?.check !== false;
3079
+ if (options?.dictionary) this._window.set(options.dictionary.subarray(-32768), 32768 - Math.min(32768, options.dictionary.length));
3080
+ }
3081
+ push(chunk, final) {
3082
+ if (this._done) throw new StreamFinishedError();
3083
+ if (!this._pending.length) this._pending = chunk;
3084
+ else if (chunk.length) {
3085
+ let next = new Uint8Array(this._pending.length + chunk.length);
3086
+ next.set(this._pending);
3087
+ next.set(chunk, this._pending.length);
3088
+ this._pending = next;
3089
+ }
3090
+ if (!this._header) {
3091
+ if (this._pending.length < 2 && !final) return empty$1;
3092
+ let size = zlibHeaderLength(this._pending, this._dictionary);
3093
+ if (this._dictionary) {
3094
+ this._state.outputLength = Math.min(32768, this._dictionary.length);
3095
+ this._window = new Uint8Array(32768);
3096
+ this._window.set(this._dictionary.subarray(-32768));
3097
+ }
3098
+ this._pending = this._pending.subarray(size);
3099
+ this._header = true;
3100
+ }
3101
+ this._state.mode = final ? 1 : 0;
3102
+ let start = this._state.outputLength || 0;
3103
+ let out = inflateRaw(this._pending, this._state, this._window, this._header && !start ? this._dictionary : void 0);
3104
+ let produced = new Uint8Array(out.subarray(start, Math.min(this._state.outputLength || 0, out.length)));
3105
+ if (produced.length) this._sum.update(produced);
3106
+ if (this._state.final && !this._state.lengthMap) {
3107
+ this._pending = this._pending.subarray(byteCeil(this._state.bitPos || 0));
3108
+ this._state.bitPos = 0;
3109
+ } else {
3110
+ this._pending = this._pending.subarray((this._state.bitPos || 0) / 8 | 0);
3111
+ this._state.bitPos = (this._state.bitPos || 0) & 7;
3112
+ }
3113
+ this._window = new Uint8Array(out.subarray(Math.max(0, (this._state.outputLength || 0) - 32768)));
3114
+ this._state.outputLength = this._window.length;
3115
+ if (final) {
3116
+ this._done = true;
3117
+ if (this._check && this._state.final) {
3118
+ if (this._pending.length < 4) throw new UnexpectedEofError();
3119
+ if (readU32BE(this._pending, 0) !== this._sum.digest()) throw new ChecksumMismatchError();
3120
+ }
3121
+ }
3122
+ return produced.length ? produced : empty$1;
3123
+ }
3124
+ };
3125
+ //#endregion
3126
+ //#region src/compress/compress.ts
3127
+ var compress_exports = /* @__PURE__ */ __exportAll({
3128
+ Deflate: () => Compressor$2,
3129
+ Gzip: () => Compressor$1,
3130
+ Zlib: () => Compressor,
3131
+ deflate: () => compress$2,
3132
+ gzip: () => compress$1,
3133
+ zlib: () => compress
3134
+ });
3135
+ //#endregion
3136
+ //#region src/compress/detect.ts
3137
+ function decompress(data, options) {
3138
+ if (data.length >= 2 && data[0] === 31 && data[1] === 139) return decompress$2(data, options);
3139
+ if (data.length >= 2 && (data[0] & 15) === 8 && data[0] >> 4 <= 7 && (data[0] << 8 | data[1]) % 31 === 0) return decompress$1(data, options);
3140
+ return decompress$3(data, options);
3141
+ }
3142
+ //#endregion
3143
+ //#region src/compress/decompress.ts
3144
+ var decompress_exports = /* @__PURE__ */ __exportAll({
3145
+ Deflate: () => Decompressor$2,
3146
+ Gzip: () => Decompressor$1,
3147
+ Zlib: () => Decompressor,
3148
+ auto: () => decompress,
3149
+ deflate: () => decompress$3,
3150
+ gzip: () => decompress$2,
3151
+ zlib: () => decompress$1
3152
+ });
3153
+ //#endregion
3154
+ export { Adler32, AggregateError, AsyncInterval, AsyncLock, AsyncQueue, AsyncResource, ChecksumMismatchError, ConditionVariable, Crc32, CustomMap, CustomSet, Deferred, DeferredTracked, Deque, Emitter, FlateError, InvalidBlockTypeError, InvalidDistanceError, InvalidHeaderError, InvalidLengthLiteralError, LruMap, LruSet, NotImplementedError, StreamFinishedError, UnexpectedEofError, abs, adler32, asNonNull, assert, assertEndsWith, assertEndsWith as assertsEndsWith, assertHashKey, assertMatches, assertNotNull, assertStartsWith, asyncPool, base64_exports as base64, bitLength, clearUndefinedInPlace, composeMiddlewares, compress_exports as compress, crc32, decompress_exports as decompress, deepMerge, enumerate, euclideanGcd, fromBytes, hex_exports as hex, isBigInt, isBoolean, isFalsy, isFunction, isNotNull, isNotUndefined, isNumber, isObject, isString, isSymbol, isTruthy, max, max2, min, min2, modInv, modPowBinary, noop, objectEntries, objectKeys, parallelMap, sleep, splitOnce, throwNotImplemented, throwUnreachable, timers_exports as timers, toBytes, twoMultiplicity, typed_exports as typed, u8_exports as u8, unknownToError, unsafeCastType, utf8_exports as utf8 };