peachsim 0.1.793 → 0.1.794

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 (81) hide show
  1. package/cli/app-config.ts +3 -7
  2. package/dist-lib/agent-daemon-client.cjs +2 -2
  3. package/dist-lib/agent-events.cjs +2 -2
  4. package/dist-lib/agent-identity.cjs +2 -2
  5. package/dist-lib/agent-sessions.cjs +2 -2
  6. package/dist-lib/attached-projects.cjs +2 -2
  7. package/dist-lib/auth/shared-session.cjs +2 -2
  8. package/dist-lib/backend-origin.cjs +2 -2
  9. package/dist-lib/beta.cjs +2 -2
  10. package/dist-lib/beta.mjs +1 -1
  11. package/dist-lib/bridge-constants.cjs +2 -2
  12. package/dist-lib/bridge-contract-input.cjs +2 -2
  13. package/dist-lib/bridge-contract-input.mjs +1 -1
  14. package/dist-lib/bridge-contract.cjs +2 -2
  15. package/dist-lib/bridge-contract.mjs +1 -1
  16. package/dist-lib/bundle-channel.cjs +9071 -0
  17. package/dist-lib/capture-contract.cjs +2 -2
  18. package/dist-lib/capture-contract.mjs +1 -1
  19. package/dist-lib/cli-constants.cjs +2 -2
  20. package/dist-lib/cloud-contract.cjs +2 -2
  21. package/dist-lib/cloud-contract.mjs +1 -1
  22. package/dist-lib/cloud-test-args.cjs +2 -2
  23. package/dist-lib/cloud-test-args.mjs +1 -1
  24. package/dist-lib/cloud.cjs +2 -2
  25. package/dist-lib/cloud.mjs +1 -1
  26. package/dist-lib/config.cjs +2 -2
  27. package/dist-lib/detox/index.cjs +2 -2
  28. package/dist-lib/dev-bundle-resolution.cjs +2 -2
  29. package/dist-lib/expo-swift-bundle.cjs +8419 -0
  30. package/dist-lib/expo-swift-metadata.cjs +91 -0
  31. package/dist-lib/expo-swift-metadata.mjs +63 -0
  32. package/dist-lib/home-paths.cjs +2 -2
  33. package/dist-lib/host/bridge-host.cjs +238 -130
  34. package/dist-lib/host/fetch-proxy-handler.cjs +2 -2
  35. package/dist-lib/host/fetch-proxy-overrides.cjs +2 -2
  36. package/dist-lib/host/fetch-proxy-overrides.mjs +1 -1
  37. package/dist-lib/host/replacement-module-handler.cjs +2 -2
  38. package/dist-lib/host/websocket-proxy.cjs +2 -2
  39. package/dist-lib/index.cjs +110 -12
  40. package/dist-lib/jump-to-source-babel.cjs +2 -2
  41. package/dist-lib/jump-to-source-native.cjs +2 -2
  42. package/dist-lib/kotlin-host.cjs +2 -2
  43. package/dist-lib/menu.cjs +2 -2
  44. package/dist-lib/menu.mjs +1 -1
  45. package/dist-lib/metro-fingerprint-registry.cjs +2 -2
  46. package/dist-lib/metro-fingerprint-registry.mjs +1 -1
  47. package/dist-lib/metro-production-bundle.cjs +2 -2
  48. package/dist-lib/metro-production-bundle.mjs +1 -1
  49. package/dist-lib/metro.cjs +110 -12
  50. package/dist-lib/native-app-identity.cjs +2 -2
  51. package/dist-lib/native-app-identity.mjs +1 -1
  52. package/dist-lib/native-firebase-metadata.cjs +2 -2
  53. package/dist-lib/native-firebase-metadata.mjs +1 -1
  54. package/dist-lib/plist.cjs +2 -2
  55. package/dist-lib/plist.mjs +1 -1
  56. package/dist-lib/profiles.cjs +2 -2
  57. package/dist-lib/public-brand.cjs +2 -2
  58. package/dist-lib/react-native-host-modules.cjs +2 -2
  59. package/dist-lib/react-native-host-modules.mjs +1 -1
  60. package/dist-lib/render-mode.cjs +2 -2
  61. package/dist-lib/scripts/dev-server-scanner.cjs +2 -2
  62. package/dist-lib/sdk.cjs +2 -2
  63. package/dist-lib/sdk.mjs +1 -1
  64. package/dist-lib/skills.cjs +349 -165
  65. package/dist-lib/swift-compile.cjs +105 -5
  66. package/dist-lib/swift-compile.mjs +101 -2
  67. package/dist-lib/swift-package.cjs +2 -2
  68. package/dist-lib/swift-package.mjs +1 -1
  69. package/dist-lib/swift-submit.cjs +2 -2
  70. package/dist-lib/swift-submit.mjs +1 -1
  71. package/dist-lib/swift-toolchain.cjs +2 -2
  72. package/dist-lib/swift.cjs +2 -2
  73. package/dist-lib/vite-swift.cjs +64 -8
  74. package/dist-lib/vite.cjs +2 -2
  75. package/package.json +20 -2
  76. package/src/bundle-channel.mjs +251 -0
  77. package/src/expo-swift-bundle.ts +32 -0
  78. package/src/expo-swift-host.ts +152 -128
  79. package/src/expoSwiftContract.ts +88 -0
  80. package/src/swift-compile.ts +111 -1
  81. package/src/swift-host.ts +4 -1
