peachsim 0.1.2588 → 0.1.2590

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/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 +1174 -447
  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 +1 -1
  25. package/dist-lib/dev-bundle-resolution.cjs +1 -1
  26. package/dist-lib/esm-chunks/{acorn-DG2TVZRD.mjs → acorn-65FNEARV.mjs} +3 -3
  27. package/dist-lib/esm-chunks/{chunk-LW5F24Y7.mjs → chunk-2GUB5OLB.mjs} +3 -3
  28. package/dist-lib/esm-chunks/{chunk-4PNMHEJB.mjs → chunk-462CWTWI.mjs} +1 -1
  29. package/dist-lib/esm-chunks/{chunk-ASL4MACC.mjs → chunk-4VCRUQ36.mjs} +1180 -453
  30. package/dist-lib/esm-chunks/{chunk-UFXK4UQL.mjs → chunk-5GNGHM5B.mjs} +1 -1
  31. package/dist-lib/esm-chunks/{chunk-BAU3IFLL.mjs → chunk-ADKUIQXX.mjs} +1 -1
  32. package/dist-lib/esm-chunks/{chunk-4GOTTBDL.mjs → chunk-BZS5SIYK.mjs} +1 -1
  33. package/dist-lib/esm-chunks/{chunk-JE7EWYAV.mjs → chunk-EFKDUMB5.mjs} +1 -1
  34. package/dist-lib/esm-chunks/{chunk-WZHOX3BM.mjs → chunk-GBD26EBV.mjs} +1 -1
  35. package/dist-lib/esm-chunks/{chunk-QRKZ3NSY.mjs → chunk-HZTK7TP5.mjs} +1 -1
  36. package/dist-lib/esm-chunks/{chunk-ELSAXANF.mjs → chunk-JG4AANWA.mjs} +1 -1
  37. package/dist-lib/esm-chunks/{chunk-V2PI4V6K.mjs → chunk-N2II5SRJ.mjs} +4 -4
  38. package/dist-lib/esm-chunks/{chunk-C7MHFZIA.mjs → chunk-NZY4GOG5.mjs} +1 -1
  39. package/dist-lib/esm-chunks/{chunk-AGQHPM6E.mjs → chunk-OZJ66CXY.mjs} +2 -2
  40. package/dist-lib/esm-chunks/{chunk-PL3OUSN3.mjs → chunk-RGC2JNCL.mjs} +1 -1
  41. package/dist-lib/esm-chunks/{chunk-GIS6FXRN.mjs → chunk-SLPXTLBK.mjs} +5 -5
  42. package/dist-lib/esm-chunks/{chunk-BSPFA6V2.mjs → chunk-SRFKOU76.mjs} +1 -1
  43. package/dist-lib/esm-chunks/{chunk-BGCADZA2.mjs → chunk-V5TTEXYO.mjs} +1 -1
  44. package/dist-lib/esm-chunks/{chunk-NSNT4FFS.mjs → chunk-WPDY5IAD.mjs} +1 -1
  45. package/dist-lib/esm-chunks/{chunk-YHJXN2S6.mjs → chunk-WYDRQRJL.mjs} +5 -5
  46. package/dist-lib/esm-chunks/{chunk-CJ6UJWGD.mjs → chunk-X2EKFONU.mjs} +1 -1
  47. package/dist-lib/esm-chunks/{chunk-OLEYCMVV.mjs → chunk-XE3VHAU2.mjs} +1 -1
  48. package/dist-lib/esm-chunks/{chunk-SDGYG4FM.mjs → chunk-YPPH6F77.mjs} +1 -1
  49. package/dist-lib/esm-chunks/{metro-layout-parser-VWCTMFOO.mjs → metro-layout-parser-CRI3GMCM.mjs} +3 -3
  50. package/dist-lib/esm-chunks/{swift-package-prebuilt-W7FEW6PS.mjs → swift-package-prebuilt-5XDZ2HZZ.mjs} +10 -10
  51. package/dist-lib/esm-chunks/{swift-sdk-app-module-J4KH7G35.mjs → swift-sdk-app-module-6H3G6AXD.mjs} +14 -14
  52. package/dist-lib/esm-chunks/{swift-sdk-image-MUWMBAKB.mjs → swift-sdk-image-WAC7GG2R.mjs} +14 -14
  53. package/dist-lib/esm-chunks/{swift-sdk-image-producer-BLO2DZ2C.mjs → swift-sdk-image-producer-B3L27QTG.mjs} +4 -4
  54. package/dist-lib/expo-swift-bundle.cjs +1173 -446
  55. package/dist-lib/expo-swift-metadata.cjs +1 -1
  56. package/dist-lib/expo-swift-metadata.mjs +7 -7
  57. package/dist-lib/home-paths.cjs +1 -1
  58. package/dist-lib/host/bridge-host.cjs +1215 -480
  59. package/dist-lib/host/fetch-proxy-handler.cjs +4 -4
  60. package/dist-lib/host/fetch-proxy-overrides.cjs +1 -1
  61. package/dist-lib/host/fetch-proxy-overrides.mjs +2 -2
  62. package/dist-lib/host/replacement-module-handler.cjs +1 -1
  63. package/dist-lib/host/websocket-proxy.cjs +1 -1
  64. package/dist-lib/index.cjs +1 -1
  65. package/dist-lib/kotlin-host.cjs +1 -1
  66. package/dist-lib/menu.cjs +1 -1
  67. package/dist-lib/menu.mjs +3 -3
  68. package/dist-lib/metro-fingerprint-registry.cjs +1 -1
  69. package/dist-lib/metro-fingerprint-registry.mjs +3 -3
  70. package/dist-lib/metro-production-bundle.cjs +1 -1
  71. package/dist-lib/metro-production-bundle.mjs +4 -4
  72. package/dist-lib/native-app-identity-project.cjs +2 -2
  73. package/dist-lib/native-app-identity-project.mjs +16 -16
  74. package/dist-lib/native-app-identity.cjs +1 -1
  75. package/dist-lib/native-app-identity.mjs +6 -6
  76. package/dist-lib/native-firebase-metadata.cjs +1 -1
  77. package/dist-lib/native-firebase-metadata.mjs +3 -3
  78. package/dist-lib/pdfium-raster.cjs +1 -1
  79. package/dist-lib/pdfium-raster.mjs +2 -2
  80. package/dist-lib/plist.cjs +1 -1
  81. package/dist-lib/plist.mjs +3 -3
  82. package/dist-lib/profiles.cjs +1 -1
  83. package/dist-lib/public-brand.cjs +1 -1
  84. package/dist-lib/public-origins-lib-esm.json +81 -81
  85. package/dist-lib/public-origins-lib.json +69 -69
  86. package/dist-lib/react-native-host-modules.cjs +1 -1
  87. package/dist-lib/react-native-host-modules.mjs +2 -2
  88. package/dist-lib/reap-browser.cjs +1 -1
  89. package/dist-lib/scripts/dev-server-scanner.cjs +1 -1
  90. package/dist-lib/sdk.cjs +1 -1
  91. package/dist-lib/sdk.mjs +8 -8
  92. package/dist-lib/skills.cjs +1225 -484
  93. package/dist-lib/swift-compile.cjs +1170 -443
  94. package/dist-lib/swift-compile.mjs +10 -10
  95. package/dist-lib/swift-package.cjs +1 -1
  96. package/dist-lib/swift-package.mjs +3 -3
  97. package/dist-lib/swift-submit.cjs +1 -1
  98. package/dist-lib/swift-submit.mjs +6 -6
  99. package/dist-lib/swift-svg-raster.cjs +1 -1
  100. package/dist-lib/swift-svg-raster.mjs +2 -2
  101. package/dist-lib/swift-toolchain.cjs +1 -1
  102. package/dist-lib/swift.cjs +1 -1
  103. package/dist-lib/vendor/@peculiar/x509.cjs +1 -1
  104. package/dist-lib/vendor/@ruby/prism/src/nodes.js.cjs +1 -1
  105. package/dist-lib/vendor/@ruby/prism/src/parsePrism.js.cjs +1 -1
  106. package/dist-lib/vendor/@xmldom/xmldom.cjs +1 -1
  107. package/dist-lib/vendor/acorn.cjs +1 -1
  108. package/dist-lib/vendor/bplist-parser.cjs +1 -1
  109. package/dist-lib/vendor/ignore.cjs +1 -1
  110. package/dist-lib/vendor/magic-string.cjs +1 -1
  111. package/dist-lib/vendor/plist.cjs +1 -1
  112. package/dist-lib/vendor/smol-toml.cjs +1 -1
  113. package/dist-lib/vendor/stream-json.cjs +1 -1
  114. package/dist-lib/vendor/sucrase/dist/index.js.cjs +1 -1
  115. package/dist-lib/vendor/sucrase/dist/parser/index.js.cjs +1 -1
  116. package/dist-lib/vendor/sucrase/dist/parser/tokenizer/index.js.cjs +1 -1
  117. package/dist-lib/vendor/sucrase/dist/parser/tokenizer/types.js.cjs +1 -1
  118. package/dist-lib/vendor/sucrase.cjs +1 -1
  119. package/dist-lib/vendor/terser.cjs +1 -1
  120. package/dist-lib/vendor/valibot.cjs +1 -1
  121. package/dist-lib/vendor/ws.cjs +1 -1
  122. package/dist-lib/vendor/zod.cjs +1 -1
  123. package/dist-lib/worklet-executable.cjs +1 -1
  124. package/dist-lib/worklet-executable.mjs +3 -3
  125. package/dist-types/packages/peach-engine/src/ios/apps/canvas-map-data.d.ts +1 -1
  126. package/kotlin/sdk.tar.gz +0 -0
  127. package/package.json +1 -1
  128. package/src/one-native-controls-package.ts +8 -7
  129. package/src/swift-guest-compile.ts +2 -2
  130. package/src/swift-guest-dyld-table.ts +9 -2
  131. package/src/swift-guest-image-ledger.ts +403 -208
  132. package/src/swift-guest-link.ts +255 -113
  133. package/src/swift-guest-linked-spans.ts +217 -28
  134. package/src/swift-guest-manifest.ts +24 -13
  135. package/src/swift-guest-projection-storage.ts +6 -8
  136. package/src/swift-guest-projection.ts +7 -6
  137. package/src/swift-sdk-image-map.ts +137 -35
  138. package/src/swift-shared-sdk.ts +8 -4
  139. package/src/swift-wasm-prune.ts +263 -85
  140. package/src/swiftGuestImageContract.ts +1 -1
@@ -1,4 +1,4 @@
1
- /*! peach v0.1.2588 | (c) 2026 Tamagui LLC | Proprietary; see LICENSE */
1
+ /*! peach v0.1.2590 | (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;
@@ -5712,13 +5712,13 @@ var init_swift_standin_digest = __esm({
5712
5712
  STANDIN_DIGEST_ENTRYPOINTS = ["swift-standins.ts", "swift-objc-compile.ts"];
5713
5713
  SPECIFIER = /from\s*['"]([^'"]+)['"]|import\s*\(\s*['"]([^'"]+)['"]\s*\)/g;
5714
5714
  standinSourceDigest = (srcDir = __sootsim_import_meta_dirname) => sourceClosureDigest(srcDir, STANDIN_DIGEST_ENTRYPOINTS);
5715
- STANDIN_SOURCE_DIGEST = true ? "3f599241e9565977a3b4bc4cae7ce5ee8032948cc6c47ca8496c9edb45f25011" : standinSourceDigest();
5715
+ STANDIN_SOURCE_DIGEST = true ? "a3bcdfe9c9957355a59c2c26155470c89a2abb30907aeeaaf1de8463aa74fc8c" : standinSourceDigest();
5716
5716
  }
5717
5717
  });
5718
5718
 
5719
5719
  // src/expo-native-compiler-digest.ts
5720
5720
  function expoNativeCompilerDigestValue() {
5721
- return true ? "ab61e93963022a221353be8f410397787d6eb35d6fdb9441d4daca8c413670ee" : expoNativeCompilerDigest(__sootsim_import_meta_dirname);
5721
+ return true ? "a8b60651de79588c6c5143dd2545ccd8e3b858acd992f46b35ba3de883118ac5" : expoNativeCompilerDigest(__sootsim_import_meta_dirname);
5722
5722
  }
5723
5723
  var import_node_crypto11;
5724
5724
  var init_expo_native_compiler_digest = __esm({
@@ -34647,6 +34647,7 @@ function stageOverlaySlot(realRoot, stagingRoot, relPath) {
34647
34647
  const segment2 = segments[i];
34648
34648
  for (const entry of (0, import_node_fs51.readdirSync)(real)) {
34649
34649
  if (entry === segment2 || i === 0 && entry === SWIFT_CACHE_HOLD_MARKER) continue;
34650
+ if (mirror === stagingRoot && entry === "configuration") continue;
34650
34651
  const dest = import_node_path51.default.join(mirror, entry);
34651
34652
  if (!import_node_fs51.default.lstatSync(dest, { throwIfNoEntry: false })) {
34652
34653
  import_node_fs51.default.symlinkSync(import_node_path51.default.join(real, entry), dest);
@@ -34681,7 +34682,7 @@ function swiftSharedSdkViewOptions(moduleRoot, distribution, toolchainBin, sdk2)
34681
34682
  const stdint = import_node_path51.default.join(overlay, "include/stdint.h");
34682
34683
  const key2 = JSON.stringify([
34683
34684
  // bump the recipe when the transformation changes; bundling changes function text.
34684
- "v38",
34685
+ "v39",
34685
34686
  [...WEAKEN_FOUNDATION_SYMS],
34686
34687
  toolchainBin,
34687
34688
  sdk2,
@@ -36313,24 +36314,56 @@ function layout(bytes, readData = true, requireExports = true) {
36313
36314
  const code = sections.get(10);
36314
36315
  if (code) {
36315
36316
  let pos = code[0];
36316
- let count;
36317
- [count, pos] = number(bytes, pos);
36317
+ const codeStart = code[0];
36318
+ const codeEnd = code[1];
36319
+ let count = 0;
36320
+ {
36321
+ let shift = 0;
36322
+ for (; ; ) {
36323
+ if (pos >= codeEnd || shift > 28) throw new Error("invalid wasm integer");
36324
+ const byte = bytes[pos++];
36325
+ count += (byte & 127) * 2 ** shift;
36326
+ if (!(byte & 128)) break;
36327
+ shift += 7;
36328
+ }
36329
+ }
36318
36330
  for (let i = 0; i < count; i++) {
36319
36331
  const prefix = pos;
36320
- let size2;
36321
- [size2, pos] = number(bytes, pos);
36322
- functionsByCodeOffset.set(prefix - code[0], imports2 + i);
36332
+ let size2 = 0;
36333
+ const b0 = bytes[pos++];
36334
+ if (b0 < 128) {
36335
+ size2 = b0;
36336
+ } else {
36337
+ size2 = b0 & 127;
36338
+ let shift = 7;
36339
+ for (; ; ) {
36340
+ if (pos >= codeEnd || shift > 28) throw new Error("invalid wasm integer");
36341
+ const byte = bytes[pos++];
36342
+ size2 += (byte & 127) * 2 ** shift;
36343
+ if (!(byte & 128)) break;
36344
+ shift += 7;
36345
+ }
36346
+ }
36347
+ functionsByCodeOffset.set(prefix - codeStart, imports2 + i);
36323
36348
  if (imports2 + i === startFunction) startup = bytes.subarray(pos, pos + size2);
36324
36349
  pos += size2;
36325
- if (pos > code[1]) throw new Error("invalid wasm code");
36350
+ if (pos > codeEnd) throw new Error("invalid wasm code");
36326
36351
  }
36327
- if (pos !== code[1]) throw new Error("invalid wasm code section");
36352
+ if (pos !== codeEnd) throw new Error("invalid wasm code section");
36328
36353
  }
36329
36354
  const functionsByTableSlot = /* @__PURE__ */ new Map();
36330
36355
  const elements = sections.get(9);
36331
36356
  if (elements) {
36332
36357
  let pos = elements[0];
36358
+ const elemEnd = elements[1];
36333
36359
  const read = () => {
36360
+ if (pos < elemEnd) {
36361
+ const b0 = bytes[pos];
36362
+ if (b0 < 128) {
36363
+ pos++;
36364
+ return b0;
36365
+ }
36366
+ }
36334
36367
  const [value, next] = number(bytes, pos);
36335
36368
  pos = next;
36336
36369
  return value;
@@ -36360,7 +36393,7 @@ function layout(bytes, readData = true, requireExports = true) {
36360
36393
  functionsByTableSlot.set(slot, read());
36361
36394
  }
36362
36395
  }
36363
- if (pos !== elements[1]) throw new Error("invalid wasm element section");
36396
+ if (pos !== elemEnd) throw new Error("invalid wasm element section");
36364
36397
  }
36365
36398
  const data = [];
36366
36399
  const passive = /* @__PURE__ */ new Map();
@@ -36425,36 +36458,141 @@ function guestWasmDataSegments(bytes, requireExports = true) {
36425
36458
  length: segment2.bytes.length
36426
36459
  }));
36427
36460
  }
