@beyondwork/xlsx-substrate-bindings 0.0.0-stage → 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 (47) hide show
  1. package/LICENSE.md +31 -0
  2. package/README.md +135 -2
  3. package/dist/ai/agent-metadata.d.ts +363 -0
  4. package/dist/ai/agent-metadata.js +227 -0
  5. package/dist/ai/index.d.ts +6 -0
  6. package/dist/ai/index.js +7 -0
  7. package/dist/ai/mutation-bridge.d.ts +82 -0
  8. package/dist/ai/mutation-bridge.js +179 -0
  9. package/dist/ai/types.d.ts +765 -0
  10. package/dist/ai/types.js +23 -0
  11. package/dist/index.d.ts +50 -0
  12. package/dist/index.js +90 -0
  13. package/dist/runtime/index.d.ts +2 -0
  14. package/dist/runtime/index.js +1 -0
  15. package/dist/runtime/types.d.ts +1435 -0
  16. package/dist/runtime/types.js +15 -0
  17. package/dist/shared.d.ts +69 -0
  18. package/dist/shared.js +1 -0
  19. package/dist/ui/index.d.ts +2 -0
  20. package/dist/ui/index.js +1 -0
  21. package/dist/ui/types.d.ts +765 -0
  22. package/dist/ui/types.js +12 -0
  23. package/dist/wasm/ai-session-bridge.d.ts +97 -0
  24. package/dist/wasm/ai-session-bridge.js +154 -0
  25. package/dist/wasm/bridge-contract.d.ts +643 -0
  26. package/dist/wasm/bridge-contract.js +1001 -0
  27. package/dist/wasm/index.d.ts +50 -0
  28. package/dist/wasm/index.js +297 -0
  29. package/dist/wasm/memory-budget.d.ts +77 -0
  30. package/dist/wasm/memory-budget.js +532 -0
  31. package/dist/wasm/runtime-guard.d.ts +141 -0
  32. package/dist/wasm/runtime-guard.js +373 -0
  33. package/dist/wasm/session-router.d.ts +98 -0
  34. package/dist/wasm/session-router.js +184 -0
  35. package/dist/wasm/sheet-window-binary-reference.d.ts +9 -0
  36. package/dist/wasm/sheet-window-binary-reference.js +308 -0
  37. package/dist/wasm/sheet-window-binary.d.ts +279 -0
  38. package/dist/wasm/sheet-window-binary.js +636 -0
  39. package/dist/wasm/web.d.ts +72 -0
  40. package/dist/wasm/web.js +142 -0
  41. package/generated/wasm-web/package.json +3 -0
  42. package/generated/wasm-web/snippets/ironcalc_base-89b4f49381e1e289/inline0.js +42 -0
  43. package/generated/wasm-web/xlsx_substrate_wasm.d.ts +532 -0
  44. package/generated/wasm-web/xlsx_substrate_wasm.js +2493 -0
  45. package/generated/wasm-web/xlsx_substrate_wasm_bg.wasm +0 -0
  46. package/generated/wasm-web/xlsx_substrate_wasm_bg.wasm.d.ts +120 -0
  47. package/package.json +55 -3
