peachsim 0.1.687 → 0.1.689

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (116) hide show
  1. package/cli/cloud-client.ts +3 -3
  2. package/cli/command-registry.ts +2 -0
  3. package/cli/commands/control.ts +1 -0
  4. package/cli/commands/debug.ts +10 -33
  5. package/cli/commands/do-chain.ts +56 -6
  6. package/cli/commands/inspect/core.ts +2 -0
  7. package/cli/commands/inspect/list.ts +2 -1
  8. package/cli/commands/inspect/settling.ts +17 -3
  9. package/cli/commands/inspect/shared.ts +2 -0
  10. package/cli/commands/inspect/wait-idle.ts +2 -2
  11. package/cli/commands/inspect/wait-ready.ts +3 -3
  12. package/cli/commands/inspect.ts +33 -7
  13. package/cli/commands/location.ts +164 -0
  14. package/cli/commands/platform.ts +1 -1
  15. package/cli/drivers/playwright-sim-host.ts +46 -25
  16. package/cli/main.ts +6 -0
  17. package/detox/index.ts +13 -8
  18. package/dist-lib/agent-daemon-client.cjs +1 -1
  19. package/dist-lib/agent-events.cjs +1 -1
  20. package/dist-lib/agent-identity.cjs +1 -1
  21. package/dist-lib/agent-sessions.cjs +1 -1
  22. package/dist-lib/attached-projects.cjs +1 -1
  23. package/dist-lib/auth/shared-session.cjs +1 -1
  24. package/dist-lib/backend-origin.cjs +1 -1
  25. package/dist-lib/beta.cjs +1 -1
  26. package/dist-lib/beta.mjs +1 -1
  27. package/dist-lib/bridge-constants.cjs +4 -3
  28. package/dist-lib/bridge-contract-input.cjs +12 -1
  29. package/dist-lib/bridge-contract-input.mjs +12 -1
  30. package/dist-lib/bridge-contract.cjs +4 -3
  31. package/dist-lib/bridge-contract.mjs +4 -3
  32. package/dist-lib/capture-contract.cjs +1 -1
  33. package/dist-lib/capture-contract.mjs +1 -1
  34. package/dist-lib/cli-constants.cjs +1 -1
  35. package/dist-lib/cloud-contract.cjs +2 -1
  36. package/dist-lib/cloud-contract.mjs +2 -1
  37. package/dist-lib/cloud-test-args.cjs +1 -1
  38. package/dist-lib/cloud-test-args.mjs +1 -1
  39. package/dist-lib/cloud.cjs +2 -1
  40. package/dist-lib/cloud.mjs +2 -1
  41. package/dist-lib/config.cjs +1 -1
  42. package/dist-lib/detox/index.cjs +1197 -65
  43. package/dist-lib/dev-bundle-resolution.cjs +1 -1
  44. package/dist-lib/home-paths.cjs +1 -1
  45. package/dist-lib/host/bridge-host.cjs +362 -108
  46. package/dist-lib/host/fetch-proxy-handler.cjs +50 -40
  47. package/dist-lib/host/fetch-proxy-overrides.cjs +50 -6
  48. package/dist-lib/host/fetch-proxy-overrides.mjs +48 -5
  49. package/dist-lib/host/replacement-module-handler.cjs +1 -1
  50. package/dist-lib/host/websocket-proxy.cjs +1 -1
  51. package/dist-lib/index.cjs +29 -11
  52. package/dist-lib/jump-to-source-babel.cjs +1 -1
  53. package/dist-lib/jump-to-source-native.cjs +1 -1
  54. package/dist-lib/kotlin-host.cjs +89 -13
  55. package/dist-lib/menu.cjs +1 -1
  56. package/dist-lib/menu.mjs +1 -1
  57. package/dist-lib/metro-fingerprint-registry.cjs +1 -1
  58. package/dist-lib/metro-fingerprint-registry.mjs +1 -1
  59. package/dist-lib/metro-production-bundle.cjs +1 -1
  60. package/dist-lib/metro-production-bundle.mjs +1 -1
  61. package/dist-lib/metro.cjs +5 -3
  62. package/dist-lib/native-app-identity.cjs +8 -3
  63. package/dist-lib/native-app-identity.mjs +8 -3
  64. package/dist-lib/native-firebase-metadata.cjs +1 -1
  65. package/dist-lib/native-firebase-metadata.mjs +1 -1
  66. package/dist-lib/plist.cjs +1 -1
  67. package/dist-lib/plist.mjs +1 -1
  68. package/dist-lib/profiles.cjs +1 -1
  69. package/dist-lib/public-brand.cjs +1 -1
  70. package/dist-lib/react-native-host-modules.cjs +1 -1
  71. package/dist-lib/react-native-host-modules.mjs +1 -1
  72. package/dist-lib/render-mode.cjs +1 -1
  73. package/dist-lib/scripts/dev-server-scanner.cjs +2 -2
  74. package/dist-lib/sdk.cjs +21 -6
  75. package/dist-lib/sdk.mjs +21 -6
  76. package/dist-lib/skills.cjs +401 -130
  77. package/dist-lib/swift-compile.cjs +277 -22
  78. package/dist-lib/swift-compile.mjs +275 -22
  79. package/dist-lib/swift-package.cjs +1 -1
  80. package/dist-lib/swift-package.mjs +1 -1
  81. package/dist-lib/swift-submit.cjs +2 -2
  82. package/dist-lib/swift-submit.mjs +2 -2
  83. package/dist-lib/swift-toolchain.cjs +10 -10
  84. package/dist-lib/swift.cjs +1 -1
  85. package/dist-lib/vite-swift.cjs +280 -44
  86. package/dist-lib/vite.cjs +1 -1
  87. package/kotlin/AppSources/android/content/res/Configuration.kt +2 -0
  88. package/kotlin/AppSources/android/content/res/Resources.kt +6 -3
  89. package/kotlin/AppSources/android/util/DisplayMetrics.kt +12 -0
  90. package/kotlin/AppSources/androidx/compose/ui/res/PainterResources.kt +70 -0
  91. package/kotlin/AppSources/dev/peach/app/PeachApp.kt +12 -10
  92. package/kotlin/AppSources/dev/peach/app/PeachDrawable.kt +95 -0
  93. package/kotlin/fixtures/kotlin-app-variants/Bitmaps.kt +50 -0
  94. package/kotlin/fixtures/kotlin-app-variants/Drawables.kt +53 -0
  95. package/package.json +2 -2
  96. package/scripts/dev-server-scanner.ts +3 -1
  97. package/skills/contrast/SKILL.md +1 -0
  98. package/src/android-drawables.ts +315 -0
  99. package/src/android-theme.ts +9 -0
  100. package/src/bridge-constants.ts +3 -2
  101. package/src/bridge-contract-input.ts +11 -0
  102. package/src/bridge-contract.ts +45 -3
  103. package/src/cloud-contract.ts +1 -0
  104. package/src/host/fetch-proxy-handler.ts +13 -49
  105. package/src/host/fetch-proxy-overrides.ts +69 -12
  106. package/src/kotlin-app.ts +6 -0
  107. package/src/kotlin-host.ts +103 -15
  108. package/src/native-app-identity.ts +16 -3
  109. package/src/swift-compile.ts +366 -24
  110. package/src/swift-distribution-contract.ts +11 -4
  111. package/src/swift-distribution.lock.json +11 -9
  112. package/src/swift-distribution.ts +4 -4
  113. package/src/swift-icu.ts +8 -11
  114. package/src/swift-submit.ts +13 -1
  115. package/src/swift-toolchain.ts +17 -9
  116. package/src/vite-plugin.ts +86 -34
