peachsim 0.1.2793 → 0.1.2794

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 (132) hide show
  1. package/dist-lib/agent-daemon-client.cjs +1 -1
  2. package/dist-lib/agent-events.cjs +1 -1
  3. package/dist-lib/attached-projects.cjs +1 -1
  4. package/dist-lib/auth/shared-session.cjs +1 -1
  5. package/dist-lib/backend-origin.cjs +1 -1
  6. package/dist-lib/beta.cjs +1 -1
  7. package/dist-lib/beta.mjs +2 -2
  8. package/dist-lib/bridge-constants.cjs +1 -1
  9. package/dist-lib/bridge-contract-input.cjs +1 -1
  10. package/dist-lib/bridge-contract-input.mjs +5 -5
  11. package/dist-lib/bridge-contract.cjs +1 -1
  12. package/dist-lib/bridge-contract.mjs +3 -3
  13. package/dist-lib/bundle-channel.cjs +1157 -993
  14. package/dist-lib/capture-contract.cjs +1 -1
  15. package/dist-lib/capture-contract.mjs +3 -3
  16. package/dist-lib/cloud-contract.cjs +1 -1
  17. package/dist-lib/cloud-contract.mjs +3 -3
  18. package/dist-lib/cloud-test-args.cjs +1 -1
  19. package/dist-lib/cloud-test-args.mjs +2 -2
  20. package/dist-lib/cloud.cjs +1 -1
  21. package/dist-lib/cloud.mjs +7 -7
  22. package/dist-lib/config.cjs +1 -1
  23. package/dist-lib/config.mjs +5 -5
  24. package/dist-lib/detox/index.cjs +1 -1
  25. package/dist-lib/dev-bundle-resolution.cjs +1 -1
  26. package/dist-lib/esm-chunks/{acorn-Q5VJTSKK.mjs → acorn-A7OMJDVK.mjs} +3 -3
  27. package/dist-lib/esm-chunks/{chunk-4P3IOCZK.mjs → chunk-2TCGEMEV.mjs} +5 -5
  28. package/dist-lib/esm-chunks/{chunk-TADAJDSF.mjs → chunk-35HEHEYA.mjs} +1 -1
  29. package/dist-lib/esm-chunks/{chunk-GVQYPMGV.mjs → chunk-5RQ3U7WK.mjs} +1 -1
  30. package/dist-lib/esm-chunks/{chunk-SCUA4P4G.mjs → chunk-7QNWHCMJ.mjs} +1116 -1056
  31. package/dist-lib/esm-chunks/{chunk-ZU4TTBLM.mjs → chunk-ANIC22U3.mjs} +1 -1
  32. package/dist-lib/esm-chunks/{chunk-6HQZNAEU.mjs → chunk-AW4Z3K2U.mjs} +1 -1
  33. package/dist-lib/esm-chunks/{chunk-JMR6F3DC.mjs → chunk-B3E5ZI2D.mjs} +1 -1
  34. package/dist-lib/esm-chunks/{chunk-PTIDPELK.mjs → chunk-CIFEHSEA.mjs} +2 -2
  35. package/dist-lib/esm-chunks/{chunk-A2KA5HK7.mjs → chunk-CIR4VZ22.mjs} +1 -1
  36. package/dist-lib/esm-chunks/{chunk-XCBOY63C.mjs → chunk-DLEQ5NZ5.mjs} +4 -4
  37. package/dist-lib/esm-chunks/{chunk-BEO5Q2GJ.mjs → chunk-E6KA576K.mjs} +1 -1
  38. package/dist-lib/esm-chunks/{chunk-TS7JWC6Z.mjs → chunk-GDITZ3K2.mjs} +1 -1
  39. package/dist-lib/esm-chunks/{chunk-2V3WPUVP.mjs → chunk-GHGDWJY3.mjs} +6 -6
  40. package/dist-lib/esm-chunks/{chunk-SQ3UKGNC.mjs → chunk-K7RLWF5X.mjs} +1 -1
  41. package/dist-lib/esm-chunks/{chunk-6LTBRJF4.mjs → chunk-KVFRYFZI.mjs} +1 -1
  42. package/dist-lib/esm-chunks/{chunk-YEBPOLJT.mjs → chunk-NKJ67PFZ.mjs} +1 -1
  43. package/dist-lib/esm-chunks/{chunk-NMSKAQXB.mjs → chunk-O6HHWO4Y.mjs} +1 -1
  44. package/dist-lib/esm-chunks/{chunk-U23E4H6F.mjs → chunk-OS6YJU3W.mjs} +1 -1
  45. package/dist-lib/esm-chunks/{chunk-ELHDFPTV.mjs → chunk-PRYC6EMT.mjs} +1 -1
  46. package/dist-lib/esm-chunks/{chunk-COIKWBXT.mjs → chunk-R6ES6QCH.mjs} +1 -1
  47. package/dist-lib/esm-chunks/{chunk-5LYBGU62.mjs → chunk-TJULYSLY.mjs} +1 -1
  48. package/dist-lib/esm-chunks/{chunk-SSZA5C37.mjs → chunk-V6BE34Q3.mjs} +1 -1
  49. package/dist-lib/esm-chunks/{chunk-RVJCN7O6.mjs → chunk-Y6YMRYNX.mjs} +64 -21
  50. package/dist-lib/esm-chunks/{chunk-6YRIQX2Q.mjs → chunk-ZTDPCBGG.mjs} +3 -3
  51. package/dist-lib/esm-chunks/{metro-layout-parser-26WDQMLR.mjs → metro-layout-parser-WG2ITRQD.mjs} +3 -3
  52. package/dist-lib/esm-chunks/{swift-package-prebuilt-DOKKJSSS.mjs → swift-package-prebuilt-DN7G5XKR.mjs} +16 -13
  53. package/dist-lib/esm-chunks/{swift-sdk-app-module-I4OZ7CGZ.mjs → swift-sdk-app-module-3DB4F4Y2.mjs} +16 -16
  54. package/dist-lib/esm-chunks/{swift-sdk-image-IPXHOUXE.mjs → swift-sdk-image-JTYM3OQY.mjs} +16 -16
  55. package/dist-lib/esm-chunks/{swift-sdk-image-producer-6P6QZQGS.mjs → swift-sdk-image-producer-QQUODPXF.mjs} +5 -5
  56. package/dist-lib/expo-swift-bundle.cjs +1099 -935
  57. package/dist-lib/expo-swift-metadata.cjs +1 -1
  58. package/dist-lib/expo-swift-metadata.mjs +7 -7
  59. package/dist-lib/home-paths.cjs +1 -1
  60. package/dist-lib/host/bridge-host.cjs +3742 -3452
  61. package/dist-lib/host/fetch-proxy-handler.cjs +121 -117
  62. package/dist-lib/host/fetch-proxy-overrides.cjs +1 -1
  63. package/dist-lib/host/fetch-proxy-overrides.mjs +2 -2
  64. package/dist-lib/host/replacement-module-handler.cjs +1 -1
  65. package/dist-lib/host/websocket-proxy.cjs +1 -1
  66. package/dist-lib/index.cjs +1 -1
  67. package/dist-lib/kotlin-host.cjs +1 -1
  68. package/dist-lib/menu.cjs +1 -1
  69. package/dist-lib/menu.mjs +3 -3
  70. package/dist-lib/metro-fingerprint-registry.cjs +1 -1
  71. package/dist-lib/metro-fingerprint-registry.mjs +3 -3
  72. package/dist-lib/metro-production-bundle.cjs +1 -1
  73. package/dist-lib/metro-production-bundle.mjs +4 -4
  74. package/dist-lib/native-app-identity-project.cjs +3 -1
  75. package/dist-lib/native-app-identity-project.mjs +15 -15
  76. package/dist-lib/native-app-identity.cjs +1 -1
  77. package/dist-lib/native-app-identity.mjs +6 -6
  78. package/dist-lib/native-firebase-metadata.cjs +1 -1
  79. package/dist-lib/native-firebase-metadata.mjs +3 -3
  80. package/dist-lib/pdfium-raster.cjs +1 -1
  81. package/dist-lib/pdfium-raster.mjs +2 -2
  82. package/dist-lib/plist.cjs +1 -1
  83. package/dist-lib/plist.mjs +3 -3
  84. package/dist-lib/profiles.cjs +1 -1
  85. package/dist-lib/public-brand.cjs +1 -1
  86. package/dist-lib/public-origins-lib-esm.json +85 -85
  87. package/dist-lib/public-origins-lib.json +76 -76
  88. package/dist-lib/react-native-host-modules.cjs +1 -1
  89. package/dist-lib/react-native-host-modules.mjs +2 -2
  90. package/dist-lib/reap-browser.cjs +1 -1
  91. package/dist-lib/scripts/dev-server-scanner.cjs +1 -1
  92. package/dist-lib/sdk.cjs +1 -1
  93. package/dist-lib/sdk.mjs +8 -8
  94. package/dist-lib/skills.cjs +2027 -1737
  95. package/dist-lib/swift-compile.cjs +1056 -963
  96. package/dist-lib/swift-compile.mjs +12 -12
  97. package/dist-lib/swift-package.cjs +1 -1
  98. package/dist-lib/swift-package.mjs +3 -3
  99. package/dist-lib/swift-submit.cjs +1 -1
  100. package/dist-lib/swift-submit.mjs +6 -6
  101. package/dist-lib/swift-svg-raster.cjs +1 -1
  102. package/dist-lib/swift-svg-raster.mjs +2 -2
  103. package/dist-lib/swift-toolchain.cjs +1 -1
  104. package/dist-lib/swift.cjs +1 -1
  105. package/dist-lib/vendor/@peculiar/x509.cjs +1 -1
  106. package/dist-lib/vendor/@ruby/prism/src/nodes.js.cjs +1 -1
  107. package/dist-lib/vendor/@ruby/prism/src/parsePrism.js.cjs +1 -1
  108. package/dist-lib/vendor/acorn.cjs +1 -1
  109. package/dist-lib/vendor/magic-string.cjs +1 -1
  110. package/dist-lib/vendor/stream-json.cjs +1 -1
  111. package/dist-lib/vendor/sucrase/dist/index.js.cjs +1 -1
  112. package/dist-lib/vendor/sucrase/dist/parser/index.js.cjs +1 -1
  113. package/dist-lib/vendor/sucrase/dist/parser/tokenizer/index.js.cjs +1 -1
  114. package/dist-lib/vendor/sucrase/dist/parser/tokenizer/types.js.cjs +1 -1
  115. package/dist-lib/vendor/sucrase.cjs +1 -1
  116. package/dist-lib/vendor/terser.cjs +1 -1
  117. package/dist-lib/vendor/valibot.cjs +1 -1
  118. package/dist-lib/vendor/ws.cjs +1 -1
  119. package/dist-lib/vendor/zod.cjs +1 -1
  120. package/dist-lib/worklet-executable.cjs +1 -1
  121. package/dist-lib/worklet-executable.mjs +3 -3
  122. package/dist-types/packages/peach-engine/src/engine/scene-native-binding.d.ts +2 -2
  123. package/dist-types/packages/peach-engine/src/render-worker/native-hot-ops.d.ts +1 -1
  124. package/dist-types/packages/peach-engine/src/render-worker/scene-packet-feed.d.ts +2 -0
  125. package/package.json +1 -1
  126. package/src/one-native-controls-package.ts +56 -54
  127. package/src/swift-compile.ts +1029 -963
  128. package/src/swift-compiler-digest.ts +79 -4
  129. package/src/swift-host.ts +246 -91
  130. package/src/swift-package-prebuilt.ts +6 -3
  131. package/src/swift-sdk-surface.ts +75 -20
  132. package/src/swift-startup-split.ts +134 -12
