space-data-module-sdk 0.9.9 → 0.9.12

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (68) hide show
  1. package/docs/_shell/consumer-assets.html +3 -3
  2. package/docs/assets/vendor/hd-wallet-ui/2.2.1/sdn-wallet-callback.0f2dee485c8f0d7afe5f70b4b42093a382c92d32af551bd71b41733336091c7a.js +1 -0
  3. package/docs/assets/vendor/hd-wallet-ui/2.2.1/sdn-wallet-public-client.9ab041131df957fcb6ef7e3d87bf9d19fe313bc5d7f1e53337752faf0ba354da.js +1 -0
  4. package/docs/assets/vendor/hd-wallet-ui/2.2.1/sdn-wallet-public-client.c3f68d1cfd88478f10d836a5e829d1dfc6a10157972cf0f7d4d319d0636f2cc4.css +32 -0
  5. package/docs/assets/vendor/sdn-stack-nav/1.0.1/sdn-stack-nav.24eb3001afc5448a90cef87e53bb4e599c0ae4dc9e14bafb6d1236e0233c6008.js +283 -0
  6. package/docs/assets/vendor/sdn-stack-nav/1.0.1/sdn-stack-nav.36a36359ce18322185e9ff179f88175bab67d5ad84a14d9c08a54f2ff27267e7.css +118 -0
  7. package/docs/browser-wasmedge-isomorphic.html +3 -3
  8. package/docs/byo-wasm-quickstart.html +3 -3
  9. package/docs/conformance.html +3 -3
  10. package/docs/events-abi.html +3 -3
  11. package/docs/families/analytics.html +3 -3
  12. package/docs/families/attitude.html +3 -3
  13. package/docs/families/behavior.html +3 -3
  14. package/docs/families/breakup.html +3 -3
  15. package/docs/families/conjunction.html +3 -3
  16. package/docs/families/data-source.html +3 -3
  17. package/docs/families/effects.html +3 -3
  18. package/docs/families/environment.html +3 -3
  19. package/docs/families/estimation.html +3 -3
  20. package/docs/families/gnc.html +3 -3
  21. package/docs/families/maneuver.html +3 -3
  22. package/docs/families/obstruction.html +3 -3
  23. package/docs/families/propagator.html +3 -3
  24. package/docs/families/propulsion.html +3 -3
  25. package/docs/families/reentry.html +3 -3
  26. package/docs/families/rf.html +3 -3
  27. package/docs/families/scheduler.html +3 -3
  28. package/docs/families/sensor.html +3 -3
  29. package/docs/families/signature.html +3 -3
  30. package/docs/flatsql-host-contract.html +3 -3
  31. package/docs/flatsql-streaming-standard.html +3 -3
  32. package/docs/gpu-module-abi.html +3 -3
  33. package/docs/index.html +3 -3
  34. package/docs/isomorphic-pthreads.html +3 -3
  35. package/docs/isomorphic-sdn-runtime-plan.html +3 -3
  36. package/docs/language-runtime-matrix.html +3 -3
  37. package/docs/module-bundle-runtime-plan.html +3 -3
  38. package/docs/module-publication-standard.html +3 -3
  39. package/docs/node-red-default-node-parity.html +3 -3
  40. package/docs/protect-and-sign.html +3 -3
  41. package/docs/protocol-installation.html +3 -3
  42. package/docs/publication-submission.html +3 -3
  43. package/docs/secrets-capability.html +3 -3
  44. package/docs/testing-harness.html +3 -3
  45. package/docs/tri-runtime-parity-gate.html +3 -3
  46. package/docs/tri-runtime-parity.html +3 -3
  47. package/docs/wallet-callback.html +1 -1
  48. package/package.json +1 -1
  49. package/src/compiler/compileCache.js +495 -0
  50. package/src/compiler/compileModule.js +537 -509
  51. package/src/compiler/emceptionNode.js +127 -1
  52. package/src/compiler/guestLinkFiles.js +60 -0
  53. package/src/compiler/index.d.ts +7 -0
  54. package/src/compiler/index.js +7 -0
  55. package/src/compiler/wasmObjectSymbols.js +369 -0
  56. package/src/flow/flowCompiler.js +124 -4
  57. package/src/flow/flowRuntimeHost.js +2 -2
  58. package/src/host/abi.js +2 -3
  59. package/src/host/hostWorkerBundleSources.js +3 -3
  60. package/src/host/hostcallWire.js +3 -2
  61. package/src/host/providerAccess.js +2 -3
  62. package/src/host/typedDispatch.js +2 -2
  63. package/src/host/wasiShim.js +5 -1
  64. package/src/index.d.ts +93 -0
  65. package/src/runtime-host/flatsqlRuntimeStore.js +2 -2
  66. package/src/testing/isomorphicHarness.js +15 -1
  67. package/src/testing/parityGate.js +14 -9
  68. package/src/utils/guestText.js +12 -0
@@ -27,7 +27,20 @@ import {
27
27
  getFlatbuffersCppRuntimeHeaders,
28
28
  getInvokeCppSchemaHeaders,
29
29
  } from "./flatcSupport.js";
