peachsim 0.1.2255 → 0.1.2258

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 (122) hide show
  1. package/cli/bridge-flow-runner.ts +41 -0
  2. package/cli/commands/control.ts +8 -2
  3. package/cli/commands/flow.ts +9 -0
  4. package/cli/commands/swift.ts +5 -0
  5. package/cli/current-sim.ts +23 -15
  6. package/cli/outbound-endpoints.ts +0 -2
  7. package/cli/secure-file.ts +8 -2
  8. package/dist-lib/agent-daemon-client.cjs +1 -1
  9. package/dist-lib/agent-events.cjs +1 -1
  10. package/dist-lib/attached-projects.cjs +1 -1
  11. package/dist-lib/auth/shared-session.cjs +1 -1
  12. package/dist-lib/backend-origin.cjs +1 -1
  13. package/dist-lib/beta.cjs +1 -1
  14. package/dist-lib/beta.mjs +1 -1
  15. package/dist-lib/bridge-constants.cjs +1 -1
  16. package/dist-lib/bridge-contract-input.cjs +1 -1
  17. package/dist-lib/bridge-contract-input.mjs +1 -1
  18. package/dist-lib/bridge-contract.cjs +1 -1
  19. package/dist-lib/bridge-contract.mjs +1 -1
  20. package/dist-lib/bundle-channel.cjs +418 -143
  21. package/dist-lib/capture-contract.cjs +1 -1
  22. package/dist-lib/capture-contract.mjs +1 -1
  23. package/dist-lib/cloud-contract.cjs +1 -1
  24. package/dist-lib/cloud-contract.mjs +1 -1
  25. package/dist-lib/cloud-test-args.cjs +1 -1
  26. package/dist-lib/cloud-test-args.mjs +1 -1
  27. package/dist-lib/cloud.cjs +1 -1
  28. package/dist-lib/cloud.mjs +1 -1
  29. package/dist-lib/config.cjs +1 -1
  30. package/dist-lib/config.mjs +1 -1
  31. package/dist-lib/detox/index.cjs +16 -12
  32. package/dist-lib/dev-bundle-resolution.cjs +1 -1
  33. package/dist-lib/expo-swift-bundle.cjs +359 -116
  34. package/dist-lib/expo-swift-metadata.cjs +1 -1
  35. package/dist-lib/expo-swift-metadata.mjs +1 -1
  36. package/dist-lib/home-paths.cjs +1 -1
  37. package/dist-lib/host/bridge-host.cjs +939 -595
  38. package/dist-lib/host/fetch-proxy-handler.cjs +3607 -1627
  39. package/dist-lib/host/fetch-proxy-overrides.cjs +1 -1
  40. package/dist-lib/host/fetch-proxy-overrides.mjs +1 -1
  41. package/dist-lib/host/replacement-module-handler.cjs +1 -1
  42. package/dist-lib/host/websocket-proxy.cjs +1 -1
  43. package/dist-lib/index.cjs +12611 -11232
  44. package/dist-lib/jump-to-source-babel.cjs +1 -1
  45. package/dist-lib/jump-to-source-native.cjs +1 -1
  46. package/dist-lib/kotlin-host.cjs +5 -4
  47. package/dist-lib/menu.cjs +1 -1
  48. package/dist-lib/menu.mjs +1 -1
  49. package/dist-lib/metro-fingerprint-registry.cjs +1 -1
  50. package/dist-lib/metro-fingerprint-registry.mjs +1 -1
  51. package/dist-lib/metro-production-bundle.cjs +1 -1
  52. package/dist-lib/metro-production-bundle.mjs +1 -1
  53. package/dist-lib/metro.cjs +9700 -8326
  54. package/dist-lib/native-app-identity-project.cjs +2 -2
  55. package/dist-lib/native-app-identity-project.mjs +2 -2
  56. package/dist-lib/native-app-identity.cjs +1 -1
  57. package/dist-lib/native-app-identity.mjs +1 -1
  58. package/dist-lib/native-firebase-metadata.cjs +1 -1
  59. package/dist-lib/native-firebase-metadata.mjs +1 -1
  60. package/dist-lib/pdfium-raster.cjs +1 -1
  61. package/dist-lib/pdfium-raster.mjs +1 -1
  62. package/dist-lib/plist.cjs +1 -1
  63. package/dist-lib/plist.mjs +1 -1
  64. package/dist-lib/profiles.cjs +1 -1
  65. package/dist-lib/public-brand.cjs +1 -1
  66. package/dist-lib/public-origins-lib-esm.json +24 -24
  67. package/dist-lib/public-origins-lib.json +606 -228
  68. package/dist-lib/react-native-host-modules.cjs +1 -1
  69. package/dist-lib/react-native-host-modules.mjs +1 -1
  70. package/dist-lib/reap-browser.cjs +1 -1
  71. package/dist-lib/scripts/dev-server-scanner.cjs +1 -1
  72. package/dist-lib/sdk.cjs +1 -1
  73. package/dist-lib/sdk.mjs +1 -1
  74. package/dist-lib/skills.cjs +1192 -797
  75. package/dist-lib/swift-compile.cjs +334 -99
  76. package/dist-lib/swift-compile.mjs +334 -99
  77. package/dist-lib/swift-package.cjs +1 -1
  78. package/dist-lib/swift-package.mjs +1 -1
  79. package/dist-lib/swift-submit.cjs +1 -1
  80. package/dist-lib/swift-submit.mjs +1 -1
  81. package/dist-lib/swift-toolchain.cjs +1 -1
  82. package/dist-lib/swift.cjs +1 -1
  83. package/dist-lib/vite-swift.cjs +340 -101
  84. package/dist-lib/vite.cjs +4729 -2900
  85. package/dist-lib/worklet-executable.cjs +1 -1
  86. package/dist-lib/worklet-executable.mjs +1 -1
  87. package/dist-types/packages/peach-engine/src/engine/node.d.ts +0 -6
  88. package/dist-types/packages/peach-engine/src/render-worker/reanimated-readiness.d.ts +1 -0
  89. package/dist-types/packages/peach-globals/src/appLifecycleBridgeContract.d.ts +1 -0
  90. package/dist-types/packages/peach-globals/src/index.d.ts +1 -0
  91. package/dist-types/packages/peach-globals/src/lockstepCaptureBridgeContract.d.ts +1 -0
  92. package/dist-types/packages/peach-kit/src/transitions/screen-transition-math.d.ts +6 -0
  93. package/java-platform/licenses/android.txt +183 -0
  94. package/java-platform/licenses/arm-optimized-routines.txt +256 -0
  95. package/java-platform/licenses/fdlibm.txt +72 -0
  96. package/java-platform/licenses/icu.txt +50 -0
  97. package/java-platform/licenses/openjdk.txt +395 -0
  98. package/java-platform/licenses/teavm.txt +182 -0
  99. package/java-platform/licenses/threeten-backport.txt +29 -0
  100. package/kotlin/README.md +1 -1
  101. package/kotlin/sdk.tar.gz +0 -0
  102. package/package.json +2 -1
  103. package/runtime-companion.json +1 -1
  104. package/src/expo-autolinking.ts +47 -4
  105. package/src/expo-native-workspace.ts +4 -1
  106. package/src/expo-pod-prebuilt.ts +96 -9
  107. package/src/expo-swift-host.ts +29 -9
  108. package/src/kotlin-host.ts +3 -2
  109. package/src/kotlinSdkContract.ts +1 -0
  110. package/src/native-package-slice-build.ts +386 -0
  111. package/src/native-package-slice.ts +835 -0
  112. package/src/native-prebuilt.ts +4 -0
  113. package/src/native-seam-manifest.ts +0 -8
  114. package/src/nitro-adapter.lock.json +255 -255
  115. package/src/nitro-compile.ts +37 -13
  116. package/src/nitro-superset.lock.json +4 -4
  117. package/src/swift-distribution.lock.json +11 -11
  118. package/src/swift-distribution.ts +7 -2
  119. package/src/swift-link-roots.ts +23 -22
  120. package/src/swift-wasm-prune.ts +436 -105
  121. package/src/turbo-compile.ts +22 -7
  122. package/src/turbo-runtime.lock.json +23 -23
