space-data-module-sdk 0.10.1 → 0.10.3
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 +42 -0
- package/bin/space-data-module.js +16 -1
- package/docs/flatsql-host-contract.html +2 -2
- package/docs/flatsql-host-contract.md +1 -1
- package/package.json +4 -3
- package/src/compiler/compileModule.js +36 -8
- package/src/compiler/guestLinkFiles.js +5 -11
- package/src/compiler/guestLinkLibraries.js +122 -0
- package/src/flow/flowCompiler.js +41 -74
- package/src/host/browserModuleHarness.js +28 -22
- package/src/index.d.ts +9 -6
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
|
package/bin/space-data-module.js
CHANGED
|
@@ -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,
|
|
@@ -5,7 +5,7 @@
|
|
|
5
5
|
<link rel="stylesheet" href="./assets/sdn-chrome/sdn-chrome.css" />
|
|
6
6
|
<script src="./assets/sdn-chrome/sdn-chrome.js"></script>
|
|
7
7
|
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
|
8
|
-
<meta name="description" content="The SDK uses FlatSQL 3.12
|
|
8
|
+
<meta name="description" content="The SDK uses FlatSQL 3.12, one public API and one flatsql/flatsql.wasm" />
|
|
9
9
|
<title>FlatSQL host contract — Space Data Module SDK</title>
|
|
10
10
|
<link rel="icon" href="data:image/svg+xml,<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 32 32' fill='none'><defs><linearGradient id='t' gradientUnits='userSpaceOnUse' x1='16' y1='29' x2='16' y2='3'><stop offset='0' stop-color='%23f5a524' stop-opacity='0'/><stop offset='.55' stop-color='%23f5a524' stop-opacity='.55'/><stop offset='1' stop-color='%23f5a524'/></linearGradient></defs><circle cx='16' cy='16' r='13' stroke='%23f5f5f7' stroke-width='1.6' opacity='.3'/><path d='M16 29A13 13 0 0 1 16 3' stroke='url(%23t)' stroke-width='2.2' stroke-linecap='round'/><path d='M16 10.2L10.4 20.1H21.6Z' stroke='%23f5f5f7' stroke-width='1.6' stroke-linejoin='round'/><circle cx='16' cy='10.2' r='2.6' fill='%23f5f5f7'/><circle cx='10.4' cy='20.1' r='2.6' fill='%23f5f5f7'/><circle cx='21.6' cy='20.1' r='2.6' fill='%23f5f5f7'/><circle cx='16' cy='3' r='2.5' fill='%23f5a524'/></svg>" />
|
|
11
11
|
<link rel="stylesheet" href="./styles.css" />
|
|
@@ -95,7 +95,7 @@
|
|
|
95
95
|
</nav>
|
|
96
96
|
<main class="doc" id="main">
|
|
97
97
|
<h1>FlatSQL host contract</h1>
|
|
98
|
-
<p>The SDK uses <strong>FlatSQL 3.12
|
|
98
|
+
<p>The SDK uses <strong>FlatSQL 3.12</strong>, one public API and one <code>flatsql/flatsql.wasm</code> artifact across Node, browsers and native WASI hosts. The runtime store uses <code>FlatSQL.open</code>, binary schema registration, native record ingestion and SDS QRP queries. All operations are asynchronous.</p>
|
|
99
99
|
<h2 id="binary-boundary"><a class="anchor" href="#binary-boundary" aria-hidden="true">#</a>Binary boundary</h2>
|
|
100
100
|
<p>Register canonical SDS BFBS schemas before ingesting records. Records are size-prefixed FlatBuffers; queries and projected results use SDS QRP. Geometry uses SDS GJN. Schema compilation, JSON/GeoJSON conversion and presentation run outside the engine, using <code>flatc-wasm</code> or generated SDS bindings.</p>
|
|
101
101
|
<p>The SDK provides <code>encodeFlatSqlQuery</code> and <code>decodeFlatSqlResult</code> as caller-side QRP helpers. <code>createFlatSqlRuntimeStore</code> owns native row identities, and <code>createFlatBufferStreamIngestor</code> supplies ordered, backpressured ingestion. Await <code>pushBytes</code>, <code>finish</code>, all row-store calls and <code>close</code>.</p>
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
# The unified FlatSQL host contract
|
|
2
2
|
|
|
3
|
-
The SDK uses **FlatSQL 3.12
|
|
3
|
+
The SDK uses **FlatSQL 3.12**, one public API and one `flatsql/flatsql.wasm`
|
|
4
4
|
artifact across Node, browsers and native WASI hosts. The runtime store uses
|
|
5
5
|
`FlatSQL.open`, binary schema registration, native record ingestion and SDS QRP
|
|
6
6
|
queries. All operations are asynchronous.
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "space-data-module-sdk",
|
|
3
|
-
"version": "0.10.
|
|
3
|
+
"version": "0.10.3",
|
|
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",
|
|
@@ -93,7 +94,7 @@
|
|
|
93
94
|
],
|
|
94
95
|
"scripts": {
|
|
95
96
|
"test": "node scripts/flatsql-release-e2e.mjs",
|
|
96
|
-
"test:host-surfaces": "node --test test/node-host.test.js test/host-abi.test.js test/browser-host.test.js test/browser-module-harness.test.js test/testing-harness.test.js",
|
|
97
|
+
"test:host-surfaces": "node --test test/node-host.test.js test/host-abi.test.js test/browser-host.test.js test/browser-module-harness.test.js test/testing-harness.test.js test/browser-owner-tls.test.js",
|
|
97
98
|
"test:runtime-matrix": "SPACE_DATA_MODULE_SDK_ENABLE_RUNTIME_MATRIX=1 node --test test/runtime-matrix.test.js",
|
|
98
99
|
"test:parity": "node --test test/parity-harness.test.js",
|
|
99
100
|
"test:parity-tri-lane": "SPACE_DATA_MODULE_SDK_ENABLE_TRI_RUNTIME_PARITY=1 node --test test/parity-tri-lane.test.js",
|
|
@@ -131,7 +132,7 @@
|
|
|
131
132
|
"flatsql": "3.12.1",
|
|
132
133
|
"hd-wallet-wasm": "2.2.2",
|
|
133
134
|
"sdn-emception": "1.0.0",
|
|
134
|
-
"spacedatastandards.org": "1.
|
|
135
|
+
"spacedatastandards.org": "1.279.0"
|
|
135
136
|
},
|
|
136
137
|
"devDependencies": {
|
|
137
138
|
"esbuild": "^0.28.0",
|
|
@@ -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
|
-
|
|
1148
|
-
|
|
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
|
-
|
|
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
|
|
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),
|
|
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
|
+
}
|
package/src/flow/flowCompiler.js
CHANGED
|
@@ -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
|
-
|
|
3240
|
-
|
|
3241
|
-
|
|
3242
|
-
|
|
3243
|
-
|
|
3244
|
-
|
|
3245
|
-
|
|
3246
|
-
|
|
3247
|
-
|
|
3248
|
-
|
|
3249
|
-
|
|
3250
|
-
|
|
3251
|
-
|
|
3252
|
-
|
|
3253
|
-
|
|
3254
|
-
|
|
3255
|
-
|
|
3256
|
-
|
|
3257
|
-
|
|
3258
|
-
|
|
3259
|
-
|
|
3260
|
-
|
|
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
|
-
|
|
3264
|
-
|
|
3265
|
-
|
|
3266
|
-
|
|
3267
|
-
|
|
3268
|
-
|
|
3269
|
-
|
|
3270
|
-
|
|
3271
|
-
|
|
3272
|
-
|
|
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 = [];
|
|
@@ -378,30 +378,10 @@ async function instantiateBrowserModule(options = {}) {
|
|
|
378
378
|
"wasi-threads module imports wasi.thread-spawn but no shared imported memory is available.",
|
|
379
379
|
);
|
|
380
380
|
}
|
|
381
|
-
|
|
382
|
-
wasmModule: options.wasmModule,
|
|
383
|
-
memory: providedMemory,
|
|
384
|
-
processState,
|
|
385
|
-
// Browser warm-pool sizing: cap pooled workers at how many guest threads
|
|
386
|
-
// the module will actually ask for. Ignored by the Node lazy path.
|
|
387
|
-
requestedThreads: options.maxThreads,
|
|
388
|
-
poolSize: options.wasiThreadPoolSize,
|
|
389
|
-
hostcallChannel: options.threadHostcallChannel,
|
|
390
|
-
requiresHostcalls: needsHostBridge,
|
|
391
|
-
enableBrowserThreads: options.enableBrowserWasiThreads,
|
|
392
|
-
// Explicit worker anchor for BUNDLED consumers: when this host source is
|
|
393
|
-
// bundled into an engine artifact, `import.meta.url` inside the SDK host
|
|
394
|
-
// points at the bundle and the sibling worker asset 404s. A host shim
|
|
395
|
-
// passes the directory its build actually serves the SDK host chain from
|
|
396
|
-
// (e.g. OrbPro: `js/vendor/space-data-module-sdk/src/host/`). Unset =
|
|
397
|
-
// packaged sibling, i.e. today's unbundled behavior.
|
|
398
|
-
browserWorkerBaseUrl: options.wasiThreadWorkerBaseUrl,
|
|
399
|
-
browserWorkerUrl: options.wasiThreadWorkerUrl,
|
|
400
|
-
spawnWaitMs: options.wasiThreadSpawnWaitMs,
|
|
401
|
-
});
|
|
381
|
+
|
|
402
382
|
importObject.wasi = {
|
|
403
383
|
...(importObject.wasi ?? {}),
|
|
404
|
-
"thread-spawn": threadHost.threadSpawn,
|
|
384
|
+
"thread-spawn": (...args) => threadHost.threadSpawn(...args),
|
|
405
385
|
};
|
|
406
386
|
}
|
|
407
387
|
|
|
@@ -437,6 +417,32 @@ async function instantiateBrowserModule(options = {}) {
|
|
|
437
417
|
}
|
|
438
418
|
wasi.setMemory(memory);
|
|
439
419
|
}
|
|
420
|
+
// Instantiate the owner before secondary instances can initialize shared
|
|
421
|
+
// memory. The WASI startup winner establishes the owner's TLS base.
|
|
422
|
+
// Constructors run after the pool is ready so they can spawn threads.
|
|
423
|
+
if (isThreaded) {
|
|
424
|
+
threadHost = await createWasiThreadSpawn({
|
|
425
|
+
wasmModule: options.wasmModule,
|
|
426
|
+
memory: providedMemory,
|
|
427
|
+
processState,
|
|
428
|
+
// Browser warm-pool sizing: cap pooled workers at how many guest threads
|
|
429
|
+
// the module will actually ask for. Ignored by the Node lazy path.
|
|
430
|
+
requestedThreads: options.maxThreads,
|
|
431
|
+
poolSize: options.wasiThreadPoolSize,
|
|
432
|
+
hostcallChannel: options.threadHostcallChannel,
|
|
433
|
+
requiresHostcalls: needsHostBridge,
|
|
434
|
+
enableBrowserThreads: options.enableBrowserWasiThreads,
|
|
435
|
+
// Explicit worker anchor for BUNDLED consumers: when this host source is
|
|
436
|
+
// bundled into an engine artifact, `import.meta.url` inside the SDK host
|
|
437
|
+
// points at the bundle and the sibling worker asset 404s. A host shim
|
|
438
|
+
// passes the directory its build actually serves the SDK host chain from
|
|
439
|
+
// (e.g. OrbPro: `js/vendor/space-data-module-sdk/src/host/`). Unset =
|
|
440
|
+
// packaged sibling, i.e. today's unbundled behavior.
|
|
441
|
+
browserWorkerBaseUrl: options.wasiThreadWorkerBaseUrl,
|
|
442
|
+
browserWorkerUrl: options.wasiThreadWorkerUrl,
|
|
443
|
+
spawnWaitMs: options.wasiThreadSpawnWaitMs,
|
|
444
|
+
});
|
|
445
|
+
}
|
|
440
446
|
initializeInstance(instance, options.directSurface === true);
|
|
441
447
|
} catch (error) {
|
|
442
448
|
await threadHost?.terminateAll();
|
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
|
|
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
|
|
1184
|
-
*
|
|
1185
|
-
*
|
|
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;
|