36428
- function guestLinkedSpans(map2, before, after, owners, sectionOwners = /* @__PURE__ */ new Map(), importsLayout = false) {
36461
+ function isMapSpace(code) {
36462
+ return code === 32 || code >= 9 && code <= 13;
36463
+ }
36464
+ function isMapHex(code) {
36465
+ return code >= 48 && code <= 57 || code >= 97 && code <= 102;
36466
+ }
36467
+ function mapHexDigit(code) {
36468
+ return code <= 57 ? code - 48 : code - 87;
36469
+ }
36470
+ function* stringLines(text7) {
36471
+ let start = 0;
36472
+ for (let end = text7.indexOf("\n"); end !== -1; end = text7.indexOf("\n", start)) {
36473
+ yield text7.slice(start, end);
36474
+ start = end + 1;
36475
+ }
36476
+ yield text7.slice(start);
36477
+ }
36478
+ function guestLinkedSpans(map2, before, after, owners, sectionOwners = /* @__PURE__ */ new Map(), importsLayout = false, extra) {
36429
36479
  const unchanged = before === after;
36430
36480
  const original = layout(before, !unchanged, !importsLayout);
36431
36481
  const optimized = unchanged ? original : layout(after, true, !importsLayout);
36482
+ const collectSymbols = extra?.collectSymbols;
36483
+ const trackedObject = extra?.trackedObject;
36484
+ const trackedObjectOwner = extra?.trackedObjectOwner;
36485
+ const trackedLinearSpans = extra?.trackedLinearSpans;
36486
+ const hasSectionOwners = sectionOwners.size > 0;
36432
36487
  let codeOffset;
36433
36488
  let outputSection = "";
36434
36489
  const codeOwners = /* @__PURE__ */ new Map();
36435
36490
  const pieces = [];
36436
- for (const line of typeof map2 === "string" ? map2.split("\n") : map2) {
36437
- const match = /^\s*(\S+)\s+([\da-f]+)\s+([\da-f]+)( +)(\S.*)$/.exec(line);
36438
- if (!match) continue;
36439
- const [, address, offset, size2, indent2, source] = match;
36440
- if (address === "-" && indent2 === " ") {
36441
- outputSection = source;
36442
- if (source === "CODE") codeOffset = parseInt(offset, 16);
36491
+ const lines = typeof map2 === "string" ? stringLines(map2) : map2;
36492
+ for (const line of lines) {
36493
+ const lineLen = line.length;
36494
+ let pos = 0;
36495
+ let onlySpaces = true;
36496
+ while (pos < lineLen) {
36497
+ const ch = line.charCodeAt(pos);
36498
+ if (!isMapSpace(ch)) break;
36499
+ if (ch !== 32) onlySpaces = false;
36500
+ pos++;
36501
+ }
36502
+ const leadingSpaces = pos;
36503
+ if (pos >= lineLen) continue;
36504
+ const addrStart = pos;
36505
+ while (pos < lineLen && !isMapSpace(line.charCodeAt(pos))) pos++;
36506
+ const addrEnd = pos;
36507
+ if (pos >= lineLen) continue;
36508
+ const s1 = pos;
36509
+ while (pos < lineLen) {
36510
+ const ch = line.charCodeAt(pos);
36511
+ if (!isMapSpace(ch)) break;
36512
+ if (ch !== 32) onlySpaces = false;
36513
+ pos++;
36514
+ }
36515
+ if (pos === s1 || pos >= lineLen) continue;
36516
+ const offStart = pos;
36517
+ let offsetVal = 0;
36518
+ while (pos < lineLen && isMapHex(line.charCodeAt(pos))) {
36519
+ offsetVal = offsetVal * 16 + mapHexDigit(line.charCodeAt(pos++));
36520
+ }
36521
+ if (pos === offStart || pos >= lineLen) continue;
36522
+ const s2 = pos;
36523
+ while (pos < lineLen) {
36524
+ const ch = line.charCodeAt(pos);
36525
+ if (!isMapSpace(ch)) break;
36526
+ if (ch !== 32) onlySpaces = false;
36527
+ pos++;
36528
+ }
36529
+ if (pos === s2 || pos >= lineLen) continue;
36530
+ const sizeStart = pos;
36531
+ let sizeVal = 0;
36532
+ while (pos < lineLen && isMapHex(line.charCodeAt(pos))) {
36533
+ sizeVal = sizeVal * 16 + mapHexDigit(line.charCodeAt(pos++));
36534
+ }
36535
+ if (pos === sizeStart || pos >= lineLen) continue;
36536
+ const indentStart = pos;
36537
+ while (pos < lineLen && line.charCodeAt(pos) === 32) pos++;
36538
+ const indentLen = pos - indentStart;
36539
+ if (indentLen === 0 || pos >= lineLen) continue;
36540
+ const firstCh = line.charCodeAt(pos);
36541
+ if (isMapSpace(firstCh)) continue;
36542
+ const sourceStart = pos;
36543
+ if (collectSymbols && onlySpaces && leadingSpaces > 0 && indentLen >= 9 && firstCh !== 47 && firstCh !== 60) {
36544
+ let symEnd = sourceStart + 1;
36545
+ while (symEnd < lineLen && !isMapSpace(line.charCodeAt(symEnd))) symEnd++;
36546
+ collectSymbols.add(line.slice(sourceStart, symEnd));
36547
+ }
36548
+ const isDash = addrEnd - addrStart === 1 && line.charCodeAt(addrStart) === 45;
36549
+ if (isDash && indentLen === 1) {
36550
+ if (line.indexOf("\r", sourceStart) >= 0) continue;
36551
+ outputSection = line.slice(sourceStart);
36552
+ if (outputSection === "CODE") codeOffset = offsetVal;
36443
36553
  continue;
36444
36554
  }
36445
- const separator = source.indexOf(":(");
36555
+ if (sizeVal === 0) continue;
36556
+ const separator = line.indexOf(":(", sourceStart);
36446
36557
  if (separator < 0) continue;
36447
- const image = sectionOwners.get(source) ?? owners.get(source.slice(0, separator));
36448
- const length = parseInt(size2, 16);
36449
- if (!length) continue;
36450
- if (address !== "-") {
36451
- if (outputSection === "DATA")
36452
- pieces.push({ image, address: parseInt(address, 16), length });
36558
+ if (line.indexOf("\r", sourceStart) >= 0) continue;
36559
+ let hasLineSep = false;
36560
+ for (let i = sourceStart; i < lineLen; i++) {
36561
+ const ch = line.charCodeAt(i);
36562
+ if (ch === 8232 || ch === 8233) {
36563
+ hasLineSep = true;
36564
+ break;
36565
+ }
36566
+ }
36567
+ if (hasLineSep) continue;
36568
+ const objectPath = line.slice(sourceStart, separator);
36569
+ let image = hasSectionOwners ? sectionOwners.get(line.slice(sourceStart)) : void 0;
36570
+ if (image === void 0) image = owners.get(objectPath);
36571
+ if (!isDash) {
36572
+ if (outputSection === "DATA") {
36573
+ let addressVal = 0;
36574
+ let allHex = true;
36575
+ for (let i = addrStart; i < addrEnd; i++) {
36576
+ const ch = line.charCodeAt(i);
36577
+ if (isMapHex(ch)) addressVal = addressVal * 16 + mapHexDigit(ch);
36578
+ else {
36579
+ allHex = false;
36580
+ break;
36581
+ }
36582
+ }
36583
+ if (!allHex) addressVal = parseInt(line.slice(addrStart, addrEnd), 16);
36584
+ pieces.push({
36585
+ image,
36586
+ address: addressVal,
36587
+ length: sizeVal,
36588
+ tracked: trackedObject !== void 0 && objectPath === trackedObject
36589
+ });
36590
+ }
36453
36591
  continue;
36454
36592
  }
36455
36593
  if (image === void 0 || outputSection !== "CODE") continue;
36456
36594
  if (codeOffset === void 0) throw new Error("link map has no code section");
36457
- const index = original.functionsByCodeOffset.get(parseInt(offset, 16) - codeOffset);
36595
+ const index = original.functionsByCodeOffset.get(offsetVal - codeOffset);
36458
36596
  if (index === void 0) throw new Error("link map function has no wasm body");
36459
36597
  const existing = codeOwners.get(index);
36460
36598
  if (existing !== void 0 && existing !== image)
@@ -36463,12 +36601,23 @@ function guestLinkedSpans(map2, before, after, owners, sectionOwners = /* @__PUR
36463
36601
  }
36464
36602
  pieces.sort((a, b) => a.address - b.address);
36465
36603
  const spans = [];
36466
- for (const [index, { image, address, length }] of pieces.entries()) {
36467
- if (image === void 0) continue;
36604
+ for (let index = 0; index < pieces.length; index++) {
36605
+ const piece = pieces[index];
36606
+ const { image, address, length, tracked } = piece;
36607
+ if (image === void 0 && !tracked) continue;
36468
36608
  let next = index + 1;
36469
36609
  while (next < pieces.length && pieces[next].address < address + length) next++;
36470
36610
  const end = pieces[next]?.address ?? address + length;
36471
- spans.push({ image, space: "linear-memory", address, length: end - address });
36611
+ const spanLength = end - address;
36612
+ if (image !== void 0)
36613
+ spans.push({ image, space: "linear-memory", address, length: spanLength });
36614
+ if (tracked && trackedLinearSpans && trackedObjectOwner !== void 0)
36615
+ trackedLinearSpans.push({
36616
+ image: trackedObjectOwner,
36617
+ space: "linear-memory",
36618
+ address,
36619
+ length: spanLength
36620
+ });
36472
36621
  }
36473
36622
  const optimizedOwners = /* @__PURE__ */ new Map();
36474
36623
  const dataAt = (module2, start, length) => {
@@ -36507,7 +36656,7 @@ function guestLinkedSpans(map2, before, after, owners, sectionOwners = /* @__PUR
36507
36656
  throw new Error(`optimization changed linked data at ${span.address}`);
36508
36657
  }
36509
36658
  let previous;
36510
- for (const span of [...spans].sort((a, b) => a.address - b.address)) {
36659
+ for (const span of spans) {
36511
36660
  if (previous && span.address < previous.address + previous.length && span.image !== previous.image)
36512
36661
  throw new Error("linked data belongs to multiple images");
36513
36662
  if (!previous || span.address + span.length > previous.address + previous.length)
@@ -36689,6 +36838,20 @@ var init_swift_guest_linked_spans = __esm({
36689
36838
  });
36690
36839
 
36691
36840
  // src/swift-sdk-image-map.ts
36841
+ function isHexChar(code) {
36842
+ return code >= 48 && code <= 57 || code >= 97 && code <= 102;
36843
+ }
36844
+ function hexDigit(code) {
36845
+ return code <= 57 ? code - 48 : code - 87;
36846
+ }
36847
+ function hasLineBreak(line, from) {
36848
+ if (line.indexOf("\r", from) >= 0) return true;
36849
+ for (let i = from; i < line.length; i++) {
36850
+ const ch = line.charCodeAt(i);
36851
+ if (ch === 8232 || ch === 8233) return true;
36852
+ }
36853
+ return false;
36854
+ }
36692
36855
  function readWasmLinkMap(file, partition) {
36693
36856
  const segments = /* @__PURE__ */ new Map();
36694
36857
  const data = [];
@@ -36696,48 +36859,117 @@ function readWasmLinkMap(file, partition) {
36696
36859
  let kind = "";
36697
36860
  let segment2 = "";
36698
36861
  let previous;
36699
- const hex = (value) => value === "-" ? -1 : parseInt(value, 16);
36700
36862
  for (const line of guestLinkLines(file)) {
36701
- const symbol2 = /^ *([0-9a-f]+|-) +[0-9a-f]+ +([0-9a-f]+) {17}(\S.*)$/.exec(line);
36702
- if (symbol2) {
36703
- previous?.symbols.push({
36704
- name: symbol2[3],
36705
- address: hex(symbol2[1]),
36706
- size: parseInt(symbol2[2], 16)
36707
- });
36863
+ const length = line.length;
36864
+ let pos = 0;
36865
+ while (pos < length && line.charCodeAt(pos) === 32) pos++;
36866
+ if (pos >= length) continue;
36867
+ const leadingSpaces = pos;
36868
+ let address = -1;
36869
+ if (line.charCodeAt(pos) === 45) {
36870
+ pos++;
36871
+ } else {
36872
+ const start = pos;
36873
+ let value = 0;
36874
+ while (pos < length && isHexChar(line.charCodeAt(pos))) {
36875
+ value = value * 16 + hexDigit(line.charCodeAt(pos++));
36876
+ }
36877
+ if (pos === start) continue;
36878
+ address = value;
36879
+ }
36880
+ const s1 = pos;
36881
+ while (pos < length && line.charCodeAt(pos) === 32) pos++;
36882
+ if (pos === s1 || pos >= length) continue;
36883
+ const offStart = pos;
36884
+ let offset = 0;
36885
+ while (pos < length && isHexChar(line.charCodeAt(pos))) {
36886
+ offset = offset * 16 + hexDigit(line.charCodeAt(pos++));
36887
+ }
36888
+ if (pos === offStart) continue;
36889
+ const s2 = pos;
36890
+ while (pos < length && line.charCodeAt(pos) === 32) pos++;
36891
+ if (pos === s2 || pos >= length) continue;
36892
+ const sizeStart = pos;
36893
+ let size2 = 0;
36894
+ while (pos < length && isHexChar(line.charCodeAt(pos))) {
36895
+ size2 = size2 * 16 + hexDigit(line.charCodeAt(pos++));
36896
+ }
36897
+ if (pos === sizeStart || pos >= length) continue;
36898
+ const indentStart = pos;
36899
+ while (pos < length && line.charCodeAt(pos) === 32) pos++;
36900
+ const indent2 = pos - indentStart;
36901
+ if (indent2 === 0 || pos >= length) continue;
36902
+ if (indent2 === 17) {
36903
+ if (previous) {
36904
+ const first = line.charCodeAt(pos);
36905
+ if (first > 32 && !hasLineBreak(line, pos)) {
36906
+ previous.symbols.push({
36907
+ name: line.slice(pos),
36908
+ address,
36909
+ size: size2
36910
+ });
36911
+ }
36912
+ }
36708
36913
  continue;
36709
36914
  }
36710
- const output = /^ +- +[0-9a-f]+ +[0-9a-f]+ (\S+)$/.exec(line);
36711
- if (output) {
36712
- kind = output[1];
36915
+ if (indent2 === 1) {
36916
+ let hasWhitespace = false;
36917
+ for (let i = pos; i < length; i++) {
36918
+ const ch = line.charCodeAt(i);
36919
+ if (ch <= 32) {
36920
+ hasWhitespace = true;
36921
+ break;
36922
+ }
36923
+ }
36924
+ if (hasWhitespace) continue;
36925
+ if (address < 0 && leadingSpaces > 0) {
36926
+ kind = line.slice(pos);
36927
+ } else if (kind === "DATA" && address >= 0) {
36928
+ segment2 = line.slice(pos);
36929
+ segments.set(segment2, { address, size: size2 });
36930
+ }
36713
36931
  continue;
36714
36932
  }
36715
- if (kind === "DATA") {
36716
- const top = /^ *([0-9a-f]+) +[0-9a-f]+ +([0-9a-f]+) (\S+)$/.exec(line);
36717
- if (top) {
36718
- segment2 = top[3];
36719
- segments.set(segment2, { address: hex(top[1]), size: parseInt(top[2], 16) });
36720
- continue;
36933
+ if (indent2 === 9 && (kind === "DATA" || kind === "CODE")) {
36934
+ const first = line.charCodeAt(pos);
36935
+ if (first !== 47 && first !== 60) continue;
36936
+ if (hasLineBreak(line, pos)) continue;
36937
+ const name3 = line.slice(pos);
36938
+ let filePath = name3;
36939
+ let section2 = "";
36940
+ if (name3.charCodeAt(name3.length - 1) === 41) {
36941
+ const splitAt = name3.indexOf(":(");
36942
+ if (splitAt >= 0) {
36943
+ filePath = name3.slice(0, splitAt);
36944
+ section2 = name3.slice(splitAt + 2, -1);
36945
+ }
36946
+ }
36947
+ let objectName;
36948
+ if (filePath.charCodeAt(filePath.length - 1) === 41) {
36949
+ const open = filePath.lastIndexOf("(");
36950
+ if (open >= 0 && open + 1 < filePath.length - 1) {
36951
+ const close = filePath.indexOf(")", open + 1);
36952
+ if (close === filePath.length - 1) {
36953
+ objectName = filePath.slice(open + 1, -1);
36954
+ }
36955
+ }
36721
36956
  }
36957
+ if (objectName === void 0) objectName = (0, import_node_path56.basename)(filePath);
36958
+ if (objectName.startsWith("lib") && objectName.includes("__")) {
36959
+ objectName = objectName.replace(/^lib\w*?__/, "");
36960
+ }
36961
+ previous = {
36962
+ inputFile: filePath,
36963
+ segment: segment2,
36964
+ address,
36965
+ offset,
36966
+ size: size2,
36967
+ object: objectName,
36968
+ section: section2,
36969
+ symbols: []
36970
+ };
36971
+ (kind === "DATA" ? data : code).push(previous);
36722
36972
  }
36723
- if (kind !== "DATA" && kind !== "CODE") continue;
36724
- const input = /^ *([0-9a-f]+|-) +([0-9a-f]+) +([0-9a-f]+) {9}([/<].*)$/.exec(line);
36725
- if (!input) continue;
36726
- const name3 = input[4];
36727
- const split = /^(.*?):\((.*)\)$/s.exec(name3);
36728
- const path161 = split ? split[1] : name3;
36729
- const member = /\(([^()]+)\)$/.exec(path161);
36730
- previous = {
36731
- inputFile: path161,
36732
- segment: segment2,
36733
- address: hex(input[1]),
36734
- offset: parseInt(input[2], 16),
36735
- size: parseInt(input[3], 16),
36736
- object: (member ? member[1] : (0, import_node_path56.basename)(path161)).replace(/^lib\w*?__/, ""),
36737
- section: split ? split[2] : "",
36738
- symbols: []
36739
- };
36740
- (kind === "DATA" ? data : code).push(previous);
36741
36973
  }
36742
36974
  return { segments, data: partition ? data.flatMap(symbolPieces) : data, code };
36743
36975
  }
@@ -37883,6 +38115,7 @@ function patchSwiftrtObject(src) {
37883
38115
  return buf;
37884
38116
  }
37885
38117
  function parseWasmObjectBytes(file, buf, isDist, symbolFlagOffsets) {
38118
+ const rawBuf = Buffer.isBuffer(buf) ? buf : Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength);
37886
38119
  let pos = 8;
37887
38120
  let numImportFuncs = 0;
37888
38121
  let importsDlsym = false;
@@ -37918,10 +38151,10 @@ function parseWasmObjectBytes(file, buf, isDist, symbolFlagOffsets) {
37918
38151
  let [cnt, cp] = readULEB2(buf, p);
37919
38152
  for (let i = 0; i < cnt; i++) {
37920
38153
  const [mLen, m2] = readULEB2(buf, cp);
37921
- const mName = Buffer.from(buf.subarray(m2, m2 + mLen)).toString("utf8");
38154
+ const mName = rawBuf.toString("utf8", m2, m2 + mLen);
37922
38155
  cp = m2 + mLen;
37923
38156
  const [fLen, f2] = readULEB2(buf, cp);
37924
- const fName = Buffer.from(buf.subarray(f2, f2 + fLen)).toString("utf8");
38157
+ const fName = rawBuf.toString("utf8", f2, f2 + fLen);
37925
38158
  cp = f2 + fLen;
37926
38159
  const kind = buf[cp++];
37927
38160
  if (kind === 0) {
@@ -38001,7 +38234,7 @@ function parseWasmObjectBytes(file, buf, isDist, symbolFlagOffsets) {
38001
38234
  }
38002
38235
  } else if (id === 0) {
38003
38236
  const [nLen, np] = readULEB2(buf, p);
38004
- const name3 = Buffer.from(buf.subarray(np, np + nLen)).toString("utf8");
38237
+ const name3 = rawBuf.toString("utf8", np, np + nLen);
38005
38238
  const cp = np + nLen;
38006
38239
  if (name3 === "linking") {
38007
38240
  let [, lp] = readULEB2(buf, cp);
@@ -38014,7 +38247,7 @@ function parseWasmObjectBytes(file, buf, isDist, symbolFlagOffsets) {
38014
38247
  let cur = p2;
38015
38248
  for (let i = 0; i < cnt; i++) {
38016
38249
  const [sLen, s2] = readULEB2(buf, cur);
38017
- segNames.push(Buffer.from(buf.subarray(s2, s2 + sLen)).toString("utf8"));
38250
+ segNames.push(rawBuf.toString("utf8", s2, s2 + sLen));
38018
38251
  cur = s2 + sLen;
38019
38252
  const [, s3] = readULEB2(buf, cur);
38020
38253
  const [fl, s4] = readULEB2(buf, s3);
@@ -38054,7 +38287,7 @@ function parseWasmObjectBytes(file, buf, isDist, symbolFlagOffsets) {
38054
38287
  let sName = "";
38055
38288
  if (!isUndef || isExplicitName) {
38056
38289
  const [sLen, c4] = readULEB2(buf, cur);
38057
- sName = Buffer.from(buf.subarray(c4, c4 + sLen)).toString("utf8");
38290
+ sName = rawBuf.toString("utf8", c4, c4 + sLen);
38058
38291
  cur = c4 + sLen;
38059
38292
  } else if (kind === 0) {
38060
38293
  sName = importFuncNames[el] ?? "";
@@ -38070,7 +38303,7 @@ function parseWasmObjectBytes(file, buf, isDist, symbolFlagOffsets) {
38070
38303
  symNames.push(sName);
38071
38304
  } else if (kind === 1) {
38072
38305
  const [sLen, c3] = readULEB2(buf, cur);
38073
- const sName = Buffer.from(buf.subarray(c3, c3 + sLen)).toString("utf8");
38306
+ const sName = rawBuf.toString("utf8", c3, c3 + sLen);
38074
38307
  cur = c3 + sLen;
38075
38308
  if (!isUndef) {
38076
38309
  const [segIdx, c4] = readULEB2(buf, cur);
@@ -38185,9 +38418,21 @@ function parseWasmObjectBytes(file, buf, isDist, symbolFlagOffsets) {
38185
38418
  const offInSeg = ro - (sPayloadStarts[lo] ?? 0);
38186
38419
  let ownerSymIdx = -1;
38187
38420
  const topList = segTopSyms.get(lo);
38188
- if (topList) {
38189
- const owner = topList.find((t) => offInSeg >= t.off && offInSeg < t.end);
38190
- if (owner) ownerSymIdx = owner.symIdx;
38421
+ if (topList && topList.length > 0) {
38422
+ let tLo = 0;
38423
+ let tHi = topList.length - 1;
38424
+ while (tLo <= tHi) {
38425
+ const tMid = tLo + tHi >> 1;
38426
+ const top = topList[tMid];
38427
+ if (offInSeg < top.off) {
38428
+ tHi = tMid - 1;
38429
+ } else if (offInSeg >= top.end) {
38430
+ tLo = tMid + 1;
38431
+ } else {
38432
+ ownerSymIdx = top.symIdx;
38433
+ break;
38434
+ }
38435
+ }
38191
38436
  }
38192
38437
  if (ownerSymIdx !== -1) {
38193
38438
  let list2 = symDataRelocs.get(ownerSymIdx);
@@ -38442,54 +38687,151 @@ function localizeDefinedWasmSymbols(bytes, names) {
38442
38687
  return output;
38443
38688
  }
38444
38689
  function guestWasmSymbols(bytes) {
38445
- const object8 = parseWasmObjectBytes("", bytes, false);
38690
+ const rawBuf = Buffer.isBuffer(bytes) ? bytes : Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength);
38691
+ let cur = 8;
38692
+ const readU = () => {
38693
+ const b0 = bytes[cur++];
38694
+ if (b0 < 128) return b0;
38695
+ let res = b0 & 127;
38696
+ let shift = 7;
38697
+ while (true) {
38698
+ const byte = bytes[cur++];
38699
+ res |= (byte & 127) << shift;
38700
+ if ((byte & 128) === 0) return res;
38701
+ shift += 7;
38702
+ }
38703
+ };
38704
+ let importsDlsym = false;
38705
+ const importFuncNames = [];
38706
+ const importFuncModules = [];
38707
+ const importGlobalNames = [];
38708
+ const importTableNames = [];
38709
+ const importEventNames = [];
38710
+ const undefinedSyms = /* @__PURE__ */ new Set();
38711
+ const tags = /* @__PURE__ */ new Set();
38712
+ const globals = /* @__PURE__ */ new Set();
38713
+ const hostImports = /* @__PURE__ */ new Set();
38714
+ const weakUndefined = /* @__PURE__ */ new Set();
38715
+ const defined = /* @__PURE__ */ new Set();
38716
+ const weakDefined = /* @__PURE__ */ new Set();
38717
+ while (cur < bytes.length) {
38718
+ const id = bytes[cur++];
38719
+ const sz = readU();
38720
+ const end = cur + sz;
38721
+ if (id === 2) {
38722
+ const cnt = readU();
38723
+ for (let i = 0; i < cnt; i++) {
38724
+ const mLen = readU();
38725
+ const mName = rawBuf.toString("utf8", cur, cur + mLen);
38726
+ cur += mLen;
38727
+ const fLen = readU();
38728
+ const fName = rawBuf.toString("utf8", cur, cur + fLen);
38729
+ cur += fLen;
38730
+ const kind = bytes[cur++];
38731
+ if (kind === 0) {
38732
+ readU();
38733
+ importFuncNames.push(fName);
38734
+ importFuncModules.push(mName);
38735
+ if (mName === "env" && fName === "dlsym") importsDlsym = true;
38736
+ } else if (kind === 1) {
38737
+ cur++;
38738
+ const fl = readU();
38739
+ readU();
38740
+ if (fl & 1) readU();
38741
+ importTableNames.push(fName);
38742
+ } else if (kind === 2) {
38743
+ const fl = readU();
38744
+ readU();
38745
+ if (fl & 1) readU();
38746
+ } else if (kind === 3) {
38747
+ cur += 2;
38748
+ importGlobalNames.push(fName);
38749
+ } else if (kind === 4) {
38750
+ cur++;
38751
+ readU();
38752
+ importEventNames.push(fName);
38753
+ }
38754
+ }
38755
+ } else if (id === 0) {
38756
+ const nLen = readU();
38757
+ if (nLen === 7 && bytes[cur] === 108 && rawBuf.toString("utf8", cur, cur + nLen) === "linking") {
38758
+ cur += nLen;
38759
+ readU();
38760
+ while (cur < end) {
38761
+ const subId = bytes[cur++];
38762
+ const subLen = readU();
38763
+ const subEnd = cur + subLen;
38764
+ if (subId === 8) {
38765
+ const cnt = readU();
38766
+ for (let i = 0; i < cnt; i++) {
38767
+ const kind = bytes[cur++];
38768
+ const fl = readU();
38769
+ const isUndef = (fl & 16) !== 0;
38770
+ const isExplicitName = (fl & 64) !== 0;
38771
+ let sName = "";
38772
+ if (kind === 0 || kind === 2 || kind === 4 || kind === 5) {
38773
+ const el = readU();
38774
+ if (!isUndef || isExplicitName) {
38775
+ const sLen = readU();
38776
+ sName = rawBuf.toString("utf8", cur, cur + sLen);
38777
+ cur += sLen;
38778
+ } else if (kind === 0) {
38779
+ sName = importFuncNames[el] ?? "";
38780
+ } else if (kind === 2) {
38781
+ sName = importGlobalNames[el] ?? "";
38782
+ } else if (kind === 4) {
38783
+ sName = importEventNames[el] ?? "";
38784
+ } else if (kind === 5) {
38785
+ sName = importTableNames[el] ?? "";
38786
+ }
38787
+ if (isUndef && kind === 0 && importFuncModules[el] !== "env")
38788
+ hostImports.add(sName);
38789
+ } else if (kind === 1) {
38790
+ const sLen = readU();
38791
+ sName = rawBuf.toString("utf8", cur, cur + sLen);
38792
+ cur += sLen;
38793
+ if (!isUndef) {
38794
+ readU();
38795
+ readU();
38796
+ readU();
38797
+ }
38798
+ } else if (kind === 3) {
38799
+ readU();
38800
+ }
38801
+ if (sName) {
38802
+ if (isUndef) {
38803
+ undefinedSyms.add(sName);
38804
+ if ((fl & 19) === 17) weakUndefined.add(sName);
38805
+ } else if ((fl & 3) !== 2) {
38806
+ defined.add(sName);
38807
+ if ((fl & 19) === 1) weakDefined.add(sName);
38808
+ }
38809
+ if (kind === 4) tags.add(sName);
38810
+ else if (kind === 2 || kind === 5) globals.add(sName);
38811
+ }
38812
+ }
38813
+ break;
38814
+ }
38815
+ cur = subEnd;
38816
+ }
38817
+ break;
38818
+ }
38819
+ }
38820
+ cur = end;
38821
+ }
38446
38822
  return {
38447
- importsDlsym: object8.importsDlsym,
38448
- undefined: [
38449
- ...new Set(
38450
- object8.symNames.filter(
38451
- (name3, index) => name3 && (object8.symFlags[index] & 16) !== 0
38452
- )
38453
- )
38454
- ],
38823
+ importsDlsym,
38824
+ undefined: [...undefinedSyms],
38455
38825
  // a wasm tag is one module entity unified by name across the link, as the
38456
38826
  // main module owns it for dynamic images, so no image scope applies.
38457
- tags: [
38458
- ...new Set(
38459
- object8.symNames.filter((name3, index) => name3 && object8.symKind[index] === 4)
38460
- )
38461
- ],
38462
- globals: [
38463
- ...new Set(
38464
- object8.symNames.filter(
38465
- (name3, index) => name3 && (object8.symKind[index] === 2 || object8.symKind[index] === 5)
38466
- )
38467
- )
38468
- ],
38827
+ tags: [...tags],
38828
+ globals: [...globals],
38469
38829
  // an undefined function imported from a module other than env is supplied
38470
38830
  // by the host, whatever linker symbol names it.
38471
- hostImports: [...object8.hostImportNames],
38472
- weakUndefined: [
38473
- ...new Set(
38474
- object8.symNames.filter(
38475
- (name3, index) => name3 && (object8.symFlags[index] & 19) === 17
38476
- )
38477
- )
38478
- ],
38479
- defined: [
38480
- ...new Set(
38481
- object8.symNames.filter(
38482
- (name3, index) => name3 && (object8.symFlags[index] & 16) === 0 && (object8.symFlags[index] & 3) !== 2
38483
- )
38484
- )
38485
- ],
38486
- weakDefined: [
38487
- ...new Set(
38488
- object8.symNames.filter(
38489
- (name3, index) => name3 && (object8.symFlags[index] & 19) === 1
38490
- )
38491
- )
38492
- ]
38831
+ hostImports: [...hostImports],
38832
+ weakUndefined: [...weakUndefined],
38833
+ defined: [...defined],
38834
+ weakDefined: [...weakDefined]
38493
38835
  };
38494
38836
  }
38495
38837
  function sdkObjectName(archive, member, ordinal) {
@@ -39006,9 +39348,12 @@ function pruneSwiftWasmLink(directory2, toolchainBin, moduleRoot, staticClangTar
39006
39348
  for (const entry of waiting) tryActivateConformance(entry);
39007
39349
  }
39008
39350
  };
39351
+ const checkedProtocolTriggers = /* @__PURE__ */ new Set();
39009
39352
  const checkProtocolTrigger = (rawSymName) => {
39010
39353
  if (!rawSymName) return;
39011
39354
  const sName = rawSymName.startsWith(".Lgot.") ? rawSymName.slice(6) : rawSymName;
39355
+ if (checkedProtocolTriggers.has(sName)) return;
39356
+ checkedProtocolTriggers.add(sName);
39012
39357
  if (knownProtocols.has(sName)) {
39013
39358
  markProtocolLive(sName);
39014
39359
  return;
@@ -39041,6 +39386,43 @@ function pruneSwiftWasmLink(directory2, toolchainBin, moduleRoot, staticClangTar
39041
39386
  }
39042
39387
  }
39043
39388
  };
39389
+ const typeIndexes = /* @__PURE__ */ new Map();
39390
+ const getTypeIndex = (obj) => {
39391
+ let idx = typeIndexes.get(obj);
39392
+ if (idx) return idx;
39393
+ const mnByPrefix = /* @__PURE__ */ new Map();
39394
+ for (let i = 0; i < obj.symNames.length; i++) {
39395
+ const name3 = obj.symNames[i];
39396
+ if ((obj.symFlags[i] & 16) === 0 && name3.startsWith("$s") && name3.endsWith("Mn")) {
39397
+ const pref = name3.slice(0, -2);
39398
+ let list2 = mnByPrefix.get(pref);
39399
+ if (!list2) mnByPrefix.set(pref, list2 = []);
39400
+ list2.push(i);
39401
+ }
39402
+ }
39403
+ const objcRegByPrefix = /* @__PURE__ */ new Map();
39404
+ for (const [lf, p] of obj.objcRegisterFuncToTypePrefix) {
39405
+ let list2 = objcRegByPrefix.get(p);
39406
+ if (!list2) objcRegByPrefix.set(p, list2 = []);
39407
+ list2.push(lf);
39408
+ }
39409
+ const objcClassByPrefix = /* @__PURE__ */ new Map();
39410
+ for (const [classSym, p] of obj.objcClassSymToTypePrefix) {
39411
+ if (!classSym.startsWith("._OBJC_CLASS_")) continue;
39412
+ let list2 = objcClassByPrefix.get(p);
39413
+ if (!list2) objcClassByPrefix.set(p, list2 = []);
39414
+ list2.push(classSym.slice("._OBJC_CLASS_".length));
39415
+ }
39416
+ let minPrefLen = Infinity;
39417
+ let maxPrefLen = 0;
39418
+ for (const p of obj.typePrefixesInObj) {
39419
+ if (p.length < minPrefLen) minPrefLen = p.length;
39420
+ if (p.length > maxPrefLen) maxPrefLen = p.length;
39421
+ }
39422
+ idx = { mnByPrefix, objcRegByPrefix, objcClassByPrefix, minPrefLen, maxPrefLen };
39423
+ typeIndexes.set(obj, idx);
39424
+ return idx;
39425
+ };
39044
39426
  const markTypeLive = (obj, pref) => {
39045
39427
  const set2 = liveTypes.get(obj);
39046
39428
  if (set2.has(pref)) return;
@@ -39054,22 +39436,10 @@ function pruneSwiftWasmLink(directory2, toolchainBin, moduleRoot, staticClangTar
39054
39436
  const outer = pref.slice(0, n);
39055
39437
  if (obj.typePrefixesInObj.has(outer)) markTypeLive(obj, outer);
39056
39438
  }
39057
- const mnName = `${pref}Mn`;
39058
- for (let i = 0; i < obj.symNames.length; i++) {
39059
- if (obj.symNames[i] === mnName && (obj.symFlags[i] & 16) === 0) {
39060
- activateSymbolInObj(obj, i);
39061
- }
39062
- }
39063
- for (const [lf, p] of obj.objcRegisterFuncToTypePrefix) {
39064
- if (p === pref) {
39065
- markFuncLive(obj, lf);
39066
- }
39067
- }
39068
- for (const [classSym, p] of obj.objcClassSymToTypePrefix) {
39069
- if (p === pref && classSym.startsWith("._OBJC_CLASS_")) {
39070
- markObjCClassLive(classSym.slice("._OBJC_CLASS_".length));
39071
- }
39072
- }
39439
+ const idx = getTypeIndex(obj);
39440
+ for (const i of idx.mnByPrefix.get(pref) ?? []) activateSymbolInObj(obj, i);
39441
+ for (const lf of idx.objcRegByPrefix.get(pref) ?? []) markFuncLive(obj, lf);
39442
+ for (const cls of idx.objcClassByPrefix.get(pref) ?? []) markObjCClassLive(cls);
39073
39443
  };
39074
39444
  const checkTypeTrigger = (obj, rawSymName) => {
39075
39445
  if (!rawSymName) return;
@@ -39094,11 +39464,12 @@ function pruneSwiftWasmLink(directory2, toolchainBin, moduleRoot, staticClangTar
39094
39464
  }
39095
39465
  }
39096
39466
  }
39097
- if (obj.file.endsWith("libswiftCore__Swift.o") || obj.file.endsWith("libswift_Concurrency___Concurrency.o")) {
39098
- for (const pref of obj.typePrefixesInObj) {
39099
- if (sName.startsWith(pref)) {
39100
- markTypeLive(obj, pref);
39101
- }
39467
+ if (obj.typePrefixesInObj.size > 0 && (obj.file.endsWith("libswiftCore__Swift.o") || obj.file.endsWith("libswift_Concurrency___Concurrency.o"))) {
39468
+ const { minPrefLen, maxPrefLen } = getTypeIndex(obj);
39469
+ const hi = Math.min(sName.length, maxPrefLen);
39470
+ for (let n = minPrefLen; n <= hi; n++) {
39471
+ const cand = sName.slice(0, n);
39472
+ if (obj.typePrefixesInObj.has(cand)) markTypeLive(obj, cand);
39102
39473
  }
39103
39474
  }
39104
39475
  };
@@ -39191,7 +39562,8 @@ function pruneSwiftWasmLink(directory2, toolchainBin, moduleRoot, staticClangTar
39191
39562
  for (const fIdx of obj.rootFuncs) markFuncLive(obj, fIdx);
39192
39563
  for (const sIdx of obj.rootSegs) markSegLive(obj, sIdx);
39193
39564
  for (const name3 of obj.symNames) {
39194
- const loaded4 = name3?.match(/^_c_(\w+)__load$/)?.[1];
39565
+ if (!name3 || !name3.startsWith("_c_") || !name3.endsWith("__load")) continue;
39566
+ const loaded4 = name3.match(/^_c_(\w+)__load$/)?.[1];
39195
39567
  if (!loaded4) continue;
39196
39568
  const classSym = obj.symNames.indexOf(`._OBJC_CLASS_${loaded4}`);
39197
39569
  if (classSym !== -1 && (obj.symFlags[classSym] & 16) === 0)
@@ -39339,14 +39711,30 @@ function pruneSwiftWasmLink(directory2, toolchainBin, moduleRoot, staticClangTar
39339
39711
  const keepObjCClassesNamedInSegment = (obj, segIdx) => {
39340
39712
  const range3 = obj.segPayloadRanges[segIdx];
39341
39713
  if (!range3) return;
39714
+ const [rangeStart, rangeEnd] = range3;
39715
+ if (rangeEnd - rangeStart < 4) return;
39342
39716
  let bytes = objectBytes.get(obj);
39343
39717
  if (!bytes) objectBytes.set(obj, bytes = import_node_fs56.default.readFileSync(obj.file));
39344
- const text7 = bytes.toString("latin1", range3[0], range3[1]);
39345
- for (const match of text7.matchAll(/So(\d+)/g)) {
39346
- const start = match.index + 2 + match[1].length;
39347
- const length = Number(match[1]);
39348
- if (text7[start + length] !== "C") continue;
39349
- const symbol2 = `._OBJC_CLASS_${text7.slice(start, start + length)}`;
39718
+ let pos = rangeStart;
39719
+ while (pos < rangeEnd - 3) {
39720
+ const at = bytes.indexOf("So", pos);
39721
+ if (at < 0 || at >= rangeEnd - 2) break;
39722
+ let digitEnd = at + 2;
39723
+ let length = 0;
39724
+ while (digitEnd < rangeEnd) {
39725
+ const ch = bytes[digitEnd];
39726
+ if (ch < 48 || ch > 57) break;
39727
+ length = length * 10 + (ch - 48);
39728
+ digitEnd++;
39729
+ }
39730
+ if (digitEnd === at + 2) {
39731
+ pos = at + 2;
39732
+ continue;
39733
+ }
39734
+ pos = digitEnd;
39735
+ const nameEnd = digitEnd + length;
39736
+ if (nameEnd >= rangeEnd || bytes[nameEnd] !== 67) continue;
39737
+ const symbol2 = `._OBJC_CLASS_${bytes.toString("latin1", digitEnd, nameEnd)}`;
39350
39738
  for (const provider of lazyProviders.get(symbol2) ?? []) {
39351
39739
  eagerDynamicObjects.add(provider);
39352
39740
  extractObject(provider);
@@ -40440,6 +40828,10 @@ var init_nativeDyldTableContract = __esm({
40440
40828
 
40441
40829
  // src/swift-guest-image-ledger.ts
40442
40830
  function readNumber(bytes, position) {
40831
+ if (position < bytes.length) {
40832
+ const first = bytes[position];
40833
+ if (first < 128) return [first, position + 1];
40834
+ }
40443
40835
  let value = 0;
40444
40836
  let shift = 0;
40445
40837
  for (; ; ) {
@@ -40451,6 +40843,7 @@ function readNumber(bytes, position) {
40451
40843
  }
40452
40844
  }
40453
40845
  function encodeNumber(value) {
40846
+ if (value < 128) return Buffer.from([value]);
40454
40847
  const bytes = [];
40455
40848
  do {
40456
40849
  let byte = value % 128;
@@ -40472,6 +40865,9 @@ function encodedString(value) {
40472
40865
  const bytes = Buffer.from(value);
40473
40866
  return Buffer.concat([encodeNumber(bytes.length), bytes]);
40474
40867
  }
40868
+ function isWasmMagic(bytes) {
40869
+ 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;
40870
+ }
40475
40871
  function llvmType(value) {
40476
40872
  switch (value) {
40477
40873
  case 127:
@@ -40487,11 +40883,12 @@ function llvmType(value) {
40487
40883
  }
40488
40884
  }
40489
40885
  function rewriteObject(bytes, names, callerAlias, binding, instrumentDynamicLookups, preserveCanonical, options2 = {}) {
40490
- if (Buffer.from(bytes.subarray(0, 8)).toString("hex") !== "0061736d01000000")
40491
- throw new Error("expected wasm object");
40886
+ if (!isWasmMagic(bytes)) throw new Error("expected wasm object");
40887
+ const rawBuf = Buffer.isBuffer(bytes) ? bytes : Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength);
40492
40888
  const { sdkLookupOnly, sdkProduct } = options2;
40493
40889
  const comdatScope = sdkProduct === void 0 ? callerAlias : `${callerAlias}:${sdkProduct}`;
40494
- const sections = binding ? [Buffer.from(bytes.subarray(0, 8))] : void 0;
40890
+ const rewrite = binding !== void 0;
40891
+ const sections = rewrite ? [bytes.subarray(0, 8)] : void 0;
40495
40892
  const types2 = [];
40496
40893
  const functionTypes = [];
40497
40894
  const definitions = [];
@@ -40505,45 +40902,74 @@ function rewriteObject(bytes, names, callerAlias, binding, instrumentDynamicLook
40505
40902
  const usedSymbols = /* @__PURE__ */ new Set();
40506
40903
  let position = 8;
40507
40904
  while (position < bytes.length) {
40905
+ const headerStart2 = position;
40508
40906
  const id = bytes[position++];
40509
- const [size2, start] = readNumber(bytes, position);
40907
+ let size2 = 0;
40908
+ if (position < bytes.length && bytes[position] < 128) {
40909
+ size2 = bytes[position++];
40910
+ } else {
40911
+ const [val, next] = readNumber(bytes, position);
40912
+ size2 = val;
40913
+ position = next;
40914
+ }
40915
+ const start = position;
40510
40916
  const end = start + size2;
40511
40917
  if (end > bytes.length) throw new Error("invalid wasm section");
40512
40918
  position = end;
40513
- if (!sections && id > 3) continue;
40514
- let section2 = Buffer.from(bytes.buffer, bytes.byteOffset + start, size2);
40515
- let offset = 0;
40919
+ if (id > 3) {
40920
+ if (sections) sections.push(bytes.subarray(headerStart2, end));
40921
+ continue;
40922
+ }
40923
+ let offset = start;
40516
40924
  const number4 = () => {
40517
- const [value, next] = readNumber(section2, offset);
40518
- offset = next;
40519
- return value;
40925
+ if (offset < end) {
40926
+ const first = bytes[offset];
40927
+ if (first < 128) {
40928
+ offset++;
40929
+ return first;
40930
+ }
40931
+ }
40932
+ let value = 0;
40933
+ let shift = 0;
40934
+ for (; ; ) {
40935
+ if (offset >= end || shift > 63) throw new Error("invalid wasm integer");
40936
+ const byte = bytes[offset++];
40937
+ value += (byte & 127) * 2 ** shift;
40938
+ if (!(byte & 128)) return value;
40939
+ shift += 7;
40940
+ }
40520
40941
  };
40521
40942
  const string8 = () => {
40522
- const [value, next] = readString(section2, offset);
40523
- offset = next;
40943
+ const length = number4();
40944
+ const strEnd = offset + length;
40945
+ if (strEnd > end) throw new Error("invalid wasm string");
40946
+ const value = rawBuf.toString("utf8", offset, strEnd);
40947
+ offset = strEnd;
40524
40948
  return value;
40525
40949
  };
40950
+ let rewrittenSection;
40526
40951
  if (id === 1) {
40527
40952
  const count = number4();
40528
40953
  for (let i = 0; i < count; i++) {
40529
- if (section2[offset++] !== 96) throw new Error("unsupported wasm type");
40954
+ if (bytes[offset++] !== 96) throw new Error("unsupported wasm type");
40530
40955
  const parameterCount = number4();
40531
- const parameters = [...section2.subarray(offset, offset + parameterCount)];
40532
- if (parameterCount !== parameters.length) throw new Error("invalid wasm type");
40533
- offset += parameterCount;
40956
+ if (offset + parameterCount > end) throw new Error("invalid wasm type");
40957
+ const parameters = new Array(parameterCount);
40958
+ for (let p = 0; p < parameterCount; p++) parameters[p] = bytes[offset++];
40534
40959
  const resultCount = number4();
40535
- const results = [...section2.subarray(offset, offset + resultCount)];
40536
- if (results.length !== resultCount) throw new Error("invalid wasm type");
40537
- offset += resultCount;
40960
+ if (offset + resultCount > end) throw new Error("invalid wasm type");
40961
+ const results = new Array(resultCount);
40962
+ for (let r = 0; r < resultCount; r++) results[r] = bytes[offset++];
40538
40963
  types2.push({ parameters, results });
40539
40964
  }
40540
40965
  } else if (id === 2) {
40541
40966
  const count = number4();
40542
- const imports2 = sections ? [encodeNumber(count)] : void 0;
40967
+ const importWriter = rewrite ? new ByteWriter(size2 + 64) : void 0;
40968
+ importWriter?.uleb(count);
40543
40969
  for (let i = 0; i < count; i++) {
40544
40970
  const module2 = string8();
40545
40971
  const name3 = string8();
40546
- const kind = section2[offset++];
40972
+ const kind = bytes[offset++];
40547
40973
  const typeStart = offset;
40548
40974
  let functionType2 = -1;
40549
40975
  if (kind === 0) {
@@ -40551,7 +40977,7 @@ function rewriteObject(bytes, names, callerAlias, binding, instrumentDynamicLook
40551
40977
  functionTypes.push(functionType2);
40552
40978
  functionImportNames.push(name3);
40553
40979
  } else if (kind === 1) {
40554
- const referenceType = section2[offset++];
40980
+ const referenceType = bytes[offset++];
40555
40981
  if (referenceType !== 112 && referenceType !== 111)
40556
40982
  throw new Error("unsupported table type");
40557
40983
  const flags = number4();
@@ -40570,11 +40996,15 @@ function rewriteObject(bytes, names, callerAlias, binding, instrumentDynamicLook
40570
40996
  } else throw new Error("unsupported wasm import");
40571
40997
  const isDlsym = instrumentDynamicLookups && module2 === "env" && name3 === "dlsym" && kind === 0;
40572
40998
  const isDlerror = instrumentDynamicLookups && module2 === "env" && name3 === "dlerror" && kind === 0;
40573
- if (module2 === "env" && names.has(name3)) usedSymbols.add(name3);
40574
- if (module2 === "env" && kind === 0 && names.has(name3)) {
40575
- const type = types2[functionType2];
40576
- if (!type) throw new Error(`missing import type for ${name3}`);
40577
- functionImports.set(name3, type);
40999
+ if (!rewrite) {
41000
+ if (module2 === "env" && names.has(name3)) {
41001
+ usedSymbols.add(name3);
41002
+ if (kind === 0) {
41003
+ const type = types2[functionType2];
41004
+ if (!type) throw new Error(`missing import type for ${name3}`);
41005
+ functionImports.set(name3, type);
41006
+ }
41007
+ }
40578
41008
  }
40579
41009
  if (isDlsym || isDlerror) {
40580
41010
  const type = types2[functionType2];
@@ -40584,17 +41014,17 @@ function rewriteObject(bytes, names, callerAlias, binding, instrumentDynamicLook
40584
41014
  }
40585
41015
  if (isDlsym) usesDlsym = true;
40586
41016
  if (isDlerror) usesDlerror = true;
40587
- imports2?.push(
40588
- encodedString(module2),
40589
- encodedString(
40590
- isDlsym ? callerAlias : isDlerror ? dlerrorAlias : module2 === "env" && name3 !== "dlsym" && name3 !== "dlerror" ? binding?.(name3) ?? name3 : name3
40591
- ),
40592
- Buffer.from([kind]),
40593
- section2.subarray(typeStart, offset)
40594
- );
41017
+ if (importWriter && binding) {
41018
+ importWriter.string(module2);
41019
+ importWriter.string(
41020
+ isDlsym ? callerAlias : isDlerror ? dlerrorAlias : module2 === "env" && name3 !== "dlsym" && name3 !== "dlerror" ? binding(name3) ?? name3 : name3
41021
+ );
41022
+ importWriter.byte(kind);
41023
+ importWriter.bytes(bytes, typeStart, offset);
41024
+ }
40595
41025
  }
40596
- if (offset !== section2.length) throw new Error("invalid wasm import section");
40597
- if (imports2) section2 = Buffer.concat(imports2);
41026
+ if (offset !== end) throw new Error("invalid wasm import section");
41027
+ if (importWriter) rewrittenSection = importWriter.finish();
40598
41028
  } else if (id === 3) {
40599
41029
  const count = number4();
40600
41030
  for (let i = 0; i < count; i++) functionTypes.push(number4());
@@ -40603,43 +41033,40 @@ function rewriteObject(bytes, names, callerAlias, binding, instrumentDynamicLook
40603
41033
  if (sectionName === "linking") {
40604
41034
  const version2 = number4();
40605
41035
  if (version2 !== 2) throw new Error("unsupported wasm linking version");
40606
- const subsections = [];
41036
+ const subsections = rewrite ? [] : void 0;
40607
41037
  let objcLoader;
40608
- while (offset < section2.length) {
40609
- const kind = section2[offset++];
41038
+ while (offset < end) {
41039
+ const kind = bytes[offset++];
40610
41040
  const length = number4();
40611
41041
  const stop = offset + length;
40612
- if (stop > section2.length) throw new Error("invalid linking subsection");
40613
- let content = section2.subarray(offset, stop);
40614
- if (kind === 7 && !sdkLookupOnly) {
40615
- const groups = [];
41042
+ if (stop > end) throw new Error("invalid linking subsection");
41043
+ const contentStart = offset;
41044
+ if (kind === 7 && rewrite && !sdkLookupOnly) {
41045
+ const comdatWriter = new ByteWriter(length + 64);
40616
41046
  const count = number4();
40617
- groups.push(encodeNumber(count));
41047
+ comdatWriter.uleb(count);
40618
41048
  for (let i = 0; i < count; i++) {
40619
41049
  const group = string8();
40620
41050
  const begin = offset;
40621
41051
  number4();
40622
41052
  const members2 = number4();
40623
41053
  for (let member = 0; member < members2 * 2; member++) number4();
40624
- groups.push(
40625
- encodedString(
40626
- group === OBJC_INIT_RECORD ? group : `${comdatScope}:${group}`
40627
- ),
40628
- section2.subarray(begin, offset)
41054
+ comdatWriter.string(
41055
+ group === OBJC_INIT_RECORD ? group : `${comdatScope}:${group}`
40629
41056
  );
41057
+ comdatWriter.bytes(bytes, begin, offset);
40630
41058
  }
40631
41059
  if (offset !== stop) throw new Error("invalid comdat subsection");
40632
- content = Buffer.concat(groups);
40633
- }
40634
- if (kind === 8) {
40635
- const entries2 = [];
40636
- const extraEntries = [];
41060
+ const buf = comdatWriter.finish();
41061
+ subsections.push({ kind, parts: [buf], byteLength: buf.length });
41062
+ } else if (kind === 8) {
41063
+ const entryWriter = rewrite ? new ByteWriter(length + 128) : void 0;
41064
+ let extraWriter;
40637
41065
  const count = number4();
40638
- entries2.push(encodeNumber(count));
40639
41066
  let added = 0;
40640
41067
  for (let i = 0; i < count; i++) {
40641
41068
  const begin = offset;
40642
- const symbolKind = section2[offset++];
41069
+ const symbolKind = bytes[offset++];
40643
41070
  const flags = number4();
40644
41071
  const flagsEnd = offset;
40645
41072
  let index = -1;
@@ -40667,25 +41094,43 @@ function rewriteObject(bytes, names, callerAlias, binding, instrumentDynamicLook
40667
41094
  }
40668
41095
  } else if (symbolKind === 3) number4();
40669
41096
  else throw new Error("unsupported wasm symbol kind");
40670
- if (symbolKind === 0)
41097
+ if (!rewrite && symbolKind === 0)
40671
41098
  functionSymbols[i] = name3 || functionImportNames[index];
40672
- if (!sdkLookupOnly && name3 === OBJC_LOAD_FUNCTION && symbolKind === 0 && !(flags & 16)) {
41099
+ if (rewrite && !sdkLookupOnly && name3 === OBJC_LOAD_FUNCTION && symbolKind === 0 && !(flags & 16)) {
40673
41100
  objcLoader = i;
40674
41101
  }
40675
41102
  const alias = names.get(name3);
40676
- if (flags & 16 && symbolKind === 1 && alias) usedSymbols.add(name3);
40677
- if ((name3 === "dlsym" && usesDlsym || name3 === "dlerror" && usesDlerror) && flags & 16 && flags & 64 && symbolKind === 0) {
40678
- entries2.push(
40679
- section2.subarray(begin, nameStart),
40680
- encodedString(name3 === "dlsym" ? callerAlias : dlerrorAlias),
40681
- section2.subarray(nameEnd, offset)
40682
- );
40683
- } else if (flags & 16 && name3 !== "dlsym" && name3 !== "dlerror" && binding?.(name3) !== void 0) {
40684
- entries2.push(
40685
- section2.subarray(begin, nameStart),
40686
- encodedString(binding(name3)),
40687
- section2.subarray(nameEnd, offset)
40688
- );
41103
+ if (!rewrite && flags & 16 && symbolKind === 1 && alias)
41104
+ usedSymbols.add(name3);
41105
+ if (entryWriter && binding) {
41106
+ if ((name3 === "dlsym" && usesDlsym || name3 === "dlerror" && usesDlerror) && flags & 16 && flags & 64 && symbolKind === 0) {
41107
+ entryWriter.bytes(bytes, begin, nameStart);
41108
+ entryWriter.string(name3 === "dlsym" ? callerAlias : dlerrorAlias);
41109
+ entryWriter.bytes(bytes, nameEnd, offset);
41110
+ } else if (flags & 16 && name3 !== "dlsym" && name3 !== "dlerror" && binding(name3) !== void 0) {
41111
+ entryWriter.bytes(bytes, begin, nameStart);
41112
+ entryWriter.string(binding(name3));
41113
+ entryWriter.bytes(bytes, nameEnd, offset);
41114
+ } else if (alias && !(flags & 16) && (flags & 3) !== 2) {
41115
+ if (symbolKind !== 0 && symbolKind !== 1)
41116
+ throw new Error(`unsupported symbol ${name3}`);
41117
+ if (preserveCanonical.has(name3)) {
41118
+ entryWriter.bytes(bytes, begin, offset);
41119
+ extraWriter ??= new ByteWriter(256);
41120
+ extraWriter.byte(bytes[begin]);
41121
+ extraWriter.uleb(flags & ~32);
41122
+ extraWriter.bytes(bytes, flagsEnd, nameStart);
41123
+ extraWriter.string(alias);
41124
+ extraWriter.bytes(bytes, nameEnd, offset);
41125
+ added++;
41126
+ } else {
41127
+ entryWriter.bytes(bytes, begin, nameStart);
41128
+ entryWriter.string(alias);
41129
+ entryWriter.bytes(bytes, nameEnd, offset);
41130
+ }
41131
+ } else {
41132
+ entryWriter.bytes(bytes, begin, offset);
41133
+ }
40689
41134
  } else if (alias && !(flags & 16) && (flags & 3) !== 2) {
40690
41135
  if (symbolKind !== 0 && symbolKind !== 1)
40691
41136
  throw new Error(`unsupported symbol ${name3}`);
@@ -40699,63 +41144,73 @@ function rewriteObject(bytes, names, callerAlias, binding, instrumentDynamicLook
40699
41144
  hidden: (flags & 4) !== 0,
40700
41145
  type
40701
41146
  });
40702
- if (preserveCanonical.has(name3)) {
40703
- entries2.push(section2.subarray(begin, offset));
40704
- extraEntries.push(
40705
- section2.subarray(begin, begin + 1),
40706
- encodeNumber(flags & ~32),
40707
- section2.subarray(flagsEnd, nameStart),
40708
- encodedString(alias),
40709
- section2.subarray(nameEnd, offset)
40710
- );
40711
- added++;
40712
- } else {
40713
- entries2.push(
40714
- section2.subarray(begin, nameStart),
40715
- encodedString(alias),
40716
- section2.subarray(nameEnd, offset)
40717
- );
40718
- }
40719
- } else entries2.push(section2.subarray(begin, offset));
41147
+ }
40720
41148
  }
40721
41149
  if (offset !== stop) throw new Error("invalid symbol subsection");
40722
- entries2[0] = encodeNumber(count + added);
40723
- content = Buffer.concat([...entries2, ...extraEntries]);
41150
+ if (entryWriter) {
41151
+ const countBytes = encodeNumber(count + added);
41152
+ const entryBuf = entryWriter.finish();
41153
+ if (extraWriter) {
41154
+ const extraBuf = extraWriter.finish();
41155
+ subsections.push({
41156
+ kind,
41157
+ parts: [countBytes, entryBuf, extraBuf],
41158
+ byteLength: countBytes.length + entryBuf.length + extraBuf.length
41159
+ });
41160
+ } else {
41161
+ subsections.push({
41162
+ kind,
41163
+ parts: [countBytes, entryBuf],
41164
+ byteLength: countBytes.length + entryBuf.length
41165
+ });
41166
+ }
41167
+ }
41168
+ } else if (subsections) {
41169
+ subsections.push({
41170
+ kind,
41171
+ parts: [bytes.subarray(contentStart, stop)],
41172
+ byteLength: length
41173
+ });
40724
41174
  }
40725
41175
  offset = stop;
40726
- subsections.push({ kind, content });
40727
- }
40728
- const parts2 = [encodedString(sectionName), encodeNumber(version2)];
40729
- for (const subsection of subsections) {
40730
- let content = subsection.content;
40731
- if (subsection.kind === 6 && objcLoader !== void 0) {
40732
- const [count, entriesStart] = readNumber(content, 0);
40733
- const entries2 = [content.subarray(0, entriesStart)];
40734
- let entryStart = entriesStart;
40735
- for (let i = 0; i < count; i++) {
40736
- const [, symbolStart] = readNumber(content, entryStart);
40737
- const [symbol2, entryEnd] = readNumber(content, symbolStart);
40738
- if (symbol2 === objcLoader) entries2.push(encodeNumber(1));
40739
- entries2.push(
40740
- content.subarray(
40741
- symbol2 === objcLoader ? symbolStart : entryStart,
40742
- entryEnd
40743
- )
40744
- );
40745
- entryStart = entryEnd;
41176
+ }
41177
+ if (subsections) {
41178
+ const linkingWriter = new ByteWriter(size2 + 128);
41179
+ linkingWriter.string(sectionName);
41180
+ linkingWriter.uleb(version2);
41181
+ for (const subsection of subsections) {
41182
+ if (subsection.kind === 6 && objcLoader !== void 0) {
41183
+ const content = subsection.parts[0];
41184
+ const [count, entriesStart] = readNumber(content, 0);
41185
+ const initWriter = new ByteWriter(content.length + 16);
41186
+ initWriter.bytes(content, 0, entriesStart);
41187
+ let entryStart = entriesStart;
41188
+ for (let i = 0; i < count; i++) {
41189
+ const [, symbolStart] = readNumber(content, entryStart);
41190
+ const [symbol2, entryEnd] = readNumber(content, symbolStart);
41191
+ if (symbol2 === objcLoader) {
41192
+ initWriter.uleb(1);
41193
+ initWriter.bytes(content, symbolStart, entryEnd);
41194
+ } else {
41195
+ initWriter.bytes(content, entryStart, entryEnd);
41196
+ }
41197
+ entryStart = entryEnd;
41198
+ }
41199
+ if (entryStart !== content.length)
41200
+ throw new Error("invalid init functions subsection");
41201
+ const initBuf = initWriter.finish();
41202
+ linkingWriter.byte(subsection.kind);
41203
+ linkingWriter.uleb(initBuf.length);
41204
+ linkingWriter.bytes(initBuf);
41205
+ } else {
41206
+ linkingWriter.byte(subsection.kind);
41207
+ linkingWriter.uleb(subsection.byteLength);
41208
+ for (const part of subsection.parts) linkingWriter.bytes(part);
40746
41209
  }
40747
- if (entryStart !== content.length)
40748
- throw new Error("invalid init functions subsection");
40749
- content = Buffer.concat(entries2);
40750
41210
  }
40751
- parts2.push(
40752
- Buffer.from([subsection.kind]),
40753
- encodeNumber(content.length),
40754
- content
40755
- );
41211
+ rewrittenSection = linkingWriter.finish();
40756
41212
  }
40757
- section2 = Buffer.concat(parts2);
40758
- } else if (!sections && sectionName.startsWith("reloc.")) {
41213
+ } else if (!rewrite && sectionName.startsWith("reloc.")) {
40759
41214
  number4();
40760
41215
  for (let count = number4(); count > 0; count--) {
40761
41216
  const type = number4();
@@ -40765,18 +41220,27 @@ function rewriteObject(bytes, names, callerAlias, binding, instrumentDynamicLook
40765
41220
  if (name3 !== void 0 && TABLE_INDEX_RELOCATIONS.has(type))
40766
41221
  addressTaken.add(name3);
40767
41222
  }
40768
- if (offset !== section2.length)
40769
- throw new Error(`invalid relocation section ${sectionName}`);
41223
+ if (offset !== end) throw new Error(`invalid relocation section ${sectionName}`);
41224
+ }
41225
+ }
41226
+ if (sections) {
41227
+ if (rewrittenSection) {
41228
+ sections.push(
41229
+ Buffer.from([id]),
41230
+ encodeNumber(rewrittenSection.length),
41231
+ rewrittenSection
41232
+ );
41233
+ } else {
41234
+ sections.push(bytes.subarray(headerStart2, end));
40770
41235
  }
40771
41236
  }
40772
- sections?.push(Buffer.from([id]), encodeNumber(section2.length), section2);
40773
41237
  }
40774
41238
  return {
40775
41239
  bytes: sections ? Buffer.concat(sections) : bytes,
40776
41240
  definitions,
40777
41241
  functionImports,
40778
41242
  usesDlsym,
40779
- usedSymbols: [...usedSymbols],
41243
+ usedSymbols,
40780
41244
  addressTaken: [...addressTaken]
40781
41245
  };
40782
41246
  }
@@ -40865,36 +41329,51 @@ function createGuestImageLedger(input) {
40865
41329
  }
40866
41330
  }
40867
41331
  }
40868
- const nameBytes = /* @__PURE__ */ new Map();
40869
- for (const definition2 of definitions)
40870
- if (!nameBytes.has(definition2.name))
40871
- nameBytes.set(definition2.name, Buffer.from(definition2.name));
40872
- definitions.sort(
40873
- (a, b) => Buffer.compare(nameBytes.get(a.name), nameBytes.get(b.name)) || a.image - b.image
40874
- );
41332
+ let hasNonAscii = false;
41333
+ for (const definition2 of definitions) {
41334
+ const s = definition2.name;
41335
+ for (let i = 0; i < s.length; i++) {
41336
+ if (s.charCodeAt(i) > 127) {
41337
+ hasNonAscii = true;
41338
+ break;
41339
+ }
41340
+ }
41341
+ if (hasNonAscii) break;
41342
+ }
41343
+ if (hasNonAscii) {
41344
+ const nameBytes = /* @__PURE__ */ new Map();
41345
+ for (const definition2 of definitions)
41346
+ if (!nameBytes.has(definition2.name))
41347
+ nameBytes.set(definition2.name, Buffer.from(definition2.name));
41348
+ definitions.sort(
41349
+ (a, b) => Buffer.compare(nameBytes.get(a.name), nameBytes.get(b.name)) || a.image - b.image
41350
+ );
41351
+ } else {
41352
+ definitions.sort(
41353
+ (a, b) => a.name < b.name ? -1 : a.name > b.name ? 1 : a.image - b.image
41354
+ );
41355
+ }
40875
41356
  const preserveCanonical = /* @__PURE__ */ new Set();
40876
41357
  const definitionsByName = Map.groupBy(definitions, (definition2) => definition2.name);
40877
- for (const name3 of input.symbols) {
41358
+ if (symbolIndices.has("__cxa_throw")) {
41359
+ const name3 = "__cxa_throw";
40878
41360
  const matching2 = definitionsByName.get(name3) ?? [];
40879
- if (new Set(matching2.map((definition2) => definition2.image)).size < 2 || !matching2.some((definition2) => definition2.weak))
40880
- continue;
40881
- const weak = matching2.filter((definition2) => definition2.weak);
40882
- const strong = matching2.filter((definition2) => !definition2.weak);
40883
- if (name3 !== "__cxa_throw") continue;
40884
- if (weak.length !== 1 || strong.length !== 1)
40885
- throw new Error(`unsupported weak interposition for ${name3}`);
40886
- const [local] = weak;
40887
- const [runtime] = strong;
40888
- if (local.kind !== "function" || runtime.kind !== "function" || local.result !== runtime.result || local.parameters.join(",") !== runtime.parameters.join(","))
40889
- throw new Error(`incompatible weak interposition for ${name3}`);
40890
- for (const caller of input.callers) {
40891
- const uses = caller.image === local.image || units.some(
40892
- (unit2) => unit2.image === caller.image && unit2.usedSymbols.includes(name3)
40893
- );
40894
- if (uses && caller.image !== runtime.image && !caller.next.includes(runtime.image))
40895
- throw new Error(`weak interposition scope excludes runtime for ${name3}`);
41361
+ if (new Set(matching2.map((definition2) => definition2.image)).size >= 2 && matching2.some((definition2) => definition2.weak)) {
41362
+ const weak = matching2.filter((definition2) => definition2.weak);
41363
+ const strong = matching2.filter((definition2) => !definition2.weak);
41364
+ if (weak.length !== 1 || strong.length !== 1)
41365
+ throw new Error(`unsupported weak interposition for ${name3}`);
41366
+ const [local] = weak;
41367
+ const [runtime] = strong;
41368
+ if (local.kind !== "function" || runtime.kind !== "function" || local.result !== runtime.result || local.parameters.join(",") !== runtime.parameters.join(","))
41369
+ throw new Error(`incompatible weak interposition for ${name3}`);
41370
+ for (const caller of input.callers) {
41371
+ const uses = caller.image === local.image || units.some((unit2) => unit2.image === caller.image && unit2.usedSymbols.has(name3));
41372
+ if (uses && caller.image !== runtime.image && !caller.next.includes(runtime.image))
41373
+ throw new Error(`weak interposition scope excludes runtime for ${name3}`);
41374
+ }
41375
+ preserveCanonical.add(name3);
40896
41376
  }
40897
- preserveCanonical.add(name3);
40898
41377
  }
40899
41378
  for (const name3 of [
40900
41379
  "dlsym",
@@ -40906,40 +41385,76 @@ function createGuestImageLedger(input) {
40906
41385
  ])
40907
41386
  preserveCanonical.add(name3);
40908
41387
  for (const name3 of input.commandLineSymbols ?? []) preserveCanonical.add(name3);
40909
- const bindingsByImage = /* @__PURE__ */ new Map();
40910
- const definitionsByImage = Map.groupBy(definitions, (definition2) => definition2.image);
41388
+ const imageAliases = /* @__PURE__ */ new Map();
41389
+ const imageWeakNames = /* @__PURE__ */ new Map();
41390
+ const singleOwnerByName = /* @__PURE__ */ new Map();
41391
+ for (const definition2 of definitions) {
41392
+ let aliases = imageAliases.get(definition2.image);
41393
+ if (!aliases) imageAliases.set(definition2.image, aliases = /* @__PURE__ */ new Map());
41394
+ const existing = aliases.get(definition2.name);
41395
+ if (existing === void 0) {
41396
+ aliases.set(definition2.name, definition2.alias);
41397
+ if (definition2.weak) {
41398
+ let weak = imageWeakNames.get(definition2.image);
41399
+ if (!weak) imageWeakNames.set(definition2.image, weak = /* @__PURE__ */ new Set());
41400
+ weak.add(definition2.name);
41401
+ }
41402
+ const owner = singleOwnerByName.get(definition2.name);
41403
+ if (owner === void 0)
41404
+ singleOwnerByName.set(definition2.name, {
41405
+ image: definition2.image,
41406
+ alias: definition2.alias
41407
+ });
41408
+ else if (owner !== null && owner.image !== definition2.image)
41409
+ singleOwnerByName.set(definition2.name, null);
41410
+ } else if (!definition2.weak && imageWeakNames.get(definition2.image)?.has(definition2.name)) {
41411
+ aliases.set(definition2.name, definition2.alias);
41412
+ imageWeakNames.get(definition2.image).delete(definition2.name);
41413
+ const owner = singleOwnerByName.get(definition2.name);
41414
+ if (owner && owner.image === definition2.image) owner.alias = definition2.alias;
41415
+ }
41416
+ }
41417
+ const sharedLookupByImage = /* @__PURE__ */ new Map();
40911
41418
  for (const caller of input.callers) {
40912
- const bindings = /* @__PURE__ */ new Map();
40913
- const seen = /* @__PURE__ */ new Map();
40914
41419
  const scope2 = [caller.image, ...caller.next];
40915
41420
  if (input.systemImage !== void 0 && !scope2.includes(input.systemImage))
40916
41421
  scope2.push(input.systemImage);
40917
- for (const image of scope2)
40918
- for (const definition2 of definitionsByImage.get(image) ?? []) {
40919
- const previous = seen.get(definition2.name);
40920
- if (previous?.image === definition2.image) {
40921
- if (previous.weak && !definition2.weak) {
40922
- seen.set(definition2.name, definition2);
40923
- if (!preserveCanonical.has(definition2.name))
40924
- bindings.set(definition2.name, definition2.alias);
40925
- }
40926
- continue;
40927
- }
40928
- if (!previous) {
40929
- seen.set(definition2.name, definition2);
40930
- if (!preserveCanonical.has(definition2.name))
40931
- bindings.set(definition2.name, definition2.alias);
41422
+ const scopeSet = new Set(scope2);
41423
+ const scopeMaps = [];
41424
+ const seenImages = /* @__PURE__ */ new Set();
41425
+ for (const image of scope2) {
41426
+ if (seenImages.has(image)) continue;
41427
+ seenImages.add(image);
41428
+ const aliases = imageAliases.get(image);
41429
+ if (aliases) scopeMaps.push(aliases);
41430
+ }
41431
+ const cache = /* @__PURE__ */ new Map();
41432
+ sharedLookupByImage.set(caller.image, (name3) => {
41433
+ if (preserveCanonical.has(name3)) return void 0;
41434
+ const single = singleOwnerByName.get(name3);
41435
+ if (single === void 0) return void 0;
41436
+ if (single !== null) return scopeSet.has(single.image) ? single.alias : void 0;
41437
+ const hit = cache.get(name3);
41438
+ if (hit !== void 0) return hit ?? void 0;
41439
+ for (const aliases of scopeMaps) {
41440
+ const alias = aliases.get(name3);
41441
+ if (alias !== void 0) {
41442
+ cache.set(name3, alias);
41443
+ return alias;
40932
41444
  }
40933
41445
  }
40934
- bindingsByImage.set(caller.image, bindings);
41446
+ cache.set(name3, null);
41447
+ return void 0;
41448
+ });
40935
41449
  }
40936
41450
  const startup = /* @__PURE__ */ new Map();
41451
+ const unitsByPath = new Map(units.map((unit2) => [unit2.object.path, unit2]));
40937
41452
  for (const binding of input.directBindings ?? []) {
40938
- const unit2 = units.find(({ object: object8 }) => object8.path === binding.object);
41453
+ const unit2 = unitsByPath.get(binding.object);
40939
41454
  const matches = (definitionsByName.get(binding.symbol) ?? []).filter(
40940
41455
  (definition2) => definition2.object === binding.providerObject && definition2.image === binding.providerImage
40941
41456
  );
40942
- if (!unit2 || !unit2.usedSymbols.includes(binding.symbol) || matches.length !== 1)
41457
+ if (!unit2 || !unit2.usedSymbols.has(binding.symbol) || matches.length !== 1)
40943
41458
  throw new Error(`invalid startup binding ${binding.object} ${binding.symbol}`);
40944
41459
  const bindings = startup.get(binding.object) ?? /* @__PURE__ */ new Map();
40945
41460
  if (bindings.has(binding.symbol))
@@ -40980,11 +41495,11 @@ function createGuestImageLedger(input) {
40980
41495
  }
40981
41496
  }
40982
41497
  const objects = units.map(({ image, object: object8, aliases, functionImports }) => {
40983
- const shared = bindingsByImage.get(image);
41498
+ const shared = sharedLookupByImage.get(image);
40984
41499
  const own2 = startup.get(object8.path);
40985
41500
  const bindings = new Map(own2);
40986
41501
  const weak = input.sdkWeakReferences?.get(object8.path);
40987
- const binding = (name3) => bindings.get(name3) ?? shared.get(name3) ?? (weak?.has(name3) ? void 0 : sdkGlobalBindings.get(name3));
41502
+ const binding = (name3) => bindings.get(name3) ?? shared(name3) ?? (weak?.has(name3) ? void 0 : sdkGlobalBindings.get(name3));
40988
41503
  for (const [name3, type] of functionImports) {
40989
41504
  const alias = binding(name3);
40990
41505
  const provider = alias === void 0 ? void 0 : definitionsByAlias.get(alias);
@@ -41249,7 +41764,7 @@ function nameGuestImageAliases(wasm, symbols) {
41249
41764
  }
41250
41765
  return Buffer.concat(parts2);
41251
41766
  }
41252
- var import_node_crypto31, OBJC_INIT_RECORD, TABLE_INDEX_RELOCATIONS, GUEST_DYLD_VALUES_SECTION, GUEST_LAZY_FUNCTION_BASE, SDK_DYLD_RESOLVER;
41767
+ var import_node_crypto31, ByteWriter, OBJC_INIT_RECORD, TABLE_INDEX_RELOCATIONS, GUEST_DYLD_VALUES_SECTION, GUEST_LAZY_FUNCTION_BASE, SDK_DYLD_RESOLVER;
41253
41768
  var init_swift_guest_image_ledger = __esm({
41254
41769
  "src/swift-guest-image-ledger.ts"() {
41255
41770
  "use strict";
@@ -41257,6 +41772,57 @@ var init_swift_guest_image_ledger = __esm({
41257
41772
  init_nativeWasmContract();
41258
41773
  init_swift_sdk_image_wasm();
41259
41774
  init_swiftSdkLinkContract();
41775
+ ByteWriter = class {
41776
+ buf;
41777
+ pos = 0;
41778
+ constructor(initialCapacity = 256) {
41779
+ this.buf = Buffer.allocUnsafe(Math.max(64, initialCapacity));
41780
+ }
41781
+ ensure(extra) {
41782
+ const needed = this.pos + extra;
41783
+ if (needed <= this.buf.length) return;
41784
+ let next = this.buf.length * 2;
41785
+ while (next < needed) next *= 2;
41786
+ const grown = Buffer.allocUnsafe(next);
41787
+ this.buf.copy(grown, 0, 0, this.pos);
41788
+ this.buf = grown;
41789
+ }
41790
+ byte(value) {
41791
+ this.ensure(1);
41792
+ this.buf[this.pos++] = value;
41793
+ }
41794
+ uleb(value) {
41795
+ this.ensure(10);
41796
+ let pos = this.pos;
41797
+ const buf = this.buf;
41798
+ do {
41799
+ let byte = value % 128;
41800
+ value = Math.floor(value / 128);
41801
+ if (value) byte |= 128;
41802
+ buf[pos++] = byte;
41803
+ } while (value);
41804
+ this.pos = pos;
41805
+ }
41806
+ bytes(source, start = 0, end = source.length) {
41807
+ const len = end - start;
41808
+ if (len <= 0) return;
41809
+ this.ensure(len);
41810
+ this.buf.set(source.subarray(start, end), this.pos);
41811
+ this.pos += len;
41812
+ }
41813
+ string(value) {
41814
+ const len = Buffer.byteLength(value, "utf8");
41815
+ this.uleb(len);
41816
+ if (len > 0) {
41817
+ this.ensure(len);
41818
+ this.buf.write(value, this.pos, len, "utf8");
41819
+ this.pos += len;
41820
+ }
41821
+ }
41822
+ finish() {
41823
+ return this.buf.subarray(0, this.pos);
41824
+ }
41825
+ };
41260
41826
  OBJC_INIT_RECORD = ".objc_init";
41261
41827
  TABLE_INDEX_RELOCATIONS = /* @__PURE__ */ new Set([1, 2, 12, 18, 19, 24]);
41262
41828
  GUEST_DYLD_VALUES_SECTION = "peach_dyld_values";
@@ -41874,8 +42440,11 @@ function moveGuestDyldTable(map2, wasm, symbols, bindingValues = /* @__PURE__ */
41874
42440
  function guestDyldValueRange(map2) {
41875
42441
  const suffix = `:(${GUEST_DYLD_VALUES_SECTION})`;
41876
42442
  let found2;
41877
- for (const line of map2.split("\n")) {
41878
- if (!line.endsWith(suffix)) continue;
42443
+ for (let at = map2.indexOf(suffix); at !== -1; at = map2.indexOf(suffix, at + suffix.length)) {
42444
+ const lineEnd = at + suffix.length;
42445
+ if (lineEnd < map2.length && map2.charCodeAt(lineEnd) !== 10) continue;
42446
+ const lineStart = map2.lastIndexOf("\n", at) + 1;
42447
+ const line = map2.slice(lineStart, lineEnd);
41879
42448
  const match = /^\s*([\da-f]+)\s+[\da-f]+\s+([\da-f]+)\s/.exec(line);
41880
42449
  if (!match) throw new Error("unreadable dyld values map line");
41881
42450
  if (found2) throw new Error("link map has several dyld value sections");
@@ -41928,7 +42497,7 @@ var init_swift_guest_link_plan = __esm({
41928
42497
  });
41929
42498
 
41930
42499
  // src/swift-guest-manifest.ts
41931
- function selectedGuestManifestInputs(plan, selection, identities) {
42500
+ function selectedGuestManifestInputs(plan, selection, identities, readSelected) {
41932
42501
  const artifacts = new Map(plan.artifacts.map((artifact) => [artifact.path, artifact]));
41933
42502
  const archives = /* @__PURE__ */ new Map();
41934
42503
  const images = /* @__PURE__ */ new Map();
@@ -41939,19 +42508,29 @@ function selectedGuestManifestInputs(plan, selection, identities) {
41939
42508
  throw new Error(`selected input has no logical identity: ${item.artifact}`);
41940
42509
  let bytes;
41941
42510
  let memberIdentity = null;
41942
- if (item.member === null) bytes = (0, import_node_fs58.readFileSync)(item.artifact);
41943
- else {
41944
- let members2 = archives.get(item.artifact);
41945
- if (!members2) {
41946
- members2 = readArMembers((0, import_node_fs58.readFileSync)(item.artifact));
41947
- archives.set(item.artifact, members2);
42511
+ if (item.member === null) {
42512
+ bytes = readSelected ? readSelected(item) : (0, import_node_fs58.readFileSync)(item.artifact);
42513
+ } else {
42514
+ if (readSelected) {
42515
+ bytes = readSelected(item);
42516
+ } else {
42517
+ let members2 = archives.get(item.artifact);
42518
+ if (!members2) {
42519
+ members2 = /* @__PURE__ */ new Map();
42520
+ for (const member of readArMembers((0, import_node_fs58.readFileSync)(item.artifact))) {
42521
+ let list2 = members2.get(member.name);
42522
+ if (!list2) members2.set(member.name, list2 = []);
42523
+ list2.push(member.bytes);
42524
+ }
42525
+ archives.set(item.artifact, members2);
42526
+ }
42527
+ const matching2 = members2.get(item.member);
42528
+ if (!matching2 || matching2.length !== 1)
42529
+ throw new Error(
42530
+ `selected archive member is ambiguous: ${item.artifact}(${item.member})`
42531
+ );
42532
+ bytes = matching2[0];
41948
42533
  }
41949
- const matching2 = members2.filter((member) => member.name === item.member);
41950
- if (matching2.length !== 1)
41951
- throw new Error(
41952
- `selected archive member is ambiguous: ${item.artifact}(${item.member})`
41953
- );
41954
- bytes = matching2[0].bytes;
41955
42534
  const origin = artifact.memberOrigins?.get(item.member);
41956
42535
  if (artifact.memberOrigins && !origin)
41957
42536
  throw new Error(
@@ -42043,7 +42622,7 @@ var init_swift_guest_manifest = __esm({
42043
42622
  function isSwiftGuestImageManifest(value) {
42044
42623
  const uint = (value2, maximum) => typeof value2 === "number" && Number.isInteger(value2) && value2 >= 0 && value2 <= maximum;
42045
42624
  const text7 = (value2) => typeof value2 === "string" && value2.length > 0 && value2.length <= 4096 && !value2.includes("\0");
42046
- const name3 = (value2) => text7(value2) && new TextEncoder().encode(value2).length <= 16;
42625
+ const name3 = (value2) => text7(value2) && Buffer.byteLength(value2, "utf8") <= 16;
42047
42626
  const version2 = (value2) => isRecord(value2) && uint(value2.major, 65535) && uint(value2.minor, 255) && uint(value2.patch, 255);
42048
42627
  if (!isRecord(value) || value.version !== 1 || !text7(value.id) || !text7(value.installName) || value.resourceBundlePath !== void 0 && !isSwiftBundlePath(value.resourceBundlePath) || value.fileType !== "executable" && value.fileType !== "dylib" || !isRecord(value.target) || value.target.triple !== SWIFT_WASM_TRIPLE || value.target.pointerWidth !== 64 || value.target.byteOrder !== "little" || value.target.cpuType !== -1 || value.target.cpuSubtype !== 0 || typeof value.inputsSha256 !== "string" || !/^[a-f0-9]{64}$/.test(value.inputsSha256) || value.uuid !== value.inputsSha256.slice(0, 32) || !isRecord(value.buildVersion) || !uint(value.buildVersion.platform, 4294967295) || !version2(value.buildVersion.minimum) || !version2(value.buildVersion.sdk) || !Array.isArray(value.regions))
42049
42628
  return false;
@@ -42357,27 +42936,25 @@ function planGuestProjectionRegions(images, capacities, spans) {
42357
42936
  function finalizeGuestProjectionStorage(options2) {
42358
42937
  const owner = options2.owners.get(options2.projectionObject);
42359
42938
  if (owner === void 0) throw new Error("guest projection object has no image owner");
42939
+ const ranges = [];
42360
42940
  const spans = guestLinkedSpans(
42361
42941
  options2.map,
42362
42942
  options2.linked,
42363
42943
  options2.optimized,
42364
42944
  options2.owners,
42365
42945
  options2.sectionOwners,
42366
- options2.sdkSpans !== void 0
42946
+ options2.sdkSpans !== void 0,
42947
+ {
42948
+ trackedObject: options2.projectionObject,
42949
+ trackedObjectOwner: owner,
42950
+ trackedLinearSpans: ranges
42951
+ }
42367
42952
  );
42368
42953
  const images = planGuestProjectionRegions(
42369
42954
  options2.reserved.images,
42370
42955
  options2.reserved.capacities,
42371
42956
  options2.sdkSpans ? [...spans, ...options2.sdkSpans] : spans
42372
42957
  );
42373
- const ranges = guestLinkedSpans(
42374
- options2.map,
42375
- options2.linked,
42376
- options2.optimized,
42377
- /* @__PURE__ */ new Map([[options2.projectionObject, owner]]),
42378
- void 0,
42379
- options2.sdkSpans !== void 0
42380
- ).filter((span) => span.space === "linear-memory");
42381
42958
  const result = Buffer.from(options2.optimized);
42382
42959
  const data = guestWasmDataSegments(options2.optimized, options2.sdkSpans === void 0);
42383
42960
  const locations = /* @__PURE__ */ new Map();
@@ -43445,7 +44022,7 @@ function occurrences(plan, args) {
43445
44022
  throw new Error("guest plan does not match linker inputs");
43446
44023
  return found2;
43447
44024
  }
43448
- function selectedGuestLinkInputs(plan, args, whyExtract, linkTrace) {
44025
+ function selectedGuestLinkInputs(plan, args, whyExtract, linkTrace, archiveCache) {
43449
44026
  const rows = whyExtract.trimEnd().split("\n");
43450
44027
  if (rows.shift() !== "reference extracted symbol")
43451
44028
  throw new Error("invalid wasm-ld extraction report");
@@ -43460,8 +44037,38 @@ function selectedGuestLinkInputs(plan, args, whyExtract, linkTrace) {
43460
44037
  for (const file of extracted)
43461
44038
  if (!traced.has(file))
43462
44039
  throw new Error(`extracted guest input is absent from link trace ${file}`);
44040
+ const foundOccurrences = occurrences(plan, args);
44041
+ const archivePaths = /* @__PURE__ */ new Set();
44042
+ for (const { artifact } of foundOccurrences)
44043
+ if (artifact.kind === "archive") archivePaths.add(artifact.path);
44044
+ const tracedMembers = /* @__PURE__ */ new Map();
44045
+ if (archivePaths.size > 0) {
44046
+ const archivePrefixes = [...archivePaths].map(
44047
+ (archivePath) => [archivePath, `${archivePath}(`]
44048
+ );
44049
+ for (const item of traced) {
44050
+ if (!item.endsWith(")")) continue;
44051
+ const open = item.lastIndexOf("(");
44052
+ if (open > 0) {
44053
+ const archivePath = item.slice(0, open);
44054
+ if (archivePaths.has(archivePath)) {
44055
+ let list2 = tracedMembers.get(archivePath);
44056
+ if (!list2) tracedMembers.set(archivePath, list2 = []);
44057
+ list2.push(item.slice(open + 1, -1));
44058
+ continue;
44059
+ }
44060
+ }
44061
+ for (const [archivePath, prefix] of archivePrefixes) {
44062
+ if (item.startsWith(prefix)) {
44063
+ let list2 = tracedMembers.get(archivePath);
44064
+ if (!list2) tracedMembers.set(archivePath, list2 = []);
44065
+ list2.push(item.slice(prefix.length, -1));
44066
+ }
44067
+ }
44068
+ }
44069
+ }
43463
44070
  const result = [];
43464
- for (const { artifact, lazy, whole } of occurrences(plan, args)) {
44071
+ for (const { artifact, lazy, whole } of foundOccurrences) {
43465
44072
  if (artifact.kind === "object") {
43466
44073
  if (!lazy && !traced.has(artifact.path))
43467
44074
  throw new Error(`eager guest input is absent from link trace ${artifact.path}`);
@@ -43469,15 +44076,21 @@ function selectedGuestLinkInputs(plan, args, whyExtract, linkTrace) {
43469
44076
  result.push({ artifact: artifact.path, member: null });
43470
44077
  continue;
43471
44078
  }
43472
- const prefix = `${artifact.path}(`;
43473
- const names = [...traced].filter((item) => item.startsWith(prefix) && item.endsWith(")")).map((item) => item.slice(prefix.length, -1));
43474
- const members2 = readArMembers(import_node_fs61.default.readFileSync(artifact.path));
44079
+ const names = tracedMembers.get(artifact.path) ?? [];
44080
+ const nameSet = new Set(names);
44081
+ let members2 = archiveCache?.get(artifact.path);
44082
+ if (!members2) {
44083
+ members2 = readArMembers(import_node_fs61.default.readFileSync(artifact.path));
44084
+ archiveCache?.set(artifact.path, members2);
44085
+ }
44086
+ const memberCounts = /* @__PURE__ */ new Map();
43475
44087
  for (const member of members2) {
43476
- if (whole || names.includes(member.name))
44088
+ memberCounts.set(member.name, (memberCounts.get(member.name) ?? 0) + 1);
44089
+ if (whole || nameSet.has(member.name))
43477
44090
  result.push({ artifact: artifact.path, member: member.name });
43478
44091
  }
43479
44092
  for (const name3 of names)
43480
- if (members2.filter((member) => member.name === name3).length !== 1)
44093
+ if (memberCounts.get(name3) !== 1)
43481
44094
  throw new Error(
43482
44095
  `ambiguous or unsupported archive member ${artifact.path}(${name3})`
43483
44096
  );
@@ -43554,14 +44167,25 @@ function linkGuestImages(options2) {
43554
44167
  }
43555
44168
  const archives = /* @__PURE__ */ new Map();
43556
44169
  const memberBytes = /* @__PURE__ */ new Map();
44170
+ const objectBytes = /* @__PURE__ */ new Map();
43557
44171
  const artifacts = new Map(plan.artifacts.map((artifact) => [artifact.path, artifact]));
43558
44172
  const providerSymbol = "__peach_dlsym_from_image";
43559
44173
  const readSelected = (item) => {
43560
- if (item.member === null) return import_node_fs61.default.readFileSync(item.artifact);
44174
+ if (item.member === null) {
44175
+ let bytes = objectBytes.get(item.artifact);
44176
+ if (!bytes) {
44177
+ bytes = import_node_fs61.default.readFileSync(item.artifact);
44178
+ objectBytes.set(item.artifact, bytes);
44179
+ }
44180
+ return bytes;
44181
+ }
43561
44182
  let byName2 = memberBytes.get(item.artifact);
43562
44183
  if (!byName2) {
43563
- const members2 = readArMembers(import_node_fs61.default.readFileSync(item.artifact));
43564
- archives.set(item.artifact, members2);
44184
+ let members2 = archives.get(item.artifact);
44185
+ if (!members2) {
44186
+ members2 = readArMembers(import_node_fs61.default.readFileSync(item.artifact));
44187
+ archives.set(item.artifact, members2);
44188
+ }
43565
44189
  byName2 = /* @__PURE__ */ new Map();
43566
44190
  for (const member of members2)
43567
44191
  if (!byName2.has(member.name))
@@ -43585,7 +44209,13 @@ function linkGuestImages(options2) {
43585
44209
  `--why-extract=${whyPath}`,
43586
44210
  `--Map=${mapPath}`
43587
44211
  ]);
43588
- return selectedGuestLinkInputs(plan, args, import_node_fs61.default.readFileSync(whyPath, "utf8"), trace);
44212
+ return selectedGuestLinkInputs(
44213
+ plan,
44214
+ args,
44215
+ import_node_fs61.default.readFileSync(whyPath, "utf8"),
44216
+ trace,
44217
+ archives
44218
+ );
43589
44219
  };
43590
44220
  const needsProvider = (item) => {
43591
44221
  if (!artifacts.get(item.artifact).instrumentDynamicLookups) return false;
@@ -43625,7 +44255,7 @@ function linkGuestImages(options2) {
43625
44255
  )
43626
44256
  ]);
43627
44257
  const originalOwnership = identity2(plan);
43628
- const resolved = options2.resolvePlan(selected, plan);
44258
+ const resolved = options2.resolvePlan(selected, plan, readSelected);
43629
44259
  if (identity2(resolved) !== originalOwnership)
43630
44260
  throw new Error("resolved guest scopes changed input ownership");
43631
44261
  plan = resolved;
@@ -43679,6 +44309,7 @@ function linkGuestImages(options2) {
43679
44309
  }
43680
44310
  }
43681
44311
  let discoveryRegions;
44312
+ let liveSymbols;
43682
44313
  if (discoveryProjection && options2.projection) {
43683
44314
  const owners = /* @__PURE__ */ new Map([[discoveryProjection, options2.projection.image]]);
43684
44315
  for (const item of selected)
@@ -43687,10 +44318,15 @@ function linkGuestImages(options2) {
43687
44318
  selectedGuestInputImage(artifacts.get(item.artifact), item.member)
43688
44319
  );
43689
44320
  const wasm = import_node_fs61.default.readFileSync(discovery);
44321
+ liveSymbols = /* @__PURE__ */ new Set();
43690
44322
  discoveryRegions = guestProjectionRegionCounts(
43691
44323
  plan.images.length,
43692
- guestLinkedSpans(guestLinkLines(mapPath), wasm, wasm, owners)
44324
+ guestLinkedSpans(guestLinkLines(mapPath), wasm, wasm, owners, void 0, false, {
44325
+ collectSymbols: liveSymbols
44326
+ })
43693
44327
  );
44328
+ } else {
44329
+ liveSymbols = linkedMapSymbols(guestLinkLines(mapPath));
43694
44330
  }
43695
44331
  const ledger = createGuestImageLedger({
43696
44332
  images: plan.images.map((image) => ({
@@ -43699,7 +44335,7 @@ function linkGuestImages(options2) {
43699
44335
  })),
43700
44336
  callers: plan.callers,
43701
44337
  symbols: plan.symbols,
43702
- liveSymbols: linkedMapSymbols(guestLinkLines(mapPath)),
44338
+ liveSymbols,
43703
44339
  commandLineSymbols: commandLineSymbols(args),
43704
44340
  directBindings: plan.directBindings,
43705
44341
  registerAppTables: sdkCallers !== void 0,
@@ -43831,7 +44467,8 @@ function linkGuestImages(options2) {
43831
44467
  const selectedInputs = selectedGuestManifestInputs(
43832
44468
  plan,
43833
44469
  selected,
43834
- projection.identities
44470
+ projection.identities,
44471
+ readSelected
43835
44472
  );
43836
44473
  const images = projection.images.map(
43837
44474
  (image) => createGuestImageManifest({
@@ -43841,6 +44478,9 @@ function linkGuestImages(options2) {
43841
44478
  regions: []
43842
44479
  })
43843
44480
  );
44481
+ objectBytes.clear();
44482
+ memberBytes.clear();
44483
+ archives.clear();
43844
44484
  if (!discoveryRegions) throw new Error("guest projection layout object missing");
43845
44485
  const regionsBefore = discoveryRegions;
43846
44486
  const ledgerPieces = guestProjectionRegionCapacity([import_node_fs61.default.readFileSync(ledgerObject)], 0);
@@ -43934,10 +44574,47 @@ ${changed2.join("\n")}`
43934
44574
  }
43935
44575
  function linkedMapSymbols(lines) {
43936
44576
  const names = /* @__PURE__ */ new Set();
43937
- const symbol2 = /^ +\S+ +[0-9a-f]+ +[0-9a-f]+ {9,}([^\s/<]\S*)/;
43938
44577
  for (const line of lines) {
43939
- const match = symbol2.exec(line);
43940
- if (match) names.add(match[1]);
44578
+ const length = line.length;
44579
+ if (length < 15 || line.charCodeAt(0) !== 32) continue;
44580
+ let pos = 1;
44581
+ while (pos < length && line.charCodeAt(pos) === 32) pos++;
44582
+ const c1 = pos;
44583
+ while (pos < length) {
44584
+ const ch = line.charCodeAt(pos);
44585
+ if (ch === 32 || ch >= 9 && ch <= 13) break;
44586
+ pos++;
44587
+ }
44588
+ if (pos === c1 || pos >= length || line.charCodeAt(pos) !== 32) continue;
44589
+ while (pos < length && line.charCodeAt(pos) === 32) pos++;
44590
+ const c2 = pos;
44591
+ while (pos < length) {
44592
+ const ch = line.charCodeAt(pos);
44593
+ if (!(ch >= 48 && ch <= 57 || ch >= 97 && ch <= 102)) break;
44594
+ pos++;
44595
+ }
44596
+ if (pos === c2 || pos >= length || line.charCodeAt(pos) !== 32) continue;
44597
+ while (pos < length && line.charCodeAt(pos) === 32) pos++;
44598
+ const c3 = pos;
44599
+ while (pos < length) {
44600
+ const ch = line.charCodeAt(pos);
44601
+ if (!(ch >= 48 && ch <= 57 || ch >= 97 && ch <= 102)) break;
44602
+ pos++;
44603
+ }
44604
+ if (pos === c3 || pos >= length || line.charCodeAt(pos) !== 32) continue;
44605
+ const sStart = pos;
44606
+ while (pos < length && line.charCodeAt(pos) === 32) pos++;
44607
+ if (pos - sStart < 9 || pos >= length) continue;
44608
+ const first = line.charCodeAt(pos);
44609
+ if (first === 47 || first === 60 || first === 32 || first >= 9 && first <= 13)
44610
+ continue;
44611
+ let end = pos + 1;
44612
+ while (end < length) {
44613
+ const ch = line.charCodeAt(end);
44614
+ if (ch === 32 || ch >= 9 && ch <= 13) break;
44615
+ end++;
44616
+ }
44617
+ names.add(line.slice(pos, end));
43941
44618
  }
43942
44619
  return names;
43943
44620
  }
@@ -44036,7 +44713,7 @@ function discoverGuestLinkInputs(options2) {
44036
44713
  import_node_fs61.default.mkdirSync(options2.directory, { recursive: true });
44037
44714
  const why = import_node_path61.default.join(options2.directory, "preselection-why.txt");
44038
44715
  const response = import_node_path61.default.join(options2.directory, "preselection.rsp");
44039
- const output = import_node_path61.default.join(options2.directory, "preselection.wasm");
44716
+ const output = process.platform !== "win32" ? "/dev/null" : import_node_path61.default.join(options2.directory, "preselection.wasm");
44040
44717
  const flags = [
44041
44718
  ...withOutput(args, output, true),
44042
44719
  ...options2.objects,
@@ -44134,7 +44811,7 @@ function prepareGuestRuntimeInputs(options2) {
44134
44811
  });
44135
44812
  return { args, selected, originalSelection, archives, sdkProducts, archiveArtifacts };
44136
44813
  }
44137
- function selectedGuestSymbolInputs(plan, selected) {
44814
+ function selectedGuestSymbolInputs(plan, selected, readSelected) {
44138
44815
  const artifacts = new Map(plan.artifacts.map((artifact) => [artifact.path, artifact]));
44139
44816
  const archives = /* @__PURE__ */ new Map();
44140
44817
  const symbols = /* @__PURE__ */ new Set();
@@ -44150,22 +44827,27 @@ function selectedGuestSymbolInputs(plan, selected) {
44150
44827
  if (!artifact) throw new Error(`selected symbol input has no owner ${item.artifact}`);
44151
44828
  let bytes;
44152
44829
  let name3 = item.artifact;
44153
- if (item.member === null) bytes = import_node_fs61.default.readFileSync(item.artifact);
44154
- else {
44155
- let members2 = archives.get(item.artifact);
44156
- if (!members2) {
44157
- members2 = Map.groupBy(
44158
- readArMembers(import_node_fs61.default.readFileSync(item.artifact)),
44159
- (member) => member.name
44160
- );
44161
- archives.set(item.artifact, members2);
44830
+ if (item.member === null) {
44831
+ bytes = readSelected ? readSelected(item) : import_node_fs61.default.readFileSync(item.artifact);
44832
+ } else {
44833
+ if (readSelected) {
44834
+ bytes = readSelected(item);
44835
+ } else {
44836
+ let members2 = archives.get(item.artifact);
44837
+ if (!members2) {
44838
+ members2 = Map.groupBy(
44839
+ readArMembers(import_node_fs61.default.readFileSync(item.artifact)),
44840
+ (member) => member.name
44841
+ );
44842
+ archives.set(item.artifact, members2);
44843
+ }
44844
+ const matching2 = members2.get(item.member) ?? [];
44845
+ if (matching2.length !== 1)
44846
+ throw new Error(
44847
+ `ambiguous selected symbol input ${item.artifact}(${item.member})`
44848
+ );
44849
+ bytes = matching2[0].bytes;
44162
44850
  }
44163
- const matching2 = members2.get(item.member) ?? [];
44164
- if (matching2.length !== 1)
44165
- throw new Error(
44166
- `ambiguous selected symbol input ${item.artifact}(${item.member})`
44167
- );
44168
- bytes = matching2[0].bytes;
44169
44851
  name3 += `(${item.member})`;
44170
44852
  }
44171
44853
  if (owners.has(name3)) throw new Error(`duplicate selected symbol input ${name3}`);
@@ -44178,9 +44860,9 @@ function selectedGuestSymbolInputs(plan, selected) {
44178
44860
  for (const symbol2 of names.tags) tags.add(symbol2);
44179
44861
  for (const symbol2 of names.defined) {
44180
44862
  definitions.add(symbol2);
44181
- const objects = definitionObjects.get(symbol2) ?? /* @__PURE__ */ new Set();
44863
+ let objects = definitionObjects.get(symbol2);
44864
+ if (!objects) definitionObjects.set(symbol2, objects = /* @__PURE__ */ new Set());
44182
44865
  objects.add(name3);
44183
- definitionObjects.set(symbol2, objects);
44184
44866
  }
44185
44867
  }
44186
44868
  return {
@@ -44201,7 +44883,7 @@ function verifyGuestSymbolScopes(options2) {
44201
44883
  if (!symbols.length) return { bindings: [], directBindings: [] };
44202
44884
  import_node_fs61.default.mkdirSync(options2.directory, { recursive: true });
44203
44885
  const response = import_node_path61.default.join(options2.directory, "scope-trace.rsp");
44204
- const output = import_node_path61.default.join(options2.directory, "scope-trace.wasm");
44886
+ const output = process.platform !== "win32" ? "/dev/null" : import_node_path61.default.join(options2.directory, "scope-trace.wasm");
44205
44887
  const args = [
44206
44888
  ...withOutput(normalizedGuestLinkArgs(options2.args), output, true),
44207
44889
  ...options2.objects,
@@ -44219,55 +44901,76 @@ function verifyGuestSymbolScopes(options2) {
44219
44901
  import_node_fs61.default.closeSync(traceOutput);
44220
44902
  }
44221
44903
  const records = /* @__PURE__ */ new Map();
44222
- const consume = (line) => {
44223
- const match = /^(.*): (reference to|definition of) (.*)$/.exec(line);
44224
- if (!match) return;
44225
- const [, object8, kind, symbol2] = match;
44226
- if (!requested.has(symbol2)) return;
44227
- if (options2.hostImports.has(symbol2)) return;
44228
- const record6 = records.get(symbol2) ?? {
44229
- references: /* @__PURE__ */ new Map(),
44230
- providers: /* @__PURE__ */ new Map(),
44231
- physicalModule: false
44232
- };
44904
+ for (const line of guestLinkLines(tracePath)) {
44905
+ const refSep = line.lastIndexOf(": reference to ");
44906
+ const defSep = line.lastIndexOf(": definition of ");
44907
+ if (refSep < 0 && defSep < 0) continue;
44908
+ const isRef = refSep > defSep;
44909
+ const sep3 = isRef ? refSep : defSep;
44910
+ const symbol2 = line.slice(sep3 + (isRef ? 15 : 16));
44911
+ if (!requested.has(symbol2) || options2.hostImports.has(symbol2)) continue;
44912
+ let record6 = records.get(symbol2);
44913
+ if (!record6) {
44914
+ record6 = {
44915
+ references: /* @__PURE__ */ new Map(),
44916
+ providers: /* @__PURE__ */ new Map(),
44917
+ physicalModule: false
44918
+ };
44919
+ records.set(symbol2, record6);
44920
+ }
44921
+ const object8 = line.slice(0, sep3);
44233
44922
  if (object8 === "<internal>") {
44234
- if (kind === "definition of") record6.physicalModule = true;
44923
+ if (!isRef) record6.physicalModule = true;
44235
44924
  } else {
44236
44925
  const image = options2.owners.get(object8);
44237
44926
  if (image === void 0)
44238
44927
  throw new Error(`traced guest object has no owner ${object8}`);
44239
- (kind === "reference to" ? record6.references : record6.providers).set(
44240
- object8,
44241
- image
44242
- );
44928
+ (isRef ? record6.references : record6.providers).set(object8, image);
44243
44929
  }
44244
- records.set(symbol2, record6);
44245
- };
44246
- for (const line of guestLinkLines(tracePath)) consume(line);
44930
+ }
44247
44931
  const callers = new Map(options2.callers.map((caller) => [caller.image, caller.next]));
44932
+ const callerSets = new Map(
44933
+ options2.callers.map((caller) => [caller.image, new Set(caller.next)])
44934
+ );
44935
+ const rootScope = callerSets.get(0);
44248
44936
  const result = [];
44249
44937
  const directBindings = [];
44250
44938
  for (const symbol2 of symbols) {
44251
44939
  const record6 = records.get(symbol2);
44252
44940
  if (!record6 || !record6.references.size) continue;
44253
44941
  if (!record6.providers.size && options2.hostImports.has(symbol2)) continue;
44254
- const startupReferences = [...record6.references].filter(
44255
- ([object8]) => options2.startupObjects.has(object8) && options2.weakReferences.get(object8)?.has(symbol2)
44256
- );
44257
- const otherReferences = [...record6.references].filter(
44258
- ([object8]) => !startupReferences.some(([startup]) => startup === object8)
44259
- );
44942
+ const startupReferences = [];
44943
+ const otherReferences = [];
44944
+ let allWeakRefs = true;
44945
+ for (const [object8, caller] of record6.references) {
44946
+ const isWeakRef = options2.weakReferences.get(object8)?.has(symbol2) === true;
44947
+ if (!isWeakRef) allWeakRefs = false;
44948
+ if (isWeakRef && options2.startupObjects.has(object8)) {
44949
+ startupReferences.push([object8, caller]);
44950
+ } else {
44951
+ otherReferences.push([object8, caller]);
44952
+ }
44953
+ }
44260
44954
  for (const [, caller] of startupReferences)
44261
44955
  if (!callers.has(caller))
44262
44956
  throw new Error(`guest image has no caller scope ${caller}`);
44263
44957
  if (startupReferences.length && !record6.physicalModule) {
44264
- const candidates = options2.definitionObjects.get(symbol2) ?? /* @__PURE__ */ new Set();
44265
- if (candidates.size > 1 || record6.providers.size > 1)
44958
+ const candidates2 = options2.definitionObjects.get(symbol2);
44959
+ const candidateSize = candidates2?.size ?? 0;
44960
+ if (candidateSize > 1 || record6.providers.size > 1)
44266
44961
  throw new Error(`ambiguous startup provider ${symbol2}`);
44267
- if (candidates.size !== record6.providers.size || [...record6.providers.keys()].some((object8) => !candidates.has(object8)))
44268
- throw new Error(`unproven startup provider ${symbol2}`);
44962
+ let unproven = candidateSize !== record6.providers.size;
44963
+ if (!unproven && candidates2) {
44964
+ for (const object8 of record6.providers.keys()) {
44965
+ if (!candidates2.has(object8)) {
44966
+ unproven = true;
44967
+ break;
44968
+ }
44969
+ }
44970
+ }
44971
+ if (unproven) throw new Error(`unproven startup provider ${symbol2}`);
44269
44972
  if (record6.providers.size === 1) {
44270
- const [providerObject, providerImage] = [...record6.providers][0];
44973
+ const [providerObject, providerImage] = record6.providers.entries().next().value;
44271
44974
  if (options2.weakDefinitions.get(providerObject)?.has(symbol2))
44272
44975
  throw new Error(`weak startup provider ${symbol2}`);
44273
44976
  for (const [object8] of startupReferences)
@@ -44275,28 +44978,34 @@ function verifyGuestSymbolScopes(options2) {
44275
44978
  }
44276
44979
  if (!otherReferences.length) continue;
44277
44980
  }
44278
- if (!record6.providers.size && !record6.physicalModule && [...record6.references.keys()].every(
44279
- (object8) => options2.weakReferences.get(object8)?.has(symbol2)
44280
- ))
44281
- continue;
44981
+ if (!record6.providers.size && !record6.physicalModule && allWeakRefs) continue;
44282
44982
  const providerImages = new Set(record6.providers.values());
44283
- const copies = [...options2.definitionObjects.get(symbol2) ?? []].flatMap(
44284
- (object8) => {
44983
+ const candidates = options2.definitionObjects.get(symbol2);
44984
+ const copyImages = /* @__PURE__ */ new Set();
44985
+ const strongImages = /* @__PURE__ */ new Set();
44986
+ let weakDefinerImages;
44987
+ if (candidates) {
44988
+ for (const object8 of candidates) {
44285
44989
  const image = options2.owners.get(object8);
44286
- return image === void 0 ? [] : [{ image, weak: !!options2.weakDefinitions.get(object8)?.has(symbol2) }];
44990
+ if (image === void 0) continue;
44991
+ copyImages.add(image);
44992
+ if (options2.weakDefinitions.get(object8)?.has(symbol2)) {
44993
+ ;
44994
+ (weakDefinerImages ??= /* @__PURE__ */ new Set()).add(image);
44995
+ } else {
44996
+ strongImages.add(image);
44997
+ }
44287
44998
  }
44288
- );
44289
- const copyImages = new Set(copies.map((copy) => copy.image));
44290
- const strongImages = new Set(
44291
- copies.filter((copy) => !copy.weak).map((copy) => copy.image)
44292
- );
44999
+ }
44293
45000
  const interposed = !record6.physicalModule && copyImages.size > 1;
44294
45001
  const providerCount = interposed ? 1 : providerImages.size + Number(record6.physicalModule);
44295
45002
  if (!providerCount) continue;
44296
45003
  if (providerCount !== 1)
44297
45004
  throw new Error(`guest symbol has ambiguous provider ${symbol2}`);
44298
- const scopedReferences = record6.physicalModule ? [...record6.references] : otherReferences;
44299
- const uniqueProvider = strongImages.size > 1 ? void 0 : [...strongImages][0] ?? [...providerImages][0];
45005
+ const scopedReferences = record6.physicalModule ? record6.references : otherReferences;
45006
+ const firstProviderImage = providerImages.values().next().value;
45007
+ const uniqueProvider = strongImages.size > 1 ? void 0 : strongImages.values().next().value ?? firstProviderImage;
45008
+ let interposedByCaller;
44300
45009
  for (const [object8, caller] of scopedReferences) {
44301
45010
  const scope2 = callers.get(caller);
44302
45011
  if (!scope2) throw new Error(`guest image has no caller scope ${caller}`);
@@ -44304,18 +45013,35 @@ function verifyGuestSymbolScopes(options2) {
44304
45013
  result.push({ symbol: symbol2, caller, provider: { kind: "physical-module" } });
44305
45014
  continue;
44306
45015
  }
44307
- const provider = interposed ? [caller, ...scope2].find((image) => copyImages.has(image)) ?? uniqueProvider : [...providerImages][0];
45016
+ let provider;
45017
+ if (interposed) {
45018
+ if (interposedByCaller?.has(caller)) {
45019
+ provider = interposedByCaller.get(caller);
45020
+ } else {
45021
+ if (copyImages.has(caller)) {
45022
+ provider = caller;
45023
+ } else {
45024
+ for (const image of scope2) {
45025
+ if (copyImages.has(image)) {
45026
+ provider = image;
45027
+ break;
45028
+ }
45029
+ }
45030
+ if (provider === void 0) provider = uniqueProvider;
45031
+ }
45032
+ ;
45033
+ (interposedByCaller ??= /* @__PURE__ */ new Map()).set(caller, provider);
45034
+ }
45035
+ } else {
45036
+ provider = firstProviderImage;
45037
+ }
44308
45038
  if (provider === void 0) {
44309
45039
  if (options2.weakReferences.get(object8)?.has(symbol2)) continue;
44310
45040
  throw new Error(`guest scope ${caller} omits every provider of ${symbol2}`);
44311
45041
  }
44312
45042
  if (caller === provider) continue;
44313
- if ([...options2.definitionObjects.get(symbol2) ?? []].some(
44314
- (definer) => options2.owners.get(definer) === caller && options2.weakDefinitions.get(definer)?.has(symbol2)
44315
- ))
44316
- continue;
44317
- if (!scope2.includes(provider)) {
44318
- const candidates = options2.definitionObjects.get(symbol2) ?? /* @__PURE__ */ new Set();
45043
+ if (weakDefinerImages?.has(caller)) continue;
45044
+ if (!callerSets.get(caller).has(provider)) {
44319
45045
  const traced = [...record6.providers.keys()];
44320
45046
  const strongTraced = traced.filter(
44321
45047
  (definer) => !options2.weakDefinitions.get(definer)?.has(symbol2)
@@ -44323,16 +45049,17 @@ function verifyGuestSymbolScopes(options2) {
44323
45049
  const providers = strongTraced.length === 1 ? strongTraced : traced;
44324
45050
  if (options2.weakReferences.get(object8)?.has(symbol2) && !providers.some((provider2) => options2.systemProviders.has(provider2)))
44325
45051
  continue;
44326
- const equivalentCopies = providers.length === 1 && candidates.has(providers[0]) && [...candidates].every(
45052
+ const candidateSet = candidates ?? /* @__PURE__ */ new Set();
45053
+ const equivalentCopies = providers.length === 1 && candidateSet.has(providers[0]) && [...candidateSet].every(
44327
45054
  (definer) => options2.weakDefinitions.get(definer)?.has(symbol2)
44328
45055
  );
44329
- const strongCandidates = [...candidates].filter(
45056
+ const strongCandidates = [...candidateSet].filter(
44330
45057
  (definer) => !options2.weakDefinitions.get(definer)?.has(symbol2)
44331
45058
  );
44332
- const soleCandidate = candidates.size === 1 || strongCandidates.length === 1 && strongCandidates[0] === providers[0];
44333
- if (!equivalentCopies && (!soleCandidate || providers.length !== 1 || !candidates.has(providers[0]) || !(options2.systemProviders.has(providers[0]) || // a strong undefined reference binds through the process global
45059
+ const soleCandidate = candidateSet.size === 1 || strongCandidates.length === 1 && strongCandidates[0] === providers[0];
45060
+ if (!equivalentCopies && (!soleCandidate || providers.length !== 1 || !candidateSet.has(providers[0]) || !(options2.systemProviders.has(providers[0]) || // a strong undefined reference binds through the process global
44334
45061
  // scope, the root image and its dependency closure, as in elf.
44335
- provider === 0 || callers.get(0)?.includes(provider) || !options2.weakReferences.get(object8)?.has(symbol2) && options2.frameworkProviders.get(object8)?.has(providers[0]))))
45062
+ provider === 0 || rootScope?.has(provider) || !options2.weakReferences.get(object8)?.has(symbol2) && options2.frameworkProviders.get(object8)?.has(providers[0]))))
44336
45063
  throw new Error(
44337
45064
  `guest scope ${caller} omits traced provider ${provider} for ${symbol2}`
44338
45065
  );
@@ -50466,9 +51193,9 @@ async function compileGuestLink(options2) {
50466
51193
  }
50467
51194
  };
50468
51195
  },
50469
- resolvePlan: (selected, plan) => {
51196
+ resolvePlan: (selected, plan, readSelected) => {
50470
51197
  if (!prepared) throw new Error("guest runtime selection is unavailable");
50471
- const scope2 = selectedGuestSymbolInputs(plan, selected);
51198
+ const scope2 = selectedGuestSymbolInputs(plan, selected, readSelected);
50472
51199
  const owners = new Map(scope2.owners);
50473
51200
  owners.set(import_node_path72.default.join(directory2, "projection-discovery.o"), 0);
50474
51201
  const providersByImage = Map.groupBy(scope2.owners, ([, image]) => image);
@@ -58144,7 +58871,7 @@ ${wasmThreadLinkFlags.map((flag) => ` "-Xlinker", ${JSON.stringify(flag
58144
58871
  REACTOR_FLAG = '"-Xclang-linker", "-mexec-model=reactor",\n';
58145
58872
  MULTI_MANIFEST_VERSION = 76;
58146
58873
  SWIFT_HEADER_PRODUCTS_TARGET = "PeachHeaderProducts";
58147
- compilerSourceDigest = true ? "6433b1a7f6d99095c2a444c33cfbf4bc62bedbf18b40e3415e37cd83e450f0df" : swiftCompilerSourceDigest2(__sootsim_import_meta_dirname);
58874
+ compilerSourceDigest = true ? "7b91fa4405159335b5484c82700e001e4c27abf15621b724ea8af4edea693f66" : swiftCompilerSourceDigest2(__sootsim_import_meta_dirname);
58148
58875
  nativeCxxCompilerFlags = ["-fno-cxx-modules"];
58149
58876
  MODULE_MAP_RESPONSE_FILE_RUN = 16;
58150
58877
  cFlagArray = (flags) => JSON.stringify(withoutGlogModuleMap(flags));
@@ -113574,7 +114301,7 @@ function eventBindings(name3, source) {
113574
114301
  });
113575
114302
  continue;
113576
114303
  }
113577
- const call = /emitter->(\w+)\( ?\{([^}]*)\} ?\)/.exec(body);
114304
+ const call = /emitter->(\w+)\(\s*\{([^}]*)\}\s*\)/.exec(body);
113578
114305
  if (!call) throw new Error(`${name3}: unmapped event block ${property}`);
113579
114306
  const fields = [...call[2].matchAll(/\.(\w+) = ([^,]+)/g)].map(
113580
114307
  ([, field, expression]) => {
@@ -113616,18 +114343,20 @@ function configuration(name3, source) {
113616
114343
  }
113617
114344
  function arrayBindings(name3, body) {
113618
114345
  const bindings = /* @__PURE__ */ new Map();
113619
- for (const [, prop, element] of body.matchAll(
113620
- /for \(const auto &item : next\.(\w+)\) \[\w+ addObject:(.*?)\];/g
114346
+ for (const [, item, prop, variable, element] of body.matchAll(
114347
+ /for \(const auto &(\w+) : next\.(\w+)\) \[(\w+) addObject:(.*?)\];/g
113621
114348
  )) {
113622
- if (element === "RCTNSStringFromString(item)") {
113623
- bindings.set(prop, []);
114349
+ if (element === `RCTNSStringFromString(${item})`) {
114350
+ bindings.set(variable, { prop, fields: [] });
113624
114351
  continue;
113625
114352
  }
113626
114353
  const fields = [
113627
- ...element.matchAll(/@"(\w+)" ?: (RCTNSStringFromString|@)\(item\.\w+\)/g)
114354
+ ...element.matchAll(
114355
+ new RegExp(`@"(\\w+)" ?: (RCTNSStringFromString|@)\\(${item}\\.\\w+\\)`, "g")
114356
+ )
113628
114357
  ].map(([, name4, kind]) => ({ name: name4, defaultValue: kind === "@" ? 0 : "" }));
113629
114358
  if (!fields.length) throw new Error(`${name3}: unmapped array ${prop}`);
113630
- bindings.set(prop, fields);
114359
+ bindings.set(variable, { prop, fields });
113631
114360
  }
113632
114361
  return bindings;
113633
114362
  }
@@ -113647,13 +114376,17 @@ function componentViews(one, selected) {
113647
114376
  return [{ name: name3, props, commands, source, file: (0, import_node_path151.join)(folder, file) }];
113648
114377
  });
113649
114378
  }
113650
- function swiftGuestControls(one, names) {
114379
+ function swiftGuestControls(one, names, linkedGroups) {
113651
114380
  const watched = [(0, import_node_path151.join)(one, "schema.json")];
113652
114381
  const defines = /* @__PURE__ */ new Set();
113653
114382
  const views = componentViews(one, names);
113654
- const entries2 = views.map(({ name: name3, props, source, file }) => {
114383
+ const groupDefines = linkedGroups && new Set(linkedGroups.map((group) => `ONE_GROUP_${group.toUpperCase()}`));
114384
+ const entries2 = views.flatMap(({ name: name3, props, source, file }) => {
113655
114385
  const { viewClass, guard, update } = configuration(name3, source);
113656
- if (guard) defines.add(guard);
114386
+ if (guard) {
114387
+ if (groupDefines && !groupDefines.has(guard)) return [];
114388
+ defines.add(guard);
114389
+ }
113657
114390
  const arrays = arrayBindings(name3, update);
113658
114391
  const swift = (0, import_node_path151.join)((0, import_node_path151.dirname)(file), viewClass + ".swift");
113659
114392
  const declaration = (0, import_node_fs150.readFileSync)(swift, "utf8");
@@ -113675,38 +114408,41 @@ function swiftGuestControls(one, names) {
113675
114408
  }
113676
114409
  const withLabel = /^(\w+)With([A-Z])(\w*)$/.exec(first);
113677
114410
  const args = selector.map(({ label, expression }, index) => {
113678
- const fields = arrays.get(expression);
114411
+ const array9 = arrays.get(expression);
113679
114412
  let value;
113680
114413
  if (expression === "OneNativeStyleDictionary(next.swiftStyle)") value = "style";
113681
114414
  else if (expression === "boundedHeight")
113682
114415
  value = 'spec["boundedHeight"] as? Bool ?? false';
113683
114416
  else if (/^@"[^"]*"$/.test(expression)) value = expression.slice(1);
113684
- else if (fields?.length) {
113685
- const entries3 = fields.map(
113686
- ({ name: name4, defaultValue: defaultValue2 }) => `"${name4}": row["${name4}"].flatMap { $0 is NSNull ? nil : $0 } ?? ${JSON.stringify(defaultValue2)}`
114417
+ else if (array9?.fields.length) {
114418
+ const entries3 = array9.fields.map(
114419
+ ({ name: name4, defaultValue: defaultValue2 }) => `"${name4}": row["${name4}"] as? ${typeof defaultValue2 === "number" ? "Double" : "String"} ?? ${JSON.stringify(defaultValue2)}`
113687
114420
  ).join(", ");
113688
- value = `(spec["${expression}"] as? [Spec] ?? []).map { row in [${entries3}] }`;
113689
- } else if (fields) value = `spec["${expression}"] as? [String] ?? []`;
114421
+ value = `(spec["${array9.prop}"] as? [Spec] ?? []).map { row in [${entries3}] }`;
114422
+ } else if (array9) value = `spec["${array9.prop}"] as? [String] ?? []`;
113690
114423
  else {
113691
- const prop = /\bnext\.(\w+)/.exec(expression)?.[1];
114424
+ const prop = /\bnext\.(\w+)/.exec(expression)?.[1] ?? "";
113692
114425
  const types2 = {
113693
- string: 'String ?? ""',
113694
- boolean: "Bool ?? false",
113695
- Double: "Double ?? 0",
113696
- Int32: "Int ?? 0"
114426
+ string: ["String", ""],
114427
+ boolean: ["Bool", false],
114428
+ Double: ["Double", 0],
114429
+ Int32: ["Int", 0]
113697
114430
  };
113698
- const type = prop && props[prop]?.type;
114431
+ const field = props[prop];
114432
+ const type = field?.type;
113699
114433
  if (type === "ColorValue") value = `spec["${prop}"].flatMap(oneControlColor)`;
113700
- else if (type && types2[type]) value = `spec["${prop}"] as? ${types2[type]}`;
113701
- else throw new Error(`${name3}: unmapped guest argument ${expression}`);
114434
+ else if (type && types2[type]) {
114435
+ const [swiftType, implicitDefault] = types2[type];
114436
+ value = `spec["${prop}"] as? ${swiftType} ?? ${JSON.stringify(field.default ?? implicitDefault)}`;
114437
+ } else throw new Error(`${name3}: unmapped guest argument ${expression}`);
113702
114438
  }
113703
114439
  const argLabel = index ? label : withLabel ? withLabel[2].toLowerCase() + withLabel[3] : "";
113704
114440
  return argLabel ? argLabel + ": " + value : value;
113705
114441
  });
113706
114442
  const call = `view.${withLabel?.[1] ?? first}(${args.join(", ")})`;
113707
- const array8 = selector[0].expression;
114443
+ const array8 = arrays.get(selector[0].expression)?.prop;
113708
114444
  lines.push(
113709
- arrays.has(array8) ? ` if previous == nil || (spec["${array8}"] as? NSArray) != (previous?["${array8}"] as? NSArray) { ${call} }` : ` ${call}`
114445
+ array8 ? ` if previous == nil || (spec["${array8}"] as? NSArray) != (previous?["${array8}"] as? NSArray) { ${call} }` : ` ${call}`
113710
114446
  );
113711
114447
  }
113712
114448
  for (const { property, parameters, fields, event, sync } of eventBindings(
@@ -113811,14 +114547,13 @@ function excludedGroupSource(source, defines) {
113811
114547
  }
113812
114548
  return false;
113813
114549
  }
113814
- async function oneNativeControlsPackage(appRoot) {
114550
+ async function oneNativeControlsPackage(appRoot, linkedGroups) {
113815
114551
  const iosDir = resolveOneNativeAppleIosDir(appRoot);
113816
- const generated = swiftGuestControls(import_node_path152.default.dirname(iosDir), [
113817
- "OneNativeButton",
113818
- "OneNativeLabel",
113819
- "OneNativeText",
113820
- "OneNativeImage"
113821
- ]);
114552
+ const generated = swiftGuestControls(
114553
+ import_node_path152.default.dirname(iosDir),
114554
+ ["OneNativeButton", "OneNativeLabel", "OneNativeText", "OneNativeImage"],
114555
+ linkedGroups
114556
+ );
113822
114557
  const sources = {};
113823
114558
  const paths = /* @__PURE__ */ new Map();
113824
114559
  const defines = /* @__PURE__ */ new Set([...ONE_SDK_DEFINES, ...generated.defines]);
@@ -118846,7 +119581,7 @@ var init_nitro_superset = __esm({
118846
119581
  init_nitroContract();
118847
119582
  init_swift_standin_digest();
118848
119583
  NITRO_SUPERSET_ENTRY_NAME = "superset";
118849
- NITRO_COMPILER_DIGEST = true ? "aadb826ed82edbe82333b9bc9eef9ac7e3faa094f27facdbba72feb1f5e3adc6" : nitroCompilerSourceDigest(__sootsim_import_meta_dirname, STANDIN_SOURCE_DIGEST2);
119584
+ NITRO_COMPILER_DIGEST = true ? "ffe0ab1580ebcb5a184764bfb3b3650342c8644057a95423913e7078c208f318" : nitroCompilerSourceDigest(__sootsim_import_meta_dirname, STANDIN_SOURCE_DIGEST2);
118850
119585
  nitroSupersetLock = parseLock(nitro_superset_lock_default);
118851
119586
  nitroSupersetKey = (inputs2) => nativeEntryKey({ ...inputs2, compiler: NITRO_COMPILER_DIGEST });
118852
119587
  published3 = /* @__PURE__ */ new Map();