peachsim 0.1.2300 → 0.1.2302

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 (107) hide show
  1. package/cli/commands/control.ts +1 -0
  2. package/cli/commands/inspect.ts +2 -1
  3. package/cli/commands/shell-url.ts +5 -0
  4. package/dist-lib/agent-daemon-client.cjs +1 -1
  5. package/dist-lib/agent-events.cjs +1 -1
  6. package/dist-lib/attached-projects.cjs +1 -1
  7. package/dist-lib/auth/shared-session.cjs +1 -1
  8. package/dist-lib/backend-origin.cjs +1 -1
  9. package/dist-lib/beta.cjs +1 -1
  10. package/dist-lib/beta.mjs +1 -1
  11. package/dist-lib/bridge-constants.cjs +1 -1
  12. package/dist-lib/bridge-contract-input.cjs +1 -1
  13. package/dist-lib/bridge-contract-input.mjs +1 -1
  14. package/dist-lib/bridge-contract.cjs +1 -1
  15. package/dist-lib/bridge-contract.mjs +1 -1
  16. package/dist-lib/bundle-channel.cjs +677 -355
  17. package/dist-lib/capture-contract.cjs +1 -1
  18. package/dist-lib/capture-contract.mjs +1 -1
  19. package/dist-lib/cloud-contract.cjs +1 -1
  20. package/dist-lib/cloud-contract.mjs +1 -1
  21. package/dist-lib/cloud-test-args.cjs +1 -1
  22. package/dist-lib/cloud-test-args.mjs +1 -1
  23. package/dist-lib/cloud.cjs +1 -1
  24. package/dist-lib/cloud.mjs +1 -1
  25. package/dist-lib/config.cjs +1 -1
  26. package/dist-lib/config.mjs +1 -1
  27. package/dist-lib/detox/index.cjs +3 -2
  28. package/dist-lib/dev-bundle-resolution.cjs +1 -1
  29. package/dist-lib/expo-swift-bundle.cjs +628 -306
  30. package/dist-lib/expo-swift-metadata.cjs +1 -1
  31. package/dist-lib/expo-swift-metadata.mjs +1 -1
  32. package/dist-lib/home-paths.cjs +1 -1
  33. package/dist-lib/host/bridge-host.cjs +2889 -354
  34. package/dist-lib/host/fetch-proxy-handler.cjs +6 -6
  35. package/dist-lib/host/fetch-proxy-overrides.cjs +1 -1
  36. package/dist-lib/host/fetch-proxy-overrides.mjs +1 -1
  37. package/dist-lib/host/replacement-module-handler.cjs +1 -1
  38. package/dist-lib/host/websocket-proxy.cjs +1 -1
  39. package/dist-lib/index.cjs +14 -9
  40. package/dist-lib/jump-to-source-babel.cjs +1 -1
  41. package/dist-lib/jump-to-source-native.cjs +1 -1
  42. package/dist-lib/kotlin-host.cjs +1 -1
  43. package/dist-lib/menu.cjs +1 -1
  44. package/dist-lib/menu.mjs +1 -1
  45. package/dist-lib/metro-fingerprint-registry.cjs +1 -1
  46. package/dist-lib/metro-fingerprint-registry.mjs +1 -1
  47. package/dist-lib/metro-production-bundle.cjs +1 -1
  48. package/dist-lib/metro-production-bundle.mjs +1 -1
  49. package/dist-lib/metro.cjs +13 -9
  50. package/dist-lib/native-app-identity-project.cjs +9 -5
  51. package/dist-lib/native-app-identity-project.mjs +9 -5
  52. package/dist-lib/native-app-identity.cjs +1 -1
  53. package/dist-lib/native-app-identity.mjs +1 -1
  54. package/dist-lib/native-firebase-metadata.cjs +1 -1
  55. package/dist-lib/native-firebase-metadata.mjs +1 -1
  56. package/dist-lib/pdfium-raster.cjs +1 -1
  57. package/dist-lib/pdfium-raster.mjs +1 -1
  58. package/dist-lib/plist.cjs +1 -1
  59. package/dist-lib/plist.mjs +1 -1
  60. package/dist-lib/profiles.cjs +1 -1
  61. package/dist-lib/public-brand.cjs +1 -1
  62. package/dist-lib/public-origins-lib-esm.json +24 -24
  63. package/dist-lib/public-origins-lib.json +56 -53
  64. package/dist-lib/react-native-host-modules.cjs +1 -1
  65. package/dist-lib/react-native-host-modules.mjs +1 -1
  66. package/dist-lib/reap-browser.cjs +1 -1
  67. package/dist-lib/scripts/dev-server-scanner.cjs +1 -1
  68. package/dist-lib/sdk.cjs +2 -1
  69. package/dist-lib/sdk.mjs +2 -1
  70. package/dist-lib/skills.cjs +788 -415
  71. package/dist-lib/swift-compile.cjs +15 -7
  72. package/dist-lib/swift-compile.mjs +15 -7
  73. package/dist-lib/swift-package.cjs +1 -1
  74. package/dist-lib/swift-package.mjs +1 -1
  75. package/dist-lib/swift-submit.cjs +1 -1
  76. package/dist-lib/swift-submit.mjs +1 -1
  77. package/dist-lib/swift-toolchain.cjs +1 -1
  78. package/dist-lib/swift.cjs +1 -1
  79. package/dist-lib/vite-swift.cjs +23 -11
  80. package/dist-lib/vite.cjs +6 -6
  81. package/dist-lib/worklet-executable.cjs +1 -1
  82. package/dist-lib/worklet-executable.mjs +1 -1
  83. package/dist-types/packages/peach-engine/src/components/native-ui/webview-frame-bridge.d.ts +1 -0
  84. package/dist-types/packages/peach-engine/src/engine/font-config.d.ts +1 -0
  85. package/dist-types/packages/peach-engine/src/engine/scene-table.d.ts +2 -0
  86. package/dist-types/packages/peach-engine/src/render-worker/activitykit-activityContract.d.ts +17 -0
  87. package/dist-types/packages/peach-engine/src/render-worker/compositor-protocol.d.ts +5 -0
  88. package/dist-types/packages/peach-engine/src/render-worker/native-ui-protocol.d.ts +4 -0
  89. package/dist-types/packages/peach-engine/src/render-worker/native-widgetContract.d.ts +3 -1
  90. package/dist-types/packages/peach-kit/src/capabilities.d.ts +4 -0
  91. package/java-platform/licenses/fdlibm.txt +3 -0
  92. package/kotlin/sdk.tar.gz +0 -0
  93. package/package.json +1 -1
  94. package/runtime-companion.json +1 -1
  95. package/src/expo-discovery-cache.ts +6 -6
  96. package/src/expo-native-workspace.ts +85 -37
  97. package/src/expo-swift-host.ts +19 -4
  98. package/src/host/bridge-host.ts +9 -0
  99. package/src/launchMetadataContract.ts +1 -0
  100. package/src/one-sdk-preparation.ts +61 -5
  101. package/src/swift-guest-compile.ts +19 -3
  102. package/src/swift-guest-source-plan.ts +7 -2
  103. package/src/swiftContract.ts +3 -0
  104. package/src/turbo-compile.ts +60 -4
  105. package/src/turbo-source.ts +239 -35
  106. package/src/widget-extension-bundle.ts +48 -0
  107. package/src/xcode-project.ts +22 -3
