space-data-module-sdk 0.10.2 → 0.10.4

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.
package/README.md CHANGED
@@ -556,6 +556,48 @@ const bundle = await createSingleFileBundle({
556
556
  const parsed = await parseSingleFileBundle(bundle.wasmBytes);
557
557
  ```
558
558
 
559
+ `prebuiltLibraries` links relocatable WebAssembly objects and static `ar` archives after
560
+ all module and source-library objects, in the supplied order:
561
+
562
+ ```js
563
+ import { readFile } from "node:fs/promises";
564
+ import { writeGuestLinkFiles } from "space-data-module-sdk/compiler";
565
+
566
+ const compilation = await compileModuleFromSource({
567
+ manifest,
568
+ sourceCode,
569
+ language: "c++",
570
+ threadModel: "wasi-sequential",
571
+ prebuiltLibraries: [{
572
+ name: "vector_math",
573
+ version: "1.0.0",
574
+ language: "c", // also "c++" or "fortran"
575
+ namespace: "sdm_lib_vector_math_",
576
+ kind: "archive", // or "wasm-object"
577
+ sha256: releaseMetadata.sha256, // the producer's pinned SHA-256
578
+ objectBytes: new Uint8Array(await readFile("./libvector_math.a")),
579
+ }],
580
+ });
581
+ await writeGuestLinkFiles(compilation, "./dist/guest-link");
582
+ ```
583
+
584
+ The compiler verifies each hash before use. It preserves the producer's symbols;
585
+ `namespace` identifies a library and does not rename prebuilt code. Producers supply
586
+ compatible symbols and a toolchain compatible with the selected thread model.
587
+ Archives retain lazy member extraction. Exact input bytes participate in the link
588
+ cache key. Linked artifacts pass the same thread, import, SIMD, and sequential
589
+ checks; errors include the participating library names.
590
+
591
+ Guest-link output includes each library's bytes, kind, and SHA-256. Flow compilation
592
+ links identical names and hashes once, in first-use order. Conflicting hashes for a
593
+ name or namespace are refused. Existing metadata without `kind` is accepted based
594
+ on the file's contents. Source libraries remain available through `libraries`.
595
+
596
+ The CLI accepts `--prebuilt-libraries ./dist/guest-link/metadata.json`. Its
597
+ `libraries` entries name files relative to that metadata file and carry the same
598
+ name, version, language, namespace, kind, and SHA-256 fields.
599
+ `--thread-model wasi-sequential` selects the sequential WASI compile profile.
600
+
559
601
  Each subsystem is also available as a subpath export:
560
602
 
561
603
  ```js
@@ -1,4 +1,5 @@
1
1
  #!/usr/bin/env node
2
+ import { readGuestLinkLibraries } from "../src/compiler/guestLinkLibraries.js";
2
3
 
3
4
  import path from "node:path";
4
5
  import process from "node:process";
@@ -93,6 +94,12 @@ function parseArgs(argv) {
93
94
  case "--wasm":
94
95
  options.wasmPath = path.resolve(requireValue(argv, ++index, value));
95
96
  break;
97
+ case "--thread-model":
98
+ options.threadModel = requireValue(argv, ++index, value);
99
+ break;
100
+ case "--prebuilt-libraries":
101
+ options.prebuiltLibrariesPath = path.resolve(requireValue(argv, ++index, value));
102
+ break;
96
103
  case "--source":
97
104
  options.sourcePath = path.resolve(requireValue(argv, ++index, value));
98
105
  break;
@@ -234,7 +241,7 @@ function printUsage() {
234
241
  console.log(`Usage:
235
242
  space-data-module check --repo-root .
236
243
  space-data-module check --manifest ./manifest.json --wasm ./dist/module.wasm
237
- space-data-module compile --manifest ./manifest.json --source ./src/module.c --out ./dist/module.wasm
244
+ space-data-module compile --manifest ./manifest.json --source ./src/module.c --out ./dist/module.wasm [--prebuilt-libraries ./dist/guest-link/metadata.json] [--thread-model wasi-sequential]
238
245
  space-data-module init --family propagator --name my-propagator
239
246
  space-data-module init --family propagator --name my-propagator --out ./modules/my-propagator [--plugin-id com.orbpro.my.propagator] [--force] [--json]
240
247
  space-data-module parity --wasm ./dist/isomorphic/module.wasm --fixture ./fixtures/parity/basic.json
@@ -628,8 +635,16 @@ async function runCompile(argv) {
628
635
  }
629
636
  const manifest = await loadManifestFromFile(options.manifestPath);
630
637
  const sourceCode = await readFile(options.sourcePath, "utf8");
638
+ const prebuiltLibraries = options.prebuiltLibrariesPath
639
+ ? await readGuestLinkLibraries({
640
+ guestLinkDir: path.dirname(options.prebuiltLibrariesPath),
641
+ metadata: JSON.parse(await readFile(options.prebuiltLibrariesPath, "utf8")),
642
+ }, manifest.pluginId)
643
+ : undefined;
631
644
  const result = await compileModuleFromSource({
632
645
  manifest,
646
+ prebuiltLibraries,
647
+ threadModel: options.threadModel,
633
648
  sourceCode,
634
649
  language: options.language,
635
650
  outputPath: options.outputPath,
@@ -422,6 +422,39 @@ worker bundles and the browser capability probe.
422
422
 
423
423
  ### Explicit pool size, partial spawns, supervision hooks
424
424
 
425
+ `createBrowserModuleHarness` accepts `wasiThreadProbeTimeoutMs`, the browser
426
+ pool arming deadline in milliseconds. It forwards the value as
427
+ `createWasiThreadSpawn`'s `probeTimeoutMs`. The default is 1500. An explicit
428
+ value must be a positive finite number; invalid values throw an `Error` before
429
+ the artifact is loaded. The option applies to the initial context and each
430
+ fresh command invocation. It has no effect on Node's on-demand pool startup.
431
+
432
+ After harness creation, the read-only `harness.wasiThreadPoolReport` property
433
+ returns a frozen `{ requested, armed }` snapshot. Counts refer to pool workers
434
+ and exclude the calling thread. With `wasiThreadPoolSize`, `requested` is that
435
+ explicit size, including when threading is unavailable. Without an explicit
436
+ size, it is the browser's selected pool size. Non-threaded artifacts return
437
+ `null`. Node reports its explicit cap (or `null` without one) and the number
438
+ of workers started on demand.
439
+
440
+ For an explicit browser pool, fewer armed workers do not throw. Workers that
441
+ miss the deadline are terminated before the harness returns; successfully
442
+ armed workers remain available. The host uses the report to decide whether
443
+ the capacity meets its needs. A guest must handle declined spawns to execute
444
+ successfully with fewer workers. After a command invocation, the property
445
+ reports that invocation's arming counts, even though its pool is terminated.
446
+ These are startup counts, not a live-worker health report.
447
+
448
+ ```js
449
+ const harness = await createBrowserModuleHarness({
450
+ wasmSource,
451
+ enableBrowserWasiThreads: true,
452
+ wasiThreadPoolSize: 8,
453
+ wasiThreadProbeTimeoutMs: 10000,
454
+ });
455
+ const { requested, armed } = harness.wasiThreadPoolReport;
456
+ ```
457
+
425
458
  `createWasiThreadSpawn` options added in 0.8.22:
426
459
 
427
460
  | Option | Effect |
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "space-data-module-sdk",
3
- "version": "0.10.2",
3
+ "version": "0.10.4",
4
4
  "license": "Apache-2.0",
5
5
  "description": "Module SDK for building, validating, signing, and deploying WebAssembly modules on the Space Data Network.",
6
6
  "type": "module",
@@ -60,6 +60,7 @@
60
60
  "default": "./src/host/isomorphicLoader.js"
61
61
  },
62
62
  "./host/browser-module": "./src/host/browserModuleHarness.js",
63
+ "./host/abi": "./src/host/abi.js",
63
64
  "./host/runtime-target-gate": "./src/host/runtimeTargetGate.js",
64
65
  "./host/node-builtin": "./src/host/nodeBuiltinSpecifier.js",
65
66
  "./host/worker-module": "./src/host/workerModuleHarness.js",
@@ -1,3 +1,4 @@
1
+ import { normalizePrebuiltLibraries, collectGuestLinkLibraries, guestLinkLibraryEntries, withLibraryContext } from "./guestLinkLibraries.js";
1
2
  import os from "node:os";
2
3
  import path from "node:path";
3
4
  import { execFile } from "node:child_process";
@@ -642,7 +643,17 @@ function createGuestLinkBundleEntries(guestLink) {
642
643
  if (!guestLink?.objectBytes || guestLink.objectBytes.length === 0) {
643
644
  return [];
644
645
  }
646
+ const libraries = guestLinkLibraryEntries(guestLink.libraries);
645
647
  return [
648
+ ...libraries.map(({ metadata, objectBytes }) => ({
649
+ entryId: metadata.file,
650
+ role: "auxiliary",
651
+ sectionName: SDS_GUEST_LINK_SECTION_NAME,
652
+ payloadEncoding: "raw-bytes",
653
+ mediaType: metadata.kind === "archive" ? "application/octet-stream" : "application/wasm",
654
+ payload: objectBytes,
655
+ description: `Guest-link library ${metadata.name}.`,
656
+ })),
646
657
  {
647
658
  entryId: SDS_GUEST_LINK_OBJECT_ENTRY_ID,
648
659
  role: "auxiliary",
@@ -659,7 +670,8 @@ function createGuestLinkBundleEntries(guestLink) {
659
670
  payloadEncoding: "json-utf8",
660
671
  mediaType: SDS_GUEST_LINK_MEDIA_TYPE,
661
672
  payload: {
662
- version: 1,
673
+ version: libraries.length ? 2 : 1,
674
+ ...(libraries.length ? { libraries: libraries.map(({ metadata }) => metadata) } : {}),
663
675
  format: "wasm-object",
664
676
  symbolPrefix: guestLink.symbolPrefix,
665
677
  methodSymbols: guestLink.methodSymbols,
@@ -1068,6 +1080,10 @@ async function compileWithToolchain(kind, options = {}) {
1068
1080
  outputPath ?? path.join(tempDir, "module.wasm"),
1069
1081
  );
1070
1082
  const libraries = normalizeLibraries(compileOptions.libraries);
1083
+ const prebuilt = compileOptions.prebuiltLibraries.map((library, index) => ({
1084
+ library, namespace: library.namespace, kind: library.kind, objectBytes: library.objectBytes,
1085
+ object: `prebuilt-${index}.${library.kind === "archive" ? "a" : "o"}`,
1086
+ }));
1071
1087
  const profile = await resolveToolchainProfile(kind, {
1072
1088
  language,
1073
1089
  sourceCompilerCommand,
@@ -1110,7 +1126,7 @@ async function compileWithToolchain(kind, options = {}) {
1110
1126
  argv: profile.compileArgv(step.role, at(step.source), at(step.object), step.extra ?? [], step.library?.language),
1111
1127
  }));
1112
1128
  const linkOutput = "module.wasm";
1113
- const linkObjects = compileSteps.map((step) => step.object);
1129
+ const linkObjects = [...compileSteps.map((step) => step.object), ...prebuilt.map((library) => library.object)];
1114
1130
  const linkArgv = profile.linkArgv(linkObjects.map(at), at(linkOutput), linkArgs);
1115
1131
 
1116
1132
  const cacheReport = { enabled: Boolean(cache), dir: cache?.root ?? null, hits: [], misses: [], stepMs: {} };
@@ -1144,10 +1160,8 @@ async function compileWithToolchain(kind, options = {}) {
1144
1160
  const objects = new Map();
1145
1161
  let linked = null;
1146
1162
  const prepareLinkInputs = () => {
1147
- if (libraries.length === 0) {
1148
- return { inputs: new Map(objects), libraries: [] };
1149
- }
1150
- const inputs = new Map(objects);
1163
+ const inputs = new Map([...objects, ...prebuilt.map((library) => [library.object, library.objectBytes])]);
1164
+ if (libraries.length === 0) return { inputs, libraries: prebuilt };
1151
1165
  const references = new Map();
1152
1166
  const namespaced = libraries.map((library) => {
1153
1167
  const step = compileSteps.find((entry) => entry.library === library);
@@ -1183,7 +1197,11 @@ async function compileWithToolchain(kind, options = {}) {
1183
1197
  { undefinedOnly: true },
1184
1198
  ),
1185
1199
  );
1186
- return { inputs, libraries: namespaced };
1200
+ const all = [...namespaced, ...prebuilt];
1201
+ collectGuestLinkLibraries(all.map(({ library, namespace, objectBytes }) => ({
1202
+ ...library, namespace, sha256: sha256Hex(objectBytes),
1203
+ })));
1204
+ return { inputs, libraries: all };
1187
1205
  };
1188
1206
 
1189
1207
  if (cache) {
@@ -1280,11 +1298,12 @@ async function compileWithToolchain(kind, options = {}) {
1280
1298
  objectBytes: guestLink.objectBytes,
1281
1299
  ...(linked.libraries.length > 0
1282
1300
  ? {
1283
- libraries: linked.libraries.map(({ library, namespace, objectBytes }) => ({
1301
+ libraries: linked.libraries.map(({ library, namespace, kind, objectBytes }) => ({
1284
1302
  name: library.name,
1285
1303
  version: library.version,
1286
1304
  language: library.language,
1287
1305
  namespace,
1306
+ ...(kind ? { kind } : {}),
1288
1307
  sha256: sha256Hex(objectBytes),
1289
1308
  objectBytes,
1290
1309
  })),
@@ -1317,6 +1336,7 @@ export async function compileModuleFromSource(options = {}) {
1317
1336
  throw error;
1318
1337
  }
1319
1338
 
1339
+ const prebuiltLibraries = await normalizePrebuiltLibraries(options.prebuiltLibraries);
1320
1340
  const compiler = selectCompiler(options.language);
1321
1341
  const invokeSurfaces = resolveInvokeSurfaces(manifest);
1322
1342
  const includeCommandMain = invokeSurfaces.includes(InvokeSurface.COMMAND);
@@ -1356,6 +1376,7 @@ export async function compileModuleFromSource(options = {}) {
1356
1376
  const simd128 = resolveSimd128(options.simd128, threadModel);
1357
1377
  const compileOptions = {
1358
1378
  ...options,
1379
+ prebuiltLibraries,
1359
1380
  noEntry: includeCommandMain !== true,
1360
1381
  threadModel,
1361
1382
  simd128,
@@ -1465,6 +1486,11 @@ export async function compileModuleFromSource(options = {}) {
1465
1486
  ...standardsOptions,
1466
1487
  });
1467
1488
 
1489
+ if (prebuiltLibraries.length && !report.ok) {
1490
+ const error = new Error(`Linked artifact validation failed: ${JSON.stringify(report.errors)}`);
1491
+ error.report = report;
1492
+ throw error;
1493
+ }
1468
1494
  handedOff = keepTempDir;
1469
1495
  return {
1470
1496
  compiler: useWasiThreads
@@ -1490,6 +1516,8 @@ export async function compileModuleFromSource(options = {}) {
1490
1516
  simd128: simd128Report,
1491
1517
  report,
1492
1518
  };
1519
+ } catch (error) {
1520
+ throw withLibraryContext(error, prebuiltLibraries);
1493
1521
  } finally {
1494
1522
  if (!handedOff) {
1495
1523
  await rm(tempDir, { recursive: true, force: true });
@@ -17,6 +17,8 @@
17
17
  import path from "node:path";
18
18
  import { mkdir, rm, writeFile } from "node:fs/promises";
19
19
 
20
+ import { guestLinkLibraryEntries } from "./guestLinkLibraries.js";
21
+
20
22
  import { canonicalBytes } from "../auth/canonicalize.js";
21
23
 
22
24
  function concatNewline(bytes) {
@@ -42,18 +44,10 @@ export async function writeGuestLinkFiles(compilation, dir, metadata = {}) {
42
44
  const librariesDir = path.join(dir, "libraries");
43
45
  await rm(librariesDir, { recursive: true, force: true });
44
46
  const libraryEntries = [];
45
- for (const library of libraries) {
46
- const file = `libraries/${library.name}-${library.version}-${library.sha256.slice(0, 12)}.o`;
47
+ for (const { metadata, objectBytes } of guestLinkLibraryEntries(libraries)) {
47
48
  await mkdir(librariesDir, { recursive: true });
48
- await writeFile(path.join(dir, file), library.objectBytes);
49
- libraryEntries.push({
50
- name: library.name,
51
- version: library.version,
52
- language: library.language,
53
- namespace: library.namespace,
54
- sha256: library.sha256,
55
- file,
56
- });
49
+ await writeFile(path.join(dir, metadata.file), objectBytes);
50
+ libraryEntries.push(metadata);
57
51
  }
58
52
  const written = {
59
53
  version: libraryEntries.length > 0 ? 2 : 1,
@@ -0,0 +1,122 @@
1
+ import path from "node:path";
2
+ import { readFile } from "node:fs/promises";
3
+ import { bytesToHex } from "../utils/encoding.js";
4
+ import { sha256Bytes } from "../utils/crypto.js";
5
+ import { parseWasmModuleSections } from "../bundle/wasm.js";
6
+
7
+ const NAME = /^[A-Za-z][A-Za-z0-9._-]*$/;
8
+ const VERSION = /^[A-Za-z0-9][A-Za-z0-9._-]*$/;
9
+ const NAMESPACE = /^sdm_lib_[A-Za-z0-9_]+_$/;
10
+
11
+ /** The same byte, hash and metadata contract applies to MODULE and FLOW inputs. */
12
+ export async function verifyGuestLinkLibrary(library, { requireKind = false } = {}) {
13
+ const label = `Guest-link library "${library?.name ?? "unnamed"}"`;
14
+ if (!NAME.test(library?.name ?? "") || !VERSION.test(library?.version ?? "") ||
15
+ !NAMESPACE.test(library?.namespace ?? "") ||
16
+ !["c", "c++", "fortran"].includes(library?.language)) {
17
+ throw new Error(`${label} has invalid name, version, namespace or language.`);
18
+ }
19
+ if (!(library.objectBytes instanceof Uint8Array) || !library.objectBytes.length) {
20
+ throw new Error(`${label} needs nonempty objectBytes.`);
21
+ }
22
+ const objectBytes = new Uint8Array(library.objectBytes);
23
+ const sha256 = bytesToHex(await sha256Bytes(objectBytes));
24
+ if (sha256 !== library.sha256) {
25
+ throw new Error(`${label} SHA-256 mismatch: expected ${library.sha256}, received ${sha256}.`);
26
+ }
27
+ const archive = new TextDecoder().decode(objectBytes.subarray(0, 8)) === "!<arch>\n";
28
+ const kind = library.kind ?? (requireKind ? null : archive ? "archive" : "wasm-object");
29
+ if (!["wasm-object", "archive"].includes(kind) || archive !== (kind === "archive")) {
30
+ throw new Error(`${label} kind must match its bytes (wasm-object or archive).`);
31
+ }
32
+ if (kind === "wasm-object") {
33
+ try {
34
+ const parsed = parseWasmModuleSections(objectBytes);
35
+ if (!parsed.sections.some(section => section.id === 0 && section.name === "linking")) {
36
+ throw new Error("missing relocatable linking section");
37
+ }
38
+ } catch (error) {
39
+ throw new Error(`${label} is not a relocatable wasm object: ${error.message}`, { cause: error });
40
+ }
41
+ }
42
+ return { ...library, kind, sha256, objectBytes };
43
+ }
44
+
45
+ // Same names identify the same bytes. Namespaces also cannot alias different bytes.
46
+ // First-use order preserves archive dependency ordering.
47
+ export function collectGuestLinkLibraries(libraries) {
48
+ const byName = new Map();
49
+ const byNamespace = new Map();
50
+ const unique = [];
51
+ for (const library of libraries) {
52
+ for (const prior of [byName.get(library.name), byNamespace.get(library.namespace)]) {
53
+ if (prior && prior.sha256 !== library.sha256) {
54
+ throw new Error(`Conflicting guest-link library "${library.name}": ${prior.sha256} and ${library.sha256} (namespace ${library.namespace}).`);
55
+ }
56
+ }
57
+ if (!byName.has(library.name) && !byNamespace.has(library.namespace)) {
58
+ unique.push(library);
59
+ }
60
+ byName.set(library.name, library);
61
+ byNamespace.set(library.namespace, library);
62
+ }
63
+ return unique;
64
+ }
65
+
66
+ export async function normalizePrebuiltLibraries(libraries) {
67
+ if (libraries == null) return [];
68
+ if (!Array.isArray(libraries)) throw new Error("prebuiltLibraries must be an array.");
69
+ const verified = [];
70
+ for (const library of libraries) verified.push(await verifyGuestLinkLibrary(library, { requireKind: true }));
71
+ return collectGuestLinkLibraries(verified);
72
+ }
73
+
74
+ export async function readGuestLinkLibraries(guestLink, pluginId) {
75
+ const listed = guestLink.metadata?.libraries;
76
+ if (listed == null) return [];
77
+ if (!Array.isArray(listed)) {
78
+ throw new Error(`Plugin "${pluginId}": guest-link metadata.libraries must be an array.`);
79
+ }
80
+ const libraries = [];
81
+ for (const library of listed) {
82
+ const file = String(library?.file ?? "");
83
+ const resolved = path.resolve(guestLink.guestLinkDir, file);
84
+ if (!file || !resolved.startsWith(guestLink.guestLinkDir + path.sep)) {
85
+ throw new Error(`Plugin "${pluginId}": guest-link library ${JSON.stringify(library?.name)} has no file inside its guest-link dir.`);
86
+ }
87
+ try {
88
+ libraries.push(await verifyGuestLinkLibrary({ ...library, objectBytes: new Uint8Array(await readFile(resolved)) }));
89
+ } catch (error) {
90
+ throw new Error(`Plugin "${pluginId}" library "${library?.name}": ${error.message}`, { cause: error });
91
+ }
92
+ }
93
+ return collectGuestLinkLibraries(libraries);
94
+ }
95
+
96
+ export async function collectFlowLibraryObjects(linkedDependencies) {
97
+ const libraries = [];
98
+ for (const dependency of linkedDependencies) {
99
+ for (const library of dependency.guestLink?.libraries ?? []) {
100
+ libraries.push(await verifyGuestLinkLibrary(library));
101
+ }
102
+ }
103
+ return collectGuestLinkLibraries(libraries);
104
+ }
105
+
106
+ export function guestLinkLibraryEntries(libraries = []) {
107
+ return libraries.map(({ objectBytes, name, version, language, namespace, sha256, kind }) => ({
108
+ objectBytes,
109
+ metadata: {
110
+ name, version, language, namespace, sha256,
111
+ ...(kind ? { kind } : {}),
112
+ file: `libraries/${name}-${version}-${sha256.slice(0, 12)}.${kind === "archive" ? "a" : "o"}`,
113
+ },
114
+ }));
115
+ }
116
+
117
+ export function withLibraryContext(error, libraries) {
118
+ if (!libraries?.length) return error;
119
+ const wrapped = new Error(`${error.message}\nGuest-link libraries: ${libraries.map(library => JSON.stringify(library.name)).join(", ")}.`, { cause: error });
120
+ if (error.report) wrapped.report = error.report;
121
+ return wrapped;
122
+ }
@@ -1,3 +1,4 @@
1
+ import { readGuestLinkLibraries, collectFlowLibraryObjects, withLibraryContext } from "../compiler/guestLinkLibraries.js";
1
2
  /**
2
3
  * SDN flow compiler (loop C.3c) — `space-data-module flow check|compile`.
3
4
  *
@@ -427,47 +428,6 @@ async function loadDependencyFromDirectory(dir) {
427
428
  return entry;
428
429
  }
429
430
 
430
- async function readGuestLinkLibraries(guestLink, pluginId) {
431
- const listed = guestLink.metadata?.libraries;
432
- if (listed === undefined || listed === null) return [];
433
- if (!Array.isArray(listed)) {
434
- throw new Error(`Plugin "${pluginId}": guest-link metadata.libraries must be an array.`);
435
- }
436
- const libraries = [];
437
- for (const library of listed) {
438
- const file = String(library?.file ?? "");
439
- const resolved = path.resolve(guestLink.guestLinkDir, file);
440
- if (!file || !resolved.startsWith(guestLink.guestLinkDir + path.sep)) {
441
- throw new Error(`Plugin "${pluginId}": guest-link library ${JSON.stringify(library?.name)} has no file inside its guest-link dir.`);
442
- }
443
- if (!/^sdm_lib_[A-Za-z0-9_]+_$/.test(String(library?.namespace ?? ""))) {
444
- throw new Error(`Plugin "${pluginId}": guest-link library ${JSON.stringify(library?.name)} has no sdm_lib_ namespace.`);
445
- }
446
- const objectBytes = new Uint8Array(await readFile(resolved));
447
- const sha256 = bytesToHex(await sha256Bytes(objectBytes));
448
- if (sha256 !== library.sha256) {
449
- throw new Error(
450
- `Plugin "${pluginId}": guest-link library ${file} hashes to ${sha256}, but its metadata records ${library.sha256}.`,
451
- );
452
- }
453
- libraries.push({ ...library, objectBytes });
454
- }
455
- return libraries;
456
- }
457
-
458
- // Each shared library namespace once, in first-use order. A namespace is the
459
- // library's name, version and a digest of its source, defines, flags and
460
- // toolchain kind, so two modules carrying the same namespace carry the same
461
- // library and the flow links one copy of it.
462
- function collectFlowLibraryObjects(linkedDependencies) {
463
- const byNamespace = new Map();
464
- for (const dependency of linkedDependencies) {
465
- for (const library of dependency.guestLink?.libraries ?? []) {
466
- if (!byNamespace.has(library.namespace)) byNamespace.set(library.namespace, library);
467
- }
468
- }
469
- return Array.from(byNamespace.values());
470
- }
471
431
 
472
432
  async function scanForDependencyDirs(root, found) {
473
433
  let entries;
@@ -3236,40 +3196,47 @@ export async function compileFlowProgram({
3236
3196
  check.threadModel !== FLOW_THREAD_MODEL.SINGLE_THREAD
3237
3197
  ? linkFlowArtifactWithWasiThreads
3238
3198
  : linkFlowArtifactWithEmception;
3239
- let wasmBytes = await linkFlowArtifactCached(linkFlowArtifact, check.threadModel, {
3240
- runtimeSource,
3241
- invokeHeader: generateInvokeSupportHeader(),
3242
- generatedInc,
3243
- manifestSource,
3244
- programSource,
3245
- dependencyObjects: [
3246
- ...linkedDependencies.map((dependency) => dependency.guestLink.objectBytes),
3247
- ...collectFlowLibraryObjects(linkedDependencies).map((library) => library.objectBytes),
3248
- ],
3249
- engineLinked: Boolean(check.engineLinkage),
3250
- sequential: check.threadModel === FLOW_THREAD_MODEL.WASI_SEQUENTIAL,
3251
- });
3252
- wasmBytes = appendWasmCustomSection(
3253
- wasmBytes,
3254
- SDS_MANIFEST_SECTION_NAME,
3255
- flowPlgBytes,
3256
- );
3257
- if (check.threadModel === FLOW_THREAD_MODEL.WASI_THREADS) {
3258
- assertPthreadArtifact(wasmBytes, { source: sourceName });
3259
- } else if (check.threadModel === FLOW_THREAD_MODEL.WASI_SEQUENTIAL) {
3260
- assertSequentialArtifact(wasmBytes, { source: sourceName });
3261
- }
3199
+ const flowLibraries = await collectFlowLibraryObjects(linkedDependencies);
3200
+ let wasmBytes;
3201
+ let report;
3202
+ try {
3203
+ wasmBytes = await linkFlowArtifactCached(linkFlowArtifact, check.threadModel, {
3204
+ runtimeSource,
3205
+ invokeHeader: generateInvokeSupportHeader(),
3206
+ generatedInc,
3207
+ manifestSource,
3208
+ programSource,
3209
+ dependencyObjects: [
3210
+ ...linkedDependencies.map((dependency) => dependency.guestLink.objectBytes),
3211
+ ...flowLibraries.map((library) => library.objectBytes),
3212
+ ],
3213
+ engineLinked: Boolean(check.engineLinkage),
3214
+ sequential: check.threadModel === FLOW_THREAD_MODEL.WASI_SEQUENTIAL,
3215
+ });
3216
+ wasmBytes = appendWasmCustomSection(
3217
+ wasmBytes,
3218
+ SDS_MANIFEST_SECTION_NAME,
3219
+ flowPlgBytes,
3220
+ );
3221
+ if (check.threadModel === FLOW_THREAD_MODEL.WASI_THREADS) {
3222
+ assertPthreadArtifact(wasmBytes, { source: sourceName });
3223
+ } else if (check.threadModel === FLOW_THREAD_MODEL.WASI_SEQUENTIAL) {
3224
+ assertSequentialArtifact(wasmBytes, { source: sourceName });
3225
+ }
3262
3226
 
3263
- const report = await validateArtifactWithStandards({
3264
- manifest,
3265
- wasmBytes,
3266
- sourceName,
3267
- ...standardsOptions,
3268
- });
3269
- if (!report.ok) {
3270
- const error = new Error("Flow artifact compliance validation failed.");
3271
- error.report = report;
3272
- throw error;
3227
+ report = await validateArtifactWithStandards({
3228
+ manifest,
3229
+ wasmBytes,
3230
+ sourceName,
3231
+ ...standardsOptions,
3232
+ });
3233
+ if (!report.ok) {
3234
+ const error = new Error("Flow artifact compliance validation failed.");
3235
+ error.report = report;
3236
+ throw error;
3237
+ }
3238
+ } catch (error) {
3239
+ throw withLibraryContext(error, flowLibraries);
3273
3240
  }
3274
3241
 
3275
3242
  const dependencyRecords = [];
@@ -429,6 +429,7 @@ async function instantiateBrowserModule(options = {}) {
429
429
  // the module will actually ask for. Ignored by the Node lazy path.
430
430
  requestedThreads: options.maxThreads,
431
431
  poolSize: options.wasiThreadPoolSize,
432
+ probeTimeoutMs: options.wasiThreadProbeTimeoutMs,
432
433
  hostcallChannel: options.threadHostcallChannel,
433
434
  requiresHostcalls: needsHostBridge,
434
435
  enableBrowserThreads: options.enableBrowserWasiThreads,
@@ -485,8 +486,14 @@ async function instantiateBrowserModule(options = {}) {
485
486
  * @param {number} [options.wasiThreadSpawnWaitMs] - How long a guest spawn that
486
487
  * finds every pooled thread busy waits for one to finish before
487
488
  * pthread_create fails (createWasiThreadSpawn `spawnWaitMs`, default 250).
489
+ * @param {number} [options.wasiThreadProbeTimeoutMs] - Positive finite browser
490
+ * pool arming deadline in milliseconds (default 1500).
488
491
  */
489
492
  export async function createBrowserModuleHarness(options = {}) {
493
+ if (options.wasiThreadProbeTimeoutMs !== undefined &&
494
+ (!Number.isFinite(options.wasiThreadProbeTimeoutMs) || options.wasiThreadProbeTimeoutMs <= 0)) {
495
+ throw new Error("wasiThreadProbeTimeoutMs must be a positive finite number.");
496
+ }
490
497
  let wasmSource = options.wasmSource;
491
498
  const signaturePolicy = resolveModuleSignaturePolicy(options);
492
499
  // Bytes THIS function materializes itself (Response/URL fetch, or the
@@ -596,6 +603,7 @@ export async function createBrowserModuleHarness(options = {}) {
596
603
  wasiThreadWorkerUrl: options.wasiThreadWorkerUrl,
597
604
  wasiThreadSpawnWaitMs: options.wasiThreadSpawnWaitMs,
598
605
  wasiThreadPoolSize: options.wasiThreadPoolSize,
606
+ wasiThreadProbeTimeoutMs: options.wasiThreadProbeTimeoutMs,
599
607
  });
600
608
  const { instance, bridge, wasi, memory, threadHost } = activeContext;
601
609
  let lastCommandContext = null;
@@ -862,6 +870,7 @@ export async function createBrowserModuleHarness(options = {}) {
862
870
  wasiThreadWorkerUrl: options.wasiThreadWorkerUrl,
863
871
  wasiThreadSpawnWaitMs: options.wasiThreadSpawnWaitMs,
864
872
  wasiThreadPoolSize: options.wasiThreadPoolSize,
873
+ wasiThreadProbeTimeoutMs: options.wasiThreadProbeTimeoutMs,
865
874
  });
866
875
  lastCommandContext = commandContext;
867
876
  let exitError = null;
@@ -974,6 +983,10 @@ export async function createBrowserModuleHarness(options = {}) {
974
983
  // spawn host so callers can observe real thread activity
975
984
  // (spawnCount/distinctOsThreadCount).
976
985
  get threadHost() { return lastCommandContext?.threadHost ?? threadHost; },
986
+ get wasiThreadPoolReport() {
987
+ const report = (lastCommandContext?.threadHost ?? threadHost)?.spawnReport();
988
+ return report ? Object.freeze({ requested: report.poolSize, armed: report.armed }) : null;
989
+ },
977
990
  callHost,
978
991
  invokeDirect,
979
992
  invoke,
package/src/index.d.ts CHANGED
@@ -1059,7 +1059,7 @@ export interface GuestLinkArtifact {
1059
1059
  /** Present (true) only for a module that uses WebAssembly SIMD, declared with `simd128: true` or not. */
1060
1060
  simd128?: true;
1061
1061
  objectBytes: Uint8Array;
1062
- /** Present when the compile linked `libraries`. */
1062
+ /** Present when the compile linked source or prebuilt libraries. */
1063
1063
  libraries?: GuestLinkLibrary[];
1064
1064
  }
1065
1065
 
@@ -1165,6 +1165,8 @@ export function compileModuleFromSource(options: {
1165
1165
  * declares their functions; the library sources define them.
1166
1166
  */
1167
1167
  libraries?: ModuleLibrarySource[];
1168
+ /** Hash-verified inputs in link order, with producer-owned symbols. */
1169
+ prebuiltLibraries?: (GuestLinkLibrary & { kind: "wasm-object" | "archive" })[];
1168
1170
  }): Promise<CompilationResult>;
1169
1171
 
1170
1172
  export interface ModuleLibrarySource {
@@ -1180,15 +1182,16 @@ export interface ModuleLibrarySource {
1180
1182
  }
1181
1183
 
1182
1184
  /**
1183
- * A shared library object. Its strong global symbols are renamed into
1184
- * `namespace` (sdm_lib_<name>_<version>_<digest>_, the digest covering its
1185
- * source, defines, flags and toolchain kind); the module object's references
1186
- * follow. A flow links each namespace once.
1185
+ * A guest-link library. Source libraries have SDK-namespaced symbols;
1186
+ * prebuilt libraries preserve the producer's symbols. A flow links identical
1187
+ * names and hashes once and refuses conflicting bytes for a name or namespace.
1187
1188
  */
1188
1189
  export interface GuestLinkLibrary {
1189
1190
  name: string;
1190
1191
  version: string;
1191
- language: "c" | "c++";
1192
+ language: "c" | "c++" | "fortran";
1193
+ /** Omitted in legacy source-library metadata (wasm-object). */
1194
+ kind?: "wasm-object" | "archive";
1192
1195
  namespace: string;
1193
1196
  sha256: string;
1194
1197
  objectBytes: Uint8Array;
@@ -2153,6 +2156,11 @@ export function createBrowserWasiShim(options?: {
2153
2156
  };
2154
2157
  }): BrowserWasiShim;
2155
2158
  export interface BrowserModuleHarness {
2159
+ /** Pool workers requested and armed; excludes the calling thread. Null for non-threaded artifacts.
2160
+ * Command calls report the most recent invocation, including after its pool is terminated.
2161
+ * Node starts workers on demand; requested is null without an explicit pool size.
2162
+ */
2163
+ readonly wasiThreadPoolReport: Readonly<{ requested: number | null; armed: number }> | null;
2156
2164
  runtime: {
2157
2165
  kind: "browser";
2158
2166
  profile: string;
@@ -2231,6 +2239,8 @@ export function createBrowserModuleHarness(options?: {
2231
2239
  wasiThreadSpawnWaitMs?: number;
2232
2240
  // Explicit wasi-threads pool size (createWasiThreadSpawn poolSize).
2233
2241
  wasiThreadPoolSize?: number;
2242
+ /** Positive finite browser pool arming deadline in milliseconds. Default 1500. */
2243
+ wasiThreadProbeTimeoutMs?: number;
2234
2244
  // Request-isolated BroadcastChannel descriptor a nested pthread hostcall
2235
2245
  // dispatches over; supplied by createWorkerModuleHarness for the in-worker
2236
2246
  // harness instance, not something a top-level caller usually sets by hand.