peachsim 0.1.2255 → 0.1.2257

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 (116) 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 +390 -130
  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 +352 -113
  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 +911 -582
  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 +1164 -784
  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 +335 -100
  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/render-worker/reanimated-readiness.d.ts +1 -0
  88. package/dist-types/packages/peach-globals/src/appLifecycleBridgeContract.d.ts +1 -0
  89. package/dist-types/packages/peach-globals/src/index.d.ts +1 -0
  90. package/dist-types/packages/peach-globals/src/lockstepCaptureBridgeContract.d.ts +1 -0
  91. package/dist-types/packages/peach-kit/src/transitions/screen-transition-math.d.ts +6 -0
  92. package/java-platform/licenses/android.txt +183 -0
  93. package/java-platform/licenses/arm-optimized-routines.txt +256 -0
  94. package/java-platform/licenses/fdlibm.txt +72 -0
  95. package/java-platform/licenses/icu.txt +50 -0
  96. package/java-platform/licenses/openjdk.txt +395 -0
  97. package/java-platform/licenses/teavm.txt +182 -0
  98. package/java-platform/licenses/threeten-backport.txt +29 -0
  99. package/kotlin/README.md +1 -1
  100. package/kotlin/sdk.tar.gz +0 -0
  101. package/package.json +2 -1
  102. package/runtime-companion.json +1 -1
  103. package/src/expo-autolinking.ts +47 -4
  104. package/src/expo-pod-prebuilt.ts +96 -9
  105. package/src/expo-swift-host.ts +29 -9
  106. package/src/kotlin-host.ts +3 -2
  107. package/src/kotlinSdkContract.ts +1 -0
  108. package/src/native-package-slice.ts +810 -0
  109. package/src/native-prebuilt.ts +4 -0
  110. package/src/native-seam-manifest.ts +0 -8
  111. package/src/nitro-adapter.lock.json +255 -255
  112. package/src/nitro-superset.lock.json +4 -4
  113. package/src/swift-distribution.lock.json +11 -11
  114. package/src/swift-link-roots.ts +23 -22
  115. package/src/swift-wasm-prune.ts +436 -105
  116. package/src/turbo-runtime.lock.json +23 -23
