peachsim 0.1.2591 → 0.1.2592

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 (139) 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 +3872 -3531
  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-67PU73QE.mjs} +3 -3
  27. package/dist-lib/esm-chunks/{chunk-UYJXLDCG.mjs → chunk-5FTHILIE.mjs} +1 -1
  28. package/dist-lib/esm-chunks/{chunk-JHXDM3YU.mjs → chunk-6DB5FR7S.mjs} +1 -1
  29. package/dist-lib/esm-chunks/{chunk-EGKH2L6J.mjs → chunk-CF3MTPMY.mjs} +1 -1
  30. package/dist-lib/esm-chunks/{chunk-MC6NMYWY.mjs → chunk-D4LYKRRB.mjs} +1 -1
  31. package/dist-lib/esm-chunks/{chunk-QBMFX3J2.mjs → chunk-DFF5XZ5M.mjs} +1 -1
  32. package/dist-lib/esm-chunks/{chunk-Q4NA6PUR.mjs → chunk-EHRSWFTD.mjs} +3 -3
  33. package/dist-lib/esm-chunks/{chunk-4QHHRGO4.mjs → chunk-EITX573K.mjs} +1 -1
  34. package/dist-lib/esm-chunks/{chunk-J676B57D.mjs → chunk-EWHA6X3Z.mjs} +5 -5
  35. package/dist-lib/esm-chunks/{chunk-AKKHSVJ4.mjs → chunk-FYXXFYML.mjs} +1 -1
  36. package/dist-lib/esm-chunks/{chunk-ILWFGZWW.mjs → chunk-GQ3EO2UV.mjs} +107 -6
  37. package/dist-lib/esm-chunks/{chunk-VD27WNCT.mjs → chunk-GY6TE4B4.mjs} +4 -4
  38. package/dist-lib/esm-chunks/{chunk-NX23AMX4.mjs → chunk-KDI5YYQ6.mjs} +1 -1
  39. package/dist-lib/esm-chunks/{chunk-VYZ5DC3M.mjs → chunk-L5T3HBPO.mjs} +792 -514
  40. package/dist-lib/esm-chunks/{chunk-7627LKJK.mjs → chunk-M4QLI2SY.mjs} +1 -1
  41. package/dist-lib/esm-chunks/{chunk-UIVXVMS5.mjs → chunk-PITO2NI2.mjs} +2 -2
  42. package/dist-lib/esm-chunks/{chunk-SOAYP72T.mjs → chunk-QSFWBVUO.mjs} +1 -1
  43. package/dist-lib/esm-chunks/{chunk-TFG4LZ5T.mjs → chunk-R3WTQB5J.mjs} +1 -1
  44. package/dist-lib/esm-chunks/{chunk-ZL5N6ENT.mjs → chunk-RV4ACE6R.mjs} +1 -1
  45. package/dist-lib/esm-chunks/{chunk-YR6DNV76.mjs → chunk-SW4PSSTF.mjs} +1 -1
  46. package/dist-lib/esm-chunks/{chunk-VF5WVB3D.mjs → chunk-TJZPNFVF.mjs} +1 -1
  47. package/dist-lib/esm-chunks/{chunk-VRVXRZI4.mjs → chunk-XSQH4R5E.mjs} +48 -15
  48. package/dist-lib/esm-chunks/{chunk-RKQZGWX2.mjs → chunk-XZ3FX3HW.mjs} +1 -1
  49. package/dist-lib/esm-chunks/{metro-layout-parser-ANKZARNW.mjs → metro-layout-parser-EX65MARK.mjs} +3 -3
  50. package/dist-lib/esm-chunks/{swift-package-prebuilt-4N5CXBOZ.mjs → swift-package-prebuilt-3BPDQVA7.mjs} +10 -10
  51. package/dist-lib/esm-chunks/{swift-sdk-app-module-5IUSRXYA.mjs → swift-sdk-app-module-CRX6E3TR.mjs} +14 -14
  52. package/dist-lib/esm-chunks/{swift-sdk-image-7T2LMQS5.mjs → swift-sdk-image-EJD5TPQH.mjs} +14 -14
  53. package/dist-lib/esm-chunks/{swift-sdk-image-producer-7QJ3BF6E.mjs → swift-sdk-image-producer-QAZOSLTZ.mjs} +4 -4
  54. package/dist-lib/expo-swift-bundle.cjs +3243 -2905
  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 +5669 -4904
  59. package/dist-lib/host/fetch-proxy-handler.cjs +310 -298
  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 +238 -223
  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 +73 -71
  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 +6291 -5526
  93. package/dist-lib/swift-compile.cjs +1051 -696
  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/package.json +1 -1
  127. package/runtime-companion.json +1 -1
  128. package/src/native-bundles.ts +2 -0
  129. package/src/one-native-controls-package.ts +141 -31
  130. package/src/one-sdk/source.ts +2 -1
  131. package/src/oneSdkContract.ts +13 -2
  132. package/src/swift-compile.ts +301 -48
  133. package/src/swift-host.ts +88 -16
  134. package/src/swift-reproducible.ts +16 -2
  135. package/src/swift-root-lock.ts +77 -5
  136. package/src/swift-sdk-image.ts +53 -10
  137. package/src/swift-startup-split.ts +65 -27
  138. package/src/swift-toolchain.ts +16 -5
  139. package/src/wasm-lazy-split.ts +46 -40
