peachsim 0.1.2439 → 0.1.2441

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 (143) hide show
  1. package/dist-lib/agent-daemon-client.cjs +1 -1
  2. package/dist-lib/agent-events.cjs +1 -1
  3. package/dist-lib/attached-projects.cjs +1 -1
  4. package/dist-lib/auth/shared-session.cjs +1 -1
  5. package/dist-lib/backend-origin.cjs +1 -1
  6. package/dist-lib/beta.cjs +1 -1
  7. package/dist-lib/beta.mjs +2 -2
  8. package/dist-lib/bridge-constants.cjs +1 -1
  9. package/dist-lib/bridge-contract-input.cjs +1 -1
  10. package/dist-lib/bridge-contract-input.mjs +5 -5
  11. package/dist-lib/bridge-contract.cjs +1 -1
  12. package/dist-lib/bridge-contract.mjs +3 -3
  13. package/dist-lib/bundle-channel.cjs +8180 -8397
  14. package/dist-lib/capture-contract.cjs +1 -1
  15. package/dist-lib/capture-contract.mjs +3 -3
  16. package/dist-lib/cloud-contract.cjs +1 -1
  17. package/dist-lib/cloud-contract.mjs +3 -3
  18. package/dist-lib/cloud-test-args.cjs +1 -1
  19. package/dist-lib/cloud-test-args.mjs +2 -2
  20. package/dist-lib/cloud.cjs +1 -1
  21. package/dist-lib/cloud.mjs +7 -7
  22. package/dist-lib/config.cjs +1 -1
  23. package/dist-lib/config.mjs +5 -5
  24. package/dist-lib/detox/index.cjs +2 -2
  25. package/dist-lib/dev-bundle-resolution.cjs +1 -1
  26. package/dist-lib/esm-chunks/{acorn-FGE4PYDJ.mjs → acorn-FRQNHKFC.mjs} +3 -3
  27. package/dist-lib/esm-chunks/{chunk-HIDNO3RP.mjs → chunk-4BZ3Z3IQ.mjs} +18 -18
  28. package/dist-lib/esm-chunks/{chunk-5T4XBUJP.mjs → chunk-4HEUXQGM.mjs} +4 -4
  29. package/dist-lib/esm-chunks/{chunk-7HANEMO4.mjs → chunk-4ZRMJ5YO.mjs} +1 -1
  30. package/dist-lib/esm-chunks/{chunk-4ZFNH7TU.mjs → chunk-6A6JEVIF.mjs} +1 -1
  31. package/dist-lib/esm-chunks/{chunk-KVTIDLBK.mjs → chunk-ABMB3G7I.mjs} +3 -3
  32. package/dist-lib/esm-chunks/{chunk-C3WBGYP6.mjs → chunk-BAYRN7ZL.mjs} +1 -1
  33. package/dist-lib/esm-chunks/{chunk-KSQ5KM5Y.mjs → chunk-DJMWTW2B.mjs} +1 -1
  34. package/dist-lib/esm-chunks/{chunk-DADGQELM.mjs → chunk-IRMC5BCX.mjs} +1 -1
  35. package/dist-lib/esm-chunks/{chunk-YB27R6JG.mjs → chunk-NPLEBOWJ.mjs} +1 -1
  36. package/dist-lib/esm-chunks/{chunk-HSADZOVN.mjs → chunk-O4EOBXAP.mjs} +1 -1
  37. package/dist-lib/esm-chunks/{chunk-JCKI3VZ6.mjs → chunk-ORYS5CC4.mjs} +1 -1
  38. package/dist-lib/esm-chunks/{chunk-2NPABFPN.mjs → chunk-PMGJ7FLI.mjs} +1 -1
  39. package/dist-lib/esm-chunks/{chunk-6VY6HTJC.mjs → chunk-QUBR7LHU.mjs} +2036 -1918
  40. package/dist-lib/esm-chunks/{chunk-IWJUYJQO.mjs → chunk-QYYJESMK.mjs} +1 -1
  41. package/dist-lib/esm-chunks/{chunk-CVGDRROP.mjs → chunk-VAQJQDWI.mjs} +1 -1
  42. package/dist-lib/esm-chunks/{chunk-DEGYKHN7.mjs → chunk-VCAJFWZD.mjs} +1 -1
  43. package/dist-lib/esm-chunks/{chunk-2EUHEBIJ.mjs → chunk-XO5GX4PI.mjs} +1 -1
  44. package/dist-lib/esm-chunks/{chunk-MIQSRBVU.mjs → chunk-ZCMAKWHN.mjs} +1 -1
  45. package/dist-lib/esm-chunks/{metro-layout-parser-MVUAXRUJ.mjs → metro-layout-parser-AUAVE5VL.mjs} +3 -3
  46. package/dist-lib/expo-swift-bundle.cjs +5580 -5768
  47. package/dist-lib/expo-swift-metadata.cjs +1 -1
  48. package/dist-lib/expo-swift-metadata.mjs +7 -7
  49. package/dist-lib/home-paths.cjs +1 -1
  50. package/dist-lib/host/bridge-host.cjs +6332 -6500
  51. package/dist-lib/host/fetch-proxy-handler.cjs +13891 -13919
  52. package/dist-lib/host/fetch-proxy-overrides.cjs +1 -1
  53. package/dist-lib/host/fetch-proxy-overrides.mjs +2 -2
  54. package/dist-lib/host/replacement-module-handler.cjs +1 -1
  55. package/dist-lib/host/websocket-proxy.cjs +1 -1
  56. package/dist-lib/index.cjs +1 -1
  57. package/dist-lib/jump-to-source-babel.cjs +1 -1
  58. package/dist-lib/jump-to-source-native.cjs +1 -1
  59. package/dist-lib/kotlin-host.cjs +1 -1
  60. package/dist-lib/menu.cjs +1 -1
  61. package/dist-lib/menu.mjs +3 -3
  62. package/dist-lib/metro-fingerprint-registry.cjs +1 -1
  63. package/dist-lib/metro-fingerprint-registry.mjs +3 -3
  64. package/dist-lib/metro-production-bundle.cjs +1 -1
  65. package/dist-lib/metro-production-bundle.mjs +4 -4
  66. package/dist-lib/native-app-identity-project.cjs +784 -536
  67. package/dist-lib/native-app-identity-project.mjs +543 -408
  68. package/dist-lib/native-app-identity.cjs +1 -1
  69. package/dist-lib/native-app-identity.mjs +6 -6
  70. package/dist-lib/native-firebase-metadata.cjs +1 -1
  71. package/dist-lib/native-firebase-metadata.mjs +3 -3
  72. package/dist-lib/pdfium-raster.cjs +1 -1
  73. package/dist-lib/pdfium-raster.mjs +2 -2
  74. package/dist-lib/plist.cjs +1 -1
  75. package/dist-lib/plist.mjs +3 -3
  76. package/dist-lib/profiles.cjs +1 -1
  77. package/dist-lib/public-brand.cjs +1 -1
  78. package/dist-lib/public-origins-lib-esm.json +81 -79
  79. package/dist-lib/public-origins-lib.json +185 -195
  80. package/dist-lib/react-native-host-modules.cjs +1 -1
  81. package/dist-lib/react-native-host-modules.mjs +2 -2
  82. package/dist-lib/reap-browser.cjs +1 -1
  83. package/dist-lib/scripts/dev-server-scanner.cjs +1 -1
  84. package/dist-lib/sdk.cjs +1 -1
  85. package/dist-lib/sdk.mjs +7 -7
  86. package/dist-lib/skills.cjs +7579 -7758
  87. package/dist-lib/swift-compile.cjs +1978 -1922
  88. package/dist-lib/swift-compile.mjs +8 -8
  89. package/dist-lib/swift-package.cjs +1 -1
  90. package/dist-lib/swift-package.mjs +3 -3
  91. package/dist-lib/swift-submit.cjs +1 -1
  92. package/dist-lib/swift-submit.mjs +5 -5
  93. package/dist-lib/swift-toolchain.cjs +3 -1
  94. package/dist-lib/swift.cjs +1 -1
  95. package/dist-lib/vendor/@peculiar/x509.cjs +1 -1
  96. package/dist-lib/vendor/acorn.cjs +1 -1
  97. package/dist-lib/vendor/bplist-parser.cjs +1 -1
  98. package/dist-lib/vendor/ignore.cjs +1 -1
  99. package/dist-lib/vendor/magic-string.cjs +1 -1
  100. package/dist-lib/vendor/plist.cjs +17 -17
  101. package/dist-lib/vendor/smol-toml.cjs +1 -1
  102. package/dist-lib/vendor/stream-json.cjs +1 -1
  103. package/dist-lib/vendor/sucrase/dist/index.js.cjs +1 -1
  104. package/dist-lib/vendor/sucrase/dist/parser/index.js.cjs +1 -1
  105. package/dist-lib/vendor/sucrase/dist/parser/tokenizer/index.js.cjs +1 -1
  106. package/dist-lib/vendor/sucrase/dist/parser/tokenizer/types.js.cjs +1 -1
  107. package/dist-lib/vendor/sucrase.cjs +1 -1
  108. package/dist-lib/vendor/terser.cjs +1 -1
  109. package/dist-lib/vendor/valibot.cjs +1 -1
  110. package/dist-lib/vendor/zod.cjs +1 -1
  111. package/dist-lib/worklet-executable.cjs +1 -1
  112. package/dist-lib/worklet-executable.mjs +3 -3
  113. package/dist-types/packages/peach-compat/src/stubs/native-seams/react-native-cookies.d.ts +4 -0
  114. package/dist-types/packages/peach-engine/src/remote-stream/cloud-display.d.ts +2 -2
  115. package/dist-types/packages/peach-engine/src/render-worker/protocol.d.ts +9 -0
  116. package/package.json +1 -1
  117. package/runtime-companion.json +1 -1
  118. package/sdk/ios/System/Library/Frameworks/Foundation.framework/Headers/NSDateComponentsFormatter.h +1 -1
  119. package/src/expo-discovery-cache.ts +9 -45
  120. package/src/expo-native-compiler-digest.ts +8 -0
  121. package/src/expo-native-prebuilt.ts +1 -10
  122. package/src/expo-native-workspace.ts +5 -120
  123. package/src/expo-pod-prebuilt.ts +1 -1
  124. package/src/expo-swift-host.ts +48 -35
  125. package/src/host/bridge-host.ts +2 -0
  126. package/src/installed-native-libraries.ts +10 -20
  127. package/src/native-slices.ts +1 -1
  128. package/src/pod-graph-specifications.ts +11 -0
  129. package/src/pods-install.ts +10 -7
  130. package/src/podspec-cocoapods.ts +8 -3
  131. package/src/podspec-sources.ts +19 -15
  132. package/src/swift-clang-type-ownership.ts +118 -0
  133. package/src/swift-compile.ts +20 -12
  134. package/src/swift-guest-image-ledger.ts +48 -0
  135. package/src/swift-guest-link.ts +11 -1
  136. package/src/swift-host.ts +7 -8
  137. package/src/swift-package-manifest.ts +13 -8
  138. package/src/swift-packages.ts +0 -5
  139. package/src/swift-toolchain.ts +1 -1
  140. package/src/xcode-project.ts +64 -46
  141. package/src/portable-expo-contract.ts +0 -108
  142. package/src/portable-expo-workspace.ts +0 -100
  143. package/src/prepared-xcode-phases.ts +0 -194
@@ -1,4 +1,4 @@
1
- /*! peach v0.1.2439 | (c) 2026 Tamagui LLC | Proprietary; see LICENSE */
1
+ /*! peach v0.1.2441 | (c) 2026 Tamagui LLC | Proprietary; see LICENSE */
2
2
  let __sootsim_import_meta_url = '', __sootsim_import_meta_dirname = '', __sootsim_import_meta_filename = ''; try { __sootsim_import_meta_url = require('url').pathToFileURL(__filename).href; __sootsim_import_meta_dirname = __dirname; __sootsim_import_meta_filename = __filename; } catch {}
3
3
  "use strict";
4
4
  var __create = Object.create;
@@ -7113,9 +7113,9 @@ function aliasGuestLinkIdentities(identities, archives) {
7113
7113
  }
7114
7114
 
7115
7115
  // src/swift-guest-link.ts
7116
- var import_node_child_process11 = require("node:child_process");
7117
- var import_node_fs17 = __toESM(require("node:fs"), 1);
7118
- var import_node_path17 = __toESM(require("node:path"), 1);
7116
+ var import_node_child_process13 = require("node:child_process");
7117
+ var import_node_fs21 = __toESM(require("node:fs"), 1);
7118
+ var import_node_path21 = __toESM(require("node:path"), 1);
7119
7119
  var import_node_string_decoder = require("node:string_decoder");
7120
7120
 
7121
7121
  // src/swift-guest-image-ledger.ts
@@ -7717,6 +7717,48 @@ function createGuestImageLedger(input) {
7717
7717
  llvmIR: ir.join("\n") + "\n"
7718
7718
  };
7719
7719
  }
7720
+ function nameGuestImageAliases(wasm, symbols) {
7721
+ const alias = /^__peach_image_\d+_symbol_(\d+)$/;
7722
+ const parts = [wasm.subarray(0, 8)];
7723
+ let position = 8;
7724
+ while (position < wasm.length) {
7725
+ const [size, start] = readNumber(wasm, position + 1);
7726
+ const end = start + size;
7727
+ const custom = wasm[position] === 0 ? readString(wasm, start) : void 0;
7728
+ if (custom?.[0] !== "name") {
7729
+ parts.push(wasm.subarray(position, end));
7730
+ position = end;
7731
+ continue;
7732
+ }
7733
+ const subsections = [encodedString("name")];
7734
+ let at = custom[1];
7735
+ while (at < end) {
7736
+ const [subSize, subStart] = readNumber(wasm, at + 1);
7737
+ const subEnd = subStart + subSize;
7738
+ if (wasm[at] !== 1) {
7739
+ subsections.push(wasm.subarray(at, subEnd));
7740
+ at = subEnd;
7741
+ continue;
7742
+ }
7743
+ let [count, cursor] = readNumber(wasm, subStart);
7744
+ const entries = [encodeNumber(count)];
7745
+ for (; count > 0; count--) {
7746
+ const [index, next] = readNumber(wasm, cursor);
7747
+ const [name2, after] = readString(wasm, next);
7748
+ cursor = after;
7749
+ const symbol = symbols[Number(alias.exec(name2)?.[1] ?? -1)];
7750
+ entries.push(encodeNumber(index), encodedString(symbol ?? name2));
7751
+ }
7752
+ const content = Buffer.concat(entries);
7753
+ subsections.push(Buffer.from([1]), encodeNumber(content.length), content);
7754
+ at = subEnd;
7755
+ }
7756
+ const section = Buffer.concat(subsections);
7757
+ parts.push(Buffer.from([0]), encodeNumber(section.length), section);
7758
+ position = end;
7759
+ }
7760
+ return Buffer.concat(parts);
7761
+ }
7720
7762
 
7721
7763
  // src/swift-guest-link-plan.ts