@@ -1,6 +1,7 @@
1
1
  import { execFile } from 'node:child_process'
2
2
  import { createHash } from 'node:crypto'
3
3
  import {
4
+ cpSync,
4
5
  existsSync,
5
6
  mkdirSync,
6
7
  readFileSync,
@@ -25,6 +26,7 @@ import {
25
26
  type SwiftPackageTarget,
26
27
  } from './swift-package'
27
28
  import type { SwiftImageUpload } from './swift-submit'
29
+ import type { SwiftWasmSdk } from './swift-toolchain'
28
30
 
29
31
  export { swiftIcuAsset, type SwiftIcuAsset }
30
32
 
@@ -85,6 +87,27 @@ export function swiftDistributionAt(root: string): SwiftDistributionManifest | n
85
87
  return parseSwiftDistributionManifest(JSON.parse(readFileSync(file, 'utf8')))
86
88
  }
87
89
 
90
+ /** the wasm SDK a module root compiles with: a distribution's manifest names
91
+ * it, a source checkout's toolchain.json pins it. */
92
+ export function swiftModuleSdk(root: string): SwiftWasmSdk {
93
+ const pin: unknown =
94
+ swiftDistributionAt(root) ??
95
+ JSON.parse(readFileSync(path.join(root, 'toolchain.json'), 'utf8'))
96
+ if (
97
+ !pin ||
98
+ typeof pin !== 'object' ||
99
+ typeof Reflect.get(pin, 'wasmSdkId') !== 'string' ||
100
+ typeof Reflect.get(pin, 'wasmSdkUrl') !== 'string' ||
101
+ typeof Reflect.get(pin, 'wasmSdkChecksum') !== 'string'
102
+ )
103
+ throw new Error(`${root} pins no wasm SDK id, url and checksum`)
104
+ return {
105
+ wasmSdkId: String(Reflect.get(pin, 'wasmSdkId')),
106
+ wasmSdkUrl: String(Reflect.get(pin, 'wasmSdkUrl')),
107
+ wasmSdkChecksum: String(Reflect.get(pin, 'wasmSdkChecksum')),
108
+ }
109
+ }
110
+
88
111
  // toolchain.json is an input for its wasm sdk checksum: the sdk's icu blob,
89
112
  // which the host fills into every artifact, is part of what the address names.
90
113
  // a distribution's manifest names every file it ships by digest.
@@ -99,7 +122,7 @@ export function swiftModuleInputFiles(root: string): string[] {
99
122
  for (const entry of readdirSync(path.join(root, dir), { withFileTypes: true })) {
100
123
  const relative = `${dir}/${entry.name}`
101
124
  if (entry.isDirectory()) walk(relative)
102
- else if (/\.(swift|c|h)$/.test(entry.name)) files.push(relative)
125
+ else if (/\.(swift|c|cpp|h)$/.test(entry.name)) files.push(relative)
103
126
  }
104
127
  }
105
128
  walk('Sources')
@@ -212,9 +235,21 @@ export function withNativeSourceGlue(
212
235
  }
213
236
  }
214
237
 
215
- const OPTIONAL_FRAMEWORKS = new Set(['CryptoKit', 'Security'])
238
+ // optional families link only into an app whose sources import them, each
239
+ // with the optional families it depends on (packages/sootsim-swift/Package.swift).
240
+ const OPTIONAL_FRAMEWORK_DEPENDENCIES: Record<string, string[]> = {
241
+ Accelerate: [],
242
+ CryptoKit: [],
243
+ Security: [],
244
+ Statsig: [],
245
+ DatadogCore: [],
246
+ DatadogLogs: ['DatadogCore'],
247
+ DatadogRUM: ['DatadogCore'],
248
+ DatadogTrace: ['DatadogCore'],
249
+ }
250
+ const OPTIONAL_FRAMEWORKS = new Set(Object.keys(OPTIONAL_FRAMEWORK_DEPENDENCIES))
216
251
 