@@ -0,0 +1,835 @@
1
+ // shared-core native package slices (native/pkg/<name>/<key>/) and single-executable
2
+ // Expo app bundles (native/app-bundle/expo/<key>/): each package compiles once to
3
+ // stripped static objects + swiftmodule on a Mac, and consumers link all installed
4
+ // slices together against one shared Swift/Foundation/ExpoModulesCore runtime.
5
+ import { execFileSync } from 'node:child_process'
6
+ import fs from 'node:fs'
7
+ import os from 'node:os'
8
+ import path from 'node:path'
9
+ import * as v from 'valibot'
10
+ import {
11
+ collectExpoSwiftSources,
12
+ EXPO_SWIFT_ENTRY,
13
+ expoEntry,
14
+ expoManifest,
15
+ targetSettings,
16
+ } from './expo-swift-host'
17
+ import {
18
+ isExpoSwiftCompilationResult,
19
+ type ExpoSwiftCompilationResult,
20
+ type ExpoSwiftSourceUnit,
21
+ } from './expoSwiftContract'
22
+ import {
23
+ describeNativeEntry,
24
+ fetchNativeEntry,
25
+ installNativeEntry,
26
+ NATIVE_PREBUILT_ORIGIN,
27
+ nativeEntryCache,
28
+ nativeEntryKey,
29
+ nativeEntryPrefix,
30
+ nativePackageEntryName,
31
+ type NativeEntryDescriptor,
32
+ } from './native-prebuilt'
33
+ import {
34
+ compileSwiftProjectUnit,
35
+ type SwiftCompileArtifact,
36
+ type SwiftCompileInput,
37
+ WASM_TRIPLE,
38
+ } from './swift-compile'
39
+ import { swiftModuleToolchain } from './swift-distribution'
40
+ import { swiftIcuAddress, swiftIcuPacked } from './swift-icu'
41
+ import { swiftNativePin } from './swift-native-pin'
42
+ import { swiftManifestTargets } from './swift-package'
43
+ import { parseSwiftNativePin } from './swiftNativePinContract'
44
+ import type { ExpoPodPackage } from './expo-pod-prebuilt'
45
+ import type { SwiftArtifact } from './swift-host'
46
+ import type { SwiftNativeTarget, SwiftResourceBundle } from './swiftContract'
47
+
48
+ export type NativePackageSliceKind = 'expo-swift' | 'turbomodule' | 'nitro'
49
+
50
+ export interface NativePackageSliceTarget {
51
+ name: string
52
+ archiveFile: string
53
+ archiveBytes: number
54
+ swiftmoduleFile?: string
55
+ swiftmoduleBytes?: number
56
+ objcHeaderFile?: string
57
+ }
58
+
59
+ export interface ExpoSliceMetadata {
60
+ namespace: string
61
+ moduleId: string
62
+ moduleIds?: string[]
63
+ classes: string[]
64
+ appDelegateSubscribers: string[]
65
+ reactDelegateHandlers: string[]
66
+ bridgeModules: string[]
67
+ hasViews: boolean
68
+ resources?: Record<string, string>
69
+ resourceBundles?: SwiftResourceBundle[]
70
+ swiftLanguageMode?: number
71
+ }
72
+
73
+ export interface TurboSliceMetadata {
74
+ coreMode: string
75
+ targetNames: string[]
76
+ headerFiles: Record<string, string>
77
+ }
78
+
79
+ export interface NitroSliceMetadata {
80
+ targetNames: string[]
81
+ hybridObjects: string[]
82
+ registrations: { symbol: string; header: string; target: string }[]
83
+ }
84
+
85
+ export interface NativePackageSliceManifest {
86
+ schema: 1
87
+ kind: NativePackageSliceKind
88
+ packageName: string
89
+ packageVersion: string
90
+ key: string
91
+ runtimePin: ReturnType<typeof swiftNativePin>
92
+ targets: NativePackageSliceTarget[]
93
+ expo?: ExpoSliceMetadata
94
+ turbo?: TurboSliceMetadata
95
+ nitro?: NitroSliceMetadata
96
+ }
97
+
98
+ export interface LoadedNativePackageSlice {
99
+ dir: string
100
+ manifest: NativePackageSliceManifest
101
+ descriptor: NativeEntryDescriptor
102
+ }
103
+
104
+ export interface ComposedExpoBundle {
105
+ bundleKey: string
106
+ dir: string
107
+ metadata: ExpoSwiftCompilationResult
108
+ wasmPath: string
109
+ icuPath: string
110
+ descriptor: NativeEntryDescriptor
111
+ inputs: Record<string, string>
112
+ }
113
+
114
+ const sliceTargetSchema = v.object({
115
+ name: v.string(),
116
+ archiveFile: v.string(),
117
+ archiveBytes: v.number(),
118
+ swiftmoduleFile: v.exactOptional(v.string()),
119
+ swiftmoduleBytes: v.exactOptional(v.number()),
120
+ objcHeaderFile: v.exactOptional(v.string()),
121
+ })
122
+
123
+ const resourceBundleSchema = v.object({
124
+ target: v.string(),
125
+ sourcePath: v.string(),
126
+ path: v.string(),
127
+ })
128
+
129
+ const sliceManifestSchema = v.object({
130
+ schema: v.literal(1),
131
+ kind: v.picklist(['expo-swift', 'turbomodule', 'nitro']),
132
+ packageName: v.string(),
133
+ packageVersion: v.string(),
134
+ key: v.string(),
135
+ runtimePin: v.pipe(v.unknown(), v.transform(parseSwiftNativePin)),
136
+ targets: v.array(sliceTargetSchema),
137
+ expo: v.exactOptional(
138
+ v.object({
139
+ namespace: v.string(),
140
+ moduleId: v.string(),
141
+ moduleIds: v.exactOptional(v.array(v.string())),
142
+ classes: v.array(v.string()),
143
+ appDelegateSubscribers: v.array(v.string()),
144
+ reactDelegateHandlers: v.array(v.string()),
145
+ bridgeModules: v.array(v.string()),
146
+ hasViews: v.boolean(),
147
+ resources: v.exactOptional(v.record(v.string(), v.string())),
148
+ resourceBundles: v.exactOptional(v.array(resourceBundleSchema)),
149
+ swiftLanguageMode: v.exactOptional(v.number()),
150
+ }),
151
+ ),
152
+ turbo: v.exactOptional(
153
+ v.object({
154
+ coreMode: v.string(),
155
+ targetNames: v.array(v.string()),
156
+ headerFiles: v.record(v.string(), v.string()),
157
+ }),
158
+ ),
159
+ nitro: v.exactOptional(
160
+ v.object({
161
+ targetNames: v.array(v.string()),
162
+ hybridObjects: v.array(v.string()),
163
+ registrations: v.array(
164
+ v.object({
165
+ symbol: v.string(),
166
+ header: v.string(),
167
+ target: v.string(),
168
+ }),
169
+ ),
170
+ }),
171
+ ),
172
+ })
173
+
174
+ export const nativePackageSliceEntryUrl = (name: string, key: string, file: string) =>
175
+ `${NATIVE_PREBUILT_ORIGIN}/${nativeEntryPrefix('pkg', nativePackageEntryName(name), key)}/${file}`
176
+
177
+ export const expoAppBundleEntryUrl = (key: string, file: string) =>
178
+ `${NATIVE_PREBUILT_ORIGIN}/${nativeEntryPrefix('app-bundle', 'expo', key)}/${file}`
179
+
180
+ /** cache inputs identifying a single Expo Swift package slice. */
181
+ export function expoPackageSliceInputs(
182
+ pod: ExpoPodPackage,
183
+ podInputs: Record<string, string>,
184
+ ): Record<string, string> {
185
+ return {
186
+ ...podInputs,
187
+ 'slice-kind': 'expo-swift',
188
+ 'swift-module': pod.swiftModule,
189
+ }
190
+ }
191
+
192
+ /** deterministic inputs identifying a composed multi-package Expo bundle. */
193
+ export function expoPodsBundleInputs(
194
+ podKeys: readonly { name: string; version: string; key: string }[],
195
+ oneSDK = false,
196
+ ): Record<string, string> {
197
+ const sorted = [...podKeys].sort((a, b) =>
198
+ a.name < b.name ? -1 : a.name > b.name ? 1 : 0,
199
+ )
200
+ return {
201
+ schema: '1',
202
+ 'swift-pin': JSON.stringify(swiftNativePin()),
203
+ 'one-sdk': String(oneSDK),
204
+ pods: JSON.stringify(
205
+ sorted.map((entry) => ({
206
+ name: entry.name,
207
+ version: entry.version,
208
+ key: entry.key,
209
+ })),
210
+ ),
211
+ }
212
+ }
213
+
214
+ /** add an iOS 17 deployment floor when the emitted Package.swift omits platforms. */
215
+ function withIosPlatformFloor(packageSwift: string): string {
216
+ if (/\bplatforms\s*:/.test(packageSwift)) return packageSwift
217
+ return packageSwift.replace(
218
+ 'Package(name: "PeachExpo", ',
219
+ 'Package(name: "PeachExpo", platforms: [.iOS("17.0")], ',
220
+ )
221
+ }
222
+
223
+ /**
224
+ * extracts debug-stripped static archives and binary swiftmodules from a compiled
225
+ * SwiftPM build directory into flat files suitable for a `native/pkg` entry.
226
+ */
227
+ export function packCompiledTargetsToSliceDir(opts: {
228
+ buildRoot: string
229
+ packageSwift: string
230
+ toolchainBin: string
231
+ stagingDir: string
232
+ excludeExecutable?: boolean
233
+ onlyTargets?: ReadonlySet<string>
234
+ }): { targets: NativePackageSliceTarget[]; files: string[] } {
235
+ const products = path.join(opts.buildRoot, '.build', WASM_TRIPLE, 'release')
236
+ const manifestTargets = swiftManifestTargets(opts.packageSwift).filter(
237
+ (target) =>
238
+ (opts.excludeExecutable === false || !target.executable) &&
239
+ (!opts.onlyTargets || opts.onlyTargets.has(target.name)),
240
+ )
241
+ const emittedFile = path.join(opts.buildRoot, 'Package.swift')
242
+ const emittedTargets = fs.existsSync(emittedFile)
243
+ ? swiftManifestTargets(fs.readFileSync(emittedFile, 'utf8')).filter(
244
+ (product) => opts.excludeExecutable === false || !product.executable,
245
+ )
246
+ : null
247
+ const membersRoot = path.join(opts.stagingDir, '.members')
248
+ fs.mkdirSync(membersRoot, { recursive: true })
249
+ const targets: NativePackageSliceTarget[] = []
250
+ const files: string[] = []
251
+ try {
252
+ for (const target of manifestTargets) {
253
+ const productNames = emittedTargets
254
+ ? [
255
+ ...new Set(
256
+ emittedTargets
257
+ .filter(
258
+ (product) =>
259
+ product.name === target.name || product.path === target.path,
260
+ )
261
+ .map((product) => product.name),
262
+ ),
263
+ ]
264
+ : [target.name]
265
+ if (productNames.length === 0) productNames.push(target.name)
266
+ const objectEntries: { productName: string; file: string }[] = []
267
+ for (const productName of productNames) {
268
+ const targetBuild = path.join(products, `${productName}.build`)
269
+ if (!fs.existsSync(targetBuild)) continue
270
+ for (const file of fs
271
+ .readdirSync(targetBuild, { recursive: true, encoding: 'utf8' })
272
+ .filter((entry) => entry.endsWith('.o'))
273
+ .sort()) {
274
+ objectEntries.push({ productName, file: path.join(targetBuild, file) })
275
+ }
276
+ }
277
+ if (objectEntries.length === 0) continue
278
+ const targetMembers = path.join(membersRoot, target.name)
279
+ fs.mkdirSync(targetMembers, { recursive: true })
280
+ const stripped = objectEntries.map(({ productName, file }, index) => {
281
+ const out = path.join(
282
+ targetMembers,
283
+ `${index}-${productName}-${path.basename(file)}`,
284
+ )
285
+ execFileSync(path.join(opts.toolchainBin, 'llvm-objcopy'), [
286
+ '--strip-debug',
287
+ file,
288
+ out,
289
+ ])
290
+ return out
291
+ })
292
+ const archiveFile = `lib${target.name}.a`
293
+ const archivePath = path.join(opts.stagingDir, archiveFile)
294
+ fs.rmSync(archivePath, { force: true })
295
+ execFileSync(path.join(opts.toolchainBin, 'llvm-ar'), [
296
+ 'rcsD',
297
+ archivePath,
298
+ ...stripped,
299
+ ])
300
+ files.push(archivePath)
301
+ const archiveBytes = fs.statSync(archivePath).size
302
+
303
+ let swiftmoduleFile: string | undefined
304
+ let swiftmoduleBytes: number | undefined
305
+ const builtModule = path.join(products, 'Modules', `${target.name}.swiftmodule`)
306
+ if (fs.existsSync(builtModule)) {
307
+ swiftmoduleFile = `${target.name}.swiftmodule`
308
+ const destModule = path.join(opts.stagingDir, swiftmoduleFile)
309
+ fs.copyFileSync(builtModule, destModule)
310
+ files.push(destModule)
311
+ swiftmoduleBytes = fs.statSync(destModule).size
312
+ }
313
+
314
+ let objcHeaderFile: string | undefined
315
+ const builtHeader = path.join(
316
+ opts.buildRoot,
317
+ '.build',
318
+ 'peach-cxx-headers',
319
+ `${target.name}-Swift.h`,
320
+ )
321
+ if (fs.existsSync(builtHeader)) {
322
+ objcHeaderFile = `${target.name}-Swift.h`
323
+ const destHeader = path.join(opts.stagingDir, objcHeaderFile)
324
+ fs.copyFileSync(builtHeader, destHeader)
325
+ files.push(destHeader)
326
+ }
327
+
328
+ targets.push({
329
+ name: target.name,
330
+ archiveFile,
331
+ archiveBytes,
332
+ ...(swiftmoduleFile !== undefined ? { swiftmoduleFile, swiftmoduleBytes } : {}),
333
+ ...(objcHeaderFile !== undefined ? { objcHeaderFile } : {}),
334
+ })
335
+ }
336
+ } finally {
337
+ fs.rmSync(membersRoot, { recursive: true, force: true })
338
+ }
339
+ if (targets.length === 0)
340
+ throw new Error('slice build produced no object-bearing targets')
341
+ return { targets, files }
342
+ }
343
+
344
+ /** install a staging directory containing `slice.json` and target files into local cache. */
345
+ export function finalizeSliceEntry(opts: {
346
+ manifest: NativePackageSliceManifest
347
+ inputs: Record<string, string>
348
+ assetFiles: string[]
349
+ stagingDir: string
350
+ }): LoadedNativePackageSlice {
351
+ const entryName = nativePackageEntryName(opts.manifest.packageName)
352
+ const slicePath = path.join(opts.stagingDir, 'slice.json')
353
+ fs.writeFileSync(slicePath, `${JSON.stringify(opts.manifest, null, 2)}\n`)
354
+ const descriptor = describeNativeEntry('pkg', entryName, opts.inputs, [
355
+ ...opts.assetFiles,
356
+ slicePath,
357
+ ])
358
+ fs.writeFileSync(
359
+ path.join(opts.stagingDir, 'descriptor.json'),
360
+ `${JSON.stringify(descriptor, null, 2)}\n`,
361
+ )
362
+ const dir = installNativeEntry('pkg', entryName, opts.manifest.key, opts.stagingDir)
363
+ return { dir, manifest: opts.manifest, descriptor }
364
+ }
365
+
366
+ function readDescriptor(dir: string): NativeEntryDescriptor {
367
+ const raw: unknown = JSON.parse(
368
+ fs.readFileSync(path.join(dir, 'descriptor.json'), 'utf8'),
369
+ )
370
+ return v.parse(
371
+ v.object({
372
+ kind: v.picklist([
373
+ 'app-bundle',
374
+ 'expo',
375
+ 'expo-pod',
376
+ 'nitro',
377
+ 'one-sdk',
378
+ 'pkg',
379
+ 'react-native',
380
+ 'rust',
381
+ 'slice',
382
+ 'turbo',
383
+ ]),
384
+ name: v.string(),
385
+ key: v.string(),
386
+ inputs: v.record(v.string(), v.string()),
387
+ files: v.array(
388
+ v.object({
389
+ path: v.string(),
390
+ sha256: v.string(),
391
+ size: v.number(),
392
+ }),
393
+ ),
394
+ }),
395
+ raw,
396
+ )
397
+ }
398
+
399
+ /** load a `native/pkg/<name>/<key>` slice from local cache, or fetch from CDN if allowed. */
400
+ export function loadNativePackageSlice(
401
+ packageName: string,
402
+ key: string,
403
+ options: { remote?: boolean } = {},
404
+ ): LoadedNativePackageSlice | null {
405
+ const entryName = nativePackageEntryName(packageName)
406
+ const cachedDir = nativeEntryCache('pkg', entryName, key)
407
+ const dir = fs.existsSync(path.join(cachedDir, 'descriptor.json'))
408
+ ? cachedDir
409
+ : options.remote !== false
410
+ ? fetchNativeEntry('pkg', entryName, key)
411
+ : null
412
+ if (!dir) return null
413
+ const sliceFile = path.join(dir, 'slice.json')
414
+ if (!fs.existsSync(sliceFile)) return null
415
+ const parsed: unknown = JSON.parse(fs.readFileSync(sliceFile, 'utf8'))
416
+ const manifest = v.parse(sliceManifestSchema, parsed)
417
+ return {
418
+ dir,
419
+ manifest,
420
+ descriptor: readDescriptor(dir),
421
+ }
422
+ }
423
+
424
+ export interface ExpoSwiftSliceBuildOptions {
425
+ appRoot: string
426
+ pod: ExpoPodPackage
427
+ podInputs: Record<string, string>
428
+ moduleRoot: string
429
+ buildRoot?: string
430
+ units?: readonly ExpoSwiftSourceUnit[] | null
431
+ optimize?: boolean
432
+ forceCompileArtifact?: boolean
433
+ }
434
+
435
+ /**
436
+ * compiles one installed Expo Swift package as a reusable static slice under
437
+ * `native/pkg/<name>/<key>/`, returning both the slice and the linked artifact
438
+ * when compiled in this invocation.
439
+ */
440
+ export async function buildExpoSwiftPackageSliceWithArtifact(
441
+ opts: ExpoSwiftSliceBuildOptions,
442
+ ): Promise<{
443
+ slice: LoadedNativePackageSlice
444
+ artifact: SwiftCompileArtifact | null
445
+ } | null> {
446
+ const inputs = expoPackageSliceInputs(opts.pod, opts.podInputs)
447
+ const key = nativeEntryKey(inputs)
448
+ if (!opts.forceCompileArtifact) {
449
+ const existing = loadNativePackageSlice(opts.pod.name, key, { remote: false })
450
+ if (existing) return { slice: existing, artifact: null }
451
+ }
452
+
453
+ const units =
454
+ opts.units !== undefined
455
+ ? opts.units
456
+ : await collectExpoSwiftSources(
457
+ opts.appRoot,
458
+ undefined,
459
+ undefined,
460
+ false,
461
+ undefined,
462
+ { moduleRoot: opts.moduleRoot },
463
+ )
464
+ const podUnits =
465
+ units?.filter((candidate) => candidate.namespace === opts.pod.swiftModule) ?? []
466
+ if (podUnits.length === 0 || podUnits.some((unit) => unit.reactNativeProvider)) {
467
+ return null
468
+ }
469
+
470
+ const settings = targetSettings(podUnits)
471
+ const buildFiles: Record<string, string> = {}
472
+ const nativeTargetsMap = new Map<string, SwiftNativeTarget>()
473
+ const headerAliases: Record<string, string> = {}
474
+ const nativeFiles: Record<string, string> = {}
475
+ const resources: Record<string, string> = {}
476
+ const resourceBundlesMap = new Map<string, SwiftResourceBundle>()
477
+ for (const unit of podUnits) {
478
+ for (const [file, source] of Object.entries(unit.files)) {
479
+ if (file !== EXPO_SWIFT_ENTRY && file !== 'Package.swift') {
480
+ buildFiles[file] = source
481
+ }
482
+ }
483
+ for (const target of unit.nativeTargets ?? []) {
484
+ nativeTargetsMap.set(target.name, target)
485
+ }
486
+ Object.assign(headerAliases, unit.headerAliases)
487
+ Object.assign(nativeFiles, unit.nativeFiles)
488
+ Object.assign(resources, unit.resources)
489
+ for (const bundle of unit.resourceBundles ?? []) {
490
+ resourceBundlesMap.set(bundle.target, bundle)
491
+ }
492
+ }
493
+ const hasViews = Object.entries(buildFiles).some(
494
+ ([file, source]) =>
495
+ file.endsWith('.swift') &&
496
+ /\bView\s*\(|\bExpoView\b|\bUIViewRepresentable\b|\bExpoSwiftUI\b/.test(source),
497
+ )
498
+ buildFiles[EXPO_SWIFT_ENTRY] = expoEntry(podUnits)
499
+ const packageSwift = withIosPlatformFloor(expoManifest(buildFiles, '', settings))
500
+ buildFiles['Package.swift'] = packageSwift
501
+ const nativeTargets = [...nativeTargetsMap.values()]
502
+ const resourceBundles = [...resourceBundlesMap.values()]
503
+ const swiftLanguageMode = podUnits.find(
504
+ (unit) => unit.swiftLanguageMode !== undefined,
505
+ )?.swiftLanguageMode
506
+
507
+ const workRoot =
508
+ opts.buildRoot ??
509
+ fs.mkdtempSync(path.join(os.tmpdir(), `peach-expo-slice-${opts.pod.swiftModule}-`))
510
+ const ownWorkRoot = opts.buildRoot === undefined
511
+ const compileRoot = path.join(workRoot, 'compile')
512
+ const stagingDir = path.join(workRoot, 'staging')
513
+ fs.rmSync(stagingDir, { recursive: true, force: true })
514
+ fs.mkdirSync(compileRoot, { recursive: true })
515
+ fs.mkdirSync(stagingDir, { recursive: true })
516
+
517
+ try {
518
+ const toolchain = swiftModuleToolchain(opts.moduleRoot)
519
+ const input: SwiftCompileInput = {
520
+ files: buildFiles,
521
+ entry: EXPO_SWIFT_ENTRY,
522
+ oneModule: false,
523
+ optimize: Boolean(opts.optimize),
524
+ ...(nativeTargets.length > 0 ? { nativeTargets } : {}),
525
+ ...(Object.keys(headerAliases).length > 0 ? { headerAliases } : {}),
526
+ ...(Object.keys(nativeFiles).length > 0 ? { nativeFiles } : {}),
527
+ ...(Object.keys(resources).length > 0 ? { resources } : {}),
528
+ ...(resourceBundles.length > 0 ? { resourceBundles } : {}),
529
+ }
530
+ const artifact = await compileSwiftProjectUnit(input, {
531
+ ...toolchain,
532
+ moduleRoot: opts.moduleRoot,
533
+ buildRoot: compileRoot,
534
+ intermediates: true,
535
+ })
536
+ const packed = packCompiledTargetsToSliceDir({
537
+ buildRoot: compileRoot,
538
+ packageSwift,
539
+ toolchainBin: toolchain.toolchainBin,
540
+ stagingDir,
541
+ })
542
+ const moduleIds = podUnits.map((unit) => unit.moduleId)
543
+ const manifest: NativePackageSliceManifest = {
544
+ schema: 1,
545
+ kind: 'expo-swift',
546
+ packageName: opts.pod.name,
547
+ packageVersion: opts.pod.version,
548
+ key,
549
+ runtimePin: swiftNativePin(),
550
+ targets: packed.targets,
551
+ expo: {
552
+ namespace: podUnits[0]!.namespace,
553
+ moduleId: moduleIds[0]!,
554
+ moduleIds,
555
+ classes: [...new Set(podUnits.flatMap((unit) => unit.classes))],
556
+ appDelegateSubscribers: [
557
+ ...new Set(podUnits.flatMap((unit) => unit.appDelegateSubscribers)),
558
+ ],
559
+ reactDelegateHandlers: [
560
+ ...new Set(podUnits.flatMap((unit) => unit.reactDelegateHandlers)),
561
+ ],
562
+ bridgeModules: [...new Set(podUnits.flatMap((unit) => unit.bridgeModules))],
563
+ hasViews,
564
+ ...(Object.keys(resources).length > 0 ? { resources } : {}),
565
+ ...(resourceBundles.length > 0 ? { resourceBundles } : {}),
566
+ ...(swiftLanguageMode !== undefined ? { swiftLanguageMode } : {}),
567
+ },
568
+ }
569
+ const slice = finalizeSliceEntry({
570
+ manifest,
571
+ inputs,
572
+ assetFiles: packed.files,
573
+ stagingDir,
574
+ })
575
+ return { slice, artifact }
576
+ } finally {
577
+ if (ownWorkRoot) fs.rmSync(workRoot, { recursive: true, force: true })
578
+ }
579
+ }
580
+
581
+ /**
582
+ * compiles one installed Expo Swift package as a reusable static slice under
583
+ * `native/pkg/<name>/<key>/` containing its `.a`, `.swiftmodule`, and `slice.json`.
584
+ */
585
+ export async function buildExpoSwiftPackageSlice(
586
+ opts: ExpoSwiftSliceBuildOptions,
587
+ ): Promise<LoadedNativePackageSlice | null> {
588
+ const built = await buildExpoSwiftPackageSliceWithArtifact(opts)
589
+ return built?.slice ?? null
590
+ }
591
+
592
+ /** build the SwiftPM prebuilt-library link input combining multiple Expo slices. */
593
+ export function buildComposedExpoCompileInput(
594
+ slices: readonly LoadedNativePackageSlice[],
595
+ options: { oneSDK?: boolean } = {},
596
+ ): {
597
+ input: SwiftCompileInput
598
+ expoSlices: {
599
+ manifest: NativePackageSliceManifest
600
+ expo: ExpoSliceMetadata
601
+ }[]
602
+ resources: Record<string, string>
603
+ } {
604
+ if (slices.length === 0)
605
+ throw new Error('composeExpoPackageSlices requires at least one slice')
606
+ const sorted = [...slices].sort((a, b) =>
607
+ a.manifest.packageName < b.manifest.packageName
608
+ ? -1
609
+ : a.manifest.packageName > b.manifest.packageName
610
+ ? 1
611
+ : 0,
612
+ )
613
+ const files: Record<string, string> = {}
614
+ const libraries: Record<string, string> = {}
615
+ const binaryModules: Record<string, string> = {}
616
+ const targetNames: string[] = []
617
+ const targetDecls: string[] = []
618
+ const virtualUnits: ExpoSwiftSourceUnit[] = []
619
+ const expoSlices: { manifest: NativePackageSliceManifest; expo: ExpoSliceMetadata }[] =
620
+ []
621
+ const resources: Record<string, string> = {}
622
+ const resourceBundlesMap = new Map<string, SwiftResourceBundle>()
623
+
624
+ for (const slice of sorted) {
625
+ const expo = slice.manifest.expo
626
+ if (slice.manifest.kind !== 'expo-swift' || !expo) {
627
+ throw new Error(
628
+ `${slice.manifest.packageName}: expected expo-swift slice, got ${slice.manifest.kind}`,
629
+ )
630
+ }
631
+ expoSlices.push({ manifest: slice.manifest, expo })
632
+ for (const target of slice.manifest.targets) {
633
+ if (targetNames.includes(target.name))
634
+ throw new Error(`duplicate Expo slice target ${target.name}`)
635
+ targetNames.push(target.name)
636
+ const dir = `Sources/${target.name}`
637
+ files[`${dir}/PeachPrebuiltCore.c`] = '\n'
638
+ files[`${dir}/include/PeachPrebuiltCore.h`] = '#pragma once\n'
639
+ if (target.objcHeaderFile) {
640
+ files[`${dir}/include/${target.name}-Swift.h`] = fs.readFileSync(
641
+ path.join(slice.dir, target.objcHeaderFile),
642
+ 'utf8',
643
+ )
644
+ }
645
+ libraries[target.name] = fs
646
+ .readFileSync(path.join(slice.dir, target.archiveFile))
647
+ .toString('base64')
648
+ if (target.swiftmoduleFile) {
649
+ binaryModules[target.name] = fs
650
+ .readFileSync(path.join(slice.dir, target.swiftmoduleFile))
651
+ .toString('base64')
652
+ }
653
+ targetDecls.push(
654
+ `.target(name: ${JSON.stringify(target.name)}, path: ${JSON.stringify(dir)})`,
655
+ )
656
+ }
657
+ for (const [key, value] of Object.entries(expo.resources ?? {})) {
658
+ if (key !== 'Info.plist') resources[key] = value
659
+ }
660
+ for (const bundle of expo.resourceBundles ?? []) {
661
+ resourceBundlesMap.set(bundle.target, bundle)
662
+ }
663
+ virtualUnits.push({
664
+ namespace: expo.namespace,
665
+ moduleId: expo.moduleId,
666
+ classes: expo.classes,
667
+ appDelegateSubscribers: expo.appDelegateSubscribers,
668
+ reactDelegateHandlers: expo.reactDelegateHandlers,
669
+ bridgeModules: expo.bridgeModules,
670
+ frameworks: [],
671
+ files: {
672
+ [`Sources/${expo.namespace}/Slice.swift`]: expo.hasViews
673
+ ? '// prebuilt view marker\nExpoView\n'
674
+ : '// prebuilt slice\n',
675
+ },
676
+ ...(expo.swiftLanguageMode !== undefined
677
+ ? { swiftLanguageMode: expo.swiftLanguageMode }
678
+ : {}),
679
+ })
680
+ }
681
+
682
+ files[EXPO_SWIFT_ENTRY] = expoEntry(virtualUnits, Boolean(options.oneSDK))
683
+ files['Package.swift'] = `// swift-tools-version: 6.0
684
+ import PackageDescription
685
+ let package = Package(
686
+ name: "PeachExpo",
687
+ platforms: [.iOS("17.0")],
688
+ targets: [
689
+ ${targetDecls.join(',\n ')},
690
+ .executableTarget(name: "PeachExpoApp", dependencies: ${JSON.stringify(targetNames)}, path: "Sources/PeachExpoApp")
691
+ ]
692
+ )
693
+ `
694
+ const resourceBundles = [...resourceBundlesMap.values()]
695
+ const input: SwiftCompileInput = {
696
+ files,
697
+ entry: EXPO_SWIFT_ENTRY,
698
+ oneModule: false,
699
+ optimize: true,
700
+ libraries,
701
+ binaryModules,
702
+ ...(resourceBundles.length > 0 ? { resourceBundles } : {}),
703
+ ...(Object.keys(resources).length > 0 ? { resources } : {}),
704
+ }
705
+ return { input, expoSlices, resources }
706
+ }
707
+
708
+ /**
709
+ * links prebuilt Expo Swift package slices into one shared-core Wasm executable
710
+ * and stores the verified `app-bundle/expo/<bundleKey>` entry in the local cache.
711
+ */
712
+ export async function composeExpoPackageSlices(
713
+ slices: readonly LoadedNativePackageSlice[],
714
+ options: {
715
+ moduleRoot: string
716
+ buildRoot?: string
717
+ oneSDK?: boolean
718
+ bundleInputs?: Record<string, string>
719
+ },
720
+ ): Promise<ComposedExpoBundle> {
721
+ const { input, expoSlices, resources } = buildComposedExpoCompileInput(slices, options)
722
+ const inputs =
723
+ options.bundleInputs ??
724
+ expoPodsBundleInputs(
725
+ expoSlices.map(({ manifest }) => ({
726
+ name: manifest.packageName,
727
+ version: manifest.packageVersion,
728
+ key: manifest.key,
729
+ })),
730
+ Boolean(options.oneSDK),
731
+ )
732
+ const bundleKey = nativeEntryKey(inputs)
733
+
734
+ const cachedDir = nativeEntryCache('app-bundle', 'expo', bundleKey)
735
+ const cachedMetaFile = path.join(cachedDir, 'metadata.json')
736
+ if (
737
+ fs.existsSync(cachedMetaFile) &&
738
+ fs.existsSync(path.join(cachedDir, 'descriptor.json'))
739
+ ) {
740
+ const cachedMeta: unknown = JSON.parse(fs.readFileSync(cachedMetaFile, 'utf8'))
741
+ if (isExpoSwiftCompilationResult(cachedMeta) && cachedMeta.modules.length === 1) {
742
+ const mod = cachedMeta.modules[0]!
743
+ const wasmPath = path.join(cachedDir, `${mod.hash}.wasm`)
744
+ const icuName = path.posix.basename(mod.icuUrl)
745
+ const icuPath = path.join(cachedDir, icuName)
746
+ if (fs.existsSync(wasmPath) && fs.existsSync(icuPath)) {
747
+ return {
748
+ bundleKey,
749
+ dir: cachedDir,
750
+ metadata: cachedMeta,
751
+ wasmPath,
752
+ icuPath,
753
+ descriptor: readDescriptor(cachedDir),
754
+ inputs,
755
+ }
756
+ }
757
+ }
758
+ }
759
+
760
+ const workRoot =
761
+ options.buildRoot ??
762
+ fs.mkdtempSync(path.join(os.tmpdir(), `peach-expo-compose-${bundleKey.slice(0, 8)}-`))
763
+ const ownWorkRoot = options.buildRoot === undefined
764
+ const compileRoot = path.join(workRoot, 'compile')
765
+ const stagingDir = path.join(workRoot, 'staging')
766
+ fs.rmSync(stagingDir, { recursive: true, force: true })
767
+ fs.mkdirSync(compileRoot, { recursive: true })
768
+ fs.mkdirSync(stagingDir, { recursive: true })
769
+
770
+ try {
771
+ const toolchain = swiftModuleToolchain(options.moduleRoot)
772
+ const artifact = await compileSwiftProjectUnit(input, {
773
+ ...toolchain,
774
+ moduleRoot: options.moduleRoot,
775
+ buildRoot: compileRoot,
776
+ })
777
+ const wasmName = `${artifact.hash}.wasm`
778
+ const wasmStage = path.join(stagingDir, wasmName)
779
+ fs.writeFileSync(wasmStage, artifact.bytes)
780
+
781
+ if (!('gzip' in artifact.icu))
782
+ throw new Error('composed Expo bundle must use packed external ICU')
783
+ const icuName = swiftIcuAddress(artifact.icu)
784
+ const packedIcu = await swiftIcuPacked(artifact.icu)
785
+ const icuStage = path.join(stagingDir, icuName)
786
+ fs.writeFileSync(icuStage, packedIcu)
787
+
788
+ const moduleIds = expoSlices.flatMap(({ expo }) => expo.moduleIds ?? [expo.moduleId])
789
+ const bridgeModules = expoSlices.flatMap(({ expo }) => expo.bridgeModules)
790
+ const metadata: ExpoSwiftCompilationResult = {
791
+ namespaces: [...moduleIds, ...bridgeModules],
792
+ ...(bridgeModules.length > 0 ? { bridgeModules } : {}),
793
+ failures: [],
794
+ modules: [
795
+ {
796
+ namespaces: moduleIds,
797
+ url: expoAppBundleEntryUrl(bundleKey, wasmName),
798
+ hash: artifact.hash,
799
+ icuUrl: expoAppBundleEntryUrl(bundleKey, icuName),
800
+ rootId: `app-bundle/expo/${bundleKey}`,
801
+ ...(Object.keys(resources).length > 0 ? { bundleFiles: resources } : {}),
802
+ },
803
+ ],
804
+ }
805
+ if (!isExpoSwiftCompilationResult(metadata))
806
+ throw new Error('composed Expo bundle produced invalid compilation metadata')
807
+
808
+ const metaStage = path.join(stagingDir, 'metadata.json')
809
+ fs.writeFileSync(metaStage, `${JSON.stringify(metadata)}\n`)
810
+
811
+ const descriptor = describeNativeEntry('app-bundle', 'expo', inputs, [
812
+ wasmStage,
813
+ icuStage,
814
+ metaStage,
815
+ ])
816
+ fs.writeFileSync(
817
+ path.join(stagingDir, 'descriptor.json'),
818
+ `${JSON.stringify(descriptor, null, 2)}\n`,
819
+ )
820
+ const dir = installNativeEntry('app-bundle', 'expo', bundleKey, stagingDir)
821
+ return {
822
+ bundleKey,
823
+ dir,
824
+ metadata,
825
+ wasmPath: path.join(dir, wasmName),
826
+ icuPath: path.join(dir, icuName),
827
+ descriptor,
828
+ inputs,
829
+ }
830
+ } finally {
831
+ if (ownWorkRoot) fs.rmSync(workRoot, { recursive: true, force: true })
832
+ }
833
+ }
834
+
835
+ export type ExpoSwiftArtifactReference = Pick<SwiftArtifact, 'hash' | 'bytes' | 'icu'>