peachsim 0.1.2591 → 0.1.2593

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 (149) 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 +5684 -5254
  14. package/dist-lib/capture-contract.cjs +1 -1
  15. package/dist-lib/capture-contract.mjs +3 -3
  16. package/dist-lib/cloud-contract.cjs +1 -1
  17. package/dist-lib/cloud-contract.mjs +3 -3
  18. package/dist-lib/cloud-test-args.cjs +1 -1
  19. package/dist-lib/cloud-test-args.mjs +2 -2
  20. package/dist-lib/cloud.cjs +1 -1
  21. package/dist-lib/cloud.mjs +7 -7
  22. package/dist-lib/config.cjs +1 -1
  23. package/dist-lib/config.mjs +5 -5
  24. package/dist-lib/detox/index.cjs +2 -2
  25. package/dist-lib/dev-bundle-resolution.cjs +1 -1
  26. package/dist-lib/esm-chunks/{acorn-EMX4WZ72.mjs → acorn-DLENU3SM.mjs} +3 -3
  27. package/dist-lib/esm-chunks/{chunk-VYZ5DC3M.mjs → chunk-23D4W2EY.mjs} +1015 -703
  28. package/dist-lib/esm-chunks/{chunk-MC6NMYWY.mjs → chunk-2MWUVSRW.mjs} +1 -1
  29. package/dist-lib/esm-chunks/{chunk-UIVXVMS5.mjs → chunk-2UERF2EN.mjs} +2 -2
  30. package/dist-lib/esm-chunks/{chunk-VRVXRZI4.mjs → chunk-4YJJKKKF.mjs} +112 -58
  31. package/dist-lib/esm-chunks/{chunk-AKKHSVJ4.mjs → chunk-6O2M4J2Y.mjs} +1 -1
  32. package/dist-lib/esm-chunks/{chunk-EGKH2L6J.mjs → chunk-BMKI4WBL.mjs} +1 -1
  33. package/dist-lib/esm-chunks/{chunk-4QHHRGO4.mjs → chunk-DLSPHUHQ.mjs} +1 -1
  34. package/dist-lib/esm-chunks/{chunk-UYJXLDCG.mjs → chunk-E6OGMX3T.mjs} +1 -1
  35. package/dist-lib/esm-chunks/{chunk-VF5WVB3D.mjs → chunk-GFMQ5PNX.mjs} +1 -1
  36. package/dist-lib/esm-chunks/{chunk-JHXDM3YU.mjs → chunk-IT4CC3HU.mjs} +1 -1
  37. package/dist-lib/esm-chunks/{chunk-J676B57D.mjs → chunk-JPNUGMLE.mjs} +5 -5
  38. package/dist-lib/esm-chunks/{chunk-RKQZGWX2.mjs → chunk-KWMJUJJS.mjs} +1 -1
  39. package/dist-lib/esm-chunks/{chunk-QBMFX3J2.mjs → chunk-LK3KQ4X3.mjs} +1 -1
  40. package/dist-lib/esm-chunks/{chunk-ZL5N6ENT.mjs → chunk-LN7ZTBNS.mjs} +1 -1
  41. package/dist-lib/esm-chunks/{chunk-Q4NA6PUR.mjs → chunk-NIYJBFXV.mjs} +3 -3
  42. package/dist-lib/esm-chunks/{chunk-7627LKJK.mjs → chunk-OIHSBING.mjs} +1 -1
  43. package/dist-lib/esm-chunks/{chunk-YR6DNV76.mjs → chunk-P3A4MQHR.mjs} +1 -1
  44. package/dist-lib/esm-chunks/{chunk-VD27WNCT.mjs → chunk-TXBZEHNH.mjs} +4 -4
  45. package/dist-lib/esm-chunks/{chunk-TFG4LZ5T.mjs → chunk-UM4DCXPA.mjs} +1 -1
  46. package/dist-lib/esm-chunks/{chunk-ILWFGZWW.mjs → chunk-UZPLSN2V.mjs} +107 -6
  47. package/dist-lib/esm-chunks/{chunk-SOAYP72T.mjs → chunk-XFFPOSW2.mjs} +1 -1
  48. package/dist-lib/esm-chunks/{chunk-NX23AMX4.mjs → chunk-ZT5ZXQC2.mjs} +1 -1
  49. package/dist-lib/esm-chunks/{metro-layout-parser-ANKZARNW.mjs → metro-layout-parser-DHGC2DVE.mjs} +3 -3
  50. package/dist-lib/esm-chunks/{swift-package-prebuilt-4N5CXBOZ.mjs → swift-package-prebuilt-ROIDLGLU.mjs} +10 -10
  51. package/dist-lib/esm-chunks/{swift-sdk-app-module-5IUSRXYA.mjs → swift-sdk-app-module-5VU63S56.mjs} +30 -20
  52. package/dist-lib/esm-chunks/{swift-sdk-image-7T2LMQS5.mjs → swift-sdk-image-SNFZVUQ3.mjs} +14 -14
  53. package/dist-lib/esm-chunks/{swift-sdk-image-producer-7QJ3BF6E.mjs → swift-sdk-image-producer-5RQDIX53.mjs} +4 -4
  54. package/dist-lib/expo-swift-bundle.cjs +3561 -3134
  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 +6082 -5142
  59. package/dist-lib/host/fetch-proxy-handler.cjs +314 -301
  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 +241 -226
  73. package/dist-lib/native-app-identity-project.mjs +17 -17
  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 +75 -73
  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 +6704 -5764
  93. package/dist-lib/swift-compile.cjs +1333 -922
  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 +12 -6
  102. package/dist-lib/swift.cjs +1 -1
  103. package/dist-lib/vendor/@peculiar/x509.cjs +1 -1
  104. package/dist-lib/vendor/@ruby/prism/src/nodes.js.cjs +1 -1
  105. package/dist-lib/vendor/@ruby/prism/src/parsePrism.js.cjs +1 -1
  106. package/dist-lib/vendor/@xmldom/xmldom.cjs +1 -1
  107. package/dist-lib/vendor/acorn.cjs +1 -1
  108. package/dist-lib/vendor/bplist-parser.cjs +1 -1
  109. package/dist-lib/vendor/ignore.cjs +1 -1
  110. package/dist-lib/vendor/magic-string.cjs +1 -1
  111. package/dist-lib/vendor/plist.cjs +1 -1
  112. package/dist-lib/vendor/smol-toml.cjs +1 -1
  113. package/dist-lib/vendor/stream-json.cjs +1 -1
  114. package/dist-lib/vendor/sucrase/dist/index.js.cjs +1 -1
  115. package/dist-lib/vendor/sucrase/dist/parser/index.js.cjs +1 -1
  116. package/dist-lib/vendor/sucrase/dist/parser/tokenizer/index.js.cjs +1 -1
  117. package/dist-lib/vendor/sucrase/dist/parser/tokenizer/types.js.cjs +1 -1
  118. package/dist-lib/vendor/sucrase.cjs +1 -1
  119. package/dist-lib/vendor/terser.cjs +1 -1
  120. package/dist-lib/vendor/valibot.cjs +1 -1
  121. package/dist-lib/vendor/ws.cjs +1 -1
  122. package/dist-lib/vendor/zod.cjs +1 -1
  123. package/dist-lib/worklet-executable.cjs +1 -1
  124. package/dist-lib/worklet-executable.mjs +3 -3
  125. package/dist-types/packages/peach-engine/src/engine/native-node-queries.d.ts +1 -0
  126. package/kotlin/sdk.tar.gz +0 -0
  127. package/package.json +1 -1
  128. package/runtime-companion.json +1 -1
  129. package/src/binaryen.lock.json +3 -3
  130. package/src/native-bundles.ts +2 -0
  131. package/src/one-native-controls-package.ts +235 -40
  132. package/src/one-sdk/source.ts +2 -1
  133. package/src/one-sdk-preparation.ts +40 -2
  134. package/src/oneSdkContract.ts +13 -2
  135. package/src/swift-compile.ts +301 -48
  136. package/src/swift-guest-compile.ts +11 -2
  137. package/src/swift-guest-projection-storage.ts +45 -26
  138. package/src/swift-guest-runtime-plan.ts +1 -1
  139. package/src/swift-host.ts +88 -16
  140. package/src/swift-reproducible.ts +16 -2
  141. package/src/swift-root-lock.ts +77 -5
  142. package/src/swift-sdk-app-module.ts +15 -6
  143. package/src/swift-sdk-image-wasm.ts +5 -2
  144. package/src/swift-sdk-image.ts +122 -59
  145. package/src/swift-startup-split.ts +65 -27
  146. package/src/swift-toolchain.ts +16 -5
  147. package/src/swift-wasm-prune.ts +51 -34
  148. package/src/wasm-lazy-split.ts +46 -40
  149. package/src/wasm-optimize.ts +146 -140