@@ -75,13 +75,23 @@ const NATIVE_CONFIG_FILE =
75
75
  // native sources steer pod install by existing, not by content: an edit to one
76
76
  // is copied into the prepared workspace, an added or removed one rebuilds it.
77
77
  const NATIVE_SOURCE_FILE = /\.(swift|mm?|hpp?|c|cc|cpp|kt|java)$/
78
+
79
+ // every load hashes each workspace byte; a file whose inode, size and both
80
+ // timestamps are unchanged keeps the digest of its last read.
81
+ type FileDigest = {
82
+ ino: number
83
+ size: number
84
+ mtimeMs: number
85
+ ctimeMs: number
86
+ digest: string
87
+ }
88
+ const fileDigests = new Map<string, FileDigest>()
78
89
  const NATIVE_PACKAGE_ENTRY =
79
90
  /^(ios|android|.*\.podspec|expo-module\.config\.json|react-native\.config\.[cm]?[jt]s|app\.plugin\.[cm]?js)$/
80
91
 
81
92
  // every file the native prepare can read, plus the toolchain that reads it.
82
93
  // node_modules stays out: the js install reconciles it with the hashed
83
94
  // lockfiles, and the discovery cache keys the live native inventory separately.
84
- // the walk yields so the bridge that runs it keeps answering its other requests.
85
95
  export async function hashExpoWorkspace(app: string, signal?: AbortSignal) {
86
96
  if (process.platform !== 'darwin') {
87
97
  const source = await hashExpoSourceWorkspace(app, signal)
@@ -281,40 +291,78 @@ async function hashWorkspaceInputs(
281
291
  relative === directory ||
282
292
  relative.startsWith(directory + path.sep),
283
293
  )
284
- const walk = async (directory: string) => {
285
- const entries = await fs.promises.readdir(directory, { withFileTypes: true })
286
- for (const entry of entries.sort((a, b) => a.name.localeCompare(b.name))) {
294
+ // the walk lists and stats synchronously: each await of an async walk queues
295
+ // behind the bridge's other native preparation, across tens of thousands of
296
+ // files. only content changed since its last read is read, overlapping.
297
+ const steps: (() => void)[] = []
298
+ const unread: { file: string; content: FileDigest }[] = []
299
+ const walk = (directory: string) => {
300
+ const entries = fs
301
+ .readdirSync(directory, { withFileTypes: true })
302
+ .sort((a, b) => a.name.localeCompare(b.name))
303
+ for (const entry of entries) {
287
304
  signal?.throwIfAborted()
288
305
  const file = path.join(directory, entry.name)
289
306
  const relative = path.relative(root, file)
290
307
  if (excluded(relative, entry.isDirectory())) continue
291
- hash.update(`${relative}\0`)
308
+ steps.push(() => hash.update(`${relative}\0`))
292
309
  if (entry.isSymbolicLink()) {
293
- const link = `link\0${await fs.promises.readlink(file)}\0`
294
- hash.update(link)
295
- if (steersNative(relative)) native.update(`${relative}\0${link}`)
310
+ const link = `link\0${fs.readlinkSync(file)}\0`
311
+ steps.push(() => {
312
+ hash.update(link)
313
+ if (steersNative(relative)) native.update(`${relative}\0${link}`)
314
+ })
296
315
  } else if (entry.isDirectory()) {
297
- hash.update('directory\0')
298
- await walk(file)
316
+ steps.push(() => hash.update('directory\0'))
317
+ walk(file)
299
318
  } else if (entry.isFile()) {
300
319
  const posix = relative.split(path.sep).join('/')
301
320
  if (NATIVE_CONFIG_FILE.test(posix)) {
302
- const bytes = await fs.promises.readFile(file)
303
- if (everyByte) hash.update(`file\0${bytes.length}\0`).update(bytes)
304
- if (steersNative(relative))
305
- native.update(`${posix}\0`).update(nativeConfigBytes(posix, bytes))
306
- } else {
307
- if (everyByte) {
308
- const bytes = await fs.promises.readFile(file)
309
- hash.update(`file\0${bytes.length}\0`).update(bytes)
310
- }
311
- if (NATIVE_SOURCE_FILE.test(posix) && steersNative(relative))
312
- native.update(`${posix}\0`)
321
+ const bytes = fs.readFileSync(file)
322
+ steps.push(() => {
323
+ if (everyByte) hash.update(`file\0${bytes.length}\0`).update(bytes)
324
+ if (steersNative(relative))
325
+ native.update(`${posix}\0`).update(nativeConfigBytes(posix, bytes))
326
+ })
327
+ continue
313
328
  }
329
+ if (everyByte) {
330
+ const stat = fs.statSync(file)
331
+ const known = fileDigests.get(file)
332
+ const content =
333
+ known?.ino === stat.ino &&
334
+ known.size === stat.size &&
335
+ known.mtimeMs === stat.mtimeMs &&
336
+ known.ctimeMs === stat.ctimeMs
337
+ ? known
338
+ : {
339
+ ino: stat.ino,
340
+ size: stat.size,
341
+ mtimeMs: stat.mtimeMs,
342
+ ctimeMs: stat.ctimeMs,
343
+ digest: '',
344
+ }
345
+ if (content !== known) unread.push({ file, content })
346
+ steps.push(() => hash.update(`file\0${content.size}\0${content.digest}`))
347
+ }
348
+ if (NATIVE_SOURCE_FILE.test(posix) && steersNative(relative))
349
+ steps.push(() => native.update(`${posix}\0`))
314
350
  }
315
351
  }
316
352
  }
317
- await walk(root)
353
+ walk(root)
354
+ for (let start = 0; start < unread.length; start += 32) {
355
+ signal?.throwIfAborted()
356
+ await Promise.all(
357
+ unread.slice(start, start + 32).map(async ({ file, content }) => {
358
+ const bytes = await fs.promises.readFile(file)
359
+ content.size = bytes.length
360
+ content.digest = createHash('sha256').update(bytes).digest('hex')
361
+ fileDigests.set(file, content)
362
+ }),
363
+ )
364
+ }
365
+ for (const step of steps) step()
318
366
  if (sourceOnly) {
319
367
  hash.update(`\0${appRelative}\0`)
320
368
  return {
@@ -327,9 +375,14 @@ async function hashWorkspaceInputs(
327
375
  }
328
376
  // cocoapods and xcode exist only on a Mac; elsewhere only the prebuild stage runs
329
377
  const execFileAsync = promisify(execFile)
330
- const mac =
378
+ const pinnedNode =
379
+ typeof manifest.engines?.node === 'string' &&
380
+ /^\d+(\.\d+){0,2}$/.test(manifest.engines.node)
381
+ ? `node@${manifest.engines.node}`
382
+ : null
383
+ const [mac, node] = await Promise.all([
331
384
  process.platform === 'darwin'
332
- ? await Promise.all([
385
+ ? Promise.all([
333
386
  // runner-toolchain-platform: darwin
334
387
  execFileAsync('pod', ['--version'], { env: utf8Env, signal }).catch(
335
388
  (cause: unknown) => {
@@ -341,23 +394,18 @@ async function hashWorkspaceInputs(
341
394
  // runner-toolchain-platform: darwin
342
395
  execFileAsync('xcodebuild', ['-version'], { env: utf8Env, signal }),
343
396
  ]).then(([pod, xcode]) => ({ podVersion: pod.stdout, xcode: xcode.stdout }))
344
- : {}
345
- const pinnedNode =
346
- typeof manifest.engines?.node === 'string' &&
347
- /^\d+(\.\d+){0,2}$/.test(manifest.engines.node)
348
- ? `node@${manifest.engines.node}`
349
- : null
397
+ : {},
398
+ execFileAsync(
399
+ pinnedNode ? 'mise' : 'node',
400
+ pinnedNode ? ['exec', pinnedNode, '--', 'node', '--version'] : ['--version'],
401
+ { cwd: root, signal },
402
+ ),
403
+ ])
350
404
  const toolchain = JSON.stringify({
351
405
  preparation: 7,
352
406
  appRelative,
353
407
  ...mac,
354
- node: (
355
- await execFileAsync(
356
- pinnedNode ? 'mise' : 'node',
357
- pinnedNode ? ['exec', pinnedNode, '--', 'node', '--version'] : ['--version'],
358
- { cwd: root, signal },
359
- )
360
- ).stdout.trim(),
408
+ node: node.stdout.trim(),
361
409
  packageManager: workspacePackageManager(root, manifest.packageManager, excluded),
362
410
  podsEnvironment,
363
411
  })
@@ -16,12 +16,14 @@ import { loadRNXAppConfig } from './app-config'
16
16
  import { isLoopbackHost } from './backend-origin'
17
17
  import { autolinkerAppleFlags } from './expo-autolinking'
18
18
  import {
19
+ expoDiscoveryCacheDir,
19
20
  expoDiscoveryKey,
20
21
  readExpoDiscovery,
21
22
  writeExpoDiscovery,
22
23
  } from './expo-discovery-cache'
23
24
  import { prebuiltExpoNative, prebuiltExpoSwiftResult } from './expo-native-prebuilt'
24
25
  import {
26
+ hashExpoWorkspace,
25
27
  nativeWorkspaceAvailable,
26
28
  prepareExpoNativeWorkspace,
27
29
  } from './expo-native-workspace'
@@ -322,6 +324,8 @@ function installSwiftInputTrace(): void {
322
324
  path.join(swiftCacheDir(), 'swift-sdk-views'),
323
325
  swiftRootLocksDir(),
324
326
  path.join(cacheDir(), 'swift-tmp'),
327
+ // content-addressed records whose reads renew their timestamps for expiry.
328
+ expoDiscoveryCacheDir(),
325
329
  ].filter((prefix, index, all) => all.indexOf(prefix) === index)
326
330
  ignoredRoots = prefixes.flatMap((root) => {
327
331
  try {
@@ -437,7 +441,9 @@ async function witnessMatches(witness: Witness): Promise<boolean> {
437
441
 
438
442
  // the evaluated Expo config is a key input: a child process evaluates it from
439
443
  // app config, plugins and env files the witness cannot see, and its result file
440
- // is new on every run, so it is read untraced and compared here instead.
444
+ // is new on every run, so it is read untraced and compared here instead. a
445
+ // prepared workspace is a key input the same way: a discovery record served
446
+ // for its hash reads none of the inputs that hash covers.
441
447
  async function discoveryKey(
442
448
  root: string,
443
449
  installedWorkspace: string | undefined,
@@ -445,11 +451,14 @@ async function discoveryKey(
445
451
  iosTarget: string | undefined,
446
452
  moduleRoot?: string,
447
453
  ): Promise<string> {
448
- const [config, expoConfig] = await Promise.all([
454
+ const preparesWorkspace =
455
+ prepareNative && !installedWorkspace && nativeWorkspaceAvailable()
456
+ const [config, expoConfig, workspace] = await Promise.all([
449
457
  loadRNXAppConfig(resolveAppProject(root)),
450
458
  readExpoConfigAsync(root),
459
+ preparesWorkspace ? traceStore.exit(() => hashExpoWorkspace(root)) : null,
451
460
  ])
452
- return `${fs.realpathSync(root)}\0${installedWorkspace ?? ''}\0${iosTarget ?? ''}\0${moduleRoot ?? ''}\0${prepareNative ? '1' : '0'}\0${JSON.stringify(config)}\0${JSON.stringify(expoConfig)}`
461
+ return `${fs.realpathSync(root)}\0${installedWorkspace ?? ''}\0${iosTarget ?? ''}\0${moduleRoot ?? ''}\0${prepareNative ? '1' : '0'}\0${JSON.stringify(config)}\0${JSON.stringify(expoConfig)}\0${workspace?.hash ?? ''}`
453
462
  }
454
463
 
455
464
  function cloneNativeTarget(target: SwiftNativeTarget): SwiftNativeTarget {
@@ -2114,7 +2123,13 @@ export function expoEntry(units: ExpoSwiftSourceUnit[], oneSDK = false): string
2114
2123
  Object.keys(unit.files).some((file) => file.startsWith(`Sources/${namespace}/`)),
2115
2124
  ),
2116
2125
  )
2117
- const bridgeModules = units.flatMap((unit) => unit.bridgeModules)
2126
+ const bridgeModules = units.flatMap((unit) =>
2127
+ unit.bridgeModules.map((registration) =>
2128
+ registration === `${unit.namespace}.__peachReactModule_${unit.namespace}()`
2129
+ ? registration.slice(unit.namespace.length + 1)
2130
+ : registration,
2131
+ ),
2132
+ )
2118
2133
  const subscribers = units.flatMap((unit) => unit.appDelegateSubscribers)
2119
2134
  const handlers = units.flatMap((unit) => unit.reactDelegateHandlers)
2120
2135
  const delegates =
@@ -57,6 +57,10 @@ import {
57
57
  import { rnxRuntime } from '../runtime-delivery.ts'
58
58
  import { ensureRuntimePackFor } from '../runtime-packs.ts'
59
59
  import { handleTurboRequest, TURBO_ROUTE } from '../turbo-bundle.ts'
60
+ import {
61
+ handleWidgetExtensionRequest,
62
+ WIDGET_EXTENSION_ROUTE,
63
+ } from '../widget-extension-bundle'
60
64
  import { AgentHost, type AgentHostOptions } from './agent-host.ts'
61
65
  import { serveAppPackageResource } from './app-package-handler'
62
66
  import {
@@ -1566,6 +1570,7 @@ export class SootSimBridgeHost {
1566
1570
  const route = req.url?.split('?')[0] ?? ''
1567
1571
  if (
1568
1572
  route === EXPO_WIDGETS_ROUTE ||
1573
+ route === WIDGET_EXTENSION_ROUTE ||
1569
1574
  route === NITRO_ROUTE ||
1570
1575
  route === ONE_SDK_ROUTE ||
1571
1576
  route === TURBO_ROUTE ||
@@ -1584,6 +1589,10 @@ export class SootSimBridgeHost {
1584
1589
  void handleExpoWidgetsRequest(req, res)
1585
1590
  return
1586
1591
  }
1592
+ if (route === WIDGET_EXTENSION_ROUTE) {
1593
+ void handleWidgetExtensionRequest(req, res)
1594
+ return
1595
+ }
1587
1596
  if (route === ONE_SDK_ROUTE) {
1588
1597
  void handleOneSDKRequest(req, res)
1589
1598
  return
@@ -14,6 +14,7 @@ export const LAUNCH_METADATA_KEYS: readonly string[] = [
14
14
  'expoKotlin',
15
15
  'nitro',
16
16
  'turbo',
17
+ 'widgetExtension',
17
18
  'appManifest',
18
19
  'packageVersions',
19
20
  'dotEnv',
@@ -1,6 +1,8 @@
1
+ import { spawn } from 'node:child_process'
1
2
  import { createHash } from 'node:crypto'
2
3
  import fs from 'node:fs'
3
4
  import { createRequire } from 'node:module'
5
+ import os from 'node:os'
4
6
  import path from 'node:path'
5
7
  import { pathToFileURL } from 'node:url'
6
8
  import { fetchNativeEntry, nativeEntryKey } from './native-prebuilt'
@@ -12,10 +14,61 @@ import {
12
14
 
13
15
  interface SDKGenerator {
14
16
  importedFrameworks(root: string): string[]
15
- generateAppSdk(frameworks: string[]): Promise<{
16
- files: Map<string, string>
17
- generation: string
18
- }>
17
+ }
18
+
19
+ // the generator reads symbol graphs and runs compiler passes in this thread for
20
+ // minutes on a cold cache, and the dev bridge that serves every peach command
21
+ // calls it, so it runs in its own process.
22
+ const GENERATE_SCRIPT = `
23
+ import { writeFileSync } from 'node:fs'
24
+ import { pathToFileURL } from 'node:url'
25
+ const [generatorFile, resultFile, frameworks] = process.argv.slice(1)
26
+ const generator = await import(pathToFileURL(generatorFile).href)
27
+ const { files, generation } = await generator.generateAppSdk(JSON.parse(frameworks))
28
+ writeFileSync(resultFile, JSON.stringify({ generation, files: [...files] }))
29
+ `
30
+
31
+ async function generateAppSdkInChild(
32
+ generatorFile: string,
33
+ frameworks: string[],
34
+ ): Promise<{ generation: string; files: Map<string, string> }> {
35
+ const directory = fs.mkdtempSync(path.join(os.tmpdir(), 'peach-one-sdk-'))
36
+ const resultFile = path.join(directory, 'result.json')
37
+ try {
38
+ const child = spawn(
39
+ 'node',
40
+ [
41
+ '--input-type=module',
42
+ '-e',
43
+ GENERATE_SCRIPT,
44
+ generatorFile,
45
+ resultFile,
46
+ JSON.stringify(frameworks),
47
+ ],
48
+ { stdio: ['ignore', 'ignore', 'pipe'] },
49
+ )
50
+ let stderr = ''
51
+ child.stderr.setEncoding('utf8')
52
+ child.stderr.on('data', (chunk: string) => {
53
+ stderr += chunk
54
+ })
55
+ const [status, signal] = await new Promise<[number | null, NodeJS.Signals | null]>(
56
+ (resolve, reject) => {
57
+ child.once('error', reject)
58
+ child.once('close', (code, closeSignal) => resolve([code, closeSignal]))
59
+ },
60
+ )
61
+ if (status !== 0)
62
+ throw new Error(
63
+ `One SDK source generation failed (${signal ?? `exit ${status}`})${stderr ? `: ${stderr.trim().slice(-2000)}` : ''}`,
64
+ )
65
+ const result: { generation: string; files: [string, string][] } = JSON.parse(
66
+ fs.readFileSync(resultFile, 'utf8'),
67
+ )
68
+ return { generation: result.generation, files: new Map(result.files) }
69
+ } finally {
70
+ fs.rmSync(directory, { recursive: true, force: true })
71
+ }
19
72
  }
20
73
 
21
74
  export async function selectOneSDK(appRoot: string) {
@@ -88,7 +141,10 @@ export async function prepareOneSDKSources(appRoot: string, output?: string) {
88
141
  fs.copyFileSync(path.join(published, name), path.join(directory, name))
89
142
  return
90
143
  }
91
- const generated = await selected.generator.generateAppSdk(selected.frameworks)
144
+ const generated = await generateAppSdkInChild(
145
+ path.join(selected.one, 'dist/sdk/app.mjs'),
146
+ selected.frameworks,
147
+ )
92
148
  if (generated.generation !== generation)
93
149
  throw new Error('One SDK source generation differs from the installed facades')
94
150
  fs.rmSync(directory, { recursive: true, force: true })
@@ -74,6 +74,12 @@ export async function compileGuestLink(options: {
74
74
  target.productName.endsWith('.framework') ? [target.productName.slice(0, -10)] : [],
75
75
  ),
76
76
  )
77
+ const sourceLibraries = new Set(
78
+ options.graph.targets.flatMap((target) => {
79
+ const library = /^lib(.+)\.(?:a|dylib)$/.exec(target.productName)
80
+ return library ? [library[1]!] : []
81
+ }),
82
+ )
77
83
  const entry = targets.get(options.graph.entry)
78
84
  if (!entry) throw new Error('guest source graph has no entry')
79
85
  const imageBuildVersion = (value: typeof entry.buildVersion) => {
@@ -269,14 +275,24 @@ export async function compileGuestLink(options: {
269
275
  objects: selectedSource
270
276
  .filter((artifact) => artifact.image === image.id)
271
277
  .map((artifact) => artifact.path),
272
- // a `-framework Name` for a framework the source graph builds links
273
- // that framework's own image, which the plan already depends on
278
+ // a `-framework Name` or `-lname` for a product the source graph
279
+ // builds links that product's own target, which the plan already holds
274
280
  linkerFlags: image.members
275
281
  .flatMap((id) => targets.get(id)!.linkerFlags)
276
282
  .filter(
277
283
  (flag, index, flags) =>
278
284
  !sourceFrameworks.has(flags[index - 1] === '-framework' ? flag : '') &&
279
- !(flag === '-framework' && sourceFrameworks.has(flags[index + 1] ?? '')),
285
+ !(
286
+ flag === '-framework' && sourceFrameworks.has(flags[index + 1] ?? '')
287
+ ) &&
288
+ !sourceLibraries.has(
289
+ flag.startsWith('-l') && flag.length > 2
290
+ ? flag.slice(2)
291
+ : flags[index - 1] === '-l'
292
+ ? flag
293
+ : '',
294
+ ) &&
295
+ !(flag === '-l' && sourceLibraries.has(flags[index + 1] ?? '')),
280
296
  ),
281
297
  clangLinkOptions: selectedSource
282
298
  .filter((artifact) => artifact.image === image.id)
@@ -38,8 +38,13 @@ function swiftPackageLinkage(
38
38
  export function guestSourceImages(graph: SwiftSourceLinkGraph): GuestSourceImage[] {
39
39
  const targets = new Map(graph.targets.map((target) => [target.id, target]))
40
40
  const entry = targets.get(graph.entry)
41
- if (!entry || entry.productType !== 'com.apple.product-type.application')
42
- throw new Error('source graph has no application entry')
41
+ // an app extension runs as its own executable, as the application does
42
+ if (
43
+ !entry ||
44
+ (entry.productType !== 'com.apple.product-type.application' &&
45
+ entry.productType !== 'com.apple.product-type.app-extension')
46
+ )
47
+ throw new Error('source graph has no application or app extension entry')
43
48
  const images: { id: number; owner: string; members: string[] }[] = [
44
49
  { id: 0, owner: entry.id, members: [] },
45
50
  ]
@@ -568,6 +568,9 @@ export interface SwiftEntryOptions extends SwiftModuleOptions {
568
568
  contractHash?: string
569
569
  // the package/source path keeps a root's identity across module reloads.
570
570
  rootId?: string
571
+ // the JSI globals the process's native runtime defines for its own evaluation
572
+ // only: Nitro's by default, React Native's TurboModule binding for a turbo app.
573
+ privateGlobals?: readonly string[]
571
574
  }
572
575
 
573
576
  export interface SwiftRuntimeHost {
@@ -103,10 +103,15 @@ export function collectTurboCompileInput(
103
103
  dependencyTargets = dependencyTargets.filter(
104
104
  (_, index) => !providerNames.has(parsedTargets[index]!.name),
105
105
  )
106
- const swift = Object.keys(files).some((file) => file.endsWith('.swift'))
106
+ // an app that links UIKit, through Swift sources or the Objective-C host, is a
107
+ // package: its key window shows what its modules present
108
+ const swift =
109
+ collection.coreMode === 'turbo' ||
110
+ Object.keys(files).some((file) => file.endsWith('.swift'))
107
111
  const entry = `Sources/PeachTurboApp/main.${swift ? 'swift' : 'cpp'}`
108
112
  const targetNames = targets.map(({ name }) => name)
109
113
  const loadTargetNames = new Set(collection.loads.map(({ target }) => target))
114
+ // the core, each +load and each Swift target; a Cxx umbrella stays unimported
110
115
  const swiftImportedTargetNames = targets
111
116
  .filter(
112
117
  (target) =>
@@ -117,10 +122,61 @@ export function collectTurboCompileInput(
117
122
  ),
118
123
  )
119
124
  .map(({ name }) => name)
125
+ const initialize = [
126
+ '_PeachReactNativeWindow.launch()',
127
+ ...collection.loads.map(({ symbol }) => `${symbol}()`),
128
+ ...(runtime ? ['peachTurboInitialize()'] : []),
129
+ ]
130
+ const fabric = collection.fabricComponents.length > 0
131
+ // the app as a package: its mounted roots are the key window, where what a
132
+ // module presents shows over the app, or one of its Fabric component views
120
133
  files[entry] = swift
121
- ? '@_spi(Peach) import PeachFoundation\n' +
122
- swiftImportedTargetNames.map((target) => `import ${target}\n`).join('') +
123
- `PeachHostDriver.installExecutor()\n${collection.loads.map(({ symbol }) => `${symbol}()\n`).join('')}${runtime ? 'peachTurboInitialize()\n' : ''}`
134
+ ? [
135
+ 'import SwiftUI',
136
+ 'import UIKit',
137
+ 'import PeachJSON',
138
+ ...swiftImportedTargetNames.map((target) => `import ${target}`),
139
+ '',
140
+ '@main struct PeachTurboApp: PeachPackage {',
141
+ ` init() { ${initialize.join('; ')} }`,
142
+ ...(fabric
143
+ ? [
144
+ ' func view(props: JSON) -> PeachTurboRoot { PeachTurboRoot(props: props) }',
145
+ '}',
146
+ '',
147
+ 'struct PeachTurboRoot: View {',
148
+ ' let fabric: Int32?',
149
+ '',
150
+ ' init(props: JSON) {',
151
+ ' guard case .object(let fields) = props, let field = fields.first(where: { $0.0 == "fabric" }), case .number(let tag) = field.1 else {',
152
+ ' fabric = nil',
153
+ ' return',
154
+ ' }',
155
+ ' fabric = Int32(tag)',
156
+ ' }',
157
+ '',
158
+ ' var body: some View {',
159
+ ' if let fabric { PeachFabricComponent(tag: fabric) } else { _PeachReactNativeWindow() }',
160
+ ' }',
161
+ '}',
162
+ '',
163
+ 'struct PeachFabricComponent: UIViewRepresentable {',
164
+ ' let tag: Int32',
165
+ '',
166
+ ' func makeUIView(context: Context) -> UIView {',
167
+ ' guard let view = peach_fabric_view_content(tag) else { fatalError("Fabric view \\(tag) is not mounted") }',
168
+ ' return Unmanaged<UIView>.fromOpaque(view).takeRetainedValue()',
169
+ ' }',
170
+ '',
171
+ ' func updateUIView(_ view: UIView, context: Context) {}',
172
+ '}',
173
+ ]
174
+ : [
175
+ ' func view(props: JSON) -> _PeachReactNativeWindow { _PeachReactNativeWindow() }',
176
+ '}',
177
+ ]),
178
+ '',
179
+ ].join('\n')
124
180
  : [
125
181
  'extern "C" void peachTurboInitialize();',
126
182
  ...collection.loads.map(({ symbol }) => `extern "C" void ${symbol}();`),