peachsim 0.1.1881 → 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 (153) 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 +8914 -4264
  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 +8494 -3955
  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 +9679 -5057
  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 +720 -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 +30711 -25956
  72. package/dist-lib/swift-compile.cjs +6782 -2533
  73. package/dist-lib/swift-compile.mjs +6112 -1864
  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 +8640 -4109
  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 +399 -72
  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/wasm-optimize.ts +16 -4
  153. package/src/xcode-project.ts +142 -14
@@ -46,6 +46,7 @@ import {
46
46
  SWIFT_DISTRIBUTION_OBJC_SELECTORS,
47
47
  } from './swift-distribution-contract'
48
48
  import { foundationCategoryObjects } from './swift-foundation'
49
+ import { compileGuestLink } from './swift-guest-compile'
49
50
  import {
50
51
  brotliCompressQ11,
51
52
  brotliCompressQ4,
@@ -115,6 +116,8 @@ import { compileUniformTypeConstants } from './swift-uniform-type-constants'
115
116
  import { pruneSwiftWasmLink } from './swift-wasm-prune'
116
117
  import {
117
118
  isSwiftNativeTargets,
119
+ isSwiftSourceLinkGraph,
120
+ type SwiftSourceLinkGraph,
118
121
  isSwiftHeaderAliases,
119
122
  isSwiftPackageFiles,
120
123
  isSwiftProjectFiles,
@@ -282,6 +285,7 @@ export interface SwiftCompileInput {
282
285
  projectFiles?: Record<string, string>
283
286
  packageGuestImports?: string[]
284
287
  nativeTargets?: SwiftNativeTarget[]
288
+ sourceLinkGraph?: SwiftSourceLinkGraph
285
289
  headerAliases?: SwiftHeaderAliases
286
290
  /** the Xcode app project's development region, for the emitted manifest's default localization. */
287
291
  defaultLocalization?: string
@@ -527,16 +531,21 @@ export function swiftModuleInputFiles(root: string): string[] {
527
531
  const files: string[] = [
528
532
  ...swiftSharedSdkInputFiles(root),
529
533
  '../peachsim/src/swift-shared-sdk.ts',
530
- '../peachsim/src/swift-darwin-records.ts',
531
- '../peachsim/src/swift-uniform-type-constants.ts',
532
534
  '../peachsim/src/swift-runtime-products.ts',
533
535
  '../peachsim/src/swiftRuntimeProductContract.ts',
536
+ '../peachsim/src/swift-darwin-records.ts',
537
+ '../peachsim/src/swift-uniform-type-constants.ts',
534
538
  '../../scripts/generate/swift-sdk-module/darwin-mach.json',
535
539
  '../../scripts/generate/swift-sdk-module/darwin-socketvar.json',
536
540
  '../../scripts/ops/swift-distribution-publish.ts',
541
+ '../../src/helpers/mapLimit.ts',
537
542
  'Package.swift',
538
543
  'scripts/contrast-app-Package.swift',
539
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',
540
549
  'scripts/distribution-clang.ts',
541
550
  'runtime/UniformTypeIdentifiersConstants.m',
542
551
  'Sources/libxml2/include/module.modulemap',
@@ -1136,6 +1145,64 @@ export function swiftSdkPaths(
1136
1145
 
1137
1146
  const availableModules = new Map<string, Set<string>>()
1138
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
+
1139
1206
  /**
1140
1207
  * every module a source compiled against `moduleRoot` can import: Peach's own
1141
1208
  * and the wasm SDK's swift modules and top-level clang modules.
@@ -1149,7 +1216,29 @@ export function swiftAvailableModules(
1149
1216
  const cached = availableModules.get(key)
1150
1217
  if (cached) return cached
1151
1218
  const modules = new Set(swiftPeachModules(moduleRoot))
1152
- 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
+ }
1153
1242
  for (const entry of readdirSync(path.join(resources, 'wasi'))) {
1154
1243
  if (entry.endsWith('.swiftmodule'))
1155
1244
  modules.add(entry.slice(0, -'.swiftmodule'.length))
@@ -1262,15 +1351,18 @@ export function swiftSystemLibraryExclusions(
1262
1351
  )
1263
1352
  }
1264
1353
 
1265
- /** a distribution modules path without the modules a local system library owns. */
1266
- function distributionModulesPath(
1354
+ /** prebuilt modules without interfaces owned by the compiling source graph. */
1355
+ function providedModulesPath(
1267
1356
  root: string,
1268
- moduleRoot: string,
1357
+ modules: string,
1269
1358
  excluded: ReadonlySet<string> | undefined,
1270
1359
  ): string {
1271
- const modules = path.join(moduleRoot, 'modules')
1272
1360
  if (!excluded || excluded.size === 0) return modules
1361
+ const entries = readdirSync(modules)
1362
+ .filter((entry) => !excluded.has(entry.replace(/\..*$/, '')))
1363
+ .sort()
1273
1364
  const key = createHash('sha256')
1365
+ .update(JSON.stringify([modules, entries]))
1274
1366
  .update([...excluded].sort().join('\0'))
1275
1367
  .digest('hex')
1276
1368
  .slice(0, 16)
@@ -1280,8 +1372,7 @@ function distributionModulesPath(
1280
1372
  mkdirSync(directory, { recursive: true })
1281
1373
  for (const entry of readdirSync(directory))
1282
1374
  rmSync(path.join(directory, entry), { recursive: true, force: true })
1283
- for (const entry of readdirSync(modules)) {
1284
- if (excluded.has(entry.replace(/\.swiftmodule$/, ''))) continue
1375
+ for (const entry of entries) {
1285
1376
  symlinkSync(path.join(modules, entry), path.join(directory, entry))
1286
1377
  }
1287
1378
  writeFileSync(complete, '')
@@ -1291,9 +1382,14 @@ function distributionModulesPath(
1291
1382
 
1292
1383
  export function swiftTargetDependencies(
1293
1384
  files: Record<string, string>,
1294
- targets: Pick<SwiftPackageTarget, 'name' | 'path' | 'dependencies'>[],
1385
+ targets: Pick<
1386
+ SwiftPackageTarget,
1387
+ 'name' | 'path' | 'dependencies' | 'sources' | 'exclude'
1388
+ >[],
1389
+ frameworks: Iterable<string> = OPTIONAL_FRAMEWORKS,
1295
1390
  ): Map<string, string[]> {
1296
- 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])
1297
1393
  const siblings = new Map<string, string[]>()
1298
1394
  for (const target of targets) {
1299
1395
  const prefix = target.path === '.' ? '' : `${target.path}/`
@@ -1322,7 +1418,23 @@ export function swiftTargetDependencies(
1322
1418
  )
1323
1419
  for (const [file, contents] of Object.entries(files)) {
1324
1420
  if (file === 'Package.swift' || !file.startsWith(prefix)) continue
1421
+ const relative = file.slice(prefix.length)
1325
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
1436
+ if (
1437
+ target.sources === undefined &&
1326
1438
  targets.some(
1327
1439
  (candidate) =>
1328
1440
  candidate.name !== target.name &&
@@ -1338,7 +1450,14 @@ export function swiftTargetDependencies(
1338
1450
  ? clangImportNames(contents, ownsHeader)
1339
1451
  : []
1340
1452
  for (const name of imports) {
1341
- 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)
1342
1461
  }
1343
1462
  }
1344
1463
  siblings.set(target.name, [...deps].sort())
@@ -1404,7 +1523,7 @@ const darwinRecordsRegion = (quoted: readonly string[]): string[] =>
1404
1523
  const REACTOR_FLAG = '"-Xclang-linker", "-mexec-model=reactor",\n'
1405
1524
 
1406
1525
  /** bump with any change to the emitted multi-target manifest text. */
1407
- export const MULTI_MANIFEST_VERSION = 65
1526
+ export const MULTI_MANIFEST_VERSION = 66
1408
1527
  const SWIFT_HEADER_PRODUCTS_TARGET = 'PeachHeaderProducts'
1409
1528
 
1410
1529
  // build-cli replaces this in every bundle; source runs read the files directly.
@@ -1463,6 +1582,7 @@ export function swiftArtifactHash(
1463
1582
  ),
1464
1583
  )
1465
1584
  hash.update(JSON.stringify(input.nativeTargets ?? []))
1585
+ hash.update(JSON.stringify(input.sourceLinkGraph ?? null))
1466
1586
  hash.update(JSON.stringify(input.staticClangTargets ?? []))
1467
1587
  hash.update(JSON.stringify(input.headerAliases ?? {}))
1468
1588
  hash.update(JSON.stringify(input.packageGuestImports ?? []))
@@ -1608,8 +1728,8 @@ export function emitSwiftPackageManifest(args: {
1608
1728
  spriteKit?: boolean
1609
1729
  /** link the prebuilt distribution at moduleRoot instead of its sources. */
1610
1730
  distribution?: SwiftDistributionManifest
1611
- /** distribution modules owned by local targets or their native headers. */
1612
- distributionExcludes?: ReadonlySet<string>
1731
+ /** prebuilt interfaces owned by local source or system-library targets. */
1732
+ moduleExcludes?: ReadonlySet<string>
1613
1733
  /**
1614
1734
  * ordered distribution objects, read by the linker without expanding argv.
1615
1735
  * absent when no source reaches a distribution framework: the executable
@@ -1638,11 +1758,13 @@ export function emitSwiftPackageManifest(args: {
1638
1758
  const linkedObjects = Boolean(distribution || prebuilt)
1639
1759
  const cxxFlagsFor = (flags: readonly string[]): readonly string[] =>
1640
1760
  args.deferDarwinOverlay ? withoutWasmOverlayIsystem(flags) : flags
1641
- // the base distribution links authenticationservices' prf key storage,
1642
- // which requires cryptokit even when an app does not import it directly.
1643
- const reachedFrameworks = new Set<string>(['CryptoKit'])
1761
+ const reachedFrameworks = new Set<string>()
1644
1762
  const reach = (name: string) => {
1645
- if (reachedFrameworks.has(name)) return
1763
+ if (
1764
+ reachedFrameworks.has(name) ||
1765
+ targets.some((target) => swiftTargetModuleName(target.name) === name)
1766
+ )
1767
+ return
1646
1768
  reachedFrameworks.add(name)
1647
1769
  for (const dependency of OPTIONAL_FRAMEWORK_DEPENDENCIES[name] ?? [])
1648
1770
  reach(dependency)
@@ -1823,10 +1945,14 @@ export function emitSwiftPackageManifest(args: {
1823
1945
  // object for autolinks; distribution.link supplies those libraries.
1824
1946
  const imports = distribution
1825
1947
  ? `, "-Isystem", ${JSON.stringify(
1826
- distributionModulesPath(args.root, moduleRoot, args.distributionExcludes),
1948
+ providedModulesPath(
1949
+ args.root,
1950
+ path.join(moduleRoot, 'modules'),
1951
+ args.moduleExcludes,
1952
+ ),
1827
1953
  )}`
1828
1954
  : prebuilt
1829
- ? `, "-Isystem", ${JSON.stringify(prebuilt.modules)}${prebuilt.moduleMaps
1955
+ ? `, "-Isystem", ${JSON.stringify(providedModulesPath(args.root, prebuilt.modules, args.moduleExcludes))}${prebuilt.moduleMaps
1830
1956
  .map((map) => `, "-Xcc", ${JSON.stringify(`-fmodule-map-file=${map}`)}`)
1831
1957
  .join('')}`
1832
1958
  : ''
@@ -2035,7 +2161,9 @@ export function emitSwiftPackageManifest(args: {
2035
2161
  ]
2036
2162
  : native?.flags
2037
2163
  ? [` sources: ${JSON.stringify(native.sources)},`]
2038
- : []),
2164
+ : target.sources !== undefined
2165
+ ? [` sources: ${JSON.stringify(target.sources)},`]
2166
+ : []),
2039
2167
  ...(!native?.clang && target.publicHeadersPath !== undefined
2040
2168
  ? [` publicHeadersPath: ${JSON.stringify(target.publicHeadersPath)},`]
2041
2169
  : []),
@@ -2183,6 +2311,7 @@ const FRAME_INIT = /^override(?=\s+(?:(?:public|open|internal)\s+)?init\s*\(\s*f
2183
2311
  function compiledSwiftSources(
2184
2312
  files: Record<string, string>,
2185
2313
  targets: SwiftPackageTarget[],
2314
+ overlayFrameworks: () => ReadonlySet<string>,
2186
2315
  ): Map<string, string> {
2187
2316
  const ordered = [...targets].sort((a, b) => b.path.length - a.path.length)
2188
2317
  return new Map(
@@ -2204,6 +2333,7 @@ function compiledSwiftSources(
2204
2333
  ? source
2205
2334
  : swiftSourceAsIOS(
2206
2335
  source,
2336
+ overlayFrameworks,
2207
2337
  owner?.defines?.includes(SWIFT_XCODE_BUILD_CONDITION) &&
2208
2338
  !owner.defines.includes('SWIFT_PACKAGE')
2209
2339
  ? false
@@ -2380,8 +2510,6 @@ const FOUNDATION_NETWORKING_TYPES = new Set([
2380
2510
  'NSURLConnectionDataDelegate',
2381
2511
  'NSURLConnectionDelegate',
2382
2512
  'NSURLConnectionDownloadDelegate',
2383
- 'URLProtocol',
2384
- 'URLProtocolClient',
2385
2513
  ])
2386
2514
 
2387
2515
  // Foundation overlay declarations live in the shared guest overlay module.
@@ -3044,7 +3172,6 @@ const CORE_FOUNDATION_HANDLE_IMPORTS = [
3044
3172
 
3045
3173
  // the guest module that owns a name darwin's Foundation declares
3046
3174
  export function foundationOwnerOf(name: string): string | undefined {
3047
- if (name === 'NSErrorPointer') return 'Foundation'
3048
3175
  if (
3049
3176
  name === 'NSClassFromString' ||
3050
3177
  name === 'NSKeyValueChange' ||
@@ -3063,7 +3190,11 @@ export function foundationOwnerOf(name: string): string | undefined {
3063
3190
  return undefined
3064
3191
  }
3065
3192
 
3066
- export function swiftSourceAsIOS(source: string, swiftPackage?: boolean): string {
3193
+ export function swiftSourceAsIOS(
3194
+ source: string,
3195
+ overlayFrameworks: () => ReadonlySet<string>,
3196
+ swiftPackage?: boolean,
3197
+ ): string {
3067
3198
  const { lineStarts, tokens } = swiftCodeScan(source)
3068
3199
  let offset = 0
3069
3200
  // equal width, so every token offset still holds
@@ -3118,16 +3249,18 @@ export function swiftSourceAsIOS(source: string, swiftPackage?: boolean): string
3118
3249
  }
3119
3250
  continue
3120
3251
  }
3121
- // a Clang submodule import (`import UIKit.UIImage`) names its framework:
3122
- // peach's frameworks are Swift modules with no submodules, and on iOS the
3123
- // 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.
3124
3254
  const imported =
3125
3255
  conditioned[at - 1] === '.'
3126
3256
  ? null
3127
3257
  : /^import[ \t]+([A-Za-z_]\w*)(?:[ \t]*\.[ \t]*[A-Za-z_]\w*)+/.exec(rest)
3128
3258
  if (imported) {
3129
3259
  out +=
3130
- 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])
3131
3264
  if (imported[1] === 'CoreFoundation') out += `; ${CORE_FOUNDATION_HANDLE_IMPORTS}`
3132
3265
  copied = at + imported[0].length
3133
3266
  continue
@@ -3915,9 +4048,14 @@ function swiftCodeScan(source: string): {
3915
4048
  * source adapted as app sources are, retaining native objective-c syntax.
3916
4049
  * its manifests stay as
3917
4050
  * published and the upstream tree is never written. */
3918
- export function prepareSwiftDependency(source: string, destination: string): void {
4051
+ export function prepareSwiftDependency(
4052
+ source: string,
4053
+ destination: string,
4054
+ overlayFrameworks: () => ReadonlySet<string>,
4055
+ ): void {
3919
4056
  rmSync(destination, { recursive: true, force: true })
3920
4057
  const origins: Record<string, string> = {}
4058
+ const moduleMaps: string[] = []
3921
4059
  const gather = (from: string) => {
3922
4060
  for (const entry of readdirSync(from, { withFileTypes: true })) {
3923
4061
  if (entry.name === '.git' || entry.name === '.build' || entry.name === '.swiftpm')
@@ -3926,6 +4064,8 @@ export function prepareSwiftDependency(source: string, destination: string): voi
3926
4064
  if (entry.isDirectory()) gather(file)
3927
4065
  else if (entry.isFile() && entry.name.endsWith('.swift'))
3928
4066
  origins[path.relative(source, file)] = readFileSync(file, 'utf8')
4067
+ else if (entry.isFile() && entry.name.endsWith('.modulemap'))
4068
+ moduleMaps.push(readFileSync(file, 'utf8'))
3929
4069
  }
3930
4070
  }
3931
4071
  gather(source)
@@ -3933,7 +4073,26 @@ export function prepareSwiftDependency(source: string, destination: string): voi
3933
4073
  const targets = existsSync(manifest)
3934
4074
  ? swiftManifestTargets(readFileSync(manifest, 'utf8'))
3935
4075
  : []
3936
- 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
+ })
3937
4096
  const copy = (from: string, to: string) => {
3938
4097
  mkdirSync(to, { recursive: true })
3939
4098
  for (const entry of readdirSync(from, { withFileTypes: true })) {
@@ -3952,6 +4111,31 @@ export function prepareSwiftDependency(source: string, destination: string): voi
3952
4111
 
3953
4112
  // where a mixed native target compiles units whose paths swiftpm would hide.
3954
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
+ }
3955
4139
 
3956
4140
  // a clang dependency's module map is written beside its public headers after
3957
4141
  // that target's own import. an earlier import already has that directory on
@@ -4036,10 +4220,18 @@ export function writeSwiftProject(
4036
4220
  input: SwiftCompileInput,
4037
4221
  moduleRoot: string,
4038
4222
  prebuilt?: SwiftFrameworkProducts,
4039
- ): SwiftProjectPreparation {
4223
+ ): SwiftProjectPreparation & {
4224
+ generatedOwners: Map<string, string>
4225
+ targetToolset: boolean
4226
+ } {
4040
4227
  const nativeToolset = needsNativeToolset(input, prebuilt)
4041
4228
  if (input.headerAliases !== undefined && !isSwiftHeaderAliases(input.headerAliases))
4042
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')
4043
4235
  if (input.nativeTargets !== undefined && !isSwiftNativeTargets(input.nativeTargets))
4044
4236
  throw new Error('swift compile input has invalid original clang target inputs')
4045
4237
  if (input.packageFiles !== undefined && !isSwiftPackageFiles(input.packageFiles))
@@ -4084,16 +4276,27 @@ export function writeSwiftProject(
4084
4276
  },
4085
4277
  ]
4086
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
+ : [])
4087
4289
  // a local target owns its module, including native React targets from the
4088
- // installed workspace. the distribution must not replace its declarations.
4089
- const distributionExcludes = distribution
4090
- ? new Set([
4091
- ...swiftSystemLibraryExclusions(input.files, targets, distribution.modules),
4092
- ...distribution.modules.filter((name) =>
4093
- targets.some((target) => target.name === name),
4094
- ),
4095
- ])
4096
- : 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
4097
4300
  const files = new Map<string, string | Buffer>()
4098
4301
  const native = new Map<string, SwiftNativeTargetPlan>()
4099
4302
  const targetFailures: string[] = []
@@ -4176,6 +4379,10 @@ export function writeSwiftProject(
4176
4379
  return Object.entries(input.files).filter(
4177
4380
  ([file]) =>
4178
4381
  file.startsWith(prefix) &&
4382
+ !target.exclude?.some(
4383
+ (excluded) =>
4384
+ file === `${prefix}${excluded}` || file.startsWith(`${prefix}${excluded}/`),
4385
+ ) &&
4179
4386
  !targets.some(
4180
4387
  (candidate) =>
4181
4388
  candidate.name !== target.name &&
@@ -4737,6 +4944,9 @@ export function writeSwiftProject(
4737
4944
  // before quoted header maps and configured user search paths.
4738
4945
  const quoteFlags = origin ? ['-iquote', path.join(layout.root, origin)] : []
4739
4946
  const perFile = [
4947
+ ...(file.endsWith('.c') && swiftWholeFileArm64Guard(contents)
4948
+ ? ['-D__arm64__=1']
4949
+ : []),
4740
4950
  ...(/\.mm?$/.test(file) ? ['-fobjc-exceptions'] : []),
4741
4951
  ...stageFlags(
4742
4952
  settings?.fileFlags[file] ?? [],
@@ -5066,6 +5276,7 @@ export function writeSwiftProject(
5066
5276
  const moduleFiles = `\n// sootsim-swift files ${modulePlan.digest('hex').slice(0, 16)}\n// resource accessors ${resourcePlan}\n`
5067
5277
  // view builder literals compile as xcode's design-time lookups, so a save
5068
5278
  // that changes only them reloads without compiling (swift-design-time.ts)
5279
+ let projectOverlayFrameworks: Set<string> | undefined
5069
5280
  const compiled = compiledSwiftSources(
5070
5281
  Object.fromEntries(
5071
5282
  Object.entries(input.files).map(([file, contents]) => [
@@ -5074,6 +5285,24 @@ export function writeSwiftProject(
5074
5285
  ]),
5075
5286
  ),
5076
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
+ },
5077
5306
  )
5078
5307
  // an application's swift module must precede its native implementations.
5079
5308
  // the tiny executable calls the original typed entry after both are linked.
@@ -5161,6 +5390,7 @@ export function writeSwiftProject(
5161
5390
  if (targets.some((candidate) => candidate.name === name))
5162
5391
  throw new Error(`mixed application executable target conflicts with ${name}`)
5163
5392
  target.executable = false
5393
+ generatedOwners.set(name, target.name)
5164
5394
  targets.push({
5165
5395
  ...target,
5166
5396
  name,
@@ -5168,6 +5398,7 @@ export function writeSwiftProject(
5168
5398
  executable: true,
5169
5399
  resources: false,
5170
5400
  dependencies: [{ kind: 'target', name: target.name }],
5401
+ sources: ['Entry.swift'],
5171
5402
  exclude: [],
5172
5403
  })
5173
5404
  files.set(
@@ -5444,7 +5675,7 @@ export function writeSwiftProject(
5444
5675
  oneModule: input.oneModule,
5445
5676
  spriteKit: importsSpriteKit(input.files),
5446
5677
  distribution: distribution ?? undefined,
5447
- distributionExcludes,
5678
+ moduleExcludes,
5448
5679
  deferDarwinOverlay:
5449
5680
  native.size > 0 &&
5450
5681
  toolsetOrdersLibcxxBeforeDarwinOverlay(
@@ -5483,15 +5714,28 @@ export function writeSwiftProject(
5483
5714
  if (files.has(destination)) continue
5484
5715
  files.set(destination, Buffer.from(bytes, 'base64'))
5485
5716
  }
5486
- 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
+ ]
5487
5731
  files.set(
5488
5732
  path.join(layout.root, '.peach-target-toolset.json'),
5489
5733
  JSON.stringify({
5490
5734
  schemaVersion: '1.0',
5491
- ...(headerAliasFlags.length > 0
5735
+ ...(nativeToolsetFlags.length > 0
5492
5736
  ? {
5493
- cCompiler: { extraCLIOptions: headerAliasFlags },
5494
- cxxCompiler: { extraCLIOptions: headerAliasFlags },
5737
+ cCompiler: { extraCLIOptions: nativeToolsetFlags },
5738
+ cxxCompiler: { extraCLIOptions: nativeToolsetFlags },
5495
5739
  }
5496
5740
  : {}),
5497
5741
  swiftCompiler: {
@@ -5499,9 +5743,13 @@ export function writeSwiftProject(
5499
5743
  ...headerAliasFlags.flatMap((flag) => ['-Xcc', flag]),
5500
5744
  distribution || prebuilt ? '-Isystem' : '-I',
5501
5745
  distribution
5502
- ? distributionModulesPath(layout.root, moduleRoot, distributionExcludes)
5746
+ ? providedModulesPath(
5747
+ layout.root,
5748
+ path.join(moduleRoot, 'modules'),
5749
+ moduleExcludes,
5750
+ )
5503
5751
  : prebuilt
5504
- ? prebuilt.modules
5752
+ ? providedModulesPath(layout.root, prebuilt.modules, moduleExcludes)
5505
5753
  : path.join(layout.root, '.build', WASM_TRIPLE, 'release', 'Modules'),
5506
5754
  ...(prebuilt?.moduleMaps.flatMap((map) => [
5507
5755
  '-Xcc',
@@ -5510,7 +5758,7 @@ export function writeSwiftProject(
5510
5758
  '-Xfrontend',
5511
5759
  '-enable-cross-import-overlays',
5512
5760
  ...swiftCrossImportFlags(moduleRoot, Boolean(distribution)),
5513
- ...(distribution || prebuilt
5761
+ ...(distribution
5514
5762
  ? FOUNDATION_IMPLICIT_MODULES.flatMap((module) => [
5515
5763
  '-Xfrontend',
5516
5764
  '-import-module',
@@ -5557,6 +5805,15 @@ export function writeSwiftProject(
5557
5805
  const producers = [
5558
5806
  ...new Set([...[...native.values()].flatMap((value) => value.late?.producers ?? [])]),
5559
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
+ }
5560
5817
  const headerProductTarget =
5561
5818
  layout.multi && producers.length > 1 ? SWIFT_HEADER_PRODUCTS_TARGET : undefined
5562
5819
  if (headerProductTarget)
@@ -5600,6 +5857,8 @@ export function writeSwiftProject(
5600
5857
  nativeHeaderDeclarations,
5601
5858
  headerProductTarget,
5602
5859
  targetFailures,
5860
+ generatedOwners,
5861
+ targetToolset,
5603
5862
  }
5604
5863
  }
5605
5864
 
@@ -5877,28 +6136,62 @@ function linkedFrameworkTargets(
5877
6136
  )
5878
6137
  const targets = compileTargets(input)
5879
6138
  const planning = targets.length > 0 ? targets : [{ name: 'App', path: '.' }]
5880
- const siblings = swiftTargetDependencies(input.files, planning)
6139
+ const siblings = swiftTargetDependencies(input.files, planning, libraries.keys())
5881
6140
  const reached = new Set<string>()
5882
6141
  const reach = (name: string) => {
5883
- 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
5884
6148
  reached.add(name)
5885
6149
  for (const dependency of OPTIONAL_FRAMEWORK_DEPENDENCIES[name] ?? [])
5886
6150
  reach(dependency)
5887
6151
  }
5888
6152
  for (const name of [...siblings.values()].flat())
5889
- if (OPTIONAL_FRAMEWORKS.has(name) && !planning.some((target) => target.name === name))
6153
+ if (libraries.has(name) && !planning.some((target) => target.name === name))
5890
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
+ }
5891
6184
  if (importsSpriteKit(input.files))
5892
6185
  for (const name of ['SpriteKit', 'PeachBox2D', 'simd', 'GLKit']) reach(name)
5893
6186
  const wanted = [
5894
- 'SwiftUI',
6187
+ 'PeachApp',
5895
6188
  ...(input.oneModule ? ['One'] : []),
5896
6189
  ...(importsSpriteKit(input.files) ? ['SpriteKit'] : []),
5897
6190
  ...reached,
5898
6191
  ]
5899
6192
  const linked = [...new Set(wanted)].filter((name) => libraries.has(name))
5900
- if (!linked.includes('SwiftUI'))
5901
- 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')
5902
6195
  const members: string[] = []
5903
6196
  for (const product of linked) {
5904
6197
  const declared = libraries.get(product) ?? []
@@ -5963,10 +6256,15 @@ ${dependencies}
5963
6256
  // node. the shell command's inputs name the modules and objects it compiles
5964
6257
  // against, which is the dependency closure. automatic products have no
5965
6258
  // Objects.LinkFileList.
5966
- function frameworkLinkClosure(
6259
+ export function frameworkLinkClosure(
5967
6260
  scratch: string,
5968
6261
  roots: readonly string[],
5969
- ): { objects: string[]; modules: Set<string>; moduleMaps: string[] } {
6262
+ ): {
6263
+ objects: string[]
6264
+ owners: Map<string, string>
6265
+ modules: Set<string>
6266
+ moduleMaps: string[]
6267
+ } {
5970
6268
  const suffix = `${WASM_TRIPLE}-release`
5971
6269
  const phonyHeader = new RegExp(`^ "<(.+)-${suffix}\\.module>":\\s*$`)
5972
6270
  const shellHeader = new RegExp(`^ "C\\.(.+)-${suffix}\\.module":\\s*$`)
@@ -6023,6 +6321,7 @@ function frameworkLinkClosure(
6023
6321
  const stack = [...roots]
6024
6322
  const files: string[] = []
6025
6323
  const seen = new Set<string>()
6324
+ const owners = new Map<string, string>()
6026
6325
  const maps = new Set<string>()
6027
6326
  while (stack.length > 0) {
6028
6327
  const name = stack.pop()!
@@ -6033,6 +6332,10 @@ function frameworkLinkClosure(
6033
6332
  if (!own || own.length === 0)
6034
6333
  throw new Error(`swift-compile: ${name} produced no objects`)
6035
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)
6036
6339
  if (seen.has(file)) continue
6037
6340
  seen.add(file)
6038
6341
  if (!existsSync(file))
@@ -6042,7 +6345,7 @@ function frameworkLinkClosure(
6042
6345
  for (const dependency of dependencies.get(name) ?? []) stack.push(dependency)
6043
6346
  }
6044
6347
  files.sort()
6045
- return { objects: files, modules, moduleMaps: [...maps].sort() }
6348
+ return { objects: files, owners, modules, moduleMaps: [...maps].sort() }
6046
6349
  }
6047
6350
 
6048
6351
  // apps with other optional frameworks share this directory, so only an artifact
@@ -6066,6 +6369,7 @@ function removeCaseCollidingModuleArtifacts(
6066
6369
  interface SwiftFrameworkProducts {
6067
6370
  modules: string
6068
6371
  objects: string[]
6372
+ owners: Map<string, string>
6069
6373
  /** the Darwin module's providers, linked as an archive ahead of the sdk's */
6070
6374
  providers: string[]
6071
6375
  link: string[]
@@ -6171,6 +6475,7 @@ async function buildFrameworkProducts(
6171
6475
  })
6172
6476
  }
6173
6477
  objects.push(object)
6478
+ linked.owners.set(object, 'UniformTypeIdentifiers')
6174
6479
  }
6175
6480
  // a previous plan of this scratch may have left a fixture module whose name
6176
6481
  // differs only by case. the app searches this directory, so that file would
@@ -6191,13 +6496,14 @@ async function buildFrameworkProducts(
6191
6496
  // category-only archive members have no symbol reference to pull them in.
6192
6497
  // source consumers need the same direct Foundation input as distributions.
6193
6498
  if (link.includes('-lFoundation'))
6194
- for (const name of foundationCategoryObjects)
6195
- objects.push(
6196
- path.join(
6197
- swiftSdkPaths(args.moduleRoot, args.toolchainBin).resources,
6198
- `wasi/${name}.objc.o`,
6199
- ),
6499
+ for (const name of foundationCategoryObjects) {
6500
+ const object = path.join(
6501
+ swiftSdkPaths(args.moduleRoot, args.toolchainBin).resources,
6502
+ `wasi/${name}.objc.o`,
6200
6503
  )
6504
+ objects.push(object)
6505
+ linked.owners.set(object, 'Foundation')
6506
+ }
6201
6507
  // the providers compile from this revision's source, once per scratch
6202
6508
  const providerDir = path.join(scratch, 'darwin-records')
6203
6509
  if (!existsSync(path.join(providerDir, '.complete'))) {
@@ -6214,13 +6520,16 @@ async function buildFrameworkProducts(
6214
6520
  })
6215
6521
  writeFileSync(path.join(providerDir, '.complete'), '')
6216
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')
6217
6528
  return {
6218
6529
  modules: path.join(release, 'Modules'),
6219
6530
  objects,
6220
- providers: readdirSync(providerDir)
6221
- .filter((file) => file.endsWith('.o'))
6222
- .sort()
6223
- .map((file) => path.join(providerDir, file)),
6531
+ owners: linked.owners,
6532
+ providers,
6224
6533
  link,
6225
6534
  moduleMaps: linked.moduleMaps,
6226
6535
  }
@@ -6442,6 +6751,9 @@ function compileSwiftProjectOnce(
6442
6751
  const root = realpathSync(options.buildRoot)
6443
6752
  const moduleRoot = path.resolve(options.moduleRoot)
6444
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 }
6445
6757
  const layout: SwiftProjectLayout = {
6446
6758
  root,
6447
6759
  sources: path.join(root, 'Sources', 'App'),
@@ -6681,7 +6993,7 @@ function compileSwiftProjectOnce(
6681
6993
  ...swiftObjCSelectorOptions(frameworkRoot),
6682
6994
  '--swift-sdk',
6683
6995
  sdk,
6684
- ...(nativeToolset
6996
+ ...(preparation.targetToolset
6685
6997
  ? ['--toolset', path.join(root, '.peach-target-toolset.json')]
6686
6998
  : []),
6687
6999
  '-c',
@@ -6864,7 +7176,8 @@ function compileSwiftProjectOnce(
6864
7176
  )
6865
7177
  }
6866
7178
  if (options.project) removeProjectLinks(root)
6867
- if (input.optimize)
7179
+ // the guest link prunes and links the response file itself.
7180
+ if (input.optimize && !guestGraph)
6868
7181
  pruneSwiftWasmLink(
6869
7182
  root,
6870
7183
  options.toolchainBin,
@@ -6876,7 +7189,21 @@ function compileSwiftProjectOnce(
6876
7189
  ? projectOutputFile(root, linked, options.project)
6877
7190
  : linked
6878
7191
  const optimized = `${output}.optimized`
6879
- 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)
6880
7207
  const artifact = {
6881
7208
  hash,
6882
7209
  bytes: readFileSync(input.optimize ? optimized : output),