peachsim 0.1.2682 → 0.1.2684

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 (140) hide show
  1. package/cli/commands/package.ts +277 -118
  2. package/dist-lib/agent-daemon-client.cjs +1 -1
  3. package/dist-lib/agent-events.cjs +1 -1
  4. package/dist-lib/attached-projects.cjs +1 -1
  5. package/dist-lib/auth/shared-session.cjs +1 -1
  6. package/dist-lib/backend-origin.cjs +1 -1
  7. package/dist-lib/beta.cjs +1 -1
  8. package/dist-lib/beta.mjs +2 -2
  9. package/dist-lib/bridge-constants.cjs +1 -1
  10. package/dist-lib/bridge-contract-input.cjs +1 -1
  11. package/dist-lib/bridge-contract-input.mjs +5 -5
  12. package/dist-lib/bridge-contract.cjs +1 -1
  13. package/dist-lib/bridge-contract.mjs +3 -3
  14. package/dist-lib/bundle-channel.cjs +506 -599
  15. package/dist-lib/capture-contract.cjs +1 -1
  16. package/dist-lib/capture-contract.mjs +3 -3
  17. package/dist-lib/cloud-contract.cjs +1 -1
  18. package/dist-lib/cloud-contract.mjs +3 -3
  19. package/dist-lib/cloud-test-args.cjs +1 -1
  20. package/dist-lib/cloud-test-args.mjs +2 -2
  21. package/dist-lib/cloud.cjs +1 -1
  22. package/dist-lib/cloud.mjs +7 -7
  23. package/dist-lib/config.cjs +1 -1
  24. package/dist-lib/config.mjs +5 -5
  25. package/dist-lib/detox/index.cjs +15 -5
  26. package/dist-lib/dev-bundle-resolution.cjs +1 -1
  27. package/dist-lib/esm-chunks/{acorn-V7B4X5PR.mjs → acorn-RMQKXS5S.mjs} +3 -3
  28. package/dist-lib/esm-chunks/{chunk-UTI6VCYT.mjs → chunk-3DE27JA4.mjs} +1 -1
  29. package/dist-lib/esm-chunks/{chunk-YKGS4NSG.mjs → chunk-42JSAQWG.mjs} +5 -5
  30. package/dist-lib/esm-chunks/{chunk-5SWSDDXC.mjs → chunk-5KWWKCPH.mjs} +1 -1
  31. package/dist-lib/esm-chunks/{chunk-Z6R2HZIH.mjs → chunk-6BWHCTIS.mjs} +1 -1
  32. package/dist-lib/esm-chunks/{chunk-64UA6DQO.mjs → chunk-7IBMZCMJ.mjs} +3 -3
  33. package/dist-lib/esm-chunks/{chunk-Y6WPXDCC.mjs → chunk-AF35PBIZ.mjs} +1 -1
  34. package/dist-lib/esm-chunks/{chunk-IOLISFIO.mjs → chunk-AYPGNUZY.mjs} +1 -1
  35. package/dist-lib/esm-chunks/{chunk-3UQZATB5.mjs → chunk-DBGGJL5W.mjs} +1 -1
  36. package/dist-lib/esm-chunks/{chunk-PE7HDZNI.mjs → chunk-DJQKYIHE.mjs} +1 -1
  37. package/dist-lib/esm-chunks/{chunk-6PSNFREM.mjs → chunk-DJSSFQTJ.mjs} +1 -1
  38. package/dist-lib/esm-chunks/{chunk-LV55WJFQ.mjs → chunk-HGTEJIU2.mjs} +1 -1
  39. package/dist-lib/esm-chunks/{chunk-BJHQOPWO.mjs → chunk-HSNC4SEX.mjs} +1 -1
  40. package/dist-lib/esm-chunks/{chunk-KYIRROKJ.mjs → chunk-I6KUV3AU.mjs} +1 -1
  41. package/dist-lib/esm-chunks/{chunk-VTJTOL53.mjs → chunk-M25SODH7.mjs} +1 -1
  42. package/dist-lib/esm-chunks/{chunk-AXBK3CA4.mjs → chunk-MEV5LY7S.mjs} +1 -1
  43. package/dist-lib/esm-chunks/{chunk-R2WPUKVT.mjs → chunk-ONY3LDGP.mjs} +1 -1
  44. package/dist-lib/esm-chunks/{chunk-ZYD227CX.mjs → chunk-PKGSIT4N.mjs} +1 -1
  45. package/dist-lib/esm-chunks/{chunk-SZ5UPZE4.mjs → chunk-QA6WIBFG.mjs} +1 -1
  46. package/dist-lib/esm-chunks/{chunk-DU3VOY6S.mjs → chunk-QUNZ325E.mjs} +6 -6
  47. package/dist-lib/esm-chunks/{chunk-3VAFU4BM.mjs → chunk-TN42RBSW.mjs} +4 -4
  48. package/dist-lib/esm-chunks/{chunk-X37OP27I.mjs → chunk-TTUUDIZL.mjs} +678 -790
  49. package/dist-lib/esm-chunks/{chunk-EK36QRGX.mjs → chunk-V4RWDRKK.mjs} +1 -1
  50. package/dist-lib/esm-chunks/{chunk-EC5RY4HR.mjs → chunk-XYDK4MKL.mjs} +2 -2
  51. package/dist-lib/esm-chunks/{chunk-GNZDVDDX.mjs → chunk-YOVFAB5L.mjs} +6 -6
  52. package/dist-lib/esm-chunks/{metro-layout-parser-5RTSOQCS.mjs → metro-layout-parser-UX26SYJA.mjs} +3 -3
  53. package/dist-lib/esm-chunks/{swift-package-prebuilt-EH5JIX6L.mjs → swift-package-prebuilt-TFU7Q54I.mjs} +12 -12
  54. package/dist-lib/esm-chunks/{swift-sdk-app-module-VHAOCBXW.mjs → swift-sdk-app-module-PT7D7AOM.mjs} +16 -16
  55. package/dist-lib/esm-chunks/{swift-sdk-image-3NCWCGQZ.mjs → swift-sdk-image-HZG64EBF.mjs} +16 -16
  56. package/dist-lib/esm-chunks/{swift-sdk-image-producer-5S4IKSJ2.mjs → swift-sdk-image-producer-MUVFVMXM.mjs} +5 -5
  57. package/dist-lib/expo-swift-bundle.cjs +495 -593
  58. package/dist-lib/expo-swift-metadata.cjs +1 -1
  59. package/dist-lib/expo-swift-metadata.mjs +7 -7
  60. package/dist-lib/home-paths.cjs +1 -1
  61. package/dist-lib/host/bridge-host.cjs +620 -715
  62. package/dist-lib/host/fetch-proxy-handler.cjs +22 -24
  63. package/dist-lib/host/fetch-proxy-overrides.cjs +1 -1
  64. package/dist-lib/host/fetch-proxy-overrides.mjs +2 -2
  65. package/dist-lib/host/replacement-module-handler.cjs +1 -1
  66. package/dist-lib/host/websocket-proxy.cjs +1 -1
  67. package/dist-lib/index.cjs +1 -1
  68. package/dist-lib/kotlin-host.cjs +1 -1
  69. package/dist-lib/menu.cjs +1 -1
  70. package/dist-lib/menu.mjs +3 -3
  71. package/dist-lib/metro-fingerprint-registry.cjs +1 -1
  72. package/dist-lib/metro-fingerprint-registry.mjs +3 -3
  73. package/dist-lib/metro-production-bundle.cjs +1 -1
  74. package/dist-lib/metro-production-bundle.mjs +4 -4
  75. package/dist-lib/native-app-identity-project.cjs +1 -1
  76. package/dist-lib/native-app-identity-project.mjs +15 -15
  77. package/dist-lib/native-app-identity.cjs +1 -1
  78. package/dist-lib/native-app-identity.mjs +6 -6
  79. package/dist-lib/native-firebase-metadata.cjs +1 -1
  80. package/dist-lib/native-firebase-metadata.mjs +3 -3
  81. package/dist-lib/pdfium-raster.cjs +1 -1
  82. package/dist-lib/pdfium-raster.mjs +2 -2
  83. package/dist-lib/plist.cjs +1 -1
  84. package/dist-lib/plist.mjs +3 -3
  85. package/dist-lib/profiles.cjs +1 -1
  86. package/dist-lib/public-brand.cjs +1 -1
  87. package/dist-lib/public-origins-lib-esm.json +87 -87
  88. package/dist-lib/public-origins-lib.json +76 -76
  89. package/dist-lib/react-native-host-modules.cjs +1 -1
  90. package/dist-lib/react-native-host-modules.mjs +2 -2
  91. package/dist-lib/reap-browser.cjs +1 -1
  92. package/dist-lib/scripts/dev-server-scanner.cjs +1 -1
  93. package/dist-lib/sdk.cjs +1 -1
  94. package/dist-lib/sdk.mjs +8 -8
  95. package/dist-lib/skills.cjs +622 -717
  96. package/dist-lib/swift-compile.cjs +502 -618
  97. package/dist-lib/swift-compile.mjs +12 -12
  98. package/dist-lib/swift-package.cjs +1 -1
  99. package/dist-lib/swift-package.mjs +3 -3
  100. package/dist-lib/swift-submit.cjs +1 -1
  101. package/dist-lib/swift-submit.mjs +6 -6
  102. package/dist-lib/swift-svg-raster.cjs +1 -1
  103. package/dist-lib/swift-svg-raster.mjs +2 -2
  104. package/dist-lib/swift-toolchain.cjs +1 -1
  105. package/dist-lib/swift.cjs +1 -1
  106. package/dist-lib/vendor/@peculiar/x509.cjs +1 -1
  107. package/dist-lib/vendor/@ruby/prism/src/nodes.js.cjs +1 -1
  108. package/dist-lib/vendor/@ruby/prism/src/parsePrism.js.cjs +1 -1
  109. package/dist-lib/vendor/acorn.cjs +1 -1
  110. package/dist-lib/vendor/magic-string.cjs +1 -1
  111. package/dist-lib/vendor/stream-json.cjs +1 -1
  112. package/dist-lib/vendor/sucrase/dist/index.js.cjs +1 -1
  113. package/dist-lib/vendor/sucrase/dist/parser/index.js.cjs +1 -1
  114. package/dist-lib/vendor/sucrase/dist/parser/tokenizer/index.js.cjs +1 -1
  115. package/dist-lib/vendor/sucrase/dist/parser/tokenizer/types.js.cjs +1 -1
  116. package/dist-lib/vendor/sucrase.cjs +1 -1
  117. package/dist-lib/vendor/terser.cjs +1 -1
  118. package/dist-lib/vendor/valibot.cjs +1 -1
  119. package/dist-lib/vendor/ws.cjs +1 -1
  120. package/dist-lib/vendor/zod.cjs +1 -1
  121. package/dist-lib/worklet-executable.cjs +1 -1
  122. package/dist-lib/worklet-executable.mjs +3 -3
  123. package/dist-types/packages/peach-engine/src/engine/image-fetch.d.ts +1 -0
  124. package/dist-types/packages/peach-engine/src/settings/devices.d.ts +1 -1
  125. package/kotlin/sdk.tar.gz +0 -0
  126. package/package.json +2 -1
  127. package/runtime-companion.json +1 -1
  128. package/src/bundle-channel.mjs +1 -1
  129. package/src/native-bundles.ts +7 -1
  130. package/src/native-package-slice.ts +28 -12
  131. package/src/nitro-bundle.ts +1 -0
  132. package/src/nitro-compile.ts +8 -2
  133. package/src/nitroContract.ts +35 -14
  134. package/src/one-sdk-bundle.ts +2 -2
  135. package/src/swift-compile.ts +25 -131
  136. package/src/swift-guest-compile.ts +184 -218
  137. package/src/swift-host.ts +13 -23
  138. package/src/swift-submit.ts +0 -2
  139. package/src/turbo-bundle.ts +2 -2
  140. package/src/turbo-compile.ts +0 -1