7722
7764
  function selectedGuestInputImage(artifact, member) {
@@ -9236,2042 +9278,2047 @@ function guestAliasedSdkArchiveArtifacts(options) {
9236
9278
  return result;
9237
9279
  }
9238
9280
 
9239
- // src/swift-guest-link.ts
9240
- function remapGuestLinkPlan(plan, rewritten) {
9241
- return {
9242
- ...plan,
9243
- artifacts: plan.artifacts.map((artifact) => ({
9244
- ...artifact,
9245
- path: rewritten.get(artifact.path) ?? artifact.path
9246
- }))
9247
- };
9248
- }
9249
- function guestLinkInputFiles(args) {
9250
- const dirs = [];
9251
- for (let i = 0; i < args.length; i++) {
9252
- const arg = args[i];
9253
- if (arg === "-L" || arg === "--library-path") dirs.push(args[++i]);
9254
- else if (arg.startsWith("-L")) dirs.push(arg.slice(2));
9255
- else if (arg.startsWith("--library-path=")) dirs.push(arg.slice(15));
9256
- }
9257
- const inputs = /* @__PURE__ */ new Set();
9258
- for (let i = 0; i < args.length; i++) {
9259
- const arg = args[i];
9260
- if (arg === "-L" || arg === "--library-path" || arg === "-o" || arg === "--output") {
9261
- i++;
9262
- continue;
9281
+ // src/wasm-optimize.ts
9282
+ var import_node_child_process12 = require("node:child_process");
9283
+ var import_node_fs20 = require("node:fs");
9284
+ var import_node_path20 = require("node:path");
9285
+ var import_node_util2 = require("node:util");
9286
+
9287
+ // ../contrast-runtime-delivery/src/index.ts
9288
+ var import_node_child_process11 = require("node:child_process");
9289
+ var import_node_crypto12 = __toESM(require("node:crypto"), 1);
9290
+ var import_node_fs18 = __toESM(require("node:fs"), 1);
9291
+ var import_node_os5 = __toESM(require("node:os"), 1);
9292
+ var import_node_path18 = __toESM(require("node:path"), 1);
9293
+ var import_promises4 = require("node:stream/promises");
9294
+ var import_node_zlib2 = __toESM(require("node:zlib"), 1);
9295
+
9296
+ // ../contrast-runtime-delivery/src/product.ts
9297
+ var import_node_fs17 = __toESM(require("node:fs"), 1);
9298
+ var import_node_path17 = __toESM(require("node:path"), 1);
9299
+
9300
+ // ../contrast-runtime-delivery/src/index.ts
9301
+ async function installVerifiedTarball(tarball) {
9302
+ const { destDir, installedMarker, signal } = tarball;
9303
+ import_node_fs18.default.mkdirSync(import_node_path18.default.dirname(destDir), { recursive: true });
9304
+ const presentAtStart = import_node_fs18.default.existsSync(import_node_path18.default.join(destDir, installedMarker));
9305
+ const lock = `${destDir}.lock`;
9306
+ for (; ; ) {
9307
+ signal?.throwIfAborted();
9308
+ try {
9309
+ import_node_fs18.default.writeFileSync(lock, String(process.pid), { flag: "wx" });
9310
+ break;
9311
+ } catch (err) {
9312
+ if (!isErrnoCode(err, "EEXIST")) throw err;
9313
+ if (lockOwnerGone(lock)) import_node_fs18.default.rmSync(lock, { force: true });
9314
+ else await new Promise((resolve) => setTimeout(resolve, 250));
9263
9315
  }
9264
- if (arg.startsWith("@")) throw new Error(`nested linker response file ${arg}`);
9265
- let file;
9266
- if (arg === "-l" || arg === "--library" || arg.startsWith("--library=") || arg.startsWith("-l") && arg.length > 2) {
9267
- const name2 = arg === "-l" || arg === "--library" ? args[++i] : arg.startsWith("--library=") ? arg.slice(10) : arg.slice(2);
9268
- const archive = name2.startsWith(":") ? name2.slice(1) : `lib${name2}.a`;
9269
- file = dirs.map((dir) => import_node_path17.default.join(dir, archive)).find((item) => import_node_fs17.default.existsSync(item));
9270
- if (!file) throw new Error(`unresolved guest link library ${name2}`);
9271
- } else if (!arg.startsWith("-") && import_node_fs17.default.existsSync(arg) && import_node_fs17.default.statSync(arg).isFile()) {
9272
- const fd = import_node_fs17.default.openSync(arg, "r");
9273
- const magic = Buffer.alloc(8);
9274
- try {
9275
- import_node_fs17.default.readSync(fd, magic, 0, magic.length, 0);
9276
- } finally {
9277
- import_node_fs17.default.closeSync(fd);
9278
- }
9279
- if (magic.subarray(0, 4).equals(Buffer.from([0, 97, 115, 109])) || magic.subarray(0, 4).equals(Buffer.from([66, 67, 192, 222])) || magic.toString("ascii") === "!<arch>\n" || magic.toString("ascii") === "!<thin>\n")
9280
- file = arg;
9316
+ }
9317
+ try {
9318
+ if (!presentAtStart && import_node_fs18.default.existsSync(import_node_path18.default.join(destDir, installedMarker))) {
9319
+ await tarball.verify?.(destDir);
9320
+ return;
9281
9321
  }
9282
- if (file) inputs.add(import_node_path17.default.resolve(file));
9322
+ await installVerifiedTarballLocked(tarball, presentAtStart);
9323
+ } finally {
9324
+ import_node_fs18.default.rmSync(lock, { force: true });
9283
9325
  }
9284
- return [...inputs];
9285
- }
9286
- function unownedGuestLinkInputs(plan, args) {
9287
- const owned = new Set(plan.artifacts.map((artifact) => import_node_path17.default.resolve(artifact.path)));
9288
- return guestLinkInputFiles(args).filter((file) => !owned.has(file));
9289
9326
  }
9290
- function occurrences(plan, args) {
9291
- const dirs = [];
9292
- for (let i = 0; i < args.length; i++) {
9293
- const arg = args[i];
9294
- if (arg === "-L") dirs.push(args[++i]);
9295
- else if (arg.startsWith("-L")) dirs.push(arg.slice(2));
9327
+ function lockOwnerGone(lock) {
9328
+ try {
9329
+ process.kill(Number(import_node_fs18.default.readFileSync(lock, "utf8")), 0);
9330
+ return false;
9331
+ } catch (err) {
9332
+ return !isErrnoCode(err, "EPERM", "ENOENT");
9296
9333
  }
9297
- const owned = new Map(
9298
- plan.artifacts.map((artifact) => [import_node_path17.default.resolve(artifact.path), artifact])
9334
+ }
9335
+ async function installVerifiedTarballLocked(tarball, presentAtStart) {
9336
+ const { url, digest, destDir, installedMarker, label, signal } = tarball;
9337
+ signal?.throwIfAborted();
9338
+ const downloadDir = import_node_fs18.default.mkdtempSync(import_node_path18.default.join(import_node_os5.default.tmpdir(), "runtime-delivery-download-"));
9339
+ const archivePath = import_node_path18.default.join(downloadDir, "archive");
9340
+ const tmpDir = import_node_fs18.default.mkdtempSync(
9341
+ import_node_path18.default.join(import_node_path18.default.dirname(destDir), `.installing-${import_node_path18.default.basename(destDir)}-`)
9299
9342
  );
9300
- if (owned.size !== plan.artifacts.length)
9301
- throw new Error("duplicate guest link artifact");
9302
- const found = [];
9303
- const seen = /* @__PURE__ */ new Map();
9304
- let lazy = false;
9305
- let whole = false;
9306
- for (const token of args) {
9307
- if (token === "--start-lib") {
9308
- lazy = true;
9309
- continue;
9310
- }
9311
- if (token === "--end-lib") {
9312
- lazy = false;
9313
- continue;
9314
- }
9315
- if (token === "--whole-archive") {
9316
- whole = true;
9317
- continue;
9318
- }
9319
- if (token === "--no-whole-archive") {
9320
- whole = false;
9321
- continue;
9343
+ try {
9344
+ for (let attempt = 1; ; attempt++) {
9345
+ await downloadToFile(url, archivePath, signal);
9346
+ const actual = await digestFile(
9347
+ archivePath,
9348
+ digest.algorithm,
9349
+ digest.encoding,
9350
+ signal
9351
+ );
9352
+ if (actual === digest.value) break;
9353
+ if (attempt >= 2) {
9354
+ throw new Error(
9355
+ `${digest.algorithm} mismatch for ${label}: expected ${digest.value}, actual ${actual}`
9356
+ );
9357
+ }
9322
9358
  }
9323
- let filename = token;
9324
- if (token.startsWith("-l") && token.length > 2) {
9325
- const library = token.slice(2);
9326
- filename = dirs.map(
9327
- (dir) => import_node_path17.default.join(
9328
- dir,
9329
- library.startsWith(":") ? library.slice(1) : `lib${library}.a`
9330
- )
9331
- ).find((file) => import_node_fs17.default.existsSync(file)) ?? token;
9359
+ const { pathname } = new URL(url);
9360
+ if (pathname.endsWith(".zip")) await extractZip(archivePath, tmpDir, signal);
9361
+ else
9362
+ await extractTarball(
9363
+ archivePath,
9364
+ pathname.endsWith(".tar.zst"),
9365
+ tmpDir,
9366
+ tarball.stripComponents ?? 0,
9367
+ signal
9368
+ );
9369
+ signal?.throwIfAborted();
9370
+ if (!import_node_fs18.default.existsSync(import_node_path18.default.join(tmpDir, installedMarker))) {
9371
+ throw new Error(`extracted tarball for ${label} is missing ${installedMarker}`);
9332
9372
  }
9333
- const artifact = owned.get(import_node_path17.default.resolve(filename));
9334
- if (artifact) {
9335
- const prior = seen.get(artifact.path);
9336
- if (prior) {
9337
- if (prior.lazy !== lazy || prior.whole !== whole)
9338
- throw new Error(
9339
- `guest link input has conflicting occurrence modes: ${artifact.path}`
9340
- );
9341
- continue;
9373
+ await tarball.verify?.(tmpDir);
9374
+ signal?.throwIfAborted();
9375
+ try {
9376
+ import_node_fs18.default.renameSync(tmpDir, destDir);
9377
+ } catch (err) {
9378
+ if (!isErrnoCode(err, "ENOTEMPTY", "EEXIST")) throw err;
9379
+ if (!presentAtStart && import_node_fs18.default.existsSync(import_node_path18.default.join(destDir, installedMarker))) {
9380
+ await tarball.verify?.(destDir);
9381
+ return;
9382
+ }
9383
+ const aside = `${tmpDir}-replaced`;
9384
+ try {
9385
+ import_node_fs18.default.renameSync(destDir, aside);
9386
+ } catch (moveErr) {
9387
+ if (!isErrnoCode(moveErr, "ENOENT")) throw moveErr;
9388
+ }
9389
+ try {
9390
+ import_node_fs18.default.renameSync(tmpDir, destDir);
9391
+ } catch (landErr) {
9392
+ if (!isErrnoCode(landErr, "ENOTEMPTY", "EEXIST") || !import_node_fs18.default.existsSync(import_node_path18.default.join(destDir, installedMarker))) {
9393
+ throw landErr;
9394
+ }
9395
+ await tarball.verify?.(destDir);
9396
+ } finally {
9397
+ import_node_fs18.default.rmSync(aside, { recursive: true, force: true });
9342
9398
  }
9343
- const occurrence = { artifact, token, lazy, whole };
9344
- seen.set(artifact.path, occurrence);
9345
- found.push(occurrence);
9346
9399
  }
9400
+ } finally {
9401
+ import_node_fs18.default.rmSync(tmpDir, { recursive: true, force: true });
9402
+ import_node_fs18.default.rmSync(downloadDir, { recursive: true, force: true });
9347
9403
  }
9348
- if (found.length !== plan.artifacts.length)
9349
- throw new Error("guest plan does not match linker inputs");
9350
- return found;
9351
9404
  }
9352
- function selectedGuestLinkInputs(plan, args, whyExtract, linkTrace) {
9353
- const rows = whyExtract.trimEnd().split("\n");
9354
- if (rows.shift() !== "reference extracted symbol")
9355
- throw new Error("invalid wasm-ld extraction report");
9356
- const extracted = new Set(
9357
- rows.map((row) => {
9358
- const fields = row.split(" ");
9359
- if (fields.length !== 3) throw new Error("invalid wasm-ld extraction row");
9360
- return fields[1];
9361
- })
9362
- );
9363
- const traced = new Set(linkTrace.split("\n").filter(Boolean));
9364
- for (const file of extracted)
9365
- if (!traced.has(file))
9366
- throw new Error(`extracted guest input is absent from link trace ${file}`);
9367
- const result = [];
9368
- for (const { artifact, lazy, whole } of occurrences(plan, args)) {
9369
- if (artifact.kind === "object") {
9370
- if (!lazy && !traced.has(artifact.path))
9371
- throw new Error(`eager guest input is absent from link trace ${artifact.path}`);
9372
- if (traced.has(artifact.path))
9373
- result.push({ artifact: artifact.path, member: null });
9374
- continue;
9375
- }
9376
- const prefix = `${artifact.path}(`;
9377
- const names = [...traced].filter((item) => item.startsWith(prefix) && item.endsWith(")")).map((item) => item.slice(prefix.length, -1));
9378
- const members = readArMembers(import_node_fs17.default.readFileSync(artifact.path));
9379
- for (const member of members) {
9380
- if (whole || names.includes(member.name))
9381
- result.push({ artifact: artifact.path, member: member.name });
9382
- }
9383
- for (const name2 of names)
9384
- if (members.filter((member) => member.name === name2).length !== 1)
9385
- throw new Error(
9386
- `ambiguous or unsupported archive member ${artifact.path}(${name2})`
9387
- );
9388
- }
9389
- return result;
9405
+ function isErrnoCode(err, ...codes) {
9406
+ return err instanceof Error && "code" in err && codes.includes(String(err.code));
9390
9407
  }
9391
- function outputPath(args) {
9392
- let output = "";
9393
- for (let i = 0; i < args.length; i++) {
9394
- const arg = args[i];
9395
- if (arg === "-o" || arg === "--output") output = args[++i];
9396
- else if (arg.startsWith("--output=")) output = arg.slice("--output=".length);
9408
+ var DownloadHttpError = class extends Error {
9409
+ retryable;
9410
+ constructor(status, statusText, url) {
9411
+ super(`download failed: ${status} ${statusText} (${url})`);
9412
+ this.retryable = status < 400 || status >= 500 || status === 408 || status === 429;
9397
9413
  }
9398
- if (!output) throw new Error("guest link has no output path");
9399
- return output;
9400
- }
9401
- function withOutput(args, output, discovery) {
9402
- const result = [];
9403
- for (let i = 0; i < args.length; i++) {
9404
- const arg = args[i];
9405
- if (arg === "-o" || arg === "--output") {
9406
- i++;
9407
- continue;
9408
- }
9409
- if (arg.startsWith("--output=")) continue;
9410
- if (discovery && (arg.startsWith("--why-extract=") || arg.startsWith("--Map=")))
9411
- continue;
9412
- result.push(arg);
9413
- }
9414
- result.push("-o", output);
9415
- return result;
9414
+ };
9415
+ async function waitRetryDelay(ms, signal) {
9416
+ signal?.throwIfAborted();
9417
+ await new Promise((resolve, reject) => {
9418
+ const onAbort = () => {
9419
+ clearTimeout(timer);
9420
+ const reason = signal?.reason;
9421
+ reject(
9422
+ reason instanceof Error ? reason : new Error("Download canceled", { cause: reason })
9423
+ );
9424
+ };
9425
+ const timer = setTimeout(() => {
9426
+ signal?.removeEventListener("abort", onAbort);
9427
+ resolve();
9428
+ }, ms);
9429
+ signal?.addEventListener("abort", onAbort, { once: true });
9430
+ });
9416
9431
  }
9417
- function linkGuestImages(options) {
9418
- const { args, directory, wasmLd, clang, llvmAr } = options;
9419
- let plan = options.plan;
9420
- if (!plan.images.some((image) => image.id === options.ledgerDataImage))
9421
- throw new Error(`unknown ledger data image ${options.ledgerDataImage}`);
9422
- import_node_fs17.default.mkdirSync(directory, { recursive: true });
9423
- const discovery = import_node_path17.default.join(directory, "discovery.wasm");
9424
- const whyPath = import_node_path17.default.join(directory, "why-extract.txt");
9425
- const mapPath = import_node_path17.default.join(directory, "discovery.map");
9426
- const runLink = (name2, arguments_) => {
9427
- const response = import_node_path17.default.join(directory, `${name2}.rsp`);
9428
- const trace = import_node_path17.default.join(directory, `${name2}-inputs.txt`);
9429
- import_node_fs17.default.writeFileSync(
9430
- response,
9431
- [...arguments_, "--trace"].map((argument2) => JSON.stringify(argument2)).join(" ")
9432
- );
9433
- const output = import_node_fs17.default.openSync(trace, "w");
9432
+ async function downloadToFile(url, destPath, signal) {
9433
+ import_node_fs18.default.mkdirSync(import_node_path18.default.dirname(destPath), { recursive: true });
9434
+ const tmp = `${destPath}.partial`;
9435
+ for (let attempt = 1; attempt <= 4; attempt++) {
9436
+ signal?.throwIfAborted();
9437
+ let reader2;
9438
+ let handle;
9439
+ let completed = false;
9434
9440
  try {
9435
- (0, import_node_child_process11.execFileSync)(wasmLd, [`@${response}`], { stdio: ["ignore", output, "pipe"] });
9436
- } finally {
9437
- import_node_fs17.default.closeSync(output);
9438
- }
9439
- return import_node_fs17.default.readFileSync(trace, "utf8");
9440
- };
9441
- let discoveryProjection;
9442
- if (options.projection) {
9443
- const source = import_node_path17.default.join(directory, "projection-discovery.c");
9444
- discoveryProjection = import_node_path17.default.join(directory, "projection-discovery.o");
9445
- import_node_fs17.default.writeFileSync(
9446
- source,
9447
- '#include "guest-image-projection.h"\nconst struct peach_guest_image __peach_guest_images[] = {{0}};\nconst uint32_t __peach_guest_image_count = 0;\n'
9448
- );
9449
- (0, import_node_child_process11.execFileSync)(
9450
- clang,
9451
- [...options.projection.clangOptions, "-c", source, "-o", discoveryProjection],
9452
- { stdio: "pipe" }
9453
- );
9454
- }
9455
- const archives = /* @__PURE__ */ new Map();
9456
- const memberBytes = /* @__PURE__ */ new Map();
9457
- const prepare = (provider2) => {
9458
- const trace = runLink("discovery", [
9459
- ...withOutput(args, discovery, true),
9460
- ...discoveryProjection ? [discoveryProjection] : [],
9461
- ...provider2 ? ["--undefined=__peach_dlsym_from_image"] : [],
9462
- `--why-extract=${whyPath}`,
9463
- `--Map=${mapPath}`
9464
- ]);
9465
- const selected2 = selectedGuestLinkInputs(
9466
- plan,
9467
- args,
9468
- import_node_fs17.default.readFileSync(whyPath, "utf8"),
9469
- trace
9470
- );
9471
- if (options.resolvePlan) {
9472
- const identity = (value) => JSON.stringify([
9473
- value.images.map(({ id, name: name2 }) => [id, name2]),
9474
- value.artifacts.map(
9475
- ({
9476
- path: file,
9477
- kind,
9478
- image,
9479
- memberImages,
9480
- memberOrigins,
9481
- instrumentDynamicLookups
9482
- }) => [
9483
- file,
9484
- kind,
9485
- image,
9486
- memberImages ? [...memberImages] : null,
9487
- memberOrigins ? [...memberOrigins] : null,
9488
- instrumentDynamicLookups
9489
- ]
9490
- )
9491
- ]);
9492
- const originalOwnership = identity(plan);
9493
- const resolved = options.resolvePlan(selected2, plan);
9494
- if (identity(resolved) !== originalOwnership)
9495
- throw new Error("resolved guest scopes changed input ownership");
9496
- plan = resolved;
9497
- }
9498
- const objectsByImage = /* @__PURE__ */ new Map();
9499
- for (const image of plan.images) objectsByImage.set(image.id, []);
9500
- const artifacts = new Map(plan.artifacts.map((artifact) => [artifact.path, artifact]));
9501
- for (const item of selected2) {
9502
- const artifact = artifacts.get(item.artifact);
9503
- const image = selectedGuestInputImage(artifact, item.member);
9504
- let bytes;
9505
- if (item.member === null) bytes = import_node_fs17.default.readFileSync(item.artifact);
9506
- else {
9507
- let byName = memberBytes.get(item.artifact);
9508
- if (!byName) {
9509
- const members = readArMembers(import_node_fs17.default.readFileSync(item.artifact));
9510
- archives.set(item.artifact, members);
9511
- byName = /* @__PURE__ */ new Map();
9512
- for (const member of members)
9513
- if (!byName.has(member.name)) byName.set(member.name, member.bytes);
9514
- memberBytes.set(item.artifact, byName);
9441
+ const res = await fetch(url, { signal });
9442
+ if (!res.ok || !res.body) {
9443
+ throw new DownloadHttpError(res.status, res.statusText, url);
9444
+ }
9445
+ reader2 = res.body.getReader();
9446
+ handle = await import_node_fs18.default.promises.open(tmp, "w");
9447
+ let written = 0;
9448
+ for (; ; ) {
9449
+ signal?.throwIfAborted();
9450
+ const { done, value } = await reader2.read();
9451
+ if (done) break;
9452
+ let offset = 0;
9453
+ while (offset < value.byteLength) {
9454
+ const { bytesWritten } = await handle.write(
9455
+ value,
9456
+ offset,
9457
+ value.byteLength - offset
9458
+ );
9459
+ offset += bytesWritten;
9515
9460
  }
9516
- bytes = byName.get(item.member);
9461
+ written += value.byteLength;
9517
9462
  }
9518
- const objects = objectsByImage.get(image);
9519
- if (!objects) throw new Error(`unknown image ${image}`);
9520
- objects.push({
9521
- path: item.member === null ? item.artifact : `${item.artifact}(${item.member})`,
9522
- bytes,
9523
- // the actual loader delegates non-ledger lookups to libc; wrapping its
9524
- // own dlsym call would recurse back into the loader.
9525
- instrumentDynamicLookups: artifact.instrumentDynamicLookups && !guestWasmSymbols(bytes).defined.includes("__peach_dlsym_from_image")
9463
+ await handle.close();
9464
+ handle = void 0;
9465
+ if (!res.headers.get("content-encoding")) {
9466
+ const header = res.headers.get("content-length");
9467
+ const expected = header ? Number(header) : Number.NaN;
9468
+ if (Number.isFinite(expected) && expected > 0 && written !== expected) {
9469
+ throw new Error(`incomplete download (${written}/${expected} bytes): ${url}`);
9470
+ }
9471
+ }
9472
+ signal?.throwIfAborted();
9473
+ import_node_fs18.default.renameSync(tmp, destPath);
9474
+ completed = true;
9475
+ return;
9476
+ } catch (err) {
9477
+ if (handle) await handle.close().catch(() => {
9478
+ });
9479
+ if (reader2 && !completed) await reader2.cancel().catch(() => {
9526
9480
  });
9481
+ try {
9482
+ import_node_fs18.default.unlinkSync(tmp);
9483
+ } catch {
9484
+ }
9485
+ const nonRetryable = err instanceof DownloadHttpError && !err.retryable;
9486
+ if (signal?.aborted || nonRetryable || attempt === 4) throw err;
9487
+ await waitRetryDelay(250 * attempt, signal);
9527
9488
  }
9528
- const ledger2 = createGuestImageLedger({
9529
- images: plan.images.map((image) => ({
9530
- ...image,
9531
- objects: objectsByImage.get(image.id)
9532
- })),
9533
- callers: plan.callers,
9534
- symbols: plan.symbols,
9535
- liveSymbols: linkedMapSymbols(import_node_fs17.default.readFileSync(mapPath, "utf8")),
9536
- commandLineSymbols: commandLineSymbols(args),
9537
- directBindings: plan.directBindings
9489
+ }
9490
+ }
9491
+ async function digestFile(filePath, algorithm, encoding, signal) {
9492
+ const hash = import_node_crypto12.default.createHash(algorithm);
9493
+ await (0, import_promises4.pipeline)(import_node_fs18.default.createReadStream(filePath), hash, { signal });
9494
+ return hash.digest(encoding);
9495
+ }
9496
+ function extractZip(zipPath, destDir, signal) {
9497
+ return runExtractor("ditto", ["-x", "-k", zipPath, destDir], signal);
9498
+ }
9499
+ async function extractTarball(tarPath, zstd, destDir, stripComponents, signal) {
9500
+ const args = [zstd ? "-xf" : "-xzf", "-"];
9501
+ if (stripComponents > 0) args.push(`--strip-components=${stripComponents}`);
9502
+ if (zstd) {
9503
+ const decoder = import_node_zlib2.default.createZstdDecompress({
9504
+ params: { [import_node_zlib2.default.constants.ZSTD_d_windowLogMax]: 30 }
9538
9505
  });
9539
- return { selected: selected2, ledger: ledger2 };
9540
- };
9541
- let prepared = prepare(false);
9542
- const provider = prepared.ledger.callerWrappers.some(
9543
- ({ symbol }) => symbol.startsWith("__peach_dlsym_caller_")
9544
- );
9545
- if (provider) prepared = prepare(true);
9546
- const { selected, ledger } = prepared;
9547
- const replacements = /* @__PURE__ */ new Map();
9548
- const linkedOwners = /* @__PURE__ */ new Map();
9549
- const ledgerObjects = new Map(ledger.objects.map((item) => [item.path, item]));
9550
- for (const [index, artifact] of plan.artifacts.entries()) {
9551
- const prefix = `${artifact.path}(`;
9552
- if (artifact.kind === "object") {
9553
- const object3 = ledgerObjects.get(artifact.path);
9554
- if (!object3) continue;
9555
- const output2 = import_node_path17.default.join(directory, `object-${index}.o`);
9556
- import_node_fs17.default.writeFileSync(output2, object3.bytes);
9557
- replacements.set(artifact.path, output2);
9558
- linkedOwners.set(output2, selectedGuestInputImage(artifact, null));
9559
- continue;
9560
- }
9561
- const members = archives.get(artifact.path);
9562
- if (!members) continue;
9563
- const listed = (0, import_node_child_process11.execFileSync)(llvmAr, ["t", artifact.path], { encoding: "utf8" }).trimEnd().split("\n");
9564
- if (listed.length !== members.length || new Set(listed).size !== listed.length || members.some(
9565
- (member, i) => listed[i] !== member.name || import_node_path17.default.basename(member.name) !== member.name
9566
- ))
9567
- throw new Error(`unsupported archive layout ${artifact.path}`);
9568
- const memberDir = import_node_path17.default.join(directory, `archive-${index}`);
9569
- import_node_fs17.default.mkdirSync(memberDir, { recursive: true });
9570
- const output = import_node_path17.default.join(directory, `archive-${index}.a`);
9571
- const inputs = members.map((member) => {
9572
- const memberOutput = import_node_path17.default.join(memberDir, member.name);
9573
- const rewritten = ledgerObjects.get(`${prefix}${member.name})`);
9574
- import_node_fs17.default.writeFileSync(memberOutput, rewritten?.bytes ?? member.bytes);
9575
- if (rewritten) {
9576
- linkedOwners.set(
9577
- `${output}(${member.name})`,
9578
- selectedGuestInputImage(artifact, member.name)
9579
- );
9580
- }
9581
- return memberOutput;
9506
+ await runExtractor("tar", ["--ignore-zeros", ...args], signal, {
9507
+ cwd: destDir,
9508
+ stdin: (stdin) => (0, import_promises4.pipeline)(import_node_fs18.default.createReadStream(tarPath), decoder, stdin, { signal })
9582
9509
  });
9583
- import_node_fs17.default.rmSync(output, { force: true });
9584
- const response = import_node_path17.default.join(memberDir, "members.rsp");
9585
- import_node_fs17.default.writeFileSync(response, inputs.map((input) => JSON.stringify(input)).join(" "));
9586
- (0, import_node_child_process11.execFileSync)(llvmAr, ["rcs", output, `@${response}`], { stdio: "pipe" });
9587
- replacements.set(artifact.path, output);
9510
+ return;
9588
9511
  }
9589
- const irPath = import_node_path17.default.join(directory, "ledger.ll");
9590
- const ledgerObject = import_node_path17.default.join(directory, "ledger.o");
9591
- import_node_fs17.default.writeFileSync(irPath, ledger.llvmIR);
9592
- (0, import_node_child_process11.execFileSync)(
9593
- clang,
9594
- ["--target=wasm64-unknown-wasip1", "-c", irPath, "-o", ledgerObject],
9595
- { stdio: "pipe" }
9596
- );
9597
- linkedOwners.set(ledgerObject, options.ledgerDataImage);
9598
- let projectionObject;
9599
- let projectionStorage;
9600
- if (options.projection) {
9601
- const projection = options.projection;
9602
- if (!plan.images.some((image) => image.id === projection.image))
9603
- throw new Error("guest projection has no source image");
9604
- if (projection.images.length !== plan.images.length || projection.images.some(
9605
- (image, index) => image.image !== index || plan.images[index]?.id !== index
9606
- ))
9607
- throw new Error("guest projection image order differs from link plan");
9608
- const selectedInputs = selectedGuestManifestInputs(
9609
- plan,
9610
- selected,
9611
- projection.identities
9612
- );
9613
- const images = projection.images.map(
9614
- (image) => createGuestImageManifest({
9615
- ...image,
9616
- inputs: selectedInputs.get(image.image) ?? [],
9617
- linkOptions: projection.linkOptions,
9618
- regions: []
9619
- })
9620
- );
9621
- const ledgerPieces = guestProjectionRegionCapacity([import_node_fs17.default.readFileSync(ledgerObject)], 0);
9622
- const capacities = ledger.images.map((image) => ({
9623
- regions: guestProjectionRegionCapacity(
9624
- image.objects.map((object3) => object3.bytes),
9625
- 1 + ledger.callerWrappers.filter((wrapper) => wrapper.image === image.id).length + (image.id === options.ledgerDataImage ? ledgerPieces : 0) + (image.id === projection.image ? images.length + 2 : 0)
9626
- ),
9627
- memoryProtection: projection.memoryProtection,
9628
- tableProtection: projection.tableProtection
9629
- }));
9630
- projectionStorage = reserveGuestProjectionStorage(images, capacities);
9631
- const projectionSource = import_node_path17.default.join(directory, "projection.c");
9632
- projectionObject = import_node_path17.default.join(directory, "projection.o");
9633
- import_node_fs17.default.writeFileSync(projectionSource, projectionStorage.source);
9634
- (0, import_node_child_process11.execFileSync)(
9635
- clang,
9636
- [...projection.clangOptions, "-c", projectionSource, "-o", projectionObject],
9637
- {
9638
- stdio: "pipe"
9639
- }
9640
- );
9641
- linkedOwners.set(projectionObject, projection.image);
9642
- }
9643
- const byToken = new Map(
9644
- occurrences(plan, args).map(({ artifact, token }) => [
9645
- token,
9646
- replacements.get(artifact.path)
9647
- ])
9648
- );
9649
- const placed = /* @__PURE__ */ new Set();
9650
- const finalArgs = args.map((arg) => byToken.get(arg) ?? arg).filter((arg) => {
9651
- if (!arg.endsWith(".o") && !arg.endsWith(".a")) return true;
9652
- if (placed.has(arg)) return false;
9653
- placed.add(arg);
9654
- return true;
9655
- });
9656
- const finalOutput = import_node_path17.default.join(directory, "final.wasm");
9657
- const finalWhy = import_node_path17.default.join(directory, "final-why-extract.txt");
9658
- const finalTrace = runLink("final", [
9659
- ...withOutput(finalArgs, finalOutput, false),
9660
- ledgerObject,
9661
- ...projectionObject ? [projectionObject] : [],
9662
- ...provider ? ["--undefined=__peach_dlsym_from_image"] : [],
9663
- `--why-extract=${finalWhy}`
9664
- ]);
9665
- const finalSelection = selectedGuestLinkInputs(
9666
- remapGuestLinkPlan(plan, replacements),
9667
- finalArgs,
9668
- import_node_fs17.default.readFileSync(finalWhy, "utf8"),
9669
- finalTrace
9670
- );
9671
- const original = new Map([...replacements].map(([before2, after2]) => [after2, before2]));
9672
- const key = (item) => JSON.stringify([original.get(item.artifact) ?? item.artifact, item.member]);
9673
- const before = new Set(selected.map(key));
9674
- const after = new Set(finalSelection.map(key));
9675
- const changed = [...before].filter((item) => !after.has(item));
9676
- changed.push(...[...after].filter((item) => !before.has(item)));
9677
- if (changed.length)
9678
- throw new Error(
9679
- `guest link selected different inputs after rewriting:
9680
- ${changed.join("\n")}`
9681
- );
9682
- import_node_fs17.default.renameSync(finalOutput, outputPath(args));
9683
- if (projectionStorage && projectionObject)
9684
- options.projection.onReserved(projectionStorage, projectionObject);
9685
- options.onLinkedOwners?.(linkedOwners);
9686
- options.onLinkedSections?.(
9687
- new Map(
9688
- ledger.callerWrappers.map(({ symbol, image }) => [
9689
- `${ledgerObject}:(${symbol})`,
9690
- image
9691
- ])
9692
- )
9693
- );
9694
- return selected;
9695
- }
9696
- function linkedMapSymbols(map) {
9697
- const names = /* @__PURE__ */ new Set();
9698
- for (const match of map.matchAll(/^ +\S+ +[0-9a-f]+ +[0-9a-f]+ {9,}([^\s/<]\S*)/gm))
9699
- names.add(match[1]);
9700
- return names;
9701
- }
9702
- function commandLineSymbols(args) {
9703
- const names = [];
9704
- for (const [i, arg] of args.entries()) {
9705
- if (arg === "--entry" || arg === "-e" || arg === "-u") names.push(args[i + 1]);
9706
- else
9707
- for (const flag of [
9708
- "--entry=",
9709
- "--undefined=",
9710
- "--export=",
9711
- "--export-if-defined="
9712
- ])
9713
- if (arg.startsWith(flag)) names.push(arg.slice(flag.length));
9714
- }
9715
- return names;
9716
- }
9717
- function normalizedGuestLinkArgs(input) {
9718
- const args = [];
9719
- for (let i = 0; i < input.length; i++) {
9720
- const arg = input[i];
9721
- if (arg === "-l" || arg === "--library") args.push(`-l${input[++i]}`);
9722
- else if (arg === "-L" || arg === "--library-path") args.push(`-L${input[++i]}`);
9723
- else if (arg.startsWith("--library=")) args.push(`-l${arg.slice(10)}`);
9724
- else if (arg.startsWith("--library-path=")) args.push(`-L${arg.slice(15)}`);
9725
- else args.push(arg);
9512
+ const archive = import_node_fs18.default.openSync(tarPath, "r");
9513
+ try {
9514
+ await runExtractor("tar", args, signal, { cwd: destDir, stdin: archive });
9515
+ } finally {
9516
+ import_node_fs18.default.closeSync(archive);
9726
9517
  }
9727
- return args;
9728
- }
9729
- function aliasGuestLinkArguments(input, archives) {
9730
- const args = normalizedGuestLinkArgs(input);
9731
- const directories = args.filter((arg) => arg.startsWith("-L")).map((arg) => arg.slice(2));
9732
- const aliases = new Map(
9733
- archives.map((archive) => [import_node_path17.default.resolve(archive.source), archive.archive])
9734
- );
9735
- if (aliases.size !== archives.length)
9736
- throw new Error("duplicate original guest archive");
9737
- const used = /* @__PURE__ */ new Set();
9738
- const result = args.map((arg) => {
9739
- let file = arg;
9740
- if (arg.startsWith("-l") && arg.length > 2) {
9741
- const name2 = arg.slice(2);
9742
- const library = name2.startsWith(":") ? name2.slice(1) : `lib${name2}.a`;
9743
- file = directories.map((directory) => import_node_path17.default.join(directory, library)).find((candidate) => import_node_fs17.default.existsSync(candidate)) ?? arg;
9744
- }
9745
- if (file.startsWith("-")) return arg;
9746
- const source = import_node_path17.default.resolve(file);
9747
- const alias = aliases.get(source);
9748
- if (alias === void 0) return arg;
9749
- used.add(source);
9750
- return alias;
9751
- });
9752
- if (used.size !== aliases.size)
9753
- throw new Error("aliased guest archive is not a link input");
9754
- return result;
9755
9518
  }
9756
- function linkCompleteGuestImages(options) {
9757
- const args = normalizedGuestLinkArgs(options.args);
9758
- const unowned = unownedGuestLinkInputs(options.plan, args);
9759
- const candidates = unowned.map((file) => {
9760
- const descriptor = import_node_fs17.default.openSync(file, "r");
9761
- const magic = Buffer.alloc(8);
9762
- try {
9763
- import_node_fs17.default.readSync(descriptor, magic, 0, magic.length, 0);
9764
- } finally {
9765
- import_node_fs17.default.closeSync(descriptor);
9766
- }
9767
- return {
9768
- path: file,
9769
- kind: magic.toString("ascii") === "!<arch>\n" ? "archive" : "object",
9770
- image: null,
9771
- instrumentDynamicLookups: false
9772
- };
9773
- });
9774
- return linkGuestImages({
9775
- ...options,
9776
- args,
9777
- plan: { ...options.plan, artifacts: [...options.plan.artifacts, ...candidates] }
9519
+ async function runExtractor(command, args, signal, input) {
9520
+ signal?.throwIfAborted();
9521
+ const stdin = input?.stdin;
9522
+ const stdio = [
9523
+ typeof stdin === "function" ? "pipe" : stdin ?? "ignore",
9524
+ "inherit",
9525
+ "inherit"
9526
+ ];
9527
+ const child = (0, import_node_child_process11.spawn)(command, args, {
9528
+ cwd: input?.cwd,
9529
+ stdio,
9530
+ detached: process.platform !== "win32"
9778
9531
  });
9779
- }
9780
- function discoverGuestLinkInputs(options) {
9781
- const args = normalizedGuestLinkArgs(options.args);
9782
- const artifacts = guestLinkInputFiles(args).map((file) => {
9783
- const descriptor = import_node_fs17.default.openSync(file, "r");
9784
- const magic = Buffer.alloc(8);
9785
- try {
9786
- import_node_fs17.default.readSync(descriptor, magic, 0, magic.length, 0);
9787
- } finally {
9788
- import_node_fs17.default.closeSync(descriptor);
9789
- }
9790
- const kind = magic.toString("ascii") === "!<arch>\n" ? "archive" : "object";
9791
- return { path: file, kind, image: 0, instrumentDynamicLookups: false };
9532
+ const fed = typeof stdin === "function" && child.stdin ? stdin(child.stdin) : void 0;
9533
+ void fed?.catch(() => {
9792
9534
  });
9793
- const plan = { images: [], callers: [], artifacts, symbols: [] };
9794
- import_node_fs17.default.mkdirSync(options.directory, { recursive: true });
9795
- const why = import_node_path17.default.join(options.directory, "preselection-why.txt");
9796
- const response = import_node_path17.default.join(options.directory, "preselection.rsp");
9797
- const output = import_node_path17.default.join(options.directory, "preselection.wasm");
9798
- const flags = [
9799
- ...withOutput(args, output, true),
9800
- ...options.objects,
9801
- // the loader runtime backs every image's lookup wrappers, so it belongs to
9802
- // the selection that assigns member owners.
9803
- "--undefined=__peach_dlsym_from_image",
9804
- `--why-extract=${why}`,
9805
- "--trace"
9806
- ];
9807
- import_node_fs17.default.writeFileSync(response, flags.map((flag) => JSON.stringify(flag)).join(" "));
9808
- const trace = import_node_path17.default.join(options.directory, "preselection-inputs.txt");
9809
- const traceOutput = import_node_fs17.default.openSync(trace, "w");
9535
+ let stopping;
9536
+ const abort = () => {
9537
+ stopping ??= terminateProcessGroup(child, "SIGKILL", 0);
9538
+ void stopping.catch(() => {
9539
+ });
9540
+ };
9810
9541
  try {
9811
- (0, import_node_child_process11.execFileSync)(options.wasmLd, [`@${response}`], {
9812
- stdio: ["ignore", traceOutput, "pipe"]
9542
+ await new Promise((resolve, reject) => {
9543
+ let failure;
9544
+ child.on("error", (error) => {
9545
+ failure = error;
9546
+ });
9547
+ child.on("close", (code) => {
9548
+ if (signal?.aborted) {
9549
+ const reason = signal.reason;
9550
+ reject(
9551
+ reason instanceof Error ? reason : new Error("Extraction canceled", { cause: reason })
9552
+ );
9553
+ } else if (failure) reject(failure);
9554
+ else if (code === 0) resolve();
9555
+ else reject(new Error(`${command} exited with code ${code}`));
9556
+ });
9557
+ signal?.addEventListener("abort", abort, { once: true });
9558
+ if (signal?.aborted) abort();
9813
9559
  });
9560
+ await fed;
9814
9561
  } finally {
9815
- import_node_fs17.default.closeSync(traceOutput);
9562
+ signal?.removeEventListener("abort", abort);
9563
+ await stopping;
9816
9564
  }
9817
- return selectedGuestLinkInputs(
9818
- plan,
9819
- args,
9820
- import_node_fs17.default.readFileSync(why, "utf8"),
9821
- import_node_fs17.default.readFileSync(trace, "utf8")
9822
- );
9823
9565
  }
9824
- function prepareGuestRuntimeInputs(options) {
9825
- const originals = new Map(
9826
- [...options.rewritten].map(([before, after]) => [
9827
- import_node_path17.default.resolve(after),
9828
- import_node_path17.default.resolve(before)
9829
- ])
9830
- );
9831
- if (originals.size !== options.rewritten.size)
9832
- throw new Error("ambiguous rewritten runtime input");
9833
- const recordedArchives = new Set(
9834
- options.products.flatMap(
9835
- ({ product, root }) => product.artifacts.flatMap(
9836
- (artifact) => artifact.kind === "archive" ? [import_node_path17.default.resolve(root, artifact.path)] : []
9837
- )
9838
- )
9839
- );
9840
- const archives = [];
9841
- for (const file of guestLinkInputFiles(normalizedGuestLinkArgs(options.args))) {
9842
- const original = originals.get(file) ?? file;
9843
- if (!recordedArchives.has(original)) continue;
9844
- const members = readArMembers(import_node_fs17.default.readFileSync(file));
9845
- if (new Set(members.map((member) => member.name)).size === members.length) continue;
9846
- archives.push(
9847
- aliasGuestArchive({
9848
- archive: file,
9849
- directory: import_node_path17.default.join(options.directory, `archive-${archives.length}`),
9850
- llvmAr: options.llvmAr
9851
- })
9852
- );
9566
+
9567
+ // src/binaryen.lock.json
9568
+ var binaryen_lock_default = {
9569
+ version: "132",
9570
+ licenseSha256: "64c0d02491e16eced74826440ecd2bcf7722d37fa586faf457b2494293afbffe",
9571
+ platforms: {
9572
+ "linux-x64": {
9573
+ asset: "x86_64-linux",
9574
+ upstreamSha256: "195ddc94f9bc89f45abdabb0b9eea86023d727ba90eac8b35b80f2544fc30572",
9575
+ sha256: "0396b1a540e9f97f30eb6a378d829305c218c821a0bd88c74e83d3d6923dad0b"
9576
+ },
9577
+ "linux-arm64": {
9578
+ asset: "aarch64-linux",
9579
+ upstreamSha256: "c58562417836c5d0493d89bdefc434933bdc097db641b483df86bcfa557a107f",
9580
+ sha256: "25e3747f19614b0281a28b9a909ddc602b546ccdfacebc8cae2f7165665328fa"
9581
+ },
9582
+ "darwin-arm64": {
9583
+ asset: "arm64-macos",
9584
+ upstreamSha256: "98aad827847af7ef990ed7098d885725c8e5b5aae75073403635617ae4e259aa",
9585
+ sha256: "34281566fe32df71337aaf0b60aa265dc853587d92bda0b5b1fac8aed8c2f8ab"
9586
+ }
9853
9587
  }
9854
- const args = aliasGuestLinkArguments(options.args, archives);
9855
- const selected = discoverGuestLinkInputs({
9856
- args,
9857
- directory: options.directory,
9858
- wasmLd: options.wasmLd,
9859
- objects: options.discoveryObjects
9860
- });
9861
- const closure = guestRuntimeProductsForInputs({
9862
- products: options.products,
9863
- selected: originalGuestArchiveSelections(selected, archives),
9864
- rewritten: options.rewritten,
9865
- sdk: options.sdk,
9866
- firstImage: options.firstImage,
9867
- containingImage: options.containingImage,
9868
- framework: options.framework
9869
- });
9870
- const aliasSources = new Set(
9871
- archives.map(
9872
- (archive) => originals.get(import_node_path17.default.resolve(archive.source)) ?? import_node_path17.default.resolve(archive.source)
9873
- )
9874
- );
9875
- const sdkProducts = {
9876
- products: options.products,
9877
- images: closure.images,
9878
- containingImages: closure.containingImages,
9879
- linkedArchives: closure.linkedArchives.filter(
9880
- (archive) => !aliasSources.has(import_node_path17.default.resolve(archive))
9881
- )
9882
- };
9883
- const archiveArtifacts = guestAliasedSdkArchiveArtifacts({
9884
- products: options.products,
9885
- archives,
9886
- selected,
9887
- rewritten: options.rewritten,
9888
- images: new Map([...closure.images, ...closure.containingImages])
9889
- });
9890
- return { args, selected, archives, sdkProducts, archiveArtifacts };
9588
+ };
9589
+
9590
+ // src/home-paths.ts
9591
+ var import_node_crypto13 = require("node:crypto");
9592
+ var import_node_fs19 = __toESM(require("node:fs"), 1);
9593
+ var import_node_os6 = require("node:os");
9594
+ var import_node_path19 = __toESM(require("node:path"), 1);
9595
+ var PEACH_HOME_ENV = "PEACH_HOME";
9596
+ function ambientHomeDir() {
9597
+ return import_node_path19.default.join((0, import_node_os6.homedir)(), ".peach");
9891
9598
  }
9892
- function selectedGuestSymbolInputs(plan, selected) {
9893
- const artifacts = new Map(plan.artifacts.map((artifact) => [artifact.path, artifact]));
9894
- const archives = /* @__PURE__ */ new Map();
9895
- const symbols = /* @__PURE__ */ new Set();
9896
- const hostImports = /* @__PURE__ */ new Set();
9897
- const tags = /* @__PURE__ */ new Set();
9898
- const definitions = /* @__PURE__ */ new Set();
9899
- const owners = /* @__PURE__ */ new Map();
9900
- const weakReferences = /* @__PURE__ */ new Map();
9901
- const weakDefinitions = /* @__PURE__ */ new Map();
9902
- const definitionObjects = /* @__PURE__ */ new Map();
9903
- for (const item of selected) {
9904
- const artifact = artifacts.get(item.artifact);
9905
- if (!artifact) throw new Error(`selected symbol input has no owner ${item.artifact}`);
9906
- let bytes;
9907
- let name2 = item.artifact;
9908
- if (item.member === null) bytes = import_node_fs17.default.readFileSync(item.artifact);
9909
- else {
9910
- let members = archives.get(item.artifact);
9911
- if (!members) {
9912
- members = Map.groupBy(
9913
- readArMembers(import_node_fs17.default.readFileSync(item.artifact)),
9914
- (member) => member.name
9915
- );
9916
- archives.set(item.artifact, members);
9917
- }
9918
- const matching = members.get(item.member) ?? [];
9919
- if (matching.length !== 1)
9920
- throw new Error(
9921
- `ambiguous selected symbol input ${item.artifact}(${item.member})`
9922
- );
9923
- bytes = matching[0].bytes;
9924
- name2 += `(${item.member})`;
9925
- }
9926
- if (owners.has(name2)) throw new Error(`duplicate selected symbol input ${name2}`);
9927
- owners.set(name2, selectedGuestInputImage(artifact, item.member));
9928
- const names = guestWasmSymbols(bytes);
9929
- weakReferences.set(name2, new Set(names.weakUndefined));
9930
- weakDefinitions.set(name2, new Set(names.weakDefined));
9931
- for (const symbol of names.undefined) symbols.add(symbol);
9932
- for (const symbol of names.hostImports) hostImports.add(symbol);
9933
- for (const symbol of names.tags) tags.add(symbol);
9934
- for (const symbol of names.defined) {
9935
- definitions.add(symbol);
9936
- const objects = definitionObjects.get(symbol) ?? /* @__PURE__ */ new Set();
9937
- objects.add(name2);
9938
- definitionObjects.set(symbol, objects);
9939
- }
9599
+ function rnxHomeDir() {
9600
+ const override = process.env[PEACH_HOME_ENV];
9601
+ return override && override.length > 0 ? import_node_path19.default.resolve(override) : ambientHomeDir();
9602
+ }
9603
+ var DAEMON_LOCKFILE_MAX_BYTES = 16 * 1024;
9604
+
9605
+ // src/wasm-narrow-boundary.ts
9606
+ var I64 = 126;
9607
+ var VALUE_TYPES = /* @__PURE__ */ new Map([
9608
+ [127, "i32"],
9609
+ [I64, "i64"],
9610
+ [125, "f32"],
9611
+ [124, "f64"],
9612
+ [123, "v128"],
9613
+ [112, "funcref"],
9614
+ [111, "externref"]
9615
+ ]);
9616
+ var GUEST = "guest";
9617
+ var BOUNDARY = "boundary";
9618
+ var WIDE = "$wide.";
9619
+ var NARROW = "$narrow.";
9620
+ function encodeNumber2(value) {
9621
+ const bytes = [];
9622
+ for (let rest = value; ; ) {
9623
+ const byte = rest % 128;
9624
+ rest = Math.floor(rest / 128);
9625
+ if (rest === 0) return [...bytes, byte];
9626
+ bytes.push(byte | 128);
9940
9627
  }
9628
+ }
9629
+ function encodeName(name2) {
9630
+ const bytes = [...Buffer.from(name2)];
9631
+ return [...encodeNumber2(bytes.length), ...bytes];
9632
+ }
9633
+ function reader(bytes, start, end) {
9634
+ let at = start;
9635
+ const number3 = () => {
9636
+ let value = 0;
9637
+ for (let shift = 0; ; shift += 7) {
9638
+ if (at >= end || shift > 63) throw new Error("invalid wasm integer");
9639
+ const byte = bytes[at++];
9640
+ value += (byte & 127) * 2 ** shift;
9641
+ if (!(byte & 128)) return value;
9642
+ }
9643
+ };
9941
9644
  return {
9942
- symbols: [...symbols].filter((symbol) => !tags.has(symbol)),
9943
- definitions: [...definitions].filter((symbol) => !tags.has(symbol)),
9944
- hostImports,
9945
- owners,
9946
- weakReferences,
9947
- weakDefinitions,
9948
- definitionObjects
9645
+ number: number3,
9646
+ byte: () => {
9647
+ if (at >= end) throw new Error("truncated wasm section");
9648
+ return bytes[at++];
9649
+ },
9650
+ name: () => {
9651
+ const length = number3();
9652
+ at += length;
9653
+ if (at > end) throw new Error("truncated wasm name");
9654
+ return Buffer.from(bytes.subarray(at - length, at)).toString();
9655
+ },
9656
+ position: () => at,
9657
+ done: () => at === end
9949
9658
  };
9950
9659
  }
9951
- function verifyGuestSymbolScopes(options) {
9952
- const symbols = [...new Set(options.symbols)];
9953
- const requested = new Set(symbols);
9954
- if (symbols.some((symbol) => !symbol || symbol.includes("\0") || symbol.includes("\n")))
9955
- throw new Error("invalid traced guest symbol");
9956
- if (!symbols.length) return { bindings: [], directBindings: [] };
9957
- import_node_fs17.default.mkdirSync(options.directory, { recursive: true });
9958
- const response = import_node_path17.default.join(options.directory, "scope-trace.rsp");
9959
- const output = import_node_path17.default.join(options.directory, "scope-trace.wasm");
9960
- const args = [
9961
- ...withOutput(normalizedGuestLinkArgs(options.args), output, true),
9962
- ...options.objects,
9963
- ...symbols.map((symbol) => `--trace-symbol=${symbol}`)
9964
- ];
9965
- import_node_fs17.default.writeFileSync(response, args.map((arg) => JSON.stringify(arg)).join(" "));
9966
- const tracePath = import_node_path17.default.join(options.directory, "scope-trace.txt");
9967
- const traceOutput = import_node_fs17.default.openSync(tracePath, "w");
9968
- try {
9969
- (0, import_node_child_process11.execFileSync)(options.wasmLd, [`@${response}`], {
9970
- stdio: ["ignore", traceOutput, "pipe"]
9971
- });
9972
- } finally {
9973
- import_node_fs17.default.closeSync(traceOutput);
9660
+ function sections(bytes) {
9661
+ if (Buffer.from(bytes.subarray(0, 8)).toString("hex") !== "0061736d01000000")
9662
+ throw new Error("not a wasm module");
9663
+ const found = [];
9664
+ for (let at = 8; at < bytes.length; ) {
9665
+ const header = reader(bytes, at, bytes.length);
9666
+ const id = header.byte();
9667
+ const size = header.number();
9668
+ const start = header.position();
9669
+ found.push({ id, start, end: start + size });
9670
+ at = start + size;
9974
9671
  }
9975
- const records = /* @__PURE__ */ new Map();
9976
- const consume = (line) => {
9977
- const match = /^(.*): (reference to|definition of) (.*)$/.exec(line);
9978
- if (!match) return;
9979
- const [, object3, kind, symbol] = match;
9980
- if (!requested.has(symbol)) return;
9981
- if (options.hostImports.has(symbol)) return;
9982
- const record = records.get(symbol) ?? {
9983
- references: /* @__PURE__ */ new Map(),
9984
- providers: /* @__PURE__ */ new Map(),
9985
- physicalModule: false
9986
- };
9987
- if (object3 === "<internal>") {
9988
- if (kind === "definition of") record.physicalModule = true;
9989
- } else {
9990
- const image = options.owners.get(object3);
9991
- if (image === void 0)
9992
- throw new Error(`traced guest object has no owner ${object3}`);
9993
- (kind === "reference to" ? record.references : record.providers).set(
9994
- object3,
9995
- image
9996
- );
9997
- }
9998
- records.set(symbol, record);
9672
+ return found;
9673
+ }
9674
+ function withSections(bytes, layout2, replacements) {
9675
+ const parts = [bytes.subarray(0, 8)];
9676
+ let at = 8;
9677
+ for (const section of layout2) {
9678
+ const body = replacements.get(section.id);
9679
+ parts.push(
9680
+ body ? Uint8Array.from([section.id, ...encodeNumber2(body.length), ...body]) : bytes.subarray(at, section.end)
9681
+ );
9682
+ at = section.end;
9683
+ }
9684
+ return Buffer.concat(parts);
9685
+ }
9686
+ var quoted = (name2) => `"${[...Buffer.from(name2)].map((byte) => `\\${byte.toString(16).padStart(2, "0")}`).join("")}"`;
9687
+ var signature = (types, keyword, narrow) => types.length === 0 ? "" : ` (${keyword} ${types.map((type) => {
9688
+ const name2 = VALUE_TYPES.get(narrow && type === I64 ? 127 : type);
9689
+ if (!name2) throw new Error(`unsupported wasm boundary type ${type}`);
9690
+ return name2;
9691
+ }).join(" ")})`;
9692
+ var wide = (type) => type.parameters.includes(I64) || type.results.includes(I64);
9693
+ function narrowWasmBoundary(bytes) {
9694
+ const layout2 = sections(bytes);
9695
+ const section = (id) => {
9696
+ const found = layout2.find((entry) => entry.id === id);
9697
+ return found && reader(bytes, found.start, found.end);
9999
9698
  };
10000
- const traceInput = import_node_fs17.default.openSync(tracePath, "r");
10001
- try {
10002
- const decoder = new import_node_string_decoder.StringDecoder("utf8");
10003
- const buffer = Buffer.allocUnsafe(64 * 1024);
10004
- let pending = "";
10005
- let count;
10006
- while ((count = import_node_fs17.default.readSync(traceInput, buffer, 0, buffer.length, null)) > 0) {
10007
- pending += decoder.write(buffer.subarray(0, count));
10008
- let end;
10009
- while ((end = pending.indexOf("\n")) !== -1) {
10010
- consume(pending.slice(0, end));
10011
- pending = pending.slice(end + 1);
10012
- }
9699
+ const types = [];
9700
+ const typeSection = section(1);
9701
+ if (typeSection) {
9702
+ for (let count = typeSection.number(); count > 0; count--) {
9703
+ if (typeSection.byte() !== 96) throw new Error("unsupported wasm type");
9704
+ const values = () => Array.from({ length: typeSection.number() }, () => typeSection.byte());
9705
+ types.push({ parameters: values(), results: values() });
10013
9706
  }
10014
- consume(pending + decoder.end());
10015
- } finally {
10016
- import_node_fs17.default.closeSync(traceInput);
10017
9707
  }
10018
- const callers = new Map(options.callers.map((caller) => [caller.image, caller.next]));
10019
- const result = [];
10020
- const directBindings = [];
10021
- for (const symbol of symbols) {
10022
- const record = records.get(symbol);
10023
- if (!record || !record.references.size) continue;
10024
- if (!record.providers.size && options.hostImports.has(symbol)) continue;
10025
- const startupReferences = [...record.references].filter(
10026
- ([object3]) => options.startupObjects.has(object3) && options.weakReferences.get(object3)?.has(symbol)
10027
- );
10028
- const otherReferences = [...record.references].filter(
10029
- ([object3]) => !startupReferences.some(([startup]) => startup === object3)
10030
- );
10031
- for (const [, caller] of startupReferences)
10032
- if (!callers.has(caller))
10033
- throw new Error(`guest image has no caller scope ${caller}`);
10034
- if (startupReferences.length && !record.physicalModule) {
10035
- const candidates = options.definitionObjects.get(symbol) ?? /* @__PURE__ */ new Set();
10036
- if (candidates.size > 1 || record.providers.size > 1)
10037
- throw new Error(`ambiguous startup provider ${symbol}`);
10038
- if (candidates.size !== record.providers.size || [...record.providers.keys()].some((object3) => !candidates.has(object3)))
10039
- throw new Error(`unproven startup provider ${symbol}`);
10040
- if (record.providers.size === 1) {
10041
- const [providerObject, providerImage] = [...record.providers][0];
10042
- if (options.weakDefinitions.get(providerObject)?.has(symbol))
10043
- throw new Error(`weak startup provider ${symbol}`);
10044
- for (const [object3] of startupReferences)
10045
- directBindings.push({ object: object3, symbol, providerObject, providerImage });
10046
- }
10047
- if (!otherReferences.length) continue;
9708
+ const typeAt = (index) => {
9709
+ const type = types[index];
9710
+ if (!type) throw new Error("invalid wasm type index");
9711
+ return type;
9712
+ };
9713
+ const thunks = [];
9714
+ const functionTypes = [];
9715
+ const importBody = [];
9716
+ const importSection = section(2);
9717
+ if (importSection) {
9718
+ const count = importSection.number();
9719
+ importBody.push(...encodeNumber2(count));
9720
+ for (let index = 0; index < count; index++) {
9721
+ const module2 = importSection.name();
9722
+ const name2 = importSection.name();
9723
+ const start = importSection.position();
9724
+ const kind = importSection.byte();
9725
+ const limits = () => {
9726
+ const flags = importSection.number();
9727
+ importSection.number();
9728
+ if (flags & 1) importSection.number();
9729
+ };
9730
+ let type;
9731
+ if (kind === 0) {
9732
+ type = typeAt(importSection.number());
9733
+ functionTypes.push(type);
9734
+ } else if (kind === 1) {
9735
+ importSection.byte();
9736
+ limits();
9737
+ } else if (kind === 2) limits();
9738
+ else if (kind === 3) {
9739
+ importSection.byte();
9740
+ importSection.byte();
9741
+ } else if (kind === 4) {
9742
+ importSection.byte();
9743
+ importSection.number();
9744
+ } else throw new Error("unsupported wasm import");
9745
+ const scalar64 = (parameter) => module2 === "wasi_snapshot_preview1" && (!name2.startsWith("peach_") || name2 === "peach_fs_path_birthtime_set" && parameter === 2) || module2 === "peach" && name2 === "hw_memsize" && parameter === null || module2 === "peach_notify" && name2 === "set" && parameter === 1;
9746
+ const parameters = type?.parameters.map(
9747
+ (value, index2) => value === I64 && !scalar64(index2) ? 127 : value
9748
+ );
9749
+ const results = type?.results.map(
9750
+ (value) => value === I64 && !scalar64(null) ? 127 : value
9751
+ );
9752
+ if (type && parameters && results && (parameters.some((value, index2) => value !== type.parameters[index2]) || results.some((value, index2) => value !== type.results[index2]))) {
9753
+ if (type.results.length > 1)
9754
+ throw new Error(`import ${module2}.${name2} returns several values`);
9755
+ const id = thunks.length;
9756
+ const call = `(call $host${id}${type.parameters.map(
9757
+ (value, at) => value !== parameters[at] ? ` (i32.wrap_i64 (local.get ${at}))` : ` (local.get ${at})`
9758
+ ).join("")})`;
9759
+ thunks.push(
9760
+ `(import ${quoted(module2)} ${quoted(name2)} (func $host${id}${signature(parameters, "param", false)}${signature(results, "result", false)}))`,
9761
+ `(func (export "${NARROW}${id}")${signature(type.parameters, "param", false)}${signature(type.results, "result", false)} ${type.results[0] !== results[0] ? `(i64.extend_i32_u ${call})` : call})`
9762
+ );
9763
+ importBody.push(...encodeName(BOUNDARY), ...encodeName(`${NARROW}${id}`));
9764
+ } else importBody.push(...encodeName(module2), ...encodeName(name2));
9765
+ importBody.push(...bytes.subarray(start, importSection.position()));
10048
9766
  }
10049
- if (!record.providers.size && !record.physicalModule && [...record.references.keys()].every(
10050
- (object3) => options.weakReferences.get(object3)?.has(symbol)
10051
- ))
10052
- continue;
10053
- const providerImages = new Set(record.providers.values());
10054
- const copies = [...options.definitionObjects.get(symbol) ?? []].flatMap(
10055
- (object3) => {
10056
- const image = options.owners.get(object3);
10057
- return image === void 0 ? [] : [{ image, weak: !!options.weakDefinitions.get(object3)?.has(symbol) }];
10058
- }
9767
+ if (!importSection.done()) throw new Error("invalid wasm imports");
9768
+ }
9769
+ const functionSection = section(3);
9770
+ if (functionSection)
9771
+ for (let count = functionSection.number(); count > 0; count--)
9772
+ functionTypes.push(typeAt(functionSection.number()));
9773
+ const exportBody = [];
9774
+ const exportSection = section(7);
9775
+ if (exportSection) {
9776
+ const count = exportSection.number();
9777
+ exportBody.push(...encodeNumber2(count));
9778
+ for (let index = 0; index < count; index++) {
9779
+ const name2 = exportSection.name();
9780
+ const kind = exportSection.byte();
9781
+ const target = exportSection.number();
9782
+ const type = kind === 0 ? functionTypes[target] : void 0;
9783
+ if (kind === 0 && !type) throw new Error("invalid wasm export");
9784
+ if (type && wide(type)) {
9785
+ if (type.results.length > 1)
9786
+ throw new Error(`export ${name2} returns several values`);
9787
+ const id = thunks.length;
9788
+ const call = `(call $guest${id}${type.parameters.map(
9789
+ (value, at) => value === I64 ? ` (i64.extend_i32_u (local.get ${at}))` : ` (local.get ${at})`
9790
+ ).join("")})`;
9791
+ thunks.push(
9792
+ `(import "${GUEST}" "${WIDE}${id}" (func $guest${id}${signature(type.parameters, "param", false)}${signature(type.results, "result", false)}))`,
9793
+ `(func (export ${quoted(name2)})${signature(type.parameters, "param", true)}${signature(type.results, "result", true)} ${type.results[0] === I64 ? `(i32.wrap_i64 ${call})` : call})`
9794
+ );
9795
+ exportBody.push(...encodeName(`${WIDE}${id}`));
9796
+ } else exportBody.push(...encodeName(name2));
9797
+ exportBody.push(kind, ...encodeNumber2(target));
9798
+ }
9799
+ if (!exportSection.done()) throw new Error("invalid wasm exports");
9800
+ }
9801
+ if (thunks.length === 0) return void 0;
9802
+ const imports = thunks.filter((line) => line.startsWith("(import"));
9803
+ const functions = thunks.filter((line) => !line.startsWith("(import"));
9804
+ return {
9805
+ module: withSections(
9806
+ bytes,
9807
+ layout2,
9808
+ /* @__PURE__ */ new Map([
9809
+ [2, importBody],
9810
+ [7, exportBody]
9811
+ ])
9812
+ ),
9813
+ thunks: `(module
9814
+ ${[...imports, ...functions].join("\n")}
9815
+ )
9816
+ `
9817
+ };
9818
+ }
9819
+ var NARROW_MERGE_NAMES = { guest: GUEST, boundary: BOUNDARY };
9820
+ function dropBoundaryExports(bytes) {
9821
+ const layout2 = sections(bytes);
9822
+ const found = layout2.find((entry) => entry.id === 7);
9823
+ if (!found) throw new Error("merged module has no exports");
9824
+ const exportSection = reader(bytes, found.start, found.end);
9825
+ const kept = [];
9826
+ for (let count = exportSection.number(); count > 0; count--) {
9827
+ const name2 = exportSection.name();
9828
+ const kind = exportSection.byte();
9829
+ const target = exportSection.number();
9830
+ if (!name2.startsWith(WIDE) && !name2.startsWith(NARROW))
9831
+ kept.push([...encodeName(name2), kind, ...encodeNumber2(target)]);
9832
+ }
9833
+ return withSections(
9834
+ bytes,
9835
+ layout2,
9836
+ /* @__PURE__ */ new Map([[7, [...encodeNumber2(kept.length), ...kept.flat()]]])
9837
+ );
9838
+ }
9839
+
9840
+ // src/wasm-optimize.ts
9841
+ var FEATURES = [
9842
+ "memory64",
9843
+ "threads",
9844
+ "bulk-memory",
9845
+ "bulk-memory-opt",
9846
+ "call-indirect-overlong",
9847
+ "exception-handling",
9848
+ "multivalue",
9849
+ "mutable-globals",
9850
+ "nontrapping-float-to-int",
9851
+ "reference-types",
9852
+ "sign-ext"
9853
+ ];
9854
+ var KEEP_WASM_NAMES = process.env.PEACH_SWIFT_NAMES === "1";
9855
+ var LOWERING = ["--memory64-lowering", "--table64-lowering"];
9856
+ var BINARYEN_VERSION = binaryen_lock_default.version;
9857
+ var runBinaryen = (0, import_node_util2.promisify)(import_node_child_process12.execFile);
9858
+ var WASM_LOWER_IDENTITY = `binaryen ${BINARYEN_VERSION} narrow ${LOWERING.join(" ")} ${FEATURES.join(",")} unoptimized-names`;
9859
+ var BINARYEN_RELEASES = new Map(Object.entries(binaryen_lock_default.platforms));
9860
+ async function runWasmOpt(file, output, optimize, skipPasses, binary) {
9861
+ const admittedCores = windowAdmission()?.cores ?? Number(process.env.TM_EXEC_CPU_CORES);
9862
+ const requestedCores = Number(process.env.BINARYEN_CORES);
9863
+ const environment = { ...process.env };
9864
+ if (Number.isInteger(admittedCores) && admittedCores > 0)
9865
+ environment.BINARYEN_CORES = String(
9866
+ Number.isInteger(requestedCores) && requestedCores > 0 ? Math.min(admittedCores, requestedCores) : admittedCores
10059
9867
  );
10060
- const copyImages = new Set(copies.map((copy) => copy.image));
10061
- const strongImages = new Set(
10062
- copies.filter((copy) => !copy.weak).map((copy) => copy.image)
9868
+ const features = FEATURES.map((feature) => `--enable-${feature}`);
9869
+ const names = optimize && !KEEP_WASM_NAMES ? [] : ["-g"];
9870
+ const narrowed = narrowWasmBoundary((0, import_node_fs20.readFileSync)(file));
9871
+ const merged = `${output}.narrowed`;
9872
+ if (narrowed) {
9873
+ const guest = `${output}.guest`;
9874
+ const thunks = `${output}.thunks.wat`;
9875
+ (0, import_node_fs20.writeFileSync)(guest, narrowed.module);
9876
+ (0, import_node_fs20.writeFileSync)(thunks, narrowed.thunks);
9877
+ await runBinaryen(
9878
+ (0, import_node_path20.join)((0, import_node_path20.dirname)(binary), "wasm-merge"),
9879
+ [
9880
+ ...features,
9881
+ ...names,
9882
+ guest,
9883
+ NARROW_MERGE_NAMES.guest,
9884
+ thunks,
9885
+ NARROW_MERGE_NAMES.boundary,
9886
+ "-o",
9887
+ merged
9888
+ ],
9889
+ { env: environment }
10063
9890
  );
10064
- const interposed = !record.physicalModule && copyImages.size > 1 && strongImages.size <= 1;
10065
- const providerCount = interposed ? 1 : providerImages.size + Number(record.physicalModule);
10066
- if (!providerCount) continue;
10067
- if (providerCount !== 1)
10068
- throw new Error(`guest symbol has ambiguous provider ${symbol}`);
10069
- const scopedReferences = record.physicalModule ? [...record.references] : otherReferences;
10070
- for (const [object3, caller] of scopedReferences) {
10071
- const scope = callers.get(caller);
10072
- if (!scope) throw new Error(`guest image has no caller scope ${caller}`);
10073
- if (record.physicalModule) {
10074
- result.push({ symbol, caller, provider: { kind: "physical-module" } });
10075
- continue;
10076
- }
10077
- const provider = interposed ? [caller, ...scope].find((image) => copyImages.has(image)) ?? [...strongImages][0] ?? [...providerImages][0] : [...providerImages][0];
10078
- if (provider === void 0)
10079
- throw new Error(`guest scope ${caller} omits every provider of ${symbol}`);
10080
- if (caller === provider) continue;
10081
- if ([...options.definitionObjects.get(symbol) ?? []].some(
10082
- (definer) => options.owners.get(definer) === caller && options.weakDefinitions.get(definer)?.has(symbol)
10083
- ))
10084
- continue;
10085
- if (!scope.includes(provider)) {
10086
- const candidates = options.definitionObjects.get(symbol) ?? /* @__PURE__ */ new Set();
10087
- const traced = [...record.providers.keys()];
10088
- const strongTraced = traced.filter(
10089
- (definer) => !options.weakDefinitions.get(definer)?.has(symbol)
10090
- );
10091
- const providers = strongTraced.length === 1 ? strongTraced : traced;
10092
- if (options.weakReferences.get(object3)?.has(symbol) && !providers.some((provider2) => options.systemProviders.has(provider2)))
10093
- continue;
10094
- const equivalentCopies = providers.length === 1 && candidates.has(providers[0]) && [...candidates].every(
10095
- (definer) => options.weakDefinitions.get(definer)?.has(symbol)
10096
- );
10097
- const strongCandidates = [...candidates].filter(
10098
- (definer) => !options.weakDefinitions.get(definer)?.has(symbol)
10099
- );
10100
- const soleCandidate = candidates.size === 1 || strongCandidates.length === 1 && strongCandidates[0] === providers[0];
10101
- if (!equivalentCopies && (!soleCandidate || providers.length !== 1 || !candidates.has(providers[0]) || !(options.systemProviders.has(providers[0]) || // a strong undefined reference binds through the process global
10102
- // scope, the root image and its dependency closure, as in elf.
10103
- provider === 0 || callers.get(0)?.includes(provider) || !options.weakReferences.get(object3)?.has(symbol) && options.frameworkProviders.get(object3)?.has(providers[0]))))
10104
- throw new Error(
10105
- `guest scope ${caller} omits traced provider ${provider} for ${symbol}`
10106
- );
10107
- directBindings.push({
10108
- object: object3,
10109
- symbol,
10110
- providerObject: providers[0],
10111
- providerImage: provider
10112
- });
10113
- continue;
9891
+ (0, import_node_fs20.writeFileSync)(merged, dropBoundaryExports((0, import_node_fs20.readFileSync)(merged)));
9892
+ (0, import_node_fs20.rmSync)(guest);
9893
+ (0, import_node_fs20.rmSync)(thunks);
9894
+ }
9895
+ try {
9896
+ await runBinaryen(
9897
+ binary,
9898
+ [
9899
+ ...LOWERING,
9900
+ ...optimize ? ["-Oz"] : [],
9901
+ ...names,
9902
+ ...skipPasses.flatMap((pass) => ["--skip-pass", pass]),
9903
+ ...features,
9904
+ narrowed ? merged : file,
9905
+ "-o",
9906
+ output
9907
+ ],
9908
+ { env: environment, maxBuffer: Infinity }
9909
+ );
9910
+ } finally {
9911
+ if (narrowed) (0, import_node_fs20.rmSync)(merged);
9912
+ }
9913
+ }
9914
+ async function installWasmOpt() {
9915
+ const platform = `${process.platform}-${process.arch}`;
9916
+ const release = BINARYEN_RELEASES.get(platform);
9917
+ if (!release) throw new Error(`no pinned Binaryen release for ${platform}`);
9918
+ const destDir = (0, import_node_path20.join)(rnxHomeDir(), "tools", "binaryen", BINARYEN_VERSION, platform);
9919
+ const binary = (0, import_node_path20.join)(destDir, "bin", "wasm-opt");
9920
+ if (!(0, import_node_fs20.existsSync)(binary))
9921
+ await installVerifiedTarball({
9922
+ url: `https://r2.rnxsim.com/peach/binaryen/${release.sha256}/${platform}.tar.gz`,
9923
+ digest: { algorithm: "sha256", encoding: "hex", value: release.sha256 },
9924
+ destDir,
9925
+ installedMarker: "bin/wasm-opt",
9926
+ label: `Binaryen ${BINARYEN_VERSION}`
9927
+ });
9928
+ return binary;
9929
+ }
9930
+ async function lowerWasm(file, output, options) {
9931
+ await runWasmOpt(
9932
+ file,
9933
+ output,
9934
+ options.optimize,
9935
+ options.skipPasses ?? [],
9936
+ await installWasmOpt()
9937
+ );
9938
+ }
9939
+
9940
+ // src/swift-guest-link.ts
9941
+ function remapGuestLinkPlan(plan, rewritten) {
9942
+ return {
9943
+ ...plan,
9944
+ artifacts: plan.artifacts.map((artifact) => ({
9945
+ ...artifact,
9946
+ path: rewritten.get(artifact.path) ?? artifact.path
9947
+ }))
9948
+ };
9949
+ }
9950
+ function guestLinkInputFiles(args) {
9951
+ const dirs = [];
9952
+ for (let i = 0; i < args.length; i++) {
9953
+ const arg = args[i];
9954
+ if (arg === "-L" || arg === "--library-path") dirs.push(args[++i]);
9955
+ else if (arg.startsWith("-L")) dirs.push(arg.slice(2));
9956
+ else if (arg.startsWith("--library-path=")) dirs.push(arg.slice(15));
9957
+ }
9958
+ const inputs = /* @__PURE__ */ new Set();
9959
+ for (let i = 0; i < args.length; i++) {
9960
+ const arg = args[i];
9961
+ if (arg === "-L" || arg === "--library-path" || arg === "-o" || arg === "--output") {
9962
+ i++;
9963
+ continue;
9964
+ }
9965
+ if (arg.startsWith("@")) throw new Error(`nested linker response file ${arg}`);
9966
+ let file;
9967
+ if (arg === "-l" || arg === "--library" || arg.startsWith("--library=") || arg.startsWith("-l") && arg.length > 2) {
9968
+ const name2 = arg === "-l" || arg === "--library" ? args[++i] : arg.startsWith("--library=") ? arg.slice(10) : arg.slice(2);
9969
+ const archive = name2.startsWith(":") ? name2.slice(1) : `lib${name2}.a`;
9970
+ file = dirs.map((dir) => import_node_path21.default.join(dir, archive)).find((item) => import_node_fs21.default.existsSync(item));
9971
+ if (!file) throw new Error(`unresolved guest link library ${name2}`);
9972
+ } else if (!arg.startsWith("-") && import_node_fs21.default.existsSync(arg) && import_node_fs21.default.statSync(arg).isFile()) {
9973
+ const fd = import_node_fs21.default.openSync(arg, "r");
9974
+ const magic = Buffer.alloc(8);
9975
+ try {
9976
+ import_node_fs21.default.readSync(fd, magic, 0, magic.length, 0);
9977
+ } finally {
9978
+ import_node_fs21.default.closeSync(fd);
10114
9979
  }
10115
- result.push({ symbol, caller, provider: { kind: "image", image: provider } });
9980
+ if (magic.subarray(0, 4).equals(Buffer.from([0, 97, 115, 109])) || magic.subarray(0, 4).equals(Buffer.from([66, 67, 192, 222])) || magic.toString("ascii") === "!<arch>\n" || magic.toString("ascii") === "!<thin>\n")
9981
+ file = arg;
10116
9982
  }
9983
+ if (file) inputs.add(import_node_path21.default.resolve(file));
10117
9984
  }
10118
- return { bindings: result, directBindings };
9985
+ return [...inputs];
10119
9986
  }
10120
- function linkPrunedGuestImages(options) {
10121
- let result;
10122
- pruneSwiftWasmLink(
10123
- options.buildDirectory,
10124
- options.toolchainBin,
10125
- options.moduleRoot,
10126
- options.staticClangTargets,
10127
- void 0,
10128
- (args, rewritten, sdk) => {
10129
- if (args.some((arg) => arg === "--Map" || arg.startsWith("--Map=")))
10130
- throw new Error("guest link already has a linker map");
10131
- const framework = options.framework;
10132
- const prepared = options.prepareRuntime?.(args, rewritten, sdk);
10133
- if (prepared && options.sdkProducts !== null)
10134
- throw new Error("guest runtime products supplied twice");
10135
- const linkedArgs = prepared?.args ?? args;
10136
- const sdkProducts = prepared?.sdkProducts ?? (typeof options.sdkProducts === "function" ? options.sdkProducts(args, rewritten, sdk) : options.sdkProducts);
10137
- const sourcePlan = options.plan(linkedArgs, rewritten, sdk, sdkProducts);
10138
- let frameworkArtifacts = [];
10139
- const selectedObjects = prepared && new Set(
10140
- prepared.selected.filter((item) => item.member === null).map((item) => import_node_path17.default.resolve(item.artifact))
10141
- );
10142
- const selectedFramework = framework && (!prepared || framework.product.objects.some((object3) => {
10143
- const original = import_node_path17.default.resolve(framework.root, object3.path);
10144
- const linked = import_node_path17.default.resolve(rewritten.get(original) ?? original);
10145
- return selectedObjects?.has(linked) ?? false;
10146
- }));
10147
- if (framework && selectedFramework) {
10148
- const image = sdkProducts?.images.get(
10149
- frameworkRuntimeProductId(framework.product)
10150
- );
10151
- if (image === void 0)
9987
+ function unownedGuestLinkInputs(plan, args) {
9988
+ const owned = new Set(plan.artifacts.map((artifact) => import_node_path21.default.resolve(artifact.path)));
9989
+ return guestLinkInputFiles(args).filter((file) => !owned.has(file));
9990
+ }
9991
+ function occurrences(plan, args) {
9992
+ const dirs = [];
9993
+ for (let i = 0; i < args.length; i++) {
9994
+ const arg = args[i];
9995
+ if (arg === "-L") dirs.push(args[++i]);
9996
+ else if (arg.startsWith("-L")) dirs.push(arg.slice(2));
9997
+ }
9998
+ const owned = new Map(
9999
+ plan.artifacts.map((artifact) => [import_node_path21.default.resolve(artifact.path), artifact])
10000
+ );
10001
+ if (owned.size !== plan.artifacts.length)
10002
+ throw new Error("duplicate guest link artifact");
10003
+ const found = [];
10004
+ const seen = /* @__PURE__ */ new Map();
10005
+ let lazy = false;
10006
+ let whole = false;
10007
+ for (const token of args) {
10008
+ if (token === "--start-lib") {
10009
+ lazy = true;
10010
+ continue;
10011
+ }
10012
+ if (token === "--end-lib") {
10013
+ lazy = false;
10014
+ continue;
10015
+ }
10016
+ if (token === "--whole-archive") {
10017
+ whole = true;
10018
+ continue;
10019
+ }
10020
+ if (token === "--no-whole-archive") {
10021
+ whole = false;
10022
+ continue;
10023
+ }
10024
+ let filename = token;
10025
+ if (token.startsWith("-l") && token.length > 2) {
10026
+ const library = token.slice(2);
10027
+ filename = dirs.map(
10028
+ (dir) => import_node_path21.default.join(
10029
+ dir,
10030
+ library.startsWith(":") ? library.slice(1) : `lib${library}.a`
10031
+ )
10032
+ ).find((file) => import_node_fs21.default.existsSync(file)) ?? token;
10033
+ }
10034
+ const artifact = owned.get(import_node_path21.default.resolve(filename));
10035
+ if (artifact) {
10036
+ const prior = seen.get(artifact.path);
10037
+ if (prior) {
10038
+ if (prior.lazy !== lazy || prior.whole !== whole)
10152
10039
  throw new Error(
10153
- "framework objects require their declared compiler runtime image"
10040
+ `guest link input has conflicting occurrence modes: ${artifact.path}`
10154
10041
  );
10155
- frameworkArtifacts = guestFrameworkLinkArtifacts(
10156
- framework.product,
10157
- framework.root,
10158
- linkedArgs,
10159
- rewritten,
10160
- image
10161
- );
10162
- }
10163
- if (sdkProducts) {
10164
- for (const image of guestSdkProductImages(
10165
- sdkProducts.products.map((entry) => entry.product),
10166
- sdkProducts.images
10167
- )) {
10168
- const planned = sourcePlan.images.find((entry) => entry.id === image.id);
10169
- if (!planned || planned.name !== image.name || planned.dependencies.length !== image.dependencies.length || planned.dependencies.some(
10170
- (dependency, index) => dependency !== image.dependencies[index]
10171
- ))
10172
- throw new Error(`SDK image scope differs from source product ${image.name}`);
10173
- }
10174
- }
10175
- const plan = remapGuestLinkPlan(
10176
- {
10177
- ...sourcePlan,
10178
- artifacts: [
10179
- ...sourcePlan.artifacts,
10180
- ...frameworkArtifacts,
10181
- ...sdkProducts ? guestSdkProductLinkArtifacts(
10182
- sdkProducts.products,
10183
- sdk,
10184
- linkedArgs,
10185
- sdkProducts.linkedArchives,
10186
- rewritten,
10187
- new Map([...sdkProducts.images, ...sdkProducts.containingImages]),
10188
- prepared?.selected
10189
- ) : [],
10190
- ...prepared?.archiveArtifacts ?? []
10191
- ]
10192
- },
10193
- rewritten
10194
- );
10195
- let owners = /* @__PURE__ */ new Map();
10196
- let generatedSectionOwners = /* @__PURE__ */ new Map();
10197
- let projection = typeof options.projection === "function" ? options.projection(linkedArgs, rewritten, sdk, sdkProducts, plan) : options.projection;
10198
- if (projection && prepared) {
10199
- const identities = new Map(projection.identities);
10200
- for (const [before, after] of rewritten) {
10201
- const identity = identities.get(before);
10202
- const existing = identities.get(after);
10203
- if (identity !== void 0 && existing !== void 0 && existing !== identity)
10204
- throw new Error(`rewritten guest input has conflicting identity ${after}`);
10205
- if (identity !== void 0) identities.set(after, identity);
10206
- }
10207
- projection = {
10208
- ...projection,
10209
- identities: aliasGuestLinkIdentities(identities, prepared.archives)
10210
- };
10042
+ continue;
10211
10043
  }
10212
- const selected = linkCompleteGuestImages({
10213
- plan,
10214
- args: [...linkedArgs, `--Map=${options.mapPath}`],
10215
- directory: options.linkDirectory,
10216
- wasmLd: import_node_path17.default.join(options.toolchainBin, "wasm-ld"),
10217
- clang: import_node_path17.default.join(options.toolchainBin, "clang"),
10218
- llvmAr: import_node_path17.default.join(options.toolchainBin, "llvm-ar"),
10219
- ledgerDataImage: options.ledgerDataImage,
10220
- projection,
10221
- resolvePlan: options.resolvePlan,
10222
- onLinkedOwners: (value) => {
10223
- owners = value;
10224
- },
10225
- onLinkedSections: (value) => {
10226
- generatedSectionOwners = value;
10227
- }
10228
- });
10229
- result = {
10230
- selected,
10231
- owners,
10232
- generatedSectionOwners,
10233
- sdk,
10234
- mapPath: options.mapPath,
10235
- generatedLedgerObject: import_node_path17.default.join(options.linkDirectory, "ledger.o")
10236
- };
10237
- },
10238
- options.resourceReferences
10044
+ const occurrence = { artifact, token, lazy, whole };
10045
+ seen.set(artifact.path, occurrence);
10046
+ found.push(occurrence);
10047
+ }
10048
+ }
10049
+ if (found.length !== plan.artifacts.length)
10050
+ throw new Error("guest plan does not match linker inputs");
10051
+ return found;
10052
+ }
10053
+ function selectedGuestLinkInputs(plan, args, whyExtract, linkTrace) {
10054
+ const rows = whyExtract.trimEnd().split("\n");
10055
+ if (rows.shift() !== "reference extracted symbol")
10056
+ throw new Error("invalid wasm-ld extraction report");
10057
+ const extracted = new Set(
10058
+ rows.map((row) => {
10059
+ const fields = row.split(" ");
10060
+ if (fields.length !== 3) throw new Error("invalid wasm-ld extraction row");
10061
+ return fields[1];
10062
+ })
10239
10063
  );
10240
- if (!result) throw new Error("guest link did not receive pruned inputs");
10064
+ const traced = new Set(linkTrace.split("\n").filter(Boolean));
10065
+ for (const file of extracted)
10066
+ if (!traced.has(file))
10067
+ throw new Error(`extracted guest input is absent from link trace ${file}`);
10068
+ const result = [];
10069
+ for (const { artifact, lazy, whole } of occurrences(plan, args)) {
10070
+ if (artifact.kind === "object") {
10071
+ if (!lazy && !traced.has(artifact.path))
10072
+ throw new Error(`eager guest input is absent from link trace ${artifact.path}`);
10073
+ if (traced.has(artifact.path))
10074
+ result.push({ artifact: artifact.path, member: null });
10075
+ continue;
10076
+ }
10077
+ const prefix = `${artifact.path}(`;
10078
+ const names = [...traced].filter((item) => item.startsWith(prefix) && item.endsWith(")")).map((item) => item.slice(prefix.length, -1));
10079
+ const members = readArMembers(import_node_fs21.default.readFileSync(artifact.path));
10080
+ for (const member of members) {
10081
+ if (whole || names.includes(member.name))
10082
+ result.push({ artifact: artifact.path, member: member.name });
10083
+ }
10084
+ for (const name2 of names)
10085
+ if (members.filter((member) => member.name === name2).length !== 1)
10086
+ throw new Error(
10087
+ `ambiguous or unsupported archive member ${artifact.path}(${name2})`
10088
+ );
10089
+ }
10241
10090
  return result;
10242
10091
  }
10243
-
10244
- // src/swift-guest-source-inputs.ts
10245
- var import_node_child_process12 = require("node:child_process");
10246
- var import_node_crypto12 = require("node:crypto");
10247
- var import_node_fs18 = require("node:fs");
10248
- var import_node_path18 = __toESM(require("node:path"), 1);
10249
-
10250
- // src/forked-script-contract.ts
10251
- var PEACH_FORKED_SCRIPT_ENV = "PEACH_RUNS_FORKED_SCRIPTS";
10252
-
10253
- // src/swift-guest-source-inputs.ts
10254
- function clangIrLinkOptions(ir) {
10255
- const list = /^!llvm\.linker\.options = !\{([^\n]*)\}$/m.exec(ir);
10256
- if (!list) {
10257
- if (/^!llvm\.linker\.options\s*=/m.test(ir))
10258
- throw new Error("invalid clang link metadata list");
10259
- return [];
10092
+ function outputPath(args) {
10093
+ let output = "";
10094
+ for (let i = 0; i < args.length; i++) {
10095
+ const arg = args[i];
10096
+ if (arg === "-o" || arg === "--output") output = args[++i];
10097
+ else if (arg.startsWith("--output=")) output = arg.slice("--output=".length);
10260
10098
  }
10261
- const ids = list[1].split(",").map((item) => item.trim());
10262
- if (ids.length === 1 && ids[0] === "") return [];
10099
+ if (!output) throw new Error("guest link has no output path");
10100
+ return output;
10101
+ }
10102
+ function withOutput(args, output, discovery) {
10263
10103
  const result = [];
10264
- for (const id of ids) {
10265
- if (!/^!\d+$/.test(id)) throw new Error(`invalid clang link metadata ${id}`);
10266
- const node = new RegExp(`^${id} = !\\{([^\\n]*)\\}$`, "m").exec(ir);
10267
- if (!node) throw new Error(`missing clang link metadata ${id}`);
10268
- const parts = node[1].split(/,\s*(?=!")/);
10269
- for (const part of parts) {
10270
- const value = /^!"((?:[^"\\]|\\[0-9A-Fa-f]{2})*)"$/.exec(part.trim());
10271
- if (!value) throw new Error(`invalid clang link option ${part}`);
10272
- const decoded = value[1].replace(
10273
- /\\([0-9A-Fa-f]{2})/g,
10274
- (_, hex) => String.fromCharCode(Number.parseInt(hex, 16))
10275
- );
10276
- const flag = Buffer.from(decoded, "latin1").toString("utf8");
10277
- if (!flag || flag.includes("\0")) throw new Error("invalid empty clang link option");
10278
- result.push(flag);
10104
+ for (let i = 0; i < args.length; i++) {
10105
+ const arg = args[i];
10106
+ if (arg === "-o" || arg === "--output") {
10107
+ i++;
10108
+ continue;
10279
10109
  }
10110
+ if (arg.startsWith("--output=")) continue;
10111
+ if (discovery && (arg.startsWith("--why-extract=") || arg.startsWith("--Map=")))
10112
+ continue;
10113
+ result.push(arg);
10280
10114
  }
10115
+ result.push("-o", output);
10281
10116
  return result;
10282
10117
  }
10283
- var CLANG_TARGET_MODULE_WRAPPER = ".peach-clang";
10284
- var PARALLEL_REPLAY = `
10285
- const { spawn } = require('node:child_process')
10286
- const commands = JSON.parse(require('node:fs').readFileSync(process.env.PEACH_CLANG_REPLAYS, 'utf8'))
10287
- let next = 0
10288
- const run = () => {
10289
- if (next >= commands.length) return Promise.resolve()
10290
- const [file, ...args] = commands[next++]
10291
- return new Promise((resolve, reject) => {
10292
- const child = spawn(file, args, { stdio: 'inherit' })
10293
- child.on('error', reject)
10294
- child.on('close', (code) => (code === 0 ? resolve() : reject(new Error('clang link replay failed: ' + file))))
10295
- }).then(run)
10296
- }
10297
- const jobs = Math.max(1, Number(process.env.PEACH_CLANG_JOBS) || 1)
10298
- Promise.all(Array.from({ length: jobs }, run)).catch((error) => {
10299
- console.error(error.message)
10300
- process.exit(1)
10301
- })
10302
- `;
10303
- function sourceGuestClangLinkOptions(options) {
10304
- const wanted = new Set(options.objects.map((file) => import_node_path18.default.resolve(file)));
10305
- const commands = /* @__PURE__ */ new Map();
10306
- let tool = "";
10307
- let outputs = [];
10308
- for (const line of (0, import_node_fs18.readFileSync)(
10309
- import_node_path18.default.join(options.buildDirectory, ".build", "release.yaml"),
10310
- "utf8"
10311
- ).split("\n")) {
10312
- if (line.startsWith(' "') && line.endsWith(":")) {
10313
- tool = "";
10314
- outputs = [];
10315
- continue;
10118
+ function linkGuestImages(options) {
10119
+ const { args, directory, wasmLd, clang, llvmAr } = options;
10120
+ let plan = options.plan;
10121
+ if (!plan.images.some((image) => image.id === options.ledgerDataImage))
10122
+ throw new Error(`unknown ledger data image ${options.ledgerDataImage}`);
10123
+ import_node_fs21.default.mkdirSync(directory, { recursive: true });
10124
+ const discovery = import_node_path21.default.join(directory, "discovery.wasm");
10125
+ const whyPath = import_node_path21.default.join(directory, "why-extract.txt");
10126
+ const mapPath = import_node_path21.default.join(directory, "discovery.map");
10127
+ const runLink = (name2, arguments_) => {
10128
+ const response = import_node_path21.default.join(directory, `${name2}.rsp`);
10129
+ const trace = import_node_path21.default.join(directory, `${name2}-inputs.txt`);
10130
+ import_node_fs21.default.writeFileSync(
10131
+ response,
10132
+ [...arguments_, "--trace"].map((argument2) => JSON.stringify(argument2)).join(" ")
10133
+ );
10134
+ const output = import_node_fs21.default.openSync(trace, "w");
10135
+ try {
10136
+ (0, import_node_child_process13.execFileSync)(wasmLd, [`@${response}`], { stdio: ["ignore", output, "pipe"] });
10137
+ } finally {
10138
+ import_node_fs21.default.closeSync(output);
10139
+ }
10140
+ return import_node_fs21.default.readFileSync(trace, "utf8");
10141
+ };
10142
+ let discoveryProjection;
10143
+ if (options.projection) {
10144
+ const source = import_node_path21.default.join(directory, "projection-discovery.c");
10145
+ discoveryProjection = import_node_path21.default.join(directory, "projection-discovery.o");
10146
+ import_node_fs21.default.writeFileSync(
10147
+ source,
10148
+ '#include "guest-image-projection.h"\nconst struct peach_guest_image __peach_guest_images[] = {{0}};\nconst uint32_t __peach_guest_image_count = 0;\n'
10149
+ );
10150
+ (0, import_node_child_process13.execFileSync)(
10151
+ clang,
10152
+ [...options.projection.clangOptions, "-c", source, "-o", discoveryProjection],
10153
+ { stdio: "pipe" }
10154
+ );
10155
+ }
10156
+ const archives = /* @__PURE__ */ new Map();
10157
+ const memberBytes = /* @__PURE__ */ new Map();
10158
+ const prepare = (provider2) => {
10159
+ const trace = runLink("discovery", [
10160
+ ...withOutput(args, discovery, true),
10161
+ ...discoveryProjection ? [discoveryProjection] : [],
10162
+ ...provider2 ? ["--undefined=__peach_dlsym_from_image"] : [],
10163
+ `--why-extract=${whyPath}`,
10164
+ `--Map=${mapPath}`
10165
+ ]);
10166
+ const selected2 = selectedGuestLinkInputs(
10167
+ plan,
10168
+ args,
10169
+ import_node_fs21.default.readFileSync(whyPath, "utf8"),
10170
+ trace
10171
+ );
10172
+ if (options.resolvePlan) {
10173
+ const identity = (value) => JSON.stringify([
10174
+ value.images.map(({ id, name: name2 }) => [id, name2]),
10175
+ value.artifacts.map(
10176
+ ({
10177
+ path: file,
10178
+ kind,
10179
+ image,
10180
+ memberImages,
10181
+ memberOrigins,
10182
+ instrumentDynamicLookups
10183
+ }) => [
10184
+ file,
10185
+ kind,
10186
+ image,
10187
+ memberImages ? [...memberImages] : null,
10188
+ memberOrigins ? [...memberOrigins] : null,
10189
+ instrumentDynamicLookups
10190
+ ]
10191
+ )
10192
+ ]);
10193
+ const originalOwnership = identity(plan);
10194
+ const resolved = options.resolvePlan(selected2, plan);
10195
+ if (identity(resolved) !== originalOwnership)
10196
+ throw new Error("resolved guest scopes changed input ownership");
10197
+ plan = resolved;
10316
10198
  }
10317
- if (line.startsWith(" tool: ")) tool = line.slice(10).trim();
10318
- if (line.startsWith(" outputs: ")) {
10319
- const value2 = JSON.parse(line.slice(13));
10320
- if (!Array.isArray(value2) || !value2.every((item) => typeof item === "string"))
10321
- throw new Error("invalid build command outputs");
10322
- outputs = value2;
10199
+ const objectsByImage = /* @__PURE__ */ new Map();
10200
+ for (const image of plan.images) objectsByImage.set(image.id, []);
10201
+ const artifacts = new Map(plan.artifacts.map((artifact) => [artifact.path, artifact]));
10202
+ for (const item of selected2) {
10203
+ const artifact = artifacts.get(item.artifact);
10204
+ const image = selectedGuestInputImage(artifact, item.member);
10205
+ let bytes;
10206
+ if (item.member === null) bytes = import_node_fs21.default.readFileSync(item.artifact);
10207
+ else {
10208
+ let byName = memberBytes.get(item.artifact);
10209
+ if (!byName) {
10210
+ const members = readArMembers(import_node_fs21.default.readFileSync(item.artifact));
10211
+ archives.set(item.artifact, members);
10212
+ byName = /* @__PURE__ */ new Map();
10213
+ for (const member of members)
10214
+ if (!byName.has(member.name)) byName.set(member.name, member.bytes);
10215
+ memberBytes.set(item.artifact, byName);
10216
+ }
10217
+ bytes = byName.get(item.member);
10218
+ }
10219
+ const objects = objectsByImage.get(image);
10220
+ if (!objects) throw new Error(`unknown image ${image}`);
10221
+ objects.push({
10222
+ path: item.member === null ? item.artifact : `${item.artifact}(${item.member})`,
10223
+ bytes,
10224
+ // the actual loader delegates non-ledger lookups to libc; wrapping its
10225
+ // own dlsym call would recurse back into the loader.
10226
+ instrumentDynamicLookups: artifact.instrumentDynamicLookups && !guestWasmSymbols(bytes).defined.includes("__peach_dlsym_from_image")
10227
+ });
10323
10228
  }
10324
- if (!line.startsWith(" args: ") || !outputs.some((file) => wanted.has(import_node_path18.default.resolve(file))))
10229
+ const ledger2 = createGuestImageLedger({
10230
+ images: plan.images.map((image) => ({
10231
+ ...image,
10232
+ objects: objectsByImage.get(image.id)
10233
+ })),
10234
+ callers: plan.callers,
10235
+ symbols: plan.symbols,
10236
+ liveSymbols: linkedMapSymbols(import_node_fs21.default.readFileSync(mapPath, "utf8")),
10237
+ commandLineSymbols: commandLineSymbols(args),
10238
+ directBindings: plan.directBindings
10239
+ });
10240
+ return { selected: selected2, ledger: ledger2 };
10241
+ };
10242
+ let prepared = prepare(false);
10243
+ const provider = prepared.ledger.callerWrappers.some(
10244
+ ({ symbol }) => symbol.startsWith("__peach_dlsym_caller_")
10245
+ );
10246
+ if (provider) prepared = prepare(true);
10247
+ const { selected, ledger } = prepared;
10248
+ const replacements = /* @__PURE__ */ new Map();
10249
+ const linkedOwners = /* @__PURE__ */ new Map();
10250
+ const ledgerObjects = new Map(ledger.objects.map((item) => [item.path, item]));
10251
+ for (const [index, artifact] of plan.artifacts.entries()) {
10252
+ const prefix = `${artifact.path}(`;
10253
+ if (artifact.kind === "object") {
10254
+ const object3 = ledgerObjects.get(artifact.path);
10255
+ if (!object3) continue;
10256
+ const output2 = import_node_path21.default.join(directory, `object-${index}.o`);
10257
+ import_node_fs21.default.writeFileSync(output2, object3.bytes);
10258
+ replacements.set(artifact.path, output2);
10259
+ linkedOwners.set(output2, selectedGuestInputImage(artifact, null));
10325
10260
  continue;
10326
- const value = JSON.parse(line.slice(10));
10327
- if (!Array.isArray(value) || !value.every((item) => typeof item === "string"))
10328
- throw new Error("invalid build command arguments");
10329
- for (const output of outputs) {
10330
- const file = import_node_path18.default.resolve(output);
10331
- if (!wanted.has(file)) continue;
10332
- if (commands.has(file)) throw new Error(`ambiguous source object producer ${file}`);
10333
- commands.set(file, { tool, args: value });
10334
10261
  }
10262
+ const members = archives.get(artifact.path);
10263
+ if (!members) continue;
10264
+ const listed = (0, import_node_child_process13.execFileSync)(llvmAr, ["t", artifact.path], { encoding: "utf8" }).trimEnd().split("\n");
10265
+ if (listed.length !== members.length || new Set(listed).size !== listed.length || members.some(
10266
+ (member, i) => listed[i] !== member.name || import_node_path21.default.basename(member.name) !== member.name
10267
+ ))
10268
+ throw new Error(`unsupported archive layout ${artifact.path}`);
10269
+ const memberDir = import_node_path21.default.join(directory, `archive-${index}`);
10270
+ import_node_fs21.default.mkdirSync(memberDir, { recursive: true });
10271
+ const output = import_node_path21.default.join(directory, `archive-${index}.a`);
10272
+ const inputs = members.map((member) => {
10273
+ const memberOutput = import_node_path21.default.join(memberDir, member.name);
10274
+ const rewritten = ledgerObjects.get(`${prefix}${member.name})`);
10275
+ import_node_fs21.default.writeFileSync(memberOutput, rewritten?.bytes ?? member.bytes);
10276
+ if (rewritten) {
10277
+ linkedOwners.set(
10278
+ `${output}(${member.name})`,
10279
+ selectedGuestInputImage(artifact, member.name)
10280
+ );
10281
+ }
10282
+ return memberOutput;
10283
+ });
10284
+ import_node_fs21.default.rmSync(output, { force: true });
10285
+ const response = import_node_path21.default.join(memberDir, "members.rsp");
10286
+ import_node_fs21.default.writeFileSync(response, inputs.map((input) => JSON.stringify(input)).join(" "));
10287
+ (0, import_node_child_process13.execFileSync)(llvmAr, ["rcs", output, `@${response}`], { stdio: "pipe" });
10288
+ replacements.set(artifact.path, output);
10335
10289
  }
10336
- const replays = [];
10337
- for (const [index, file] of [...wanted].entries()) {
10338
- const command = commands.get(file);
10339
- if (!command) throw new Error(`missing source object producer ${file}`);
10340
- if (command.tool === "shell") {
10341
- if (!command.args.length || (0, import_node_fs18.realpathSync)(command.args[0]) !== (0, import_node_fs18.realpathSync)(options.swiftCompiler))
10342
- throw new Error(`unsupported source object producer ${file}`);
10343
- continue;
10344
- }
10345
- const compiler = command.args[0] ? (0, import_node_fs18.realpathSync)(command.args[0]) : "";
10346
- if (command.tool !== "clang" || compiler !== (0, import_node_fs18.realpathSync)(import_node_path18.default.join(options.toolchainBin, "clang")) && compiler !== (0, import_node_fs18.realpathSync)(import_node_path18.default.join(options.buildDirectory, CLANG_TARGET_MODULE_WRAPPER)))
10347
- throw new Error(`unsupported source object producer ${file}`);
10348
- const args = command.args.slice(1).filter((arg) => arg !== "-c");
10349
- const targetBuild = import_node_path18.default.relative(options.buildDirectory, file).split(import_node_path18.default.sep).findLast((part) => part !== ".build" && part.endsWith(".build"));
10350
- const outputDirectory = import_node_path18.default.join(
10351
- options.directory,
10352
- targetBuild ?? import_node_path18.default.basename(import_node_path18.default.dirname(file))
10290
+ const irPath = import_node_path21.default.join(directory, "ledger.ll");
10291
+ const ledgerObject = import_node_path21.default.join(directory, "ledger.o");
10292
+ import_node_fs21.default.writeFileSync(irPath, ledger.llvmIR);
10293
+ (0, import_node_child_process13.execFileSync)(
10294
+ clang,
10295
+ ["--target=wasm64-unknown-wasip1", "-c", irPath, "-o", ledgerObject],
10296
+ { stdio: "pipe" }
10297
+ );
10298
+ linkedOwners.set(ledgerObject, options.ledgerDataImage);
10299
+ let projectionObject;
10300
+ let projectionStorage;
10301
+ if (options.projection) {
10302
+ const projection = options.projection;
10303
+ if (!plan.images.some((image) => image.id === projection.image))
10304
+ throw new Error("guest projection has no source image");
10305
+ if (projection.images.length !== plan.images.length || projection.images.some(
10306
+ (image, index) => image.image !== index || plan.images[index]?.id !== index
10307
+ ))
10308
+ throw new Error("guest projection image order differs from link plan");
10309
+ const selectedInputs = selectedGuestManifestInputs(
10310
+ plan,
10311
+ selected,
10312
+ projection.identities
10353
10313
  );
10354
- (0, import_node_fs18.mkdirSync)(outputDirectory, { recursive: true });
10355
- const output = import_node_path18.default.join(outputDirectory, `clang-link-${index}.ll`);
10356
- for (const flag of ["-o", "-MF"]) {
10357
- const index2 = args.lastIndexOf(flag);
10358
- if (index2 < 0 || index2 + 1 >= args.length)
10359
- throw new Error(`missing clang ${flag} for ${file}`);
10360
- args[index2 + 1] = flag === "-o" ? output : `${output}.d`;
10361
- }
10362
- replays.push({
10363
- file,
10364
- compiler: command.args[0],
10365
- args: [...args, "-S", "-emit-llvm", "-Xclang", "-disable-llvm-passes"],
10366
- output
10367
- });
10314
+ const images = projection.images.map(
10315
+ (image) => createGuestImageManifest({
10316
+ ...image,
10317
+ inputs: selectedInputs.get(image.image) ?? [],
10318
+ linkOptions: projection.linkOptions,
10319
+ regions: []
10320
+ })
10321
+ );
10322
+ const ledgerPieces = guestProjectionRegionCapacity([import_node_fs21.default.readFileSync(ledgerObject)], 0);
10323
+ const capacities = ledger.images.map((image) => ({
10324
+ regions: guestProjectionRegionCapacity(
10325
+ image.objects.map((object3) => object3.bytes),
10326
+ 1 + ledger.callerWrappers.filter((wrapper) => wrapper.image === image.id).length + (image.id === options.ledgerDataImage ? ledgerPieces : 0) + (image.id === projection.image ? images.length + 2 : 0)
10327
+ ),
10328
+ memoryProtection: projection.memoryProtection,
10329
+ tableProtection: projection.tableProtection
10330
+ }));
10331
+ projectionStorage = reserveGuestProjectionStorage(images, capacities);
10332
+ const projectionSource = import_node_path21.default.join(directory, "projection.c");
10333
+ projectionObject = import_node_path21.default.join(directory, "projection.o");
10334
+ import_node_fs21.default.writeFileSync(projectionSource, projectionStorage.source);
10335
+ (0, import_node_child_process13.execFileSync)(
10336
+ clang,
10337
+ [...projection.clangOptions, "-c", projectionSource, "-o", projectionObject],
10338
+ {
10339
+ stdio: "pipe"
10340
+ }
10341
+ );
10342
+ linkedOwners.set(projectionObject, projection.image);
10343
+ }
10344
+ const byToken = new Map(
10345
+ occurrences(plan, args).map(({ artifact, token }) => [
10346
+ token,
10347
+ replacements.get(artifact.path)
10348
+ ])
10349
+ );
10350
+ const placed = /* @__PURE__ */ new Set();
10351
+ const finalArgs = args.map((arg) => byToken.get(arg) ?? arg).filter((arg) => {
10352
+ if (!arg.endsWith(".o") && !arg.endsWith(".a")) return true;
10353
+ if (placed.has(arg)) return false;
10354
+ placed.add(arg);
10355
+ return true;
10356
+ });
10357
+ const finalOutput = import_node_path21.default.join(directory, "final.wasm");
10358
+ const finalWhy = import_node_path21.default.join(directory, "final-why-extract.txt");
10359
+ const finalTrace = runLink("final", [
10360
+ ...withOutput(finalArgs, finalOutput, false),
10361
+ ledgerObject,
10362
+ ...projectionObject ? [projectionObject] : [],
10363
+ ...provider ? ["--undefined=__peach_dlsym_from_image"] : [],
10364
+ `--why-extract=${finalWhy}`
10365
+ ]);
10366
+ const finalSelection = selectedGuestLinkInputs(
10367
+ remapGuestLinkPlan(plan, replacements),
10368
+ finalArgs,
10369
+ import_node_fs21.default.readFileSync(finalWhy, "utf8"),
10370
+ finalTrace
10371
+ );
10372
+ const original = new Map([...replacements].map(([before2, after2]) => [after2, before2]));
10373
+ const key = (item) => JSON.stringify([original.get(item.artifact) ?? item.artifact, item.member]);
10374
+ const before = new Set(selected.map(key));
10375
+ const after = new Set(finalSelection.map(key));
10376
+ const changed = [...before].filter((item) => !after.has(item));
10377
+ changed.push(...[...after].filter((item) => !before.has(item)));
10378
+ if (changed.length)
10379
+ throw new Error(
10380
+ `guest link selected different inputs after rewriting:
10381
+ ${changed.join("\n")}`
10382
+ );
10383
+ import_node_fs21.default.renameSync(finalOutput, outputPath(args));
10384
+ if (KEEP_WASM_NAMES)
10385
+ import_node_fs21.default.writeFileSync(
10386
+ outputPath(args),
10387
+ nameGuestImageAliases(import_node_fs21.default.readFileSync(outputPath(args)), plan.symbols)
10388
+ );
10389
+ if (projectionStorage && projectionObject)
10390
+ options.projection.onReserved(projectionStorage, projectionObject);
10391
+ options.onLinkedOwners?.(linkedOwners);
10392
+ options.onLinkedSections?.(
10393
+ new Map(
10394
+ ledger.callerWrappers.map(({ symbol, image }) => [
10395
+ `${ledgerObject}:(${symbol})`,
10396
+ image
10397
+ ])
10398
+ )
10399
+ );
10400
+ return selected;
10401
+ }
10402
+ function linkedMapSymbols(map) {
10403
+ const names = /* @__PURE__ */ new Set();
10404
+ for (const match of map.matchAll(/^ +\S+ +[0-9a-f]+ +[0-9a-f]+ {9,}([^\s/<]\S*)/gm))
10405
+ names.add(match[1]);
10406
+ return names;
10407
+ }
10408
+ function commandLineSymbols(args) {
10409
+ const names = [];
10410
+ for (const [i, arg] of args.entries()) {
10411
+ if (arg === "--entry" || arg === "-e" || arg === "-u") names.push(args[i + 1]);
10412
+ else
10413
+ for (const flag of [
10414
+ "--entry=",
10415
+ "--undefined=",
10416
+ "--export=",
10417
+ "--export-if-defined="
10418
+ ])
10419
+ if (arg.startsWith(flag)) names.push(arg.slice(flag.length));
10368
10420
  }
10369
- const plan = import_node_path18.default.join(options.directory, "clang-link-replays.json");
10370
- (0, import_node_fs18.writeFileSync)(
10371
- plan,
10372
- JSON.stringify(replays.map(({ compiler, args }) => [compiler, ...args]))
10421
+ return names;
10422
+ }
10423
+ function normalizedGuestLinkArgs(input) {
10424
+ const args = [];
10425
+ for (let i = 0; i < input.length; i++) {
10426
+ const arg = input[i];
10427
+ if (arg === "-l" || arg === "--library") args.push(`-l${input[++i]}`);
10428
+ else if (arg === "-L" || arg === "--library-path") args.push(`-L${input[++i]}`);
10429
+ else if (arg.startsWith("--library=")) args.push(`-l${arg.slice(10)}`);
10430
+ else if (arg.startsWith("--library-path=")) args.push(`-L${arg.slice(15)}`);
10431
+ else args.push(arg);
10432
+ }
10433
+ return args;
10434
+ }
10435
+ function aliasGuestLinkArguments(input, archives) {
10436
+ const args = normalizedGuestLinkArgs(input);
10437
+ const directories = args.filter((arg) => arg.startsWith("-L")).map((arg) => arg.slice(2));
10438
+ const aliases = new Map(
10439
+ archives.map((archive) => [import_node_path21.default.resolve(archive.source), archive.archive])
10373
10440
  );
10374
- const script = import_node_path18.default.join(options.directory, "clang-link-replay.cjs");
10375
- (0, import_node_fs18.writeFileSync)(script, PARALLEL_REPLAY);
10376
- (0, import_node_child_process12.execFileSync)(process.execPath, [script], {
10377
- stdio: "inherit",
10378
- env: {
10379
- ...process.env,
10380
- [PEACH_FORKED_SCRIPT_ENV]: "1",
10381
- PEACH_CLANG_REPLAYS: plan,
10382
- PEACH_CLANG_JOBS: String(options.jobs)
10441
+ if (aliases.size !== archives.length)
10442
+ throw new Error("duplicate original guest archive");
10443
+ const used = /* @__PURE__ */ new Set();
10444
+ const result = args.map((arg) => {
10445
+ let file = arg;
10446
+ if (arg.startsWith("-l") && arg.length > 2) {
10447
+ const name2 = arg.slice(2);
10448
+ const library = name2.startsWith(":") ? name2.slice(1) : `lib${name2}.a`;
10449
+ file = directories.map((directory) => import_node_path21.default.join(directory, library)).find((candidate) => import_node_fs21.default.existsSync(candidate)) ?? arg;
10383
10450
  }
10451
+ if (file.startsWith("-")) return arg;
10452
+ const source = import_node_path21.default.resolve(file);
10453
+ const alias = aliases.get(source);
10454
+ if (alias === void 0) return arg;
10455
+ used.add(source);
10456
+ return alias;
10384
10457
  });
10385
- const result = /* @__PURE__ */ new Map();
10386
- for (const { file, output } of replays) {
10387
- const flags = clangIrLinkOptions((0, import_node_fs18.readFileSync)(output, "utf8"));
10388
- for (let index = 0; index < flags.length; index++) {
10389
- const flag = flags[index];
10390
- if (flag === "-framework" || flag === "-l" || flag === "--library") {
10391
- const name2 = flags[++index];
10392
- if (!name2 || name2.startsWith("-"))
10393
- throw new Error(`missing clang link name after ${flag}`);
10394
- } else if (!/^(-l.+|--library=.+)$/.test(flag)) {
10395
- throw new Error(`unsupported clang link option ${flag}`);
10396
- }
10397
- }
10398
- result.set(file, flags);
10399
- }
10458
+ if (used.size !== aliases.size)
10459
+ throw new Error("aliased guest archive is not a link input");
10400
10460
  return result;
10401
10461
  }
10402
- function sourceGuestInputIdentities(graph, buildDirectory, objects) {
10403
- const producers = /* @__PURE__ */ new Map();
10404
- for (const target of graph.targets)
10405
- if (target.sourceTarget !== null)
10406
- producers.set(
10407
- target.sourceTarget,
10408
- producers.has(target.sourceTarget) ? null : target.id
10409
- );
10410
- const identities = /* @__PURE__ */ new Map();
10411
- for (const object3 of objects) {
10412
- const target = producers.get(object3.sourceTarget);
10413
- if (target === null || target === void 0)
10414
- throw new Error(`ambiguous source producer ${object3.sourceTarget}`);
10415
- if (object3.kind === "archive") {
10416
- identities.set(
10417
- object3.path,
10418
- JSON.stringify([
10419
- "source",
10420
- target,
10421
- `libraries/lib${libraryArchiveTarget(object3.path)}.a`
10422
- ])
10423
- );
10424
- continue;
10425
- }
10426
- const relative = import_node_path18.default.relative(buildDirectory, object3.path).split(import_node_path18.default.sep);
10427
- if (!relative[0]?.endsWith(".build") || relative.length < 2)
10428
- throw new Error(`source object is outside its producer ${object3.path}`);
10429
- identities.set(object3.path, JSON.stringify(["source", target, relative.join("/")]));
10430
- }
10431
- return identities;
10432
- }
10433
- function sourceGuestRuntimeLinks(options) {
10434
- const aliases = /* @__PURE__ */ new Map();
10435
- const artifacts = /* @__PURE__ */ new Map();
10436
- const frameworkAliases = /* @__PURE__ */ new Map();
10437
- const sdkAliases = /* @__PURE__ */ new Map();
10438
- for (const { product, root } of options.products) {
10439
- for (const alias of product.frameworkAliases) {
10440
- if (product.linkOwnership !== "image")
10441
- throw new Error(`framework namespace has no image owner ${product.id}`);
10442
- const previous = sdkAliases.get(alias.name);
10443
- if (previous) {
10444
- if (previous.product !== product.id || previous.moduleMap !== alias.moduleMap || previous.sha256 !== alias.moduleMapSha256)
10445
- throw new Error(`ambiguous declared framework ${alias.name}`);
10446
- continue;
10447
- }
10448
- const directory = import_node_path18.default.resolve(options.sdk.root);
10449
- const file = import_node_path18.default.resolve(directory, alias.moduleMap);
10450
- if (!file.startsWith(directory + import_node_path18.default.sep))
10451
- throw new Error(`invalid framework module map ${alias.moduleMap}`);
10452
- if ((0, import_node_crypto12.createHash)("sha256").update((0, import_node_fs18.readFileSync)(file)).digest("hex") !== alias.moduleMapSha256)
10453
- throw new Error(`framework module map changed ${alias.moduleMap}`);
10454
- sdkAliases.set(alias.name, {
10455
- product: product.id,
10456
- moduleMap: alias.moduleMap,
10457
- sha256: alias.moduleMapSha256
10458
- });
10459
- frameworkAliases.set(alias.name, { kind: "sdk", product: product.id });
10460
- }
10461
- for (const artifact of product.artifacts) {
10462
- const file = import_node_path18.default.resolve(root, artifact.path);
10463
- const prior = artifacts.get(file);
10464
- artifacts.set(file, prior === void 0 || prior === product.id ? product.id : null);
10465
- }
10466
- for (const name2 of product.linkNames) {
10467
- const prior = aliases.get(name2);
10468
- if (prior !== void 0 && prior !== product.id)
10469
- throw new Error(`ambiguous declared runtime link name ${name2}`);
10470
- aliases.set(name2, product.id);
10462
+ function linkCompleteGuestImages(options) {
10463
+ const args = normalizedGuestLinkArgs(options.args);
10464
+ const unowned = unownedGuestLinkInputs(options.plan, args);
10465
+ const candidates = unowned.map((file) => {
10466
+ const descriptor = import_node_fs21.default.openSync(file, "r");
10467
+ const magic = Buffer.alloc(8);
10468
+ try {
10469
+ import_node_fs21.default.readSync(descriptor, magic, 0, magic.length, 0);
10470
+ } finally {
10471
+ import_node_fs21.default.closeSync(descriptor);
10471
10472
  }
10472
- }
10473
- const frameworkId = frameworkRuntimeProductId(options.framework.product);
10474
- const owners = options.products.filter(({ product }) => product.id === frameworkId);
10475
- if (owners.length !== 1 || owners[0].product.linkOwnership !== "image" || import_node_path18.default.resolve(owners[0].root) !== import_node_path18.default.resolve(options.framework.root))
10476
- throw new Error(`missing or ambiguous packaged image ${frameworkId}`);
10477
- const targets = new Map(
10478
- options.framework.product.targets.map((target) => [target.name, target])
10479
- );
10480
- if (targets.size !== options.framework.product.targets.length)
10481
- throw new Error("ambiguous packaged framework target");
10482
- const objectTargets = new Set(
10483
- options.framework.product.objects.map((object3) => object3.target)
10484
- );
10485
- const closure = (names) => {
10486
- const linked = /* @__PURE__ */ new Set();
10487
- const visit = (name2) => {
10488
- if (linked.has(name2)) return;
10489
- const target = targets.get(name2);
10490
- if (!target) throw new Error(`unknown packaged framework target ${name2}`);
10491
- linked.add(name2);
10492
- for (const dependency of target.dependencies) visit(dependency);
10473
+ return {
10474
+ path: file,
10475
+ kind: magic.toString("ascii") === "!<arch>\n" ? "archive" : "object",
10476
+ image: null,
10477
+ instrumentDynamicLookups: false
10493
10478
  };
10494
- for (const name2 of names) visit(name2);
10495
- return [...linked];
10496
- };
10497
- for (const alias of options.framework.product.frameworkAliases) {
10498
- if (frameworkAliases.has(alias.name))
10499
- throw new Error(`ambiguous declared framework ${alias.name}`);
10500
- if (alias.wasmSdkId !== options.sdk.wasmSdkId || alias.wasmSdkChecksum !== options.sdk.wasmSdkChecksum)
10501
- throw new Error(`framework SDK identity differs for ${alias.name}`);
10502
- if (!alias.targets.length || alias.targets.some((target) => !targets.has(target) || !objectTargets.has(target)))
10503
- throw new Error(`framework target ownership differs for ${alias.name}`);
10504
- const root = import_node_path18.default.resolve(options.framework.root);
10505
- const map = import_node_path18.default.resolve(root, alias.moduleMap);
10506
- if (!map.startsWith(root + import_node_path18.default.sep))
10507
- throw new Error(`invalid framework module map ${alias.moduleMap}`);
10508
- if ((0, import_node_crypto12.createHash)("sha256").update((0, import_node_fs18.readFileSync)(map)).digest("hex") !== alias.moduleMapSha256)
10509
- throw new Error(`framework module map changed ${alias.moduleMap}`);
10510
- frameworkAliases.set(alias.name, { kind: "package", targets: closure(alias.targets) });
10511
- }
10512
- for (const name2 of objectTargets)
10513
- if (!frameworkAliases.has(name2) && targets.has(name2))
10514
- frameworkAliases.set(name2, { kind: "package", targets: closure([name2]) });
10515
- const result = /* @__PURE__ */ new Map();
10516
- const frameworkRequests = /* @__PURE__ */ new Map();
10517
- for (const image of options.images) {
10518
- if (result.has(image.id)) throw new Error(`duplicate source image ${image.id}`);
10519
- const response = import_node_path18.default.join(options.directory, `image-${image.id}-autolink.rsp`);
10520
- (0, import_node_fs18.writeFileSync)(
10521
- response,
10522
- image.objects.map((file) => JSON.stringify(file)).join("\n") + "\n"
10523
- );
10524
- const autolink = image.objects.length ? (0, import_node_child_process12.execFileSync)(
10525
- import_node_path18.default.join(options.toolchainBin, "swift-autolink-extract"),
10526
- [`@${response}`, "-o", "-"],
10527
- { encoding: "utf8" }
10528
- ).split("\n").map((line) => line.trim()).filter((line) => line.length > 0) : [];
10529
- const links = [];
10530
- const requests = [];
10531
- const optionGroups = [
10532
- { object: null, flags: image.linkerFlags, autoLinked: false },
10533
- { object: null, flags: autolink, autoLinked: true },
10534
- ...image.clangLinkOptions.map((options2) => ({ ...options2, autoLinked: true }))
10535
- ];
10536
- for (const { object: object3, flags, autoLinked } of optionGroups) {
10537
- for (let index = 0; index < flags.length; index++) {
10538
- const flag = flags[index];
10539
- const artifact = artifacts.get(flag);
10540
- if (artifact === null)
10541
- throw new Error(`ambiguous declared runtime artifact ${flag}`);
10542
- if (artifact !== void 0) {
10543
- if (!links.includes(artifact)) links.push(artifact);
10544
- continue;
10545
- }
10546
- if (import_node_path18.default.isAbsolute(flag) && flag.endsWith(".a"))
10547
- throw new Error(
10548
- `source image ${image.id} has unresolved runtime artifact ${flag}`
10549
- );
10550
- if (flag === "-framework") {
10551
- const name3 = flags[++index];
10552
- const provider = name3 && frameworkAliases.get(name3);
10553
- if (!provider && name3 && autoLinked) continue;
10554
- if (!provider)
10555
- throw new Error(
10556
- `source image ${image.id} has unresolved framework linkage ${name3}`
10557
- );
10558
- requests.push({ object: object3, provider });
10559
- continue;
10560
- }
10561
- if (flag.startsWith("-weak") || flag.startsWith("-reexport") || flag.startsWith("-upward") || flag.startsWith("-lazy") || flag.startsWith("-Wl,"))
10562
- throw new Error(
10563
- `source image ${image.id} has unsupported runtime scope flag ${flag}`
10564
- );
10565
- const name2 = flag === "-l" || flag === "--library" ? flags[++index] : flag.startsWith("-l") ? flag.slice(2) : flag.startsWith("--library=") ? flag.slice("--library=".length) : null;
10566
- if (name2 === null) continue;
10567
- const product = name2 === void 0 ? void 0 : aliases.get(name2);
10568
- if (product === void 0)
10569
- throw new Error(`source image ${image.id} has unresolved runtime link ${name2}`);
10570
- if (!links.includes(product)) links.push(product);
10571
- }
10479
+ });
10480
+ return linkGuestImages({
10481
+ ...options,
10482
+ args,
10483
+ plan: { ...options.plan, artifacts: [...options.plan.artifacts, ...candidates] }
10484
+ });
10485
+ }
10486
+ function discoverGuestLinkInputs(options) {
10487
+ const args = normalizedGuestLinkArgs(options.args);
10488
+ const artifacts = guestLinkInputFiles(args).map((file) => {
10489
+ const descriptor = import_node_fs21.default.openSync(file, "r");
10490
+ const magic = Buffer.alloc(8);
10491
+ try {
10492
+ import_node_fs21.default.readSync(descriptor, magic, 0, magic.length, 0);
10493
+ } finally {
10494
+ import_node_fs21.default.closeSync(descriptor);
10572
10495
  }
10573
- result.set(image.id, links);
10574
- frameworkRequests.set(image.id, requests);
10496
+ const kind = magic.toString("ascii") === "!<arch>\n" ? "archive" : "object";
10497
+ return { path: file, kind, image: 0, instrumentDynamicLookups: false };
10498
+ });
10499
+ const plan = { images: [], callers: [], artifacts, symbols: [] };
10500
+ import_node_fs21.default.mkdirSync(options.directory, { recursive: true });
10501
+ const why = import_node_path21.default.join(options.directory, "preselection-why.txt");
10502
+ const response = import_node_path21.default.join(options.directory, "preselection.rsp");
10503
+ const output = import_node_path21.default.join(options.directory, "preselection.wasm");
10504
+ const flags = [
10505
+ ...withOutput(args, output, true),
10506
+ ...options.objects,
10507
+ // the loader runtime backs every image's lookup wrappers, so it belongs to
10508
+ // the selection that assigns member owners.
10509
+ "--undefined=__peach_dlsym_from_image",
10510
+ `--why-extract=${why}`,
10511
+ "--trace"
10512
+ ];
10513
+ import_node_fs21.default.writeFileSync(response, flags.map((flag) => JSON.stringify(flag)).join(" "));
10514
+ const trace = import_node_path21.default.join(options.directory, "preselection-inputs.txt");
10515
+ const traceOutput = import_node_fs21.default.openSync(trace, "w");
10516
+ try {
10517
+ (0, import_node_child_process13.execFileSync)(options.wasmLd, [`@${response}`], {
10518
+ stdio: ["ignore", traceOutput, "pipe"]
10519
+ });
10520
+ } finally {
10521
+ import_node_fs21.default.closeSync(traceOutput);
10575
10522
  }
10576
- return { links: result, frameworkRequests };
10523
+ return selectedGuestLinkInputs(
10524
+ plan,
10525
+ args,
10526
+ import_node_fs21.default.readFileSync(why, "utf8"),
10527
+ import_node_fs21.default.readFileSync(trace, "utf8")
10528
+ );
10577
10529
  }
10578
- function logicalGuestLinkOptions(args, identities, roots) {
10579
- const orderedRoots = [...roots].sort(
10580
- (left, right) => right.path.length - left.path.length
10530
+ function prepareGuestRuntimeInputs(options) {
10531
+ const originals = new Map(
10532
+ [...options.rewritten].map(([before, after]) => [
10533
+ import_node_path21.default.resolve(after),
10534
+ import_node_path21.default.resolve(before)
10535
+ ])
10581
10536
  );
10582
- const logicalPath = (file) => {
10583
- const direct = identities.get(file);
10584
- if (direct !== void 0) return direct;
10585
- if (/\.(?:o|obj|a)$/.test(file))
10586
- throw new Error(`link input has no logical identity ${file}`);
10587
- for (const root of orderedRoots) {
10588
- const relative = import_node_path18.default.relative(root.path, file);
10589
- if (relative !== ".." && !relative.startsWith(`..${import_node_path18.default.sep}`) && !import_node_path18.default.isAbsolute(relative))
10590
- return `${root.identity}/${relative.split(import_node_path18.default.sep).join("/")}`;
10591
- }
10592
- throw new Error(`link option has no logical path identity ${file}`);
10593
- };
10594
- const output = [];
10595
- for (let index = 0; index < args.length; index++) {
10596
- const arg = args[index];
10597
- if (arg === "-o" || arg === "--output" || arg === "--Map") {
10598
- index++;
10599
- continue;
10600
- }
10601
- if (arg.startsWith("--output=") || arg.startsWith("--Map=")) continue;
10602
- if (arg === "-L" || arg === "--library-path") {
10603
- output.push(arg, logicalPath(args[++index]));
10604
- continue;
10605
- }
10606
- if (arg.startsWith("-L")) output.push(`-L${logicalPath(arg.slice(2))}`);
10607
- else if (arg.startsWith("--library-path="))
10608
- output.push(`--library-path=${logicalPath(arg.slice("--library-path=".length))}`);
10609
- else if (import_node_path18.default.isAbsolute(arg)) output.push(logicalPath(arg));
10610
- else if (/^[^=]+=\//.test(arg)) {
10611
- const equals = arg.indexOf("=");
10612
- output.push(arg.slice(0, equals + 1) + logicalPath(arg.slice(equals + 1)));
10613
- } else output.push(identities.get(arg) ?? arg);
10537
+ if (originals.size !== options.rewritten.size)
10538
+ throw new Error("ambiguous rewritten runtime input");
10539
+ const recordedArchives = new Set(
10540
+ options.products.flatMap(
10541
+ ({ product, root }) => product.artifacts.flatMap(
10542
+ (artifact) => artifact.kind === "archive" ? [import_node_path21.default.resolve(root, artifact.path)] : []
10543
+ )
10544
+ )
10545
+ );
10546
+ const archives = [];
10547
+ for (const file of guestLinkInputFiles(normalizedGuestLinkArgs(options.args))) {
10548
+ const original = originals.get(file) ?? file;
10549
+ if (!recordedArchives.has(original)) continue;
10550
+ const members = readArMembers(import_node_fs21.default.readFileSync(file));
10551
+ if (new Set(members.map((member) => member.name)).size === members.length) continue;
10552
+ archives.push(
10553
+ aliasGuestArchive({
10554
+ archive: file,
10555
+ directory: import_node_path21.default.join(options.directory, `archive-${archives.length}`),
10556
+ llvmAr: options.llvmAr
10557
+ })
10558
+ );
10614
10559
  }
10615
- return output;
10560
+ const args = aliasGuestLinkArguments(options.args, archives);
10561
+ const selected = discoverGuestLinkInputs({
10562
+ args,
10563
+ directory: options.directory,
10564
+ wasmLd: options.wasmLd,
10565
+ objects: options.discoveryObjects
10566
+ });
10567
+ const closure = guestRuntimeProductsForInputs({
10568
+ products: options.products,
10569
+ selected: originalGuestArchiveSelections(selected, archives),
10570
+ rewritten: options.rewritten,
10571
+ sdk: options.sdk,
10572
+ firstImage: options.firstImage,
10573
+ containingImage: options.containingImage,
10574
+ framework: options.framework
10575
+ });
10576
+ const aliasSources = new Set(
10577
+ archives.map(
10578
+ (archive) => originals.get(import_node_path21.default.resolve(archive.source)) ?? import_node_path21.default.resolve(archive.source)
10579
+ )
10580
+ );
10581
+ const sdkProducts = {
10582
+ products: options.products,
10583
+ images: closure.images,
10584
+ containingImages: closure.containingImages,
10585
+ linkedArchives: closure.linkedArchives.filter(
10586
+ (archive) => !aliasSources.has(import_node_path21.default.resolve(archive))
10587
+ )
10588
+ };
10589
+ const archiveArtifacts = guestAliasedSdkArchiveArtifacts({
10590
+ products: options.products,
10591
+ archives,
10592
+ selected,
10593
+ rewritten: options.rewritten,
10594
+ images: new Map([...closure.images, ...closure.containingImages])
10595
+ });
10596
+ return { args, selected, archives, sdkProducts, archiveArtifacts };
10616
10597
  }
10617
-
10618
- // src/wasm-optimize.ts
10619
- var import_node_child_process14 = require("node:child_process");
10620
- var import_node_fs22 = require("node:fs");
10621
- var import_node_path22 = require("node:path");
10622
- var import_node_util2 = require("node:util");
10623
-
10624
- // ../contrast-runtime-delivery/src/index.ts
10625
- var import_node_child_process13 = require("node:child_process");
10626
- var import_node_crypto13 = __toESM(require("node:crypto"), 1);
10627
- var import_node_fs20 = __toESM(require("node:fs"), 1);
10628
- var import_node_os5 = __toESM(require("node:os"), 1);
10629
- var import_node_path20 = __toESM(require("node:path"), 1);
10630
- var import_promises4 = require("node:stream/promises");
10631
- var import_node_zlib2 = __toESM(require("node:zlib"), 1);
10632
-
10633
- // ../contrast-runtime-delivery/src/product.ts
10634
- var import_node_fs19 = __toESM(require("node:fs"), 1);
10635
- var import_node_path19 = __toESM(require("node:path"), 1);
10636
-
10637
- // ../contrast-runtime-delivery/src/index.ts
10638
- async function installVerifiedTarball(tarball) {
10639
- const { destDir, installedMarker, signal } = tarball;
10640
- import_node_fs20.default.mkdirSync(import_node_path20.default.dirname(destDir), { recursive: true });
10641
- const presentAtStart = import_node_fs20.default.existsSync(import_node_path20.default.join(destDir, installedMarker));
10642
- const lock = `${destDir}.lock`;
10643
- for (; ; ) {
10644
- signal?.throwIfAborted();
10645
- try {
10646
- import_node_fs20.default.writeFileSync(lock, String(process.pid), { flag: "wx" });
10647
- break;
10648
- } catch (err) {
10649
- if (!isErrnoCode(err, "EEXIST")) throw err;
10650
- if (lockOwnerGone(lock)) import_node_fs20.default.rmSync(lock, { force: true });
10651
- else await new Promise((resolve) => setTimeout(resolve, 250));
10598
+ function selectedGuestSymbolInputs(plan, selected) {
10599
+ const artifacts = new Map(plan.artifacts.map((artifact) => [artifact.path, artifact]));
10600
+ const archives = /* @__PURE__ */ new Map();
10601
+ const symbols = /* @__PURE__ */ new Set();
10602
+ const hostImports = /* @__PURE__ */ new Set();
10603
+ const tags = /* @__PURE__ */ new Set();
10604
+ const definitions = /* @__PURE__ */ new Set();
10605
+ const owners = /* @__PURE__ */ new Map();
10606
+ const weakReferences = /* @__PURE__ */ new Map();
10607
+ const weakDefinitions = /* @__PURE__ */ new Map();
10608
+ const definitionObjects = /* @__PURE__ */ new Map();
10609
+ for (const item of selected) {
10610
+ const artifact = artifacts.get(item.artifact);
10611
+ if (!artifact) throw new Error(`selected symbol input has no owner ${item.artifact}`);
10612
+ let bytes;
10613
+ let name2 = item.artifact;
10614
+ if (item.member === null) bytes = import_node_fs21.default.readFileSync(item.artifact);
10615
+ else {
10616
+ let members = archives.get(item.artifact);
10617
+ if (!members) {
10618
+ members = Map.groupBy(
10619
+ readArMembers(import_node_fs21.default.readFileSync(item.artifact)),
10620
+ (member) => member.name
10621
+ );
10622
+ archives.set(item.artifact, members);
10623
+ }
10624
+ const matching = members.get(item.member) ?? [];
10625
+ if (matching.length !== 1)
10626
+ throw new Error(
10627
+ `ambiguous selected symbol input ${item.artifact}(${item.member})`
10628
+ );
10629
+ bytes = matching[0].bytes;
10630
+ name2 += `(${item.member})`;
10652
10631
  }
10653
- }
10654
- try {
10655
- if (!presentAtStart && import_node_fs20.default.existsSync(import_node_path20.default.join(destDir, installedMarker))) {
10656
- await tarball.verify?.(destDir);
10657
- return;
10632
+ if (owners.has(name2)) throw new Error(`duplicate selected symbol input ${name2}`);
10633
+ owners.set(name2, selectedGuestInputImage(artifact, item.member));
10634
+ const names = guestWasmSymbols(bytes);
10635
+ weakReferences.set(name2, new Set(names.weakUndefined));
10636
+ weakDefinitions.set(name2, new Set(names.weakDefined));
10637
+ for (const symbol of names.undefined) symbols.add(symbol);
10638
+ for (const symbol of names.hostImports) hostImports.add(symbol);
10639
+ for (const symbol of names.tags) tags.add(symbol);
10640
+ for (const symbol of names.defined) {
10641
+ definitions.add(symbol);
10642
+ const objects = definitionObjects.get(symbol) ?? /* @__PURE__ */ new Set();
10643
+ objects.add(name2);
10644
+ definitionObjects.set(symbol, objects);
10658
10645
  }
10659
- await installVerifiedTarballLocked(tarball, presentAtStart);
10660
- } finally {
10661
- import_node_fs20.default.rmSync(lock, { force: true });
10662
10646
  }
10647
+ return {
10648
+ symbols: [...symbols].filter((symbol) => !tags.has(symbol)),
10649
+ definitions: [...definitions].filter((symbol) => !tags.has(symbol)),
10650
+ hostImports,
10651
+ owners,
10652
+ weakReferences,
10653
+ weakDefinitions,
10654
+ definitionObjects
10655
+ };
10663
10656
  }
10664
- function lockOwnerGone(lock) {
10657
+ function verifyGuestSymbolScopes(options) {
10658
+ const symbols = [...new Set(options.symbols)];
10659
+ const requested = new Set(symbols);
10660
+ if (symbols.some((symbol) => !symbol || symbol.includes("\0") || symbol.includes("\n")))
10661
+ throw new Error("invalid traced guest symbol");
10662
+ if (!symbols.length) return { bindings: [], directBindings: [] };
10663
+ import_node_fs21.default.mkdirSync(options.directory, { recursive: true });
10664
+ const response = import_node_path21.default.join(options.directory, "scope-trace.rsp");
10665
+ const output = import_node_path21.default.join(options.directory, "scope-trace.wasm");
10666
+ const args = [
10667
+ ...withOutput(normalizedGuestLinkArgs(options.args), output, true),
10668
+ ...options.objects,
10669
+ ...symbols.map((symbol) => `--trace-symbol=${symbol}`)
10670
+ ];
10671
+ import_node_fs21.default.writeFileSync(response, args.map((arg) => JSON.stringify(arg)).join(" "));
10672
+ const tracePath = import_node_path21.default.join(options.directory, "scope-trace.txt");
10673
+ const traceOutput = import_node_fs21.default.openSync(tracePath, "w");
10665
10674
  try {
10666
- process.kill(Number(import_node_fs20.default.readFileSync(lock, "utf8")), 0);
10667
- return false;
10668
- } catch (err) {
10669
- return !isErrnoCode(err, "EPERM", "ENOENT");
10675
+ (0, import_node_child_process13.execFileSync)(options.wasmLd, [`@${response}`], {
10676
+ stdio: ["ignore", traceOutput, "pipe"]
10677
+ });
10678
+ } finally {
10679
+ import_node_fs21.default.closeSync(traceOutput);
10670
10680
  }
10671
- }
10672
- async function installVerifiedTarballLocked(tarball, presentAtStart) {
10673
- const { url, digest, destDir, installedMarker, label, signal } = tarball;
10674
- signal?.throwIfAborted();
10675
- const downloadDir = import_node_fs20.default.mkdtempSync(import_node_path20.default.join(import_node_os5.default.tmpdir(), "runtime-delivery-download-"));
10676
- const archivePath = import_node_path20.default.join(downloadDir, "archive");
10677
- const tmpDir = import_node_fs20.default.mkdtempSync(
10678
- import_node_path20.default.join(import_node_path20.default.dirname(destDir), `.installing-${import_node_path20.default.basename(destDir)}-`)
10679
- );
10680
- try {
10681
- for (let attempt = 1; ; attempt++) {
10682
- await downloadToFile(url, archivePath, signal);
10683
- const actual = await digestFile(
10684
- archivePath,
10685
- digest.algorithm,
10686
- digest.encoding,
10687
- signal
10681
+ const records = /* @__PURE__ */ new Map();
10682
+ const consume = (line) => {
10683
+ const match = /^(.*): (reference to|definition of) (.*)$/.exec(line);
10684
+ if (!match) return;
10685
+ const [, object3, kind, symbol] = match;
10686
+ if (!requested.has(symbol)) return;
10687
+ if (options.hostImports.has(symbol)) return;
10688
+ const record = records.get(symbol) ?? {
10689
+ references: /* @__PURE__ */ new Map(),
10690
+ providers: /* @__PURE__ */ new Map(),
10691
+ physicalModule: false
10692
+ };
10693
+ if (object3 === "<internal>") {
10694
+ if (kind === "definition of") record.physicalModule = true;
10695
+ } else {
10696
+ const image = options.owners.get(object3);
10697
+ if (image === void 0)
10698
+ throw new Error(`traced guest object has no owner ${object3}`);
10699
+ (kind === "reference to" ? record.references : record.providers).set(
10700
+ object3,
10701
+ image
10688
10702
  );
10689
- if (actual === digest.value) break;
10690
- if (attempt >= 2) {
10691
- throw new Error(
10692
- `${digest.algorithm} mismatch for ${label}: expected ${digest.value}, actual ${actual}`
10693
- );
10703
+ }
10704
+ records.set(symbol, record);
10705
+ };
10706
+ const traceInput = import_node_fs21.default.openSync(tracePath, "r");
10707
+ try {
10708
+ const decoder = new import_node_string_decoder.StringDecoder("utf8");
10709
+ const buffer = Buffer.allocUnsafe(64 * 1024);
10710
+ let pending = "";
10711
+ let count;
10712
+ while ((count = import_node_fs21.default.readSync(traceInput, buffer, 0, buffer.length, null)) > 0) {
10713
+ pending += decoder.write(buffer.subarray(0, count));
10714
+ let end;
10715
+ while ((end = pending.indexOf("\n")) !== -1) {
10716
+ consume(pending.slice(0, end));
10717
+ pending = pending.slice(end + 1);
10718
+ }
10719
+ }
10720
+ consume(pending + decoder.end());
10721
+ } finally {
10722
+ import_node_fs21.default.closeSync(traceInput);
10723
+ }
10724
+ const callers = new Map(options.callers.map((caller) => [caller.image, caller.next]));
10725
+ const result = [];
10726
+ const directBindings = [];
10727
+ for (const symbol of symbols) {
10728
+ const record = records.get(symbol);
10729
+ if (!record || !record.references.size) continue;
10730
+ if (!record.providers.size && options.hostImports.has(symbol)) continue;
10731
+ const startupReferences = [...record.references].filter(
10732
+ ([object3]) => options.startupObjects.has(object3) && options.weakReferences.get(object3)?.has(symbol)
10733
+ );
10734
+ const otherReferences = [...record.references].filter(
10735
+ ([object3]) => !startupReferences.some(([startup]) => startup === object3)
10736
+ );
10737
+ for (const [, caller] of startupReferences)
10738
+ if (!callers.has(caller))
10739
+ throw new Error(`guest image has no caller scope ${caller}`);
10740
+ if (startupReferences.length && !record.physicalModule) {
10741
+ const candidates = options.definitionObjects.get(symbol) ?? /* @__PURE__ */ new Set();
10742
+ if (candidates.size > 1 || record.providers.size > 1)
10743
+ throw new Error(`ambiguous startup provider ${symbol}`);
10744
+ if (candidates.size !== record.providers.size || [...record.providers.keys()].some((object3) => !candidates.has(object3)))
10745
+ throw new Error(`unproven startup provider ${symbol}`);
10746
+ if (record.providers.size === 1) {
10747
+ const [providerObject, providerImage] = [...record.providers][0];
10748
+ if (options.weakDefinitions.get(providerObject)?.has(symbol))
10749
+ throw new Error(`weak startup provider ${symbol}`);
10750
+ for (const [object3] of startupReferences)
10751
+ directBindings.push({ object: object3, symbol, providerObject, providerImage });
10694
10752
  }
10753
+ if (!otherReferences.length) continue;
10695
10754
  }
10696
- const { pathname } = new URL(url);
10697
- if (pathname.endsWith(".zip")) await extractZip(archivePath, tmpDir, signal);
10698
- else
10699
- await extractTarball(
10700
- archivePath,
10701
- pathname.endsWith(".tar.zst"),
10702
- tmpDir,
10703
- tarball.stripComponents ?? 0,
10704
- signal
10705
- );
10706
- signal?.throwIfAborted();
10707
- if (!import_node_fs20.default.existsSync(import_node_path20.default.join(tmpDir, installedMarker))) {
10708
- throw new Error(`extracted tarball for ${label} is missing ${installedMarker}`);
10709
- }
10710
- await tarball.verify?.(tmpDir);
10711
- signal?.throwIfAborted();
10712
- try {
10713
- import_node_fs20.default.renameSync(tmpDir, destDir);
10714
- } catch (err) {
10715
- if (!isErrnoCode(err, "ENOTEMPTY", "EEXIST")) throw err;
10716
- if (!presentAtStart && import_node_fs20.default.existsSync(import_node_path20.default.join(destDir, installedMarker))) {
10717
- await tarball.verify?.(destDir);
10718
- return;
10755
+ if (!record.providers.size && !record.physicalModule && [...record.references.keys()].every(
10756
+ (object3) => options.weakReferences.get(object3)?.has(symbol)
10757
+ ))
10758
+ continue;
10759
+ const providerImages = new Set(record.providers.values());
10760
+ const copies = [...options.definitionObjects.get(symbol) ?? []].flatMap(
10761
+ (object3) => {
10762
+ const image = options.owners.get(object3);
10763
+ return image === void 0 ? [] : [{ image, weak: !!options.weakDefinitions.get(object3)?.has(symbol) }];
10719
10764
  }
10720
- const aside = `${tmpDir}-replaced`;
10721
- try {
10722
- import_node_fs20.default.renameSync(destDir, aside);
10723
- } catch (moveErr) {
10724
- if (!isErrnoCode(moveErr, "ENOENT")) throw moveErr;
10765
+ );
10766
+ const copyImages = new Set(copies.map((copy) => copy.image));
10767
+ const strongImages = new Set(
10768
+ copies.filter((copy) => !copy.weak).map((copy) => copy.image)
10769
+ );
10770
+ const interposed = !record.physicalModule && copyImages.size > 1 && strongImages.size <= 1;
10771
+ const providerCount = interposed ? 1 : providerImages.size + Number(record.physicalModule);
10772
+ if (!providerCount) continue;
10773
+ if (providerCount !== 1)
10774
+ throw new Error(`guest symbol has ambiguous provider ${symbol}`);
10775
+ const scopedReferences = record.physicalModule ? [...record.references] : otherReferences;
10776
+ for (const [object3, caller] of scopedReferences) {
10777
+ const scope = callers.get(caller);
10778
+ if (!scope) throw new Error(`guest image has no caller scope ${caller}`);
10779
+ if (record.physicalModule) {
10780
+ result.push({ symbol, caller, provider: { kind: "physical-module" } });
10781
+ continue;
10725
10782
  }
10726
- try {
10727
- import_node_fs20.default.renameSync(tmpDir, destDir);
10728
- } catch (landErr) {
10729
- if (!isErrnoCode(landErr, "ENOTEMPTY", "EEXIST") || !import_node_fs20.default.existsSync(import_node_path20.default.join(destDir, installedMarker))) {
10730
- throw landErr;
10731
- }
10732
- await tarball.verify?.(destDir);
10733
- } finally {
10734
- import_node_fs20.default.rmSync(aside, { recursive: true, force: true });
10783
+ const provider = interposed ? [caller, ...scope].find((image) => copyImages.has(image)) ?? [...strongImages][0] ?? [...providerImages][0] : [...providerImages][0];
10784
+ if (provider === void 0)
10785
+ throw new Error(`guest scope ${caller} omits every provider of ${symbol}`);
10786
+ if (caller === provider) continue;
10787
+ if ([...options.definitionObjects.get(symbol) ?? []].some(
10788
+ (definer) => options.owners.get(definer) === caller && options.weakDefinitions.get(definer)?.has(symbol)
10789
+ ))
10790
+ continue;
10791
+ if (!scope.includes(provider)) {
10792
+ const candidates = options.definitionObjects.get(symbol) ?? /* @__PURE__ */ new Set();
10793
+ const traced = [...record.providers.keys()];
10794
+ const strongTraced = traced.filter(
10795
+ (definer) => !options.weakDefinitions.get(definer)?.has(symbol)
10796
+ );
10797
+ const providers = strongTraced.length === 1 ? strongTraced : traced;
10798
+ if (options.weakReferences.get(object3)?.has(symbol) && !providers.some((provider2) => options.systemProviders.has(provider2)))
10799
+ continue;
10800
+ const equivalentCopies = providers.length === 1 && candidates.has(providers[0]) && [...candidates].every(
10801
+ (definer) => options.weakDefinitions.get(definer)?.has(symbol)
10802
+ );
10803
+ const strongCandidates = [...candidates].filter(
10804
+ (definer) => !options.weakDefinitions.get(definer)?.has(symbol)
10805
+ );
10806
+ const soleCandidate = candidates.size === 1 || strongCandidates.length === 1 && strongCandidates[0] === providers[0];
10807
+ if (!equivalentCopies && (!soleCandidate || providers.length !== 1 || !candidates.has(providers[0]) || !(options.systemProviders.has(providers[0]) || // a strong undefined reference binds through the process global
10808
+ // scope, the root image and its dependency closure, as in elf.
10809
+ provider === 0 || callers.get(0)?.includes(provider) || !options.weakReferences.get(object3)?.has(symbol) && options.frameworkProviders.get(object3)?.has(providers[0]))))
10810
+ throw new Error(
10811
+ `guest scope ${caller} omits traced provider ${provider} for ${symbol}`
10812
+ );
10813
+ directBindings.push({
10814
+ object: object3,
10815
+ symbol,
10816
+ providerObject: providers[0],
10817
+ providerImage: provider
10818
+ });
10819
+ continue;
10735
10820
  }
10821
+ result.push({ symbol, caller, provider: { kind: "image", image: provider } });
10736
10822
  }
10737
- } finally {
10738
- import_node_fs20.default.rmSync(tmpDir, { recursive: true, force: true });
10739
- import_node_fs20.default.rmSync(downloadDir, { recursive: true, force: true });
10740
10823
  }
10824
+ return { bindings: result, directBindings };
10741
10825
  }
10742
- function isErrnoCode(err, ...codes) {
10743
- return err instanceof Error && "code" in err && codes.includes(String(err.code));
10744
- }
10745
- var DownloadHttpError = class extends Error {
10746
- retryable;
10747
- constructor(status, statusText, url) {
10748
- super(`download failed: ${status} ${statusText} (${url})`);
10749
- this.retryable = status < 400 || status >= 500 || status === 408 || status === 429;
10750
- }
10751
- };
10752
- async function waitRetryDelay(ms, signal) {
10753
- signal?.throwIfAborted();
10754
- await new Promise((resolve, reject) => {
10755
- const onAbort = () => {
10756
- clearTimeout(timer);
10757
- const reason = signal?.reason;
10758
- reject(
10759
- reason instanceof Error ? reason : new Error("Download canceled", { cause: reason })
10826
+ function linkPrunedGuestImages(options) {
10827
+ let result;
10828
+ pruneSwiftWasmLink(
10829
+ options.buildDirectory,
10830
+ options.toolchainBin,
10831
+ options.moduleRoot,
10832
+ options.staticClangTargets,
10833
+ void 0,
10834
+ (args, rewritten, sdk) => {
10835
+ if (args.some((arg) => arg === "--Map" || arg.startsWith("--Map=")))
10836
+ throw new Error("guest link already has a linker map");
10837
+ const framework = options.framework;
10838
+ const prepared = options.prepareRuntime?.(args, rewritten, sdk);
10839
+ if (prepared && options.sdkProducts !== null)
10840
+ throw new Error("guest runtime products supplied twice");
10841
+ const linkedArgs = prepared?.args ?? args;
10842
+ const sdkProducts = prepared?.sdkProducts ?? (typeof options.sdkProducts === "function" ? options.sdkProducts(args, rewritten, sdk) : options.sdkProducts);
10843
+ const sourcePlan = options.plan(linkedArgs, rewritten, sdk, sdkProducts);
10844
+ let frameworkArtifacts = [];
10845
+ const selectedObjects = prepared && new Set(
10846
+ prepared.selected.filter((item) => item.member === null).map((item) => import_node_path21.default.resolve(item.artifact))
10760
10847
  );
10761
- };
10762
- const timer = setTimeout(() => {
10763
- signal?.removeEventListener("abort", onAbort);
10764
- resolve();
10765
- }, ms);
10766
- signal?.addEventListener("abort", onAbort, { once: true });
10767
- });
10768
- }
10769
- async function downloadToFile(url, destPath, signal) {
10770
- import_node_fs20.default.mkdirSync(import_node_path20.default.dirname(destPath), { recursive: true });
10771
- const tmp = `${destPath}.partial`;
10772
- for (let attempt = 1; attempt <= 4; attempt++) {
10773
- signal?.throwIfAborted();
10774
- let reader2;
10775
- let handle;
10776
- let completed = false;
10777
- try {
10778
- const res = await fetch(url, { signal });
10779
- if (!res.ok || !res.body) {
10780
- throw new DownloadHttpError(res.status, res.statusText, url);
10781
- }
10782
- reader2 = res.body.getReader();
10783
- handle = await import_node_fs20.default.promises.open(tmp, "w");
10784
- let written = 0;
10785
- for (; ; ) {
10786
- signal?.throwIfAborted();
10787
- const { done, value } = await reader2.read();
10788
- if (done) break;
10789
- let offset = 0;
10790
- while (offset < value.byteLength) {
10791
- const { bytesWritten } = await handle.write(
10792
- value,
10793
- offset,
10794
- value.byteLength - offset
10848
+ const selectedFramework = framework && (!prepared || framework.product.objects.some((object3) => {
10849
+ const original = import_node_path21.default.resolve(framework.root, object3.path);
10850
+ const linked = import_node_path21.default.resolve(rewritten.get(original) ?? original);
10851
+ return selectedObjects?.has(linked) ?? false;
10852
+ }));
10853
+ if (framework && selectedFramework) {
10854
+ const image = sdkProducts?.images.get(
10855
+ frameworkRuntimeProductId(framework.product)
10856
+ );
10857
+ if (image === void 0)
10858
+ throw new Error(
10859
+ "framework objects require their declared compiler runtime image"
10795
10860
  );
10796
- offset += bytesWritten;
10861
+ frameworkArtifacts = guestFrameworkLinkArtifacts(
10862
+ framework.product,
10863
+ framework.root,
10864
+ linkedArgs,
10865
+ rewritten,
10866
+ image
10867
+ );
10868
+ }
10869
+ if (sdkProducts) {
10870
+ for (const image of guestSdkProductImages(
10871
+ sdkProducts.products.map((entry) => entry.product),
10872
+ sdkProducts.images
10873
+ )) {
10874
+ const planned = sourcePlan.images.find((entry) => entry.id === image.id);
10875
+ if (!planned || planned.name !== image.name || planned.dependencies.length !== image.dependencies.length || planned.dependencies.some(
10876
+ (dependency, index) => dependency !== image.dependencies[index]
10877
+ ))
10878
+ throw new Error(`SDK image scope differs from source product ${image.name}`);
10879
+ }
10880
+ }
10881
+ const plan = remapGuestLinkPlan(
10882
+ {
10883
+ ...sourcePlan,
10884
+ artifacts: [
10885
+ ...sourcePlan.artifacts,
10886
+ ...frameworkArtifacts,
10887
+ ...sdkProducts ? guestSdkProductLinkArtifacts(
10888
+ sdkProducts.products,
10889
+ sdk,
10890
+ linkedArgs,
10891
+ sdkProducts.linkedArchives,
10892
+ rewritten,
10893
+ new Map([...sdkProducts.images, ...sdkProducts.containingImages]),
10894
+ prepared?.selected
10895
+ ) : [],
10896
+ ...prepared?.archiveArtifacts ?? []
10897
+ ]
10898
+ },
10899
+ rewritten
10900
+ );
10901
+ let owners = /* @__PURE__ */ new Map();
10902
+ let generatedSectionOwners = /* @__PURE__ */ new Map();
10903
+ let projection = typeof options.projection === "function" ? options.projection(linkedArgs, rewritten, sdk, sdkProducts, plan) : options.projection;
10904
+ if (projection && prepared) {
10905
+ const identities = new Map(projection.identities);
10906
+ for (const [before, after] of rewritten) {
10907
+ const identity = identities.get(before);
10908
+ const existing = identities.get(after);
10909
+ if (identity !== void 0 && existing !== void 0 && existing !== identity)
10910
+ throw new Error(`rewritten guest input has conflicting identity ${after}`);
10911
+ if (identity !== void 0) identities.set(after, identity);
10797
10912
  }
10798
- written += value.byteLength;
10913
+ projection = {
10914
+ ...projection,
10915
+ identities: aliasGuestLinkIdentities(identities, prepared.archives)
10916
+ };
10799
10917
  }
10800
- await handle.close();
10801
- handle = void 0;
10802
- if (!res.headers.get("content-encoding")) {
10803
- const header = res.headers.get("content-length");
10804
- const expected = header ? Number(header) : Number.NaN;
10805
- if (Number.isFinite(expected) && expected > 0 && written !== expected) {
10806
- throw new Error(`incomplete download (${written}/${expected} bytes): ${url}`);
10918
+ const selected = linkCompleteGuestImages({
10919
+ plan,
10920
+ args: [...linkedArgs, `--Map=${options.mapPath}`],
10921
+ directory: options.linkDirectory,
10922
+ wasmLd: import_node_path21.default.join(options.toolchainBin, "wasm-ld"),
10923
+ clang: import_node_path21.default.join(options.toolchainBin, "clang"),
10924
+ llvmAr: import_node_path21.default.join(options.toolchainBin, "llvm-ar"),
10925
+ ledgerDataImage: options.ledgerDataImage,
10926
+ projection,
10927
+ resolvePlan: options.resolvePlan,
10928
+ onLinkedOwners: (value) => {
10929
+ owners = value;
10930
+ },
10931
+ onLinkedSections: (value) => {
10932
+ generatedSectionOwners = value;
10807
10933
  }
10808
- }
10809
- signal?.throwIfAborted();
10810
- import_node_fs20.default.renameSync(tmp, destPath);
10811
- completed = true;
10812
- return;
10813
- } catch (err) {
10814
- if (handle) await handle.close().catch(() => {
10815
- });
10816
- if (reader2 && !completed) await reader2.cancel().catch(() => {
10817
- });
10818
- try {
10819
- import_node_fs20.default.unlinkSync(tmp);
10820
- } catch {
10821
- }
10822
- const nonRetryable = err instanceof DownloadHttpError && !err.retryable;
10823
- if (signal?.aborted || nonRetryable || attempt === 4) throw err;
10824
- await waitRetryDelay(250 * attempt, signal);
10825
- }
10826
- }
10827
- }
10828
- async function digestFile(filePath, algorithm, encoding, signal) {
10829
- const hash = import_node_crypto13.default.createHash(algorithm);
10830
- await (0, import_promises4.pipeline)(import_node_fs20.default.createReadStream(filePath), hash, { signal });
10831
- return hash.digest(encoding);
10832
- }
10833
- function extractZip(zipPath, destDir, signal) {
10834
- return runExtractor("ditto", ["-x", "-k", zipPath, destDir], signal);
10835
- }
10836
- async function extractTarball(tarPath, zstd, destDir, stripComponents, signal) {
10837
- const args = [zstd ? "-xf" : "-xzf", "-"];
10838
- if (stripComponents > 0) args.push(`--strip-components=${stripComponents}`);
10839
- if (zstd) {
10840
- const decoder = import_node_zlib2.default.createZstdDecompress({
10841
- params: { [import_node_zlib2.default.constants.ZSTD_d_windowLogMax]: 30 }
10842
- });
10843
- await runExtractor("tar", ["--ignore-zeros", ...args], signal, {
10844
- cwd: destDir,
10845
- stdin: (stdin) => (0, import_promises4.pipeline)(import_node_fs20.default.createReadStream(tarPath), decoder, stdin, { signal })
10846
- });
10847
- return;
10848
- }
10849
- const archive = import_node_fs20.default.openSync(tarPath, "r");
10850
- try {
10851
- await runExtractor("tar", args, signal, { cwd: destDir, stdin: archive });
10852
- } finally {
10853
- import_node_fs20.default.closeSync(archive);
10854
- }
10855
- }
10856
- async function runExtractor(command, args, signal, input) {
10857
- signal?.throwIfAborted();
10858
- const stdin = input?.stdin;
10859
- const stdio = [
10860
- typeof stdin === "function" ? "pipe" : stdin ?? "ignore",
10861
- "inherit",
10862
- "inherit"
10863
- ];
10864
- const child = (0, import_node_child_process13.spawn)(command, args, {
10865
- cwd: input?.cwd,
10866
- stdio,
10867
- detached: process.platform !== "win32"
10868
- });
10869
- const fed = typeof stdin === "function" && child.stdin ? stdin(child.stdin) : void 0;
10870
- void fed?.catch(() => {
10871
- });
10872
- let stopping;
10873
- const abort = () => {
10874
- stopping ??= terminateProcessGroup(child, "SIGKILL", 0);
10875
- void stopping.catch(() => {
10876
- });
10877
- };
10878
- try {
10879
- await new Promise((resolve, reject) => {
10880
- let failure;
10881
- child.on("error", (error) => {
10882
- failure = error;
10883
- });
10884
- child.on("close", (code) => {
10885
- if (signal?.aborted) {
10886
- const reason = signal.reason;
10887
- reject(
10888
- reason instanceof Error ? reason : new Error("Extraction canceled", { cause: reason })
10889
- );
10890
- } else if (failure) reject(failure);
10891
- else if (code === 0) resolve();
10892
- else reject(new Error(`${command} exited with code ${code}`));
10893
10934
  });
10894
- signal?.addEventListener("abort", abort, { once: true });
10895
- if (signal?.aborted) abort();
10896
- });
10897
- await fed;
10898
- } finally {
10899
- signal?.removeEventListener("abort", abort);
10900
- await stopping;
10901
- }
10902
- }
10903
-
10904
- // src/binaryen.lock.json
10905
- var binaryen_lock_default = {
10906
- version: "132",
10907
- licenseSha256: "64c0d02491e16eced74826440ecd2bcf7722d37fa586faf457b2494293afbffe",
10908
- platforms: {
10909
- "linux-x64": {
10910
- asset: "x86_64-linux",
10911
- upstreamSha256: "195ddc94f9bc89f45abdabb0b9eea86023d727ba90eac8b35b80f2544fc30572",
10912
- sha256: "0396b1a540e9f97f30eb6a378d829305c218c821a0bd88c74e83d3d6923dad0b"
10913
- },
10914
- "linux-arm64": {
10915
- asset: "aarch64-linux",
10916
- upstreamSha256: "c58562417836c5d0493d89bdefc434933bdc097db641b483df86bcfa557a107f",
10917
- sha256: "25e3747f19614b0281a28b9a909ddc602b546ccdfacebc8cae2f7165665328fa"
10935
+ result = {
10936
+ selected,
10937
+ owners,
10938
+ generatedSectionOwners,
10939
+ sdk,
10940
+ mapPath: options.mapPath,
10941
+ generatedLedgerObject: import_node_path21.default.join(options.linkDirectory, "ledger.o")
10942
+ };
10918
10943
  },
10919
- "darwin-arm64": {
10920
- asset: "arm64-macos",
10921
- upstreamSha256: "98aad827847af7ef990ed7098d885725c8e5b5aae75073403635617ae4e259aa",
10922
- sha256: "34281566fe32df71337aaf0b60aa265dc853587d92bda0b5b1fac8aed8c2f8ab"
10923
- }
10924
- }
10925
- };
10944
+ options.resourceReferences
10945
+ );
10946
+ if (!result) throw new Error("guest link did not receive pruned inputs");
10947
+ return result;
10948
+ }
10926
10949
 
10927
- // src/home-paths.ts
10950
+ // src/swift-guest-source-inputs.ts
10951
+ var import_node_child_process14 = require("node:child_process");
10928
10952
  var import_node_crypto14 = require("node:crypto");
10929
- var import_node_fs21 = __toESM(require("node:fs"), 1);
10930
- var import_node_os6 = require("node:os");
10931
- var import_node_path21 = __toESM(require("node:path"), 1);
10932
- var PEACH_HOME_ENV = "PEACH_HOME";
10933
- function ambientHomeDir() {
10934
- return import_node_path21.default.join((0, import_node_os6.homedir)(), ".peach");
10935
- }
10936
- function rnxHomeDir() {
10937
- const override = process.env[PEACH_HOME_ENV];
10938
- return override && override.length > 0 ? import_node_path21.default.resolve(override) : ambientHomeDir();
10939
- }
10940
- var DAEMON_LOCKFILE_MAX_BYTES = 16 * 1024;
10953
+ var import_node_fs22 = require("node:fs");
10954
+ var import_node_path22 = __toESM(require("node:path"), 1);
10941
10955
 
10942
- // src/wasm-narrow-boundary.ts
10943
- var I64 = 126;
10944
- var VALUE_TYPES = /* @__PURE__ */ new Map([
10945
- [127, "i32"],
10946
- [I64, "i64"],
10947
- [125, "f32"],
10948
- [124, "f64"],
10949
- [123, "v128"],
10950
- [112, "funcref"],
10951
- [111, "externref"]
10952
- ]);
10953
- var GUEST = "guest";
10954
- var BOUNDARY = "boundary";
10955
- var WIDE = "$wide.";
10956
- var NARROW = "$narrow.";
10957
- function encodeNumber2(value) {
10958
- const bytes = [];
10959
- for (let rest = value; ; ) {
10960
- const byte = rest % 128;
10961
- rest = Math.floor(rest / 128);
10962
- if (rest === 0) return [...bytes, byte];
10963
- bytes.push(byte | 128);
10956
+ // src/forked-script-contract.ts
10957
+ var PEACH_FORKED_SCRIPT_ENV = "PEACH_RUNS_FORKED_SCRIPTS";
10958
+
10959
+ // src/swift-guest-source-inputs.ts
10960
+ function clangIrLinkOptions(ir) {
10961
+ const list = /^!llvm\.linker\.options = !\{([^\n]*)\}$/m.exec(ir);
10962
+ if (!list) {
10963
+ if (/^!llvm\.linker\.options\s*=/m.test(ir))
10964
+ throw new Error("invalid clang link metadata list");
10965
+ return [];
10964
10966
  }
10967
+ const ids = list[1].split(",").map((item) => item.trim());
10968
+ if (ids.length === 1 && ids[0] === "") return [];
10969
+ const result = [];
10970
+ for (const id of ids) {
10971
+ if (!/^!\d+$/.test(id)) throw new Error(`invalid clang link metadata ${id}`);
10972
+ const node = new RegExp(`^${id} = !\\{([^\\n]*)\\}$`, "m").exec(ir);
10973
+ if (!node) throw new Error(`missing clang link metadata ${id}`);
10974
+ const parts = node[1].split(/,\s*(?=!")/);
10975
+ for (const part of parts) {
10976
+ const value = /^!"((?:[^"\\]|\\[0-9A-Fa-f]{2})*)"$/.exec(part.trim());
10977
+ if (!value) throw new Error(`invalid clang link option ${part}`);
10978
+ const decoded = value[1].replace(
10979
+ /\\([0-9A-Fa-f]{2})/g,
10980
+ (_, hex) => String.fromCharCode(Number.parseInt(hex, 16))
10981
+ );
10982
+ const flag = Buffer.from(decoded, "latin1").toString("utf8");
10983
+ if (!flag || flag.includes("\0")) throw new Error("invalid empty clang link option");
10984
+ result.push(flag);
10985
+ }
10986
+ }
10987
+ return result;
10965
10988
  }
10966
- function encodeName(name2) {
10967
- const bytes = [...Buffer.from(name2)];
10968
- return [...encodeNumber2(bytes.length), ...bytes];
10989
+ var CLANG_TARGET_MODULE_WRAPPER = ".peach-clang";
10990
+ var PARALLEL_REPLAY = `
10991
+ const { spawn } = require('node:child_process')
10992
+ const commands = JSON.parse(require('node:fs').readFileSync(process.env.PEACH_CLANG_REPLAYS, 'utf8'))
10993
+ let next = 0
10994
+ const run = () => {
10995
+ if (next >= commands.length) return Promise.resolve()
10996
+ const [file, ...args] = commands[next++]
10997
+ return new Promise((resolve, reject) => {
10998
+ const child = spawn(file, args, { stdio: 'inherit' })
10999
+ child.on('error', reject)
11000
+ child.on('close', (code) => (code === 0 ? resolve() : reject(new Error('clang link replay failed: ' + file))))
11001
+ }).then(run)
10969
11002
  }
10970
- function reader(bytes, start, end) {
10971
- let at = start;
10972
- const number3 = () => {
10973
- let value = 0;
10974
- for (let shift = 0; ; shift += 7) {
10975
- if (at >= end || shift > 63) throw new Error("invalid wasm integer");
10976
- const byte = bytes[at++];
10977
- value += (byte & 127) * 2 ** shift;
10978
- if (!(byte & 128)) return value;
11003
+ const jobs = Math.max(1, Number(process.env.PEACH_CLANG_JOBS) || 1)
11004
+ Promise.all(Array.from({ length: jobs }, run)).catch((error) => {
11005
+ console.error(error.message)
11006
+ process.exit(1)
11007
+ })
11008
+ `;
11009
+ function sourceGuestClangLinkOptions(options) {
11010
+ const wanted = new Set(options.objects.map((file) => import_node_path22.default.resolve(file)));
11011
+ const commands = /* @__PURE__ */ new Map();
11012
+ let tool = "";
11013
+ let outputs = [];
11014
+ for (const line of (0, import_node_fs22.readFileSync)(
11015
+ import_node_path22.default.join(options.buildDirectory, ".build", "release.yaml"),
11016
+ "utf8"
11017
+ ).split("\n")) {
11018
+ if (line.startsWith(' "') && line.endsWith(":")) {
11019
+ tool = "";
11020
+ outputs = [];
11021
+ continue;
11022
+ }
11023
+ if (line.startsWith(" tool: ")) tool = line.slice(10).trim();
11024
+ if (line.startsWith(" outputs: ")) {
11025
+ const value2 = JSON.parse(line.slice(13));
11026
+ if (!Array.isArray(value2) || !value2.every((item) => typeof item === "string"))
11027
+ throw new Error("invalid build command outputs");
11028
+ outputs = value2;
11029
+ }
11030
+ if (!line.startsWith(" args: ") || !outputs.some((file) => wanted.has(import_node_path22.default.resolve(file))))
11031
+ continue;
11032
+ const value = JSON.parse(line.slice(10));
11033
+ if (!Array.isArray(value) || !value.every((item) => typeof item === "string"))
11034
+ throw new Error("invalid build command arguments");
11035
+ for (const output of outputs) {
11036
+ const file = import_node_path22.default.resolve(output);
11037
+ if (!wanted.has(file)) continue;
11038
+ if (commands.has(file)) throw new Error(`ambiguous source object producer ${file}`);
11039
+ commands.set(file, { tool, args: value });
10979
11040
  }
10980
- };
10981
- return {
10982
- number: number3,
10983
- byte: () => {
10984
- if (at >= end) throw new Error("truncated wasm section");
10985
- return bytes[at++];
10986
- },
10987
- name: () => {
10988
- const length = number3();
10989
- at += length;
10990
- if (at > end) throw new Error("truncated wasm name");
10991
- return Buffer.from(bytes.subarray(at - length, at)).toString();
10992
- },
10993
- position: () => at,
10994
- done: () => at === end
10995
- };
10996
- }
10997
- function sections(bytes) {
10998
- if (Buffer.from(bytes.subarray(0, 8)).toString("hex") !== "0061736d01000000")
10999
- throw new Error("not a wasm module");
11000
- const found = [];
11001
- for (let at = 8; at < bytes.length; ) {
11002
- const header = reader(bytes, at, bytes.length);
11003
- const id = header.byte();
11004
- const size = header.number();
11005
- const start = header.position();
11006
- found.push({ id, start, end: start + size });
11007
- at = start + size;
11008
11041
  }
11009
- return found;
11010
- }
11011
- function withSections(bytes, layout2, replacements) {
11012
- const parts = [bytes.subarray(0, 8)];
11013
- let at = 8;
11014
- for (const section of layout2) {
11015
- const body = replacements.get(section.id);
11016
- parts.push(
11017
- body ? Uint8Array.from([section.id, ...encodeNumber2(body.length), ...body]) : bytes.subarray(at, section.end)
11042
+ const replays = [];
11043
+ for (const [index, file] of [...wanted].entries()) {
11044
+ const command = commands.get(file);
11045
+ if (!command) throw new Error(`missing source object producer ${file}`);
11046
+ if (command.tool === "shell") {
11047
+ if (!command.args.length || (0, import_node_fs22.realpathSync)(command.args[0]) !== (0, import_node_fs22.realpathSync)(options.swiftCompiler))
11048
+ throw new Error(`unsupported source object producer ${file}`);
11049
+ continue;
11050
+ }
11051
+ const compiler = command.args[0] ? (0, import_node_fs22.realpathSync)(command.args[0]) : "";
11052
+ if (command.tool !== "clang" || compiler !== (0, import_node_fs22.realpathSync)(import_node_path22.default.join(options.toolchainBin, "clang")) && compiler !== (0, import_node_fs22.realpathSync)(import_node_path22.default.join(options.buildDirectory, CLANG_TARGET_MODULE_WRAPPER)))
11053
+ throw new Error(`unsupported source object producer ${file}`);
11054
+ const args = command.args.slice(1).filter((arg) => arg !== "-c");
11055
+ const targetBuild = import_node_path22.default.relative(options.buildDirectory, file).split(import_node_path22.default.sep).findLast((part) => part !== ".build" && part.endsWith(".build"));
11056
+ const outputDirectory = import_node_path22.default.join(
11057
+ options.directory,
11058
+ targetBuild ?? import_node_path22.default.basename(import_node_path22.default.dirname(file))
11018
11059
  );
11019
- at = section.end;
11060
+ (0, import_node_fs22.mkdirSync)(outputDirectory, { recursive: true });
11061
+ const output = import_node_path22.default.join(outputDirectory, `clang-link-${index}.ll`);
11062
+ for (const flag of ["-o", "-MF"]) {
11063
+ const index2 = args.lastIndexOf(flag);
11064
+ if (index2 < 0 || index2 + 1 >= args.length)
11065
+ throw new Error(`missing clang ${flag} for ${file}`);
11066
+ args[index2 + 1] = flag === "-o" ? output : `${output}.d`;
11067
+ }
11068
+ replays.push({
11069
+ file,
11070
+ compiler: command.args[0],
11071
+ args: [...args, "-S", "-emit-llvm", "-Xclang", "-disable-llvm-passes"],
11072
+ output
11073
+ });
11020
11074
  }
11021
- return Buffer.concat(parts);
11022
- }
11023
- var quoted = (name2) => `"${[...Buffer.from(name2)].map((byte) => `\\${byte.toString(16).padStart(2, "0")}`).join("")}"`;
11024
- var signature = (types, keyword, narrow) => types.length === 0 ? "" : ` (${keyword} ${types.map((type) => {
11025
- const name2 = VALUE_TYPES.get(narrow && type === I64 ? 127 : type);
11026
- if (!name2) throw new Error(`unsupported wasm boundary type ${type}`);
11027
- return name2;
11028
- }).join(" ")})`;
11029
- var wide = (type) => type.parameters.includes(I64) || type.results.includes(I64);
11030
- function narrowWasmBoundary(bytes) {
11031
- const layout2 = sections(bytes);
11032
- const section = (id) => {
11033
- const found = layout2.find((entry) => entry.id === id);
11034
- return found && reader(bytes, found.start, found.end);
11035
- };
11036
- const types = [];
11037
- const typeSection = section(1);
11038
- if (typeSection) {
11039
- for (let count = typeSection.number(); count > 0; count--) {
11040
- if (typeSection.byte() !== 96) throw new Error("unsupported wasm type");
11041
- const values = () => Array.from({ length: typeSection.number() }, () => typeSection.byte());
11042
- types.push({ parameters: values(), results: values() });
11075
+ const plan = import_node_path22.default.join(options.directory, "clang-link-replays.json");
11076
+ (0, import_node_fs22.writeFileSync)(
11077
+ plan,
11078
+ JSON.stringify(replays.map(({ compiler, args }) => [compiler, ...args]))
11079
+ );
11080
+ const script = import_node_path22.default.join(options.directory, "clang-link-replay.cjs");
11081
+ (0, import_node_fs22.writeFileSync)(script, PARALLEL_REPLAY);
11082
+ (0, import_node_child_process14.execFileSync)(process.execPath, [script], {
11083
+ stdio: "inherit",
11084
+ env: {
11085
+ ...process.env,
11086
+ [PEACH_FORKED_SCRIPT_ENV]: "1",
11087
+ PEACH_CLANG_REPLAYS: plan,
11088
+ PEACH_CLANG_JOBS: String(options.jobs)
11089
+ }
11090
+ });
11091
+ const result = /* @__PURE__ */ new Map();
11092
+ for (const { file, output } of replays) {
11093
+ const flags = clangIrLinkOptions((0, import_node_fs22.readFileSync)(output, "utf8"));
11094
+ for (let index = 0; index < flags.length; index++) {
11095
+ const flag = flags[index];
11096
+ if (flag === "-framework" || flag === "-l" || flag === "--library") {
11097
+ const name2 = flags[++index];
11098
+ if (!name2 || name2.startsWith("-"))
11099
+ throw new Error(`missing clang link name after ${flag}`);
11100
+ } else if (!/^(-l.+|--library=.+)$/.test(flag)) {
11101
+ throw new Error(`unsupported clang link option ${flag}`);
11102
+ }
11043
11103
  }
11104
+ result.set(file, flags);
11044
11105
  }
11045
- const typeAt = (index) => {
11046
- const type = types[index];
11047
- if (!type) throw new Error("invalid wasm type index");
11048
- return type;
11049
- };
11050
- const thunks = [];
11051
- const functionTypes = [];
11052
- const importBody = [];
11053
- const importSection = section(2);
11054
- if (importSection) {
11055
- const count = importSection.number();
11056
- importBody.push(...encodeNumber2(count));
11057
- for (let index = 0; index < count; index++) {
11058
- const module2 = importSection.name();
11059
- const name2 = importSection.name();
11060
- const start = importSection.position();
11061
- const kind = importSection.byte();
11062
- const limits = () => {
11063
- const flags = importSection.number();
11064
- importSection.number();
11065
- if (flags & 1) importSection.number();
11066
- };
11067
- let type;
11068
- if (kind === 0) {
11069
- type = typeAt(importSection.number());
11070
- functionTypes.push(type);
11071
- } else if (kind === 1) {
11072
- importSection.byte();
11073
- limits();
11074
- } else if (kind === 2) limits();
11075
- else if (kind === 3) {
11076
- importSection.byte();
11077
- importSection.byte();
11078
- } else if (kind === 4) {
11079
- importSection.byte();
11080
- importSection.number();
11081
- } else throw new Error("unsupported wasm import");
11082
- const scalar64 = (parameter) => module2 === "wasi_snapshot_preview1" && (!name2.startsWith("peach_") || name2 === "peach_fs_path_birthtime_set" && parameter === 2) || module2 === "peach" && name2 === "hw_memsize" && parameter === null || module2 === "peach_notify" && name2 === "set" && parameter === 1;
11083
- const parameters = type?.parameters.map(
11084
- (value, index2) => value === I64 && !scalar64(index2) ? 127 : value
11106
+ return result;
11107
+ }
11108
+ function sourceGuestInputIdentities(graph, buildDirectory, objects) {
11109
+ const producers = /* @__PURE__ */ new Map();
11110
+ for (const target of graph.targets)
11111
+ if (target.sourceTarget !== null)
11112
+ producers.set(
11113
+ target.sourceTarget,
11114
+ producers.has(target.sourceTarget) ? null : target.id
11085
11115
  );
11086
- const results = type?.results.map(
11087
- (value) => value === I64 && !scalar64(null) ? 127 : value
11116
+ const identities = /* @__PURE__ */ new Map();
11117
+ for (const object3 of objects) {
11118
+ const target = producers.get(object3.sourceTarget);
11119
+ if (target === null || target === void 0)
11120
+ throw new Error(`ambiguous source producer ${object3.sourceTarget}`);
11121
+ if (object3.kind === "archive") {
11122
+ identities.set(
11123
+ object3.path,
11124
+ JSON.stringify([
11125
+ "source",
11126
+ target,
11127
+ `libraries/lib${libraryArchiveTarget(object3.path)}.a`
11128
+ ])
11088
11129
  );
11089
- if (type && parameters && results && (parameters.some((value, index2) => value !== type.parameters[index2]) || results.some((value, index2) => value !== type.results[index2]))) {
11090
- if (type.results.length > 1)
11091
- throw new Error(`import ${module2}.${name2} returns several values`);
11092
- const id = thunks.length;
11093
- const call = `(call $host${id}${type.parameters.map(
11094
- (value, at) => value !== parameters[at] ? ` (i32.wrap_i64 (local.get ${at}))` : ` (local.get ${at})`
11095
- ).join("")})`;
11096
- thunks.push(
11097
- `(import ${quoted(module2)} ${quoted(name2)} (func $host${id}${signature(parameters, "param", false)}${signature(results, "result", false)}))`,
11098
- `(func (export "${NARROW}${id}")${signature(type.parameters, "param", false)}${signature(type.results, "result", false)} ${type.results[0] !== results[0] ? `(i64.extend_i32_u ${call})` : call})`
11099
- );
11100
- importBody.push(...encodeName(BOUNDARY), ...encodeName(`${NARROW}${id}`));
11101
- } else importBody.push(...encodeName(module2), ...encodeName(name2));
11102
- importBody.push(...bytes.subarray(start, importSection.position()));
11130
+ continue;
11103
11131
  }
11104
- if (!importSection.done()) throw new Error("invalid wasm imports");
11132
+ const relative = import_node_path22.default.relative(buildDirectory, object3.path).split(import_node_path22.default.sep);
11133
+ if (!relative[0]?.endsWith(".build") || relative.length < 2)
11134
+ throw new Error(`source object is outside its producer ${object3.path}`);
11135
+ identities.set(object3.path, JSON.stringify(["source", target, relative.join("/")]));
11105
11136
  }
11106
- const functionSection = section(3);
11107
- if (functionSection)
11108
- for (let count = functionSection.number(); count > 0; count--)
11109
- functionTypes.push(typeAt(functionSection.number()));
11110
- const exportBody = [];
11111
- const exportSection = section(7);
11112
- if (exportSection) {
11113
- const count = exportSection.number();
11114
- exportBody.push(...encodeNumber2(count));
11115
- for (let index = 0; index < count; index++) {
11116
- const name2 = exportSection.name();
11117
- const kind = exportSection.byte();
11118
- const target = exportSection.number();
11119
- const type = kind === 0 ? functionTypes[target] : void 0;
11120
- if (kind === 0 && !type) throw new Error("invalid wasm export");
11121
- if (type && wide(type)) {
11122
- if (type.results.length > 1)
11123
- throw new Error(`export ${name2} returns several values`);
11124
- const id = thunks.length;
11125
- const call = `(call $guest${id}${type.parameters.map(
11126
- (value, at) => value === I64 ? ` (i64.extend_i32_u (local.get ${at}))` : ` (local.get ${at})`
11127
- ).join("")})`;
11128
- thunks.push(
11129
- `(import "${GUEST}" "${WIDE}${id}" (func $guest${id}${signature(type.parameters, "param", false)}${signature(type.results, "result", false)}))`,
11130
- `(func (export ${quoted(name2)})${signature(type.parameters, "param", true)}${signature(type.results, "result", true)} ${type.results[0] === I64 ? `(i32.wrap_i64 ${call})` : call})`
11131
- );
11132
- exportBody.push(...encodeName(`${WIDE}${id}`));
11133
- } else exportBody.push(...encodeName(name2));
11134
- exportBody.push(kind, ...encodeNumber2(target));
11137
+ return identities;
11138
+ }
11139
+ function sourceGuestRuntimeLinks(options) {
11140
+ const aliases = /* @__PURE__ */ new Map();
11141
+ const artifacts = /* @__PURE__ */ new Map();
11142
+ const frameworkAliases = /* @__PURE__ */ new Map();
11143
+ const sdkAliases = /* @__PURE__ */ new Map();
11144
+ for (const { product, root } of options.products) {
11145
+ for (const alias of product.frameworkAliases) {
11146
+ if (product.linkOwnership !== "image")
11147
+ throw new Error(`framework namespace has no image owner ${product.id}`);
11148
+ const previous = sdkAliases.get(alias.name);
11149
+ if (previous) {
11150
+ if (previous.product !== product.id || previous.moduleMap !== alias.moduleMap || previous.sha256 !== alias.moduleMapSha256)
11151
+ throw new Error(`ambiguous declared framework ${alias.name}`);
11152
+ continue;
11153
+ }
11154
+ const directory = import_node_path22.default.resolve(options.sdk.root);
11155
+ const file = import_node_path22.default.resolve(directory, alias.moduleMap);
11156
+ if (!file.startsWith(directory + import_node_path22.default.sep))
11157
+ throw new Error(`invalid framework module map ${alias.moduleMap}`);
11158
+ if ((0, import_node_crypto14.createHash)("sha256").update((0, import_node_fs22.readFileSync)(file)).digest("hex") !== alias.moduleMapSha256)
11159
+ throw new Error(`framework module map changed ${alias.moduleMap}`);
11160
+ sdkAliases.set(alias.name, {
11161
+ product: product.id,
11162
+ moduleMap: alias.moduleMap,
11163
+ sha256: alias.moduleMapSha256
11164
+ });
11165
+ frameworkAliases.set(alias.name, { kind: "sdk", product: product.id });
11166
+ }
11167
+ for (const artifact of product.artifacts) {
11168
+ const file = import_node_path22.default.resolve(root, artifact.path);
11169
+ const prior = artifacts.get(file);
11170
+ artifacts.set(file, prior === void 0 || prior === product.id ? product.id : null);
11171
+ }
11172
+ for (const name2 of product.linkNames) {
11173
+ const prior = aliases.get(name2);
11174
+ if (prior !== void 0 && prior !== product.id)
11175
+ throw new Error(`ambiguous declared runtime link name ${name2}`);
11176
+ aliases.set(name2, product.id);
11135
11177
  }
11136
- if (!exportSection.done()) throw new Error("invalid wasm exports");
11137
- }
11138
- if (thunks.length === 0) return void 0;
11139
- const imports = thunks.filter((line) => line.startsWith("(import"));
11140
- const functions = thunks.filter((line) => !line.startsWith("(import"));
11141
- return {
11142
- module: withSections(
11143
- bytes,
11144
- layout2,
11145
- /* @__PURE__ */ new Map([
11146
- [2, importBody],
11147
- [7, exportBody]
11148
- ])
11149
- ),
11150
- thunks: `(module
11151
- ${[...imports, ...functions].join("\n")}
11152
- )
11153
- `
11154
- };
11155
- }
11156
- var NARROW_MERGE_NAMES = { guest: GUEST, boundary: BOUNDARY };
11157
- function dropBoundaryExports(bytes) {
11158
- const layout2 = sections(bytes);
11159
- const found = layout2.find((entry) => entry.id === 7);
11160
- if (!found) throw new Error("merged module has no exports");
11161
- const exportSection = reader(bytes, found.start, found.end);
11162
- const kept = [];
11163
- for (let count = exportSection.number(); count > 0; count--) {
11164
- const name2 = exportSection.name();
11165
- const kind = exportSection.byte();
11166
- const target = exportSection.number();
11167
- if (!name2.startsWith(WIDE) && !name2.startsWith(NARROW))
11168
- kept.push([...encodeName(name2), kind, ...encodeNumber2(target)]);
11169
11178
  }
11170
- return withSections(
11171
- bytes,
11172
- layout2,
11173
- /* @__PURE__ */ new Map([[7, [...encodeNumber2(kept.length), ...kept.flat()]]])
11179
+ const frameworkId = frameworkRuntimeProductId(options.framework.product);
11180
+ const owners = options.products.filter(({ product }) => product.id === frameworkId);
11181
+ if (owners.length !== 1 || owners[0].product.linkOwnership !== "image" || import_node_path22.default.resolve(owners[0].root) !== import_node_path22.default.resolve(options.framework.root))
11182
+ throw new Error(`missing or ambiguous packaged image ${frameworkId}`);
11183
+ const targets = new Map(
11184
+ options.framework.product.targets.map((target) => [target.name, target])
11174
11185
  );
11175
- }
11176
-
11177
- // src/wasm-optimize.ts
11178
- var FEATURES = [
11179
- "memory64",
11180
- "threads",
11181
- "bulk-memory",
11182
- "bulk-memory-opt",
11183
- "call-indirect-overlong",
11184
- "exception-handling",
11185
- "multivalue",
11186
- "mutable-globals",
11187
- "nontrapping-float-to-int",
11188
- "reference-types",
11189
- "sign-ext"
11190
- ];
11191
- var KEEP_WASM_NAMES = process.env.PEACH_SWIFT_NAMES === "1";
11192
- var LOWERING = ["--memory64-lowering", "--table64-lowering"];
11193
- var BINARYEN_VERSION = binaryen_lock_default.version;
11194
- var runBinaryen = (0, import_node_util2.promisify)(import_node_child_process14.execFile);
11195
- var WASM_LOWER_IDENTITY = `binaryen ${BINARYEN_VERSION} narrow ${LOWERING.join(" ")} ${FEATURES.join(",")} unoptimized-names`;
11196
- var BINARYEN_RELEASES = new Map(Object.entries(binaryen_lock_default.platforms));
11197
- async function runWasmOpt(file, output, optimize, skipPasses, binary) {
11198
- const admittedCores = windowAdmission()?.cores ?? Number(process.env.TM_EXEC_CPU_CORES);
11199
- const requestedCores = Number(process.env.BINARYEN_CORES);
11200
- const environment = { ...process.env };
11201
- if (Number.isInteger(admittedCores) && admittedCores > 0)
11202
- environment.BINARYEN_CORES = String(
11203
- Number.isInteger(requestedCores) && requestedCores > 0 ? Math.min(admittedCores, requestedCores) : admittedCores
11204
- );
11205
- const features = FEATURES.map((feature) => `--enable-${feature}`);
11206
- const names = optimize && !KEEP_WASM_NAMES ? [] : ["-g"];
11207
- const narrowed = narrowWasmBoundary((0, import_node_fs22.readFileSync)(file));
11208
- const merged = `${output}.narrowed`;
11209
- if (narrowed) {
11210
- const guest = `${output}.guest`;
11211
- const thunks = `${output}.thunks.wat`;
11212
- (0, import_node_fs22.writeFileSync)(guest, narrowed.module);
11213
- (0, import_node_fs22.writeFileSync)(thunks, narrowed.thunks);
11214
- await runBinaryen(
11215
- (0, import_node_path22.join)((0, import_node_path22.dirname)(binary), "wasm-merge"),
11216
- [
11217
- ...features,
11218
- ...names,
11219
- guest,
11220
- NARROW_MERGE_NAMES.guest,
11221
- thunks,
11222
- NARROW_MERGE_NAMES.boundary,
11223
- "-o",
11224
- merged
11225
- ],
11226
- { env: environment }
11227
- );
11228
- (0, import_node_fs22.writeFileSync)(merged, dropBoundaryExports((0, import_node_fs22.readFileSync)(merged)));
11229
- (0, import_node_fs22.rmSync)(guest);
11230
- (0, import_node_fs22.rmSync)(thunks);
11186
+ if (targets.size !== options.framework.product.targets.length)
11187
+ throw new Error("ambiguous packaged framework target");
11188
+ const objectTargets = new Set(
11189
+ options.framework.product.objects.map((object3) => object3.target)
11190
+ );
11191
+ const closure = (names) => {
11192
+ const linked = /* @__PURE__ */ new Set();
11193
+ const visit = (name2) => {
11194
+ if (linked.has(name2)) return;
11195
+ const target = targets.get(name2);
11196
+ if (!target) throw new Error(`unknown packaged framework target ${name2}`);
11197
+ linked.add(name2);
11198
+ for (const dependency of target.dependencies) visit(dependency);
11199
+ };
11200
+ for (const name2 of names) visit(name2);
11201
+ return [...linked];
11202
+ };
11203
+ for (const alias of options.framework.product.frameworkAliases) {
11204
+ if (frameworkAliases.has(alias.name))
11205
+ throw new Error(`ambiguous declared framework ${alias.name}`);
11206
+ if (alias.wasmSdkId !== options.sdk.wasmSdkId || alias.wasmSdkChecksum !== options.sdk.wasmSdkChecksum)
11207
+ throw new Error(`framework SDK identity differs for ${alias.name}`);
11208
+ if (!alias.targets.length || alias.targets.some((target) => !targets.has(target) || !objectTargets.has(target)))
11209
+ throw new Error(`framework target ownership differs for ${alias.name}`);
11210
+ const root = import_node_path22.default.resolve(options.framework.root);
11211
+ const map = import_node_path22.default.resolve(root, alias.moduleMap);
11212
+ if (!map.startsWith(root + import_node_path22.default.sep))
11213
+ throw new Error(`invalid framework module map ${alias.moduleMap}`);
11214
+ if ((0, import_node_crypto14.createHash)("sha256").update((0, import_node_fs22.readFileSync)(map)).digest("hex") !== alias.moduleMapSha256)
11215
+ throw new Error(`framework module map changed ${alias.moduleMap}`);
11216
+ frameworkAliases.set(alias.name, { kind: "package", targets: closure(alias.targets) });
11231
11217
  }
11232
- try {
11233
- await runBinaryen(
11234
- binary,
11235
- [
11236
- ...LOWERING,
11237
- ...optimize ? ["-Oz"] : [],
11238
- ...names,
11239
- ...skipPasses.flatMap((pass) => ["--skip-pass", pass]),
11240
- ...features,
11241
- narrowed ? merged : file,
11242
- "-o",
11243
- output
11244
- ],
11245
- { env: environment, maxBuffer: Infinity }
11218
+ for (const name2 of objectTargets)
11219
+ if (!frameworkAliases.has(name2) && targets.has(name2))
11220
+ frameworkAliases.set(name2, { kind: "package", targets: closure([name2]) });
11221
+ const result = /* @__PURE__ */ new Map();
11222
+ const frameworkRequests = /* @__PURE__ */ new Map();
11223
+ for (const image of options.images) {
11224
+ if (result.has(image.id)) throw new Error(`duplicate source image ${image.id}`);
11225
+ const response = import_node_path22.default.join(options.directory, `image-${image.id}-autolink.rsp`);
11226
+ (0, import_node_fs22.writeFileSync)(
11227
+ response,
11228
+ image.objects.map((file) => JSON.stringify(file)).join("\n") + "\n"
11246
11229
  );
11247
- } finally {
11248
- if (narrowed) (0, import_node_fs22.rmSync)(merged);
11230
+ const autolink = image.objects.length ? (0, import_node_child_process14.execFileSync)(
11231
+ import_node_path22.default.join(options.toolchainBin, "swift-autolink-extract"),
11232
+ [`@${response}`, "-o", "-"],
11233
+ { encoding: "utf8" }
11234
+ ).split("\n").map((line) => line.trim()).filter((line) => line.length > 0) : [];
11235
+ const links = [];
11236
+ const requests = [];
11237
+ const optionGroups = [
11238
+ { object: null, flags: image.linkerFlags, autoLinked: false },
11239
+ { object: null, flags: autolink, autoLinked: true },
11240
+ ...image.clangLinkOptions.map((options2) => ({ ...options2, autoLinked: true }))
11241
+ ];
11242
+ for (const { object: object3, flags, autoLinked } of optionGroups) {
11243
+ for (let index = 0; index < flags.length; index++) {
11244
+ const flag = flags[index];
11245
+ const artifact = artifacts.get(flag);
11246
+ if (artifact === null)
11247
+ throw new Error(`ambiguous declared runtime artifact ${flag}`);
11248
+ if (artifact !== void 0) {
11249
+ if (!links.includes(artifact)) links.push(artifact);
11250
+ continue;
11251
+ }
11252
+ if (import_node_path22.default.isAbsolute(flag) && flag.endsWith(".a"))
11253
+ throw new Error(
11254
+ `source image ${image.id} has unresolved runtime artifact ${flag}`
11255
+ );
11256
+ if (flag === "-framework") {
11257
+ const name3 = flags[++index];
11258
+ const provider = name3 && frameworkAliases.get(name3);
11259
+ if (!provider && name3 && autoLinked) continue;
11260
+ if (!provider)
11261
+ throw new Error(
11262
+ `source image ${image.id} has unresolved framework linkage ${name3}`
11263
+ );
11264
+ requests.push({ object: object3, provider });
11265
+ continue;
11266
+ }
11267
+ if (flag.startsWith("-weak") || flag.startsWith("-reexport") || flag.startsWith("-upward") || flag.startsWith("-lazy") || flag.startsWith("-Wl,"))
11268
+ throw new Error(
11269
+ `source image ${image.id} has unsupported runtime scope flag ${flag}`
11270
+ );
11271
+ const name2 = flag === "-l" || flag === "--library" ? flags[++index] : flag.startsWith("-l") ? flag.slice(2) : flag.startsWith("--library=") ? flag.slice("--library=".length) : null;
11272
+ if (name2 === null) continue;
11273
+ const product = name2 === void 0 ? void 0 : aliases.get(name2);
11274
+ if (product === void 0)
11275
+ throw new Error(`source image ${image.id} has unresolved runtime link ${name2}`);
11276
+ if (!links.includes(product)) links.push(product);
11277
+ }
11278
+ }
11279
+ result.set(image.id, links);
11280
+ frameworkRequests.set(image.id, requests);
11249
11281
  }
11282
+ return { links: result, frameworkRequests };
11250
11283
  }
11251
- async function installWasmOpt() {
11252
- const platform = `${process.platform}-${process.arch}`;
11253
- const release = BINARYEN_RELEASES.get(platform);
11254
- if (!release) throw new Error(`no pinned Binaryen release for ${platform}`);
11255
- const destDir = (0, import_node_path22.join)(rnxHomeDir(), "tools", "binaryen", BINARYEN_VERSION, platform);
11256
- const binary = (0, import_node_path22.join)(destDir, "bin", "wasm-opt");
11257
- if (!(0, import_node_fs22.existsSync)(binary))
11258
- await installVerifiedTarball({
11259
- url: `https://r2.rnxsim.com/peach/binaryen/${release.sha256}/${platform}.tar.gz`,
11260
- digest: { algorithm: "sha256", encoding: "hex", value: release.sha256 },
11261
- destDir,
11262
- installedMarker: "bin/wasm-opt",
11263
- label: `Binaryen ${BINARYEN_VERSION}`
11264
- });
11265
- return binary;
11266
- }
11267
- async function lowerWasm(file, output, options) {
11268
- await runWasmOpt(
11269
- file,
11270
- output,
11271
- options.optimize,
11272
- options.skipPasses ?? [],
11273
- await installWasmOpt()
11284
+ function logicalGuestLinkOptions(args, identities, roots) {
11285
+ const orderedRoots = [...roots].sort(
11286
+ (left, right) => right.path.length - left.path.length
11274
11287
  );
11288
+ const logicalPath = (file) => {
11289
+ const direct = identities.get(file);
11290
+ if (direct !== void 0) return direct;
11291
+ if (/\.(?:o|obj|a)$/.test(file))
11292
+ throw new Error(`link input has no logical identity ${file}`);
11293
+ for (const root of orderedRoots) {
11294
+ const relative = import_node_path22.default.relative(root.path, file);
11295
+ if (relative !== ".." && !relative.startsWith(`..${import_node_path22.default.sep}`) && !import_node_path22.default.isAbsolute(relative))
11296
+ return `${root.identity}/${relative.split(import_node_path22.default.sep).join("/")}`;
11297
+ }
11298
+ throw new Error(`link option has no logical path identity ${file}`);
11299
+ };
11300
+ const output = [];
11301
+ for (let index = 0; index < args.length; index++) {
11302
+ const arg = args[index];
11303
+ if (arg === "-o" || arg === "--output" || arg === "--Map") {
11304
+ index++;
11305
+ continue;
11306
+ }
11307
+ if (arg.startsWith("--output=") || arg.startsWith("--Map=")) continue;
11308
+ if (arg === "-L" || arg === "--library-path") {
11309
+ output.push(arg, logicalPath(args[++index]));
11310
+ continue;
11311
+ }
11312
+ if (arg.startsWith("-L")) output.push(`-L${logicalPath(arg.slice(2))}`);
11313
+ else if (arg.startsWith("--library-path="))
11314
+ output.push(`--library-path=${logicalPath(arg.slice("--library-path=".length))}`);
11315
+ else if (import_node_path22.default.isAbsolute(arg)) output.push(logicalPath(arg));
11316
+ else if (/^[^=]+=\//.test(arg)) {
11317
+ const equals = arg.indexOf("=");
11318
+ output.push(arg.slice(0, equals + 1) + logicalPath(arg.slice(equals + 1)));
11319
+ } else output.push(identities.get(arg) ?? arg);
11320
+ }
11321
+ return output;
11275
11322
  }
11276
11323
 
11277
11324
  // src/swift-guest-compile.ts
@@ -13137,13 +13184,10 @@ function swiftDistributionAt(root) {
13137
13184
  return parseSwiftDistributionManifest(JSON.parse((0, import_node_fs31.readFileSync)(file, "utf8")));
13138
13185
  }
13139
13186
  var REACH_STAGED_FRAMEWORKS = /* @__PURE__ */ new Set(["React"]);
13140
- function swiftModuleInterface(moduleRoot, name2, interfaceRoot) {
13187
+ function swiftModuleInterface(moduleRoot, name2) {
13141
13188
  if (REACH_STAGED_FRAMEWORKS.has(name2)) return null;
13142
13189
  if (swiftDistributionAt(moduleRoot)) {
13143
- const file = import_node_path32.default.join(
13144
- interfaceRoot ?? import_node_path32.default.join(moduleRoot, "modules"),
13145
- `${name2}-Swift.h`
13146
- );
13190
+ const file = import_node_path32.default.join(moduleRoot, "modules", `${name2}-Swift.h`);
13147
13191
  if (!(0, import_node_fs31.existsSync)(file)) return null;
13148
13192
  const header = clangInterfaceHeader((0, import_node_fs31.readFileSync)(file, "utf8"));
13149
13193
  return { declared: swiftInterfaceDeclarations(header), header };
@@ -14105,7 +14149,7 @@ var darwinRecordsRegion = (quoted2) => quoted2.length ? ["-Wl,--start-lib", ...q
14105
14149
  var REACTOR_FLAG = '"-Xclang-linker", "-mexec-model=reactor",\n';
14106
14150
  var MULTI_MANIFEST_VERSION = 72;
14107
14151
  var SWIFT_HEADER_PRODUCTS_TARGET = "PeachHeaderProducts";
14108
- var compilerSourceDigest = true ? "4a6e02699924195639b15c5cdfd8852b5f17fb2ffacb8f9f964ef3daeee8b9dc" : swiftCompilerSourceDigest(__sootsim_import_meta_dirname);
14152
+ var compilerSourceDigest = true ? "f691ad9847363fc601dda32d460b473efaac6c30948a278f162a896afa1df816" : swiftCompilerSourceDigest(__sootsim_import_meta_dirname);
14109
14153
  function swiftArtifactHash(input, release, moduleRoot) {
14110
14154
  const hash = (0, import_node_crypto18.createHash)("sha256");
14111
14155
  hash.update(`swift-compile
@@ -16837,6 +16881,10 @@ ${swiftProjectFilesProblems(input.projectFiles).join("\n")}`
16837
16881
  includeDirectory: import_node_path32.default.join(layout2.root, includes),
16838
16882
  sources: units.map(([file]) => file.slice(prefix.length)),
16839
16883
  lateSources: late.map(([file]) => file.slice(prefix.length)),
16884
+ exclude: [
16885
+ ...late.map(([file]) => file.slice(prefix.length)),
16886
+ ...entries.filter(([file]) => /\.(?:inc|inl|ipp|def)$/.test(file)).map(([file]) => file.slice(prefix.length))
16887
+ ],
16840
16888
  ...late.length > 0 ? {
16841
16889
  late: {
16842
16890
  name: `${target.name}SwiftImplementation`,
@@ -17399,6 +17447,7 @@ module ${moduleName}.Swift {
17399
17447
  "explicit=",
17400
17448
  "prev=",
17401
17449
  "cxx=",
17450
+ "plainCxx=",
17402
17451
  "cxxModules=",
17403
17452
  'for arg in "$@"; do',
17404
17453
  " case $arg in -fmodule-name=*) explicit=1 ;; esac",
@@ -17417,17 +17466,24 @@ module ${moduleName}.Swift {
17417
17466
  " fi",
17418
17467
  " prev=$arg",
17419
17468
  " case $arg in",
17420
- " *.mm|*.cpp|*.cc|*.cxx) cxx=1 ;;",
17469
+ " *.mm) cxx=1 ;;",
17470
+ " *.cpp|*.cc|*.cxx) cxx=1; plainCxx=1 ;;",
17421
17471
  " -fno-cxx-modules) cxxModules=off ;;",
17422
17472
  " -fcxx-modules) cxxModules=on ;;",
17423
17473
  " esac",
17424
17474
  "done",
17425
17475
  // apple clang claims the toolset's cache path in a c++ unit whose modules
17426
- // are off; this clang reports it unused, which -Werror turns into a failure
17476
+ // are off; this clang reports it unused and can still import explicit
17477
+ // swiftpm umbrella maps from inside a namespace in plain c++.
17427
17478
  'if [ -n "$cxx" ] && [ "$cxxModules" = off ]; then',
17428
17479
  ' for arg in "$@"; do',
17429
17480
  " shift",
17430
- ' case $arg in -fmodules-cache-path=*) ;; *) set -- "$@" "$arg" ;; esac',
17481
+ " case $arg in",
17482
+ " -fmodules-cache-path=*) ;;",
17483
+ " -fmodule-map-file=*/.build/*/*.build/module.modulemap)",
17484
+ ' [ -n "$plainCxx" ] || set -- "$@" "$arg" ;;',
17485
+ ' *) set -- "$@" "$arg" ;;',
17486
+ " esac",
17431
17487
  " done",
17432
17488
  "fi",
17433
17489
  'if [ -n "$name" ] && [ -z "$explicit" ]; then',