@@ -1,5 +1,6 @@
1
1
  import {
2
2
  spawn,
3
+ spawnSync,
3
4
  execFileSync,
4
5
  type ExecFileOptions,
5
6
  type SpawnOptions,
@@ -126,7 +127,14 @@ import {
126
127
  type SwiftProjectUser,
127
128
  } from './swift-project-user'
128
129
  import { swiftReproducibleBuildFlags } from './swift-reproducible'
129
- import { withSwiftRootLock, type SwiftRootLease } from './swift-root-lock'
130
+ import {
131
+ acquireSwiftRootReadHold,
132
+ hasLiveSwiftRootReaders,
133
+ waitForNoSwiftRootReaders,
134
+ withSwiftRootLock,
135
+ type SwiftRootLease,
136
+ type SwiftRootReadHold,
137
+ } from './swift-root-lock'
130
138
  import { orderObjCConstructors } from './swift-sdk-image-wasm'
131
139
  import {
132
140
  swiftSharedSdkInputFiles,
@@ -821,10 +829,13 @@ function swiftObjCSelectorOptions(moduleRoot: string): string[] {
821
829
  ))
822
830
  classes[name] = [...(classes[name] ?? []), ...members]
823
831
  map = path.join(moduleRoot, '.build', SWIFT_DISTRIBUTION_OBJC_SELECTORS)
824
- mkdirSync(path.dirname(map), { recursive: true })
825
- const partial = `${map}.${randomUUID()}`
826
- writeFileSync(partial, `${JSON.stringify({ classes }, null, 2)}\n`)
827
- renameSync(partial, map)
832
+ const content = `${JSON.stringify({ classes }, null, 2)}\n`
833
+ if (!existsSync(map) || readFileSync(map, 'utf8') !== content) {
834
+ mkdirSync(path.dirname(map), { recursive: true })
835
+ const partial = `${map}.${randomUUID()}`
836
+ writeFileSync(partial, content)
837
+ renameSync(partial, map)
838
+ }
828
839
  }
829
840
  return ['-Xswiftc', '-Xllvm', '-Xswiftc', `-peach-objc-selector-map=${map}`]
830
841
  }
@@ -989,6 +1000,73 @@ export function clearLinkedModuleDigests(root?: string): void {
989
1000
  else linkedModuleDigests.delete(root)
990
1001
  }
991
1002
 
1003
+ // a clean git worktree shares the exact same source bytes as any other worktree
1004
+ // on the same tree/blob OIDs. hashing the git OIDs avoids reading 14k+ files on
1005
+ // every fresh worktree while still falling back to full reads on any dirty input.
1006
+ function gitCleanModuleInputsKey(root: string, files: readonly string[]): string | null {
1007
+ if (swiftDistributionAt(root)) return null
1008
+ const top = spawnSync('git', ['-C', root, 'rev-parse', '--show-toplevel'], {
1009
+ encoding: 'utf8',
1010
+ stdio: ['ignore', 'pipe', 'ignore'],
1011
+ })
1012
+ if (top.status !== 0) return null
1013
+ const repoTop = top.stdout.trim()
1014
+ if (!repoTop) return null
1015
+ const realTop = realpathSync(repoTop)
1016
+ const realRoot = realpathSync(root)
1017
+ const collapsedDirs = [
1018
+ path.join(realRoot, 'Sources'),
1019
+ path.join(realRoot, 'cross-import-overlays'),
1020
+ path.join(realRoot, 'ios-simulator-stdlib'),
1021
+ realpathSync(path.resolve(realRoot, '../peachsim/sdk/ios')),
1022
+ ]
1023
+ const scoped = new Set<string>()
1024
+ for (const dir of collapsedDirs) {
1025
+ const rel = path.relative(realTop, dir).split(path.sep).join('/')
1026
+ if (!rel || rel.startsWith('../')) return null
1027
+ scoped.add(rel)
1028
+ }
1029
+ for (const file of files) {
1030
+ const full = path.resolve(realRoot, file)
1031
+ if (collapsedDirs.some((dir) => full.startsWith(dir + path.sep))) continue
1032
+ const rel = path.relative(realTop, full).split(path.sep).join('/')
1033
+ if (!rel || rel.startsWith('../')) return null
1034
+ scoped.add(rel)
1035
+ }
1036
+ const paths = [...scoped].sort()
1037
+ const status = spawnSync(
1038
+ 'git',
1039
+ [
1040
+ '-C',
1041
+ realTop,
1042
+ 'status',
1043
+ '--porcelain',
1044
+ '--untracked-files=all',
1045
+ '--ignored=matching',
1046
+ '--',
1047
+ ...paths,
1048
+ ],
1049
+ {
1050
+ encoding: 'utf8',
1051
+ stdio: ['ignore', 'pipe', 'ignore'],
1052
+ maxBuffer: 16 * 1024 * 1024,
1053
+ },
1054
+ )
1055
+ if (status.status !== 0 || status.stdout.trim().length > 0) return null
1056
+ const oids = spawnSync(
1057
+ 'git',
1058
+ ['-C', realTop, 'rev-parse', ...paths.map((entry) => `HEAD:${entry}`)],
1059
+ { encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] },
1060
+ )
1061
+ if (oids.status !== 0) return null
1062
+ const keyHash = createHash('sha256')
1063
+ keyHash.update('git-module-digest/v1\n')
1064
+ keyHash.update(oids.stdout)
1065
+ keyHash.update('\n')
1066
+ for (const file of files) keyHash.update(file).update('\n')
1067
+ return keyHash.digest('hex')
1068
+ }
1069
+
992
1070
  /** the digest of a module checkout's inputs: what an artifact address and a
993
1071
  * distribution's id name it by. */