@@ -34,13 +34,13 @@ import { SWIFT_HMR_PATH, SWIFT_PACKAGE_PATH } from './swift-submit'
34
34
  import { swiftCacheDir } from './swift-toolchain'
35
35
  import {
36
36
  instrumentNativeWasm,
37
- mergeNativeWasmProfiles,
38
37
  sealNativeWasmSplit,
39
38
  splitNativeWasm,
40
39
  } from './wasm-lazy-split'
41
40
  import {
42
41
  makeWasmFunctionNamesSingleLine,
43
42
  readWasmCustomSection,
43
+ readWasmFunctionCount,
44
44
  readWasmMemory,
45
45
  } from './wasm-narrow-boundary'
46
46
  import { installWasmOpt } from './wasm-optimize'
@@ -181,6 +181,27 @@ export async function splitSwiftApp(
181
181
  )
182
182
  }
183
183
 
184
+ // canonicalize binaryen wasm-split profiles (8-byte module hash + u32 slots) to a
185
+ // presence bitset (0 or 1 per function) and union them in memory without spawning
186
+ // wasm-split --merge-profiles. identical hot sets always share one cache hash even
187
+ // when execution timestamps differ.
188
+ function mergeProfileBitsets(files: readonly Buffer[]): Buffer {
189
+ const first = files[0]
190
+ if (!first || first.length < 8 || (first.length - 8) % 4 !== 0)
191
+ throw new Error('invalid native startup profile buffer')
192
+ const merged = Buffer.allocUnsafe(first.length)
193
+ first.copy(merged, 0, 0, 8)
194
+ merged.fill(0, 8)
195
+ const header = first.subarray(0, 8)
196
+ for (const file of files) {
197
+ if (file.length !== first.length || !file.subarray(0, 8).equals(header))
198
+ throw new Error('native startup profiles do not match the same sdk image')
199
+ for (let offset = 8; offset < file.length; offset += 4)
200
+ if (file.readUInt32LE(offset) !== 0) merged.writeUInt32LE(1, offset)
201
+ }
202
+ return merged
203
+ }
204
+
184
205
  /**
185
206
  * splits a shared sdk image by the merged startup of every app profiled on it: each app's
186
207
  * profile stays beside the image, and a new app's profile widens the startup file.
@@ -195,34 +216,40 @@ export async function splitSwiftSdkImage(
195
216
  const prefix = `${app}-`
196
217
  const own = join(profiles, `${prefix}${launch.artifactHash}.profile`)
197
218
  const names = () =>
198
- readdirSync(profiles)
199
- .filter((name) => !name.startsWith('.') && name.endsWith('.profile'))
200
- .sort()
219
+ existsSync(profiles)
220
+ ? readdirSync(profiles)
221
+ .filter((name) => !name.startsWith('.') && name.endsWith('.profile'))
222
+ .sort()
223
+ : []
201
224
  const union = () => {
202
- const files = names().map((name) => readFileSync(join(profiles, name)))
203
- const hash = createHash('sha256')
204
- for (const file of files) hash.update(file)
225
+ const merged = mergeProfileBitsets(
226
+ names().map((name) => readFileSync(join(profiles, name))),
227
+ )
205
228
  const cache = join(
206
229
  directory,
207
- `startup-v11-${platform}-${hash.digest('hex').slice(0, 16)}`,
230
+ `startup-v11-${platform}-${digest(merged).slice(0, 16)}`,
208
231
  )
209
- return { files, cache }
232
+ return { merged, cache }
210
233
  }
234
+ // an existing profile for this normalized app on the same sdk image already covers its
235
+ // startup paths; any newly called sdk function loads lazily on demand.
211
236
  const current = () =>
212
- withSwiftRootLock(profiles, async () => (existsSync(own) ? union() : undefined))
237
+ withSwiftRootLock(profiles, async () =>
238
+ names().some((name) => name.startsWith(prefix)) ? union() : undefined,
239
+ )
213
240
  const available = await current()
214
241
  if (available) {
215
242
  const ready = readSwiftStartupImage(available.cache)
216
243
  if (ready) return ready
217
244
  }
218
245
  return withStartupWork(bytes, async (work) => {
219
- const { files, cache } =
246
+ const { merged, cache } =
220
247
  available ??
221
- (await withSwiftRootLock(own, async () => {
248
+ (await withSwiftRootLock(join(profiles, `${prefix}record`), async () => {
222
249
  const alreadyRecorded = await current()
223
250
  if (alreadyRecorded) return alreadyRecorded
224
251
  const recorded = join(work.directory, 'app.profile')
225
- await profileStartup(work, launch, 'sdkUrl', recorded)
252
+ await profileStartup(work, launch, 'sdkUrl', recorded, directory)
226
253
  return withSwiftRootLock(profiles, async () => {
227
254
  mkdirSync(profiles, { recursive: true })
228
255
  const pending = join(profiles, `.${prefix}${launch.artifactHash}.profile`)
@@ -238,15 +265,10 @@ export async function splitSwiftSdkImage(
238
265
  return withSwiftRootLock(cache, async () => {
239
266
  const existing = readSwiftStartupImage(cache)
240
267
  if (existing) return existing
241
- const inputs = files.map((file, index) => {
242
- const input = join(work.directory, `input-${index}.profile`)
243
- writeFileSync(input, file)
244
- return input
245
- })
246
- const merged = join(work.directory, 'merged.profile')
247
- await mergeNativeWasmProfiles(work.binaryen, inputs, merged)
268
+ const mergedPath = join(work.directory, 'merged.profile')
269
+ writeFileSync(mergedPath, merged)
248
270
  // an app outside the profiled set misses sdk code, so a miss loads a small part
249
- return storeStartupSplit(work, merged, directory, cache, 1 << 18)
271
+ return storeStartupSplit(work, mergedPath, directory, cache, 1 << 18)
250
272
  })
251
273
  })
252
274
  }
@@ -280,13 +302,29 @@ async function profileStartup(
280
302
  launch: SwiftStartupLaunch,
281
303
  role: 'url' | 'sdkUrl',
282
304
  output: string,
305
+ sharedDirectory?: string,
283
306
  ) {
284
- const instrumented = join(work.directory, 'instrumented.wasm')
285
- const functionCount = await instrumentNativeWasm(
286
- work.original,
287
- instrumented,
288
- work.binaryen,
289
- )
307
+ let instrumented = join(work.directory, 'instrumented.wasm')
308
+ let functionCount: number
309
+ if (sharedDirectory) {
310
+ const cachedInstrumented = join(sharedDirectory, `instrumented-v1-${platform}.wasm`)
311
+ if (!existsSync(cachedInstrumented)) {
312
+ await withSwiftRootLock(cachedInstrumented, async () => {
313
+ if (existsSync(cachedInstrumented)) return
314
+ const pending = join(sharedDirectory, `.instrumented-${process.pid}.wasm`)
315
+ try {
316
+ await instrumentNativeWasm(work.original, pending, work.binaryen)
317
+ renameSync(pending, cachedInstrumented)
318
+ } finally {
319
+ rmSync(pending, { force: true })
320
+ }
321
+ })
322
+ }
323
+ instrumented = cachedInstrumented
324
+ functionCount = readWasmFunctionCount(work.bytes)
325
+ } else {
326
+ functionCount = await instrumentNativeWasm(work.original, instrumented, work.binaryen)
327
+ }
290
328
  writeFileSync(
291
329
  output,
292
330
  await bootSwiftPreview(launch, { instrumented, functionCount, role }),
@@ -490,7 +490,8 @@ export function swiftToolchainBin(release: string): string {
490
490
  const dirs = [os.homedir(), '/'].map((base) =>
491
491
  path.join(base, `Library/Developer/Toolchains/${release}.xctoolchain/usr/bin`),
492
492
  )
493
- return dirs.find((dir) => fs.existsSync(path.join(dir, 'swift'))) ?? dirs[0]!
493
+ const found = dirs.find((dir) => fs.existsSync(path.join(dir, 'swift')))
494
+ return found ? fs.realpathSync(found) : dirs[0]!
494
495
  }
495
496
  if (process.env.CONTRAST_SWIFT_TOOLCHAINS) {
496
497
  return path.join(process.env.CONTRAST_SWIFT_TOOLCHAINS, release, 'usr/bin')
@@ -557,7 +558,11 @@ exec ${JSON.stringify(path.join(toolchainBin, 'wasm-ld'))} "$@"
557
558
  // home-paths.ts's rnxHomeDir, repeated because this file imports node builtins only.
558
559
  export function peachHome(): string {
559
560
  const override = process.env.PEACH_HOME
560
- return override ? path.resolve(override) : path.join(os.homedir(), '.peach')
561
+ if (override) return path.resolve(override)
562
+ const home = path.join(os.homedir(), '.peach')
563
+ // agent profiles symlink ~/.peach to the host user's ~/.peach; canonicalize so
564
+ // swift-sdk-views hashes and llbuild plans match across sessions on one host.
565
+ return fs.existsSync(home) ? fs.realpathSync(home) : home
561
566
  }
562
567
 
563
568
  /** where the pinned wasm SDK installs unless PEACH_SWIFT_SDKS_PATH names another. */
