peachsim 0.1.1667 → 0.1.1674

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 (204) hide show
  1. package/README.md +1 -1
  2. package/cli/bridge-flow-runner.ts +4 -1
  3. package/cli/commands/coverage-swift.ts +291 -0
  4. package/cli/commands/coverage.ts +168 -24
  5. package/cli/commands/diagnose.ts +1 -19
  6. package/cli/commands/inspect/settling.ts +37 -4
  7. package/cli/commands/react.ts +3 -18
  8. package/cli/commands/screenshot.ts +1 -1
  9. package/cli/commands/screenshots-capture.ts +1 -1
  10. package/cli/drivers/playwright-provisioning.ts +1 -4
  11. package/cli/drivers/playwright.ts +15 -1
  12. package/cli/scene-video.ts +1 -1
  13. package/cli/ui.ts +20 -0
  14. package/cli/ws-bridge.ts +7 -36
  15. package/detox/frame-identity.cjs +21 -0
  16. package/detox/frame-identity.d.cts +6 -0
  17. package/detox/index.ts +39 -33
  18. package/detox/jest-environment.cjs +4 -1
  19. package/detox/jest-setup-after-env.cjs +0 -4
  20. package/detox/navigation-lifecycle.ts +2 -2
  21. package/detox/proof-observer.ts +126 -0
  22. package/dist-lib/agent-daemon-client.cjs +29 -1
  23. package/dist-lib/agent-events.cjs +1 -1
  24. package/dist-lib/attached-projects.cjs +10 -1
  25. package/dist-lib/auth/shared-session.cjs +1 -1
  26. package/dist-lib/backend-origin.cjs +1 -1
  27. package/dist-lib/beta.cjs +1 -1
  28. package/dist-lib/beta.mjs +1 -1
  29. package/dist-lib/bridge-constants.cjs +1 -1
  30. package/dist-lib/bridge-contract-input.cjs +1 -1
  31. package/dist-lib/bridge-contract-input.mjs +1 -1
  32. package/dist-lib/bridge-contract.cjs +1 -1
  33. package/dist-lib/bridge-contract.mjs +1 -1
  34. package/dist-lib/bundle-channel.cjs +557 -158
  35. package/dist-lib/capture-contract.cjs +1 -1
  36. package/dist-lib/capture-contract.mjs +1 -1
  37. package/dist-lib/cloud-contract.cjs +1 -1
  38. package/dist-lib/cloud-contract.mjs +1 -1
  39. package/dist-lib/cloud-test-args.cjs +1 -1
  40. package/dist-lib/cloud-test-args.mjs +1 -1
  41. package/dist-lib/cloud.cjs +1 -1
  42. package/dist-lib/cloud.mjs +1 -1
  43. package/dist-lib/config.cjs +1 -1
  44. package/dist-lib/config.mjs +1 -1
  45. package/dist-lib/detox/index.cjs +5098 -7344
  46. package/dist-lib/detox/jest-environment.cjs +4 -1
  47. package/dist-lib/dev-bundle-resolution.cjs +1 -1
  48. package/dist-lib/expo-swift-bundle.cjs +602 -152
  49. package/dist-lib/expo-swift-metadata.cjs +1 -1
  50. package/dist-lib/expo-swift-metadata.mjs +1 -1
  51. package/dist-lib/home-paths.cjs +1 -1
  52. package/dist-lib/host/bridge-host.cjs +688 -194
  53. package/dist-lib/host/fetch-proxy-handler.cjs +6 -3
  54. package/dist-lib/host/fetch-proxy-overrides.cjs +1 -1
  55. package/dist-lib/host/fetch-proxy-overrides.mjs +1 -1
  56. package/dist-lib/host/replacement-module-handler.cjs +1 -1
  57. package/dist-lib/host/websocket-proxy.cjs +1 -1
  58. package/dist-lib/index.cjs +247 -11
  59. package/dist-lib/jump-to-source-babel.cjs +1 -1
  60. package/dist-lib/jump-to-source-native.cjs +1 -1
  61. package/dist-lib/kotlin-host.cjs +1 -1
  62. package/dist-lib/menu.cjs +1 -1
  63. package/dist-lib/menu.mjs +1 -1
  64. package/dist-lib/metro-fingerprint-registry.cjs +1 -1
  65. package/dist-lib/metro-fingerprint-registry.mjs +1 -1
  66. package/dist-lib/metro-production-bundle.cjs +10 -1
  67. package/dist-lib/metro-production-bundle.mjs +12 -1
  68. package/dist-lib/metro.cjs +155 -5
  69. package/dist-lib/native-app-identity-project.cjs +43 -5
  70. package/dist-lib/native-app-identity-project.mjs +43 -5
  71. package/dist-lib/native-app-identity.cjs +1 -1
  72. package/dist-lib/native-app-identity.mjs +1 -1
  73. package/dist-lib/native-firebase-metadata.cjs +1 -1
  74. package/dist-lib/native-firebase-metadata.mjs +1 -1
  75. package/dist-lib/plist.cjs +1 -1
  76. package/dist-lib/plist.mjs +1 -1
  77. package/dist-lib/profiles.cjs +21 -1
  78. package/dist-lib/public-brand.cjs +1 -1
  79. package/dist-lib/public-origins-lib-esm.json +73 -27
  80. package/dist-lib/public-origins-lib-static.json +1 -1
  81. package/dist-lib/public-origins-lib.json +563 -183
  82. package/dist-lib/react-native-host-modules.cjs +1 -1
  83. package/dist-lib/react-native-host-modules.mjs +1 -1
  84. package/dist-lib/reap-browser.cjs +964 -0
  85. package/dist-lib/scripts/dev-server-scanner.cjs +1 -1
  86. package/dist-lib/sdk.cjs +38 -5
  87. package/dist-lib/sdk.mjs +38 -5
  88. package/dist-lib/skills.cjs +1031 -530
  89. package/dist-lib/swift-compile.cjs +298 -86
  90. package/dist-lib/swift-compile.mjs +298 -86
  91. package/dist-lib/swift-package.cjs +53 -4
  92. package/dist-lib/swift-package.mjs +52 -4
  93. package/dist-lib/swift-submit.cjs +2 -2
  94. package/dist-lib/swift-submit.mjs +2 -2
  95. package/dist-lib/swift-toolchain.cjs +25 -44
  96. package/dist-lib/swift.cjs +1 -1
  97. package/dist-lib/vite-swift.cjs +603 -114
  98. package/dist-lib/vite.cjs +65 -3
  99. package/dist-lib/worklet-executable.cjs +1 -1
  100. package/dist-lib/worklet-executable.mjs +1 -1
  101. package/dist-types/packages/peach-engine/src/engine/clipboardContract.d.ts +7 -0
  102. package/dist-types/packages/peach-engine/src/engine/glass-material.d.ts +1 -1
  103. package/dist-types/packages/peach-engine/src/engine/image-loader.d.ts +2 -0
  104. package/dist-types/packages/peach-engine/src/engine/inspect-outline.d.ts +2 -1
  105. package/dist-types/packages/peach-engine/src/engine/liquid-glass.d.ts +1 -0
  106. package/dist-types/packages/peach-engine/src/engine/paint-boundary.d.ts +4 -1
  107. package/dist-types/packages/peach-engine/src/render-worker/host-service-protocol.d.ts +7 -0
  108. package/dist-types/packages/peach-engine/src/render-worker/worklet-runtime-kind.d.ts +24 -0
  109. package/dist-types/packages/peach-engine/src/render-worker/worklet-runtime.d.ts +4 -2
  110. package/dist-types/packages/peach-engine/src/rolldown-bundle-inventory.d.ts +1 -1
  111. package/dist-types/packages/peach-engine/src/settings/devices.d.ts +1 -0
  112. package/dist-types/packages/peach-globals/src/clipboardBridgeContract.d.ts +18 -0
  113. package/dist-types/packages/peach-globals/src/compositorBridgeContract.d.ts +10 -1
  114. package/dist-types/packages/peach-globals/src/index.d.ts +2 -2
  115. package/dist-types/packages/peach-globals/src/nodeContract.d.ts +1 -0
  116. package/dist-types/packages/peach-kit/src/capabilities.d.ts +1 -0
  117. package/package.json +1 -1
  118. package/runtime-companion.json +1 -1
  119. package/sdk/ios/System/Library/Frameworks/CoreFoundation.framework/Headers/CFString.h +2 -0
  120. package/sdk/ios/System/Library/Frameworks/CoreFoundation.framework/Headers/CoreFoundation.h +54 -0
  121. package/sdk/ios/System/Library/Frameworks/Foundation.framework/Headers/Foundation.h +23 -4
  122. package/sdk/ios/System/Library/Frameworks/SystemConfiguration.framework/Headers/SCDynamicStore.h +439 -0
  123. package/sdk/ios/System/Library/Frameworks/SystemConfiguration.framework/Headers/SCDynamicStoreCopySpecific.h +216 -0
  124. package/sdk/ios/System/Library/Frameworks/SystemConfiguration.framework/Headers/SCDynamicStoreKey.h +267 -0
  125. package/sdk/ios/System/Library/Frameworks/SystemConfiguration.framework/Headers/SCNetwork.h +204 -0
  126. package/sdk/ios/System/Library/Frameworks/SystemConfiguration.framework/Headers/SCNetworkConfiguration.h +1393 -0
  127. package/sdk/ios/System/Library/Frameworks/SystemConfiguration.framework/Headers/SCNetworkConnection.h +568 -0
  128. package/sdk/ios/System/Library/Frameworks/SystemConfiguration.framework/Headers/SCNetworkReachability.h +369 -0
  129. package/sdk/ios/System/Library/Frameworks/SystemConfiguration.framework/Headers/SCPreferences.h +473 -0
  130. package/sdk/ios/System/Library/Frameworks/SystemConfiguration.framework/Headers/SCPreferencesPath.h +179 -0
  131. package/sdk/ios/System/Library/Frameworks/SystemConfiguration.framework/Headers/SCPreferencesSetSpecific.h +95 -0
  132. package/sdk/ios/System/Library/Frameworks/SystemConfiguration.framework/Headers/SCSchemaDefinitions.h +2395 -0
  133. package/sdk/ios/System/Library/Frameworks/SystemConfiguration.framework/Headers/SystemConfiguration.h +184 -0
  134. package/sdk/ios/usr/include/_ctype.h +388 -0
  135. package/sdk/ios/usr/include/_inttypes.h +296 -0
  136. package/sdk/ios/usr/include/_locale.h +83 -0
  137. package/sdk/ios/usr/include/_locale_posix2008.h +65 -0
  138. package/sdk/ios/usr/include/_time.h +207 -0
  139. package/sdk/ios/usr/include/ctype.h +70 -0
  140. package/sdk/ios/usr/include/dispatch/dispatch.h +69 -6
  141. package/sdk/ios/usr/include/inttypes.h +35 -0
  142. package/sdk/ios/usr/include/libkern/OSByteOrder.h +315 -0
  143. package/sdk/ios/usr/include/libkern/machine/OSByteOrder.h +147 -0
  144. package/sdk/ios/usr/include/locale.h +59 -0
  145. package/sdk/ios/usr/include/runetype.h +118 -0
  146. package/sdk/ios/usr/include/setjmp.h +99 -0
  147. package/sdk/ios/usr/include/sys/_types/_clock_t.h +32 -0
  148. package/sdk/ios/usr/include/sys/_types/_ct_rune_t.h +33 -0
  149. package/sdk/ios/usr/include/sys/_types/_rune_t.h +32 -0
  150. package/sdk/ios/usr/include/sys/_types/_time_t.h +32 -0
  151. package/sdk/ios/usr/include/sys/_types/_wint_t.h +33 -0
  152. package/sdk/ios/usr/include/sys/cdefs.h +2 -0
  153. package/sdk/ios/usr/include/time.h +67 -2
  154. package/src/bridge-contract.ts +42 -0
  155. package/src/chromium-admission.ts +196 -0
  156. package/src/host/bridge-host.ts +6 -43
  157. package/src/host/rolldown-bundle-forward.ts +4 -1
  158. package/src/launch-deadline.ts +74 -0
  159. package/src/nitro-adapter.lock.json +3 -3
  160. package/src/profiles.ts +21 -0
  161. package/src/react-native-coverage/capability-reference-resolution.ts +402 -0
  162. package/src/react-native-coverage/capability-source-references.ts +1296 -0
  163. package/src/react-native-coverage/native-typescript-parser.ts +74 -0
  164. package/src/react-native-coverage/project-aliases.ts +207 -0
  165. package/src/react-native-coverage/verified-reach.ts +47 -0
  166. package/src/reap-browser.ts +1019 -0
  167. package/src/skills/builtin/a11y-review.ts +1 -1
  168. package/src/skills/builtin/perf-profile.ts +1 -1
  169. package/src/skills/builtin/screenshot-all.ts +1 -1
  170. package/src/skills/builtin/visual-diff.ts +1 -1
  171. package/src/swift-compile.ts +109 -57
  172. package/src/swift-coverage/indexdump.ts +80 -0
  173. package/src/swift-coverage/indexing.ts +147 -0
  174. package/src/swift-coverage/package.ts +230 -0
  175. package/src/swift-coverage/provenance.ts +47 -0
  176. package/src/swift-coverage/reader.ts +81 -0
  177. package/src/swift-coverage/source.ts +252 -0
  178. package/src/swift-coverage/types.ts +58 -0
  179. package/src/swift-coverage/xcode-assets.ts +175 -0
  180. package/src/swift-coverage/xcode-bridging.ts +160 -0
  181. package/src/swift-coverage/xcode-packages.ts +251 -0
  182. package/src/swift-coverage/xcode-strings.ts +78 -0
  183. package/src/swift-coverage/xcode.ts +656 -0
  184. package/src/swift-distribution.lock.json +8 -8
  185. package/src/swift-host.ts +21 -1
  186. package/src/swift-objc-compile.ts +7 -3
  187. package/src/swift-objc-import.ts +191 -27
  188. package/src/swift-objc-metadata.ts +2 -2
  189. package/src/swift-objc-standin.ts +9 -2
  190. package/src/swift-package-manifest.ts +134 -13
  191. package/src/swift-package.ts +69 -4
  192. package/src/swift-standins.ts +4 -1
  193. package/src/swift-submit.ts +2 -1
  194. package/src/swift-toolchain.ts +36 -61
  195. package/src/worker-system-chunks.ts +3 -10
  196. package/src/xcode-project.ts +5 -5
  197. package/detox/attempt-events.cjs +0 -914
  198. package/detox/attempt-events.d.cts +0 -113
  199. package/detox/motion-change.cjs +0 -524
  200. package/detox/motion-change.d.cts +0 -140
  201. package/detox/motion-leg-starts.cjs +0 -20
  202. package/detox/motion-leg-starts.d.cts +0 -8
  203. package/detox/proof-frame.cjs +0 -190
  204. package/detox/record-block-execution.cjs +0 -78
