peachsim 0.1.730 → 0.1.746

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (107) hide show
  1. package/cli/bridge-flow-runner.ts +15 -2
  2. package/cli/commands/control.ts +13 -3
  3. package/cli/commands/desktop.ts +1 -0
  4. package/cli/commands/electron.ts +12 -8
  5. package/cli/commands/flow.ts +1 -3
  6. package/cli/commands/install-desktop.ts +105 -66
  7. package/cli/commands/logout.ts +5 -1
  8. package/cli/commands/no-bridge-hint.ts +2 -2
  9. package/cli/commands/swift.ts +26 -9
  10. package/cli/desktop-companion.ts +36 -9
  11. package/cli/drivers/desktop.ts +65 -0
  12. package/cli/drivers/electron.ts +4 -66
  13. package/cli/drivers/index.ts +1 -0
  14. package/cli/drivers/playwright-sim-host.ts +2 -0
  15. package/cli/drivers/playwright.ts +3 -3
  16. package/cli/drivers/registry.ts +7 -2
  17. package/cli/drivers/types.ts +4 -3
  18. package/cli/maestro-js.ts +10 -0
  19. package/cli/outbound-endpoints.ts +2 -2
  20. package/dist-lib/agent-daemon-client.cjs +1 -1
  21. package/dist-lib/agent-events.cjs +1 -1
  22. package/dist-lib/agent-identity.cjs +1 -1
  23. package/dist-lib/agent-sessions.cjs +1 -1
  24. package/dist-lib/attached-projects.cjs +1 -1
  25. package/dist-lib/auth/shared-session.cjs +39 -9
  26. package/dist-lib/backend-origin.cjs +1 -1
  27. package/dist-lib/beta.cjs +1 -1
  28. package/dist-lib/beta.mjs +1 -1
  29. package/dist-lib/bridge-constants.cjs +1 -1
  30. package/dist-lib/bridge-contract-input.cjs +1 -1
  31. package/dist-lib/bridge-contract-input.mjs +1 -1
  32. package/dist-lib/bridge-contract.cjs +1 -1
  33. package/dist-lib/bridge-contract.mjs +1 -1
  34. package/dist-lib/capture-contract.cjs +13 -19
  35. package/dist-lib/capture-contract.mjs +13 -19
  36. package/dist-lib/cli-constants.cjs +1 -1
  37. package/dist-lib/cloud-contract.cjs +1 -1
  38. package/dist-lib/cloud-contract.mjs +1 -1
  39. package/dist-lib/cloud-test-args.cjs +1 -1
  40. package/dist-lib/cloud-test-args.mjs +1 -1
  41. package/dist-lib/cloud.cjs +1 -1
  42. package/dist-lib/cloud.mjs +1 -1
  43. package/dist-lib/config.cjs +1 -1
  44. package/dist-lib/detox/index.cjs +117 -11
  45. package/dist-lib/dev-bundle-resolution.cjs +1 -1
  46. package/dist-lib/home-paths.cjs +32 -1
  47. package/dist-lib/host/bridge-host.cjs +1741 -540
  48. package/dist-lib/host/fetch-proxy-handler.cjs +1 -1
  49. package/dist-lib/host/fetch-proxy-overrides.cjs +1 -1
  50. package/dist-lib/host/fetch-proxy-overrides.mjs +1 -1
  51. package/dist-lib/host/replacement-module-handler.cjs +1 -1
  52. package/dist-lib/host/websocket-proxy.cjs +1 -1
  53. package/dist-lib/index.cjs +17 -22
  54. package/dist-lib/jump-to-source-babel.cjs +1 -1
  55. package/dist-lib/jump-to-source-native.cjs +1 -1
  56. package/dist-lib/kotlin-host.cjs +1 -1
  57. package/dist-lib/menu.cjs +1 -1
  58. package/dist-lib/menu.mjs +1 -1
  59. package/dist-lib/metro-fingerprint-registry.cjs +1 -1
  60. package/dist-lib/metro-fingerprint-registry.mjs +1 -1
  61. package/dist-lib/metro-production-bundle.cjs +1 -1
  62. package/dist-lib/metro-production-bundle.mjs +1 -1
  63. package/dist-lib/metro.cjs +1 -1
  64. package/dist-lib/native-app-identity.cjs +1 -1
  65. package/dist-lib/native-app-identity.mjs +1 -1
  66. package/dist-lib/native-firebase-metadata.cjs +1 -1
  67. package/dist-lib/native-firebase-metadata.mjs +1 -1
  68. package/dist-lib/plist.cjs +1 -1
  69. package/dist-lib/plist.mjs +1 -1
  70. package/dist-lib/profiles.cjs +1 -1
  71. package/dist-lib/public-brand.cjs +1 -1
  72. package/dist-lib/react-native-host-modules.cjs +1 -1
  73. package/dist-lib/react-native-host-modules.mjs +1 -1
  74. package/dist-lib/render-mode.cjs +1 -1
  75. package/dist-lib/scripts/dev-server-scanner.cjs +1 -1
  76. package/dist-lib/sdk.cjs +2 -1
  77. package/dist-lib/sdk.mjs +2 -1
  78. package/dist-lib/skills.cjs +2431 -1075
  79. package/dist-lib/swift-compile.cjs +374 -65
  80. package/dist-lib/swift-compile.mjs +369 -66
  81. package/dist-lib/swift-package.cjs +146 -9
  82. package/dist-lib/swift-package.mjs +144 -9
  83. package/dist-lib/swift-submit.cjs +2 -2
  84. package/dist-lib/swift-submit.mjs +2 -2
  85. package/dist-lib/swift-toolchain.cjs +1 -1
  86. package/dist-lib/swift.cjs +1 -1
  87. package/dist-lib/vite-swift.cjs +1690 -233
  88. package/dist-lib/vite.cjs +4 -4
  89. package/package.json +1 -1
  90. package/skills/contrast/SKILL.md +1 -1
  91. package/src/auth/shared-session.ts +45 -9
  92. package/src/bridge-constants.ts +7 -7
  93. package/src/capture-contract.ts +18 -33
  94. package/src/desktop-host-delivery.ts +81 -0
  95. package/src/home-paths.ts +30 -0
  96. package/src/host/bridge-host.ts +11 -6
  97. package/src/native-seam-manifest.ts +0 -11
  98. package/src/sim-client.ts +1 -0
  99. package/src/swift-compile.ts +479 -76
  100. package/src/swift-distribution.lock.json +11 -11
  101. package/src/swift-host.ts +338 -45
  102. package/src/swift-package.ts +204 -19
  103. package/src/swift-remote-packages.ts +255 -0
  104. package/src/swift-submit.ts +4 -1
  105. package/src/vite-plugin-one.ts +2 -2
  106. package/src/vite-plugin.ts +29 -9
  107. package/src/xcode-project.ts +612 -0
