@beyondwork/xlsx-substrate-bindings 0.1.0 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (42) hide show
  1. package/README.md +136 -0
  2. package/dist/ai/agent-metadata.d.ts +363 -0
  3. package/dist/ai/agent-metadata.js +227 -0
  4. package/dist/ai/index.d.ts +5 -1
  5. package/dist/ai/index.js +6 -0
  6. package/dist/ai/mutation-bridge.d.ts +82 -0
  7. package/dist/ai/mutation-bridge.js +179 -0
  8. package/dist/ai/types.d.ts +448 -3
  9. package/dist/index.d.ts +7 -3
  10. package/dist/index.js +20 -2
  11. package/dist/runtime/index.d.ts +1 -1
  12. package/dist/runtime/types.d.ts +57 -1
  13. package/dist/wasm/ai-session-bridge.d.ts +97 -0
  14. package/dist/wasm/ai-session-bridge.js +154 -0
  15. package/dist/wasm/bridge-contract.d.ts +108 -6
  16. package/dist/wasm/bridge-contract.js +146 -7
  17. package/dist/wasm/index.d.ts +43 -2
  18. package/dist/wasm/index.js +253 -23
  19. package/dist/wasm/memory-budget.d.ts +77 -0
  20. package/dist/wasm/memory-budget.js +532 -0
  21. package/dist/wasm/runtime-guard.d.ts +141 -0
  22. package/dist/wasm/runtime-guard.js +373 -0
  23. package/dist/wasm/web.d.ts +16 -3
  24. package/dist/wasm/web.js +91 -9
  25. package/generated/wasm-web/xlsx_substrate_wasm.d.ts +66 -0
  26. package/generated/wasm-web/xlsx_substrate_wasm.js +2488 -2104
  27. package/generated/wasm-web/xlsx_substrate_wasm_bg.wasm +0 -0
  28. package/generated/wasm-web/xlsx_substrate_wasm_bg.wasm.d.ts +15 -0
  29. package/package.json +18 -4
  30. package/dist/wasm/chart-test-fixture.d.ts +0 -19
  31. package/dist/wasm/chart-test-fixture.js +0 -42
  32. package/dist/wasm/media-test-fixture.d.ts +0 -44
  33. package/dist/wasm/media-test-fixture.js +0 -160
  34. package/dist/wasm/volatile-test-fixture.d.ts +0 -7
  35. package/dist/wasm/volatile-test-fixture.js +0 -35
  36. package/generated/wasm/package.json +0 -3
  37. package/generated/wasm/sheet-window-binary.mjs +0 -482
  38. package/generated/wasm/snippets/ironcalc_base-89b4f49381e1e289/inline0.js +0 -45
  39. package/generated/wasm/xlsx_substrate_wasm.d.ts +0 -336
  40. package/generated/wasm/xlsx_substrate_wasm.js +0 -2108
  41. package/generated/wasm/xlsx_substrate_wasm_bg.wasm +0 -0
  42. package/generated/wasm/xlsx_substrate_wasm_bg.wasm.d.ts +0 -105
