peachsim 0.1.679 → 0.1.681

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 (84) hide show
  1. package/cli/commands/daemon-mac-app.ts +11 -2
  2. package/cli/commands/daemon.ts +2 -3
  3. package/cli/commands/swift.ts +40 -19
  4. package/cli/outbound-endpoints.ts +8 -0
  5. package/dist-lib/agent-daemon-client.cjs +1 -1
  6. package/dist-lib/agent-events.cjs +1 -1
  7. package/dist-lib/agent-identity.cjs +1 -1
  8. package/dist-lib/agent-sessions.cjs +1 -1
  9. package/dist-lib/attached-projects.cjs +1 -1
  10. package/dist-lib/auth/shared-session.cjs +1 -1
  11. package/dist-lib/backend-origin.cjs +1 -1
  12. package/dist-lib/beta.cjs +1 -1
  13. package/dist-lib/beta.mjs +1 -1
  14. package/dist-lib/bridge-constants.cjs +1 -1
  15. package/dist-lib/bridge-contract-input.cjs +1 -1
  16. package/dist-lib/bridge-contract-input.mjs +1 -1
  17. package/dist-lib/bridge-contract.cjs +1 -1
  18. package/dist-lib/bridge-contract.mjs +1 -1
  19. package/dist-lib/capture-contract.cjs +1 -1
  20. package/dist-lib/capture-contract.mjs +1 -1
  21. package/dist-lib/cli-constants.cjs +1 -1
  22. package/dist-lib/cloud-contract.cjs +1 -1
  23. package/dist-lib/cloud-contract.mjs +1 -1
  24. package/dist-lib/cloud-test-args.cjs +1 -1
  25. package/dist-lib/cloud-test-args.mjs +1 -1
  26. package/dist-lib/cloud.cjs +1 -1
  27. package/dist-lib/cloud.mjs +1 -1
  28. package/dist-lib/config.cjs +1 -1
  29. package/dist-lib/detox/index.cjs +1 -1
  30. package/dist-lib/dev-bundle-resolution.cjs +1 -1
  31. package/dist-lib/home-paths.cjs +1 -1
  32. package/dist-lib/host/bridge-host.cjs +2548 -2327
  33. package/dist-lib/host/fetch-proxy-handler.cjs +5 -13
  34. package/dist-lib/host/fetch-proxy-overrides.cjs +2 -6
  35. package/dist-lib/host/fetch-proxy-overrides.mjs +2 -6
  36. package/dist-lib/host/replacement-module-handler.cjs +1 -1
  37. package/dist-lib/host/websocket-proxy.cjs +1 -1
  38. package/dist-lib/index.cjs +1 -1
  39. package/dist-lib/jump-to-source-babel.cjs +1 -1
  40. package/dist-lib/jump-to-source-native.cjs +1 -1
  41. package/dist-lib/kotlin-host.cjs +1 -1
  42. package/dist-lib/menu.cjs +1 -1
  43. package/dist-lib/menu.mjs +1 -1
  44. package/dist-lib/metro-fingerprint-registry.cjs +1 -1
  45. package/dist-lib/metro-fingerprint-registry.mjs +1 -1
  46. package/dist-lib/metro-production-bundle.cjs +1 -1
  47. package/dist-lib/metro-production-bundle.mjs +1 -1
  48. package/dist-lib/metro.cjs +1 -1
  49. package/dist-lib/native-app-identity.cjs +1 -1
  50. package/dist-lib/native-app-identity.mjs +1 -1
  51. package/dist-lib/native-firebase-metadata.cjs +1 -1
  52. package/dist-lib/native-firebase-metadata.mjs +1 -1
  53. package/dist-lib/plist.cjs +1 -1
  54. package/dist-lib/plist.mjs +1 -1
  55. package/dist-lib/profiles.cjs +1 -1
  56. package/dist-lib/public-brand.cjs +1 -1
  57. package/dist-lib/react-native-host-modules.cjs +1 -1
  58. package/dist-lib/react-native-host-modules.mjs +1 -1
  59. package/dist-lib/render-mode.cjs +1 -1
  60. package/dist-lib/scripts/dev-server-scanner.cjs +1 -1
  61. package/dist-lib/sdk.cjs +1 -1
  62. package/dist-lib/sdk.mjs +1 -1
  63. package/dist-lib/skills.cjs +2296 -2053
  64. package/dist-lib/swift-compile.cjs +78 -12
  65. package/dist-lib/swift-compile.mjs +76 -12
  66. package/dist-lib/swift-package.cjs +1 -1
  67. package/dist-lib/swift-package.mjs +1 -1
  68. package/dist-lib/swift-submit.cjs +1 -1
  69. package/dist-lib/swift-submit.mjs +1 -1
  70. package/dist-lib/swift-toolchain.cjs +115 -0
  71. package/dist-lib/swift.cjs +1 -1
  72. package/dist-lib/vite-swift.cjs +470 -149
  73. package/dist-lib/vite.cjs +1 -1
  74. package/package.json +7 -1
  75. package/skills/contrast/SKILL.md +1 -1
  76. package/src/expo-swift-host.ts +9 -13
  77. package/src/host/fetch-proxy-handler.ts +11 -10
  78. package/src/host/fetch-proxy-overrides.ts +9 -10
  79. package/src/swift-compile.ts +76 -10
  80. package/src/swift-distribution-contract.ts +138 -0
  81. package/src/swift-distribution.lock.json +20 -0
  82. package/src/swift-distribution.ts +108 -0
  83. package/src/swift-host.ts +8 -30
  84. package/src/swift-toolchain.ts +102 -0