@@ -0,0 +1,810 @@
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 membersRoot = path.join(opts.stagingDir, '.members')
242
+ fs.mkdirSync(membersRoot, { recursive: true })
243
+ const targets: NativePackageSliceTarget[] = []
244
+ const files: string[] = []
245
+ try {
246
+ for (const target of manifestTargets) {
247
+ const targetBuild = path.join(products, `${target.name}.build`)
248
+ const objects = fs.existsSync(targetBuild)
249
+ ? fs
250
+ .readdirSync(targetBuild, { recursive: true, encoding: 'utf8' })
251
+ .filter((file) => file.endsWith('.o'))
252
+ .map((file) => path.join(targetBuild, file))
253
+ .sort()
254
+ : []
255
+ if (objects.length === 0) continue
256
+ const targetMembers = path.join(membersRoot, target.name)
257
+ fs.mkdirSync(targetMembers, { recursive: true })
258
+ const stripped = objects.map((file, index) => {
259
+ const out = path.join(targetMembers, `${index}-${path.basename(file)}`)
260
+ execFileSync(path.join(opts.toolchainBin, 'llvm-objcopy'), [
261
+ '--strip-debug',
262
+ file,
263
+ out,
264
+ ])
265
+ return out
266
+ })
267
+ const archiveFile = `lib${target.name}.a`
268
+ const archivePath = path.join(opts.stagingDir, archiveFile)
269
+ fs.rmSync(archivePath, { force: true })
270
+ execFileSync(path.join(opts.toolchainBin, 'llvm-ar'), [
271
+ 'rcsD',
272
+ archivePath,
273
+ ...stripped,
274
+ ])
275
+ files.push(archivePath)
276
+ const archiveBytes = fs.statSync(archivePath).size
277
+
278
+ let swiftmoduleFile: string | undefined
279
+ let swiftmoduleBytes: number | undefined
280
+ const builtModule = path.join(products, 'Modules', `${target.name}.swiftmodule`)
281
+ if (fs.existsSync(builtModule)) {
282
+ swiftmoduleFile = `${target.name}.swiftmodule`
283
+ const destModule = path.join(opts.stagingDir, swiftmoduleFile)
284
+ fs.copyFileSync(builtModule, destModule)
285
+ files.push(destModule)
286
+ swiftmoduleBytes = fs.statSync(destModule).size
287
+ }
288
+
289
+ let objcHeaderFile: string | undefined
290
+ const builtHeader = path.join(
291
+ opts.buildRoot,
292
+ '.build',
293
+ 'peach-cxx-headers',
294
+ `${target.name}-Swift.h`,
295
+ )
296
+ if (fs.existsSync(builtHeader)) {
297
+ objcHeaderFile = `${target.name}-Swift.h`
298
+ const destHeader = path.join(opts.stagingDir, objcHeaderFile)
299
+ fs.copyFileSync(builtHeader, destHeader)
300
+ files.push(destHeader)
301
+ }
302
+
303
+ targets.push({
304
+ name: target.name,
305
+ archiveFile,
306
+ archiveBytes,
307
+ ...(swiftmoduleFile !== undefined ? { swiftmoduleFile, swiftmoduleBytes } : {}),
308
+ ...(objcHeaderFile !== undefined ? { objcHeaderFile } : {}),
309
+ })
310
+ }
311
+ } finally {
312
+ fs.rmSync(membersRoot, { recursive: true, force: true })
313
+ }
314
+ if (targets.length === 0)
315
+ throw new Error('slice build produced no object-bearing targets')
316
+ return { targets, files }
317
+ }
318
+
319
+ /** install a staging directory containing `slice.json` and target files into local cache. */
320
+ export function finalizeSliceEntry(opts: {
321
+ manifest: NativePackageSliceManifest
322
+ inputs: Record<string, string>
323
+ assetFiles: string[]
324
+ stagingDir: string
325
+ }): LoadedNativePackageSlice {
326
+ const entryName = nativePackageEntryName(opts.manifest.packageName)
327
+ const slicePath = path.join(opts.stagingDir, 'slice.json')
328
+ fs.writeFileSync(slicePath, `${JSON.stringify(opts.manifest, null, 2)}\n`)
329
+ const descriptor = describeNativeEntry('pkg', entryName, opts.inputs, [
330
+ ...opts.assetFiles,
331
+ slicePath,
332
+ ])
333
+ fs.writeFileSync(
334
+ path.join(opts.stagingDir, 'descriptor.json'),
335
+ `${JSON.stringify(descriptor, null, 2)}\n`,
336
+ )
337
+ const dir = installNativeEntry('pkg', entryName, opts.manifest.key, opts.stagingDir)
338
+ return { dir, manifest: opts.manifest, descriptor }
339
+ }
340
+
341
+ function readDescriptor(dir: string): NativeEntryDescriptor {
342
+ const raw: unknown = JSON.parse(
343
+ fs.readFileSync(path.join(dir, 'descriptor.json'), 'utf8'),
344
+ )
345
+ return v.parse(
346
+ v.object({
347
+ kind: v.picklist([
348
+ 'app-bundle',
349
+ 'expo',
350
+ 'expo-pod',
351
+ 'nitro',
352
+ 'one-sdk',
353
+ 'pkg',
354
+ 'react-native',
355
+ 'rust',
356
+ 'slice',
357
+ 'turbo',
358
+ ]),
359
+ name: v.string(),
360
+ key: v.string(),
361
+ inputs: v.record(v.string(), v.string()),
362
+ files: v.array(
363
+ v.object({
364
+ path: v.string(),
365
+ sha256: v.string(),
366
+ size: v.number(),
367
+ }),
368
+ ),
369
+ }),
370
+ raw,
371
+ )
372
+ }
373
+
374
+ /** load a `native/pkg/<name>/<key>` slice from local cache, or fetch from CDN if allowed. */
375
+ export function loadNativePackageSlice(
376
+ packageName: string,
377
+ key: string,
378
+ options: { remote?: boolean } = {},
379
+ ): LoadedNativePackageSlice | null {
380
+ const entryName = nativePackageEntryName(packageName)
381
+ const cachedDir = nativeEntryCache('pkg', entryName, key)
382
+ const dir = fs.existsSync(path.join(cachedDir, 'descriptor.json'))
383
+ ? cachedDir
384
+ : options.remote !== false
385
+ ? fetchNativeEntry('pkg', entryName, key)
386
+ : null
387
+ if (!dir) return null
388
+ const sliceFile = path.join(dir, 'slice.json')
389
+ if (!fs.existsSync(sliceFile)) return null
390
+ const parsed: unknown = JSON.parse(fs.readFileSync(sliceFile, 'utf8'))
391
+ const manifest = v.parse(sliceManifestSchema, parsed)
392
+ return {
393
+ dir,
394
+ manifest,
395
+ descriptor: readDescriptor(dir),
396
+ }
397
+ }
398
+
399
+ export interface ExpoSwiftSliceBuildOptions {
400
+ appRoot: string
401
+ pod: ExpoPodPackage
402
+ podInputs: Record<string, string>
403
+ moduleRoot: string
404
+ buildRoot?: string
405
+ units?: readonly ExpoSwiftSourceUnit[] | null
406
+ optimize?: boolean
407
+ forceCompileArtifact?: boolean
408
+ }
409
+
410
+ /**
411
+ * compiles one installed Expo Swift package as a reusable static slice under
412
+ * `native/pkg/<name>/<key>/`, returning both the slice and the linked artifact
413
+ * when compiled in this invocation.
414
+ */
415
+ export async function buildExpoSwiftPackageSliceWithArtifact(
416
+ opts: ExpoSwiftSliceBuildOptions,
417
+ ): Promise<{
418
+ slice: LoadedNativePackageSlice
419
+ artifact: SwiftCompileArtifact | null
420
+ } | null> {
421
+ const inputs = expoPackageSliceInputs(opts.pod, opts.podInputs)
422
+ const key = nativeEntryKey(inputs)
423
+ if (!opts.forceCompileArtifact) {
424
+ const existing = loadNativePackageSlice(opts.pod.name, key, { remote: false })
425
+ if (existing) return { slice: existing, artifact: null }
426
+ }
427
+
428
+ const units =
429
+ opts.units !== undefined
430
+ ? opts.units
431
+ : await collectExpoSwiftSources(
432
+ opts.appRoot,
433
+ undefined,
434
+ undefined,
435
+ false,
436
+ undefined,
437
+ { moduleRoot: opts.moduleRoot },
438
+ )
439
+ const podUnits =
440
+ units?.filter((candidate) => candidate.namespace === opts.pod.swiftModule) ?? []
441
+ if (podUnits.length === 0 || podUnits.some((unit) => unit.reactNativeProvider)) {
442
+ return null
443
+ }
444
+
445
+ const settings = targetSettings(podUnits)
446
+ const buildFiles: Record<string, string> = {}
447
+ const nativeTargetsMap = new Map<string, SwiftNativeTarget>()
448
+ const headerAliases: Record<string, string> = {}
449
+ const nativeFiles: Record<string, string> = {}
450
+ const resources: Record<string, string> = {}
451
+ const resourceBundlesMap = new Map<string, SwiftResourceBundle>()
452
+ for (const unit of podUnits) {
453
+ for (const [file, source] of Object.entries(unit.files)) {
454
+ if (file !== EXPO_SWIFT_ENTRY && file !== 'Package.swift') {
455
+ buildFiles[file] = source
456
+ }
457
+ }
458
+ for (const target of unit.nativeTargets ?? []) {
459
+ nativeTargetsMap.set(target.name, target)
460
+ }
461
+ Object.assign(headerAliases, unit.headerAliases)
462
+ Object.assign(nativeFiles, unit.nativeFiles)
463
+ Object.assign(resources, unit.resources)
464
+ for (const bundle of unit.resourceBundles ?? []) {
465
+ resourceBundlesMap.set(bundle.target, bundle)
466
+ }
467
+ }
468
+ const hasViews = Object.entries(buildFiles).some(
469
+ ([file, source]) =>
470
+ file.endsWith('.swift') &&
471
+ /\bView\s*\(|\bExpoView\b|\bUIViewRepresentable\b|\bExpoSwiftUI\b/.test(source),
472
+ )
473
+ buildFiles[EXPO_SWIFT_ENTRY] = expoEntry(podUnits)
474
+ const packageSwift = withIosPlatformFloor(expoManifest(buildFiles, '', settings))
475
+ buildFiles['Package.swift'] = packageSwift
476
+ const nativeTargets = [...nativeTargetsMap.values()]
477
+ const resourceBundles = [...resourceBundlesMap.values()]
478
+ const swiftLanguageMode = podUnits.find(
479
+ (unit) => unit.swiftLanguageMode !== undefined,
480
+ )?.swiftLanguageMode
481
+
482
+ const workRoot =
483
+ opts.buildRoot ??
484
+ fs.mkdtempSync(path.join(os.tmpdir(), `peach-expo-slice-${opts.pod.swiftModule}-`))
485
+ const ownWorkRoot = opts.buildRoot === undefined
486
+ const compileRoot = path.join(workRoot, 'compile')
487
+ const stagingDir = path.join(workRoot, 'staging')
488
+ fs.rmSync(stagingDir, { recursive: true, force: true })
489
+ fs.mkdirSync(compileRoot, { recursive: true })
490
+ fs.mkdirSync(stagingDir, { recursive: true })
491
+
492
+ try {
493
+ const toolchain = swiftModuleToolchain(opts.moduleRoot)
494
+ const input: SwiftCompileInput = {
495
+ files: buildFiles,
496
+ entry: EXPO_SWIFT_ENTRY,
497
+ oneModule: false,
498
+ optimize: Boolean(opts.optimize),
499
+ ...(nativeTargets.length > 0 ? { nativeTargets } : {}),
500
+ ...(Object.keys(headerAliases).length > 0 ? { headerAliases } : {}),
501
+ ...(Object.keys(nativeFiles).length > 0 ? { nativeFiles } : {}),
502
+ ...(Object.keys(resources).length > 0 ? { resources } : {}),
503
+ ...(resourceBundles.length > 0 ? { resourceBundles } : {}),
504
+ }
505
+ const artifact = await compileSwiftProjectUnit(input, {
506
+ ...toolchain,
507
+ moduleRoot: opts.moduleRoot,
508
+ buildRoot: compileRoot,
509
+ intermediates: true,
510
+ })
511
+ const packed = packCompiledTargetsToSliceDir({
512
+ buildRoot: compileRoot,
513
+ packageSwift,
514
+ toolchainBin: toolchain.toolchainBin,
515
+ stagingDir,
516
+ })
517
+ const moduleIds = podUnits.map((unit) => unit.moduleId)
518
+ const manifest: NativePackageSliceManifest = {
519
+ schema: 1,
520
+ kind: 'expo-swift',
521
+ packageName: opts.pod.name,
522
+ packageVersion: opts.pod.version,
523
+ key,
524
+ runtimePin: swiftNativePin(),
525
+ targets: packed.targets,
526
+ expo: {
527
+ namespace: podUnits[0]!.namespace,
528
+ moduleId: moduleIds[0]!,
529
+ moduleIds,
530
+ classes: [...new Set(podUnits.flatMap((unit) => unit.classes))],
531
+ appDelegateSubscribers: [
532
+ ...new Set(podUnits.flatMap((unit) => unit.appDelegateSubscribers)),
533
+ ],
534
+ reactDelegateHandlers: [
535
+ ...new Set(podUnits.flatMap((unit) => unit.reactDelegateHandlers)),
536
+ ],
537
+ bridgeModules: [...new Set(podUnits.flatMap((unit) => unit.bridgeModules))],
538
+ hasViews,
539
+ ...(Object.keys(resources).length > 0 ? { resources } : {}),
540
+ ...(resourceBundles.length > 0 ? { resourceBundles } : {}),
541
+ ...(swiftLanguageMode !== undefined ? { swiftLanguageMode } : {}),
542
+ },
543
+ }
544
+ const slice = finalizeSliceEntry({
545
+ manifest,
546
+ inputs,
547
+ assetFiles: packed.files,
548
+ stagingDir,
549
+ })
550
+ return { slice, artifact }
551
+ } finally {
552
+ if (ownWorkRoot) fs.rmSync(workRoot, { recursive: true, force: true })
553
+ }
554
+ }
555
+
556
+ /**
557
+ * compiles one installed Expo Swift package as a reusable static slice under
558
+ * `native/pkg/<name>/<key>/` containing its `.a`, `.swiftmodule`, and `slice.json`.
559
+ */
560
+ export async function buildExpoSwiftPackageSlice(
561
+ opts: ExpoSwiftSliceBuildOptions,
562
+ ): Promise<LoadedNativePackageSlice | null> {
563
+ const built = await buildExpoSwiftPackageSliceWithArtifact(opts)
564
+ return built?.slice ?? null
565
+ }
566
+
567
+ /** build the SwiftPM prebuilt-library link input combining multiple Expo slices. */
568
+ export function buildComposedExpoCompileInput(
569
+ slices: readonly LoadedNativePackageSlice[],
570
+ options: { oneSDK?: boolean } = {},
571
+ ): {
572
+ input: SwiftCompileInput
573
+ expoSlices: {
574
+ manifest: NativePackageSliceManifest
575
+ expo: ExpoSliceMetadata
576
+ }[]
577
+ resources: Record<string, string>
578
+ } {
579
+ if (slices.length === 0)
580
+ throw new Error('composeExpoPackageSlices requires at least one slice')
581
+ const sorted = [...slices].sort((a, b) =>
582
+ a.manifest.packageName < b.manifest.packageName
583
+ ? -1
584
+ : a.manifest.packageName > b.manifest.packageName
585
+ ? 1
586
+ : 0,
587
+ )
588
+ const files: Record<string, string> = {}
589
+ const libraries: Record<string, string> = {}
590
+ const binaryModules: Record<string, string> = {}
591
+ const targetNames: string[] = []
592
+ const targetDecls: string[] = []
593
+ const virtualUnits: ExpoSwiftSourceUnit[] = []
594
+ const expoSlices: { manifest: NativePackageSliceManifest; expo: ExpoSliceMetadata }[] =
595
+ []
596
+ const resources: Record<string, string> = {}
597
+ const resourceBundlesMap = new Map<string, SwiftResourceBundle>()
598
+
599
+ for (const slice of sorted) {
600
+ const expo = slice.manifest.expo
601
+ if (slice.manifest.kind !== 'expo-swift' || !expo) {
602
+ throw new Error(
603
+ `${slice.manifest.packageName}: expected expo-swift slice, got ${slice.manifest.kind}`,
604
+ )
605
+ }
606
+ expoSlices.push({ manifest: slice.manifest, expo })
607
+ for (const target of slice.manifest.targets) {
608
+ if (targetNames.includes(target.name))
609
+ throw new Error(`duplicate Expo slice target ${target.name}`)
610
+ targetNames.push(target.name)
611
+ const dir = `Sources/${target.name}`
612
+ files[`${dir}/PeachPrebuiltCore.c`] = '\n'
613
+ files[`${dir}/include/PeachPrebuiltCore.h`] = '#pragma once\n'
614
+ if (target.objcHeaderFile) {
615
+ files[`${dir}/include/${target.name}-Swift.h`] = fs.readFileSync(
616
+ path.join(slice.dir, target.objcHeaderFile),
617
+ 'utf8',
618
+ )
619
+ }
620
+ libraries[target.name] = fs
621
+ .readFileSync(path.join(slice.dir, target.archiveFile))
622
+ .toString('base64')
623
+ if (target.swiftmoduleFile) {
624
+ binaryModules[target.name] = fs
625
+ .readFileSync(path.join(slice.dir, target.swiftmoduleFile))
626
+ .toString('base64')
627
+ }
628
+ targetDecls.push(
629
+ `.target(name: ${JSON.stringify(target.name)}, path: ${JSON.stringify(dir)})`,
630
+ )
631
+ }
632
+ for (const [key, value] of Object.entries(expo.resources ?? {})) {
633
+ if (key !== 'Info.plist') resources[key] = value
634
+ }
635
+ for (const bundle of expo.resourceBundles ?? []) {
636
+ resourceBundlesMap.set(bundle.target, bundle)
637
+ }
638
+ virtualUnits.push({
639
+ namespace: expo.namespace,
640
+ moduleId: expo.moduleId,
641
+ classes: expo.classes,
642
+ appDelegateSubscribers: expo.appDelegateSubscribers,
643
+ reactDelegateHandlers: expo.reactDelegateHandlers,
644
+ bridgeModules: expo.bridgeModules,
645
+ frameworks: [],
646
+ files: {
647
+ [`Sources/${expo.namespace}/Slice.swift`]: expo.hasViews
648
+ ? '// prebuilt view marker\nExpoView\n'
649
+ : '// prebuilt slice\n',
650
+ },
651
+ ...(expo.swiftLanguageMode !== undefined
652
+ ? { swiftLanguageMode: expo.swiftLanguageMode }
653
+ : {}),
654
+ })
655
+ }
656
+
657
+ files[EXPO_SWIFT_ENTRY] = expoEntry(virtualUnits, Boolean(options.oneSDK))
658
+ files['Package.swift'] = `// swift-tools-version: 6.0
659
+ import PackageDescription
660
+ let package = Package(
661
+ name: "PeachExpo",
662
+ platforms: [.iOS("17.0")],
663
+ targets: [
664
+ ${targetDecls.join(',\n ')},
665
+ .executableTarget(name: "PeachExpoApp", dependencies: ${JSON.stringify(targetNames)}, path: "Sources/PeachExpoApp")
666
+ ]
667
+ )
668
+ `
669
+ const resourceBundles = [...resourceBundlesMap.values()]
670
+ const input: SwiftCompileInput = {
671
+ files,
672
+ entry: EXPO_SWIFT_ENTRY,
673
+ oneModule: false,
674
+ optimize: true,
675
+ libraries,
676
+ binaryModules,
677
+ ...(resourceBundles.length > 0 ? { resourceBundles } : {}),
678
+ ...(Object.keys(resources).length > 0 ? { resources } : {}),
679
+ }
680
+ return { input, expoSlices, resources }
681
+ }
682
+
683
+ /**
684
+ * links prebuilt Expo Swift package slices into one shared-core Wasm executable
685
+ * and stores the verified `app-bundle/expo/<bundleKey>` entry in the local cache.
686
+ */
687
+ export async function composeExpoPackageSlices(
688
+ slices: readonly LoadedNativePackageSlice[],
689
+ options: {
690
+ moduleRoot: string
691
+ buildRoot?: string
692
+ oneSDK?: boolean
693
+ bundleInputs?: Record<string, string>
694
+ },
695
+ ): Promise<ComposedExpoBundle> {
696
+ const { input, expoSlices, resources } = buildComposedExpoCompileInput(slices, options)
697
+ const inputs =
698
+ options.bundleInputs ??
699
+ expoPodsBundleInputs(
700
+ expoSlices.map(({ manifest }) => ({
701
+ name: manifest.packageName,
702
+ version: manifest.packageVersion,
703
+ key: manifest.key,
704
+ })),
705
+ Boolean(options.oneSDK),
706
+ )
707
+ const bundleKey = nativeEntryKey(inputs)
708
+
709
+ const cachedDir = nativeEntryCache('app-bundle', 'expo', bundleKey)
710
+ const cachedMetaFile = path.join(cachedDir, 'metadata.json')
711
+ if (
712
+ fs.existsSync(cachedMetaFile) &&
713
+ fs.existsSync(path.join(cachedDir, 'descriptor.json'))
714
+ ) {
715
+ const cachedMeta: unknown = JSON.parse(fs.readFileSync(cachedMetaFile, 'utf8'))
716
+ if (isExpoSwiftCompilationResult(cachedMeta) && cachedMeta.modules.length === 1) {
717
+ const mod = cachedMeta.modules[0]!
718
+ const wasmPath = path.join(cachedDir, `${mod.hash}.wasm`)
719
+ const icuName = path.posix.basename(mod.icuUrl)
720
+ const icuPath = path.join(cachedDir, icuName)
721
+ if (fs.existsSync(wasmPath) && fs.existsSync(icuPath)) {
722
+ return {
723
+ bundleKey,
724
+ dir: cachedDir,
725
+ metadata: cachedMeta,
726
+ wasmPath,
727
+ icuPath,
728
+ descriptor: readDescriptor(cachedDir),
729
+ inputs,
730
+ }
731
+ }
732
+ }
733
+ }
734
+
735
+ const workRoot =
736
+ options.buildRoot ??
737
+ fs.mkdtempSync(path.join(os.tmpdir(), `peach-expo-compose-${bundleKey.slice(0, 8)}-`))
738
+ const ownWorkRoot = options.buildRoot === undefined
739
+ const compileRoot = path.join(workRoot, 'compile')
740
+ const stagingDir = path.join(workRoot, 'staging')
741
+ fs.rmSync(stagingDir, { recursive: true, force: true })
742
+ fs.mkdirSync(compileRoot, { recursive: true })
743
+ fs.mkdirSync(stagingDir, { recursive: true })
744
+
745
+ try {
746
+ const toolchain = swiftModuleToolchain(options.moduleRoot)
747
+ const artifact = await compileSwiftProjectUnit(input, {
748
+ ...toolchain,
749
+ moduleRoot: options.moduleRoot,
750
+ buildRoot: compileRoot,
751
+ })
752
+ const wasmName = `${artifact.hash}.wasm`
753
+ const wasmStage = path.join(stagingDir, wasmName)
754
+ fs.writeFileSync(wasmStage, artifact.bytes)
755
+
756
+ if (!('gzip' in artifact.icu))
757
+ throw new Error('composed Expo bundle must use packed external ICU')
758
+ const icuName = swiftIcuAddress(artifact.icu)
759
+ const packedIcu = await swiftIcuPacked(artifact.icu)
760
+ const icuStage = path.join(stagingDir, icuName)
761
+ fs.writeFileSync(icuStage, packedIcu)
762
+
763
+ const moduleIds = expoSlices.flatMap(({ expo }) => expo.moduleIds ?? [expo.moduleId])
764
+ const bridgeModules = expoSlices.flatMap(({ expo }) => expo.bridgeModules)
765
+ const metadata: ExpoSwiftCompilationResult = {
766
+ namespaces: [...moduleIds, ...bridgeModules],
767
+ ...(bridgeModules.length > 0 ? { bridgeModules } : {}),
768
+ failures: [],
769
+ modules: [
770
+ {
771
+ namespaces: moduleIds,
772
+ url: expoAppBundleEntryUrl(bundleKey, wasmName),
773
+ hash: artifact.hash,
774
+ icuUrl: expoAppBundleEntryUrl(bundleKey, icuName),
775
+ rootId: `app-bundle/expo/${bundleKey}`,
776
+ ...(Object.keys(resources).length > 0 ? { bundleFiles: resources } : {}),
777
+ },
778
+ ],
779
+ }
780
+ if (!isExpoSwiftCompilationResult(metadata))
781
+ throw new Error('composed Expo bundle produced invalid compilation metadata')
782
+
783
+ const metaStage = path.join(stagingDir, 'metadata.json')
784
+ fs.writeFileSync(metaStage, `${JSON.stringify(metadata)}\n`)
785
+
786
+ const descriptor = describeNativeEntry('app-bundle', 'expo', inputs, [
787
+ wasmStage,
788
+ icuStage,
789
+ metaStage,
790
+ ])
791
+ fs.writeFileSync(
792
+ path.join(stagingDir, 'descriptor.json'),
793
+ `${JSON.stringify(descriptor, null, 2)}\n`,
794
+ )
795
+ const dir = installNativeEntry('app-bundle', 'expo', bundleKey, stagingDir)
796
+ return {
797
+ bundleKey,
798
+ dir,
799
+ metadata,
800
+ wasmPath: path.join(dir, wasmName),
801
+ icuPath: path.join(dir, icuName),
802
+ descriptor,
803
+ inputs,
804
+ }
805
+ } finally {
806
+ if (ownWorkRoot) fs.rmSync(workRoot, { recursive: true, force: true })
807
+ }
808
+ }
809
+
810
+ export type ExpoSwiftArtifactReference = Pick<SwiftArtifact, 'hash' | 'bytes' | 'icu'>