peachsim 0.1.1881 → 0.1.1887

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 (160) hide show
  1. package/cli/commands/control.ts +11 -10
  2. package/cli/commands/reset.ts +1 -1
  3. package/cli/native-input.ts +1 -1
  4. package/cli/outbound-endpoints.ts +1 -1
  5. package/detox/index.ts +62 -1
  6. package/dist-lib/agent-daemon-client.cjs +1 -1
  7. package/dist-lib/agent-events.cjs +1 -1
  8. package/dist-lib/attached-projects.cjs +1 -1
  9. package/dist-lib/auth/shared-session.cjs +1 -1
  10. package/dist-lib/backend-origin.cjs +1 -1
  11. package/dist-lib/beta.cjs +1 -1
  12. package/dist-lib/beta.mjs +1 -1
  13. package/dist-lib/bridge-constants.cjs +1 -1
  14. package/dist-lib/bridge-contract-input.cjs +1 -1
  15. package/dist-lib/bridge-contract-input.mjs +1 -1
  16. package/dist-lib/bridge-contract.cjs +1 -1
  17. package/dist-lib/bridge-contract.mjs +1 -1
  18. package/dist-lib/bundle-channel.cjs +9079 -4305
  19. package/dist-lib/capture-contract.cjs +1 -1
  20. package/dist-lib/capture-contract.mjs +1 -1
  21. package/dist-lib/cloud-contract.cjs +1 -1
  22. package/dist-lib/cloud-contract.mjs +1 -1
  23. package/dist-lib/cloud-test-args.cjs +1 -1
  24. package/dist-lib/cloud-test-args.mjs +1 -1
  25. package/dist-lib/cloud.cjs +1 -1
  26. package/dist-lib/cloud.mjs +1 -1
  27. package/dist-lib/config.cjs +1 -1
  28. package/dist-lib/config.mjs +1 -1
  29. package/dist-lib/detox/index.cjs +35 -2
  30. package/dist-lib/dev-bundle-resolution.cjs +1 -1
  31. package/dist-lib/expo-swift-bundle.cjs +8609 -3976
  32. package/dist-lib/expo-swift-metadata.cjs +5 -1
  33. package/dist-lib/expo-swift-metadata.mjs +5 -1
  34. package/dist-lib/home-paths.cjs +1 -1
  35. package/dist-lib/host/bridge-host.cjs +9894 -5149
  36. package/dist-lib/host/fetch-proxy-handler.cjs +93 -13
  37. package/dist-lib/host/fetch-proxy-overrides.cjs +10 -2
  38. package/dist-lib/host/fetch-proxy-overrides.mjs +8 -2
  39. package/dist-lib/host/replacement-module-handler.cjs +1 -1
  40. package/dist-lib/host/websocket-proxy.cjs +1 -1
  41. package/dist-lib/index.cjs +538 -120
  42. package/dist-lib/jump-to-source-babel.cjs +1 -1
  43. package/dist-lib/jump-to-source-native.cjs +1 -1
  44. package/dist-lib/kotlin-host.cjs +1 -1
  45. package/dist-lib/menu.cjs +1 -1
  46. package/dist-lib/menu.mjs +1 -1
  47. package/dist-lib/metro-fingerprint-registry.cjs +1 -1
  48. package/dist-lib/metro-fingerprint-registry.mjs +1 -1
  49. package/dist-lib/metro-production-bundle.cjs +1 -1
  50. package/dist-lib/metro-production-bundle.mjs +1 -1
  51. package/dist-lib/metro.cjs +536 -118
  52. package/dist-lib/native-app-identity-project.cjs +408 -72
  53. package/dist-lib/native-app-identity-project.mjs +739 -375
  54. package/dist-lib/native-app-identity.cjs +37 -1
  55. package/dist-lib/native-app-identity.mjs +36 -1
  56. package/dist-lib/native-firebase-metadata.cjs +1 -1
  57. package/dist-lib/native-firebase-metadata.mjs +1 -1
  58. package/dist-lib/pdfium-raster.cjs +1 -1
  59. package/dist-lib/pdfium-raster.mjs +1 -1
  60. package/dist-lib/plist.cjs +1 -1
  61. package/dist-lib/plist.mjs +1 -1
  62. package/dist-lib/profiles.cjs +1 -1
  63. package/dist-lib/public-brand.cjs +1 -1
  64. package/dist-lib/public-origins-lib-esm.json +61 -28
  65. package/dist-lib/public-origins-lib.json +250 -92
  66. package/dist-lib/react-native-host-modules.cjs +1 -1
  67. package/dist-lib/react-native-host-modules.mjs +1 -1
  68. package/dist-lib/reap-browser.cjs +1 -1
  69. package/dist-lib/scripts/dev-server-scanner.cjs +1 -1
  70. package/dist-lib/sdk.cjs +1 -1
  71. package/dist-lib/sdk.mjs +1 -1
  72. package/dist-lib/skills.cjs +16568 -11674
  73. package/dist-lib/swift-compile.cjs +6874 -2537
  74. package/dist-lib/swift-compile.mjs +6207 -1866
  75. package/dist-lib/swift-package.cjs +20 -3
  76. package/dist-lib/swift-package.mjs +20 -3
  77. package/dist-lib/swift-submit.cjs +2 -2
  78. package/dist-lib/swift-submit.mjs +2 -2
  79. package/dist-lib/swift-toolchain.cjs +19 -1
  80. package/dist-lib/swift.cjs +1 -1
  81. package/dist-lib/vite-swift.cjs +8753 -4124
  82. package/dist-lib/vite.cjs +93 -13
  83. package/dist-lib/worklet-executable.cjs +1 -1
  84. package/dist-lib/worklet-executable.mjs +1 -1
  85. package/dist-types/packages/peach-engine/src/engine/canvaskit-api.d.ts +1 -1
  86. package/dist-types/packages/peach-engine/src/engine/fontDataContract.d.ts +2 -0
  87. package/dist-types/packages/peach-engine/src/render-worker/host-service-protocol.d.ts +3 -0
  88. package/dist-types/packages/peach-engine/src/render-worker/native-ui-protocol.d.ts +1 -0
  89. package/dist-types/packages/peach-engine/src/render-worker/protocol.d.ts +11 -1
  90. package/dist-types/packages/peach-engine/src/render-worker/shell-tree-wire.d.ts +2 -1
  91. package/dist-types/packages/peach-globals/src/nodeContract.d.ts +1 -0
  92. package/dist-types/packages/peach-globals/src/testBridgeContract.d.ts +10 -1
  93. package/dist-types/packages/peach-kit/src/capabilities.d.ts +1 -0
  94. package/dist-types/packages/peach-kit/src/ui/popover-placement.d.ts +1 -1
  95. package/dist-types/packages/sootsim-swift/src/securityHostContract.d.ts +10 -0
  96. package/package.json +1 -1
  97. package/runtime-companion.json +1 -1
  98. package/sdk/ios/System/Library/Frameworks/CFNetwork.framework/Headers/CFHost.h +555 -0
  99. package/sdk/ios/System/Library/Frameworks/CFNetwork.framework/Headers/CFNetwork.h +1 -0
  100. package/sdk/ios/System/Library/Frameworks/Foundation.framework/Headers/Foundation.apinotes +6 -0
  101. package/sdk/ios/System/Library/Frameworks/Foundation.framework/Headers/NSURLProtocol.h +0 -1
  102. package/sdk/ios/System/Library/Frameworks/QuartzCore.framework/Modules/module.modulemap +6 -0
  103. package/sdk/ios/System/Library/Frameworks/UIKit.framework/Headers/UIBarButtonItemBadge.h +1 -1
  104. package/sdk/ios/System/Library/Frameworks/UIKit.framework/Headers/UIBarMinimization.h +1 -1
  105. package/sdk/ios/System/Library/Frameworks/UIKit.framework/Headers/UIScrollView.h +1 -1
  106. package/sdk/ios/System/Library/Frameworks/UIKit.framework/Headers/UISearchTab.h +1 -1
  107. package/sdk/ios/System/Library/Frameworks/UIKit.framework/Headers/UITab.h +1 -1
  108. package/sdk/ios/System/Library/Frameworks/UIKit.framework/Headers/UITabAccessory.h +2 -2
  109. package/sdk/ios/usr/include/os/activity.h +534 -0
  110. package/sdk/ios/usr/include/os.modulemap +15 -0
  111. package/sdk/ios/wasm/include/fcntl.h +16 -0
  112. package/sdk/ios/wasm/include/string.h +5 -0
  113. package/sdk/native-hashes.json +1 -1
  114. package/src/dns-over-https.ts +61 -9
  115. package/src/expo-swift-bundle.ts +2 -7
  116. package/src/expo-swift-host.ts +11 -3
  117. package/src/host/fetch-proxy-handler.ts +51 -2
  118. package/src/host/fetch-proxy-overrides.ts +4 -0
  119. package/src/host/hostname-resolver.ts +9 -5
  120. package/src/native-app-identity-project.ts +13 -2
  121. package/src/native-app-identity.ts +47 -0
  122. package/src/nitro-adapter.lock.json +260 -260
  123. package/src/nitro-bundle.ts +7 -10
  124. package/src/nitro-superset.lock.json +4 -4
  125. package/src/podspec-sources.ts +20 -0
  126. package/src/storageSnapshotContract.ts +20 -1
  127. package/src/swift-compile.ts +409 -77
  128. package/src/swift-compiler-digest.ts +15 -0
  129. package/src/swift-coverage/xcode-packages.ts +3 -2
  130. package/src/swift-distribution.lock.json +12 -12
  131. package/src/swift-guest-archive.ts +153 -0
  132. package/src/swift-guest-compile.ts +449 -0
  133. package/src/swift-guest-image-ledger.ts +656 -0
  134. package/src/swift-guest-link-plan.ts +52 -0
  135. package/src/swift-guest-link.ts +1414 -0
  136. package/src/swift-guest-linked-spans.ts +338 -0
  137. package/src/swift-guest-manifest.ts +141 -0
  138. package/src/swift-guest-projection-storage.ts +310 -0
  139. package/src/swift-guest-projection.ts +252 -0
  140. package/src/swift-guest-runtime-plan.ts +834 -0
  141. package/src/swift-guest-source-inputs.ts +427 -0
  142. package/src/swift-guest-source-plan.ts +279 -0
  143. package/src/swift-host.ts +157 -36
  144. package/src/swift-icu.ts +60 -18
  145. package/src/swift-link-roots.ts +27 -50
  146. package/src/swift-package-manifest.ts +34 -18
  147. package/src/swift-package.ts +32 -2
  148. package/src/swift-packages.ts +138 -17
  149. package/src/swift-runtime-products.ts +73 -0
  150. package/src/swift-shared-sdk.ts +1 -1
  151. package/src/swift-submit.ts +15 -3
  152. package/src/swift-toolchain.ts +18 -0
  153. package/src/swift-wasm-prune.ts +313 -14
  154. package/src/swiftContract.ts +83 -0
  155. package/src/swiftRuntimeProductContract.ts +85 -45
  156. package/src/turbo-bundle.ts +1 -1
  157. package/src/turbo-codegen-intake.ts +10 -3
  158. package/src/turbo-runtime.lock.json +23 -23
  159. package/src/wasm-optimize.ts +16 -4
  160. package/src/xcode-project.ts +142 -14
