space-data-module-sdk 0.9.13 → 0.9.15

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
@@ -385,6 +385,38 @@ If a runtime cannot interoperate with the guest pthread contract directly,
385
385
  document that as a wrapper requirement instead of changing the guest artifact
386
386
  semantics.
387
387
 
388
+ ## WebAssembly SIMD (opt-in)
389
+
390
+ `compileModuleFromSource({ simd128: true })` compiles the module's own code and its `libraries` with
391
+ `-msimd128`: `__wasm_simd128__` is defined, clang vector types and `wasm_simd128.h` lower to `v128`
392
+ instructions, and the compiler may vectorize. It needs `threadModel` `"wasi-sequential"` or
393
+ `"emscripten-pthreads"` (the clang `wasm32-wasip1-threads` toolchain); the legacy `"single-thread"`
394
+ model refuses it. The generated manifest exports and invoke bridge keep their flags.
395
+
396
+ - A module that does not opt in compiles with exactly the flags it always did: its `module.wasm`
397
+ and guest-link object are byte-identical to SDK 0.9.14's.
398
+ - The artifact guard (`src/compiler/simdArtifactGuard.js`) holds the emitted wasm to the declaration:
399
+ an opted-in build must declare `simd128` in `target_features`; relaxed-SIMD is always refused (its
400
+ results are implementation-defined and would differ between the browser and WasmEdge); and an
401
+ artifact with a function body the scanner cannot decode is refused, because SIMD inside it would go
402
+ uncounted.
403
+ - SIMD without the option is NOT refused yet. A module built by its own clang driver with `-msimd128`
404
+ (a driver named by `SDN_WASI_CLANGXX`, as the modules `propagator/ffm` and `analysis/density-calibration`
405
+ do), or with a per-function `target("simd128")` attribute, still compiles. Its SIMD is recorded as if
406
+ the module had declared it (`result.simd128` with `undeclared: true`, `result.guestLink.simd128`,
407
+ `metadata.json`), and a warning (`result.warnings`, and the process warning `SDM_SIMD128_UNDECLARED`)
408
+ tells the module to pass `simd128: true`. Undeclared SIMD will become an error in a later release.
409
+ - The use is recorded: `result.simd128` (`requested`, `undeclared`, `declared`, `used`,
410
+ `instructionCount`, ...), `result.guestLink.simd128`, the guest-link bundle metadata and
411
+ `writeGuestLinkFiles`' `metadata.json` (`simd128: true`, only for a module that uses SIMD), and the
412
+ artifact's own `target_features` section. The plugin manifest FlatBuffer has no field for build
413
+ features and is unchanged.
414
+ - Runtimes: every current browser engine and WasmEdge 0.16.4 run fixed-width SIMD, interpreted and
415
+ AOT (`wasmedge compile`); no exception handling is involved.
416
+ - Proof: `node scripts/e2e/simd128-option.mjs` builds one kernel with and without the option on both
417
+ thread models, runs it in headless Chromium and native WasmEdge (and as WasmEdge AOT) with
418
+ byte-identical responses at 1, 2 and 4 threads, and checks the unchanged build is byte-identical.
419
+
388
420
  ## Browser + WasmEdge Isomorphism
389
421
 
390
422
  The supported isomorphic profile and browser edge shims are documented in
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "space-data-module-sdk",
3
- "version": "0.9.13",
3
+ "version": "0.9.15",
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",
@@ -45,8 +45,10 @@ const execFileAsync = promisify(execFile);
45
45
  const require = createRequire(import.meta.url);
46
46
 
47
47
  // Bump when the entry layout or the meaning of a key changes.
48
- export const COMPILE_CACHE_FORMAT = "sdm-compile-cache-v1";
49
- const ENTRY_MAGIC = new TextEncoder().encode("SDMCC1\n");
48
+ export const COMPILE_CACHE_FORMAT = "sdm-compile-cache-v2";
49
+ // v2 (0.9.14): binary keys and a fixed binary entry layout. A v1 entry (0.9.12)
50
+ // has another magic and is a miss.
51
+ const ENTRY_MAGIC = new TextEncoder().encode("SDMCC2\n");
50
52
  const ENTRY_SUFFIX = ".entry";
51
53
  const DISABLED_VALUES = new Set(["0", "off", "false", "no", "disabled"]);
52
54
  const DEFAULT_MAX_BYTES = 4 * 1024 ** 3;
@@ -81,16 +83,60 @@ export function sha256Hex(bytes) {
81
83
  return createHash("sha256").update(bytes).digest("hex");
82
84
  }
