peachsim 0.1.1635 → 0.1.1641

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 (142) hide show
  1. package/README.md +10 -1
  2. package/cli/app-config.ts +14 -5
  3. package/cli/app-stubs.ts +96 -22
  4. package/cli/bridge-flow-runner.ts +2 -2
  5. package/cli/cloud-client.ts +60 -40
  6. package/cli/cloud-session.ts +16 -0
  7. package/cli/commands/assert.ts +17 -4
  8. package/cli/commands/box.ts +33 -19
  9. package/cli/commands/doctor.ts +37 -20
  10. package/cli/commands/flow.ts +1 -1
  11. package/cli/commands/inspect/actions.ts +3 -2
  12. package/cli/commands/inspect/core.ts +0 -8
  13. package/cli/commands/inspect/shared.ts +9 -4
  14. package/cli/commands/inspect.ts +65 -61
  15. package/cli/commands/platform.ts +2 -1
  16. package/cli/commands/preview.ts +1 -1
  17. package/cli/commands/record.ts +154 -68
  18. package/cli/commands/swift.ts +18 -4
  19. package/cli/commands/three-mode.ts +4 -38
  20. package/cli/commands/upload.ts +55 -49
  21. package/cli/drivers/playwright-sim-host.ts +65 -42
  22. package/cli/flow-live-status.ts +0 -2
  23. package/cli/main.ts +2 -2
  24. package/cli/outbound-endpoints.ts +7 -5
  25. package/cli/pause-aware-timeout.ts +4 -0
  26. package/cli/ws-bridge.ts +19 -16
  27. package/detox/attempt-events.cjs +99 -6
  28. package/detox/attempt-events.d.cts +7 -0
  29. package/detox/expectations.ts +7 -3
  30. package/detox/index.ts +259 -139
  31. package/detox/jest-environment.cjs +5 -1
  32. package/detox/motion-change.cjs +170 -21
  33. package/detox/motion-change.d.cts +32 -0
  34. package/detox/navigation-lifecycle.ts +35 -3
  35. package/dist-lib/agent-daemon-client.cjs +1 -1
  36. package/dist-lib/agent-events.cjs +1 -1
  37. package/dist-lib/attached-projects.cjs +1 -1
  38. package/dist-lib/auth/shared-session.cjs +1 -1
  39. package/dist-lib/backend-origin.cjs +17 -7
  40. package/dist-lib/beta.cjs +1 -1
  41. package/dist-lib/beta.mjs +1 -1
  42. package/dist-lib/bridge-constants.cjs +1 -1
  43. package/dist-lib/bridge-contract-input.cjs +1 -1
  44. package/dist-lib/bridge-contract-input.mjs +1 -1
  45. package/dist-lib/bridge-contract.cjs +1 -1
  46. package/dist-lib/bridge-contract.mjs +1 -1
  47. package/dist-lib/bundle-channel.cjs +5014 -2268
  48. package/dist-lib/capture-contract.cjs +1 -1
  49. package/dist-lib/capture-contract.mjs +1 -1
  50. package/dist-lib/cloud-contract.cjs +1 -1
  51. package/dist-lib/cloud-contract.mjs +1 -1
  52. package/dist-lib/cloud-test-args.cjs +1 -1
  53. package/dist-lib/cloud-test-args.mjs +1 -1
  54. package/dist-lib/cloud.cjs +1 -1
  55. package/dist-lib/cloud.mjs +1 -1
  56. package/dist-lib/config.cjs +1 -1
  57. package/dist-lib/config.mjs +1 -1
  58. package/dist-lib/detox/index.cjs +1036 -166
  59. package/dist-lib/detox/jest-environment.cjs +5 -1
  60. package/dist-lib/dev-bundle-resolution.cjs +1 -1
  61. package/dist-lib/expo-swift-bundle.cjs +4613 -1963
  62. package/dist-lib/expo-swift-metadata.cjs +9 -7
  63. package/dist-lib/expo-swift-metadata.mjs +9 -7
  64. package/dist-lib/home-paths.cjs +1 -1
  65. package/dist-lib/host/bridge-host.cjs +58072 -16400
  66. package/dist-lib/host/fetch-proxy-handler.cjs +1 -1
  67. package/dist-lib/host/fetch-proxy-overrides.cjs +1 -1
  68. package/dist-lib/host/fetch-proxy-overrides.mjs +1 -1
  69. package/dist-lib/host/replacement-module-handler.cjs +1 -1
  70. package/dist-lib/host/websocket-proxy.cjs +1 -1
  71. package/dist-lib/index.cjs +2790 -143
  72. package/dist-lib/jump-to-source-babel.cjs +1 -1
  73. package/dist-lib/jump-to-source-native.cjs +1 -1
  74. package/dist-lib/kotlin-host.cjs +1 -1
  75. package/dist-lib/menu.cjs +1 -1
  76. package/dist-lib/menu.mjs +1 -1
  77. package/dist-lib/metro-fingerprint-registry.cjs +1 -1
  78. package/dist-lib/metro-fingerprint-registry.mjs +1 -1
  79. package/dist-lib/metro-production-bundle.cjs +1 -1
  80. package/dist-lib/metro-production-bundle.mjs +1 -1
  81. package/dist-lib/metro.cjs +2579 -95
  82. package/dist-lib/native-app-identity-project.cjs +243 -53
  83. package/dist-lib/native-app-identity-project.mjs +243 -53
  84. package/dist-lib/native-app-identity.cjs +29 -30
  85. package/dist-lib/native-app-identity.mjs +29 -30
  86. package/dist-lib/native-firebase-metadata.cjs +1 -1
  87. package/dist-lib/native-firebase-metadata.mjs +1 -1
  88. package/dist-lib/plist.cjs +1 -1
  89. package/dist-lib/plist.mjs +1 -1
  90. package/dist-lib/profiles.cjs +1 -1
  91. package/dist-lib/public-brand.cjs +1 -1
  92. package/dist-lib/react-native-host-modules.cjs +2 -2
  93. package/dist-lib/react-native-host-modules.mjs +2 -2
  94. package/dist-lib/scripts/dev-server-scanner.cjs +8 -6
  95. package/dist-lib/sdk.cjs +4 -3
  96. package/dist-lib/sdk.mjs +4 -3
  97. package/dist-lib/skills.cjs +66475 -23097
  98. package/dist-lib/swift-compile.cjs +452 -260
  99. package/dist-lib/swift-compile.mjs +451 -252
  100. package/dist-lib/swift-package.cjs +1 -1
  101. package/dist-lib/swift-package.mjs +1 -1
  102. package/dist-lib/swift-submit.cjs +14 -7
  103. package/dist-lib/swift-submit.mjs +14 -7
  104. package/dist-lib/swift-toolchain.cjs +316 -41
  105. package/dist-lib/swift.cjs +1 -1
  106. package/dist-lib/vite-swift.cjs +8188 -5636
  107. package/dist-lib/vite.cjs +2857 -12
  108. package/dist-lib/worklet-executable.cjs +14 -2
  109. package/dist-lib/worklet-executable.mjs +14 -2
  110. package/package.json +1 -1
  111. package/src/backend-origin.ts +21 -6
  112. package/src/expo-swift-host.ts +5 -2
  113. package/src/expoKotlinContract.ts +4 -7
  114. package/src/expoSwiftContract.ts +4 -6
  115. package/src/host/staged-host-files.ts +9 -0
  116. package/src/native-app-identity-project.ts +1 -4
  117. package/src/native-app-identity.ts +1 -4
  118. package/src/nativeAppIconContract.ts +1 -4
  119. package/src/output-lock-stdio.ts +36 -0
  120. package/src/react-native-bridge-modules.ts +106 -78
  121. package/src/react-native-host-modules.ts +4 -1
  122. package/src/settings-bundle.ts +1 -4
  123. package/src/swift-compile.ts +224 -139
  124. package/src/swift-distribution.lock.json +23 -12
  125. package/src/swift-distribution.ts +103 -4
  126. package/src/swift-host.ts +95 -30
  127. package/src/swift-icu.ts +16 -10
  128. package/src/swift-objc-compile.ts +547 -0
  129. package/src/swift-objc-metadata.ts +204 -0
  130. package/src/swift-objc-sdk.ts +883 -19
  131. package/src/swift-objc-standin.ts +126 -14
  132. package/src/swift-package-manifest.ts +42 -1
  133. package/src/swift-packages.ts +35 -21
  134. package/src/swift-root-lock.ts +153 -0
  135. package/src/swift-standin-emit.ts +40 -7
  136. package/src/swift-standins.ts +404 -138
  137. package/src/swift-submit.ts +18 -7
  138. package/src/swift-toolchain.ts +378 -46
  139. package/src/swiftContract.ts +12 -0
  140. package/src/worker-system-chunks.ts +11 -12
  141. package/src/worklet-executable.ts +19 -1
  142. package/src/xcode-project.ts +280 -33
