peachsim 0.1.2622 → 0.1.2624

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 (138) 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 +693 -306
  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-FYCW5KQE.mjs → acorn-DH6VFUJ3.mjs} +3 -3
  27. package/dist-lib/esm-chunks/{chunk-UQ3ACQY7.mjs → chunk-265THLTP.mjs} +1 -1
  28. package/dist-lib/esm-chunks/{chunk-5SDBXLYL.mjs → chunk-2YHIYKY2.mjs} +4 -4
  29. package/dist-lib/esm-chunks/{chunk-SKVUSWJU.mjs → chunk-3XA5HYI5.mjs} +6 -6
  30. package/dist-lib/esm-chunks/{chunk-W7AGZLTK.mjs → chunk-A2WMBGJO.mjs} +3 -3
  31. package/dist-lib/esm-chunks/{chunk-HY7D6BBU.mjs → chunk-AV7G5PTE.mjs} +1 -1
  32. package/dist-lib/esm-chunks/{chunk-HMWCDFVQ.mjs → chunk-CM2NU5MS.mjs} +5 -5
  33. package/dist-lib/esm-chunks/{chunk-C2QXEBC5.mjs → chunk-EFQFJ7M6.mjs} +1 -1
  34. package/dist-lib/esm-chunks/{chunk-7Z4ESZI7.mjs → chunk-HKPKCJI5.mjs} +1 -1
  35. package/dist-lib/esm-chunks/{chunk-N3LFPMVM.mjs → chunk-IMI2NE4A.mjs} +1 -1
  36. package/dist-lib/esm-chunks/{chunk-G7NMIYJW.mjs → chunk-JHMD4G4V.mjs} +1 -1
  37. package/dist-lib/esm-chunks/{chunk-67RCWRPX.mjs → chunk-LCO2EXKF.mjs} +1 -1
  38. package/dist-lib/esm-chunks/{chunk-DOCJYFRP.mjs → chunk-LD7Z3NDO.mjs} +1 -1
  39. package/dist-lib/esm-chunks/{chunk-7DFBTAWA.mjs → chunk-LMWSFXYN.mjs} +1 -1
  40. package/dist-lib/esm-chunks/{chunk-IEVIGGKG.mjs → chunk-LOQBWIPM.mjs} +1 -1
  41. package/dist-lib/esm-chunks/{chunk-X62EBL6H.mjs → chunk-LT533AHJ.mjs} +1 -1
  42. package/dist-lib/esm-chunks/{chunk-P64OR3XD.mjs → chunk-N4ZJZUCO.mjs} +1 -1
  43. package/dist-lib/esm-chunks/{chunk-UR2EIB2I.mjs → chunk-OLAYY7SG.mjs} +1 -1
  44. package/dist-lib/esm-chunks/{chunk-G4CIR7M6.mjs → chunk-QNXV766K.mjs} +565 -290
  45. package/dist-lib/esm-chunks/{chunk-3XZWIVAA.mjs → chunk-QZ5HTMWV.mjs} +1 -1
  46. package/dist-lib/esm-chunks/{chunk-V7CGV5XO.mjs → chunk-T7C6Z5UH.mjs} +1 -1
  47. package/dist-lib/esm-chunks/{chunk-Y2RPOAEE.mjs → chunk-UJORQHAE.mjs} +1 -1
  48. package/dist-lib/esm-chunks/{chunk-IRUQ2NMF.mjs → chunk-VH4BJS5V.mjs} +1 -1
  49. package/dist-lib/esm-chunks/{chunk-5UDR743S.mjs → chunk-XONCLAVA.mjs} +8 -7
  50. package/dist-lib/esm-chunks/{chunk-WRQCYESG.mjs → chunk-YOD53JTM.mjs} +2 -2
  51. package/dist-lib/esm-chunks/{metro-layout-parser-GR4EJUCZ.mjs → metro-layout-parser-MDVTDJ65.mjs} +3 -3
  52. package/dist-lib/esm-chunks/{swift-package-prebuilt-CW6VQ6A5.mjs → swift-package-prebuilt-ZN7I4FYC.mjs} +12 -12
  53. package/dist-lib/esm-chunks/{swift-sdk-app-module-NULACNZJ.mjs → swift-sdk-app-module-DUVE2OXH.mjs} +107 -20
  54. package/dist-lib/esm-chunks/{swift-sdk-image-ZFATI6XZ.mjs → swift-sdk-image-YSWQBCYV.mjs} +16 -16
  55. package/dist-lib/esm-chunks/{swift-sdk-image-producer-WKVRKIRF.mjs → swift-sdk-image-producer-MZ235WSK.mjs} +5 -5
  56. package/dist-lib/expo-swift-bundle.cjs +686 -299
  57. package/dist-lib/expo-swift-metadata.cjs +1 -1
  58. package/dist-lib/expo-swift-metadata.mjs +7 -7
  59. package/dist-lib/home-paths.cjs +1 -1
  60. package/dist-lib/host/bridge-host.cjs +691 -304
  61. package/dist-lib/host/fetch-proxy-handler.cjs +7 -7
  62. package/dist-lib/host/fetch-proxy-overrides.cjs +1 -1
  63. package/dist-lib/host/fetch-proxy-overrides.mjs +2 -2
  64. package/dist-lib/host/replacement-module-handler.cjs +1 -1
  65. package/dist-lib/host/websocket-proxy.cjs +1 -1
  66. package/dist-lib/index.cjs +1 -1
  67. package/dist-lib/kotlin-host.cjs +1 -1
  68. package/dist-lib/menu.cjs +1 -1
  69. package/dist-lib/menu.mjs +3 -3
  70. package/dist-lib/metro-fingerprint-registry.cjs +1 -1
  71. package/dist-lib/metro-fingerprint-registry.mjs +3 -3
  72. package/dist-lib/metro-production-bundle.cjs +1 -1
  73. package/dist-lib/metro-production-bundle.mjs +4 -4
  74. package/dist-lib/native-app-identity-project.cjs +30 -15
  75. package/dist-lib/native-app-identity-project.mjs +44 -29
  76. package/dist-lib/native-app-identity.cjs +1 -1
  77. package/dist-lib/native-app-identity.mjs +6 -6
  78. package/dist-lib/native-firebase-metadata.cjs +1 -1
  79. package/dist-lib/native-firebase-metadata.mjs +3 -3
  80. package/dist-lib/pdfium-raster.cjs +1 -1
  81. package/dist-lib/pdfium-raster.mjs +2 -2
  82. package/dist-lib/plist.cjs +1 -1
  83. package/dist-lib/plist.mjs +3 -3
  84. package/dist-lib/profiles.cjs +1 -1
  85. package/dist-lib/public-brand.cjs +1 -1
  86. package/dist-lib/public-origins-lib-esm.json +85 -85
  87. package/dist-lib/public-origins-lib.json +64 -64
  88. package/dist-lib/react-native-host-modules.cjs +1 -1
  89. package/dist-lib/react-native-host-modules.mjs +2 -2
  90. package/dist-lib/reap-browser.cjs +1 -1
  91. package/dist-lib/scripts/dev-server-scanner.cjs +1 -1
  92. package/dist-lib/sdk.cjs +1 -1
  93. package/dist-lib/sdk.mjs +8 -8
  94. package/dist-lib/skills.cjs +691 -304
  95. package/dist-lib/swift-compile.cjs +638 -280
  96. package/dist-lib/swift-compile.mjs +12 -12
  97. package/dist-lib/swift-package.cjs +1 -1
  98. package/dist-lib/swift-package.mjs +3 -3
  99. package/dist-lib/swift-submit.cjs +1 -1
  100. package/dist-lib/swift-submit.mjs +6 -6
  101. package/dist-lib/swift-svg-raster.cjs +1 -1
  102. package/dist-lib/swift-svg-raster.mjs +2 -2
  103. package/dist-lib/swift-toolchain.cjs +1 -1
  104. package/dist-lib/swift.cjs +1 -1
  105. package/dist-lib/vendor/@peculiar/x509.cjs +1 -1
  106. package/dist-lib/vendor/@ruby/prism/src/nodes.js.cjs +1 -1
  107. package/dist-lib/vendor/@ruby/prism/src/parsePrism.js.cjs +1 -1
  108. package/dist-lib/vendor/acorn.cjs +1 -1
  109. package/dist-lib/vendor/magic-string.cjs +1 -1
  110. package/dist-lib/vendor/stream-json.cjs +1 -1
  111. package/dist-lib/vendor/sucrase/dist/index.js.cjs +1 -1
  112. package/dist-lib/vendor/sucrase/dist/parser/index.js.cjs +1 -1
  113. package/dist-lib/vendor/sucrase/dist/parser/tokenizer/index.js.cjs +1 -1
  114. package/dist-lib/vendor/sucrase/dist/parser/tokenizer/types.js.cjs +1 -1
  115. package/dist-lib/vendor/sucrase.cjs +1 -1
  116. package/dist-lib/vendor/terser.cjs +1 -1
  117. package/dist-lib/vendor/valibot.cjs +1 -1
  118. package/dist-lib/vendor/ws.cjs +1 -1
  119. package/dist-lib/vendor/zod.cjs +1 -1
  120. package/dist-lib/worklet-executable.cjs +1 -1
  121. package/dist-lib/worklet-executable.mjs +3 -3
  122. package/package.json +1 -1
  123. package/src/bazel-project.ts +34 -18
  124. package/src/binaryen.lock.json +3 -3
  125. package/src/swift-compile.ts +8 -0
  126. package/src/swift-distribution.lock.json +8 -3
  127. package/src/swift-guest-compile.ts +170 -160
  128. package/src/swift-guest-dyld-table.ts +22 -9
  129. package/src/swift-guest-link.ts +116 -42
  130. package/src/swift-guest-linked-spans.ts +63 -14
  131. package/src/swift-guest-projection-storage.ts +7 -6
  132. package/src/swift-guest-source-inputs.ts +35 -21
  133. package/src/swift-objc-compile.ts +1 -0
  134. package/src/swift-sdk-app-module.ts +118 -15
  135. package/src/swift-sdk-image-wasm.ts +119 -17
  136. package/src/swift-sdk-image.ts +4 -1
  137. package/src/swift-wasm-prune.ts +71 -41
  138. package/src/wasm-narrow-boundary.ts +31 -6
