peachsim 0.1.2589 → 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 (137) 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 +1172 -446
  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-6FUOY6FX.mjs → acorn-65FNEARV.mjs} +3 -3
  27. package/dist-lib/esm-chunks/{chunk-EAIFG4MQ.mjs → chunk-2GUB5OLB.mjs} +3 -3
  28. package/dist-lib/esm-chunks/{chunk-FQQ2DMXS.mjs → chunk-462CWTWI.mjs} +1 -1
  29. package/dist-lib/esm-chunks/{chunk-L3OSVIGA.mjs → chunk-4VCRUQ36.mjs} +1178 -452
  30. package/dist-lib/esm-chunks/{chunk-5QWQDXXD.mjs → chunk-5GNGHM5B.mjs} +1 -1
  31. package/dist-lib/esm-chunks/{chunk-JLOJZF2Y.mjs → chunk-ADKUIQXX.mjs} +1 -1
  32. package/dist-lib/esm-chunks/{chunk-M4KUWGU3.mjs → chunk-BZS5SIYK.mjs} +1 -1
  33. package/dist-lib/esm-chunks/{chunk-47K4QPVA.mjs → chunk-EFKDUMB5.mjs} +1 -1
  34. package/dist-lib/esm-chunks/{chunk-I22LAVD5.mjs → chunk-GBD26EBV.mjs} +1 -1
  35. package/dist-lib/esm-chunks/{chunk-CRIYVOMB.mjs → chunk-HZTK7TP5.mjs} +1 -1
  36. package/dist-lib/esm-chunks/{chunk-5EFD2VBY.mjs → chunk-JG4AANWA.mjs} +1 -1
  37. package/dist-lib/esm-chunks/{chunk-FMWEI6OI.mjs → chunk-N2II5SRJ.mjs} +4 -4
  38. package/dist-lib/esm-chunks/{chunk-33SCXU3Y.mjs → chunk-NZY4GOG5.mjs} +1 -1
  39. package/dist-lib/esm-chunks/{chunk-KFHCRS5K.mjs → chunk-OZJ66CXY.mjs} +2 -2
  40. package/dist-lib/esm-chunks/{chunk-464CBA5U.mjs → chunk-RGC2JNCL.mjs} +1 -1
  41. package/dist-lib/esm-chunks/{chunk-57FFWABF.mjs → chunk-SLPXTLBK.mjs} +5 -5
  42. package/dist-lib/esm-chunks/{chunk-Y4PV4HZB.mjs → chunk-SRFKOU76.mjs} +1 -1
  43. package/dist-lib/esm-chunks/{chunk-3VNUC4DT.mjs → chunk-V5TTEXYO.mjs} +1 -1
  44. package/dist-lib/esm-chunks/{chunk-MKSOJCRT.mjs → chunk-WPDY5IAD.mjs} +1 -1
  45. package/dist-lib/esm-chunks/{chunk-WQ73RKJY.mjs → chunk-WYDRQRJL.mjs} +5 -5
  46. package/dist-lib/esm-chunks/{chunk-BSAAJR25.mjs → chunk-X2EKFONU.mjs} +1 -1
  47. package/dist-lib/esm-chunks/{chunk-PUBH3EXI.mjs → chunk-XE3VHAU2.mjs} +1 -1
  48. package/dist-lib/esm-chunks/{chunk-XTKKROVU.mjs → chunk-YPPH6F77.mjs} +1 -1
  49. package/dist-lib/esm-chunks/{metro-layout-parser-T5QIJTEV.mjs → metro-layout-parser-CRI3GMCM.mjs} +3 -3
  50. package/dist-lib/esm-chunks/{swift-package-prebuilt-AWTZHPDM.mjs → swift-package-prebuilt-5XDZ2HZZ.mjs} +10 -10
  51. package/dist-lib/esm-chunks/{swift-sdk-app-module-MGTJTVKU.mjs → swift-sdk-app-module-6H3G6AXD.mjs} +14 -14
  52. package/dist-lib/esm-chunks/{swift-sdk-image-JABGF3ZR.mjs → swift-sdk-image-WAC7GG2R.mjs} +14 -14
  53. package/dist-lib/esm-chunks/{swift-sdk-image-producer-RJRJ3EFU.mjs → swift-sdk-image-producer-B3L27QTG.mjs} +4 -4
  54. package/dist-lib/expo-swift-bundle.cjs +1171 -445
  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 +1200 -469
  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 +1202 -471
  93. package/dist-lib/swift-compile.cjs +1168 -442
  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/kotlin/sdk.tar.gz +0 -0
  126. package/package.json +1 -1
  127. package/src/swift-guest-compile.ts +2 -2
  128. package/src/swift-guest-dyld-table.ts +9 -2
  129. package/src/swift-guest-image-ledger.ts +403 -208
  130. package/src/swift-guest-link.ts +255 -113
  131. package/src/swift-guest-linked-spans.ts +217 -28
  132. package/src/swift-guest-manifest.ts +24 -13
  133. package/src/swift-guest-projection-storage.ts +6 -8
  134. package/src/swift-guest-projection.ts +7 -6
  135. package/src/swift-sdk-image-map.ts +137 -35
  136. package/src/swift-wasm-prune.ts +263 -85
  137. package/src/swiftGuestImageContract.ts +1 -1
@@ -1,4 +1,4 @@
1
- /*! peach v0.1.2589 | (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;
@@ -23829,24 +23829,56 @@ function layout(bytes, readData = true, requireExports = true) {
23829
23829
  const code = sections.get(10);
23830
23830
  if (code) {
23831
23831
  let pos = code[0];
23832
- let count;
23833
- [count, pos] = number(bytes, pos);
23832
+ const codeStart = code[0];
23833
+ const codeEnd = code[1];
23834
+ let count = 0;
23835
+ {
23836
+ let shift = 0;
23837
+ for (; ; ) {
23838
+ if (pos >= codeEnd || shift > 28) throw new Error("invalid wasm integer");
23839
+ const byte = bytes[pos++];
23840
+ count += (byte & 127) * 2 ** shift;
23841
+ if (!(byte & 128)) break;
23842
+ shift += 7;
23843
+ }
23844
+ }
23834
23845
  for (let i = 0; i < count; i++) {
23835
23846
  const prefix = pos;
23836
- let size2;
23837
- [size2, pos] = number(bytes, pos);
23838
- functionsByCodeOffset.set(prefix - code[0], imports2 + i);
23847
+ let size2 = 0;
23848
+ const b0 = bytes[pos++];
23849
+ if (b0 < 128) {
23850
+ size2 = b0;
23851
+ } else {
23852
+ size2 = b0 & 127;
23853
+ let shift = 7;
23854
+ for (; ; ) {
23855
+ if (pos >= codeEnd || shift > 28) throw new Error("invalid wasm integer");
23856
+ const byte = bytes[pos++];
23857
+ size2 += (byte & 127) * 2 ** shift;
23858
+ if (!(byte & 128)) break;
23859
+ shift += 7;
23860
+ }
23861
+ }
23862
+ functionsByCodeOffset.set(prefix - codeStart, imports2 + i);
23839
23863
  if (imports2 + i === startFunction) startup = bytes.subarray(pos, pos + size2);
23840
23864
  pos += size2;
23841
- if (pos > code[1]) throw new Error("invalid wasm code");
23865
+ if (pos > codeEnd) throw new Error("invalid wasm code");
23842
23866
  }
23843
- if (pos !== code[1]) throw new Error("invalid wasm code section");
23867
+ if (pos !== codeEnd) throw new Error("invalid wasm code section");
23844
23868
  }
23845
23869
  const functionsByTableSlot = /* @__PURE__ */ new Map();
23846
23870
  const elements = sections.get(9);
23847
23871
  if (elements) {
23848
23872
  let pos = elements[0];
23873
+ const elemEnd = elements[1];
23849
23874
  const read = () => {
23875
+ if (pos < elemEnd) {
23876
+ const b0 = bytes[pos];
23877
+ if (b0 < 128) {
23878
+ pos++;
23879
+ return b0;
23880
+ }
23881
+ }
23850
23882
  const [value, next] = number(bytes, pos);
23851
23883
  pos = next;
23852
23884
  return value;
@@ -23876,7 +23908,7 @@ function layout(bytes, readData = true, requireExports = true) {
23876
23908
  functionsByTableSlot.set(slot, read());
23877
23909
  }
23878
23910
  }
23879
- if (pos !== elements[1]) throw new Error("invalid wasm element section");
23911
+ if (pos !== elemEnd) throw new Error("invalid wasm element section");
23880
23912
  }
23881
23913
  const data = [];
23882
23914
  const passive = /* @__PURE__ */ new Map();
@@ -23941,36 +23973,141 @@ function guestWasmDataSegments(bytes, requireExports = true) {
23941
23973
  length: segment3.bytes.length
23942
23974
  }));
23943
23975
  }