package/dist-lib/vite.cjs CHANGED
@@ -1,4 +1,4 @@
1
- /*! rnx v0.1.679 | (c) 2026 Tamagui LLC | Proprietary — see LICENSE */
1
+ /*! rnx v0.1.681 | (c) 2026 Tamagui LLC | Proprietary — see LICENSE */
2
2
  let __sootsim_import_meta_url = ''; try { __sootsim_import_meta_url = require('url').pathToFileURL(__filename).href; } catch {}
3
3
  "use strict";
4
4
  var __create = Object.create;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "peachsim",
3
- "version": "0.1.679",
3
+ "version": "0.1.681",
4
4
  "description": "Vite and Metro plugins, testing drivers, and SDK exports for peach.",
5
5
  "author": "Tamagui LLC",
6
6
  "license": "SEE LICENSE IN LICENSE",
@@ -73,6 +73,12 @@
73
73
  "import": "./dist-lib/swift-compile.mjs",
74
74
  "default": "./dist-lib/swift-compile.cjs"
75
75
  },
76
+ "./swift-toolchain": {
77
+ "types": "./src/swift-toolchain.ts",
78
+ "source": "./src/swift-toolchain.ts",
79
+ "bun": "./src/swift-toolchain.ts",
80
+ "default": "./dist-lib/swift-toolchain.cjs"
81
+ },
76
82
  "./metro": {
77
83
  "source": "./src/metro-plugin.ts",
78
84
  "default": "./dist-lib/metro.cjs"
@@ -19,7 +19,7 @@ automation, inspecting the render tree, and managing sims.
19
19
 
20
20
  | command | description |
21
21
  | --- | --- |
22
- | `peach swift` | preview a SwiftPM app with hosted compilation and live Swift edits |
22
+ | `peach swift` | preview a SwiftPM app with live Swift edits, compiled on this machine |
23
23
  | `peach kotlin` | run an Android Compose app module from its launcher activity |
24
24
  | `peach maestro` | author, generate, and run Maestro YAML flows against peach |
25
25
  | `peach detox` | run existing Detox suites against peach on headless Chromium |
@@ -9,13 +9,8 @@ import path from 'node:path'
9
9
  import { promisify } from 'node:util'
10
10
  import { RNX_FORKED_SCRIPT_ENV } from '../cli/internal-child'
11
11
  import { isLoopbackHost } from './backend-origin'
12
- import {
13
- artifactFor,
14
- icuUrl,
15
- localSwiftToolchain,
16
- projectFor,
17
- serveSwiftPackageAsset,
18
- } from './swift-host'
12
+ import { resolveSwiftModule } from './swift-distribution'
13
+ import { artifactFor, icuUrl, projectFor, serveSwiftPackageAsset } from './swift-host'
19
14
  import { MAX_SWIFT_COMPILE_FILES, MAX_SWIFT_COMPILE_SOURCE_BYTES } from './swift-submit'
20
15
  import type { IncomingMessage, ServerResponse } from 'node:http'
21
16
 
@@ -212,11 +207,12 @@ export async function handleExpoSwiftRequest(
212
207
  pending = (async () => {
213
208
  const files = await collectExpoSwiftSources(root)
214
209
  if (!files) return null
215
- // app Swift compiles only on this machine, never on a remote service;
216
- // an install without the SwiftUI module and toolchain leaves the
217
- // app's own native modules unregistered, as an unlinked module is.
218
- const moduleRoot = path.resolve(import.meta.dirname, '../../sootsim-swift')
219
- if (!localSwiftToolchain(moduleRoot)) return null
210
+ // app Swift compiles only on this machine, never on a remote service,
211
+ // against the checkout's module or the distribution PEACH_SWIFT_ENDPOINT
212
+ // names. with neither, the app's own native modules stay unregistered,
213
+ // as an unlinked module is.
214
+ const module = await resolveSwiftModule()
215
+ if (!module) return null
220
216
  const key = createHash('sha256').update(fs.realpathSync(root)).digest('hex')
221
217
  const packagePath = path.join(os.tmpdir(), 'peach-expo-swift', key)
222
218
  const sources = path.join(packagePath, 'Sources')
@@ -231,7 +227,7 @@ export async function handleExpoSwiftRequest(
231
227
  const artifact = await artifactFor(
232
228
  projectFor(packagePath),
233
229
  EXPO_SWIFT_ENTRY,
234
- moduleRoot,
230
+ module.root,
235
231
  )
236
232
  const host = req.headers.host
237
233
  if (!host) throw new Error('Expo Swift request has no host')
@@ -28,7 +28,6 @@ import https from 'https'
28
28
  import { finished, pipeline } from 'stream/promises'
29
29
  import { isLoopbackHost, normalizeHostname } from '../backend-origin.ts'
30
30
  import {
31
- FETCH_PROXY_BROWSER_USER_AGENT,
32
31
  getFetchProxyTargetHeaders,
33
32
  resolveFetchProxyTargetUrl,
34
33
  } from './fetch-proxy-overrides.ts'
@@ -113,12 +112,7 @@ export function buildFetchProxyHeaders(
113
112
  if (STRIP_FETCH_PROXY_HEADERS.has(key.toLowerCase())) continue
114
113
  headers[key] = Array.isArray(value) ? value.join(', ') : value
115
114
  }
116
- Object.assign(
117
- headers,
118
- targetUrl
119
- ? getFetchProxyTargetHeaders(targetUrl)
120
- : { 'user-agent': FETCH_PROXY_BROWSER_USER_AGENT },
121
- )
115
+ Object.assign(headers, targetUrl ? getFetchProxyTargetHeaders(targetUrl) : {})
122
116
  return headers
123
117
  }
124
118
 
@@ -306,9 +300,16 @@ export async function handleFetchProxyRequest(
306
300
  isLoopbackHost(norm) &&
307
301
  (err as { code?: string })?.code === 'ECONNREFUSED'
308
302
  ) {
309
- const altHost =
310
- norm === '::1' ? '127.0.0.1' : norm === '127.0.0.1' ? '::1' : '127.0.0.1'
311
- if (altHost !== norm) {
303
+ // a name like localhost resolves to one family first, and a dev server
304
+ // (expo start --localhost on Linux) may listen on only the other. the
305
+ // URL setter ignores an unbracketed IPv6 hostname
306
+ const altHosts =
307
+ norm === '::1'
308
+ ? ['127.0.0.1']
309
+ : norm === '127.0.0.1'
310
+ ? ['[::1]']
311
+ : ['[::1]', '127.0.0.1']
312
+ for (const altHost of altHosts) {
312
313
  try {
313
314
  const altUrl = new URL(upstreamUrl.href)
314
315
  altUrl.hostname = altHost
@@ -1,8 +1,15 @@
1
1
  // shared upstream header policy for SootSim's CORS-bypassing fetch proxy.
2
2
  // requests still forward tenant auth and app headers, but the proxy transport
3
- // defaults to native-app semantics: no browser Origin or Referer. web-backed
4
- // mobile APIs that require a specific web origin opt in below.
3
+ // defaults to native-app semantics: no browser Origin, Referer, Sec-Fetch-*,
4
+ // or User-Agent — an NSURLSession request on a real device sends none of
5
+ // those to a third-party host. web-backed mobile APIs that require a
6
+ // specific web origin or user-agent opt in below.
5
7
 
8
+ // only for a host override below that explicitly wants to look like a
9
+ // desktop browser (e.g. a web-backed API with no native-app allowance).
10
+ // never the proxy's default: a key-restricted upstream (address
11
+ // autocomplete, places lookups) sees this and a bare Origin/Referer the same
12
+ // way a real device's absent ones read — not a browser, not restricted.
6
13
  export const FETCH_PROXY_BROWSER_USER_AGENT =
7
14
  'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 ' +
8
15
  '(KHTML, like Gecko) Chrome/146.0.0.0 Safari/537.36'
@@ -10,7 +17,6 @@ export const FETCH_PROXY_BROWSER_USER_AGENT =
10
17
  const HOST_HEADER_OVERRIDES: Array<{
11
18
  hostSuffix: string
12
19
  headers: Record<string, string>
13
- suppressBrowserUserAgent?: boolean
14
20
  }> = [
15
21
  {
16
22
  hostSuffix: 'uniswap.org',
@@ -18,16 +24,12 @@ const HOST_HEADER_OVERRIDES: Array<{
18
24
  origin: 'https://app.uniswap.org',
19
25
  referer: 'https://app.uniswap.org/',
20
26
  },
21
- // uniswap's native gateway accepts the app origin, but forcing a desktop
22
- // browser ua on native api posts returns a bogus 414/tcp-stack response.
23
- suppressBrowserUserAgent: true,
24
27
  },
25
28
  ]
26
29
 
27
30
  function headerOverridesFor(hostname: string):
28
31
  | {
29
32
  headers: Record<string, string>
30
- suppressBrowserUserAgent?: boolean
31
33
  }
32
34
  | undefined {
33
35
  const host = hostname.toLowerCase()
@@ -84,9 +86,6 @@ export function getFetchProxyTargetHeaders(targetUrl: URL): Record<string, strin
84
86
  const hostOverrides = headerOverridesFor(targetUrl.hostname)
85
87
  return {
86
88
  'accept-encoding': 'identity',
87
- ...(hostOverrides?.suppressBrowserUserAgent
88
- ? {}
89
- : { 'user-agent': FETCH_PROXY_BROWSER_USER_AGENT }),
90
89
  ...hostOverrides?.headers,
91
90
  }
92
91
  }
@@ -13,6 +13,11 @@ import {
13
13
  import os from 'node:os'
14
14
  import path from 'node:path'
15
15
  import { promisify } from 'node:util'
16
+ import {
17
+ parseSwiftDistributionManifest,
18
+ SWIFT_DISTRIBUTION_MANIFEST,
19
+ type SwiftDistributionManifest,
20
+ } from './swift-distribution-contract'
16
21
  import { swiftIcuAsset, type SwiftIcuAsset } from './swift-icu'
17
22
  import {
18
23
  swiftManifestTargets,
@@ -68,9 +73,23 @@ export interface SwiftProjectLayout {
68
73
  multi: boolean
69
74
  }
70
75
 
76
+ /**
77
+ * the prebuilt distribution at a module root, or null for a sootsim-swift
78
+ * source checkout. an installed peach links the distribution: compiled
79
+ * modules, one static library and host macro plugins, and no source
80
+ * (docs/swift-distribution.md).
81
+ */
82
+ export function swiftDistributionAt(root: string): SwiftDistributionManifest | null {
83
+ const file = path.join(root, SWIFT_DISTRIBUTION_MANIFEST)
84
+ if (!existsSync(file)) return null
85
+ return parseSwiftDistributionManifest(JSON.parse(readFileSync(file, 'utf8')))
86
+ }
87
+
71
88
  // toolchain.json is an input for its wasm sdk checksum: the sdk's icu blob,
72
89
  // which the host fills into every artifact, is part of what the address names.
90
+ // a distribution's manifest names every file it ships by digest.
73
91
  export function swiftModuleInputFiles(root: string): string[] {
92
+ if (swiftDistributionAt(root)) return [SWIFT_DISTRIBUTION_MANIFEST]
74
93
  const files: string[] = [
75
94
  'Package.swift',
76
95
  'scripts/contrast-app-Package.swift',
@@ -97,6 +116,9 @@ async function ensureMacroPlugins(
97
116
  moduleRoot: string,
98
117
  toolchainBin: string,
99
118
  ): Promise<string[]> {
119
+ const distribution = swiftDistributionAt(moduleRoot)
120
+ if (distribution)
121
+ return distribution.plugins.map((plugin) => path.join(moduleRoot, plugin))
100
122
  const dir = path.join(moduleRoot, '.build/host/RnxPreviewMacros')
101
123
  // linux names a plugin's module from lib<Module>.so
102
124
  const ext = process.platform === 'darwin' ? 'dylib' : 'so'
@@ -131,7 +153,9 @@ export function clearLinkedModuleDigests(root?: string): void {
131
153
  else linkedModuleDigests.delete(root)
132
154
  }
133
155
 
134
- function linkedModuleDigest(root: string): Buffer {
156
+ /** the digest of a module checkout's inputs: what an artifact address and a
157
+ * distribution's id name it by. */
158
+ export function swiftModuleDigest(root: string): Buffer {
135
159
  const files = swiftModuleInputFiles(root)
136
160
  const stampHash = createHash('sha256')
137
161
  for (const file of files) {
@@ -235,7 +259,7 @@ export function swiftArtifactHash(
235
259
  // v4: sources compile through swiftSourceAsIOS)
236
260
  hash.update(`swift-compile/v7\n${release}\n`)
237
261
  if (input.oneModule) hash.update('one-module\n')
238
- hash.update(linkedModuleDigest(moduleRoot))
262
+ hash.update(swiftModuleDigest(moduleRoot))
239
263
  for (const file of Object.keys(input.files).sort()) {
240
264
  hash.update(createHash('sha256').update(file).digest())
241
265
  hash.update(createHash('sha256').update(input.files[file]).digest())
@@ -275,8 +299,10 @@ export function emitSwiftPackageManifest(args: {
275
299
  siblings: Map<string, string[]>
276
300
  moduleRoot: string
277
301
  oneModule?: boolean
302
+ /** link the prebuilt distribution at moduleRoot instead of its sources. */
303
+ distribution?: SwiftDistributionManifest
278
304
  }): string {
279
- const { targets, siblings, moduleRoot, oneModule } = args
305
+ const { targets, siblings, moduleRoot, oneModule, distribution } = args
280
306
  const executable = targets.find((target) => target.executable)
281
307
  if (!executable) throw new Error('swift-compile: no executable target to emit')
282
308
  // each target compiles in the language mode and default isolation its
@@ -285,19 +311,42 @@ export function emitSwiftPackageManifest(args: {
285
311
  const isolation = target.mainActorIsolation
286
312
  ? ' .defaultIsolation(MainActor.self),'
287
313
  : ''
288
- const swiftSettings = `swiftSettings: [.swiftLanguageMode(.v${target.languageMode}),${isolation} .unsafeFlags(["-Osize"${OBJC_IMPLICIT_FLAGS}${oneModule ? ONE_IMPLICIT_FLAGS : ''}])]`
314
+ // a distribution's modules import from its modules/ directory, and its
315
+ // objects link as inputs, exactly as a source build links every object it
316
+ // compiled: whole, and ahead of the sdk libraries, so PeachICU's
317
+ // reservation keeps icu's data member out. merged into one relocatable
318
+ // object (wasm-ld -r) or linked from an archive, a protocol conformance
319
+ // goes unfound at runtime or icu links twice (RAN, the Expo fixture). the
320
+ // libraries the objects autolink follow, since the driver reads autolink
321
+ // entries only from objects it compiled.
322
+ const imports = distribution
323
+ ? `, "-I", ${JSON.stringify(path.join(moduleRoot, 'modules'))}`
324
+ : ''
325
+ const swiftSettings = `swiftSettings: [.swiftLanguageMode(.v${target.languageMode}),${isolation} .unsafeFlags(["-Osize"${OBJC_IMPLICIT_FLAGS}${oneModule ? ONE_IMPLICIT_FLAGS : ''}${imports}])]`
289
326
  const deps = [
290
- '.product(name: "SwiftUI", package: "sootsim-swift")',
291
- ...(oneModule ? [ONE_PRODUCT] : []),
327
+ ...(distribution
328
+ ? []
329
+ : [
330
+ '.product(name: "SwiftUI", package: "sootsim-swift")',
331
+ ...(oneModule ? [ONE_PRODUCT] : []),
332
+ ]),
292
333
  ...(siblings.get(target.name) ?? []).map((sibling) => `"${sibling}"`),
293
334
  ].join(', ')
335
+ const library = distribution
336
+ ? [
337
+ ...distribution.objects.map((object) => path.join(moduleRoot, object)),
338
+ ...distribution.link,
339
+ ]
340
+ .map((flag) => `, ${JSON.stringify(flag)}`)
341
+ .join('')
342
+ : ''
294
343
  const kind = target.executable ? '.executableTarget' : '.target'
295
344
  const link = target.executable
296
345
  ? `,
297
346
  linkerSettings: [
298
347
  .unsafeFlags([
299
348
  "-Xclang-linker", "-mexec-model=reactor",
300
- "-Xlinker", "--export-if-defined=__main_argc_argv",
349
+ "-Xlinker", "--export-if-defined=__main_argc_argv"${library},
301
350
  ]),
302
351
  .unsafeFlags(["-Xlinker", "--strip-all"], .when(configuration: .release)),
303
352
  ]`
@@ -321,7 +370,7 @@ export function emitSwiftPackageManifest(args: {
321
370
  'let package = Package(',
322
371
  ' name: "app",',
323
372
  ` products: [.executable(name: "${executable.name}", targets: ["${executable.name}"])],`,
324
- ` dependencies: [.package(path: "${moduleRoot}")],`,
373
+ ` dependencies: [${distribution ? '' : `.package(path: "${moduleRoot}")`}],`,
325
374
  ' targets: [',
326
375
  ...targets.map(stanza),
327
376
  ' ]',
@@ -548,7 +597,22 @@ export function writeSwiftProject(
548
597
  input: SwiftCompileInput,
549
598
  moduleRoot: string,
550
599
  ): void {
551
- const targets = compileTargets(input)
600
+ const distribution = swiftDistributionAt(moduleRoot)
601
+ // a distribution ships no manifest template, so a project without its own
602
+ // manifest compiles as the one App target the template declares
603
+ const targets: SwiftPackageTarget[] =
604
+ distribution && compileTargets(input).length === 0
605
+ ? [
606
+ {
607
+ name: 'App',
608
+ path: path.relative(layout.root, layout.sources),
609
+ executable: true,
610
+ languageMode: 5,
611
+ mainActorIsolation: false,
612
+ resources: false,
613
+ },
614
+ ]
615
+ : compileTargets(input)
552
616
  const files = new Map<string, string>()
553
617
  // swiftpm plans a build root's build once and reuses the plan until a
554
618
  // manifest changes, so a file added to the module would never compile
@@ -580,9 +644,10 @@ export function writeSwiftProject(
580
644
  }
581
645
  files.set(path.join(layout.root, 'Package.swift'), manifest + moduleFiles)
582
646
  } else {
647
+ const base = layout.multi ? layout.root : layout.sources
583
648
  for (const [file, contents] of Object.entries(input.files)) {
584
649
  if (file === 'Package.swift') continue
585
- files.set(path.join(layout.root, file), compiledSource(file, contents))
650
+ files.set(path.join(base, file), compiledSource(file, contents))
586
651
  }
587
652
  // SwiftPM writes this accessor into a target that declares resources. the
588
653
  // emitted manifest declares none, since Peach serves every target's
@@ -608,6 +673,7 @@ export function writeSwiftProject(
608
673
  siblings: swiftSiblingDependencies(input.files, targets),
609
674
  moduleRoot,
610
675
  oneModule: input.oneModule,
676
+ distribution: distribution ?? undefined,
611
677
  }) + moduleFiles,
612
678
  )
613
679
  }
@@ -0,0 +1,138 @@
1
+ // the prebuilt Swift distribution's shapes, shared by its builder
2
+ // (packages/sootsim-swift/scripts/build-distribution.ts), its publisher
3
+ // (scripts/ops/swift-distribution-publish.ts) and the CLI that installs it
4
+ // (swift-distribution.ts). docs/swift-distribution.md owns the design.
5
+ import { isRecord } from './is-record'
6
+
7
+ /** the file at the root of an unpacked distribution, and its install marker. */
8
+ export const SWIFT_DISTRIBUTION_MANIFEST = 'distribution.json'
9
+
10
+ export const SWIFT_DISTRIBUTION_HOSTS = [
11
+ 'darwin-arm64',
12
+ 'linux-x64',
13
+ 'linux-arm64',
14
+ ] as const
15
+ export type SwiftDistributionHost = (typeof SWIFT_DISTRIBUTION_HOSTS)[number]
16
+
17
+ export function swiftDistributionHost(
18
+ platform: string,
19
+ arch: string,
20
+ ): SwiftDistributionHost | null {
21
+ const host = `${platform}-${arch}`
22
+ return SWIFT_DISTRIBUTION_HOSTS.find((candidate) => candidate === host) ?? null
23
+ }
24
+
25
+ /** the host-independent half: wasm32 modules and their objects. */
26
+ export interface SwiftDistributionWasm {
27
+ /** the digest of the module sources it was built from (swiftModuleDigest). */
28
+ id: string
29
+ /** the swift.org release that built it, the only one that can read it. */
30
+ release: string
31
+ wasmSdkChecksum: string
32
+ /** the importable Swift modules under modules/. */
33
+ modules: string[]
34
+ /** the modules' wasm32 objects, relative to the root, in link order. */
35
+ objects: string[]
36
+ /** linker flags the objects autolink. */
37
+ link: string[]
38
+ /** every shipped file, relative to the root, to its sha256. */
39
+ files: Record<string, string>
40
+ }
41
+
42
+ /** an unpacked distribution: the wasm half plus one host's macro plugins. */
43
+ export interface SwiftDistributionManifest extends SwiftDistributionWasm {
44
+ host: SwiftDistributionHost
45
+ /** macro plugin libraries, relative to the root. */
46
+ plugins: string[]
47
+ }
48
+
49
+ /** the published archives one CLI build installs, committed beside this file. */
50
+ export interface SwiftDistributionLock {
51
+ id: string
52
+ release: string
53
+ wasmSdkChecksum: string
54
+ /** the commit the module sources were built from. */
55
+ source: string
56
+ hosts: Record<SwiftDistributionHost, { sha256: string; size: number }>
57
+ }
58
+
59
+ const isStrings = (value: unknown): value is string[] =>
60
+ Array.isArray(value) && value.every((item) => typeof item === 'string')
61
+
62
+ export function parseSwiftDistributionManifest(
63
+ value: unknown,
64
+ ): SwiftDistributionManifest {
65
+ if (
66
+ !isRecord(value) ||
67
+ typeof value.id !== 'string' ||
68
+ typeof value.release !== 'string' ||
69
+ typeof value.wasmSdkChecksum !== 'string' ||
70
+ !isStrings(value.modules) ||
71
+ !isStrings(value.objects) ||
72
+ !isStrings(value.link) ||
73
+ !isRecord(value.files) ||
74
+ !Object.values(value.files).every((sha) => typeof sha === 'string') ||
75
+ typeof value.host !== 'string' ||
76
+ !isStrings(value.plugins)
77
+ ) {
78
+ throw new Error(`invalid Swift distribution ${SWIFT_DISTRIBUTION_MANIFEST}`)
79
+ }
80
+ const host = SWIFT_DISTRIBUTION_HOSTS.find((candidate) => candidate === value.host)
81
+ if (!host) throw new Error(`Swift distribution names an unknown host ${value.host}`)
82
+ return {
83
+ id: value.id,
84
+ release: value.release,
85
+ wasmSdkChecksum: value.wasmSdkChecksum,
86
+ modules: value.modules,
87
+ objects: value.objects,
88
+ link: value.link,
89
+ files: Object.fromEntries(
90
+ Object.entries(value.files).map(([file, sha]) => [file, String(sha)]),
91
+ ),
92
+ host,
93
+ plugins: value.plugins,
94
+ }
95
+ }
96
+
97
+ export function parseSwiftDistributionLock(value: unknown): SwiftDistributionLock {
98
+ if (
99
+ !isRecord(value) ||
100
+ typeof value.id !== 'string' ||
101
+ !/^[a-f0-9]{16}$/.test(value.id) ||
102
+ typeof value.release !== 'string' ||
103
+ typeof value.wasmSdkChecksum !== 'string' ||
104
+ typeof value.source !== 'string' ||
105
+ !isRecord(value.hosts)
106
+ ) {
107
+ throw new Error('invalid Swift distribution lock')
108
+ }
109
+ const hosts = value.hosts
110
+ const entry = (host: SwiftDistributionHost) => {
111
+ const item = hosts[host]
112
+ if (
113
+ !isRecord(item) ||
114
+ typeof item.sha256 !== 'string' ||
115
+ !/^[a-f0-9]{64}$/.test(item.sha256) ||
116
+ typeof item.size !== 'number'
117
+ ) {
118
+ throw new Error(`invalid Swift distribution lock entry for ${host}`)
119
+ }
120
+ return { sha256: item.sha256, size: item.size }
121
+ }
122
+ return {
123
+ id: value.id,
124
+ release: value.release,
125
+ wasmSdkChecksum: value.wasmSdkChecksum,
126
+ source: value.source,
127
+ hosts: {
128
+ 'darwin-arm64': entry('darwin-arm64'),
129
+ 'linux-x64': entry('linux-x64'),
130
+ 'linux-arm64': entry('linux-arm64'),
131
+ },
132
+ }
133
+ }
134
+
135
+ /** the archive's path under PEACH_SWIFT_ENDPOINT. */
136
+ export function swiftDistributionKey(id: string, host: SwiftDistributionHost): string {
137
+ return `${id}/${host}.tar.gz`
138
+ }
@@ -0,0 +1,20 @@
1
+ {
2
+ "id": "6f2d91274094c8af",
3
+ "release": "swift-6.3-RELEASE",
4
+ "wasmSdkChecksum": "9fa4016ee632c7e9e906608ec3b55cf13dfc4dff44e47574c5af58064dc33fd9",
5
+ "source": "27df8ca4ecdc5369d51f08fe54ac32a1f21c5949",
6
+ "hosts": {
7
+ "darwin-arm64": {
8
+ "sha256": "606751627cfeafedfeb6a0abefc7f9a734935b7fd222d93ead096a6d89695a98",
9
+ "size": 4551053
10
+ },
11
+ "linux-x64": {
12
+ "sha256": "7d7cb0adc43af4b83576979693a9a4994abca5d773e5550f4f154939fe08b091",
13
+ "size": 4556463
14
+ },
15
+ "linux-arm64": {
16
+ "sha256": "78c7c76b8a29a3ec797cd410fd882a6f1dfb349f1785e0cf5cf0d8aebb2d96a9",
17
+ "size": 4555726
18
+ }
19
+ }
20
+ }
@@ -0,0 +1,108 @@
1
+ // the SwiftUI module app Swift compiles against on this machine, and the
2
+ // swift.org toolchain that compiles it. a source checkout links
3
+ // packages/sootsim-swift; an installed peach downloads the prebuilt
4
+ // distribution from PEACH_SWIFT_ENDPOINT, verifies it against the lock this
5
+ // build carries, and unpacks it under the peach home
6
+ // (docs/swift-distribution.md). no path here asks Contrast to compile.
7
+ import fs from 'node:fs'
8
+ import path from 'node:path'
9
+ import { installVerifiedTarball } from '@contrast/runtime-delivery'
10
+ import { rnxHomeDir } from './home-paths'
11
+ import { swiftDistributionAt } from './swift-compile'
12
+ import {
13
+ parseSwiftDistributionLock,
14
+ SWIFT_DISTRIBUTION_MANIFEST,
15
+ swiftDistributionHost,
16
+ swiftDistributionKey,
17
+ } from './swift-distribution-contract'
18
+ import lockJson from './swift-distribution.lock.json' with { type: 'json' }
19
+ import { swiftToolchain } from './swift-toolchain'
20
+
21
+ export const SWIFT_ENDPOINT_ENV = 'PEACH_SWIFT_ENDPOINT'
22
+
23
+ export interface SwiftModule {
24
+ /** the module root compileSwiftProjectUnit links: a checkout or a distribution. */
25
+ root: string
26
+ release: string
27
+ toolchainBin: string
28
+ }
29
+
30
+ const installs = new Map<string, Promise<string>>()
31
+
32
+ /** the installed distribution's root, downloading it on first use, or null
33
+ * when PEACH_SWIFT_ENDPOINT is unset. */
34
+ export function swiftDistributionRoot(): Promise<string | null> {
35
+ const endpoint = process.env[SWIFT_ENDPOINT_ENV]?.trim().replace(/\/+$/, '')
36
+ if (!endpoint) return Promise.resolve(null)
37
+ const lock = parseSwiftDistributionLock(lockJson)
38
+ const host = swiftDistributionHost(process.platform, process.arch)
39
+ if (!host) {
40
+ throw new Error(
41
+ `peach has no Swift distribution for ${process.platform}-${process.arch}; it ships for macOS arm64 and Linux x64 and arm64`,
42
+ )
43
+ }
44
+ // the archive is useless without its compiler, so a missing or wrong
45
+ // toolchain fails before the download
46
+ swiftToolchain(lock.release, lock.wasmSdkChecksum)
47
+ const dir = path.join(rnxHomeDir(), 'swift', `${lock.id}-${host}`)
48
+ let pending = installs.get(dir)
49
+ if (!pending) {
50
+ pending = (async () => {
51
+ if (!fs.existsSync(path.join(dir, SWIFT_DISTRIBUTION_MANIFEST))) {
52
+ process.stderr.write(
53
+ `peach: downloading Swift distribution ${lock.id} (${host})…\n`,
54
+ )
55
+ await installVerifiedTarball({
56
+ url: `${endpoint}/${swiftDistributionKey(lock.id, host)}`,
57
+ digest: {
58
+ algorithm: 'sha256',
59
+ encoding: 'hex',
60
+ value: lock.hosts[host].sha256,
61
+ },
62
+ destDir: dir,
63
+ installedMarker: SWIFT_DISTRIBUTION_MANIFEST,
64
+ label: `Swift distribution ${lock.id} (${host})`,
65
+ })
66
+ }
67
+ const manifest = swiftDistributionAt(dir)
68
+ if (manifest?.id !== lock.id || manifest.host !== host) {
69
+ throw new Error(`${dir} does not hold Swift distribution ${lock.id} (${host})`)
70
+ }
71
+ return dir
72
+ })()
73
+ pending.catch(() => installs.delete(dir))
74
+ installs.set(dir, pending)
75
+ }
76
+ return pending
77
+ }
78
+
79
+ /** the module this process compiles app Swift against: the checkout beside a
80
+ * source peach, else the distribution, else null. */
81
+ export async function resolveSwiftModule(): Promise<SwiftModule | null> {
82
+ const checkout = path.resolve(import.meta.dirname, '../../sootsim-swift')
83
+ if (fs.existsSync(path.join(checkout, 'toolchain.json'))) {
84
+ // a checkout is implicit: without its toolchain, apps run without their
85
+ // Swift. a distribution is asked for, so its toolchain errors surface.
86
+ try {
87
+ return { root: checkout, ...swiftModuleToolchain(checkout) }
88
+ } catch {
89
+ return null
90
+ }
91
+ }
92
+ const root = await swiftDistributionRoot()
93
+ return root ? { root, ...swiftModuleToolchain(root) } : null
94
+ }
95
+
96
+ /** the release a module root was built for and its installed toolchain. */
97
+ export function swiftModuleToolchain(root: string): {
98
+ release: string
99
+ toolchainBin: string
100
+ } {
101
+ const pin: { release: string; wasmSdkChecksum: string } =
102
+ swiftDistributionAt(root) ??
103
+ JSON.parse(fs.readFileSync(path.join(root, 'toolchain.json'), 'utf8'))
104
+ return {
105
+ release: pin.release,
106
+ toolchainBin: swiftToolchain(pin.release, pin.wasmSdkChecksum),
107
+ }
108
+ }