@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
@@ -6,7 +6,12 @@
6
6
  // on artifact-less checkouts. Loader shells own artifact resolution and
7
7
  // instantiation; everything after a raw module object exists (validation,
8
8
  // wrapping, normalization) lives here.
9
+ import { AI_SESSION_AGENT_CAPABILITY, AI_SESSION_RAW_METHODS, attachAiSessionMethods } from "./ai-session-bridge.js";
10
+ import { createXlsxWasmRuntime } from "./runtime-guard.js";
9
11
  import { createSheetWindowDecodedReader } from "./sheet-window-binary.js";
12
+ // R4 (runtime 0.2.0): the memory contract and the typed bridge errors.
13
+ export { createXlsxWasmRuntime, deserializeXlsxWasmBridgeError, isXlsxWasmBridgeError, serializeXlsxWasmBridgeError, XlsxWasmBridgeError } from "./runtime-guard.js";
14
+ export { estimateXlsxPackageMemory, readWasmMemoryLimits, XLSX_WASM_LINEAR_MEMORY_MAXIMUM_BYTES } from "./memory-budget.js";
10
15
  /** Every runtime-session-mutations-v1 method name, used by feature detection. */
11
16
  const RUNTIME_SESSION_MUTATION_METHODS = [
12
17
  "commitCellFormulaInSession",
@@ -26,7 +31,23 @@ const RUNTIME_SESSION_MUTATION_METHODS = [
26
31
  "mutateSheetStructureInSession",
27
32
  "mutateSheetTabsInSession",
28
33
  "commitTableAppendRowInSession",
29
- "commitShiftCellsInSession"
34
+ "commitShiftCellsInSession",
35
+ // UX-P-102 P2a (v42).
36
+ "commitSelectionSetPasteInSession",
37
+ "commitSelectionSetClearInSession",
38
+ "commitSelectionSetFormatInSession",
39
+ "commitRangeHyperlinkInSession",
40
+ "commitRangeDataValidationInSession",
41
+ "commitReviewCommentInSession",
42
+ // UX-P-102 P2b (v43).
43
+ "commitApplyFilterInSession",
44
+ "commitClearFilterInSession",
45
+ "commitApplySortInSession",
46
+ "setRowOutlineGroupHiddenInSession",
47
+ "setColumnOutlineGroupHiddenInSession",
48
+ "setSheetOutlineLevelInSession",
49
+ // X5-U-023 (v44).
50
+ "defineNameInSession"
30
51
  ];
31
52
  /**
32
53
  * T1 feature detection: true when the mounted wasm build advertises
@@ -49,7 +70,7 @@ export function supportsRuntimeSessionMutations(bridge) {
49
70
  RUNTIME_SESSION_MUTATION_METHODS.every((method) => typeof bridge[method] === "function"));
50
71
  }
51
72
  export { createSheetWindowDecodedReader, decodeSheetWindowBinary, SHEET_WINDOW_BINARY_SCHEMA_ID } from "./sheet-window-binary.js";
52
- const requiredBridgeVersion = "xlsx-wasm-bridge-v40"; // v40: X3-R-012 (`dataRegionInRuntimeSession`: Excel's Ctrl+Arrow / Ctrl+Shift+Arrow / Ctrl+A targets over the canonical cells, with the data-region-v1 capability; v39 was X5-C-056)
73
+ const requiredBridgeVersion = "xlsx-wasm-bridge-v46"; // v46: X5-U-083 (table-append empty cell; v45 was WP-DOC-T-O)
53
74
  const requiredCapabilities = [
54
75
  "workflow-context-v2",
55
76
  "workflow-overlay-lanes-v1",
@@ -117,8 +138,25 @@ const requiredCapabilities = [
117
138
  // X3-R-012 (bridge v40): `dataRegionInRuntimeSession`. A bridge without it
118
139
  // would answer Ctrl+Down with `not a function`, so it fails the mount gate
119
140
  // instead.
120
- "data-region-v1"
141
+ "data-region-v1",
142
+ // XB5: the AI session lane is all-or-nothing per build (Q8). A bridge
143
+ // without it would answer every fenced AI call with `not a function`, so
144
+ // it fails the mount gate instead.
145
+ AI_SESSION_AGENT_CAPABILITY
121
146
  ];
147
+ /**
148
+ * R5: the bridge version this package mounts. A host reports it with
149
+ * `generatedWasmModuleSha256()`; the package version policy (README, the
150
+ * package.json `conductor` field) moves the MINOR version whenever the
151
+ * published value of this constant changes.
152
+ */
153
+ export const BRIDGE_VERSION = requiredBridgeVersion;
154
+ /**
155
+ * R5: the capabilities every mounted bridge advertises (the mount gate's
156
+ * list). Hosts gate on the capabilities they call; see
157
+ * `missingXlsxWasmCapabilities`.
158
+ */
159
+ export const BRIDGE_CAPABILITIES = Object.freeze([...requiredCapabilities]);
122
160
  const requiredRawMethods = [
123
161
  "getWasmStatus",
124
162
  "openWorkbookRuntimeSession",
@@ -193,7 +231,13 @@ const requiredRawMethods = [
193
231
  "commitClearFilter",
194
232
  "commitApplySort",
195
233
  "mutateSheetTabs",
196
- "commitShiftCells"
234
+ "commitShiftCells",
235
+ // X5-U-023 (bridge v44): defined-name authoring over bytes.
236
+ "defineName",
237
+ // XB5 (§5.5 under Q8's fold): the AI lane's ONE raw export, declared once
238
+ // in ai-session-bridge.ts and spread here so the mount gate and the pool
239
+ // allowlists read one declaration (the eight verbs are its `op` values).
240
+ ...AI_SESSION_RAW_METHODS
197
241
  ];
198
242
  /**
199
243
  * Target-independent mount gate: role, bridge version, required
@@ -230,7 +274,16 @@ export function validateRawXlsxWasmModule(raw) {
230
274
  }
231
275
  return { ok: true, status };
232
276
  }
233
- export function createXlsxWasmBridge(raw, status = raw.getWasmStatus()) {
277
+ /**
278
+ * Wrap a raw wasm module object in the typed bridge. Every call goes through
279
+ * `runtime` (R4): pre-admission against the memory budget before open and
280
+ * recalculate, and trap containment at the call boundary. Without a runtime
281
+ * the bridge builds one over `source` that can contain a trap but has no
282
+ * Module to re-instantiate from (the loaders always pass one that can).
283
+ */
284
+ export function createXlsxWasmBridge(source, status, runtime = createXlsxWasmRuntime({ instance: { raw: source } })) {
285
+ const raw = runtime.raw;
286
+ const bridgeStatus = status ?? raw.getWasmStatus();
234
287
  // T1 feature detection: session-mutation exports are optional on the raw
235
288
  // wasm module object so older generated builds keep mounting with the
236
289
  // byte-based surface only. Capture the raw functions once so the closures
@@ -253,6 +306,26 @@ export function createXlsxWasmBridge(raw, status = raw.getWasmStatus()) {
253
306
  const rawMutateSheetTabsInSession = typeof raw.mutateSheetTabsInSession === "function" ? raw.mutateSheetTabsInSession.bind(raw) : undefined;
254
307
  const rawCommitTableAppendRowInSession = typeof raw.commitTableAppendRowInSession === "function" ? raw.commitTableAppendRowInSession.bind(raw) : undefined;
255
308
  const rawCommitShiftCellsInSession = typeof raw.commitShiftCellsInSession === "function" ? raw.commitShiftCellsInSession.bind(raw) : undefined;
309
+ // UX-P-102 P2a (v42): the six families that had only a bytes export.
310
+ const rawCommitSelectionSetPasteInSession = typeof raw.commitSelectionSetPasteInSession === "function" ? raw.commitSelectionSetPasteInSession.bind(raw) : undefined;
311
+ const rawCommitSelectionSetClearInSession = typeof raw.commitSelectionSetClearInSession === "function" ? raw.commitSelectionSetClearInSession.bind(raw) : undefined;
312
+ const rawCommitSelectionSetFormatInSession = typeof raw.commitSelectionSetFormatInSession === "function" ? raw.commitSelectionSetFormatInSession.bind(raw) : undefined;
313
+ const rawCommitRangeHyperlinkInSession = typeof raw.commitRangeHyperlinkInSession === "function" ? raw.commitRangeHyperlinkInSession.bind(raw) : undefined;
314
+ const rawCommitRangeDataValidationInSession = typeof raw.commitRangeDataValidationInSession === "function"
315
+ ? raw.commitRangeDataValidationInSession.bind(raw)
316
+ : undefined;
317
+ const rawCommitReviewCommentInSession = typeof raw.commitReviewCommentInSession === "function" ? raw.commitReviewCommentInSession.bind(raw) : undefined;
318
+ // UX-P-102 P2b (v43): the last six bytes-only families.
319
+ const rawCommitApplyFilterInSession = typeof raw.commitApplyFilterInSession === "function" ? raw.commitApplyFilterInSession.bind(raw) : undefined;
320
+ const rawCommitClearFilterInSession = typeof raw.commitClearFilterInSession === "function" ? raw.commitClearFilterInSession.bind(raw) : undefined;
321
+ const rawCommitApplySortInSession = typeof raw.commitApplySortInSession === "function" ? raw.commitApplySortInSession.bind(raw) : undefined;
322
+ const rawSetRowOutlineGroupHiddenInSession = typeof raw.setRowOutlineGroupHiddenInSession === "function" ? raw.setRowOutlineGroupHiddenInSession.bind(raw) : undefined;
323
+ const rawSetColumnOutlineGroupHiddenInSession = typeof raw.setColumnOutlineGroupHiddenInSession === "function"
324
+ ? raw.setColumnOutlineGroupHiddenInSession.bind(raw)
325
+ : undefined;
326
+ const rawSetSheetOutlineLevelInSession = typeof raw.setSheetOutlineLevelInSession === "function" ? raw.setSheetOutlineLevelInSession.bind(raw) : undefined;
327
+ // X5-U-023 (v44): defined-name authoring.
328
+ const rawDefineNameInSession = typeof raw.defineNameInSession === "function" ? raw.defineNameInSession.bind(raw) : undefined;
256
329
  // X5-U-012 feature detection: the delimited-text export is optional and
257
330
  // independent of the mutation family, so it is attached on its own.
258
331
  const rawExportRuntimeSessionDelimitedText = typeof raw.exportRuntimeSessionDelimitedText === "function"
@@ -280,7 +353,11 @@ export function createXlsxWasmBridge(raw, status = raw.getWasmStatus()) {
280
353
  rawResizeRowHeightInSession && rawSetColumnHiddenInSession && rawSetRowHiddenInSession &&
281
354
  rawSetFrozenPaneInSession && rawMergeCellsInSession &&
282
355
  rawMutateSheetStructureInSession && rawMutateSheetTabsInSession && rawCommitTableAppendRowInSession &&
283
- rawCommitShiftCellsInSession
356
+ rawCommitShiftCellsInSession && rawCommitSelectionSetPasteInSession && rawCommitSelectionSetClearInSession &&
357
+ rawCommitSelectionSetFormatInSession && rawCommitRangeHyperlinkInSession &&
358
+ rawCommitRangeDataValidationInSession && rawCommitReviewCommentInSession && rawCommitApplyFilterInSession &&
359
+ rawCommitClearFilterInSession && rawCommitApplySortInSession && rawSetRowOutlineGroupHiddenInSession &&
360
+ rawSetColumnOutlineGroupHiddenInSession && rawSetSheetOutlineLevelInSession && rawDefineNameInSession
284
361
  ? {
285
362
  commitCellFormulaInSession(handleId, request) {
286
363
  return normalizeFormulaCommitResult(rawCommitCellFormulaInSession(handleId, request));
@@ -335,12 +412,60 @@ export function createXlsxWasmBridge(raw, status = raw.getWasmStatus()) {
335
412
  },
336
413
  commitShiftCellsInSession(handleId, request) {
337
414
  return normalizeShiftCellsCommitResult(rawCommitShiftCellsInSession(handleId, request));
415
+ },
416
+ commitSelectionSetPasteInSession(handleId, request) {
417
+ return normalizeRangePasteCommitResult(rawCommitSelectionSetPasteInSession(handleId, request));
418
+ },
419
+ commitSelectionSetClearInSession(handleId, request) {
420
+ return normalizeRangeClearCommitResult(rawCommitSelectionSetClearInSession(handleId, request));
421
+ },
422
+ commitSelectionSetFormatInSession(handleId, request) {
423
+ return normalizeRangeFormatCommitResult(rawCommitSelectionSetFormatInSession(handleId, request));
424
+ },
425
+ commitRangeHyperlinkInSession(handleId, request) {
426
+ return normalizeRangeHyperlinkCommitResult(rawCommitRangeHyperlinkInSession(handleId, request));
427
+ },
428
+ commitRangeDataValidationInSession(handleId, request) {
429
+ return normalizeRangeDataValidationCommitResult(rawCommitRangeDataValidationInSession(handleId, request));
430
+ },
431
+ commitReviewCommentInSession(handleId, request) {
432
+ return normalizeReviewCommentCommitResult(rawCommitReviewCommentInSession(handleId, request));
433
+ },
434
+ commitApplyFilterInSession(handleId, request) {
435
+ return normalizeRangeFilterResult(rawCommitApplyFilterInSession(handleId, request));
436
+ },
437
+ commitClearFilterInSession(handleId, request) {
438
+ return normalizeRangeFilterResult(rawCommitClearFilterInSession(handleId, request));
439
+ },
440
+ commitApplySortInSession(handleId, request) {
441
+ return normalizeRangeSortResult(rawCommitApplySortInSession(handleId, request));
442
+ },
443
+ setRowOutlineGroupHiddenInSession(handleId, request) {
444
+ return normalizeOutlineGroupVisibilityResult(rawSetRowOutlineGroupHiddenInSession(handleId, request));
445
+ },
446
+ setColumnOutlineGroupHiddenInSession(handleId, request) {
447
+ return normalizeOutlineGroupVisibilityResult(rawSetColumnOutlineGroupHiddenInSession(handleId, request));
448
+ },
449
+ setSheetOutlineLevelInSession(handleId, request) {
450
+ return normalizeOutlineLevelResult(rawSetSheetOutlineLevelInSession(handleId, request));
451
+ },
452
+ defineNameInSession(handleId, request) {
453
+ return normalizeDefinedNameMutationResult(rawDefineNameInSession(handleId, request));
338
454
  }
339
455
  }
340
456
  : undefined;
341
457
  return {
342
- status,
458
+ status: bridgeStatus,
459
+ wasmMemoryBytes() {
460
+ return runtime.wasmMemoryBytes();
461
+ },
462
+ highWater(bytes) {
463
+ return runtime.highWater(bytes);
464
+ },
343
465
  ...(sessionMutationMethods ?? {}),
466
+ // XB5: the eight typed AI methods, each dispatching to the one required
467
+ // raw export `aiSessionCall` with its verb.
468
+ ...attachAiSessionMethods(raw),
344
469
  openWorkbookRuntimeSession(bytes, request = {}) {
345
470
  return raw.openWorkbookRuntimeSession(bytes, request);
346
471
  },
@@ -579,6 +704,9 @@ export function createXlsxWasmBridge(raw, status = raw.getWasmStatus()) {
579
704
  mutateSheetTabs(bytes, request) {
580
705
  return normalizeSheetTabMutationResult(raw.mutateSheetTabs(bytes, request));
581
706
  },
707
+ defineName(bytes, request) {
708
+ return normalizeDefinedNameMutationResult(raw.defineName(bytes, request));
709
+ },
582
710
  commitShiftCells(bytes, request) {
583
711
  return normalizeShiftCellsCommitResult(raw.commitShiftCells(bytes, request));
584
712
  }
@@ -815,6 +943,17 @@ function normalizeRangeSortResult(result) {
815
943
  exportedBytes
816
944
  };
817
945
  }
946
+ function normalizeDefinedNameMutationResult(result) {
947
+ const exportedBytes = result.exportedBytes
948
+ ? result.exportedBytes instanceof Uint8Array
949
+ ? result.exportedBytes
950
+ : Uint8Array.from(result.exportedBytes)
951
+ : undefined;
952
+ return {
953
+ ...result,
954
+ exportedBytes
955
+ };
956
+ }
818
957
  function normalizeSheetTabMutationResult(result) {
819
958
  const exportedBytes = result.exportedBytes
820
959
  ? result.exportedBytes instanceof Uint8Array
@@ -1,6 +1,47 @@
1
- import { type XlsxWasmBridgeLoadResult } from "./bridge-contract.ts";
1
+ import { type XlsxWasmAdmissionOptions, type XlsxWasmBridgeLoadResult } from "./bridge-contract.ts";
2
2
  export * from "./bridge-contract.ts";
3
- export declare function loadGeneratedXlsxWasmBridge(): XlsxWasmBridgeLoadResult;
3
+ export { AI_SESSION_AGENT_CAPABILITY, AI_SESSION_METHODS, AI_SESSION_OPS, AI_SESSION_POOL_METHODS, AI_SESSION_RAW_METHOD, AI_SESSION_RAW_METHODS, aiSessionOpClass, attachAiSessionMethods, isXlsxAiUnknownOpRefusal, XlsxAiUnknownOpRefusalError, type RawXlsxAiSessionModule, type XlsxAiSessionBridgeMethods, type AiSessionCallOp, type AiSessionCommitMethod, type AiSessionMethod, type AiSessionOp } from "./ai-session-bridge.ts";
4
+ /**
5
+ * R3: compile the package's wasm binary once, asynchronously, into a
6
+ * `WebAssembly.Module` a host can share: pass it to `loadXlsxWasmBridge`
7
+ * here, or post it to worker_threads, each of which instantiates its own
8
+ * instance from it without compiling again. The Module is compiled from the
9
+ * exact bytes `generatedWasmModuleSha256()` hashes.
10
+ */
11
+ export declare function compileXlsxWasmModule(): Promise<WebAssembly.Module>;
12
+ /**
13
+ * The SHA-256 this realm recorded for the bytes it compiled `module` from
14
+ * (`compileXlsxWasmModule`, or the default instance's Module). It is a
15
+ * lookup, not a hash of the Module: a `WebAssembly.Module` exposes no bytes.
16
+ * A Module received from another thread is a clone and answers undefined.
17
+ */
18
+ export declare function xlsxWasmModuleSha256(module: WebAssembly.Module): string | undefined;
19
+ export interface XlsxWasmBridgeLoadOptions extends XlsxWasmAdmissionOptions {
20
+ /**
21
+ * A Module from `compileXlsxWasmModule()` (possibly in another thread).
22
+ * Given: the bridge runs on a NEW instance of its own. Absent: the bridge
23
+ * runs on the process's shared default instance, as every
24
+ * `loadGeneratedXlsxWasmBridge()` bridge does.
25
+ *
26
+ * `memoryBudgetBytes` and `admission` apply to the returned bridge only.
27
+ * On the shared default instance each bridge keeps its own setting, and
28
+ * every bridge's live sessions count against the one maximum.
29
+ */
30
+ readonly module?: WebAssembly.Module;
31
+ /** Throw instead of returning not-mounted. Defaults to XLSX_WASM_REQUIRED=1. */
32
+ readonly required?: boolean;
33
+ }
34
+ /**
35
+ * R3: mount the bridge on a wasm instance. Synchronous: with a Module the
36
+ * instantiation is cheap; without one the default instance is created (and
37
+ * the binary compiled) once per process.
38
+ */
39
+ export declare function loadXlsxWasmBridge(options?: XlsxWasmBridgeLoadOptions): XlsxWasmBridgeLoadResult;
40
+ /**
41
+ * The process's shared default bridge (unchanged entry point). `options`
42
+ * sets this bridge's own admission (see `XlsxWasmBridgeLoadOptions`).
43
+ */
44
+ export declare function loadGeneratedXlsxWasmBridge(options?: XlsxWasmAdmissionOptions): XlsxWasmBridgeLoadResult;
4
45
  /**
5
46
  * SHA-256 of the WebAssembly binary this loader instantiates. Hosts report it
6
47
  * with the bridge version so a deployed runtime is identifiable without
@@ -1,35 +1,98 @@
1
- // Node.js loader shell over the `--target nodejs` CJS wasm artifact in
2
- // `generated/wasm/`. The full target-independent bridge contract (types,
1
+ // Node.js loader over the ONE wasm binary (runtime 0.2.0, R2): the
2
+ // wasm-bindgen web-target ESM glue in `generated/wasm-web/`, instantiated
3
+ // with initSync({ module }). The target-independent bridge contract (types,
3
4
  // required-capability / required-method lists, `validateRawXlsxWasmModule`,
4
- // `createXlsxWasmBridge`, result normalizers, and the sheet-window binary
5
- // decoder re-exports) lives in `bridge-contract.ts` so the browser loader
6
- // (`web.ts`) shares it verbatim without pulling `node:` imports.
5
+ // `createXlsxWasmBridge`, result normalizers, the memory contract and the
6
+ // sheet-window binary decoder re-exports) lives in `bridge-contract.ts` so
7
+ // the browser loader (`web.ts`) shares it verbatim without `node:` imports.
7
8
  import { createHash } from "node:crypto";
8
9
  import { existsSync, readFileSync } from "node:fs";
9
10
  import { createRequire } from "node:module";
10
11
  import { dirname, resolve } from "node:path";
11
12
  import { fileURLToPath } from "node:url";
12
- import { createXlsxWasmBridge, validateRawXlsxWasmModule } from "./bridge-contract.js";
13
+ import { createXlsxWasmBridge, createXlsxWasmRuntime, readWasmMemoryLimits, validateRawXlsxWasmModule, XLSX_WASM_LINEAR_MEMORY_MAXIMUM_BYTES } from "./bridge-contract.js";
13
14
  export * from "./bridge-contract.js";
14
- function loadCommonJsModule(moduleUrl, modulePath) {
15
- const nativeRequire = typeof __non_webpack_require__ === "function"
15
+ // XB5 (Q8 "Bindings package surface"): the pool, the worker's twin and the
16
+ // packed consumer read the AI constants through this entry.
17
+ export { AI_SESSION_AGENT_CAPABILITY, AI_SESSION_METHODS, AI_SESSION_OPS, AI_SESSION_POOL_METHODS, AI_SESSION_RAW_METHOD, AI_SESSION_RAW_METHODS, aiSessionOpClass, attachAiSessionMethods, isXlsxAiUnknownOpRefusal, XlsxAiUnknownOpRefusalError } from "./ai-session-bridge.js";
18
+ function nativeRequire(path) {
19
+ const load = typeof __non_webpack_require__ === "function"
16
20
  ? __non_webpack_require__
17
- : createRequire(moduleUrl);
18
- return nativeRequire(modulePath);
21
+ : createRequire(import.meta.url);
22
+ return load(path);
19
23
  }
20
- export function loadGeneratedXlsxWasmBridge() {
21
- const modulePath = generatedWasmModulePath();
22
- if (!existsSync(modulePath)) {
24
+ const SHIM_INSTANCE_KEY = Symbol.for("@beyondwork/xlsx-substrate-bindings/wasm-instance");
25
+ function packageRoot() {
26
+ // src/wasm/index.ts and dist/wasm/index.js both sit two levels below it.
27
+ return resolve(dirname(fileURLToPath(import.meta.url)), "../..");
28
+ }
29
+ function generatedGluePath() {
30
+ return resolve(packageRoot(), "generated/wasm-web/xlsx_substrate_wasm.js");
31
+ }
32
+ function generatedBinaryPath() {
33
+ return resolve(packageRoot(), "generated/wasm-web/xlsx_substrate_wasm_bg.wasm");
34
+ }
35
+ /** The in-repo CommonJS shim; absent from the published package. */
36
+ function generatedShimPath() {
37
+ return resolve(packageRoot(), "generated/wasm/xlsx_substrate_wasm.js");
38
+ }
39
+ const moduleSha256 = new WeakMap();
40
+ let compiledModule;
41
+ let defaultRuntime;
42
+ function sha256(bytes) {
43
+ return createHash("sha256").update(bytes).digest("hex");
44
+ }
45
+ function maximumMemoryBytes(bytes) {
46
+ return readWasmMemoryLimits(bytes)?.maximumBytes ?? XLSX_WASM_LINEAR_MEMORY_MAXIMUM_BYTES;
47
+ }
48
+ /**
49
+ * R3: compile the package's wasm binary once, asynchronously, into a
50
+ * `WebAssembly.Module` a host can share: pass it to `loadXlsxWasmBridge`
51
+ * here, or post it to worker_threads, each of which instantiates its own
52
+ * instance from it without compiling again. The Module is compiled from the
53
+ * exact bytes `generatedWasmModuleSha256()` hashes.
54
+ */
55
+ export function compileXlsxWasmModule() {
56
+ compiledModule ??= (async () => {
57
+ const bytes = readFileSync(generatedBinaryPath());
58
+ const module = await WebAssembly.compile(bytes);
59
+ moduleSha256.set(module, sha256(bytes));
60
+ return module;
61
+ })();
62
+ compiledModule.catch(() => {
63
+ compiledModule = undefined;
64
+ });
65
+ return compiledModule;
66
+ }
67
+ /**
68
+ * The SHA-256 this realm recorded for the bytes it compiled `module` from
69
+ * (`compileXlsxWasmModule`, or the default instance's Module). It is a
70
+ * lookup, not a hash of the Module: a `WebAssembly.Module` exposes no bytes.
71
+ * A Module received from another thread is a clone and answers undefined.
72
+ */
73
+ export function xlsxWasmModuleSha256(module) {
74
+ return moduleSha256.get(module);
75
+ }
76
+ /**
77
+ * R3: mount the bridge on a wasm instance. Synchronous: with a Module the
78
+ * instantiation is cheap; without one the default instance is created (and
79
+ * the binary compiled) once per process.
80
+ */
81
+ export function loadXlsxWasmBridge(options = {}) {
82
+ const required = options.required ?? process.env.XLSX_WASM_REQUIRED === "1";
83
+ if (!existsSync(generatedGluePath()) || !existsSync(generatedBinaryPath())) {
84
+ // Absent artifacts stay a soft result even in required mode, as before:
85
+ // the tests that require the runtime fail on the missing bridge.
23
86
  return {
24
87
  wasmBinding: "not-mounted",
25
88
  reason: "generated WASM module is absent; run build:wasm"
26
89
  };
27
90
  }
28
91
  try {
29
- const raw = loadCommonJsModule(import.meta.url, modulePath);
30
- const validation = validateRawXlsxWasmModule(raw);
92
+ const mounted = options.module ? instantiateOwnRuntime(options.module, options) : sharedDefaultView(options);
93
+ const validation = validateRawXlsxWasmModule(mounted.raw);
31
94
  if (!validation.ok) {
32
- if (process.env.XLSX_WASM_REQUIRED === "1") {
95
+ if (required) {
33
96
  throw new Error(validation.requiredModeMessage);
34
97
  }
35
98
  return {
@@ -39,11 +102,11 @@ export function loadGeneratedXlsxWasmBridge() {
39
102
  }
40
103
  return {
41
104
  wasmBinding: "mounted",
42
- bridge: createXlsxWasmBridge(raw, validation.status)
105
+ bridge: createXlsxWasmBridge(mounted.raw, validation.status, mounted.runtime)
43
106
  };
44
107
  }
45
108
  catch (error) {
46
- if (process.env.XLSX_WASM_REQUIRED === "1") {
109
+ if (required) {
47
110
  throw error;
48
111
  }
49
112
  return {
@@ -52,9 +115,177 @@ export function loadGeneratedXlsxWasmBridge() {
52
115
  };
53
116
  }
54
117
  }
55
- function generatedWasmModulePath() {
56
- const here = dirname(fileURLToPath(import.meta.url));
57
- return resolve(here, "../../generated/wasm/xlsx_substrate_wasm.js");
118
+ /**
119
+ * The process's shared default bridge (unchanged entry point). `options`
120
+ * sets this bridge's own admission (see `XlsxWasmBridgeLoadOptions`).
121
+ */
122
+ export function loadGeneratedXlsxWasmBridge(options = {}) {
123
+ return loadXlsxWasmBridge(admissionOptions(options));
124
+ }
125
+ function admissionOptions(options) {
126
+ return {
127
+ ...(options.memoryBudgetBytes !== undefined ? { memoryBudgetBytes: options.memoryBudgetBytes } : {}),
128
+ ...(options.admission !== undefined ? { admission: options.admission } : {})
129
+ };
130
+ }
131
+ function loadGlue() {
132
+ // require(esm) (Node >= 22.12): the glue is ESM without top-level await.
133
+ const glue = nativeRequire(generatedGluePath());
134
+ if (typeof glue.createXlsxSubstrateGlue !== "function") {
135
+ throw new Error("generated WASM glue has no createXlsxSubstrateGlue; run build:wasm");
136
+ }
137
+ return glue;
138
+ }
139
+ function freshInstance(glue, module) {
140
+ const instance = glue.createXlsxSubstrateGlue();
141
+ const wasmExports = instance.initSync({ module });
142
+ return { instance, ...(wasmExports.memory ? { memory: wasmExports.memory } : {}) };
143
+ }
144
+ /**
145
+ * A runtime over a holder object. Recovery after a trap copies a fresh
146
+ * instance's functions onto the same holder, so a caller that required the
147
+ * holder by path (the in-repo shim) also lands on the fresh instance.
148
+ */
149
+ function runtimeOverHolder(holder, memory, glue, module, maximumBytes, options) {
150
+ const instance = memory ? { raw: holder, memory } : { raw: holder };
151
+ const runtime = createXlsxWasmRuntime({
152
+ instance,
153
+ maximumMemoryBytes: maximumBytes,
154
+ ...admissionOptions(options),
155
+ reinstantiate() {
156
+ const fresh = freshInstance(glue, module);
157
+ Object.assign(holder, fresh.instance);
158
+ return fresh.memory ? { raw: holder, memory: fresh.memory } : { raw: holder };
159
+ }
160
+ });
161
+ return { runtime, raw: runtime.raw };
162
+ }
163
+ /** Glue fields that are not bridge calls: wasm-bindgen's init entry points. */
164
+ const UNGUARDED_GLUE_FIELDS = new Set(["default", "initSync"]);
165
+ function isPlainFunction(value) {
166
+ return typeof value === "function" && !/^class\b/u.test(Function.prototype.toString.call(value));
167
+ }
168
+ /**
169
+ * The runtime over the in-repo CommonJS shim. The shim is an object other
170
+ * in-repo code requires by path and calls directly, so it must never route a
171
+ * call around the guard. This puts a guarded function on the shim for every
172
+ * bridge call and keeps the instance's own functions private:
173
+ *
174
+ * - a direct shim call goes through the runtime: its handle ids are checked
175
+ * and translated, a trap is contained, and after a recovery an id from the
176
+ * lost instance is refused instead of reaching a new session that reused
177
+ * its native number;
178
+ * - the runtime calls back through the shim's current property, so a test
179
+ * or tally that wraps a shim export still sees every bridge call. Those
180
+ * inner calls reach the instance's own function directly;
181
+ * - a recovery swaps the private functions for the fresh instance's and
182
+ * updates the carried memory. The shim keeps its guarded functions.
183
+ */
184
+ function runtimeOverShim(shim, carried, maximumBytes) {
185
+ const holder = shim;
186
+ let instanceFunctions = { ...holder };
187
+ let insideRuntime = false;
188
+ let guarded;
189
+ for (const [name, value] of Object.entries(instanceFunctions)) {
190
+ if (UNGUARDED_GLUE_FIELDS.has(name) || !isPlainFunction(value))
191
+ continue;
192
+ holder[name] = function guardedShimCall(...args) {
193
+ if (insideRuntime) {
194
+ const own = instanceFunctions[name];
195
+ if (typeof own !== "function") {
196
+ throw new TypeError(`wasm bridge method ${name} is not a function`);
197
+ }
198
+ return own.apply(instanceFunctions, args);
199
+ }
200
+ return guarded[name](...args);
201
+ };
202
+ }
203
+ const dispatchers = new Map();
204
+ // What the runtime calls: the shim's current property, marked as an inner call.
205
+ const inner = new Proxy({}, {
206
+ get(_target, property) {
207
+ const value = holder[property];
208
+ if (typeof property !== "string" || typeof value !== "function")
209
+ return value;
210
+ let dispatch = dispatchers.get(property);
211
+ if (!dispatch) {
212
+ dispatch = (...args) => {
213
+ const outer = insideRuntime;
214
+ insideRuntime = true;
215
+ try {
216
+ return holder[property].apply(holder, args);
217
+ }
218
+ finally {
219
+ insideRuntime = outer;
220
+ }
221
+ };
222
+ dispatchers.set(property, dispatch);
223
+ }
224
+ return dispatch;
225
+ },
226
+ has(_target, property) {
227
+ return property in holder;
228
+ }
229
+ });
230
+ const runtime = createXlsxWasmRuntime({
231
+ instance: carried.memory ? { raw: inner, memory: carried.memory } : { raw: inner },
232
+ maximumMemoryBytes: maximumBytes,
233
+ reinstantiate() {
234
+ const fresh = freshInstance(carried.glue, carried.module);
235
+ instanceFunctions = { ...fresh.instance };
236
+ if (fresh.memory)
237
+ carried.memory = fresh.memory;
238
+ else
239
+ delete carried.memory;
240
+ return fresh.memory ? { raw: inner, memory: fresh.memory } : { raw: inner };
241
+ }
242
+ });
243
+ guarded = runtime.raw;
244
+ return { runtime, raw: runtime.raw };
245
+ }
246
+ function instantiateOwnRuntime(module, options) {
247
+ const glue = loadGlue();
248
+ const fresh = freshInstance(glue, module);
249
+ const holder = { ...fresh.instance };
250
+ // The build checks the binary against this constant, so a Module compiled
251
+ // from the package's binary carries exactly this maximum.
252
+ return runtimeOverHolder(holder, fresh.memory, glue, module, XLSX_WASM_LINEAR_MEMORY_MAXIMUM_BYTES, options);
253
+ }
254
+ /** A view of the shared default instance with this bridge's own admission. */
255
+ function sharedDefaultView(options) {
256
+ const shared = sharedDefaultRuntime();
257
+ if (options.memoryBudgetBytes === undefined && options.admission === undefined) {
258
+ return shared;
259
+ }
260
+ const runtime = shared.runtime.withAdmission(options);
261
+ return { runtime, raw: runtime.raw };
262
+ }
263
+ function sharedDefaultRuntime() {
264
+ if (defaultRuntime) {
265
+ return defaultRuntime;
266
+ }
267
+ // In the repository the CommonJS shim exists and is the default instance,
268
+ // so in-process code that requires the glue by path shares sessions with
269
+ // this loader, as it did with the CommonJS glue.
270
+ const shimPath = generatedShimPath();
271
+ if (existsSync(shimPath)) {
272
+ const shim = nativeRequire(shimPath);
273
+ const carried = shim[SHIM_INSTANCE_KEY];
274
+ if (carried) {
275
+ const bytes = readFileSync(generatedBinaryPath());
276
+ moduleSha256.set(carried.module, sha256(bytes));
277
+ defaultRuntime = runtimeOverShim(shim, carried, maximumMemoryBytes(bytes));
278
+ return defaultRuntime;
279
+ }
280
+ }
281
+ const bytes = readFileSync(generatedBinaryPath());
282
+ const module = new WebAssembly.Module(bytes);
283
+ moduleSha256.set(module, sha256(bytes));
284
+ const glue = loadGlue();
285
+ const fresh = freshInstance(glue, module);
286
+ const holder = { ...fresh.instance };
287
+ defaultRuntime = runtimeOverHolder(holder, fresh.memory, glue, module, maximumMemoryBytes(bytes), {});
288
+ return defaultRuntime;
58
289
  }
59
290
  /**
60
291
  * SHA-256 of the WebAssembly binary this loader instantiates. Hosts report it
@@ -62,6 +293,5 @@ function generatedWasmModulePath() {
62
293
  * reading the package's directory layout.
63
294
  */
64
295
  export function generatedWasmModuleSha256() {
65
- const binary = resolve(dirname(generatedWasmModulePath()), "xlsx_substrate_wasm_bg.wasm");
66
- return createHash("sha256").update(readFileSync(binary)).digest("hex");
296
+ return sha256(readFileSync(generatedBinaryPath()));
67
297
  }