994
1072
  export function swiftModuleDigest(root: string): Buffer {
@@ -1006,11 +1084,17 @@ export function swiftModuleDigest(root: string): Buffer {
1006
1084
  if (cached?.stamp === stamp) return cached.digest
1007
1085
  // a source checkout holds thousands of inputs, so a fresh bridge reuses the
1008
1086
  // digest an earlier process recorded under the same stamp.
1087
+ const digestDir = path.join(swiftCacheDir(), 'swift-module-digests')
1009
1088
  const record = path.join(
1010
- swiftCacheDir(),
1011
- 'swift-module-digests',
1089
+ digestDir,
1012
1090
  `${createHash('sha256').update(root).digest('hex')}.json`,
1013
1091
  )
1092
+ const writeRecord = (target: string, body: string) => {
1093
+ mkdirSync(path.dirname(target), { recursive: true })
1094
+ const partial = `${target}.${process.pid}.${randomUUID()}`
1095
+ writeFileSync(partial, body)
1096
+ renameSync(partial, target)
1097
+ }
1014
1098
  if (existsSync(record)) {
1015
1099
  const saved: unknown = JSON.parse(readFileSync(record, 'utf8'))
1016
1100
  if (
@@ -1024,6 +1108,22 @@ export function swiftModuleDigest(root: string): Buffer {
1024
1108
  return digest
1025
1109
  }
1026
1110
  }
1111
+ const gitKey = gitCleanModuleInputsKey(root, files)
1112
+ const gitRecord = gitKey ? path.join(digestDir, `git-${gitKey}.json`) : null
1113
+ if (gitRecord && existsSync(gitRecord)) {
1114
+ const saved: unknown = JSON.parse(readFileSync(gitRecord, 'utf8'))
1115
+ if (
1116
+ saved &&
1117
+ typeof saved === 'object' &&
1118
+ typeof Reflect.get(saved, 'digest') === 'string'
1119
+ ) {
1120
+ const hex = String(Reflect.get(saved, 'digest'))
1121
+ const digest = Buffer.from(hex, 'hex')
1122
+ linkedModuleDigests.set(root, { stamp, digest })
1123
+ writeRecord(record, JSON.stringify({ stamp, digest: hex }))
1124
+ return digest
1125
+ }
1126
+ }
1027
1127
  const hash = createHash('sha256')
1028
1128
  for (const file of files) {
1029
1129
  hash.update(createHash('sha256').update(file).digest())
@@ -1034,11 +1134,10 @@ export function swiftModuleDigest(root: string): Buffer {
1034
1134
  )
1035
1135
  }
1036
1136
  const digest = hash.digest()
1137
+ const hex = digest.toString('hex')
1037
1138
  linkedModuleDigests.set(root, { stamp, digest })
1038
- mkdirSync(path.dirname(record), { recursive: true })
1039
- const partial = `${record}.${process.pid}.${randomUUID()}`
1040
- writeFileSync(partial, JSON.stringify({ stamp, digest: digest.toString('hex') }))
1041
- renameSync(partial, record)
1139
+ writeRecord(record, JSON.stringify({ stamp, digest: hex }))
1140
+ if (gitRecord) writeRecord(gitRecord, JSON.stringify({ digest: hex }))
1042
1141
  return digest
1043
1142
  }
1044
1143
 
@@ -7567,15 +7666,97 @@ type FrameworkBuildArgs = {
7567
7666
  }
7568
7667
  }
7569
7668
 
7669
+ const frameworkProductsReceiptSchema = v.object({
7670
+ modules: v.string(),
7671
+ objects: v.array(v.string()),
7672
+ lazyObjects: v.array(v.string()),
7673
+ owners: v.array(v.tuple([v.string(), v.string()])),
7674
+ providers: v.array(v.string()),
7675
+ link: v.array(v.string()),
7676
+ moduleMaps: v.array(v.string()),
7677
+ objcHeaders: v.array(v.tuple([v.string(), v.string()])),
7678
+ archived: v.array(v.tuple([v.string(), v.string()])),
7679
+ })
7680
+
7681
+ function readFrameworkProductsReceipt(
7682
+ scratch: string,
7683
+ receiptKey: string,
7684
+ ): SwiftFrameworkProducts | null {
7685
+ const receiptFile = path.join(scratch, 'products-ready', `${receiptKey}.json`)
7686
+ if (!existsSync(receiptFile)) return null
7687
+ let parsed: v.InferOutput<typeof frameworkProductsReceiptSchema>
7688
+ try {
7689
+ parsed = v.parse(
7690
+ frameworkProductsReceiptSchema,
7691
+ JSON.parse(readFileSync(receiptFile, 'utf8')),
7692
+ )
7693
+ } catch {
7694
+ return null
7695
+ }
7696
+ const archive = path.join(scratch, 'lib')
7697
+ const archiveStamp = path.join(archive, '.receipt')
7698
+ const archiveMatches =
7699
+ existsSync(archiveStamp) && readFileSync(archiveStamp, 'utf8') === receiptKey
7700
+ if (!existsSync(parsed.modules)) return null
7701
+ for (const [object] of parsed.archived) if (!existsSync(object)) return null
7702
+ for (const file of parsed.providers) if (!existsSync(file)) return null
7703
+ for (const file of parsed.moduleMaps) if (!existsSync(file)) return null
7704
+ if (!archiveMatches) {
7705
+ rmSync(archive, { recursive: true, force: true })
7706
+ mkdirSync(archive, { recursive: true })
7707
+ for (const [object, rel] of parsed.archived)
7708
+ symlinkSync(object, path.join(scratch, rel))
7709
+ writeFileSync(archiveStamp, receiptKey)
7710
+ }
7711
+ for (const file of parsed.objects) if (!existsSync(file)) return null
7712
+ for (const file of parsed.lazyObjects) if (!existsSync(file)) return null
7713
+ return {
7714
+ root: scratch,
7715
+ modules: parsed.modules,
7716
+ objects: parsed.objects,
7717
+ lazyObjects: parsed.lazyObjects,
7718
+ owners: new Map(parsed.owners),
7719
+ providers: parsed.providers,
7720
+ link: parsed.link,
7721
+ moduleMaps: parsed.moduleMaps,
7722
+ objcHeaders: new Map(parsed.objcHeaders),
7723
+ }
7724
+ }
7725
+
7570
7726
  async function buildFrameworkProducts(
7571
7727
  scratch: string,
7572
7728
  args: FrameworkBuildArgs,
7573
7729
  ): Promise<SwiftFrameworkProducts> {
7574
7730
  const linkedTargets = linkedFrameworkTargets(args.moduleRoot, args.input)
7731
+ const unoptimized = args.input.unoptimized === true
7732
+ const sdkOptions = swiftCompileSdkOptions(args.moduleRoot, args.toolchainBin)
7733
+ const selectorOptions = swiftObjCSelectorOptions(args.moduleRoot)
7734
+ const receiptKey = createHash('sha256')
7735
+ .update(
7736
+ JSON.stringify([
7737
+ 'framework-products/v1',
7738
+ args.frameworkKey,
7739
+ unoptimized,
7740
+ args.sdk,
7741
+ args.toolchainBin,
7742
+ [...linkedTargets.products].sort(),
7743
+ darwinRecordsMinimum(),
7744
+ args.plugins,
7745
+ sdkOptions,
7746
+ selectorOptions,
7747
+ ]),
7748
+ )
7749
+ .digest('hex')
7750
+ .slice(0, 32)
7751
+ const ready = readFrameworkProductsReceipt(scratch, receiptKey)
7752
+ if (ready) return ready
7753
+ await waitForNoSwiftRootReaders(scratch, args.buildOptions.signal)
7754
+
7575
7755
  const linkRoot = path.join(scratch, 'link')
7576
7756
  writeFrameworkLinkPackage(linkRoot, args.moduleRoot, linkedTargets.products)
7757
+ const frameworkTmp = path.join(scratch, 'peach-compiler-tmp')
7758
+ mkdirSync(frameworkTmp, { recursive: true })
7577
7759
  const jobs = swiftCompilerJobs()
7578
- const unoptimized = args.input.unoptimized === true
7579
7760
  // an unoptimized target can launch multiple batch frontends at once.
7580
7761
  const targetJobs = unoptimized ? (jobs >= 4 ? 2 : 1) : jobs
7581
7762
  const driverJobs = unoptimized ? Math.max(1, Math.floor(jobs / targetJobs)) : jobs
@@ -7594,8 +7775,8 @@ async function buildFrameworkProducts(
7594
7775
  scratch,
7595
7776
  '--target',
7596
7777
  FRAMEWORK_LINK_TARGET,
7597
- ...swiftCompileSdkOptions(args.moduleRoot, args.toolchainBin),
7598
- ...swiftObjCSelectorOptions(args.moduleRoot),
7778
+ ...sdkOptions,
7779
+ ...selectorOptions,
7599
7780
  '--swift-sdk',
7600
7781
  args.sdk,
7601
7782
  '-c',
@@ -7616,13 +7797,15 @@ async function buildFrameworkProducts(
7616
7797
  String(driverJobs),
7617
7798
  ]
7618
7799
  : ['-Xswiftc', '-Osize']),
7619
- // the release link strips all debug info, so none is generated
7800
+ // the release link strips all debug info, so none is generated. keep
7801
+ // -num-threads fixed across caller core caps so llbuild does not rebuild
7802
+ // every framework target when callers alternate --cores.
7620
7803
  '-Xswiftc',
7621
7804
  '-gnone',
7622
7805
  '-Xswiftc',
7623
7806
  '-num-threads',
7624
7807
  '-Xswiftc',
7625
- String(unoptimized ? 1 : jobs),
7808
+ String(unoptimized ? 1 : Math.min(4, os.availableParallelism())),
7626
7809
  ...swiftReproducibleBuildFlags([
7627
7810
  [path.dirname(args.toolchainBin), 'toolchain'],
7628
7811
  [args.moduleRoot, 'framework'],
@@ -7641,9 +7824,14 @@ async function buildFrameworkProducts(
7641
7824
  `${plugin}#ExpoModulesMacros`,
7642
7825
  ]),
7643
7826
  ],
7827
+ // swiftpm hashes TMPDIR into its plan; keep one stable compiler scratch inside the locked slot.
7644
7828
  // the framework build's warnings alone pass the default 1 MiB cap, which kills
7645
7829
  // the build one step from the end.
7646
- { ...args.buildOptions, maxBuffer: 64 * 1024 * 1024 },
7830
+ {
7831
+ ...args.buildOptions,
7832
+ temporaryDirectory: frameworkTmp,
7833
+ maxBuffer: 64 * 1024 * 1024,
7834
+ },
7647
7835
  SWIFTPM_PROGRESS,
7648
7836
  SWIFTPM_NOISE,
7649
7837
  ).catch((error: unknown) => {
@@ -7758,7 +7946,7 @@ async function buildFrameworkProducts(
7758
7946
  ? { path: path.join(scratch, name), lazy: !roots.has(name) }
7759
7947
  : { path: object, lazy: false }
7760
7948
  })
7761
- return {
7949
+ const result: SwiftFrameworkProducts = {
7762
7950
  root: scratch,
7763
7951
  modules: path.join(release, 'Modules'),
7764
7952
  objects: linkedObjects.filter((object) => !object.lazy).map((object) => object.path),
@@ -7771,6 +7959,27 @@ async function buildFrameworkProducts(
7771
7959
  moduleMaps: linked.moduleMaps,
7772
7960
  objcHeaders: linked.objcHeaders,
7773
7961
  }
7962
+ writeFileSync(path.join(archive, '.receipt'), receiptKey)
7963
+ const receiptsDir = path.join(scratch, 'products-ready')
7964
+ mkdirSync(receiptsDir, { recursive: true })
7965
+ const receiptFile = path.join(receiptsDir, `${receiptKey}.json`)
7966
+ const partialReceipt = `${receiptFile}.${process.pid}.${randomUUID()}`
7967
+ writeFileSync(
7968
+ partialReceipt,
7969
+ JSON.stringify({
7970
+ modules: result.modules,
7971
+ objects: result.objects,
7972
+ lazyObjects: result.lazyObjects,
7973
+ owners: [...result.owners.entries()],
7974
+ providers: result.providers,
7975
+ link: result.link,
7976
+ moduleMaps: result.moduleMaps,
7977
+ objcHeaders: [...result.objcHeaders.entries()],
7978
+ archived: [...archived.entries()],
7979
+ }),
7980
+ )
7981
+ renameSync(partialReceipt, receiptFile)
7982
+ return result
7774
7983
  }
7775
7984
 
7776
7985
  // swiftpm tracks the app's own sources and the package graph, not the framework
@@ -7852,7 +8061,12 @@ async function withSwiftFrameworkSlot<T>(
7852
8061
  const source = path.join(slot, 'source', 'packages', path.basename(moduleRoot))
7853
8062
  for (const [file, contents] of inputs) {
7854
8063
  try {
7855
- if (!readFileSync(path.join(source, file)).equals(contents)) changes++
8064
+ const candidate = path.join(source, file)
8065
+ if (
8066
+ statSync(candidate).size !== contents.length ||
8067
+ !readFileSync(candidate).equals(contents)
8068
+ )
8069
+ changes++
7856
8070
  } catch (error) {
7857
8071
  if (!vanished(error)) throw error
7858
8072
  changes++
@@ -7867,9 +8081,11 @@ async function withSwiftFrameworkSlot<T>(
7867
8081
  (built.get(right.slot) ?? 0) - (built.get(left.slot) ?? 0),
7868
8082
  )
7869
8083
  for (const { slot, changes } of ranked) {
8084
+ if (await hasLiveSwiftRootReaders(slot, signal)) continue
7870
8085
  const result = await withSwiftRootLock(
7871
8086
  slot,
7872
8087
  async (lease) => {
8088
+ if (await hasLiveSwiftRootReaders(slot, signal)) return undefined
7873
8089
  console.error(
7874
8090
  `[swift-framework-cache] ${path.basename(slot)} changedInputs=${changes} totalInputs=${inputs.size}`,
7875
8091
  )
@@ -7955,6 +8171,8 @@ function stageFrameworkSource(
7955
8171
  if (hadKey !== frameworkKey) {
7956
8172
  // an interrupted restage must not look like a finished one
7957
8173
  rmSync(path.join(slot, SWIFT_FRAMEWORK_SLOT_KEY), { force: true })
8174
+ rmSync(path.join(slot, 'products-ready'), { recursive: true, force: true })
8175
+ rmSync(path.join(slot, 'lib', '.receipt'), { force: true })
7958
8176
  const moduleRestructured = mirrorTree(moduleRoot, stagedModule, '.build')
7959
8177
  const sdkRestructured = mirrorTree(
7960
8178
  swiftSharedSdkRoot(moduleRoot, false),
@@ -8309,8 +8527,38 @@ async function compileSwiftProjectOnce(
8309
8527
  work,
8310
8528
  unoptimized,
8311
8529
  )
8312
- return withFrameworkLock(async (slot, frameworkLease) => {
8530
+ const baseBuildEnv = {
8531
+ ...(options.project?.env ?? process.env),
8532
+ // shipped host plugins resolve against the selected compiler's runtime.
8533
+ ...(process.platform === 'linux'
8534
+ ? {
8535
+ LD_LIBRARY_PATH: [
8536
+ path.resolve(options.toolchainBin, '../lib/swift/linux'),
8537
+ path.resolve(options.toolchainBin, '../lib/swift/host'),
8538
+ process.env.LD_LIBRARY_PATH,
8539
+ ]
8540
+ .filter(Boolean)
8541
+ .join(':'),
8542
+ }
8543
+ : {}),
8544
+ PEACH_DEFER_WASM_LINK: '1',
8545
+ }
8546
+ // hold the exclusive framework slot lock only while staging and
8547
+ // building framework products; take a shared read hold before
8548
+ // releasing it so other builds on the same framework revision
8549
+ // compile and link their apps concurrently.
8550
+ const {
8551
+ frameworkRoot,
8552
+ compileFrameworkRoot,
8553
+ macroPlugins,
8554
+ sdk,
8555
+ icu,
8556
+ prebuilt,
8557
+ readHold,
8558
+ } = await withFrameworkLock(async (slot, frameworkLease) => {
8313
8559
  budget.startCompile()
8560
+ if (slot && swiftFrameworkSlotKey(slot) !== frameworkKey)
8561
+ await waitForNoSwiftRootReaders(slot, budget.signal)
8314
8562
  // project users own their build roots; resolve their sdk outside them.
8315
8563
  const frameworkRoot = mirrorDistribution
8316
8564
  ? syncSwiftDistributionMirror(root, moduleRoot, mirrorDistribution)
@@ -8336,28 +8584,6 @@ async function compileSwiftProjectOnce(
8336
8584
  const icu = options.linkOnly
8337
8585
  ? null
8338
8586
  : swiftIcuAsset(options.toolchainBin, sdk)
8339
- const buildOptions = {
8340
- env: {
8341
- ...(options.project?.env ?? process.env),
8342
- // shipped host plugins resolve against the selected compiler's runtime.
8343
- ...(process.platform === 'linux'
8344
- ? {
8345
- LD_LIBRARY_PATH: [
8346
- path.resolve(options.toolchainBin, '../lib/swift/linux'),
8347
- path.resolve(options.toolchainBin, '../lib/swift/host'),
8348
- process.env.LD_LIBRARY_PATH,
8349
- ]
8350
- .filter(Boolean)
8351
- .join(':'),
8352
- }
8353
- : {}),
8354
- PEACH_DEFER_WASM_LINK: '1',
8355
- },
8356
- maxBuffer: 64 * 1024 * 1024,
8357
- signal: budget.signal,
8358
- lease,
8359
- frameworkLease,
8360
- }
8361
8587
  let prebuilt: SwiftFrameworkProducts | undefined
8362
8588
  if (!distribution) {
8363
8589
  report('compiling framework products')
@@ -8369,9 +8595,35 @@ async function compileSwiftProjectOnce(
8369
8595
  sdk,
8370
8596
  toolchainBin: options.toolchainBin,
8371
8597
  plugins: macroPlugins,
8372
- buildOptions,
8598
+ buildOptions: {
8599
+ env: baseBuildEnv,
8600
+ maxBuffer: 64 * 1024 * 1024,
8601
+ signal: budget.signal,
8602
+ lease,
8603
+ frameworkLease,
8604
+ },
8373
8605
  })
8374
8606
  }
8607
+ const readHold: SwiftRootReadHold | undefined = slot
8608
+ ? acquireSwiftRootReadHold(slot)
8609
+ : undefined
8610
+ return {
8611
+ frameworkRoot,
8612
+ compileFrameworkRoot,
8613
+ macroPlugins,
8614
+ sdk,
8615
+ icu,
8616
+ prebuilt,
8617
+ readHold,
8618
+ }
8619
+ })
8620
+ const buildOptions = {
8621
+ env: baseBuildEnv,
8622
+ maxBuffer: 64 * 1024 * 1024,
8623
+ signal: budget.signal,
8624
+ lease,
8625
+ }
8626
+ try {
8375
8627
  if (options.project) removeProjectLinks(root)
8376
8628
  const packageHostMacros =
8377
8629
  process.platform === 'linux' ? input.packageHostMacros : undefined
@@ -8541,10 +8793,9 @@ async function compileSwiftProjectOnce(
8541
8793
  // the link strips debug info, so none is generated (as for the framework)
8542
8794
  '-Xswiftc',
8543
8795
  '-gnone',
8544
- '-Xswiftc',
8545
- '-num-threads',
8546
- '-Xswiftc',
8547
- String(perFile ? 1 : jobs),
8796
+ ...(incrementalPreview
8797
+ ? []
8798
+ : ['-Xswiftc', '-num-threads', '-Xswiftc', String(perFile ? 1 : jobs)]),
8548
8799
  ...swiftReproducibleBuildFlags([
8549
8800
  [path.dirname(options.toolchainBin), 'toolchain'],
8550
8801
  [compileFrameworkRoot, 'framework'],
@@ -8994,7 +9245,9 @@ async function compileSwiftProjectOnce(
8994
9245
  saveSharedArtifact(sharedRoot, artifact)
8995
9246
  report('compiled artifact verified')
8996
9247
  return retain(root, artifact)
8997
- })
9248
+ } finally {
9249
+ readHold?.release()
9250
+ }
8998
9251
  },
8999
9252
  budget.signal,
9000
9253
  )
package/src/swift-host.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import { AsyncLocalStorage } from 'node:async_hooks'
2
- import { execFile, execFileSync } from 'node:child_process'
2
+ import { execFile, execFileSync, spawn } from 'node:child_process'
3
3
  import { createHash, type Hash } from 'node:crypto'
4
4
  // the node host for every Swift preview: package inputs, one compile and
5
5
  // immutable artifact addresses. vite and the foreground CLI adapt this host.
@@ -25,7 +25,11 @@ import { type NativeAppIdentity } from './native-app-identity'
25
25
  import { readNativeAppIdentityFromXcodeTarget } from './native-app-identity-project'
26
26
  import { rustStaticLibrary } from './native-static-libraries'
27
27
  import { parsePlistSource } from './plist'
28
- import { resolveActiveRuntimeRoot } from './runtime-assets'
28
+ import {
29
+ findMonorepoRoot,
30
+ resolveActiveRuntimeRoot,
31
+ resolveDevCheckoutRuntimeRoot,
32
+ } from './runtime-assets'
29
33
  import { swiftBinaryModules } from './swift-binary-modules'
30
34
  import { normalizeSwiftCatalogPng } from './swift-catalog-png'
31
35
  import {
@@ -3339,22 +3343,45 @@ export function compileInput(
3339
3343
  )
3340
3344
  }
3341
3345
 
3342
- export function swiftBuildRoot(packagePath: string, moduleRoot: string): string {
3343
- if (process.env.CONTRAST_SWIFT_BUILD_ROOT) return process.env.CONTRAST_SWIFT_BUILD_ROOT
3344
- const distribution = swiftDistributionAt(moduleRoot)
3345
- const compilerKey = distribution
3346
- ? `${distribution.release}\0${distribution.wasmSdkChecksum}`
3347
- : moduleRoot
3346
+ function normalizedSwiftPackagePath(packagePath: string): string {
3348
3347
  const resolvedPath = path.resolve(packagePath)
3349
3348
  const parts = resolvedPath.split(path.sep)
3350
3349
  const scopedAt = Math.max(
3351
3350
  parts.lastIndexOf('peach-expo-swift'),
3352
3351
  parts.lastIndexOf('peach-nitro-swift'),
3353
3352
  )
3354
- const buildKeyPath =
3355
- scopedAt >= 0 && parts.length >= scopedAt + 3
3356
- ? parts.slice(0, scopedAt + 2).join(path.sep)
3357
- : (sourceEntries().get(resolvedPath) ?? resolvedPath)
3353
+ if (scopedAt >= 0 && parts.length >= scopedAt + 3)
3354
+ return parts.slice(0, scopedAt + 2).join(path.sep)
3355
+ const keyedAt = Math.max(
3356
+ parts.lastIndexOf('one-native-controls'),
3357
+ parts.lastIndexOf('peach-one-sdk-swift'),
3358
+ )
3359
+ if (keyedAt >= 0 && parts.length >= keyedAt + 3)
3360
+ return [...parts.slice(0, keyedAt + 1), ...parts.slice(keyedAt + 2)].join(path.sep)
3361
+ return sourceEntries().get(resolvedPath) ?? resolvedPath
3362
+ }
3363
+
3364
+ export function swiftBuildRoot(packagePath: string, moduleRoot: string): string {
3365
+ if (process.env.CONTRAST_SWIFT_BUILD_ROOT) return process.env.CONTRAST_SWIFT_BUILD_ROOT
3366
+ const distribution = swiftDistributionAt(moduleRoot)
3367
+ const resolvedModuleRoot = path.resolve(moduleRoot)
3368
+ let compilerKey = distribution
3369
+ ? `${distribution.release}\0${distribution.wasmSdkChecksum}`
3370
+ : resolvedModuleRoot
3371
+ if (
3372
+ !distribution &&
3373
+ path.basename(resolvedModuleRoot) === 'sootsim-swift' &&
3374
+ path.basename(path.dirname(resolvedModuleRoot)) === 'packages' &&
3375
+ fs.existsSync(path.join(resolvedModuleRoot, 'toolchain.json'))
3376
+ ) {
3377
+ // worktrees on the same swift toolchain share one incremental build tree;
3378
+ // swiftLinkStamp retires stale app objects whenever framework products move.
3379
+ const release = JSON.parse(
3380
+ fs.readFileSync(path.join(resolvedModuleRoot, 'toolchain.json'), 'utf8'),
3381
+ ).release
3382
+ if (typeof release === 'string') compilerKey = `source-checkout\0${release}`
3383
+ }
3384
+ const buildKeyPath = normalizedSwiftPackagePath(packagePath)
3358
3385
  return path.join(
3359
3386
  swiftCacheDir(),
3360
3387
  'swift-builds',
@@ -4104,7 +4131,7 @@ export async function swiftPackageMetadata(
4104
4131
  let startup = profiles.get(key)
4105
4132
  if (!startup) {
4106
4133
  startup = (async () => {
4107
- const runtimeRoot = startupRuntimeUrl ?? resolveActiveRuntimeRoot()
4134
+ const runtimeRoot = startupRuntimeUrl ?? (await ensureSwiftStartupRuntimeRoot())
4108
4135
  if (!runtimeRoot)
4109
4136
  throw new Error('cannot profile Swift startup without the engine runtime')
4110
4137
  const { splitSwiftApp } = await import('./swift-startup-split')
@@ -4187,6 +4214,50 @@ function swiftCodePartAssets(
4187
4214
  return codePartUrls.length ? { codePartUrls } : {}
4188
4215
  }
4189
4216
 
4217
+ // inside a Contrast monorepo worktree, Swift startup profiling must run against
4218
+ // this checkout's own engine build rather than silently falling back to an older
4219
+ // installed runtime under ~/.peach/runtimes/active (which may lack new host imports).
4220
+ async function ensureSwiftStartupRuntimeRoot(): Promise<string | null> {
4221
+ if (process.env.PEACH_HOME) {
4222
+ const active = resolveActiveRuntimeRoot()
4223
+ if (active) return active
4224
+ }
4225
+ const repo = findMonorepoRoot()
4226
+ if (!repo) return resolveActiveRuntimeRoot()
4227
+ const { findStaleDevBuildRoutes } = await import('../cli/dev-build-freshness')
4228
+ const current = () => {
4229
+ const devRoot = resolveDevCheckoutRuntimeRoot()
4230
+ if (!devRoot) return null
4231
+ // a staged symlink tree carries an exact runtime build without local
4232
+ // dev-build freshness stamps; trust it instead of rebuilding over the links.
4233
+ if (fs.lstatSync(path.join(devRoot, 'engine')).isSymbolicLink()) return devRoot
4234
+ return findStaleDevBuildRoutes(repo).length === 0 ? devRoot : null
4235
+ }
4236
+ const ready = current()
4237
+ if (ready) return ready
4238
+ const { withSwiftRootLock } = await import('./swift-root-lock')
4239
+ return withSwiftRootLock(path.join(repo, 'public', 'sootsim'), async () => {
4240
+ const built = current()
4241
+ if (built) return built
4242
+ await new Promise<void>((resolveBuild, rejectBuild) => {
4243
+ const child = spawn(
4244
+ process.execPath,
4245
+ [path.join(repo, 'scripts/build/peach-public.ts')],
4246
+ { cwd: repo, env: { ...process.env, TM_WINDOW_WAIT: '1' }, stdio: 'inherit' },
4247
+ )
4248
+ child.once('error', rejectBuild)
4249
+ child.once('close', (code) => {
4250
+ if (code === 0) resolveBuild()
4251
+ else
4252
+ rejectBuild(
4253
+ new Error(`checkout engine runtime build failed (exit ${code ?? 'signal'})`),
4254
+ )
4255
+ })
4256
+ })
4257
+ return resolveDevCheckoutRuntimeRoot()
4258
+ })
4259
+ }
4260
+
4190
4261
  export function swiftSdkEntryAssets(
4191
4262
  origin: string,
4192
4263
  image: SwiftArtifact,
@@ -4211,10 +4282,11 @@ function swiftSdkStartup(
4211
4282
  runtimeRootOverride?: URL,
4212
4283
  ) {
4213
4284
  const { key } = sdk
4285
+ const normalizedPackage = normalizedSwiftPackagePath(packagePath)
4214
4286
  const app = createHash('sha256')
4215
4287
  .update(
4216
4288
  JSON.stringify([
4217
- packagePath,
4289
+ normalizedPackage,
4218
4290
  launch.environment,
4219
4291
  runtimeRootOverride?.origin,
4220
4292
  ...(launch.arguments?.length ? [launch.arguments] : []),
@@ -4225,9 +4297,9 @@ function swiftSdkStartup(
4225
4297
  .slice(0, 16)
4226
4298
  const cacheKey = `${key}/${app}`
4227
4299
  const cached = sdkStartups.get(cacheKey)
4228
- if (cached?.artifactHash === artifactHash) return cached.startup
4300
+ if (cached) return cached.startup
4229
4301
  const startup = (async () => {
4230
- const runtimeRoot = runtimeRootOverride ?? resolveActiveRuntimeRoot()
4302
+ const runtimeRoot = runtimeRootOverride ?? (await ensureSwiftStartupRuntimeRoot())
4231
4303
  if (!runtimeRoot)
4232
4304
  throw new Error('cannot profile Swift startup without the engine runtime')
4233
4305
  const [{ splitSwiftSdkImage }, { swiftSdkImageFile }] = await Promise.all([