217
- function swiftTargetDependencies(
252
+ export function swiftTargetDependencies(
218
253
  files: Record<string, string>,
219
254
  targets: Pick<SwiftPackageTarget, 'name' | 'path'>[],
220
255
  ): Map<string, string[]> {
@@ -260,15 +295,19 @@ const importsSpriteKit = (files: Record<string, string>): boolean =>
260
295
  contents,
261
296
  ),
262
297
  )
263
- // every iOS source sees the ObjectiveC module's selectors through Foundation;
264
- // PeachObjC stands in for it, so a source that imports only Foundation still
265
- // compiles `@objc` and `#selector`. scripts/contrast-app-Package.swift and
298
+ // every iOS source sees through Foundation what darwin's Foundation exports:
299
+ // PeachObjC supplies the ObjectiveC module's selectors, Dispatch Foundation's
300
+ // Darwin queue exports, and FoundationNetworking (re-exporting PeachFoundation)
301
+ // URLSession, NotificationCenter, OperationQueue and the CoreFoundation types.
302
+ // these modules export only names iOS has; Peach's host plumbing is `package`
303
+ // or lives in PeachJSON, which none of them re-exports. scripts/contrast-app-Package.swift and
266
304
  // example/Package.swift carry the same flags.
267
- const OBJC_IMPLICIT_FLAGS = ', "-Xfrontend", "-import-module", "-Xfrontend", "PeachObjC"'
305
+ const FOUNDATION_IMPLICIT_FLAGS =
306
+ ', "-Xfrontend", "-import-module", "-Xfrontend", "PeachObjC", "-Xfrontend", "-import-module", "-Xfrontend", "Dispatch", "-Xfrontend", "-import-module", "-Xfrontend", "FoundationNetworking"'
268
307
  const ONE_IMPLICIT_FLAGS = ', "-Xfrontend", "-import-module", "-Xfrontend", "One"'
269
308
 
270
309
  /** bump with any change to the emitted multi-target manifest text. */
271
- export const MULTI_MANIFEST_VERSION = 8
310
+ export const MULTI_MANIFEST_VERSION = 10
272
311
 