23944
- function guestLinkedSpans(map2, before, after, owners, sectionOwners = /* @__PURE__ */ new Map(), importsLayout = false) {
23976
+ function isMapSpace(code) {
23977
+ return code === 32 || code >= 9 && code <= 13;
23978
+ }
23979
+ function isMapHex(code) {
23980
+ return code >= 48 && code <= 57 || code >= 97 && code <= 102;
23981
+ }
23982
+ function mapHexDigit(code) {
23983
+ return code <= 57 ? code - 48 : code - 87;
23984
+ }
23985
+ function* stringLines(text7) {
23986
+ let start = 0;
23987
+ for (let end = text7.indexOf("\n"); end !== -1; end = text7.indexOf("\n", start)) {
23988
+ yield text7.slice(start, end);
23989
+ start = end + 1;
23990
+ }
23991
+ yield text7.slice(start);
23992
+ }
23993
+ function guestLinkedSpans(map2, before, after, owners, sectionOwners = /* @__PURE__ */ new Map(), importsLayout = false, extra) {
23945
23994
  const unchanged = before === after;
23946
23995
  const original = layout(before, !unchanged, !importsLayout);
23947
23996
  const optimized = unchanged ? original : layout(after, true, !importsLayout);
23997
+ const collectSymbols = extra?.collectSymbols;
23998
+ const trackedObject = extra?.trackedObject;
23999
+ const trackedObjectOwner = extra?.trackedObjectOwner;
24000
+ const trackedLinearSpans = extra?.trackedLinearSpans;
24001
+ const hasSectionOwners = sectionOwners.size > 0;
23948
24002
  let codeOffset;
23949
24003
  let outputSection = "";
23950
24004
  const codeOwners = /* @__PURE__ */ new Map();
23951
24005
  const pieces = [];
23952
- for (const line of typeof map2 === "string" ? map2.split("\n") : map2) {
23953
- const match = /^\s*(\S+)\s+([\da-f]+)\s+([\da-f]+)( +)(\S.*)$/.exec(line);
23954
- if (!match) continue;
23955
- const [, address, offset, size2, indent2, source] = match;
23956
- if (address === "-" && indent2 === " ") {
23957
- outputSection = source;
23958
- if (source === "CODE") codeOffset = parseInt(offset, 16);
24006
+ const lines = typeof map2 === "string" ? stringLines(map2) : map2;
24007
+ for (const line of lines) {
24008
+ const lineLen = line.length;
24009
+ let pos = 0;
24010
+ let onlySpaces = true;
24011
+ while (pos < lineLen) {
24012
+ const ch = line.charCodeAt(pos);
24013
+ if (!isMapSpace(ch)) break;
24014
+ if (ch !== 32) onlySpaces = false;
24015
+ pos++;
24016
+ }
24017
+ const leadingSpaces = pos;
24018
+ if (pos >= lineLen) continue;
24019
+ const addrStart = pos;
24020
+ while (pos < lineLen && !isMapSpace(line.charCodeAt(pos))) pos++;
24021
+ const addrEnd = pos;
24022
+ if (pos >= lineLen) continue;
24023
+ const s1 = pos;
24024
+ while (pos < lineLen) {
24025
+ const ch = line.charCodeAt(pos);
24026
+ if (!isMapSpace(ch)) break;
24027
+ if (ch !== 32) onlySpaces = false;
24028
+ pos++;
24029
+ }
24030
+ if (pos === s1 || pos >= lineLen) continue;
24031
+ const offStart = pos;
24032
+ let offsetVal = 0;
24033
+ while (pos < lineLen && isMapHex(line.charCodeAt(pos))) {
24034
+ offsetVal = offsetVal * 16 + mapHexDigit(line.charCodeAt(pos++));
24035
+ }
24036
+ if (pos === offStart || pos >= lineLen) continue;
24037
+ const s2 = pos;
24038
+ while (pos < lineLen) {
24039
+ const ch = line.charCodeAt(pos);
24040
+ if (!isMapSpace(ch)) break;
24041
+ if (ch !== 32) onlySpaces = false;
24042
+ pos++;
24043
+ }
24044
+ if (pos === s2 || pos >= lineLen) continue;
24045
+ const sizeStart = pos;
24046
+ let sizeVal = 0;
24047
+ while (pos < lineLen && isMapHex(line.charCodeAt(pos))) {
24048
+ sizeVal = sizeVal * 16 + mapHexDigit(line.charCodeAt(pos++));
24049
+ }
24050
+ if (pos === sizeStart || pos >= lineLen) continue;
24051
+ const indentStart = pos;
24052
+ while (pos < lineLen && line.charCodeAt(pos) === 32) pos++;
24053
+ const indentLen = pos - indentStart;
24054
+ if (indentLen === 0 || pos >= lineLen) continue;
24055
+ const firstCh = line.charCodeAt(pos);
24056
+ if (isMapSpace(firstCh)) continue;
24057
+ const sourceStart = pos;
24058
+ if (collectSymbols && onlySpaces && leadingSpaces > 0 && indentLen >= 9 && firstCh !== 47 && firstCh !== 60) {
24059
+ let symEnd = sourceStart + 1;
24060
+ while (symEnd < lineLen && !isMapSpace(line.charCodeAt(symEnd))) symEnd++;
24061
+ collectSymbols.add(line.slice(sourceStart, symEnd));
24062
+ }
24063
+ const isDash = addrEnd - addrStart === 1 && line.charCodeAt(addrStart) === 45;
24064
+ if (isDash && indentLen === 1) {
24065
+ if (line.indexOf("\r", sourceStart) >= 0) continue;
24066
+ outputSection = line.slice(sourceStart);
24067
+ if (outputSection === "CODE") codeOffset = offsetVal;
23959
24068
  continue;
23960
24069
  }
23961
- const separator = source.indexOf(":(");
24070
+ if (sizeVal === 0) continue;
24071
+ const separator = line.indexOf(":(", sourceStart);
23962
24072
  if (separator < 0) continue;
23963
- const image = sectionOwners.get(source) ?? owners.get(source.slice(0, separator));
23964
- const length = parseInt(size2, 16);
23965
- if (!length) continue;
23966
- if (address !== "-") {
23967
- if (outputSection === "DATA")
23968
- pieces.push({ image, address: parseInt(address, 16), length });
24073
+ if (line.indexOf("\r", sourceStart) >= 0) continue;
24074
+ let hasLineSep = false;
24075
+ for (let i = sourceStart; i < lineLen; i++) {
24076
+ const ch = line.charCodeAt(i);
24077
+ if (ch === 8232 || ch === 8233) {
24078
+ hasLineSep = true;
24079
+ break;
24080
+ }
24081
+ }
24082
+ if (hasLineSep) continue;
24083
+ const objectPath = line.slice(sourceStart, separator);
24084
+ let image = hasSectionOwners ? sectionOwners.get(line.slice(sourceStart)) : void 0;
24085
+ if (image === void 0) image = owners.get(objectPath);
24086
+ if (!isDash) {
24087
+ if (outputSection === "DATA") {
24088
+ let addressVal = 0;
24089
+ let allHex = true;
24090
+ for (let i = addrStart; i < addrEnd; i++) {
24091
+ const ch = line.charCodeAt(i);
24092
+ if (isMapHex(ch)) addressVal = addressVal * 16 + mapHexDigit(ch);
24093
+ else {
24094
+ allHex = false;
24095
+ break;
24096
+ }
24097
+ }
24098
+ if (!allHex) addressVal = parseInt(line.slice(addrStart, addrEnd), 16);
24099
+ pieces.push({
24100
+ image,
24101
+ address: addressVal,
24102
+ length: sizeVal,
24103
+ tracked: trackedObject !== void 0 && objectPath === trackedObject
24104
+ });
24105
+ }
23969
24106
  continue;
23970
24107
  }
23971
24108
  if (image === void 0 || outputSection !== "CODE") continue;
23972
24109
  if (codeOffset === void 0) throw new Error("link map has no code section");
23973
- const index = original.functionsByCodeOffset.get(parseInt(offset, 16) - codeOffset);
24110
+ const index = original.functionsByCodeOffset.get(offsetVal - codeOffset);
23974
24111
  if (index === void 0) throw new Error("link map function has no wasm body");
23975
24112
  const existing = codeOwners.get(index);
23976
24113
  if (existing !== void 0 && existing !== image)
@@ -23979,12 +24116,23 @@ function guestLinkedSpans(map2, before, after, owners, sectionOwners = /* @__PUR
23979
24116
  }
23980
24117
  pieces.sort((a, b) => a.address - b.address);
23981
24118
  const spans = [];
23982
- for (const [index, { image, address, length }] of pieces.entries()) {
23983
- if (image === void 0) continue;
24119
+ for (let index = 0; index < pieces.length; index++) {
24120
+ const piece = pieces[index];
24121
+ const { image, address, length, tracked } = piece;
24122
+ if (image === void 0 && !tracked) continue;
23984
24123
  let next = index + 1;
23985
24124
  while (next < pieces.length && pieces[next].address < address + length) next++;
23986
24125
  const end = pieces[next]?.address ?? address + length;
23987
- spans.push({ image, space: "linear-memory", address, length: end - address });
24126
+ const spanLength = end - address;
24127
+ if (image !== void 0)
24128
+ spans.push({ image, space: "linear-memory", address, length: spanLength });
24129
+ if (tracked && trackedLinearSpans && trackedObjectOwner !== void 0)
24130
+ trackedLinearSpans.push({
24131
+ image: trackedObjectOwner,
24132
+ space: "linear-memory",
24133
+ address,
24134
+ length: spanLength
24135
+ });
23988
24136
  }
23989
24137
  const optimizedOwners = /* @__PURE__ */ new Map();
23990
24138
  const dataAt = (module2, start, length) => {
@@ -24023,7 +24171,7 @@ function guestLinkedSpans(map2, before, after, owners, sectionOwners = /* @__PUR
24023
24171
  throw new Error(`optimization changed linked data at ${span.address}`);
24024
24172
  }
24025
24173
  let previous;
24026
- for (const span of [...spans].sort((a, b) => a.address - b.address)) {
24174
+ for (const span of spans) {
24027
24175
  if (previous && span.address < previous.address + previous.length && span.image !== previous.image)
24028
24176
  throw new Error("linked data belongs to multiple images");
24029
24177
  if (!previous || span.address + span.length > previous.address + previous.length)
@@ -24205,6 +24353,20 @@ var init_swift_guest_linked_spans = __esm({
24205
24353
  });
24206
24354
 
24207
24355
  // src/swift-sdk-image-map.ts
24356
+ function isHexChar(code) {
24357
+ return code >= 48 && code <= 57 || code >= 97 && code <= 102;
24358
+ }
24359
+ function hexDigit(code) {
24360
+ return code <= 57 ? code - 48 : code - 87;
24361
+ }
24362
+ function hasLineBreak(line, from) {
24363
+ if (line.indexOf("\r", from) >= 0) return true;
24364
+ for (let i = from; i < line.length; i++) {
24365
+ const ch = line.charCodeAt(i);
24366
+ if (ch === 8232 || ch === 8233) return true;
24367
+ }
24368
+ return false;
24369
+ }
24208
24370
  function readWasmLinkMap(file, partition) {
24209
24371
  const segments = /* @__PURE__ */ new Map();
24210
24372
  const data = [];
@@ -24212,48 +24374,117 @@ function readWasmLinkMap(file, partition) {
24212
24374
  let kind = "";
24213
24375
  let segment3 = "";
24214
24376
  let previous;
24215
- const hex = (value) => value === "-" ? -1 : parseInt(value, 16);
24216
24377
  for (const line of guestLinkLines(file)) {
24217
- const symbol2 = /^ *([0-9a-f]+|-) +[0-9a-f]+ +([0-9a-f]+) {17}(\S.*)$/.exec(line);
24218
- if (symbol2) {
24219
- previous?.symbols.push({
24220
- name: symbol2[3],
24221
- address: hex(symbol2[1]),
24222
- size: parseInt(symbol2[2], 16)
24223
- });
24378
+ const length = line.length;
24379
+ let pos = 0;
24380
+ while (pos < length && line.charCodeAt(pos) === 32) pos++;
24381
+ if (pos >= length) continue;
24382
+ const leadingSpaces = pos;
24383
+ let address = -1;
24384
+ if (line.charCodeAt(pos) === 45) {
24385
+ pos++;
24386
+ } else {
24387
+ const start = pos;
24388
+ let value = 0;
24389
+ while (pos < length && isHexChar(line.charCodeAt(pos))) {
24390
+ value = value * 16 + hexDigit(line.charCodeAt(pos++));
24391
+ }
24392
+ if (pos === start) continue;
24393
+ address = value;
24394
+ }
24395
+ const s1 = pos;
24396
+ while (pos < length && line.charCodeAt(pos) === 32) pos++;
24397
+ if (pos === s1 || pos >= length) continue;
24398
+ const offStart = pos;
24399
+ let offset = 0;
24400
+ while (pos < length && isHexChar(line.charCodeAt(pos))) {
24401
+ offset = offset * 16 + hexDigit(line.charCodeAt(pos++));
24402
+ }
24403
+ if (pos === offStart) continue;
24404
+ const s2 = pos;
24405
+ while (pos < length && line.charCodeAt(pos) === 32) pos++;
24406
+ if (pos === s2 || pos >= length) continue;
24407
+ const sizeStart = pos;
24408
+ let size2 = 0;
24409
+ while (pos < length && isHexChar(line.charCodeAt(pos))) {
24410
+ size2 = size2 * 16 + hexDigit(line.charCodeAt(pos++));
24411
+ }
24412
+ if (pos === sizeStart || pos >= length) continue;
24413
+ const indentStart = pos;
24414
+ while (pos < length && line.charCodeAt(pos) === 32) pos++;
24415
+ const indent2 = pos - indentStart;
24416
+ if (indent2 === 0 || pos >= length) continue;
24417
+ if (indent2 === 17) {
24418
+ if (previous) {
24419
+ const first = line.charCodeAt(pos);
24420
+ if (first > 32 && !hasLineBreak(line, pos)) {
24421
+ previous.symbols.push({
24422
+ name: line.slice(pos),
24423
+ address,
24424
+ size: size2
24425
+ });
24426
+ }
24427
+ }
24224
24428
  continue;
24225
24429
  }
24226
- const output = /^ +- +[0-9a-f]+ +[0-9a-f]+ (\S+)$/.exec(line);
24227
- if (output) {
24228
- kind = output[1];
24430
+ if (indent2 === 1) {
24431
+ let hasWhitespace = false;
24432
+ for (let i = pos; i < length; i++) {
24433
+ const ch = line.charCodeAt(i);
24434
+ if (ch <= 32) {
24435
+ hasWhitespace = true;
24436
+ break;
24437
+ }
24438
+ }
24439
+ if (hasWhitespace) continue;
24440
+ if (address < 0 && leadingSpaces > 0) {
24441
+ kind = line.slice(pos);
24442
+ } else if (kind === "DATA" && address >= 0) {
24443
+ segment3 = line.slice(pos);
24444
+ segments.set(segment3, { address, size: size2 });
24445
+ }
24229
24446
  continue;
24230
24447
  }
24231
- if (kind === "DATA") {
24232
- const top = /^ *([0-9a-f]+) +[0-9a-f]+ +([0-9a-f]+) (\S+)$/.exec(line);
24233
- if (top) {
24234
- segment3 = top[3];
24235
- segments.set(segment3, { address: hex(top[1]), size: parseInt(top[2], 16) });
24236
- continue;
24448
+ if (indent2 === 9 && (kind === "DATA" || kind === "CODE")) {
24449
+ const first = line.charCodeAt(pos);
24450
+ if (first !== 47 && first !== 60) continue;
24451
+ if (hasLineBreak(line, pos)) continue;
24452
+ const name3 = line.slice(pos);
24453
+ let filePath = name3;
24454
+ let section2 = "";
24455
+ if (name3.charCodeAt(name3.length - 1) === 41) {
24456
+ const splitAt = name3.indexOf(":(");
24457
+ if (splitAt >= 0) {
24458
+ filePath = name3.slice(0, splitAt);
24459
+ section2 = name3.slice(splitAt + 2, -1);
24460
+ }
24461
+ }
24462
+ let objectName;
24463
+ if (filePath.charCodeAt(filePath.length - 1) === 41) {
24464
+ const open = filePath.lastIndexOf("(");
24465
+ if (open >= 0 && open + 1 < filePath.length - 1) {
24466
+ const close = filePath.indexOf(")", open + 1);
24467
+ if (close === filePath.length - 1) {
24468
+ objectName = filePath.slice(open + 1, -1);
24469
+ }
24470
+ }
24471
+ }
24472
+ if (objectName === void 0) objectName = (0, import_node_path27.basename)(filePath);
24473
+ if (objectName.startsWith("lib") && objectName.includes("__")) {
24474
+ objectName = objectName.replace(/^lib\w*?__/, "");
24237
24475
  }
24476
+ previous = {
24477
+ inputFile: filePath,
24478
+ segment: segment3,
24479
+ address,
24480
+ offset,
24481
+ size: size2,
24482
+ object: objectName,
24483
+ section: section2,
24484
+ symbols: []
24485
+ };
24486
+ (kind === "DATA" ? data : code).push(previous);
24238
24487
  }
24239
- if (kind !== "DATA" && kind !== "CODE") continue;
24240
- const input = /^ *([0-9a-f]+|-) +([0-9a-f]+) +([0-9a-f]+) {9}([/<].*)$/.exec(line);
24241
- if (!input) continue;
24242
- const name3 = input[4];
24243
- const split = /^(.*?):\((.*)\)$/s.exec(name3);
24244
- const path138 = split ? split[1] : name3;
24245
- const member = /\(([^()]+)\)$/.exec(path138);
24246
- previous = {
24247
- inputFile: path138,
24248
- segment: segment3,
24249
- address: hex(input[1]),
24250
- offset: parseInt(input[2], 16),
24251
- size: parseInt(input[3], 16),
24252
- object: (member ? member[1] : (0, import_node_path27.basename)(path138)).replace(/^lib\w*?__/, ""),
24253
- section: split ? split[2] : "",
24254
- symbols: []
24255
- };
24256
- (kind === "DATA" ? data : code).push(previous);
24257
24488
  }
24258
24489
  return { segments, data: partition ? data.flatMap(symbolPieces) : data, code };
24259
24490
  }
@@ -25399,6 +25630,7 @@ function patchSwiftrtObject(src) {
25399
25630
  return buf;
25400
25631
  }
25401
25632
  function parseWasmObjectBytes(file, buf, isDist, symbolFlagOffsets) {
25633
+ const rawBuf = Buffer.isBuffer(buf) ? buf : Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength);
25402
25634
  let pos = 8;
25403
25635
  let numImportFuncs = 0;
25404
25636
  let importsDlsym = false;
@@ -25434,10 +25666,10 @@ function parseWasmObjectBytes(file, buf, isDist, symbolFlagOffsets) {
25434
25666
  let [cnt, cp] = readULEB2(buf, p);
25435
25667
  for (let i = 0; i < cnt; i++) {
25436
25668
  const [mLen, m2] = readULEB2(buf, cp);
25437
- const mName = Buffer.from(buf.subarray(m2, m2 + mLen)).toString("utf8");
25669
+ const mName = rawBuf.toString("utf8", m2, m2 + mLen);
25438
25670
  cp = m2 + mLen;
25439
25671
  const [fLen, f2] = readULEB2(buf, cp);
25440
- const fName = Buffer.from(buf.subarray(f2, f2 + fLen)).toString("utf8");
25672
+ const fName = rawBuf.toString("utf8", f2, f2 + fLen);
25441
25673
  cp = f2 + fLen;
25442
25674
  const kind = buf[cp++];
25443
25675
  if (kind === 0) {
@@ -25517,7 +25749,7 @@ function parseWasmObjectBytes(file, buf, isDist, symbolFlagOffsets) {
25517
25749
  }
25518
25750
  } else if (id === 0) {
25519
25751
  const [nLen, np] = readULEB2(buf, p);
25520
- const name3 = Buffer.from(buf.subarray(np, np + nLen)).toString("utf8");
25752
+ const name3 = rawBuf.toString("utf8", np, np + nLen);
25521
25753
  const cp = np + nLen;
25522
25754
  if (name3 === "linking") {
25523
25755
  let [, lp] = readULEB2(buf, cp);
@@ -25530,7 +25762,7 @@ function parseWasmObjectBytes(file, buf, isDist, symbolFlagOffsets) {
25530
25762
  let cur = p2;
25531
25763
  for (let i = 0; i < cnt; i++) {
25532
25764
  const [sLen, s2] = readULEB2(buf, cur);
25533
- segNames.push(Buffer.from(buf.subarray(s2, s2 + sLen)).toString("utf8"));
25765
+ segNames.push(rawBuf.toString("utf8", s2, s2 + sLen));
25534
25766
  cur = s2 + sLen;
25535
25767
  const [, s3] = readULEB2(buf, cur);
25536
25768
  const [fl, s4] = readULEB2(buf, s3);
@@ -25570,7 +25802,7 @@ function parseWasmObjectBytes(file, buf, isDist, symbolFlagOffsets) {
25570
25802
  let sName = "";
25571
25803
  if (!isUndef || isExplicitName) {
25572
25804
  const [sLen, c4] = readULEB2(buf, cur);
25573
- sName = Buffer.from(buf.subarray(c4, c4 + sLen)).toString("utf8");
25805
+ sName = rawBuf.toString("utf8", c4, c4 + sLen);
25574
25806
  cur = c4 + sLen;
25575
25807
  } else if (kind === 0) {
25576
25808
  sName = importFuncNames[el] ?? "";
@@ -25586,7 +25818,7 @@ function parseWasmObjectBytes(file, buf, isDist, symbolFlagOffsets) {
25586
25818
  symNames.push(sName);
25587
25819
  } else if (kind === 1) {
25588
25820
  const [sLen, c3] = readULEB2(buf, cur);
25589
- const sName = Buffer.from(buf.subarray(c3, c3 + sLen)).toString("utf8");
25821
+ const sName = rawBuf.toString("utf8", c3, c3 + sLen);
25590
25822
  cur = c3 + sLen;
25591
25823
  if (!isUndef) {
25592
25824
  const [segIdx, c4] = readULEB2(buf, cur);
@@ -25701,9 +25933,21 @@ function parseWasmObjectBytes(file, buf, isDist, symbolFlagOffsets) {
25701
25933
  const offInSeg = ro - (sPayloadStarts[lo] ?? 0);
25702
25934
  let ownerSymIdx = -1;
25703
25935
  const topList = segTopSyms.get(lo);
25704
- if (topList) {
25705
- const owner = topList.find((t) => offInSeg >= t.off && offInSeg < t.end);
25706
- if (owner) ownerSymIdx = owner.symIdx;
25936
+ if (topList && topList.length > 0) {
25937
+ let tLo = 0;
25938
+ let tHi = topList.length - 1;
25939
+ while (tLo <= tHi) {
25940
+ const tMid = tLo + tHi >> 1;
25941
+ const top = topList[tMid];
25942
+ if (offInSeg < top.off) {
25943
+ tHi = tMid - 1;
25944
+ } else if (offInSeg >= top.end) {
25945
+ tLo = tMid + 1;
25946
+ } else {
25947
+ ownerSymIdx = top.symIdx;
25948
+ break;
25949
+ }
25950
+ }
25707
25951
  }
25708
25952
  if (ownerSymIdx !== -1) {
25709
25953
  let list2 = symDataRelocs.get(ownerSymIdx);
@@ -25958,54 +26202,151 @@ function localizeDefinedWasmSymbols(bytes, names) {
25958
26202
  return output;
25959
26203
  }
25960
26204
  function guestWasmSymbols(bytes) {
25961
- const object7 = parseWasmObjectBytes("", bytes, false);
26205
+ const rawBuf = Buffer.isBuffer(bytes) ? bytes : Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength);
26206
+ let cur = 8;
26207
+ const readU = () => {
26208
+ const b0 = bytes[cur++];
26209
+ if (b0 < 128) return b0;
26210
+ let res = b0 & 127;
26211
+ let shift = 7;
26212
+ while (true) {
26213
+ const byte = bytes[cur++];
26214
+ res |= (byte & 127) << shift;
26215
+ if ((byte & 128) === 0) return res;
26216
+ shift += 7;
26217
+ }
26218
+ };
26219
+ let importsDlsym = false;
26220
+ const importFuncNames = [];
26221
+ const importFuncModules = [];
26222
+ const importGlobalNames = [];
26223
+ const importTableNames = [];
26224
+ const importEventNames = [];
26225
+ const undefinedSyms = /* @__PURE__ */ new Set();
26226
+ const tags = /* @__PURE__ */ new Set();
26227
+ const globals = /* @__PURE__ */ new Set();
26228
+ const hostImports = /* @__PURE__ */ new Set();
26229
+ const weakUndefined = /* @__PURE__ */ new Set();
26230
+ const defined = /* @__PURE__ */ new Set();
26231
+ const weakDefined = /* @__PURE__ */ new Set();
26232
+ while (cur < bytes.length) {
26233
+ const id = bytes[cur++];
26234
+ const sz = readU();
26235
+ const end = cur + sz;
26236
+ if (id === 2) {
26237
+ const cnt = readU();
26238
+ for (let i = 0; i < cnt; i++) {
26239
+ const mLen = readU();
26240
+ const mName = rawBuf.toString("utf8", cur, cur + mLen);
26241
+ cur += mLen;
26242
+ const fLen = readU();
26243
+ const fName = rawBuf.toString("utf8", cur, cur + fLen);
26244
+ cur += fLen;
26245
+ const kind = bytes[cur++];
26246
+ if (kind === 0) {
26247
+ readU();
26248
+ importFuncNames.push(fName);
26249
+ importFuncModules.push(mName);
26250
+ if (mName === "env" && fName === "dlsym") importsDlsym = true;
26251
+ } else if (kind === 1) {
26252
+ cur++;
26253
+ const fl = readU();
26254
+ readU();
26255
+ if (fl & 1) readU();
26256
+ importTableNames.push(fName);
26257
+ } else if (kind === 2) {
26258
+ const fl = readU();
26259
+ readU();
26260
+ if (fl & 1) readU();
26261
+ } else if (kind === 3) {
26262
+ cur += 2;
26263
+ importGlobalNames.push(fName);
26264
+ } else if (kind === 4) {
26265
+ cur++;
26266
+ readU();
26267
+ importEventNames.push(fName);
26268
+ }
26269
+ }
26270
+ } else if (id === 0) {
26271
+ const nLen = readU();
26272
+ if (nLen === 7 && bytes[cur] === 108 && rawBuf.toString("utf8", cur, cur + nLen) === "linking") {
26273
+ cur += nLen;
26274
+ readU();
26275
+ while (cur < end) {
26276
+ const subId = bytes[cur++];
26277
+ const subLen = readU();
26278
+ const subEnd = cur + subLen;
26279
+ if (subId === 8) {
26280
+ const cnt = readU();
26281
+ for (let i = 0; i < cnt; i++) {
26282
+ const kind = bytes[cur++];
26283
+ const fl = readU();
26284
+ const isUndef = (fl & 16) !== 0;
26285
+ const isExplicitName = (fl & 64) !== 0;
26286
+ let sName = "";
26287
+ if (kind === 0 || kind === 2 || kind === 4 || kind === 5) {
26288
+ const el = readU();
26289
+ if (!isUndef || isExplicitName) {
26290
+ const sLen = readU();
26291
+ sName = rawBuf.toString("utf8", cur, cur + sLen);
26292
+ cur += sLen;
26293
+ } else if (kind === 0) {
26294
+ sName = importFuncNames[el] ?? "";
26295
+ } else if (kind === 2) {
26296
+ sName = importGlobalNames[el] ?? "";
26297
+ } else if (kind === 4) {
26298
+ sName = importEventNames[el] ?? "";
26299
+ } else if (kind === 5) {
26300
+ sName = importTableNames[el] ?? "";
26301
+ }
26302
+ if (isUndef && kind === 0 && importFuncModules[el] !== "env")
26303
+ hostImports.add(sName);
26304
+ } else if (kind === 1) {
26305
+ const sLen = readU();
26306
+ sName = rawBuf.toString("utf8", cur, cur + sLen);
26307
+ cur += sLen;
26308
+ if (!isUndef) {
26309
+ readU();
26310
+ readU();
26311
+ readU();
26312
+ }
26313
+ } else if (kind === 3) {
26314
+ readU();
26315
+ }
26316
+ if (sName) {
26317
+ if (isUndef) {
26318
+ undefinedSyms.add(sName);
26319
+ if ((fl & 19) === 17) weakUndefined.add(sName);
26320
+ } else if ((fl & 3) !== 2) {
26321
+ defined.add(sName);
26322
+ if ((fl & 19) === 1) weakDefined.add(sName);
26323
+ }
26324
+ if (kind === 4) tags.add(sName);
26325
+ else if (kind === 2 || kind === 5) globals.add(sName);
26326
+ }
26327
+ }
26328
+ break;
26329
+ }
26330
+ cur = subEnd;
26331
+ }
26332
+ break;
26333
+ }
26334
+ }
26335
+ cur = end;
26336
+ }
25962
26337
  return {
25963
- importsDlsym: object7.importsDlsym,
25964
- undefined: [
25965
- ...new Set(
25966
- object7.symNames.filter(
25967
- (name3, index) => name3 && (object7.symFlags[index] & 16) !== 0
25968
- )
25969
- )
25970
- ],
26338
+ importsDlsym,
26339
+ undefined: [...undefinedSyms],
25971
26340
  // a wasm tag is one module entity unified by name across the link, as the
25972
26341
  // main module owns it for dynamic images, so no image scope applies.
25973
- tags: [
25974
- ...new Set(
25975
- object7.symNames.filter((name3, index) => name3 && object7.symKind[index] === 4)
25976
- )
25977
- ],
25978
- globals: [
25979
- ...new Set(
25980
- object7.symNames.filter(
25981
- (name3, index) => name3 && (object7.symKind[index] === 2 || object7.symKind[index] === 5)
25982
- )
25983
- )
25984
- ],
26342
+ tags: [...tags],
26343
+ globals: [...globals],
25985
26344
  // an undefined function imported from a module other than env is supplied
25986
26345
  // by the host, whatever linker symbol names it.
25987
- hostImports: [...object7.hostImportNames],
25988
- weakUndefined: [
25989
- ...new Set(
25990
- object7.symNames.filter(
25991
- (name3, index) => name3 && (object7.symFlags[index] & 19) === 17
25992
- )
25993
- )
25994
- ],
25995
- defined: [
25996
- ...new Set(
25997
- object7.symNames.filter(
25998
- (name3, index) => name3 && (object7.symFlags[index] & 16) === 0 && (object7.symFlags[index] & 3) !== 2
25999
- )
26000
- )
26001
- ],
26002
- weakDefined: [
26003
- ...new Set(
26004
- object7.symNames.filter(
26005
- (name3, index) => name3 && (object7.symFlags[index] & 19) === 1
26006
- )
26007
- )
26008
- ]
26346
+ hostImports: [...hostImports],
26347
+ weakUndefined: [...weakUndefined],
26348
+ defined: [...defined],
26349
+ weakDefined: [...weakDefined]
26009
26350
  };
26010
26351
  }
26011
26352
  function sdkObjectName(archive, member, ordinal) {
@@ -26522,9 +26863,12 @@ function pruneSwiftWasmLink(directory2, toolchainBin, moduleRoot, staticClangTar
26522
26863
  for (const entry of waiting) tryActivateConformance(entry);
26523
26864
  }
26524
26865
  };
26866
+ const checkedProtocolTriggers = /* @__PURE__ */ new Set();
26525
26867
  const checkProtocolTrigger = (rawSymName) => {
26526
26868
  if (!rawSymName) return;
26527
26869
  const sName = rawSymName.startsWith(".Lgot.") ? rawSymName.slice(6) : rawSymName;
26870
+ if (checkedProtocolTriggers.has(sName)) return;
26871
+ checkedProtocolTriggers.add(sName);
26528
26872
  if (knownProtocols.has(sName)) {
26529
26873
  markProtocolLive(sName);
26530
26874
  return;
@@ -26557,6 +26901,43 @@ function pruneSwiftWasmLink(directory2, toolchainBin, moduleRoot, staticClangTar
26557
26901
  }
26558
26902
  }
26559
26903
  };
26904
+ const typeIndexes = /* @__PURE__ */ new Map();
26905
+ const getTypeIndex = (obj) => {
26906
+ let idx = typeIndexes.get(obj);
26907
+ if (idx) return idx;
26908
+ const mnByPrefix = /* @__PURE__ */ new Map();
26909
+ for (let i = 0; i < obj.symNames.length; i++) {
26910
+ const name3 = obj.symNames[i];
26911
+ if ((obj.symFlags[i] & 16) === 0 && name3.startsWith("$s") && name3.endsWith("Mn")) {
26912
+ const pref = name3.slice(0, -2);
26913
+ let list2 = mnByPrefix.get(pref);
26914
+ if (!list2) mnByPrefix.set(pref, list2 = []);
26915
+ list2.push(i);
26916
+ }
26917
+ }
26918
+ const objcRegByPrefix = /* @__PURE__ */ new Map();
26919
+ for (const [lf, p] of obj.objcRegisterFuncToTypePrefix) {
26920
+ let list2 = objcRegByPrefix.get(p);
26921
+ if (!list2) objcRegByPrefix.set(p, list2 = []);
26922
+ list2.push(lf);
26923
+ }
26924
+ const objcClassByPrefix = /* @__PURE__ */ new Map();
26925
+ for (const [classSym, p] of obj.objcClassSymToTypePrefix) {
26926
+ if (!classSym.startsWith("._OBJC_CLASS_")) continue;
26927
+ let list2 = objcClassByPrefix.get(p);
26928
+ if (!list2) objcClassByPrefix.set(p, list2 = []);
26929
+ list2.push(classSym.slice("._OBJC_CLASS_".length));
26930
+ }
26931
+ let minPrefLen = Infinity;
26932
+ let maxPrefLen = 0;
26933
+ for (const p of obj.typePrefixesInObj) {
26934
+ if (p.length < minPrefLen) minPrefLen = p.length;
26935
+ if (p.length > maxPrefLen) maxPrefLen = p.length;
26936
+ }
26937
+ idx = { mnByPrefix, objcRegByPrefix, objcClassByPrefix, minPrefLen, maxPrefLen };
26938
+ typeIndexes.set(obj, idx);
26939
+ return idx;
26940
+ };
26560
26941
  const markTypeLive = (obj, pref) => {
26561
26942
  const set2 = liveTypes.get(obj);
26562
26943
  if (set2.has(pref)) return;
@@ -26570,22 +26951,10 @@ function pruneSwiftWasmLink(directory2, toolchainBin, moduleRoot, staticClangTar
26570
26951
  const outer = pref.slice(0, n);
26571
26952
  if (obj.typePrefixesInObj.has(outer)) markTypeLive(obj, outer);
26572
26953
  }
26573
- const mnName = `${pref}Mn`;
26574
- for (let i = 0; i < obj.symNames.length; i++) {
26575
- if (obj.symNames[i] === mnName && (obj.symFlags[i] & 16) === 0) {
26576
- activateSymbolInObj(obj, i);
26577
- }
26578
- }
26579
- for (const [lf, p] of obj.objcRegisterFuncToTypePrefix) {
26580
- if (p === pref) {
26581
- markFuncLive(obj, lf);
26582
- }
26583
- }
26584
- for (const [classSym, p] of obj.objcClassSymToTypePrefix) {
26585
- if (p === pref && classSym.startsWith("._OBJC_CLASS_")) {
26586
- markObjCClassLive(classSym.slice("._OBJC_CLASS_".length));
26587
- }
26588
- }
26954
+ const idx = getTypeIndex(obj);
26955
+ for (const i of idx.mnByPrefix.get(pref) ?? []) activateSymbolInObj(obj, i);
26956
+ for (const lf of idx.objcRegByPrefix.get(pref) ?? []) markFuncLive(obj, lf);
26957
+ for (const cls of idx.objcClassByPrefix.get(pref) ?? []) markObjCClassLive(cls);
26589
26958
  };
26590
26959
  const checkTypeTrigger = (obj, rawSymName) => {
26591
26960
  if (!rawSymName) return;
@@ -26610,11 +26979,12 @@ function pruneSwiftWasmLink(directory2, toolchainBin, moduleRoot, staticClangTar
26610
26979
  }
26611
26980
  }
26612
26981
  }
26613
- if (obj.file.endsWith("libswiftCore__Swift.o") || obj.file.endsWith("libswift_Concurrency___Concurrency.o")) {
26614
- for (const pref of obj.typePrefixesInObj) {
26615
- if (sName.startsWith(pref)) {
26616
- markTypeLive(obj, pref);
26617
- }
26982
+ if (obj.typePrefixesInObj.size > 0 && (obj.file.endsWith("libswiftCore__Swift.o") || obj.file.endsWith("libswift_Concurrency___Concurrency.o"))) {
26983
+ const { minPrefLen, maxPrefLen } = getTypeIndex(obj);
26984
+ const hi = Math.min(sName.length, maxPrefLen);
26985
+ for (let n = minPrefLen; n <= hi; n++) {
26986
+ const cand = sName.slice(0, n);
26987
+ if (obj.typePrefixesInObj.has(cand)) markTypeLive(obj, cand);
26618
26988
  }
26619
26989
  }
26620
26990
  };
@@ -26707,7 +27077,8 @@ function pruneSwiftWasmLink(directory2, toolchainBin, moduleRoot, staticClangTar
26707
27077
  for (const fIdx of obj.rootFuncs) markFuncLive(obj, fIdx);
26708
27078
  for (const sIdx of obj.rootSegs) markSegLive(obj, sIdx);
26709
27079
  for (const name3 of obj.symNames) {
26710
- const loaded4 = name3?.match(/^_c_(\w+)__load$/)?.[1];
27080
+ if (!name3 || !name3.startsWith("_c_") || !name3.endsWith("__load")) continue;
27081
+ const loaded4 = name3.match(/^_c_(\w+)__load$/)?.[1];
26711
27082
  if (!loaded4) continue;
26712
27083
  const classSym = obj.symNames.indexOf(`._OBJC_CLASS_${loaded4}`);
26713
27084
  if (classSym !== -1 && (obj.symFlags[classSym] & 16) === 0)
@@ -26855,14 +27226,30 @@ function pruneSwiftWasmLink(directory2, toolchainBin, moduleRoot, staticClangTar
26855
27226
  const keepObjCClassesNamedInSegment = (obj, segIdx) => {
26856
27227
  const range3 = obj.segPayloadRanges[segIdx];
26857
27228
  if (!range3) return;
27229
+ const [rangeStart, rangeEnd] = range3;
27230
+ if (rangeEnd - rangeStart < 4) return;
26858
27231
  let bytes = objectBytes.get(obj);
26859
27232
  if (!bytes) objectBytes.set(obj, bytes = import_node_fs29.default.readFileSync(obj.file));
26860
- const text7 = bytes.toString("latin1", range3[0], range3[1]);
26861
- for (const match of text7.matchAll(/So(\d+)/g)) {
26862
- const start = match.index + 2 + match[1].length;
26863
- const length = Number(match[1]);
26864
- if (text7[start + length] !== "C") continue;
26865
- const symbol2 = `._OBJC_CLASS_${text7.slice(start, start + length)}`;
27233
+ let pos = rangeStart;
27234
+ while (pos < rangeEnd - 3) {
27235
+ const at = bytes.indexOf("So", pos);
27236
+ if (at < 0 || at >= rangeEnd - 2) break;
27237
+ let digitEnd = at + 2;
27238
+ let length = 0;
27239
+ while (digitEnd < rangeEnd) {
27240
+ const ch = bytes[digitEnd];
27241
+ if (ch < 48 || ch > 57) break;
27242
+ length = length * 10 + (ch - 48);
27243
+ digitEnd++;
27244
+ }
27245
+ if (digitEnd === at + 2) {
27246
+ pos = at + 2;
27247
+ continue;
27248
+ }
27249
+ pos = digitEnd;
27250
+ const nameEnd = digitEnd + length;
27251
+ if (nameEnd >= rangeEnd || bytes[nameEnd] !== 67) continue;
27252
+ const symbol2 = `._OBJC_CLASS_${bytes.toString("latin1", digitEnd, nameEnd)}`;
26866
27253
  for (const provider of lazyProviders.get(symbol2) ?? []) {
26867
27254
  eagerDynamicObjects.add(provider);
26868
27255
  extractObject(provider);
@@ -27839,6 +28226,10 @@ var init_nativeDyldTableContract = __esm({
27839
28226
 
27840
28227
  // src/swift-guest-image-ledger.ts
27841
28228
  function readNumber(bytes, position) {
28229
+ if (position < bytes.length) {
28230
+ const first = bytes[position];
28231
+ if (first < 128) return [first, position + 1];
28232
+ }
27842
28233
  let value = 0;
27843
28234
  let shift = 0;
27844
28235
  for (; ; ) {
@@ -27850,6 +28241,7 @@ function readNumber(bytes, position) {
27850
28241
  }
27851
28242
  }
27852
28243
  function encodeNumber(value) {
28244
+ if (value < 128) return Buffer.from([value]);
27853
28245
  const bytes = [];
27854
28246
  do {
27855
28247
  let byte = value % 128;
@@ -27871,6 +28263,9 @@ function encodedString(value) {
27871
28263
  const bytes = Buffer.from(value);
27872
28264
  return Buffer.concat([encodeNumber(bytes.length), bytes]);
27873
28265
  }
28266
+ function isWasmMagic(bytes) {
28267
+ 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;
28268
+ }
27874
28269
  function llvmType(value) {
27875
28270
  switch (value) {
27876
28271
  case 127:
@@ -27886,11 +28281,12 @@ function llvmType(value) {
27886
28281
  }
27887
28282
  }
27888
28283
  function rewriteObject(bytes, names, callerAlias, binding, instrumentDynamicLookups, preserveCanonical, options2 = {}) {
27889
- if (Buffer.from(bytes.subarray(0, 8)).toString("hex") !== "0061736d01000000")
27890
- throw new Error("expected wasm object");
28284
+ if (!isWasmMagic(bytes)) throw new Error("expected wasm object");
28285
+ const rawBuf = Buffer.isBuffer(bytes) ? bytes : Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength);
27891
28286
  const { sdkLookupOnly, sdkProduct } = options2;
27892
28287
  const comdatScope = sdkProduct === void 0 ? callerAlias : `${callerAlias}:${sdkProduct}`;
27893
- const sections = binding ? [Buffer.from(bytes.subarray(0, 8))] : void 0;
28288
+ const rewrite = binding !== void 0;
28289
+ const sections = rewrite ? [bytes.subarray(0, 8)] : void 0;
27894
28290
  const types2 = [];
27895
28291
  const functionTypes = [];
27896
28292
  const definitions = [];
@@ -27904,45 +28300,74 @@ function rewriteObject(bytes, names, callerAlias, binding, instrumentDynamicLook
27904
28300
  const usedSymbols = /* @__PURE__ */ new Set();
27905
28301
  let position = 8;
27906
28302
  while (position < bytes.length) {
28303
+ const headerStart2 = position;
27907
28304
  const id = bytes[position++];
27908
- const [size2, start] = readNumber(bytes, position);
28305
+ let size2 = 0;
28306
+ if (position < bytes.length && bytes[position] < 128) {
28307
+ size2 = bytes[position++];
28308
+ } else {
28309
+ const [val, next] = readNumber(bytes, position);
28310
+ size2 = val;
28311
+ position = next;
28312
+ }
28313
+ const start = position;
27909
28314
  const end = start + size2;
27910
28315
  if (end > bytes.length) throw new Error("invalid wasm section");
27911
28316
  position = end;
27912
- if (!sections && id > 3) continue;
27913
- let section2 = Buffer.from(bytes.buffer, bytes.byteOffset + start, size2);
27914
- let offset = 0;
28317
+ if (id > 3) {
28318
+ if (sections) sections.push(bytes.subarray(headerStart2, end));
28319
+ continue;
28320
+ }
28321
+ let offset = start;
27915
28322
  const number3 = () => {
27916
- const [value, next] = readNumber(section2, offset);
27917
- offset = next;
27918
- return value;
28323
+ if (offset < end) {
28324
+ const first = bytes[offset];
28325
+ if (first < 128) {
28326
+ offset++;
28327
+ return first;
28328
+ }
28329
+ }
28330
+ let value = 0;
28331
+ let shift = 0;
28332
+ for (; ; ) {
28333
+ if (offset >= end || shift > 63) throw new Error("invalid wasm integer");
28334
+ const byte = bytes[offset++];
28335
+ value += (byte & 127) * 2 ** shift;
28336
+ if (!(byte & 128)) return value;
28337
+ shift += 7;
28338
+ }
27919
28339
  };
27920
28340
  const string7 = () => {
27921
- const [value, next] = readString(section2, offset);
27922
- offset = next;
28341
+ const length = number3();
28342
+ const strEnd = offset + length;
28343
+ if (strEnd > end) throw new Error("invalid wasm string");
28344
+ const value = rawBuf.toString("utf8", offset, strEnd);
28345
+ offset = strEnd;
27923
28346
  return value;
27924
28347
  };
28348
+ let rewrittenSection;
27925
28349
  if (id === 1) {
27926
28350
  const count = number3();
27927
28351
  for (let i = 0; i < count; i++) {
27928
- if (section2[offset++] !== 96) throw new Error("unsupported wasm type");
28352
+ if (bytes[offset++] !== 96) throw new Error("unsupported wasm type");
27929
28353
  const parameterCount = number3();
27930
- const parameters = [...section2.subarray(offset, offset + parameterCount)];
27931
- if (parameterCount !== parameters.length) throw new Error("invalid wasm type");
27932
- offset += parameterCount;
28354
+ if (offset + parameterCount > end) throw new Error("invalid wasm type");
28355
+ const parameters = new Array(parameterCount);
28356
+ for (let p = 0; p < parameterCount; p++) parameters[p] = bytes[offset++];
27933
28357
  const resultCount = number3();
27934
- const results = [...section2.subarray(offset, offset + resultCount)];
27935
- if (results.length !== resultCount) throw new Error("invalid wasm type");
27936
- offset += resultCount;
28358
+ if (offset + resultCount > end) throw new Error("invalid wasm type");
28359
+ const results = new Array(resultCount);
28360
+ for (let r = 0; r < resultCount; r++) results[r] = bytes[offset++];
27937
28361
  types2.push({ parameters, results });
27938
28362
  }
27939
28363
  } else if (id === 2) {
27940
28364
  const count = number3();
27941
- const imports2 = sections ? [encodeNumber(count)] : void 0;
28365
+ const importWriter = rewrite ? new ByteWriter(size2 + 64) : void 0;
28366
+ importWriter?.uleb(count);
27942
28367
  for (let i = 0; i < count; i++) {
27943
28368
  const module2 = string7();
27944
28369
  const name3 = string7();
27945
- const kind = section2[offset++];
28370
+ const kind = bytes[offset++];
27946
28371
  const typeStart = offset;
27947
28372
  let functionType2 = -1;
27948
28373
  if (kind === 0) {
@@ -27950,7 +28375,7 @@ function rewriteObject(bytes, names, callerAlias, binding, instrumentDynamicLook
27950
28375
  functionTypes.push(functionType2);
27951
28376
  functionImportNames.push(name3);
27952
28377
  } else if (kind === 1) {
27953
- const referenceType = section2[offset++];
28378
+ const referenceType = bytes[offset++];
27954
28379
  if (referenceType !== 112 && referenceType !== 111)
27955
28380
  throw new Error("unsupported table type");
27956
28381
  const flags = number3();
@@ -27969,11 +28394,15 @@ function rewriteObject(bytes, names, callerAlias, binding, instrumentDynamicLook
27969
28394
  } else throw new Error("unsupported wasm import");
27970
28395
  const isDlsym = instrumentDynamicLookups && module2 === "env" && name3 === "dlsym" && kind === 0;
27971
28396
  const isDlerror = instrumentDynamicLookups && module2 === "env" && name3 === "dlerror" && kind === 0;
27972
- if (module2 === "env" && names.has(name3)) usedSymbols.add(name3);
27973
- if (module2 === "env" && kind === 0 && names.has(name3)) {
27974
- const type = types2[functionType2];
27975
- if (!type) throw new Error(`missing import type for ${name3}`);
27976
- functionImports.set(name3, type);
28397
+ if (!rewrite) {
28398
+ if (module2 === "env" && names.has(name3)) {
28399
+ usedSymbols.add(name3);
28400
+ if (kind === 0) {
28401
+ const type = types2[functionType2];
28402
+ if (!type) throw new Error(`missing import type for ${name3}`);
28403
+ functionImports.set(name3, type);
28404
+ }
28405
+ }
27977
28406
  }
27978
28407
  if (isDlsym || isDlerror) {
27979
28408
  const type = types2[functionType2];
@@ -27983,17 +28412,17 @@ function rewriteObject(bytes, names, callerAlias, binding, instrumentDynamicLook
27983
28412
  }
27984
28413
  if (isDlsym) usesDlsym = true;
27985
28414
  if (isDlerror) usesDlerror = true;
27986
- imports2?.push(
27987
- encodedString(module2),
27988
- encodedString(
27989
- isDlsym ? callerAlias : isDlerror ? dlerrorAlias : module2 === "env" && name3 !== "dlsym" && name3 !== "dlerror" ? binding?.(name3) ?? name3 : name3
27990
- ),
27991
- Buffer.from([kind]),
27992
- section2.subarray(typeStart, offset)
27993
- );
28415
+ if (importWriter && binding) {
28416
+ importWriter.string(module2);
28417
+ importWriter.string(
28418
+ isDlsym ? callerAlias : isDlerror ? dlerrorAlias : module2 === "env" && name3 !== "dlsym" && name3 !== "dlerror" ? binding(name3) ?? name3 : name3
28419
+ );
28420
+ importWriter.byte(kind);
28421
+ importWriter.bytes(bytes, typeStart, offset);
28422
+ }
27994
28423
  }
27995
- if (offset !== section2.length) throw new Error("invalid wasm import section");
27996
- if (imports2) section2 = Buffer.concat(imports2);
28424
+ if (offset !== end) throw new Error("invalid wasm import section");
28425
+ if (importWriter) rewrittenSection = importWriter.finish();
27997
28426
  } else if (id === 3) {
27998
28427
  const count = number3();
27999
28428
  for (let i = 0; i < count; i++) functionTypes.push(number3());
@@ -28002,43 +28431,40 @@ function rewriteObject(bytes, names, callerAlias, binding, instrumentDynamicLook
28002
28431
  if (sectionName === "linking") {
28003
28432
  const version2 = number3();
28004
28433
  if (version2 !== 2) throw new Error("unsupported wasm linking version");
28005
- const subsections = [];
28434
+ const subsections = rewrite ? [] : void 0;
28006
28435
  let objcLoader;
28007
- while (offset < section2.length) {
28008
- const kind = section2[offset++];
28436
+ while (offset < end) {
28437
+ const kind = bytes[offset++];
28009
28438
  const length = number3();
28010
28439
  const stop = offset + length;
28011
- if (stop > section2.length) throw new Error("invalid linking subsection");
28012
- let content = section2.subarray(offset, stop);
28013
- if (kind === 7 && !sdkLookupOnly) {
28014
- const groups = [];
28440
+ if (stop > end) throw new Error("invalid linking subsection");
28441
+ const contentStart = offset;
28442
+ if (kind === 7 && rewrite && !sdkLookupOnly) {
28443
+ const comdatWriter = new ByteWriter(length + 64);
28015
28444
  const count = number3();
28016
- groups.push(encodeNumber(count));
28445
+ comdatWriter.uleb(count);
28017
28446
  for (let i = 0; i < count; i++) {
28018
28447
  const group = string7();
28019
28448
  const begin = offset;
28020
28449
  number3();
28021
28450
  const members2 = number3();
28022
28451
  for (let member = 0; member < members2 * 2; member++) number3();
28023
- groups.push(
28024
- encodedString(
28025
- group === OBJC_INIT_RECORD ? group : `${comdatScope}:${group}`
28026
- ),
28027
- section2.subarray(begin, offset)
28452
+ comdatWriter.string(
28453
+ group === OBJC_INIT_RECORD ? group : `${comdatScope}:${group}`
28028
28454
  );
28455
+ comdatWriter.bytes(bytes, begin, offset);
28029
28456
  }
28030
28457
  if (offset !== stop) throw new Error("invalid comdat subsection");
28031
- content = Buffer.concat(groups);
28032
- }
28033
- if (kind === 8) {
28034
- const entries2 = [];
28035
- const extraEntries = [];
28458
+ const buf = comdatWriter.finish();
28459
+ subsections.push({ kind, parts: [buf], byteLength: buf.length });
28460
+ } else if (kind === 8) {
28461
+ const entryWriter = rewrite ? new ByteWriter(length + 128) : void 0;
28462
+ let extraWriter;
28036
28463
  const count = number3();
28037
- entries2.push(encodeNumber(count));
28038
28464
  let added = 0;
28039
28465
  for (let i = 0; i < count; i++) {
28040
28466
  const begin = offset;
28041
- const symbolKind = section2[offset++];
28467
+ const symbolKind = bytes[offset++];
28042
28468
  const flags = number3();
28043
28469
  const flagsEnd = offset;
28044
28470
  let index = -1;
@@ -28066,25 +28492,43 @@ function rewriteObject(bytes, names, callerAlias, binding, instrumentDynamicLook
28066
28492
  }
28067
28493
  } else if (symbolKind === 3) number3();
28068
28494
  else throw new Error("unsupported wasm symbol kind");
28069
- if (symbolKind === 0)
28495
+ if (!rewrite && symbolKind === 0)
28070
28496
  functionSymbols[i] = name3 || functionImportNames[index];
28071
- if (!sdkLookupOnly && name3 === OBJC_LOAD_FUNCTION && symbolKind === 0 && !(flags & 16)) {
28497
+ if (rewrite && !sdkLookupOnly && name3 === OBJC_LOAD_FUNCTION && symbolKind === 0 && !(flags & 16)) {
28072
28498
  objcLoader = i;
28073
28499
  }
28074
28500
  const alias = names.get(name3);
28075
- if (flags & 16 && symbolKind === 1 && alias) usedSymbols.add(name3);
28076
- if ((name3 === "dlsym" && usesDlsym || name3 === "dlerror" && usesDlerror) && flags & 16 && flags & 64 && symbolKind === 0) {
28077
- entries2.push(
28078
- section2.subarray(begin, nameStart),
28079
- encodedString(name3 === "dlsym" ? callerAlias : dlerrorAlias),
28080
- section2.subarray(nameEnd, offset)
28081
- );
28082
- } else if (flags & 16 && name3 !== "dlsym" && name3 !== "dlerror" && binding?.(name3) !== void 0) {
28083
- entries2.push(
28084
- section2.subarray(begin, nameStart),
28085
- encodedString(binding(name3)),
28086
- section2.subarray(nameEnd, offset)
28087
- );
28501
+ if (!rewrite && flags & 16 && symbolKind === 1 && alias)
28502
+ usedSymbols.add(name3);
28503
+ if (entryWriter && binding) {
28504
+ if ((name3 === "dlsym" && usesDlsym || name3 === "dlerror" && usesDlerror) && flags & 16 && flags & 64 && symbolKind === 0) {
28505
+ entryWriter.bytes(bytes, begin, nameStart);
28506
+ entryWriter.string(name3 === "dlsym" ? callerAlias : dlerrorAlias);
28507
+ entryWriter.bytes(bytes, nameEnd, offset);
28508
+ } else if (flags & 16 && name3 !== "dlsym" && name3 !== "dlerror" && binding(name3) !== void 0) {
28509
+ entryWriter.bytes(bytes, begin, nameStart);
28510
+ entryWriter.string(binding(name3));
28511
+ entryWriter.bytes(bytes, nameEnd, offset);
28512
+ } else if (alias && !(flags & 16) && (flags & 3) !== 2) {
28513
+ if (symbolKind !== 0 && symbolKind !== 1)
28514
+ throw new Error(`unsupported symbol ${name3}`);
28515
+ if (preserveCanonical.has(name3)) {
28516
+ entryWriter.bytes(bytes, begin, offset);
28517
+ extraWriter ??= new ByteWriter(256);
28518
+ extraWriter.byte(bytes[begin]);
28519
+ extraWriter.uleb(flags & ~32);
28520
+ extraWriter.bytes(bytes, flagsEnd, nameStart);
28521
+ extraWriter.string(alias);
28522
+ extraWriter.bytes(bytes, nameEnd, offset);
28523
+ added++;
28524
+ } else {
28525
+ entryWriter.bytes(bytes, begin, nameStart);
28526
+ entryWriter.string(alias);
28527
+ entryWriter.bytes(bytes, nameEnd, offset);
28528
+ }
28529
+ } else {
28530
+ entryWriter.bytes(bytes, begin, offset);
28531
+ }
28088
28532
  } else if (alias && !(flags & 16) && (flags & 3) !== 2) {
28089
28533
  if (symbolKind !== 0 && symbolKind !== 1)
28090
28534
  throw new Error(`unsupported symbol ${name3}`);
@@ -28098,63 +28542,73 @@ function rewriteObject(bytes, names, callerAlias, binding, instrumentDynamicLook
28098
28542
  hidden: (flags & 4) !== 0,
28099
28543
  type
28100
28544
  });
28101
- if (preserveCanonical.has(name3)) {
28102
- entries2.push(section2.subarray(begin, offset));
28103
- extraEntries.push(
28104
- section2.subarray(begin, begin + 1),
28105
- encodeNumber(flags & ~32),
28106
- section2.subarray(flagsEnd, nameStart),
28107
- encodedString(alias),
28108
- section2.subarray(nameEnd, offset)
28109
- );
28110
- added++;
28111
- } else {
28112
- entries2.push(
28113
- section2.subarray(begin, nameStart),
28114
- encodedString(alias),
28115
- section2.subarray(nameEnd, offset)
28116
- );
28117
- }
28118
- } else entries2.push(section2.subarray(begin, offset));
28545
+ }
28119
28546
  }
28120
28547
  if (offset !== stop) throw new Error("invalid symbol subsection");
28121
- entries2[0] = encodeNumber(count + added);
28122
- content = Buffer.concat([...entries2, ...extraEntries]);
28548
+ if (entryWriter) {
28549
+ const countBytes = encodeNumber(count + added);
28550
+ const entryBuf = entryWriter.finish();
28551
+ if (extraWriter) {
28552
+ const extraBuf = extraWriter.finish();
28553
+ subsections.push({
28554
+ kind,
28555
+ parts: [countBytes, entryBuf, extraBuf],
28556
+ byteLength: countBytes.length + entryBuf.length + extraBuf.length
28557
+ });
28558
+ } else {
28559
+ subsections.push({
28560
+ kind,
28561
+ parts: [countBytes, entryBuf],
28562
+ byteLength: countBytes.length + entryBuf.length
28563
+ });
28564
+ }
28565
+ }
28566
+ } else if (subsections) {
28567
+ subsections.push({
28568
+ kind,
28569
+ parts: [bytes.subarray(contentStart, stop)],
28570
+ byteLength: length
28571
+ });
28123
28572
  }
28124
28573
  offset = stop;
28125
- subsections.push({ kind, content });
28126
- }
28127
- const parts = [encodedString(sectionName), encodeNumber(version2)];
28128
- for (const subsection of subsections) {
28129
- let content = subsection.content;
28130
- if (subsection.kind === 6 && objcLoader !== void 0) {
28131
- const [count, entriesStart] = readNumber(content, 0);
28132
- const entries2 = [content.subarray(0, entriesStart)];
28133
- let entryStart = entriesStart;
28134
- for (let i = 0; i < count; i++) {
28135
- const [, symbolStart] = readNumber(content, entryStart);
28136
- const [symbol2, entryEnd] = readNumber(content, symbolStart);
28137
- if (symbol2 === objcLoader) entries2.push(encodeNumber(1));
28138
- entries2.push(
28139
- content.subarray(
28140
- symbol2 === objcLoader ? symbolStart : entryStart,
28141
- entryEnd
28142
- )
28143
- );
28144
- entryStart = entryEnd;
28574
+ }
28575
+ if (subsections) {
28576
+ const linkingWriter = new ByteWriter(size2 + 128);
28577
+ linkingWriter.string(sectionName);
28578
+ linkingWriter.uleb(version2);
28579
+ for (const subsection of subsections) {
28580
+ if (subsection.kind === 6 && objcLoader !== void 0) {
28581
+ const content = subsection.parts[0];
28582
+ const [count, entriesStart] = readNumber(content, 0);
28583
+ const initWriter = new ByteWriter(content.length + 16);
28584
+ initWriter.bytes(content, 0, entriesStart);
28585
+ let entryStart = entriesStart;
28586
+ for (let i = 0; i < count; i++) {
28587
+ const [, symbolStart] = readNumber(content, entryStart);
28588
+ const [symbol2, entryEnd] = readNumber(content, symbolStart);
28589
+ if (symbol2 === objcLoader) {
28590
+ initWriter.uleb(1);
28591
+ initWriter.bytes(content, symbolStart, entryEnd);
28592
+ } else {
28593
+ initWriter.bytes(content, entryStart, entryEnd);
28594
+ }
28595
+ entryStart = entryEnd;
28596
+ }
28597
+ if (entryStart !== content.length)
28598
+ throw new Error("invalid init functions subsection");
28599
+ const initBuf = initWriter.finish();
28600
+ linkingWriter.byte(subsection.kind);
28601
+ linkingWriter.uleb(initBuf.length);
28602
+ linkingWriter.bytes(initBuf);
28603
+ } else {
28604
+ linkingWriter.byte(subsection.kind);
28605
+ linkingWriter.uleb(subsection.byteLength);
28606
+ for (const part of subsection.parts) linkingWriter.bytes(part);
28145
28607
  }
28146
- if (entryStart !== content.length)
28147
- throw new Error("invalid init functions subsection");
28148
- content = Buffer.concat(entries2);
28149
28608
  }
28150
- parts.push(
28151
- Buffer.from([subsection.kind]),
28152
- encodeNumber(content.length),
28153
- content
28154
- );
28609
+ rewrittenSection = linkingWriter.finish();
28155
28610
  }
28156
- section2 = Buffer.concat(parts);
28157
- } else if (!sections && sectionName.startsWith("reloc.")) {
28611
+ } else if (!rewrite && sectionName.startsWith("reloc.")) {
28158
28612
  number3();
28159
28613
  for (let count = number3(); count > 0; count--) {
28160
28614
  const type = number3();
@@ -28164,18 +28618,27 @@ function rewriteObject(bytes, names, callerAlias, binding, instrumentDynamicLook
28164
28618
  if (name3 !== void 0 && TABLE_INDEX_RELOCATIONS.has(type))
28165
28619
  addressTaken.add(name3);
28166
28620
  }
28167
- if (offset !== section2.length)
28168
- throw new Error(`invalid relocation section ${sectionName}`);
28621
+ if (offset !== end) throw new Error(`invalid relocation section ${sectionName}`);
28622
+ }
28623
+ }
28624
+ if (sections) {
28625
+ if (rewrittenSection) {
28626
+ sections.push(
28627
+ Buffer.from([id]),
28628
+ encodeNumber(rewrittenSection.length),
28629
+ rewrittenSection
28630
+ );
28631
+ } else {
28632
+ sections.push(bytes.subarray(headerStart2, end));
28169
28633
  }
28170
28634
  }
28171
- sections?.push(Buffer.from([id]), encodeNumber(section2.length), section2);
28172
28635
  }
28173
28636
  return {
28174
28637
  bytes: sections ? Buffer.concat(sections) : bytes,
28175
28638
  definitions,
28176
28639
  functionImports,
28177
28640
  usesDlsym,
28178
- usedSymbols: [...usedSymbols],
28641
+ usedSymbols,
28179
28642
  addressTaken: [...addressTaken]
28180
28643
  };
28181
28644
  }
@@ -28264,36 +28727,51 @@ function createGuestImageLedger(input) {
28264
28727
  }
28265
28728
  }
28266
28729
  }
28267
- const nameBytes = /* @__PURE__ */ new Map();
28268
- for (const definition2 of definitions)
28269
- if (!nameBytes.has(definition2.name))
28270
- nameBytes.set(definition2.name, Buffer.from(definition2.name));
28271
- definitions.sort(
28272
- (a, b) => Buffer.compare(nameBytes.get(a.name), nameBytes.get(b.name)) || a.image - b.image
28273
- );
28730
+ let hasNonAscii = false;
28731
+ for (const definition2 of definitions) {
28732
+ const s = definition2.name;
28733
+ for (let i = 0; i < s.length; i++) {
28734
+ if (s.charCodeAt(i) > 127) {
28735
+ hasNonAscii = true;
28736
+ break;
28737
+ }
28738
+ }
28739
+ if (hasNonAscii) break;
28740
+ }
28741
+ if (hasNonAscii) {
28742
+ const nameBytes = /* @__PURE__ */ new Map();
28743
+ for (const definition2 of definitions)
28744
+ if (!nameBytes.has(definition2.name))
28745
+ nameBytes.set(definition2.name, Buffer.from(definition2.name));
28746
+ definitions.sort(
28747
+ (a, b) => Buffer.compare(nameBytes.get(a.name), nameBytes.get(b.name)) || a.image - b.image
28748
+ );
28749
+ } else {
28750
+ definitions.sort(
28751
+ (a, b) => a.name < b.name ? -1 : a.name > b.name ? 1 : a.image - b.image
28752
+ );
28753
+ }
28274
28754
  const preserveCanonical = /* @__PURE__ */ new Set();
28275
28755
  const definitionsByName = Map.groupBy(definitions, (definition2) => definition2.name);
28276
- for (const name3 of input.symbols) {
28756
+ if (symbolIndices.has("__cxa_throw")) {
28757
+ const name3 = "__cxa_throw";
28277
28758
  const matching2 = definitionsByName.get(name3) ?? [];
28278
- if (new Set(matching2.map((definition2) => definition2.image)).size < 2 || !matching2.some((definition2) => definition2.weak))
28279
- continue;
28280
- const weak = matching2.filter((definition2) => definition2.weak);
28281
- const strong = matching2.filter((definition2) => !definition2.weak);
28282
- if (name3 !== "__cxa_throw") continue;
28283
- if (weak.length !== 1 || strong.length !== 1)
28284
- throw new Error(`unsupported weak interposition for ${name3}`);
28285
- const [local] = weak;
28286
- const [runtime] = strong;
28287
- if (local.kind !== "function" || runtime.kind !== "function" || local.result !== runtime.result || local.parameters.join(",") !== runtime.parameters.join(","))
28288
- throw new Error(`incompatible weak interposition for ${name3}`);
28289
- for (const caller of input.callers) {
28290
- const uses = caller.image === local.image || units.some(
28291
- (unit2) => unit2.image === caller.image && unit2.usedSymbols.includes(name3)
28292
- );
28293
- if (uses && caller.image !== runtime.image && !caller.next.includes(runtime.image))
28294
- throw new Error(`weak interposition scope excludes runtime for ${name3}`);
28759
+ if (new Set(matching2.map((definition2) => definition2.image)).size >= 2 && matching2.some((definition2) => definition2.weak)) {
28760
+ const weak = matching2.filter((definition2) => definition2.weak);
28761
+ const strong = matching2.filter((definition2) => !definition2.weak);
28762
+ if (weak.length !== 1 || strong.length !== 1)
28763
+ throw new Error(`unsupported weak interposition for ${name3}`);
28764
+ const [local] = weak;
28765
+ const [runtime] = strong;
28766
+ if (local.kind !== "function" || runtime.kind !== "function" || local.result !== runtime.result || local.parameters.join(",") !== runtime.parameters.join(","))
28767
+ throw new Error(`incompatible weak interposition for ${name3}`);
28768
+ for (const caller of input.callers) {
28769
+ const uses = caller.image === local.image || units.some((unit2) => unit2.image === caller.image && unit2.usedSymbols.has(name3));
28770
+ if (uses && caller.image !== runtime.image && !caller.next.includes(runtime.image))
28771
+ throw new Error(`weak interposition scope excludes runtime for ${name3}`);
28772
+ }
28773
+ preserveCanonical.add(name3);
28295
28774
  }
28296
- preserveCanonical.add(name3);
28297
28775
  }
28298
28776
  for (const name3 of [
28299
28777
  "dlsym",
@@ -28305,40 +28783,76 @@ function createGuestImageLedger(input) {
28305
28783
  ])
28306
28784
  preserveCanonical.add(name3);
28307
28785
  for (const name3 of input.commandLineSymbols ?? []) preserveCanonical.add(name3);
28308
- const bindingsByImage = /* @__PURE__ */ new Map();
28309
- const definitionsByImage = Map.groupBy(definitions, (definition2) => definition2.image);
28786
+ const imageAliases = /* @__PURE__ */ new Map();
28787
+ const imageWeakNames = /* @__PURE__ */ new Map();
28788
+ const singleOwnerByName = /* @__PURE__ */ new Map();
28789
+ for (const definition2 of definitions) {
28790
+ let aliases = imageAliases.get(definition2.image);
28791
+ if (!aliases) imageAliases.set(definition2.image, aliases = /* @__PURE__ */ new Map());
28792
+ const existing = aliases.get(definition2.name);
28793
+ if (existing === void 0) {
28794
+ aliases.set(definition2.name, definition2.alias);
28795
+ if (definition2.weak) {
28796
+ let weak = imageWeakNames.get(definition2.image);
28797
+ if (!weak) imageWeakNames.set(definition2.image, weak = /* @__PURE__ */ new Set());
28798
+ weak.add(definition2.name);
28799
+ }
28800
+ const owner = singleOwnerByName.get(definition2.name);
28801
+ if (owner === void 0)
28802
+ singleOwnerByName.set(definition2.name, {
28803
+ image: definition2.image,
28804
+ alias: definition2.alias
28805
+ });
28806
+ else if (owner !== null && owner.image !== definition2.image)
28807
+ singleOwnerByName.set(definition2.name, null);
28808
+ } else if (!definition2.weak && imageWeakNames.get(definition2.image)?.has(definition2.name)) {
28809
+ aliases.set(definition2.name, definition2.alias);
28810
+ imageWeakNames.get(definition2.image).delete(definition2.name);
28811
+ const owner = singleOwnerByName.get(definition2.name);
28812
+ if (owner && owner.image === definition2.image) owner.alias = definition2.alias;
28813
+ }
28814
+ }
28815
+ const sharedLookupByImage = /* @__PURE__ */ new Map();
28310
28816
  for (const caller of input.callers) {
28311
- const bindings = /* @__PURE__ */ new Map();
28312
- const seen = /* @__PURE__ */ new Map();
28313
28817
  const scope2 = [caller.image, ...caller.next];
28314
28818
  if (input.systemImage !== void 0 && !scope2.includes(input.systemImage))
28315
28819
  scope2.push(input.systemImage);
28316
- for (const image of scope2)
28317
- for (const definition2 of definitionsByImage.get(image) ?? []) {
28318
- const previous = seen.get(definition2.name);
28319
- if (previous?.image === definition2.image) {
28320
- if (previous.weak && !definition2.weak) {
28321
- seen.set(definition2.name, definition2);
28322
- if (!preserveCanonical.has(definition2.name))
28323
- bindings.set(definition2.name, definition2.alias);
28324
- }
28325
- continue;
28326
- }
28327
- if (!previous) {
28328
- seen.set(definition2.name, definition2);
28329
- if (!preserveCanonical.has(definition2.name))
28330
- bindings.set(definition2.name, definition2.alias);
28820
+ const scopeSet = new Set(scope2);
28821
+ const scopeMaps = [];
28822
+ const seenImages = /* @__PURE__ */ new Set();
28823
+ for (const image of scope2) {
28824
+ if (seenImages.has(image)) continue;
28825
+ seenImages.add(image);
28826
+ const aliases = imageAliases.get(image);
28827
+ if (aliases) scopeMaps.push(aliases);
28828
+ }
28829
+ const cache = /* @__PURE__ */ new Map();
28830
+ sharedLookupByImage.set(caller.image, (name3) => {
28831
+ if (preserveCanonical.has(name3)) return void 0;
28832
+ const single = singleOwnerByName.get(name3);
28833
+ if (single === void 0) return void 0;
28834
+ if (single !== null) return scopeSet.has(single.image) ? single.alias : void 0;
28835
+ const hit = cache.get(name3);
28836
+ if (hit !== void 0) return hit ?? void 0;
28837
+ for (const aliases of scopeMaps) {
28838
+ const alias = aliases.get(name3);
28839
+ if (alias !== void 0) {
28840
+ cache.set(name3, alias);
28841
+ return alias;
28331
28842
  }
28332
28843
  }
28333
- bindingsByImage.set(caller.image, bindings);
28844
+ cache.set(name3, null);
28845
+ return void 0;
28846
+ });
28334
28847
  }
28335
28848
  const startup = /* @__PURE__ */ new Map();
28849
+ const unitsByPath = new Map(units.map((unit2) => [unit2.object.path, unit2]));
28336
28850
  for (const binding of input.directBindings ?? []) {
28337
- const unit2 = units.find(({ object: object7 }) => object7.path === binding.object);
28851
+ const unit2 = unitsByPath.get(binding.object);
28338
28852
  const matches = (definitionsByName.get(binding.symbol) ?? []).filter(
28339
28853
  (definition2) => definition2.object === binding.providerObject && definition2.image === binding.providerImage
28340
28854
  );
28341
- if (!unit2 || !unit2.usedSymbols.includes(binding.symbol) || matches.length !== 1)
28855
+ if (!unit2 || !unit2.usedSymbols.has(binding.symbol) || matches.length !== 1)
28342
28856
  throw new Error(`invalid startup binding ${binding.object} ${binding.symbol}`);
28343
28857
  const bindings = startup.get(binding.object) ?? /* @__PURE__ */ new Map();
28344
28858
  if (bindings.has(binding.symbol))
@@ -28379,11 +28893,11 @@ function createGuestImageLedger(input) {
28379
28893
  }
28380
28894
  }
28381
28895
  const objects = units.map(({ image, object: object7, aliases, functionImports }) => {
28382
- const shared = bindingsByImage.get(image);
28896
+ const shared = sharedLookupByImage.get(image);
28383
28897
  const own2 = startup.get(object7.path);
28384
28898
  const bindings = new Map(own2);
28385
28899
  const weak = input.sdkWeakReferences?.get(object7.path);
28386
- const binding = (name3) => bindings.get(name3) ?? shared.get(name3) ?? (weak?.has(name3) ? void 0 : sdkGlobalBindings.get(name3));
28900
+ const binding = (name3) => bindings.get(name3) ?? shared(name3) ?? (weak?.has(name3) ? void 0 : sdkGlobalBindings.get(name3));
28387
28901
  for (const [name3, type] of functionImports) {
28388
28902
  const alias = binding(name3);
28389
28903
  const provider = alias === void 0 ? void 0 : definitionsByAlias.get(alias);
@@ -28648,7 +29162,7 @@ function nameGuestImageAliases(wasm, symbols) {
28648
29162
  }
28649
29163
  return Buffer.concat(parts);
28650
29164
  }
28651
- var import_node_crypto16, OBJC_INIT_RECORD, TABLE_INDEX_RELOCATIONS, GUEST_DYLD_VALUES_SECTION, GUEST_LAZY_FUNCTION_BASE, SDK_DYLD_RESOLVER;
29165
+ var import_node_crypto16, ByteWriter, OBJC_INIT_RECORD, TABLE_INDEX_RELOCATIONS, GUEST_DYLD_VALUES_SECTION, GUEST_LAZY_FUNCTION_BASE, SDK_DYLD_RESOLVER;
28652
29166
  var init_swift_guest_image_ledger = __esm({
28653
29167
  "src/swift-guest-image-ledger.ts"() {
28654
29168
  "use strict";
@@ -28656,6 +29170,57 @@ var init_swift_guest_image_ledger = __esm({
28656
29170
  init_nativeWasmContract();
28657
29171
  init_swift_sdk_image_wasm();
28658
29172
  init_swiftSdkLinkContract();
29173
+ ByteWriter = class {
29174
+ buf;
29175
+ pos = 0;
29176
+ constructor(initialCapacity = 256) {
29177
+ this.buf = Buffer.allocUnsafe(Math.max(64, initialCapacity));
29178
+ }
29179
+ ensure(extra) {
29180
+ const needed = this.pos + extra;
29181
+ if (needed <= this.buf.length) return;
29182
+ let next = this.buf.length * 2;
29183
+ while (next < needed) next *= 2;
29184
+ const grown = Buffer.allocUnsafe(next);
29185
+ this.buf.copy(grown, 0, 0, this.pos);
29186
+ this.buf = grown;
29187
+ }
29188
+ byte(value) {
29189
+ this.ensure(1);
29190
+ this.buf[this.pos++] = value;
29191
+ }
29192
+ uleb(value) {
29193
+ this.ensure(10);
29194
+ let pos = this.pos;
29195
+ const buf = this.buf;
29196
+ do {
29197
+ let byte = value % 128;
29198
+ value = Math.floor(value / 128);
29199
+ if (value) byte |= 128;
29200
+ buf[pos++] = byte;
29201
+ } while (value);
29202
+ this.pos = pos;
29203
+ }
29204
+ bytes(source, start = 0, end = source.length) {
29205
+ const len = end - start;
29206
+ if (len <= 0) return;
29207
+ this.ensure(len);
29208
+ this.buf.set(source.subarray(start, end), this.pos);
29209
+ this.pos += len;
29210
+ }
29211
+ string(value) {
29212
+ const len = Buffer.byteLength(value, "utf8");
29213
+ this.uleb(len);
29214
+ if (len > 0) {
29215
+ this.ensure(len);
29216
+ this.buf.write(value, this.pos, len, "utf8");
29217
+ this.pos += len;
29218
+ }
29219
+ }
29220
+ finish() {
29221
+ return this.buf.subarray(0, this.pos);
29222
+ }
29223
+ };
28659
29224
  OBJC_INIT_RECORD = ".objc_init";
28660
29225
  TABLE_INDEX_RELOCATIONS = /* @__PURE__ */ new Set([1, 2, 12, 18, 19, 24]);
28661
29226
  GUEST_DYLD_VALUES_SECTION = "peach_dyld_values";
@@ -29107,8 +29672,11 @@ function moveGuestDyldTable(map2, wasm, symbols, bindingValues = /* @__PURE__ */
29107
29672
  function guestDyldValueRange(map2) {
29108
29673
  const suffix = `:(${GUEST_DYLD_VALUES_SECTION})`;
29109
29674
  let found;
29110
- for (const line of map2.split("\n")) {
29111
- if (!line.endsWith(suffix)) continue;
29675
+ for (let at = map2.indexOf(suffix); at !== -1; at = map2.indexOf(suffix, at + suffix.length)) {
29676
+ const lineEnd = at + suffix.length;
29677
+ if (lineEnd < map2.length && map2.charCodeAt(lineEnd) !== 10) continue;
29678
+ const lineStart = map2.lastIndexOf("\n", at) + 1;
29679
+ const line = map2.slice(lineStart, lineEnd);
29112
29680
  const match = /^\s*([\da-f]+)\s+[\da-f]+\s+([\da-f]+)\s/.exec(line);
29113
29681
  if (!match) throw new Error("unreadable dyld values map line");
29114
29682
  if (found) throw new Error("link map has several dyld value sections");
@@ -29161,7 +29729,7 @@ var init_swift_guest_link_plan = __esm({
29161
29729
  });
29162
29730
 
29163
29731
  // src/swift-guest-manifest.ts
29164
- function selectedGuestManifestInputs(plan, selection, identities) {
29732
+ function selectedGuestManifestInputs(plan, selection, identities, readSelected) {
29165
29733
  const artifacts = new Map(plan.artifacts.map((artifact) => [artifact.path, artifact]));
29166
29734
  const archives = /* @__PURE__ */ new Map();
29167
29735
  const images = /* @__PURE__ */ new Map();
@@ -29172,19 +29740,29 @@ function selectedGuestManifestInputs(plan, selection, identities) {
29172
29740
  throw new Error(`selected input has no logical identity: ${item.artifact}`);
29173
29741
  let bytes;
29174
29742
  let memberIdentity = null;
29175
- if (item.member === null) bytes = (0, import_node_fs31.readFileSync)(item.artifact);
29176
- else {
29177
- let members2 = archives.get(item.artifact);
29178
- if (!members2) {
29179
- members2 = readArMembers((0, import_node_fs31.readFileSync)(item.artifact));
29180
- archives.set(item.artifact, members2);
29743
+ if (item.member === null) {
29744
+ bytes = readSelected ? readSelected(item) : (0, import_node_fs31.readFileSync)(item.artifact);
29745
+ } else {
29746
+ if (readSelected) {
29747
+ bytes = readSelected(item);
29748
+ } else {
29749
+ let members2 = archives.get(item.artifact);
29750
+ if (!members2) {
29751
+ members2 = /* @__PURE__ */ new Map();
29752
+ for (const member of readArMembers((0, import_node_fs31.readFileSync)(item.artifact))) {
29753
+ let list2 = members2.get(member.name);
29754
+ if (!list2) members2.set(member.name, list2 = []);
29755
+ list2.push(member.bytes);
29756
+ }
29757
+ archives.set(item.artifact, members2);
29758
+ }
29759
+ const matching2 = members2.get(item.member);
29760
+ if (!matching2 || matching2.length !== 1)
29761
+ throw new Error(
29762
+ `selected archive member is ambiguous: ${item.artifact}(${item.member})`
29763
+ );
29764
+ bytes = matching2[0];
29181
29765
  }
29182
- const matching2 = members2.filter((member) => member.name === item.member);
29183
- if (matching2.length !== 1)
29184
- throw new Error(
29185
- `selected archive member is ambiguous: ${item.artifact}(${item.member})`
29186
- );
29187
- bytes = matching2[0].bytes;
29188
29766
  const origin = artifact.memberOrigins?.get(item.member);
29189
29767
  if (artifact.memberOrigins && !origin)
29190
29768
  throw new Error(
@@ -29276,7 +29854,7 @@ var init_swift_guest_manifest = __esm({
29276
29854
  function isSwiftGuestImageManifest(value) {
29277
29855
  const uint = (value2, maximum) => typeof value2 === "number" && Number.isInteger(value2) && value2 >= 0 && value2 <= maximum;
29278
29856
  const text7 = (value2) => typeof value2 === "string" && value2.length > 0 && value2.length <= 4096 && !value2.includes("\0");
29279
- const name3 = (value2) => text7(value2) && new TextEncoder().encode(value2).length <= 16;
29857
+ const name3 = (value2) => text7(value2) && Buffer.byteLength(value2, "utf8") <= 16;
29280
29858
  const version2 = (value2) => isRecord(value2) && uint(value2.major, 65535) && uint(value2.minor, 255) && uint(value2.patch, 255);
29281
29859
  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))
29282
29860
  return false;
@@ -29590,27 +30168,25 @@ function planGuestProjectionRegions(images, capacities, spans) {
29590
30168
  function finalizeGuestProjectionStorage(options2) {
29591
30169
  const owner = options2.owners.get(options2.projectionObject);
29592
30170
  if (owner === void 0) throw new Error("guest projection object has no image owner");
30171
+ const ranges = [];
29593
30172
  const spans = guestLinkedSpans(
29594
30173
  options2.map,
29595
30174
  options2.linked,
29596
30175
  options2.optimized,
29597
30176
  options2.owners,
29598
30177
  options2.sectionOwners,
29599
- options2.sdkSpans !== void 0
30178
+ options2.sdkSpans !== void 0,
30179
+ {
30180
+ trackedObject: options2.projectionObject,
30181
+ trackedObjectOwner: owner,
30182
+ trackedLinearSpans: ranges
30183
+ }
29600
30184
  );
29601
30185
  const images = planGuestProjectionRegions(
29602
30186
  options2.reserved.images,
29603
30187
  options2.reserved.capacities,
29604
30188
  options2.sdkSpans ? [...spans, ...options2.sdkSpans] : spans
29605
30189
  );
29606
- const ranges = guestLinkedSpans(
29607
- options2.map,
29608
- options2.linked,
29609
- options2.optimized,
29610
- /* @__PURE__ */ new Map([[options2.projectionObject, owner]]),
29611
- void 0,
29612
- options2.sdkSpans !== void 0
29613
- ).filter((span) => span.space === "linear-memory");
29614
30190
  const result = Buffer.from(options2.optimized);
29615
30191
  const data = guestWasmDataSegments(options2.optimized, options2.sdkSpans === void 0);
29616
30192
  const locations = /* @__PURE__ */ new Map();
@@ -30678,7 +31254,7 @@ function occurrences(plan, args) {
30678
31254
  throw new Error("guest plan does not match linker inputs");
30679
31255
  return found;
30680
31256
  }
30681
- function selectedGuestLinkInputs(plan, args, whyExtract, linkTrace) {
31257
+ function selectedGuestLinkInputs(plan, args, whyExtract, linkTrace, archiveCache) {
30682
31258
  const rows = whyExtract.trimEnd().split("\n");
30683
31259
  if (rows.shift() !== "reference extracted symbol")
30684
31260
  throw new Error("invalid wasm-ld extraction report");
@@ -30693,8 +31269,38 @@ function selectedGuestLinkInputs(plan, args, whyExtract, linkTrace) {
30693
31269
  for (const file of extracted)
30694
31270
  if (!traced.has(file))
30695
31271
  throw new Error(`extracted guest input is absent from link trace ${file}`);
31272
+ const foundOccurrences = occurrences(plan, args);
31273
+ const archivePaths = /* @__PURE__ */ new Set();
31274
+ for (const { artifact } of foundOccurrences)
31275
+ if (artifact.kind === "archive") archivePaths.add(artifact.path);
31276
+ const tracedMembers = /* @__PURE__ */ new Map();
31277
+ if (archivePaths.size > 0) {
31278
+ const archivePrefixes = [...archivePaths].map(
31279
+ (archivePath) => [archivePath, `${archivePath}(`]
31280
+ );
31281
+ for (const item of traced) {
31282
+ if (!item.endsWith(")")) continue;
31283
+ const open = item.lastIndexOf("(");
31284
+ if (open > 0) {
31285
+ const archivePath = item.slice(0, open);
31286
+ if (archivePaths.has(archivePath)) {
31287
+ let list2 = tracedMembers.get(archivePath);
31288
+ if (!list2) tracedMembers.set(archivePath, list2 = []);
31289
+ list2.push(item.slice(open + 1, -1));
31290
+ continue;
31291
+ }
31292
+ }
31293
+ for (const [archivePath, prefix] of archivePrefixes) {
31294
+ if (item.startsWith(prefix)) {
31295
+ let list2 = tracedMembers.get(archivePath);
31296
+ if (!list2) tracedMembers.set(archivePath, list2 = []);
31297
+ list2.push(item.slice(prefix.length, -1));
31298
+ }
31299
+ }
31300
+ }
31301
+ }
30696
31302
  const result = [];
30697
- for (const { artifact, lazy, whole } of occurrences(plan, args)) {
31303
+ for (const { artifact, lazy, whole } of foundOccurrences) {
30698
31304
  if (artifact.kind === "object") {
30699
31305
  if (!lazy && !traced.has(artifact.path))
30700
31306
  throw new Error(`eager guest input is absent from link trace ${artifact.path}`);
@@ -30702,15 +31308,21 @@ function selectedGuestLinkInputs(plan, args, whyExtract, linkTrace) {
30702
31308
  result.push({ artifact: artifact.path, member: null });
30703
31309
  continue;
30704
31310
  }
30705
- const prefix = `${artifact.path}(`;
30706
- const names = [...traced].filter((item) => item.startsWith(prefix) && item.endsWith(")")).map((item) => item.slice(prefix.length, -1));
30707
- const members2 = readArMembers(import_node_fs34.default.readFileSync(artifact.path));
31311
+ const names = tracedMembers.get(artifact.path) ?? [];
31312
+ const nameSet = new Set(names);
31313
+ let members2 = archiveCache?.get(artifact.path);
31314
+ if (!members2) {
31315
+ members2 = readArMembers(import_node_fs34.default.readFileSync(artifact.path));
31316
+ archiveCache?.set(artifact.path, members2);
31317
+ }
31318
+ const memberCounts = /* @__PURE__ */ new Map();
30708
31319
  for (const member of members2) {
30709
- if (whole || names.includes(member.name))
31320
+ memberCounts.set(member.name, (memberCounts.get(member.name) ?? 0) + 1);
31321
+ if (whole || nameSet.has(member.name))
30710
31322
  result.push({ artifact: artifact.path, member: member.name });
30711
31323
  }
30712
31324
  for (const name3 of names)
30713
- if (members2.filter((member) => member.name === name3).length !== 1)
31325
+ if (memberCounts.get(name3) !== 1)
30714
31326
  throw new Error(
30715
31327
  `ambiguous or unsupported archive member ${artifact.path}(${name3})`
30716
31328
  );
@@ -30787,14 +31399,25 @@ function linkGuestImages(options2) {
30787
31399
  }
30788
31400
  const archives = /* @__PURE__ */ new Map();
30789
31401
  const memberBytes = /* @__PURE__ */ new Map();
31402
+ const objectBytes = /* @__PURE__ */ new Map();
30790
31403
  const artifacts = new Map(plan.artifacts.map((artifact) => [artifact.path, artifact]));
30791
31404
  const providerSymbol = "__peach_dlsym_from_image";
30792
31405
  const readSelected = (item) => {
30793
- if (item.member === null) return import_node_fs34.default.readFileSync(item.artifact);
31406
+ if (item.member === null) {
31407
+ let bytes = objectBytes.get(item.artifact);
31408
+ if (!bytes) {
31409
+ bytes = import_node_fs34.default.readFileSync(item.artifact);
31410
+ objectBytes.set(item.artifact, bytes);
31411
+ }
31412
+ return bytes;
31413
+ }
30794
31414
  let byName2 = memberBytes.get(item.artifact);
30795
31415
  if (!byName2) {
30796
- const members2 = readArMembers(import_node_fs34.default.readFileSync(item.artifact));
30797
- archives.set(item.artifact, members2);
31416
+ let members2 = archives.get(item.artifact);
31417
+ if (!members2) {
31418
+ members2 = readArMembers(import_node_fs34.default.readFileSync(item.artifact));
31419
+ archives.set(item.artifact, members2);
31420
+ }
30798
31421
  byName2 = /* @__PURE__ */ new Map();
30799
31422
  for (const member of members2)
30800
31423
  if (!byName2.has(member.name))
@@ -30818,7 +31441,13 @@ function linkGuestImages(options2) {
30818
31441
  `--why-extract=${whyPath}`,
30819
31442
  `--Map=${mapPath}`
30820
31443
  ]);
30821
- return selectedGuestLinkInputs(plan, args, import_node_fs34.default.readFileSync(whyPath, "utf8"), trace);
31444
+ return selectedGuestLinkInputs(
31445
+ plan,
31446
+ args,
31447
+ import_node_fs34.default.readFileSync(whyPath, "utf8"),
31448
+ trace,
31449
+ archives
31450
+ );
30822
31451
  };
30823
31452
  const needsProvider = (item) => {
30824
31453
  if (!artifacts.get(item.artifact).instrumentDynamicLookups) return false;
@@ -30858,7 +31487,7 @@ function linkGuestImages(options2) {
30858
31487
  )
30859
31488
  ]);
30860
31489
  const originalOwnership = identity2(plan);
30861
- const resolved = options2.resolvePlan(selected, plan);
31490
+ const resolved = options2.resolvePlan(selected, plan, readSelected);
30862
31491
  if (identity2(resolved) !== originalOwnership)
30863
31492
  throw new Error("resolved guest scopes changed input ownership");
30864
31493
  plan = resolved;
@@ -30912,6 +31541,7 @@ function linkGuestImages(options2) {
30912
31541
  }
30913
31542
  }
30914
31543
  let discoveryRegions;
31544
+ let liveSymbols;
30915
31545
  if (discoveryProjection && options2.projection) {
30916
31546
  const owners = /* @__PURE__ */ new Map([[discoveryProjection, options2.projection.image]]);
30917
31547
  for (const item of selected)
@@ -30920,10 +31550,15 @@ function linkGuestImages(options2) {
30920
31550
  selectedGuestInputImage(artifacts.get(item.artifact), item.member)
30921
31551
  );
30922
31552
  const wasm = import_node_fs34.default.readFileSync(discovery);
31553
+ liveSymbols = /* @__PURE__ */ new Set();
30923
31554
  discoveryRegions = guestProjectionRegionCounts(
30924
31555
  plan.images.length,
30925
- guestLinkedSpans(guestLinkLines(mapPath), wasm, wasm, owners)
31556
+ guestLinkedSpans(guestLinkLines(mapPath), wasm, wasm, owners, void 0, false, {
31557
+ collectSymbols: liveSymbols
31558
+ })
30926
31559
  );
31560
+ } else {
31561
+ liveSymbols = linkedMapSymbols(guestLinkLines(mapPath));
30927
31562
  }
30928
31563
  const ledger = createGuestImageLedger({
30929
31564
  images: plan.images.map((image) => ({
@@ -30932,7 +31567,7 @@ function linkGuestImages(options2) {
30932
31567
  })),
30933
31568
  callers: plan.callers,
30934
31569
  symbols: plan.symbols,
30935
- liveSymbols: linkedMapSymbols(guestLinkLines(mapPath)),
31570
+ liveSymbols,
30936
31571
  commandLineSymbols: commandLineSymbols(args),
30937
31572
  directBindings: plan.directBindings,
30938
31573
  registerAppTables: sdkCallers !== void 0,
@@ -31064,7 +31699,8 @@ function linkGuestImages(options2) {
31064
31699
  const selectedInputs = selectedGuestManifestInputs(
31065
31700
  plan,
31066
31701
  selected,
31067
- projection.identities
31702
+ projection.identities,
31703
+ readSelected
31068
31704
  );
31069
31705
  const images = projection.images.map(
31070
31706
  (image) => createGuestImageManifest({
@@ -31074,6 +31710,9 @@ function linkGuestImages(options2) {
31074
31710
  regions: []
31075
31711
  })
31076
31712
  );
31713
+ objectBytes.clear();
31714
+ memberBytes.clear();
31715
+ archives.clear();
31077
31716
  if (!discoveryRegions) throw new Error("guest projection layout object missing");
31078
31717
  const regionsBefore = discoveryRegions;
31079
31718
  const ledgerPieces = guestProjectionRegionCapacity([import_node_fs34.default.readFileSync(ledgerObject)], 0);
@@ -31167,10 +31806,47 @@ ${changed.join("\n")}`
31167
31806
  }
31168
31807
  function linkedMapSymbols(lines) {
31169
31808
  const names = /* @__PURE__ */ new Set();
31170
- const symbol2 = /^ +\S+ +[0-9a-f]+ +[0-9a-f]+ {9,}([^\s/<]\S*)/;
31171
31809
  for (const line of lines) {
31172
- const match = symbol2.exec(line);
31173
- if (match) names.add(match[1]);
31810
+ const length = line.length;
31811
+ if (length < 15 || line.charCodeAt(0) !== 32) continue;
31812
+ let pos = 1;
31813
+ while (pos < length && line.charCodeAt(pos) === 32) pos++;
31814
+ const c1 = pos;
31815
+ while (pos < length) {
31816
+ const ch = line.charCodeAt(pos);
31817
+ if (ch === 32 || ch >= 9 && ch <= 13) break;
31818
+ pos++;
31819
+ }
31820
+ if (pos === c1 || pos >= length || line.charCodeAt(pos) !== 32) continue;
31821
+ while (pos < length && line.charCodeAt(pos) === 32) pos++;
31822
+ const c2 = pos;
31823
+ while (pos < length) {
31824
+ const ch = line.charCodeAt(pos);
31825
+ if (!(ch >= 48 && ch <= 57 || ch >= 97 && ch <= 102)) break;
31826
+ pos++;
31827
+ }
31828
+ if (pos === c2 || pos >= length || line.charCodeAt(pos) !== 32) continue;
31829
+ while (pos < length && line.charCodeAt(pos) === 32) pos++;
31830
+ const c3 = pos;
31831
+ while (pos < length) {
31832
+ const ch = line.charCodeAt(pos);
31833
+ if (!(ch >= 48 && ch <= 57 || ch >= 97 && ch <= 102)) break;
31834
+ pos++;
31835
+ }
31836
+ if (pos === c3 || pos >= length || line.charCodeAt(pos) !== 32) continue;
31837
+ const sStart = pos;
31838
+ while (pos < length && line.charCodeAt(pos) === 32) pos++;
31839
+ if (pos - sStart < 9 || pos >= length) continue;
31840
+ const first = line.charCodeAt(pos);
31841
+ if (first === 47 || first === 60 || first === 32 || first >= 9 && first <= 13)
31842
+ continue;
31843
+ let end = pos + 1;
31844
+ while (end < length) {
31845
+ const ch = line.charCodeAt(end);
31846
+ if (ch === 32 || ch >= 9 && ch <= 13) break;
31847
+ end++;
31848
+ }
31849
+ names.add(line.slice(pos, end));
31174
31850
  }
31175
31851
  return names;
31176
31852
  }
@@ -31269,7 +31945,7 @@ function discoverGuestLinkInputs(options2) {
31269
31945
  import_node_fs34.default.mkdirSync(options2.directory, { recursive: true });
31270
31946
  const why = import_node_path32.default.join(options2.directory, "preselection-why.txt");
31271
31947
  const response = import_node_path32.default.join(options2.directory, "preselection.rsp");
31272
- const output = import_node_path32.default.join(options2.directory, "preselection.wasm");
31948
+ const output = process.platform !== "win32" ? "/dev/null" : import_node_path32.default.join(options2.directory, "preselection.wasm");
31273
31949
  const flags = [
31274
31950
  ...withOutput(args, output, true),
31275
31951
  ...options2.objects,
@@ -31367,7 +32043,7 @@ function prepareGuestRuntimeInputs(options2) {
31367
32043
  });
31368
32044
  return { args, selected, originalSelection, archives, sdkProducts, archiveArtifacts };
31369
32045
  }
31370
- function selectedGuestSymbolInputs(plan, selected) {
32046
+ function selectedGuestSymbolInputs(plan, selected, readSelected) {
31371
32047
  const artifacts = new Map(plan.artifacts.map((artifact) => [artifact.path, artifact]));
31372
32048
  const archives = /* @__PURE__ */ new Map();
31373
32049
  const symbols = /* @__PURE__ */ new Set();
@@ -31383,22 +32059,27 @@ function selectedGuestSymbolInputs(plan, selected) {
31383
32059
  if (!artifact) throw new Error(`selected symbol input has no owner ${item.artifact}`);
31384
32060
  let bytes;
31385
32061
  let name3 = item.artifact;
31386
- if (item.member === null) bytes = import_node_fs34.default.readFileSync(item.artifact);
31387
- else {
31388
- let members2 = archives.get(item.artifact);
31389
- if (!members2) {
31390
- members2 = Map.groupBy(
31391
- readArMembers(import_node_fs34.default.readFileSync(item.artifact)),
31392
- (member) => member.name
31393
- );
31394
- archives.set(item.artifact, members2);
32062
+ if (item.member === null) {
32063
+ bytes = readSelected ? readSelected(item) : import_node_fs34.default.readFileSync(item.artifact);
32064
+ } else {
32065
+ if (readSelected) {
32066
+ bytes = readSelected(item);
32067
+ } else {
32068
+ let members2 = archives.get(item.artifact);
32069
+ if (!members2) {
32070
+ members2 = Map.groupBy(
32071
+ readArMembers(import_node_fs34.default.readFileSync(item.artifact)),
32072
+ (member) => member.name
32073
+ );
32074
+ archives.set(item.artifact, members2);
32075
+ }
32076
+ const matching2 = members2.get(item.member) ?? [];
32077
+ if (matching2.length !== 1)
32078
+ throw new Error(
32079
+ `ambiguous selected symbol input ${item.artifact}(${item.member})`
32080
+ );
32081
+ bytes = matching2[0].bytes;
31395
32082
  }
31396
- const matching2 = members2.get(item.member) ?? [];
31397
- if (matching2.length !== 1)
31398
- throw new Error(
31399
- `ambiguous selected symbol input ${item.artifact}(${item.member})`
31400
- );
31401
- bytes = matching2[0].bytes;
31402
32083
  name3 += `(${item.member})`;
31403
32084
  }
31404
32085
  if (owners.has(name3)) throw new Error(`duplicate selected symbol input ${name3}`);
@@ -31411,9 +32092,9 @@ function selectedGuestSymbolInputs(plan, selected) {
31411
32092
  for (const symbol2 of names.tags) tags.add(symbol2);
31412
32093
  for (const symbol2 of names.defined) {
31413
32094
  definitions.add(symbol2);
31414
- const objects = definitionObjects.get(symbol2) ?? /* @__PURE__ */ new Set();
32095
+ let objects = definitionObjects.get(symbol2);
32096
+ if (!objects) definitionObjects.set(symbol2, objects = /* @__PURE__ */ new Set());
31415
32097
  objects.add(name3);
31416
- definitionObjects.set(symbol2, objects);
31417
32098
  }
31418
32099
  }
31419
32100
  return {
@@ -31434,7 +32115,7 @@ function verifyGuestSymbolScopes(options2) {
31434
32115
  if (!symbols.length) return { bindings: [], directBindings: [] };
31435
32116
  import_node_fs34.default.mkdirSync(options2.directory, { recursive: true });
31436
32117
  const response = import_node_path32.default.join(options2.directory, "scope-trace.rsp");
31437
- const output = import_node_path32.default.join(options2.directory, "scope-trace.wasm");
32118
+ const output = process.platform !== "win32" ? "/dev/null" : import_node_path32.default.join(options2.directory, "scope-trace.wasm");
31438
32119
  const args = [
31439
32120
  ...withOutput(normalizedGuestLinkArgs(options2.args), output, true),
31440
32121
  ...options2.objects,
@@ -31452,55 +32133,76 @@ function verifyGuestSymbolScopes(options2) {
31452
32133
  import_node_fs34.default.closeSync(traceOutput);
31453
32134
  }
31454
32135
  const records = /* @__PURE__ */ new Map();
31455
- const consume = (line) => {
31456
- const match = /^(.*): (reference to|definition of) (.*)$/.exec(line);
31457
- if (!match) return;
31458
- const [, object7, kind, symbol2] = match;
31459
- if (!requested.has(symbol2)) return;
31460
- if (options2.hostImports.has(symbol2)) return;
31461
- const record5 = records.get(symbol2) ?? {
31462
- references: /* @__PURE__ */ new Map(),
31463
- providers: /* @__PURE__ */ new Map(),
31464
- physicalModule: false
31465
- };
32136
+ for (const line of guestLinkLines(tracePath)) {
32137
+ const refSep = line.lastIndexOf(": reference to ");
32138
+ const defSep = line.lastIndexOf(": definition of ");
32139
+ if (refSep < 0 && defSep < 0) continue;
32140
+ const isRef = refSep > defSep;
32141
+ const sep3 = isRef ? refSep : defSep;
32142
+ const symbol2 = line.slice(sep3 + (isRef ? 15 : 16));
32143
+ if (!requested.has(symbol2) || options2.hostImports.has(symbol2)) continue;
32144
+ let record5 = records.get(symbol2);
32145
+ if (!record5) {
32146
+ record5 = {
32147
+ references: /* @__PURE__ */ new Map(),
32148
+ providers: /* @__PURE__ */ new Map(),
32149
+ physicalModule: false
32150
+ };
32151
+ records.set(symbol2, record5);
32152
+ }
32153
+ const object7 = line.slice(0, sep3);
31466
32154
  if (object7 === "<internal>") {
31467
- if (kind === "definition of") record5.physicalModule = true;
32155
+ if (!isRef) record5.physicalModule = true;
31468
32156
  } else {
31469
32157
  const image = options2.owners.get(object7);
31470
32158
  if (image === void 0)
31471
32159
  throw new Error(`traced guest object has no owner ${object7}`);
31472
- (kind === "reference to" ? record5.references : record5.providers).set(
31473
- object7,
31474
- image
31475
- );
32160
+ (isRef ? record5.references : record5.providers).set(object7, image);
31476
32161
  }
31477
- records.set(symbol2, record5);
31478
- };
31479
- for (const line of guestLinkLines(tracePath)) consume(line);
32162
+ }
31480
32163
  const callers = new Map(options2.callers.map((caller) => [caller.image, caller.next]));
32164
+ const callerSets = new Map(
32165
+ options2.callers.map((caller) => [caller.image, new Set(caller.next)])
32166
+ );
32167
+ const rootScope = callerSets.get(0);
31481
32168
  const result = [];
31482
32169
  const directBindings = [];
31483
32170
  for (const symbol2 of symbols) {
31484
32171
  const record5 = records.get(symbol2);
31485
32172
  if (!record5 || !record5.references.size) continue;
31486
32173
  if (!record5.providers.size && options2.hostImports.has(symbol2)) continue;
31487
- const startupReferences = [...record5.references].filter(
31488
- ([object7]) => options2.startupObjects.has(object7) && options2.weakReferences.get(object7)?.has(symbol2)
31489
- );
31490
- const otherReferences = [...record5.references].filter(
31491
- ([object7]) => !startupReferences.some(([startup]) => startup === object7)
31492
- );
32174
+ const startupReferences = [];
32175
+ const otherReferences = [];
32176
+ let allWeakRefs = true;
32177
+ for (const [object7, caller] of record5.references) {
32178
+ const isWeakRef = options2.weakReferences.get(object7)?.has(symbol2) === true;
32179
+ if (!isWeakRef) allWeakRefs = false;
32180
+ if (isWeakRef && options2.startupObjects.has(object7)) {
32181
+ startupReferences.push([object7, caller]);
32182
+ } else {
32183
+ otherReferences.push([object7, caller]);
32184
+ }
32185
+ }
31493
32186
  for (const [, caller] of startupReferences)
31494
32187
  if (!callers.has(caller))
31495
32188
  throw new Error(`guest image has no caller scope ${caller}`);
31496
32189
  if (startupReferences.length && !record5.physicalModule) {
31497
- const candidates = options2.definitionObjects.get(symbol2) ?? /* @__PURE__ */ new Set();
31498
- if (candidates.size > 1 || record5.providers.size > 1)
32190
+ const candidates2 = options2.definitionObjects.get(symbol2);
32191
+ const candidateSize = candidates2?.size ?? 0;
32192
+ if (candidateSize > 1 || record5.providers.size > 1)
31499
32193
  throw new Error(`ambiguous startup provider ${symbol2}`);
31500
- if (candidates.size !== record5.providers.size || [...record5.providers.keys()].some((object7) => !candidates.has(object7)))
31501
- throw new Error(`unproven startup provider ${symbol2}`);
32194
+ let unproven = candidateSize !== record5.providers.size;
32195
+ if (!unproven && candidates2) {
32196
+ for (const object7 of record5.providers.keys()) {
32197
+ if (!candidates2.has(object7)) {
32198
+ unproven = true;
32199
+ break;
32200
+ }
32201
+ }
32202
+ }
32203
+ if (unproven) throw new Error(`unproven startup provider ${symbol2}`);
31502
32204
  if (record5.providers.size === 1) {
31503
- const [providerObject, providerImage] = [...record5.providers][0];
32205
+ const [providerObject, providerImage] = record5.providers.entries().next().value;
31504
32206
  if (options2.weakDefinitions.get(providerObject)?.has(symbol2))
31505
32207
  throw new Error(`weak startup provider ${symbol2}`);
31506
32208
  for (const [object7] of startupReferences)
@@ -31508,28 +32210,34 @@ function verifyGuestSymbolScopes(options2) {
31508
32210
  }
31509
32211
  if (!otherReferences.length) continue;
31510
32212
  }
31511
- if (!record5.providers.size && !record5.physicalModule && [...record5.references.keys()].every(
31512
- (object7) => options2.weakReferences.get(object7)?.has(symbol2)
31513
- ))
31514
- continue;
32213
+ if (!record5.providers.size && !record5.physicalModule && allWeakRefs) continue;
31515
32214
  const providerImages = new Set(record5.providers.values());
31516
- const copies = [...options2.definitionObjects.get(symbol2) ?? []].flatMap(
31517
- (object7) => {
32215
+ const candidates = options2.definitionObjects.get(symbol2);
32216
+ const copyImages = /* @__PURE__ */ new Set();
32217
+ const strongImages = /* @__PURE__ */ new Set();
32218
+ let weakDefinerImages;
32219
+ if (candidates) {
32220
+ for (const object7 of candidates) {
31518
32221
  const image = options2.owners.get(object7);
31519
- return image === void 0 ? [] : [{ image, weak: !!options2.weakDefinitions.get(object7)?.has(symbol2) }];
32222
+ if (image === void 0) continue;
32223
+ copyImages.add(image);
32224
+ if (options2.weakDefinitions.get(object7)?.has(symbol2)) {
32225
+ ;
32226
+ (weakDefinerImages ??= /* @__PURE__ */ new Set()).add(image);
32227
+ } else {
32228
+ strongImages.add(image);
32229
+ }
31520
32230
  }
31521
- );
31522
- const copyImages = new Set(copies.map((copy) => copy.image));
31523
- const strongImages = new Set(
31524
- copies.filter((copy) => !copy.weak).map((copy) => copy.image)
31525
- );
32231
+ }
31526
32232
  const interposed = !record5.physicalModule && copyImages.size > 1;
31527
32233
  const providerCount = interposed ? 1 : providerImages.size + Number(record5.physicalModule);
31528
32234
  if (!providerCount) continue;
31529
32235
  if (providerCount !== 1)
31530
32236
  throw new Error(`guest symbol has ambiguous provider ${symbol2}`);
31531
- const scopedReferences = record5.physicalModule ? [...record5.references] : otherReferences;
31532
- const uniqueProvider = strongImages.size > 1 ? void 0 : [...strongImages][0] ?? [...providerImages][0];
32237
+ const scopedReferences = record5.physicalModule ? record5.references : otherReferences;
32238
+ const firstProviderImage = providerImages.values().next().value;
32239
+ const uniqueProvider = strongImages.size > 1 ? void 0 : strongImages.values().next().value ?? firstProviderImage;
32240
+ let interposedByCaller;
31533
32241
  for (const [object7, caller] of scopedReferences) {
31534
32242
  const scope2 = callers.get(caller);
31535
32243
  if (!scope2) throw new Error(`guest image has no caller scope ${caller}`);
@@ -31537,18 +32245,35 @@ function verifyGuestSymbolScopes(options2) {
31537
32245
  result.push({ symbol: symbol2, caller, provider: { kind: "physical-module" } });
31538
32246
  continue;
31539
32247
  }
31540
- const provider = interposed ? [caller, ...scope2].find((image) => copyImages.has(image)) ?? uniqueProvider : [...providerImages][0];
32248
+ let provider;
32249
+ if (interposed) {
32250
+ if (interposedByCaller?.has(caller)) {
32251
+ provider = interposedByCaller.get(caller);
32252
+ } else {
32253
+ if (copyImages.has(caller)) {
32254
+ provider = caller;
32255
+ } else {
32256
+ for (const image of scope2) {
32257
+ if (copyImages.has(image)) {
32258
+ provider = image;
32259
+ break;
32260
+ }
32261
+ }
32262
+ if (provider === void 0) provider = uniqueProvider;
32263
+ }
32264
+ ;
32265
+ (interposedByCaller ??= /* @__PURE__ */ new Map()).set(caller, provider);
32266
+ }
32267
+ } else {
32268
+ provider = firstProviderImage;
32269
+ }
31541
32270
  if (provider === void 0) {
31542
32271
  if (options2.weakReferences.get(object7)?.has(symbol2)) continue;
31543
32272
  throw new Error(`guest scope ${caller} omits every provider of ${symbol2}`);
31544
32273
  }
31545
32274
  if (caller === provider) continue;
31546
- if ([...options2.definitionObjects.get(symbol2) ?? []].some(
31547
- (definer) => options2.owners.get(definer) === caller && options2.weakDefinitions.get(definer)?.has(symbol2)
31548
- ))
31549
- continue;
31550
- if (!scope2.includes(provider)) {
31551
- const candidates = options2.definitionObjects.get(symbol2) ?? /* @__PURE__ */ new Set();
32275
+ if (weakDefinerImages?.has(caller)) continue;
32276
+ if (!callerSets.get(caller).has(provider)) {
31552
32277
  const traced = [...record5.providers.keys()];
31553
32278
  const strongTraced = traced.filter(
31554
32279
  (definer) => !options2.weakDefinitions.get(definer)?.has(symbol2)
@@ -31556,16 +32281,17 @@ function verifyGuestSymbolScopes(options2) {
31556
32281
  const providers = strongTraced.length === 1 ? strongTraced : traced;
31557
32282
  if (options2.weakReferences.get(object7)?.has(symbol2) && !providers.some((provider2) => options2.systemProviders.has(provider2)))
31558
32283
  continue;
31559
- const equivalentCopies = providers.length === 1 && candidates.has(providers[0]) && [...candidates].every(
32284
+ const candidateSet = candidates ?? /* @__PURE__ */ new Set();
32285
+ const equivalentCopies = providers.length === 1 && candidateSet.has(providers[0]) && [...candidateSet].every(
31560
32286
  (definer) => options2.weakDefinitions.get(definer)?.has(symbol2)
31561
32287
  );
31562
- const strongCandidates = [...candidates].filter(
32288
+ const strongCandidates = [...candidateSet].filter(
31563
32289
  (definer) => !options2.weakDefinitions.get(definer)?.has(symbol2)
31564
32290
  );
31565
- const soleCandidate = candidates.size === 1 || strongCandidates.length === 1 && strongCandidates[0] === providers[0];
31566
- if (!equivalentCopies && (!soleCandidate || providers.length !== 1 || !candidates.has(providers[0]) || !(options2.systemProviders.has(providers[0]) || // a strong undefined reference binds through the process global
32291
+ const soleCandidate = candidateSet.size === 1 || strongCandidates.length === 1 && strongCandidates[0] === providers[0];
32292
+ if (!equivalentCopies && (!soleCandidate || providers.length !== 1 || !candidateSet.has(providers[0]) || !(options2.systemProviders.has(providers[0]) || // a strong undefined reference binds through the process global
31567
32293
  // scope, the root image and its dependency closure, as in elf.
31568
- provider === 0 || callers.get(0)?.includes(provider) || !options2.weakReferences.get(object7)?.has(symbol2) && options2.frameworkProviders.get(object7)?.has(providers[0]))))
32294
+ provider === 0 || rootScope?.has(provider) || !options2.weakReferences.get(object7)?.has(symbol2) && options2.frameworkProviders.get(object7)?.has(providers[0]))))
31569
32295
  throw new Error(
31570
32296
  `guest scope ${caller} omits traced provider ${provider} for ${symbol2}`
31571
32297
  );
@@ -37584,9 +38310,9 @@ async function compileGuestLink(options2) {
37584
38310
  }
37585
38311
  };
37586
38312
  },
37587
- resolvePlan: (selected, plan) => {
38313
+ resolvePlan: (selected, plan, readSelected) => {
37588
38314
  if (!prepared) throw new Error("guest runtime selection is unavailable");
37589
- const scope2 = selectedGuestSymbolInputs(plan, selected);
38315
+ const scope2 = selectedGuestSymbolInputs(plan, selected, readSelected);
37590
38316
  const owners = new Map(scope2.owners);
37591
38317
  owners.set(import_node_path43.default.join(directory2, "projection-discovery.o"), 0);
37592
38318
  const providersByImage = Map.groupBy(scope2.owners, ([, image]) => image);
@@ -45283,7 +46009,7 @@ ${wasmThreadLinkFlags.map((flag) => ` "-Xlinker", ${JSON.stringify(flag
45283
46009
  REACTOR_FLAG = '"-Xclang-linker", "-mexec-model=reactor",\n';
45284
46010
  MULTI_MANIFEST_VERSION = 76;
45285
46011
  SWIFT_HEADER_PRODUCTS_TARGET = "PeachHeaderProducts";
45286
- compilerSourceDigest = true ? "80c152de0e5f41327f3fe7c71ce7df4cd206c0ba2bb0373f71654a0661829c6e" : swiftCompilerSourceDigest(__sootsim_import_meta_dirname);
46012
+ compilerSourceDigest = true ? "7b91fa4405159335b5484c82700e001e4c27abf15621b724ea8af4edea693f66" : swiftCompilerSourceDigest(__sootsim_import_meta_dirname);
45287
46013
  nativeCxxCompilerFlags = ["-fno-cxx-modules"];
45288
46014
  MODULE_MAP_RESPONSE_FILE_RUN = 16;
45289
46015
  cFlagArray = (flags) => JSON.stringify(withoutGlogModuleMap(flags));
@@ -85719,7 +86445,7 @@ var init_swift_standin_digest = __esm({
85719
86445
  STANDIN_DIGEST_ENTRYPOINTS = ["swift-standins.ts", "swift-objc-compile.ts"];
85720
86446
  SPECIFIER = /from\s*['"]([^'"]+)['"]|import\s*\(\s*['"]([^'"]+)['"]\s*\)/g;
85721
86447
  standinSourceDigest = (srcDir = __sootsim_import_meta_dirname) => sourceClosureDigest(srcDir, STANDIN_DIGEST_ENTRYPOINTS);
85722
- STANDIN_SOURCE_DIGEST = true ? "b4ec01293af51e43890fb5aa52c9dc6d240c73b8fe722cdaff952457b08d94ff" : standinSourceDigest();
86448
+ STANDIN_SOURCE_DIGEST = true ? "a3bcdfe9c9957355a59c2c26155470c89a2abb30907aeeaaf1de8463aa74fc8c" : standinSourceDigest();
85723
86449
  }
85724
86450
  });
85725
86451
 
@@ -102163,7 +102889,7 @@ var init_nitro_superset = __esm({
102163
102889
  init_nitroContract();
102164
102890
  init_swift_standin_digest();
102165
102891
  NITRO_SUPERSET_ENTRY_NAME = "superset";
102166
- NITRO_COMPILER_DIGEST = true ? "59081cf672cb2bb9c125425cd97f2df60507acfc6de96f1525f18ddca39ff000" : nitroCompilerSourceDigest(__sootsim_import_meta_dirname, STANDIN_SOURCE_DIGEST2);
102892
+ NITRO_COMPILER_DIGEST = true ? "ffe0ab1580ebcb5a184764bfb3b3650342c8644057a95423913e7078c208f318" : nitroCompilerSourceDigest(__sootsim_import_meta_dirname, STANDIN_SOURCE_DIGEST2);
102167
102893
  nitroSupersetLock = parseLock(nitro_superset_lock_default);
102168
102894
  nitroSupersetKey = (inputs2) => nativeEntryKey({ ...inputs2, compiler: NITRO_COMPILER_DIGEST });
102169
102895
  published = /* @__PURE__ */ new Map();
@@ -103030,7 +103756,7 @@ var init_expo_eager_seam_contract = __esm({
103030
103756
 
103031
103757
  // src/expo-native-compiler-digest.ts
103032
103758
  function expoNativeCompilerDigestValue() {
103033
- return true ? "bc9bf63858735336bd46e9b34db5ced39d682f7200bbbc3eafbf5470dae0018f" : expoNativeCompilerDigest(__sootsim_import_meta_dirname);
103759
+ return true ? "a8b60651de79588c6c5143dd2545ccd8e3b858acd992f46b35ba3de883118ac5" : expoNativeCompilerDigest(__sootsim_import_meta_dirname);
103034
103760
  }
103035
103761
  var import_node_crypto78;
103036
103762
  var init_expo_native_compiler_digest = __esm({