@@ -625,11 +630,17 @@ function buildersRootEnv(): string | null {
625
630
  return root ? root : null
626
631
  }
627
632
 
633
+ // mac agent sessions without an explicit private PEACH_HOME share the machine's
634
+ // resolved builders cache rather than cold-rebuilding SDK images on internal disk.
635
+ function resolvedBuildersRoot(): string | null {
636
+ return buildersRootEnv() ?? (process.env.PEACH_HOME ? null : agentSharedCacheRoot())
637
+ }
638
+
628
639
  // machine-wide swift scratch and package caches, shared across lanes. keep
629
640
  // their implementation with the compiler so daemon edits cannot cold-split
630
641
  // the twin warm trees. the complete implementation remains a hashed input.
631
642
  export function swiftCacheDir(): string {
632
- const root = buildersRootEnv()
643
+ const root = resolvedBuildersRoot()
633
644
  return root ? path.join(root, 'peach-cache') : path.join(peachHome(), 'cache')
634
645
  }
635
646
 
@@ -647,7 +658,7 @@ export function refreshSwiftCacheHold(directory: string): void {
647
658
  const [kind, key] = relative.split(path.sep)
648
659
  if (!key || kind === '..' || path.isAbsolute(relative)) return
649
660
  const entry = path.join(cacheRoot, kind, key)
650
- if (!buildersRootEnv()) {
661
+ if (!resolvedBuildersRoot()) {
651
662
  const now = new Date()
652
663
  fs.utimesSync(entry, now, now)
653
664
  return
@@ -665,7 +676,7 @@ export function refreshSwiftCacheHold(directory: string): void {
665
676
  }
666
677
 
667
678
  export function hasSwiftCacheHold(directory: string): boolean {
668
- if (!buildersRootEnv()) return false
679
+ if (!resolvedBuildersRoot()) return false
669
680
  const marker = fs.lstatSync(path.join(directory, SWIFT_CACHE_HOLD_MARKER), {
670
681
  throwIfNoEntry: false,
671
682
  })
@@ -810,18 +810,32 @@ function parseWasmObjectBytes(
810
810
  dataOwnerSymIdx[kept] = ownerSymIdx
811
811
  kept++
812
812
  }
813
- const dataRelocs: DataRelocs = {
814
- count: kept,
815
- bytes: rawData.bytes,
816
- start: rawData.start.slice(0, kept),
817
- end: rawData.end.slice(0, kept),
818
- ro: rawData.ro.slice(0, kept),
819
- rs: rawData.rs.slice(0, kept),
820
- addend: rawData.addend.slice(0, kept),
821
- segIdx: dataSegIdx.slice(0, kept),
822
- offInSeg: dataOffInSeg.slice(0, kept),
823
- ownerSymIdx: dataOwnerSymIdx.slice(0, kept),
824
- }
813
+ const dataRelocs: DataRelocs =
814
+ kept === rawData.count
815
+ ? {
816
+ count: kept,
817
+ bytes: rawData.bytes,
818
+ start: rawData.start,
819
+ end: rawData.end,
820
+ ro: rawData.ro,
821
+ rs: rawData.rs,
822
+ addend: rawData.addend,
823
+ segIdx: dataSegIdx,
824
+ offInSeg: dataOffInSeg,
825
+ ownerSymIdx: dataOwnerSymIdx,
826
+ }
827
+ : {
828
+ count: kept,
829
+ bytes: rawData.bytes,
830
+ start: rawData.start.slice(0, kept),
831
+ end: rawData.end.slice(0, kept),
832
+ ro: rawData.ro.slice(0, kept),
833
+ rs: rawData.rs.slice(0, kept),
834
+ addend: rawData.addend.slice(0, kept),
835
+ segIdx: dataSegIdx.slice(0, kept),
836
+ offInSeg: dataOffInSeg.slice(0, kept),
837
+ ownerSymIdx: dataOwnerSymIdx.slice(0, kept),
838
+ }
825
839
 
826
840
  // swift places constant metadata in one explicit .rodata segment, and the
827
841
  // assembler folds a relative pointer between two symbols of that segment
@@ -829,26 +843,29 @@ function parseWasmObjectBytes(
829
843
  // nested type's parent). a relocation-free word that lands on another
830
844
  // symbol's start, past swift's two low int-pair flag bits, keeps that symbol
831
845
  // live as a relocation would; a coincidental match only keeps extra data.
832
- const relocatedWords = new Map<number, Set<number>>()
833
- for (let i = 0; i < dataRelocs.count; i++) {
834
- const segIdx = dataRelocs.segIdx[i]!
835
- let words = relocatedWords.get(segIdx)
836
- if (!words) relocatedWords.set(segIdx, (words = new Set()))
837
- words.add(dataRelocs.offInSeg[i]!)
838
- }
839
- for (const [segIdx, tops] of segTopSyms) {
840
- const starts = new Map(tops.map((top) => [top.off, top.symIdx]))
841
- const relocated = relocatedWords.get(segIdx)
842
- const payload = dataStart + sPayloadStarts[segIdx]!
843
- const view = new DataView(buf.buffer, buf.byteOffset + payload)
844
- for (const top of tops) {
845
- for (let at = top.off; at + 4 <= top.end; at += 4) {
846
- if (relocated?.has(at)) continue
847
- const target = starts.get(at + (view.getInt32(at, true) & ~3))
848
- if (target === undefined || target === top.symIdx) continue
849
- let list = symDataRelocs.get(top.symIdx)
850
- if (!list) symDataRelocs.set(top.symIdx, (list = []))
851
- list.push(target)
846
+ if (segTopSyms.size > 0) {
847
+ const relocatedWords = new Map<number, Set<number>>()
848
+ for (let i = 0; i < dataRelocs.count; i++) {
849
+ const segIdx = dataRelocs.segIdx[i]!
850
+ if (!segTopSyms.has(segIdx)) continue
851
+ let words = relocatedWords.get(segIdx)
852
+ if (!words) relocatedWords.set(segIdx, (words = new Set()))
853
+ words.add(dataRelocs.offInSeg[i]!)
854
+ }
855
+ for (const [segIdx, tops] of segTopSyms) {
856
+ const starts = new Map(tops.map((top) => [top.off, top.symIdx]))
857
+ const relocated = relocatedWords.get(segIdx)
858
+ const payload = dataStart + sPayloadStarts[segIdx]!
859
+ const view = new DataView(buf.buffer, buf.byteOffset + payload)
860
+ for (const top of tops) {
861
+ for (let at = top.off; at + 4 <= top.end; at += 4) {
862
+ if (relocated?.has(at)) continue
863
+ const target = starts.get(at + (view.getInt32(at, true) & ~3))
864
+ if (target === undefined || target === top.symIdx) continue
865
+ let list = symDataRelocs.get(top.symIdx)
866
+ if (!list) symDataRelocs.set(top.symIdx, (list = []))
867
+ list.push(target)
868
+ }
852
869
  }
853
870
  }
854
871
  }
@@ -1056,7 +1073,7 @@ function parseWasmObjectBytes(
1056
1073
  }
1057
1074
 
1058
1075
  function parseWasmObjectFile(file: string, isDist: boolean): ParsedObject {
1059
- return parseWasmObjectBytes(file, new Uint8Array(fs.readFileSync(file)), isDist)
1076
+ return parseWasmObjectBytes(file, fs.readFileSync(file), isDist)
1060
1077
  }
1061
1078
 
1062
1079
  function parseWasmObjectCached(
@@ -1080,7 +1097,7 @@ export function localizeDefinedWasmSymbols(
1080
1097
  ): Uint8Array {
1081
1098
  const offsets: number[] = []
1082
1099
  const object = parseWasmObjectBytes('', bytes, false, offsets)
1083
- const output = Uint8Array.from(bytes)
1100
+ const output = new Uint8Array(bytes)
1084
1101
  let changed = 0
1085
1102
  for (let index = 0; index < object.symNames.length; index++) {
1086
1103
  if (!names.has(object.symNames[index]!)) continue
@@ -117,19 +117,6 @@ export async function instrumentNativeWasm(
117
117
  return count
118
118
  }
119
119
 
120
- export async function mergeNativeWasmProfiles(
121
- binaryen: string,
122
- profiles: readonly string[],
123
- output: string,
124
- ): Promise<void> {
125
- await run(join(dirname(binaryen), 'wasm-split'), [
126
- '--merge-profiles',
127
- ...profiles,
128
- '-o',
129
- output,
130
- ])
131
- }
132
-
133
120
  // split after lowering and profile collection, before either image's table guard.
134
121
  export async function splitNativeWasm(
135
122
  input: string,
@@ -168,33 +155,52 @@ export async function splitNativeWasm(
168
155
  const source = join(directory, 'source.wasm')
169
156
  writeFileSync(source, prepared)
170
157
  const named = keepNames || !!placement
171
- const symbols = await run(binaryen, [source, ...features, '--print-function-map'], {
172
- maxBuffer: Infinity,
173
- })
174
- const startup = await run(splitter, [...features, '--print-profile', profile, input], {
175
- maxBuffer: Infinity,
176
- })
177
- const bytes = readFileSync(source)
178
- const sizes = readWasmCodeLengths(bytes)
158
+ const sizes = readWasmCodeLengths(prepared)
179
159
  if (!sizes.length) return { primary: describePart(input), sides: [] }
180
- const startIndex = readWasmStartFunction(bytes)
181
- const names = symbols.stdout
182
- .trimEnd()
183
- .split('\n')
184
- .slice(-sizes.length)
185
- .map((line) => {
186
- const separator = line.indexOf(':')
187
- if (separator < 1) throw new Error('invalid Binaryen function map')
188
- return { index: Number(line.slice(0, separator)), name: line.slice(separator + 1) }
189
- })
160
+ const startIndex = readWasmStartFunction(prepared)
161
+ const names = readWasmCustomSection(prepared, 'name')
162
+ ? (
163
+ await run(binaryen, [source, ...features, '--print-function-map'], {
164
+ maxBuffer: Infinity,
165
+ })
166
+ ).stdout
167
+ .trimEnd()
168
+ .split('\n')
169
+ .slice(-sizes.length)
170
+ .map((line) => {
171
+ const separator = line.indexOf(':')
172
+ if (separator < 1) throw new Error('invalid Binaryen function map')
173
+ return {
174
+ index: Number(line.slice(0, separator)),
175
+ name: line.slice(separator + 1),
176
+ }
177
+ })
178
+ : (() => {
179
+ let importedFuncs = 0
180
+ const importSection = wasmSections(prepared).find(({ id }) => id === 2)
181
+ if (importSection)
182
+ readWasmImports(prepared, importSection, ({ kind }) => {
183
+ if (kind === 0) importedFuncs++
184
+ })
185
+ return Array.from({ length: sizes.length }, (_, ordinal) => ({
186
+ index: importedFuncs + ordinal,
187
+ name: String(ordinal),
188
+ }))
189
+ })()
190
190
  if (names.length !== sizes.length)
191
191
  throw new Error('Binaryen function map is incomplete')
192
- const hot = new Set(
193
- startup.stdout
194
- .split('\n')
195
- .filter((line) => line.startsWith('+ '))
196
- .map((line) => line.slice(2)),
192
+ const profileBytes = readFileSync(profile)
193
+ const expectedProfileSlots = readWasmFunctionCount(delivered)
194
+ if (
195
+ profileBytes.length < 8 ||
196
+ profileBytes.length !== 8 + expectedProfileSlots * 4 ||
197
+ expectedProfileSlots < sizes.length
197
198
  )
199
+ throw new Error('native startup profile size does not match module function count')
200
+ const hot = new Set<string>()
201
+ for (let ordinal = 0; ordinal < sizes.length; ordinal++) {
202
+ if (profileBytes.readUInt32LE(8 + ordinal * 4) !== 0) hot.add(names[ordinal]!.name)
203
+ }
198
204
  if (hot.size === 0)
199
205
  throw new Error('native startup profile contains no executed functions')
200
206
  const lazyAt = new Map<number, number[]>()
@@ -371,11 +377,11 @@ export async function splitNativeWasm(
371
377
  if (!parts.length) return { primary: describePart(input), sides: [] }
372
378
  const admitted = windowAdmission()?.cores ?? Number(process.env.TM_EXEC_CPU_CORES)
373
379
  const requested = Number(process.env.BINARYEN_CORES)
380
+ const cores = Math.max(1, availableParallelism())
374
381
  const jobs = Math.min(
375
- 8,
376
- availableParallelism(),
377
- Number.isInteger(admitted) && admitted > 0 ? admitted : 8,
378
- Number.isInteger(requested) && requested > 0 ? requested : 8,
382
+ cores,
383
+ Number.isInteger(admitted) && admitted > 0 ? admitted : cores,
384
+ Number.isInteger(requested) && requested > 0 ? requested : cores,
379
385
  )
380
386
  const env = jobs > 1 ? { ...process.env, BINARYEN_CORES: '1' } : undefined
381
387
  const sides = await mapLimit(