@@ -1,11 +1,11 @@
1
- /*! peach v0.1.2682 | (c) 2026 Tamagui LLC | Proprietary; see LICENSE */
1
+ /*! peach v0.1.2684 | (c) 2026 Tamagui LLC | Proprietary; see LICENSE */
2
2
  import {
3
3
  acquireSwiftRootReadHold,
4
4
  hasLiveSwiftRootReaders,
5
5
  retainSwiftRootReadHold,
6
6
  waitForNoSwiftRootReaders,
7
7
  withSwiftRootLock
8
- } from "./chunk-EC5RY4HR.mjs";
8
+ } from "./chunk-XYDK4MKL.mjs";
9
9
  import {
10
10
  CORE_FOUNDATION_OVERLAY_GLOBALS,
11
11
  NATIVE_GRAPH_SDK_VERSION,
@@ -56,13 +56,12 @@ import {
56
56
  withoutImportedSdkEnumForwards,
57
57
  withoutSwiftDeclarations,
58
58
  writeBuildFile
59
- } from "./chunk-DU3VOY6S.mjs";
59
+ } from "./chunk-QUNZ325E.mjs";
60
60
  import {
61
61
  SWIFT_AUTOLINK_LINKER,
62
62
  SWIFT_CACHE_HOLD_MARKER,
63
63
  SWIFT_WASM_TRIPLE,
64
64
  refreshSwiftCacheHold,
65
- sourceSwiftCheckout,
66
65
  swiftCacheDir,
67
66
  swiftEnvironment,
68
67
  swiftFileChecksum,
@@ -74,7 +73,7 @@ import {
74
73
  wasmThreadLinkFlags,
75
74
  windowAdmission,
76
75
  writeSwiftAutolinkLinker
77
- } from "./chunk-R2WPUKVT.mjs";
76
+ } from "./chunk-ONY3LDGP.mjs";
78
77
  import {
79
78
  SWIFT_BINARY_TREES_DIR,
80
79
  SWIFT_NATIVE_INPUT_ROOT,
@@ -89,7 +88,7 @@ import {
89
88
  isSwiftResourcePath,
90
89
  isSwiftSourceLinkGraph,
91
90
  swiftProjectFilesProblems
92
- } from "./chunk-5SWSDDXC.mjs";
91
+ } from "./chunk-5KWWKCPH.mjs";
93
92
  import {
94
93
  OBJC_RESOURCE_ACCESSOR_BODY,
95
94
  OBJC_RESOURCE_ACCESSOR_HEADER,
@@ -112,16 +111,16 @@ import {
112
111
  swiftPackagePartition,
113
112
  swiftTargetModuleName,
114
113
  withoutGlogModuleMap
115
- } from "./chunk-6PSNFREM.mjs";
114
+ } from "./chunk-DJSSFQTJ.mjs";
116
115
  import {
117
116
  rnxPublicBrand
118
- } from "./chunk-AXBK3CA4.mjs";
117
+ } from "./chunk-MEV5LY7S.mjs";
119
118
  import {
120
119
  isRecord
121
- } from "./chunk-IOLISFIO.mjs";
120
+ } from "./chunk-AYPGNUZY.mjs";
122
121
  import {
123
122
  __publicField
124
- } from "./chunk-ZYD227CX.mjs";
123
+ } from "./chunk-PKGSIT4N.mjs";
125
124
 
126
125
  // src/swift-compile.ts
127
126
  import { spawn as spawn2 } from "node:child_process";
