peachsim 0.1.1880 → 0.1.1886

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 (154) hide show
  1. package/cli/commands/control.ts +11 -10
  2. package/cli/commands/reset.ts +1 -1
  3. package/cli/outbound-endpoints.ts +1 -1
  4. package/detox/index.ts +62 -1
  5. package/dist-lib/agent-daemon-client.cjs +1 -1
  6. package/dist-lib/agent-events.cjs +1 -1
  7. package/dist-lib/attached-projects.cjs +1 -1
  8. package/dist-lib/auth/shared-session.cjs +1 -1
  9. package/dist-lib/backend-origin.cjs +1 -1
  10. package/dist-lib/beta.cjs +1 -1
  11. package/dist-lib/beta.mjs +1 -1
  12. package/dist-lib/bridge-constants.cjs +1 -1
  13. package/dist-lib/bridge-contract-input.cjs +1 -1
  14. package/dist-lib/bridge-contract-input.mjs +1 -1
  15. package/dist-lib/bridge-contract.cjs +1 -1
  16. package/dist-lib/bridge-contract.mjs +1 -1
  17. package/dist-lib/bundle-channel.cjs +8980 -4279
  18. package/dist-lib/capture-contract.cjs +1 -1
  19. package/dist-lib/capture-contract.mjs +1 -1
  20. package/dist-lib/cloud-contract.cjs +1 -1
  21. package/dist-lib/cloud-contract.mjs +1 -1
  22. package/dist-lib/cloud-test-args.cjs +1 -1
  23. package/dist-lib/cloud-test-args.mjs +1 -1
  24. package/dist-lib/cloud.cjs +1 -1
  25. package/dist-lib/cloud.mjs +1 -1
  26. package/dist-lib/config.cjs +1 -1
  27. package/dist-lib/config.mjs +1 -1
  28. package/dist-lib/detox/index.cjs +35 -2
  29. package/dist-lib/dev-bundle-resolution.cjs +1 -1
  30. package/dist-lib/expo-swift-bundle.cjs +8500 -3912
  31. package/dist-lib/expo-swift-metadata.cjs +5 -1
  32. package/dist-lib/expo-swift-metadata.mjs +5 -1
  33. package/dist-lib/home-paths.cjs +1 -1
  34. package/dist-lib/host/bridge-host.cjs +9744 -5071
  35. package/dist-lib/host/fetch-proxy-handler.cjs +93 -13
  36. package/dist-lib/host/fetch-proxy-overrides.cjs +10 -2
  37. package/dist-lib/host/fetch-proxy-overrides.mjs +8 -2
  38. package/dist-lib/host/replacement-module-handler.cjs +1 -1
  39. package/dist-lib/host/websocket-proxy.cjs +1 -1
  40. package/dist-lib/index.cjs +525 -120
  41. package/dist-lib/jump-to-source-babel.cjs +1 -1
  42. package/dist-lib/jump-to-source-native.cjs +1 -1
  43. package/dist-lib/kotlin-host.cjs +1 -1
  44. package/dist-lib/menu.cjs +1 -1
  45. package/dist-lib/menu.mjs +1 -1
  46. package/dist-lib/metro-fingerprint-registry.cjs +1 -1
  47. package/dist-lib/metro-fingerprint-registry.mjs +1 -1
  48. package/dist-lib/metro-production-bundle.cjs +1 -1
  49. package/dist-lib/metro-production-bundle.mjs +1 -1
  50. package/dist-lib/metro.cjs +523 -118
  51. package/dist-lib/native-app-identity-project.cjs +395 -72
  52. package/dist-lib/native-app-identity-project.mjs +723 -375
  53. package/dist-lib/native-app-identity.cjs +37 -1
  54. package/dist-lib/native-app-identity.mjs +36 -1
  55. package/dist-lib/native-firebase-metadata.cjs +1 -1
  56. package/dist-lib/native-firebase-metadata.mjs +1 -1
  57. package/dist-lib/pdfium-raster.cjs +1 -1
  58. package/dist-lib/pdfium-raster.mjs +1 -1
  59. package/dist-lib/plist.cjs +1 -1
  60. package/dist-lib/plist.mjs +1 -1
  61. package/dist-lib/profiles.cjs +1 -1
  62. package/dist-lib/public-brand.cjs +1 -1
  63. package/dist-lib/public-origins-lib-esm.json +58 -28
  64. package/dist-lib/public-origins-lib.json +233 -92
  65. package/dist-lib/react-native-host-modules.cjs +1 -1
  66. package/dist-lib/react-native-host-modules.mjs +1 -1
  67. package/dist-lib/reap-browser.cjs +1 -1
  68. package/dist-lib/scripts/dev-server-scanner.cjs +1 -1
  69. package/dist-lib/sdk.cjs +1 -1
  70. package/dist-lib/sdk.mjs +1 -1
  71. package/dist-lib/skills.cjs +30639 -25833
  72. package/dist-lib/swift-compile.cjs +6823 -2525
  73. package/dist-lib/swift-compile.mjs +6809 -2509
  74. package/dist-lib/swift-package.cjs +20 -3
  75. package/dist-lib/swift-package.mjs +20 -3
  76. package/dist-lib/swift-submit.cjs +2 -2
  77. package/dist-lib/swift-submit.mjs +2 -2
  78. package/dist-lib/swift-toolchain.cjs +19 -1
  79. package/dist-lib/swift.cjs +1 -1
  80. package/dist-lib/vite-swift.cjs +8704 -4124
  81. package/dist-lib/vite.cjs +93 -13
  82. package/dist-lib/worklet-executable.cjs +1 -1
  83. package/dist-lib/worklet-executable.mjs +1 -1
  84. package/dist-types/packages/peach-engine/src/engine/canvaskit-api.d.ts +1 -1
  85. package/dist-types/packages/peach-engine/src/engine/fontDataContract.d.ts +2 -0
  86. package/dist-types/packages/peach-engine/src/render-worker/host-service-protocol.d.ts +3 -0
  87. package/dist-types/packages/peach-engine/src/render-worker/native-ui-protocol.d.ts +1 -0
  88. package/dist-types/packages/peach-engine/src/render-worker/protocol.d.ts +11 -1
  89. package/dist-types/packages/peach-engine/src/render-worker/shell-tree-wire.d.ts +2 -1
  90. package/dist-types/packages/peach-globals/src/nodeContract.d.ts +1 -0
  91. package/dist-types/packages/peach-globals/src/testBridgeContract.d.ts +10 -1
  92. package/dist-types/packages/peach-kit/src/capabilities.d.ts +1 -0
  93. package/dist-types/packages/peach-kit/src/ui/popover-placement.d.ts +1 -1
  94. package/dist-types/packages/sootsim-swift/src/securityHostContract.d.ts +10 -0
  95. package/package.json +1 -1
  96. package/runtime-companion.json +1 -1
  97. package/sdk/ios/System/Library/Frameworks/CFNetwork.framework/Headers/CFHost.h +555 -0
  98. package/sdk/ios/System/Library/Frameworks/CFNetwork.framework/Headers/CFNetwork.h +1 -0
  99. package/sdk/ios/System/Library/Frameworks/Foundation.framework/Headers/Foundation.apinotes +6 -0
  100. package/sdk/ios/System/Library/Frameworks/Foundation.framework/Headers/NSURLProtocol.h +0 -1
  101. package/sdk/ios/System/Library/Frameworks/QuartzCore.framework/Modules/module.modulemap +6 -0
  102. package/sdk/ios/System/Library/Frameworks/UIKit.framework/Headers/UIBarButtonItemBadge.h +1 -1
  103. package/sdk/ios/System/Library/Frameworks/UIKit.framework/Headers/UIBarMinimization.h +1 -1
  104. package/sdk/ios/System/Library/Frameworks/UIKit.framework/Headers/UIScrollView.h +1 -1
  105. package/sdk/ios/System/Library/Frameworks/UIKit.framework/Headers/UISearchTab.h +1 -1
  106. package/sdk/ios/System/Library/Frameworks/UIKit.framework/Headers/UITab.h +1 -1
  107. package/sdk/ios/System/Library/Frameworks/UIKit.framework/Headers/UITabAccessory.h +2 -2
  108. package/sdk/ios/usr/include/os/activity.h +534 -0
  109. package/sdk/ios/usr/include/os.modulemap +15 -0
  110. package/sdk/ios/wasm/include/fcntl.h +16 -0
  111. package/sdk/ios/wasm/include/string.h +5 -0
  112. package/sdk/native-hashes.json +1 -1
  113. package/src/dns-over-https.ts +61 -9
  114. package/src/expo-swift-host.ts +11 -3
  115. package/src/host/fetch-proxy-handler.ts +51 -2
  116. package/src/host/fetch-proxy-overrides.ts +4 -0
  117. package/src/host/hostname-resolver.ts +9 -5
  118. package/src/native-app-identity-project.ts +13 -2
  119. package/src/native-app-identity.ts +47 -0
  120. package/src/nitro-adapter.lock.json +260 -260
  121. package/src/nitro-superset.lock.json +4 -4
  122. package/src/storageSnapshotContract.ts +20 -1
  123. package/src/swift-compile.ts +534 -136
  124. package/src/swift-compiler-digest.ts +15 -0
  125. package/src/swift-coverage/xcode-packages.ts +3 -2
  126. package/src/swift-distribution.lock.json +12 -12
  127. package/src/swift-guest-archive.ts +153 -0
  128. package/src/swift-guest-compile.ts +449 -0
  129. package/src/swift-guest-image-ledger.ts +656 -0
  130. package/src/swift-guest-link-plan.ts +52 -0
  131. package/src/swift-guest-link.ts +1414 -0
  132. package/src/swift-guest-linked-spans.ts +338 -0
  133. package/src/swift-guest-manifest.ts +141 -0
  134. package/src/swift-guest-projection-storage.ts +310 -0
  135. package/src/swift-guest-projection.ts +252 -0
  136. package/src/swift-guest-runtime-plan.ts +834 -0
  137. package/src/swift-guest-source-inputs.ts +427 -0
  138. package/src/swift-guest-source-plan.ts +279 -0
  139. package/src/swift-host.ts +125 -17
  140. package/src/swift-link-roots.ts +27 -50
  141. package/src/swift-package-manifest.ts +34 -18
  142. package/src/swift-package.ts +32 -2
  143. package/src/swift-packages.ts +138 -17
  144. package/src/swift-runtime-products.ts +73 -0
  145. package/src/swift-shared-sdk.ts +1 -1
  146. package/src/swift-submit.ts +13 -3
  147. package/src/swift-toolchain.ts +18 -0
  148. package/src/swift-wasm-prune.ts +313 -14
  149. package/src/swiftContract.ts +83 -0
  150. package/src/swiftRuntimeProductContract.ts +85 -45
  151. package/src/turbo-runtime.lock.json +23 -23
  152. package/src/turbo-source.ts +4 -1
  153. package/src/wasm-optimize.ts +16 -4
  154. package/src/xcode-project.ts +142 -14