30
- import { runWithEmceptionLock } from "./emceptionNode.js";
30
+ import { getEmceptionCompileIdentity, runWithEmceptionLock } from "./emceptionNode.js";
31
+ import {
32
+ COMPILE_CACHE_FORMAT,
33
+ describeExternalDependencies,
34
+ digestFiles,
35
+ digestOf,
36
+ getNativeClangIdentity,
37
+ getSdkCompileIdentity,
38
+ getSystemEmscriptenIdentity,
39
+ openCompileCache,
40
+ parseDepfile,
41
+ sha256Hex,
42
+ } from "./compileCache.js";
43
+ import { listWasmObjectSymbols, renameWasmObjectSymbols } from "./wasmObjectSymbols.js";
31
44
  import {
32
45
  assertPthreadArtifact,
33
46
  assertPthreadFlagsPresent,
@@ -59,11 +72,7 @@ import {
59
72
  SDS_GUEST_LINK_SECTION_NAME,
60
73
  SDS_MANIFEST_SECTION_NAME,
61
74
  } from "../bundle/constants.js";
62
- import {
63
- appendWasmCustomSection,
64
- decodeUnsignedLeb128,
65
- parseWasmModuleSections,
66
- } from "../bundle/wasm.js";
75
+ import { appendWasmCustomSection } from "../bundle/wasm.js";
67
76
  import {
68
77
  base64ToBytes,
69
78
  bytesToBase64,
@@ -543,118 +552,29 @@ function parseStrongDefinedIdentifiers(nmOutput = "") {
543
552
  return Array.from(identifiers).sort();
544
553
  }
545
554
 
546
- const WASM_SYM_BINDING_WEAK = 0x01;
547
- const WASM_SYM_BINDING_LOCAL = 0x02;
548
- const WASM_SYM_UNDEFINED = 0x10;
549
- const WASM_SYM_EXPLICIT_NAME = 0x40;
550
- const WASM_SYMBOL_KIND_FUNCTION = 0;
551
- const WASM_SYMBOL_KIND_DATA = 1;
552
- const WASM_SYMBOL_KIND_GLOBAL = 2;
553
- const WASM_SYMBOL_KIND_SECTION = 3;
554
- const WASM_SYMBOL_KIND_EVENT = 4;
555
- const WASM_SYMBOL_KIND_TABLE = 5;
556
- const LINKING_SYMBOL_TABLE_SUBSECTION_ID = 8;
557
- const textDecoder = new TextDecoder();
558
-
559
- function decodeWasmName(bytes, offset) {
560
- const lengthInfo = decodeUnsignedLeb128(bytes, offset);
561
- const nameStart = lengthInfo.nextOffset;
562
- const nameEnd = nameStart + lengthInfo.value;
563
- if (nameEnd > bytes.length) {
564
- throw new Error("WASM name extends past end of symbol payload.");
565
- }
566
- return {
567
- value: textDecoder.decode(bytes.subarray(nameStart, nameEnd)),
568
- nextOffset: nameEnd,
569
- };
570
- }
571
-
572
- function parseDefinedLinkSymbolsFromObjectBytes(objectBytes) {
573
- const parsed = parseWasmModuleSections(objectBytes);
574
- const linkingSection = parsed.sections.find(
575
- (section) => section.id === 0 && section.name === "linking",
576
- );
577
- if (!linkingSection) {
578
- throw new Error("Guest-link object is missing a linking custom section.");
579
- }
580
- const payload = linkingSection.dataBytes;
581
- let offset = decodeUnsignedLeb128(payload, 0).nextOffset;
555
+ // The guest-link symbol set: every strong, global symbol module.o DEFINES with
556
+ // a C identifier for a name, plus the manifest's method ids. The guest-link
557
+ // object is module.o with each of those renamed to `<prefix><name>`. Until
558
+ // 0.9.11 that object came from a second compile of the source with one
559
+ // `-D<name>=<prefix><name>` per symbol; it is now the one module.o, renamed in
560
+ // its symbol table (src/compiler/wasmObjectSymbols.js), which is what the
561
+ // macros achieved without the second compile.
562
+ function definedGuestLinkIdentifiers(objectBytes) {
582
563
  const identifiers = new Set();
583
- while (offset < payload.length) {
584
- const subsectionId = payload[offset++];
585
- const sizeInfo = decodeUnsignedLeb128(payload, offset);
586
- offset = sizeInfo.nextOffset;
587
- const subsectionEnd = offset + sizeInfo.value;
588
- if (subsectionEnd > payload.length) {
589
- throw new Error("Linking subsection extends past end of payload.");
590
- }
591
- if (subsectionId !== LINKING_SYMBOL_TABLE_SUBSECTION_ID) {
592
- offset = subsectionEnd;
593
- continue;
594
- }
595
- let cursor = offset;
596
- const countInfo = decodeUnsignedLeb128(payload, cursor);
597
- cursor = countInfo.nextOffset;
598
- for (let symbolIndex = 0; symbolIndex < countInfo.value; symbolIndex += 1) {
599
- const kind = payload[cursor++];
600
- const flagsInfo = decodeUnsignedLeb128(payload, cursor);
601
- const flags = flagsInfo.value;
602
- cursor = flagsInfo.nextOffset;
603
- let name = "";
604
- if (
605
- kind === WASM_SYMBOL_KIND_FUNCTION ||
606
- kind === WASM_SYMBOL_KIND_GLOBAL ||
607
- kind === WASM_SYMBOL_KIND_EVENT ||
608
- kind === WASM_SYMBOL_KIND_TABLE
609
- ) {
610
- cursor = decodeUnsignedLeb128(payload, cursor).nextOffset;
611
- if (
612
- (flags & WASM_SYM_UNDEFINED) === 0 ||
613
- (flags & WASM_SYM_EXPLICIT_NAME) !== 0
614
- ) {
615
- const nameInfo = decodeWasmName(payload, cursor);
616
- name = nameInfo.value;
617
- cursor = nameInfo.nextOffset;
618
- }
619
- } else if (kind === WASM_SYMBOL_KIND_DATA) {
620
- const nameInfo = decodeWasmName(payload, cursor);
621
- name = nameInfo.value;
622
- cursor = nameInfo.nextOffset;
623
- if ((flags & WASM_SYM_UNDEFINED) === 0) {
624
- cursor = decodeUnsignedLeb128(payload, cursor).nextOffset;
625
- cursor = decodeUnsignedLeb128(payload, cursor).nextOffset;
626
- cursor = decodeUnsignedLeb128(payload, cursor).nextOffset;
627
- }
628
- } else if (kind === WASM_SYMBOL_KIND_SECTION) {
629
- cursor = decodeUnsignedLeb128(payload, cursor).nextOffset;
630
- } else {
631
- throw new Error(`Unsupported WASM linking symbol kind: ${kind}`);
632
- }
633
- if ((flags & WASM_SYM_UNDEFINED) !== 0) {
634
- continue;
635
- }
636
- if ((flags & WASM_SYM_BINDING_LOCAL) !== 0) {
637
- continue;
638
- }
639
- if ((flags & WASM_SYM_BINDING_WEAK) !== 0) {
640
- continue;
641
- }
642
- if (!C_IDENTIFIER.test(name)) {
643
- continue;
644
- }
645
- identifiers.add(name);
646
- }
647
- return Array.from(identifiers).sort();
564
+ for (const symbol of listWasmObjectSymbols(objectBytes)) {
565
+ if (!symbol.defined || symbol.local || symbol.weak) continue;
566
+ if (!C_IDENTIFIER.test(symbol.name)) continue;
567
+ identifiers.add(symbol.name);
648
568
  }
649
- throw new Error("Guest-link object is missing a symbol table subsection.");
569
+ return Array.from(identifiers).sort();
650
570
  }
651
571
 
652
- function deriveGuestLinkRenameArgs({
572
+ function deriveGuestLinkRenames({
653
573
  objectBytes,
654
574
  pluginId,
655
575
  methodIds = [],
656
576
  } = {}) {
657
- const identifiers = parseDefinedLinkSymbolsFromObjectBytes(objectBytes);
577
+ const identifiers = definedGuestLinkIdentifiers(objectBytes);
658
578
  const prefix = guestLinkSymbolPrefix(pluginId);
659
579
  const renamedIdentifiers = Array.from(
660
580
  new Set([...identifiers, ...methodIds.filter((value) => C_IDENTIFIER.test(value))]),
@@ -662,15 +582,28 @@ function deriveGuestLinkRenameArgs({
662
582
  return {
663
583
  prefix,
664
584
  identifiers: renamedIdentifiers,
665
- renameArgs: renamedIdentifiers.map(
666
- (identifier) => `-D${identifier}=${prefix}${identifier}`,
667
- ),
585
+ renames: new Map(renamedIdentifiers.map((identifier) => [identifier, `${prefix}${identifier}`])),
668
586
  methodSymbols: Object.fromEntries(
669
587
  methodIds.map((methodId) => [methodId, `${prefix}${methodId}`]),
670
588
  ),
671
589
  };
672
590
  }
673
591
 
592
+ /**
593
+ * The guest-link object of a compiled module object: its guest-link symbols
594
+ * renamed under the plugin's prefix. Exported for tooling that holds a
595
+ * module.o; compileModuleFromSource does this itself.
596
+ */
597
+ export function deriveGuestLinkObject({ objectBytes, pluginId, methodIds = [] } = {}) {
598
+ const guestLink = deriveGuestLinkRenames({ objectBytes, pluginId, methodIds });
599
+ return {
600
+ symbolPrefix: guestLink.prefix,
601
+ methodSymbols: guestLink.methodSymbols,
602
+ renamedSymbols: guestLink.identifiers,
603
+ objectBytes: renameWasmObjectSymbols(objectBytes, guestLink.renames),
604
+ };
605
+ }
606
+
674
607
  function createGuestLinkBundleEntries(guestLink) {
675
608
  if (!guestLink?.objectBytes || guestLink.objectBytes.length === 0) {
676
609
  return [];
@@ -733,22 +666,6 @@ async function getInvokeCppSupportFiles() {
733
666
  return { runtimeHeaders, schemaHeaders: { ...schemaHeaders, ...hostcallHeaders } };
734
667
  }
735
668
 
736
- async function writeFilesToEmception(emception, rootDir, files) {
737
- for (const [relativePath, content] of Object.entries(files)) {
738
- const filePath = path.posix.join(rootDir, relativePath);
739
- emception.FS.mkdirTree(path.posix.dirname(filePath));
740
- emception.writeFile(filePath, content);
741
- }
742
- }
743
-
744
- async function writeFilesToDirectory(rootDir, files) {
745
- for (const [relativePath, content] of Object.entries(files)) {
746
- const filePath = path.join(rootDir, relativePath);
747
- await mkdir(path.dirname(filePath), { recursive: true });
748
- await writeFile(filePath, content);
749
- }
750
- }
751
-
752
669
  function removeEmceptionDirectory(emception, directoryPath) {
753
670
  if (!emception.FS.analyzePath(directoryPath).exists) {
754
671
  return;
@@ -769,173 +686,6 @@ function removeEmceptionDirectory(emception, directoryPath) {
769
686
  emception.FS.rmdir(directoryPath);
770
687
  }
771
688
 
772
- async function compileWithEmception(options = {}) {
773
- const {
774
- manifest,
775
- language,
776
- sourceCompilerCommand,
777
- sourceExtension,
778
- sourceCode,
779
- manifestSource,
780
- invokeHeaderSource,
781
- invokeSource,
782
- exportedSymbols,
783
- outputPath,
784
- tempDir,
785
- compileOptions,
786
- } = options;
787
- const resolvedOutputPath = path.resolve(
788
- outputPath ?? path.join(tempDir, "module.wasm"),
789
- );
790
-
791
- return runWithEmceptionLock(async (emception) => {
792
- const workDir = "/working/space-data-module-sdk-compile";
793
- const runtimeIncludeDir = path.posix.join(workDir, "flatbuffers-runtime");
794
- const sourcePath = path.posix.join(workDir, `module.${sourceExtension}`);
795
- const manifestSourcePath = path.posix.join(workDir, "plugin-manifest-exports.cpp");
796
- const invokeHeaderPath = path.posix.join(workDir, "space_data_module_invoke.h");
797
- const invokeSourcePath = path.posix.join(workDir, "plugin-invoke-bridge.cpp");
798
- const sourceObjectPath = path.posix.join(workDir, "module.o");
799
- const linkObjectPath = path.posix.join(workDir, "module-link.o");
800
- const manifestObjectPath = path.posix.join(workDir, "plugin-manifest-exports.o");
801
- const invokeObjectPath = path.posix.join(workDir, "plugin-invoke-bridge.o");
802
- const wasmOutputPath = path.posix.join(workDir, "module.wasm");
803
-
804
- const { runtimeHeaders, schemaHeaders } = await getInvokeCppSupportFiles();
805
- const args = buildCompilerArgs(exportedSymbols, compileOptions);
806
-
807
- try {
808
- emception.FS.mkdirTree(workDir);
809
- await writeFilesToEmception(emception, runtimeIncludeDir, runtimeHeaders);
810
- await writeFilesToEmception(emception, workDir, schemaHeaders);
811
- emception.writeFile(sourcePath, sourceCode);
812
- emception.writeFile(manifestSourcePath, manifestSource);
813
- emception.writeFile(invokeHeaderPath, invokeHeaderSource);
814
- emception.writeFile(invokeSourcePath, invokeSource);
815
-
816
- const commands = [
817
- [
818
- sourceCompilerCommand,
819
- "-c",
820
- sourcePath,
821
- `-I${workDir}`,
822
- `-I${runtimeIncludeDir}`,
823
- ...buildSourceCompilerArgs(compileOptions),
824
- "-o",
825
- sourceObjectPath,
826
- ],
827
- ];
828
-
829
- for (const command of commands) {
830
- const result = emception.run(command.join(" "));
831
- if (result.returncode !== 0) {
832
- throw new Error(
833
- `Compilation failed with ${command[0]} (emception): ${result.stderr || result.stdout}`,
834
- );
835
- }
836
- }
837
-
838
- const sourceObjectBytes = new Uint8Array(emception.readFile(sourceObjectPath));
839
- const guestLink = deriveGuestLinkRenameArgs({
840
- objectBytes: sourceObjectBytes,
841
- pluginId: manifest?.pluginId,
842
- methodIds: Array.isArray(manifest?.methods)
843
- ? manifest.methods.map((method) => String(method?.methodId ?? ""))
844
- : [],
845
- });
846
-
847
- const linkCompileCommand = [
848
- sourceCompilerCommand,
849
- "-c",
850
- sourcePath,
851
- `-I${workDir}`,
852
- `-I${runtimeIncludeDir}`,
853
- ...guestLink.renameArgs,
854
- ...buildSourceCompilerArgs(compileOptions),
855
- "-o",
856
- linkObjectPath,
857
- ];
858
- const linkCompileResult = emception.run(linkCompileCommand.join(" "));
859
- if (linkCompileResult.returncode !== 0) {
860
- throw new Error(
861
- `Compilation failed with ${linkCompileCommand[0]} (emception): ${linkCompileResult.stderr || linkCompileResult.stdout}`,
862
- );
863
- }
864
-
865
- // The embedded manifest and the invoke bridge get the module source's
866
- // own optimization flags. Without them both objects built at -O0 and
867
- // every payload byte crossing the bridge (the std::vector copies of
868
- // each request and response) cost hundreds of interpreted wasm
869
- // instructions. The wasi path already compiles them this way.
870
- const remainingCommands = [
871
- [
872
- "em++",
873
- "-c",
874
- manifestSourcePath,
875
- "-std=c++17",
876
- `-I${workDir}`,
877
- `-I${runtimeIncludeDir}`,
878
- ...buildSourceCompilerArgs(compileOptions),
879
- "-o",
880
- manifestObjectPath,
881
- ],
882
- [
883
- "em++",
884
- "-c",
885
- invokeSourcePath,
886
- "-std=c++17",
887
- `-I${workDir}`,
888
- `-I${runtimeIncludeDir}`,
889
- ...buildSourceCompilerArgs(compileOptions),
890
- "-o",
891
- invokeObjectPath,
892
- ],
893
- [
894
- "em++",
895
- sourceObjectPath,
896
- manifestObjectPath,
897
- invokeObjectPath,
898
- ...args,
899
- "-o",
900
- wasmOutputPath,
901
- ],
902
- ];
903
- for (const command of remainingCommands) {
904
- const result = emception.run(command.join(" "));
905
- if (result.returncode !== 0) {
906
- throw new Error(
907
- `Compilation failed with ${command[0]} (emception): ${result.stderr || result.stdout}`,
908
- );
909
- }
910
- }
911
-
912
- const wasmBytes = new Uint8Array(emception.readFile(wasmOutputPath));
913
- const linkObjectBytes = new Uint8Array(emception.readFile(linkObjectPath));
914
- await writeFile(resolvedOutputPath, wasmBytes);
915
- return {
916
- wasmBytes,
917
- outputPath: resolvedOutputPath,
918
- guestLink: {
919
- format: "wasm-object",
920
- language,
921
- symbolPrefix: guestLink.prefix,
922
- methodSymbols: guestLink.methodSymbols,
923
- threadModel:
924
- compileOptions.threadModel ?? ModuleThreadModel.SINGLE_THREAD,
925
- capabilities: compileOptions.guestLinkCapabilities,
926
- objectBytes: linkObjectBytes,
927
- },
928
- };
929
- } finally {
930
- try {
931
- removeEmceptionDirectory(emception, workDir);
932
- } catch {
933
- // Best-effort cleanup only; the shared emception instance remains usable.
934
- }
935
- }
936
- });
937
- }
938
-
939
689
  async function ensureSystemCompilerAvailable(command) {
940
690
  try {
941
691
  await execFileAsync(command, ["--version"]);
@@ -965,126 +715,6 @@ async function runSystemCompiler(command, args, options = {}) {
965
715
  }
966
716
  }
967
717
 
968
- async function compileWithSystemEmscripten(options = {}) {
969
- const {
970
- manifest,
971
- language,
972
- sourceCompilerCommand,
973
- sourceExtension,
974
- sourceCode,
975
- manifestSource,
976
- invokeHeaderSource,
977
- invokeSource,
978
- exportedSymbols,
979
- outputPath,
980
- tempDir,
981
- compileOptions,
982
- } = options;
983
- const resolvedOutputPath = path.resolve(
984
- outputPath ?? path.join(tempDir, "module.wasm"),
985
- );
986
- const runtimeIncludeDir = path.join(tempDir, "flatbuffers-runtime");
987
- const sourcePath = path.join(tempDir, `module.${sourceExtension}`);
988
- const manifestSourcePath = path.join(tempDir, "plugin-manifest-exports.cpp");
989
- const invokeHeaderPath = path.join(tempDir, "space_data_module_invoke.h");
990
- const invokeSourcePath = path.join(tempDir, "plugin-invoke-bridge.cpp");
991
- const sourceObjectPath = path.join(tempDir, "module.o");
992
- const linkObjectPath = path.join(tempDir, "module-link.o");
993
- const manifestObjectPath = path.join(tempDir, "plugin-manifest-exports.o");
994
- const invokeObjectPath = path.join(tempDir, "plugin-invoke-bridge.o");
995
- const wasmOutputPath = path.join(tempDir, "module.wasm");
996
-
997
- await ensureSystemCompilerAvailable(sourceCompilerCommand);
998
- await ensureSystemCompilerAvailable("em++");
999
- const { runtimeHeaders, schemaHeaders } = await getInvokeCppSupportFiles();
1000
- const args = buildCompilerArgs(exportedSymbols, compileOptions);
1001
- await writeFilesToDirectory(runtimeIncludeDir, runtimeHeaders);
1002
- await writeFilesToDirectory(tempDir, schemaHeaders);
1003
- await writeFile(sourcePath, sourceCode);
1004
- await writeFile(manifestSourcePath, manifestSource);
1005
- await writeFile(invokeHeaderPath, invokeHeaderSource);
1006
- await writeFile(invokeSourcePath, invokeSource);
1007
-
1008
- const sourceCompileArgs = [
1009
- "-c",
1010
- sourcePath,
1011
- `-I${tempDir}`,
1012
- `-I${runtimeIncludeDir}`,
1013
- ...buildSourceCompilerArgs(compileOptions),
1014
- "-o",
1015
- sourceObjectPath,
1016
- ];
1017
- await runSystemCompiler(sourceCompilerCommand, sourceCompileArgs);
1018
-
1019
- const sourceObjectBytes = new Uint8Array(await readFile(sourceObjectPath));
1020
- const guestLink = deriveGuestLinkRenameArgs({
1021
- objectBytes: sourceObjectBytes,
1022
- pluginId: manifest?.pluginId,
1023
- methodIds: Array.isArray(manifest?.methods)
1024
- ? manifest.methods.map((method) => String(method?.methodId ?? ""))
1025
- : [],
1026
- });
1027
-
1028
- const linkCompileArgs = [
1029
- "-c",
1030
- sourcePath,
1031
- `-I${tempDir}`,
1032
- `-I${runtimeIncludeDir}`,
1033
- ...guestLink.renameArgs,
1034
- ...buildSourceCompilerArgs(compileOptions),
1035
- "-o",
1036
- linkObjectPath,
1037
- ];
1038
- await runSystemCompiler(sourceCompilerCommand, linkCompileArgs);
1039
- // Same optimization flags as the module source (see compileWithEmception).
1040
- // buildSourceCompilerArgs carries -pthread whenever usesPthreadCompileFlags.
1041
- await runSystemCompiler("em++", [
1042
- "-c",
1043
- manifestSourcePath,
1044
- "-std=c++17",
1045
- `-I${tempDir}`,
1046
- `-I${runtimeIncludeDir}`,
1047
- ...buildSourceCompilerArgs(compileOptions),
1048
- "-o",
1049
- manifestObjectPath,
1050
- ]);
1051
- await runSystemCompiler("em++", [
1052
- "-c",
1053
- invokeSourcePath,
1054
- "-std=c++17",
1055
- `-I${tempDir}`,
1056
- `-I${runtimeIncludeDir}`,
1057
- ...buildSourceCompilerArgs(compileOptions),
1058
- "-o",
1059
- invokeObjectPath,
1060
- ]);
1061
- await runSystemCompiler("em++", [
1062
- sourceObjectPath,
1063
- manifestObjectPath,
1064
- invokeObjectPath,
1065
- ...args,
1066
- "-o",
1067
- wasmOutputPath,
1068
- ]);
1069
-
1070
- const wasmBytes = new Uint8Array(await readFile(wasmOutputPath));
1071
- const linkObjectBytes = new Uint8Array(await readFile(linkObjectPath));
1072
- await writeFile(resolvedOutputPath, wasmBytes);
1073
- return {
1074
- wasmBytes,
1075
- outputPath: resolvedOutputPath,
1076
- guestLink: {
1077
- format: "wasm-object",
1078
- language,
1079
- symbolPrefix: guestLink.prefix,
1080
- methodSymbols: guestLink.methodSymbols,
1081
- threadModel: compileOptions.threadModel,
1082
- capabilities: compileOptions.guestLinkCapabilities,
1083
- objectBytes: linkObjectBytes,
1084
- },
1085
- };
1086
- }
1087
-
1088
718
  async function runWasiCompiler(command, args, options = {}) {
1089
719
  try {
1090
720
  await execFileAsync(command, args, {
@@ -1104,16 +734,287 @@ async function runWasiCompiler(command, args, options = {}) {
1104
734
  }
1105
735
  }
1106
736
 
1107
- // Builds the isomorphic-pthreads artifact with the wasi-threads toolchain
1108
- // (clang --target=wasm32-wasip1-threads). Emits a wasi-threads wasm (imports
1109
- // wasi.thread-spawn, exports wasi_thread_start over an imported shared memory)
1110
- // that threads under WasmEdge and, via a SharedArrayBuffer/Worker shim, the
1111
- // browser — NOT an Emscripten Web-Worker build. See wasiThreadsToolchain.js and
1112
- // docs/isomorphic-pthreads.md.
1113
- async function compileWithWasiThreads(options = {}) {
737
+ // ---------------------------------------------------------------------------
738
+ // The compile pipeline
739
+ //
740
+ // One translation unit -> module.o (ONE compile), plus the generated embedded
741
+ // manifest and invoke bridge objects, linked into module.wasm. The guest-link
742
+ // object (module-link.o) is module.o with its guest-link symbols renamed; it
743
+ // is not compiled again. Each compile and the link is a step with a content
744
+ // key (compileCache.js): a step whose key is in the cache is not run, and a
745
+ // compile whose every step hits never starts a toolchain at all.
746
+ //
747
+ // Three toolchains run the same steps:
748
+ // emception single-thread: the vendored Emscripten, in-process wasm
749
+ // system-emscripten shared-memory single-thread builds: em++ on PATH
750
+ // wasi emscripten-pthreads and wasi-sequential: clang
751
+ // --target=wasm32-wasip1-threads
752
+ // ---------------------------------------------------------------------------
753
+
754
+ const EMCEPTION_WORK_DIR = "/working/space-data-module-sdk-compile";
755
+ const WORK_DIR_TOKEN = "<work>";
756
+
757
+ function normalizeArgv(argv, workDir) {
758
+ return argv.map((arg) => String(arg).split(workDir).join(WORK_DIR_TOKEN));
759
+ }
760
+
761
+ // The toolchain profile: the commands and flags of every step, and the driver
762
+ // that runs them.
763
+ async function resolveToolchainProfile(kind, { language, sourceCompilerCommand, compileOptions, tempDir }) {
764
+ const sourceCompilerArgs = buildSourceCompilerArgs(compileOptions);
765
+ if (kind === "wasi") {
766
+ const toolchain = resolveWasiThreadsToolchain();
767
+ const isCpp = String(language ?? "").toLowerCase().startsWith("c++");
768
+ const workDir = tempDir;
769
+ const includeArgs = [`-I${workDir}`, `-I${path.join(workDir, "flatbuffers-runtime")}`];
770
+ return {
771
+ kind,
772
+ workDir,
773
+ join: path.join,
774
+ supportsDepfile: true,
775
+ identity: () =>
776
+ getNativeClangIdentity({
777
+ drivers: Array.from(new Set([toolchain.clang, toolchain.clangxx])),
778
+ toolchainArgs: toolchain.toolchainArgs,
779
+ roots: [toolchain.sysroot, toolchain.resourceDir],
780
+ }).then((id) => digestOf({ id, env: nativeCompilerEnv() })),
781
+ compileArgv: (role, sourcePath, objectPath, extra = [], libraryLanguage = "c") =>
782
+ role === "library"
783
+ ? [
784
+ libraryLanguage === "c++" ? toolchain.clangxx : toolchain.clang,
785
+ ...toolchain.toolchainArgs,
786
+ "-c",
787
+ sourcePath,
788
+ ...includeArgs,
789
+ ...(libraryLanguage === "c++" ? ["-std=c++17"] : []),
790
+ ...extra,
791
+ ...sourceCompilerArgs,
792
+ "-o",
793
+ objectPath,
794
+ ]
795
+ : role === "module"
796
+ ? [
797
+ isCpp ? toolchain.clangxx : toolchain.clang,
798
+ ...toolchain.toolchainArgs,
799
+ "-c",
800
+ sourcePath,
801
+ ...includeArgs,
802
+ ...(isCpp ? ["-std=c++17"] : []),
803
+ ...extra,
804
+ ...sourceCompilerArgs,
805
+ "-o",
806
+ objectPath,
807
+ ]
808
+ : [
809
+ toolchain.clangxx,
810
+ ...toolchain.toolchainArgs,
811
+ "-c",
812
+ sourcePath,
813
+ "-std=c++17",
814
+ ...includeArgs,
815
+ ...extra,
816
+ ...sourceCompilerArgs,
817
+ "-o",
818
+ objectPath,
819
+ ],
820
+ linkArgv: (objectPaths, outputPath, linkArgs) => [
821
+ toolchain.clangxx,
822
+ ...toolchain.toolchainArgs,
823
+ ...objectPaths,
824
+ ...linkArgs,
825
+ "-o",
826
+ outputPath,
827
+ ],
828
+ withDriver: (task) => task(createNativeDriver(workDir, runWasiCompiler)),
829
+ };
830
+ }
831
+
832
+ const emscriptenProfile = (workDir) => {
833
+ const includeArgs = [`-I${workDir}`, `-I${path.posix.join(workDir, "flatbuffers-runtime")}`];
834
+ return {
835
+ compileArgv: (role, sourcePath, objectPath, extra = [], libraryLanguage = "c") =>
836
+ role === "library"
837
+ ? [libraryLanguage === "c++" ? "em++" : "emcc", "-c", sourcePath, ...includeArgs, ...extra, ...sourceCompilerArgs, "-o", objectPath]
838
+ : role === "module"
839
+ ? [sourceCompilerCommand, "-c", sourcePath, ...includeArgs, ...extra, ...sourceCompilerArgs, "-o", objectPath]
840
+ : ["em++", "-c", sourcePath, "-std=c++17", ...includeArgs, ...extra, ...sourceCompilerArgs, "-o", objectPath],
841
+ linkArgv: (objectPaths, outputPath, linkArgs) => ["em++", ...objectPaths, ...linkArgs, "-o", outputPath],
842
+ };
843
+ };
844
+
845
+ if (kind === "system-emscripten") {
846
+ const workDir = tempDir;
847
+ await ensureSystemCompilerAvailable(sourceCompilerCommand);
848
+ await ensureSystemCompilerAvailable("em++");
849
+ return {
850
+ kind,
851
+ workDir,
852
+ join: path.join,
853
+ supportsDepfile: true,
854
+ identity: () =>
855
+ getSystemEmscriptenIdentity(Array.from(new Set(["emcc", "em++", sourceCompilerCommand]))).then((id) =>
856
+ digestOf({ id, env: nativeCompilerEnv() }),
857
+ ),
858
+ ...emscriptenProfile(workDir),
859
+ withDriver: (task) => task(createNativeDriver(workDir, runSystemCompiler)),
860
+ };
861
+ }
862
+
863
+ const workDir = EMCEPTION_WORK_DIR;
864
+ return {
865
+ kind,
866
+ workDir,
867
+ join: path.posix.join,
868
+ supportsDepfile: false,
869
+ identity: () => getEmceptionCompileIdentity(),
870
+ ...emscriptenProfile(workDir),
871
+ withDriver: (task) =>
872
+ runWithEmceptionLock(async (emception) => {
873
+ try {
874
+ return await task(createEmceptionDriver(emception, workDir));
875
+ } finally {
876
+ try {
877
+ removeEmceptionDirectory(emception, workDir);
878
+ } catch {
879
+ // Best-effort cleanup only; the shared emception instance remains usable.
880
+ }
881
+ }
882
+ }),
883
+ };
884
+ }
885
+
886
+ // Environment a native compiler reads besides its arguments.
887
+ function nativeCompilerEnv() {
888
+ const names = ["CPATH", "C_INCLUDE_PATH", "CPLUS_INCLUDE_PATH", "OBJC_INCLUDE_PATH", "EMCC_CFLAGS", "SDN_WASI_TARGET"];
889
+ return Object.fromEntries(names.map((name) => [name, process.env[name] ?? null]));
890
+ }
891
+
892
+ function createNativeDriver(workDir, run) {
893
+ return {
894
+ async writeFile(filePath, content) {
895
+ await mkdir(path.dirname(filePath), { recursive: true });
896
+ await writeFile(filePath, content);
897
+ },
898
+ async readFile(filePath) {
899
+ return new Uint8Array(await readFile(filePath));
900
+ },
901
+ async readText(filePath) {
902
+ return readFile(filePath, "utf8");
903
+ },
904
+ async exec(argv) {
905
+ await run(argv[0], argv.slice(1), { cwd: workDir });
906
+ },
907
+ };
908
+ }
909
+
910
+ function createEmceptionDriver(emception, workDir) {
911
+ emception.FS.mkdirTree(workDir);
912
+ return {
913
+ async writeFile(filePath, content) {
914
+ emception.FS.mkdirTree(path.posix.dirname(filePath));
915
+ emception.writeFile(filePath, content);
916
+ },
917
+ async readFile(filePath) {
918
+ return new Uint8Array(emception.readFile(filePath));
919
+ },
920
+ async readText(filePath) {
921
+ return emception.readFile(filePath, { encoding: "utf8" });
922
+ },
923
+ async exec(argv) {
924
+ const result = emception.run(argv.join(" "));
925
+ if (result.returncode !== 0) {
926
+ throw new Error(
927
+ `Compilation failed with ${argv[0]} (emception): ${result.stderr || result.stdout}`,
928
+ );
929
+ }
930
+ },
931
+ };
932
+ }
933
+
934
+ // Shared libraries (compile option `libraries`): code several modules carry
935
+ // (ERFA, miniz, SGP4, ...) compiled ONCE per (source, flags, toolchain) into
936
+ // its own object, whose strong global symbols are renamed into a versioned
937
+ // namespace, sdm_lib_<name>_<version>_<digest>_<symbol>. The module object's
938
+ // references to those symbols are renamed to match; the module source only
939
+ // declares them. The standalone module.wasm links the library object; the
940
+ // guest-link metadata lists it, and a flow links each namespace once however
941
+ // many of its modules use it (src/flow/flowCompiler.js), instead of every
942
+ // module carrying an internal-linkage copy.
943
+ const LIBRARY_NAME = /^[A-Za-z][A-Za-z0-9_.-]*$/;
944
+ const LIBRARY_VERSION = /^[A-Za-z0-9][A-Za-z0-9_.-]*$/;
945
+ const PREPROCESSOR_DEFINE = /^[A-Za-z_][A-Za-z0-9_]*(=[^\s]*)?$/;
946
+
947
+ function normalizeLibraries(libraries) {
948
+ if (libraries === undefined || libraries === null) return [];
949
+ if (!Array.isArray(libraries)) {
950
+ throw new Error("libraries must be an array of { name, version, sourceCode, language?, defines? }.");
951
+ }
952
+ const seen = new Set();
953
+ return libraries.map((library, index) => {
954
+ const name = String(library?.name ?? "");
955
+ const version = String(library?.version ?? "");
956
+ if (!LIBRARY_NAME.test(name) || !LIBRARY_VERSION.test(version)) {
957
+ throw new Error(
958
+ `libraries[${index}] needs a name and a version of letters, digits, '.', '_' or '-' ` +
959
+ `(got name ${JSON.stringify(library?.name)}, version ${JSON.stringify(library?.version)}).`,
960
+ );
961
+ }
962
+ if (seen.has(name)) {
963
+ throw new Error(`libraries[${index}]: library "${name}" is listed twice.`);
964
+ }
965
+ seen.add(name);
966
+ const sourceCode = String(library?.sourceCode ?? "");
967
+ if (!sourceCode.trim()) {
968
+ throw new Error(`libraries[${index}] ("${name}") has no sourceCode.`);
969
+ }
970
+ const language = String(library?.language ?? "c").trim().toLowerCase();
971
+ 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)}.`);
973
+ }
974
+ const defines = (Array.isArray(library?.defines) ? library.defines : []).map((define) => {
975
+ const text = String(define ?? "").trim();
976
+ if (!PREPROCESSOR_DEFINE.test(text)) {
977
+ throw new Error(`libraries[${index}] ("${name}"): define ${JSON.stringify(define)} is not NAME or NAME=VALUE.`);
978
+ }
979
+ return text;
980
+ });
981
+ const safe = (text) => text.replace(/[^A-Za-z0-9]/g, "_");
982
+ const stem = `library-${safe(name)}`;
983
+ return {
984
+ name,
985
+ version,
986
+ language: language === "c" ? "c" : "c++",
987
+ defines,
988
+ sourceCode,
989
+ safeName: safe(name),
990
+ safeVersion: safe(version),
991
+ source: `${stem}.${language === "c" ? "c" : "cpp"}`,
992
+ object: `${stem}.o`,
993
+ };
994
+ });
995
+ }
996
+
997
+ // The library object with its strong global definitions in its namespace, and
998
+ // the old-name -> new-name map the module's references follow.
999
+ function namespaceLibraryObject(library, objectBytes, digest) {
1000
+ const namespace = `sdm_lib_${library.safeName}_${library.safeVersion}_${digest.slice(0, 12)}_`;
1001
+ const renames = new Map();
1002
+ for (const symbol of listWasmObjectSymbols(objectBytes)) {
1003
+ if (!symbol.defined || symbol.local || symbol.weak || !symbol.name) continue;
1004
+ renames.set(symbol.name, `${namespace}${symbol.name}`);
1005
+ }
1006
+ return {
1007
+ namespace,
1008
+ renames,
1009
+ objectBytes: renameWasmObjectSymbols(objectBytes, renames),
1010
+ };
1011
+ }
1012
+
1013
+ async function compileWithToolchain(kind, options = {}) {
1114
1014
  const {
1115
1015
  manifest,
1116
1016
  language,
1017
+ sourceCompilerCommand,
1117
1018
  sourceExtension,
1118
1019
  sourceCode,
1119
1020
  manifestSource,
@@ -1123,110 +1024,234 @@ async function compileWithWasiThreads(options = {}) {
1123
1024
  outputPath,
1124
1025
  tempDir,
1125
1026
  compileOptions,
1027
+ cache,
1126
1028
  } = options;
1127
- const toolchain = resolveWasiThreadsToolchain();
1128
- const isCpp = String(language ?? "").toLowerCase().startsWith("c++");
1129
- const sourceDriver = isCpp ? toolchain.clangxx : toolchain.clang;
1130
- const cppDriver = toolchain.clangxx;
1131
-
1132
1029
  const resolvedOutputPath = path.resolve(
1133
1030
  outputPath ?? path.join(tempDir, "module.wasm"),
1134
1031
  );
1135
- const runtimeIncludeDir = path.join(tempDir, "flatbuffers-runtime");
1136
- const sourcePath = path.join(tempDir, `module.${sourceExtension}`);
1137
- const manifestSourcePath = path.join(tempDir, "plugin-manifest-exports.cpp");
1138
- const invokeHeaderPath = path.join(tempDir, "space_data_module_invoke.h");
1139
- const invokeSourcePath = path.join(tempDir, "plugin-invoke-bridge.cpp");
1140
- const sourceObjectPath = path.join(tempDir, "module.o");
1141
- const linkObjectPath = path.join(tempDir, "module-link.o");
1142
- const manifestObjectPath = path.join(tempDir, "plugin-manifest-exports.o");
1143
- const invokeObjectPath = path.join(tempDir, "plugin-invoke-bridge.o");
1144
- const wasmOutputPath = path.join(tempDir, "module.wasm");
1032
+ const libraries = normalizeLibraries(compileOptions.libraries);
1033
+ const profile = await resolveToolchainProfile(kind, {
1034
+ language,
1035
+ sourceCompilerCommand,
1036
+ compileOptions,
1037
+ tempDir,
1038
+ });
1039
+ const { workDir, join } = profile;
1040
+ const at = (name) => join(workDir, name);
1145
1041
 
1146
1042
  const { runtimeHeaders, schemaHeaders } = await getInvokeCppSupportFiles();
1043
+ const supportFiles = {
1044
+ ...Object.fromEntries(
1045
+ Object.entries(runtimeHeaders).map(([name, content]) => [`flatbuffers-runtime/${name}`, content]),
1046
+ ),
1047
+ ...schemaHeaders,
1048
+ "space_data_module_invoke.h": invokeHeaderSource,
1049
+ };
1050
+ const sourceFiles = {
1051
+ [`module.${sourceExtension}`]: sourceCode,
1052
+ "plugin-manifest-exports.cpp": manifestSource,
1053
+ "plugin-invoke-bridge.cpp": invokeSource,
1054
+ ...Object.fromEntries(libraries.map((library) => [library.source, library.sourceCode])),
1055
+ };
1147
1056
  const linkArgs = buildCompilerArgs(exportedSymbols, compileOptions);
1148
- await writeFilesToDirectory(runtimeIncludeDir, runtimeHeaders);
1149
- await writeFilesToDirectory(tempDir, schemaHeaders);
1150
- await writeFile(sourcePath, sourceCode);
1151
- await writeFile(manifestSourcePath, manifestSource);
1152
- await writeFile(invokeHeaderPath, invokeHeaderSource);
1153
- await writeFile(invokeSourcePath, invokeSource);
1154
-
1155
- const includeArgs = [`-I${tempDir}`, `-I${runtimeIncludeDir}`];
1156
- const sourceCompilerArgs = buildSourceCompilerArgs(compileOptions);
1157
1057
 
1158
- await runWasiCompiler(sourceDriver, [
1159
- ...toolchain.toolchainArgs,
1160
- "-c",
1161
- sourcePath,
1162
- ...includeArgs,
1163
- ...(isCpp ? ["-std=c++17"] : []),
1164
- ...sourceCompilerArgs,
1165
- "-o",
1166
- sourceObjectPath,
1167
- ]);
1058
+ const compileSteps = [
1059
+ { name: "module", role: "module", source: `module.${sourceExtension}`, object: "module.o" },
1060
+ { name: "manifest", role: "support", source: "plugin-manifest-exports.cpp", object: "plugin-manifest-exports.o" },
1061
+ { name: "invoke", role: "support", source: "plugin-invoke-bridge.cpp", object: "plugin-invoke-bridge.o" },
1062
+ ...libraries.map((library) => ({
1063
+ name: `library:${library.name}`,
1064
+ role: "library",
1065
+ source: library.source,
1066
+ object: library.object,
1067
+ library,
1068
+ extra: library.defines.map((define) => `-D${define}`),
1069
+ })),
1070
+ ].map((step) => ({
1071
+ ...step,
1072
+ argv: profile.compileArgv(step.role, at(step.source), at(step.object), step.extra ?? [], step.library?.language),
1073
+ }));
1074
+ const linkOutput = "module.wasm";
1075
+ const linkObjects = compileSteps.map((step) => step.object);
1076
+ const linkArgv = profile.linkArgv(linkObjects.map(at), at(linkOutput), linkArgs);
1077
+
1078
+ const cacheReport = { enabled: Boolean(cache), dir: cache?.root ?? null, hits: [], misses: [], stepMs: {} };
1079
+ let keyBase = null;
1080
+ if (cache) {
1081
+ const sdk = await getSdkCompileIdentity();
1082
+ keyBase = {
1083
+ format: COMPILE_CACHE_FORMAT,
1084
+ sdk,
1085
+ toolchain: { kind, id: await profile.identity() },
1086
+ support: digestFiles(supportFiles),
1087
+ };
1088
+ }
1089
+ const compileKey = (step) =>
1090
+ digestOf({
1091
+ ...keyBase,
1092
+ step: step.name,
1093
+ argv: normalizeArgv(step.argv, workDir),
1094
+ source: sha256Hex(new TextEncoder().encode(sourceFiles[step.source])),
1095
+ });
1096
+ const linkKey = (objects) =>
1097
+ digestOf({
1098
+ ...keyBase,
1099
+ step: "link",
1100
+ argv: normalizeArgv(linkArgv, workDir),
1101
+ objects: objects.map((bytes) => sha256Hex(bytes)),
1102
+ });
1103
+
1104
+ // The objects as compiled, then as linked: library objects namespaced and the
1105
+ // module object's references to them renamed to match.
1106
+ const objects = new Map();
1107
+ let linked = null;
1108
+ const prepareLinkInputs = () => {
1109
+ if (libraries.length === 0) {
1110
+ return { inputs: new Map(objects), libraries: [] };
1111
+ }
1112
+ const inputs = new Map(objects);
1113
+ const references = new Map();
1114
+ const namespaced = libraries.map((library) => {
1115
+ const step = compileSteps.find((entry) => entry.library === library);
1116
+ // The namespace is part of the library's identity: its name, version,
1117
+ // language, defines, source and flags, and the toolchain kind. Two
1118
+ // modules compiling the same library the same way share it in a flow.
1119
+ const digest = digestOf({
1120
+ name: library.name,
1121
+ version: library.version,
1122
+ language: library.language,
1123
+ defines: library.defines,
1124
+ source: sha256Hex(new TextEncoder().encode(library.sourceCode)),
1125
+ argv: normalizeArgv(step.argv, workDir),
1126
+ kind,
1127
+ });
1128
+ const result = namespaceLibraryObject(library, objects.get(library.object), digest);
1129
+ for (const [from, to] of result.renames) {
1130
+ if (references.has(from)) {
1131
+ throw new Error(
1132
+ `Libraries "${references.get(from).library}" and "${library.name}" both define the symbol "${from}".`,
1133
+ );
1134
+ }
1135
+ references.set(from, { to, library: library.name });
1136
+ }
1137
+ inputs.set(library.object, result.objectBytes);
1138
+ return { library, ...result };
1139
+ });
1140
+ inputs.set(
1141
+ "module.o",
1142
+ renameWasmObjectSymbols(
1143
+ objects.get("module.o"),
1144
+ new Map(Array.from(references, ([from, { to }]) => [from, to])),
1145
+ { undefinedOnly: true },
1146
+ ),
1147
+ );
1148
+ return { inputs, libraries: namespaced };
1149
+ };
1168
1150
 
1169
- const sourceObjectBytes = new Uint8Array(await readFile(sourceObjectPath));
1170
- const guestLink = deriveGuestLinkRenameArgs({
1171
- objectBytes: sourceObjectBytes,
1151
+ if (cache) {
1152
+ for (const step of compileSteps) {
1153
+ step.key = compileKey(step);
1154
+ const entry = await cache.get(step.key);
1155
+ if (entry?.blobs?.object) objects.set(step.object, entry.blobs.object);
1156
+ }
1157
+ }
1158
+ let wasmBytes = null;
1159
+ let linkCacheKey = null;
1160
+ if (cache && objects.size === compileSteps.length) {
1161
+ linked = prepareLinkInputs();
1162
+ linkCacheKey = linkKey(linkObjects.map((name) => linked.inputs.get(name)));
1163
+ wasmBytes = (await cache.get(linkCacheKey))?.blobs?.wasm ?? null;
1164
+ }
1165
+
1166
+ if (!wasmBytes) {
1167
+ wasmBytes = await profile.withDriver(async (driver) => {
1168
+ for (const [name, content] of Object.entries(supportFiles)) {
1169
+ await driver.writeFile(at(name), content);
1170
+ }
1171
+ for (const [name, content] of Object.entries(sourceFiles)) {
1172
+ await driver.writeFile(at(name), content);
1173
+ }
1174
+ for (const step of compileSteps) {
1175
+ if (objects.has(step.object)) {
1176
+ cacheReport.hits.push(step.name);
1177
+ continue;
1178
+ }
1179
+ cacheReport.misses.push(step.name);
1180
+ const depfile = at(`${step.object}.d`);
1181
+ const useDepfile = Boolean(cache) && profile.supportsDepfile;
1182
+ const started = performance.now();
1183
+ await driver.exec(useDepfile ? [...step.argv, "-MD", "-MF", depfile] : step.argv);
1184
+ cacheReport.stepMs[step.name] = Math.round(performance.now() - started);
1185
+ const objectBytes = await driver.readFile(at(step.object));
1186
+ objects.set(step.object, objectBytes);
1187
+ if (cache) {
1188
+ const externalDeps = useDepfile
1189
+ ? await describeExternalDependencies(
1190
+ parseDepfile(await driver.readText(depfile))
1191
+ .map((dep) => path.resolve(workDir, dep))
1192
+ .filter((dep) => !dep.startsWith(workDir + path.sep) && dep !== workDir),
1193
+ )
1194
+ : [];
1195
+ await cache.put(step.key, { object: objectBytes }, { step: step.name, externalDeps });
1196
+ }
1197
+ }
1198
+ linked = prepareLinkInputs();
1199
+ const objectBytesList = linkObjects.map((name) => linked.inputs.get(name));
1200
+ for (const name of linkObjects) {
1201
+ await driver.writeFile(at(name), linked.inputs.get(name));
1202
+ }
1203
+ if (cache) {
1204
+ linkCacheKey = linkKey(objectBytesList);
1205
+ const entry = await cache.get(linkCacheKey);
1206
+ if (entry?.blobs?.wasm) {
1207
+ cacheReport.hits.push("link");
1208
+ return entry.blobs.wasm;
1209
+ }
1210
+ }
1211
+ cacheReport.misses.push("link");
1212
+ const linkStarted = performance.now();
1213
+ await driver.exec(linkArgv);
1214
+ cacheReport.stepMs.link = Math.round(performance.now() - linkStarted);
1215
+ const linkedBytes = await driver.readFile(at(linkOutput));
1216
+ if (cache) await cache.put(linkCacheKey, { wasm: linkedBytes }, { step: "link" });
1217
+ return linkedBytes;
1218
+ });
1219
+ } else {
1220
+ cacheReport.hits.push(...compileSteps.map((step) => step.name), "link");
1221
+ }
1222
+
1223
+ const guestLink = deriveGuestLinkObject({
1224
+ objectBytes: linked.inputs.get("module.o"),
1172
1225
  pluginId: manifest?.pluginId,
1173
1226
  methodIds: Array.isArray(manifest?.methods)
1174
1227
  ? manifest.methods.map((method) => String(method?.methodId ?? ""))
1175
1228
  : [],
1176
1229
  });
1177
-
1178
- await runWasiCompiler(sourceDriver, [
1179
- ...toolchain.toolchainArgs,
1180
- "-c",
1181
- sourcePath,
1182
- ...includeArgs,
1183
- ...(isCpp ? ["-std=c++17"] : []),
1184
- ...guestLink.renameArgs,
1185
- ...sourceCompilerArgs,
1186
- "-o",
1187
- linkObjectPath,
1188
- ]);
1189
-
1190
- for (const [srcPath, objPath] of [
1191
- [manifestSourcePath, manifestObjectPath],
1192
- [invokeSourcePath, invokeObjectPath],
1193
- ]) {
1194
- await runWasiCompiler(cppDriver, [
1195
- ...toolchain.toolchainArgs,
1196
- "-c",
1197
- srcPath,
1198
- "-std=c++17",
1199
- ...includeArgs,
1200
- ...sourceCompilerArgs,
1201
- "-o",
1202
- objPath,
1203
- ]);
1204
- }
1205
-
1206
- await runWasiCompiler(cppDriver, [
1207
- ...toolchain.toolchainArgs,
1208
- sourceObjectPath,
1209
- manifestObjectPath,
1210
- invokeObjectPath,
1211
- ...linkArgs,
1212
- "-o",
1213
- wasmOutputPath,
1214
- ]);
1215
-
1216
- const wasmBytes = new Uint8Array(await readFile(wasmOutputPath));
1217
- const linkObjectBytes = new Uint8Array(await readFile(linkObjectPath));
1218
1230
  await writeFile(resolvedOutputPath, wasmBytes);
1219
1231
  return {
1220
1232
  wasmBytes,
1221
1233
  outputPath: resolvedOutputPath,
1234
+ cache: cacheReport,
1222
1235
  guestLink: {
1223
1236
  format: "wasm-object",
1224
1237
  language,
1225
- symbolPrefix: guestLink.prefix,
1238
+ symbolPrefix: guestLink.symbolPrefix,
1226
1239
  methodSymbols: guestLink.methodSymbols,
1227
- threadModel: compileOptions.threadModel,
1240
+ threadModel: compileOptions.threadModel ?? ModuleThreadModel.SINGLE_THREAD,
1228
1241
  capabilities: compileOptions.guestLinkCapabilities,
1229
- objectBytes: linkObjectBytes,
1242
+ objectBytes: guestLink.objectBytes,
1243
+ ...(linked.libraries.length > 0
1244
+ ? {
1245
+ libraries: linked.libraries.map(({ library, namespace, objectBytes }) => ({
1246
+ name: library.name,
1247
+ version: library.version,
1248
+ language: library.language,
1249
+ namespace,
1250
+ sha256: sha256Hex(objectBytes),
1251
+ objectBytes,
1252
+ })),
1253
+ }
1254
+ : {}),
1230
1255
  },
1231
1256
  };
1232
1257
  }
@@ -1310,11 +1335,12 @@ export async function compileModuleFromSource(options = {}) {
1310
1335
  threadModel === ModuleThreadModel.WASI_SEQUENTIAL;
1311
1336
  const useSystemEmscripten =
1312
1337
  !useWasiThreads && requiresSystemEmscripten(threadModel, compileOptions);
1313
- const compileFunction = useWasiThreads
1314
- ? compileWithWasiThreads
1338
+ const toolchainKind = useWasiThreads
1339
+ ? "wasi"
1315
1340
  : useSystemEmscripten
1316
- ? compileWithSystemEmscripten
1317
- : compileWithEmception;
1341
+ ? "system-emscripten"
1342
+ : "emception";
1343
+ const cache = openCompileCache(options.compileCache);
1318
1344
  // Scratch for the toolchain and, without an explicit outputPath, the home of
1319
1345
  // the emitted artifact. Removed in finally on success, failure and throw.
1320
1346
  // `keepTempDir: true` hands it to the caller on success instead
@@ -1326,7 +1352,7 @@ export async function compileModuleFromSource(options = {}) {
1326
1352
  );
1327
1353
  let handedOff = false;
1328
1354
  try {
1329
- const result = await compileFunction({
1355
+ const result = await compileWithToolchain(toolchainKind, {
1330
1356
  manifest,
1331
1357
  language: compiler.language,
1332
1358
  sourceCompilerCommand: compiler.command,
@@ -1339,6 +1365,7 @@ export async function compileModuleFromSource(options = {}) {
1339
1365
  outputPath: options.outputPath,
1340
1366
  tempDir,
1341
1367
  compileOptions,
1368
+ cache,
1342
1369
  });
1343
1370
  const wasmBytes = appendWasmCustomSection(
1344
1371
  result.wasmBytes,
@@ -1392,6 +1419,7 @@ export async function compileModuleFromSource(options = {}) {
1392
1419
  tempDir: keepTempDir ? tempDir : null,
1393
1420
  wasmBytes,
1394
1421
  guestLink: result.guestLink,
1422
+ compileCache: result.cache,
1395
1423
  manifestWarnings: warnings,
1396
1424
  threadFeatures,
1397
1425
  report,