@@ -2820,10 +2819,6 @@ function reapRetiredCacheDirectory(parent, name) {
2820
2819
  // src/swift-compile-budget.ts
2821
2820
  var SWIFT_COMPILE_TIMEOUT_MS = 18e5;
2822
2821
  var SWIFT_LOCK_WAIT_TIMEOUT_MS = 36e5;
2823
- var SWIFT_TRANSPORT_MARGIN_MS = 3e5;
2824
- function swiftBuilderHopTimeoutMs(compileTimeoutMs) {
2825
- return SWIFT_LOCK_WAIT_TIMEOUT_MS + (compileTimeoutMs ?? SWIFT_COMPILE_TIMEOUT_MS) + SWIFT_TRANSPORT_MARGIN_MS;
2826
- }
2827
2822
  async function withSwiftCompileBudget(compileTimeoutMs, signal, work) {
2828
2823
  const deadline = new AbortController();
2829
2824
  const combined = signal ? AbortSignal.any([signal, deadline.signal]) : deadline.signal;
@@ -8476,6 +8471,17 @@ function aliasGuestLinkIdentities(identities, archives) {
8476
8471
  return result;
8477
8472
  }
8478
8473
 
8474
+ // src/swift-guest-dyld-table.ts
8475
+ import { createHash as createHash5 } from "node:crypto";
8476
+ import { deflateRawSync } from "node:zlib";
8477
+
8478
+ // ../peach-kit/src/nativeDyldTableContract.ts
8479
+ var NATIVE_DYLD_TABLE_SECTION = "peach.dyld-table-v1";
8480
+ var NATIVE_DYLD_PACKS_SECTION = "peach.dyld-packs-v1";
8481
+
8482
+ // src/swift-guest-image-ledger.ts
8483
+ import { createHash as createHash4 } from "node:crypto";
8484
+
8479
8485
  // ../peach-kit/src/nativeWasmContract.ts
8480
8486
  var NATIVE_IMAGE_SECTION = "peach.native-image-v1";
8481
8487
  var NATIVE_TABLE_ABI = "peach-native-table-v1";
@@ -8490,379 +8496,124 @@ var NATIVE_LAZY_DIGEST_BYTES = 32;
8490
8496
  var NATIVE_LAZY_PART_BYTES = NATIVE_LAZY_DIGEST_BYTES + 4;
8491
8497
  var NATIVE_TABLE_RESERVE_SLOTS = 4096;
8492
8498
 
8493
- // src/swift-guest-dyld-functions.ts
8494
- var uleb2 = (value) => {
8495
- const out = [];
8499
+ // src/swift-guest-image-ledger.ts
8500
+ var ByteWriter = class {
8501
+ constructor(initialCapacity = 256) {
8502
+ __publicField(this, "buf");
8503
+ __publicField(this, "pos", 0);
8504
+ this.buf = Buffer.allocUnsafe(Math.max(64, initialCapacity));
8505
+ }
8506
+ ensure(extra) {
8507
+ const needed = this.pos + extra;
8508
+ if (needed <= this.buf.length) return;
8509
+ let next = this.buf.length * 2;
8510
+ while (next < needed) next *= 2;
8511
+ const grown = Buffer.allocUnsafe(next);
8512
+ this.buf.copy(grown, 0, 0, this.pos);
8513
+ this.buf = grown;
8514
+ }
8515
+ byte(value) {
8516
+ this.ensure(1);
8517
+ this.buf[this.pos++] = value;
8518
+ }
8519
+ uleb(value) {
8520
+ this.ensure(10);
8521
+ let pos = this.pos;
8522
+ const buf = this.buf;
8523
+ do {
8524
+ let byte = value % 128;
8525
+ value = Math.floor(value / 128);
8526
+ if (value) byte |= 128;
8527
+ buf[pos++] = byte;
8528
+ } while (value);
8529
+ this.pos = pos;
8530
+ }
8531
+ bytes(source, start = 0, end = source.length) {
8532
+ const len = end - start;
8533
+ if (len <= 0) return;
8534
+ this.ensure(len);
8535
+ this.buf.set(source.subarray(start, end), this.pos);
8536
+ this.pos += len;
8537
+ }
8538
+ string(value) {
8539
+ const len = Buffer.byteLength(value, "utf8");
8540
+ this.uleb(len);
8541
+ if (len > 0) {
8542
+ this.ensure(len);
8543
+ this.buf.write(value, this.pos, len, "utf8");
8544
+ this.pos += len;
8545
+ }
8546
+ }
8547
+ finish() {
8548
+ return this.buf.subarray(0, this.pos);
8549
+ }
8550
+ };
8551
+ function readNumber(bytes, position) {
8552
+ if (position < bytes.length) {
8553
+ const first = bytes[position];
8554
+ if (first < 128) return [first, position + 1];
8555
+ }
8556
+ let value = 0;
8557
+ let shift = 0;
8558
+ for (; ; ) {
8559
+ if (position >= bytes.length || shift > 63) throw new Error("invalid wasm integer");
8560
+ const byte = bytes[position++];
8561
+ value += (byte & 127) * 2 ** shift;
8562
+ if (!(byte & 128)) return [value, position];
8563
+ shift += 7;
8564
+ }
8565
+ }
8566
+ function encodeNumber(value) {
8567
+ if (value < 128) return Buffer.from([value]);
8568
+ const bytes = [];
8496
8569
  do {
8497
8570
  let byte = value % 128;
8498
8571
  value = Math.floor(value / 128);
8499
8572
  if (value) byte |= 128;
8500
- out.push(byte);
8573
+ bytes.push(byte);
8501
8574
  } while (value);
8502
- return out;
8503
- };
8504
- var SECTION_ORDER = [1, 2, 3, 4, 5, 13, 6, 7, 8, 9, 12, 10, 11];
8505
- function skipValueType(r) {
8506
- const type = r.byte();
8507
- if (type === 99 || type === 100) r.s();
8575
+ return Buffer.from(bytes);
8508
8576
  }
8509
- function readImports2(bytes, sections) {
8510
- let functions = 0;
8511
- let table64;
8512
- const imports = sections.find((s) => s.id === 2);
8513
- if (imports) {
8514
- const r = wasmReader(bytes, imports.start);
8515
- for (let n = r.u(); n > 0; n--) {
8516
- r.name();
8517
- r.name();
8518
- const kind = r.byte();
8519
- if (kind === 0) {
8520
- functions++;
8521
- r.u();
8522
- } else if (kind === 1 || kind === 2) {
8523
- if (kind === 1) skipValueType(r);
8524
- const flags = r.u();
8525
- r.u();
8526
- if (flags & 1) r.u();
8527
- if (kind === 1) table64 ?? (table64 = (flags & 4) !== 0);
8528
- } else if (kind === 3) {
8529
- skipValueType(r);
8530
- r.byte();
8531
- } else if (kind === 4) {
8532
- r.byte();
8533
- r.u();
8534
- } else throw new Error(`unsupported wasm import kind ${kind}`);
8535
- }
8536
- }
8537
- const tables = sections.find((s) => s.id === 4);
8538
- if (table64 === void 0 && tables) {
8539
- const r = wasmReader(bytes, tables.start);
8540
- if (r.u()) {
8541
- skipValueType(r);
8542
- table64 = (r.u() & 4) !== 0;
8543
- }
8544
- }
8545
- return { functions, table64 };
8577
+ function readString(bytes, position) {
8578
+ const [length, start] = readNumber(bytes, position);
8579
+ if (start + length > bytes.length) throw new Error("invalid wasm string");
8580
+ return [
8581
+ Buffer.from(bytes.buffer, bytes.byteOffset + start, length).toString("utf8"),
8582
+ start + length
8583
+ ];
8546
8584
  }
8547
- function vectorSection(id, count, parts) {
8548
- const body = Buffer.concat([Buffer.from(uleb2(count)), ...parts]);
8549
- return Buffer.concat([Buffer.from([id, ...uleb2(body.length)]), body]);
8585
+ function encodedString(value) {
8586
+ const bytes = Buffer.from(value);
8587
+ return Buffer.concat([encodeNumber(bytes.length), bytes]);
8550
8588
  }
8551
- function rewriteSections(bytes, sections, changes) {
8552
- const out = [bytes.subarray(0, 8)];
8553
- const pending = new Map(changes);
8554
- const flushBefore = (id) => {
8555
- for (const [missing, section2] of pending) {
8556
- if (SECTION_ORDER.indexOf(missing) >= SECTION_ORDER.indexOf(id)) continue;
8557
- if (section2) out.push(section2);
8558
- pending.delete(missing);
8559
- }
8560
- };
8561
- for (const s of sections) {
8562
- if (s.id !== 0) flushBefore(s.id);
8563
- if (!pending.has(s.id)) {
8564
- out.push(bytes.subarray(s.offset, s.end));
8565
- continue;
8566
- }
8567
- const section2 = pending.get(s.id);
8568
- pending.delete(s.id);
8569
- if (section2) out.push(section2);
8589
+ function isWasmMagic(bytes) {
8590
+ return bytes.length >= 8 && bytes[0] === 0 && bytes[1] === 97 && bytes[2] === 115 && bytes[3] === 109 && bytes[4] === 1 && bytes[5] === 0 && bytes[6] === 0 && bytes[7] === 0;
8591
+ }
8592
+ function llvmType(value) {
8593
+ switch (value) {
8594
+ case 127:
8595
+ return "i32";
8596
+ case 126:
8597
+ return "i64";
8598
+ case 125:
8599
+ return "float";
8600
+ case 124:
8601
+ return "double";
8602
+ default:
8603
+ throw new Error(`unsupported wasm function value type ${value}`);
8570
8604
  }
8571
- for (const section2 of pending.values()) if (section2) out.push(section2);
8572
- return Buffer.concat(out);
8573
8605
  }
8574
- function entries(bytes, section2, entry) {
8575
- if (!section2) return [];
8576
- const r = wasmReader(bytes, section2.start);
8577
- const out = [];
8578
- for (let n = r.u(); n > 0; n--) {
8579
- const begin = r.at;
8580
- entry(r);
8581
- out.push(bytes.subarray(begin, r.at));
8582
- }
8583
- if (r.at !== section2.end) throw new Error(`invalid wasm section ${section2.id}`);
8584
- return out;
8585
- }
8586
- var readExport = (r) => {
8587
- r.name();
8588
- r.byte();
8589
- r.u();
8590
- };
8591
- function appendLazyPlacement(bytes, functions, table) {
8592
- const sections = wasmSections(bytes);
8593
- const section2 = (id) => sections.find((s) => s.id === id);
8594
- const imports = readImports2(bytes, sections);
8595
- const changes = /* @__PURE__ */ new Map();
8596
- let table64 = imports.table64;
8597
- if (table64 === void 0) {
8598
- if (!table) throw new Error("native image has no function table");
8599
- table64 = table.table64;
8600
- const found = section2(2);
8601
- const header = found && wasmReader(bytes, found.start);
8602
- const count = header ? header.u() : 0;
8603
- const module = Buffer.from("primary");
8604
- const name2 = Buffer.from(table.name);
8605
- changes.set(
8606
- 2,
8607
- vectorSection(2, count + 1, [
8608
- found && header ? bytes.subarray(header.at, found.end) : new Uint8Array(),
8609
- Buffer.from([
8610
- ...uleb2(module.length),
8611
- ...module,
8612
- ...uleb2(name2.length),
8613
- ...name2,
8614
- 1,
8615
- 112,
8616
- table64 ? 4 : 0,
8617
- 0
8618
- ])
8619
- ])
8620
- );
8621
- }
8622
- const types = entries(bytes, section2(1), (r) => {
8623
- if (r.byte() !== 96) throw new Error("native image has a non-function type");
8624
- for (let side = 0; side < 2; side++) for (let n = r.u(); n > 0; n--) skipValueType(r);
8625
- });
8626
- const declared = entries(bytes, section2(3), (r) => r.u());
8627
- const bodies = entries(bytes, section2(10), (r) => r.skip(r.u()));
8628
- const exports = entries(bytes, section2(7), readExport);
8629
- const elements = entries(bytes, section2(9), skipElementSegment);
8630
- const placementIndex = lastTableElement(elements) + 1;
8631
- elements.splice(
8632
- placementIndex,
8633
- 0,
8634
- Buffer.from([1, 0, ...uleb2(functions.length), ...functions.flatMap(uleb2)])
8635
- );
8636
- const place2 = imports.functions + declared.length;
8637
- const instructions = [
8638
- 0,
8639
- 32,
8640
- 1,
8641
- ...table64 ? [173] : [],
8642
- 32,
8643
- 0,
8644
- 65,
8645
- 1,
8646
- 252,
8647
- 12,
8648
- ...uleb2(placementIndex),
8649
- 0,
8650
- 11
8651
- ];
8652
- const name = Buffer.from(NATIVE_DYLD_PLACE_EXPORT);
8653
- return rewriteSections(
8654
- bytes,
8655
- sections,
8656
- new Map([
8657
- ...changes,
8658
- [
8659
- 1,
8660
- vectorSection(1, types.length + 1, [
8661
- ...types,
8662
- Buffer.from([96, 2, 127, 127, 0])
8663
- ])
8664
- ],
8665
- [
8666
- 3,
8667
- vectorSection(3, declared.length + 1, [
8668
- ...declared,
8669
- Buffer.from(uleb2(types.length))
8670
- ])
8671
- ],
8672
- [
8673
- 7,
8674
- vectorSection(7, exports.length + 1, [
8675
- ...exports,
8676
- Buffer.from([...uleb2(name.length), ...name, 0, ...uleb2(place2)])
8677
- ])
8678
- ],
8679
- [9, vectorSection(9, elements.length, elements)],
8680
- [
8681
- 10,
8682
- vectorSection(10, bodies.length + 1, [
8683
- ...bodies,
8684
- Buffer.from([...uleb2(instructions.length), ...instructions])
8685
- ])
8686
- ]
8687
- ])
8688
- );
8689
- }
8690
- function skipConstant(r) {
8691
- for (let op = r.byte(); op !== 11; op = r.byte()) {
8692
- if (op === 65 || op === 66) r.s();
8693
- else if (op === 35 || op === 210) r.u();
8694
- else if (op === 208) r.s();
8695
- else if (![106, 107, 108, 124, 125, 126].includes(op))
8696
- throw new Error(`unsupported constant expression op ${op}`);
8697
- }
8698
- }
8699
- function skipElementSegment(r) {
8700
- const flags = r.u();
8701
- if (flags > 7) throw new Error(`unsupported element segment flags ${flags}`);
8702
- if ((flags & 3) === 2) r.u();
8703
- if (!(flags & 1)) skipConstant(r);
8704
- if (flags & 3) skipValueType(r);
8705
- for (let count = r.u(); count > 0; count--)
8706
- if (flags & 4) skipConstant(r);
8707
- else r.u();
8708
- }
8709
- var lastTableElement = (segments) => segments.findLastIndex((segment) => (segment[0] & 3) !== 3);
8710
- function placeGuestLazyFunctions(bytes, lazy) {
8711
- const sections = wasmSections(bytes);
8712
- const lazyIndex = new Map(lazy.map((name, index) => [name, index]));
8713
- const functions = new Array(lazy.length);
8714
- let found = 0;
8715
- const kept = entries(
8716
- bytes,
8717
- sections.find((s) => s.id === 7),
8718
- readExport
8719
- ).filter((entry) => {
8720
- const r = wasmReader(entry, 0);
8721
- const position = lazyIndex.get(r.name());
8722
- const kind = r.byte();
8723
- if (kind !== 0 || position === void 0) return true;
8724
- functions[position] = r.u();
8725
- found++;
8726
- return false;
8727
- });
8728
- if (found !== lazy.length)
8729
- throw new Error("guest link lost a lazy dlsym function export");
8730
- return appendLazyPlacement(
8731
- rewriteSections(bytes, sections, /* @__PURE__ */ new Map([[7, vectorSection(7, kept.length, kept)]])),
8732
- functions
8733
- );
8734
- }
8735
- function guestLazyExports(lazy) {
8736
- return lazy.map((name) => JSON.stringify(`--export=${name}`)).join("\n");
8737
- }
8738
-
8739
- // src/swift-guest-dyld-table.ts
8740
- import { createHash as createHash5 } from "node:crypto";
8741
- import { deflateRawSync } from "node:zlib";
8742
-
8743
- // ../peach-kit/src/nativeDyldTableContract.ts
8744
- var NATIVE_DYLD_TABLE_SECTION = "peach.dyld-table-v1";
8745
- var NATIVE_DYLD_PACKS_SECTION = "peach.dyld-packs-v1";
8746
-
8747
- // src/swift-guest-image-ledger.ts
8748
- import { createHash as createHash4 } from "node:crypto";
8749
- var ByteWriter = class {
8750
- constructor(initialCapacity = 256) {
8751
- __publicField(this, "buf");
8752
- __publicField(this, "pos", 0);
8753
- this.buf = Buffer.allocUnsafe(Math.max(64, initialCapacity));
8754
- }
8755
- ensure(extra) {
8756
- const needed = this.pos + extra;
8757
- if (needed <= this.buf.length) return;
8758
- let next = this.buf.length * 2;
8759
- while (next < needed) next *= 2;
8760
- const grown = Buffer.allocUnsafe(next);
8761
- this.buf.copy(grown, 0, 0, this.pos);
8762
- this.buf = grown;
8763
- }
8764
- byte(value) {
8765
- this.ensure(1);
8766
- this.buf[this.pos++] = value;
8767
- }
8768
- uleb(value) {
8769
- this.ensure(10);
8770
- let pos = this.pos;
8771
- const buf = this.buf;
8772
- do {
8773
- let byte = value % 128;
8774
- value = Math.floor(value / 128);
8775
- if (value) byte |= 128;
8776
- buf[pos++] = byte;
8777
- } while (value);
8778
- this.pos = pos;
8779
- }
8780
- bytes(source, start = 0, end = source.length) {
8781
- const len = end - start;
8782
- if (len <= 0) return;
8783
- this.ensure(len);
8784
- this.buf.set(source.subarray(start, end), this.pos);
8785
- this.pos += len;
8786
- }
8787
- string(value) {
8788
- const len = Buffer.byteLength(value, "utf8");
8789
- this.uleb(len);
8790
- if (len > 0) {
8791
- this.ensure(len);
8792
- this.buf.write(value, this.pos, len, "utf8");
8793
- this.pos += len;
8794
- }
8795
- }
8796
- finish() {
8797
- return this.buf.subarray(0, this.pos);
8798
- }
8799
- };
8800
- function readNumber(bytes, position) {
8801
- if (position < bytes.length) {
8802
- const first = bytes[position];
8803
- if (first < 128) return [first, position + 1];
8804
- }
8805
- let value = 0;
8806
- let shift = 0;
8807
- for (; ; ) {
8808
- if (position >= bytes.length || shift > 63) throw new Error("invalid wasm integer");
8809
- const byte = bytes[position++];
8810
- value += (byte & 127) * 2 ** shift;
8811
- if (!(byte & 128)) return [value, position];
8812
- shift += 7;
8813
- }
8814
- }
8815
- function encodeNumber(value) {
8816
- if (value < 128) return Buffer.from([value]);
8817
- const bytes = [];
8818
- do {
8819
- let byte = value % 128;
8820
- value = Math.floor(value / 128);
8821
- if (value) byte |= 128;
8822
- bytes.push(byte);
8823
- } while (value);
8824
- return Buffer.from(bytes);
8825
- }
8826
- function readString(bytes, position) {
8827
- const [length, start] = readNumber(bytes, position);
8828
- if (start + length > bytes.length) throw new Error("invalid wasm string");
8829
- return [
8830
- Buffer.from(bytes.buffer, bytes.byteOffset + start, length).toString("utf8"),
8831
- start + length
8832
- ];
8833
- }
8834
- function encodedString(value) {
8835
- const bytes = Buffer.from(value);
8836
- return Buffer.concat([encodeNumber(bytes.length), bytes]);
8837
- }
8838
- function isWasmMagic(bytes) {
8839
- return bytes.length >= 8 && bytes[0] === 0 && bytes[1] === 97 && bytes[2] === 115 && bytes[3] === 109 && bytes[4] === 1 && bytes[5] === 0 && bytes[6] === 0 && bytes[7] === 0;
8840
- }
8841
- function llvmType(value) {
8842
- switch (value) {
8843
- case 127:
8844
- return "i32";
8845
- case 126:
8846
- return "i64";
8847
- case 125:
8848
- return "float";
8849
- case 124:
8850
- return "double";
8851
- default:
8852
- throw new Error(`unsupported wasm function value type ${value}`);
8853
- }
8854
- }
8855
- var OBJC_INIT_RECORD = ".objc_init";
8856
- var TABLE_INDEX_RELOCATIONS = /* @__PURE__ */ new Set([1, 2, 12, 18, 19, 24]);
8857
- function concatParts(parts) {
8858
- let total = 0;
8859
- for (let i = 0; i < parts.length; i++) total += parts[i].byteLength;
8860
- const out = Buffer.allocUnsafe(total);
8861
- let offset = 0;
8862
- for (let i = 0; i < parts.length; i++) {
8863
- const part = parts[i];
8864
- out.set(part, offset);
8865
- offset += part.byteLength;
8606
+ var OBJC_INIT_RECORD = ".objc_init";
8607
+ var TABLE_INDEX_RELOCATIONS = /* @__PURE__ */ new Set([1, 2, 12, 18, 19, 24]);
8608
+ function concatParts(parts) {
8609
+ let total = 0;
8610
+ for (let i = 0; i < parts.length; i++) total += parts[i].byteLength;
8611
+ const out = Buffer.allocUnsafe(total);
8612
+ let offset = 0;
8613
+ for (let i = 0; i < parts.length; i++) {
8614
+ const part = parts[i];
8615
+ out.set(part, offset);
8616
+ offset += part.byteLength;
8866
8617
  }
8867
8618
  return out;
8868
8619
  }
@@ -10360,139 +10111,385 @@ function withWasmTableMinimum(bytes, minimum) {
10360
10111
  layout2,
10361
10112
  /* @__PURE__ */ new Map([
10362
10113
  [
10363
- 4,
10364
- [
10365
- 1,
10366
- type,
10367
- flags,
10368
- ...encodeWasmNumber(minimum),
10369
- ...maximum === void 0 ? [] : encodeWasmNumber(Math.max(maximum, minimum)),
10370
- ...rest
10371
- ]
10114
+ 4,
10115
+ [
10116
+ 1,
10117
+ type,
10118
+ flags,
10119
+ ...encodeWasmNumber(minimum),
10120
+ ...maximum === void 0 ? [] : encodeWasmNumber(Math.max(maximum, minimum)),
10121
+ ...rest
10122
+ ]
10123
+ ]
10124
+ ])
10125
+ );
10126
+ }
10127
+
10128
+ // src/swift-guest-dyld-table.ts
10129
+ function sha256Buffer(bytes) {
10130
+ if (typeof Bun !== "undefined")
10131
+ return Buffer.from(new Bun.CryptoHasher("sha256").update(bytes).digest());
10132
+ return createHash5("sha256").update(bytes).digest();
10133
+ }
10134
+ var PACK_BYTES = 64 * 1024;
10135
+ function uleb2(value) {
10136
+ const bytes = [];
10137
+ for (let rest = value; ; rest = Math.floor(rest / 128)) {
10138
+ if (rest < 128) return [...bytes, rest];
10139
+ bytes.push(rest % 128 | 128);
10140
+ }
10141
+ }
10142
+ function encodeGuestDyldTable(rows) {
10143
+ const encoded = rows.map((row) => ({ ...row, bytes: Buffer.from(row.name) })).sort((a, b) => Buffer.compare(a.bytes, b.bytes));
10144
+ const packs = [];
10145
+ const firsts = [];
10146
+ let current = [];
10147
+ let size = 0;
10148
+ for (const [index, row] of encoded.entries()) {
10149
+ if (row.bytes.includes(0)) throw new Error("dyld symbol name contains a null byte");
10150
+ const value = Buffer.alloc(8);
10151
+ value.writeBigUInt64LE(row.value);
10152
+ const bytes = Buffer.concat([
10153
+ row.bytes,
10154
+ Buffer.from([0, ...uleb2(row.image), row.kind]),
10155
+ value
10156
+ ]);
10157
+ if (!current.length) firsts.push(row.bytes);
10158
+ current.push(bytes);
10159
+ size += bytes.length;
10160
+ const next = encoded[index + 1];
10161
+ if (!next || size >= PACK_BYTES && !next.bytes.equals(row.bytes)) {
10162
+ packs.push(deflateRawSync(Buffer.concat(current), { level: 9 }));
10163
+ current = [];
10164
+ size = 0;
10165
+ }
10166
+ }
10167
+ const file = Buffer.concat(packs);
10168
+ const header = Buffer.alloc(40 + packs.length * 8);
10169
+ sha256Buffer(file).copy(header, 0);
10170
+ header.writeUInt32LE(file.length, 32);
10171
+ header.writeUInt32LE(packs.length, 36);
10172
+ let offset = 0;
10173
+ for (const [index, pack] of packs.entries()) {
10174
+ header.writeUInt32LE(offset, 40 + index * 8);
10175
+ header.writeUInt32LE(pack.length, 44 + index * 8);
10176
+ offset += pack.length;
10177
+ }
10178
+ const names = firsts.flatMap((name) => [name, Buffer.of(0)]);
10179
+ return { index: Buffer.concat([header, ...names]), packs: file };
10180
+ }
10181
+ function moveGuestDyldTable(map, wasm, symbols, bindingValues = /* @__PURE__ */ new Map(), extraSections = []) {
10182
+ const range = guestDyldValueRange(map);
10183
+ if (!range) {
10184
+ if (symbols.length) throw new Error("link map has no dyld values");
10185
+ return extraSections.length ? writeWasmCustomSections(wasm, extraSections) : wasm;
10186
+ }
10187
+ if (range.length !== symbols.length * 8)
10188
+ throw new Error("linked dyld values do not match the ledger rows");
10189
+ const taken = takeGuestStartupData(wasm, range.address, range.length);
10190
+ const view = new DataView(
10191
+ taken.bytes.buffer,
10192
+ taken.bytes.byteOffset,
10193
+ taken.bytes.length
10194
+ );
10195
+ const rows = symbols.map(({ name, image }, index2) => {
10196
+ const binding = bindingValues.get(index2);
10197
+ return binding === void 0 ? { name, image, kind: 0, value: view.getBigUint64(index2 * 8, true) } : { name, image, kind: 1, value: BigInt(binding) };
10198
+ });
10199
+ const { index, packs } = encodeGuestDyldTable(rows);
10200
+ return writeWasmCustomSections(taken.wasm, [
10201
+ [NATIVE_DYLD_TABLE_SECTION, index],
10202
+ [NATIVE_DYLD_PACKS_SECTION, packs],
10203
+ ...extraSections
10204
+ ]);
10205
+ }
10206
+ function guestDyldValueRange(map) {
10207
+ const suffix = `:(${GUEST_DYLD_VALUES_SECTION})`;
10208
+ let found;
10209
+ for (let at = map.indexOf(suffix); at !== -1; at = map.indexOf(suffix, at + suffix.length)) {
10210
+ const lineEnd = at + suffix.length;
10211
+ if (lineEnd < map.length && map.charCodeAt(lineEnd) !== 10) continue;
10212
+ const lineStart = map.lastIndexOf("\n", at) + 1;
10213
+ const line = map.slice(lineStart, lineEnd);
10214
+ const match = /^\s*([\da-f]+)\s+[\da-f]+\s+([\da-f]+)\s/.exec(line);
10215
+ if (!match) throw new Error("unreadable dyld values map line");
10216
+ if (found) throw new Error("link map has several dyld value sections");
10217
+ found = { address: parseInt(match[1], 16), length: parseInt(match[2], 16) };
10218
+ }
10219
+ return found;
10220
+ }
10221
+
10222
+ // src/swift-guest-link.ts
10223
+ import { execFile as execFile2, execFileSync as execFileSync5, spawn } from "node:child_process";
10224
+ import fs3 from "node:fs";
10225
+ import path10 from "node:path";
10226
+ import { promisify as promisify2 } from "node:util";
10227
+
10228
+ // ../../src/helpers/mapLimit.ts
10229
+ async function mapLimit(items, limit, worker) {
10230
+ const results = new Array(items.length);
10231
+ let next = 0;
10232
+ let failure;
10233
+ await Promise.all(
10234
+ Array.from({ length: Math.min(limit, items.length) }, async () => {
10235
+ while (!failure && next < items.length) {
10236
+ const index = next++;
10237
+ try {
10238
+ results[index] = await worker(items[index], index);
10239
+ } catch (error) {
10240
+ failure ?? (failure = { error });
10241
+ }
10242
+ }
10243
+ })
10244
+ );
10245
+ if (failure) throw failure.error;
10246
+ return results;
10247
+ }
10248
+
10249
+ // src/swift-guest-dyld-functions.ts
10250
+ var uleb3 = (value) => {
10251
+ const out = [];
10252
+ do {
10253
+ let byte = value % 128;
10254
+ value = Math.floor(value / 128);
10255
+ if (value) byte |= 128;
10256
+ out.push(byte);
10257
+ } while (value);
10258
+ return out;
10259
+ };
10260
+ var SECTION_ORDER = [1, 2, 3, 4, 5, 13, 6, 7, 8, 9, 12, 10, 11];
10261
+ function skipValueType(r) {
10262
+ const type = r.byte();
10263
+ if (type === 99 || type === 100) r.s();
10264
+ }
10265
+ function readImports2(bytes, sections) {
10266
+ let functions = 0;
10267
+ let table64;
10268
+ const imports = sections.find((s) => s.id === 2);
10269
+ if (imports) {
10270
+ const r = wasmReader(bytes, imports.start);
10271
+ for (let n = r.u(); n > 0; n--) {
10272
+ r.name();
10273
+ r.name();
10274
+ const kind = r.byte();
10275
+ if (kind === 0) {
10276
+ functions++;
10277
+ r.u();
10278
+ } else if (kind === 1 || kind === 2) {
10279
+ if (kind === 1) skipValueType(r);
10280
+ const flags = r.u();
10281
+ r.u();
10282
+ if (flags & 1) r.u();
10283
+ if (kind === 1) table64 ?? (table64 = (flags & 4) !== 0);
10284
+ } else if (kind === 3) {
10285
+ skipValueType(r);
10286
+ r.byte();
10287
+ } else if (kind === 4) {
10288
+ r.byte();
10289
+ r.u();
10290
+ } else throw new Error(`unsupported wasm import kind ${kind}`);
10291
+ }
10292
+ }
10293
+ const tables = sections.find((s) => s.id === 4);
10294
+ if (table64 === void 0 && tables) {
10295
+ const r = wasmReader(bytes, tables.start);
10296
+ if (r.u()) {
10297
+ skipValueType(r);
10298
+ table64 = (r.u() & 4) !== 0;
10299
+ }
10300
+ }
10301
+ return { functions, table64 };
10302
+ }
10303
+ function vectorSection(id, count, parts) {
10304
+ const body = Buffer.concat([Buffer.from(uleb3(count)), ...parts]);
10305
+ return Buffer.concat([Buffer.from([id, ...uleb3(body.length)]), body]);
10306
+ }
10307
+ function rewriteSections(bytes, sections, changes) {
10308
+ const out = [bytes.subarray(0, 8)];
10309
+ const pending = new Map(changes);
10310
+ const flushBefore = (id) => {
10311
+ for (const [missing, section2] of pending) {
10312
+ if (SECTION_ORDER.indexOf(missing) >= SECTION_ORDER.indexOf(id)) continue;
10313
+ if (section2) out.push(section2);
10314
+ pending.delete(missing);
10315
+ }
10316
+ };
10317
+ for (const s of sections) {
10318
+ if (s.id !== 0) flushBefore(s.id);
10319
+ if (!pending.has(s.id)) {
10320
+ out.push(bytes.subarray(s.offset, s.end));
10321
+ continue;
10322
+ }
10323
+ const section2 = pending.get(s.id);
10324
+ pending.delete(s.id);
10325
+ if (section2) out.push(section2);
10326
+ }
10327
+ for (const section2 of pending.values()) if (section2) out.push(section2);
10328
+ return Buffer.concat(out);
10329
+ }
10330
+ function entries(bytes, section2, entry) {
10331
+ if (!section2) return [];
10332
+ const r = wasmReader(bytes, section2.start);
10333
+ const out = [];
10334
+ for (let n = r.u(); n > 0; n--) {
10335
+ const begin = r.at;
10336
+ entry(r);
10337
+ out.push(bytes.subarray(begin, r.at));
10338
+ }
10339
+ if (r.at !== section2.end) throw new Error(`invalid wasm section ${section2.id}`);
10340
+ return out;
10341
+ }
10342
+ var readExport = (r) => {
10343
+ r.name();
10344
+ r.byte();
10345
+ r.u();
10346
+ };
10347
+ function appendLazyPlacement(bytes, functions, table) {
10348
+ const sections = wasmSections(bytes);
10349
+ const section2 = (id) => sections.find((s) => s.id === id);
10350
+ const imports = readImports2(bytes, sections);
10351
+ const changes = /* @__PURE__ */ new Map();
10352
+ let table64 = imports.table64;
10353
+ if (table64 === void 0) {
10354
+ if (!table) throw new Error("native image has no function table");
10355
+ table64 = table.table64;
10356
+ const found = section2(2);
10357
+ const header = found && wasmReader(bytes, found.start);
10358
+ const count = header ? header.u() : 0;
10359
+ const module = Buffer.from("primary");
10360
+ const name2 = Buffer.from(table.name);
10361
+ changes.set(
10362
+ 2,
10363
+ vectorSection(2, count + 1, [
10364
+ found && header ? bytes.subarray(header.at, found.end) : new Uint8Array(),
10365
+ Buffer.from([
10366
+ ...uleb3(module.length),
10367
+ ...module,
10368
+ ...uleb3(name2.length),
10369
+ ...name2,
10370
+ 1,
10371
+ 112,
10372
+ table64 ? 4 : 0,
10373
+ 0
10374
+ ])
10375
+ ])
10376
+ );
10377
+ }
10378
+ const types = entries(bytes, section2(1), (r) => {
10379
+ if (r.byte() !== 96) throw new Error("native image has a non-function type");
10380
+ for (let side = 0; side < 2; side++) for (let n = r.u(); n > 0; n--) skipValueType(r);
10381
+ });
10382
+ const declared = entries(bytes, section2(3), (r) => r.u());
10383
+ const bodies = entries(bytes, section2(10), (r) => r.skip(r.u()));
10384
+ const exports = entries(bytes, section2(7), readExport);
10385
+ const elements = entries(bytes, section2(9), skipElementSegment);
10386
+ const placementIndex = lastTableElement(elements) + 1;
10387
+ elements.splice(
10388
+ placementIndex,
10389
+ 0,
10390
+ Buffer.from([1, 0, ...uleb3(functions.length), ...functions.flatMap(uleb3)])
10391
+ );
10392
+ const place2 = imports.functions + declared.length;
10393
+ const instructions = [
10394
+ 0,
10395
+ 32,
10396
+ 1,
10397
+ ...table64 ? [173] : [],
10398
+ 32,
10399
+ 0,
10400
+ 65,
10401
+ 1,
10402
+ 252,
10403
+ 12,
10404
+ ...uleb3(placementIndex),
10405
+ 0,
10406
+ 11
10407
+ ];
10408
+ const name = Buffer.from(NATIVE_DYLD_PLACE_EXPORT);
10409
+ return rewriteSections(
10410
+ bytes,
10411
+ sections,
10412
+ new Map([
10413
+ ...changes,
10414
+ [
10415
+ 1,
10416
+ vectorSection(1, types.length + 1, [
10417
+ ...types,
10418
+ Buffer.from([96, 2, 127, 127, 0])
10419
+ ])
10420
+ ],
10421
+ [
10422
+ 3,
10423
+ vectorSection(3, declared.length + 1, [
10424
+ ...declared,
10425
+ Buffer.from(uleb3(types.length))
10426
+ ])
10427
+ ],
10428
+ [
10429
+ 7,
10430
+ vectorSection(7, exports.length + 1, [
10431
+ ...exports,
10432
+ Buffer.from([...uleb3(name.length), ...name, 0, ...uleb3(place2)])
10433
+ ])
10434
+ ],
10435
+ [9, vectorSection(9, elements.length, elements)],
10436
+ [
10437
+ 10,
10438
+ vectorSection(10, bodies.length + 1, [
10439
+ ...bodies,
10440
+ Buffer.from([...uleb3(instructions.length), ...instructions])
10441
+ ])
10372
10442
  ]
10373
10443
  ])
10374
10444
  );
10375
10445
  }
10376
-
10377
- // src/swift-guest-dyld-table.ts
10378
- function sha256Buffer(bytes) {
10379
- if (typeof Bun !== "undefined")
10380
- return Buffer.from(new Bun.CryptoHasher("sha256").update(bytes).digest());
10381
- return createHash5("sha256").update(bytes).digest();
10382
- }
10383
- var PACK_BYTES = 64 * 1024;
10384
- function uleb3(value) {
10385
- const bytes = [];
10386
- for (let rest = value; ; rest = Math.floor(rest / 128)) {
10387
- if (rest < 128) return [...bytes, rest];
10388
- bytes.push(rest % 128 | 128);
10446
+ function skipConstant(r) {
10447
+ for (let op = r.byte(); op !== 11; op = r.byte()) {
10448
+ if (op === 65 || op === 66) r.s();
10449
+ else if (op === 35 || op === 210) r.u();
10450
+ else if (op === 208) r.s();
10451
+ else if (![106, 107, 108, 124, 125, 126].includes(op))
10452
+ throw new Error(`unsupported constant expression op ${op}`);
10389
10453
  }
10390
10454
  }
10391
- function encodeGuestDyldTable(rows) {
10392
- const encoded = rows.map((row) => ({ ...row, bytes: Buffer.from(row.name) })).sort((a, b) => Buffer.compare(a.bytes, b.bytes));
10393
- const packs = [];
10394
- const firsts = [];
10395
- let current = [];
10396
- let size = 0;
10397
- for (const [index, row] of encoded.entries()) {
10398
- if (row.bytes.includes(0)) throw new Error("dyld symbol name contains a null byte");
10399
- const value = Buffer.alloc(8);
10400
- value.writeBigUInt64LE(row.value);
10401
- const bytes = Buffer.concat([
10402
- row.bytes,
10403
- Buffer.from([0, ...uleb3(row.image), row.kind]),
10404
- value
10405
- ]);
10406
- if (!current.length) firsts.push(row.bytes);
10407
- current.push(bytes);
10408
- size += bytes.length;
10409
- const next = encoded[index + 1];
10410
- if (!next || size >= PACK_BYTES && !next.bytes.equals(row.bytes)) {
10411
- packs.push(deflateRawSync(Buffer.concat(current), { level: 9 }));
10412
- current = [];
10413
- size = 0;
10414
- }
10415
- }
10416
- const file = Buffer.concat(packs);
10417
- const header = Buffer.alloc(40 + packs.length * 8);
10418
- sha256Buffer(file).copy(header, 0);
10419
- header.writeUInt32LE(file.length, 32);
10420
- header.writeUInt32LE(packs.length, 36);
10421
- let offset = 0;
10422
- for (const [index, pack] of packs.entries()) {
10423
- header.writeUInt32LE(offset, 40 + index * 8);
10424
- header.writeUInt32LE(pack.length, 44 + index * 8);
10425
- offset += pack.length;
10426
- }
10427
- const names = firsts.flatMap((name) => [name, Buffer.of(0)]);
10428
- return { index: Buffer.concat([header, ...names]), packs: file };
10455
+ function skipElementSegment(r) {
10456
+ const flags = r.u();
10457
+ if (flags > 7) throw new Error(`unsupported element segment flags ${flags}`);
10458
+ if ((flags & 3) === 2) r.u();
10459
+ if (!(flags & 1)) skipConstant(r);
10460
+ if (flags & 3) skipValueType(r);
10461
+ for (let count = r.u(); count > 0; count--)
10462
+ if (flags & 4) skipConstant(r);
10463
+ else r.u();
10429
10464
  }
10430
- function moveGuestDyldTable(map, wasm, symbols, bindingValues = /* @__PURE__ */ new Map(), extraSections = []) {
10431
- const range = guestDyldValueRange(map);
10432
- if (!range) {
10433
- if (symbols.length) throw new Error("link map has no dyld values");
10434
- return extraSections.length ? writeWasmCustomSections(wasm, extraSections) : wasm;
10435
- }
10436
- if (range.length !== symbols.length * 8)
10437
- throw new Error("linked dyld values do not match the ledger rows");
10438
- const taken = takeGuestStartupData(wasm, range.address, range.length);
10439
- const view = new DataView(
10440
- taken.bytes.buffer,
10441
- taken.bytes.byteOffset,
10442
- taken.bytes.length
10443
- );
10444
- const rows = symbols.map(({ name, image }, index2) => {
10445
- const binding = bindingValues.get(index2);
10446
- return binding === void 0 ? { name, image, kind: 0, value: view.getBigUint64(index2 * 8, true) } : { name, image, kind: 1, value: BigInt(binding) };
10465
+ var lastTableElement = (segments) => segments.findLastIndex((segment) => (segment[0] & 3) !== 3);
10466
+ function placeGuestLazyFunctions(bytes, lazy) {
10467
+ const sections = wasmSections(bytes);
10468
+ const lazyIndex = new Map(lazy.map((name, index) => [name, index]));
10469
+ const functions = new Array(lazy.length);
10470
+ let found = 0;
10471
+ const kept = entries(
10472
+ bytes,
10473
+ sections.find((s) => s.id === 7),
10474
+ readExport
10475
+ ).filter((entry) => {
10476
+ const r = wasmReader(entry, 0);
10477
+ const position = lazyIndex.get(r.name());
10478
+ const kind = r.byte();
10479
+ if (kind !== 0 || position === void 0) return true;
10480
+ functions[position] = r.u();
10481
+ found++;
10482
+ return false;
10447
10483
  });
10448
- const { index, packs } = encodeGuestDyldTable(rows);
10449
- return writeWasmCustomSections(taken.wasm, [
10450
- [NATIVE_DYLD_TABLE_SECTION, index],
10451
- [NATIVE_DYLD_PACKS_SECTION, packs],
10452
- ...extraSections
10453
- ]);
10454
- }
10455
- function guestDyldValueRange(map) {
10456
- const suffix = `:(${GUEST_DYLD_VALUES_SECTION})`;
10457
- let found;
10458
- for (let at = map.indexOf(suffix); at !== -1; at = map.indexOf(suffix, at + suffix.length)) {
10459
- const lineEnd = at + suffix.length;
10460
- if (lineEnd < map.length && map.charCodeAt(lineEnd) !== 10) continue;
10461
- const lineStart = map.lastIndexOf("\n", at) + 1;
10462
- const line = map.slice(lineStart, lineEnd);
10463
- const match = /^\s*([\da-f]+)\s+[\da-f]+\s+([\da-f]+)\s/.exec(line);
10464
- if (!match) throw new Error("unreadable dyld values map line");
10465
- if (found) throw new Error("link map has several dyld value sections");
10466
- found = { address: parseInt(match[1], 16), length: parseInt(match[2], 16) };
10467
- }
10468
- return found;
10469
- }
10470
-
10471
- // src/swift-guest-link.ts
10472
- import { execFile as execFile2, execFileSync as execFileSync5, spawn } from "node:child_process";
10473
- import fs3 from "node:fs";
10474
- import path10 from "node:path";
10475
- import { promisify as promisify2 } from "node:util";
10476
-
10477
- // ../../src/helpers/mapLimit.ts
10478
- async function mapLimit(items, limit, worker) {
10479
- const results = new Array(items.length);
10480
- let next = 0;
10481
- let failure;
10482
- await Promise.all(
10483
- Array.from({ length: Math.min(limit, items.length) }, async () => {
10484
- while (!failure && next < items.length) {
10485
- const index = next++;
10486
- try {
10487
- results[index] = await worker(items[index], index);
10488
- } catch (error) {
10489
- failure ?? (failure = { error });
10490
- }
10491
- }
10492
- })
10484
+ if (found !== lazy.length)
10485
+ throw new Error("guest link lost a lazy dlsym function export");
10486
+ return appendLazyPlacement(
10487
+ rewriteSections(bytes, sections, /* @__PURE__ */ new Map([[7, vectorSection(7, kept.length, kept)]])),
10488
+ functions
10493
10489
  );
10494
- if (failure) throw failure.error;
10495
- return results;
10490
+ }
10491
+ function guestLazyExports(lazy) {
10492
+ return lazy.map((name) => JSON.stringify(`--export=${name}`)).join("\n");
10496
10493
  }
10497
10494
 
10498
10495
  // src/swift-guest-link-plan.ts
@@ -14362,9 +14359,11 @@ async function compileGuestLink(options) {
14362
14359
  return [...source, ...runtime].sort((a, b) => a.image - b.image);
14363
14360
  };
14364
14361
  const sdk = options.sdkImage;
14365
- const sdkCallers = sdk?.sdkInterface.guestCallers;
14366
- const sdkObjects = sdk ? (await import("./swift-sdk-image-3NCWCGQZ.mjs")).readSwiftSdkManifestIndex(sdk).guestObjects : void 0;
14367
- if (sdk && (!sdkCallers || !sdkObjects))
14362
+ const sdkCallers = sdk.sdkInterface.guestCallers;
14363
+ const sdkObjects = (await import("./swift-sdk-image-HZG64EBF.mjs")).readSwiftSdkManifestIndex(
14364
+ sdk
14365
+ ).guestObjects;
14366
+ if (!sdkCallers || !sdkObjects)
14368
14367
  throw new Error("the SDK image has no guest link manifest");
14369
14368
  const result = await linkPrunedGuestImages({
14370
14369
  buildDirectory: options.buildDirectory,
@@ -14377,14 +14376,14 @@ async function compileGuestLink(options) {
14377
14376
  ledgerDataImage: 0,
14378
14377
  framework: catalogs.framework,
14379
14378
  sdkProducts: null,
14380
- sharedSdk: sdkCallers && sdkObjects ? {
14379
+ sharedSdk: {
14381
14380
  callers: sdkCallers,
14382
14381
  hasContainingObject: (identity) => sdkObjects[sdkGuestObjectKey(identity)] !== void 0
14383
- } : void 0,
14384
- onSplitInputs: sdk ? (value) => {
14382
+ },
14383
+ onSplitInputs: (value) => {
14385
14384
  splitInputs = value;
14386
- } : void 0,
14387
- deferFinalLink: Boolean(sdk),
14385
+ },
14386
+ deferFinalLink: true,
14388
14387
  onDyldRows: (rows) => {
14389
14388
  lazyFunctions = rows.lazyFunctions;
14390
14389
  dyldSymbols = rows.dyldSymbols;
@@ -14652,191 +14651,165 @@ async function compileGuestLink(options) {
14652
14651
  }
14653
14652
  });
14654
14653
  if (!reserved || !projectionObject) throw new Error("guest projection was not reserved");
14655
- if (sdk) {
14656
- try {
14657
- if (!splitInputs) throw new Error("guest link did not select shared SDK inputs");
14658
- const {
14659
- createSwiftSdkBinding,
14660
- linkSwiftAppModule,
14661
- readSwiftSdkUsage,
14662
- swiftAppModuleThunkSection,
14663
- swiftSdkProjectionSpans
14664
- } = await import("./swift-sdk-app-module-VHAOCBXW.mjs");
14665
- const project = options.project;
14666
- const work = project ? mkdtempSync2(path14.join(directory, "app-module-")) : path14.join(directory, "app-module");
14667
- if (project) chownSync(work, project.uid, project.gid);
14668
- else mkdirSync5(work, { recursive: true });
14669
- const layoutMap = path14.join(work, "app.map");
14670
- let appProjectionObject = projectionObject;
14671
- const owners = new Map(splitInputs.appObjects).set(appProjectionObject, 0);
14672
- const sdkObjectKeys = /* @__PURE__ */ new Map();
14673
- const sdkObjectImages = /* @__PURE__ */ new Map();
14674
- const sdkProductImages = new Map(prepared?.sdkProducts.images);
14675
- for (const [file, { image, product, identity }] of splitInputs.sdkObjects) {
14676
- const key = sdkGuestObjectKey(identity);
14677
- sdkObjectKeys.set(file, key);
14678
- sdkObjectImages.set(key, image);
14679
- const priorImage = sdkProductImages.get(product);
14680
- if (priorImage !== void 0 && priorImage !== image)
14681
- throw new Error(`SDK product ${product} has several guest images`);
14682
- sdkProductImages.set(product, image);
14654
+ try {
14655
+ if (!splitInputs) throw new Error("guest link did not select shared SDK inputs");
14656
+ const {
14657
+ createSwiftSdkBinding,
14658
+ linkSwiftAppModule,
14659
+ readSwiftSdkUsage,
14660
+ swiftAppModuleThunkSection,
14661
+ swiftSdkProjectionSpans
14662
+ } = await import("./swift-sdk-app-module-PT7D7AOM.mjs");
14663
+ const project = options.project;
14664
+ const work = project ? mkdtempSync2(path14.join(directory, "app-module-")) : path14.join(directory, "app-module");
14665
+ if (project) chownSync(work, project.uid, project.gid);
14666
+ else mkdirSync5(work, { recursive: true });
14667
+ const layoutMap = path14.join(work, "app.map");
14668
+ let appProjectionObject = projectionObject;
14669
+ const owners = new Map(splitInputs.appObjects).set(appProjectionObject, 0);
14670
+ const sdkObjectKeys = /* @__PURE__ */ new Map();
14671
+ const sdkObjectImages = /* @__PURE__ */ new Map();
14672
+ const sdkProductImages = new Map(prepared?.sdkProducts.images);
14673
+ for (const [file, { image, product, identity }] of splitInputs.sdkObjects) {
14674
+ const key = sdkGuestObjectKey(identity);
14675
+ sdkObjectKeys.set(file, key);
14676
+ sdkObjectImages.set(key, image);
14677
+ const priorImage = sdkProductImages.get(product);
14678
+ if (priorImage !== void 0 && priorImage !== image)
14679
+ throw new Error(`SDK product ${product} has several guest images`);
14680
+ sdkProductImages.set(product, image);
14681
+ }
14682
+ const linkedModule = path14.join(work, "app.wasm");
14683
+ const sdkSpans = swiftSdkProjectionSpans(
14684
+ sdk,
14685
+ (object2, product) => sdkObjectImages.get(object2) ?? sdkProductImages.get(product)
14686
+ );
14687
+ const compileAppProjection = (source) => {
14688
+ const projectionSource = path14.join(work, "projection.c");
14689
+ const nextObject = path14.join(work, "projection.o");
14690
+ writeFileSync5(projectionSource, source);
14691
+ execFileSync8(
14692
+ path14.join(options.toolchainBin, "clang"),
14693
+ [...clangOptions, "-c", projectionSource, "-o", nextObject],
14694
+ { stdio: "pipe" }
14695
+ );
14696
+ if (nextObject !== appProjectionObject) {
14697
+ owners.delete(appProjectionObject);
14698
+ appProjectionObject = nextObject;
14699
+ owners.set(appProjectionObject, 0);
14683
14700
  }
14684
- const linkedModule = path14.join(work, "app.wasm");
14685
- const sdkSpans = swiftSdkProjectionSpans(
14686
- sdk,
14687
- (object2, product) => sdkObjectImages.get(object2) ?? sdkProductImages.get(product)
14701
+ };
14702
+ let storage = reserved;
14703
+ if (sdkSpans.length > 0) {
14704
+ const sdkCounts = guestProjectionRegionCounts(storage.images.length, sdkSpans);
14705
+ storage = reserveGuestProjectionStorage(
14706
+ storage.images,
14707
+ storage.capacities.map((capacity, index) => ({
14708
+ ...capacity,
14709
+ regions: capacity.regions + sdkCounts[index] + 16
14710
+ }))
14688
14711
  );
14689
- const compileAppProjection = (source) => {
14690
- const projectionSource = path14.join(work, "projection.c");
14691
- const nextObject = path14.join(work, "projection.o");
14692
- writeFileSync5(projectionSource, source);
14693
- execFileSync8(
14694
- path14.join(options.toolchainBin, "clang"),
14695
- [...clangOptions, "-c", projectionSource, "-o", nextObject],
14696
- { stdio: "pipe" }
14697
- );
14698
- if (nextObject !== appProjectionObject) {
14699
- owners.delete(appProjectionObject);
14700
- appProjectionObject = nextObject;
14701
- owners.set(appProjectionObject, 0);
14712
+ compileAppProjection(storage.source);
14713
+ }
14714
+ let precomputedSymbols;
14715
+ if (splitInputs.appReferencedSymbols && splitInputs.appDefinedSymbols) {
14716
+ const referenced = new Set(splitInputs.appReferencedSymbols);
14717
+ const defined = new Set(splitInputs.appDefinedSymbols);
14718
+ const projSyms = guestWasmSymbols(readFileSync10(appProjectionObject));
14719
+ for (const name of projSyms.undefined) referenced.add(name);
14720
+ for (const name of projSyms.defined) defined.add(name);
14721
+ precomputedSymbols = { referenced, defined };
14722
+ }
14723
+ for (; ; ) {
14724
+ const link = await linkSwiftAppModule({
14725
+ objects: [...owners.keys()],
14726
+ lazyFunctions: splitInputs.lazyFunctions,
14727
+ toolchainBin: options.toolchainBin,
14728
+ sdk,
14729
+ work,
14730
+ output: options.optimized,
14731
+ optimize: options.optimize,
14732
+ layoutMap,
14733
+ project,
14734
+ precomputedSymbols,
14735
+ loweringCache: project ? void 0 : {
14736
+ file: path14.join(
14737
+ options.buildDirectory,
14738
+ ".build",
14739
+ "peach-app-module-lowered.wasm"
14740
+ ),
14741
+ compilerDigest: options.compilerDigest
14702
14742
  }
14703
- };
14704
- let storage = reserved;
14705
- if (sdkSpans.length > 0) {
14706
- const sdkCounts = guestProjectionRegionCounts(storage.images.length, sdkSpans);
14743
+ });
14744
+ const map = readFileSync10(
14745
+ project ? projectOutputFile(work, layoutMap, project) : layoutMap,
14746
+ "utf8"
14747
+ );
14748
+ const values = guestDyldValueRange(map);
14749
+ const bindingRows = /* @__PURE__ */ new Map();
14750
+ const data = [];
14751
+ for (let at = 0; at < link.linkage.data.length; at += 3) {
14752
+ const address = link.linkage.data[at];
14753
+ const size = link.linkage.data[at + 1];
14754
+ const value = link.linkage.data[at + 2];
14755
+ if (values && address >= values.address && address < values.address + values.length) {
14756
+ if (size !== 8 || (address - values.address) % 8)
14757
+ throw new Error("sdk binding splits a dyld value");
14758
+ bindingRows.set((address - values.address) / 8, value);
14759
+ } else data.push(address, size, value);
14760
+ }
14761
+ const linked = readFileSync10(
14762
+ project ? projectOutputFile(work, linkedModule, project) : linkedModule
14763
+ );
14764
+ const required = guestProjectionRegionCounts(storage.images.length, [
14765
+ ...guestLinkedSpans(map, linked, linked, owners, splitInputs.appSections, true),
14766
+ ...sdkSpans
14767
+ ]);
14768
+ if (storage.capacities.some(({ regions }, index) => required[index] > regions)) {
14707
14769
  storage = reserveGuestProjectionStorage(
14708
14770
  storage.images,
14709
- storage.capacities.map((capacity, index) => ({
14710
- ...capacity,
14711
- regions: capacity.regions + sdkCounts[index] + 16
14712
- }))
14771
+ storage.capacities.map((capacity, index) => {
14772
+ const count = required[index];
14773
+ return count > capacity.regions ? { ...capacity, regions: Math.max(count, capacity.regions * 2) } : capacity;
14774
+ })
14713
14775
  );
14714
14776
  compileAppProjection(storage.source);
14777
+ continue;
14715
14778
  }
14716
- let precomputedSymbols;
14717
- if (splitInputs.appReferencedSymbols && splitInputs.appDefinedSymbols) {
14718
- const referenced = new Set(splitInputs.appReferencedSymbols);
14719
- const defined = new Set(splitInputs.appDefinedSymbols);
14720
- const projSyms = guestWasmSymbols(readFileSync10(appProjectionObject));
14721
- for (const name of projSyms.undefined) referenced.add(name);
14722
- for (const name of projSyms.defined) defined.add(name);
14723
- precomputedSymbols = { referenced, defined };
14724
- }
14725
- for (; ; ) {
14726
- const link = await linkSwiftAppModule({
14727
- objects: [...owners.keys()],
14728
- lazyFunctions: splitInputs.lazyFunctions,
14729
- toolchainBin: options.toolchainBin,
14730
- sdk,
14731
- work,
14732
- output: options.optimized,
14733
- optimize: options.optimize,
14734
- layoutMap,
14735
- project,
14736
- precomputedSymbols,
14737
- loweringCache: project ? void 0 : {
14738
- file: path14.join(
14739
- options.buildDirectory,
14740
- ".build",
14741
- "peach-app-module-lowered.wasm"
14742
- ),
14743
- compilerDigest: options.compilerDigest
14744
- }
14745
- });
14746
- const map2 = readFileSync10(
14747
- project ? projectOutputFile(work, layoutMap, project) : layoutMap,
14748
- "utf8"
14749
- );
14750
- const values = guestDyldValueRange(map2);
14751
- const bindingRows = /* @__PURE__ */ new Map();
14752
- const data = [];
14753
- for (let at = 0; at < link.linkage.data.length; at += 3) {
14754
- const address = link.linkage.data[at];
14755
- const size = link.linkage.data[at + 1];
14756
- const value = link.linkage.data[at + 2];
14757
- if (values && address >= values.address && address < values.address + values.length) {
14758
- if (size !== 8 || (address - values.address) % 8)
14759
- throw new Error("sdk binding splits a dyld value");
14760
- bindingRows.set((address - values.address) / 8, value);
14761
- } else data.push(address, size, value);
14762
- }
14763
- const linked = readFileSync10(
14764
- project ? projectOutputFile(work, linkedModule, project) : linkedModule
14765
- );
14766
- const required = guestProjectionRegionCounts(storage.images.length, [
14767
- ...guestLinkedSpans(map2, linked, linked, owners, splitInputs.appSections, true),
14768
- ...sdkSpans
14769
- ]);
14770
- if (storage.capacities.some(({ regions }, index) => required[index] > regions)) {
14771
- storage = reserveGuestProjectionStorage(
14772
- storage.images,
14773
- storage.capacities.map((capacity, index) => {
14774
- const count = required[index];
14775
- return count > capacity.regions ? { ...capacity, regions: Math.max(count, capacity.regions * 2) } : capacity;
14776
- })
14777
- );
14778
- compileAppProjection(storage.source);
14779
- continue;
14780
- }
14781
- options.onStage("lowering the app image");
14782
- const lowerPromise = link.lower();
14783
- await new Promise((resolve) => setImmediate(resolve));
14784
- let binding;
14785
- try {
14786
- if (result.finalLinkDone) await result.finalLinkDone;
14787
- const usage = readSwiftSdkUsage(result.mapPath, options.output, sdkObjectKeys);
14788
- binding = createSwiftSdkBinding({ ...link.linkage, data }, sdk, usage);
14789
- } catch (error) {
14790
- await Promise.allSettled([lowerPromise]);
14791
- throw error;
14792
- }
14793
- await lowerPromise;
14794
- const finalized = finalizeGuestProjectionStorage({
14795
- map: map2,
14796
- linked,
14797
- optimized: readFileSync10(options.optimized),
14798
- owners,
14799
- sectionOwners: splitInputs.appSections,
14800
- projectionObject: appProjectionObject,
14801
- reserved: storage,
14802
- sdkSpans
14803
- });
14804
- writeFileSync5(
14805
- options.optimized,
14806
- moveGuestDyldTable(map2, finalized.wasm, splitInputs.dyldSymbols, bindingRows, [
14807
- swiftAppModuleThunkSection(finalized.wasm)
14808
- ])
14809
- );
14810
- return binding;
14779
+ options.onStage("lowering the app image");
14780
+ const lowerPromise = link.lower();
14781
+ await new Promise((resolve) => setImmediate(resolve));
14782
+ let binding;
14783
+ try {
14784
+ if (result.finalLinkDone) await result.finalLinkDone;
14785
+ const usage = readSwiftSdkUsage(result.mapPath, options.output, sdkObjectKeys);
14786
+ binding = createSwiftSdkBinding({ ...link.linkage, data }, sdk, usage);
14787
+ } catch (error) {
14788
+ await Promise.allSettled([lowerPromise]);
14789
+ throw error;
14811
14790
  }
14812
- } finally {
14813
- if (result.finalLinkDone) await Promise.allSettled([result.finalLinkDone]);
14791
+ await lowerPromise;
14792
+ const finalized = finalizeGuestProjectionStorage({
14793
+ map,
14794
+ linked,
14795
+ optimized: readFileSync10(options.optimized),
14796
+ owners,
14797
+ sectionOwners: splitInputs.appSections,
14798
+ projectionObject: appProjectionObject,
14799
+ reserved: storage,
14800
+ sdkSpans
14801
+ });
14802
+ writeFileSync5(
14803
+ options.optimized,
14804
+ moveGuestDyldTable(map, finalized.wasm, splitInputs.dyldSymbols, bindingRows, [
14805
+ swiftAppModuleThunkSection(finalized.wasm)
14806
+ ])
14807
+ );
14808
+ return binding;
14814
14809
  }
14810
+ } finally {
14811
+ if (result.finalLinkDone) await Promise.allSettled([result.finalLinkDone]);
14815
14812
  }
14816
- options.onStage("lowering the app image");
14817
- await lowerWasm(options.output, options.optimized, {
14818
- optimize: options.optimize,
14819
- skipPasses: ["duplicate-function-elimination"],
14820
- wideExports: lazyFunctions
14821
- });
14822
- if (lazyFunctions.length)
14823
- writeFileSync5(
14824
- options.optimized,
14825
- placeGuestLazyFunctions(readFileSync10(options.optimized), lazyFunctions)
14826
- );
14827
- const map = readFileSync10(result.mapPath, "utf8");
14828
- let optimized = readFileSync10(options.optimized);
14829
- if (/ __peach_guest_images$/m.test(map))
14830
- optimized = finalizeGuestProjectionStorage({
14831
- map,
14832
- linked: readFileSync10(options.output),
14833
- optimized,
14834
- owners: result.owners,
14835
- sectionOwners: result.generatedSectionOwners,
14836
- projectionObject,
14837
- reserved
14838
- }).wasm;
14839
- writeFileSync5(options.optimized, moveGuestDyldTable(map, optimized, dyldSymbols));
14840
14813
  }
14841
14814
 
14842
14815
  // src/swift-header-compiler.ts
@@ -16615,7 +16588,7 @@ var darwinRecordsRegion = (quoted2) => quoted2.length ? ["-Wl,--start-lib", ...q
16615
16588
  var REACTOR_FLAG = '"-Xclang-linker", "-mexec-model=reactor",\n';
16616
16589
  var MULTI_MANIFEST_VERSION = 76;
16617
16590
  var SWIFT_HEADER_PRODUCTS_TARGET = "PeachHeaderProducts";
16618
- var compilerSourceDigest = true ? "229f789297c5cb8e33a042e23ad3c1df20450a712a02dd0b50d2e78bc8ed3de6" : swiftCompilerSourceDigest(import.meta.dirname);
16591
+ var compilerSourceDigest = true ? "dcd0189f8bf1a7fc415f2c92825f8b3bbc2089ae9697ffcb50cc9a7e65e99990" : swiftCompilerSourceDigest(import.meta.dirname);
16619
16592
  function swiftArtifactHash(input, release, moduleRoot) {
16620
16593
  return swiftCompileInputHash(input, release).update(swiftModuleDigest(moduleRoot)).digest("hex");
16621
16594
  }
@@ -19982,20 +19955,17 @@ function readCompiledArtifact(directory, hash) {
19982
19955
  const gzip2 = readFileSync13(path23.join(directory, "icu.gz"));
19983
19956
  if (createHash15("sha256").update(bytes).digest("hex") !== receipt.wasm || createHash15("sha256").update(gzip2).digest("hex") !== receipt.icu || bytes.length <= 8 || bytes.readUInt32LE(0) !== 1836278016 || bytes.readUInt32LE(4) !== 1)
19984
19957
  return null;
19985
- let sdk;
19986
- if ("sdk" in receipt) {
19987
- const image = receipt.sdk;
19988
- if (!isRecord(image) || typeof image.key !== "string" || typeof image.sha256 !== "string" || typeof image.binding !== "string")
19989
- return null;
19990
- const binding = readFileSync13(path23.join(directory, "sdk-binding.bin"));
19991
- if (createHash15("sha256").update(binding).digest("hex") !== image.binding)
19992
- return null;
19993
- sdk = {
19994
- key: image.key,
19995
- sha256: image.sha256,
19996
- binding: { bytes: binding, sha256: image.binding }
19997
- };
19998
- }
19958
+ if (!("sdk" in receipt)) return null;
19959
+ const image = receipt.sdk;
19960
+ if (!isRecord(image) || typeof image.key !== "string" || typeof image.sha256 !== "string" || typeof image.binding !== "string")
19961
+ return null;
19962
+ const binding = readFileSync13(path23.join(directory, "sdk-binding.bin"));
19963
+ if (createHash15("sha256").update(binding).digest("hex") !== image.binding) return null;
19964
+ const sdk = {
19965
+ key: image.key,
19966
+ sha256: image.sha256,
19967
+ binding: { bytes: binding, sha256: image.binding }
19968
+ };
19999
19969
  return { hash, bytes, icu: { sha256: receipt.icu, gzip: gzip2 }, sdk };
20000
19970
  } catch (error) {
20001
19971
  if (error instanceof SyntaxError || error instanceof Error && "code" in error && error.code === "ENOENT")
@@ -20939,7 +20909,7 @@ async function compileSwiftProjectOnce(sources, options) {
20939
20909
  const distribution = swiftDistributionAt(moduleRoot);
20940
20910
  const mirrorDistribution = options.linkOnly || options.project ? null : distribution;
20941
20911
  if (distribution) refreshSwiftCacheHold(moduleRoot);
20942
- const input = distribution && !options.intermediates ? (await import("./swift-package-prebuilt-EH5JIX6L.mjs")).useSwiftPackagePrebuilts(
20912
+ const input = distribution && !options.intermediates ? (await import("./swift-package-prebuilt-TFU7Q54I.mjs")).useSwiftPackagePrebuilts(
20943
20913
  sources,
20944
20914
  moduleRoot,
20945
20915
  options.toolchainBin
@@ -20952,13 +20922,12 @@ async function compileSwiftProjectOnce(sources, options) {
20952
20922
  sources: path23.join(root, "Sources", "App"),
20953
20923
  multi: compileTargets(input).length > 0
20954
20924
  };
20955
- const sdkModule = options.sdkModule && !options.linkOnly;
20956
- const sdkImage = sdkModule ? await (await import("./swift-sdk-image-3NCWCGQZ.mjs")).buildSwiftSdkImage(
20925
+ const sdkImage = options.linkOnly ? void 0 : await (await import("./swift-sdk-image-HZG64EBF.mjs")).buildSwiftSdkImage(
20957
20926
  moduleRoot,
20958
20927
  !!guestGraph,
20959
20928
  distribution ? [] : linkedFrameworkTargets(moduleRoot, input).imports,
20960
20929
  { signal: options.signal }
20961
- ) : void 0;
20930
+ );
20962
20931
  const inputHash = swiftCompileInputHash(input, options.release);
20963
20932
  const moduleDigest = swiftModuleDigest(moduleRoot);
20964
20933
  const sourceHash = inputHash.copy().update(moduleDigest).digest("hex");
@@ -20989,79 +20958,10 @@ sdk module ${sdkImage.key}`).digest("hex") : sourceHash;
20989
20958
  return retain(root, previous);
20990
20959
  }
20991
20960
  }
20992
- if (!options.intermediates && !sdkImage && process.platform === "darwin" && process.env.TM_SESSION && !windowAdmission() && process.env.CI !== "true" && moduleRoot === sourceSwiftCheckout() && !swiftDistributionAt(moduleRoot)) {
20993
- const requestRoot = mkdtempSync4(`${root}.builder-request-`);
20994
- const output = path23.join(requestRoot, "output");
20995
- const request = path23.join(requestRoot, "request.json");
20996
- writeFileSync7(
20997
- request,
20998
- JSON.stringify({
20999
- input,
21000
- hash,
21001
- release: options.release,
21002
- timeoutMs: options.timeoutMs,
21003
- // framework sources and compiler inputs own the shared object tree;
21004
- // unrelated app edits reuse it without retaining stale private ABI.
21005
- buildKey: frameworkKey
21006
- })
21007
- );
21008
- try {
21009
- const repo = path23.resolve(moduleRoot, "../..");
21010
- const timeout = swiftBuilderHopTimeoutMs(options.timeoutMs);
21011
- report("requesting builder admission or cached result");
21012
- await runCompiler(
21013
- "bun",
21014
- [
21015
- path23.join(repo, "scripts/build/swift-project.ts"),
21016
- "--request",
21017
- request,
21018
- "--output",
21019
- output
21020
- ],
21021
- {
21022
- cwd: repo,
21023
- timeout,
21024
- maxBuffer: 64 * 1024 * 1024,
21025
- signal: options.signal
21026
- },
21027
- true
21028
- ).catch((error) => {
21029
- if (options.signal?.aborted) throw error;
21030
- const output2 = outputOf(error);
21031
- if (!(error instanceof Error) || Reflect.get(error, "exitCode") !== 124)
21032
- throw new Error(output2, { cause: error });
21033
- const prefix = `[swift-project ${hash.slice(0, 16)}] `;
21034
- const lines = output2.split("\n");
21035
- const stage = lines.findLast((line) => line.startsWith(prefix))?.slice(prefix.length);
21036
- const cap = lines.find(
21037
- (line) => line.startsWith("[remote] outer deadline leaves ")
21038
- );
21039
- const deadline = cap ? `
21040
- ${cap}` : "";
21041
- throw new Error(
21042
- `Swift builder deadline expired during ${stage ?? "builder preparation"} (requested ${Math.ceil(timeout / 1e3)}s for the builder hop).${deadline}`,
21043
- { cause: error }
21044
- );
21045
- });
21046
- const artifact = readCompiledArtifact(output, hash);
21047
- if (!artifact) {
21048
- throw new Error(
21049
- "swift-compile: builder artifact source, digest or wasm header is invalid"
21050
- );
21051
- }
21052
- saveCompiledArtifact(root, artifact);
21053
- saveSharedArtifact(sharedRoot, artifact);
21054
- report("builder artifact verified");
21055
- return retain(root, artifact);
21056
- } finally {
21057
- rmSync7(requestRoot, { recursive: true, force: true });
21058
- }
21059
- }
21060
20961
  const baseRoot = root;
21061
20962
  const canPoolBuildRoot = !options.intermediates && !options.project && !options.linkOnly && path23.basename(path23.dirname(baseRoot)) === "swift-builds";
21062
20963
  const compatShapeParts = canPoolBuildRoot ? [
21063
20964
  frameworkKey,
21064
- Boolean(sdkImage),
21065
20965
  compileTargets(input).map((target) => target.name).sort(),
21066
20966
  input.oneModule === true,
21067
20967
  input.optimize === true,
@@ -21699,7 +21599,8 @@ ${compatShape}` : "";
21699
21599
  }
21700
21600
  const output = options.project ? projectOutputFile(root2, linked, options.project) : linked;
21701
21601
  const optimized = `${output}.optimized`;
21702
- if (sdkImage && options.project) rmSync7(optimized, { force: true });
21602
+ if (!sdkImage) throw new Error("swift-compile: missing shared SDK image");
21603
+ if (options.project) rmSync7(optimized, { force: true });
21703
21604
  let sdkAsset;
21704
21605
  stage("linking the app image");
21705
21606
  if (guestGraph) {
@@ -21728,10 +21629,9 @@ ${compatShape}` : "";
21728
21629
  jobs: swiftBuildJobs(),
21729
21630
  onStage: stage
21730
21631
  });
21731
- if (sdkImage && binding)
21732
- sdkAsset = { key: sdkImage.key, sha256: sdkImage.sha256, binding };
21733
- } else if (sdkImage) {
21734
- const { buildSwiftAppModule } = await import("./swift-sdk-app-module-VHAOCBXW.mjs");
21632
+ sdkAsset = { key: sdkImage.key, sha256: sdkImage.sha256, binding };
21633
+ } else {
21634
+ const { buildSwiftAppModule } = await import("./swift-sdk-app-module-PT7D7AOM.mjs");
21735
21635
  const binding = await buildSwiftAppModule({
21736
21636
  buildRoot: root2,
21737
21637
  toolchainBin: options.toolchainBin,
@@ -21748,19 +21648,7 @@ ${compatShape}` : "";
21748
21648
  }
21749
21649
  });
21750
21650
  sdkAsset = { key: sdkImage.key, sha256: sdkImage.sha256, binding };
21751
- } else {
21752
- const bytes = readFileSync13(output);
21753
- const ordered = orderObjCConstructors(bytes);
21754
- if (ordered !== bytes) writeFileSync7(output, ordered);
21755
- stage("lowering the app image");
21756
- await lowerWasm(output, optimized, { optimize: input.optimize === true });
21757
21651
  }
21758
- if (!sdkImage)
21759
- await runCompiler(
21760
- path23.join(options.toolchainBin, "llvm-objcopy"),
21761
- ["--remove-section=.swift1_autolink_entries", optimized],
21762
- buildOptions
21763
- );
21764
21652
  const artifact = {
21765
21653
  hash,
21766
21654
  bytes: readFileSync13(optimized),
@@ -21811,10 +21699,10 @@ export {
21811
21699
  NATIVE_SDK_IMPORT_MODULE,
21812
21700
  NATIVE_SDK_THUNK_SECTION,
21813
21701
  NATIVE_LAZY_SLOT_IMPORT,
21814
- placeGuestLazyFunctions,
21815
- guestLazyExports,
21816
21702
  SDK_DYLD_RESOLVER,
21817
21703
  writeWasmCustomSection,
21704
+ placeGuestLazyFunctions,
21705
+ guestLazyExports,
21818
21706
  KEEP_WASM_NAMES,
21819
21707
  WASM_LOWER_IDENTITY,
21820
21708
  lowerWasm,