@@ -1,4 +1,4 @@
1
- import { execFile } from 'node:child_process'
1
+ import { execFile, execFileSync } from 'node:child_process'
2
2
  import { createHash } from 'node:crypto'
3
3
  import {
4
4
  cpSync,
@@ -38,7 +38,10 @@ const WASM_TRIPLE = 'wasm32-unknown-wasip1'
38
38
  // binaryen's own cap holds it to 4 threads (400%, 26 -> 32 s); swiftpm's jobs
39
39
  // take half the cores, as the fixture build does.
40
40
  const cores = os.availableParallelism()
41
- const BUILD_ENV = { ...process.env, BINARYEN_CORES: String(Math.min(4, cores)) }
41
+ const BUILD_ENV = {
42
+ ...process.env,
43
+ BINARYEN_CORES: String(Math.min(4, cores)),
44
+ }
42
45
  const BUILD_JOBS = String(Math.max(1, Math.floor(cores / 2)))
43
46
 
44
47
  export interface SwiftCompileInput {
@@ -121,7 +124,9 @@ export function swiftModuleInputFiles(root: string): string[] {
121
124
  'toolchain.json',
122
125
  ]
123
126
  const walk = (dir: string) => {
124
- for (const entry of readdirSync(path.join(root, dir), { withFileTypes: true })) {
127
+ for (const entry of readdirSync(path.join(root, dir), {
128
+ withFileTypes: true,
129
+ })) {
125
130
  const relative = `${dir}/${entry.name}`
126
131
  if (entry.isDirectory()) walk(relative)
127
132
  else if (/\.(swift|c|cpp|h)$/.test(entry.name)) files.push(relative)
@@ -247,6 +252,9 @@ const OPTIONAL_FRAMEWORK_DEPENDENCIES: Record<string, string[]> = {
247
252
  CryptoKit: [],
248
253
  CommonCrypto: [],
249
254
  CoreText: [],
255
+ Compression: ['PeachCodec'],
256
+ zlib: ['PeachCodec'],
257
+ PeachCodec: [],
250
258
  Security: ['CryptoKit'],
251
259
  TikTokBusinessSDK: [],
252
260
  nSure: [],
@@ -258,6 +266,101 @@ const OPTIONAL_FRAMEWORK_DEPENDENCIES: Record<string, string[]> = {
258
266
  }
259
267
  const OPTIONAL_FRAMEWORKS = new Set(Object.keys(OPTIONAL_FRAMEWORK_DEPENDENCIES))
260
268
 
269
+ // an import may carry attributes (`@_exported`, `@preconcurrency`) and a
270
+ // declaration kind (`import struct Nuke.ImageRequest`).
271
+ const SWIFT_IMPORT =
272
+ /^\s*(?:@\w+(?:\([^)]*\))?\s+)*import\s+(?:(?:typealias|struct|class|enum|protocol|let|var|func)\s+)?([A-Za-z_][A-Za-z0-9_]*)/
273
+
274
+ /**
275
+ * the modules a source imports, in order. `unconditional` keeps only imports
276
+ * outside every `#if`: a conditional one may compile out (`os(macOS)`,
277
+ * `canImport`), so only an unconditional import is certainly required.
278
+ */
279
+ export function swiftImportNames(contents: string, unconditional = false): string[] {
280
+ const names: string[] = []
281
+ let depth = 0
282
+ for (const line of contents.split('\n')) {
283
+ const directive = /^\s*#(if|endif)\b/.exec(line)?.[1]
284
+ if (directive === 'if') depth++
285
+ else if (directive === 'endif') depth = Math.max(0, depth - 1)
286
+ if (unconditional && depth > 0) continue
287
+ const name = SWIFT_IMPORT.exec(line)?.[1]
288
+ if (name) names.push(name)
289
+ }
290
+ return names
291
+ }
292
+
293
+ /**
294
+ * the modules peach itself provides at `moduleRoot`: a distribution lists
295
+ * them, a checkout's manifest declares them as targets.
296
+ */
297
+ export function swiftPeachModules(moduleRoot: string): string[] {
298
+ const distribution = swiftDistributionAt(moduleRoot)
299
+ return distribution
300
+ ? distribution.modules
301
+ : [
302
+ ...readFileSync(path.join(moduleRoot, 'Package.swift'), 'utf8').matchAll(
303
+ /\.(?:target|systemLibrary)\(\s*name:\s*"([^"]+)"/g,
304
+ ),
305
+ ].map((match) => match[1]!)
306
+ }
307
+
308
+ const availableModules = new Map<string, Set<string>>()
309
+
310
+ /**
311
+ * every module a source compiled against `moduleRoot` can import: Peach's own
312
+ * and the wasm SDK's swift modules and top-level clang modules.
313
+ */
314
+ export function swiftAvailableModules(
315
+ moduleRoot: string,
316
+ toolchainBin: string,
317
+ ): Set<string> {
318
+ const sdk = swiftModuleSdk(moduleRoot).wasmSdkId
319
+ const key = `${moduleRoot}\0${sdk}`
320
+ const cached = availableModules.get(key)
321
+ if (cached) return cached
322
+ const modules = new Set(swiftPeachModules(moduleRoot))
323
+ const configuration = execFileSync(
324
+ path.join(toolchainBin, 'swift'),
325
+ ['sdk', 'configure', '--show-configuration', sdk, 'wasm32-unknown-wasip1'],
326
+ { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] },
327
+ )
328
+ const resources = /^swiftResourcesPath:\s*(.+)$/m.exec(configuration)?.[1]?.trim()
329
+ if (!resources) throw new Error(`swift sdk ${sdk} reports no swiftResourcesPath`)
330
+ for (const entry of readdirSync(path.join(resources, 'wasi'))) {
331
+ if (entry.endsWith('.swiftmodule'))
332
+ modules.add(entry.slice(0, -'.swiftmodule'.length))
333
+ }
334
+ for (const entry of readdirSync(resources)) {
335
+ const map = path.join(resources, entry, 'module.modulemap')
336
+ if (!existsSync(map)) continue
337
+ for (const match of readFileSync(map, 'utf8').matchAll(/^module\s+([A-Za-z_]\w*)/gm))
338
+ modules.add(match[1]!)
339
+ }
340
+ availableModules.set(key, modules)
341
+ return modules
342
+ }
343
+
344
+ /**
345
+ * the modules the sources import outside any `#if` that nothing available
346
+ * provides, each with the files importing it. the compiler stops at the first
347
+ * missing module; this names all of them at once.
348
+ */
349
+ export function missingSwiftModules(
350
+ files: Record<string, string>,
351
+ available: ReadonlySet<string>,
352
+ ): Map<string, string[]> {
353
+ const missing = new Map<string, string[]>()
354
+ for (const [file, contents] of Object.entries(files)) {
355
+ if (!file.endsWith('.swift') || file === 'Package.swift') continue
356
+ for (const name of new Set(swiftImportNames(contents, true))) {
357
+ if (available.has(name)) continue
358
+ missing.set(name, [...(missing.get(name) ?? []), file])
359
+ }
360
+ }
361
+ return new Map([...missing].sort(([left], [right]) => left.localeCompare(right)))
362
+ }
363
+
261
364
  export function swiftTargetDependencies(
262
365
  files: Record<string, string>,
263
366
  targets: Pick<SwiftPackageTarget, 'name' | 'path'>[],
@@ -279,12 +382,8 @@ export function swiftTargetDependencies(
279
382
  )
280
383
  )
281
384
  continue
282
- // an import may carry attributes (`@_exported`, `@preconcurrency`) and a
283
- // declaration kind (`import struct Nuke.ImageRequest`).
284
- for (const match of contents.matchAll(
285
- /^\s*(?:@\w+(?:\([^)]*\))?\s+)*import\s+(?:(?:typealias|struct|class|enum|protocol|let|var|func)\s+)?([A-Za-z_][A-Za-z0-9_]*)/gm,
286
- )) {
287
- if (names.has(match[1]) && match[1] !== target.name) deps.add(match[1])
385
+ for (const name of swiftImportNames(contents)) {
386
+ if (names.has(name) && name !== target.name) deps.add(name)
288
387
  }
289
388
  }
290
389
  siblings.set(target.name, [...deps].sort())
@@ -299,24 +398,28 @@ const SPRITEKIT_PRODUCT = '.product(name: "SpriteKit", package: "sootsim-swift")
299
398
  const importsSpriteKit = (files: Record<string, string>): boolean =>
300
399
  Object.entries(files).some(
301
400
  ([file, contents]) =>
302
- file.endsWith('.swift') &&
303
- /^\s*(?:@\w+(?:\([^)]*\))?\s+)*import\s+(?:(?:typealias|struct|class|enum|protocol|let|var|func)\s+)?SpriteKit\b/m.test(
304
- contents,
305
- ),
401
+ file.endsWith('.swift') && swiftImportNames(contents).includes('SpriteKit'),
306
402
  )
307
403
  // every iOS source sees through Foundation what darwin's Foundation exports:
308
404
  // PeachObjC supplies the ObjectiveC module's selectors, Dispatch Foundation's
309
405
  // Darwin queue exports, and FoundationNetworking (re-exporting PeachFoundation)
310
406
  // URLSession, NotificationCenter, OperationQueue and the CoreFoundation types.
311
- // these modules export only names iOS has; Peach's host plumbing is `package`
312
- // or lives in PeachJSON, which none of them re-exports. scripts/contrast-app-Package.swift and
407
+ // WASILibc is the platform libc the way Darwin's headers are on iOS: its
408
+ // math.h answers the free round Kingfisher's SizeExtensions reaches, and its
409
+ // pthread mutexes are what a Foundation-only source reaches there
410
+ // (SwiftSoup's Mutex). pthread.h is not in the overlay's module: the sdk's
411
+ // wasi-libc.modulemap (swift_static/wasi/wasm32) carries it as the separate
412
+ // top-level module wasi_pthread, which nothing re-exports, so the flags name
413
+ // both. these modules export only names iOS has, WASILibc's wasi-only names
414
+ // aside; Peach's host plumbing is `package` or lives in PeachJSON, which none
415
+ // of them re-exports. scripts/contrast-app-Package.swift and
313
416
  // example/Package.swift carry the same flags.
314
417
  const FOUNDATION_IMPLICIT_FLAGS =
315
- ', "-Xfrontend", "-import-module", "-Xfrontend", "PeachObjC", "-Xfrontend", "-import-module", "-Xfrontend", "Dispatch", "-Xfrontend", "-import-module", "-Xfrontend", "FoundationNetworking"'
418
+ ', "-Xfrontend", "-import-module", "-Xfrontend", "PeachObjC", "-Xfrontend", "-import-module", "-Xfrontend", "Dispatch", "-Xfrontend", "-import-module", "-Xfrontend", "FoundationNetworking", "-Xfrontend", "-import-module", "-Xfrontend", "WASILibc", "-Xfrontend", "-import-module", "-Xfrontend", "wasi_pthread"'
316
419
  const ONE_IMPLICIT_FLAGS = ', "-Xfrontend", "-import-module", "-Xfrontend", "One"'
317
420
 
318
421
  /** bump with any change to the emitted multi-target manifest text. */
319
- export const MULTI_MANIFEST_VERSION = 10
422
+ export const MULTI_MANIFEST_VERSION = 11
320
423
 
321
424
  export function swiftArtifactHash(
322
425
  input: SwiftCompileInput,
@@ -324,6 +427,9 @@ export function swiftArtifactHash(
324
427
  moduleRoot: string,
325
428
  ): string {
326
429
  const hash = createHash('sha256')
430
+ // v16: overrides of @objc extension members rename to __peach_ovr_
431
+ // v15: Foundation-only sources see the platform libc (WASILibc, including
432
+ // math round) and its pthread mutexes (wasi_pthread)
327
433
  // v14: AnyObject doubleValue lowers to the typed _objcNumber getter
328
434
  // v13: implicit target resources synthesize Bundle.module
329
435
  // v12: overrides in an extension of a same-file class lift into the class
@@ -334,7 +440,7 @@ export function swiftArtifactHash(
334
440
  // v6: app and scene delegate classes compile final
335
441
  // (v5: a target declaring resources gets SwiftPM's Bundle.module accessor;
336
442
  // v4: sources compile through swiftSourceAsIOS)
337
- hash.update(`swift-compile/v14\n${release}\n`)
443
+ hash.update(`swift-compile/v16\n${release}\n`)
338
444
  if (input.oneModule) hash.update('one-module\n')
339
445
  hash.update(swiftModuleDigest(moduleRoot))
340
446
  for (const file of Object.keys(input.files).sort()) {
@@ -560,12 +666,17 @@ const CLASS_BASE =
560
666
  const FRAME_INIT = /^override(?=\s+(?:(?:public|open|internal)\s+)?init\s*\(\s*frame\s*:)/
561
667
  // uikit's members are @objc, so an app may override one from an extension;
562
668
  // swift without an objc runtime rejects that. an `override` of an @objc
563
- // member (overridesObjC below) that is a direct member of an extension of a
669
+ // member (overrideKind below) that is a direct member of an extension of a
564
670
  // class declared in the same file is lifted: the extension keeps it as `__peach_ext_<name>` with `override`
565
671
  // blanked, and the class body gains, on its opening brace's line, an
566
672
  // override that forwards to it, so lines keep their numbers and the
567
- // override takes its place in the class as an objc one does. a class in
568
- // another file, a property with a setter or observers, a subscript and a
673
+ // override takes its place in the class as an objc one does. a member the
674
+ // superclass declares in an extension instead of its class body (an @objc
675
+ // one on iOS) cannot keep its name without an objc runtime at all: any
676
+ // same-name member fails, with `override`, @nonobjc or the @ObjC macro's
677
+ // same-named static accessors alike. so the override drops `override` and
678
+ // takes `__peach_ovr_<name>`, keeping its body and lines. a member from
679
+ // another module, a property with a setter or observers, a subscript and a
569
680
  // variadic parameter stay as written and fail to compile as before.
570
681
  // an Apple framework class: an ObjC prefix and a capital
571
682
  const APPLE_CLASS = /^(?:UI|NS|CA|SK|WK|MK|AV|PK|CL|GK|PH|SF|AS|QL)[A-Z]/
@@ -609,8 +720,108 @@ function forwardedArguments(parameters: string): string | null {
609
720
  return args.join(', ')
610
721
  }
611
722
 
612
- function liftExtensionOverrides(source: string): string {
723
+ // the offset just past the brace that closes the one at `open`
724
+ function closingBrace(source: string, tokens: number[], open: number): number {
725
+ let depth = 0
726
+ for (const at of tokens) {
727
+ if (at < open) continue
728
+ if (source[at] === '{') depth++
729
+ else if (source[at] === '}' && --depth === 0) return at + 1
730
+ }
731
+ return source.length
732
+ }
733
+
734
+ // every @objc instance member extensions declare, by extended type: the
735
+ // module-wide view one file's lowering cannot see. private, fileprivate,
736
+ // static and class members are never overridable and stay out.
737
+ function scanObjCExtensionMembers(
738
+ source: string,
739
+ tokens: number[],
740
+ records: { type: string; open: number; objcMembers: boolean }[],
741
+ ): Map<string, Set<string>> {
742
+ const masked = swiftCodeMask(source)
743
+ const found = new Map<string, Set<string>>()
744
+ const member = /\b(func|var)\s+([A-Za-z_]\w*)/g
745
+ for (const record of records) {
746
+ const close = closingBrace(source, tokens, record.open)
747
+ const body = masked.slice(record.open, close)
748
+ member.lastIndex = 0
749
+ for (let match = member.exec(body); match; match = member.exec(body)) {
750
+ const at = record.open + match.index + match[0].indexOf(match[1]!)
751
+ let depth = 0
752
+ for (const token of tokens) {
753
+ if (token <= record.open) continue
754
+ if (token >= at) break
755
+ if (source[token] === '{') depth++
756
+ else if (source[token] === '}') depth--
757
+ }
758
+ if (depth > 0) continue
759
+ const head = masked.slice(record.open, at)
760
+ const bound = Math.max(
761
+ head.lastIndexOf(';'),
762
+ head.lastIndexOf('{'),
763
+ head.lastIndexOf('}'),
764
+ )
765
+ const prefix = head.slice(bound + 1)
766
+ if (
767
+ /(?:^|[^A-Za-z0-9_$])(?:private|fileprivate|static|class)(?:[^A-Za-z0-9_$]|$)/.test(
768
+ prefix,
769
+ )
770
+ )
771
+ continue
772
+ if (!/@objc\b/.test(prefix) && !/@IBAction\b/.test(prefix) && !record.objcMembers)
773
+ continue
774
+ const members = found.get(record.type) ?? new Set<string>()
775
+ members.add(match[2]!)
776
+ found.set(record.type, members)
777
+ }
778
+ }
779
+ return found
780
+ }
781
+
782
+ /** every @objc instance member extensions declare across `sources`, by
783
+ * extended type, for a lowering pass that sees one file at a time. */
784
+ export function objcExtensionMemberIndex(
785
+ sources: Iterable<string>,
786
+ ): Map<string, Set<string>> {
787
+ const index = new Map<string, Set<string>>()
788
+ for (const source of sources) {
789
+ const { tokens } = swiftCodeScan(source)
790
+ const masked = swiftCodeMask(source)
791
+ const records: { type: string; open: number; objcMembers: boolean }[] = []
792
+ let pending: { type: string; objcMembers: boolean } | null = null
793
+ for (const at of tokens) {
794
+ const rest = source.slice(at, at + 600)
795
+ if (rest.startsWith('{')) {
796
+ if (pending) records.push({ ...pending, open: at })
797
+ pending = null
798
+ continue
799
+ }
800
+ if (rest.startsWith('}')) continue
801
+ const extended = EXTENSION_DECL.exec(rest)
802
+ if (extended) {
803
+ const lines = source.lastIndexOf('\n', source.lastIndexOf('\n', at - 1) - 1) + 1
804
+ pending = {
805
+ type: extended[1]!.split('.').pop()!,
806
+ objcMembers: /@objcMembers\b/.test(masked.slice(lines, at)),
807
+ }
808
+ }
809
+ }
810
+ for (const [type, members] of scanObjCExtensionMembers(source, tokens, records)) {
811
+ const into = index.get(type) ?? new Set<string>()
812
+ for (const member of members) into.add(member)
813
+ index.set(type, into)
814
+ }
815
+ }
816
+ return index
817
+ }
818
+
819
+ function liftExtensionOverrides(
820
+ source: string,
821
+ extraObjCExtensions?: Map<string, Set<string>>,
822
+ ): string {
613
823
  const { tokens } = swiftCodeScan(source)
824
+ const masked = swiftCodeMask(source)
614
825
  type Frame = { kind: 'class' | 'extension' | 'other'; name: string }
615
826
  const stack: Frame[] = []
616
827
  let pending: Frame | null = null
@@ -620,22 +831,21 @@ function liftExtensionOverrides(source: string): string {
620
831
  >()
621
832
  let declaredBase: string | null = null
622
833
  let declaredObjCMembers = false
834
+ const extensions: { type: string; open: number; objcMembers: boolean }[] = []
835
+ let declaredExtObjCMembers = false
623
836
  const lifted: {
624
837
  type: string
625
838
  member: string
626
- stub: string
839
+ at: number
840
+ modifiers: string[]
841
+ decl: string
842
+ forward: string
843
+ nameAt: number
627
844
  edits: [number, number, string][]
628
845
  }[] = []
846
+ const overrides: { type: string; member: string; at: number; nameAt: number }[] = []
629
847
  // the offset just past the brace that closes the one at `open`
630
- const closing = (open: number): number => {
631
- let depth = 0
632
- for (const at of tokens) {
633
- if (at < open) continue
634
- if (source[at] === '{') depth++
635
- else if (source[at] === '}' && --depth === 0) return at + 1
636
- }
637
- return source.length
638
- }
848
+ const closing = (open: number): number => closingBrace(source, tokens, open)
639
849
  for (const at of tokens) {
640
850
  const rest = source.slice(at, at + 600)
641
851
  if (rest.startsWith('{')) {
@@ -646,6 +856,12 @@ function liftExtensionOverrides(source: string): string {
646
856
  base: declaredBase,
647
857
  objcMembers: declaredObjCMembers,
648
858
  })
859
+ if (frame.kind === 'extension')
860
+ extensions.push({
861
+ type: frame.name,
862
+ open: at,
863
+ objcMembers: declaredExtObjCMembers,
864
+ })
649
865
  stack.push(frame)
650
866
  pending = null
651
867
  continue
@@ -665,12 +881,47 @@ function liftExtensionOverrides(source: string): string {
665
881
  const extended = EXTENSION_DECL.exec(rest)
666
882
  if (extended) {
667
883
  pending = { kind: 'extension', name: extended[1]!.split('.').pop()! }
884
+ const lines = source.lastIndexOf('\n', source.lastIndexOf('\n', at - 1) - 1) + 1
885
+ declaredExtObjCMembers = /@objcMembers\b/.test(masked.slice(lines, at))
668
886
  continue
669
887
  }
670
888
  const top = stack.at(-1)
671
- if (!rest.startsWith('override') || top?.kind !== 'extension' || pending) continue
889
+ if (!rest.startsWith('override') || pending) continue
672
890
  const line = source.slice(source.lastIndexOf('\n', at - 1) + 1, at)
673
891
  const modifiers = (` ${line} `.match(MODIFIERS) ?? []).map((word) => word.trim())
892
+ if (top?.kind === 'class') {
893
+ let member: string | undefined
894
+ let nameAt = 0
895
+ const direct = OVERRIDE_FUNC.exec(rest)
896
+ if (direct) {
897
+ member = direct[2]
898
+ nameAt =
899
+ at +
900
+ rest.indexOf(
901
+ member!,
902
+ rest.indexOf('func', 'override'.length + direct[1]!.length) + 4,
903
+ )
904
+ } else {
905
+ const property = OVERRIDE_VAR.exec(rest)
906
+ if (property) {
907
+ const open = at + property[0].length - 1
908
+ if (!/\b(?:set|willSet|didSet)\b/.test(source.slice(open, closing(open)))) {
909
+ member = property[2]
910
+ nameAt = at + rest.indexOf(member!, rest.indexOf('var'))
911
+ }
912
+ }
913
+ }
914
+ // a private override is invisible to subclasses on iOS too, so it
915
+ // stays to fail there rather than lowering into a shadowing member.
916
+ if (
917
+ member !== undefined &&
918
+ !modifiers.includes('private') &&
919
+ !modifiers.includes('fileprivate')
920
+ )
921
+ overrides.push({ type: top.name, member, at, nameAt })
922
+ continue
923
+ }
924
+ if (top?.kind !== 'extension') continue
674
925
  const func = OVERRIDE_FUNC.exec(rest)
675
926
  if (func) {
676
927
  const name = func[2]!
@@ -692,21 +943,20 @@ function liftExtensionOverrides(source: string): string {
692
943
  (/\basync\b/.test(clause) ? 'await ' : '') +
693
944
  `__peach_ext_${name}(${args})`
694
945
  const signature = `func ${name}${func[3] ?? ''}${source.slice(open, close + 1)}${clause ? ` ${clause}` : ''}`
946
+ const nameAt =
947
+ at +
948
+ rest.indexOf(name, rest.indexOf('func', 'override'.length + func[1]!.length) + 4)
695
949
  lifted.push({
696
950
  type: top.name,
697
951
  member: name,
698
- stub: `${[...modifiers, 'override'].join(' ')} ${signature} { ${call} };`,
952
+ at,
953
+ modifiers,
954
+ decl: signature,
955
+ forward: `{ ${call} };`,
956
+ nameAt,
699
957
  edits: [
700
958
  [at, 'override'.length, ' '.repeat('override'.length)],
701
- [
702
- at +
703
- rest.indexOf(
704
- name,
705
- rest.indexOf('func', 'override'.length + func[1]!.length) + 4,
706
- ),
707
- 0,
708
- '__peach_ext_',
709
- ],
959
+ [nameAt, 0, '__peach_ext_'],
710
960
  ],
711
961
  })
712
962
  continue
@@ -716,45 +966,96 @@ function liftExtensionOverrides(source: string): string {
716
966
  const open = at + property[0].length - 1
717
967
  if (/\b(?:set|willSet|didSet)\b/.test(source.slice(open, closing(open)))) continue
718
968
  const name = property[2]!
969
+ const nameAt = at + rest.indexOf(name, rest.indexOf('var'))
719
970
  lifted.push({
720
971
  type: top.name,
721
972
  member: name,
722
- stub: `${[...modifiers, 'override'].join(' ')} var ${name}: ${property[3]!.trim()} { __peach_ext_${name} };`,
973
+ at,
974
+ modifiers,
975
+ decl: `var ${name}: ${property[3]!.trim()}`,
976
+ forward: `{ __peach_ext_${name} };`,
977
+ nameAt,
723
978
  edits: [
724
979
  [at, 'override'.length, ' '.repeat('override'.length)],
725
- [at + rest.indexOf(name, rest.indexOf('var')), 0, '__peach_ext_'],
980
+ [nameAt, 0, '__peach_ext_'],
726
981
  ],
727
982
  })
728
983
  }
729
984
  }
730
- // whether the member a class inherits is @objc, as an extension override
731
- // needs on iOS: an Apple framework class's members are, and an app class
732
- // in this file declares it with @objc or under @objcMembers. a base this
733
- // file does not declare, or a plain Swift member, is not, and the override
734
- // stays to fail as it does on iOS.
735
- const overridesObjC = (type: string, member: string): boolean => {
985
+ // how the member a class inherits is declared, as an override needs on
986
+ // iOS: `apple` members and `objc` ones (declared with @objc or under
987
+ // @objcMembers in a class body in this file) take `override` in the class
988
+ // as they do on iOS. `ext` is declared with @objc in an extension of a
989
+ // base here or elsewhere in the module: iOS accepts the override, but
990
+ // without an objc runtime no same-name member compiles, so the override
991
+ // drops `override` and is renamed `__peach_ovr_<name>`.
992
+ // a `plain` Swift member or one of an `unknown` base stays as written and
993
+ // fails to compile as it does on iOS.
994
+ const extIndex = new Map<string, Set<string>>()
995
+ if (extraObjCExtensions)
996
+ for (const [type, members] of extraObjCExtensions)
997
+ extIndex.set(type, new Set(members))
998
+ for (const [type, members] of scanObjCExtensionMembers(source, tokens, extensions)) {
999
+ const into = extIndex.get(type) ?? new Set<string>()
1000
+ for (const member of members) into.add(member)
1001
+ extIndex.set(type, into)
1002
+ }
1003
+ const overrideKind = (type: string, member: string): string => {
736
1004
  let base = classes.get(type)?.base ?? null
737
1005
  while (base !== null) {
738
- if (APPLE_CLASS.test(base)) return true
739
1006
  const declaredClass = classes.get(base)
740
- if (!declaredClass) return false
741
- const body = source.slice(declaredClass.brace, closing(declaredClass.brace))
742
- const found = new RegExp(`\\b(?:func|var)\\s+${member}\\b`).exec(body)
743
- if (found) {
744
- const line = body.slice(body.lastIndexOf('\n', found.index) + 1, found.index)
745
- return declaredClass.objcMembers || /@objc\b/.test(line)
746
- }
747
- base = declaredClass.base
1007
+ if (declaredClass) {
1008
+ const body = source.slice(declaredClass.brace, closing(declaredClass.brace))
1009
+ const found = new RegExp(`\\b(?:func|var)\\s+${member}\\b`).exec(body)
1010
+ if (found) {
1011
+ const line = body.slice(body.lastIndexOf('\n', found.index) + 1, found.index)
1012
+ return declaredClass.objcMembers || /@objc\b/.test(line) ? 'objc' : 'plain'
1013
+ }
1014
+ if (extIndex.get(base)?.has(member)) return 'ext'
1015
+ base = declaredClass.base
1016
+ } else if (extIndex.get(base)?.has(member)) return 'ext'
1017
+ else if (APPLE_CLASS.test(base)) return 'apple'
1018
+ else return 'unknown'
748
1019
  }
749
- return false
1020
+ return 'unknown'
750
1021
  }
1022
+ // an ext override takes `__peach_ovr_<name>`: without an objc runtime
1023
+ // no same-name member compiles, with `override`, @nonobjc or the @ObjC
1024
+ // macro's same-named static accessors alike. the renamed member keeps its
1025
+ // body and lines; callers keep binding the base member (a known
1026
+ // divergence, reported with the slice).
1027
+ const rename = (at: number, nameAt: number): [number, number, string][] => [
1028
+ [at, 'override'.length, ' '.repeat('override'.length)],
1029
+ [nameAt, 0, '__peach_ovr_'],
1030
+ ]
751
1031
  const edits: [number, number, string][] = []
752
1032
  const stubs = new Map<number, string[]>()
753
1033
  for (const entry of lifted) {
754
1034
  const brace = classes.get(entry.type)?.brace
755
- if (brace === undefined || !overridesObjC(entry.type, entry.member)) continue
1035
+ if (brace === undefined) continue
1036
+ const kind = overrideKind(entry.type, entry.member)
1037
+ if (kind !== 'apple' && kind !== 'objc' && kind !== 'ext') continue
1038
+ // a private override is invisible to subclasses on iOS too, so it stays
1039
+ // to fail there rather than lowering into a shadowing member.
1040
+ if (
1041
+ kind === 'ext' &&
1042
+ (entry.modifiers.includes('private') || entry.modifiers.includes('fileprivate'))
1043
+ )
1044
+ continue
1045
+ if (kind === 'ext') {
1046
+ edits.push(...rename(entry.at, entry.nameAt))
1047
+ continue
1048
+ }
756
1049
  edits.push(...entry.edits)
757
- stubs.set(brace, [...(stubs.get(brace) ?? []), entry.stub])
1050
+ const head = [...entry.modifiers, 'override'].filter((word) => word !== '').join(' ')
1051
+ stubs.set(brace, [
1052
+ ...(stubs.get(brace) ?? []),
1053
+ `${head} ${entry.decl} ${entry.forward}`,
1054
+ ])
1055
+ }
1056
+ for (const candidate of overrides) {
1057
+ if (overrideKind(candidate.type, candidate.member) !== 'ext') continue
1058
+ edits.push(...rename(candidate.at, candidate.nameAt))
758
1059
  }
759
1060
  for (const [brace, list] of stubs) edits.push([brace + 1, 0, ` ${list.join(' ')}`])
760
1061
  let out = source
@@ -974,8 +1275,11 @@ function swiftCodeMask(source: string): string {
974
1275
  return chars.join('')
975
1276
  }
976
1277
 
977
- export function swiftSourceAsIOS(original: string): string {
978
- const source = liftExtensionOverrides(original)
1278
+ export function swiftSourceAsIOS(
1279
+ original: string,
1280
+ extraObjCExtensions?: Map<string, Set<string>>,
1281
+ ): string {
1282
+ const source = liftExtensionOverrides(original, extraObjCExtensions)
979
1283
  const { lineStarts, tokens } = swiftCodeScan(source)
980
1284
  let offset = 0
981
1285
  // equal width, so every token offset still holds
@@ -995,9 +1299,16 @@ export function swiftSourceAsIOS(original: string): string {
995
1299
  const reusableBodies: number[] = []
996
1300
  let depth = 0
997
1301
  let opensReusableBody = false
1302
+ const sceneLifecycleBodies = new Set<number>()
998
1303
  for (const at of tokens) {
999
1304
  const rest = conditioned.slice(at, at + 400)
1000
1305
  if (rest.startsWith('{')) {
1306
+ if (sceneLifecycleBodies.has(at)) {
1307
+ out +=
1308
+ conditioned.slice(copied, at + 1) +
1309
+ ' public var _peachUsesSceneLifecycle: Bool { true };'
1310
+ copied = at + 1
1311
+ }
1001
1312
  depth++
1002
1313
  if (opensReusableBody) reusableBodies.push(depth)
1003
1314
  opensReusableBody = false
@@ -1036,12 +1347,36 @@ export function swiftSourceAsIOS(original: string): string {
1036
1347
  opensReusableBody = true
1037
1348
  }
1038
1349
  const modifiers = conditioned.slice(conditioned.lastIndexOf('\n', at - 1) + 1, at)
1350
+ const delegateClass = DELEGATE_CLASS.exec(rest)
1351
+ if (delegateClass && /\bUIApplicationDelegate\b/.test(delegateClass[0])) {
1352
+ const body = at + delegateClass[0].lastIndexOf('{')
1353
+ let bodyDepth = 0
1354
+ for (const token of tokens) {
1355
+ if (token < body) continue
1356
+ if (conditioned[token] === '{') bodyDepth++
1357
+ else if (conditioned[token] === '}' && --bodyDepth === 0) break
1358
+ else if (
1359
+ bodyDepth === 1 &&
1360
+ /^func\s+application\s*\([^{}]*\bconfigurationForConnecting\s+/.test(
1361
+ conditioned.slice(token, token + 600),
1362
+ )
1363
+ ) {
1364
+ sceneLifecycleBodies.add(body)
1365
+ break
1366
+ }
1367
+ }
1368
+ }
1039
1369
  if (DELEGATE_CLASS.test(rest) && !/\b(?:final|open)\b/.test(modifiers)) {
1040
1370
  out += `${conditioned.slice(copied, at)}final `
1041
1371
  copied = at
1042
1372
  }
1043
1373
  continue
1044
1374
  }
1375
+ if (/^@UIApplicationMain\b/.test(rest)) {
1376
+ out += conditioned.slice(copied, at) + '@main'.padEnd('@UIApplicationMain'.length)
1377
+ copied = at + '@UIApplicationMain'.length
1378
+ continue
1379
+ }
1045
1380
  const selector = SELECTOR.exec(rest)
1046
1381
  const match = selector ?? OBJC_ATTRIBUTE.exec(rest)
1047
1382
  if (!match) continue
@@ -1059,6 +1394,25 @@ export function swiftSourceAsIOS(original: string): string {
1059
1394
  return lowerAnyObjectDoubleValue(out + conditioned.slice(copied))
1060
1395
  }
1061
1396
 
1397
+ /** Swift's application entry declarations, ignoring comments and strings. */
1398
+ export function swiftApplicationEntry(file: string, source: string): boolean {
1399
+ const { tokens } = swiftCodeScan(source)
1400
+ let depth = 0
1401
+ for (const at of tokens) {
1402
+ if (source[at] === '{') depth++
1403
+ else if (source[at] === '}') depth--
1404
+ else if (depth === 0 && /^@(?:main|UIApplicationMain)\b/.test(source.slice(at)))
1405
+ return true
1406
+ else if (
1407
+ depth === 0 &&
1408
+ path.basename(file) === 'main.swift' &&
1409
+ /^UIApplicationMain\s*\(/.test(source.slice(at))
1410
+ )
1411
+ return true
1412
+ }
1413
+ return false
1414
+ }
1415
+
1062
1416
  // the offsets of the lines that begin in code, and of every `@`, `#`,
1063
1417
  // `class`, `extension` and `override` keyword that stands in code (an interpolation's code included), from a scan of Swift's
1064
1418
  // lexical contexts: nested block comments, line comments, string literals (single and
@@ -1070,7 +1424,10 @@ type Lexical =
1070
1424
  | { kind: 'block'; depth: number }
1071
1425
  | { kind: 'string'; hashes: number; multiline: boolean }
1072
1426
  | { kind: 'regex'; hashes: number }
1073
- function swiftCodeScan(source: string): { lineStarts: Set<number>; tokens: number[] } {
1427
+ function swiftCodeScan(source: string): {
1428
+ lineStarts: Set<number>
1429
+ tokens: number[]
1430
+ } {
1074
1431
  const starts = new Set<number>()
1075
1432
  const tokens: number[] = []
1076
1433
  const stack: Lexical[] = [{ kind: 'code', parens: 0 }]
@@ -1160,9 +1517,13 @@ function swiftCodeScan(source: string): { lineStarts: Set<number>; tokens: numbe
1160
1517
  ? 'override'
1161
1518
  : source.startsWith('import', i)
1162
1519
  ? 'import'
1163
- : source.startsWith('NSClassFromString', i)
1164
- ? 'NSClassFromString'
1165
- : null
1520
+ : source.startsWith('func', i)
1521
+ ? 'func'
1522
+ : source.startsWith('UIApplicationMain', i)
1523
+ ? 'UIApplicationMain'
1524
+ : source.startsWith('NSClassFromString', i)
1525
+ ? 'NSClassFromString'
1526
+ : null
1166
1527
  if (
1167
1528
  keyword &&
1168
1529
  !/[\w$]/.test(source[i - 1] ?? '') &&
@@ -1179,8 +1540,12 @@ function swiftCodeScan(source: string): { lineStarts: Set<number>; tokens: numbe
1179
1540
  return { lineStarts: starts, tokens }
1180
1541
  }
1181
1542
 
1182
- const compiledSource = (file: string, contents: string) =>
1183
- file.endsWith('.swift') ? swiftSourceAsIOS(contents) : contents
1543
+ const compiledSource = (
1544
+ file: string,
1545
+ contents: string,
1546
+ extraObjCExtensions?: Map<string, Set<string>>,
1547
+ ) =>
1548
+ file.endsWith('.swift') ? swiftSourceAsIOS(contents, extraObjCExtensions) : contents
1184
1549
 
1185
1550
  /** a dependency package's build copy: the published tree with every Swift
1186
1551
  * source rewritten as app sources are, so an unchanged upstream package that
@@ -1188,6 +1553,25 @@ const compiledSource = (file: string, contents: string) =>
1188
1553
  * published and the upstream tree is never written. */
1189
1554
  export function prepareSwiftDependency(source: string, destination: string): void {
1190
1555
  rmSync(destination, { recursive: true, force: true })
1556
+ // an override in one file may answer an @objc member an extension
1557
+ // declares in another, so the module-wide member index precedes the copy.
1558
+ const origins: string[] = []
1559
+ const gather = (from: string, root: boolean) => {
1560
+ for (const entry of readdirSync(from, { withFileTypes: true })) {
1561
+ if (entry.name === '.git' || entry.name === '.build' || entry.name === '.swiftpm')
1562
+ continue
1563
+ const file = path.join(from, entry.name)
1564
+ if (entry.isDirectory()) gather(file, false)
1565
+ else if (
1566
+ entry.isFile() &&
1567
+ entry.name.endsWith('.swift') &&
1568
+ !(root && /^Package(@swift-[\d.]+)?\.swift$/.test(entry.name))
1569
+ )
1570
+ origins.push(readFileSync(file, 'utf8'))
1571
+ }
1572
+ }
1573
+ gather(source, true)
1574
+ const objcExtensions = objcExtensionMemberIndex(origins)
1191
1575
  const copy = (from: string, to: string, root: boolean) => {
1192
1576
  mkdirSync(to, { recursive: true })
1193
1577
  for (const entry of readdirSync(from, { withFileTypes: true })) {
@@ -1201,7 +1585,10 @@ export function prepareSwiftDependency(source: string, destination: string): voi
1201
1585
  entry.name.endsWith('.swift') &&
1202
1586
  !(root && /^Package(@swift-[\d.]+)?\.swift$/.test(entry.name))
1203
1587
  )
1204
- writeFileSync(target, compiledSource(file, readFileSync(file, 'utf8')))
1588
+ writeFileSync(
1589
+ target,
1590
+ compiledSource(file, readFileSync(file, 'utf8'), objcExtensions),
1591
+ )
1205
1592
  else cpSync(file, target, { verbatimSymlinks: true })
1206
1593
  }
1207
1594
  }
@@ -1255,10 +1642,20 @@ export function writeSwiftProject(
1255
1642
  .digest('hex')
1256
1643
  .slice(0, 16)
1257
1644
  const moduleFiles = `\n// sootsim-swift files ${modulePlan.digest('hex').slice(0, 16)}\n// resource accessors ${resourcePlan}\n`
1645
+ // an override in one file may answer an @objc member an extension
1646
+ // declares in another, so the module-wide member index precedes the copy.
1647
+ const objcExtensions = objcExtensionMemberIndex(
1648
+ Object.entries(input.files)
1649
+ .filter(([file]) => file.endsWith('.swift'))
1650
+ .map(([, contents]) => contents),
1651
+ )
1258
1652
  if (targets.length === 0) {
1259
1653
  for (const [file, contents] of Object.entries(input.files)) {
1260
1654
  if (file === 'Package.swift') continue
1261
- files.set(path.join(layout.sources, file), compiledSource(file, contents))
1655
+ files.set(
1656
+ path.join(layout.sources, file),
1657
+ compiledSource(file, contents, objcExtensions),
1658
+ )
1262
1659
  }
1263
1660
  let manifest = readFileSync(
1264
1661
  path.join(moduleRoot, 'scripts/contrast-app-Package.swift'),
@@ -1307,7 +1704,7 @@ export function writeSwiftProject(
1307
1704
  const base = layout.multi ? layout.root : layout.sources
1308
1705
  for (const [file, contents] of Object.entries(input.files)) {
1309
1706
  if (file === 'Package.swift') continue
1310
- files.set(path.join(base, file), compiledSource(file, contents))
1707
+ files.set(path.join(base, file), compiledSource(file, contents, objcExtensions))
1311
1708
  }
1312
1709
  files.set(
1313
1710
  path.join(layout.root, 'Package.swift'),
@@ -1461,10 +1858,16 @@ export function compileSwiftProjectUnit(
1461
1858
  plugin,
1462
1859
  ]),
1463
1860
  ],
1464
- { env: BUILD_ENV, maxBuffer: 64 * 1024 * 1024, timeout: options.timeoutMs },
1861
+ {
1862
+ env: BUILD_ENV,
1863
+ maxBuffer: 64 * 1024 * 1024,
1864
+ timeout: options.timeoutMs,
1865
+ },
1465
1866
  )
1466
1867
  } catch (error) {
1467
- throw new Error(projectDiagnostic(outputOf(error), layout), { cause: error })
1868
+ throw new Error(projectDiagnostic(outputOf(error), layout), {
1869
+ cause: error,
1870
+ })
1468
1871
  }
1469
1872
  return {
1470
1873
  hash,