@@ -6,12 +6,15 @@ import {
6
6
  } from 'node:child_process'
7
7
  import { createHash, randomUUID } from 'node:crypto'
8
8
  import {
9
+ copyFileSync,
9
10
  cpSync,
10
11
  existsSync,
12
+ lstatSync,
11
13
  mkdirSync,
12
14
  mkdtempSync,
13
15
  readFileSync,
14
16
  readdirSync,
17
+ readlinkSync,
15
18
  realpathSync,
16
19
  renameSync,
17
20
  rmSync,
@@ -43,6 +46,7 @@ import {
43
46
  SWIFT_DISTRIBUTION_OBJC_SELECTORS,
44
47
  } from './swift-distribution-contract'
45
48
  import { foundationCategoryObjects } from './swift-foundation'
49
+ import { compileGuestLink } from './swift-guest-compile'
46
50
  import {
47
51
  brotliCompressQ11,
48
52
  brotliCompressQ4,
@@ -112,6 +116,8 @@ import { compileUniformTypeConstants } from './swift-uniform-type-constants'
112
116
  import { pruneSwiftWasmLink } from './swift-wasm-prune'
113
117
  import {
114
118
  isSwiftNativeTargets,
119
+ isSwiftSourceLinkGraph,
120
+ type SwiftSourceLinkGraph,
115
121
  isSwiftHeaderAliases,
116
122
  isSwiftPackageFiles,
117
123
  isSwiftProjectFiles,
@@ -279,6 +285,7 @@ export interface SwiftCompileInput {
279
285
  projectFiles?: Record<string, string>
280
286
  packageGuestImports?: string[]
281
287
  nativeTargets?: SwiftNativeTarget[]
288
+ sourceLinkGraph?: SwiftSourceLinkGraph
282
289
  headerAliases?: SwiftHeaderAliases
283
290
  /** the Xcode app project's development region, for the emitted manifest's default localization. */
284
291
  defaultLocalization?: string
@@ -524,16 +531,21 @@ export function swiftModuleInputFiles(root: string): string[] {
524
531
  const files: string[] = [
525
532
  ...swiftSharedSdkInputFiles(root),
526
533
  '../peachsim/src/swift-shared-sdk.ts',
527
- '../peachsim/src/swift-darwin-records.ts',
528
- '../peachsim/src/swift-uniform-type-constants.ts',
529
534
  '../peachsim/src/swift-runtime-products.ts',
530
535
  '../peachsim/src/swiftRuntimeProductContract.ts',
536
+ '../peachsim/src/swift-darwin-records.ts',
537
+ '../peachsim/src/swift-uniform-type-constants.ts',
531
538
  '../../scripts/generate/swift-sdk-module/darwin-mach.json',
532
539
  '../../scripts/generate/swift-sdk-module/darwin-socketvar.json',
533
540
  '../../scripts/ops/swift-distribution-publish.ts',
541
+ '../../src/helpers/mapLimit.ts',
534
542
  'Package.swift',
535
543
  'scripts/contrast-app-Package.swift',
536
544
  'scripts/build-distribution.ts',
545
+ 'scripts/runtime-product.ts',
546
+ 'scripts/runtime-product-scopes.ts',
547
+ 'scripts/distribution-runtime-products.ts',
548
+ 'scripts/build-helpers.ts',
537
549
  'scripts/distribution-clang.ts',
538
550
  'runtime/UniformTypeIdentifiersConstants.m',
539
551
  'Sources/libxml2/include/module.modulemap',
@@ -1133,6 +1145,64 @@ export function swiftSdkPaths(
1133
1145
 
1134
1146
  const availableModules = new Map<string, Set<string>>()
1135
1147
 
1148
+ // only frameworks replaced by a Swift module lose their clang submodules.
1149
+ // non-framework clang modules can coexist with a same-name Swift module.
1150
+ function addSwiftOverlayFrameworks(
1151
+ text: string,
1152
+ swiftModules: ReadonlySet<string>,
1153
+ frameworks: Set<string>,
1154
+ ): void {
1155
+ const tokens = moduleMapTokens(text)
1156
+ for (let i = 0; i < tokens.length - 2; i++)
1157
+ if (
1158
+ tokens[i] === 'framework' &&
1159
+ tokens[i - 1] !== 'extern' &&
1160
+ tokens[i + 1] === 'module' &&
1161
+ swiftModules.has(tokens[i + 2]!)
1162
+ )
1163
+ frameworks.add(tokens[i + 2]!)
1164
+ }
1165
+
1166
+ const sdkOverlayFrameworks = new Map<string, Set<string>>()
1167
+
1168
+ export function swiftOverlayFrameworks(
1169
+ moduleRoot: string,
1170
+ toolchainBin: string,
1171
+ ): ReadonlySet<string> {
1172
+ const key = JSON.stringify([
1173
+ moduleRoot,
1174
+ toolchainBin,
1175
+ swiftModuleSdk(moduleRoot).wasmSdkId,
1176
+ swiftSdkOptions(),
1177
+ ])
1178
+ const cached = sdkOverlayFrameworks.get(key)
1179
+ if (cached) return cached
1180
+ const { darwin, resources, frameworks } = swiftSdkPaths(moduleRoot, toolchainBin)
1181
+ const swiftModules = new Set(swiftPeachModules(moduleRoot))
1182
+ const result = new Set<string>()
1183
+ const include = path.join(darwin, 'usr/include')
1184
+ for (const entry of readdirSync(include))
1185
+ if (entry.endsWith('.modulemap'))
1186
+ addSwiftOverlayFrameworks(
1187
+ readFileSync(path.join(include, entry), 'utf8'),
1188
+ swiftModules,
1189
+ result,
1190
+ )
1191
+ for (const entry of readdirSync(resources)) {
1192
+ const map = path.join(resources, entry, 'module.modulemap')
1193
+ if (existsSync(map))
1194
+ addSwiftOverlayFrameworks(readFileSync(map, 'utf8'), swiftModules, result)
1195
+ }
1196
+ for (const directory of frameworks)
1197
+ for (const entry of readdirSync(directory)) {
1198
+ const map = path.join(directory, entry, 'Modules/module.modulemap')
1199
+ if (existsSync(map))
1200
+ addSwiftOverlayFrameworks(readFileSync(map, 'utf8'), swiftModules, result)
1201
+ }
1202
+ sdkOverlayFrameworks.set(key, result)
1203
+ return result
1204
+ }
1205
+
1136
1206
  /**
1137
1207
  * every module a source compiled against `moduleRoot` can import: Peach's own
1138
1208
  * and the wasm SDK's swift modules and top-level clang modules.
@@ -1146,7 +1216,29 @@ export function swiftAvailableModules(
1146
1216
  const cached = availableModules.get(key)
1147
1217
  if (cached) return cached
1148
1218
  const modules = new Set(swiftPeachModules(moduleRoot))
1149
- const { darwin, resources, frameworks } = swiftSdkPaths(moduleRoot, toolchainBin)
1219
+ const { resources, frameworks, sysroot, darwin, cFlags } = swiftSdkPaths(
1220
+ moduleRoot,
1221
+ toolchainBin,
1222
+ )
1223
+ const maps = new Set([
1224
+ path.join(darwin, 'usr/include/module.modulemap'),
1225
+ ...cFlags
1226
+ .filter((flag) => flag.startsWith('-fmodule-map-file='))
1227
+ .map((flag) => {
1228
+ const file = flag.slice('-fmodule-map-file='.length)
1229
+ return file.startsWith('=') ? path.join(sysroot, file.slice(1)) : file
1230
+ }),
1231
+ ])
1232
+ for (const map of maps) {
1233
+ if (!existsSync(map)) continue
1234
+ const contents = readFileSync(map, 'utf8')
1235
+ for (const match of contents.matchAll(
1236
+ /^(?:explicit\s+)?(?:framework\s+)?module\s+([A-Za-z_]\w*)/gm,
1237
+ ))
1238
+ modules.add(match[1]!)
1239
+ for (const match of contents.matchAll(/^\s*extern\s+module\s+\w+\s+"([^"]+)"/gm))
1240
+ maps.add(path.resolve(path.dirname(map), match[1]!))
1241
+ }
1150
1242
  for (const entry of readdirSync(path.join(resources, 'wasi'))) {
1151
1243
  if (entry.endsWith('.swiftmodule'))
1152
1244
  modules.add(entry.slice(0, -'.swiftmodule'.length))
@@ -1259,15 +1351,18 @@ export function swiftSystemLibraryExclusions(
1259
1351
  )
1260
1352
  }
1261
1353
 
1262
- /** a distribution modules path without the modules a local system library owns. */
1263
- function distributionModulesPath(
1354
+ /** prebuilt modules without interfaces owned by the compiling source graph. */
1355
+ function providedModulesPath(
1264
1356
  root: string,
1265
- moduleRoot: string,
1357
+ modules: string,
1266
1358
  excluded: ReadonlySet<string> | undefined,
1267
1359
  ): string {
1268
- const modules = path.join(moduleRoot, 'modules')
1269
1360
  if (!excluded || excluded.size === 0) return modules
1361
+ const entries = readdirSync(modules)
1362
+ .filter((entry) => !excluded.has(entry.replace(/\..*$/, '')))
1363
+ .sort()
1270
1364
  const key = createHash('sha256')
1365
+ .update(JSON.stringify([modules, entries]))
1271
1366
  .update([...excluded].sort().join('\0'))
1272
1367
  .digest('hex')
1273
1368
  .slice(0, 16)
@@ -1277,8 +1372,7 @@ function distributionModulesPath(
1277
1372
  mkdirSync(directory, { recursive: true })
1278
1373
  for (const entry of readdirSync(directory))
1279
1374
  rmSync(path.join(directory, entry), { recursive: true, force: true })
1280
- for (const entry of readdirSync(modules)) {
1281
- if (excluded.has(entry.replace(/\.swiftmodule$/, ''))) continue
1375
+ for (const entry of entries) {
1282
1376
  symlinkSync(path.join(modules, entry), path.join(directory, entry))
1283
1377
  }
1284
1378
  writeFileSync(complete, '')
@@ -1288,9 +1382,14 @@ function distributionModulesPath(
1288
1382
 
1289
1383
  export function swiftTargetDependencies(
1290
1384
  files: Record<string, string>,
1291
- targets: Pick<SwiftPackageTarget, 'name' | 'path' | 'dependencies'>[],
1385
+ targets: Pick<
1386
+ SwiftPackageTarget,
1387
+ 'name' | 'path' | 'dependencies' | 'sources' | 'exclude'
1388
+ >[],
1389
+ frameworks: Iterable<string> = OPTIONAL_FRAMEWORKS,
1292
1390
  ): Map<string, string[]> {
1293
- const names = new Set([...OPTIONAL_FRAMEWORKS, ...targets.map((target) => target.name)])
1391
+ const localNames = new Set(targets.map((target) => target.name))
1392
+ const names = new Set([...frameworks, ...localNames])
1294
1393
  const siblings = new Map<string, string[]>()
1295
1394
  for (const target of targets) {
1296
1395
  const prefix = target.path === '.' ? '' : `${target.path}/`
@@ -1319,7 +1418,23 @@ export function swiftTargetDependencies(
1319
1418
  )
1320
1419
  for (const [file, contents] of Object.entries(files)) {
1321
1420
  if (file === 'Package.swift' || !file.startsWith(prefix)) continue
1421
+ const relative = file.slice(prefix.length)
1422
+ if (
1423
+ target.sources !== undefined &&
1424
+ !target.sources.some(
1425
+ (source) =>
1426
+ source === '.' || relative === source || relative.startsWith(`${source}/`),
1427
+ )
1428
+ )
1429
+ continue
1430
+ if (
1431
+ target.exclude?.some(
1432
+ (excluded) => relative === excluded || relative.startsWith(`${excluded}/`),
1433
+ )
1434
+ )
1435
+ continue
1322
1436
  if (
1437
+ target.sources === undefined &&
1323
1438
  targets.some(
1324
1439
  (candidate) =>
1325
1440
  candidate.name !== target.name &&
@@ -1335,7 +1450,14 @@ export function swiftTargetDependencies(
1335
1450
  ? clangImportNames(contents, ownsHeader)
1336
1451
  : []
1337
1452
  for (const name of imports) {
1338
- if (names.has(name) && name !== target.name) deps.add(name)
1453
+ // public umbrella headers may import their own consumers. a declared
1454
+ // package graph owns local edges; imports still select sdk frameworks.
1455
+ if (
1456
+ names.has(name) &&
1457
+ name !== target.name &&
1458
+ !(target.dependencies !== undefined && localNames.has(name))
1459
+ )
1460
+ deps.add(name)
1339
1461
  }
1340
1462
  }
1341
1463
  siblings.set(target.name, [...deps].sort())
@@ -1401,7 +1523,7 @@ const darwinRecordsRegion = (quoted: readonly string[]): string[] =>
1401
1523
  const REACTOR_FLAG = '"-Xclang-linker", "-mexec-model=reactor",\n'
1402
1524
 
1403
1525
  /** bump with any change to the emitted multi-target manifest text. */
1404
- export const MULTI_MANIFEST_VERSION = 65
1526
+ export const MULTI_MANIFEST_VERSION = 66
1405
1527
  const SWIFT_HEADER_PRODUCTS_TARGET = 'PeachHeaderProducts'
1406
1528
 
1407
1529
  // build-cli replaces this in every bundle; source runs read the files directly.
@@ -1460,6 +1582,7 @@ export function swiftArtifactHash(
1460
1582
  ),
1461
1583
  )
1462
1584
  hash.update(JSON.stringify(input.nativeTargets ?? []))
1585
+ hash.update(JSON.stringify(input.sourceLinkGraph ?? null))
1463
1586
  hash.update(JSON.stringify(input.staticClangTargets ?? []))
1464
1587
  hash.update(JSON.stringify(input.headerAliases ?? {}))
1465
1588
  hash.update(JSON.stringify(input.packageGuestImports ?? []))
@@ -1605,8 +1728,8 @@ export function emitSwiftPackageManifest(args: {
1605
1728
  spriteKit?: boolean
1606
1729
  /** link the prebuilt distribution at moduleRoot instead of its sources. */
1607
1730
  distribution?: SwiftDistributionManifest
1608
- /** distribution modules owned by local targets or their native headers. */
1609
- distributionExcludes?: ReadonlySet<string>
1731
+ /** prebuilt interfaces owned by local source or system-library targets. */
1732
+ moduleExcludes?: ReadonlySet<string>
1610
1733
  /**
1611
1734
  * ordered distribution objects, read by the linker without expanding argv.
1612
1735
  * absent when no source reaches a distribution framework: the executable
@@ -1635,11 +1758,13 @@ export function emitSwiftPackageManifest(args: {
1635
1758
  const linkedObjects = Boolean(distribution || prebuilt)
1636
1759
  const cxxFlagsFor = (flags: readonly string[]): readonly string[] =>
1637
1760
  args.deferDarwinOverlay ? withoutWasmOverlayIsystem(flags) : flags
1638
- // the base distribution links authenticationservices' prf key storage,
1639
- // which requires cryptokit even when an app does not import it directly.
1640
- const reachedFrameworks = new Set<string>(['CryptoKit'])
1761
+ const reachedFrameworks = new Set<string>()
1641
1762
  const reach = (name: string) => {
1642
- if (reachedFrameworks.has(name)) return
1763
+ if (
1764
+ reachedFrameworks.has(name) ||
1765
+ targets.some((target) => swiftTargetModuleName(target.name) === name)
1766
+ )
1767
+ return
1643
1768
  reachedFrameworks.add(name)
1644
1769
  for (const dependency of OPTIONAL_FRAMEWORK_DEPENDENCIES[name] ?? [])
1645
1770
  reach(dependency)
@@ -1820,10 +1945,14 @@ export function emitSwiftPackageManifest(args: {
1820
1945
  // object for autolinks; distribution.link supplies those libraries.
1821
1946
  const imports = distribution
1822
1947
  ? `, "-Isystem", ${JSON.stringify(
1823
- distributionModulesPath(args.root, moduleRoot, args.distributionExcludes),
1948
+ providedModulesPath(
1949
+ args.root,
1950
+ path.join(moduleRoot, 'modules'),
1951
+ args.moduleExcludes,
1952
+ ),
1824
1953
  )}`
1825
1954
  : prebuilt
1826
- ? `, "-Isystem", ${JSON.stringify(prebuilt.modules)}${prebuilt.moduleMaps
1955
+ ? `, "-Isystem", ${JSON.stringify(providedModulesPath(args.root, prebuilt.modules, args.moduleExcludes))}${prebuilt.moduleMaps
1827
1956
  .map((map) => `, "-Xcc", ${JSON.stringify(`-fmodule-map-file=${map}`)}`)
1828
1957
  .join('')}`
1829
1958
  : ''
@@ -2032,7 +2161,9 @@ export function emitSwiftPackageManifest(args: {
2032
2161
  ]
2033
2162
  : native?.flags
2034
2163
  ? [` sources: ${JSON.stringify(native.sources)},`]
2035
- : []),
2164
+ : target.sources !== undefined
2165
+ ? [` sources: ${JSON.stringify(target.sources)},`]
2166
+ : []),
2036
2167
  ...(!native?.clang && target.publicHeadersPath !== undefined
2037
2168
  ? [` publicHeadersPath: ${JSON.stringify(target.publicHeadersPath)},`]
2038
2169
  : []),
@@ -2180,6 +2311,7 @@ const FRAME_INIT = /^override(?=\s+(?:(?:public|open|internal)\s+)?init\s*\(\s*f
2180
2311
  function compiledSwiftSources(
2181
2312
  files: Record<string, string>,
2182
2313
  targets: SwiftPackageTarget[],
2314
+ overlayFrameworks: () => ReadonlySet<string>,
2183
2315
  ): Map<string, string> {
2184
2316
  const ordered = [...targets].sort((a, b) => b.path.length - a.path.length)
2185
2317
  return new Map(
@@ -2201,6 +2333,7 @@ function compiledSwiftSources(
2201
2333
  ? source
2202
2334
  : swiftSourceAsIOS(
2203
2335
  source,
2336
+ overlayFrameworks,
2204
2337
  owner?.defines?.includes(SWIFT_XCODE_BUILD_CONDITION) &&
2205
2338
  !owner.defines.includes('SWIFT_PACKAGE')
2206
2339
  ? false
@@ -2377,8 +2510,6 @@ const FOUNDATION_NETWORKING_TYPES = new Set([
2377
2510
  'NSURLConnectionDataDelegate',
2378
2511
  'NSURLConnectionDelegate',
2379
2512
  'NSURLConnectionDownloadDelegate',
2380
- 'URLProtocol',
2381
- 'URLProtocolClient',
2382
2513
  ])
2383
2514
 
2384
2515
  // Foundation overlay declarations live in the shared guest overlay module.
@@ -3041,7 +3172,6 @@ const CORE_FOUNDATION_HANDLE_IMPORTS = [
3041
3172
 
3042
3173
  // the guest module that owns a name darwin's Foundation declares
3043
3174
  export function foundationOwnerOf(name: string): string | undefined {
3044
- if (name === 'NSErrorPointer') return 'Foundation'
3045
3175
  if (
3046
3176
  name === 'NSClassFromString' ||
3047
3177
  name === 'NSKeyValueChange' ||
@@ -3060,7 +3190,11 @@ export function foundationOwnerOf(name: string): string | undefined {
3060
3190
  return undefined
3061
3191
  }
3062
3192
 
3063
- export function swiftSourceAsIOS(source: string, swiftPackage?: boolean): string {
3193
+ export function swiftSourceAsIOS(
3194
+ source: string,
3195
+ overlayFrameworks: () => ReadonlySet<string>,
3196
+ swiftPackage?: boolean,
3197
+ ): string {
3064
3198
  const { lineStarts, tokens } = swiftCodeScan(source)
3065
3199
  let offset = 0
3066
3200
  // equal width, so every token offset still holds
@@ -3115,16 +3249,18 @@ export function swiftSourceAsIOS(source: string, swiftPackage?: boolean): string
3115
3249
  }
3116
3250
  continue
3117
3251
  }
3118
- // a Clang submodule import (`import UIKit.UIImage`) names its framework:
3119
- // peach's frameworks are Swift modules with no submodules, and on iOS the
3120
- // submodule brings in the framework's Swift overlay too.
3252
+ // keep Clang submodules the selected SDK actually owns. a framework
3253
+ // replaced by a Swift overlay imports the overlay instead.
3121
3254
  const imported =
3122
3255
  conditioned[at - 1] === '.'
3123
3256
  ? null
3124
3257
  : /^import[ \t]+([A-Za-z_]\w*)(?:[ \t]*\.[ \t]*[A-Za-z_]\w*)+/.exec(rest)
3125
3258
  if (imported) {
3126
3259
  out +=
3127
- conditioned.slice(copied, at) + `import ${imported[1]}`.padEnd(imported[0].length)
3260
+ conditioned.slice(copied, at) +
3261
+ (overlayFrameworks().has(imported[1]!)
3262
+ ? `import ${imported[1]}`.padEnd(imported[0].length)
3263
+ : imported[0])
3128
3264
  if (imported[1] === 'CoreFoundation') out += `; ${CORE_FOUNDATION_HANDLE_IMPORTS}`
3129
3265
  copied = at + imported[0].length
3130
3266
  continue
@@ -3912,9 +4048,14 @@ function swiftCodeScan(source: string): {
3912
4048
  * source adapted as app sources are, retaining native objective-c syntax.
3913
4049
  * its manifests stay as
3914
4050
  * published and the upstream tree is never written. */
3915
- export function prepareSwiftDependency(source: string, destination: string): void {
4051
+ export function prepareSwiftDependency(
4052
+ source: string,
4053
+ destination: string,
4054
+ overlayFrameworks: () => ReadonlySet<string>,
4055
+ ): void {
3916
4056
  rmSync(destination, { recursive: true, force: true })
3917
4057
  const origins: Record<string, string> = {}
4058
+ const moduleMaps: string[] = []
3918
4059
  const gather = (from: string) => {
3919
4060
  for (const entry of readdirSync(from, { withFileTypes: true })) {
3920
4061
  if (entry.name === '.git' || entry.name === '.build' || entry.name === '.swiftpm')
@@ -3923,6 +4064,8 @@ export function prepareSwiftDependency(source: string, destination: string): voi
3923
4064
  if (entry.isDirectory()) gather(file)
3924
4065
  else if (entry.isFile() && entry.name.endsWith('.swift'))
3925
4066
  origins[path.relative(source, file)] = readFileSync(file, 'utf8')
4067
+ else if (entry.isFile() && entry.name.endsWith('.modulemap'))
4068
+ moduleMaps.push(readFileSync(file, 'utf8'))
3926
4069
  }
3927
4070
  }
3928
4071
  gather(source)
@@ -3930,7 +4073,26 @@ export function prepareSwiftDependency(source: string, destination: string): voi
3930
4073
  const targets = existsSync(manifest)
3931
4074
  ? swiftManifestTargets(readFileSync(manifest, 'utf8'))
3932
4075
  : []
3933
- const compiled = compiledSwiftSources(origins, targets)
4076
+ let dependencyOverlays: Set<string> | undefined
4077
+ const compiled = compiledSwiftSources(origins, targets, () => {
4078
+ if (dependencyOverlays) return dependencyOverlays
4079
+ dependencyOverlays = new Set(overlayFrameworks())
4080
+ const sourceFiles = Object.keys(origins)
4081
+ const swiftModules = new Set(
4082
+ targets
4083
+ .filter((target) =>
4084
+ sourceFiles.some(
4085
+ (file) =>
4086
+ file !== 'Package.swift' &&
4087
+ (target.path === '.' || file.startsWith(`${target.path}/`)),
4088
+ ),
4089
+ )
4090
+ .map((target) => swiftTargetModuleName(target.name)),
4091
+ )
4092
+ for (const map of moduleMaps)
4093
+ addSwiftOverlayFrameworks(map, swiftModules, dependencyOverlays)
4094
+ return dependencyOverlays
4095
+ })
3934
4096
  const copy = (from: string, to: string) => {
3935
4097
  mkdirSync(to, { recursive: true })
3936
4098
  for (const entry of readdirSync(from, { withFileTypes: true })) {
@@ -3949,6 +4111,31 @@ export function prepareSwiftDependency(source: string, destination: string): voi
3949
4111
 
3950
4112
  // where a mixed native target compiles units whose paths swiftpm would hide.
3951
4113
  const HIDDEN_UNITS = 'PeachHiddenUnits'
4114
+ // a package's arch-selected units (KSCrash's KSCPU_arm64.c) wrap their whole
4115
+ // body in one arch guard. the guest is arm64 at 32-bit pointers, as arm64_32
4116
+ // is, and clang defines __arm64__ for that triple, so each such unit compiles
4117
+ // with it defined. a global define would flip headers (setjmp, simd, objc)
4118
+ // for every unit.
4119
+ // whether the unit's only content is one `__arm64__` conditional.
4120
+ function swiftWholeFileArm64Guard(source: string): boolean {
4121
+ const lines = stripCCode(source)
4122
+ .replace(/\\\r?\n/g, '')
4123
+ .split('\n')
4124
+ .map((line) => line.trim())
4125
+ .filter((line) => line !== '')
4126
+ if (
4127
+ !/^#\s*(?:if\s+defined\s*\(\s*__arm64__\s*\)|ifdef\s+__arm64__)$/.test(lines[0] ?? '')
4128
+ )
4129
+ return false
4130
+ let depth = 0
4131
+ for (const [index, line] of lines.entries()) {
4132
+ if (/^#\s*if/.test(line)) depth++
4133
+ else if (/^#\s*endif\b/.test(line)) depth--
4134
+ if (depth === 0 && index !== lines.length - 1) return false
4135
+ if (depth === 0 && /^#\s*(?:else|elif)/.test(line)) return false
4136
+ }
4137
+ return depth === 0 && /^#\s*endif\b/.test(lines.at(-1) ?? '')
4138
+ }
3952
4139
 
3953
4140
  // a clang dependency's module map is written beside its public headers after
3954
4141
  // that target's own import. an earlier import already has that directory on
@@ -4033,10 +4220,18 @@ export function writeSwiftProject(
4033
4220
  input: SwiftCompileInput,
4034
4221
  moduleRoot: string,
4035
4222
  prebuilt?: SwiftFrameworkProducts,
4036
- ): SwiftProjectPreparation {
4223
+ ): SwiftProjectPreparation & {
4224
+ generatedOwners: Map<string, string>
4225
+ targetToolset: boolean
4226
+ } {
4037
4227
  const nativeToolset = needsNativeToolset(input, prebuilt)
4038
4228
  if (input.headerAliases !== undefined && !isSwiftHeaderAliases(input.headerAliases))
4039
4229
  throw new Error('swift compile input has invalid original header aliases')
4230
+ if (
4231
+ input.sourceLinkGraph !== undefined &&
4232
+ !isSwiftSourceLinkGraph(input.sourceLinkGraph)
4233
+ )
4234
+ throw new Error('swift compile input has invalid source product links')
4040
4235
  if (input.nativeTargets !== undefined && !isSwiftNativeTargets(input.nativeTargets))
4041
4236
  throw new Error('swift compile input has invalid original clang target inputs')
4042
4237
  if (input.packageFiles !== undefined && !isSwiftPackageFiles(input.packageFiles))
@@ -4081,16 +4276,27 @@ export function writeSwiftProject(
4081
4276
  },
4082
4277
  ]
4083
4278
  : compileTargets(input)
4279
+ const generatedOwners = new Map(targets.map((target) => [target.name, target.name]))
4280
+ // source owns its module name, including clang targets: a same-name Swift
4281
+ // preview must not hide their original Objective-C interface.
4282
+ const providedModules =
4283
+ distribution?.modules ??
4284
+ (prebuilt
4285
+ ? readdirSync(prebuilt.modules)
4286
+ .filter((entry) => entry.endsWith('.swiftmodule'))
4287
+ .map((entry) => entry.slice(0, -'.swiftmodule'.length))
4288
+ : [])
4084
4289
  // a local target owns its module, including native React targets from the
4085
- // installed workspace. the distribution must not replace its declarations.
4086
- const distributionExcludes = distribution
4087
- ? new Set([
4088
- ...swiftSystemLibraryExclusions(input.files, targets, distribution.modules),
4089
- ...distribution.modules.filter((name) =>
4090
- targets.some((target) => target.name === name),
4091
- ),
4092
- ])
4093
- : undefined
4290
+ // installed workspace. the prebuilt interface must not replace its declarations.
4291
+ const moduleExcludes =
4292
+ distribution || prebuilt
4293
+ ? new Set([
4294
+ ...swiftSystemLibraryExclusions(input.files, targets, providedModules),
4295
+ ...providedModules.filter((name) =>
4296
+ targets.some((target) => swiftTargetModuleName(target.name) === name),
4297
+ ),
4298
+ ])
4299
+ : undefined
4094
4300
  const files = new Map<string, string | Buffer>()
4095
4301
  const native = new Map<string, SwiftNativeTargetPlan>()
4096
4302
  const targetFailures: string[] = []
@@ -4173,6 +4379,10 @@ export function writeSwiftProject(
4173
4379
  return Object.entries(input.files).filter(
4174
4380
  ([file]) =>
4175
4381
  file.startsWith(prefix) &&
4382
+ !target.exclude?.some(
4383
+ (excluded) =>
4384
+ file === `${prefix}${excluded}` || file.startsWith(`${prefix}${excluded}/`),
4385
+ ) &&
4176
4386
  !targets.some(
4177
4387
  (candidate) =>
4178
4388
  candidate.name !== target.name &&
@@ -4734,6 +4944,9 @@ export function writeSwiftProject(
4734
4944
  // before quoted header maps and configured user search paths.
4735
4945
  const quoteFlags = origin ? ['-iquote', path.join(layout.root, origin)] : []
4736
4946
  const perFile = [
4947
+ ...(file.endsWith('.c') && swiftWholeFileArm64Guard(contents)
4948
+ ? ['-D__arm64__=1']
4949
+ : []),
4737
4950
  ...(/\.mm?$/.test(file) ? ['-fobjc-exceptions'] : []),
4738
4951
  ...stageFlags(
4739
4952
  settings?.fileFlags[file] ?? [],
@@ -5063,6 +5276,7 @@ export function writeSwiftProject(
5063
5276
  const moduleFiles = `\n// sootsim-swift files ${modulePlan.digest('hex').slice(0, 16)}\n// resource accessors ${resourcePlan}\n`
5064
5277
  // view builder literals compile as xcode's design-time lookups, so a save
5065
5278
  // that changes only them reloads without compiling (swift-design-time.ts)
5279
+ let projectOverlayFrameworks: Set<string> | undefined
5066
5280
  const compiled = compiledSwiftSources(
5067
5281
  Object.fromEntries(
5068
5282
  Object.entries(input.files).map(([file, contents]) => [
@@ -5071,6 +5285,24 @@ export function writeSwiftProject(
5071
5285
  ]),
5072
5286
  ),
5073
5287
  targets,
5288
+ () => {
5289
+ if (projectOverlayFrameworks) return projectOverlayFrameworks
5290
+ projectOverlayFrameworks = new Set(
5291
+ swiftOverlayFrameworks(moduleRoot, nativeToolchain()),
5292
+ )
5293
+ const swiftModules = new Set(swiftPeachModules(moduleRoot))
5294
+ const sourceModules = new Set([...swiftTargets].map(swiftTargetModuleName))
5295
+ for (const name of moduleExcludes ?? [])
5296
+ if (!sourceModules.has(name)) {
5297
+ swiftModules.delete(name)
5298
+ projectOverlayFrameworks.delete(name)
5299
+ }
5300
+ for (const name of sourceModules) swiftModules.add(name)
5301
+ for (const [file, contents] of Object.entries(input.files))
5302
+ if (file.endsWith('.modulemap'))
5303
+ addSwiftOverlayFrameworks(contents, swiftModules, projectOverlayFrameworks)
5304
+ return projectOverlayFrameworks
5305
+ },
5074
5306
  )
5075
5307
  // an application's swift module must precede its native implementations.
5076
5308
  // the tiny executable calls the original typed entry after both are linked.
@@ -5158,6 +5390,7 @@ export function writeSwiftProject(
5158
5390
  if (targets.some((candidate) => candidate.name === name))
5159
5391
  throw new Error(`mixed application executable target conflicts with ${name}`)
5160
5392
  target.executable = false
5393
+ generatedOwners.set(name, target.name)
5161
5394
  targets.push({
5162
5395
  ...target,
5163
5396
  name,
@@ -5165,6 +5398,7 @@ export function writeSwiftProject(
5165
5398
  executable: true,
5166
5399
  resources: false,
5167
5400
  dependencies: [{ kind: 'target', name: target.name }],
5401
+ sources: ['Entry.swift'],
5168
5402
  exclude: [],
5169
5403
  })
5170
5404
  files.set(
@@ -5441,7 +5675,7 @@ export function writeSwiftProject(
5441
5675
  oneModule: input.oneModule,
5442
5676
  spriteKit: importsSpriteKit(input.files),
5443
5677
  distribution: distribution ?? undefined,
5444
- distributionExcludes,
5678
+ moduleExcludes,
5445
5679
  deferDarwinOverlay:
5446
5680
  native.size > 0 &&
5447
5681
  toolsetOrdersLibcxxBeforeDarwinOverlay(
@@ -5480,15 +5714,28 @@ export function writeSwiftProject(
5480
5714
  if (files.has(destination)) continue
5481
5715
  files.set(destination, Buffer.from(bytes, 'base64'))
5482
5716
  }
5483
- if (nativeToolset) {
5717
+ const targetToolset = nativeToolset || native.size > 0
5718
+ if (targetToolset) {
5719
+ const nativeToolsetFlags = [
5720
+ ...headerAliasFlags,
5721
+ ...(native.size > 0
5722
+ ? [
5723
+ '-fmodule-map-file=' +
5724
+ path.join(
5725
+ swiftSdkPaths(moduleRoot, nativeToolchain()).sysroot,
5726
+ 'darwin/wasm/include/module.modulemap',
5727
+ ),
5728
+ ]
5729
+ : []),
5730
+ ]
5484
5731
  files.set(
5485
5732
  path.join(layout.root, '.peach-target-toolset.json'),
5486
5733
  JSON.stringify({
5487
5734
  schemaVersion: '1.0',
5488
- ...(headerAliasFlags.length > 0
5735
+ ...(nativeToolsetFlags.length > 0
5489
5736
  ? {
5490
- cCompiler: { extraCLIOptions: headerAliasFlags },
5491
- cxxCompiler: { extraCLIOptions: headerAliasFlags },
5737
+ cCompiler: { extraCLIOptions: nativeToolsetFlags },
5738
+ cxxCompiler: { extraCLIOptions: nativeToolsetFlags },
5492
5739
  }
5493
5740
  : {}),
5494
5741
  swiftCompiler: {
@@ -5496,9 +5743,13 @@ export function writeSwiftProject(
5496
5743
  ...headerAliasFlags.flatMap((flag) => ['-Xcc', flag]),
5497
5744
  distribution || prebuilt ? '-Isystem' : '-I',
5498
5745
  distribution
5499
- ? distributionModulesPath(layout.root, moduleRoot, distributionExcludes)
5746
+ ? providedModulesPath(
5747
+ layout.root,
5748
+ path.join(moduleRoot, 'modules'),
5749
+ moduleExcludes,
5750
+ )
5500
5751
  : prebuilt
5501
- ? prebuilt.modules
5752
+ ? providedModulesPath(layout.root, prebuilt.modules, moduleExcludes)
5502
5753
  : path.join(layout.root, '.build', WASM_TRIPLE, 'release', 'Modules'),
5503
5754
  ...(prebuilt?.moduleMaps.flatMap((map) => [
5504
5755
  '-Xcc',
@@ -5507,7 +5758,7 @@ export function writeSwiftProject(
5507
5758
  '-Xfrontend',
5508
5759
  '-enable-cross-import-overlays',
5509
5760
  ...swiftCrossImportFlags(moduleRoot, Boolean(distribution)),
5510
- ...(distribution || prebuilt
5761
+ ...(distribution
5511
5762
  ? FOUNDATION_IMPLICIT_MODULES.flatMap((module) => [
5512
5763
  '-Xfrontend',
5513
5764
  '-import-module',
@@ -5554,6 +5805,15 @@ export function writeSwiftProject(
5554
5805
  const producers = [
5555
5806
  ...new Set([...[...native.values()].flatMap((value) => value.late?.producers ?? [])]),
5556
5807
  ]
5808
+ for (const [owner, plan] of native) {
5809
+ if (!plan.late) continue
5810
+ for (const group of plan.groups ?? [{ name: plan.late.name }]) {
5811
+ const prior = generatedOwners.get(group.name)
5812
+ if (prior !== undefined && prior !== owner)
5813
+ throw new Error(`generated target ${group.name} has multiple owners`)
5814
+ generatedOwners.set(group.name, owner)
5815
+ }
5816
+ }
5557
5817
  const headerProductTarget =
5558
5818
  layout.multi && producers.length > 1 ? SWIFT_HEADER_PRODUCTS_TARGET : undefined
5559
5819
  if (headerProductTarget)
@@ -5597,6 +5857,8 @@ export function writeSwiftProject(
5597
5857
  nativeHeaderDeclarations,
5598
5858
  headerProductTarget,
5599
5859
  targetFailures,
5860
+ generatedOwners,
5861
+ targetToolset,
5600
5862
  }
5601
5863
  }
5602
5864
 
@@ -5874,28 +6136,62 @@ function linkedFrameworkTargets(
5874
6136
  )
5875
6137
  const targets = compileTargets(input)
5876
6138
  const planning = targets.length > 0 ? targets : [{ name: 'App', path: '.' }]
5877
- const siblings = swiftTargetDependencies(input.files, planning)
6139
+ const siblings = swiftTargetDependencies(input.files, planning, libraries.keys())
5878
6140
  const reached = new Set<string>()
5879
6141
  const reach = (name: string) => {
5880
- if (reached.has(name)) return
6142
+ if (name === 'SwiftUI') return
6143
+ if (
6144
+ reached.has(name) ||
6145
+ planning.some((target) => swiftTargetModuleName(target.name) === name)
6146
+ )
6147
+ return
5881
6148
  reached.add(name)
5882
6149
  for (const dependency of OPTIONAL_FRAMEWORK_DEPENDENCIES[name] ?? [])
5883
6150
  reach(dependency)
5884
6151
  }
5885
6152
  for (const name of [...siblings.values()].flat())
5886
- if (OPTIONAL_FRAMEWORKS.has(name) && !planning.some((target) => target.name === name))
6153
+ if (libraries.has(name) && !planning.some((target) => target.name === name))
5887
6154
  reach(name)
6155
+ // SwiftUI is always present; its companion imports activate these modules.
6156
+ // a companion built as another module's dependency activates its overlay too.
6157
+ const manifest = readFileSync(path.join(moduleRoot, 'Package.swift'), 'utf8')
6158
+ const targetDependencies = new Map<string, string[]>()
6159
+ for (const match of manifest.matchAll(
6160
+ /\.target\(\s*name:\s*"([^"]+)"\s*,\s*dependencies:\s*\[([^\]]*)\]/g,
6161
+ ))
6162
+ targetDependencies.set(
6163
+ match[1]!,
6164
+ [...match[2]!.matchAll(/"([^"]+)"/g)].map((item) => item[1]!),
6165
+ )
6166
+ const built = new Set<string>()
6167
+ const build = (name: string) => {
6168
+ if (built.has(name)) return
6169
+ built.add(name)
6170
+ for (const dependency of targetDependencies.get(name) ?? []) build(dependency)
6171
+ }
6172
+ for (const name of reached)
6173
+ for (const member of libraries.get(name) ?? []) build(member)
6174
+ const overlays = path.join(moduleRoot, 'cross-import-overlays')
6175
+ for (const directory of readdirSync(overlays)) {
6176
+ const companion = path.basename(directory, '.swiftcrossimport')
6177
+ if (!built.has(companion)) continue
6178
+ const declaration = path.join(overlays, directory, 'SwiftUI.swiftoverlay')
6179
+ for (const match of readFileSync(declaration, 'utf8').matchAll(
6180
+ /^\s*- name: ([A-Za-z_]\w*)\s*$/gm,
6181
+ ))
6182
+ reach(match[1]!)
6183
+ }
5888
6184
  if (importsSpriteKit(input.files))
5889
6185
  for (const name of ['SpriteKit', 'PeachBox2D', 'simd', 'GLKit']) reach(name)
5890
6186
  const wanted = [
5891
- 'SwiftUI',
6187
+ 'PeachApp',
5892
6188
  ...(input.oneModule ? ['One'] : []),
5893
6189
  ...(importsSpriteKit(input.files) ? ['SpriteKit'] : []),
5894
6190
  ...reached,
5895
6191
  ]
5896
6192
  const linked = [...new Set(wanted)].filter((name) => libraries.has(name))
5897
- if (!linked.includes('SwiftUI'))
5898
- throw new Error('swift-compile: the framework package declares no SwiftUI library')
6193
+ if (!linked.includes('PeachApp'))
6194
+ throw new Error('swift-compile: the framework package declares no PeachApp library')
5899
6195
  const members: string[] = []
5900
6196
  for (const product of linked) {
5901
6197
  const declared = libraries.get(product) ?? []
@@ -5960,10 +6256,15 @@ ${dependencies}
5960
6256
  // node. the shell command's inputs name the modules and objects it compiles
5961
6257
  // against, which is the dependency closure. automatic products have no
5962
6258
  // Objects.LinkFileList.
5963
- function frameworkLinkClosure(
6259
+ export function frameworkLinkClosure(
5964
6260
  scratch: string,
5965
6261
  roots: readonly string[],
5966
- ): { objects: string[]; modules: Set<string>; moduleMaps: string[] } {
6262
+ ): {
6263
+ objects: string[]
6264
+ owners: Map<string, string>
6265
+ modules: Set<string>
6266
+ moduleMaps: string[]
6267
+ } {
5967
6268
  const suffix = `${WASM_TRIPLE}-release`
5968
6269
  const phonyHeader = new RegExp(`^ "<(.+)-${suffix}\\.module>":\\s*$`)
5969
6270
  const shellHeader = new RegExp(`^ "C\\.(.+)-${suffix}\\.module":\\s*$`)
@@ -6020,6 +6321,7 @@ function frameworkLinkClosure(
6020
6321
  const stack = [...roots]
6021
6322
  const files: string[] = []
6022
6323
  const seen = new Set<string>()
6324
+ const owners = new Map<string, string>()
6023
6325
  const maps = new Set<string>()
6024
6326
  while (stack.length > 0) {
6025
6327
  const name = stack.pop()!
@@ -6030,6 +6332,10 @@ function frameworkLinkClosure(
6030
6332
  if (!own || own.length === 0)
6031
6333
  throw new Error(`swift-compile: ${name} produced no objects`)
6032
6334
  for (const file of own) {
6335
+ const owner = owners.get(file)
6336
+ if (owner !== undefined && owner !== name)
6337
+ throw new Error(`swift-compile: framework object ${file} has multiple owners`)
6338
+ owners.set(file, name)
6033
6339
  if (seen.has(file)) continue
6034
6340
  seen.add(file)
6035
6341
  if (!existsSync(file))
@@ -6039,7 +6345,7 @@ function frameworkLinkClosure(
6039
6345
  for (const dependency of dependencies.get(name) ?? []) stack.push(dependency)
6040
6346
  }
6041
6347
  files.sort()
6042
- return { objects: files, modules, moduleMaps: [...maps].sort() }
6348
+ return { objects: files, owners, modules, moduleMaps: [...maps].sort() }
6043
6349
  }
6044
6350
 
6045
6351
  // apps with other optional frameworks share this directory, so only an artifact
@@ -6063,6 +6369,7 @@ function removeCaseCollidingModuleArtifacts(
6063
6369
  interface SwiftFrameworkProducts {
6064
6370
  modules: string
6065
6371
  objects: string[]
6372
+ owners: Map<string, string>
6066
6373
  /** the Darwin module's providers, linked as an archive ahead of the sdk's */
6067
6374
  providers: string[]
6068
6375
  link: string[]
@@ -6075,7 +6382,7 @@ interface SwiftFrameworkProducts {
6075
6382
  // targets differ only by case overwrite each other on a case-insensitive
6076
6383
  // volume. building the framework package into the sibling scratch leaves each
6077
6384
  // target's objects and modules under its own package, on either volume.
6078
- async function compileFrameworkProducts(args: {
6385
+ type FrameworkBuildArgs = {
6079
6386
  moduleRoot: string
6080
6387
  frameworkKey: string
6081
6388
  input: SwiftCompileInput
@@ -6088,18 +6395,11 @@ async function compileFrameworkProducts(args: {
6088
6395
  lease?: SwiftRootLease
6089
6396
  frameworkLease?: SwiftRootLease
6090
6397
  }
6091
- }): Promise<SwiftFrameworkProducts> {
6092
- const scratch = swiftFrameworkScratch(args.frameworkKey)
6093
- mkdirSync(scratch, { recursive: true })
6094
- // incremental builds leave the directory's own mtime alone, which the prune reads
6095
- const now = new Date()
6096
- utimesSync(scratch, now, now)
6097
- return buildFrameworkProducts(scratch, args)
6098
6398
  }
6099
6399
 
6100
6400
  async function buildFrameworkProducts(
6101
6401
  scratch: string,
6102
- args: Parameters<typeof compileFrameworkProducts>[0],
6402
+ args: FrameworkBuildArgs,
6103
6403
  ): Promise<SwiftFrameworkProducts> {
6104
6404
  const linkedTargets = linkedFrameworkTargets(args.moduleRoot, args.input)
6105
6405
  const linkRoot = path.join(scratch, 'link')
@@ -6175,6 +6475,7 @@ async function buildFrameworkProducts(
6175
6475
  })
6176
6476
  }
6177
6477
  objects.push(object)
6478
+ linked.owners.set(object, 'UniformTypeIdentifiers')
6178
6479
  }
6179
6480
  // a previous plan of this scratch may have left a fixture module whose name
6180
6481
  // differs only by case. the app searches this directory, so that file would
@@ -6195,13 +6496,14 @@ async function buildFrameworkProducts(
6195
6496
  // category-only archive members have no symbol reference to pull them in.
6196
6497
  // source consumers need the same direct Foundation input as distributions.
6197
6498
  if (link.includes('-lFoundation'))
6198
- for (const name of foundationCategoryObjects)
6199
- objects.push(
6200
- path.join(
6201
- swiftSdkPaths(args.moduleRoot, args.toolchainBin).resources,
6202
- `wasi/${name}.objc.o`,
6203
- ),
6499
+ for (const name of foundationCategoryObjects) {
6500
+ const object = path.join(
6501
+ swiftSdkPaths(args.moduleRoot, args.toolchainBin).resources,
6502
+ `wasi/${name}.objc.o`,
6204
6503
  )
6504
+ objects.push(object)
6505
+ linked.owners.set(object, 'Foundation')
6506
+ }
6205
6507
  // the providers compile from this revision's source, once per scratch
6206
6508
  const providerDir = path.join(scratch, 'darwin-records')
6207
6509
  if (!existsSync(path.join(providerDir, '.complete'))) {
@@ -6218,13 +6520,16 @@ async function buildFrameworkProducts(
6218
6520
  })
6219
6521
  writeFileSync(path.join(providerDir, '.complete'), '')
6220
6522
  }
6523
+ const providers = readdirSync(providerDir)
6524
+ .filter((file) => file.endsWith('.o'))
6525
+ .sort()
6526
+ .map((file) => path.join(providerDir, file))
6527
+ for (const provider of providers) linked.owners.set(provider, 'DarwinRecords')
6221
6528
  return {
6222
6529
  modules: path.join(release, 'Modules'),
6223
6530
  objects,
6224
- providers: readdirSync(providerDir)
6225
- .filter((file) => file.endsWith('.o'))
6226
- .sort()
6227
- .map((file) => path.join(providerDir, file)),
6531
+ owners: linked.owners,
6532
+ providers,
6228
6533
  link,
6229
6534
  moduleMaps: linked.moduleMaps,
6230
6535
  }
@@ -6240,9 +6545,14 @@ async function buildFrameworkProducts(
6240
6545
  // the way the builder's per-build-key roots do.
6241
6546
  const SWIFT_LINK_STAMP = '.peach-link-stamp'
6242
6547
 
6243
- // one scratch per framework revision on the machine: every app built against
6244
- // that revision reuses its compiled products.
6245
- const SWIFT_FRAMEWORK_SCRATCHES_KEPT = 3
6548
+ // a few scratch slots at fixed paths hold the framework revisions in use; every
6549
+ // app built against a revision reuses its slot's compiled products. a revision
6550
+ // with no slot takes the least recently built one, restages only the files that
6551
+ // differ and rebuilds only the modules those files reach: swiftpm and llbuild
6552
+ // key their plans on absolute paths, so a fresh path per revision recompiled
6553
+ // every module.
6554
+ const SWIFT_FRAMEWORK_SLOTS = 3
6555
+ const SWIFT_FRAMEWORK_SLOT_KEY = '.peach-framework-key'
6246
6556
 
6247
6557
  function swiftFrameworksDir(): string {
6248
6558
  return path.join(swiftCacheDir(), 'swift-frameworks')
@@ -6252,35 +6562,124 @@ function swiftFrameworkScratch(frameworkKey: string): string {
6252
6562
  return path.join(swiftFrameworksDir(), frameworkKey)
6253
6563
  }
6254
6564
 
6255
- // a builder receives every delivery at a new path, and swiftpm keys its plan and
6256
- // llbuild its inputs on absolute paths and inodes. one copy of the module and
6257
- // its shared sdk per framework key, at a fixed path, gives every delivery
6258
- // identical inputs. a published distribution is already immutable and stays put.
6259
- function stageFrameworkSource(moduleRoot: string, frameworkKey: string): string {
6260
- if (swiftDistributionAt(moduleRoot)) return moduleRoot
6261
- const staged = path.join(swiftFrameworkScratch(frameworkKey), 'source')
6262
- const stagedModule = path.join(staged, 'packages', path.basename(moduleRoot))
6263
- if (existsSync(path.join(staged, '.complete'))) return stagedModule
6264
- const partial = `${staged}.${randomUUID()}`
6265
- mkdirSync(partial, { recursive: true })
6266
- cpSync(moduleRoot, path.join(partial, 'packages', path.basename(moduleRoot)), {
6267
- recursive: true,
6268
- preserveTimestamps: true,
6269
- filter: (source) => path.relative(moduleRoot, source) !== '.build',
6565
+ function swiftFrameworkSlotKey(slot: string): string | null {
6566
+ try {
6567
+ return readFileSync(path.join(slot, SWIFT_FRAMEWORK_SLOT_KEY), 'utf8').trim()
6568
+ } catch (error) {
6569
+ if (!vanished(error)) throw error
6570
+ return null
6571
+ }
6572
+ }
6573
+
6574
+ /** runs `work` holding the slot that builds `frameworkKey`'s products: the slot
6575
+ * already staged for it, else an idle one, else the least recently built. */
6576
+ async function withSwiftFrameworkSlot<T>(
6577
+ frameworkKey: string,
6578
+ signal: AbortSignal | undefined,
6579
+ work: (slot: string, lease: SwiftRootLease) => Promise<T>,
6580
+ ): Promise<T> {
6581
+ const slots = Array.from({ length: SWIFT_FRAMEWORK_SLOTS }, (_, index) => {
6582
+ const slot = path.join(swiftFrameworksDir(), `slot-${index}`)
6583
+ mkdirSync(slot, { recursive: true })
6584
+ return slot
6270
6585
  })
6271
- cpSync(
6272
- swiftSharedSdkRoot(moduleRoot, false),
6273
- path.join(partial, 'packages/peachsim/sdk/ios'),
6274
- { recursive: true, preserveTimestamps: true },
6275
- )
6276
- // the plugin build resolves the macro scanner from the module's node_modules
6277
- symlinkSync(
6278
- realpathSync(path.join(moduleRoot, '../../node_modules')),
6279
- path.join(partial, 'node_modules'),
6586
+ const run = (slot: string) => (lease: SwiftRootLease) => {
6587
+ // an incremental build leaves the directory's own mtime alone, which orders reuse
6588
+ const now = new Date()
6589
+ utimesSync(slot, now, now)
6590
+ return work(slot, lease)
6591
+ }
6592
+ const staged = slots.find((slot) => swiftFrameworkSlotKey(slot) === frameworkKey)
6593
+ if (staged) return withSwiftRootLock(staged, run(staged), signal)
6594
+ const oldest = slots.sort(
6595
+ (left, right) => statSync(left).mtimeMs - statSync(right).mtimeMs,
6280
6596
  )
6281
- writeFileSync(path.join(partial, '.complete'), '')
6282
- rmSync(staged, { recursive: true, force: true })
6283
- renameSync(partial, staged)
6597
+ for (const slot of oldest) {
6598
+ const result = await withSwiftRootLock(
6599
+ slot,
6600
+ async (lease) => ({ value: await run(slot)(lease) }),
6601
+ signal,
6602
+ false,
6603
+ )
6604
+ if (result) return result.value
6605
+ }
6606
+ return withSwiftRootLock(oldest[0]!, run(oldest[0]!), signal)
6607
+ }
6608
+
6609
+ // copies the files of `source` that differ into `target` and removes the rest of
6610
+ // `target`. a file whose size and mtime match, or whose bytes match, is left
6611
+ // alone so llbuild sees it unchanged; a changed file arrives as a new inode.
6612
+ function mirrorTree(source: string, target: string, skip?: string): void {
6613
+ mkdirSync(target, { recursive: true })
6614
+ const wanted = new Set<string>()
6615
+ for (const entry of readdirSync(source, { withFileTypes: true })) {
6616
+ if (entry.name === skip) continue
6617
+ wanted.add(entry.name)
6618
+ const from = path.join(source, entry.name)
6619
+ const to = path.join(target, entry.name)
6620
+ let existing: ReturnType<typeof lstatSync> | null = null
6621
+ try {
6622
+ existing = lstatSync(to)
6623
+ } catch (error) {
6624
+ if (!vanished(error)) throw error
6625
+ }
6626
+ if (entry.isDirectory()) {
6627
+ if (existing && !existing.isDirectory()) rmSync(to, { force: true })
6628
+ mirrorTree(from, to)
6629
+ } else if (entry.isSymbolicLink()) {
6630
+ const link = readlinkSync(from)
6631
+ if (existing?.isSymbolicLink() && readlinkSync(to) === link) continue
6632
+ if (existing) rmSync(to, { recursive: true, force: true })
6633
+ symlinkSync(link, to)
6634
+ } else {
6635
+ const stat = statSync(from)
6636
+ if (
6637
+ existing?.isFile() &&
6638
+ existing.size === stat.size &&
6639
+ (existing.mtimeMs === stat.mtimeMs || readFileSync(from).equals(readFileSync(to)))
6640
+ )
6641
+ continue
6642
+ if (existing) rmSync(to, { recursive: true, force: true })
6643
+ const partial = `${to}.${randomUUID()}`
6644
+ copyFileSync(from, partial)
6645
+ utimesSync(partial, stat.atime, stat.mtime)
6646
+ renameSync(partial, to)
6647
+ }
6648
+ }
6649
+ for (const name of readdirSync(target))
6650
+ if (!wanted.has(name) && name !== skip)
6651
+ rmSync(path.join(target, name), { recursive: true, force: true })
6652
+ }
6653
+
6654
+ // a builder receives every delivery at a new path, and swiftpm keys its plan and
6655
+ // llbuild its inputs on absolute paths and inodes. the module and its shared sdk
6656
+ // are mirrored into the slot at a fixed path, so a revision rebuilds only what
6657
+ // changed. a published distribution is already immutable and stays put.
6658
+ function stageFrameworkSource(
6659
+ moduleRoot: string,
6660
+ slot: string | null,
6661
+ frameworkKey: string,
6662
+ ): string {
6663
+ if (!slot) return moduleRoot
6664
+ const staged = path.join(slot, 'source')
6665
+ const stagedModule = path.join(staged, 'packages', path.basename(moduleRoot))
6666
+ if (swiftFrameworkSlotKey(slot) !== frameworkKey) {
6667
+ // an interrupted restage must not look like a finished one
6668
+ rmSync(path.join(slot, SWIFT_FRAMEWORK_SLOT_KEY), { force: true })
6669
+ mirrorTree(moduleRoot, stagedModule, '.build')
6670
+ mirrorTree(
6671
+ swiftSharedSdkRoot(moduleRoot, false),
6672
+ path.join(staged, 'packages/peachsim/sdk/ios'),
6673
+ )
6674
+ // the plugin build resolves the macro scanner from the module's node_modules
6675
+ const modules = path.join(staged, 'node_modules')
6676
+ const target = realpathSync(path.join(moduleRoot, '../../node_modules'))
6677
+ if (!existsSync(modules) || readlinkSync(modules) !== target) {
6678
+ rmSync(modules, { recursive: true, force: true })
6679
+ symlinkSync(target, modules)
6680
+ }
6681
+ writeFileSync(path.join(slot, SWIFT_FRAMEWORK_SLOT_KEY), frameworkKey)
6682
+ }
6284
6683
  return stagedModule
6285
6684
  }
6286
6685
 
@@ -6308,24 +6707,6 @@ function swiftLinkStamp(args: {
6308
6707
  return hash.digest('hex')
6309
6708
  }
6310
6709
 
6311
- // each scratch holds over a gibibyte, so the least recently built revisions go.
6312
- // a scratch another process holds is skipped.
6313
- async function pruneFrameworkScratches(keep: string): Promise<void> {
6314
- const dir = swiftFrameworksDir()
6315
- const idle = readdirSync(dir)
6316
- .filter((name) => name !== keep)
6317
- .map((name) => ({ name, modified: statSync(path.join(dir, name)).mtimeMs }))
6318
- .sort((left, right) => right.modified - left.modified)
6319
- .slice(SWIFT_FRAMEWORK_SCRATCHES_KEPT - 1)
6320
- for (const { name } of idle)
6321
- await withSwiftRootLock(
6322
- path.join(dir, name),
6323
- async () => rmSync(path.join(dir, name), { recursive: true, force: true }),
6324
- undefined,
6325
- false,
6326
- )
6327
- }
6328
-
6329
6710
  /** the root keeps one app object tree per linked framework build. */
6330
6711
  function retireStaleSwiftLink(root: string, stamp: string): boolean {
6331
6712
  const receipt = path.join(root, SWIFT_LINK_STAMP)
@@ -6370,6 +6751,9 @@ function compileSwiftProjectOnce(
6370
6751
  const root = realpathSync(options.buildRoot)
6371
6752
  const moduleRoot = path.resolve(options.moduleRoot)
6372
6753
  const distribution = swiftDistributionAt(moduleRoot)
6754
+ const guestGraph = distribution ? input.sourceLinkGraph : undefined
6755
+ // the guest link always runs wasm-opt, so its artifact is the optimized one.
6756
+ if (guestGraph && !input.optimize) input = { ...input, optimize: true }
6373
6757
  const layout: SwiftProjectLayout = {
6374
6758
  root,
6375
6759
  sources: path.join(root, 'Sources', 'App'),
@@ -6493,13 +6877,13 @@ function compileSwiftProjectOnce(
6493
6877
  // roots compiling against it overlap and only its plugin check queues.
6494
6878
  const frameworkScratch = swiftFrameworkScratch(frameworkKey)
6495
6879
  const withFrameworkLock = <T>(
6496
- work: (frameworkLease?: SwiftRootLease) => Promise<T>,
6880
+ work: (slot: string | null, frameworkLease?: SwiftRootLease) => Promise<T>,
6497
6881
  ) =>
6498
6882
  distribution
6499
- ? work()
6500
- : withSwiftRootLock(frameworkScratch, work, options.signal)
6501
- return withFrameworkLock(async (frameworkLease) => {
6502
- const frameworkRoot = stageFrameworkSource(moduleRoot, frameworkKey)
6883
+ ? work(null)
6884
+ : withSwiftFrameworkSlot(frameworkKey, options.signal, work)
6885
+ return withFrameworkLock(async (slot, frameworkLease) => {
6886
+ const frameworkRoot = stageFrameworkSource(moduleRoot, slot, frameworkKey)
6503
6887
  report('preparing compiler plugins')
6504
6888
  const pluginsFor = (pluginLease?: SwiftRootLease) =>
6505
6889
  ensureMacroPlugins(
@@ -6542,7 +6926,7 @@ function compileSwiftProjectOnce(
6542
6926
  let prebuilt: SwiftFrameworkProducts | undefined
6543
6927
  if (!distribution) {
6544
6928
  report('compiling framework products')
6545
- prebuilt = await compileFrameworkProducts({
6929
+ prebuilt = await buildFrameworkProducts(slot!, {
6546
6930
  moduleRoot: frameworkRoot,
6547
6931
  frameworkKey,
6548
6932
  input,
@@ -6552,7 +6936,6 @@ function compileSwiftProjectOnce(
6552
6936
  plugins: macroPlugins,
6553
6937
  buildOptions,
6554
6938
  })
6555
- await pruneFrameworkScratches(frameworkKey)
6556
6939
  }
6557
6940
  if (options.project) removeProjectLinks(root)
6558
6941
  if (
@@ -6610,7 +6993,7 @@ function compileSwiftProjectOnce(
6610
6993
  ...swiftObjCSelectorOptions(frameworkRoot),
6611
6994
  '--swift-sdk',
6612
6995
  sdk,
6613
- ...(nativeToolset
6996
+ ...(preparation.targetToolset
6614
6997
  ? ['--toolset', path.join(root, '.peach-target-toolset.json')]
6615
6998
  : []),
6616
6999
  '-c',
@@ -6793,7 +7176,8 @@ function compileSwiftProjectOnce(
6793
7176
  )
6794
7177
  }
6795
7178
  if (options.project) removeProjectLinks(root)
6796
- if (input.optimize)
7179
+ // the guest link prunes and links the response file itself.
7180
+ if (input.optimize && !guestGraph)
6797
7181
  pruneSwiftWasmLink(
6798
7182
  root,
6799
7183
  options.toolchainBin,
@@ -6805,7 +7189,21 @@ function compileSwiftProjectOnce(
6805
7189
  ? projectOutputFile(root, linked, options.project)
6806
7190
  : linked
6807
7191
  const optimized = `${output}.optimized`
6808
- if (input.optimize) await optimizeWasm(output, optimized)
7192
+ if (guestGraph)
7193
+ await compileGuestLink({
7194
+ graph: guestGraph,
7195
+ buildDirectory: root,
7196
+ releaseDirectory: path.dirname(linked),
7197
+ moduleRoot: frameworkRoot,
7198
+ toolchainBin: options.toolchainBin,
7199
+ sysroot: swiftSdkPaths(frameworkRoot, options.toolchainBin).sysroot,
7200
+ sdk: swiftModuleSdk(frameworkRoot),
7201
+ staticClangTargets: input.staticClangTargets ?? [],
7202
+ generatedOwners: preparation.generatedOwners,
7203
+ output,
7204
+ optimized,
7205
+ })
7206
+ else if (input.optimize) await optimizeWasm(output, optimized)
6809
7207
  const artifact = {
6810
7208
  hash,
6811
7209
  bytes: readFileSync(input.optimize ? optimized : output),