@@ -0,0 +1,77 @@
1
+ /** The 64 KiB wasm page. */
2
+ export declare const XLSX_WASM_PAGE_BYTES: number;
3
+ /**
4
+ * The linear-memory maximum `scripts/build-wasm.mjs` sets at link time
5
+ * (`-C link-arg=--max-memory`). 2 GiB is the value the S34 runtime policy
6
+ * ruling sets: half the wasm32 address space, so a runaway allocation traps
7
+ * well before the engine's 4 GiB ceiling, with room above the 1 GiB point
8
+ * where xlsx-api recycles a worker. The build checks the emitted module
9
+ * against this number.
10
+ */
11
+ export declare const XLSX_WASM_LINEAR_MEMORY_MAXIMUM_BYTES: number;
12
+ /**
13
+ * Pre-admission estimate weights. They are coarse and they are NOT upper
14
+ * bounds. One measurement so far (gate job d950f2f82b9948d8b4ae62b28d0a80d0,
15
+ * the memory-contract test's 5,000 x 21 workbook with one SUM per row): the
16
+ * estimate was 26.7 MB for open plus recalculation, and linear memory grew
17
+ * 244 MB. So admission refuses packages whose declared size or shape is far
18
+ * over budget, and a workbook it admits can still exhaust memory; trap
19
+ * containment is the backstop. Calibrating these needs retained and peak
20
+ * figures per workbook shape.
21
+ *
22
+ * A part's declared uncompressed bytes count twice (the inflated XML plus
23
+ * the model built from it), and each cell a sheet can hold counts
24
+ * `ESTIMATE_BYTES_PER_CELL` (cell record, layout and calc-graph entries). A
25
+ * sheet's cell count is the smaller of its `<dimension>` area and what its XML
26
+ * size can carry at `ESTIMATE_MIN_CELL_XML_BYTES` per cell, so a sparse sheet
27
+ * with a whole-grid dimension is not refused for its declared shape.
28
+ */
29
+ export declare const ESTIMATE_PART_EXPANSION = 2;
30
+ export declare const ESTIMATE_BYTES_PER_CELL = 128;
31
+ export declare const ESTIMATE_MIN_CELL_XML_BYTES = 10;
32
+ /** Recalculation working set per cell the session holds. */
33
+ export declare const ESTIMATE_RECALC_BYTES_PER_CELL = 64;
34
+ /**
35
+ * How much compressed input one `<dimension>` read may consume. Output alone
36
+ * does not bound the work: an empty stored block is 5 input bytes and no
37
+ * output, so a part made of them would keep the decoder looping through its
38
+ * whole declared size. 64 KiB is four times the output prefix, which covers
39
+ * a stored (uncompressible) prefix with room to spare.
40
+ */
41
+ export declare const DIMENSION_INPUT_BYTES: number;
42
+ export interface XlsxWasmMemoryLimits {
43
+ readonly minimumBytes: number;
44
+ /** Undefined when the module declares no maximum. */
45
+ readonly maximumBytes: number | undefined;
46
+ }
47
+ /**
48
+ * The linear-memory limits of a wasm binary's first defined memory (memory
49
+ * section, id 5), or undefined when the binary defines none or is not wasm.
50
+ */
51
+ export declare function readWasmMemoryLimits(bytes: Uint8Array): XlsxWasmMemoryLimits | undefined;
52
+ export interface XlsxPackageMemoryEstimate {
53
+ /** Bytes handed to the bridge (copied into linear memory as is). */
54
+ readonly packageBytes: number;
55
+ /** False when no ZIP central directory was found; the estimate is then the package size. */
56
+ readonly zipReadable: boolean;
57
+ readonly partCount: number;
58
+ /** Sum of the parts' declared uncompressed sizes. */
59
+ readonly declaredUncompressedBytes: number;
60
+ readonly worksheetCount: number;
61
+ /** Cells the worksheets can hold (dimension area, bounded by XML size). */
62
+ readonly cellBound: number;
63
+ /** Worksheets whose `<dimension>` was read. */
64
+ readonly dimensionsRead: number;
65
+ /** The open estimate: package + expanded parts + cells. */
66
+ readonly estimatedBytes: number;
67
+ /** The recalculation working-set estimate for the same workbook. */
68
+ readonly recalcEstimatedBytes: number;
69
+ }
70
+ /**
71
+ * Estimate the linear memory opening `bytes` needs, from the package's
72
+ * declared part sizes and sheet dimensions, without calling into wasm. Never
73
+ * throws: a malformed package gets the package-size estimate and the native
74
+ * open reports its own typed error.
75
+ */
76
+ export declare function estimateXlsxPackageMemory(bytes: Uint8Array): XlsxPackageMemoryEstimate;
77
+ export declare function inflateRawPrefix(input: Uint8Array, maxOutput: number, maxInput?: number): Uint8Array;
@@ -0,0 +1,532 @@
1
+ // Runtime 0.2.0 memory contract (R4), the parts that need no wasm call:
2
+ // the link-time linear-memory maximum, a reader for a wasm binary's memory
3
+ // limits, and the pre-admission estimate the bridge checks before it opens
4
+ // or recalculates a workbook. Browser-safe: no `node:` imports, no
5
+ // references to generated artifacts, synchronous, and bounded in the work it
6
+ // does on untrusted bytes.
7
+ /** The 64 KiB wasm page. */
8
+ export const XLSX_WASM_PAGE_BYTES = 64 * 1024;
9
+ /**
10
+ * The linear-memory maximum `scripts/build-wasm.mjs` sets at link time
11
+ * (`-C link-arg=--max-memory`). 2 GiB is the value the S34 runtime policy
12
+ * ruling sets: half the wasm32 address space, so a runaway allocation traps
13
+ * well before the engine's 4 GiB ceiling, with room above the 1 GiB point
14
+ * where xlsx-api recycles a worker. The build checks the emitted module
15
+ * against this number.
16
+ */
17
+ export const XLSX_WASM_LINEAR_MEMORY_MAXIMUM_BYTES = 2 * 1024 * 1024 * 1024;
18
+ /**
19
+ * Pre-admission estimate weights. They are coarse and they are NOT upper
20
+ * bounds. One measurement so far (gate job d950f2f82b9948d8b4ae62b28d0a80d0,
21
+ * the memory-contract test's 5,000 x 21 workbook with one SUM per row): the
22
+ * estimate was 26.7 MB for open plus recalculation, and linear memory grew
23
+ * 244 MB. So admission refuses packages whose declared size or shape is far
24
+ * over budget, and a workbook it admits can still exhaust memory; trap
25
+ * containment is the backstop. Calibrating these needs retained and peak
26
+ * figures per workbook shape.
27
+ *
28
+ * A part's declared uncompressed bytes count twice (the inflated XML plus
29
+ * the model built from it), and each cell a sheet can hold counts
30
+ * `ESTIMATE_BYTES_PER_CELL` (cell record, layout and calc-graph entries). A
31
+ * sheet's cell count is the smaller of its `<dimension>` area and what its XML
32
+ * size can carry at `ESTIMATE_MIN_CELL_XML_BYTES` per cell, so a sparse sheet
33
+ * with a whole-grid dimension is not refused for its declared shape.
34
+ */
35
+ export const ESTIMATE_PART_EXPANSION = 2;
36
+ export const ESTIMATE_BYTES_PER_CELL = 128;
37
+ export const ESTIMATE_MIN_CELL_XML_BYTES = 10;
38
+ /** Recalculation working set per cell the session holds. */
39
+ export const ESTIMATE_RECALC_BYTES_PER_CELL = 64;
40
+ /** How much of each worksheet part is inflated to find `<dimension>`. */
41
+ const DIMENSION_PREFIX_BYTES = 16 * 1024;
42
+ /**
43
+ * How much compressed input one `<dimension>` read may consume. Output alone
44
+ * does not bound the work: an empty stored block is 5 input bytes and no
45
+ * output, so a part made of them would keep the decoder looping through its
46
+ * whole declared size. 64 KiB is four times the output prefix, which covers
47
+ * a stored (uncompressible) prefix with room to spare.
48
+ */
49
+ export const DIMENSION_INPUT_BYTES = 64 * 1024;
50
+ /** Bounds on the work done reading an untrusted package. */
51
+ const MAX_CENTRAL_DIRECTORY_ENTRIES = 100_000;
52
+ const MAX_DIMENSION_READS = 512;
53
+ /**
54
+ * The linear-memory limits of a wasm binary's first defined memory (memory
55
+ * section, id 5), or undefined when the binary defines none or is not wasm.
56
+ */
57
+ export function readWasmMemoryLimits(bytes) {
58
+ if (bytes.length < 8 ||
59
+ bytes[0] !== 0x00 ||
60
+ bytes[1] !== 0x61 ||
61
+ bytes[2] !== 0x73 ||
62
+ bytes[3] !== 0x6d) {
63
+ return undefined;
64
+ }
65
+ let offset = 8;
66
+ const leb = () => {
67
+ let result = 0;
68
+ let shift = 0;
69
+ for (;;) {
70
+ if (offset >= bytes.length || shift > 63) {
71
+ throw new RangeError("truncated LEB128");
72
+ }
73
+ const byte = bytes[offset++];
74
+ result += (byte & 0x7f) * 2 ** shift;
75
+ shift += 7;
76
+ if ((byte & 0x80) === 0) {
77
+ return result;
78
+ }
79
+ }
80
+ };
81
+ try {
82
+ while (offset < bytes.length) {
83
+ const id = bytes[offset++];
84
+ const size = leb();
85
+ const end = offset + size;
86
+ if (id === 5) {
87
+ if (leb() < 1) {
88
+ return undefined;
89
+ }
90
+ const flags = bytes[offset++];
91
+ const minimumPages = leb();
92
+ const maximumPages = flags & 1 ? leb() : undefined;
93
+ return {
94
+ minimumBytes: minimumPages * XLSX_WASM_PAGE_BYTES,
95
+ maximumBytes: maximumPages === undefined ? undefined : maximumPages * XLSX_WASM_PAGE_BYTES
96
+ };
97
+ }
98
+ offset = end;
99
+ }
100
+ }
101
+ catch {
102
+ return undefined;
103
+ }
104
+ return undefined;
105
+ }
106
+ /**
107
+ * Estimate the linear memory opening `bytes` needs, from the package's
108
+ * declared part sizes and sheet dimensions, without calling into wasm. Never
109
+ * throws: a malformed package gets the package-size estimate and the native
110
+ * open reports its own typed error.
111
+ */
112
+ export function estimateXlsxPackageMemory(bytes) {
113
+ const packageBytes = bytes.byteLength;
114
+ const entries = readCentralDirectory(bytes);
115
+ if (!entries) {
116
+ return {
117
+ packageBytes,
118
+ zipReadable: false,
119
+ partCount: 0,
120
+ declaredUncompressedBytes: 0,
121
+ worksheetCount: 0,
122
+ cellBound: 0,
123
+ dimensionsRead: 0,
124
+ estimatedBytes: packageBytes,
125
+ recalcEstimatedBytes: 0
126
+ };
127
+ }
128
+ let declaredUncompressedBytes = 0;
129
+ let worksheetCount = 0;
130
+ let cellBound = 0;
131
+ let dimensionsRead = 0;
132
+ let dimensionAttempts = 0;
133
+ // A crafted directory can point many entries at one local header; read
134
+ // each header's data once.
135
+ const headersRead = new Set();
136
+ for (const entry of entries) {
137
+ declaredUncompressedBytes += entry.uncompressedSize;
138
+ if (!/^xl\/worksheets\/[^/]+\.xml$/iu.test(entry.name)) {
139
+ continue;
140
+ }
141
+ worksheetCount += 1;
142
+ const xmlBound = Math.floor(entry.uncompressedSize / ESTIMATE_MIN_CELL_XML_BYTES);
143
+ let cells = xmlBound;
144
+ if (dimensionAttempts < MAX_DIMENSION_READS && !headersRead.has(entry.localHeaderOffset)) {
145
+ headersRead.add(entry.localHeaderOffset);
146
+ dimensionAttempts += 1;
147
+ const dimension = readWorksheetDimension(bytes, entry);
148
+ if (dimension !== undefined) {
149
+ dimensionsRead += 1;
150
+ cells = Math.min(dimension, xmlBound);
151
+ }
152
+ }
153
+ cellBound += cells;
154
+ }
155
+ const estimatedBytes = packageBytes + declaredUncompressedBytes * ESTIMATE_PART_EXPANSION + cellBound * ESTIMATE_BYTES_PER_CELL;
156
+ return {
157
+ packageBytes,
158
+ zipReadable: true,
159
+ partCount: entries.length,
160
+ declaredUncompressedBytes,
161
+ worksheetCount,
162
+ cellBound,
163
+ dimensionsRead,
164
+ estimatedBytes,
165
+ recalcEstimatedBytes: cellBound * ESTIMATE_RECALC_BYTES_PER_CELL
166
+ };
167
+ }
168
+ function u16(bytes, offset) {
169
+ return bytes[offset] | (bytes[offset + 1] << 8);
170
+ }
171
+ function u32(bytes, offset) {
172
+ return ((bytes[offset] |
173
+ (bytes[offset + 1] << 8) |
174
+ (bytes[offset + 2] << 16) |
175
+ (bytes[offset + 3] << 24)) >>>
176
+ 0);
177
+ }
178
+ function u64(bytes, offset) {
179
+ return u32(bytes, offset) + u32(bytes, offset + 4) * 2 ** 32;
180
+ }
181
+ function readCentralDirectory(bytes) {
182
+ const length = bytes.byteLength;
183
+ if (length < 22) {
184
+ return undefined;
185
+ }
186
+ let eocd = -1;
187
+ for (let offset = length - 22; offset >= Math.max(0, length - 22 - 0xffff); offset -= 1) {
188
+ if (u32(bytes, offset) === 0x06054b50) {
189
+ eocd = offset;
190
+ break;
191
+ }
192
+ }
193
+ if (eocd < 0) {
194
+ return undefined;
195
+ }
196
+ let entryCount = u16(bytes, eocd + 10);
197
+ let directorySize = u32(bytes, eocd + 12);
198
+ let directoryOffset = u32(bytes, eocd + 16);
199
+ if (entryCount === 0xffff || directorySize === 0xffffffff || directoryOffset === 0xffffffff) {
200
+ const locator = eocd - 20;
201
+ if (locator >= 0 && u32(bytes, locator) === 0x07064b50) {
202
+ const zip64 = u64(bytes, locator + 8);
203
+ if (zip64 + 56 <= length && u32(bytes, zip64) === 0x06064b50) {
204
+ entryCount = u64(bytes, zip64 + 32);
205
+ directorySize = u64(bytes, zip64 + 40);
206
+ directoryOffset = u64(bytes, zip64 + 48);
207
+ }
208
+ }
209
+ }
210
+ if (directoryOffset + directorySize > length) {
211
+ return undefined;
212
+ }
213
+ const entries = [];
214
+ let offset = directoryOffset;
215
+ const limit = Math.min(entryCount, MAX_CENTRAL_DIRECTORY_ENTRIES);
216
+ for (let index = 0; index < limit; index += 1) {
217
+ if (offset + 46 > length || u32(bytes, offset) !== 0x02014b50) {
218
+ break;
219
+ }
220
+ const method = u16(bytes, offset + 10);
221
+ let compressedSize = u32(bytes, offset + 20);
222
+ let uncompressedSize = u32(bytes, offset + 24);
223
+ const nameLength = u16(bytes, offset + 28);
224
+ const extraLength = u16(bytes, offset + 30);
225
+ const commentLength = u16(bytes, offset + 32);
226
+ let localHeaderOffset = u32(bytes, offset + 42);
227
+ const nameStart = offset + 46;
228
+ if (nameStart + nameLength + extraLength > length) {
229
+ break;
230
+ }
231
+ let name = "";
232
+ for (let cursor = nameStart; cursor < nameStart + nameLength; cursor += 1) {
233
+ name += String.fromCharCode(bytes[cursor]);
234
+ }
235
+ // ZIP64 extended information (header id 1): only the fields whose
236
+ // 32-bit slot is saturated are present, in this order.
237
+ let extra = nameStart + nameLength;
238
+ const extraEnd = extra + extraLength;
239
+ while (extra + 4 <= extraEnd) {
240
+ const id = u16(bytes, extra);
241
+ const size = u16(bytes, extra + 2);
242
+ if (id === 0x0001) {
243
+ let field = extra + 4;
244
+ if (uncompressedSize === 0xffffffff && field + 8 <= extra + 4 + size) {
245
+ uncompressedSize = u64(bytes, field);
246
+ field += 8;
247
+ }
248
+ if (compressedSize === 0xffffffff && field + 8 <= extra + 4 + size) {
249
+ compressedSize = u64(bytes, field);
250
+ field += 8;
251
+ }
252
+ if (localHeaderOffset === 0xffffffff && field + 8 <= extra + 4 + size) {
253
+ localHeaderOffset = u64(bytes, field);
254
+ }
255
+ }
256
+ extra += 4 + size;
257
+ }
258
+ entries.push({ name, method, compressedSize, uncompressedSize, localHeaderOffset });
259
+ offset = extraEnd + commentLength;
260
+ }
261
+ return entries;
262
+ }
263
+ /** Cell area of a worksheet part's `<dimension ref>`, or undefined when unreadable. */
264
+ function readWorksheetDimension(bytes, entry) {
265
+ const header = entry.localHeaderOffset;
266
+ if (header + 30 > bytes.byteLength || u32(bytes, header) !== 0x04034b50) {
267
+ return undefined;
268
+ }
269
+ const dataStart = header + 30 + u16(bytes, header + 26) + u16(bytes, header + 28);
270
+ const dataEnd = Math.min(bytes.byteLength, dataStart + entry.compressedSize);
271
+ if (dataStart >= dataEnd) {
272
+ return undefined;
273
+ }
274
+ let prefix;
275
+ if (entry.method === 0) {
276
+ prefix = bytes.subarray(dataStart, Math.min(dataEnd, dataStart + DIMENSION_PREFIX_BYTES));
277
+ }
278
+ else if (entry.method === 8) {
279
+ try {
280
+ prefix = inflateRawPrefix(bytes.subarray(dataStart, dataEnd), DIMENSION_PREFIX_BYTES, DIMENSION_INPUT_BYTES);
281
+ }
282
+ catch {
283
+ return undefined;
284
+ }
285
+ }
286
+ else {
287
+ return undefined;
288
+ }
289
+ let text = "";
290
+ for (let index = 0; index < prefix.length; index += 1) {
291
+ text += String.fromCharCode(prefix[index]);
292
+ }
293
+ const match = /<(?:[A-Za-z_][\w.-]*:)?dimension\b[^>]*?\bref\s*=\s*["']\$?([A-Za-z]{1,3})\$?(\d{1,7})(?::\$?([A-Za-z]{1,3})\$?(\d{1,7}))?["']/u.exec(text);
294
+ if (!match) {
295
+ return undefined;
296
+ }
297
+ const startColumn = columnNumber(match[1]);
298
+ const startRow = Number(match[2]);
299
+ const endColumn = match[3] ? columnNumber(match[3]) : startColumn;
300
+ const endRow = match[4] ? Number(match[4]) : startRow;
301
+ const rows = Math.abs(endRow - startRow) + 1;
302
+ const columns = Math.abs(endColumn - startColumn) + 1;
303
+ return rows * columns;
304
+ }
305
+ function columnNumber(letters) {
306
+ let value = 0;
307
+ for (const letter of letters.toUpperCase()) {
308
+ value = value * 26 + (letter.charCodeAt(0) - 64);
309
+ }
310
+ return value;
311
+ }
312
+ // ---------------------------------------------------------------------------
313
+ // Raw DEFLATE (RFC 1951), prefix only. Decodes at most `maxOutput` bytes from
314
+ // at most `maxInput` input bytes and stops, so reading a worksheet's
315
+ // `<dimension>` costs at most 16 KiB of output and 64 KiB of input whatever
316
+ // the part's size or shape. When the input budget runs out first it returns
317
+ // what it decoded so far. Throws on malformed input; the caller treats that
318
+ // as "no dimension".
319
+ const LENGTH_BASE = [3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31, 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258];
320
+ const LENGTH_EXTRA = [0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0];
321
+ const DISTANCE_BASE = [
322
+ 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193, 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,
323
+ 8193, 12289, 16385, 24577
324
+ ];
325
+ const DISTANCE_EXTRA = [0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13];
326
+ const CODE_LENGTH_ORDER = [16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15];
327
+ function buildHuffman(lengths, count) {
328
+ const counts = new Uint16Array(16);
329
+ for (let symbol = 0; symbol < count; symbol += 1) {
330
+ const length = lengths[symbol];
331
+ counts[length] = counts[length] + 1;
332
+ }
333
+ counts[0] = 0;
334
+ const offsets = new Uint16Array(16);
335
+ for (let length = 1; length < 16; length += 1) {
336
+ offsets[length] = offsets[length - 1] + counts[length - 1];
337
+ }
338
+ const symbols = new Uint16Array(count);
339
+ for (let symbol = 0; symbol < count; symbol += 1) {
340
+ const length = lengths[symbol];
341
+ if (length !== 0) {
342
+ const slot = offsets[length];
343
+ symbols[slot] = symbol;
344
+ offsets[length] = slot + 1;
345
+ }
346
+ }
347
+ return { counts, symbols };
348
+ }
349
+ let fixedLiteral;
350
+ let fixedDistance;
351
+ function fixedTables() {
352
+ if (!fixedLiteral || !fixedDistance) {
353
+ const lengths = new Uint8Array(288);
354
+ lengths.fill(8, 0, 144);
355
+ lengths.fill(9, 144, 256);
356
+ lengths.fill(7, 256, 280);
357
+ lengths.fill(8, 280, 288);
358
+ fixedLiteral = buildHuffman(lengths, 288);
359
+ fixedDistance = buildHuffman(new Uint8Array(30).fill(5), 30);
360
+ }
361
+ return [fixedLiteral, fixedDistance];
362
+ }
363
+ /** Thrown inside `inflateRawPrefix` when the input budget runs out; never escapes it. */
364
+ class InputBudgetUsedUp extends Error {
365
+ }
366
+ export function inflateRawPrefix(input, maxOutput, maxInput = Number.POSITIVE_INFINITY) {
367
+ const output = new Uint8Array(maxOutput);
368
+ let outputLength = 0;
369
+ try {
370
+ inflateInto(input, output, maxInput, (length) => {
371
+ outputLength = length;
372
+ });
373
+ }
374
+ catch (error) {
375
+ if (!(error instanceof InputBudgetUsedUp))
376
+ throw error;
377
+ }
378
+ return outputLength === maxOutput ? output : output.subarray(0, outputLength);
379
+ }
380
+ function inflateInto(input, output, maxInput, report) {
381
+ const maxOutput = output.length;
382
+ const inputLimit = Math.min(input.length, maxInput);
383
+ let outputLength = 0;
384
+ let position = 0;
385
+ let bitBuffer = 0;
386
+ let bitCount = 0;
387
+ const budgetUsedUp = () => {
388
+ report(outputLength);
389
+ throw new InputBudgetUsedUp();
390
+ };
391
+ const bits = (need) => {
392
+ while (bitCount < need) {
393
+ if (position >= inputLimit) {
394
+ if (inputLimit < input.length)
395
+ budgetUsedUp();
396
+ throw new RangeError("deflate input ended early");
397
+ }
398
+ bitBuffer |= input[position++] << bitCount;
399
+ bitCount += 8;
400
+ }
401
+ const value = bitBuffer & ((1 << need) - 1);
402
+ bitBuffer >>>= need;
403
+ bitCount -= need;
404
+ return value;
405
+ };
406
+ const decode = (table) => {
407
+ let code = 0;
408
+ let first = 0;
409
+ let index = 0;
410
+ for (let length = 1; length < 16; length += 1) {
411
+ code |= bits(1);
412
+ const count = table.counts[length];
413
+ if (code - count < first) {
414
+ return table.symbols[index + (code - first)];
415
+ }
416
+ index += count;
417
+ first += count;
418
+ first <<= 1;
419
+ code <<= 1;
420
+ }
421
+ throw new RangeError("invalid deflate code");
422
+ };
423
+ let final = 0;
424
+ while (final === 0 && outputLength < maxOutput) {
425
+ final = bits(1);
426
+ const type = bits(2);
427
+ if (type === 0) {
428
+ bitBuffer = 0;
429
+ bitCount = 0;
430
+ if (position + 4 > inputLimit) {
431
+ if (inputLimit < input.length)
432
+ budgetUsedUp();
433
+ throw new RangeError("stored block header ended early");
434
+ }
435
+ const length = u16(input, position);
436
+ if ((length ^ 0xffff) !== u16(input, position + 2)) {
437
+ throw new RangeError("stored block length check failed");
438
+ }
439
+ position += 4;
440
+ const take = Math.min(length, maxOutput - outputLength, inputLimit - position);
441
+ output.set(input.subarray(position, position + take), outputLength);
442
+ outputLength += take;
443
+ position += length;
444
+ continue;
445
+ }
446
+ let literal;
447
+ let distance;
448
+ if (type === 1) {
449
+ [literal, distance] = fixedTables();
450
+ }
451
+ else if (type === 2) {
452
+ const literalCount = bits(5) + 257;
453
+ const distanceCount = bits(5) + 1;
454
+ const codeLengthCount = bits(4) + 4;
455
+ const codeLengths = new Uint8Array(19);
456
+ for (let index = 0; index < codeLengthCount; index += 1) {
457
+ codeLengths[CODE_LENGTH_ORDER[index]] = bits(3);
458
+ }
459
+ const codeLengthTable = buildHuffman(codeLengths, 19);
460
+ const lengths = new Uint8Array(literalCount + distanceCount);
461
+ let index = 0;
462
+ while (index < literalCount + distanceCount) {
463
+ const symbol = decode(codeLengthTable);
464
+ if (symbol < 16) {
465
+ lengths[index++] = symbol;
466
+ continue;
467
+ }
468
+ let repeat;
469
+ let value = 0;
470
+ if (symbol === 16) {
471
+ if (index === 0) {
472
+ throw new RangeError("repeat with no previous length");
473
+ }
474
+ value = lengths[index - 1];
475
+ repeat = 3 + bits(2);
476
+ }
477
+ else if (symbol === 17) {
478
+ repeat = 3 + bits(3);
479
+ }
480
+ else {
481
+ repeat = 11 + bits(7);
482
+ }
483
+ if (index + repeat > lengths.length) {
484
+ throw new RangeError("code lengths overflow");
485
+ }
486
+ lengths.fill(value, index, index + repeat);
487
+ index += repeat;
488
+ }
489
+ literal = buildHuffman(lengths.subarray(0, literalCount), literalCount);
490
+ distance = buildHuffman(lengths.subarray(literalCount), distanceCount);
491
+ }
492
+ else {
493
+ throw new RangeError("invalid deflate block type");
494
+ }
495
+ for (;;) {
496
+ const symbol = decode(literal);
497
+ if (symbol < 256) {
498
+ output[outputLength++] = symbol;
499
+ if (outputLength >= maxOutput) {
500
+ report(outputLength);
501
+ return;
502
+ }
503
+ continue;
504
+ }
505
+ if (symbol === 256) {
506
+ break;
507
+ }
508
+ const lengthIndex = symbol - 257;
509
+ if (lengthIndex >= LENGTH_BASE.length) {
510
+ throw new RangeError("invalid length symbol");
511
+ }
512
+ const length = LENGTH_BASE[lengthIndex] + bits(LENGTH_EXTRA[lengthIndex]);
513
+ const distanceSymbol = decode(distance);
514
+ if (distanceSymbol >= DISTANCE_BASE.length) {
515
+ throw new RangeError("invalid distance symbol");
516
+ }
517
+ const back = DISTANCE_BASE[distanceSymbol] + bits(DISTANCE_EXTRA[distanceSymbol]);
518
+ if (back > outputLength) {
519
+ throw new RangeError("distance before output start");
520
+ }
521
+ for (let copied = 0; copied < length; copied += 1) {
522
+ output[outputLength] = output[outputLength - back];
523
+ outputLength += 1;
524
+ if (outputLength >= maxOutput) {
525
+ report(outputLength);
526
+ return;
527
+ }
528
+ }
529
+ }
530
+ }
531
+ report(outputLength);
532
+ }