@@ -140,6 +140,7 @@ import {
140
140
  cActiveCode,
141
141
  clangInterfaceHeader,
142
142
  clearLinkedModuleDigests,
143
+ clearSwiftModuleDigestScope,
143
144
  clearSwiftSdkPathsCache,
144
145
  CORE_FOUNDATION_OVERLAY_GLOBALS,
145
146
  emptyMacroEnvironment,
@@ -172,6 +173,7 @@ import {
172
173
  swiftSdkPaths,
173
174
  wasmMacroEnvironment,
174
175
  withFrameworkCompanionImports,
176
+ withSwiftModuleDigestScope,
175
177
  withoutImportedSdkEnumForwards,
176
178
  withoutSwiftDeclarations,
177
179
  type SwiftCMacroEnvironment,
@@ -502,7 +504,9 @@ export interface SwiftCompileOptions {
502
504
  buildRoot: string
503
505
  moduleRoot: string
504
506
  release: string
505
- toolchainBin: string
507
+ toolchainBin?: string
508
+ resolveToolchain?: () => string
509
+ beforeCompile?: (toolchainBin: string) => void | Promise<void>
506
510
  /**
507
511
  * run the compilers that read project sources (the app's swift build, which
508
512
  * evaluates its manifests and macros) as this user, from this base
@@ -2797,6 +2801,12 @@ export function swiftSourceClosure(
2797
2801
 
2798
2802
  /** application entries, excluding comments, strings and inactive branches. */
2799
2803
  export function swiftApplicationEntry(file: string, source: string): boolean {
2804
+ if (
2805
+ !source.includes('@main') &&
2806
+ !source.includes('@UIApplicationMain') &&
2807
+ !(path.basename(file) === 'main.swift' && source.includes('UIApplicationMain'))
2808
+ )
2809
+ return false
2800
2810
  const code = [...swiftConditionalLines(swiftCodeMask(source))]
2801
2811
  .map(({ line, active }) => (active === false ? ' '.repeat(line.length) : line))
2802
2812
  .join('\n')
@@ -7481,1002 +7491,1058 @@ async function compileSwiftProjectOnce(
7481
7491
  sources: SwiftCompileInput,
7482
7492
  options: SwiftProjectCompileOptions,
7483
7493
  ): Promise<SwiftCompileArtifact | void> {
7484
- options.signal?.throwIfAborted()
7485
- assertSwiftBuildCores()
7486
- mkdirSync(options.buildRoot, { recursive: true })
7487
- const root = realpathSync(options.buildRoot)
7488
- refreshSwiftCacheHold(root)
7489
- const moduleRoot = path.resolve(options.moduleRoot)
7490
- const distribution = swiftDistributionAt(moduleRoot)
7491
- const mirrorDistribution = options.linkOnly || options.project ? null : distribution
7492
- if (distribution) refreshSwiftCacheHold(moduleRoot)
7493
- const input =
7494
- distribution && !options.intermediates
7495
- ? (await import('./swift-package-prebuilt')).useSwiftPackagePrebuilts(
7496
- sources,
7494
+ return withSwiftModuleDigestScope(async () => {
7495
+ options.signal?.throwIfAborted()
7496
+ mkdirSync(options.buildRoot, { recursive: true })
7497
+ const root = realpathSync(options.buildRoot)
7498
+ refreshSwiftCacheHold(root)
7499
+ const moduleRoot = path.resolve(options.moduleRoot)
7500
+ const distribution = swiftDistributionAt(moduleRoot)
7501
+ const mirrorDistribution = options.linkOnly || options.project ? null : distribution
7502
+ if (distribution) refreshSwiftCacheHold(moduleRoot)
7503
+ let resolvedToolchainBin = options.toolchainBin
7504
+ const resolveToolchainBin = (): string => {
7505
+ if (resolvedToolchainBin) return resolvedToolchainBin
7506
+ if (!options.resolveToolchain)
7507
+ throw new Error('swift-compile: missing toolchainBin')
7508
+ resolvedToolchainBin = options.resolveToolchain()
7509
+ return resolvedToolchainBin
7510
+ }
7511
+ const input =
7512
+ distribution && !options.intermediates
7513
+ ? (await import('./swift-package-prebuilt')).useSwiftPackagePrebuilts(
7514
+ sources,
7515
+ moduleRoot,
7516
+ resolveToolchainBin,
7517
+ )
7518
+ : sources
7519
+ const guestGraph = distribution ? input.sourceLinkGraph : undefined
7520
+ if (options.linkOnly && guestGraph)
7521
+ throw new Error('swift-compile: link-only builds do not support guest image graphs')
7522
+ const layout: SwiftProjectLayout = {
7523
+ root,
7524
+ sources: path.join(root, 'Sources', 'App'),
7525
+ multi: compileTargets(input).length > 0,
7526
+ }
7527
+ // the shared sdk image builds once per distribution, outside this project's lock
7528
+ const sdkImage = options.linkOnly
7529
+ ? undefined
7530
+ : await (
7531
+ await import('./swift-sdk-image')
7532
+ ).buildSwiftSdkImage(
7497
7533
  moduleRoot,
7498
- options.toolchainBin,
7534
+ !!guestGraph,
7535
+ distribution ? [] : linkedFrameworkTargets(moduleRoot, input).imports,
7536
+ { signal: options.signal },
7499
7537
  )
7500
- : sources
7501
- const guestGraph = distribution ? input.sourceLinkGraph : undefined
7502
- if (options.linkOnly && guestGraph)
7503
- throw new Error('swift-compile: link-only builds do not support guest image graphs')
7504
- const layout: SwiftProjectLayout = {
7505
- root,
7506
- sources: path.join(root, 'Sources', 'App'),
7507
- multi: compileTargets(input).length > 0,
7508
- }
7509
- // the shared sdk image builds once per distribution, outside this project's lock
7510
- const sdkImage = options.linkOnly
7511
- ? undefined
7512
- : await (
7513
- await import('./swift-sdk-image')
7514
- ).buildSwiftSdkImage(
7515
- moduleRoot,
7516
- !!guestGraph,
7517
- distribution ? [] : linkedFrameworkTargets(moduleRoot, input).imports,
7518
- { signal: options.signal },
7519
- )
7520
- const inputHash = swiftCompileInputHash(input, options.release)
7521
- const moduleDigest = swiftModuleDigest(moduleRoot)
7522
- const sourceHash = inputHash.copy().update(moduleDigest).digest('hex')
7523
- const hash = sdkImage ? swiftSdkArtifactHash(sourceHash, sdkImage.key) : sourceHash
7524
- const frameworkKey = swiftProjectBuildKey(moduleRoot, options.release)
7525
- const sharedRoot = path.join(swiftCacheDir(), 'swift-projects', hash)
7526
- const report = (message: string) => {
7527
- console.error(`[swift-project ${hash.slice(0, 16)}] ${message}`)
7528
- options.onStage?.(message)
7529
- }
7530
- return serialize(
7531
- root,
7532
- async () => {
7533
- if (!options.intermediates) {
7534
- report('checking verified artifacts')
7535
- const retained = retainedArtifacts.get(root)?.find((old) => old.hash === hash)
7536
- if (retained) {
7537
- report('reusing memory artifact')
7538
- return retain(root, retained)
7539
- }
7540
- const cached = readCompiledArtifact(path.join(sharedRoot, 'artifact'), hash)
7541
- // a build root the project user writes in cannot vouch for an artifact
7542
- const previous =
7543
- cached ??
7544
- (options.project
7545
- ? null
7546
- : readCompiledArtifact(path.join(root, 'artifact'), hash))
7547
- if (previous) {
7548
- if (cached) renewSharedArtifact(sharedRoot)
7549
- else saveSharedArtifact(sharedRoot, previous)
7550
- report('reusing verified disk artifact')
7551
- return retain(root, previous)
7552
- }
7553
- }
7554
- // the root's sources, manifest and executable are shared by every process
7555
- // using it, so one process writes, builds and reads them at a time.
7556
- const baseRoot = root
7557
- const canPoolBuildRoot =
7558
- !options.intermediates &&
7559
- !options.project &&
7560
- !options.linkOnly &&
7561
- path.basename(path.dirname(baseRoot)) === 'swift-builds'
7562
- const compatShapeParts = canPoolBuildRoot
7563
- ? [
7564
- distribution ? options.release : frameworkKey,
7565
- compileTargets(input)
7566
- .map((target) => target.name)
7567
- .sort(),
7568
- input.oneModule === true,
7569
- input.optimize === true,
7570
- input.unoptimized === true,
7571
- ]
7572
- : null
7573
- const compatShape = compatShapeParts
7574
- ? createHash('sha256')
7575
- .update(JSON.stringify(compatShapeParts))
7576
- .digest('hex')
7577
- .slice(0, 16)
7578
- : ''
7579
- const exactShape = compatShapeParts
7580
- ? createHash('sha256')
7581
- .update(
7582
- JSON.stringify([...compatShapeParts, Object.keys(input.files).sort()]),
7583
- )
7584
- .digest('hex')
7585
- .slice(0, 16)
7586
- : ''
7587
- const buildShape = compatShapeParts ? `${exactShape}\n${compatShape}` : ''
7588
- return withSwiftCompileBudget(options.timeoutMs, options.signal, async (budget) => {
7589
- const stage = (message: string) => {
7590
- budget.progress()
7591
- report(message)
7592
- }
7593
- const runLocked = (
7594
- work: (
7595
- slotRoot: string,
7596
- lease: SwiftRootLease,
7597
- waitedMs: number,
7598
- ) => Promise<SwiftCompileArtifact | void>,
7599
- ) => {
7600
- const runInBuildRoot = () => {
7601
- if (canPoolBuildRoot)
7602
- return withSwiftBuildRootSlot(
7603
- baseRoot,
7604
- exactShape,
7605
- compatShape,
7606
- budget.signal,
7607
- work,
7608
- )
7609
- const waitStart = Date.now()
7610
- return withSwiftRootLock(
7611
- baseRoot,
7612
- (lease) => work(baseRoot, lease, Date.now() - waitStart),
7613
- budget.signal,
7614
- )
7538
+ const inputHash = swiftCompileInputHash(input, options.release)
7539
+ const moduleDigest = swiftModuleDigest(moduleRoot)
7540
+ const sourceHash = inputHash.copy().update(moduleDigest).digest('hex')
7541
+ const hash = sdkImage ? swiftSdkArtifactHash(sourceHash, sdkImage.key) : sourceHash
7542
+ const sharedRoot = path.join(swiftCacheDir(), 'swift-projects', hash)
7543
+ const report = (message: string) => {
7544
+ console.error(`[swift-project ${hash.slice(0, 16)}] ${message}`)
7545
+ options.onStage?.(message)
7546
+ }
7547
+ return serialize(
7548
+ root,
7549
+ async () => {
7550
+ if (!options.intermediates) {
7551
+ report('checking verified artifacts')
7552
+ const retained = retainedArtifacts.get(root)?.find((old) => old.hash === hash)
7553
+ if (retained) {
7554
+ report('reusing memory artifact')
7555
+ return retain(root, retained)
7615
7556
  }
7616
- if (options.intermediates || baseRoot === sharedRoot) return runInBuildRoot()
7617
- return withSwiftRootLock(
7618
- sharedRoot,
7619
- async () => {
7620
- const built = readCompiledArtifact(path.join(sharedRoot, 'artifact'), hash)
7621
- if (built) {
7622
- renewSharedArtifact(sharedRoot)
7623
- stage('reusing verified disk artifact')
7624
- return retain(baseRoot, built)
7625
- }
7626
- return runInBuildRoot()
7627
- },
7628
- budget.signal,
7629
- )
7630
- }
7631
- return runLocked(async (slotRoot, lease, waitedMs) => {
7632
- const root = slotRoot
7633
- const layout: SwiftProjectLayout = {
7634
- root,
7635
- sources: path.join(root, 'Sources', 'App'),
7636
- multi: compileTargets(input).length > 0,
7557
+ const cached = readCompiledArtifact(path.join(sharedRoot, 'artifact'), hash)
7558
+ // a build root the project user writes in cannot vouch for an artifact
7559
+ const previous =
7560
+ cached ??
7561
+ (options.project
7562
+ ? null
7563
+ : readCompiledArtifact(path.join(root, 'artifact'), hash))
7564
+ if (previous) {
7565
+ if (cached) renewSharedArtifact(sharedRoot)
7566
+ else saveSharedArtifact(sharedRoot, previous)
7567
+ report('reusing verified disk artifact')
7568
+ return retain(root, previous)
7637
7569
  }
7638
- // a process that held the root while this one waited may have built
7639
- // this exact address.
7640
- if (!options.intermediates) {
7641
- const built = readCompiledArtifact(path.join(sharedRoot, 'artifact'), hash)
7642
- if (built) {
7643
- stage('reusing verified disk artifact')
7644
- return retain(baseRoot, built)
7570
+ }
7571
+ assertSwiftBuildCores()
7572
+ const toolchainBin = resolveToolchainBin()
7573
+ await options.beforeCompile?.(toolchainBin)
7574
+ clearSwiftModuleDigestScope(moduleRoot)
7575
+ const frameworkKey = swiftProjectBuildKey(moduleRoot, options.release)
7576
+ // the root's sources, manifest and executable are shared by every process
7577
+ // using it, so one process writes, builds and reads them at a time.
7578
+ const baseRoot = root
7579
+ const canPoolBuildRoot =
7580
+ !options.intermediates &&
7581
+ !options.project &&
7582
+ !options.linkOnly &&
7583
+ path.basename(path.dirname(baseRoot)) === 'swift-builds'
7584
+ const compatShapeParts = canPoolBuildRoot
7585
+ ? [
7586
+ distribution ? options.release : frameworkKey,
7587
+ compileTargets(input)
7588
+ .map((target) => target.name)
7589
+ .sort(),
7590
+ input.oneModule === true,
7591
+ input.optimize === true,
7592
+ input.unoptimized === true,
7593
+ ]
7594
+ : null
7595
+ const compatShape = compatShapeParts
7596
+ ? createHash('sha256')
7597
+ .update(JSON.stringify(compatShapeParts))
7598
+ .digest('hex')
7599
+ .slice(0, 16)
7600
+ : ''
7601
+ const exactShape = compatShapeParts
7602
+ ? createHash('sha256')
7603
+ .update(
7604
+ JSON.stringify([...compatShapeParts, Object.keys(input.files).sort()]),
7605
+ )
7606
+ .digest('hex')
7607
+ .slice(0, 16)
7608
+ : ''
7609
+ const buildShape = compatShapeParts ? `${exactShape}\n${compatShape}` : ''
7610
+ return withSwiftCompileBudget(
7611
+ options.timeoutMs,
7612
+ options.signal,
7613
+ async (budget) => {
7614
+ const stage = (message: string) => {
7615
+ budget.progress()
7616
+ report(message)
7645
7617
  }
7646
- }
7647
- if (waitedMs >= 1_000)
7648
- report(`acquired build root ${path.basename(root)} after ${waitedMs}ms`)
7649
- if (canPoolBuildRoot) {
7650
- refreshSwiftCacheHold(root)
7651
- writeFileSync(path.join(root, SWIFT_BUILD_ROOT_SHAPE), buildShape)
7652
- }
7653
- const swift = path.join(options.toolchainBin, 'swift')
7654
- if (!existsSync(swift)) {
7655
- throw new Error(
7656
- `swift-compile: no swift.org toolchain at ${options.toolchainBin}; install ${options.release} and its matching wasm sdk`,
7657
- )
7658
- }
7659
- // a distribution's immutable modules and host plugins need no source build.
7660
- const unoptimized = input.unoptimized === true
7661
- const baseBuildEnv = options.project?.env
7662
- ? {
7663
- ...options.project.env,
7664
- // shipped host plugins resolve against the selected compiler's runtime.
7665
- ...(process.platform === 'linux'
7666
- ? {
7667
- LD_LIBRARY_PATH: [
7668
- path.resolve(options.toolchainBin, '../lib/swift/linux'),
7669
- path.resolve(options.toolchainBin, '../lib/swift/host'),
7670
- process.env.LD_LIBRARY_PATH,
7671
- ]
7672
- .filter(Boolean)
7673
- .join(':'),
7674
- }
7675
- : {}),
7676
- PEACH_DEFER_WASM_LINK: '1',
7618
+ const runLocked = (
7619
+ work: (
7620
+ slotRoot: string,
7621
+ lease: SwiftRootLease,
7622
+ waitedMs: number,
7623
+ ) => Promise<SwiftCompileArtifact | void>,
7624
+ ) => {
7625
+ const runInBuildRoot = () => {
7626
+ if (canPoolBuildRoot)
7627
+ return withSwiftBuildRootSlot(
7628
+ baseRoot,
7629
+ exactShape,
7630
+ compatShape,
7631
+ budget.signal,
7632
+ work,
7633
+ )
7634
+ const waitStart = Date.now()
7635
+ return withSwiftRootLock(
7636
+ baseRoot,
7637
+ (lease) => work(baseRoot, lease, Date.now() - waitStart),
7638
+ budget.signal,
7639
+ )
7677
7640
  }
7678
- : swiftCompilerBaseEnv(options.toolchainBin, process.env)
7679
- // hold the exclusive framework slot lock only while staging and
7680
- // building framework products; take a shared read hold before
7681
- // releasing it so other builds on the same framework revision
7682
- // compile and link their apps concurrently.
7683
- const prepareFrameworks = async (
7684
- slot: string | null,
7685
- frameworkLease?: SwiftRootLease,
7686
- allowWrite = true,
7687
- ) => {
7688
- if (allowWrite) budget.startCompile()
7689
- // project users own their build roots; resolve their sdk outside them.
7690
- const frameworkRoot = mirrorDistribution
7691
- ? syncSwiftDistributionMirror(root, moduleRoot, mirrorDistribution)
7692
- : distribution
7693
- ? moduleRoot
7694
- : stageFrameworkSource(moduleRoot, slot, frameworkKey, options.release)
7695
- if (!swiftModuleDigest(frameworkRoot).equals(moduleDigest))
7696
- throw new Error('Swift staged project source differs from the caller')
7697
- if (!allowWrite && swiftMacroPlugins(frameworkRoot).stale) return
7698
- if (allowWrite) stage('preparing compiler plugins')
7699
- const macroPlugins = await ensureMacroPlugins(
7700
- frameworkRoot,
7701
- options.toolchainBin,
7702
- options.release,
7703
- budget.signal,
7704
- frameworkLease,
7705
- )
7706
- const compileFrameworkRoot = distribution
7707
- ? swiftDistributionCompileView(frameworkRoot, distribution)
7708
- : frameworkRoot
7709
- // memoized per toolchain, so only a process's first build waits on it,
7710
- // and that one reads and gzips it while swift builds
7711
- const sdk = swiftModuleSdk(frameworkRoot).wasmSdkId
7712
- const compileSdk: SwiftMirrorSdk = mirrorDistribution
7713
- ? syncSwiftSdkMirror(root, frameworkRoot, options.toolchainBin, sdk)
7714
- : {
7715
- id: sdk,
7716
- options: swiftCompileSdkOptions(frameworkRoot, options.toolchainBin),
7717
- toolsetChanged: false,
7718
- }
7719
- if (mirrorDistribution && compileSdk.toolsetChanged)
7720
- clearSwiftSdkPathsCache(path.join(root, SWIFT_SDK_MIRROR))
7721
- const icu = options.linkOnly ? null : swiftIcuAsset(options.toolchainBin, sdk)
7722
- let prebuilt: SwiftFrameworkProducts | undefined
7723
- if (!distribution) {
7724
- if (allowWrite) stage('compiling framework products')
7725
- prebuilt = await buildFrameworkProducts(
7726
- slot!,
7727
- {
7728
- moduleRoot: frameworkRoot,
7729
- frameworkKey,
7730
- input,
7731
- swift,
7732
- sdk,
7733
- toolchainBin: options.toolchainBin,
7734
- plugins: macroPlugins,
7735
- buildOptions: {
7736
- env: baseBuildEnv,
7737
- maxBuffer: 64 * 1024 * 1024,
7738
- signal: budget.signal,
7739
- onOutput: budget.progress,
7740
- lease,
7741
- frameworkLease,
7742
- },
7641
+ if (options.intermediates || baseRoot === sharedRoot)
7642
+ return runInBuildRoot()
7643
+ return withSwiftRootLock(
7644
+ sharedRoot,
7645
+ async () => {
7646
+ const built = readCompiledArtifact(
7647
+ path.join(sharedRoot, 'artifact'),
7648
+ hash,
7649
+ )
7650
+ if (built) {
7651
+ renewSharedArtifact(sharedRoot)
7652
+ stage('reusing verified disk artifact')
7653
+ return retain(baseRoot, built)
7654
+ }
7655
+ return runInBuildRoot()
7743
7656
  },
7744
- allowWrite,
7745
- )
7746
- if (!prebuilt) return
7747
- if (!allowWrite) {
7748
- budget.startCompile()
7749
- stage('reusing verified framework products')
7750
- }
7751
- }
7752
- const readHold: SwiftRootReadHold | undefined = slot
7753
- ? acquireSwiftRootReadHold(slot)
7754
- : undefined
7755
- return {
7756
- frameworkRoot,
7757
- compileFrameworkRoot,
7758
- macroPlugins,
7759
- sdk,
7760
- compileSdk,
7761
- icu,
7762
- prebuilt,
7763
- readHold,
7764
- }
7765
- }
7766
- const frameworks = distribution
7767
- ? await prepareFrameworks(null)
7768
- : await withSwiftFrameworkSlot(
7769
- frameworkKey,
7770
- options.release,
7771
- moduleRoot,
7772
7657
  budget.signal,
7773
- prepareFrameworks,
7774
- unoptimized,
7775
- options.linkOnly === true,
7776
- )
7777
- if (!frameworks)
7778
- throw new Error('Swift distribution did not provide its frameworks')
7779
- const {
7780
- frameworkRoot,
7781
- compileFrameworkRoot,
7782
- macroPlugins,
7783
- compileSdk,
7784
- icu,
7785
- prebuilt,
7786
- } = frameworks
7787
- let readHold = frameworks.readHold
7788
- const buildOptions = {
7789
- env: baseBuildEnv,
7790
- maxBuffer: 64 * 1024 * 1024,
7791
- signal: budget.signal,
7792
- onOutput: budget.progress,
7793
- lease,
7794
- }
7795
- try {
7796
- if (options.project) removeProjectLinks(root)
7797
- const packageHostMacros =
7798
- process.platform === 'linux' ? input.packageHostMacros : undefined
7799
- if (
7800
- retireStaleSwiftLink(
7801
- root,
7802
- swiftLinkStamp({
7803
- frameworkKey: mirrorDistribution
7804
- ? `${options.release}\0mirror`
7805
- : `${options.release}\0${Boolean(distribution)}\0${swiftModuleSdk(frameworkRoot).wasmSdkId}`,
7806
- packageHostMacros,
7807
- }),
7808
- swiftLinkStamp({
7809
- // mirrored distributions and their WASI SDK mirror invalidate
7810
- // dependents per changed file instead of wiping every Clang object.
7811
- frameworkKey: mirrorDistribution
7812
- ? `${options.release}\0mirror`
7813
- : distribution
7814
- ? `${options.release}\0${distribution.wasmSdkChecksum}`
7815
- : frameworkKey,
7816
- prebuilt,
7817
- packageHostMacros,
7818
- }),
7819
- Boolean(options.linkOnly),
7820
7658
  )
7821
- )
7822
- stage('framework revision changed; rebuilding the app link')
7823
- const nativeToolset = needsNativeToolset(input, prebuilt)
7824
- const preparation = writeSwiftProject(
7825
- layout,
7826
- input,
7827
- frameworkRoot,
7828
- prebuilt,
7829
- !options.project,
7830
- options.project
7831
- ? false
7832
- : (options.objcPrebuiltStage ??
7833
- (options.intermediates ? false : undefined)),
7834
- compileSdk,
7835
- )
7836
- // the framework objects link as inputs, so the product name its
7837
- // modules autolink has no archive to load
7838
- const productFile = path.join(frameworkRoot, SWIFT_FRAMEWORK_PRODUCT_FILE)
7839
- writeSwiftAutolinkLinker(
7840
- root,
7841
- options.toolchainBin,
7842
- existsSync(productFile)
7843
- ? [
7844
- v.parse(
7845
- swiftFrameworkProductSchema,
7846
- JSON.parse(readFileSync(productFile, 'utf8')),
7847
- ).product.name,
7848
- ]
7849
- : [],
7850
- )
7851
- // the native build system takes its C compiler from CC, never a toolset
7852
- const compiler: Record<string, string> = preparation.targetToolset
7853
- ? { CC: path.join(root, CLANG_TARGET_MODULE_WRAPPER) }
7854
- : {}
7855
- if (packageHostMacros?.length) {
7856
- // swiftpm build-tool flags skip macro targets; forward the import
7857
- // when swiftpm compiles a declared macro for the linux host.
7858
- const swiftc = path.join(root, SWIFT_HOST_COMPILER_WRAPPER)
7859
- writeBuildFile(
7860
- swiftc,
7861
- [
7862
- '#!/bin/sh',
7863
- 'target=',
7864
- 'module=',
7865
- 'compile=',
7866
- 'previous=',
7867
- 'for argument do',
7868
- ' case "$previous" in -target) target=$argument ;; -module-name) module=$argument ;; esac',
7869
- ' case "$argument" in -c|-emit-module|-scan-dependencies|-typecheck) compile=1 ;; esac',
7870
- ' previous=$argument',
7871
- 'done',
7872
- 'case "$target/$compile" in',
7873
- ' *-*-linux*/1)',
7874
- ' case ",$PEACH_SWIFT_HOST_MACROS," in',
7875
- ' *",$module,"*) set -- "$@" -Xfrontend -import-module -Xfrontend Foundation ;;',
7876
- ' esac ;;',
7877
- 'esac',
7878
- 'exec "$PEACH_SWIFTC" "$@"',
7879
- '',
7880
- ].join('\n'),
7881
- )
7882
- chmodSync(swiftc, 0o755)
7883
- compiler.SWIFT_EXEC = swiftc
7884
- compiler.PEACH_SWIFT_HOST_MACROS = packageHostMacros.join(',')
7885
- compiler.PEACH_SWIFTC = path.join(options.toolchainBin, 'swiftc')
7886
7659
  }
7887
- const projectProcess = options.project
7888
- ? prepareSwiftProjectProcess(root, options.project)
7889
- : undefined
7890
- // swiftpm hashes TMPDIR into its plan. the root lock owns this scratch.
7891
- const temporaryDirectory = projectProcess
7892
- ? undefined
7893
- : path.join(root, '.build', 'peach-compiler-tmp')
7894
- const appOptions = projectProcess
7895
- ? {
7896
- ...buildOptions,
7897
- uid: projectProcess.uid,
7898
- gid: projectProcess.gid,
7899
- confined: { ...projectProcess.env, ...compiler },
7660
+ return runLocked(async (slotRoot, lease, waitedMs) => {
7661
+ const root = slotRoot
7662
+ const layout: SwiftProjectLayout = {
7663
+ root,
7664
+ sources: path.join(root, 'Sources', 'App'),
7665
+ multi: compileTargets(input).length > 0,
7666
+ }
7667
+ // a process that held the root while this one waited may have built
7668
+ // this exact address.
7669
+ if (!options.intermediates) {
7670
+ const built = readCompiledArtifact(
7671
+ path.join(sharedRoot, 'artifact'),
7672
+ hash,
7673
+ )
7674
+ if (built) {
7675
+ stage('reusing verified disk artifact')
7676
+ return retain(baseRoot, built)
7900
7677
  }
7901
- : {
7902
- ...buildOptions,
7903
- temporaryDirectory,
7904
- env: {
7905
- ...buildOptions.env,
7906
- ...(preparation.usesObjcPrebuilt &&
7907
- process.env.PEACH_HOME !== undefined
7908
- ? { PEACH_HOME: process.env.PEACH_HOME }
7678
+ }
7679
+ if (waitedMs >= 1_000)
7680
+ report(`acquired build root ${path.basename(root)} after ${waitedMs}ms`)
7681
+ if (canPoolBuildRoot) {
7682
+ refreshSwiftCacheHold(root)
7683
+ writeFileSync(path.join(root, SWIFT_BUILD_ROOT_SHAPE), buildShape)
7684
+ }
7685
+ const swift = path.join(toolchainBin, 'swift')
7686
+ if (!existsSync(swift)) {
7687
+ throw new Error(
7688
+ `swift-compile: no swift.org toolchain at ${toolchainBin}; install ${options.release} and its matching wasm sdk`,
7689
+ )
7690
+ }
7691
+ // a distribution's immutable modules and host plugins need no source build.
7692
+ const unoptimized = input.unoptimized === true
7693
+ const baseBuildEnv = options.project?.env
7694
+ ? {
7695
+ ...options.project.env,
7696
+ // shipped host plugins resolve against the selected compiler's runtime.
7697
+ ...(process.platform === 'linux'
7698
+ ? {
7699
+ LD_LIBRARY_PATH: [
7700
+ path.resolve(toolchainBin, '../lib/swift/linux'),
7701
+ path.resolve(toolchainBin, '../lib/swift/host'),
7702
+ process.env.LD_LIBRARY_PATH,
7703
+ ]
7704
+ .filter(Boolean)
7705
+ .join(':'),
7706
+ }
7909
7707
  : {}),
7910
- ...compiler,
7911
- },
7708
+ PEACH_DEFER_WASM_LINK: '1',
7709
+ }
7710
+ : swiftCompilerBaseEnv(toolchainBin, process.env)
7711
+ // hold the exclusive framework slot lock only while staging and
7712
+ // building framework products; take a shared read hold before
7713
+ // releasing it so other builds on the same framework revision
7714
+ // compile and link their apps concurrently.
7715
+ const prepareFrameworks = async (
7716
+ slot: string | null,
7717
+ frameworkLease?: SwiftRootLease,
7718
+ allowWrite = true,
7719
+ ) => {
7720
+ if (allowWrite) budget.startCompile()
7721
+ // project users own their build roots; resolve their sdk outside them.
7722
+ const frameworkRoot = mirrorDistribution
7723
+ ? syncSwiftDistributionMirror(root, moduleRoot, mirrorDistribution)
7724
+ : distribution
7725
+ ? moduleRoot
7726
+ : stageFrameworkSource(
7727
+ moduleRoot,
7728
+ slot,
7729
+ frameworkKey,
7730
+ options.release,
7731
+ )
7732
+ if (!swiftModuleDigest(frameworkRoot).equals(moduleDigest))
7733
+ throw new Error('Swift staged project source differs from the caller')
7734
+ if (!allowWrite && swiftMacroPlugins(frameworkRoot).stale) return
7735
+ if (allowWrite) stage('preparing compiler plugins')
7736
+ const macroPlugins = await ensureMacroPlugins(
7737
+ frameworkRoot,
7738
+ toolchainBin,
7739
+ options.release,
7740
+ budget.signal,
7741
+ frameworkLease,
7742
+ )
7743
+ const compileFrameworkRoot = distribution
7744
+ ? swiftDistributionCompileView(frameworkRoot, distribution)
7745
+ : frameworkRoot
7746
+ // memoized per toolchain, so only a process's first build waits on it,
7747
+ // and that one reads and gzips it while swift builds
7748
+ const sdk = swiftModuleSdk(frameworkRoot).wasmSdkId
7749
+ const compileSdk: SwiftMirrorSdk = mirrorDistribution
7750
+ ? syncSwiftSdkMirror(root, frameworkRoot, toolchainBin, sdk)
7751
+ : {
7752
+ id: sdk,
7753
+ options: swiftCompileSdkOptions(frameworkRoot, toolchainBin),
7754
+ toolsetChanged: false,
7755
+ }
7756
+ if (mirrorDistribution && compileSdk.toolsetChanged)
7757
+ clearSwiftSdkPathsCache(path.join(root, SWIFT_SDK_MIRROR))
7758
+ const icu = options.linkOnly ? null : swiftIcuAsset(toolchainBin, sdk)
7759
+ let prebuilt: SwiftFrameworkProducts | undefined
7760
+ if (!distribution) {
7761
+ if (allowWrite) stage('compiling framework products')
7762
+ prebuilt = await buildFrameworkProducts(
7763
+ slot!,
7764
+ {
7765
+ moduleRoot: frameworkRoot,
7766
+ frameworkKey,
7767
+ input,
7768
+ swift,
7769
+ sdk,
7770
+ toolchainBin,
7771
+ plugins: macroPlugins,
7772
+ buildOptions: {
7773
+ env: baseBuildEnv,
7774
+ maxBuffer: 64 * 1024 * 1024,
7775
+ signal: budget.signal,
7776
+ onOutput: budget.progress,
7777
+ lease,
7778
+ frameworkLease,
7779
+ },
7780
+ },
7781
+ allowWrite,
7782
+ )
7783
+ if (!prebuilt) return
7784
+ if (!allowWrite) {
7785
+ budget.startCompile()
7786
+ stage('reusing verified framework products')
7787
+ }
7912
7788
  }
7913
- const unprepared = preparation.targetFailures.map(
7914
- (failure) => `error: target ${failure}`,
7915
- )
7916
- // a forwarder header (`#include "../../x.hpp"`) reaches its target
7917
- // through `..`, which clang keeps in __FILE__, while the header
7918
- // alias overlay names the same file directly. mapping each
7919
- // forwarder spelling to the directory it reaches makes a debug
7920
- // assert expand alike in every module that includes the header.
7921
- const forwarders = new Map<string, string>()
7922
- for (const [file, text] of Object.entries(input.files)) {
7923
- const parents = /^#include "((?:\.\.\/)+)[^"\n]+"\n$/.exec(text)?.[1]
7924
- if (!parents) continue
7925
- const directory = path.posix.dirname(file)
7926
- forwarders.set(
7927
- `${path.join(root, directory)}/${parents.slice(0, -1)}`,
7928
- path.posix.join('build', directory, parents).replace(/\/$/, ''),
7929
- )
7930
- }
7931
- const jobs = swiftCompilerJobs()
7932
- const incrementalPreview =
7933
- sdkImage !== undefined &&
7934
- !guestGraph &&
7935
- !options.project &&
7936
- !input.optimize &&
7937
- !input.unoptimized
7938
- const batchGuest =
7939
- guestGraph !== undefined && !options.project && !input.unoptimized
7940
- const guestDriverJobs = Math.min(8, jobs)
7941
- // large producers already get their own stage. keep room for their
7942
- // prerequisites while giving a lone driver more of the core grant.
7943
- const singleProducerJobs = Math.min(16, Math.floor(jobs / 2))
7944
- const batch = incrementalPreview || batchGuest
7945
- const perFile = input.unoptimized || batch
7946
- const reproducibleFrameworkRoot = mirrorDistribution
7947
- ? frameworkRoot
7948
- : compileFrameworkRoot
7949
- const buildArgs = [
7950
- 'build',
7951
- ...(projectProcess?.cacheOptions ?? swiftPackageCacheOptions()),
7952
- '--build-system',
7953
- 'native',
7954
- '-j',
7955
- String(jobs),
7956
- '--package-path',
7957
- root,
7958
- ...compileSdk.options,
7959
- ...swiftObjCSelectorOptions(frameworkRoot),
7960
- '--swift-sdk',
7961
- compileSdk.id,
7962
- ...(preparation.targetToolset
7963
- ? ['--toolset', path.join(root, '.peach-target-toolset.json')]
7964
- : []),
7965
- '-c',
7966
- 'release',
7967
- ...(input.unoptimized ? ['-Xswiftc', '-Onone'] : []),
7968
- ...(perFile
7969
- ? [
7970
- '-Xswiftc',
7971
- '-no-whole-module-optimization',
7972
- '-Xswiftc',
7973
- '-j',
7974
- '-Xswiftc',
7975
- String(batchGuest ? guestDriverJobs : jobs),
7976
- ]
7977
- : []),
7978
- // optimized batches can move specialized definitions between objects.
7979
- ...(incrementalPreview ? ['-Xswiftc', '-incremental'] : []),
7980
- ...(batch ? ['-Xswiftc', '-enable-batch-mode'] : []),
7981
- // the mirror finds a changed sdk header's readers in their
7982
- // dependency files, which omit system headers by default
7983
- ...(mirrorDistribution ? ['-Xswiftc', '-track-system-dependencies'] : []),
7984
- // the link strips debug info, so none is generated (as for the framework).
7985
- // keep -num-threads fixed across caller core caps so llbuild does not
7986
- // rebuild every target when callers alternate --cores, and bound backend
7987
- // fan-out under high -j.
7988
- '-Xswiftc',
7989
- '-gnone',
7990
- '-Xcc',
7991
- '-g0',
7992
- '-Xcxx',
7993
- '-g0',
7994
- ...(batch
7995
- ? []
7996
- : [
7997
- '-Xswiftc',
7998
- '-num-threads',
7999
- '-Xswiftc',
8000
- String(perFile ? 1 : Math.min(8, os.availableParallelism())),
8001
- ]),
8002
- ...swiftReproducibleBuildFlags([
8003
- [path.dirname(options.toolchainBin), 'toolchain'],
8004
- [reproducibleFrameworkRoot, 'framework'],
8005
- [root, 'build'],
8006
- ...forwarders,
8007
- ]).flatMap((flag, index, flags) => {
8008
- if (!nativeToolset || !flag.startsWith('-ffile-prefix-map='))
8009
- return [flag]
8010
- const toolchainDir = path.dirname(options.toolchainBin)
8011
- let mapped = flag
8012
- for (const [dir, target] of [
8013
- [root, '/peach/build'],
8014
- [reproducibleFrameworkRoot, '/peach/framework'],
8015
- [realpathSync(reproducibleFrameworkRoot), '/peach/framework'],
8016
- [toolchainDir, '/peach/toolchain'],
8017
- [realpathSync(toolchainDir), '/peach/toolchain'],
8018
- ] as const) {
8019
- mapped = mapped.replaceAll(dir, target)
7789
+ const readHold: SwiftRootReadHold | undefined = slot
7790
+ ? acquireSwiftRootReadHold(slot)
7791
+ : undefined
7792
+ return {
7793
+ frameworkRoot,
7794
+ compileFrameworkRoot,
7795
+ macroPlugins,
7796
+ sdk,
7797
+ compileSdk,
7798
+ icu,
7799
+ prebuilt,
7800
+ readHold,
8020
7801
  }
8021
- const [, from, to] = /^-ffile-prefix-map=([^=]+)=(.+)$/.exec(mapped) ?? []
8022
- const tool = flags[index - 1]!
8023
- // clang applies the longest prefix once without chaining: keep the
8024
- // physical map for direct compiles and add the mapped form for
8025
- // subpaths already rewritten by modular depscan.
8026
- return mapped !== flag && from !== to ? [flag, tool, mapped] : [flag]
8027
- }),
8028
- ...macroPlugins.libraries.flatMap((plugin) => [
8029
- '-Xswiftc',
8030
- '-load-plugin-library',
8031
- '-Xswiftc',
8032
- plugin,
8033
- ]),
8034
- ...macroPlugins.executables.flatMap((plugin) => [
8035
- '-Xswiftc',
8036
- '-load-plugin-executable',
8037
- '-Xswiftc',
8038
- `${plugin}#ExpoModulesMacros`,
8039
- ]),
8040
- ]
8041
- const linked = builtArtifact(layout)
8042
- // every link is deferred: a build stopped after the linker wrapper wrote
8043
- // its 8-byte placeholder would otherwise leave swiftpm seeing a fresh,
8044
- // empty executable and skipping the link on the next build.
8045
- rmSync(path.join(root, '.peach-link.rsp'), { force: true })
8046
- // archive producers reuse objects across compiler recipe changes,
8047
- // so qualify each new entry with the current linker.
8048
- if (options.linkOnly || (existsSync(linked) && statSync(linked).size <= 8))
8049
- rmSync(linked, { force: true })
8050
- stage('compiling and linking Swift modules')
8051
- const frameworkInterfaces = new Map<
8052
- string,
8053
- { file: string; header: string; module: boolean } | null
8054
- >()
8055
- const compileSdkPaths = swiftSdkPaths(
8056
- frameworkRoot,
8057
- options.toolchainBin,
8058
- compileSdk.options,
8059
- compileSdk.id,
8060
- )
8061
- const sdkFrameworks = path.join(
8062
- compileSdkPaths.darwin,
8063
- 'System/Library/Frameworks',
8064
- )
8065
- const generatedInterface = (source: string) =>
8066
- withoutImportedSdkEnumForwards(
8067
- clangInterfaceHeader(readFileSync(source, 'utf8'), frameworkRoot),
8068
- sdkObjCDeclarationOwners(sdkFrameworks),
8069
- )
8070
- const nativeDeclarations = new Map<string, Set<string>>()
8071
- const nativeHeaders = Object.entries(input.files)
8072
- .filter(([name]) => name.endsWith('.h') && !name.endsWith('-Swift.h'))
8073
- .map(([, source]) => source)
8074
- for (const [file, contents] of Object.entries(input.files)) {
8075
- if (!file.endsWith('.modulemap')) continue
8076
- const name = moduleMapName(contents)
8077
- const umbrella = /\bumbrella\s+header\s+"([^"]+)"/.exec(contents)?.[1]
8078
- if (!name || !umbrella) continue
8079
- const header =
8080
- input.files[path.posix.join(path.posix.dirname(file), umbrella)]
8081
- if (header === undefined) continue
8082
- const included = new Set(
8083
- [
8084
- ...header.matchAll(/^\s*#\s*(?:import|include)\s*[<"]([^">]+)[">]/gm),
8085
- ].map((match) => path.posix.basename(match[1]!)),
8086
- )
8087
- const declarations = nativeDeclarations.get(name) ?? new Set<string>()
8088
- for (const declaration of swiftInterfaceDeclarations(header))
8089
- declarations.add(declaration)
8090
- for (const [candidate, source] of Object.entries(input.files))
8091
- if (included.has(path.posix.basename(candidate)))
8092
- for (const declaration of swiftInterfaceDeclarations(source))
8093
- declarations.add(declaration)
8094
- nativeDeclarations.set(name, declarations)
8095
- }
8096
- const frameworkInterface = (
8097
- name: string,
8098
- ): { file: string; header: string; module: boolean } | null => {
8099
- if (frameworkInterfaces.has(name)) return frameworkInterfaces.get(name)!
8100
- const source = distribution
8101
- ? path.join(frameworkRoot, 'modules', `${name}-Swift.h`)
8102
- : prebuilt!.objcHeaders.get(name)
8103
- if (!source || !existsSync(source)) {
8104
- frameworkInterfaces.set(name, null)
8105
- return null
8106
- }
8107
- const headers = path.join(sdkFrameworks, `${name}.framework/Headers`)
8108
- const declared = new Set<string>()
8109
- if (existsSync(headers))
8110
- for (const file of readdirSync(headers, {
8111
- recursive: true,
8112
- encoding: 'utf8',
8113
- }))
8114
- if (file.endsWith('.h'))
8115
- for (const name of swiftInterfaceDeclarations(
8116
- readFileSync(path.join(headers, file), 'utf8'),
8117
- ))
8118
- declared.add(name)
8119
- for (const declaration of nativeDeclarations.get(name) ?? [])
8120
- declared.add(declaration)
8121
- const own = withoutSwiftDeclarations(
8122
- generatedInterface(source),
8123
- declared,
8124
- nativeDeclarations.has(name)
8125
- ? `@import ${name};`
8126
- : `#import <${name}/${name}.h>`,
8127
- )
8128
- // the swift module also implements classes another framework's headers
8129
- // already define; clang takes those from the owning framework
8130
- const owners = sdkObjCDeclarationOwners(sdkFrameworks)
8131
- const foreign = new Map<string, string>()
8132
- for (const declaration of [
8133
- ...swiftInterfaceDeclarations(own),
8134
- ...objcEnumerations(own),
8135
- ...[...own.matchAll(/^\s*SWIFT_EXTERN\b[^(\n]*?\b(\w+)\s*\(/gm)].map(
8136
- (match) => match[1]!,
8137
- ),
8138
- ]) {
8139
- const owner = owners.get(declaration)
8140
- if (owner && owner !== name) foreign.set(declaration, owner)
8141
7802
  }
8142
- const header = foreign.size
8143
- ? withoutSwiftDeclarations(
8144
- own,
8145
- new Set(foreign.keys()),
8146
- [...new Set(foreign.values())]
8147
- .map((owner) => `#import <${owner}/${owner}.h>`)
8148
- .join('\n'),
7803
+ const frameworks = distribution
7804
+ ? await prepareFrameworks(null)
7805
+ : await withSwiftFrameworkSlot(
7806
+ frameworkKey,
7807
+ options.release,
7808
+ moduleRoot,
7809
+ budget.signal,
7810
+ prepareFrameworks,
7811
+ unoptimized,
7812
+ options.linkOnly === true,
8149
7813
  )
8150
- : own
8151
- const value = {
8152
- file: path.join(root, '.build/peach-framework-objc', `${name}-Swift.h`),
8153
- header,
8154
- module: existsSync(headers),
7814
+ if (!frameworks)
7815
+ throw new Error('Swift distribution did not provide its frameworks')
7816
+ const {
7817
+ frameworkRoot,
7818
+ compileFrameworkRoot,
7819
+ macroPlugins,
7820
+ compileSdk,
7821
+ icu,
7822
+ prebuilt,
7823
+ } = frameworks
7824
+ let readHold = frameworks.readHold
7825
+ const buildOptions = {
7826
+ env: baseBuildEnv,
7827
+ maxBuffer: 64 * 1024 * 1024,
7828
+ signal: budget.signal,
7829
+ onOutput: budget.progress,
7830
+ lease,
8155
7831
  }
8156
- frameworkInterfaces.set(name, value)
8157
- writeBuildFile(
8158
- value.file,
8159
- (existsSync(path.join(headers, `${name}.h`))
8160
- ? `#import <${name}/${name}.h>\n`
8161
- : '') + swiftHeaderWithSuperclassImports(header, frameworkInterface),
8162
- )
8163
- return value
8164
- }
8165
- const headerPaths = (producer: string) => {
8166
- const stem = path.join(
8167
- root,
8168
- '.build',
8169
- 'peach-cxx-headers',
8170
- `${producer}-Swift`,
8171
- )
8172
- return { producer, original: `${stem}.original.h`, emitted: `${stem}.h` }
8173
- }
8174
- const publishHeader = ({
8175
- producer,
8176
- original,
8177
- emitted,
8178
- }: ReturnType<typeof headerPaths>) => {
8179
- const generated = generatedInterface(original)
8180
- writeBuildFile(
8181
- emitted,
8182
- withoutSwiftDeclarations(
8183
- swiftHeaderWithSuperclassImports(generated, frameworkInterface),
8184
- new Set([
8185
- ...(preparation.nativeHeaderDeclarations[producer] ?? []),
8186
- ...nativelyDeclaredFunctions(generated, nativeHeaders),
8187
- ]),
8188
- `#import <${producer}/${producer}.h>`,
8189
- ),
8190
- )
8191
- }
8192
- const recipe = inputHash
8193
- .copy()
8194
- .update(
8195
- distribution ? swiftCompileSurfaceDigest(frameworkRoot) : moduleDigest,
8196
- )
8197
- .update(readFileSync(path.join(root, 'Package.swift')))
8198
- .update(JSON.stringify(buildArgs))
8199
- .digest('hex')
8200
- const runApp = async (compiler?: Record<string, string>) => {
8201
- const optionsWithCompiler = compiler
8202
- ? { ...appOptions, env: { ...appOptions.env, ...compiler } }
8203
- : appOptions
8204
- // clang consumes the real emitted headers after swift finishes.
8205
- // swiftpm's transitive swift module maps are not C declarations:
8206
- // importing them would shadow SDK modules such as ObjectiveC.
8207
- const stages = [
8208
- ...(preparation.nativePrerequisiteTargets ?? []).map((target) => ({
8209
- target,
8210
- producers: [],
8211
- })),
8212
- ...preparation.headerBuilds,
8213
- ...(preparation.nativeProductTargets ?? []).map((target) => ({
8214
- target,
8215
- producers: [],
8216
- })),
8217
- ]
8218
- const checkpoints = path.join(root, '.build', 'peach-product-checkpoints')
8219
- const buildDbExists = existsSync(path.join(root, '.build', 'build.db'))
8220
- const releaseDir = path.dirname(linked)
8221
- for (const { target, producers } of stages) {
8222
- // pure native checkpoint stages exist only to commit build.db on cold
8223
- // builds; when build.db and all stage objects are already warm, the
8224
- // header stage and final full-graph build still validate every input.
8225
- if (!options.project && producers.length === 0 && buildDbExists) {
8226
- const expectedObjects = preparation.nativeStageObjects.get(target)
8227
- if (
8228
- expectedObjects &&
8229
- expectedObjects.length > 0 &&
8230
- expectedObjects.every((relative) =>
8231
- statSync(path.join(releaseDir, relative), {
8232
- throwIfNoEntry: false,
8233
- })?.isFile(),
8234
- )
7832
+ try {
7833
+ if (options.project) removeProjectLinks(root)
7834
+ const packageHostMacros =
7835
+ process.platform === 'linux' ? input.packageHostMacros : undefined
7836
+ if (
7837
+ retireStaleSwiftLink(
7838
+ root,
7839
+ swiftLinkStamp({
7840
+ frameworkKey: mirrorDistribution
7841
+ ? `${options.release}\0mirror`
7842
+ : `${options.release}\0${Boolean(distribution)}\0${swiftModuleSdk(frameworkRoot).wasmSdkId}`,
7843
+ packageHostMacros,
7844
+ }),
7845
+ swiftLinkStamp({
7846
+ // mirrored distributions and their WASI SDK mirror invalidate
7847
+ // dependents per changed file instead of wiping every Clang object.
7848
+ frameworkKey: mirrorDistribution
7849
+ ? `${options.release}\0mirror`
7850
+ : distribution
7851
+ ? `${options.release}\0${distribution.wasmSdkChecksum}`
7852
+ : frameworkKey,
7853
+ prebuilt,
7854
+ packageHostMacros,
7855
+ }),
7856
+ Boolean(options.linkOnly),
8235
7857
  )
8236
- continue
7858
+ )
7859
+ stage('framework revision changed; rebuilding the app link')
7860
+ const nativeToolset = needsNativeToolset(input, prebuilt)
7861
+ const preparation = writeSwiftProject(
7862
+ layout,
7863
+ input,
7864
+ frameworkRoot,
7865
+ prebuilt,
7866
+ !options.project,
7867
+ options.project
7868
+ ? false
7869
+ : (options.objcPrebuiltStage ??
7870
+ (options.intermediates ? false : undefined)),
7871
+ compileSdk,
7872
+ )
7873
+ // the framework objects link as inputs, so the product name its
7874
+ // modules autolink has no archive to load
7875
+ const productFile = path.join(frameworkRoot, SWIFT_FRAMEWORK_PRODUCT_FILE)
7876
+ writeSwiftAutolinkLinker(
7877
+ root,
7878
+ toolchainBin,
7879
+ existsSync(productFile)
7880
+ ? [
7881
+ v.parse(
7882
+ swiftFrameworkProductSchema,
7883
+ JSON.parse(readFileSync(productFile, 'utf8')),
7884
+ ).product.name,
7885
+ ]
7886
+ : [],
7887
+ )
7888
+ // the native build system takes its C compiler from CC, never a toolset
7889
+ const compiler: Record<string, string> = preparation.targetToolset
7890
+ ? { CC: path.join(root, CLANG_TARGET_MODULE_WRAPPER) }
7891
+ : {}
7892
+ if (packageHostMacros?.length) {
7893
+ // swiftpm build-tool flags skip macro targets; forward the import
7894
+ // when swiftpm compiles a declared macro for the linux host.
7895
+ const swiftc = path.join(root, SWIFT_HOST_COMPILER_WRAPPER)
7896
+ writeBuildFile(
7897
+ swiftc,
7898
+ [
7899
+ '#!/bin/sh',
7900
+ 'target=',
7901
+ 'module=',
7902
+ 'compile=',
7903
+ 'previous=',
7904
+ 'for argument do',
7905
+ ' case "$previous" in -target) target=$argument ;; -module-name) module=$argument ;; esac',
7906
+ ' case "$argument" in -c|-emit-module|-scan-dependencies|-typecheck) compile=1 ;; esac',
7907
+ ' previous=$argument',
7908
+ 'done',
7909
+ 'case "$target/$compile" in',
7910
+ ' *-*-linux*/1)',
7911
+ ' case ",$PEACH_SWIFT_HOST_MACROS," in',
7912
+ ' *",$module,"*) set -- "$@" -Xfrontend -import-module -Xfrontend Foundation ;;',
7913
+ ' esac ;;',
7914
+ 'esac',
7915
+ 'exec "$PEACH_SWIFTC" "$@"',
7916
+ '',
7917
+ ].join('\n'),
7918
+ )
7919
+ chmodSync(swiftc, 0o755)
7920
+ compiler.SWIFT_EXEC = swiftc
7921
+ compiler.PEACH_SWIFT_HOST_MACROS = packageHostMacros.join(',')
7922
+ compiler.PEACH_SWIFTC = path.join(toolchainBin, 'swiftc')
8237
7923
  }
8238
- const receipt = path.join(
8239
- checkpoints,
8240
- createHash('sha256').update(target).digest('hex'),
7924
+ const projectProcess = options.project
7925
+ ? prepareSwiftProjectProcess(root, options.project)
7926
+ : undefined
7927
+ // swiftpm hashes TMPDIR into its plan. the root lock owns this scratch.
7928
+ const temporaryDirectory = projectProcess
7929
+ ? undefined
7930
+ : path.join(root, '.build', 'peach-compiler-tmp')
7931
+ const appOptions = projectProcess
7932
+ ? {
7933
+ ...buildOptions,
7934
+ uid: projectProcess.uid,
7935
+ gid: projectProcess.gid,
7936
+ confined: { ...projectProcess.env, ...compiler },
7937
+ }
7938
+ : {
7939
+ ...buildOptions,
7940
+ temporaryDirectory,
7941
+ env: {
7942
+ ...buildOptions.env,
7943
+ ...(preparation.usesObjcPrebuilt &&
7944
+ process.env.PEACH_HOME !== undefined
7945
+ ? { PEACH_HOME: process.env.PEACH_HOME }
7946
+ : {}),
7947
+ ...compiler,
7948
+ },
7949
+ }
7950
+ const unprepared = preparation.targetFailures.map(
7951
+ (failure) => `error: target ${failure}`,
8241
7952
  )
8242
- const headers = producers.map(headerPaths)
8243
- for (const header of headers)
8244
- if (existsSync(header.original)) publishHeader(header)
8245
- const fingerprint = (): string | undefined => {
8246
- const digest = createHash('sha256').update(recipe)
8247
- for (const { original, emitted } of headers) {
8248
- if (!existsSync(original) || !existsSync(emitted)) return
8249
- digest.update(
8250
- createHash('sha256').update(readFileSync(emitted)).digest(),
8251
- )
8252
- }
8253
- return digest.digest('hex')
7953
+ // a forwarder header (`#include "../../x.hpp"`) reaches its target
7954
+ // through `..`, which clang keeps in __FILE__, while the header
7955
+ // alias overlay names the same file directly. mapping each
7956
+ // forwarder spelling to the directory it reaches makes a debug
7957
+ // assert expand alike in every module that includes the header.
7958
+ const forwarders = new Map<string, string>()
7959
+ for (const [file, text] of Object.entries(input.files)) {
7960
+ const parents = /^#include "((?:\.\.\/)+)[^"\n]+"\n$/.exec(text)?.[1]
7961
+ if (!parents) continue
7962
+ const directory = path.posix.dirname(file)
7963
+ forwarders.set(
7964
+ `${path.join(root, directory)}/${parents.slice(0, -1)}`,
7965
+ path.posix.join('build', directory, parents).replace(/\/$/, ''),
7966
+ )
8254
7967
  }
8255
- if (
7968
+ const jobs = swiftCompilerJobs()
7969
+ const incrementalPreview =
7970
+ sdkImage !== undefined &&
7971
+ !guestGraph &&
8256
7972
  !options.project &&
8257
- existsSync(receipt) &&
8258
- readFileSync(receipt, 'utf8') === fingerprint()
7973
+ !input.optimize &&
7974
+ !input.unoptimized
7975
+ const batchGuest =
7976
+ guestGraph !== undefined && !options.project && !input.unoptimized
7977
+ const guestDriverJobs = Math.min(8, jobs)
7978
+ // large producers already get their own stage. keep room for their
7979
+ // prerequisites while giving a lone driver more of the core grant.
7980
+ const singleProducerJobs = Math.min(16, Math.floor(jobs / 2))
7981
+ const batch = incrementalPreview || batchGuest
7982
+ const perFile = input.unoptimized || batch
7983
+ const reproducibleFrameworkRoot = mirrorDistribution
7984
+ ? frameworkRoot
7985
+ : compileFrameworkRoot
7986
+ const buildArgs = [
7987
+ 'build',
7988
+ ...(projectProcess?.cacheOptions ?? swiftPackageCacheOptions()),
7989
+ '--build-system',
7990
+ 'native',
7991
+ '-j',
7992
+ String(jobs),
7993
+ '--package-path',
7994
+ root,
7995
+ ...compileSdk.options,
7996
+ ...swiftObjCSelectorOptions(frameworkRoot),
7997
+ '--swift-sdk',
7998
+ compileSdk.id,
7999
+ ...(preparation.targetToolset
8000
+ ? ['--toolset', path.join(root, '.peach-target-toolset.json')]
8001
+ : []),
8002
+ '-c',
8003
+ 'release',
8004
+ ...(input.unoptimized ? ['-Xswiftc', '-Onone'] : []),
8005
+ ...(perFile
8006
+ ? [
8007
+ '-Xswiftc',
8008
+ '-no-whole-module-optimization',
8009
+ '-Xswiftc',
8010
+ '-j',
8011
+ '-Xswiftc',
8012
+ String(batchGuest ? guestDriverJobs : jobs),
8013
+ ]
8014
+ : []),
8015
+ // optimized batches can move specialized definitions between objects.
8016
+ ...(incrementalPreview ? ['-Xswiftc', '-incremental'] : []),
8017
+ ...(batch ? ['-Xswiftc', '-enable-batch-mode'] : []),
8018
+ // the mirror finds a changed sdk header's readers in their
8019
+ // dependency files, which omit system headers by default
8020
+ ...(mirrorDistribution
8021
+ ? ['-Xswiftc', '-track-system-dependencies']
8022
+ : []),
8023
+ // the link strips debug info, so none is generated (as for the framework).
8024
+ // keep -num-threads fixed across caller core caps so llbuild does not
8025
+ // rebuild every target when callers alternate --cores, and bound backend
8026
+ // fan-out under high -j.
8027
+ '-Xswiftc',
8028
+ '-gnone',
8029
+ '-Xcc',
8030
+ '-g0',
8031
+ '-Xcxx',
8032
+ '-g0',
8033
+ ...(batch
8034
+ ? []
8035
+ : [
8036
+ '-Xswiftc',
8037
+ '-num-threads',
8038
+ '-Xswiftc',
8039
+ String(perFile ? 1 : Math.min(8, os.availableParallelism())),
8040
+ ]),
8041
+ ...swiftReproducibleBuildFlags([
8042
+ [path.dirname(toolchainBin), 'toolchain'],
8043
+ [reproducibleFrameworkRoot, 'framework'],
8044
+ [root, 'build'],
8045
+ ...forwarders,
8046
+ ]).flatMap((flag, index, flags) => {
8047
+ if (!nativeToolset || !flag.startsWith('-ffile-prefix-map='))
8048
+ return [flag]
8049
+ const toolchainDir = path.dirname(toolchainBin)
8050
+ let mapped = flag
8051
+ for (const [dir, target] of [
8052
+ [root, '/peach/build'],
8053
+ [reproducibleFrameworkRoot, '/peach/framework'],
8054
+ [realpathSync(reproducibleFrameworkRoot), '/peach/framework'],
8055
+ [toolchainDir, '/peach/toolchain'],
8056
+ [realpathSync(toolchainDir), '/peach/toolchain'],
8057
+ ] as const) {
8058
+ mapped = mapped.replaceAll(dir, target)
8059
+ }
8060
+ const [, from, to] =
8061
+ /^-ffile-prefix-map=([^=]+)=(.+)$/.exec(mapped) ?? []
8062
+ const tool = flags[index - 1]!
8063
+ // clang applies the longest prefix once without chaining: keep the
8064
+ // physical map for direct compiles and add the mapped form for
8065
+ // subpaths already rewritten by modular depscan.
8066
+ return mapped !== flag && from !== to ? [flag, tool, mapped] : [flag]
8067
+ }),
8068
+ ...macroPlugins.libraries.flatMap((plugin) => [
8069
+ '-Xswiftc',
8070
+ '-load-plugin-library',
8071
+ '-Xswiftc',
8072
+ plugin,
8073
+ ]),
8074
+ ...macroPlugins.executables.flatMap((plugin) => [
8075
+ '-Xswiftc',
8076
+ '-load-plugin-executable',
8077
+ '-Xswiftc',
8078
+ `${plugin}#ExpoModulesMacros`,
8079
+ ]),
8080
+ ]
8081
+ const linked = builtArtifact(layout)
8082
+ // every link is deferred: a build stopped after the linker wrapper wrote
8083
+ // its 8-byte placeholder would otherwise leave swiftpm seeing a fresh,
8084
+ // empty executable and skipping the link on the next build.
8085
+ rmSync(path.join(root, '.peach-link.rsp'), { force: true })
8086
+ // archive producers reuse objects across compiler recipe changes,
8087
+ // so qualify each new entry with the current linker.
8088
+ if (
8089
+ options.linkOnly ||
8090
+ (existsSync(linked) && statSync(linked).size <= 8)
8091
+ )
8092
+ rmSync(linked, { force: true })
8093
+ stage('compiling and linking Swift modules')
8094
+ const frameworkInterfaces = new Map<
8095
+ string,
8096
+ { file: string; header: string; module: boolean } | null
8097
+ >()
8098
+ const compileSdkPaths = swiftSdkPaths(
8099
+ frameworkRoot,
8100
+ toolchainBin,
8101
+ compileSdk.options,
8102
+ compileSdk.id,
8259
8103
  )
8260
- continue
8261
- if (!options.project) rmSync(receipt, { force: true })
8262
- // swiftpm doesn't track custom objc header paths as outputs.
8263
- for (const header of headers) {
8264
- if (!existsSync(header.original))
8265
- rmSync(
8266
- path.join(
8267
- path.dirname(linked),
8268
- 'Modules',
8269
- `${swiftTargetModuleName(header.producer)}.swiftmodule`,
8104
+ const sdkFrameworks = path.join(
8105
+ compileSdkPaths.darwin,
8106
+ 'System/Library/Frameworks',
8107
+ )
8108
+ const generatedInterface = (source: string) =>
8109
+ withoutImportedSdkEnumForwards(
8110
+ clangInterfaceHeader(readFileSync(source, 'utf8'), frameworkRoot),
8111
+ sdkObjCDeclarationOwners(sdkFrameworks),
8112
+ )
8113
+ const nativeDeclarations = new Map<string, Set<string>>()
8114
+ const nativeHeaders = Object.entries(input.files)
8115
+ .filter(([name]) => name.endsWith('.h') && !name.endsWith('-Swift.h'))
8116
+ .map(([, source]) => source)
8117
+ for (const [file, contents] of Object.entries(input.files)) {
8118
+ if (!file.endsWith('.modulemap')) continue
8119
+ const name = moduleMapName(contents)
8120
+ const umbrella = /\bumbrella\s+header\s+"([^"]+)"/.exec(contents)?.[1]
8121
+ if (!name || !umbrella) continue
8122
+ const header =
8123
+ input.files[path.posix.join(path.posix.dirname(file), umbrella)]
8124
+ if (header === undefined) continue
8125
+ const included = new Set(
8126
+ [
8127
+ ...header.matchAll(
8128
+ /^\s*#\s*(?:import|include)\s*[<"]([^">]+)[">]/gm,
8270
8129
  ),
8271
- { force: true },
8272
- )
8130
+ ].map((match) => path.posix.basename(match[1]!)),
8131
+ )
8132
+ const declarations = nativeDeclarations.get(name) ?? new Set<string>()
8133
+ for (const declaration of swiftInterfaceDeclarations(header))
8134
+ declarations.add(declaration)
8135
+ for (const [candidate, source] of Object.entries(input.files))
8136
+ if (included.has(path.posix.basename(candidate)))
8137
+ for (const declaration of swiftInterfaceDeclarations(source))
8138
+ declarations.add(declaration)
8139
+ nativeDeclarations.set(name, declarations)
8273
8140
  }
8274
- await runCompiler(
8275
- swift,
8276
- [...buildArgs, '--target', target],
8277
- optionsWithCompiler,
8278
- /^(?:\[swift-prebuilt\]|\[\d+\/\d+\] )/,
8279
- SWIFTPM_NOISE,
8280
- )
8281
- if (!compiler) for (const header of headers) publishHeader(header)
8282
- if (!options.project) {
8283
- const checkpoint = fingerprint()
8284
- if (checkpoint === undefined)
8285
- throw new Error(`missing Swift headers after building ${target}`)
8286
- mkdirSync(checkpoints, { recursive: true })
8287
- writeFileSync(`${receipt}.partial`, checkpoint)
8288
- renameSync(`${receipt}.partial`, receipt)
8141
+ const frameworkInterface = (
8142
+ name: string,
8143
+ ): { file: string; header: string; module: boolean } | null => {
8144
+ if (frameworkInterfaces.has(name)) return frameworkInterfaces.get(name)!
8145
+ const source = distribution
8146
+ ? path.join(frameworkRoot, 'modules', `${name}-Swift.h`)
8147
+ : prebuilt!.objcHeaders.get(name)
8148
+ if (!source || !existsSync(source)) {
8149
+ frameworkInterfaces.set(name, null)
8150
+ return null
8151
+ }
8152
+ const headers = path.join(sdkFrameworks, `${name}.framework/Headers`)
8153
+ const declared = new Set<string>()
8154
+ if (existsSync(headers))
8155
+ for (const file of readdirSync(headers, {
8156
+ recursive: true,
8157
+ encoding: 'utf8',
8158
+ }))
8159
+ if (file.endsWith('.h'))
8160
+ for (const name of swiftInterfaceDeclarations(
8161
+ readFileSync(path.join(headers, file), 'utf8'),
8162
+ ))
8163
+ declared.add(name)
8164
+ for (const declaration of nativeDeclarations.get(name) ?? [])
8165
+ declared.add(declaration)
8166
+ const own = withoutSwiftDeclarations(
8167
+ generatedInterface(source),
8168
+ declared,
8169
+ nativeDeclarations.has(name)
8170
+ ? `@import ${name};`
8171
+ : `#import <${name}/${name}.h>`,
8172
+ )
8173
+ // the swift module also implements classes another framework's headers
8174
+ // already define; clang takes those from the owning framework
8175
+ const owners = sdkObjCDeclarationOwners(sdkFrameworks)
8176
+ const foreign = new Map<string, string>()
8177
+ for (const declaration of [
8178
+ ...swiftInterfaceDeclarations(own),
8179
+ ...objcEnumerations(own),
8180
+ ...[...own.matchAll(/^\s*SWIFT_EXTERN\b[^(\n]*?\b(\w+)\s*\(/gm)].map(
8181
+ (match) => match[1]!,
8182
+ ),
8183
+ ]) {
8184
+ const owner = owners.get(declaration)
8185
+ if (owner && owner !== name) foreign.set(declaration, owner)
8186
+ }
8187
+ const header = foreign.size
8188
+ ? withoutSwiftDeclarations(
8189
+ own,
8190
+ new Set(foreign.keys()),
8191
+ [...new Set(foreign.values())]
8192
+ .map((owner) => `#import <${owner}/${owner}.h>`)
8193
+ .join('\n'),
8194
+ )
8195
+ : own
8196
+ const value = {
8197
+ file: path.join(
8198
+ root,
8199
+ '.build/peach-framework-objc',
8200
+ `${name}-Swift.h`,
8201
+ ),
8202
+ header,
8203
+ module: existsSync(headers),
8204
+ }
8205
+ frameworkInterfaces.set(name, value)
8206
+ writeBuildFile(
8207
+ value.file,
8208
+ (existsSync(path.join(headers, `${name}.h`))
8209
+ ? `#import <${name}/${name}.h>\n`
8210
+ : '') +
8211
+ swiftHeaderWithSuperclassImports(header, frameworkInterface),
8212
+ )
8213
+ return value
8289
8214
  }
8290
- }
8291
- // always let swiftpm check the full graph, including missing outputs.
8292
- await runCompiler(
8293
- swift,
8294
- buildArgs,
8295
- optionsWithCompiler,
8296
- SWIFTPM_PROGRESS,
8297
- SWIFTPM_NOISE,
8298
- )
8299
- }
8300
- const compileApp = () =>
8301
- preparation.headerCompiler
8302
- ? withSwiftHeaderCompiler(
8215
+ const headerPaths = (producer: string) => {
8216
+ const stem = path.join(
8303
8217
  root,
8304
- options.toolchainBin,
8305
- recipe,
8306
- new Map(
8307
- preparation.headerBuilds.flatMap(({ producers }) => {
8308
- const driverJobs =
8309
- batchGuest &&
8310
- producers.length === 1 &&
8311
- singleProducerJobs > guestDriverJobs
8312
- ? singleProducerJobs
8313
- : undefined
8314
- return producers.map((producer) => {
8315
- const paths = headerPaths(producer)
8316
- return [
8317
- swiftTargetModuleName(producer),
8318
- {
8319
- header: paths.original,
8320
- publish: () => publishHeader(paths),
8321
- jobs: driverJobs,
8322
- },
8323
- ] as const
8324
- })
8325
- }),
8218
+ '.build',
8219
+ 'peach-cxx-headers',
8220
+ `${producer}-Swift`,
8221
+ )
8222
+ return {
8223
+ producer,
8224
+ original: `${stem}.original.h`,
8225
+ emitted: `${stem}.h`,
8226
+ }
8227
+ }
8228
+ const publishHeader = ({
8229
+ producer,
8230
+ original,
8231
+ emitted,
8232
+ }: ReturnType<typeof headerPaths>) => {
8233
+ const generated = generatedInterface(original)
8234
+ writeBuildFile(
8235
+ emitted,
8236
+ withoutSwiftDeclarations(
8237
+ swiftHeaderWithSuperclassImports(generated, frameworkInterface),
8238
+ new Set([
8239
+ ...(preparation.nativeHeaderDeclarations[producer] ?? []),
8240
+ ...nativelyDeclaredFunctions(generated, nativeHeaders),
8241
+ ]),
8242
+ `#import <${producer}/${producer}.h>`,
8326
8243
  ),
8327
- runApp,
8328
8244
  )
8329
- : runApp()
8330
- try {
8331
- if (temporaryDirectory) mkdirSync(temporaryDirectory, { recursive: true })
8332
- await compileApp()
8333
- } catch (error) {
8334
- const output = outputOf(error)
8335
- const moduleCache = path.join(
8336
- root,
8337
- '.build',
8338
- WASM_TRIPLE,
8339
- 'release',
8340
- 'ModuleCache',
8341
- )
8342
- if (
8343
- output.includes('was compiled with module cache path') &&
8344
- existsSync(moduleCache)
8345
- ) {
8346
- rmSync(moduleCache, { recursive: true, force: true })
8245
+ }
8246
+ const recipe = inputHash
8247
+ .copy()
8248
+ .update(
8249
+ distribution
8250
+ ? swiftCompileSurfaceDigest(frameworkRoot)
8251
+ : moduleDigest,
8252
+ )
8253
+ .update(readFileSync(path.join(root, 'Package.swift')))
8254
+ .update(JSON.stringify(buildArgs))
8255
+ .digest('hex')
8256
+ const runApp = async (compiler?: Record<string, string>) => {
8257
+ const optionsWithCompiler = compiler
8258
+ ? { ...appOptions, env: { ...appOptions.env, ...compiler } }
8259
+ : appOptions
8260
+ // clang consumes the real emitted headers after swift finishes.
8261
+ // swiftpm's transitive swift module maps are not C declarations:
8262
+ // importing them would shadow SDK modules such as ObjectiveC.
8263
+ const stages = [
8264
+ ...(preparation.nativePrerequisiteTargets ?? []).map((target) => ({
8265
+ target,
8266
+ producers: [],
8267
+ })),
8268
+ ...preparation.headerBuilds,
8269
+ ...(preparation.nativeProductTargets ?? []).map((target) => ({
8270
+ target,
8271
+ producers: [],
8272
+ })),
8273
+ ]
8274
+ const checkpoints = path.join(
8275
+ root,
8276
+ '.build',
8277
+ 'peach-product-checkpoints',
8278
+ )
8279
+ const buildDbExists = existsSync(path.join(root, '.build', 'build.db'))
8280
+ const releaseDir = path.dirname(linked)
8281
+ for (const { target, producers } of stages) {
8282
+ // pure native checkpoint stages exist only to commit build.db on cold
8283
+ // builds; when build.db and all stage objects are already warm, the
8284
+ // header stage and final full-graph build still validate every input.
8285
+ if (!options.project && producers.length === 0 && buildDbExists) {
8286
+ const expectedObjects = preparation.nativeStageObjects.get(target)
8287
+ if (
8288
+ expectedObjects &&
8289
+ expectedObjects.length > 0 &&
8290
+ expectedObjects.every((relative) =>
8291
+ statSync(path.join(releaseDir, relative), {
8292
+ throwIfNoEntry: false,
8293
+ })?.isFile(),
8294
+ )
8295
+ )
8296
+ continue
8297
+ }
8298
+ const receipt = path.join(
8299
+ checkpoints,
8300
+ createHash('sha256').update(target).digest('hex'),
8301
+ )
8302
+ const headers = producers.map(headerPaths)
8303
+ for (const header of headers)
8304
+ if (existsSync(header.original)) publishHeader(header)
8305
+ const fingerprint = (): string | undefined => {
8306
+ const digest = createHash('sha256').update(recipe)
8307
+ for (const { original, emitted } of headers) {
8308
+ if (!existsSync(original) || !existsSync(emitted)) return
8309
+ digest.update(
8310
+ createHash('sha256').update(readFileSync(emitted)).digest(),
8311
+ )
8312
+ }
8313
+ return digest.digest('hex')
8314
+ }
8315
+ if (
8316
+ !options.project &&
8317
+ existsSync(receipt) &&
8318
+ readFileSync(receipt, 'utf8') === fingerprint()
8319
+ )
8320
+ continue
8321
+ if (!options.project) rmSync(receipt, { force: true })
8322
+ // swiftpm doesn't track custom objc header paths as outputs.
8323
+ for (const header of headers) {
8324
+ if (!existsSync(header.original))
8325
+ rmSync(
8326
+ path.join(
8327
+ path.dirname(linked),
8328
+ 'Modules',
8329
+ `${swiftTargetModuleName(header.producer)}.swiftmodule`,
8330
+ ),
8331
+ { force: true },
8332
+ )
8333
+ }
8334
+ await runCompiler(
8335
+ swift,
8336
+ [...buildArgs, '--target', target],
8337
+ optionsWithCompiler,
8338
+ /^(?:\[swift-prebuilt\]|\[\d+\/\d+\] )/,
8339
+ SWIFTPM_NOISE,
8340
+ )
8341
+ if (!compiler) for (const header of headers) publishHeader(header)
8342
+ if (!options.project) {
8343
+ const checkpoint = fingerprint()
8344
+ if (checkpoint === undefined)
8345
+ throw new Error(`missing Swift headers after building ${target}`)
8346
+ mkdirSync(checkpoints, { recursive: true })
8347
+ writeFileSync(`${receipt}.partial`, checkpoint)
8348
+ renameSync(`${receipt}.partial`, receipt)
8349
+ }
8350
+ }
8351
+ // always let swiftpm check the full graph, including missing outputs.
8352
+ await runCompiler(
8353
+ swift,
8354
+ buildArgs,
8355
+ optionsWithCompiler,
8356
+ SWIFTPM_PROGRESS,
8357
+ SWIFTPM_NOISE,
8358
+ )
8359
+ }
8360
+ const compileApp = () =>
8361
+ preparation.headerCompiler
8362
+ ? withSwiftHeaderCompiler(
8363
+ root,
8364
+ toolchainBin,
8365
+ recipe,
8366
+ new Map(
8367
+ preparation.headerBuilds.flatMap(({ producers }) => {
8368
+ const driverJobs =
8369
+ batchGuest &&
8370
+ producers.length === 1 &&
8371
+ singleProducerJobs > guestDriverJobs
8372
+ ? singleProducerJobs
8373
+ : undefined
8374
+ return producers.map((producer) => {
8375
+ const paths = headerPaths(producer)
8376
+ return [
8377
+ swiftTargetModuleName(producer),
8378
+ {
8379
+ header: paths.original,
8380
+ publish: () => publishHeader(paths),
8381
+ jobs: driverJobs,
8382
+ },
8383
+ ] as const
8384
+ })
8385
+ }),
8386
+ ),
8387
+ runApp,
8388
+ )
8389
+ : runApp()
8347
8390
  try {
8391
+ if (temporaryDirectory)
8392
+ mkdirSync(temporaryDirectory, { recursive: true })
8348
8393
  await compileApp()
8349
- } catch (retryError) {
8394
+ } catch (error) {
8395
+ const output = outputOf(error)
8396
+ const moduleCache = path.join(
8397
+ root,
8398
+ '.build',
8399
+ WASM_TRIPLE,
8400
+ 'release',
8401
+ 'ModuleCache',
8402
+ )
8403
+ if (
8404
+ output.includes('was compiled with module cache path') &&
8405
+ existsSync(moduleCache)
8406
+ ) {
8407
+ rmSync(moduleCache, { recursive: true, force: true })
8408
+ try {
8409
+ await compileApp()
8410
+ } catch (retryError) {
8411
+ throw new Error(
8412
+ [
8413
+ ...unprepared,
8414
+ projectDiagnostic(outputOf(retryError), layout, input.files),
8415
+ ].join('\n'),
8416
+ { cause: retryError },
8417
+ )
8418
+ }
8419
+ } else {
8420
+ throw new Error(
8421
+ [
8422
+ ...unprepared,
8423
+ projectDiagnostic(output, layout, input.files),
8424
+ ].join('\n'),
8425
+ { cause: error },
8426
+ )
8427
+ }
8428
+ } finally {
8429
+ if (temporaryDirectory)
8430
+ rmSync(temporaryDirectory, { recursive: true, force: true })
8431
+ // a manifest, macro or build tool can leave processes behind that
8432
+ // outlive the compiler's own group; none runs once the host reads.
8433
+ if (options.project) endSwiftProjectProcesses(options.project)
8434
+ }
8435
+ if (unprepared.length) throw new Error(unprepared.join('\n'))
8436
+ if (!existsSync(linked)) {
8437
+ const binDir = path.dirname(linked)
8438
+ const found = existsSync(binDir)
8439
+ ? readdirSync(binDir)
8440
+ .filter((name) => name.endsWith('.wasm'))
8441
+ .sort()
8442
+ : []
8350
8443
  throw new Error(
8351
- [
8352
- ...unprepared,
8353
- projectDiagnostic(outputOf(retryError), layout, input.files),
8354
- ].join('\n'),
8355
- { cause: retryError },
8444
+ `swift-compile: the build produced no ${path.basename(linked)} (found: ${found.join(', ') || 'none'})`,
8356
8445
  )
8357
8446
  }
8358
- } else {
8359
- throw new Error(
8360
- [...unprepared, projectDiagnostic(output, layout, input.files)].join(
8361
- '\n',
8362
- ),
8363
- { cause: error },
8447
+ if (options.project) removeProjectLinks(root)
8448
+ const resourceReferences = Object.values(input.resources ?? {}).map(
8449
+ (value) => Buffer.from(value, 'base64'),
8364
8450
  )
8451
+ // the guest link prunes and links the response file itself.
8452
+ if (!guestGraph)
8453
+ pruneSwiftWasmLink(
8454
+ root,
8455
+ toolchainBin,
8456
+ prebuilt?.root ?? frameworkRoot,
8457
+ input.staticClangTargets,
8458
+ options.project,
8459
+ undefined,
8460
+ resourceReferences,
8461
+ )
8462
+ if (options.linkOnly) {
8463
+ if (statSync(linked).size <= 8)
8464
+ throw new Error(
8465
+ 'swift-compile: deferred linker produced no executable',
8466
+ )
8467
+ stage('project link verified')
8468
+ // the sdk image relinks the response while its framework objects are still held.
8469
+ if (readHold && retainSwiftRootReadHold(readHold)) readHold = undefined
8470
+ return
8471
+ }
8472
+ const output = options.project
8473
+ ? projectOutputFile(root, linked, options.project)
8474
+ : linked
8475
+ const optimized = `${output}.optimized`
8476
+ if (!sdkImage) throw new Error('swift-compile: missing shared SDK image')
8477
+ if (options.project) rmSync(optimized, { force: true })
8478
+ let sdkAsset: SwiftSdkModuleAsset
8479
+ stage('linking the app image')
8480
+ if (guestGraph) {
8481
+ const binding = await compileGuestLink({
8482
+ graph: guestGraph,
8483
+ buildDirectory: root,
8484
+ releaseDirectory: path.dirname(linked),
8485
+ moduleRoot: frameworkRoot,
8486
+ toolchainBin,
8487
+ swiftCompiler: preparation.headerCompiler
8488
+ ? path.join(root, SWIFT_HEADER_COMPILER_WRAPPER)
8489
+ : (compiler.SWIFT_EXEC ?? path.join(toolchainBin, 'swiftc')),
8490
+ sysroot: compileSdkPaths.sysroot,
8491
+ sdk: swiftModuleSdk(frameworkRoot),
8492
+ sdkImage,
8493
+ compilerDigest: compilerSourceDigest,
8494
+ project: options.project && {
8495
+ ...options.project,
8496
+ env: { ...options.project.env, ...projectProcess?.env },
8497
+ },
8498
+ staticClangTargets: input.staticClangTargets ?? [],
8499
+ resourceReferences,
8500
+ resourceBundles: input.resourceBundles ?? [],
8501
+ generatedOwners: preparation.generatedOwners,
8502
+ output,
8503
+ optimized,
8504
+ optimize: input.optimize === true,
8505
+ jobs: swiftBuildJobs(),
8506
+ onStage: stage,
8507
+ })
8508
+ sdkAsset = { key: sdkImage.key, sha256: sdkImage.sha256, binding }
8509
+ } else {
8510
+ const { buildSwiftAppModule } = await import('./swift-sdk-app-module')
8511
+ const binding = await buildSwiftAppModule({
8512
+ buildRoot: root,
8513
+ toolchainBin,
8514
+ sdk: sdkImage,
8515
+ output: optimized,
8516
+ optimize: input.optimize === true,
8517
+ project: options.project && {
8518
+ ...options.project,
8519
+ env: { ...options.project.env, ...projectProcess?.env },
8520
+ sdkRoot: path.dirname(compileSdkPaths.sysroot),
8521
+ linked: output,
8522
+ },
8523
+ })
8524
+ sdkAsset = { key: sdkImage.key, sha256: sdkImage.sha256, binding }
8525
+ }
8526
+ const artifact = {
8527
+ hash,
8528
+ bytes: readFileSync(optimized),
8529
+ icu: await icu!,
8530
+ sdk: sdkAsset,
8531
+ }
8532
+ if (artifact.bytes.length <= 8)
8533
+ throw new Error('swift-compile: deferred linker produced no executable')
8534
+ if (!options.project) saveCompiledArtifact(root, artifact)
8535
+ saveSharedArtifact(sharedRoot, artifact)
8536
+ stage('compiled artifact verified')
8537
+ return retain(baseRoot, artifact)
8538
+ } finally {
8539
+ readHold?.release()
8365
8540
  }
8366
- } finally {
8367
- if (temporaryDirectory)
8368
- rmSync(temporaryDirectory, { recursive: true, force: true })
8369
- // a manifest, macro or build tool can leave processes behind that
8370
- // outlive the compiler's own group; none runs once the host reads.
8371
- if (options.project) endSwiftProjectProcesses(options.project)
8372
- }
8373
- if (unprepared.length) throw new Error(unprepared.join('\n'))
8374
- if (!existsSync(linked)) {
8375
- const binDir = path.dirname(linked)
8376
- const found = existsSync(binDir)
8377
- ? readdirSync(binDir)
8378
- .filter((name) => name.endsWith('.wasm'))
8379
- .sort()
8380
- : []
8381
- throw new Error(
8382
- `swift-compile: the build produced no ${path.basename(linked)} (found: ${found.join(', ') || 'none'})`,
8383
- )
8384
- }
8385
- if (options.project) removeProjectLinks(root)
8386
- const resourceReferences = Object.values(input.resources ?? {}).map((value) =>
8387
- Buffer.from(value, 'base64'),
8388
- )
8389
- // the guest link prunes and links the response file itself.
8390
- if (!guestGraph)
8391
- pruneSwiftWasmLink(
8392
- root,
8393
- options.toolchainBin,
8394
- prebuilt?.root ?? frameworkRoot,
8395
- input.staticClangTargets,
8396
- options.project,
8397
- undefined,
8398
- resourceReferences,
8399
- )
8400
- if (options.linkOnly) {
8401
- if (statSync(linked).size <= 8)
8402
- throw new Error('swift-compile: deferred linker produced no executable')
8403
- stage('project link verified')
8404
- // the sdk image relinks the response while its framework objects are still held.
8405
- if (readHold && retainSwiftRootReadHold(readHold)) readHold = undefined
8406
- return
8407
- }
8408
- const output = options.project
8409
- ? projectOutputFile(root, linked, options.project)
8410
- : linked
8411
- const optimized = `${output}.optimized`
8412
- if (!sdkImage) throw new Error('swift-compile: missing shared SDK image')
8413
- if (options.project) rmSync(optimized, { force: true })
8414
- let sdkAsset: SwiftSdkModuleAsset
8415
- stage('linking the app image')
8416
- if (guestGraph) {
8417
- const binding = await compileGuestLink({
8418
- graph: guestGraph,
8419
- buildDirectory: root,
8420
- releaseDirectory: path.dirname(linked),
8421
- moduleRoot: frameworkRoot,
8422
- toolchainBin: options.toolchainBin,
8423
- swiftCompiler: preparation.headerCompiler
8424
- ? path.join(root, SWIFT_HEADER_COMPILER_WRAPPER)
8425
- : (compiler.SWIFT_EXEC ?? path.join(options.toolchainBin, 'swiftc')),
8426
- sysroot: compileSdkPaths.sysroot,
8427
- sdk: swiftModuleSdk(frameworkRoot),
8428
- sdkImage,
8429
- compilerDigest: compilerSourceDigest,
8430
- project: options.project && {
8431
- ...options.project,
8432
- env: { ...options.project.env, ...projectProcess?.env },
8433
- },
8434
- staticClangTargets: input.staticClangTargets ?? [],
8435
- resourceReferences,
8436
- resourceBundles: input.resourceBundles ?? [],
8437
- generatedOwners: preparation.generatedOwners,
8438
- output,
8439
- optimized,
8440
- optimize: input.optimize === true,
8441
- jobs: swiftBuildJobs(),
8442
- onStage: stage,
8443
- })
8444
- sdkAsset = { key: sdkImage.key, sha256: sdkImage.sha256, binding }
8445
- } else {
8446
- const { buildSwiftAppModule } = await import('./swift-sdk-app-module')
8447
- const binding = await buildSwiftAppModule({
8448
- buildRoot: root,
8449
- toolchainBin: options.toolchainBin,
8450
- sdk: sdkImage,
8451
- output: optimized,
8452
- optimize: input.optimize === true,
8453
- project: options.project && {
8454
- ...options.project,
8455
- env: { ...options.project.env, ...projectProcess?.env },
8456
- sdkRoot: path.dirname(compileSdkPaths.sysroot),
8457
- linked: output,
8458
- },
8459
- })
8460
- sdkAsset = { key: sdkImage.key, sha256: sdkImage.sha256, binding }
8461
- }
8462
- const artifact = {
8463
- hash,
8464
- bytes: readFileSync(optimized),
8465
- icu: await icu!,
8466
- sdk: sdkAsset,
8467
- }
8468
- if (artifact.bytes.length <= 8)
8469
- throw new Error('swift-compile: deferred linker produced no executable')
8470
- if (!options.project) saveCompiledArtifact(root, artifact)
8471
- saveSharedArtifact(sharedRoot, artifact)
8472
- stage('compiled artifact verified')
8473
- return retain(baseRoot, artifact)
8474
- } finally {
8475
- readHold?.release()
8476
- }
8477
- })
8478
- })
8479
- },
8480
- options.signal,
8481
- )
8541
+ })
8542
+ },
8543
+ )
8544
+ },
8545
+ options.signal,
8546
+ )
8547
+ })
8482
8548
  }