@@ -0,0 +1,175 @@
1
+ import { execFileSync } from 'node:child_process'
2
+ import { createHash } from 'node:crypto'
3
+ import { mkdirSync, readFileSync, readdirSync, statSync } from 'node:fs'
4
+ import { join, relative, sep } from 'node:path'
5
+
6
+ const sha256 = (bytes: string | Buffer) =>
7
+ createHash('sha256').update(bytes).digest('hex')
8
+
9
+ // settings that change what Xcode passes to actool beyond the symbol file
10
+ // itself. their effect on the generated source is unproven, so they stay unknown.
11
+ export const assetSymbolSettingKeys = [
12
+ 'ASSETCATALOG_COMPILER_GENERATE_ASSET_SYMBOLS',
13
+ 'ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS',
14
+ 'PRODUCT_BUNDLE_IDENTIFIER',
15
+ 'TARGETED_DEVICE_FAMILY',
16
+ 'ASSETCATALOG_COMPILER_GENERATE_ASSET_SYMBOL_FRAMEWORKS',
17
+ 'ASSETCATALOG_COMPILER_GENERATE_ASSET_SYMBOL_WARNINGS',
18
+ 'ASSETCATALOG_COMPILER_GENERATE_ASSET_SYMBOL_ERRORS',
19
+ 'ASSETCATALOG_COMPILER_GENERATE_ASSET_SYMBOL_BACKWARDS_DEPLOYMENT_SUPPORT',
20
+ 'ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOLS_PATH',
21
+ 'ASSETCATALOG_COMPILER_GENERATE_OBJC_ASSET_SYMBOLS_PATH',
22
+ 'ASSETCATALOG_COMPILER_GENERATE_ASSET_SYMBOL_INDEX_PATH',
23
+ 'ASSETCATALOG_COMPILER_BUNDLE_IDENTIFIER',
24
+ 'ASSETCATALOG_COMPILER_LIGHTWEIGHT_ASSET_RUNTIME_MODE',
25
+ 'ASSETCATALOG_OTHER_FLAGS',
26
+ ]
27
+
28
+ const unprovenAssetSettings = assetSymbolSettingKeys.slice(4)
29
+
30
+ export type SwiftAssetPlan = {
31
+ catalogs: { path: string; sha256: string }[]
32
+ arguments: string[]
33
+ }
34
+
35
+ // the catalog directories that hold target resources, with a digest of every
36
+ // file inside so a change between planning and generation is detectable.
37
+ function catalogDigest(directory: string) {
38
+ const hashes: [string, string][] = []
39
+ const walk = (dir: string) => {
40
+ for (const entry of readdirSync(dir, { withFileTypes: true }).sort((a, b) =>
41
+ a.name.localeCompare(b.name),
42
+ )) {
43
+ const path = join(dir, entry.name)
44
+ if (entry.isDirectory()) walk(path)
45
+ else if (entry.isFile() && statSync(path).size <= 64 * 1024 * 1024)
46
+ hashes.push([relative(directory, path), sha256(readFileSync(path))])
47
+ else throw new Error(`Unsupported asset catalog entry: ${path}`)
48
+ }
49
+ }
50
+ walk(directory)
51
+ return sha256(JSON.stringify(hashes))
52
+ }
53
+
54
+ // stock Xcode runs actool with these arguments; the extension flag appears only
55
+ // when the setting resolves to NO, which is also the xcspec default.
56
+ export function planAssetSymbols(
57
+ resources: string[],
58
+ root: string,
59
+ settings: Record<string, string>,
60
+ ) {
61
+ const marker = '.xcassets'
62
+ const catalogs = [
63
+ ...new Set(
64
+ resources.flatMap((file) => {
65
+ const at = file.indexOf(`${marker}${sep}`)
66
+ return file.endsWith(marker)
67
+ ? [file]
68
+ : at >= 0
69
+ ? [file.slice(0, at + marker.length)]
70
+ : []
71
+ }),
72
+ ),
73
+ ].sort()
74
+ if (!catalogs.length) return { status: 'none' as const }
75
+ if (settings.ASSETCATALOG_COMPILER_GENERATE_ASSET_SYMBOLS === 'NO')
76
+ return { status: 'none' as const }
77
+ const unknown = (reason: string) => ({ status: 'unknown' as const, reason })
78
+ const generate = settings.ASSETCATALOG_COMPILER_GENERATE_ASSET_SYMBOLS
79
+ if (generate && generate !== 'YES')
80
+ return unknown(
81
+ 'ASSETCATALOG_COMPILER_GENERATE_ASSET_SYMBOLS must resolve to YES or NO.',
82
+ )
83
+ const extensions = settings.ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS
84
+ if (extensions && extensions !== 'YES' && extensions !== 'NO')
85
+ return unknown(
86
+ 'ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS must resolve to YES or NO.',
87
+ )
88
+ const set = unprovenAssetSettings.filter((key) => settings[key])
89
+ if (set.length)
90
+ return unknown(
91
+ `Generated asset symbols are unproven with these settings: ${set.join(', ')}`,
92
+ )
93
+ const bundle = settings.PRODUCT_BUNDLE_IDENTIFIER
94
+ const target = settings.IPHONEOS_DEPLOYMENT_TARGET
95
+ if (!bundle || !target || /\$\(|\s/.test(bundle + target))
96
+ return unknown(
97
+ 'Generated asset symbols need a resolved PRODUCT_BUNDLE_IDENTIFIER and IPHONEOS_DEPLOYMENT_TARGET.',
98
+ )
99
+ const families = (settings.TARGETED_DEVICE_FAMILY ?? '').split(',').sort().join(',')
100
+ // family 7 adds the visionOS designed-for-iPad slot, which changes neither the
101
+ // actool arguments nor the symbols for the iOS slice
102
+ const devices = {
103
+ '1': ['iphone'],
104
+ '2': ['ipad'],
105
+ '1,2': ['iphone', 'ipad'],
106
+ '1,2,7': ['iphone', 'ipad'],
107
+ }[families]
108
+ if (!devices)
109
+ return unknown(
110
+ `Generated asset symbols are proven only for TARGETED_DEVICE_FAMILY 1, 2, 1,2 or 1,2,7; this target resolves to "${settings.TARGETED_DEVICE_FAMILY ?? ''}".`,
111
+ )
112
+ return {
113
+ status: 'plan' as const,
114
+ plan: {
115
+ catalogs: catalogs.map((path) => ({
116
+ path,
117
+ sha256: catalogDigest(join(root, path)),
118
+ })),
119
+ arguments: [
120
+ '--output-format',
121
+ 'human-readable-text',
122
+ '--platform',
123
+ 'iphonesimulator',
124
+ '--minimum-deployment-target',
125
+ target,
126
+ ...devices.flatMap((device) => ['--target-device', device]),
127
+ '--bundle-identifier',
128
+ bundle,
129
+ ...(extensions === 'YES'
130
+ ? []
131
+ : ['--generate-swift-asset-symbol-extensions', 'NO']),
132
+ ],
133
+ } satisfies SwiftAssetPlan,
134
+ }
135
+ }
136
+
137
+ // run the same actool Xcode runs and return the swift symbol file it writes.
138
+ export function generateAssetSymbols(plan: SwiftAssetPlan, root: string, work: string) {
139
+ const compile = join(work, 'compiled')
140
+ mkdirSync(compile, { recursive: true })
141
+ const swift = join(work, 'GeneratedAssetSymbols.swift')
142
+ const args = [
143
+ 'actool',
144
+ ...plan.catalogs.map(({ path }) => join(root, path)),
145
+ '--compile',
146
+ compile,
147
+ '--output-partial-info-plist',
148
+ join(work, 'partial-info.plist'),
149
+ ...plan.arguments,
150
+ '--generate-swift-asset-symbols',
151
+ swift,
152
+ '--generate-objc-asset-symbols',
153
+ join(work, 'GeneratedAssetSymbols.h'),
154
+ '--generate-asset-symbol-index',
155
+ join(work, 'GeneratedAssetSymbols-Index.plist'),
156
+ ]
157
+ const run = (extra: string[]) =>
158
+ execFileSync('xcrun', extra, {
159
+ encoding: 'utf8',
160
+ stdio: ['ignore', 'pipe', 'pipe'],
161
+ })
162
+ const version = run(['actool', '--version', '--output-format', 'xml1'])
163
+ run(args)
164
+ const content = readFileSync(swift)
165
+ return {
166
+ path: swift,
167
+ producer: {
168
+ tool: 'xcrun actool',
169
+ version: version.trim(),
170
+ arguments: args.map((arg) => arg.replace(root, '<root>').replace(work, '<work>')),
171
+ catalogs: plan.catalogs,
172
+ sha256: sha256(content),
173
+ },
174
+ }
175
+ }
@@ -0,0 +1,160 @@
1
+ import { createHash } from 'node:crypto'
2
+ import { basename, isAbsolute, join, relative, sep } from 'node:path'
3
+ import { readPackageFile } from '../swift-source-file'
4
+ import { writeXcodeHeaderSearch } from '../xcode-header-search'
5
+ import type { SwiftNativeHeaderMap } from '../swiftContract'
6
+ import type { readXcodeAppTarget } from '../xcode-project'
7
+
8
+ const sha256 = (bytes: string | Buffer) =>
9
+ createHash('sha256').update(bytes).digest('hex')
10
+
11
+ export type SwiftBridgingPlan = {
12
+ header: string
13
+ /** every project header the clang importer can reach, with the bytes it read. */
14
+ headers: { path: string; sha256: string }[]
15
+ /** header map entries, with values relative to the app root. */
16
+ headerMaps: SwiftNativeHeaderMap[]
17
+ searchPaths: string[]
18
+ userSearchPaths: string[]
19
+ definitions: string[]
20
+ }
21
+
22
+ type App = Pick<ReturnType<typeof readXcodeAppTarget>, 'objc' | 'settings'>
23
+
24
+ // settings that reach swiftc through a bridging header. Xcode passes the header
25
+ // maps, USER_HEADER_SEARCH_PATHS, HEADER_SEARCH_PATHS and the preprocessor
26
+ // definitions as -Xcc arguments before -import-objc-header (checked against
27
+ // the swift-frontend command line of a real build).
28
+ export function planBridgingHeader(
29
+ app: App,
30
+ root: string,
31
+ files: Record<string, string>,
32
+ settings: Record<string, string>,
33
+ ) {
34
+ const raw = settings.SWIFT_OBJC_BRIDGING_HEADER
35
+ if (!raw) return { status: 'none' as const }
36
+ const unknown = (reason: string) => ({ status: 'unknown' as const, reason })
37
+ const objc = app.objc
38
+ if (!objc)
39
+ return unknown(
40
+ 'A bridging header needs the target header maps, which Xcode models only for targets with C-family implementation sources.',
41
+ )
42
+ if (settings.ALWAYS_SEARCH_USER_PATHS === 'YES')
43
+ return unknown(
44
+ 'ALWAYS_SEARCH_USER_PATHS=YES also searches USER_HEADER_SEARCH_PATHS for angle-bracket includes, which is not modeled.',
45
+ )
46
+ const relativeToRoot = (file: string) => {
47
+ const path = relative(root, file)
48
+ return path === '..' || path.startsWith(`..${sep}`) || isAbsolute(path) ? null : path
49
+ }
50
+ // every path inside the app root, or null when one escapes it
51
+ const inside = (paths: readonly string[]) => {
52
+ const found: string[] = []
53
+ for (const file of paths) {
54
+ const path = relativeToRoot(file)
55
+ if (path === null) return null
56
+ found.push(path)
57
+ }
58
+ return found
59
+ }
60
+ const byName = (a: string, b: string) => (a < b ? -1 : a > b ? 1 : 0)
61
+ const header = objc.bridgingHeader && relativeToRoot(objc.bridgingHeader)
62
+ if (!header)
63
+ return unknown('The bridging header must resolve to a file inside the app root.')
64
+ const searchPaths = inside(objc.headerSearchPaths)
65
+ const userSearchPaths = inside(objc.userHeaderSearchPaths)
66
+ const members = inside(objc.headers)
67
+ if (!searchPaths || !userSearchPaths || !members)
68
+ return unknown(
69
+ 'Header search paths and project headers must stay inside the app root.',
70
+ )
71
+ const headerMaps: SwiftNativeHeaderMap[] = []
72
+ for (const map of objc.headerMaps) {
73
+ const entries: [string, string][] = []
74
+ for (const [name, value] of map.entries) {
75
+ const path = isAbsolute(value) ? relativeToRoot(value) : null
76
+ if (path === null)
77
+ return unknown(
78
+ `Header map entry ${name} names a header outside the app root or a framework include, which is not modeled.`,
79
+ )
80
+ entries.push([name, path])
81
+ }
82
+ headerMaps.push({ flag: map.flag, entries })
83
+ }
84
+ // xcode's project map also lists the headers of synchronized source folders,
85
+ // which the project reader's map omits because they are not file references.
86
+ const projectMap = headerMaps.find((map) => map.flag === '-iquote')
87
+ if (projectMap) {
88
+ const named = new Set(projectMap.entries.map(([name]) => name.toLowerCase()))
89
+ for (const path of [...members].sort(byName))
90
+ if (!named.has(basename(path).toLowerCase())) {
91
+ named.add(basename(path).toLowerCase())
92
+ projectMap.entries.push([basename(path), path])
93
+ }
94
+ }
95
+ const definitions = (settings.GCC_PREPROCESSOR_DEFINITIONS ?? '')
96
+ .split(/\s+/)
97
+ .filter(Boolean)
98
+ if (!definitions.every((item) => /^[A-Za-z_]\w*(?:=[^\s"'\\$]*)?$/.test(item)))
99
+ return unknown(
100
+ 'GCC_PREPROCESSOR_DEFINITIONS holds a value that is not a plain macro.',
101
+ )
102
+ const digests: { path: string; sha256: string }[] = []
103
+ for (const path of [...new Set([header, ...members])].sort(byName)) {
104
+ const snapshot = files[path]
105
+ if (snapshot === undefined)
106
+ return unknown('Project headers must belong to the source snapshot.')
107
+ const bytes = readPackageFile(root, join(root, path), 4 * 1024 * 1024)
108
+ if (snapshot !== bytes.toString('utf8'))
109
+ throw new Error(`Header differs from the original snapshot: ${path}`)
110
+ digests.push({ path, sha256: sha256(bytes) })
111
+ }
112
+ return {
113
+ status: 'plan' as const,
114
+ plan: {
115
+ header,
116
+ headers: digests,
117
+ headerMaps,
118
+ searchPaths,
119
+ userSearchPaths,
120
+ definitions,
121
+ } satisfies SwiftBridgingPlan,
122
+ }
123
+ }
124
+
125
+ // the swiftc arguments for a planned bridging header, with its header maps
126
+ // written into `work`. an application publishes no framework headers, so the
127
+ // product header overlay stays out, as in Xcode's command line.
128
+ export function bridgingFlags(plan: SwiftBridgingPlan, root: string, work: string) {
129
+ const absolute = (path: string) => join(root, path)
130
+ const { flags } = writeXcodeHeaderSearch(join(work, 'header-search'), [
131
+ {
132
+ headerMaps: plan.headerMaps.map((map) => ({
133
+ flag: map.flag,
134
+ entries: map.entries.map(([name, path]): [string, string] => [
135
+ name,
136
+ absolute(path),
137
+ ]),
138
+ })),
139
+ productHeaders: {},
140
+ userHeaderSearchPaths: plan.userSearchPaths.map(absolute),
141
+ },
142
+ ])
143
+ const search = flags[0]!.filter(
144
+ (arg, at, all) => arg !== '-ivfsoverlay' && all[at - 1] !== '-ivfsoverlay',
145
+ )
146
+ const clang: string[] = []
147
+ for (let at = 0; at < search.length; at += 2) clang.push(search[at]!, search[at + 1]!)
148
+ for (const path of plan.searchPaths) clang.push('-I', absolute(path))
149
+ return [
150
+ ...Array.from({ length: clang.length / 2 }, (_, at) => [
151
+ '-Xcc',
152
+ clang[at * 2]!,
153
+ '-Xcc',
154
+ clang[at * 2 + 1]!,
155
+ ]).flat(),
156
+ ...plan.definitions.flatMap((item) => ['-Xcc', `-D${item}`]),
157
+ '-import-objc-header',
158
+ absolute(plan.header),
159
+ ]
160
+ }
@@ -0,0 +1,251 @@
1
+ import { execFileSync } from 'node:child_process'
2
+ import { createHash } from 'node:crypto'
3
+ import { mkdirSync, realpathSync } from 'node:fs'
4
+ import { isAbsolute, join, relative, resolve, sep } from 'node:path'
5
+ import {
6
+ swiftPackageDescription,
7
+ swiftPackageManifest,
8
+ type SwiftManifestTarget,
9
+ type SwiftPackageManifest,
10
+ } from '../swift-package-manifest'
11
+ import { readPackageFile } from '../swift-source-file'
12
+ import { swiftPackageConditions, swiftPackageName } from './package'
13
+ import type { readXcodeAppTarget } from '../xcode-project'
14
+ import type { SwiftSourceLeg } from './types'
15
+
16
+ const sha256 = (bytes: string | Buffer) =>
17
+ createHash('sha256').update(bytes).digest('hex')
18
+
19
+ type App = Pick<
20
+ ReturnType<typeof readXcodeAppTarget>,
21
+ 'linkedProducts' | 'localPackageDirs' | 'configuration'
22
+ >
23
+
24
+ export type SwiftLocalModule = {
25
+ /** the package directory, relative to the app root. */
26
+ package: string
27
+ /** the -package-name swiftpm gives the package's modules. */
28
+ packageName: string
29
+ target: string
30
+ moduleName: string
31
+ /** original Swift sources, relative to the app root. */
32
+ files: string[]
33
+ languageMode: number
34
+ mainActorIsolation: boolean
35
+ /** compilation conditions active in the app's build configuration. */
36
+ defines: string[]
37
+ /** module names this module imports among the local package modules. */
38
+ dependsOn: string[]
39
+ }
40
+
41
+ export type SwiftLocalPackagesPlan = {
42
+ modules: (SwiftLocalModule & { sources: { path: string; sha256: string }[] })[]
43
+ }
44
+
45
+ // swiftpm evaluation and target membership stay with their existing owner;
46
+ // this walks the products the app links through local packages and returns
47
+ // each Swift target they need, dependencies first.
48
+ export function localPackageModules(app: App, root: string) {
49
+ const unknown = (reason: string) => ({ status: 'unknown' as const, reason })
50
+ if (!app.linkedProducts.length) return { status: 'none' as const }
51
+ const configuration =
52
+ app.configuration === 'Debug'
53
+ ? 'debug'
54
+ : app.configuration === 'Release'
55
+ ? 'release'
56
+ : null
57
+ if (!configuration)
58
+ return unknown(
59
+ `Package build settings for the ${app.configuration} configuration remain unknown.`,
60
+ )
61
+ const manifests = new Map<
62
+ string,
63
+ {
64
+ manifest: SwiftPackageManifest
65
+ description: ReturnType<typeof swiftPackageDescription>
66
+ }
67
+ >()
68
+ const load = (dir: string) => {
69
+ const real = realpathSync(dir)
70
+ const known = manifests.get(real)
71
+ if (known) return known
72
+ const manifest = swiftPackageManifest(real)
73
+ const loaded = { manifest, description: swiftPackageDescription(manifest) }
74
+ manifests.set(real, loaded)
75
+ return loaded
76
+ }
77
+ const modules = new Map<string, SwiftLocalModule>()
78
+ const visiting = new Set<string>()
79
+ const done = new Map<string, string>()
80
+ const addTarget = (dir: string, name: string): string | { reason: string } => {
81
+ const { manifest, description } = load(dir)
82
+ const target: SwiftManifestTarget | undefined = manifest.targets.get(name)
83
+ const described = description.targets.find((item) => item.name === name)
84
+ if (!target || !described)
85
+ return { reason: `Package ${manifest.name} declares no target ${name}.` }
86
+ const key = `${manifest.dir}\0${name}`
87
+ const known = done.get(key)
88
+ if (known) return known
89
+ if (visiting.has(key)) return { reason: `Package target ${name} depends on itself.` }
90
+ if (
91
+ target.type !== 'regular' ||
92
+ described.moduleType !== 'SwiftTarget' ||
93
+ target.declaresResources ||
94
+ target.nativeSettings.length ||
95
+ target.hasPluginUsages ||
96
+ target.unsupportedSwiftSettings.length
97
+ )
98
+ return {
99
+ reason: `Package target ${manifest.name}/${name} is not a plain Swift source target; resources, native sources, plugins, macros and unsupported Swift settings cannot establish source reach.`,
100
+ }
101
+ if (target.languageMode !== 5 && target.languageMode !== 6)
102
+ return { reason: `Unsupported Swift language mode: ${target.languageMode}` }
103
+ visiting.add(key)
104
+ const dependsOn: string[] = []
105
+ for (const dependency of target.dependencies) {
106
+ let dependencyDir = manifest.dir
107
+ let names = [dependency.name]
108
+ if (dependency.kind === 'product') {
109
+ const source = manifest.packages.get(dependency.package)
110
+ if (!source || !('dir' in source))
111
+ return {
112
+ reason: `Package ${manifest.name} depends on ${dependency.package}/${dependency.name}, which is not a local package; dependency modules remain unknown.`,
113
+ }
114
+ dependencyDir = resolve(manifest.dir, source.dir)
115
+ const products = load(dependencyDir).manifest.products.get(dependency.name)
116
+ if (!products)
117
+ return {
118
+ reason: `Package ${dependency.package} declares no library product ${dependency.name}.`,
119
+ }
120
+ names = products
121
+ }
122
+ for (const dependencyTarget of names) {
123
+ const added = addTarget(dependencyDir, dependencyTarget)
124
+ if (typeof added !== 'string') return added
125
+ dependsOn.push(added)
126
+ }
127
+ }
128
+ visiting.delete(key)
129
+ if (
130
+ !described.sources.length ||
131
+ described.sources.length > 2_000 ||
132
+ !described.sources.every((source) => source.endsWith('.swift'))
133
+ )
134
+ return {
135
+ reason: `Package target ${manifest.name}/${name} needs 1 to 2000 Swift sources.`,
136
+ }
137
+ const files = described.sources.map((source) => {
138
+ const path = relative(root, join(manifest.dir, described.path, source))
139
+ if (path === '..' || path.startsWith(`..${sep}`) || isAbsolute(path))
140
+ throw new Error(`Package source escapes the selected root: ${path}`)
141
+ return path
142
+ })
143
+ const moduleName = described.moduleName
144
+ const collision = modules.get(moduleName)
145
+ if (collision)
146
+ return {
147
+ reason: `Package modules named ${moduleName} collide across ${collision.package} and ${relative(root, manifest.dir)}.`,
148
+ }
149
+ modules.set(moduleName, {
150
+ package: relative(root, manifest.dir),
151
+ packageName: swiftPackageName(manifest.dir),
152
+ target: name,
153
+ moduleName,
154
+ files,
155
+ languageMode: target.languageMode,
156
+ mainActorIsolation: target.mainActorIsolation,
157
+ defines: swiftPackageConditions(target, configuration),
158
+ dependsOn: [...new Set(dependsOn)],
159
+ })
160
+ done.set(key, moduleName)
161
+ return moduleName
162
+ }
163
+ try {
164
+ for (const { product, source } of app.linkedProducts) {
165
+ if (source.kind === 'remote')
166
+ return unknown(
167
+ `Package product ${product} comes from ${source.url}; remote dependency modules remain unknown.`,
168
+ )
169
+ const candidates = source.kind === 'local' ? [source.dir] : app.localPackageDirs
170
+ const owner = candidates.find((dir) => load(dir).manifest.products.has(product))
171
+ if (!owner)
172
+ return unknown(
173
+ `Package product ${product} names no library of a local package; its module remains unknown.`,
174
+ )
175
+ for (const target of load(owner).manifest.products.get(product) ?? []) {
176
+ const added = addTarget(owner, target)
177
+ if (typeof added !== 'string') return unknown(added.reason)
178
+ }
179
+ }
180
+ } catch (error) {
181
+ return unknown(error instanceof Error ? error.message : String(error))
182
+ }
183
+ return { status: 'modules' as const, modules: [...modules.values()] }
184
+ }
185
+
186
+ // the snapshot holds every package source, and a module's bytes are hashed once.
187
+ export function planLocalPackages(app: App, root: string, files: Record<string, string>) {
188
+ const found = localPackageModules(app, root)
189
+ if (found.status !== 'modules') return found
190
+ let total = 0
191
+ const modules = found.modules.map((module) => ({
192
+ ...module,
193
+ sources: module.files.map((path) => {
194
+ const content = readPackageFile(root, join(root, path), 4 * 1024 * 1024)
195
+ total += content.length
196
+ if (total > 32 * 1024 * 1024) throw new Error('Package modules exceed 32 MiB')
197
+ if (files[path] !== content.toString('utf8'))
198
+ throw new Error(
199
+ `Package source is missing or differs from the original snapshot: ${path}`,
200
+ )
201
+ return { path, sha256: sha256(content) }
202
+ }),
203
+ }))
204
+ return { status: 'plan' as const, plan: { modules } satisfies SwiftLocalPackagesPlan }
205
+ }
206
+
207
+ // compile each module with the caller's compiler into a module directory, as
208
+ // swiftpm would, and return the flag that lets the app import them. a module
209
+ // that fails to compile fails every import of it, so the diagnostics throw.
210
+ export function buildLocalPackageModules(
211
+ plan: SwiftLocalPackagesPlan,
212
+ root: string,
213
+ work: string,
214
+ leg: SwiftSourceLeg,
215
+ ) {
216
+ const modules = join(work, 'package-modules')
217
+ mkdirSync(modules, { recursive: true })
218
+ for (const module of plan.modules) {
219
+ try {
220
+ execFileSync(
221
+ leg.swiftc,
222
+ [
223
+ ...leg.flags,
224
+ '-emit-module',
225
+ '-emit-module-path',
226
+ join(modules, `${module.moduleName}.swiftmodule`),
227
+ '-module-name',
228
+ module.moduleName,
229
+ '-package-name',
230
+ module.packageName,
231
+ '-parse-as-library',
232
+ '-swift-version',
233
+ String(module.languageMode),
234
+ ...module.defines.flatMap((define) => ['-D', define]),
235
+ ...(module.mainActorIsolation ? ['-default-isolation', 'MainActor'] : []),
236
+ '-I',
237
+ modules,
238
+ ...module.sources.map(({ path }) => join(root, path)),
239
+ ],
240
+ { cwd: root, encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] },
241
+ )
242
+ } catch (error) {
243
+ const stderr =
244
+ error instanceof Error && 'stderr' in error ? String(error.stderr) : ''
245
+ throw new Error(
246
+ `Package module ${module.moduleName} failed to compile: ${stderr.split('\n').slice(0, 12).join('\n')}`,
247
+ )
248
+ }
249
+ }
250
+ return ['-I', modules]
251
+ }
@@ -0,0 +1,78 @@
1
+ import { execFileSync } from 'node:child_process'
2
+ import { createHash } from 'node:crypto'
3
+ import { mkdirSync, readFileSync, readdirSync } from 'node:fs'
4
+ import { basename, join } from 'node:path'
5
+
6
+ const sha256 = (bytes: string | Buffer) =>
7
+ createHash('sha256').update(bytes).digest('hex')
8
+
9
+ export type SwiftStringPlan = { catalogs: { path: string; sha256: string }[] }
10
+
11
+ // Xcode runs `xcstringstool generate-symbols --language swift` once per catalog
12
+ // and compiles each GeneratedStringSymbols_<table>.swift into the module. the
13
+ // setting defaults to NO in CoreBuildSystem.xcspec, so an unset value adds nothing.
14
+ export function planStringSymbols(
15
+ resources: string[],
16
+ root: string,
17
+ settings: Record<string, string>,
18
+ ) {
19
+ const catalogs = [
20
+ ...new Set(resources.filter((file) => file.endsWith('.xcstrings'))),
21
+ ].sort()
22
+ const generate = settings.STRING_CATALOG_GENERATE_SYMBOLS
23
+ if (!catalogs.length || !generate || generate === 'NO')
24
+ return { status: 'none' as const }
25
+ const unknown = (reason: string) => ({ status: 'unknown' as const, reason })
26
+ if (generate !== 'YES')
27
+ return unknown('STRING_CATALOG_GENERATE_SYMBOLS must resolve to YES or NO.')
28
+ const tables = catalogs.map((path) => basename(path, '.xcstrings'))
29
+ if (new Set(tables).size !== tables.length)
30
+ return unknown(
31
+ 'String catalogs sharing a table name generate colliding symbol files; their effect remains unknown.',
32
+ )
33
+ return {
34
+ status: 'plan' as const,
35
+ plan: {
36
+ catalogs: catalogs.map((path) => ({
37
+ path,
38
+ sha256: sha256(readFileSync(join(root, path))),
39
+ })),
40
+ } satisfies SwiftStringPlan,
41
+ }
42
+ }
43
+
44
+ // run the same xcstringstool Xcode runs and return one swift file per catalog.
45
+ export function generateStringSymbols(plan: SwiftStringPlan, root: string, work: string) {
46
+ const tool = execFileSync('xcrun', ['-f', 'xcstringstool'], {
47
+ encoding: 'utf8',
48
+ }).trim()
49
+ const toolSha256 = sha256(readFileSync(tool))
50
+ return plan.catalogs.map(({ path, sha256: catalogSha256 }) => {
51
+ const output = join(work, basename(path, '.xcstrings'))
52
+ mkdirSync(output, { recursive: true })
53
+ const args = [
54
+ 'generate-symbols',
55
+ '--language',
56
+ 'swift',
57
+ '--output-directory',
58
+ output,
59
+ join(root, path),
60
+ ]
61
+ execFileSync(tool, args, { stdio: ['ignore', 'pipe', 'pipe'] })
62
+ const files = readdirSync(output)
63
+ const name = `GeneratedStringSymbols_${basename(path, '.xcstrings')}.swift`
64
+ if (files.length !== 1 || files[0] !== name)
65
+ throw new Error(`xcstringstool wrote ${files.join(', ') || 'nothing'} for ${path}`)
66
+ const swift = join(output, name)
67
+ return {
68
+ path: swift,
69
+ producer: {
70
+ tool: 'xcstringstool generate-symbols',
71
+ toolSha256,
72
+ arguments: args.map((arg) => arg.replace(root, '<root>').replace(work, '<work>')),
73
+ catalogs: [{ path, sha256: catalogSha256 }],
74
+ sha256: sha256(readFileSync(swift)),
75
+ },
76
+ }
77
+ })
78
+ }