@@ -3,6 +3,12 @@ import * as v from 'valibot'
3
3
  import { isRecord } from './is-record'
4
4
  import type { SwiftFrameworkProduct } from './swiftRuntimeProductContract'
5
5
 
6
+ export function frameworkRuntimeProductId(
7
+ product: Pick<SwiftFrameworkProduct, 'packageName' | 'product'>,
8
+ ): string {
9
+ return `swift-package/${product.packageName}/${product.product.name}`
10
+ }
11
+
6
12
  const packageSchema = v.object({
7
13
  name: v.string(),
8
14
  products: v.array(
@@ -80,8 +86,75 @@ export function frameworkRuntimeProduct(
80
86
  packageName: packageDescription.name,
81
87
  manifestSha256: createHash('sha256').update(manifest).digest('hex'),
82
88
  product: { name: product.name, linkage, targets: product.targets },
89
+ frameworkAliases: [],
83
90
  targets,
84
91
  objects,
85
92
  autolink,
86
93
  }
87
94
  }
95
+
96
+ /**
97
+ * derive framework names only from evaluated library products and their SDK
98
+ * maps. A product named like a framework owns its targets; a target exported
99
+ * by any library product and named like a framework owns itself. A declaration
100
+ * framework (a header partition the SDK generator splits out of an owner) takes
101
+ * the targets of that owner, which hold the objects defining its declarations.
102
+ */
103
+ export function frameworkRuntimeAliases(options: {
104
+ packageDump: unknown
105
+ product: SwiftFrameworkProduct
106
+ wasmSdkId: string
107
+ wasmSdkChecksum: string
108
+ declarationFrameworks: ReadonlyMap<string, string>
109
+ moduleMap: (name: string) => { path: string; bytes: string } | null
110
+ }): SwiftFrameworkProduct['frameworkAliases'] {
111
+ const packageDescription = v.parse(packageSchema, options.packageDump)
112
+ if (packageDescription.name !== options.product.packageName)
113
+ throw new Error('framework alias package identity changed')
114
+ const productNames = new Set<string>()
115
+ const selected = new Set(options.product.targets.map((target) => target.name))
116
+ const objectTargets = new Set(options.product.objects.map((object) => object.target))
117
+ const owned = (target: string) => selected.has(target) && objectTargets.has(target)
118
+ const libraries = packageDescription.products.filter((item) => {
119
+ if (productNames.has(item.name))
120
+ throw new Error(`duplicate evaluated library product ${item.name}`)
121
+ productNames.add(item.name)
122
+ if (!isRecord(item.type) || !Array.isArray(item.type.library)) return false
123
+ const [linkage] = item.type.library
124
+ return linkage === 'automatic' || linkage === 'static'
125
+ })
126
+ const candidates = new Map<string, readonly string[]>()
127
+ for (const item of libraries)
128
+ if (item.targets.length && item.targets.every(owned))
129
+ candidates.set(item.name, item.targets)
130
+ for (const item of libraries)
131
+ for (const target of item.targets)
132
+ if (owned(target) && !candidates.has(target)) candidates.set(target, [target])
133
+ const aliases: SwiftFrameworkProduct['frameworkAliases'] = []
134
+ const declare = (name: string, targets: readonly string[]) => {
135
+ const map = options.moduleMap(name)
136
+ if (!map) return
137
+ const declared = /^\s*framework\s+module\s+([A-Za-z_]\w*)\b/m.exec(map.bytes)?.[1]
138
+ if (declared !== name)
139
+ throw new Error(`framework module map ownership differs for ${name}`)
140
+ // explicit link clauses can name another owner and need independent proof.
141
+ if (/\blink\s+(?:framework\s+)?"/.test(map.bytes)) return
142
+ aliases.push({
143
+ kind: 'framework',
144
+ name,
145
+ targets: [...targets],
146
+ moduleMap: map.path,
147
+ moduleMapSha256: createHash('sha256').update(map.bytes).digest('hex'),
148
+ wasmSdkId: options.wasmSdkId,
149
+ wasmSdkChecksum: options.wasmSdkChecksum,
150
+ })
151
+ }
152
+ for (const [name, targets] of candidates) declare(name, targets)
153
+ for (const [name, owner] of options.declarationFrameworks) {
154
+ const targets = candidates.get(owner)
155
+ if (!targets || candidates.has(name))
156
+ throw new Error(`declaration framework ${name} has no distinct owner ${owner}`)
157
+ declare(name, targets)
158
+ }
159
+ return aliases
160
+ }
@@ -135,7 +135,7 @@ function weakenBundleSymbolsInWasmObj(buf: Uint8Array): void {
135
135
  }
136
136
  }
137
137
 
138
- function weakenBundleInArchive(arBuf: Uint8Array): void {
138
+ export function weakenBundleInArchive(arBuf: Uint8Array): void {
139
139
  let gnuNames: Uint8Array | null = null
140
140
  let pos = 8
141
141
  while (pos + 60 <= arBuf.length) {
@@ -27,6 +27,7 @@ import {
27
27
  type SwiftResourceBundle,
28
28
  type SwiftPackageFiles,
29
29
  type SwiftNativeTarget,
30
+ type SwiftSourceLinkGraph,
30
31
  type SwiftHeaderAliases,
31
32
  } from './swiftContract'
32
33
 
@@ -134,9 +135,18 @@ export const MAX_SWIFT_COMPILE_IMAGE_TOTAL_BYTES = 16 * 1024 * 1024
134
135
  // 59: `peach.idle_timer_disabled` moves the screen wake lock behind
135
136
  // UIApplication.isIdleTimerDisabled.
136
137
  // 60: `peach.net_en0_ipv4` answers the en0 IPv4 address getifaddrs lists.
137
- // 61: `peach.dyld_image_uuid` supplies the compiled app image identity.
138
- // 62: fetch headers replies carry `setCookies`, the response's Set-Cookie list.
139
- export const SWIFT_HOST_ABI = 62
138
+ // 61: Security reads entitled access groups and their device-scoped snapshots.
139
+ // 62: URLSession exchanges task cookies with the host at every HTTP hop.
140
+ // 63: URLSession sends the measured TLS floor to a capable proxy.
141
+ // 64: URLSession redirect decisions cross the host boundary.
142
+ // 65: Darwin notifications share named device state and deliver on guest queues.
143
+ // 66: `peach.hw_model_size` and `peach.hw_model_copy` answer the device's
144
+ // sysctl hw.model board configuration.
145
+ // 67: `peach.dyld_image_uuid` supplies the compiled app image identity.
146
+ // 68: fetch headers replies carry `setCookies`, the response's Set-Cookie list.
147
+ // 69: `peach.icu_item_v1` replaces `icu_data_v1`: the host fills icu's table of
148
+ // contents and places each item's pack the first time icu opens it.
149
+ export const SWIFT_HOST_ABI = 69
140
150
 
141
151
  export interface SwiftImageUpload {
142
152
  /** the raster file picked for the asset (has the extension). */
@@ -263,6 +273,7 @@ export type SwiftCompileSubmit = (work: {
263
273
  packageFiles?: SwiftPackageFiles
264
274
  packageGuestImports?: string[]
265
275
  nativeTargets?: SwiftNativeTarget[]
276
+ sourceLinkGraph?: SwiftSourceLinkGraph
266
277
  headerAliases?: SwiftHeaderAliases
267
278
  metalSources?: Record<string, string>
268
279
  /** the bundle pack; absent means the project packs none. */
@@ -438,6 +449,7 @@ export async function compileSwiftProject(
438
449
  packageFiles?: SwiftPackageFiles
439
450
  packageGuestImports?: string[]
440
451
  nativeTargets?: SwiftNativeTarget[]
452
+ sourceLinkGraph?: SwiftSourceLinkGraph
441
453
  headerAliases?: SwiftHeaderAliases
442
454
  metalSources?: Record<string, string>
443
455
  resources?: Record<string, string>
@@ -65,6 +65,24 @@ export interface SwiftHostCompilerPin {
65
65
  // advance. an installed CLI adds the compiler its runtime pins
66
66
  // (registerSwiftHostCompiler).
67
67
  const compilerArchives: Record<string, SwiftHostCompilerPin> = {
68
+ 'swift-6.4.0-RELEASE-custom-45bb46301c86fe73': {
69
+ identity: '45bb46301c86fe73',
70
+ archive: 'tar.gz',
71
+ hosts: {
72
+ 'darwin-arm64': {
73
+ checksum: '102dfbbb7b451be0685763b7a427284b75a8078874543f091b1c4b3db86e6565',
74
+ manifest: 'fb6c4d75ef6f4b3c094ae5a4d5d1e6bdfd85431f3fe25d514f3e7a0b4add60ef',
75
+ },
76
+ 'linux-x64': {
77
+ checksum: 'd3c040e042e12ff787b64bfde1d85238254365036ce093f3b20ff86e8ff996f0',
78
+ manifest: '7c7144be591692e563396fe3c987c5aa56fbaea4faacaad62283c0c6e5c04ae2',
79
+ },
80
+ 'linux-arm64': {
81
+ checksum: '604e6fc5fc0f5a93cee3ca6dfa9616244a2a49ef517caa3155a12ae4a0ecf72b',
82
+ manifest: '075fd53d03ecf099954f1d023bb4bb67a5c5ee946537466d6c105022bdf8ecde',
83
+ },
84
+ },
85
+ },
68
86
  'swift-6.4.0-RELEASE-custom-0b2d0a9011c88e66': {
69
87
  identity: '0b2d0a9011c88e66',
70
88
  archive: 'tar.gz',
@@ -22,7 +22,12 @@ import { createHash } from 'node:crypto'
22
22
  import fs from 'node:fs'
23
23
  import os from 'node:os'
24
24
  import path from 'node:path'
25
+ import * as v from 'valibot'
25
26
  import { foundationCategoryObjects } from './swift-foundation'
27
+ import {
28
+ SWIFT_FRAMEWORK_PRODUCT_FILE,
29
+ swiftFrameworkProductSchema,
30
+ } from './swiftRuntimeProductContract'
26
31
 
27
32
  function readULEB(b: Uint8Array, o: number): [number, number] {
28
33
  let res = 0
@@ -163,6 +168,8 @@ interface ParsedObject {
163
168
  isDist: boolean
164
169
  numImportFuncs: number
165
170
  numFuncs: number
171
+ /** Undefined functions imported from a module other than env. */
172
+ hostImportNames: Set<string>
166
173
  numSegments: number
167
174
  segNames: string[]
168
175
  symKind: Uint8Array
@@ -273,6 +280,7 @@ export function patchSwiftrtObject(src: Uint8Array): Uint8Array {
273
280
  let [cnt, cur] = readULEB(buf, sp)
274
281
  for (let i = 0; i < cnt; i++) {
275
282
  const kind = buf[cur++]!
283
+ const flPos = cur
276
284
  const [fl, c2] = readULEB(buf, cur)
277
285
  cur = c2
278
286
  const isUndef = (fl & 0x10) !== 0
@@ -294,6 +302,8 @@ export function patchSwiftrtObject(src: Uint8Array): Uint8Array {
294
302
  NEUTRALIZED_SWIFTRT_SECTIONS.has(sName.slice(prefix.length))
295
303
  ) {
296
304
  buf[c3] = 0x78
305
+ // the renamed bound is never defined, so it stays an absent weak import
306
+ buf[flPos] = fl | 0x01
297
307
  neutralizedSyms.add(i)
298
308
  }
299
309
  }
@@ -356,6 +366,8 @@ function parseWasmObjectBytes(
356
366
  let pos = 8
357
367
  let numImportFuncs = 0
358
368
  const importFuncNames: string[] = []
369
+ const importFuncModules: string[] = []
370
+ const hostImportNames = new Set<string>()
359
371
  const importGlobalNames: string[] = []
360
372
  const importTableNames: string[] = []
361
373
  const importEventNames: string[] = []
@@ -389,6 +401,7 @@ function parseWasmObjectBytes(
389
401
  let [cnt, cp] = readULEB(buf, p)
390
402
  for (let i = 0; i < cnt; i++) {
391
403
  const [mLen, m2] = readULEB(buf, cp)
404
+ const mName = Buffer.from(buf.subarray(m2, m2 + mLen)).toString('utf8')
392
405
  cp = m2 + mLen
393
406
  const [fLen, f2] = readULEB(buf, cp)
394
407
  const fName = Buffer.from(buf.subarray(f2, f2 + fLen)).toString('utf8')
@@ -398,6 +411,7 @@ function parseWasmObjectBytes(
398
411
  const [, c2] = readULEB(buf, cp)
399
412
  cp = c2
400
413
  importFuncNames.push(fName)
414
+ importFuncModules.push(mName)
401
415
  numImportFuncs++
402
416
  } else if (kind === 1) {
403
417
  cp++
@@ -532,6 +546,9 @@ function parseWasmObjectBytes(
532
546
  } else if (kind === 5) {
533
547
  sName = importTableNames[el] ?? ''
534
548
  }
549
+ // an undefined function imported from another module than env is host-supplied.
550
+ if (isUndef && kind === 0 && importFuncModules[el] !== 'env')
551
+ hostImportNames.add(sName)
535
552
  symNames.push(sName)
536
553
  } else if (kind === 1) {
537
554
  const [sLen, c3] = readULEB(buf, cur)
@@ -744,6 +761,7 @@ function parseWasmObjectBytes(
744
761
  isDist,
745
762
  numImportFuncs,
746
763
  numFuncs: fEnds.length,
764
+ hostImportNames,
747
765
  numSegments: segNames.length,
748
766
  segNames,
749
767
  symKind,
@@ -782,11 +800,220 @@ function parseWasmObjectCached(
782
800
  return parsed
783
801
  }
784
802
 
803
+ /** Original undefined symbols from a selected Wasm object. */
804
+ export function guestWasmUndefinedSymbols(bytes: Uint8Array): string[] {
805
+ return guestWasmSymbols(bytes).undefined
806
+ }
807
+
808
+ /** Original undefined and externally visible symbols from a selected object. */
809
+ export function guestWasmSymbols(bytes: Uint8Array): {
810
+ undefined: string[]
811
+ tags: string[]
812
+ hostImports: string[]
813
+ weakUndefined: string[]
814
+ defined: string[]
815
+ weakDefined: string[]
816
+ } {
817
+ const object = parseWasmObjectBytes('', bytes, false)
818
+ return {
819
+ undefined: [
820
+ ...new Set(
821
+ object.symNames.filter(
822
+ (name, index) => name && (object.symFlags[index]! & 0x10) !== 0,
823
+ ),
824
+ ),
825
+ ],
826
+ // a wasm tag is one module entity unified by name across the link, as the
827
+ // main module owns it for dynamic images, so no image scope applies.
828
+ tags: [
829
+ ...new Set(
830
+ object.symNames.filter((name, index) => name && object.symKind[index] === 4),
831
+ ),
832
+ ],
833
+ // an undefined function imported from a module other than env is supplied
834
+ // by the host, whatever linker symbol names it.
835
+ hostImports: [...object.hostImportNames],
836
+ weakUndefined: [
837
+ ...new Set(
838
+ object.symNames.filter(
839
+ (name, index) => name && (object.symFlags[index]! & 0x13) === 0x11,
840
+ ),
841
+ ),
842
+ ],
843
+ defined: [
844
+ ...new Set(
845
+ object.symNames.filter(
846
+ (name, index) =>
847
+ name &&
848
+ (object.symFlags[index]! & 0x10) === 0 &&
849
+ (object.symFlags[index]! & 3) !== 2,
850
+ ),
851
+ ),
852
+ ],
853
+ weakDefined: [
854
+ ...new Set(
855
+ object.symNames.filter(
856
+ (name, index) => name && (object.symFlags[index]! & 0x13) === 0x01,
857
+ ),
858
+ ),
859
+ ],
860
+ }
861
+ }
862
+
785
863
  function peachHome(): string {
786
864
  const override = process.env.PEACH_HOME
787
865
  return override ? path.resolve(override) : path.join(os.homedir(), '.peach')
788
866
  }
789
867
 
868
+ function sdkObjectName(archive: string, member: string, ordinal: number): string {
869
+ const base = archive.replace(/\.a$/, '')
870
+ const suffix = ordinal > 1 ? `_${ordinal}` : ''
871
+ return `${base}__${member.replaceAll('/', '__')}${suffix}`
872
+ }
873
+
874
+ export interface SwiftSdkObjectOrigin {
875
+ readonly archive: string
876
+ readonly member: string
877
+ readonly ordinal: number
878
+ }
879
+
880
+ export interface SwiftPrunedSdkInputs {
881
+ readonly wasiDirectory: string
882
+ readonly objectDirectory: string
883
+ readonly objectOrigins: ReadonlyMap<string, SwiftSdkObjectOrigin & { original: string }>
884
+ readonly transformations: ReadonlyMap<string, SwiftObjectTransformation>
885
+ }
886
+
887
+ export interface SwiftObjectTransformation {
888
+ readonly output: string
889
+ readonly inputSha256: string
890
+ readonly outputSha256: string
891
+ readonly kind: 'swiftrt' | 'pruned'
892
+ }
893
+
894
+ export interface SwiftArchiveProduct {
895
+ readonly product: string
896
+ readonly archive: string
897
+ }
898
+
899
+ export interface SwiftArchiveMemberProducts {
900
+ readonly original: SwiftSdkObjectOrigin
901
+ readonly sha256: string
902
+ readonly products: readonly (SwiftArchiveProduct & { ordinal: number })[]
903
+ }
904
+
905
+ /** Compare actual member bytes across the SDK's declared build products. */
906
+ export function swiftArchiveMemberProducts(
907
+ selected: readonly SwiftSdkObjectOrigin[],
908
+ products: readonly SwiftArchiveProduct[],
909
+ ): SwiftArchiveMemberProducts[] {
910
+ if (new Set(products.map((product) => product.product)).size !== products.length)
911
+ throw new Error('duplicate SDK archive product')
912
+ const archives = new Map<string, ReturnType<typeof readArMembers>>()
913
+ const members = (archive: string) => {
914
+ let result = archives.get(archive)
915
+ if (!result) {
916
+ result = readArMembers(fs.readFileSync(archive))
917
+ archives.set(archive, result)
918
+ }
919
+ return result
920
+ }
921
+ const hash = (bytes: Uint8Array) => createHash('sha256').update(bytes).digest('hex')
922
+ const names = new Set(selected.map((origin) => origin.member))
923
+ const matches = new Map<string, (SwiftArchiveProduct & { ordinal: number })[]>()
924
+ for (const product of products) {
925
+ const counts = new Map<string, number>()
926
+ for (const member of members(product.archive)) {
927
+ if (!names.has(member.name)) continue
928
+ const ordinal = (counts.get(member.name) ?? 0) + 1
929
+ counts.set(member.name, ordinal)
930
+ const key = `${member.name}\0${hash(member.bytes)}`
931
+ const group = matches.get(key) ?? []
932
+ group.push({ ...product, ordinal })
933
+ matches.set(key, group)
934
+ }
935
+ }
936
+ return selected.map((original) => {
937
+ const source = members(original.archive).filter(
938
+ (member) => member.name === original.member,
939
+ )[original.ordinal - 1]
940
+ if (!source)
941
+ throw new Error(
942
+ `missing SDK archive member ${original.archive}(${original.member})`,
943
+ )
944
+ const sha256 = hash(source.bytes)
945
+ return {
946
+ original,
947
+ sha256,
948
+ products: matches.get(`${original.member}\0${sha256}`) ?? [],
949
+ }
950
+ })
951
+ }
952
+
953
+ /** Recover ownership from the actual SDK archives used by the link. */
954
+ export function swiftSdkObjectOrigins(
955
+ sdkWasiDir: string,
956
+ sdkObjsDir: string,
957
+ files: ReadonlySet<string>,
958
+ ): Map<string, SwiftSdkObjectOrigin> {
959
+ const objectDirectory = path.resolve(sdkObjsDir)
960
+ const wanted = new Set(
961
+ [...files]
962
+ .filter((file) => path.dirname(path.resolve(file)) === objectDirectory)
963
+ .map((file) => path.basename(file)),
964
+ )
965
+ const result = new Map<string, SwiftSdkObjectOrigin>()
966
+ for (const archive of fs
967
+ .readdirSync(sdkWasiDir)
968
+ .filter((file) => file.endsWith('.a'))) {
969
+ const prefix = `${archive.slice(0, -2)}__`
970
+ if (![...wanted].some((file) => file.startsWith(prefix))) continue
971
+ const archivePath = path.join(sdkWasiDir, archive)
972
+ const seen = new Map<string, number>()
973
+ for (const member of readArMembers(fs.readFileSync(archivePath))) {
974
+ const ordinal = (seen.get(member.name) ?? 0) + 1
975
+ seen.set(member.name, ordinal)
976
+ const name = sdkObjectName(archive, member.name, ordinal)
977
+ if (!wanted.has(name)) continue
978
+ const file = path.join(sdkObjsDir, name)
979
+ if (result.has(file)) throw new Error(`ambiguous SDK object origin ${file}`)
980
+ result.set(file, { archive: archivePath, member: member.name, ordinal })
981
+ }
982
+ }
983
+ return result
984
+ }
985
+
986
+ /** Recover source archive members for the actual inputs after pruning. */
987
+ export function swiftPrunedSdkObjectOrigins(
988
+ sdk: { wasiDirectory: string; objectDirectory: string },
989
+ args: readonly string[],
990
+ rewritten: ReadonlyMap<string, string>,
991
+ ): Map<string, SwiftSdkObjectOrigin & { original: string }> {
992
+ const originals = new Map<string, string>()
993
+ for (const [original, output] of rewritten) {
994
+ if (originals.has(output)) throw new Error(`ambiguous pruned link object ${output}`)
995
+ originals.set(output, original)
996
+ }
997
+ const sdkObjects = new Map<string, string>()
998
+ for (const input of args) {
999
+ const original = originals.get(input) ?? input
1000
+ if (path.dirname(path.resolve(original)) === path.resolve(sdk.objectDirectory))
1001
+ sdkObjects.set(input, original)
1002
+ }
1003
+ const origins = swiftSdkObjectOrigins(
1004
+ sdk.wasiDirectory,
1005
+ sdk.objectDirectory,
1006
+ new Set(sdkObjects.values()),
1007
+ )
1008
+ return new Map(
1009
+ [...sdkObjects].map(([input, original]) => {
1010
+ const origin = origins.get(original)
1011
+ if (!origin) throw new Error(`missing SDK archive origin ${original}`)
1012
+ return [input, { ...origin, original }]
1013
+ }),
1014
+ )
1015
+ }
1016
+
790
1017
  function ensureUnpackedSdkObjects(sdkWasiDir: string): string {
791
1018
  const sdkKey = createHash('sha256').update(sdkWasiDir).digest('hex').slice(0, 16)
792
1019
  const outDir = path.join(peachHome(), 'cache', 'swift-builds', `sdk-objs-${sdkKey}`)
@@ -800,7 +1027,6 @@ function ensureUnpackedSdkObjects(sdkWasiDir: string): string {
800
1027
  .filter((f) => f.endsWith('.a'))
801
1028
  .sort()
802
1029
  for (const archive of archives) {
803
- const aBase = archive.replace(/\.a$/, '')
804
1030
  const members = readArMembers(
805
1031
  new Uint8Array(fs.readFileSync(path.join(sdkWasiDir, archive))),
806
1032
  )
@@ -808,9 +1034,7 @@ function ensureUnpackedSdkObjects(sdkWasiDir: string): string {
808
1034
  for (const m of members) {
809
1035
  const count = (seen.get(m.name) ?? 0) + 1
810
1036
  seen.set(m.name, count)
811
- const suffix = count > 1 ? `_${count}` : ''
812
- const safeName = m.name.replaceAll('/', '__')
813
- const outName = `${aBase}__${safeName}${suffix}`
1037
+ const outName = sdkObjectName(archive, m.name, count)
814
1038
  fs.writeFileSync(path.join(tmpDir, outName), m.bytes)
815
1039
  }
816
1040
  }
@@ -854,6 +1078,11 @@ export function pruneSwiftWasmLink(
854
1078
  // a sandboxed build wrote the response file as this user: its link runs as
855
1079
  // that user, so no token it chose can make the host write outside the build.
856
1080
  owner?: { uid: number; gid: number; env: NodeJS.ProcessEnv },
1081
+ link?: (
1082
+ args: readonly string[],
1083
+ rewritten: ReadonlyMap<string, string>,
1084
+ sdk: SwiftPrunedSdkInputs,
1085
+ ) => void,
857
1086
  ): void {
858
1087
  const rspPath = path.join(directory, '.peach-link.rsp')
859
1088
  if (!fs.existsSync(rspPath)) return
@@ -873,8 +1102,10 @@ export function pruneSwiftWasmLink(
873
1102
  const distDir = path.join(moduleRoot, 'lib')
874
1103
  // the app's own struct and class field descriptors stay: SwiftUI attaches
875
1104
  // @State and @StateObject by reflecting the app's view structs.
1105
+ // the shim reflects its own wrappers and views (State, ObservedObject, Published), so SwiftUI and Combine keep their descriptors
876
1106
  const dropsReflection = (obj: ParsedObject, name: string | undefined) =>
877
1107
  !!name &&
1108
+ !/^(SwiftUI|Combine)-/.test(path.basename(obj.file)) &&
878
1109
  (name.startsWith('l__swift5_reflection_descriptor') ||
879
1110
  (name.startsWith('$s') &&
880
1111
  (name.endsWith('CMF') || name.endsWith('VMF')) &&
@@ -883,6 +1114,22 @@ export function pruneSwiftWasmLink(
883
1114
  const prunedObjsDir = path.join(directory, '.peach-pruned-objs')
884
1115
  fs.rmSync(prunedObjsDir, { recursive: true, force: true })
885
1116
  fs.mkdirSync(prunedObjsDir, { recursive: true })
1117
+ const transformations = new Map<string, SwiftObjectTransformation>()
1118
+ const recordTransformation = (
1119
+ file: string,
1120
+ output: string,
1121
+ inputSha256: string,
1122
+ result: Uint8Array,
1123
+ kind: SwiftObjectTransformation['kind'],
1124
+ ) => {
1125
+ if (!link) return
1126
+ transformations.set(file, {
1127
+ output,
1128
+ inputSha256,
1129
+ outputSha256: createHash('sha256').update(result).digest('hex'),
1130
+ kind,
1131
+ })
1132
+ }
886
1133
 
887
1134
  // collect distribution and unpacked sdk object files
888
1135
  const distFiles: string[] = []
@@ -943,6 +1190,13 @@ export function pruneSwiftWasmLink(
943
1190
  const distBaseNames = new Set(distFiles.map((f) => path.basename(f)))
944
1191
  const libDirs = tokens.filter((t) => t.startsWith('-L')).map((t) => t.slice(2))
945
1192
  const supersededLibFlags = new Set<string>()
1193
+ // the distribution links its framework objects as inputs, so the product
1194
+ // name its modules autolink has no archive to load
1195
+ const frameworkFile = path.join(moduleRoot, SWIFT_FRAMEWORK_PRODUCT_FILE)
1196
+ if (fs.existsSync(frameworkFile))
1197
+ supersededLibFlags.add(
1198
+ `-l${v.parse(swiftFrameworkProductSchema, JSON.parse(fs.readFileSync(frameworkFile, 'utf8'))).product.name}`,
1199
+ )
946
1200
  for (const t of tokens) {
947
1201
  if (!t.startsWith('-l') || OMIT_SDK_LIB_FLAGS.has(t)) continue
948
1202
  const archive = libDirs
@@ -958,9 +1212,15 @@ export function pruneSwiftWasmLink(
958
1212
  let patchedSwiftrtPath = ''
959
1213
  if (swiftrtOrigPath && fs.existsSync(swiftrtOrigPath)) {
960
1214
  patchedSwiftrtPath = path.join(prunedObjsDir, 'swiftrt-patched.o')
961
- fs.writeFileSync(
1215
+ const input = new Uint8Array(fs.readFileSync(swiftrtOrigPath))
1216
+ const result = patchSwiftrtObject(input)
1217
+ fs.writeFileSync(patchedSwiftrtPath, result)
1218
+ recordTransformation(
1219
+ swiftrtOrigPath,
962
1220
  patchedSwiftrtPath,
963
- patchSwiftrtObject(new Uint8Array(fs.readFileSync(swiftrtOrigPath))),
1221
+ link ? createHash('sha256').update(input).digest('hex') : '',
1222
+ result,
1223
+ 'swiftrt',
964
1224
  )
965
1225
  eagerFiles.push(patchedSwiftrtPath)
966
1226
  }
@@ -1087,6 +1347,13 @@ export function pruneSwiftWasmLink(
1087
1347
  if (obj.typePrefixesInObj.has(outer)) markTypeLive(obj, outer)
1088
1348
  }
1089
1349
 
1350
+ // a nested type's descriptor reaches its parent by a relative offset the
1351
+ // assembler resolves without a relocation when both sit in one segment.
1352
+ for (let n = pref.length - 1; n > 2; n--) {
1353
+ const outer = pref.slice(0, n)
1354
+ if (obj.typePrefixesInObj.has(outer)) markTypeLive(obj, outer)
1355
+ }
1356
+
1090
1357
  const mnName = `${pref}Mn`
1091
1358
  for (let i = 0; i < obj.symNames.length; i++) {
1092
1359
  if (obj.symNames[i] === mnName && (obj.symFlags[i]! & 0x10) === 0) {
@@ -1226,6 +1493,15 @@ export function pruneSwiftWasmLink(
1226
1493
  activateSymbolInObj(obj, classSym)
1227
1494
  }
1228
1495
 
1496
+ // app classes can be addressed by module-qualified names in plists or
1497
+ // NSClassFromString even when their Objective-C names are mangled.
1498
+ if (obj.isDist) {
1499
+ const isBuildSwift = !obj.file.startsWith(distDir) && obj.file.endsWith('.swift.o')
1500
+ for (const [classSym, pref] of obj.objcClassSymToTypePrefix)
1501
+ if (isBuildSwift || !classSym.startsWith('._OBJC_CLASS__Tt'))
1502
+ markTypeLive(obj, pref)
1503
+ }
1504
+
1229
1505
  if (obj.file.endsWith('libswiftCore__Swift.o')) {
1230
1506
  for (const pref of obj.typePrefixesInObj) {
1231
1507
  if (!pref.startsWith('$ss')) {
@@ -1325,6 +1601,14 @@ export function pruneSwiftWasmLink(
1325
1601
  const def = definedGlobalSyms.get(symName)
1326
1602
  if (def) activateSymbolInObj(def.obj, def.symIdx)
1327
1603
  }
1604
+ // the image ledger's generated lookup wrappers call the loader runtime, a
1605
+ // reference the pruner cannot see before the ledger exists.
1606
+ for (const symName of ['__peach_dlsym_from_image', '__peach_dlerror']) {
1607
+ const provider = lazyProviders.get(symName)?.[0]
1608
+ if (provider) extractObject(provider)
1609
+ const def = definedGlobalSyms.get(symName)
1610
+ if (def) activateSymbolInObj(def.obj, def.symIdx)
1611
+ }
1328
1612
 
1329
1613
  const WEAKEN_SDK_BUNDLE_SYMS = new Set([
1330
1614
  '$s10Foundation6BundleC22preferredLocalizations4from14forPreferencesSaySSGAG_AGSgtFZ',
@@ -1429,6 +1713,7 @@ export function pruneSwiftWasmLink(
1429
1713
 
1430
1714
  const writePrunedObject = (obj: ParsedObject, outFile: string) => {
1431
1715
  const buf = new Uint8Array(fs.readFileSync(obj.file))
1716
+ const inputSha256 = link ? createHash('sha256').update(buf).digest('hex') : ''
1432
1717
  const fLive = liveFuncs.get(obj)!
1433
1718
  const sLive = liveSegs.get(obj)!
1434
1719
  const dLive = liveDataSyms.get(obj)!
@@ -1462,7 +1747,8 @@ export function pruneSwiftWasmLink(
1462
1747
  const keptDataRelocBytes: Uint8Array[] = []
1463
1748
  const zeroDataRelocOffsets: number[] = []
1464
1749
  const usedSyms = new Set<number>()
1465
- for (const r of keptCodeRelocs) usedSyms.add(r.rs)
1750
+ // a type index relocation carries a type index, not a symbol index
1751
+ for (const r of keptCodeRelocs) if (r.rawBytes[0] !== 6) usedSyms.add(r.rs)
1466
1752
 
1467
1753
  for (const r of obj.dataRelocList) {
1468
1754
  const sName = obj.segNames[r.segIdx]!
@@ -1496,7 +1782,8 @@ export function pruneSwiftWasmLink(
1496
1782
  } else if (sLive[r.segIdx] === 1) {
1497
1783
  if (
1498
1784
  obj.isDist &&
1499
- obj.symNames[r.rs]?.startsWith('l__swift5_reflection_descriptor')
1785
+ obj.symNames[r.rs]?.startsWith('l__swift5_reflection_descriptor') &&
1786
+ dropsReflection(obj, obj.symNames[r.rs])
1500
1787
  ) {
1501
1788
  zeroDataRelocOffsets.push(r.ro)
1502
1789
  } else {
@@ -1723,7 +2010,9 @@ export function pruneSwiftWasmLink(
1723
2010
  pos = end
1724
2011
  }
1725
2012
 
1726
- fs.writeFileSync(outFile, Buffer.concat(outChunks))
2013
+ const output = Buffer.concat(outChunks)
2014
+ fs.writeFileSync(outFile, output)
2015
+ recordTransformation(obj.file, outFile, inputSha256, output, 'pruned')
1727
2016
  }
1728
2017
 
1729
2018
  const prunableCandidates = [
@@ -1735,6 +2024,8 @@ export function pruneSwiftWasmLink(
1735
2024
  .filter((o) => extractedObjs.has(o))
1736
2025
 
1737
2026
  const prunedMap = new Map<string, string>()
2027
+ if (swiftrtOrigPath && patchedSwiftrtPath)
2028
+ prunedMap.set(swiftrtOrigPath, patchedSwiftrtPath)
1738
2029
  for (const o of reachedPrunableObjs) {
1739
2030
  const outPath = path.join(prunedObjsDir, path.basename(o.file))
1740
2031
  writePrunedObject(o, outPath)
@@ -1809,10 +2100,18 @@ export function pruneSwiftWasmLink(
1809
2100
 
1810
2101
  const prunedRspPath = path.join(directory, '.peach-link.pruned.rsp')
1811
2102
  fs.writeFileSync(prunedRspPath, outTokens.map((t) => JSON.stringify(t)).join(' '))
1812
- execFileSync(path.join(toolchainBin, 'wasm-ld'), [`@${prunedRspPath}`], {
1813
- stdio: 'pipe',
1814
- maxBuffer: Infinity,
1815
- ...owner,
1816
- })
2103
+ if (link) {
2104
+ const sdk = { wasiDirectory: sdkWasiDir, objectDirectory: sdkObjsDir }
2105
+ link(outTokens, prunedMap, {
2106
+ ...sdk,
2107
+ objectOrigins: swiftPrunedSdkObjectOrigins(sdk, outTokens, prunedMap),
2108
+ transformations,
2109
+ })
2110
+ } else
2111
+ execFileSync(path.join(toolchainBin, 'wasm-ld'), [`@${prunedRspPath}`], {
2112
+ stdio: 'pipe',
2113
+ maxBuffer: Infinity,
2114
+ ...owner,
2115
+ })
1817
2116
  fs.rmSync(rspPath, { force: true })
1818
2117
  }