273
312
  export function swiftArtifactHash(
274
313
  input: SwiftCompileInput,
@@ -276,12 +315,15 @@ export function swiftArtifactHash(
276
315
  moduleRoot: string,
277
316
  ): string {
278
317
  const hash = createHash('sha256')
318
+ // v12: overrides in an extension of a same-file class lift into the class
319
+ // v10: Foundation-only sources see Dispatch queues
320
+ // v9: table cell and header footer view initializers compile required
279
321
  // v8: optional framework products and distribution objects link on import
280
322
  // v7: runtime class lookup uses the same objc class registry as messages
281
323
  // v6: app and scene delegate classes compile final
282
324
  // (v5: a target declaring resources gets SwiftPM's Bundle.module accessor;
283
325
  // v4: sources compile through swiftSourceAsIOS)
284
- hash.update(`swift-compile/v8\n${release}\n`)
326
+ hash.update(`swift-compile/v12\n${release}\n`)
285
327
  if (input.oneModule) hash.update('one-module\n')
286
328
  hash.update(swiftModuleDigest(moduleRoot))
287
329
  for (const file of Object.keys(input.files).sort()) {
@@ -335,7 +377,8 @@ export function emitSwiftPackageManifest(args: {
335
377
  (name) =>
336
378
  OPTIONAL_FRAMEWORKS.has(name) &&
337
379
  !targets.some((target) => target.name === name),
338
- ),
380
+ )
381
+ .flatMap((name) => [name, ...(OPTIONAL_FRAMEWORK_DEPENDENCIES[name] ?? [])]),
339
382
  )
340
383
  // the distribution builder names each object lib/<target>-<file>.o.
341
384
  // preserve link order while leaving unreached optional module objects out.
@@ -363,7 +406,7 @@ export function emitSwiftPackageManifest(args: {
363
406
  const imports = distribution
364
407
  ? `, "-I", ${JSON.stringify(path.join(moduleRoot, 'modules'))}`
365
408
  : ''
366
- const swiftSettings = `swiftSettings: [.swiftLanguageMode(.v${target.languageMode}),${isolation} .unsafeFlags(["-Osize"${OBJC_IMPLICIT_FLAGS}${oneModule ? ONE_IMPLICIT_FLAGS : ''}${imports}])]`
409
+ const swiftSettings = `swiftSettings: [.swiftLanguageMode(.v${target.languageMode}),${isolation} .unsafeFlags(["-Osize"${FOUNDATION_IMPLICIT_FLAGS}${oneModule ? ONE_IMPLICIT_FLAGS : ''}${imports}])]`
367
410
  const deps = [
368
411
  ...(distribution
369
412
  ? []
@@ -461,12 +504,18 @@ function syncSwiftTree(base: string, files: Map<string, string>): void {
461
504
  // `@objcMembers` `@ObjCMembers`, `@IBAction` `@ObjC` padded, and `#selector(`
462
505
  // `#Selector(`: the module's macros that expose a method to selector dispatch
463
506
  // (plans/peach/uikit-shell.md, gate B). all keep their width except an
464
- // explicit `@objc(name:)`, whose name becomes a string argument, and a
465
- // delegate class that becomes final (below).
507
+ // explicit `@objc(name:)` on a member, whose name becomes a string argument,
508
+ // and a delegate class that becomes final (below).
466
509
  const DIRECTIVE = /^[ \t]*#(?:if|elseif)\b/
467
510
  const OS_IOS = /\bos\(\s*iOS\s*\)/g
468
511
  const OBJC_ATTRIBUTE = /^@(?:objcMembers\b|objc\b(?:(\s*)\(([^()]*)\))?|IBAction\b)/
469
512
  const SELECTOR = /^#selector\b/
513
+ // `@objc` on a type exposes no selector here, and Swift rejects a peer macro
514
+ // that names arbitrary peers on a global declaration, so on a type it becomes
515
+ // blanks of its width; comments may sit between the attribute and the type.
516
+ // `class func` and `class var` are methods.
517
+ const TYPE_AFTER_ATTRIBUTE =
518
+ /^(?:\s+|\/\/[^\n]*|\/\*[\s\S]*?\*\/|@\w+(?:\([^()]*\))?|\b(?:public|open|final|internal|fileprivate|private|package|nonisolated|indirect)\b)*\b(?:class(?!\s+(?:func|var|let|subscript)\b)|struct|enum|protocol|extension|actor)\b/
470
519
  // uikit makes app and scene delegates from their class through the objc
471
520
  // runtime; here their protocols require init(), which a non-final class
472
521
  // meets only with a required one. a class declaring one of them that is
@@ -474,7 +523,233 @@ const SELECTOR = /^#selector\b/
474
523
  // compile naming itself.
475
524
  const DELEGATE_CLASS =
476
525
  /^class\s+[A-Za-z_]\w*\s*(?:<[^>{]*>)?\s*:[^{]*\b(?:UIApplicationDelegate|UISceneDelegate|UIWindowSceneDelegate)\b[^{]*\{/
477
- export function swiftSourceAsIOS(source: string): string {
526
+ // a table makes its cells and header footer views from their class, which
527
+ // here needs the initializer it calls to be required. a subclass's override
528
+ // of it says `required`, the same width: the cell's
529
+ // init(style:reuseIdentifier:) and the header footer view's
530
+ // init(reuseIdentifier:).
531
+ const REUSABLE_INIT =
532
+ /^override(?=\s+init\s*\(\s*(?:style\s*:[^,)]*,\s*reuseIdentifier|reuseIdentifier)\s*:)/
533
+ // a collection view makes its cells and supplementary views with
534
+ // init(frame:), so inside a class that inherits from one, directly or
535
+ // through a class declared earlier in the file, an override of it says
536
+ // `required` too. a class whose base is declared in another file is not
537
+ // seen and fails to compile.
538
+ const REUSABLE_VIEW_BASES = [
539
+ 'UICollectionReusableView',
540
+ 'UICollectionViewCell',
541
+ 'UICollectionViewListCell',
542
+ ]
543
+ const CLASS_BASE =
544
+ /^class\s+([A-Za-z_]\w*)\s*(?:<[^>{]*>)?\s*:\s*([A-Za-z_][\w.]*)[^{]*\{/
545
+ const FRAME_INIT = /^override(?=\s+(?:(?:public|open|internal)\s+)?init\s*\(\s*frame\s*:)/
546
+ // uikit's members are @objc, so an app may override one from an extension;
547
+ // swift without an objc runtime rejects that. an `override` of an @objc
548
+ // member (overridesObjC below) that is a direct member of an extension of a
549
+ // class declared in the same file is lifted: the extension keeps it as `__peach_ext_<name>` with `override`
550
+ // blanked, and the class body gains, on its opening brace's line, an
551
+ // override that forwards to it, so lines keep their numbers and the
552
+ // override takes its place in the class as an objc one does. a class in
553
+ // another file, a property with a setter or observers, a subscript and a
554
+ // variadic parameter stay as written and fail to compile as before.
555
+ // an Apple framework class: an ObjC prefix and a capital
556
+ const APPLE_CLASS = /^(?:UI|NS|CA|SK|WK|MK|AV|PK|CL|GK|PH|SF|AS|QL)[A-Z]/
557
+ const EXTENSION_DECL = /^extension\s+([A-Za-z_][\w.]*)/
558
+ const CLASS_DECL = /^class\s+(?!(?:func|var|let|subscript)\b)([A-Za-z_]\w*)/
559
+ const MODIFIERS =
560
+ /(?:^|\s)(public|open|internal|fileprivate|private|final|nonisolated|@MainActor)(?=\s)/g
561
+ const OVERRIDE_FUNC =
562
+ /^override((?:\s+(?:public|open|internal|fileprivate|private|final|nonisolated|dynamic|@\w+))*)\s+func\s+([A-Za-z_]\w*)\s*(<[^>{}]*>)?\s*\(/
563
+ const OVERRIDE_VAR =
564
+ /^override((?:\s+(?:public|open|internal|fileprivate|private|final|nonisolated|dynamic|@\w+))*)\s+var\s+([A-Za-z_]\w*)\s*:\s*([^{=]+?)\s*\{/
565
+
566
+ function splitTopLevel(text: string): string[] {
567
+ const parts: string[] = []
568
+ let depth = 0
569
+ let start = 0
570
+ for (let i = 0; i < text.length; i++) {
571
+ const char = text[i]
572
+ if (char === '(' || char === '[' || char === '<') depth++
573
+ else if (char === ')' || char === ']' || (char === '>' && text[i - 1] !== '-'))
574
+ depth--
575
+ else if (char === ',' && depth === 0) {
576
+ parts.push(text.slice(start, i))
577
+ start = i + 1
578
+ }
579
+ }
580
+ parts.push(text.slice(start))
581
+ return parts.map((part) => part.trim()).filter((part) => part !== '')
582
+ }
583
+
584
+ // the call that forwards a parameter list, or null when one cannot forward
585
+ function forwardedArguments(parameters: string): string | null {
586
+ const args: string[] = []
587
+ for (const parameter of splitTopLevel(parameters)) {
588
+ const match = /^(?:([A-Za-z_]\w*)\s+)?([A-Za-z_]\w*)\s*:\s*([\s\S]*)$/.exec(parameter)
589
+ if (!match || match[3]!.includes('...')) return null
590
+ const label = match[1] ?? match[2]!
591
+ const value = (/^(?:@\w+\s+)*inout\b/.test(match[3]!) ? '&' : '') + match[2]!
592
+ args.push(label === '_' ? value : `${label}: ${value}`)
593
+ }
594
+ return args.join(', ')
595
+ }
596
+
597
+ function liftExtensionOverrides(source: string): string {
598
+ const { tokens } = swiftCodeScan(source)
599
+ type Frame = { kind: 'class' | 'extension' | 'other'; name: string }
600
+ const stack: Frame[] = []
601
+ let pending: Frame | null = null
602
+ const classes = new Map<
603
+ string,
604
+ { brace: number; base: string | null; objcMembers: boolean }
605
+ >()
606
+ let declaredBase: string | null = null
607
+ let declaredObjCMembers = false
608
+ const lifted: {
609
+ type: string
610
+ member: string
611
+ stub: string
612
+ edits: [number, number, string][]
613
+ }[] = []
614
+ // the offset just past the brace that closes the one at `open`
615
+ const closing = (open: number): number => {
616
+ let depth = 0
617
+ for (const at of tokens) {
618
+ if (at < open) continue
619
+ if (source[at] === '{') depth++
620
+ else if (source[at] === '}' && --depth === 0) return at + 1
621
+ }
622
+ return source.length
623
+ }
624
+ for (const at of tokens) {
625
+ const rest = source.slice(at, at + 600)
626
+ if (rest.startsWith('{')) {
627
+ const frame = pending ?? { kind: 'other', name: '' }
628
+ if (frame.kind === 'class' && !classes.has(frame.name))
629
+ classes.set(frame.name, {
630
+ brace: at,
631
+ base: declaredBase,
632
+ objcMembers: declaredObjCMembers,
633
+ })
634
+ stack.push(frame)
635
+ pending = null
636
+ continue
637
+ }
638
+ if (rest.startsWith('}')) {
639
+ stack.pop()
640
+ continue
641
+ }
642
+ const declared = CLASS_DECL.exec(rest)
643
+ if (declared) {
644
+ pending = { kind: 'class', name: declared[1]! }
645
+ declaredBase = CLASS_BASE.exec(rest)?.[2]?.split('.').pop() ?? null
646
+ const lines = source.lastIndexOf('\n', source.lastIndexOf('\n', at - 1) - 1) + 1
647
+ declaredObjCMembers = /@objcMembers\b/.test(source.slice(lines, at))
648
+ continue
649
+ }
650
+ const extended = EXTENSION_DECL.exec(rest)
651
+ if (extended) {
652
+ pending = { kind: 'extension', name: extended[1]!.split('.').pop()! }
653
+ continue
654
+ }
655
+ const top = stack.at(-1)
656
+ if (!rest.startsWith('override') || top?.kind !== 'extension' || pending) continue
657
+ const line = source.slice(source.lastIndexOf('\n', at - 1) + 1, at)
658
+ const modifiers = (` ${line} `.match(MODIFIERS) ?? []).map((word) => word.trim())
659
+ const func = OVERRIDE_FUNC.exec(rest)
660
+ if (func) {
661
+ const name = func[2]!
662
+ const open = at + func[0].length - 1
663
+ let depth = 0
664
+ let close = open
665
+ for (; close < source.length; close++) {
666
+ if (source[close] === '(') depth++
667
+ else if (source[close] === ')' && --depth === 0) break
668
+ }
669
+ const body = tokens.find((token) => token > close && source[token] === '{')
670
+ if (body === undefined) continue
671
+ const clause = source.slice(close + 1, body).trim()
672
+ const args = forwardedArguments(source.slice(open + 1, close))
673
+ if (args === null) continue
674
+ const call =
675
+ (clause.includes('->') ? 'return ' : '') +
676
+ (/\b(?:throws|rethrows)\b/.test(clause) ? 'try ' : '') +
677
+ (/\basync\b/.test(clause) ? 'await ' : '') +
678
+ `__peach_ext_${name}(${args})`
679
+ const signature = `func ${name}${func[3] ?? ''}${source.slice(open, close + 1)}${clause ? ` ${clause}` : ''}`
680
+ lifted.push({
681
+ type: top.name,
682
+ member: name,
683
+ stub: `${[...modifiers, 'override'].join(' ')} ${signature} { ${call} };`,
684
+ edits: [
685
+ [at, 'override'.length, ' '.repeat('override'.length)],
686
+ [
687
+ at +
688
+ rest.indexOf(
689
+ name,
690
+ rest.indexOf('func', 'override'.length + func[1]!.length) + 4,
691
+ ),
692
+ 0,
693
+ '__peach_ext_',
694
+ ],
695
+ ],
696
+ })
697
+ continue
698
+ }
699
+ const property = OVERRIDE_VAR.exec(rest)
700
+ if (property) {
701
+ const open = at + property[0].length - 1
702
+ if (/\b(?:set|willSet|didSet)\b/.test(source.slice(open, closing(open)))) continue
703
+ const name = property[2]!
704
+ lifted.push({
705
+ type: top.name,
706
+ member: name,
707
+ stub: `${[...modifiers, 'override'].join(' ')} var ${name}: ${property[3]!.trim()} { __peach_ext_${name} };`,
708
+ edits: [
709
+ [at, 'override'.length, ' '.repeat('override'.length)],
710
+ [at + rest.indexOf(name, rest.indexOf('var')), 0, '__peach_ext_'],
711
+ ],
712
+ })
713
+ }
714
+ }
715
+ // whether the member a class inherits is @objc, as an extension override
716
+ // needs on iOS: an Apple framework class's members are, and an app class
717
+ // in this file declares it with @objc or under @objcMembers. a base this
718
+ // file does not declare, or a plain Swift member, is not, and the override
719
+ // stays to fail as it does on iOS.
720
+ const overridesObjC = (type: string, member: string): boolean => {
721
+ let base = classes.get(type)?.base ?? null
722
+ while (base !== null) {
723
+ if (APPLE_CLASS.test(base)) return true
724
+ const declaredClass = classes.get(base)
725
+ if (!declaredClass) return false
726
+ const body = source.slice(declaredClass.brace, closing(declaredClass.brace))
727
+ const found = new RegExp(`\\b(?:func|var)\\s+${member}\\b`).exec(body)
728
+ if (found) {
729
+ const line = body.slice(body.lastIndexOf('\n', found.index) + 1, found.index)
730
+ return declaredClass.objcMembers || /@objc\b/.test(line)
731
+ }
732
+ base = declaredClass.base
733
+ }
734
+ return false
735
+ }
736
+ const edits: [number, number, string][] = []
737
+ const stubs = new Map<number, string[]>()
738
+ for (const entry of lifted) {
739
+ const brace = classes.get(entry.type)?.brace
740
+ if (brace === undefined || !overridesObjC(entry.type, entry.member)) continue
741
+ edits.push(...entry.edits)
742
+ stubs.set(brace, [...(stubs.get(brace) ?? []), entry.stub])
743
+ }
744
+ for (const [brace, list] of stubs) edits.push([brace + 1, 0, ` ${list.join(' ')}`])
745
+ let out = source
746
+ for (const [at, remove, insert] of edits.sort((a, b) => b[0] - a[0]))
747
+ out = out.slice(0, at) + insert + out.slice(at + remove)
748
+ return out
749
+ }
750
+
751
+ export function swiftSourceAsIOS(original: string): string {
752
+ const source = liftExtensionOverrides(original)
478
753
  const { lineStarts, tokens } = swiftCodeScan(source)
479
754
  let offset = 0
480
755
  // equal width, so every token offset still holds
@@ -489,8 +764,34 @@ export function swiftSourceAsIOS(source: string): string {
489
764
  .join('\n')
490
765
  let out = ''
491
766
  let copied = 0
767
+ const reusableViews = new Set(REUSABLE_VIEW_BASES)
768
+ // the brace depth of each open reusable view class's body
769
+ const reusableBodies: number[] = []
770
+ let depth = 0
771
+ let opensReusableBody = false
492
772
  for (const at of tokens) {
493
773
  const rest = conditioned.slice(at, at + 400)
774
+ if (rest.startsWith('{')) {
775
+ depth++
776
+ if (opensReusableBody) reusableBodies.push(depth)
777
+ opensReusableBody = false
778
+ continue
779
+ }
780
+ if (rest.startsWith('}')) {
781
+ if (reusableBodies.at(-1) === depth) reusableBodies.pop()
782
+ depth--
783
+ continue
784
+ }
785
+ if (rest.startsWith('override')) {
786
+ if (
787
+ REUSABLE_INIT.test(rest) ||
788
+ (reusableBodies.at(-1) === depth && FRAME_INIT.test(rest))
789
+ ) {
790
+ out += `${conditioned.slice(copied, at)}required`
791
+ copied = at + 'override'.length
792
+ }
793
+ continue
794
+ }
494
795
  const imported = /^import\s+CoreImage\.CIFilterBuiltins\b/.exec(rest)
495
796
  if (imported) {
496
797
  out += conditioned.slice(copied, at) + 'import CoreImage'.padEnd(imported[0].length)
@@ -503,6 +804,11 @@ export function swiftSourceAsIOS(source: string): string {
503
804
  continue
504
805
  }
505
806
  if (rest.startsWith('class')) {
807
+ const declared = CLASS_BASE.exec(rest)
808
+ if (declared && reusableViews.has(declared[2]!.split('.').pop()!)) {
809
+ reusableViews.add(declared[1]!)
810
+ opensReusableBody = true
811
+ }
506
812
  const modifiers = conditioned.slice(conditioned.lastIndexOf('\n', at - 1) + 1, at)
507
813
  if (DELEGATE_CLASS.test(rest) && !/\b(?:final|open)\b/.test(modifiers)) {
508
814
  out += `${conditioned.slice(copied, at)}final `
@@ -517,6 +823,8 @@ export function swiftSourceAsIOS(source: string): string {
517
823
  if (selector) replacement = '#Selector'
518
824
  else if (match[0] === '@objcMembers') replacement = '@ObjCMembers'
519
825
  else if (match[0] === '@IBAction') replacement = '@ObjC'.padEnd(match[0].length)
826
+ else if (TYPE_AFTER_ATTRIBUTE.test(rest.slice(match[0].length)))
827
+ replacement = ' '.repeat(match[0].length)
520
828
  else if (match[2] !== undefined)
521
829
  replacement = `@ObjC${match[1]}("${match[2].trim()}")`
522
830
  out += conditioned.slice(copied, at) + replacement
@@ -525,8 +833,8 @@ export function swiftSourceAsIOS(source: string): string {
525
833
  return out + conditioned.slice(copied)
526
834
  }
527
835
 
528
- // the offsets of the lines that begin in code, and of every `@`, `#` and
529
- // `class` keyword that stands in code (an interpolation's code included), from a scan of Swift's
836
+ // the offsets of the lines that begin in code, and of every `@`, `#`,
837
+ // `class`, `extension` and `override` keyword that stands in code (an interpolation's code included), from a scan of Swift's
530
838
  // lexical contexts: nested block comments, line comments, string literals (single and
531
839
  // multiline, raw with any number of #, interpolations holding code and
532
840
  // strings of their own) and #/ /# regex literals. a bare /regex/ literal
@@ -607,6 +915,9 @@ function swiftCodeScan(source: string): { lineStarts: Set<number>; tokens: numbe
607
915
  if (hashes > 0) tokens.push(at - 1)
608
916
  i = Math.max(at, i + 1)
609
917
  }
918
+ } else if (char === '{' || char === '}') {
919
+ tokens.push(i)
920
+ i++
610
921
  } else if (char === '(') {
611
922
  top.parens++
612
923
  i++
@@ -617,11 +928,15 @@ function swiftCodeScan(source: string): { lineStarts: Set<number>; tokens: numbe
617
928
  } else {
618
929
  const keyword = source.startsWith('class', i)
619
930
  ? 'class'
620
- : source.startsWith('import', i)
621
- ? 'import'
622
- : source.startsWith('NSClassFromString', i)
623
- ? 'NSClassFromString'
624
- : null
931
+ : source.startsWith('extension', i)
932
+ ? 'extension'
933
+ : source.startsWith('override', i)
934
+ ? 'override'
935
+ : source.startsWith('import', i)
936
+ ? 'import'
937
+ : source.startsWith('NSClassFromString', i)
938
+ ? 'NSClassFromString'
939
+ : null
625
940
  if (
626
941
  keyword &&
627
942
  !/[\w$]/.test(source[i - 1] ?? '') &&
@@ -641,6 +956,32 @@ function swiftCodeScan(source: string): { lineStarts: Set<number>; tokens: numbe
641
956
  const compiledSource = (file: string, contents: string) =>
642
957
  file.endsWith('.swift') ? swiftSourceAsIOS(contents) : contents
643
958
 
959
+ /** a dependency package's build copy: the published tree with every Swift
960
+ * source rewritten as app sources are, so an unchanged upstream package that
961
+ * uses `@objc` and `#selector` reaches PeachObjC. its manifests stay as
962
+ * published and the upstream tree is never written. */
963
+ export function prepareSwiftDependency(source: string, destination: string): void {
964
+ rmSync(destination, { recursive: true, force: true })
965
+ const copy = (from: string, to: string, root: boolean) => {
966
+ mkdirSync(to, { recursive: true })
967
+ for (const entry of readdirSync(from, { withFileTypes: true })) {
968
+ if (entry.name === '.git' || entry.name === '.build' || entry.name === '.swiftpm')
969
+ continue
970
+ const file = path.join(from, entry.name)
971
+ const target = path.join(to, entry.name)
972
+ if (entry.isDirectory()) copy(file, target, false)
973
+ else if (
974
+ entry.isFile() &&
975
+ entry.name.endsWith('.swift') &&
976
+ !(root && /^Package(@swift-[\d.]+)?\.swift$/.test(entry.name))
977
+ )
978
+ writeFileSync(target, compiledSource(file, readFileSync(file, 'utf8')))
979
+ else cpSync(file, target, { verbatimSymlinks: true })
980
+ }
981
+ }
982
+ copy(source, destination, true)
983
+ }
984
+
644
985
  export function writeSwiftProject(
645
986
  layout: SwiftProjectLayout,
646
987
  input: SwiftCompileInput,
@@ -697,7 +1038,7 @@ export function writeSwiftProject(
697
1038
  // anchored on lines the template already has, so the template stays a
698
1039
  // valid manifest for a compiler build that predates the One module
699
1040
  const product = '.product(name: "CoreLocation", package: "sootsim-swift"),'
700
- const flags = `"-Osize"${OBJC_IMPLICIT_FLAGS}`
1041
+ const flags = `"-Osize"${FOUNDATION_IMPLICIT_FLAGS}`
701
1042
  if (!manifest.includes(product) || !manifest.includes(flags)) {
702
1043
  throw new Error(
703
1044
  'scripts/contrast-app-Package.swift lost the lines the One module links at',
@@ -850,7 +1191,8 @@ export function compileSwiftProjectUnit(
850
1191
  const macroPlugins = await ensureMacroPlugins(moduleRoot, options.toolchainBin)
851
1192
  // memoized per toolchain, so only a process's first build waits on it,
852
1193
  // and that one reads and gzips it while swift builds
853
- const icu = swiftIcuAsset(options.toolchainBin, options.release)
1194
+ const sdk = swiftModuleSdk(moduleRoot).wasmSdkId
1195
+ const icu = swiftIcuAsset(options.toolchainBin, sdk)
854
1196
  try {
855
1197
  await run(
856
1198
  swift,
@@ -861,7 +1203,7 @@ export function compileSwiftProjectUnit(
861
1203
  '--package-path',
862
1204
  root,
863
1205
  '--swift-sdk',
864
- `${options.release}_wasm`,
1206
+ sdk,
865
1207
  '-c',
866
1208
  'release',
867
1209
  '-Xswiftc',
@@ -3,6 +3,7 @@
3
3
  // (scripts/ops/swift-distribution-publish.ts) and the CLI that installs it
4
4
  // (swift-distribution.ts). docs/swift-distribution.md owns the design.
5
5
  import { isRecord } from './is-record'
6
+ import type { SwiftWasmSdk } from './swift-toolchain'
6
7
 
7
8
  /** the file at the root of an unpacked distribution, and its install marker. */
8
9
  export const SWIFT_DISTRIBUTION_MANIFEST = 'distribution.json'
@@ -23,12 +24,11 @@ export function swiftDistributionHost(
23
24
  }
24
25
 
25
26
  /** the host-independent half: wasm32 modules and their objects. */
26
- export interface SwiftDistributionWasm {
27
+ export interface SwiftDistributionWasm extends SwiftWasmSdk {
27
28
  /** the digest of the module sources it was built from (swiftModuleDigest). */
28
29
  id: string
29
30
  /** the swift.org release that built it, the only one that can read it. */
30
31
  release: string
31
- wasmSdkChecksum: string
32
32
  /** the importable Swift modules under modules/. */
33
33
  modules: string[]
34
34
  /** the modules' wasm32 objects, relative to the root, in link order. */
@@ -47,10 +47,9 @@ export interface SwiftDistributionManifest extends SwiftDistributionWasm {
47
47
  }
48
48
 
49
49
  /** the published archives one CLI build installs, committed beside this file. */
50
- export interface SwiftDistributionLock {
50
+ export interface SwiftDistributionLock extends SwiftWasmSdk {
51
51
  id: string
52
52
  release: string
53
- wasmSdkChecksum: string
54
53
  /** the commit the module sources were built from. */
55
54
  source: string
56
55
  hosts: Record<SwiftDistributionHost, { sha256: string; size: number }>
@@ -66,6 +65,8 @@ export function parseSwiftDistributionManifest(
66
65
  !isRecord(value) ||
67
66
  typeof value.id !== 'string' ||
68
67
  typeof value.release !== 'string' ||
68
+ typeof value.wasmSdkId !== 'string' ||
69
+ typeof value.wasmSdkUrl !== 'string' ||
69
70
  typeof value.wasmSdkChecksum !== 'string' ||
70
71
  !isStrings(value.modules) ||
71
72
  !isStrings(value.objects) ||
@@ -82,6 +83,8 @@ export function parseSwiftDistributionManifest(
82
83
  return {
83
84
  id: value.id,
84
85
  release: value.release,
86
+ wasmSdkId: value.wasmSdkId,
87
+ wasmSdkUrl: value.wasmSdkUrl,
85
88
  wasmSdkChecksum: value.wasmSdkChecksum,
86
89
  modules: value.modules,
87
90
  objects: value.objects,
@@ -100,6 +103,8 @@ export function parseSwiftDistributionLock(value: unknown): SwiftDistributionLoc
100
103
  typeof value.id !== 'string' ||
101
104
  !/^[a-f0-9]{16}$/.test(value.id) ||
102
105
  typeof value.release !== 'string' ||
106
+ typeof value.wasmSdkId !== 'string' ||
107
+ typeof value.wasmSdkUrl !== 'string' ||
103
108
  typeof value.wasmSdkChecksum !== 'string' ||
104
109
  typeof value.source !== 'string' ||
105
110
  !isRecord(value.hosts)
@@ -122,6 +127,8 @@ export function parseSwiftDistributionLock(value: unknown): SwiftDistributionLoc
122
127
  return {
123
128
  id: value.id,
124
129
  release: value.release,
130
+ wasmSdkId: value.wasmSdkId,
131
+ wasmSdkUrl: value.wasmSdkUrl,
125
132
  wasmSdkChecksum: value.wasmSdkChecksum,
126
133
  source: value.source,
127
134
  hosts: {
@@ -1,20 +1,22 @@
1
1
  {
2
- "id": "6f2d91274094c8af",
2
+ "id": "ea62f48cbd9a2e88",
3
3
  "release": "swift-6.3-RELEASE",
4
- "wasmSdkChecksum": "9fa4016ee632c7e9e906608ec3b55cf13dfc4dff44e47574c5af58064dc33fd9",
5
- "source": "27df8ca4ecdc5369d51f08fe54ac32a1f21c5949",
4
+ "wasmSdkId": "swift-6.3-RELEASE_wasm-peach-728c7263",
5
+ "wasmSdkUrl": "https://r2.sootsim.com/swift-wasm-sdk/swift-6.3-RELEASE_wasm-peach-728c7263.artifactbundle.tar.gz",
6
+ "wasmSdkChecksum": "5df8ab7be805d67d69d8dcd3ef7eec940b4eb1f3261410eba09d891ee170c559",
7
+ "source": "2cb10cefd9d1815ba7396966712cd3b8b111af1a",
6
8
  "hosts": {
7
9
  "darwin-arm64": {
8
- "sha256": "606751627cfeafedfeb6a0abefc7f9a734935b7fd222d93ead096a6d89695a98",
9
- "size": 4551053
10
+ "sha256": "02001da13c7e4cd3d2efd027c49f0e95a7906d5d27234b848ba2bcbc43d0d6dc",
11
+ "size": 7016511
10
12
  },
11
13
  "linux-x64": {
12
- "sha256": "7d7cb0adc43af4b83576979693a9a4994abca5d773e5550f4f154939fe08b091",
13
- "size": 4556463
14
+ "sha256": "3b5fc0fdfd2f46bab1b74bf5e9d38d01489891dcfe46f3ef5901e1d7b47e8c86",
15
+ "size": 7021925
14
16
  },
15
17
  "linux-arm64": {
16
- "sha256": "78c7c76b8a29a3ec797cd410fd882a6f1dfb349f1785e0cf5cf0d8aebb2d96a9",
17
- "size": 4555726
18
+ "sha256": "186af6b69296088b48a514eaba23c8e0edd8084ebb7dccf7aa86f5d8953a61d5",
19
+ "size": 7021099
18
20
  }
19
21
  }
20
22
  }