@@ -1,13 +1,18 @@
1
1
  import { execFile } from 'node:child_process'
2
2
  import { createHash } from 'node:crypto'
3
3
  import {
4
+ appendFileSync,
4
5
  chownSync,
6
+ closeSync,
5
7
  constants,
6
8
  copyFileSync,
7
9
  existsSync,
10
+ fstatSync,
8
11
  mkdirSync,
9
12
  mkdtempSync,
13
+ openSync,
10
14
  readFileSync,
15
+ readSync,
11
16
  realpathSync,
12
17
  rmSync,
13
18
  statSync,
@@ -135,10 +140,16 @@ export async function buildSwiftAppModule(options: {
135
140
  linkage: link.linkage,
136
141
  usage,
137
142
  })
138
- writeFileSync(options.output, finishSwiftAppModule(readFileSync(options.output)))
143
+ finishSwiftAppModuleFile(options.output)
139
144
  return binding
140
145
  }
141
146
 
147
+ export function swiftAppModuleThunkSection(
148
+ lowered: Uint8Array,
149
+ ): readonly [string, Uint8Array] {
150
+ return [NATIVE_SDK_THUNK_SECTION, sdkImportThunks(lowered)]
151
+ }
152
+
142
153
  export function finishSwiftAppModule(lowered: Uint8Array) {
143
154
  return writeWasmCustomSection(
144
155
  lowered,
@@ -147,6 +158,79 @@ export function finishSwiftAppModule(lowered: Uint8Array) {
147
158
  )
148
159
  }
149
160
 
161
+ // reads only through section 2 (type + import) and appends the thunk section in place
162
+ // instead of copying multi-hundred-MB lowered modules through JS memory.
163
+ function finishSwiftAppModuleFile(file: string): void {
164
+ const fd = openSync(file, 'r')
165
+ let prefixEnd = 8
166
+ let hasExistingThunk = false
167
+ let prefix: Buffer | undefined
168
+ try {
169
+ const total = fstatSync(fd).size
170
+ const probe = Buffer.allocUnsafe(16)
171
+ let offset = 8
172
+ while (offset < total) {
173
+ const read = readSync(fd, probe, 0, Math.min(16, total - offset), offset)
174
+ if (read < 2) break
175
+ const id = probe[0]!
176
+ let size = 0
177
+ let shift = 0
178
+ let at = 1
179
+ for (;;) {
180
+ const byte = probe[at++]!
181
+ size += (byte & 127) * 2 ** shift
182
+ if (!(byte & 128)) break
183
+ shift += 7
184
+ }
185
+ const start = offset + at
186
+ const next = start + size
187
+ if (id === 1 || id === 2) prefixEnd = next
188
+ else if (id === 0) {
189
+ const nameBuf = Buffer.allocUnsafe(Math.min(128, size))
190
+ const nRead = readSync(fd, nameBuf, 0, nameBuf.length, start)
191
+ let nLen = 0
192
+ let nShift = 0
193
+ let nAt = 0
194
+ for (;;) {
195
+ if (nAt >= nRead) break
196
+ const byte = nameBuf[nAt++]!
197
+ nLen += (byte & 127) * 2 ** nShift
198
+ if (!(byte & 128)) break
199
+ nShift += 7
200
+ }
201
+ if (
202
+ nAt + nLen <= nRead &&
203
+ nameBuf.toString('utf8', nAt, nAt + nLen) === NATIVE_SDK_THUNK_SECTION
204
+ ) {
205
+ hasExistingThunk = true
206
+ break
207
+ }
208
+ }
209
+ offset = next
210
+ }
211
+ if (!hasExistingThunk) {
212
+ prefix = Buffer.allocUnsafe(prefixEnd)
213
+ let filled = 0
214
+ while (filled < prefixEnd) {
215
+ const n = readSync(fd, prefix, filled, prefixEnd - filled, filled)
216
+ if (n <= 0) break
217
+ filled += n
218
+ }
219
+ prefix = prefix.subarray(0, filled)
220
+ }
221
+ } finally {
222
+ closeSync(fd)
223
+ }
224
+ if (hasExistingThunk || !prefix) {
225
+ writeFileSync(file, finishSwiftAppModule(readFileSync(file)))
226
+ return
227
+ }
228
+ const thunks = sdkImportThunks(prefix)
229
+ const nameBytes = Buffer.from(encodedName(NATIVE_SDK_THUNK_SECTION))
230
+ const header = Buffer.from([0, ...uleb(nameBytes.length + thunks.length)])
231
+ appendFileSync(file, Buffer.concat([header, nameBytes, thunks]))
232
+ }
233
+
150
234
  /**
151
235
  * the inputs of a whole-program link the app module links: every input its build root holds
152
236
  * (objects, vendored archives, native library members) but the pruned sdk copies, and each
@@ -418,6 +502,7 @@ export async function linkSwiftAppModule(options: {
418
502
  '--unresolved-symbols=ignore-all',
419
503
  '--import-undefined',
420
504
  '--emit-relocs',
505
+ '--strip-debug',
421
506
  '--gc-sections',
422
507
  '--keep-section=target_features',
423
508
  '--error-limit=0',
@@ -442,19 +527,33 @@ export async function linkSwiftAppModule(options: {
442
527
  const { loweringCache } = options
443
528
  const loweringKey =
444
529
  loweringCache &&
445
- createHash('sha256')
446
- .update(
447
- JSON.stringify([
448
- loweringCache.compilerDigest,
449
- optimize,
450
- skipPasses,
451
- sdkTableEnd,
452
- lazy,
453
- KEEP_WASM_NAMES,
454
- ]),
455
- )
456
- .update(bytes)
457
- .digest('hex')
530
+ (typeof Bun !== 'undefined'
531
+ ? new Bun.CryptoHasher('sha256')
532
+ .update(
533
+ JSON.stringify([
534
+ loweringCache.compilerDigest,
535
+ optimize,
536
+ skipPasses,
537
+ sdkTableEnd,
538
+ lazy,
539
+ KEEP_WASM_NAMES,
540
+ ]),
541
+ )
542
+ .update(bytes)
543
+ .digest('hex')
544
+ : createHash('sha256')
545
+ .update(
546
+ JSON.stringify([
547
+ loweringCache.compilerDigest,
548
+ optimize,
549
+ skipPasses,
550
+ sdkTableEnd,
551
+ lazy,
552
+ KEEP_WASM_NAMES,
553
+ ]),
554
+ )
555
+ .update(bytes)
556
+ .digest('hex'))
458
557
  return {
459
558
  linkage,
460
559
  async lower() {
@@ -1217,7 +1316,11 @@ export function createSwiftSdkBinding(
1217
1316
  bindSwiftAppModule(linkage, sdk),
1218
1317
  selectSwiftSdkData(sdk, usage, linkage, projection),
1219
1318
  ])
1220
- return { bytes, sha256: createHash('sha256').update(bytes).digest('hex') }
1319
+ const sha256 =
1320
+ typeof Bun !== 'undefined'
1321
+ ? new Bun.CryptoHasher('sha256').update(bytes).digest('hex')
1322
+ : createHash('sha256').update(bytes).digest('hex')
1323
+ return { bytes, sha256 }
1221
1324
  }
1222
1325
 
1223
1326
  /** use the native object names from the link before guest image aliases are assigned. */
@@ -146,6 +146,36 @@ function readImports(bytes: Uint8Array, imports: WasmSection | undefined) {
146
146
  return { functionTypes, importedGlobals, memoryPages }
147
147
  }
148
148
 
149
+ function countImportedFunctions(
150
+ bytes: Uint8Array,
151
+ imports: WasmSection | undefined,
152
+ ): number {
153
+ let count = 0
154
+ if (!imports) return count
155
+ const r = wasmReader(bytes, imports.start)
156
+ for (let n = r.u(); n > 0; n--) {
157
+ r.skip(r.u())
158
+ r.skip(r.u())
159
+ const kind = r.byte()
160
+ if (kind === 0) {
161
+ r.u()
162
+ count++
163
+ } else if (kind === 1) {
164
+ r.byte()
165
+ skipLimits(r)
166
+ } else if (kind === 2) {
167
+ skipLimits(r)
168
+ } else if (kind === 3) {
169
+ r.byte()
170
+ r.byte()
171
+ } else if (kind === 4) {
172
+ r.byte()
173
+ r.u()
174
+ } else throw new Error(`unknown wasm import kind ${kind}`)
175
+ }
176
+ return count
177
+ }
178
+
149
179
  function* readFunctionNames(bytes: Uint8Array, names: WasmSection) {
150
180
  for (const r = wasmReader(bytes, names.start); r.at < names.end; ) {
151
181
  const id = r.byte()
@@ -592,29 +622,77 @@ export const SWIFT_SDK_CONSTRUCTOR_LIMIT = 16384
592
622
 
593
623
  /** the direct calls of __wasm_call_ctors, each named by its defining object and function. */
594
624
  export function constructorKeys(map: WasmLinkMap, bytes: Uint8Array): string[] {
595
- const m = readModule(bytes)
596
625
  const first = map.code[0]
597
- if (!first || !m.bodies.length) throw new Error('link has no code')
598
- // a map's code offset plus one delta is the body's size prefix in the section
599
- const prefixes = m.bodies.map(({ prefix }) => prefix)
600
- const delta = prefixes[0]! - first.offset
601
- const byOffset = new Map(map.code.map((chunk) => [chunk.offset + delta, chunk]))
626
+ if (!first) throw new Error('link has no code')
627
+ const sections = wasmSections(bytes)
628
+ const code = sections.find((s) => s.id === 10)
629
+ if (!code) throw new Error('link has no code')
602
630
  const ctors = map.code.find((chunk) => chunk.section === '__wasm_call_ctors')
603
631
  if (!ctors) throw new Error('link has no constructors')
604
- const index = prefixes.indexOf(ctors.offset + delta)
605
- if (index < 0) throw new Error('constructor function not found by map offset')
606
- const body = m.bodies[index]!
607
- const r = wasmReader(bytes, body.start)
632
+ const importedFuncs = countImportedFunctions(
633
+ bytes,
634
+ sections.find((s) => s.id === 2),
635
+ )
636
+ const codeReader = wasmReader(bytes, code.start)
637
+ const bodyCount = codeReader.u()
638
+ if (!bodyCount) throw new Error('link has no code')
639
+ const prefixes = new Uint32Array(bodyCount)
640
+ let delta = 0
641
+ let ctorPrefix = -1
642
+ let ctorStart = -1
643
+ let ctorEnd = -1
644
+ for (let i = 0; i < bodyCount; i++) {
645
+ const prefix = codeReader.at
646
+ const size = codeReader.u()
647
+ prefixes[i] = prefix
648
+ if (i === 0) {
649
+ delta = prefix - first.offset
650
+ ctorPrefix = ctors.offset + delta
651
+ }
652
+ if (prefix === ctorPrefix) {
653
+ ctorStart = codeReader.at
654
+ ctorEnd = ctorStart + size
655
+ }
656
+ codeReader.skip(size)
657
+ }
658
+ if (ctorStart < 0) throw new Error('constructor function not found by map offset')
659
+ // map.code is emitted by wasm-ld in ascending offset order; binary search avoids a giant Map.
660
+ let sorted = true
661
+ for (let i = 1; i < map.code.length; i++) {
662
+ if (map.code[i]!.offset < map.code[i - 1]!.offset) {
663
+ sorted = false
664
+ break
665
+ }
666
+ }
667
+ const byOffset = sorted
668
+ ? undefined
669
+ : new Map(map.code.map((chunk) => [chunk.offset + delta, chunk]))
670
+ const findChunk = (targetPrefix: number) => {
671
+ if (byOffset) return byOffset.get(targetPrefix)
672
+ const targetOffset = targetPrefix - delta
673
+ let lo = 0
674
+ let hi = map.code.length - 1
675
+ while (lo <= hi) {
676
+ const mid = (lo + hi) >> 1
677
+ const offset = map.code[mid]!.offset
678
+ if (offset < targetOffset) lo = mid + 1
679
+ else if (offset > targetOffset) hi = mid - 1
680
+ else return map.code[mid]
681
+ }
682
+ return undefined
683
+ }
684
+ const r = wasmReader(bytes, ctorStart)
608
685
  for (let n = r.u(); n > 0; n--) {
609
686
  r.u()
610
687
  r.byte()
611
688
  }
612
689
  const keys: string[] = []
613
- while (r.at < body.end) {
690
+ while (r.at < ctorEnd) {
614
691
  const op = r.byte()
615
692
  if (op === 0x10) {
616
- const callee = r.u() - m.importedFuncs
617
- const chunk = byOffset.get(prefixes[callee]!)
693
+ const callee = r.u() - importedFuncs
694
+ const chunk =
695
+ callee >= 0 && callee < bodyCount ? findChunk(prefixes[callee]!) : undefined
618
696
  if (!chunk) throw new Error('constructor without a map chunk')
619
697
  keys.push(chunkKey(chunk, ''))
620
698
  } else if (op !== 0x1a && op !== 0x0b) throw new Error(`constructor op ${op}`)
@@ -718,7 +796,10 @@ export function relocationEdges(
718
796
  r.skip(r.u())
719
797
  }
720
798
  }
721
- const importedFunctions = readModule(bytes).importedFuncs
799
+ const importedFunctions = countImportedFunctions(
800
+ bytes,
801
+ sections.find((s) => s.id === 2),
802
+ )
722
803
  const data: number[] = []
723
804
  const dataFunctions: number[] = []
724
805
  const bodyCount = bodyStarts.length
@@ -852,7 +933,28 @@ export function strongDefinitions(bytes: Uint8Array): string[] {
852
933
 
853
934
  /** the slots a startup split may append past an image's table: one per function without one. */
854
935
  export function unslottedFunctions(bytes: Uint8Array): number {
855
- const m = readModule(bytes)
856
- const slotted = new Set([...m.slots.keys()].filter((index) => index >= m.importedFuncs))
857
- return m.bodies.length - slotted.size
936
+ const sections = wasmSections(bytes)
937
+ const importedFuncs = countImportedFunctions(
938
+ bytes,
939
+ sections.find((s) => s.id === 2),
940
+ )
941
+ const code = sections.find((s) => s.id === 10)
942
+ const definedFuncs = code ? wasmReader(bytes, code.start).u() : 0
943
+ const slotted = new Set<number>()
944
+ const elements = sections.find((s) => s.id === 9)
945
+ if (elements) {
946
+ const r = wasmReader(bytes, elements.start)
947
+ for (let n = r.u(); n > 0; n--) {
948
+ const flags = r.u()
949
+ if (flags !== 0 && flags !== 2) throw new Error(`sdk image element flags ${flags}`)
950
+ if (flags === 2) r.u()
951
+ constant(r)
952
+ if (flags === 2) r.byte()
953
+ for (let i = 0, count = r.u(); i < count; i++) {
954
+ const index = r.u()
955
+ if (index >= importedFuncs) slotted.add(index)
956
+ }
957
+ }
958
+ }
959
+ return definedFuncs - slotted.size
858
960
  }
@@ -578,6 +578,7 @@ async function linkSwiftSdkImage(
578
578
  ].map((name) => `--export=${name}`),
579
579
  `@${path.join(work, 'exports.rsp')}`,
580
580
  '--gc-sections',
581
+ '--strip-debug',
581
582
  // strings stay with their objects, so an app loads only the ones its pieces reference
582
583
  '-O0',
583
584
  ]
@@ -640,7 +641,9 @@ async function linkSwiftSdkImage(
640
641
  writeFileSync(path.join(work, INTERFACE_FILE), JSON.stringify(sdkInterface))
641
642
  writeFileSync(
642
643
  path.join(work, IMAGE_DIGEST),
643
- createHash('sha256').update(image).digest('hex'),
644
+ typeof Bun !== 'undefined'
645
+ ? new Bun.CryptoHasher('sha256').update(image).digest('hex')
646
+ : createHash('sha256').update(image).digest('hex'),
644
647
  )
645
648
  if (
646
649
  swiftSdkImageKey(
@@ -39,6 +39,12 @@ import {
39
39
 
40
40
  export { localizeDefinedWasmSymbols, readArMembers }
41
41
 
42
+ function sha256Hex(bytes: Uint8Array | Buffer): string {
43
+ if (typeof Bun !== 'undefined')
44
+ return new Bun.CryptoHasher('sha256').update(bytes).digest('hex')
45
+ return createHash('sha256').update(bytes).digest('hex')
46
+ }
47
+
42
48
  function readULEB(b: Uint8Array, o: number): [number, number] {
43
49
  let res = 0
44
50
  let shift = 0
@@ -294,8 +300,8 @@ interface ParsedObject {
294
300
  objcCategoryTargets: string[]
295
301
  rootFuncs: number[]
296
302
  rootSegs: number[]
297
- /** absolute file offsets of each data segment's payload. */
298
- segPayloadRanges: [number, number][]
303
+ /** ObjC class symbols (`._OBJC_CLASS_<name>`) embedded in each data segment's mangled names. */
304
+ segObjCClasses: Map<number, string[]>
299
305
  }
300
306
 
301
307
  // keyed by path, stamped by file identity: a framework slot rewrites its
@@ -1023,6 +1029,43 @@ function parseWasmObjectBytes(
1023
1029
  }
1024
1030
  }
1025
1031
 
1032
+ const segObjCClasses = new Map<number, string[]>()
1033
+ for (let segIdx = 0; segIdx < sEnds.length; segIdx++) {
1034
+ const rangeStart = dataStart + sPayloadStarts[segIdx]!
1035
+ const rangeEnd = dataStart + sEnds[segIdx]!
1036
+ const sliceLen = rangeEnd - rangeStart
1037
+ if (sliceLen < 4) continue
1038
+ const slice = Buffer.from(rawBuf.buffer, rawBuf.byteOffset + rangeStart, sliceLen)
1039
+ let segPos = 0
1040
+ let classes: string[] | undefined
1041
+ while (segPos < sliceLen - 3) {
1042
+ const at = slice.indexOf('So', segPos)
1043
+ if (at < 0 || at >= sliceLen - 2) break
1044
+ let digitEnd = at + 2
1045
+ let length = 0
1046
+ while (digitEnd < sliceLen) {
1047
+ const ch = slice[digitEnd]!
1048
+ if (ch < 0x30 || ch > 0x39) break
1049
+ length = length * 10 + (ch - 0x30)
1050
+ digitEnd++
1051
+ }
1052
+ if (digitEnd === at + 2) {
1053
+ segPos = at + 2
1054
+ continue
1055
+ }
1056
+ segPos = digitEnd
1057
+ const nameEnd = digitEnd + length
1058
+ if (nameEnd >= sliceLen || slice[nameEnd] !== 0x43) continue
1059
+ const symbol = `._OBJC_CLASS_${slice.toString('latin1', digitEnd, nameEnd)}`
1060
+ if (!classes) {
1061
+ classes = [symbol]
1062
+ segObjCClasses.set(segIdx, classes)
1063
+ } else if (!classes.includes(symbol)) {
1064
+ classes.push(symbol)
1065
+ }
1066
+ }
1067
+ }
1068
+
1026
1069
  return {
1027
1070
  file,
1028
1071
  isDist,
@@ -1052,10 +1095,7 @@ function parseWasmObjectBytes(
1052
1095
  objcCategoryTargets,
1053
1096
  rootFuncs,
1054
1097
  rootSegs,
1055
- segPayloadRanges: sEnds.map((end, i) => [
1056
- dataStart + sPayloadStarts[i]!,
1057
- dataStart + end,
1058
- ]),
1098
+ segObjCClasses,
1059
1099
  }
1060
1100
  }
1061
1101
 
@@ -1637,7 +1677,7 @@ export function pruneSwiftWasmLink(
1637
1677
  transformations.set(file, {
1638
1678
  output,
1639
1679
  inputSha256,
1640
- outputSha256: createHash('sha256').update(result).digest('hex'),
1680
+ outputSha256: sha256Hex(result),
1641
1681
  kind,
1642
1682
  })
1643
1683
  }
@@ -1646,9 +1686,19 @@ export function pruneSwiftWasmLink(
1646
1686
  const distFiles: string[] = []
1647
1687
  const distBaseNames = new Set<string>()
1648
1688
  const eagerFiles: string[] = []
1689
+ const parsedBuildObjects = new Map<string, ParsedObject>()
1649
1690
  const lazyBuildObjects = new Map<string, ParsedObject>()
1650
1691
  const extraArchiveObjs: ParsedObject[] = []
1651
1692
  const objectBytes = new Map<ParsedObject, Buffer>()
1693
+ const archiveMembers = new Map<string, ReturnType<typeof readArMembers>>()
1694
+ const readArchiveMembers = (archive: string) => {
1695
+ let members = archiveMembers.get(archive)
1696
+ if (!members) {
1697
+ members = readArMembers(new Uint8Array(fs.readFileSync(archive)))
1698
+ archiveMembers.set(archive, members)
1699
+ }
1700
+ return members
1701
+ }
1652
1702
  let inStartLib = false
1653
1703
  let swiftrtOrigPath = ''
1654
1704
 
@@ -1696,8 +1746,10 @@ export function pruneSwiftWasmLink(
1696
1746
  break
1697
1747
  }
1698
1748
  }
1699
- if (definesObjCClassOrCategory) eagerFiles.push(t)
1700
- else lazyBuildObjects.set(t, obj)
1749
+ if (definesObjCClassOrCategory) {
1750
+ parsedBuildObjects.set(t, obj)
1751
+ eagerFiles.push(t)
1752
+ } else lazyBuildObjects.set(t, obj)
1701
1753
  } else {
1702
1754
  eagerFiles.push(t)
1703
1755
  }
@@ -1712,7 +1764,7 @@ export function pruneSwiftWasmLink(
1712
1764
  !t.endsWith('libclang_rt.builtins-wasm64.a') &&
1713
1765
  fs.existsSync(t)
1714
1766
  ) {
1715
- const members = readArMembers(new Uint8Array(fs.readFileSync(t)))
1767
+ const members = readArchiveMembers(t)
1716
1768
  for (const m of members) {
1717
1769
  const object = parseWasmObjectBytes(`${t}(${m.name})`, m.bytes, false)
1718
1770
  extraArchiveObjs.push(object)
@@ -1742,7 +1794,7 @@ export function pruneSwiftWasmLink(
1742
1794
  )
1743
1795
  const archiveOverlapsDist = (archive: string): boolean => {
1744
1796
  if (!fs.existsSync(archive)) return false
1745
- const members = readArMembers(new Uint8Array(fs.readFileSync(archive)))
1797
+ const members = readArchiveMembers(archive)
1746
1798
  return members.some((m) => distBaseNames.has(m.name))
1747
1799
  }
1748
1800
  for (const t of tokens) {
@@ -1773,7 +1825,7 @@ export function pruneSwiftWasmLink(
1773
1825
  path.basename(archive),
1774
1826
  )
1775
1827
  const ordinals = new Map<string, number>()
1776
- for (const m of readArMembers(new Uint8Array(fs.readFileSync(archive)))) {
1828
+ for (const m of readArchiveMembers(archive)) {
1777
1829
  const ordinal = (ordinals.get(m.name) ?? 0) + 1
1778
1830
  ordinals.set(m.name, ordinal)
1779
1831
  if (distBaseNames.has(m.name) || writtenLeftovers.has(m.name)) continue
@@ -1810,7 +1862,7 @@ export function pruneSwiftWasmLink(
1810
1862
  recordTransformation(
1811
1863
  swiftrtOrigPath,
1812
1864
  patchedSwiftrtPath,
1813
- link ? createHash('sha256').update(input).digest('hex') : '',
1865
+ link ? sha256Hex(input) : '',
1814
1866
  result,
1815
1867
  'swiftrt',
1816
1868
  )
@@ -2425,7 +2477,8 @@ export function pruneSwiftWasmLink(
2425
2477
  const isDist = f.startsWith(distDir)
2426
2478
  // the app's own objects link whole, as ld64 keeps every swift type record:
2427
2479
  // storyboards, data models and NSClassFromString name app classes by string.
2428
- const obj = distObjs.get(f) ?? parseWasmObjectFile(f, isDist)
2480
+ const obj =
2481
+ distObjs.get(f) ?? parsedBuildObjects.get(f) ?? parseWasmObjectFile(f, isDist)
2429
2482
  extractObject(obj)
2430
2483
  if (isDist) {
2431
2484
  const base = path.basename(f)
@@ -2498,32 +2551,9 @@ export function pruneSwiftWasmLink(
2498
2551
  // such as the argument of Outcome<AVTimedMetadataGroup>, by objc_getClass
2499
2552
  // alone: no relocation reaches the class, so a live name keeps its provider.
2500
2553
  const keepObjCClassesNamedInSegment = (obj: ParsedObject, segIdx: number) => {
2501
- const range = obj.segPayloadRanges[segIdx]
2502
- if (!range) return
2503
- const [rangeStart, rangeEnd] = range
2504
- if (rangeEnd - rangeStart < 4) return
2505
- let bytes = objectBytes.get(obj)
2506
- if (!bytes) objectBytes.set(obj, (bytes = fs.readFileSync(obj.file)))
2507
- let pos: number = rangeStart
2508
- while (pos < rangeEnd - 3) {
2509
- const at: number = bytes.indexOf('So', pos)
2510
- if (at < 0 || at >= rangeEnd - 2) break
2511
- let digitEnd: number = at + 2
2512
- let length = 0
2513
- while (digitEnd < rangeEnd) {
2514
- const ch = bytes[digitEnd]!
2515
- if (ch < 0x30 || ch > 0x39) break
2516
- length = length * 10 + (ch - 0x30)
2517
- digitEnd++
2518
- }
2519
- if (digitEnd === at + 2) {
2520
- pos = at + 2
2521
- continue
2522
- }
2523
- pos = digitEnd
2524
- const nameEnd = digitEnd + length
2525
- if (nameEnd >= rangeEnd || bytes[nameEnd] !== 0x43) continue
2526
- const symbol = `._OBJC_CLASS_${bytes.toString('latin1', digitEnd, nameEnd)}`
2554
+ const symbols = obj.segObjCClasses.get(segIdx)
2555
+ if (!symbols) return
2556
+ for (const symbol of symbols) {
2527
2557
  for (const provider of lazyProviders.get(symbol) ?? []) {
2528
2558
  eagerDynamicObjects.add(provider)
2529
2559
  extractObject(provider)
@@ -2635,7 +2665,7 @@ export function pruneSwiftWasmLink(
2635
2665
  ? new Uint8Array(cached)
2636
2666
  : new Uint8Array(fs.readFileSync(obj.file))
2637
2667
  const rawBuf = Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength)
2638
- const inputSha256 = link ? createHash('sha256').update(buf).digest('hex') : ''
2668
+ const inputSha256 = link ? sha256Hex(buf) : ''
2639
2669
  const fLive = liveFuncs.get(obj)!
2640
2670
  const sLive = liveSegs.get(obj)!
2641
2671
  const dLive = liveDataSyms.get(obj)!
@@ -57,17 +57,42 @@ export function dropWasmCustomSection(bytes: Uint8Array, name: string): Buffer {
57
57
  return Buffer.concat(parts)
58
58
  }
59
59
 
60
+ export function writeWasmCustomSections(
61
+ bytes: Uint8Array,
62
+ entries: readonly (readonly [string, Uint8Array])[],
63
+ ) {
64
+ if (entries.length === 0) return Buffer.concat([bytes])
65
+ const replaced = new Set(entries.map(([name]) => name))
66
+ const parts: Uint8Array[] = []
67
+ let sliceStart = 0
68
+ let sliceEnd = 8
69
+ for (const { id, start, end } of sections(bytes)) {
70
+ if (id === 0 && replaced.has(reader(bytes, start, end).name())) {
71
+ if (sliceEnd > sliceStart) parts.push(bytes.subarray(sliceStart, sliceEnd))
72
+ sliceStart = end
73
+ sliceEnd = end
74
+ } else {
75
+ sliceEnd = end
76
+ }
77
+ }
78
+ if (sliceEnd > sliceStart) parts.push(bytes.subarray(sliceStart, sliceEnd))
79
+ for (const [name, data] of entries) {
80
+ const nameBytes = Buffer.from(encodeName(name))
81
+ parts.push(
82
+ Buffer.from([0, ...encodeNumber(nameBytes.length + data.length)]),
83
+ nameBytes,
84
+ data,
85
+ )
86
+ }
87
+ return Buffer.concat(parts)
88
+ }
89
+
60
90
  export function writeWasmCustomSection(
61
91
  bytes: Uint8Array,
62
92
  name: string,
63
93
  data: Uint8Array,
64
94
  ) {
65
- const section = Buffer.concat([Buffer.from(encodeName(name)), data])
66
- return Buffer.concat([
67
- dropWasmCustomSection(bytes, name),
68
- Buffer.from([0, ...encodeNumber(section.length)]),
69
- section,
70
- ])
95
+ return writeWasmCustomSections(bytes, [[name, data]])
71
96
  }
72
97
 
73
98
  /** function indices by their name-section names. */