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
@@ -0,0 +1,834 @@
1
+ import { createHash } from 'node:crypto'
2
+ import { readFileSync, realpathSync } from 'node:fs'
3
+ import path from 'node:path'
4
+ import * as v from 'valibot'
5
+ import { ordinaryGuestCallerScopes } from './swift-guest-source-plan'
6
+ import { frameworkRuntimeProductId } from './swift-runtime-products'
7
+ import { weakenBundleInArchive } from './swift-shared-sdk'
8
+ import {
9
+ patchSwiftrtObject,
10
+ readArMembers,
11
+ swiftArchiveMemberProducts,
12
+ type SwiftPrunedSdkInputs,
13
+ type SwiftSdkObjectOrigin,
14
+ type SwiftObjectTransformation,
15
+ } from './swift-wasm-prune'
16
+ import {
17
+ SWIFT_FRAMEWORK_PRODUCT_FILE,
18
+ SWIFT_SDK_PRODUCT_FILE,
19
+ swiftFrameworkProductSchema,
20
+ swiftSdkProductsSchema,
21
+ type SwiftFrameworkProduct,
22
+ type SwiftSdkProduct,
23
+ } from './swiftRuntimeProductContract'
24
+ import type { AliasedGuestArchive } from './swift-guest-archive'
25
+ import type {
26
+ GuestLinkArtifact,
27
+ GuestLinkPlan,
28
+ GuestLinkSelection,
29
+ } from './swift-guest-link-plan'
30
+
31
+ const SDK_CATALOG_DIRECTORY = 'swift.xctoolchain/usr/lib/swift_static/wasi'
32
+
33
+ // the SDK view weakens three Foundation Bundle symbols. bind that view to the
34
+ // catalogued archive by reproducing the exact transformation on its bytes.
35
+ function sdkArtifactBytes(root: string, artifact: SwiftSdkProduct['artifacts'][number]) {
36
+ const file = path.resolve(root, artifact.path)
37
+ const linked = readFileSync(file)
38
+ const hash = (bytes: Uint8Array) => createHash('sha256').update(bytes).digest('hex')
39
+ if (hash(linked) === artifact.sha256) return { source: linked, linked }
40
+ if (
41
+ artifact.kind !== 'archive' ||
42
+ artifact.path !== `${SDK_CATALOG_DIRECTORY}/libFoundation.a`
43
+ )
44
+ throw new Error(`SDK product artifact changed ${file}`)
45
+ const catalog = path.join(root, SDK_CATALOG_DIRECTORY, SWIFT_SDK_PRODUCT_FILE)
46
+ const sourceDirectory = path.dirname(realpathSync(catalog))
47
+ const source = readFileSync(path.join(sourceDirectory, 'libFoundation.a'))
48
+ if (hash(source) !== artifact.sha256)
49
+ throw new Error(`SDK product artifact changed ${file}`)
50
+ const transformed = Uint8Array.from(source)
51
+ weakenBundleInArchive(transformed)
52
+ if (!linked.equals(transformed))
53
+ throw new Error(`SDK view transformation changed ${file}`)
54
+ return { source, linked }
55
+ }
56
+
57
+ function indexSdkMembers(bytes: Uint8Array): Map<string, Uint8Array> {
58
+ const counts = new Map<string, number>()
59
+ return new Map(
60
+ readArMembers(bytes).map((member) => {
61
+ const ordinal = (counts.get(member.name) ?? 0) + 1
62
+ counts.set(member.name, ordinal)
63
+ return [JSON.stringify([member.name, ordinal]), member.bytes]
64
+ }),
65
+ )
66
+ }
67
+
68
+ /** Bind a rewritten SDK object to its recorded original and pruner output. */
69
+ export function verifySdkObjectTransform(
70
+ source: Uint8Array,
71
+ linked: Uint8Array,
72
+ sourceSha256: string,
73
+ transformation: SwiftObjectTransformation,
74
+ ): void {
75
+ if (
76
+ createHash('sha256').update(source).digest('hex') !== sourceSha256 ||
77
+ transformation.inputSha256 !== sourceSha256
78
+ )
79
+ throw new Error('SDK object transform input changed')
80
+ if (
81
+ createHash('sha256').update(linked).digest('hex') !== transformation.outputSha256 ||
82
+ (transformation.kind === 'swiftrt' &&
83
+ !Buffer.from(patchSwiftrtObject(source)).equals(linked))
84
+ )
85
+ throw new Error('SDK object transform output changed')
86
+ }
87
+
88
+ /** Read each producer's records relative to the root that owns its bytes. */
89
+ export function readGuestRuntimeCatalogs(
90
+ sdkRoot: string,
91
+ distributionRoot: string,
92
+ ): {
93
+ readonly framework: { readonly product: SwiftFrameworkProduct; readonly root: string }
94
+ readonly products: readonly {
95
+ readonly product: SwiftSdkProduct
96
+ readonly root: string
97
+ }[]
98
+ } {
99
+ const read = (file: string): unknown => JSON.parse(readFileSync(file, 'utf8'))
100
+ const framework = v.parse(
101
+ swiftFrameworkProductSchema,
102
+ read(path.join(distributionRoot, SWIFT_FRAMEWORK_PRODUCT_FILE)),
103
+ )
104
+ const sdk = v.parse(
105
+ swiftSdkProductsSchema,
106
+ read(
107
+ path.join(
108
+ sdkRoot,
109
+ 'swift.xctoolchain/usr/lib/swift_static/wasi',
110
+ SWIFT_SDK_PRODUCT_FILE,
111
+ ),
112
+ ),
113
+ )
114
+ const distribution = v.parse(
115
+ swiftSdkProductsSchema,
116
+ read(path.join(distributionRoot, 'lib', SWIFT_SDK_PRODUCT_FILE)),
117
+ )
118
+ return {
119
+ framework: { product: framework, root: distributionRoot },
120
+ products: [
121
+ ...sdk.products.map((product) => ({ product, root: sdkRoot })),
122
+ ...distribution.products.map((product) => ({ product, root: distributionRoot })),
123
+ ],
124
+ }
125
+ }
126
+
127
+ /** Stable producer identities for actual framework and SDK link artifacts. */
128
+ export function guestRuntimeInputIdentities(options: {
129
+ readonly sdkRoot: string
130
+ readonly distributionRoot: string
131
+ readonly framework: SwiftFrameworkProduct
132
+ readonly products: readonly {
133
+ readonly product: SwiftSdkProduct
134
+ readonly root: string
135
+ }[]
136
+ readonly sdk: SwiftPrunedSdkInputs
137
+ }): Map<string, string> {
138
+ const sdkRoot = path.resolve(options.sdkRoot)
139
+ const distributionRoot = path.resolve(options.distributionRoot)
140
+ if (sdkRoot === distributionRoot)
141
+ throw new Error('SDK and distribution roots must differ')
142
+ const identities = new Map<string, string>()
143
+ const origins = new Map<string, (SwiftSdkObjectOrigin & { original: string })[]>()
144
+ for (const origin of options.sdk.objectOrigins.values()) {
145
+ const archive = path.resolve(origin.archive)
146
+ const members = origins.get(archive) ?? []
147
+ members.push(origin)
148
+ origins.set(archive, members)
149
+ }
150
+ const add = (file: string, identity: string) => {
151
+ const prior = identities.get(file)
152
+ if (prior !== undefined && prior !== identity)
153
+ throw new Error(`ambiguous runtime input identity ${file}`)
154
+ identities.set(file, identity)
155
+ }
156
+ for (const object of options.framework.objects)
157
+ add(
158
+ path.resolve(distributionRoot, object.path),
159
+ JSON.stringify([
160
+ 'framework',
161
+ options.framework.packageName,
162
+ object.target,
163
+ object.path,
164
+ ]),
165
+ )
166
+ for (const { product, root } of options.products) {
167
+ const actualRoot = path.resolve(root)
168
+ const role =
169
+ actualRoot === sdkRoot
170
+ ? 'sdk'
171
+ : actualRoot === distributionRoot
172
+ ? 'distribution'
173
+ : null
174
+ if (role === null) throw new Error(`unknown runtime catalog root ${root}`)
175
+ for (const artifact of product.artifacts) {
176
+ const file = path.resolve(actualRoot, artifact.path)
177
+ // an archive may contain members owned by several source products.
178
+ // its byte identity is shared; selected members supply their own image.
179
+ const identity = [
180
+ 'runtime',
181
+ role,
182
+ artifact.kind === 'archive' ? 'archive' : product.id,
183
+ artifact.path,
184
+ ]
185
+ add(file, JSON.stringify(identity))
186
+ if (artifact.kind !== 'archive') continue
187
+ for (const origin of origins.get(file) ?? [])
188
+ add(
189
+ path.resolve(origin.original),
190
+ JSON.stringify([...identity, origin.member, origin.ordinal]),
191
+ )
192
+ }
193
+ }
194
+ return identities
195
+ }
196
+
197
+ /** The three static products declared by the source SDK runtime build. */
198
+ export interface GuestCxxProducts {
199
+ readonly libcxx: { readonly archive: string; readonly image: number }
200
+ readonly libcxxabi: { readonly archive: string; readonly image: number }
201
+ readonly unwind: { readonly archive: string; readonly image: number }
202
+ }
203
+
204
+ /** Own only framework objects actually retained in the final linker inputs. */
205
+ export function guestFrameworkLinkArtifacts(
206
+ product: SwiftFrameworkProduct,
207
+ root: string,
208
+ inputs: readonly string[],
209
+ rewritten: ReadonlyMap<string, string>,
210
+ image: number,
211
+ ): GuestLinkArtifact[] {
212
+ const linked = new Set(inputs.map((input) => path.resolve(input)))
213
+ const seen = new Set<string>()
214
+ const result: GuestLinkArtifact[] = []
215
+ for (const object of product.objects) {
216
+ const original = path.resolve(root, object.path)
217
+ if (seen.has(original)) throw new Error(`duplicate framework object ${original}`)
218
+ seen.add(original)
219
+ if (!linked.has(path.resolve(rewritten.get(original) ?? original))) continue
220
+ result.push({ path: original, kind: 'object', image, instrumentDynamicLookups: true })
221
+ }
222
+ return result
223
+ }
224
+
225
+ /** Resolve only producer-declared runtime link edges, never build order. */
226
+ export function guestSdkProductImages(
227
+ products: readonly SwiftSdkProduct[],
228
+ images: ReadonlyMap<string, number>,
229
+ ): GuestLinkPlan['images'] {
230
+ const byId = new Map<string, SwiftSdkProduct>()
231
+ for (const product of products) {
232
+ const previous = byId.get(product.id)
233
+ if (
234
+ previous &&
235
+ JSON.stringify([
236
+ previous.installName,
237
+ previous.target,
238
+ previous.linkNames,
239
+ previous.frameworkAliases,
240
+ previous.buildDependencies,
241
+ previous.linkOwnership,
242
+ previous.linkDependencies,
243
+ previous.autolink,
244
+ ]) !==
245
+ JSON.stringify([
246
+ product.installName,
247
+ product.target,
248
+ product.linkNames,
249
+ product.frameworkAliases,
250
+ product.buildDependencies,
251
+ product.linkOwnership,
252
+ product.linkDependencies,
253
+ product.autolink,
254
+ ])
255
+ )
256
+ throw new Error(`conflicting SDK source product ${product.id}`)
257
+ byId.set(product.id, product)
258
+ }
259
+ if (new Set(images.values()).size !== images.size)
260
+ throw new Error('SDK source products must have distinct images')
261
+ return [...images].map(([id, image]) => {
262
+ const product = byId.get(id)
263
+ if (!product) throw new Error(`unknown SDK source product ${id}`)
264
+ if (product.linkDependencies === null)
265
+ throw new Error(`unresolved SDK link scope ${id}`)
266
+ const dependencies = product.linkDependencies.flatMap((dependency) => {
267
+ const targetProduct = byId.get(dependency)
268
+ if (!targetProduct) throw new Error(`unknown SDK source product ${dependency}`)
269
+ if (targetProduct.linkOwnership === 'containing-image') return []
270
+ const target = images.get(dependency)
271
+ if (target === undefined)
272
+ throw new Error(`unresolved SDK link dependency ${dependency}`)
273
+ return [target]
274
+ })
275
+ return { id: image, name: product.installName, dependencies }
276
+ })
277
+ }
278
+
279
+ /** Select runtime products by exact selected inputs and declared dependencies. */
280
+ export function guestRuntimeProductsForInputs(options: {
281
+ readonly products: readonly {
282
+ readonly product: SwiftSdkProduct
283
+ readonly root: string
284
+ }[]
285
+ readonly selected: readonly {
286
+ readonly artifact: string
287
+ readonly member: string | null
288
+ readonly ordinal: number | null
289
+ }[]
290
+ readonly rewritten: ReadonlyMap<string, string>
291
+ readonly sdk: SwiftPrunedSdkInputs
292
+ readonly firstImage: number
293
+ readonly containingImage?: number
294
+ readonly framework?: {
295
+ readonly product: SwiftFrameworkProduct
296
+ readonly root: string
297
+ }
298
+ }): {
299
+ readonly images: ReadonlyMap<string, number>
300
+ readonly containingImages: ReadonlyMap<string, number>
301
+ readonly linkedArchives: readonly string[]
302
+ } {
303
+ const byFile = new Map<
304
+ string,
305
+ { id: string; artifact: SwiftSdkProduct['artifacts'][number] }[]
306
+ >()
307
+ const byId = new Map<string, SwiftSdkProduct>()
308
+ for (const { product, root } of options.products) {
309
+ byId.set(product.id, product)
310
+ for (const artifact of product.artifacts) {
311
+ const file = path.resolve(root, artifact.path)
312
+ const owners = byFile.get(file) ?? []
313
+ owners.push({ id: product.id, artifact })
314
+ byFile.set(file, owners)
315
+ }
316
+ }
317
+ const original = new Map<string, string>()
318
+ for (const [before, after] of options.rewritten) {
319
+ if (original.has(path.resolve(after)))
320
+ throw new Error(`ambiguous rewritten input ${after}`)
321
+ original.set(path.resolve(after), path.resolve(before))
322
+ }
323
+ const origins = new Map(
324
+ [...options.sdk.objectOrigins.values()].map((origin) => [
325
+ path.resolve(origin.original),
326
+ origin,
327
+ ]),
328
+ )
329
+ const roots: string[] = []
330
+ const frameworkId = options.framework
331
+ ? frameworkRuntimeProductId(options.framework.product)
332
+ : null
333
+ const frameworkObjects = new Set(
334
+ options.framework?.product.objects.map((object) =>
335
+ path.resolve(options.framework!.root, object.path),
336
+ ) ?? [],
337
+ )
338
+ const linkedArchives = new Set<string>()
339
+ for (const selection of options.selected) {
340
+ if ((selection.member === null) !== (selection.ordinal === null))
341
+ throw new Error(`incomplete selected archive member ${selection.artifact}`)
342
+ const file =
343
+ original.get(path.resolve(selection.artifact)) ?? path.resolve(selection.artifact)
344
+ const origin = origins.get(file)
345
+ const archive = origin ? path.resolve(origin.archive) : file
346
+ const records = byFile.get(archive)
347
+ if (frameworkObjects.has(file)) {
348
+ if (frameworkId === null || !byId.has(frameworkId))
349
+ throw new Error(`framework runtime product has no producer record ${file}`)
350
+ if (records?.some((record) => record.id !== frameworkId))
351
+ throw new Error(`framework input has conflicting runtime owner ${file}`)
352
+ if (!roots.includes(frameworkId)) roots.push(frameworkId)
353
+ if (!records) continue
354
+ }
355
+ if (!records) continue
356
+ const member = origin?.member ?? selection.member
357
+ const ordinal = origin?.ordinal ?? selection.ordinal
358
+ const owners = new Set(
359
+ records
360
+ .filter(({ artifact }) =>
361
+ artifact.kind === 'object'
362
+ ? member === null
363
+ : member !== null &&
364
+ ordinal !== null &&
365
+ artifact.members.some(
366
+ (entry) => entry.name === member && entry.ordinal === ordinal,
367
+ ),
368
+ )
369
+ .map(({ id }) => id),
370
+ )
371
+ if (owners.size !== 1)
372
+ throw new Error(`runtime input has missing or ambiguous product owner ${file}`)
373
+ const id = [...owners][0]!
374
+ if (!roots.includes(id)) roots.push(id)
375
+ if (!origin && member !== null) linkedArchives.add(file)
376
+ }
377
+ const images = new Map<string, number>()
378
+ const containingImages = new Map<string, number>()
379
+ const visit = (id: string) => {
380
+ if (images.has(id) || containingImages.has(id)) return
381
+ const product = byId.get(id)
382
+ if (!product) throw new Error(`unknown SDK source product ${id}`)
383
+ if (product.linkOwnership === 'containing-image') {
384
+ if (
385
+ options.containingImage === undefined ||
386
+ options.containingImage < 0 ||
387
+ options.containingImage >= options.firstImage
388
+ )
389
+ throw new Error(`SDK product ${id} has no containing image`)
390
+ if (product.linkDependencies !== null || product.autolink.length)
391
+ throw new Error(`SDK product ${id} has unresolved containing-image link facts`)
392
+ containingImages.set(id, options.containingImage)
393
+ return
394
+ }
395
+ if (product.linkDependencies === null)
396
+ throw new Error(`unresolved SDK link scope ${id}`)
397
+ images.set(id, options.firstImage + images.size)
398
+ for (const dependency of product.linkDependencies) {
399
+ const target = byId.get(dependency)
400
+ if (!target) throw new Error(`unknown SDK source product ${dependency}`)
401
+ if (target.linkOwnership === 'image') visit(dependency)
402
+ }
403
+ }
404
+ for (const root of roots) visit(root)
405
+ // verify duplicate catalog records agree before using the selected closure.
406
+ guestSdkProductImages(
407
+ options.products.map(({ product }) => product),
408
+ images,
409
+ )
410
+ return { images, containingImages, linkedArchives: [...linkedArchives] }
411
+ }
412
+
413
+ /** Join source and SDK products using only the caller's resolved direct links. */
414
+ export function composeGuestRuntimeLinkPlan(
415
+ source: GuestLinkPlan,
416
+ products: readonly SwiftSdkProduct[],
417
+ sdkImages: ReadonlyMap<string, number>,
418
+ sourceRuntimeLinks: ReadonlyMap<number, readonly string[]>,
419
+ ): GuestLinkPlan {
420
+ const runtime = guestSdkProductImages(products, sdkImages)
421
+ const ids = new Set(source.images.map((image) => image.id))
422
+ for (const image of runtime) {
423
+ if (ids.has(image.id)) throw new Error(`duplicate guest image ${image.id}`)
424
+ ids.add(image.id)
425
+ }
426
+ const sourceIds = new Set(source.images.map((image) => image.id))
427
+ const byId = new Map(products.map((product) => [product.id, product]))
428
+ for (const id of sourceRuntimeLinks.keys())
429
+ if (!sourceIds.has(id)) throw new Error(`unknown source image ${id}`)
430
+ const images: GuestLinkPlan['images'][number][] = source.images.map((image) => {
431
+ const links = sourceRuntimeLinks.get(image.id)
432
+ if (!links) throw new Error(`unresolved runtime scope for source image ${image.id}`)
433
+ const dependencies = [...image.dependencies]
434
+ for (const link of links) {
435
+ const product = byId.get(link)
436
+ if (!product) throw new Error(`unknown runtime product ${link}`)
437
+ // a static product lives in its containing image; another image that links
438
+ // it resolves those symbols from the containing image it is loaded into
439
+ if (product.linkOwnership === 'containing-image') continue
440
+ // a linked library the link extracted nothing from has no image, as an
441
+ // archive with no selected member contributes no object
442
+ const target = sdkImages.get(link)
443
+ if (target !== undefined && !dependencies.includes(target))
444
+ dependencies.push(target)
445
+ }
446
+ return { ...image, dependencies }
447
+ })
448
+ images.push(...runtime)
449
+ return { ...source, images, callers: ordinaryGuestCallerScopes(images) }
450
+ }
451
+
452
+ /** Own the actual SDK inputs described by source-produced product records. */
453
+ export function guestSdkProductLinkArtifacts(
454
+ products: readonly { readonly product: SwiftSdkProduct; readonly root: string }[],
455
+ sdk: SwiftPrunedSdkInputs,
456
+ inputs: readonly string[],
457
+ linkedArchives: readonly string[],
458
+ rewritten: ReadonlyMap<string, string>,
459
+ images: ReadonlyMap<string, number>,
460
+ selected?: readonly GuestLinkSelection[],
461
+ ): GuestLinkArtifact[] {
462
+ const linked = new Set(inputs.map((input) => path.resolve(input)))
463
+ const archives = new Set(linkedArchives.map((archive) => path.resolve(archive)))
464
+ const selectedObjects =
465
+ selected &&
466
+ new Set(
467
+ selected
468
+ .filter((entry) => entry.member === null)
469
+ .map((entry) => path.resolve(entry.artifact)),
470
+ )
471
+ const origins = [...sdk.objectOrigins.values()]
472
+ const claimed = new Set<string>()
473
+ const result: GuestLinkArtifact[] = []
474
+ const hashes = new Map<string, string>()
475
+ const archiveMembers = new Map<string, ReturnType<typeof readArMembers>>()
476
+ const verifiedMembers = new Map<
477
+ string,
478
+ { source: Map<string, Uint8Array>; linked: Map<string, Uint8Array> }
479
+ >()
480
+ const digest = (file: string) => {
481
+ let value = hashes.get(file)
482
+ if (!value) {
483
+ value = createHash('sha256').update(readFileSync(file)).digest('hex')
484
+ hashes.set(file, value)
485
+ }
486
+ return value
487
+ }
488
+ const byId = new Map<string, (typeof products)[number][]>()
489
+ for (const entry of products) {
490
+ const group = byId.get(entry.product.id) ?? []
491
+ group.push(entry)
492
+ byId.set(entry.product.id, group)
493
+ }
494
+ for (const { product, root } of products) {
495
+ for (const artifact of product.artifacts) {
496
+ const file = path.resolve(root, artifact.path)
497
+ const objects =
498
+ artifact.kind === 'archive'
499
+ ? origins.filter(
500
+ (origin) =>
501
+ path.resolve(origin.archive) === file &&
502
+ (!selectedObjects ||
503
+ selectedObjects.has(
504
+ path.resolve(rewritten.get(origin.original) ?? origin.original),
505
+ )),
506
+ )
507
+ : []
508
+ const direct =
509
+ artifact.kind === 'archive'
510
+ ? archives.has(file)
511
+ : linked.has(path.resolve(rewritten.get(file) ?? file)) &&
512
+ (!selectedObjects ||
513
+ selectedObjects.has(path.resolve(rewritten.get(file) ?? file)))
514
+ if (!direct && objects.length === 0) continue
515
+ const image = images.get(product.id)
516
+ if (image === undefined)
517
+ throw new Error(`SDK product ${product.id} has no guest image`)
518
+ const verified = sdkArtifactBytes(root, artifact)
519
+ const add = (input: GuestLinkArtifact) => {
520
+ if (claimed.has(input.path))
521
+ throw new Error(`SDK input has multiple owners ${input.path}`)
522
+ claimed.add(input.path)
523
+ result.push(input)
524
+ }
525
+ if (artifact.kind === 'object') {
526
+ const transformed = rewritten.get(file)
527
+ if (transformed) {
528
+ const transformation = sdk.transformations.get(file)
529
+ if (!transformation || transformation.output !== transformed)
530
+ throw new Error(`SDK object has no matching transformation ${file}`)
531
+ verifySdkObjectTransform(
532
+ verified.source,
533
+ readFileSync(transformed),
534
+ artifact.sha256,
535
+ transformation,
536
+ )
537
+ }
538
+ if (artifact.input) {
539
+ const input = artifact.input
540
+ const sources = byId.get(input.product)
541
+ if (!sources) throw new Error(`missing SDK input product ${input.product}`)
542
+ const matches = sources.flatMap((source) =>
543
+ source.product.artifacts
544
+ .filter(
545
+ (entry) =>
546
+ entry.path === input.artifact.path &&
547
+ entry.sha256 === input.artifact.sha256,
548
+ )
549
+ .map((original) => ({ original, root: source.root })),
550
+ )
551
+ if (matches.length !== 1)
552
+ throw new Error(
553
+ `ambiguous or missing SDK input artifact ${input.artifact.path}`,
554
+ )
555
+ const { original, root: sourceRoot } = matches[0]!
556
+ const originalFile = path.resolve(sourceRoot, original.path)
557
+ const originalBytes = sdkArtifactBytes(sourceRoot, original)
558
+ if (input.member) {
559
+ if (original.kind !== 'archive')
560
+ throw new Error(`SDK input member has no archive ${originalFile}`)
561
+ const { name, ordinal, sha256 } = input.member
562
+ const member = original.members.find(
563
+ (entry) =>
564
+ entry.name === name &&
565
+ entry.ordinal === ordinal &&
566
+ entry.sha256 === sha256,
567
+ )
568
+ let records = archiveMembers.get(originalFile)
569
+ if (!records) {
570
+ records = readArMembers(originalBytes.source)
571
+ archiveMembers.set(originalFile, records)
572
+ }
573
+ const bytes = records.filter((entry) => entry.name === name)[ordinal - 1]
574
+ ?.bytes
575
+ if (
576
+ !member ||
577
+ !bytes ||
578
+ createHash('sha256').update(bytes).digest('hex') !== sha256
579
+ )
580
+ throw new Error(`SDK input member changed ${originalFile}(${name})`)
581
+ } else if (original.kind !== 'object')
582
+ throw new Error(`SDK object input has no member ${originalFile}`)
583
+ }
584
+ add({ path: file, kind: 'object', image, instrumentDynamicLookups: true })
585
+ continue
586
+ }
587
+ const members = new Map(
588
+ artifact.members.map((member) => [
589
+ JSON.stringify([member.name, member.ordinal]),
590
+ member,
591
+ ]),
592
+ )
593
+ if (members.size !== artifact.members.length)
594
+ throw new Error(`duplicate SDK member record ${file}`)
595
+ let indexed = verifiedMembers.get(file)
596
+ if (!indexed) {
597
+ indexed = {
598
+ source: indexSdkMembers(verified.source),
599
+ linked: indexSdkMembers(verified.linked),
600
+ }
601
+ verifiedMembers.set(file, indexed)
602
+ }
603
+ for (const origin of objects) {
604
+ const key = JSON.stringify([origin.member, origin.ordinal])
605
+ const member = members.get(key)
606
+ const source = indexed.source.get(key)
607
+ const linked = indexed.linked.get(key)
608
+ if (
609
+ !member ||
610
+ !source ||
611
+ !linked ||
612
+ createHash('sha256').update(source).digest('hex') !== member.sha256 ||
613
+ createHash('sha256').update(linked).digest('hex') !== digest(origin.original)
614
+ )
615
+ throw new Error(`SDK member differs from source product ${origin.original}`)
616
+ add({
617
+ path: origin.original,
618
+ kind: 'object',
619
+ image,
620
+ instrumentDynamicLookups: true,
621
+ })
622
+ }
623
+ if (direct) {
624
+ const names = new Set(artifact.members.map((member) => member.name))
625
+ if (names.size !== artifact.members.length)
626
+ throw new Error(`ambiguous SDK archive member ${file}`)
627
+ add({
628
+ path: file,
629
+ kind: 'archive',
630
+ image,
631
+ instrumentDynamicLookups: true,
632
+ })
633
+ }
634
+ }
635
+ }
636
+ return result
637
+ }
638
+
639
+ /** Bind selected archive aliases to exact producer member identities. */
640
+ export function guestAliasedSdkArchiveArtifacts(options: {
641
+ readonly products: readonly {
642
+ readonly product: SwiftSdkProduct
643
+ readonly root: string
644
+ }[]
645
+ readonly archives: readonly AliasedGuestArchive[]
646
+ readonly selected: readonly GuestLinkSelection[]
647
+ readonly rewritten: ReadonlyMap<string, string>
648
+ readonly images: ReadonlyMap<string, number>
649
+ }): GuestLinkArtifact[] {
650
+ const originals = new Map(
651
+ [...options.rewritten].map(([before, after]) => [
652
+ path.resolve(after),
653
+ path.resolve(before),
654
+ ]),
655
+ )
656
+ if (originals.size !== options.rewritten.size)
657
+ throw new Error('ambiguous rewritten runtime archive')
658
+ const aliases = new Map(
659
+ options.archives.map((archive) => [path.resolve(archive.archive), archive]),
660
+ )
661
+ if (aliases.size !== options.archives.length)
662
+ throw new Error('duplicate aliased runtime archive')
663
+ const result: GuestLinkArtifact[] = []
664
+ for (const [alias, archive] of aliases) {
665
+ const source =
666
+ originals.get(path.resolve(archive.source)) ?? path.resolve(archive.source)
667
+ const records = options.products.flatMap(({ product, root }) =>
668
+ product.artifacts.flatMap((artifact) =>
669
+ artifact.kind === 'archive' && path.resolve(root, artifact.path) === source
670
+ ? [{ product, artifact, root }]
671
+ : [],
672
+ ),
673
+ )
674
+ if (!records.length) continue
675
+ const verified = records.map(({ root, artifact }) => sdkArtifactBytes(root, artifact))
676
+ const sourceMembers = verified.map(({ source }) => indexSdkMembers(source))
677
+ const viewMembers = verified.map(({ linked }) => indexSdkMembers(linked))
678
+ const memberImages = new Map<string, number>()
679
+ const memberOrigins = new Map(archive.members.map((member) => [member.alias, member]))
680
+ for (const selection of options.selected) {
681
+ if (path.resolve(selection.artifact) !== alias) continue
682
+ const member =
683
+ selection.member === null ? undefined : memberOrigins.get(selection.member)
684
+ if (!member) throw new Error(`unknown selected runtime member ${selection.member}`)
685
+ const owners = new Set(
686
+ records.flatMap(({ product, artifact }, index) =>
687
+ artifact.members.some((entry) => {
688
+ if (entry.name !== member.name || entry.ordinal !== member.ordinal)
689
+ return false
690
+ const key = JSON.stringify([member.name, member.ordinal])
691
+ const bytes = sourceMembers[index]!.get(key)
692
+ const linked = viewMembers[index]!.get(key)
693
+ return (
694
+ bytes !== undefined &&
695
+ linked !== undefined &&
696
+ createHash('sha256').update(bytes).digest('hex') === entry.sha256 &&
697
+ createHash('sha256').update(linked).digest('hex') === member.sha256
698
+ )
699
+ })
700
+ ? [product.id]
701
+ : [],
702
+ ),
703
+ )
704
+ if (owners.size !== 1)
705
+ throw new Error(
706
+ `runtime member has missing or ambiguous product owner ${source}(${member.name}, ${member.ordinal})`,
707
+ )
708
+ const image = options.images.get([...owners][0]!)
709
+ if (image === undefined)
710
+ throw new Error(
711
+ `runtime member has no guest image ${source}(${member.name}, ${member.ordinal})`,
712
+ )
713
+ memberImages.set(member.alias, image)
714
+ }
715
+ result.push({
716
+ path: archive.archive,
717
+ kind: 'archive',
718
+ image: null,
719
+ memberImages,
720
+ memberOrigins,
721
+ instrumentDynamicLookups: true,
722
+ })
723
+ }
724
+ return result
725
+ }
726
+
727
+ /** Resolve merged runtime members using their original product bytes. */
728
+ export function guestCxxMemberOwners(
729
+ origins: readonly SwiftSdkObjectOrigin[],
730
+ products: GuestCxxProducts,
731
+ ): {
732
+ readonly origin: SwiftSdkObjectOrigin
733
+ readonly image: number
734
+ readonly sha256: string
735
+ }[] {
736
+ const inputs = [
737
+ { product: 'libcxx', ...products.libcxx },
738
+ { product: 'libcxxabi', ...products.libcxxabi },
739
+ { product: 'unwind', ...products.unwind },
740
+ ]
741
+ if (new Set(inputs.map((input) => path.resolve(input.archive))).size !== inputs.length)
742
+ throw new Error('C++ runtime products must have distinct archives')
743
+ if (new Set(inputs.map((input) => input.image)).size !== inputs.length)
744
+ throw new Error('C++ runtime products must have distinct images')
745
+ const archives = new Set(inputs.map((input) => path.resolve(input.archive)))
746
+ const selected = origins.filter((origin) => archives.has(path.resolve(origin.archive)))
747
+ return swiftArchiveMemberProducts(selected, inputs).map((match) => {
748
+ // the source build places unwind into libcxxabi and libcxxabi into libcxx.
749
+ // the innermost matching product owns a byte-identical merged member.
750
+ const names = new Set(match.products.map((product) => product.product))
751
+ const owner = names.has('unwind')
752
+ ? products.unwind
753
+ : names.has('libcxxabi')
754
+ ? products.libcxxabi
755
+ : names.has('libcxx')
756
+ ? products.libcxx
757
+ : undefined
758
+ if (!owner)
759
+ throw new Error(
760
+ `unowned C++ runtime member ${match.original.archive}(${match.original.member})`,
761
+ )
762
+ return { origin: match.original, image: owner.image, sha256: match.sha256 }
763
+ })
764
+ }
765
+
766
+ /** Own runtime archives and unpacked SDK members actually supplied to the link. */
767
+ export function guestCxxLinkArtifacts(
768
+ sdk: SwiftPrunedSdkInputs,
769
+ linkedArchives: readonly string[],
770
+ products: GuestCxxProducts,
771
+ ): GuestLinkArtifact[] {
772
+ const runtimeArchives = new Set(
773
+ [products.libcxx, products.libcxxabi, products.unwind].map((product) =>
774
+ path.resolve(product.archive),
775
+ ),
776
+ )
777
+ const objects = [...sdk.objectOrigins.values()].filter((origin) =>
778
+ runtimeArchives.has(path.resolve(origin.archive)),
779
+ )
780
+ const archives = linkedArchives.filter((archive) =>
781
+ runtimeArchives.has(path.resolve(archive)),
782
+ )
783
+ const origins: SwiftSdkObjectOrigin[] = [...objects]
784
+ for (const archive of archives) {
785
+ const members = readArMembers(readFileSync(archive))
786
+ const names = new Set<string>()
787
+ for (const member of members) {
788
+ if (names.has(member.name)) throw new Error(`ambiguous runtime archive ${archive}`)
789
+ names.add(member.name)
790
+ origins.push({ archive, member: member.name, ordinal: 1 })
791
+ }
792
+ }
793
+ const owners = guestCxxMemberOwners(origins, products)
794
+ const byOrigin = new Map(
795
+ owners.map(({ origin, image }) => [
796
+ JSON.stringify([path.resolve(origin.archive), origin.member, origin.ordinal]),
797
+ image,
798
+ ]),
799
+ )
800
+ const imageOf = (origin: SwiftSdkObjectOrigin) => {
801
+ const image = byOrigin.get(
802
+ JSON.stringify([path.resolve(origin.archive), origin.member, origin.ordinal]),
803
+ )
804
+ if (image === undefined) throw new Error(`unowned runtime object ${origin.member}`)
805
+ return image
806
+ }
807
+ return [
808
+ ...objects.map(
809
+ (origin) =>
810
+ ({
811
+ path: origin.original,
812
+ kind: 'object',
813
+ image: imageOf(origin),
814
+ instrumentDynamicLookups: false,
815
+ }) satisfies GuestLinkArtifact,
816
+ ),
817
+ ...archives.map(
818
+ (archive) =>
819
+ ({
820
+ path: archive,
821
+ kind: 'archive',
822
+ image: null,
823
+ memberImages: new Map(
824
+ owners
825
+ .filter(
826
+ ({ origin }) => path.resolve(origin.archive) === path.resolve(archive),
827
+ )
828
+ .map(({ origin, image }) => [origin.member, image]),
829
+ ),
830
+ instrumentDynamicLookups: false,
831
+ }) satisfies GuestLinkArtifact,
832
+ ),
833
+ ]
834
+ }