@@ -0,0 +1,636 @@
1
+ /**
2
+ * T5 — Binary Sheet-Window Snapshot v1 (`xlsx-sheet-window-binary/1`) decoder.
3
+ *
4
+ * The wasm export `readRuntimeSessionSheetWindowBinary` returns a hybrid
5
+ * envelope `{ schemaId, bytes, rest }`: `bytes` carries the four bulk arrays
6
+ * (`rows`, `columns`, `cells`, `paintGeometry.rows/columns/cells+rects`) in a
7
+ * flat little-endian layout; `rest` is a small JSON DTO with everything O(1)-
8
+ * sized, rare, or deeply nested. This replaces the per-call
9
+ * `serde_wasm_bindgen::to_value` of the full window DTO (~3.5ms of the
10
+ * scroll-step readback; bench BR-6, test/perf/xlsx-interaction-latency.bench.ts).
11
+ *
12
+ * ## Copy-out-once posture (wasm memory-growth footgun)
13
+ *
14
+ * Views into `WebAssembly.Memory` are invalidated by memory growth — any
15
+ * allocation-capable call (including the decode itself, via JS-heap pressure
16
+ * triggering wasm-side reentry in future designs) can leave a `Uint8Array`
17
+ * view over detached garbage. The decoder therefore REQUIRES that
18
+ * `envelope.bytes` is already detached from live wasm memory:
19
+ *
20
+ * - wasm-bindgen `Vec<u8>` returns perform exactly one memcpy out of linear
21
+ * memory into a fresh JS-heap `Uint8Array` in generated glue — that IS the
22
+ * copy-out-once, with no window in which growth can invalidate a view;
23
+ * - through the T2 worker pool the envelope arrives structured-cloned — the
24
+ * `ArrayBuffer` is a fresh copy on the receiving side.
25
+ *
26
+ * A single memcpy of a ~100-400KB snapshot is tens of microseconds —
27
+ * predictable and orders cheaper than the per-field serde it replaces. If a
28
+ * future ptr+len fast path lands, callers must
29
+ * `Uint8Array.prototype.slice()` BEFORE handing bytes to this decoder. As a
30
+ * defensive backstop the decoder copies the region out itself before
31
+ * touching it when `bytes` could alias growable memory: a view over a larger
32
+ * buffer (the signature of a raw view into linear memory), a full-length
33
+ * view over a resizable `ArrayBuffer`, or any view whose backing store is
34
+ * not a plain fixed `ArrayBuffer` (growable or concurrently mutable shared
35
+ * memory).
36
+ *
37
+ * ## Laziness and output shape
38
+ *
39
+ * The decoded object exposes `rows`, `columns`, `cells`, and `paintGeometry`
40
+ * as memoized section-level getters: nothing decodes until first access, and
41
+ * each section decodes wholesale into plain objects **field-identical to the
42
+ * JSON `XlsxUiSheetWindowReadback`** — including serde's key-presence
43
+ * semantics (ground truth probed against the live wasm build):
44
+ *
45
+ * - `Option` fields WITHOUT `skip_serializing_if` are present with value
46
+ * `undefined` (e.g. `formulaText`, `mergeOwner`);
47
+ * - fields WITH `skip_serializing_if` are ABSENT when skipped (`fillColor`,
48
+ * `wrapText`, `borderTop`, ... only exist when set/true);
49
+ * - required arrays (`blockers`, `postureMarkers`, `paintGeometry.objects`)
50
+ * are always present.
51
+ *
52
+ * All `rest` fields pass through unchanged (minus the transport-internal
53
+ * fields enumerated in `decodeSheetWindowBinary`), so readback.ts,
54
+ * tile-scheduler.ts, and the workbook painter consume the decoded object
55
+ * with zero changes. v2 follow-up (named, not in scope): zero-copy-into-paint
56
+ * — teach the canvas painter to read PAINT_CELLS/RECTS typed arrays directly
57
+ * per tile range, skipping object materialization.
58
+ *
59
+ * ## Layout deviations vs the T5 contract draft (frozen here, golden-guarded)
60
+ *
61
+ * The contract's §1 table has three internal inconsistencies this
62
+ * implementation resolves; any further change requires re-agreeing the layout
63
+ * with the Rust encoder and bumping the header version:
64
+ *
65
+ * 1. PAINT_ROWS/PAINT_COLS are 32 B/record, not the stated 24 B (the listed
66
+ * fields sum to 28 and the stated layout misaligns the f64 pair; 32 keeps
67
+ * 8-byte alignment). 32 is the ONLY accepted stride: no encoder emits the
68
+ * contract-draft 28 B packed layout, and tolerating one with a guessed
69
+ * field order would silently decode garbage f64 geometry instead of
70
+ * failing the stride assert.
71
+ * 2. RECTS are 48 B/record, not 32: `UiPaintRectDto` carries per-rect
72
+ * `coordinateSpace` (tagged kind + optional pane region) and `precision`,
73
+ * which the contract's bare x/y/w/h pool cannot represent. Encoded as
74
+ * three interned string ids + pad after the four f64s.
75
+ * 3. `postureMarkers` moved OUT of `rest.rareCells` into an interned
76
+ * string-table id on the cell record (US-joined list, `\x1f` separator):
77
+ * measured prevalence is ~99% of cells (`["empty"]`, `["formula"]`,
78
+ * `["merge-owner"]`, ...) from a tiny vocabulary — the contract's
79
+ * "almost always empty" premise holds for `selectionHandle`/`blockers`
80
+ * (which stay in `rest.rareCells`) but not for markers, and routing ~475
81
+ * marker arrays through JSON `rest` would rebuild the serde cost the
82
+ * binary path removes. Cell records are therefore 96 B, not 88.
83
+ */
84
+ export const SHEET_WINDOW_BINARY_SCHEMA_ID = "xlsx-sheet-window-binary/1";
85
+ /** "XSW1" read as a little-endian u32. */
86
+ export const SHEET_WINDOW_BINARY_MAGIC = 0x31575358;
87
+ export const SHEET_WINDOW_BINARY_VERSION = 1;
88
+ export const SHEET_WINDOW_BINARY_HEADER_BYTES = 32;
89
+ export const SHEET_WINDOW_BINARY_SECTION_ENTRY_BYTES = 16;
90
+ export const SHEET_WINDOW_SECTION_ROWS = 1;
91
+ export const SHEET_WINDOW_SECTION_COLS = 2;
92
+ export const SHEET_WINDOW_SECTION_CELLS = 3;
93
+ export const SHEET_WINDOW_SECTION_PAINT_ROWS = 4;
94
+ export const SHEET_WINDOW_SECTION_PAINT_COLS = 5;
95
+ export const SHEET_WINDOW_SECTION_RECTS = 6;
96
+ export const SHEET_WINDOW_SECTION_PAINT_CELLS = 7;
97
+ export const SHEET_WINDOW_SECTION_STRTAB = 8;
98
+ export const SHEET_WINDOW_SECTION_STRBLOB = 9;
99
+ export const SHEET_WINDOW_LINE_RECORD_BYTES = 24;
100
+ export const SHEET_WINDOW_CELL_RECORD_BYTES = 96;
101
+ export const SHEET_WINDOW_PAINT_LINE_RECORD_BYTES = 32;
102
+ export const SHEET_WINDOW_RECT_RECORD_BYTES = 48;
103
+ export const SHEET_WINDOW_PAINT_CELL_RECORD_BYTES = 32;
104
+ export const SHEET_WINDOW_STRTAB_ENTRY_BYTES = 8;
105
+ /** Sentinel for absent u32 indices (`mergedRangeIdx`, `rareIdx`, `numFmtId`, merge-owner coords). */
106
+ export const SHEET_WINDOW_U32_NONE = 0xffffffff;
107
+ /** Sentinel for absent `outlineLevel`. */
108
+ export const SHEET_WINDOW_OUTLINE_NONE = 0xff;
109
+ /** Separator for the interned `postureMarkers` list (`\u001f` unit separator, cannot appear in marker tokens). */
110
+ export const SHEET_WINDOW_MARKER_SEPARATOR = "\u001f";
111
+ /** Header flag bit0: binary paint-geometry sections are present. */
112
+ export const SHEET_WINDOW_FLAG_PAINT_GEOMETRY = 0x0001;
113
+ const utf8Decoder = new TextDecoder("utf-8", { fatal: true });
114
+ class SheetWindowStringTable {
115
+ view;
116
+ bytes;
117
+ strtab;
118
+ blob;
119
+ cache;
120
+ markerCache = new Map();
121
+ constructor(view, bytes, strtab, blob) {
122
+ this.view = view;
123
+ this.bytes = bytes;
124
+ this.strtab = strtab;
125
+ this.blob = blob;
126
+ this.cache = new Array(strtab.recordCount);
127
+ }
128
+ /** id 0 = absent/None (uniform encoding for every optional string field). */
129
+ at(id) {
130
+ if (id === 0) {
131
+ return undefined;
132
+ }
133
+ if (id >= this.strtab.recordCount) {
134
+ throw new Error(`sheet-window binary: string id ${id} out of range (${this.strtab.recordCount})`);
135
+ }
136
+ const cached = this.cache[id];
137
+ if (cached !== undefined) {
138
+ return cached;
139
+ }
140
+ const entryOffset = this.strtab.byteOffset + id * SHEET_WINDOW_STRTAB_ENTRY_BYTES;
141
+ const blobOffset = this.view.getUint32(entryOffset, true);
142
+ const byteLen = this.view.getUint32(entryOffset + 4, true);
143
+ if (blobOffset + byteLen > this.blob.byteLen) {
144
+ throw new Error(`sheet-window binary: string id ${id} escapes the blob section`);
145
+ }
146
+ const start = this.blob.byteOffset + blobOffset;
147
+ const decoded = utf8Decoder.decode(this.bytes.subarray(start, start + byteLen));
148
+ this.cache[id] = decoded;
149
+ return decoded;
150
+ }
151
+ /** Required-string accessor for enum-like fields that are never absent. */
152
+ required(id, field) {
153
+ const value = this.at(id);
154
+ if (value === undefined) {
155
+ throw new Error(`sheet-window binary: required string field ${field} was absent (id 0)`);
156
+ }
157
+ return value;
158
+ }
159
+ /**
160
+ * Interned `\x1f`-joined posture-marker list. The memoized array is shared
161
+ * across cells with the same marker set — readbacks are immutable by
162
+ * contract, and marker sets repeat on ~99% of cells.
163
+ */
164
+ markers(id) {
165
+ if (id === 0) {
166
+ return [];
167
+ }
168
+ const cached = this.markerCache.get(id);
169
+ if (cached !== undefined) {
170
+ return cached;
171
+ }
172
+ const joined = this.required(id, "postureMarkers");
173
+ // Frozen: the same array instance is shared across every cell with this
174
+ // marker set — a consumer mutation would otherwise corrupt siblings.
175
+ const split = Object.freeze(joined.split(SHEET_WINDOW_MARKER_SEPARATOR));
176
+ this.markerCache.set(id, split);
177
+ return split;
178
+ }
179
+ }
180
+ /**
181
+ * Memoizing lazy getter. When `recover` is provided, a `compute` failure is
182
+ * routed through it: a `{ value }` result is memoized as the substitute (the
183
+ * consumer never observes the throw); `undefined` rethrows the original
184
+ * decode error. This is the seam that lets section-level decode failures —
185
+ * which surface at first CONSUMER access, not inside `decodeSheetWindowBinary`
186
+ * — reach the bridge's permanent-JSON-fallback latch (see
187
+ * `createSheetWindowDecodedReader`).
188
+ */
189
+ function defineLazy(target, key, compute, recover) {
190
+ Object.defineProperty(target, key, {
191
+ enumerable: true,
192
+ configurable: true,
193
+ get() {
194
+ let value;
195
+ try {
196
+ value = compute();
197
+ }
198
+ catch (error) {
199
+ const recovered = recover?.(error);
200
+ if (recovered === undefined) {
201
+ throw error;
202
+ }
203
+ value = recovered.value;
204
+ }
205
+ Object.defineProperty(target, key, {
206
+ enumerable: true,
207
+ configurable: true,
208
+ writable: false,
209
+ value
210
+ });
211
+ return value;
212
+ }
213
+ });
214
+ }
215
+ /**
216
+ * X5-U-008 (ii): vertical alignment by the two-bit code packed into cell-flag
217
+ * bits 8-9. Index 0 is "unset" — the runtime resolved no explicit anchor.
218
+ */
219
+ const SHEET_WINDOW_VERTICAL_ALIGNMENTS = [undefined, "top", "middle", "bottom"];
220
+ /** Cell-record string-id slots in on-wire order (16 × u32 at record offset 8). */
221
+ const CellStr = {
222
+ CellId: 0,
223
+ DisplayText: 1,
224
+ ValueKind: 2,
225
+ FormulaText: 3,
226
+ DisplayFingerprint: 4,
227
+ StyleRef: 5,
228
+ DisplayFormatPosture: 6,
229
+ FormatCode: 7,
230
+ FillColor: 8,
231
+ FontColor: 9,
232
+ FontName: 10,
233
+ FontSizePoints: 11,
234
+ DisplayTextColor: 12,
235
+ HorizontalAlignment: 13,
236
+ MergeRole: 14,
237
+ Editability: 15
238
+ };
239
+ function requireSection(ctx, id, label) {
240
+ const section = ctx.sections.get(id);
241
+ if (!section) {
242
+ throw new Error(`sheet-window binary: missing required section ${label} (${id})`);
243
+ }
244
+ return section;
245
+ }
246
+ function assertStride(section, expected, label) {
247
+ if (section.recordCount === 0) {
248
+ return;
249
+ }
250
+ if (section.recordCount * expected !== section.byteLen) {
251
+ throw new Error(`sheet-window binary: section ${label} stride mismatch — ${section.byteLen} bytes for ${section.recordCount} records (expected ${expected} B/record)`);
252
+ }
253
+ }
254
+ function decodeLineSection(ctx, sectionId, kind) {
255
+ const label = kind === "row" ? "ROWS" : "COLS";
256
+ const section = requireSection(ctx, sectionId, label);
257
+ assertStride(section, SHEET_WINDOW_LINE_RECORD_BYTES, label);
258
+ const { view, strings } = ctx;
259
+ const out = new Array(section.recordCount);
260
+ for (let i = 0; i < section.recordCount; i++) {
261
+ const o = section.byteOffset + i * SHEET_WINDOW_LINE_RECORD_BYTES;
262
+ const line = view.getUint32(o, true);
263
+ const metric = strings.required(view.getUint32(o + 4, true), kind === "row" ? "heightPoints" : "width");
264
+ const precision = strings.required(view.getUint32(o + 8, true), "precision");
265
+ const hiddenPosture = strings.at(view.getUint32(o + 12, true));
266
+ const flags = view.getUint8(o + 16);
267
+ const outlineRaw = view.getUint8(o + 17);
268
+ // Key-presence parity with serde: every field on the line DTOs is
269
+ // unconditionally serialized (Options surface as undefined-valued keys).
270
+ out[i] =
271
+ kind === "row"
272
+ ? {
273
+ row: line,
274
+ heightPoints: metric,
275
+ hidden: (flags & 0x01) !== 0,
276
+ customHeight: (flags & 0x02) !== 0,
277
+ precision,
278
+ outlineLevel: outlineRaw === SHEET_WINDOW_OUTLINE_NONE ? undefined : outlineRaw,
279
+ collapsed: (flags & 0x04) !== 0,
280
+ hiddenPosture
281
+ }
282
+ : {
283
+ column: line,
284
+ width: metric,
285
+ hidden: (flags & 0x01) !== 0,
286
+ customWidth: (flags & 0x02) !== 0,
287
+ precision,
288
+ outlineLevel: outlineRaw === SHEET_WINDOW_OUTLINE_NONE ? undefined : outlineRaw,
289
+ collapsed: (flags & 0x04) !== 0,
290
+ hiddenPosture
291
+ };
292
+ }
293
+ return out;
294
+ }
295
+ function decodeCells(ctx) {
296
+ const section = requireSection(ctx, SHEET_WINDOW_SECTION_CELLS, "CELLS");
297
+ assertStride(section, SHEET_WINDOW_CELL_RECORD_BYTES, "CELLS");
298
+ const { view, strings, rest } = ctx;
299
+ const mergedRanges = rest.mergedRanges;
300
+ const rareCells = rest.rareCells ?? [];
301
+ const out = new Array(section.recordCount);
302
+ for (let i = 0; i < section.recordCount; i++) {
303
+ const o = section.byteOffset + i * SHEET_WINDOW_CELL_RECORD_BYTES;
304
+ const str = (slot) => view.getUint32(o + 8 + slot * 4, true);
305
+ const numFmtRaw = view.getUint32(o + 72, true);
306
+ const flags = view.getUint16(o + 76, true);
307
+ const mergedRangeIdx = view.getUint32(o + 80, true);
308
+ const rareIdx = view.getUint32(o + 84, true);
309
+ const markersId = view.getUint32(o + 88, true);
310
+ const rare = rareIdx === SHEET_WINDOW_U32_NONE ? undefined : rareCells[rareIdx];
311
+ if (rareIdx !== SHEET_WINDOW_U32_NONE && rare === undefined) {
312
+ throw new Error(`sheet-window binary: cell ${i} references missing rareCells[${rareIdx}]`);
313
+ }
314
+ const merged = mergedRangeIdx === SHEET_WINDOW_U32_NONE ? undefined : mergedRanges[mergedRangeIdx];
315
+ if (mergedRangeIdx !== SHEET_WINDOW_U32_NONE && merged === undefined) {
316
+ throw new Error(`sheet-window binary: cell ${i} references missing mergedRanges[${mergedRangeIdx}]`);
317
+ }
318
+ // Field emission mirrors serde on UiSheetWindowCellDto exactly:
319
+ // non-skip Options are present-with-undefined; skip_serializing_if
320
+ // fields (fillColor..horizontalAlignment, wrapText, borders) only exist
321
+ // when set/true. Declaration order matches the DTO for readability.
322
+ const cell = {
323
+ address: { row: view.getUint32(o, true), column: view.getUint32(o + 4, true) },
324
+ cellId: strings.at(str(CellStr.CellId)),
325
+ selectionHandle: rare?.selectionHandle,
326
+ displayText: strings.at(str(CellStr.DisplayText)),
327
+ valueKind: strings.at(str(CellStr.ValueKind)),
328
+ formulaText: strings.at(str(CellStr.FormulaText)),
329
+ displayFingerprint: strings.at(str(CellStr.DisplayFingerprint)),
330
+ styleRef: strings.at(str(CellStr.StyleRef)),
331
+ displayFormatPosture: strings.at(str(CellStr.DisplayFormatPosture)),
332
+ numFmtId: numFmtRaw === SHEET_WINDOW_U32_NONE ? undefined : numFmtRaw,
333
+ formatCode: strings.at(str(CellStr.FormatCode)),
334
+ bold: (flags & 0x0001) !== 0,
335
+ italic: (flags & 0x0002) !== 0,
336
+ underline: (flags & 0x0004) !== 0
337
+ };
338
+ const fillColor = strings.at(str(CellStr.FillColor));
339
+ if (fillColor !== undefined)
340
+ cell.fillColor = fillColor;
341
+ const fontColor = strings.at(str(CellStr.FontColor));
342
+ if (fontColor !== undefined)
343
+ cell.fontColor = fontColor;
344
+ const fontName = strings.at(str(CellStr.FontName));
345
+ if (fontName !== undefined)
346
+ cell.fontName = fontName;
347
+ const fontSizePoints = strings.at(str(CellStr.FontSizePoints));
348
+ if (fontSizePoints !== undefined)
349
+ cell.fontSizePoints = fontSizePoints;
350
+ const displayTextColor = strings.at(str(CellStr.DisplayTextColor));
351
+ if (displayTextColor !== undefined)
352
+ cell.displayTextColor = displayTextColor;
353
+ const horizontalAlignment = strings.at(str(CellStr.HorizontalAlignment));
354
+ if (horizontalAlignment !== undefined)
355
+ cell.horizontalAlignment = horizontalAlignment;
356
+ // X5-U-008 (ii): vertical alignment rides two spare flag bits (8-9) of the
357
+ // frozen 96-byte cell record rather than a 17th string slot.
358
+ const verticalAlignment = SHEET_WINDOW_VERTICAL_ALIGNMENTS[(flags >> 8) & 0x03];
359
+ if (verticalAlignment !== undefined)
360
+ cell.verticalAlignment = verticalAlignment;
361
+ if ((flags & 0x0008) !== 0)
362
+ cell.wrapText = true;
363
+ if ((flags & 0x0010) !== 0)
364
+ cell.borderTop = true;
365
+ if ((flags & 0x0020) !== 0)
366
+ cell.borderRight = true;
367
+ if ((flags & 0x0040) !== 0)
368
+ cell.borderBottom = true;
369
+ if ((flags & 0x0080) !== 0)
370
+ cell.borderLeft = true;
371
+ cell.mergeRole = strings.required(str(CellStr.MergeRole), "mergeRole");
372
+ // mergeOwner/mergeRange re-derive from the merged-range table: the cell
373
+ // DTO carries the merge's FULL source range (CellMergeRole::{Owner,
374
+ // Covered} range) and its owner address — both live on the rest entry.
375
+ cell.mergeOwner = merged ? { ...merged.owner } : undefined;
376
+ cell.mergeRange = merged
377
+ ? { start: { ...merged.sourceRange.start }, end: { ...merged.sourceRange.end } }
378
+ : undefined;
379
+ cell.editability = strings.required(str(CellStr.Editability), "editability");
380
+ cell.blockers = rare?.blockers ? [...rare.blockers] : [];
381
+ cell.postureMarkers = rare?.postureMarkers ?? strings.markers(markersId);
382
+ if (rare?.hyperlink !== undefined)
383
+ cell.hyperlink = rare.hyperlink;
384
+ out[i] = cell;
385
+ }
386
+ return out;
387
+ }
388
+ function decodePaintLines(ctx, sectionId, kind) {
389
+ const label = kind === "row" ? "PAINT_ROWS" : "PAINT_COLS";
390
+ const section = requireSection(ctx, sectionId, label);
391
+ // 32 B (8-aligned f64 pair) is the only accepted stride; see module
392
+ // docblock deviation 1. A foreign stride fails loudly here rather than
393
+ // being guessed at — silent misdecoding of f64 geometry is worse.
394
+ assertStride(section, SHEET_WINDOW_PAINT_LINE_RECORD_BYTES, label);
395
+ const { view, strings } = ctx;
396
+ const out = new Array(section.recordCount);
397
+ for (let i = 0; i < section.recordCount; i++) {
398
+ const o = section.byteOffset + i * SHEET_WINDOW_PAINT_LINE_RECORD_BYTES;
399
+ const line = view.getUint32(o, true);
400
+ const precision = strings.required(view.getUint32(o + 4, true), "precision");
401
+ const hidden = (view.getUint8(o + 8) & 0x01) !== 0;
402
+ const offsetPx = view.getFloat64(o + 16, true);
403
+ const sizePx = view.getFloat64(o + 24, true);
404
+ out[i] =
405
+ kind === "row"
406
+ ? { row: line, offsetPx, sizePx, hidden, precision }
407
+ : { column: line, offsetPx, sizePx, hidden, precision };
408
+ }
409
+ return out;
410
+ }
411
+ function decodeRects(ctx) {
412
+ const section = requireSection(ctx, SHEET_WINDOW_SECTION_RECTS, "RECTS");
413
+ assertStride(section, SHEET_WINDOW_RECT_RECORD_BYTES, "RECTS");
414
+ const { view, strings } = ctx;
415
+ const out = new Array(section.recordCount);
416
+ for (let i = 0; i < section.recordCount; i++) {
417
+ const o = section.byteOffset + i * SHEET_WINDOW_RECT_RECORD_BYTES;
418
+ const kind = strings.required(view.getUint32(o + 32, true), "coordinateSpace.kind");
419
+ const region = strings.at(view.getUint32(o + 36, true));
420
+ out[i] = {
421
+ xPx: view.getFloat64(o, true),
422
+ yPx: view.getFloat64(o + 8, true),
423
+ widthPx: view.getFloat64(o + 16, true),
424
+ heightPx: view.getFloat64(o + 24, true),
425
+ // serde's tagged enum: struct variants carry `region`, unit variants
426
+ // emit only `kind` — the region key must be ABSENT on unit variants.
427
+ coordinateSpace: (region === undefined ? { kind } : { kind, region }),
428
+ precision: strings.required(view.getUint32(o + 40, true), "precision")
429
+ };
430
+ }
431
+ return out;
432
+ }
433
+ function decodePaintCells(ctx, rects) {
434
+ const section = requireSection(ctx, SHEET_WINDOW_SECTION_PAINT_CELLS, "PAINT_CELLS");
435
+ assertStride(section, SHEET_WINDOW_PAINT_CELL_RECORD_BYTES, "PAINT_CELLS");
436
+ const { view, strings } = ctx;
437
+ const out = new Array(section.recordCount);
438
+ for (let i = 0; i < section.recordCount; i++) {
439
+ const o = section.byteOffset + i * SHEET_WINDOW_PAINT_CELL_RECORD_BYTES;
440
+ const rectStart = view.getUint32(o + 8, true);
441
+ const rectCount = view.getUint16(o + 12, true);
442
+ if (rectStart + rectCount > rects.length) {
443
+ throw new Error(`sheet-window binary: paint cell ${i} references rects beyond the pool`);
444
+ }
445
+ const ownerRow = view.getUint32(o + 20, true);
446
+ const ownerCol = view.getUint32(o + 24, true);
447
+ out[i] = {
448
+ address: { row: view.getUint32(o, true), column: view.getUint32(o + 4, true) },
449
+ rects: rects.slice(rectStart, rectStart + rectCount),
450
+ hidden: (view.getUint8(o + 14) & 0x01) !== 0,
451
+ precision: strings.required(view.getUint32(o + 16, true), "precision"),
452
+ mergeOwner: ownerRow === SHEET_WINDOW_U32_NONE ? undefined : { row: ownerRow, column: ownerCol }
453
+ };
454
+ }
455
+ return out;
456
+ }
457
+ /**
458
+ * Decode the hybrid binary envelope into the exact JSON readback shape.
459
+ *
460
+ * `rows`/`columns`/`cells`/`paintGeometry` are memoized lazy getters —
461
+ * consumers that only touch `paintGeometry` (the tile scheduler) never pay
462
+ * for cell decoding, and vice versa. Everything else spreads through from
463
+ * `rest` unchanged (transport-internal fields are stripped). Because those
464
+ * getters run at consumer access time, callers that need the documented
465
+ * permanent-JSON fallback must pass `onSectionDecodeError` (the bridge does,
466
+ * via {@link createSheetWindowDecodedReader}) — a bare try/catch around this
467
+ * call only covers the eager header validation.
468
+ */
469
+ export function decodeSheetWindowBinary(env, options) {
470
+ if (env.schemaId !== SHEET_WINDOW_BINARY_SCHEMA_ID) {
471
+ throw new Error(`sheet-window binary: unknown schemaId ${env.schemaId}`);
472
+ }
473
+ let bytes = env.bytes instanceof Uint8Array ? env.bytes : Uint8Array.from(env.bytes);
474
+ // Copy-out-once backstop: detach with one memcpy before decoding lazily
475
+ // when the bytes could alias growable memory. Growth hazards:
476
+ // - a view over a LARGER buffer — the signature of a raw ptr+len view
477
+ // into wasm linear memory (growth invalidates such views);
478
+ // - a full-length view whose backing store is not a plain fixed
479
+ // `ArrayBuffer`: a resizable ArrayBuffer (`resizable`), or any
480
+ // growable/shared-memory backing (which can also be mutated
481
+ // concurrently — the lazy decoder must never observe that).
482
+ // The `instanceof ArrayBuffer` test intentionally treats every non-plain
483
+ // backing as hazardous (default browser posture carries no shared-memory
484
+ // dependency; the decoder only ever copies OUT of such buffers).
485
+ // Unreachable through the wasm-bindgen return path today (Rust copies via
486
+ // js_sys::Uint8Array::from) but the docblock names a future ptr+len path.
487
+ const backing = bytes.buffer;
488
+ const plainFixedBacking = backing instanceof ArrayBuffer && backing.resizable !== true;
489
+ if (!plainFixedBacking ||
490
+ bytes.byteOffset !== 0 ||
491
+ bytes.byteLength !== backing.byteLength) {
492
+ bytes = bytes.slice();
493
+ }
494
+ if (bytes.byteLength < SHEET_WINDOW_BINARY_HEADER_BYTES) {
495
+ throw new Error(`sheet-window binary: truncated header (${bytes.byteLength} bytes)`);
496
+ }
497
+ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
498
+ if (view.getUint32(0, true) !== SHEET_WINDOW_BINARY_MAGIC) {
499
+ throw new Error("sheet-window binary: bad magic (expected XSW1 little-endian)");
500
+ }
501
+ const version = view.getUint16(4, true);
502
+ if (version !== SHEET_WINDOW_BINARY_VERSION) {
503
+ throw new Error(`sheet-window binary: unsupported version ${version}`);
504
+ }
505
+ const flags = view.getUint16(6, true);
506
+ const sectionCount = view.getUint32(8, true);
507
+ const totalByteLen = view.getUint32(12, true);
508
+ if (totalByteLen > bytes.byteLength) {
509
+ throw new Error(`sheet-window binary: totalByteLen ${totalByteLen} exceeds buffer ${bytes.byteLength}`);
510
+ }
511
+ const tableEnd = SHEET_WINDOW_BINARY_HEADER_BYTES + sectionCount * SHEET_WINDOW_BINARY_SECTION_ENTRY_BYTES;
512
+ if (tableEnd > totalByteLen) {
513
+ throw new Error("sheet-window binary: section table escapes the buffer");
514
+ }
515
+ const sections = new Map();
516
+ for (let i = 0; i < sectionCount; i++) {
517
+ const o = SHEET_WINDOW_BINARY_HEADER_BYTES + i * SHEET_WINDOW_BINARY_SECTION_ENTRY_BYTES;
518
+ const sectionId = view.getUint32(o, true);
519
+ const byteOffset = view.getUint32(o + 4, true);
520
+ const byteLen = view.getUint32(o + 8, true);
521
+ if (byteOffset + byteLen > totalByteLen) {
522
+ throw new Error(`sheet-window binary: section ${sectionId} escapes the buffer`);
523
+ }
524
+ // Unknown section ids are recorded but never required — forward-compat:
525
+ // decoders skip what they do not understand.
526
+ sections.set(sectionId, { byteOffset, byteLen, recordCount: view.getUint32(o + 12, true) });
527
+ }
528
+ const strtab = sections.get(SHEET_WINDOW_SECTION_STRTAB);
529
+ const blob = sections.get(SHEET_WINDOW_SECTION_STRBLOB);
530
+ if (!strtab || !blob) {
531
+ throw new Error("sheet-window binary: missing required string sections (STRTAB/STRBLOB)");
532
+ }
533
+ assertStride(strtab, SHEET_WINDOW_STRTAB_ENTRY_BYTES, "STRTAB");
534
+ const strings = new SheetWindowStringTable(view, bytes, strtab, blob);
535
+ const rest = env.rest;
536
+ const ctx = { view, strings, sections, rest };
537
+ const paintGeometryPresent = (flags & SHEET_WINDOW_FLAG_PAINT_GEOMETRY) !== 0;
538
+ // Strip transport-internal fields; everything else passes through
539
+ // unchanged so the decoded object is field-identical to the JSON readback.
540
+ const { rareCells: _rareCells, paintGeometryPresent: _pgPresent, paintGeometryActiveSelection, paintGeometryObjects, paintGeometrySparklines, paintGeometry: nestedPaintGeometry, encodeMs: _encodeMs, ...readbackRest } = rest;
541
+ // Section-level recovery seam: when a lazy getter throws, substitute the
542
+ // failing section from the caller-provided fallback readback (memoized as
543
+ // the getter value) instead of crashing the consumer.
544
+ const onSectionDecodeError = options?.onSectionDecodeError;
545
+ const recoverSection = onSectionDecodeError
546
+ ? (key) => (error) => {
547
+ const substitute = onSectionDecodeError(error);
548
+ return substitute === undefined ? undefined : { value: substitute[key] };
549
+ }
550
+ : undefined;
551
+ const out = { ...readbackRest };
552
+ const defineLazySection = (key, compute) => {
553
+ defineLazy(out, key, compute, recoverSection?.(key));
554
+ };
555
+ defineLazySection("rows", () => decodeLineSection(ctx, SHEET_WINDOW_SECTION_ROWS, "row"));
556
+ defineLazySection("columns", () => decodeLineSection(ctx, SHEET_WINDOW_SECTION_COLS, "column"));
557
+ defineLazySection("cells", () => decodeCells(ctx));
558
+ defineLazySection("paintGeometry", () => {
559
+ if (!paintGeometryPresent) {
560
+ return undefined;
561
+ }
562
+ const rects = decodeRects(ctx);
563
+ const geometry = {
564
+ rows: decodePaintLines(ctx, SHEET_WINDOW_SECTION_PAINT_ROWS, "row"),
565
+ columns: decodePaintLines(ctx, SHEET_WINDOW_SECTION_PAINT_COLS, "column"),
566
+ cells: decodePaintCells(ctx, rects),
567
+ activeSelection: nestedPaintGeometry?.activeSelection ?? paintGeometryActiveSelection,
568
+ objects: nestedPaintGeometry?.objects ?? paintGeometryObjects ?? [],
569
+ // X5-U-017: same either-spelling merge as `objects`.
570
+ sparklines: nestedPaintGeometry?.sparklines ?? paintGeometrySparklines ?? []
571
+ };
572
+ return geometry;
573
+ });
574
+ return out;
575
+ }
576
+ /**
577
+ * Build the `readSheetWindowDecoded` seam with the permanent-JSON-fallback
578
+ * latch. Covers BOTH failure surfaces of the binary lane:
579
+ *
580
+ * - EAGER decode errors (header/section-table/STRTAB validation) throw from
581
+ * `decodeSheetWindowBinary` synchronously — caught here, latch flips, and
582
+ * the SAME call returns the JSON readback;
583
+ * - LAZY section decode errors (stride mismatch, out-of-range string id,
584
+ * blob escape, missing rareCells/mergedRanges reference in
585
+ * rows/columns/cells/paintGeometry) surface at first CONSUMER access,
586
+ * possibly frames later — routed back through `onSectionDecodeError`,
587
+ * which flips the latch for every subsequent call AND substitutes the
588
+ * failing section from a fresh JSON readback for the same request so the
589
+ * in-flight frame degrades instead of throwing. The substituted section
590
+ * may reflect a marginally newer document state than the rest of the
591
+ * decoded object if the session mutated between decode and access — an
592
+ * accepted one-frame degradation on an already-failing lane (all later
593
+ * frames are pure JSON). If even the JSON re-read fails (e.g. the session
594
+ * was disposed), the original decode error rethrows.
595
+ *
596
+ * The latch is per-reader (= per bridge instance), mirroring the previous
597
+ * `binarySheetWindowDisabled` flag.
598
+ */
599
+ export function createSheetWindowDecodedReader(deps) {
600
+ let disabled = false;
601
+ const warn = deps.warn ??
602
+ ((message, error) => {
603
+ console.warn(message, error instanceof Error ? error.message : error);
604
+ });
605
+ const disable = (error) => {
606
+ if (disabled) {
607
+ return;
608
+ }
609
+ disabled = true;
610
+ warn(`xlsx ${SHEET_WINDOW_BINARY_SCHEMA_ID} decode failed; permanently falling back to the JSON sheet-window export for this bridge instance:`, error);
611
+ };
612
+ return (...args) => {
613
+ const readBinary = deps.readBinary;
614
+ if (readBinary && !disabled) {
615
+ let recovered;
616
+ try {
617
+ return decodeSheetWindowBinary(readBinary(...args), {
618
+ onSectionDecodeError: (error) => {
619
+ disable(error);
620
+ try {
621
+ recovered ??= deps.readJson(...args);
622
+ return recovered;
623
+ }
624
+ catch {
625
+ return undefined;
626
+ }
627
+ }
628
+ });
629
+ }
630
+ catch (error) {
631
+ disable(error);
632
+ }
633
+ }
634
+ return deps.readJson(...args);
635
+ };
636
+ }