@@ -0,0 +1,251 @@
1
+ // publish the plain OTA bundle for Peach without changing the phone's bytecode.
2
+ import { createHash } from 'node:crypto'
3
+ import { Script } from 'node:vm'
4
+ import { terminateProcessGroup } from '../../contrast/src/runtime/process-group'
5
+ import { insertExpoSwiftFooter } from './expoSwiftContract'
6
+
7
+ const digest = (bytes) => createHash('sha256').update(bytes).digest('hex')
8
+ const segment = /^[a-zA-Z0-9._-]+$/
9
+
10
+ export function prepareBundleChannel({
11
+ prefix,
12
+ publicOrigin,
13
+ sourceSha,
14
+ runtimeVersion,
15
+ name,
16
+ icon,
17
+ bundle,
18
+ assets,
19
+ expoSwift = null,
20
+ }) {
21
+ if (!/^[a-f0-9]{40}$/.test(sourceSha) || !/^\d+$/.test(runtimeVersion)) {
22
+ throw new Error('invalid bundle channel source identity')
23
+ }
24
+ const origin = new URL(publicOrigin)
25
+ if (
26
+ origin.protocol !== 'https:' ||
27
+ origin.pathname !== '/' ||
28
+ origin.search ||
29
+ origin.hash ||
30
+ origin.username ||
31
+ origin.password
32
+ ) {
33
+ throw new Error('bundle channels require a public HTTPS origin')
34
+ }
35
+ if (!prefix.split('/').every((s) => segment.test(s) && s !== '.' && s !== '..')) {
36
+ throw new Error('invalid bundle channel prefix')
37
+ }
38
+ if (!icon.subarray(0, 8).equals(Buffer.from('89504e470d0a1a0a', 'hex')))
39
+ throw new Error('bundle channel icon must be PNG')
40
+ const files = new Map()
41
+ for (const asset of assets) {
42
+ if (
43
+ !asset.path.startsWith('assets/') ||
44
+ !asset.path
45
+ .split('/')
46
+ .every((s) => s && s !== '.' && s !== '..' && !/[\\?#%]/.test(s))
47
+ ) {
48
+ throw new Error(`invalid packaged asset path: ${asset.path}`)
49
+ }
50
+ if (files.has(asset.path)) throw new Error(`duplicate packaged asset: ${asset.path}`)
51
+ files.set(asset.path, asset.bytes)
52
+ }
53
+ for (const asset of expoSwift?.assets ?? []) {
54
+ if (!/^__peach\/(swift|swift-icu)\/[a-f0-9]{64}(\.wasm)?$/.test(asset.path))
55
+ throw new Error(`invalid Swift artifact path: ${asset.path}`)
56
+ if (files.has(asset.path)) throw new Error(`duplicate packaged asset: ${asset.path}`)
57
+ files.set(asset.path, asset.bytes)
58
+ }
59
+ // content identity includes native metadata and assets as well as images.
60
+
61
+ const identity = createHash('sha256').update(bundle).update(icon)
62
+ for (const [path, bytes] of [...files].sort(([a], [b]) =>
63
+ a < b ? -1 : a > b ? 1 : 0,
64
+ )) {
65
+ identity.update(JSON.stringify([path, digest(bytes)]))
66
+ }
67
+ if (expoSwift) identity.update(JSON.stringify(expoSwift.metadata))
68
+ const releaseKey = `${prefix}/peach/releases/${identity.digest('hex')}`
69
+ const assetBaseUrl = `${origin.origin}/${releaseKey}/`
70
+ const directories = new Set(
71
+ [...files.keys()].map((path) => path.slice(0, path.lastIndexOf('/'))),
72
+ )
73
+ let locations = 0
74
+ let source = new TextDecoder('utf-8', { fatal: true }).decode(bundle).replace(
75
+ // minifiers emit the location as a JSON string or a plain template literal.
76
+ /("?httpServerLocation"?\s*:\s*)(?:"((?:[^"\\]|\\.)*)"|`([^`\\$]*)`)/g,
77
+ (match, property, quoted, template) => {
78
+ const location = quoted === undefined ? template : JSON.parse(`"${quoted}"`)
79
+ const parsed = new URL(location, 'https://packaged.invalid')
80
+ if (parsed.origin !== 'https://packaged.invalid')
81
+ throw new Error(`non-packaged asset location: ${location}`)
82
+ const path = (parsed.searchParams.get('unstable_path') ?? parsed.pathname)
83
+ .replace(/^\/+/, '')
84
+ .replace(/\.\.\//g, '_')
85
+ if (!directories.has(path)) {
86
+ throw new Error(`bundle asset location has no packaged files: ${location}`)
87
+ }
88
+ locations++
89
+ return `${property}${JSON.stringify(new URL(path, assetBaseUrl).href)}`
90
+ },
91
+ )
92
+ if (assets.length && !locations)
93
+ throw new Error('bundle has packaged files but no asset metadata')
94
+ let nativeMetadata = null
95
+ if (expoSwift) {
96
+ nativeMetadata = {
97
+ ...expoSwift.metadata,
98
+ modules: expoSwift.metadata.modules.map((artifact) => ({
99
+ ...artifact,
100
+ url: new URL(artifact.url.replace(/^\//, ''), assetBaseUrl).href,
101
+ icuUrl: artifact.icuUrl.startsWith('/')
102
+ ? new URL(artifact.icuUrl.slice(1), assetBaseUrl).href
103
+ : artifact.icuUrl,
104
+ })),
105
+ }
106
+ source = insertExpoSwiftFooter(source, nativeMetadata)
107
+ }
108
+ new Script(source, { filename: 'peach-release-bundle.js' })
109
+ const bundleBytes = Buffer.from(source)
110
+ const metadata = {
111
+ schemaVersion: 1,
112
+ ...(nativeMetadata ? { expoSwift: nativeMetadata } : {}),
113
+ channel: 'prod',
114
+ name,
115
+ iconUrl: `${assetBaseUrl}icon.png`,
116
+ bundleUrl: `${assetBaseUrl}bundle.js`,
117
+ assetBaseUrl,
118
+ sourceSha,
119
+ runtimeVersion,
120
+ platform: 'ios',
121
+ bundleHash: digest(bundleBytes),
122
+ }
123
+ const objects = [
124
+ {
125
+ key: `${releaseKey}/bundle.js`,
126
+ bytes: bundleBytes,
127
+ contentType: 'application/javascript',
128
+ },
129
+ { key: `${releaseKey}/icon.png`, bytes: icon, contentType: 'image/png' },
130
+ ...[...files].map(([path, bytes]) => ({
131
+ key: `${releaseKey}/${path}`,
132
+ bytes,
133
+ contentType:
134
+ expoSwift?.assets.find((asset) => asset.path === path)?.contentType ??
135
+ {
136
+ png: 'image/png',
137
+ jpg: 'image/jpeg',
138
+ jpeg: 'image/jpeg',
139
+ webp: 'image/webp',
140
+ svg: 'image/svg+xml',
141
+ ttf: 'font/ttf',
142
+ otf: 'font/otf',
143
+ wav: 'audio/wav',
144
+ }[path.split('.').pop()] ??
145
+ 'application/octet-stream',
146
+ })),
147
+ ]
148
+ return { prefix, origin: origin.origin, metadata, objects }
149
+ }
150
+
151
+ export async function publishBundleChannel(release, { put, fetchObject = fetch }) {
152
+ // prove every immutable object is downloadable before changing the channel.
153
+ async function uploadVerified(object, cacheControl) {
154
+ await put(object.key, object.bytes, object.contentType, cacheControl)
155
+ const response = await fetchObject(`${release.origin}/${object.key}`)
156
+ if (!response.ok)
157
+ throw new Error(`bundle channel download failed: ${response.status} ${object.key}`)
158
+ const bytes = Buffer.from(await response.arrayBuffer())
159
+ if (digest(bytes) !== digest(object.bytes))
160
+ throw new Error(`bundle channel download mismatch: ${object.key}`)
161
+ }
162
+ for (const object of release.objects) await uploadVerified(object)
163
+ const bundle = release.objects[0]
164
+ await uploadVerified(
165
+ { ...bundle, key: `${release.prefix}/peach/channels/prod.js` },
166
+ 'no-store',
167
+ )
168
+ await put(
169
+ `${release.prefix}/peach/channels/prod.json`,
170
+ Buffer.from(JSON.stringify(release.metadata)),
171
+ 'application/json',
172
+ 'no-store',
173
+ )
174
+ const response = await fetchObject(
175
+ `${release.origin}/${release.prefix}/peach/channels/prod.json`,
176
+ { cache: 'no-store' },
177
+ )
178
+ if (
179
+ !response.ok ||
180
+ JSON.stringify(await response.json()) !== JSON.stringify(release.metadata)
181
+ ) {
182
+ throw new Error('published bundle channel metadata did not match')
183
+ }
184
+ console.log(
185
+ `[ota] Peach prod channel: ${release.origin}/${release.prefix}/peach/channels/prod.json`,
186
+ )
187
+ }
188
+
189
+ // peach boots a One app from the dev server's bundle: it carries the module
190
+ // graph peach maps native seams by, which a release build erases. snapshot it
191
+ // from a private dev server and package the files its assets register.
192
+ export async function snapshotOneDevBundle(projectRoot, env = {}) {
193
+ const { spawn } = await import('node:child_process')
194
+ const { readFileSync } = await import('node:fs')
195
+ const { createServer } = await import('node:net')
196
+ const { basename, dirname, join } = await import('node:path')
197
+ const { createRequire } = await import('node:module')
198
+ const onePackage = createRequire(join(projectRoot, 'package.json')).resolve(
199
+ 'one/package.json',
200
+ )
201
+ const oneBin = join(
202
+ dirname(onePackage),
203
+ JSON.parse(readFileSync(onePackage, 'utf8')).bin.one,
204
+ )
205
+ const port = await new Promise((resolve, reject) => {
206
+ const server = createServer()
207
+ .listen(0, '127.0.0.1', () => {
208
+ const { port } = server.address()
209
+ server.close(() => resolve(port))
210
+ })
211
+ .on('error', reject)
212
+ })
213
+ const child = spawn(process.execPath, [oneBin, 'dev', '--port', String(port)], {
214
+ cwd: projectRoot,
215
+ env: { ...process.env, ...env },
216
+ stdio: ['ignore', 'inherit', 'inherit'],
217
+ detached: true,
218
+ })
219
+ try {
220
+ const url = `http://127.0.0.1:${port}/index.bundle?platform=ios&dev=true&minify=false`
221
+ const deadline = Date.now() + 10 * 60_000
222
+ let bundle
223
+ while (!bundle) {
224
+ if (child.exitCode !== null)
225
+ throw new Error(`one dev exited with ${child.exitCode}`)
226
+ if (Date.now() > deadline) throw new Error('one dev bundle timed out')
227
+ const response = await fetch(url).catch(() => null)
228
+ if (response?.ok) bundle = Buffer.from(await response.arrayBuffer())
229
+ else await new Promise((resolve) => setTimeout(resolve, 2000))
230
+ }
231
+ const assets = new Map()
232
+ for (const [registration] of bundle
233
+ .toString('utf8')
234
+ .matchAll(/(?<=registerAsset\()\{[^{}]*"__packager_asset": true[^{}]*\}/g)) {
235
+ const asset = JSON.parse(registration)
236
+ for (const file of asset.files) {
237
+ const path = `${asset.httpServerLocation.replace(/^\/+/, '')}/${basename(file)}`
238
+ if (!assets.has(path)) assets.set(path, readFileSync(file))
239
+ }
240
+ }
241
+ const { buildExpoSwiftBundle } = await import('./expo-swift-bundle')
242
+ const expoSwift = await buildExpoSwiftBundle(projectRoot)
243
+ return {
244
+ bundle,
245
+ assets: [...assets].map(([path, bytes]) => ({ path, bytes })),
246
+ expoSwift,
247
+ }
248
+ } finally {
249
+ await terminateProcessGroup(child)
250
+ }
251
+ }
@@ -0,0 +1,32 @@
1
+ // release publishers use the same app compiler as local launches, then carry
2
+ // its immutable native assets beside the javascript bundle.
3
+ import { compileExpoSwiftModules } from './expo-swift-host'
4
+ import type { ExpoSwiftCompilationResult } from './expoSwiftContract'
5
+
6
+ export interface ExpoSwiftBundle {
7
+ metadata: ExpoSwiftCompilationResult
8
+ assets: { path: string; bytes: Buffer; contentType: string }[]
9
+ }
10
+
11
+ export async function buildExpoSwiftBundle(
12
+ appRoot: string,
13
+ ): Promise<ExpoSwiftBundle | null> {
14
+ const assets: ExpoSwiftBundle['assets'] = []
15
+ const metadata = await compileExpoSwiftModules(appRoot, '', async (artifact) => {
16
+ assets.push({
17
+ path: `__peach/swift/${artifact.hash}.wasm`,
18
+ bytes: artifact.bytes,
19
+ contentType: 'application/wasm',
20
+ })
21
+ if ('gzip' in artifact.icu) {
22
+ assets.push({
23
+ path: `__peach/swift-icu/${artifact.icu.sha256}`,
24
+ bytes: artifact.icu.gzip,
25
+ contentType: 'application/gzip',
26
+ })
27
+ }
28
+ })
29
+ if (!metadata) return null
30
+
31
+ return { metadata, assets }
32
+ }
@@ -9,7 +9,11 @@ import path from 'node:path'
9
9
  import { promisify } from 'node:util'
10
10
  import { RNX_FORKED_SCRIPT_ENV } from '../cli/internal-child'
11
11
  import { isLoopbackHost } from './backend-origin'
12
- import { swiftTargetDependencies, syncSwiftTree } from './swift-compile'
12
+ import {
13
+ swiftSourceClosure,
14
+ swiftTargetDependencies,
15
+ syncSwiftTree,
16
+ } from './swift-compile'
13
17
  import { resolveSwiftModule } from './swift-distribution'
14
18
  import {
15
19
  artifactFor,
@@ -17,6 +21,7 @@ import {
17
21
  projectFor,
18
22
  serveSwiftPackageAsset,
19
23
  sourceStamp,
24
+ SwiftMissingModulesError,
20
25
  } from './swift-host'
21
26
  import { MAX_SWIFT_COMPILE_FILES, MAX_SWIFT_COMPILE_SOURCE_BYTES } from './swift-submit'
22
27
  import type { ExpoSwiftSourceUnit, ExpoSwiftCompilationResult } from './expoSwiftContract'
@@ -117,7 +122,7 @@ export async function collectExpoSwiftSources(
117
122
  throw new Error(`duplicate local Expo Swift module ${namespace}`)
118
123
  namespacesSeen.add(namespace)
119
124
  const files: Record<string, string> = {}
120
- const classes: string[] = []
125
+ const classes: { name: string; registration: string }[] = []
121
126
  for (const module of modules) {
122
127
  const className =
123
128
  module && typeof module === 'object' ? Reflect.get(module, 'class') : null
@@ -129,9 +134,10 @@ export async function collectExpoSwiftSources(
129
134
  (name !== null && typeof name !== 'string')
130
135
  )
131
136
  throw new Error(`${sourceRoot}: invalid Expo Apple module descriptor`)
132
- classes.push(
133
- `(${className.includes('.') ? className : `${namespace}.${className}`}.self, ${name === null ? 'nil' : JSON.stringify(name)})`,
134
- )
137
+ classes.push({
138
+ name: className.split('.').pop()!,
139
+ registration: `(${className.includes('.') ? className : `${namespace}.${className}`}.self, ${name === null ? 'nil' : JSON.stringify(name)})`,
140
+ })
135
141
  }
136
142
  const ios = path.join(canonical, 'ios')
137
143
  if (fs.lstatSync(ios).isSymbolicLink())
@@ -163,21 +169,33 @@ export async function collectExpoSwiftSources(
163
169
  }
164
170
  }
165
171
  walk(ios)
166
- const unit = { namespace, classes, files }
167
- files[EXPO_SWIFT_ENTRY] = expoEntry([unit])
168
- units.push(unit)
172
+ for (const module of classes) {
173
+ const unit = {
174
+ namespace,
175
+ moduleId: `${namespace}.${module.name}`,
176
+ classes: [module.registration],
177
+ files: swiftSourceClosure(files, [module.name]),
178
+ }
179
+ unit.files[EXPO_SWIFT_ENTRY] = expoEntry([unit])
180
+ units.push(unit)
181
+ }
169
182
  }
170
183
  if (units.length === 0) return null
171
184
  const allFiles: Record<string, string> = Object.assign(
172
185
  {},
173
186
  ...units.map((unit) => unit.files),
174
187
  )
175
- const targets = units.map((unit) => ({
176
- name: unit.namespace,
177
- path: `Sources/${unit.namespace}`,
188
+ const targets = [...new Set(units.map((unit) => unit.namespace))].map((namespace) => ({
189
+ name: namespace,
190
+ path: `Sources/${namespace}`,
178
191
  }))
179
192
  const dependencies = swiftTargetDependencies(allFiles, targets)
180
- const byNamespace = new Map(units.map((unit) => [unit.namespace, unit]))
193
+ const byNamespace = new Map<string, ExpoSwiftSourceUnit[]>()
194
+ for (const unit of units) {
195
+ const entries = byNamespace.get(unit.namespace) ?? []
196
+ entries.push(unit)
197
+ byNamespace.set(unit.namespace, entries)
198
+ }
181
199
  for (const unit of units) {
182
200
  const included = new Set([unit.namespace])
183
201
  const visit = (namespace: string) => {
@@ -203,13 +221,133 @@ export async function collectExpoSwiftSources(
203
221
  }
204
222
 
205
223
  function expoEntry(units: ExpoSwiftSourceUnit[]): string {
206
- return `import SwiftUI\nimport ExpoModulesCore\n${units.map((unit) => `import ${unit.namespace}`).join('\n')}\n\n@main struct PeachExpoApp: RNXPackage {\n init() { MainActor.assumeIsolated { PeachExpoRuntime.register([${units.flatMap((unit) => unit.classes).join(', ')}]) } }\n func view(props: JSON) -> PeachExpoNativeView { PeachExpoNativeView(props: props) }\n}\n\n@_expose(wasm, "peach_expo_call")\n@_cdecl("peach_expo_call")\n@MainActor public func peachExpoCall(_ payload: UnsafePointer<UInt8>?, _ length: Int32) -> UnsafeMutablePointer<UInt8>? {\n PeachExpoRuntime.dispatch(payload, length)\n}\n`
224
+ return `import SwiftUI\nimport ExpoModulesCore\n${[...new Set(units.map((unit) => unit.namespace))].map((namespace) => `import ${namespace}`).join('\n')}\n\n@main struct PeachExpoApp: RNXPackage {\n init() { MainActor.assumeIsolated { PeachExpoRuntime.register([${units.flatMap((unit) => unit.classes).join(', ')}]) } }\n func view(props: JSON) -> PeachExpoNativeView { PeachExpoNativeView(props: props) }\n}\n\n@_expose(wasm, "peach_expo_call")\n@_cdecl("peach_expo_call")\n@MainActor public func peachExpoCall(_ payload: UnsafePointer<UInt8>?, _ length: Int32) -> UnsafeMutablePointer<UInt8>? {\n PeachExpoRuntime.dispatch(payload, length)\n}\n`
207
225
  }
208
226
 
209
227
  const compiling = new Map<string, Promise<unknown>>()
210
228
  // a failed compiler result is valid only for the exact app and framework inputs.
211
229
  const failedCompilations = new Map<string, { stamp: string; diagnostic: string }>()
212
230
 
231
+ export async function compileExpoSwiftModules(
232
+ root: string,
233
+ base: string,
234
+ publishArtifact?: (artifact: import('./swift-host').SwiftArtifact) => Promise<void>,
235
+ ): Promise<ExpoSwiftCompilationResult | null> {
236
+ const units = await collectExpoSwiftSources(root)
237
+ if (!units) return null
238
+ // source checks isolate failures; successful modules share one linked app.
239
+ const module = await resolveSwiftModule()
240
+ if (!module && publishArtifact)
241
+ throw new Error('No local Swift toolchain or distribution is available')
242
+ const result: ExpoSwiftCompilationResult = {
243
+ namespaces: units.map((unit) => unit.moduleId),
244
+ modules: [],
245
+ failures: [],
246
+ }
247
+ const key = createHash('sha256').update(fs.realpathSync(root)).digest('hex')
248
+ const linked: ExpoSwiftSourceUnit[] = []
249
+ for (const unit of units) {
250
+ if (!module) {
251
+ result.failures.push({
252
+ namespace: unit.moduleId,
253
+ diagnostic: 'No local Swift toolchain or distribution is available',
254
+ })
255
+ continue
256
+ }
257
+ try {
258
+ const packagePath = path.join(os.tmpdir(), 'peach-expo-swift', key, unit.moduleId)
259
+ // preserve the compiler's input stamp across unchanged reloads.
260
+ // only this adapter's build copy is synchronized; app sources are read only.
261
+ syncSwiftTree(
262
+ packagePath,
263
+ new Map(
264
+ Object.entries(unit.files).map(([name, source]) => [
265
+ path.join(packagePath, name),
266
+ source,
267
+ ]),
268
+ ),
269
+ )
270
+ const stamp = sourceStamp(packagePath, module.root)
271
+ const failed = failedCompilations.get(packagePath)
272
+ if (failed?.stamp === stamp) {
273
+ result.failures.push({
274
+ namespace: unit.moduleId,
275
+ diagnostic: failed.diagnostic,
276
+ })
277
+ continue
278
+ }
279
+ failedCompilations.delete(packagePath)
280
+ await artifactFor(projectFor(packagePath), EXPO_SWIFT_ENTRY, module.root).catch(
281
+ (error: unknown) => {
282
+ const diagnostic = error instanceof Error ? error.message : String(error)
283
+ // retain actual source diagnostics, not a timeout or infrastructure failure.
284
+ if (
285
+ /^.+:\d+(?::\d+)?: error:/m.test(diagnostic) &&
286
+ sourceStamp(packagePath, module.root) === stamp
287
+ )
288
+ failedCompilations.set(packagePath, { stamp, diagnostic })
289
+ throw error
290
+ },
291
+ )
292
+ linked.push(unit)
293
+ } catch (error) {
294
+ const diagnostic = error instanceof Error ? error.message : String(error)
295
+ const sourceErrors = diagnostic.match(/^.+:\d+(?::\d+)?: error:.*$/gm)
296
+ if (
297
+ publishArtifact &&
298
+ !sourceErrors &&
299
+ !(error instanceof SwiftMissingModulesError)
300
+ )
301
+ throw error
302
+ result.failures.push({
303
+ namespace: unit.moduleId,
304
+ diagnostic: sourceErrors ? sourceErrors.join('\n') : diagnostic,
305
+ })
306
+ }
307
+ }
308
+ if (module && linked.length) {
309
+ const files: Record<string, string> = Object.assign(
310
+ {},
311
+ ...linked.map((unit) => unit.files),
312
+ )
313
+ files[EXPO_SWIFT_ENTRY] = expoEntry(linked)
314
+ const targets = [
315
+ ...new Set(
316
+ Object.keys(files).flatMap((name) => {
317
+ const match = /^Sources\/([^/]+)\//.exec(name)
318
+ return match && match[1] !== 'PeachExpoApp' ? [match[1]] : []
319
+ }),
320
+ ),
321
+ ]
322
+ files['Package.swift'] =
323
+ `// swift-tools-version: 6.0\nimport PackageDescription\nlet package = Package(name: "PeachExpo", targets: [${targets.map((name) => `.target(name: ${JSON.stringify(name)}, path: ${JSON.stringify(`Sources/${name}`)})`).join(', ')}, .executableTarget(name: "PeachExpoApp", path: "Sources/PeachExpoApp")])\n`
324
+ const packagePath = path.join(os.tmpdir(), 'peach-expo-swift', key, 'linked-app')
325
+ syncSwiftTree(
326
+ packagePath,
327
+ new Map(
328
+ Object.entries(files).map(([name, source]) => [
329
+ path.join(packagePath, name),
330
+ source,
331
+ ]),
332
+ ),
333
+ )
334
+ const artifact = await artifactFor(
335
+ projectFor(packagePath),
336
+ EXPO_SWIFT_ENTRY,
337
+ module.root,
338
+ )
339
+ await publishArtifact?.(artifact)
340
+ result.modules.push({
341
+ namespaces: linked.map((unit) => unit.moduleId),
342
+ url: `${base}/__peach/swift/${artifact.hash}.wasm`,
343
+ hash: artifact.hash,
344
+ icuUrl: icuUrl(base, artifact),
345
+ rootId: `${key}/Expo`,
346
+ })
347
+ }
348
+ return result
349
+ }
350
+
213
351
  export async function handleExpoSwiftRequest(
214
352
  req: IncomingMessage,
215
353
  res: ServerResponse,
@@ -248,123 +386,9 @@ export async function handleExpoSwiftRequest(
248
386
  let pending = compiling.get(root)
249
387
  if (!pending) {
250
388
  pending = (async () => {
251
- const units = await collectExpoSwiftSources(root)
252
- if (!units) return null
253
- // source checks isolate failures; successful modules share one linked app.
254
- const module = await resolveSwiftModule()
255
- const result: ExpoSwiftCompilationResult = {
256
- namespaces: units.map((unit) => unit.namespace),
257
- modules: [],
258
- failures: [],
259
- }
260
- const key = createHash('sha256').update(fs.realpathSync(root)).digest('hex')
261
389
  const host = req.headers.host
262
390
  if (!host) throw new Error('Expo Swift request has no host')
263
- const base = `http://${host}`
264
- const linked: ExpoSwiftSourceUnit[] = []
265
- for (const unit of units) {
266
- if (!module) {
267
- result.failures.push({
268
- namespace: unit.namespace,
269
- diagnostic: 'No local Swift toolchain or distribution is available',
270
- })
271
- continue
272
- }
273
- try {
274
- const packagePath = path.join(
275
- os.tmpdir(),
276
- 'peach-expo-swift',
277
- key,
278
- unit.namespace,
279
- )
280
- // preserve the compiler's input stamp across unchanged reloads.
281
- // only this adapter's build copy is synchronized; app sources are read only.
282
- syncSwiftTree(
283
- packagePath,
284
- new Map(
285
- Object.entries(unit.files).map(([name, source]) => [
286
- path.join(packagePath, name),
287
- source,
288
- ]),
289
- ),
290
- )
291
- const stamp = sourceStamp(packagePath, module.root)
292
- const failed = failedCompilations.get(packagePath)
293
- if (failed?.stamp === stamp) {
294
- result.failures.push({
295
- namespace: unit.namespace,
296
- diagnostic: failed.diagnostic,
297
- })
298
- continue
299
- }
300
- failedCompilations.delete(packagePath)
301
- await artifactFor(
302
- projectFor(packagePath),
303
- EXPO_SWIFT_ENTRY,
304
- module.root,
305
- ).catch((error: unknown) => {
306
- const diagnostic = error instanceof Error ? error.message : String(error)
307
- // retain actual source diagnostics, not a timeout or infrastructure failure.
308
- if (
309
- /^.+:\d+(?::\d+)?: error:/m.test(diagnostic) &&
310
- sourceStamp(packagePath, module.root) === stamp
311
- )
312
- failedCompilations.set(packagePath, { stamp, diagnostic })
313
- throw error
314
- })
315
- linked.push(unit)
316
- } catch (error) {
317
- result.failures.push({
318
- namespace: unit.namespace,
319
- diagnostic: error instanceof Error ? error.message : String(error),
320
- })
321
- }
322
- }
323
- if (module && linked.length) {
324
- const files: Record<string, string> = Object.assign(
325
- {},
326
- ...linked.map((unit) => unit.files),
327
- )
328
- files[EXPO_SWIFT_ENTRY] = expoEntry(linked)
329
- const targets = [
330
- ...new Set(
331
- Object.keys(files).flatMap((name) => {
332
- const match = /^Sources\/([^/]+)\//.exec(name)
333
- return match && match[1] !== 'PeachExpoApp' ? [match[1]] : []
334
- }),
335
- ),
336
- ]
337
- files['Package.swift'] =
338
- `// swift-tools-version: 6.0\nimport PackageDescription\nlet package = Package(name: "PeachExpo", targets: [${targets.map((name) => `.target(name: ${JSON.stringify(name)}, path: ${JSON.stringify(`Sources/${name}`)})`).join(', ')}, .executableTarget(name: "PeachExpoApp", path: "Sources/PeachExpoApp")])\n`
339
- const packagePath = path.join(
340
- os.tmpdir(),
341
- 'peach-expo-swift',
342
- key,
343
- 'linked-app',
344
- )
345
- syncSwiftTree(
346
- packagePath,
347
- new Map(
348
- Object.entries(files).map(([name, source]) => [
349
- path.join(packagePath, name),
350
- source,
351
- ]),
352
- ),
353
- )
354
- const artifact = await artifactFor(
355
- projectFor(packagePath),
356
- EXPO_SWIFT_ENTRY,
357
- module.root,
358
- )
359
- result.modules.push({
360
- namespaces: linked.map((unit) => unit.namespace),
361
- url: `${base}/__peach/swift/${artifact.hash}.wasm`,
362
- hash: artifact.hash,
363
- icuUrl: icuUrl(base, artifact),
364
- rootId: `${key}/Expo`,
365
- })
366
- }
367
- return result
391
+ return compileExpoSwiftModules(root, `http://${host}`)
368
392
  })()
369
393
  compiling.set(root, pending)
370
394
  }