83
85
 
84
- // A stable digest of a JSON-able value (object keys sorted).
85
- export function digestOf(value) {
86
- return sha256Hex(stableStringify(value));
86
+ // A stable digest of a value made of null, booleans, numbers, strings, byte
87
+ // arrays, arrays and plain objects. Each field is fed into the sha256 as a type
88
+ // tag and length-prefixed bytes (object keys sorted, undefined members
89
+ // skipped), so distinct values never share an encoding.
90
+ const DIGEST_TAG = Object.freeze({ NULL: 0, FALSE: 1, TRUE: 2, NUMBER: 3, STRING: 4, BYTES: 5, ARRAY: 6, OBJECT: 7 });
91
+ const textEncoder = new TextEncoder();
92
+
93
+ function u32(value) {
94
+ const out = Buffer.alloc(4);
95
+ out.writeUInt32LE(value >>> 0, 0);
96
+ return out;
97
+ }
98
+
99
+ function feedLengthPrefixed(hash, tag, bytes) {
100
+ hash.update(Uint8Array.of(tag));
101
+ hash.update(u32(bytes.length));
102
+ hash.update(bytes);
103
+ }
104
+
105
+ function feedDigestValue(hash, value) {
106
+ if (value === null || value === undefined) {
107
+ hash.update(Uint8Array.of(DIGEST_TAG.NULL));
108
+ } else if (typeof value === "boolean") {
109
+ hash.update(Uint8Array.of(value ? DIGEST_TAG.TRUE : DIGEST_TAG.FALSE));
110
+ } else if (typeof value === "number") {
111
+ const bytes = Buffer.alloc(8);
112
+ bytes.writeDoubleLE(value, 0);
113
+ hash.update(Uint8Array.of(DIGEST_TAG.NUMBER));
114
+ hash.update(bytes);
115
+ } else if (typeof value === "string") {
116
+ feedLengthPrefixed(hash, DIGEST_TAG.STRING, textEncoder.encode(value));
117
+ } else if (value instanceof Uint8Array) {
118
+ feedLengthPrefixed(hash, DIGEST_TAG.BYTES, value);
119
+ } else if (Array.isArray(value)) {
120
+ hash.update(Uint8Array.of(DIGEST_TAG.ARRAY));
121
+ hash.update(u32(value.length));
122
+ for (const item of value) feedDigestValue(hash, item);
123
+ } else if (typeof value === "object") {
124
+ const keys = Object.keys(value).filter((key) => value[key] !== undefined).sort();
125
+ hash.update(Uint8Array.of(DIGEST_TAG.OBJECT));
126
+ hash.update(u32(keys.length));
127
+ for (const key of keys) {
128
+ feedLengthPrefixed(hash, DIGEST_TAG.STRING, textEncoder.encode(key));
129
+ feedDigestValue(hash, value[key]);
130
+ }
131
+ } else {
132
+ throw new TypeError(`digestOf cannot encode a ${typeof value}.`);
133
+ }
87
134
  }
88
135
 
89
- function stableStringify(value) {
90
- if (value === null || typeof value !== "object") return JSON.stringify(value);
91
- if (Array.isArray(value)) return `[${value.map(stableStringify).join(",")}]`;
92
- const keys = Object.keys(value).filter((key) => value[key] !== undefined).sort();
93
- return `{${keys.map((key) => `${JSON.stringify(key)}:${stableStringify(value[key])}`).join(",")}}`;
136
+ export function digestOf(value) {
137
+ const hash = createHash("sha256");
138
+ feedDigestValue(hash, value);
139
+ return hash.digest("hex");
94
140
  }
95
141
 
96
142
  function toBytes(content) {
@@ -110,38 +156,91 @@ export function digestFiles(files) {
110
156
  return hash.digest("hex");
111
157
  }
112
158
 
113
- function encodeEntry(meta, blobs) {
159
+ // One entry, a fixed little-endian layout:
160
+ //
161
+ // magic "SDMCC2\n"
162
+ // key 32 bytes (the sha256 key the entry is stored under)
163
+ // u32 dependency count, then per dependency:
164
+ // u32 path length, path (utf-8), f64 size, f64 mtimeMs, 32-byte sha256
165
+ // u32 blob count, then per blob (sorted by name):
166
+ // u16 name length, name (utf-8), u32 size, 32-byte sha256
167
+ // blob bytes, in the same order
168
+ function encodeEntry(key, blobs, externalDeps = []) {
169
+ const parts = [ENTRY_MAGIC, Buffer.from(key, "hex"), u32(externalDeps.length)];
170
+ for (const dep of externalDeps) {
171
+ const pathBytes = textEncoder.encode(dep.path);
172
+ const stats = Buffer.alloc(16);
173
+ stats.writeDoubleLE(dep.size, 0);
174
+ stats.writeDoubleLE(dep.mtimeMs, 8);
175
+ parts.push(u32(pathBytes.length), pathBytes, stats, Buffer.from(dep.sha256, "hex"));
176
+ }
114
177
  const names = Object.keys(blobs).sort();
115
- const header = {
116
- format: COMPILE_CACHE_FORMAT,
117
- meta,
118
- blobs: names.map((name) => ({ name, size: blobs[name].length, sha256: sha256Hex(blobs[name]) })),
119
- };
120
- const headerBytes = new TextEncoder().encode(JSON.stringify(header));
121
- const lengthBytes = new Uint8Array(4);
122
- new DataView(lengthBytes.buffer).setUint32(0, headerBytes.length, true);
123
- return Buffer.concat([ENTRY_MAGIC, lengthBytes, headerBytes, ...names.map((name) => blobs[name])]);
178
+ parts.push(u32(names.length));
179
+ for (const name of names) {
180
+ const nameBytes = textEncoder.encode(name);
181
+ const nameLength = Buffer.alloc(2);
182
+ nameLength.writeUInt16LE(nameBytes.length, 0);
183
+ parts.push(nameLength, nameBytes, u32(blobs[name].length), Buffer.from(sha256Hex(blobs[name]), "hex"));
184
+ }
185
+ return Buffer.concat([...parts, ...names.map((name) => blobs[name])]);
124
186
  }
125
187
 
126
188
  function decodeEntry(bytes) {
127
- if (bytes.length < ENTRY_MAGIC.length + 4) return null;
189
+ const buffer = Buffer.from(bytes.buffer, bytes.byteOffset, bytes.length);
190
+ let offset = 0;
191
+ const need = (count) => {
192
+ if (offset + count > buffer.length) throw new RangeError("truncated cache entry");
193
+ };
194
+ need(ENTRY_MAGIC.length + 32);
128
195
  for (let index = 0; index < ENTRY_MAGIC.length; index += 1) {
129
- if (bytes[index] !== ENTRY_MAGIC[index]) return null;
196
+ if (buffer[index] !== ENTRY_MAGIC[index]) return null;
197
+ }
198
+ offset = ENTRY_MAGIC.length;
199
+ const key = buffer.subarray(offset, offset + 32).toString("hex");
200
+ offset += 32;
201
+ need(4);
202
+ const depCount = buffer.readUInt32LE(offset);
203
+ offset += 4;
204
+ const externalDeps = [];
205
+ for (let index = 0; index < depCount; index += 1) {
206
+ need(4);
207
+ const pathLength = buffer.readUInt32LE(offset);
208
+ offset += 4;
209
+ need(pathLength + 48);
210
+ const depPath = buffer.subarray(offset, offset + pathLength).toString("utf8");
211
+ offset += pathLength;
212
+ const size = buffer.readDoubleLE(offset);
213
+ const mtimeMs = buffer.readDoubleLE(offset + 8);
214
+ const sha256 = buffer.subarray(offset + 16, offset + 48).toString("hex");
215
+ offset += 48;
216
+ externalDeps.push({ path: depPath, size, mtimeMs, sha256 });
217
+ }
218
+ need(4);
219
+ const blobCount = buffer.readUInt32LE(offset);
220
+ offset += 4;
221
+ const index = [];
222
+ for (let blob = 0; blob < blobCount; blob += 1) {
223
+ need(2);
224
+ const nameLength = buffer.readUInt16LE(offset);
225
+ offset += 2;
226
+ need(nameLength + 36);
227
+ const name = buffer.subarray(offset, offset + nameLength).toString("utf8");
228
+ offset += nameLength;
229
+ const size = buffer.readUInt32LE(offset);
230
+ const sha256 = buffer.subarray(offset + 4, offset + 36).toString("hex");
231
+ offset += 36;
232
+ index.push({ name, size, sha256 });
130
233
  }
131
- const headerLength = new DataView(bytes.buffer, bytes.byteOffset + ENTRY_MAGIC.length, 4).getUint32(0, true);
132
- const headerStart = ENTRY_MAGIC.length + 4;
133
- const header = JSON.parse(new TextDecoder().decode(bytes.subarray(headerStart, headerStart + headerLength)));
134
- if (header?.format !== COMPILE_CACHE_FORMAT || !Array.isArray(header.blobs)) return null;
135
234
  const blobs = {};
136
- let offset = headerStart + headerLength;
137
- for (const { name, size, sha256 } of header.blobs) {
138
- const blob = new Uint8Array(bytes.subarray(offset, offset + size));
139
- if (blob.length !== size || sha256Hex(blob) !== sha256) return null;
235
+ for (const { name, size, sha256 } of index) {
236
+ need(size);
237
+ const blob = new Uint8Array(buffer.subarray(offset, offset + size));
238
+ if (sha256Hex(blob) !== sha256) return null;
140
239
  blobs[name] = blob;
141
240
  offset += size;
142
241
  }
143
- if (offset !== bytes.length) return null;
144
- return { meta: header.meta ?? {}, blobs };
242
+ if (offset !== buffer.length) return null;
243
+ return { key, externalDeps, blobs };
145
244
  }
146
245
 
147
246
  // Header dependencies outside the staged build dir: each is recorded with its
@@ -216,7 +315,7 @@ export class CompileCache {
216
315
  return path.join(this.entriesDir, key.slice(0, 2), `${key}${ENTRY_SUFFIX}`);
217
316
  }
218
317
 
219
- /** The stored entry for `key` ({ meta, blobs }), or null. */
318
+ /** The stored entry for `key` ({ key, externalDeps, blobs }), or null. */
220
319
  async get(key) {
221
320
  const file = this.entryPath(key);
222
321
  let bytes;
@@ -232,7 +331,7 @@ export class CompileCache {
232
331
  } catch {
233
332
  entry = null;
234
333
  }
235
- if (!entry || entry.meta?.key !== key || !(await externalDependenciesUnchanged(entry.meta?.externalDeps))) {
334
+ if (!entry || entry.key !== key || !(await externalDependenciesUnchanged(entry.externalDeps))) {
236
335
  this.stats.misses += 1;
237
336
  return null;
238
337
  }
@@ -243,14 +342,17 @@ export class CompileCache {
243
342
  return entry;
244
343
  }
245
344
 
246
- /** Store `blobs` ({ name: Uint8Array }) under `key`, atomically. */
247
- async put(key, blobs, meta = {}) {
345
+ /**
346
+ * Store `blobs` ({ name: Uint8Array }) under `key`, atomically, with the
347
+ * external header dependencies a lookup re-checks (`{ externalDeps }`).
348
+ */
349
+ async put(key, blobs, { externalDeps = [] } = {}) {
248
350
  const file = this.entryPath(key);
249
351
  const dir = path.dirname(file);
250
352
  try {
251
353
  await mkdir(dir, { recursive: true });
252
354
  const temp = path.join(dir, `.${key}.${process.pid}-${randomBytes(6).toString("hex")}.tmp`);
253
- await writeFile(temp, encodeEntry({ ...meta, key }, blobs));
355
+ await writeFile(temp, encodeEntry(key, blobs, externalDeps));
254
356
  try {
255
357
  await rename(temp, file);
256
358
  } catch (error) {
@@ -339,9 +441,7 @@ let sdkIdentityPromise = null;
339
441
  export function getSdkCompileIdentity() {
340
442
  sdkIdentityPromise ??= (async () => {
341
443
  const compilerDir = path.dirname(fileURLToPath(import.meta.url));
342
- const packageJson = JSON.parse(
343
- await readFile(path.join(compilerDir, "..", "..", "package.json"), "utf8"),
344
- );
444
+ const packageJson = require(path.join(compilerDir, "..", "..", "package.json"));
345
445
  const files = {};
346
446
  for (const name of (await readdir(compilerDir)).filter((entry) => entry.endsWith(".js")).sort()) {
347
447
  files[name] = await readFile(path.join(compilerDir, name));
@@ -385,7 +485,7 @@ const toolchainIdentityCache = new Map();
385
485
  * libraries.
386
486
  */
387
487
  export function getNativeClangIdentity({ drivers, toolchainArgs = [], roots = [] }) {
388
- const cacheKey = JSON.stringify({ drivers, toolchainArgs, roots });
488
+ const cacheKey = ["native-clang", drivers.join("\u0001"), toolchainArgs.join("\u0001"), roots.join("\u0001")].join("\u0000");
389
489
  if (!toolchainIdentityCache.has(cacheKey)) {
390
490
  toolchainIdentityCache.set(cacheKey, (async () => {
391
491
  const driverIds = [];
@@ -436,7 +536,7 @@ async function describeLibraries(root) {
436
536
 
437
537
  /** Identity of a system Emscripten (em++ / emcc on PATH). */
438
538
  export function getSystemEmscriptenIdentity(commands) {
439
- const cacheKey = JSON.stringify({ emscripten: commands });
539
+ const cacheKey = ["system-emscripten", ...commands].join("\u0000");
440
540
  if (!toolchainIdentityCache.has(cacheKey)) {
441
541
  toolchainIdentityCache.set(cacheKey, (async () => {
442
542
  const ids = [];
@@ -463,7 +563,7 @@ export function getEmceptionPackageIdentity(extra = "") {
463
563
  let version = "unknown";
464
564
  for (;;) {
465
565
  try {
466
- const pkg = JSON.parse(await readFile(path.join(packageRoot, "package.json"), "utf8"));
566
+ const pkg = require(path.join(packageRoot, "package.json"));
467
567
  if (pkg?.name === "sdn-emception") {
468
568
  version = String(pkg.version);
469
569
  break;
@@ -48,6 +48,11 @@ import {
48
48
  assertSequentialFlagsAbsent,
49
49
  PTHREAD_FINAL_LINK_FLAGS,
50
50
  } from "./pthreadArtifactGuard.js";
51
+ import {
52
+ SIMD128_COMPILE_FLAG,
53
+ SIMD128_UNDECLARED_WARNING_CODE,
54
+ assertSimdArtifact,
55
+ } from "./simdArtifactGuard.js";
51
56
  import { resolveWasiThreadsToolchain } from "./wasiThreadsToolchain.js";
52
57
  import { encodePluginManifest, toEmbeddedPluginManifest } from "../manifest/index.js";
53
58
  import {
@@ -399,6 +404,35 @@ function buildSourceCompilerArgs(options = {}) {
399
404
  return args;
400
405
  }
401
406
 
407
+ // WebAssembly SIMD is an OPT-IN of the module, never a default: a module that does
408
+ // not ask for it compiles with exactly the flags it always has. It is a flag of the
409
+ // sanctioned clang wasm32-wasip1-threads toolchain, so the legacy single-thread
410
+ // (Emscripten) model refuses it rather than ship a lane no guard or runtime proof
411
+ // covers. See simdArtifactGuard.js for what the emitted artifact is held to.
412
+ function resolveSimd128(value, threadModel) {
413
+ if (value === undefined || value === null || value === false) {
414
+ return false;
415
+ }
416
+ if (value !== true) {
417
+ throw new Error(`simd128 must be true or false, got "${String(value)}".`);
418
+ }
419
+ if (threadModel === ModuleThreadModel.SINGLE_THREAD) {
420
+ throw new Error(
421
+ `simd128 requires threadModel "${ModuleThreadModel.WASI_SEQUENTIAL}" or ` +
422
+ `"${ModuleThreadModel.EMSCRIPTEN_PTHREADS}": SIMD is built by the clang ` +
423
+ `wasm32-wasip1-threads toolchain, not the legacy Emscripten "${ModuleThreadModel.SINGLE_THREAD}" model.`,
424
+ );
425
+ }
426
+ return true;
427
+ }
428
+
429
+ // The flags that apply to the module's OWN code - its source and its `libraries` -
430
+ // and not to the SDK's generated manifest exports and invoke bridge, which are the
431
+ // same objects (and the same compile-cache entries) with or without SIMD.
432
+ function moduleCodeCompilerArgs(options = {}) {
433
+ return options.simd128 === true ? [SIMD128_COMPILE_FLAG] : [];
434
+ }
435
+
402
436
  function normalizeThreadModel(value) {
403
437
  if (value === undefined || value === null || value === "") {
404
438
  return null;
@@ -635,6 +669,7 @@ function createGuestLinkBundleEntries(guestLink) {
635
669
  ...(Array.isArray(guestLink.capabilities)
636
670
  ? { capabilities: [...guestLink.capabilities] }
637
671
  : {}),
672
+ ...(guestLink.simd128 === true ? { simd128: true } : {}),
638
673
  },
639
674
  description: "Guest-link metadata for monolithic flow linking.",
640
675
  },
@@ -762,6 +797,7 @@ function normalizeArgv(argv, workDir) {
762
797
  // that runs them.
763
798
  async function resolveToolchainProfile(kind, { language, sourceCompilerCommand, compileOptions, tempDir }) {
764
799
  const sourceCompilerArgs = buildSourceCompilerArgs(compileOptions);
800
+ const moduleCodeArgs = moduleCodeCompilerArgs(compileOptions);
765
801
  if (kind === "wasi") {
766
802
  const toolchain = resolveWasiThreadsToolchain();
767
803
  const isCpp = String(language ?? "").toLowerCase().startsWith("c++");
@@ -789,6 +825,7 @@ async function resolveToolchainProfile(kind, { language, sourceCompilerCommand,
789
825
  ...(libraryLanguage === "c++" ? ["-std=c++17"] : []),
790
826
  ...extra,
791
827
  ...sourceCompilerArgs,
828
+ ...moduleCodeArgs,
792
829
  "-o",
793
830
  objectPath,
794
831
  ]
@@ -802,6 +839,7 @@ async function resolveToolchainProfile(kind, { language, sourceCompilerCommand,
802
839
  ...(isCpp ? ["-std=c++17"] : []),
803
840
  ...extra,
804
841
  ...sourceCompilerArgs,
842
+ ...moduleCodeArgs,
805
843
  "-o",
806
844
  objectPath,
807
845
  ]
@@ -956,7 +994,7 @@ function normalizeLibraries(libraries) {
956
994
  if (!LIBRARY_NAME.test(name) || !LIBRARY_VERSION.test(version)) {
957
995
  throw new Error(
958
996
  `libraries[${index}] needs a name and a version of letters, digits, '.', '_' or '-' ` +
959
- `(got name ${JSON.stringify(library?.name)}, version ${JSON.stringify(library?.version)}).`,
997
+ `(got name "${String(library?.name)}", version "${String(library?.version)}").`,
960
998
  );
961
999
  }
962
1000
  if (seen.has(name)) {
@@ -969,12 +1007,12 @@ function normalizeLibraries(libraries) {
969
1007
  }
970
1008
  const language = String(library?.language ?? "c").trim().toLowerCase();
971
1009
  if (!["c", "c++", "cpp", "cxx"].includes(language)) {
972
- throw new Error(`libraries[${index}] ("${name}"): language must be "c" or "c++", got ${JSON.stringify(library?.language)}.`);
1010
+ throw new Error(`libraries[${index}] ("${name}"): language must be "c" or "c++", got "${String(library?.language)}".`);
973
1011
  }
974
1012
  const defines = (Array.isArray(library?.defines) ? library.defines : []).map((define) => {
975
1013
  const text = String(define ?? "").trim();
976
1014
  if (!PREPROCESSOR_DEFINE.test(text)) {
977
- throw new Error(`libraries[${index}] ("${name}"): define ${JSON.stringify(define)} is not NAME or NAME=VALUE.`);
1015
+ throw new Error(`libraries[${index}] ("${name}"): define "${String(define)}" is not NAME or NAME=VALUE.`);
978
1016
  }
979
1017
  return text;
980
1018
  });
@@ -1315,10 +1353,12 @@ export async function compileModuleFromSource(options = {}) {
1315
1353
  manifest,
1316
1354
  threadModel: options.threadModel,
1317
1355
  });
1356
+ const simd128 = resolveSimd128(options.simd128, threadModel);
1318
1357
  const compileOptions = {
1319
1358
  ...options,
1320
1359
  noEntry: includeCommandMain !== true,
1321
1360
  threadModel,
1361
+ simd128,
1322
1362
  guestLinkCapabilities: resolveGuestLinkCapabilities(
1323
1363
  manifest,
1324
1364
  options.guestLinkCapabilities,
@@ -1394,6 +1434,30 @@ export async function compileModuleFromSource(options = {}) {
1394
1434
  });
1395
1435
  }
1396
1436
 
1437
+ // The SIMD guard holds the artifact to the build's declaration: never relaxed-SIMD,
1438
+ // every function body decodable, and simd128 in target_features when the module
1439
+ // opted in. SIMD without the opt-in is recorded as if declared, with a warning
1440
+ // (it becomes an error in a later release). See simdArtifactGuard.js.
1441
+ const { warning: simd128Warning, ...simd128Report } = assertSimdArtifact(wasmBytes, {
1442
+ optedIn: simd128,
1443
+ // A path only when the caller asked for one: otherwise the artifact is in a temp dir that is gone.
1444
+ source: options.outputPath != null ? resolvedOutputPath : `the module "${manifest.pluginId ?? "unnamed"}"`,
1445
+ });
1446
+ const buildWarnings = [];
1447
+ if (simd128Warning) {
1448
+ buildWarnings.push(simd128Warning);
1449
+ process.emitWarning(simd128Warning, {
1450
+ type: "DeprecationWarning",
1451
+ code: SIMD128_UNDECLARED_WARNING_CODE,
1452
+ });
1453
+ }
1454
+ // Present only for a module that uses SIMD (declared or not): any other module has
1455
+ // a guest-link record byte-identical to what it always had.
1456
+ const guestLink =
1457
+ result.guestLink && (simd128 || simd128Report.undeclared)
1458
+ ? { ...result.guestLink, simd128: true }
1459
+ : result.guestLink;
1460
+
1397
1461
  // Validate the compiled artifact
1398
1462
  const report = await validateArtifactWithStandards({
1399
1463
  manifest,
@@ -1418,10 +1482,12 @@ export async function compileModuleFromSource(options = {}) {
1418
1482
  options.outputPath != null || keepTempDir ? resolvedOutputPath : null,
1419
1483
  tempDir: keepTempDir ? tempDir : null,
1420
1484
  wasmBytes,
1421
- guestLink: result.guestLink,
1485
+ guestLink,
1422
1486
  compileCache: result.cache,
1423
1487
  manifestWarnings: warnings,
1488
+ warnings: buildWarnings,
1424
1489
  threadFeatures,
1490
+ simd128: simd128Report,
1425
1491
  report,
1426
1492
  };
1427
1493
  } finally {
@@ -2,7 +2,8 @@
2
2
  //
3
3
  // <dir>/module-link.o the prefixed guest-link object
4
4
  // <dir>/metadata.json format, language, threadModel, symbolPrefix, methodSymbols
5
- // (+ libraries, below)
5
+ // (+ libraries, below; + simd128: true when the module
6
+ // opted in to WebAssembly SIMD)
6
7
  // <dir>/libraries/<name>-<version>-<sha12>.o
7
8
  // each shared library object the module links
8
9
  // (compile option `libraries`), listed in
@@ -16,6 +17,15 @@
16
17
  import path from "node:path";
17
18
  import { mkdir, rm, writeFile } from "node:fs/promises";
18
19
 
20
+ import { canonicalBytes } from "../auth/canonicalize.js";
21
+
22
+ function concatNewline(bytes) {
23
+ const out = new Uint8Array(bytes.length + 1);
24
+ out.set(bytes, 0);
25
+ out[bytes.length] = 0x0a;
26
+ return out;
27
+ }
28
+
19
29
  /**
20
30
  * Write a compilation's guest-link object, its library objects and
21
31
  * metadata.json into `dir` (usually `<package>/dist/guest-link`). `metadata`
@@ -53,8 +63,11 @@ export async function writeGuestLinkFiles(compilation, dir, metadata = {}) {
53
63
  symbolPrefix: guestLink.symbolPrefix,
54
64
  methodSymbols: guestLink.methodSymbols,
55
65
  ...(libraryEntries.length > 0 ? { libraries: libraryEntries } : {}),
66
+ ...(guestLink.simd128 === true ? { simd128: true } : {}),
56
67
  ...metadata,
57
68
  };
58
- await writeFile(path.join(dir, "metadata.json"), `${JSON.stringify(written, null, 2)}\n`);
69
+ // The SDK's one canonical writer of this metadata (the guest-link bundle entry
70
+ // encodes the same object the same way): sorted keys, no whitespace.
71
+ await writeFile(path.join(dir, "metadata.json"), concatNewline(canonicalBytes(written)));
59
72
  return written;
60
73
  }
@@ -6,6 +6,7 @@ export type {
6
6
  ModuleLibrarySource,
7
7
  ModuleThreadModelName,
8
8
  ProtectedArtifact,
9
+ Simd128Report,
9
10
  } from "../index.js";
10
11
 
11
12
  export {
@@ -35,3 +36,81 @@ export {
35
36
  loadSharedEmception,
36
37
  withSharedEmception,
37
38
  } from "./emception.js";
39
+
40
+ // --- Artifact guards (src/compiler/pthreadArtifactGuard.js, simdArtifactGuard.js) ---
41
+
42
+ type WasmBytes = Uint8Array | ArrayBuffer | ArrayBufferView;
43
+
44
+ /** One memory of a wasm module, imported or declared. */
45
+ export interface WasmMemoryLimits {
46
+ source: "import" | "declared";
47
+ /** Present for an imported memory. */
48
+ module?: string;
49
+ name?: string;
50
+ flags: number;
51
+ min: number;
52
+ max: number | null;
53
+ shared: boolean;
54
+ growable: boolean;
55
+ }
56
+
57
+ /** What analyzeWasmThreadFeatures reads off a compiled artifact. */
58
+ export interface WasmThreadFeatures {
59
+ hasSharedMemory: boolean;
60
+ sharedMemory: WasmMemoryLimits | null;
61
+ memories: WasmMemoryLimits[];
62
+ usesAtomics: boolean;
63
+ atomicInstructionCount: number;
64
+ /** The names in the target_features section; null when the module has none. */
65
+ declaredFeatures: string[] | null;
66
+ isGrowableSharedMemory: boolean;
67
+ hasWasiThreadSpawnImport: boolean;
68
+ hasWasiThreadStartExport: boolean;
69
+ emscriptenThreadHooks: string[];
70
+ isIsomorphicPthreads: boolean;
71
+ }
72
+
73
+ export function analyzeWasmThreadFeatures(wasmBytes: WasmBytes): WasmThreadFeatures;
74
+ /** Throws unless the artifact is a real wasi-threads shared-memory/atomics module. */
75
+ export function assertPthreadArtifact(wasmBytes: WasmBytes, options?: { source?: string }): WasmThreadFeatures;
76
+ /** Throws unless the artifact is a self-contained wasi-sequential module built for the sanctioned target. */
77
+ export function assertSequentialArtifact(
78
+ wasmBytes: WasmBytes,
79
+ options?: { source?: string; target?: string },
80
+ ): WasmThreadFeatures;
81
+ /** Throws when an assembled emscripten-pthreads final-link argument list lost a mandated flag. */
82
+ export function assertPthreadFlagsPresent(args: string[], context?: { threadModel?: string }): void;
83
+ /** Throws when an assembled wasi-sequential final-link argument list carries a thread-memory flag. */
84
+ export function assertSequentialFlagsAbsent(args: string[], context?: { threadModel?: string }): string[];
85
+ export const PTHREAD_FINAL_LINK_FLAGS: readonly string[];
86
+ export const SANCTIONED_WASI_TARGET: "wasm32-wasip1-threads";
87
+
88
+ /** What analyzeWasmSimdFeatures reads off a compiled artifact. */
89
+ export interface WasmSimdFeatures {
90
+ /** target_features lists simd128 as used; null when the module has no target_features section. */
91
+ declared: boolean | null;
92
+ /** target_features lists relaxed-simd as used; null when the module has no target_features section. */
93
+ declaredRelaxed: boolean | null;
94
+ /** The code section holds fixed-width SIMD instructions. */
95
+ used: boolean;
96
+ instructionCount: number;
97
+ /** SIMD instructions beyond the fixed-width set (relaxed-simd and later proposals). */
98
+ relaxedInstructionCount: number;
99
+ /** Function bodies the scanner could not decode; their instructions are not counted. */
100
+ undecodableFunctions: number;
101
+ }
102
+
103
+ export function analyzeWasmSimdFeatures(wasmBytes: WasmBytes): WasmSimdFeatures;
104
+ /**
105
+ * Hold an artifact's SIMD use to the build's declaration. Throws on relaxed-SIMD, on a function body
106
+ * the scanner cannot decode, and on an opted-in build whose artifact does not declare simd128. SIMD
107
+ * without the opt-in is returned as `undeclared` with a `warning`, not thrown (an error in a later release).
108
+ */
109
+ export function assertSimdArtifact(
110
+ wasmBytes: WasmBytes,
111
+ options?: { optedIn?: boolean; source?: string },
112
+ ): WasmSimdFeatures & { requested: boolean; undeclared: boolean; warning?: string };
113
+ /** The clang flag the `simd128` compile option adds to a module's own code. */
114
+ export const SIMD128_COMPILE_FLAG: "-msimd128";
115
+ /** The process warning code emitted for an artifact that carries SIMD its build did not declare. */
116
+ export const SIMD128_UNDECLARED_WARNING_CODE: "SDM_SIMD128_UNDECLARED";
@@ -17,6 +17,13 @@ export {
17
17
  PTHREAD_FINAL_LINK_FLAGS,
18
18
  } from "./pthreadArtifactGuard.js";
19
19
 
20
+ export {
21
+ analyzeWasmSimdFeatures,
22
+ assertSimdArtifact,
23
+ SIMD128_COMPILE_FLAG,
24
+ SIMD128_UNDECLARED_WARNING_CODE,
25
+ } from "./simdArtifactGuard.js";
26
+
20
27
  export { resolveWasiThreadsToolchain } from "./wasiThreadsToolchain.js";
21
28
  export { writeGuestLinkFiles } from "./guestLinkFiles.js";
22
29