@@ -0,0 +1,547 @@
1
+ import { spawnSync } from 'node:child_process'
2
+ import { createHash } from 'node:crypto'
3
+ import fs from 'node:fs'
4
+ import path from 'node:path'
5
+ import { cacheDir } from './home-paths'
6
+ import { swiftSdkPaths, swiftModuleSdk } from './swift-compile'
7
+ import { swiftModuleToolchain } from './swift-distribution'
8
+ import {
9
+ compileObjcPeerMetadata,
10
+ ObjcPeerMetadataError,
11
+ validateObjcPeerClasses,
12
+ } from './swift-objc-metadata'
13
+ import { IOS_SDK_ID, materializeObjcSdk } from './swift-objc-standin'
14
+ import { swiftTargetModuleName } from './swift-package'
15
+ import { swiftPackageManifest, swiftTargetFiles } from './swift-package-manifest'
16
+ import { remoteSwiftCheckouts, type SwiftPackageBinary } from './swift-packages'
17
+ import { readPackageFile } from './swift-source-file'
18
+ import { swiftEnvironment } from './swift-toolchain'
19
+ import type {
20
+ SwiftObjCImplementationPreparation,
21
+ SwiftObjCPeerClass,
22
+ } from './swiftContract'
23
+ import type { XcodeAppTarget } from './xcode-project'
24
+
25
+ export class SwiftObjCCompilationError extends Error {}
26
+
27
+ /** compile original implementations before any header-derived replacement can hide them.
28
+ * successful objects still require the canonical framework bridge before linking. */
29
+ export function compileXcodeObjCImplementations(
30
+ app: XcodeAppTarget,
31
+ binaries: readonly SwiftPackageBinary[],
32
+ moduleRoot: string,
33
+ ): never {
34
+ const prepared = prepareXcodeObjCImplementations(app, binaries, moduleRoot)
35
+ throw new SwiftObjCCompilationError(
36
+ `Objective-C implementations compiled, but linking their original method bodies requires the canonical Swift framework object bridge. No implementation was replaced. Inputs and objects: ${prepared.receipt}`,
37
+ )
38
+ }
39
+
40
+ /** prepares genuine objects without authorizing unsupported framework linkage. */
41
+ export function prepareXcodeObjCImplementations(
42
+ app: XcodeAppTarget,
43
+ binaries: readonly SwiftPackageBinary[],
44
+ moduleRoot: string,
45
+ peers?: readonly SwiftObjCPeerClass[],
46
+ ): SwiftObjCImplementationPreparation {
47
+ if (peers) validateObjcPeerClasses(peers)
48
+ const toolchain = swiftModuleToolchain(moduleRoot)
49
+ const sdk = swiftSdkPaths(moduleRoot, toolchain.toolchainBin)
50
+ const sources = new Map<string, Buffer>()
51
+ const links: Record<string, string> = {}
52
+ const checkouts = remoteSwiftCheckouts(app.rootDir)
53
+ const add = (file: string, header = false) => {
54
+ const resolved = header ? fs.realpathSync(file) : file
55
+ if (resolved !== file) links[file] = resolved
56
+ if (!sources.has(file))
57
+ sources.set(
58
+ file,
59
+ readPackageFile(
60
+ file.startsWith(`${checkouts}${path.sep}`) ? checkouts : app.rootDir,
61
+ resolved,
62
+ Infinity,
63
+ ),
64
+ )
65
+ }
66
+ const addHeaders = (directory: string): void => {
67
+ for (const entry of fs.readdirSync(directory, { withFileTypes: true })) {
68
+ if (entry.isDirectory() && entry.name.startsWith('.')) continue
69
+ const file = path.join(directory, entry.name)
70
+ if (entry.isDirectory()) addHeaders(file)
71
+ else if (/\.(h|hh|hpp|hxx|inc|inl|modulemap)$/.test(entry.name)) add(file, true)
72
+ }
73
+ }
74
+ const targets: {
75
+ name: string
76
+ deploymentTarget: string | null
77
+ files: string[]
78
+ includes: string[]
79
+ frameworks: string[]
80
+ flags: string[]
81
+ cxxFlags: string[]
82
+ prefix: string | null
83
+ fileFlags: Record<string, string[]>
84
+ publicHeaders?: string
85
+ }[] = []
86
+ const configuration = app.configuration === 'Debug' ? 'debug' : 'release'
87
+ for (const binary of binaries) {
88
+ if (!binary.reached || binary.publicHeaders === undefined) continue
89
+ const manifest = swiftPackageManifest(binary.dir)
90
+ const target = manifest.targets.get(binary.target)
91
+ if (!target)
92
+ throw new Error(`missing original implementation target ${binary.target}`)
93
+ const files = swiftTargetFiles(manifest, target)
94
+ for (const file of files) add(file)
95
+ // explicit sources select compile units, not the private headers they include.
96
+ addHeaders(target.dir)
97
+ for (const dependency of binary.headerDependencies ?? [])
98
+ addHeaders(path.resolve(binary.dir, dependency.path))
99
+ const settings = target.nativeSettings.filter(
100
+ (setting) =>
101
+ setting.configuration === null || setting.configuration === configuration,
102
+ )
103
+ const nativeFlags = settings.flatMap((setting) => setting.flags)
104
+ for (const [index, flag] of nativeFlags.entries()) {
105
+ const directory = ['-I', '-iquote', '-isystem'].includes(
106
+ nativeFlags[index - 1] ?? '',
107
+ )
108
+ ? flag
109
+ : /^-I(.+)$/.exec(flag)?.[1]
110
+ if (directory) {
111
+ const include = path.resolve(target.dir, directory)
112
+ if (fs.existsSync(include)) addHeaders(include)
113
+ }
114
+ }
115
+ targets.push({
116
+ name: target.name,
117
+ deploymentTarget: app.iosDeploymentTarget,
118
+ files: files.filter((file) => /\.(c|cc|cpp|cxx|m|mm)$/.test(file)),
119
+ includes: [
120
+ path.join(target.dir, target.publicHeadersPath),
121
+ ...(binary.headerDependencies ?? []).map((dependency) =>
122
+ path.resolve(binary.dir, dependency.path),
123
+ ),
124
+ ],
125
+ frameworks: [],
126
+ // retain the source iOS package's ARC and module semantics on the wasm ABI.
127
+ flags: [
128
+ '-fobjc-arc',
129
+ '-fmodules',
130
+ '-DSWIFT_PACKAGE',
131
+ ...(configuration === 'debug' ? ['-DDEBUG'] : []),
132
+ ...settings
133
+ .filter((setting) => setting.tool === 'c')
134
+ .flatMap((setting) => setting.flags),
135
+ ],
136
+ cxxFlags: settings
137
+ .filter((setting) => setting.tool === 'cxx')
138
+ .flatMap((setting) => setting.flags),
139
+ prefix: null,
140
+ fileFlags: {},
141
+ publicHeaders: path.join(target.dir, target.publicHeadersPath),
142
+ })
143
+ }
144
+ for (const target of [...app.frameworks, app]) {
145
+ if (!target.objc) continue
146
+ const files = target.allSources.filter((file) => /\.(c|cc|cpp|cxx|m|mm)$/.test(file))
147
+ for (const file of files) add(file)
148
+ for (const file of [
149
+ ...target.objc.headers,
150
+ ...[target.objc.prefixHeader, target.objc.bridgingHeader].filter(
151
+ (file): file is string => file !== null,
152
+ ),
153
+ ])
154
+ add(file, true)
155
+ targets.push({
156
+ name: target.moduleName,
157
+ deploymentTarget: target.iosDeploymentTarget,
158
+ files,
159
+ includes: target.objc.headerSearchPaths,
160
+ frameworks: target.objc.frameworkSearchPaths,
161
+ flags: target.objc.flags,
162
+ cxxFlags: target.objc.cxxFlags,
163
+ prefix: target.objc.prefixHeader,
164
+ fileFlags: target.objc.fileFlags,
165
+ })
166
+ }
167
+ const digest = (bytes: Buffer | string) =>
168
+ createHash('sha256').update(bytes).digest('hex')
169
+ const inputs = Object.fromEntries(
170
+ [...sources].map(([file, bytes]) => [file, digest(bytes)]),
171
+ )
172
+ const identity = {
173
+ version: 8,
174
+ peers,
175
+ metadataDeploymentTarget: peers ? app.iosDeploymentTarget : undefined,
176
+ release: toolchain.release,
177
+ compiler: digest(fs.readFileSync(path.join(toolchain.toolchainBin, 'clang'))),
178
+ sdk: swiftModuleSdk(moduleRoot),
179
+ declarations: IOS_SDK_ID,
180
+ targets,
181
+ inputs,
182
+ links,
183
+ }
184
+ const parent = path.join(cacheDir(), 'swift-objc-implementations')
185
+ fs.mkdirSync(parent, { recursive: true })
186
+ const key = digest(JSON.stringify(identity))
187
+ const work = path.join(parent, key)
188
+ const descriptor = fs.openSync(`${work}.lock`, 'a')
189
+ try {
190
+ // the inherited descriptor keeps the kernel lock after perl exits.
191
+ const locked = spawnSync(
192
+ 'perl',
193
+ ['-e', 'open(my $f, ">&=", 3) or die $!; flock($f, 2) or die $!'],
194
+ { stdio: ['ignore', 'pipe', 'pipe', descriptor], encoding: 'utf8' },
195
+ )
196
+ if (locked.error || locked.status !== 0)
197
+ throw new Error(
198
+ `Could not lock Objective-C implementation inputs: ${locked.error?.message ?? locked.stderr}`,
199
+ )
200
+ const resultFile = path.join(work, 'result.json')
201
+ const preparation = (): SwiftObjCImplementationPreparation => ({
202
+ receipt: path.join(work, 'receipt.json'),
203
+ objects: targets.flatMap((target, index) =>
204
+ target.files.map((source, unit) => ({
205
+ target: target.name,
206
+ source,
207
+ file: path.join(work, `${index}-${unit}.o`),
208
+ })),
209
+ ),
210
+ ...(peers
211
+ ? {
212
+ metadata: path.join(work, 'peer-metadata.o'),
213
+ registration: path.join(work, 'peer-registration.swift'),
214
+ }
215
+ : {}),
216
+ })
217
+ const record = (value: unknown): value is Record<string, unknown> =>
218
+ value !== null && typeof value === 'object' && !Array.isArray(value)
219
+ if (fs.existsSync(work)) {
220
+ let message: string | undefined
221
+ let interrupted = false
222
+ let prepared = false
223
+ try {
224
+ const result: unknown = JSON.parse(
225
+ readPackageFile(work, resultFile, Infinity).toString(),
226
+ )
227
+ if (
228
+ !record(result) ||
229
+ result.key !== key ||
230
+ typeof result.reusable !== 'boolean' ||
231
+ typeof result.prepared !== 'boolean' ||
232
+ typeof result.message !== 'string' ||
233
+ !result.message ||
234
+ !record(result.files) ||
235
+ Object.keys(result.files).length < sources.size + 1 ||
236
+ !('receipt.json' in result.files)
237
+ )
238
+ throw new Error('invalid completed receipt')
239
+ for (const [file, hash] of Object.entries(result.files)) {
240
+ if (
241
+ typeof hash !== 'string' ||
242
+ digest(readPackageFile(work, path.resolve(work, file), Infinity)) !== hash
243
+ )
244
+ throw new Error(`retained file changed: ${file}`)
245
+ }
246
+ if (result.prepared) {
247
+ for (const file of [
248
+ ...preparation().objects.map((object) => object.file),
249
+ ...(peers
250
+ ? [
251
+ 'peer-metadata.o',
252
+ 'peer-metadata.m',
253
+ 'peer-metadata.log',
254
+ 'peer-metadata.json',
255
+ 'peer-registration.swift',
256
+ ].map((file) => path.join(work, file))
257
+ : []),
258
+ ])
259
+ if (!(path.relative(work, file) in result.files))
260
+ throw new Error(`missing prepared object or metadata input: ${file}`)
261
+ prepared = true
262
+ } else if (result.reusable) message = result.message
263
+ else interrupted = true
264
+ } catch {
265
+ // no writer can remain under this kernel lock; rebuild invalid proof.
266
+ fs.rmSync(work, { recursive: true })
267
+ }
268
+ if (prepared) return preparation()
269
+ if (message !== undefined) throw new SwiftObjCCompilationError(message)
270
+ // retain the first and latest complete interruptions for this input identity.
271
+ if (interrupted) {
272
+ const first = `${work}-interrupted-first`
273
+ const destination = fs.existsSync(first) ? `${work}-interrupted-latest` : first
274
+ fs.rmSync(destination, { recursive: true, force: true })
275
+ fs.renameSync(work, destination)
276
+ }
277
+ }
278
+ fs.mkdirSync(work)
279
+ const staged = (file: string): string => {
280
+ for (const { root, name } of [
281
+ { root: checkouts, name: 'packages' },
282
+ { root: app.rootDir, name: 'project' },
283
+ ]) {
284
+ const relative = path.relative(root, file)
285
+ if (
286
+ relative !== '..' &&
287
+ !relative.startsWith(`..${path.sep}`) &&
288
+ !path.isAbsolute(relative)
289
+ )
290
+ return path.join(work, name, relative)
291
+ }
292
+ // native SDK include paths select the wasm SDK, never host system headers.
293
+ if (file.startsWith('/usr/include/'))
294
+ return path.join(sdk.sysroot, 'include', file.slice('/usr/include/'.length))
295
+ throw new Error(
296
+ `Objective-C compiler input is outside the project and its pinned packages: ${file}`,
297
+ )
298
+ }
299
+ for (const [file, bytes] of sources) {
300
+ const output = staged(file)
301
+ fs.mkdirSync(path.dirname(output), { recursive: true })
302
+ fs.writeFileSync(output, bytes)
303
+ }
304
+ const headers = materializeObjcSdk(path.join(cacheDir(), 'swift-standins'))
305
+ const modulemaps = targets.flatMap((target, index) => {
306
+ if (!target.publicHeaders) return []
307
+ const custom = path.join(target.publicHeaders, 'module.modulemap')
308
+ if (sources.has(custom)) return [`-fmodule-map-file=${staged(custom)}`]
309
+ const output = path.join(work, `module-${index}.modulemap`)
310
+ fs.writeFileSync(
311
+ output,
312
+ `module ${swiftTargetModuleName(target.name)} {\n umbrella ${JSON.stringify(staged(target.publicHeaders))}\n export *\n}\n`,
313
+ )
314
+ return [`-fmodule-map-file=${output}`]
315
+ })
316
+ const commands: {
317
+ target: string
318
+ source: string
319
+ args: string[]
320
+ status: number | null
321
+ signal: string | null
322
+ error?: string
323
+ object?: string
324
+ }[] = []
325
+ const receipt = path.join(work, 'receipt.json')
326
+ const save = (status: string) =>
327
+ fs.writeFileSync(
328
+ receipt,
329
+ JSON.stringify({ ...identity, work, status, commands }, null, 2),
330
+ )
331
+ let metadataFiles: string[] = []
332
+ const complete = (
333
+ status: string,
334
+ message: string,
335
+ reusable = true,
336
+ additionalFiles: string[] = [],
337
+ ): void => {
338
+ save(status)
339
+ const files = [
340
+ ...[...sources.keys()].map(staged),
341
+ ...modulemaps.map((flag) => flag.slice('-fmodule-map-file='.length)),
342
+ receipt,
343
+ ...metadataFiles,
344
+ ...additionalFiles,
345
+ ...commands.flatMap((command) => {
346
+ const output = command.args[command.args.lastIndexOf('-o') + 1]!
347
+ return [output.replace(/\.o$/, '.log'), ...(command.object ? [output] : [])]
348
+ }),
349
+ ]
350
+ const result = {
351
+ key,
352
+ message,
353
+ reusable,
354
+ prepared: status === 'prepared',
355
+ files: Object.fromEntries(
356
+ files.map((file) => [path.relative(work, file), digest(fs.readFileSync(file))]),
357
+ ),
358
+ }
359
+ fs.writeFileSync(`${resultFile}.pending`, JSON.stringify(result, null, 2))
360
+ fs.renameSync(`${resultFile}.pending`, resultFile)
361
+ }
362
+ const finish = (
363
+ status: string,
364
+ message: string,
365
+ reusable = true,
366
+ metadataFiles: string[] = [],
367
+ ): never => {
368
+ complete(status, message, reusable, metadataFiles)
369
+ throw new SwiftObjCCompilationError(message)
370
+ }
371
+ save('compiling')
372
+ const minimumFor = (target: {
373
+ name: string
374
+ deploymentTarget: string | null
375
+ }): number => {
376
+ const version = /^(\d{1,2})(?:\.(\d{1,2}))?(?:\.(\d{1,2}))?$/.exec(
377
+ target.deploymentTarget ?? '',
378
+ )
379
+ if (!version) {
380
+ return finish(
381
+ 'unsupported-deployment-target',
382
+ `${target.name}: Objective-C compilation requires an explicit numeric IPHONEOS_DEPLOYMENT_TARGET; received ${JSON.stringify(target.deploymentTarget)}. Inputs: ${receipt}`,
383
+ )
384
+ }
385
+ const minimum =
386
+ Number(version[1]) * 10_000 +
387
+ Number(version[2] ?? 0) * 100 +
388
+ Number(version[3] ?? 0)
389
+ return minimum
390
+ }
391
+ if (targets.length === 0)
392
+ return finish(
393
+ 'missing-target',
394
+ 'Objective-C preparation requires an original implementation target',
395
+ )
396
+ const minimums = targets.map(minimumFor)
397
+ if (peers) {
398
+ try {
399
+ metadataFiles = compileObjcPeerMetadata({
400
+ classes: peers,
401
+ work,
402
+ headerCache: path.join(cacheDir(), 'swift-standins'),
403
+ toolchainBin: toolchain.toolchainBin,
404
+ sysroot: sdk.sysroot,
405
+ minimum: minimumFor({
406
+ name: app.moduleName,
407
+ deploymentTarget: app.iosDeploymentTarget,
408
+ }),
409
+ descriptor,
410
+ }).files
411
+ } catch (error) {
412
+ if (error instanceof ObjcPeerMetadataError)
413
+ return finish(
414
+ error.reusable ? 'metadata-failed' : 'metadata-interrupted',
415
+ error.message,
416
+ error.reusable,
417
+ error.files,
418
+ )
419
+ throw error
420
+ }
421
+ }
422
+ const failures: string[] = []
423
+ let interrupted = false
424
+ compile: for (const [index, target] of targets.entries()) {
425
+ const minimum = minimums[index]!
426
+ for (const [unit, file] of target.files.entries()) {
427
+ const output = path.join(work, `${index}-${unit}.o`)
428
+ const cxx = /\.(mm|cc|cpp|cxx)$/.test(file)
429
+ const objc = /\.mm?$/.test(file)
430
+ const flags = [
431
+ ...target.flags.filter(
432
+ (flag) =>
433
+ (!cxx || !flag.startsWith('-std=')) && (objc || flag !== '-fobjc-arc'),
434
+ ),
435
+ ...(cxx ? target.cxxFlags : []),
436
+ ...(target.fileFlags[file] ?? []),
437
+ ].map((flag, index, flags) => {
438
+ if (
439
+ ['-I', '-F', '-iquote', '-isystem', '-include'].includes(
440
+ flags[index - 1] ?? '',
441
+ )
442
+ )
443
+ return staged(flag)
444
+ const include = /^(-I|-F)(\/.*)$/.exec(flag)
445
+ return include ? `${include[1]}${staged(include[2]!)}` : flag
446
+ })
447
+ const args = [
448
+ '--target=wasm32-unknown-wasip1',
449
+ `--sysroot=${sdk.sysroot}`,
450
+ '-fwasm-exceptions',
451
+ '-fexceptions',
452
+ '-D_WASI_EMULATED_SIGNAL',
453
+ '-D_WASI_EMULATED_MMAN',
454
+ `-D__ENVIRONMENT_IPHONE_OS_VERSION_MIN_REQUIRED__=${minimum}`,
455
+ `-D__IPHONE_OS_VERSION_MIN_REQUIRED=${minimum}`,
456
+ ...(objc
457
+ ? ['-fobjc-runtime=gnustep-2.2', '-fobjc-exceptions', '-fblocks']
458
+ : []),
459
+ '-F',
460
+ path.join(headers, 'System/Library/Frameworks'),
461
+ // installed libc and objc runtime headers own the target ABI.
462
+ '-idirafter',
463
+ path.join(headers, 'usr/include'),
464
+ ...target.includes.flatMap((include) => ['-I', staged(include)]),
465
+ ...target.frameworks.flatMap((framework) => ['-F', staged(framework)]),
466
+ ...modulemaps,
467
+ `-fmodule-name=${swiftTargetModuleName(target.name)}`,
468
+ `-fmodules-cache-path=${path.join(work, 'module-cache')}`,
469
+ ...flags,
470
+ ...(target.prefix ? ['-include', staged(target.prefix)] : []),
471
+ '-Os',
472
+ '-c',
473
+ staged(file),
474
+ '-o',
475
+ output,
476
+ ]
477
+ const result = spawnSync(
478
+ path.join(toolchain.toolchainBin, cxx ? 'clang++' : 'clang'),
479
+ args,
480
+ {
481
+ cwd: work,
482
+ encoding: 'utf8',
483
+ stdio: ['ignore', 'pipe', 'pipe', descriptor],
484
+ env: swiftEnvironment(),
485
+ timeout: 120_000,
486
+ maxBuffer: 16 * 1024 * 1024,
487
+ },
488
+ )
489
+ const diagnostics = `${result.stdout ?? ''}${result.stderr ?? ''}${result.error ? `\n${result.error.message}` : ''}${result.signal ? `\nClang terminated by ${result.signal}` : ''}`
490
+ fs.writeFileSync(path.join(work, `${index}-${unit}.log`), diagnostics)
491
+ commands.push({
492
+ target: target.name,
493
+ source: file,
494
+ args,
495
+ status: result.status,
496
+ signal: result.signal,
497
+ ...(result.error ? { error: result.error.message } : {}),
498
+ ...(!result.error && !result.signal && result.status === 0
499
+ ? { object: digest(fs.readFileSync(output)) }
500
+ : {}),
501
+ })
502
+ if (result.error || result.signal || result.status !== 0) {
503
+ failures.push(
504
+ `${target.name}: ${file}\n${diagnostics.trimEnd() || `Clang exited with status ${result.status}`}`,
505
+ )
506
+ // clang's driver also returns 1 when its frontend crashes or cannot write.
507
+ if (
508
+ result.error ||
509
+ result.signal ||
510
+ result.status !== 1 ||
511
+ /^(?:PLEASE submit a bug report|LLVM ERROR:|(?:clang(?:\+\+)?(?:-\d+)?: )?(?:fatal )?error: (?:error in backend:|unable to (?:execute command|open output file|make temporary file)|.*command failed))/m.test(
512
+ result.stderr ?? '',
513
+ )
514
+ ) {
515
+ interrupted = true
516
+ break compile
517
+ }
518
+ }
519
+ save('compiling')
520
+ }
521
+ }
522
+ if (failures.length > 0) {
523
+ const selected = targets.reduce((count, target) => count + target.files.length, 0)
524
+ const successes = commands.filter((command) => command.object !== undefined).length
525
+ return finish(
526
+ interrupted ? 'compile-interrupted' : 'compile-failed',
527
+ [
528
+ interrupted
529
+ ? `Objective-C implementation compilation interrupted after ${commands.length} of ${selected} translation units; this attempt will not be reused.`
530
+ : `Objective-C implementation compilation failed in ${failures.length} of ${selected} translation units.`,
531
+ `${successes} successful object${successes === 1 ? '' : 's'} retained.`,
532
+ ...failures,
533
+ `Original inputs, compiler commands and diagnostics: ${receipt}`,
534
+ ].join('\n\n'),
535
+ !interrupted,
536
+ )
537
+ }
538
+ complete(
539
+ 'prepared',
540
+ 'Original Objective-C objects prepared; framework linkage remains unqualified.',
541
+ true,
542
+ )
543
+ return preparation()
544
+ } finally {
545
+ fs.closeSync(descriptor)
546
+ }
547
+ }