peachsim 0.1.2606 → 0.1.2607

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 (133) hide show
  1. package/cli/commands/package.ts +71 -39
  2. package/cli/commands/perf-native.ts +259 -6
  3. package/cli/commands/shell-url.ts +1 -0
  4. package/dist-lib/agent-daemon-client.cjs +1 -1
  5. package/dist-lib/agent-events.cjs +1 -1
  6. package/dist-lib/attached-projects.cjs +1 -1
  7. package/dist-lib/auth/shared-session.cjs +1 -1
  8. package/dist-lib/backend-origin.cjs +1 -1
  9. package/dist-lib/beta.cjs +1 -1
  10. package/dist-lib/beta.mjs +2 -2
  11. package/dist-lib/bridge-constants.cjs +1 -1
  12. package/dist-lib/bridge-contract-input.cjs +1 -1
  13. package/dist-lib/bridge-contract-input.mjs +5 -5
  14. package/dist-lib/bridge-contract.cjs +1 -1
  15. package/dist-lib/bridge-contract.mjs +3 -3
  16. package/dist-lib/bundle-channel.cjs +815 -674
  17. package/dist-lib/capture-contract.cjs +1 -1
  18. package/dist-lib/capture-contract.mjs +3 -3
  19. package/dist-lib/cloud-contract.cjs +1 -1
  20. package/dist-lib/cloud-contract.mjs +3 -3
  21. package/dist-lib/cloud-test-args.cjs +1 -1
  22. package/dist-lib/cloud-test-args.mjs +2 -2
  23. package/dist-lib/cloud.cjs +1 -1
  24. package/dist-lib/cloud.mjs +7 -7
  25. package/dist-lib/config.cjs +1 -1
  26. package/dist-lib/config.mjs +5 -5
  27. package/dist-lib/detox/index.cjs +1 -1
  28. package/dist-lib/dev-bundle-resolution.cjs +1 -1
  29. package/dist-lib/esm-chunks/{acorn-UL7Z3WUQ.mjs → acorn-KFWXYMX5.mjs} +3 -3
  30. package/dist-lib/esm-chunks/{chunk-EXB4QSQI.mjs → chunk-6JPUMAC2.mjs} +1 -1
  31. package/dist-lib/esm-chunks/{chunk-CPMK3DA6.mjs → chunk-6NDABMDX.mjs} +3 -3
  32. package/dist-lib/esm-chunks/{chunk-5JMW5G3U.mjs → chunk-7SKDPTZN.mjs} +1 -1
  33. package/dist-lib/esm-chunks/{chunk-MBCSJQRY.mjs → chunk-ACAXWH62.mjs} +1 -1
  34. package/dist-lib/esm-chunks/{chunk-25LYRBSX.mjs → chunk-ARYRQJUB.mjs} +1 -1
  35. package/dist-lib/esm-chunks/{chunk-KWLQDES2.mjs → chunk-BNAXRY5Q.mjs} +1 -1
  36. package/dist-lib/esm-chunks/{chunk-VTZJPPTE.mjs → chunk-CA64UUHF.mjs} +1 -1
  37. package/dist-lib/esm-chunks/{chunk-OB5XSLW6.mjs → chunk-DBW62F4N.mjs} +3 -2
  38. package/dist-lib/esm-chunks/{chunk-RTPUFY2K.mjs → chunk-ESS2CG5G.mjs} +5 -5
  39. package/dist-lib/esm-chunks/{chunk-O6NRI4T2.mjs → chunk-IGSLOAPL.mjs} +1 -1
  40. package/dist-lib/esm-chunks/{chunk-5ANQR24T.mjs → chunk-KIIALACX.mjs} +1 -1
  41. package/dist-lib/esm-chunks/{chunk-66ESCMV3.mjs → chunk-LJZ373SO.mjs} +818 -678
  42. package/dist-lib/esm-chunks/{chunk-TVICD24H.mjs → chunk-M4ORY3NH.mjs} +1 -1
  43. package/dist-lib/esm-chunks/{chunk-34CIYRB7.mjs → chunk-MBWWOGI5.mjs} +4 -4
  44. package/dist-lib/esm-chunks/{chunk-QFASF6EH.mjs → chunk-O5BPZVLB.mjs} +5 -5
  45. package/dist-lib/esm-chunks/{chunk-L7FPUZZO.mjs → chunk-P5Q5QCTP.mjs} +1 -1
  46. package/dist-lib/esm-chunks/{chunk-B7AXR7WA.mjs → chunk-QJUAWJDB.mjs} +1 -1
  47. package/dist-lib/esm-chunks/{chunk-O6ZNRBLB.mjs → chunk-RIDXKGBZ.mjs} +1 -1
  48. package/dist-lib/esm-chunks/{chunk-WJKACRMG.mjs → chunk-TD2DBEKQ.mjs} +1 -1
  49. package/dist-lib/esm-chunks/{chunk-E2TASYAA.mjs → chunk-UTSB5CDG.mjs} +1 -1
  50. package/dist-lib/esm-chunks/{chunk-PLOV7VQQ.mjs → chunk-WMWOBH7E.mjs} +1 -1
  51. package/dist-lib/esm-chunks/{chunk-XUWYWP35.mjs → chunk-ZNGLVJYL.mjs} +1 -1
  52. package/dist-lib/esm-chunks/{metro-layout-parser-OMUFYOJI.mjs → metro-layout-parser-UY3B6VGU.mjs} +3 -3
  53. package/dist-lib/esm-chunks/{swift-package-prebuilt-X7EZCX34.mjs → swift-package-prebuilt-HDHPWS44.mjs} +10 -10
  54. package/dist-lib/esm-chunks/{swift-sdk-app-module-E3IF2XPD.mjs → swift-sdk-app-module-U6G5RZV2.mjs} +14 -14
  55. package/dist-lib/esm-chunks/{swift-sdk-image-57YYLNU6.mjs → swift-sdk-image-PVDA2MVM.mjs} +14 -14
  56. package/dist-lib/esm-chunks/{swift-sdk-image-producer-DZOZTTDZ.mjs → swift-sdk-image-producer-YHPS3KNR.mjs} +4 -4
  57. package/dist-lib/expo-swift-bundle.cjs +814 -673
  58. package/dist-lib/expo-swift-metadata.cjs +1 -1
  59. package/dist-lib/expo-swift-metadata.mjs +7 -7
  60. package/dist-lib/home-paths.cjs +1 -1
  61. package/dist-lib/host/bridge-host.cjs +959 -676
  62. package/dist-lib/host/fetch-proxy-handler.cjs +6 -5
  63. package/dist-lib/host/fetch-proxy-overrides.cjs +1 -1
  64. package/dist-lib/host/fetch-proxy-overrides.mjs +2 -2
  65. package/dist-lib/host/replacement-module-handler.cjs +1 -1
  66. package/dist-lib/host/websocket-proxy.cjs +1 -1
  67. package/dist-lib/index.cjs +1 -1
  68. package/dist-lib/kotlin-host.cjs +1 -1
  69. package/dist-lib/menu.cjs +1 -1
  70. package/dist-lib/menu.mjs +3 -3
  71. package/dist-lib/metro-fingerprint-registry.cjs +1 -1
  72. package/dist-lib/metro-fingerprint-registry.mjs +3 -3
  73. package/dist-lib/metro-production-bundle.cjs +1 -1
  74. package/dist-lib/metro-production-bundle.mjs +4 -4
  75. package/dist-lib/native-app-identity-project.cjs +6 -4
  76. package/dist-lib/native-app-identity-project.mjs +17 -17
  77. package/dist-lib/native-app-identity.cjs +1 -1
  78. package/dist-lib/native-app-identity.mjs +6 -6
  79. package/dist-lib/native-firebase-metadata.cjs +1 -1
  80. package/dist-lib/native-firebase-metadata.mjs +3 -3
  81. package/dist-lib/pdfium-raster.cjs +1 -1
  82. package/dist-lib/pdfium-raster.mjs +2 -2
  83. package/dist-lib/plist.cjs +1 -1
  84. package/dist-lib/plist.mjs +3 -3
  85. package/dist-lib/profiles.cjs +1 -1
  86. package/dist-lib/public-brand.cjs +1 -1
  87. package/dist-lib/public-origins-lib-esm.json +81 -81
  88. package/dist-lib/public-origins-lib.json +64 -64
  89. package/dist-lib/react-native-host-modules.cjs +1 -1
  90. package/dist-lib/react-native-host-modules.mjs +2 -2
  91. package/dist-lib/reap-browser.cjs +1 -1
  92. package/dist-lib/scripts/dev-server-scanner.cjs +1 -1
  93. package/dist-lib/sdk.cjs +1 -1
  94. package/dist-lib/sdk.mjs +8 -8
  95. package/dist-lib/skills.cjs +959 -676
  96. package/dist-lib/swift-compile.cjs +811 -670
  97. package/dist-lib/swift-compile.mjs +10 -10
  98. package/dist-lib/swift-package.cjs +1 -1
  99. package/dist-lib/swift-package.mjs +3 -3
  100. package/dist-lib/swift-submit.cjs +1 -1
  101. package/dist-lib/swift-submit.mjs +6 -6
  102. package/dist-lib/swift-svg-raster.cjs +1 -1
  103. package/dist-lib/swift-svg-raster.mjs +2 -2
  104. package/dist-lib/swift-toolchain.cjs +3 -2
  105. package/dist-lib/swift.cjs +1 -1
  106. package/dist-lib/vendor/@peculiar/x509.cjs +1 -1
  107. package/dist-lib/vendor/@ruby/prism/src/nodes.js.cjs +1 -1
  108. package/dist-lib/vendor/@ruby/prism/src/parsePrism.js.cjs +1 -1
  109. package/dist-lib/vendor/acorn.cjs +1 -1
  110. package/dist-lib/vendor/magic-string.cjs +1 -1
  111. package/dist-lib/vendor/stream-json.cjs +1 -1
  112. package/dist-lib/vendor/sucrase/dist/index.js.cjs +1 -1
  113. package/dist-lib/vendor/sucrase/dist/parser/index.js.cjs +1 -1
  114. package/dist-lib/vendor/sucrase/dist/parser/tokenizer/index.js.cjs +1 -1
  115. package/dist-lib/vendor/sucrase/dist/parser/tokenizer/types.js.cjs +1 -1
  116. package/dist-lib/vendor/sucrase.cjs +1 -1
  117. package/dist-lib/vendor/terser.cjs +1 -1
  118. package/dist-lib/vendor/valibot.cjs +1 -1
  119. package/dist-lib/vendor/ws.cjs +1 -1
  120. package/dist-lib/vendor/zod.cjs +1 -1
  121. package/dist-lib/worklet-executable.cjs +1 -1
  122. package/dist-lib/worklet-executable.mjs +3 -3
  123. package/dist-types/packages/peach-engine/src/ios/apps/canvas-map-data.d.ts +38 -2
  124. package/dist-types/packages/peach-globals/src/canvasAgentContract.d.ts +8 -0
  125. package/dist-types/packages/peach-globals/src/index.d.ts +1 -1
  126. package/package.json +1 -1
  127. package/src/agent-prompt.ts +5 -1
  128. package/src/one-native-controls-package.ts +143 -1
  129. package/src/oneNativeControlsContract.ts +1 -0
  130. package/src/swift-compile-budget.ts +28 -7
  131. package/src/swift-compile.ts +968 -803
  132. package/src/swift-guest-compile.ts +3 -0
  133. package/src/swift-toolchain.ts +4 -1
@@ -208,6 +208,7 @@ export {
208
208
  // `stream` echoes the output as it arrives: all of it, or only matching lines.
209
209
  // a successful run then echoes the rest minus lines matching `quiet`, its
210
210
  // warnings; a failed run's output goes to the caller's one diagnostic.
211
+ // `timeout` bounds silence: each output chunk restarts it and calls `onOutput`.
211
212
  async function runCompiler(
212
213
  command: string,
213
214
  args: string[],
@@ -218,6 +219,7 @@ async function runCompiler(
218
219
  temporaryDirectory?: string
219
220
  /** applied over the confined scratch environment, for a child that cannot use the host's. */
220
221
  confined?: Record<string, string>
222
+ onOutput?: () => void
221
223
  },
222
224
  stream: boolean | RegExp = false,
223
225
  quiet?: RegExp,
@@ -253,8 +255,18 @@ async function runCompiler(
253
255
  // close and cancellation share the same awaited cleanup below.
254
256
  void stopping.catch(() => {})
255
257
  }
258
+ const restartTimeout = () => {
259
+ if (!options.timeout) return
260
+ clearTimeout(timeout)
261
+ timeout = setTimeout(() => {
262
+ failure = new Error(`Swift compiler was silent for ${options.timeout}ms`)
263
+ stop()
264
+ }, options.timeout)
265
+ }
256
266
  for (const name of ['stdout', 'stderr'] as const) {
257
267
  child[name].on('data', (bytes: Buffer) => {
268
+ restartTimeout()
269
+ options.onOutput?.()
258
270
  if (stream === true) process[name].write(bytes)
259
271
  else if (stream) {
260
272
  const lines = (partial[name] + bytes.toString()).split('\n')
@@ -302,11 +314,7 @@ async function runCompiler(
302
314
  resolve(Buffer.concat(chunks.stdout).toString())
303
315
  }
304
316
  })
305
- if (options.timeout)
306
- timeout = setTimeout(() => {
307
- failure = new Error('Swift compiler timed out')
308
- stop()
309
- }, options.timeout)
317
+ restartTimeout()
310
318
  if (signal?.aborted) stop()
311
319
  })
312
320
  } finally {
@@ -7872,10 +7880,12 @@ type FrameworkBuildArgs = {
7872
7880
  signal?: AbortSignal
7873
7881
  lease?: SwiftRootLease
7874
7882
  frameworkLease?: SwiftRootLease
7883
+ onOutput?: () => void
7875
7884
  }
7876
7885
  }
7877
7886
 
7878
7887
  const frameworkProductsReceiptSchema = v.object({
7888
+ root: v.string(),
7879
7889
  modules: v.string(),
7880
7890
  objects: v.array(v.string()),
7881
7891
  lazyObjects: v.array(v.string()),
@@ -7902,25 +7912,18 @@ function readFrameworkProductsReceipt(
7902
7912
  } catch {
7903
7913
  return null
7904
7914
  }
7905
- const archive = path.join(scratch, 'lib')
7906
- const archiveStamp = path.join(archive, '.receipt')
7907
- const archiveMatches =
7908
- existsSync(archiveStamp) && readFileSync(archiveStamp, 'utf8') === receiptKey
7915
+ const archiveRoot = path.join(scratch, 'products-lib', receiptKey)
7916
+ if (parsed.root !== archiveRoot) return null
7909
7917
  if (!existsSync(parsed.modules)) return null
7910
- for (const [object] of parsed.archived) if (!existsSync(object)) return null
7918
+ for (const [object, rel] of parsed.archived) {
7919
+ if (!existsSync(object) || !existsSync(path.join(archiveRoot, rel))) return null
7920
+ }
7911
7921
  for (const file of parsed.providers) if (!existsSync(file)) return null
7912
7922
  for (const file of parsed.moduleMaps) if (!existsSync(file)) return null
7913
- if (!archiveMatches) {
7914
- rmSync(archive, { recursive: true, force: true })
7915
- mkdirSync(archive, { recursive: true })
7916
- for (const [object, rel] of parsed.archived)
7917
- symlinkSync(object, path.join(scratch, rel))
7918
- writeFileSync(archiveStamp, receiptKey)
7919
- }
7920
7923
  for (const file of parsed.objects) if (!existsSync(file)) return null
7921
7924
  for (const file of parsed.lazyObjects) if (!existsSync(file)) return null
7922
7925
  return {
7923
- root: scratch,
7926
+ root: parsed.root,
7924
7927
  modules: parsed.modules,
7925
7928
  objects: parsed.objects,
7926
7929
  lazyObjects: parsed.lazyObjects,
@@ -7943,7 +7946,7 @@ async function buildFrameworkProducts(
7943
7946
  const receiptKey = createHash('sha256')
7944
7947
  .update(
7945
7948
  JSON.stringify([
7946
- 'framework-products/v1',
7949
+ 'framework-products/v2',
7947
7950
  args.frameworkKey,
7948
7951
  unoptimized,
7949
7952
  args.sdk,
@@ -8130,33 +8133,47 @@ async function buildFrameworkProducts(
8130
8133
  // the framework objects link as a distribution's do: under lib/ with the names
8131
8134
  // build-distribution.ts gives them, Objective-C roots whole and the rest as an
8132
8135
  // archive region the pruner trims (swift-wasm-prune.ts reads <root>/lib).
8136
+ // each receipt owns an immutable archive root so simultaneous apps with
8137
+ // different linked product sets never delete or relink a reader's lib/.
8133
8138
  // Darwin stays whole: a distribution leaves it to the sdk's image.
8134
- const archive = path.join(scratch, 'lib')
8135
- rmSync(archive, { recursive: true, force: true })
8136
- mkdirSync(archive)
8139
+ const archiveBase = path.join(scratch, 'products-lib')
8140
+ mkdirSync(archiveBase, { recursive: true })
8141
+ const archiveRoot = path.join(archiveBase, receiptKey)
8142
+ const stagedArchiveRoot = `${archiveRoot}.tmp-${process.pid}-${randomUUID()}`
8143
+ const stagedArchive = path.join(stagedArchiveRoot, 'lib')
8144
+ mkdirSync(stagedArchive, { recursive: true })
8137
8145
  const archived = new Map<string, string>()
8138
- for (const object of objects) {
8139
- const target = linked.owners.get(object)
8140
- const dir = path.join(release, `${target}.build`)
8141
- if (!target || target === 'Darwin' || !object.startsWith(dir + path.sep)) continue
8142
- const name = `${target}-${path
8143
- .relative(dir, object)
8144
- .replaceAll(path.sep, '-')
8145
- .replace(/\.swift\.o$/, '.o')}`
8146
- symlinkSync(object, path.join(archive, name))
8147
- archived.set(object, `lib/${name}`)
8148
- }
8149
- const roots = swiftObjcRootObjects(`${scratch}\n${args.frameworkKey}`, scratch, [
8150
- ...archived.values(),
8151
- ])
8146
+ try {
8147
+ for (const object of objects) {
8148
+ const target = linked.owners.get(object)
8149
+ const dir = path.join(release, `${target}.build`)
8150
+ if (!target || target === 'Darwin' || !object.startsWith(dir + path.sep)) continue
8151
+ const name = `${target}-${path
8152
+ .relative(dir, object)
8153
+ .replaceAll(path.sep, '-')
8154
+ .replace(/\.swift\.o$/, '.o')}`
8155
+ symlinkSync(object, path.join(stagedArchive, name))
8156
+ archived.set(object, `lib/${name}`)
8157
+ }
8158
+ rmSync(archiveRoot, { recursive: true, force: true })
8159
+ renameSync(stagedArchiveRoot, archiveRoot)
8160
+ } catch (error) {
8161
+ rmSync(stagedArchiveRoot, { recursive: true, force: true })
8162
+ throw error
8163
+ }
8164
+ const roots = swiftObjcRootObjects(
8165
+ `${archiveRoot}\n${args.frameworkKey}`,
8166
+ archiveRoot,
8167
+ [...archived.values()],
8168
+ )
8152
8169
  const linkedObjects = objects.map((object) => {
8153
8170
  const name = archived.get(object)
8154
8171
  return name
8155
- ? { path: path.join(scratch, name), lazy: !roots.has(name) }
8172
+ ? { path: path.join(archiveRoot, name), lazy: !roots.has(name) }
8156
8173
  : { path: object, lazy: false }
8157
8174
  })
8158
8175
  const result: SwiftFrameworkProducts = {
8159
- root: scratch,
8176
+ root: archiveRoot,
8160
8177
  modules: path.join(release, 'Modules'),
8161
8178
  objects: linkedObjects.filter((object) => !object.lazy).map((object) => object.path),
8162
8179
  lazyObjects: linkedObjects
@@ -8168,7 +8185,6 @@ async function buildFrameworkProducts(
8168
8185
  moduleMaps: linked.moduleMaps,
8169
8186
  objcHeaders: linked.objcHeaders,
8170
8187
  }
8171
- writeFileSync(path.join(archive, '.receipt'), receiptKey)
8172
8188
  const receiptsDir = path.join(scratch, 'products-ready')
8173
8189
  mkdirSync(receiptsDir, { recursive: true })
8174
8190
  const receiptFile = path.join(receiptsDir, `${receiptKey}.json`)
@@ -8176,6 +8192,7 @@ async function buildFrameworkProducts(
8176
8192
  writeFileSync(
8177
8193
  partialReceipt,
8178
8194
  JSON.stringify({
8195
+ root: result.root,
8179
8196
  modules: result.modules,
8180
8197
  objects: result.objects,
8181
8198
  lazyObjects: result.lazyObjects,
@@ -8207,6 +8224,10 @@ const SWIFT_FRAMEWORK_SLOTS = 8
8207
8224
  const SWIFT_FRAMEWORK_UNOPTIMIZED_SLOTS = 4
8208
8225
  const SWIFT_FRAMEWORK_SLOT_KEY = '.peach-framework-key'
8209
8226
  const SWIFT_FRAMEWORK_SLOT_ORIGIN = '.peach-framework-origin'
8227
+ const SWIFT_FRAMEWORK_SLOT_RELEASE = '.peach-framework-release'
8228
+
8229
+ const SWIFT_BUILD_ROOT_SLOTS = 4
8230
+ const SWIFT_BUILD_ROOT_SHAPE = '.peach-build-shape'
8210
8231
 
8211
8232
  function swiftFrameworksDir(unoptimized = false): string {
8212
8233
  return path.join(
@@ -8228,8 +8249,13 @@ function swiftFrameworkSlotKey(slot: string): string | null {
8228
8249
  return swiftFrameworkSlotRecord(slot, SWIFT_FRAMEWORK_SLOT_KEY)
8229
8250
  }
8230
8251
 
8252
+ function swiftFrameworkSlotRelease(slot: string): string | null {
8253
+ return swiftFrameworkSlotRecord(slot, SWIFT_FRAMEWORK_SLOT_RELEASE)
8254
+ }
8255
+
8231
8256
  async function withSwiftFrameworkSlot<T>(
8232
8257
  frameworkKey: string,
8258
+ release: string,
8233
8259
  moduleRoot: string,
8234
8260
  signal: AbortSignal | undefined,
8235
8261
  work: (slot: string, lease: SwiftRootLease) => Promise<T>,
@@ -8261,12 +8287,18 @@ async function withSwiftFrameworkSlot<T>(
8261
8287
  readFileSync(path.join(moduleRoot, file)),
8262
8288
  ]),
8263
8289
  )
8264
- // a new builder workspace has no origin match; choose by source bytes so it
8265
- // inherits the nearest revision's products instead of an empty or old tree.
8290
+ // swiftc's swift-version hash invalidates every framework target when a slot
8291
+ // switches compiler release. keep each compiler release in its own slot:
8292
+ // tier 0 reuses a warm slot from the same release (nearest source revision),
8293
+ // tier 1 takes an empty slot, and tier 2 evicts another release only LRU when
8294
+ // all slots are full.
8266
8295
  const ranked = slots
8267
- .map((slot) => {
8296
+ .map((slot, index) => {
8297
+ const slotKey = swiftFrameworkSlotKey(slot)
8298
+ if (slotKey === null) return { slot, index, tier: 1, changes: Infinity }
8299
+ if (swiftFrameworkSlotRelease(slot) !== release)
8300
+ return { slot, index, tier: 2, changes: Infinity }
8268
8301
  let changes = 0
8269
- if (swiftFrameworkSlotKey(slot) === null) return { slot, changes: Infinity }
8270
8302
  const source = path.join(slot, 'source', 'packages', path.basename(moduleRoot))
8271
8303
  for (const [file, contents] of inputs) {
8272
8304
  try {
@@ -8281,22 +8313,27 @@ async function withSwiftFrameworkSlot<T>(
8281
8313
  changes++
8282
8314
  }
8283
8315
  }
8284
- return { slot, changes }
8316
+ return { slot, index, tier: 0, changes }
8285
8317
  })
8286
- .sort(
8287
- (left, right) =>
8288
- left.changes - right.changes ||
8289
- Number(own(right.slot)) - Number(own(left.slot)) ||
8290
- (built.get(right.slot) ?? 0) - (built.get(left.slot) ?? 0),
8291
- )
8292
- for (const { slot, changes } of ranked) {
8318
+ .sort((left, right) => {
8319
+ if (left.tier !== right.tier) return left.tier - right.tier
8320
+ if (left.tier === 0)
8321
+ return (
8322
+ left.changes - right.changes ||
8323
+ Number(own(right.slot)) - Number(own(left.slot)) ||
8324
+ (built.get(right.slot) ?? 0) - (built.get(left.slot) ?? 0)
8325
+ )
8326
+ if (left.tier === 1) return left.index - right.index
8327
+ return (built.get(left.slot) ?? 0) - (built.get(right.slot) ?? 0)
8328
+ })
8329
+ for (const { slot, tier, changes } of ranked) {
8293
8330
  if (await hasLiveSwiftRootReaders(slot, signal)) continue
8294
8331
  const result = await withSwiftRootLock(
8295
8332
  slot,
8296
8333
  async (lease) => {
8297
8334
  if (await hasLiveSwiftRootReaders(slot, signal)) return undefined
8298
8335
  console.error(
8299
- `[swift-framework-cache] ${path.basename(slot)} changedInputs=${changes} totalInputs=${inputs.size}`,
8336
+ `[swift-framework-cache] ${path.basename(slot)} release=${release} tier=${tier} changedInputs=${changes} totalInputs=${inputs.size}`,
8300
8337
  )
8301
8338
  return { value: await run(slot)(lease) }
8302
8339
  },
@@ -8309,6 +8346,56 @@ async function withSwiftFrameworkSlot<T>(
8309
8346
  return withSwiftRootLock(nearest, run(nearest), signal)
8310
8347
  }
8311
8348
 
8349
+ // normalized shared build roots (such as OneNativeControls) serve concurrent
8350
+ // callers with different inputs or target shapes. callers hold the per-hash
8351
+ // sharedRoot lock before entering here so identical concurrent builds never
8352
+ // race onto two slots, while distinct hashes claim idle matching or empty
8353
+ // slots without blocking or thrashing each other's incremental objects.
8354
+ async function withSwiftBuildRootSlot<T>(
8355
+ baseRoot: string,
8356
+ buildShape: string,
8357
+ signal: AbortSignal | undefined,
8358
+ work: (slotRoot: string, lease: SwiftRootLease, waitedMs: number) => Promise<T>,
8359
+ ): Promise<T> {
8360
+ const slots = Array.from({ length: SWIFT_BUILD_ROOT_SLOTS }, (_, index) => {
8361
+ const slot = index === 0 ? baseRoot : `${baseRoot}-s${index}`
8362
+ mkdirSync(slot, { recursive: true })
8363
+ return slot
8364
+ })
8365
+ const runInSlot = (slot: string, waitStart: number) => (lease: SwiftRootLease) => {
8366
+ const waitedMs = Date.now() - waitStart
8367
+ const now = new Date()
8368
+ utimesSync(slot, now, now)
8369
+ return work(slot, lease, waitedMs)
8370
+ }
8371
+ const built = new Map(slots.map((slot) => [slot, statSync(slot).mtimeMs]))
8372
+ const ranked = slots
8373
+ .map((slot, index) => {
8374
+ const shape = swiftFrameworkSlotRecord(slot, SWIFT_BUILD_ROOT_SHAPE)
8375
+ const tier = shape === buildShape ? 0 : shape === null ? 1 : 2
8376
+ return { slot, index, tier }
8377
+ })
8378
+ .sort((left, right) => {
8379
+ if (left.tier !== right.tier) return left.tier - right.tier
8380
+ if (left.tier === 0)
8381
+ return (built.get(right.slot) ?? 0) - (built.get(left.slot) ?? 0)
8382
+ if (left.tier === 1) return left.index - right.index
8383
+ return (built.get(left.slot) ?? 0) - (built.get(right.slot) ?? 0)
8384
+ })
8385
+ for (const { slot } of ranked) {
8386
+ const result = await withSwiftRootLock(
8387
+ slot,
8388
+ async (lease) => ({ value: await runInSlot(slot, Date.now())(lease) }),
8389
+ signal,
8390
+ false,
8391
+ )
8392
+ if (result) return result.value
8393
+ }
8394
+ const nearest = ranked[0]!.slot
8395
+ const waitStart = Date.now()
8396
+ return withSwiftRootLock(nearest, runInSlot(nearest, waitStart), signal)
8397
+ }
8398
+
8312
8399
  // copies the files of `source` that differ into `target` and removes the rest of
8313
8400
  // `target`. a file whose size and mtime match, or whose bytes match, is left
8314
8401
  // alone so llbuild sees it unchanged; a changed file arrives as a new inode.
@@ -8380,8 +8467,10 @@ function stageFrameworkSource(
8380
8467
  if (hadKey !== frameworkKey) {
8381
8468
  // an interrupted restage must not look like a finished one
8382
8469
  rmSync(path.join(slot, SWIFT_FRAMEWORK_SLOT_KEY), { force: true })
8470
+ rmSync(path.join(slot, SWIFT_FRAMEWORK_SLOT_RELEASE), { force: true })
8383
8471
  rmSync(path.join(slot, 'products-ready'), { recursive: true, force: true })
8384
- rmSync(path.join(slot, 'lib', '.receipt'), { force: true })
8472
+ rmSync(path.join(slot, 'products-lib'), { recursive: true, force: true })
8473
+ rmSync(path.join(slot, 'lib'), { recursive: true, force: true })
8385
8474
  const moduleRestructured = mirrorTree(moduleRoot, stagedModule, '.build')
8386
8475
  const sdkRestructured = mirrorTree(
8387
8476
  swiftSharedSdkRoot(moduleRoot, false),
@@ -8413,8 +8502,11 @@ function stageFrameworkSource(
8413
8502
  rmSync(modules, { recursive: true, force: true })
8414
8503
  symlinkSync(target, modules)
8415
8504
  }
8505
+ writeFileSync(path.join(slot, SWIFT_FRAMEWORK_SLOT_RELEASE), release)
8416
8506
  writeFileSync(path.join(slot, SWIFT_FRAMEWORK_SLOT_KEY), frameworkKey)
8417
8507
  writeFileSync(path.join(slot, SWIFT_FRAMEWORK_SLOT_ORIGIN), moduleRoot)
8508
+ } else if (swiftFrameworkSlotRelease(slot) !== release) {
8509
+ writeFileSync(path.join(slot, SWIFT_FRAMEWORK_SLOT_RELEASE), release)
8418
8510
  }
8419
8511
  return stagedModule
8420
8512
  }
@@ -8703,62 +8795,194 @@ async function compileSwiftProjectOnce(
8703
8795
  }
8704
8796
  // the root's sources, manifest and executable are shared by every process
8705
8797
  // using it, so one process writes, builds and reads them at a time.
8798
+ const baseRoot = root
8799
+ const canPoolBuildRoot =
8800
+ !options.intermediates &&
8801
+ !options.project &&
8802
+ !options.linkOnly &&
8803
+ path.basename(path.dirname(baseRoot)) === 'swift-builds'
8804
+ const buildShape = canPoolBuildRoot
8805
+ ? createHash('sha256')
8806
+ .update(
8807
+ JSON.stringify([
8808
+ frameworkKey,
8809
+ Boolean(sdkImage),
8810
+ compileTargets(input)
8811
+ .map((target) => target.name)
8812
+ .sort(),
8813
+ input.oneModule === true,
8814
+ input.optimize === true,
8815
+ input.unoptimized === true,
8816
+ Object.keys(input.files).sort(),
8817
+ ]),
8818
+ )
8819
+ .digest('hex')
8820
+ .slice(0, 16)
8821
+ : ''
8706
8822
  return withSwiftCompileBudget(options.timeoutMs, options.signal, async (budget) => {
8707
- return withSwiftRootLock(
8708
- root,
8709
- async (lease) => {
8710
- // a process that held the root while this one waited may have built
8711
- // this exact address.
8712
- if (!options.intermediates) {
8713
- const built = readCompiledArtifact(path.join(sharedRoot, 'artifact'), hash)
8714
- if (built) {
8715
- report('reusing verified disk artifact')
8716
- return retain(root, built)
8717
- }
8823
+ const stage = (message: string) => {
8824
+ budget.progress()
8825
+ report(message)
8826
+ }
8827
+ const runLocked = (
8828
+ work: (
8829
+ slotRoot: string,
8830
+ lease: SwiftRootLease,
8831
+ waitedMs: number,
8832
+ ) => Promise<SwiftCompileArtifact | void>,
8833
+ ) => {
8834
+ if (canPoolBuildRoot) {
8835
+ mkdirSync(sharedRoot, { recursive: true })
8836
+ return withSwiftRootLock(
8837
+ sharedRoot,
8838
+ async () => {
8839
+ // a concurrent caller with the exact same hash may have finished
8840
+ // while we waited on sharedRoot; return before touching any slot.
8841
+ const built = readCompiledArtifact(
8842
+ path.join(sharedRoot, 'artifact'),
8843
+ hash,
8844
+ )
8845
+ if (built) {
8846
+ stage('reusing verified disk artifact')
8847
+ return retain(baseRoot, built)
8848
+ }
8849
+ return withSwiftBuildRootSlot(baseRoot, buildShape, budget.signal, work)
8850
+ },
8851
+ budget.signal,
8852
+ )
8853
+ }
8854
+ const waitStart = Date.now()
8855
+ return withSwiftRootLock(
8856
+ baseRoot,
8857
+ (lease) => work(baseRoot, lease, Date.now() - waitStart),
8858
+ budget.signal,
8859
+ )
8860
+ }
8861
+ return runLocked(async (slotRoot, lease, waitedMs) => {
8862
+ const root = slotRoot
8863
+ const layout: SwiftProjectLayout = {
8864
+ root,
8865
+ sources: path.join(root, 'Sources', 'App'),
8866
+ multi: compileTargets(input).length > 0,
8867
+ }
8868
+ // a process that held the root while this one waited may have built
8869
+ // this exact address.
8870
+ if (!options.intermediates) {
8871
+ const built = readCompiledArtifact(path.join(sharedRoot, 'artifact'), hash)
8872
+ if (built) {
8873
+ stage('reusing verified disk artifact')
8874
+ return retain(baseRoot, built)
8718
8875
  }
8719
- const swift = path.join(options.toolchainBin, 'swift')
8720
- if (!existsSync(swift)) {
8721
- throw new Error(
8722
- `swift-compile: no swift.org toolchain at ${options.toolchainBin}; install ${options.release} and its matching wasm sdk`,
8723
- )
8876
+ }
8877
+ if (waitedMs >= 1_000)
8878
+ report(`acquired build root ${path.basename(root)} after ${waitedMs}ms`)
8879
+ if (canPoolBuildRoot) {
8880
+ refreshSwiftCacheHold(root)
8881
+ writeFileSync(path.join(root, SWIFT_BUILD_ROOT_SHAPE), buildShape)
8882
+ }
8883
+ const swift = path.join(options.toolchainBin, 'swift')
8884
+ if (!existsSync(swift)) {
8885
+ throw new Error(
8886
+ `swift-compile: no swift.org toolchain at ${options.toolchainBin}; install ${options.release} and its matching wasm sdk`,
8887
+ )
8888
+ }
8889
+ // a distribution's immutable modules and host plugins need no source build.
8890
+ const unoptimized = input.unoptimized === true
8891
+ const withFrameworkLock = <T>(
8892
+ work: (slot: string | null, frameworkLease?: SwiftRootLease) => Promise<T>,
8893
+ ) =>
8894
+ distribution
8895
+ ? work(null)
8896
+ : withSwiftFrameworkSlot(
8897
+ frameworkKey,
8898
+ options.release,
8899
+ moduleRoot,
8900
+ budget.signal,
8901
+ work,
8902
+ unoptimized,
8903
+ )
8904
+ const baseBuildEnv = options.project?.env
8905
+ ? {
8906
+ ...options.project.env,
8907
+ // shipped host plugins resolve against the selected compiler's runtime.
8908
+ ...(process.platform === 'linux'
8909
+ ? {
8910
+ LD_LIBRARY_PATH: [
8911
+ path.resolve(options.toolchainBin, '../lib/swift/linux'),
8912
+ path.resolve(options.toolchainBin, '../lib/swift/host'),
8913
+ process.env.LD_LIBRARY_PATH,
8914
+ ]
8915
+ .filter(Boolean)
8916
+ .join(':'),
8917
+ }
8918
+ : {}),
8919
+ PEACH_DEFER_WASM_LINK: '1',
8920
+ }
8921
+ : swiftCompilerBaseEnv(options.toolchainBin, process.env)
8922
+ // hold the exclusive framework slot lock only while staging and
8923
+ // building framework products; take a shared read hold before
8924
+ // releasing it so other builds on the same framework revision
8925
+ // compile and link their apps concurrently.
8926
+ const {
8927
+ frameworkRoot,
8928
+ compileFrameworkRoot,
8929
+ macroPlugins,
8930
+ sdk,
8931
+ icu,
8932
+ prebuilt,
8933
+ readHold,
8934
+ } = await withFrameworkLock(async (slot, frameworkLease) => {
8935
+ budget.startCompile()
8936
+ if (slot && swiftFrameworkSlotKey(slot) !== frameworkKey)
8937
+ await waitForNoSwiftRootReaders(slot, budget.signal)
8938
+ // project users own their build roots; resolve their sdk outside them.
8939
+ const frameworkRoot = mirrorDistribution
8940
+ ? syncSwiftDistributionMirror(root, moduleRoot, mirrorDistribution)
8941
+ : distribution
8942
+ ? moduleRoot
8943
+ : stageFrameworkSource(moduleRoot, slot, frameworkKey, options.release)
8944
+ if (!swiftModuleDigest(frameworkRoot).equals(moduleDigest))
8945
+ throw new Error('Swift staged project source differs from the caller')
8946
+ stage('preparing compiler plugins')
8947
+ const macroPlugins = await ensureMacroPlugins(
8948
+ frameworkRoot,
8949
+ options.toolchainBin,
8950
+ options.release,
8951
+ budget.signal,
8952
+ frameworkLease,
8953
+ )
8954
+ const compileFrameworkRoot = distribution
8955
+ ? swiftDistributionCompileView(frameworkRoot, distribution)
8956
+ : frameworkRoot
8957
+ // memoized per toolchain, so only a process's first build waits on it,
8958
+ // and that one reads and gzips it while swift builds
8959
+ const sdk = swiftModuleSdk(frameworkRoot).wasmSdkId
8960
+ const icu = options.linkOnly ? null : swiftIcuAsset(options.toolchainBin, sdk)
8961
+ let prebuilt: SwiftFrameworkProducts | undefined
8962
+ if (!distribution) {
8963
+ stage('compiling framework products')
8964
+ prebuilt = await buildFrameworkProducts(slot!, {
8965
+ moduleRoot: frameworkRoot,
8966
+ frameworkKey,
8967
+ input,
8968
+ swift,
8969
+ sdk,
8970
+ toolchainBin: options.toolchainBin,
8971
+ plugins: macroPlugins,
8972
+ buildOptions: {
8973
+ env: baseBuildEnv,
8974
+ maxBuffer: 64 * 1024 * 1024,
8975
+ signal: budget.signal,
8976
+ onOutput: budget.progress,
8977
+ lease,
8978
+ frameworkLease,
8979
+ },
8980
+ })
8724
8981
  }
8725
- // a distribution's immutable modules and host plugins need no source build.
8726
- const unoptimized = input.unoptimized === true
8727
- const withFrameworkLock = <T>(
8728
- work: (slot: string | null, frameworkLease?: SwiftRootLease) => Promise<T>,
8729
- ) =>
8730
- distribution
8731
- ? work(null)
8732
- : withSwiftFrameworkSlot(
8733
- frameworkKey,
8734
- moduleRoot,
8735
- budget.signal,
8736
- work,
8737
- unoptimized,
8738
- )
8739
- const baseBuildEnv = options.project?.env
8740
- ? {
8741
- ...options.project.env,
8742
- // shipped host plugins resolve against the selected compiler's runtime.
8743
- ...(process.platform === 'linux'
8744
- ? {
8745
- LD_LIBRARY_PATH: [
8746
- path.resolve(options.toolchainBin, '../lib/swift/linux'),
8747
- path.resolve(options.toolchainBin, '../lib/swift/host'),
8748
- process.env.LD_LIBRARY_PATH,
8749
- ]
8750
- .filter(Boolean)
8751
- .join(':'),
8752
- }
8753
- : {}),
8754
- PEACH_DEFER_WASM_LINK: '1',
8755
- }
8756
- : swiftCompilerBaseEnv(options.toolchainBin, process.env)
8757
- // hold the exclusive framework slot lock only while staging and
8758
- // building framework products; take a shared read hold before
8759
- // releasing it so other builds on the same framework revision
8760
- // compile and link their apps concurrently.
8761
- const {
8982
+ const readHold: SwiftRootReadHold | undefined = slot
8983
+ ? acquireSwiftRootReadHold(slot)
8984
+ : undefined
8985
+ return {
8762
8986
  frameworkRoot,
8763
8987
  compileFrameworkRoot,
8764
8988
  macroPlugins,
@@ -8766,735 +8990,676 @@ async function compileSwiftProjectOnce(
8766
8990
  icu,
8767
8991
  prebuilt,
8768
8992
  readHold,
8769
- } = await withFrameworkLock(async (slot, frameworkLease) => {
8770
- budget.startCompile()
8771
- if (slot && swiftFrameworkSlotKey(slot) !== frameworkKey)
8772
- await waitForNoSwiftRootReaders(slot, budget.signal)
8773
- // project users own their build roots; resolve their sdk outside them.
8774
- const frameworkRoot = mirrorDistribution
8775
- ? syncSwiftDistributionMirror(root, moduleRoot, mirrorDistribution)
8776
- : distribution
8777
- ? moduleRoot
8778
- : stageFrameworkSource(moduleRoot, slot, frameworkKey, options.release)
8779
- if (!swiftModuleDigest(frameworkRoot).equals(moduleDigest))
8780
- throw new Error('Swift staged project source differs from the caller')
8781
- report('preparing compiler plugins')
8782
- const macroPlugins = await ensureMacroPlugins(
8783
- frameworkRoot,
8784
- options.toolchainBin,
8785
- options.release,
8786
- budget.signal,
8787
- frameworkLease,
8993
+ }
8994
+ })
8995
+ const buildOptions = {
8996
+ env: baseBuildEnv,
8997
+ maxBuffer: 64 * 1024 * 1024,
8998
+ signal: budget.signal,
8999
+ onOutput: budget.progress,
9000
+ lease,
9001
+ }
9002
+ try {
9003
+ if (options.project) removeProjectLinks(root)
9004
+ const packageHostMacros =
9005
+ process.platform === 'linux' ? input.packageHostMacros : undefined
9006
+ if (
9007
+ retireStaleSwiftLink(
9008
+ root,
9009
+ swiftLinkStamp({
9010
+ frameworkKey: `${options.release}\0${Boolean(distribution)}\0${swiftModuleSdk(frameworkRoot).wasmSdkId}`,
9011
+ packageHostMacros,
9012
+ }),
9013
+ swiftLinkStamp({
9014
+ // a distribution's objects reach only the deferred link, and
9015
+ // the root's mirror keeps its compile inputs at fixed paths
9016
+ frameworkKey: distribution
9017
+ ? `${options.release}\0${distribution.wasmSdkChecksum}`
9018
+ : frameworkKey,
9019
+ prebuilt,
9020
+ packageHostMacros,
9021
+ }),
9022
+ Boolean(options.linkOnly),
8788
9023
  )
8789
- const compileFrameworkRoot = distribution
8790
- ? swiftDistributionCompileView(frameworkRoot, distribution)
8791
- : frameworkRoot
8792
- // memoized per toolchain, so only a process's first build waits on it,
8793
- // and that one reads and gzips it while swift builds
8794
- const sdk = swiftModuleSdk(frameworkRoot).wasmSdkId
8795
- const icu = options.linkOnly
8796
- ? null
8797
- : swiftIcuAsset(options.toolchainBin, sdk)
8798
- let prebuilt: SwiftFrameworkProducts | undefined
8799
- if (!distribution) {
8800
- report('compiling framework products')
8801
- prebuilt = await buildFrameworkProducts(slot!, {
8802
- moduleRoot: frameworkRoot,
8803
- frameworkKey,
8804
- input,
8805
- swift,
8806
- sdk,
8807
- toolchainBin: options.toolchainBin,
8808
- plugins: macroPlugins,
8809
- buildOptions: {
8810
- env: baseBuildEnv,
8811
- maxBuffer: 64 * 1024 * 1024,
8812
- signal: budget.signal,
8813
- lease,
8814
- frameworkLease,
8815
- },
8816
- })
8817
- }
8818
- const readHold: SwiftRootReadHold | undefined = slot
8819
- ? acquireSwiftRootReadHold(slot)
8820
- : undefined
8821
- return {
8822
- frameworkRoot,
8823
- compileFrameworkRoot,
8824
- macroPlugins,
8825
- sdk,
8826
- icu,
8827
- prebuilt,
8828
- readHold,
8829
- }
8830
- })
8831
- const buildOptions = {
8832
- env: baseBuildEnv,
8833
- maxBuffer: 64 * 1024 * 1024,
8834
- signal: budget.signal,
8835
- lease,
9024
+ )
9025
+ stage('framework revision changed; rebuilding the app link')
9026
+ const nativeToolset = needsNativeToolset(input, prebuilt)
9027
+ const preparation = writeSwiftProject(
9028
+ layout,
9029
+ input,
9030
+ frameworkRoot,
9031
+ prebuilt,
9032
+ !options.project,
9033
+ options.project
9034
+ ? false
9035
+ : (options.objcPrebuiltStage ??
9036
+ (options.intermediates ? false : undefined)),
9037
+ )
9038
+ // the framework objects link as inputs, so the product name its
9039
+ // modules autolink has no archive to load
9040
+ const productFile = path.join(frameworkRoot, SWIFT_FRAMEWORK_PRODUCT_FILE)
9041
+ writeSwiftAutolinkLinker(
9042
+ root,
9043
+ options.toolchainBin,
9044
+ existsSync(productFile)
9045
+ ? [
9046
+ v.parse(
9047
+ swiftFrameworkProductSchema,
9048
+ JSON.parse(readFileSync(productFile, 'utf8')),
9049
+ ).product.name,
9050
+ ]
9051
+ : [],
9052
+ )
9053
+ // the native build system takes its C compiler from CC, never a toolset
9054
+ const compiler: Record<string, string> = preparation.targetToolset
9055
+ ? { CC: path.join(root, CLANG_TARGET_MODULE_WRAPPER) }
9056
+ : {}
9057
+ if (packageHostMacros?.length) {
9058
+ // swiftpm build-tool flags skip macro targets; forward the import
9059
+ // when swiftpm compiles a declared macro for the linux host.
9060
+ const swiftc = path.join(root, SWIFT_HOST_COMPILER_WRAPPER)
9061
+ writeBuildFile(
9062
+ swiftc,
9063
+ [
9064
+ '#!/bin/sh',
9065
+ 'target=',
9066
+ 'module=',
9067
+ 'compile=',
9068
+ 'previous=',
9069
+ 'for argument do',
9070
+ ' case "$previous" in -target) target=$argument ;; -module-name) module=$argument ;; esac',
9071
+ ' case "$argument" in -c|-emit-module|-scan-dependencies|-typecheck) compile=1 ;; esac',
9072
+ ' previous=$argument',
9073
+ 'done',
9074
+ 'case "$target/$compile" in',
9075
+ ' *-*-linux*/1)',
9076
+ ' case ",$PEACH_SWIFT_HOST_MACROS," in',
9077
+ ' *",$module,"*) set -- "$@" -Xfrontend -import-module -Xfrontend Foundation ;;',
9078
+ ' esac ;;',
9079
+ 'esac',
9080
+ 'exec "$PEACH_SWIFTC" "$@"',
9081
+ '',
9082
+ ].join('\n'),
9083
+ )
9084
+ chmodSync(swiftc, 0o755)
9085
+ compiler.SWIFT_EXEC = swiftc
9086
+ compiler.PEACH_SWIFT_HOST_MACROS = packageHostMacros.join(',')
9087
+ compiler.PEACH_SWIFTC = path.join(options.toolchainBin, 'swiftc')
8836
9088
  }
8837
- try {
8838
- if (options.project) removeProjectLinks(root)
8839
- const packageHostMacros =
8840
- process.platform === 'linux' ? input.packageHostMacros : undefined
8841
- if (
8842
- retireStaleSwiftLink(
8843
- root,
8844
- swiftLinkStamp({
8845
- frameworkKey: `${options.release}\0${Boolean(distribution)}\0${swiftModuleSdk(frameworkRoot).wasmSdkId}`,
8846
- packageHostMacros,
8847
- }),
8848
- swiftLinkStamp({
8849
- // a distribution's objects reach only the deferred link, and
8850
- // the root's mirror keeps its compile inputs at fixed paths
8851
- frameworkKey: distribution
8852
- ? `${options.release}\0${distribution.wasmSdkChecksum}`
8853
- : frameworkKey,
8854
- prebuilt,
8855
- packageHostMacros,
8856
- }),
8857
- Boolean(options.linkOnly),
8858
- )
9089
+ const projectProcess = options.project
9090
+ ? prepareSwiftProjectProcess(root, options.project)
9091
+ : undefined
9092
+ // swiftpm hashes TMPDIR into its plan. the root lock owns this scratch.
9093
+ const temporaryDirectory = projectProcess
9094
+ ? undefined
9095
+ : path.join(root, '.build', 'peach-compiler-tmp')
9096
+ const appOptions = projectProcess
9097
+ ? {
9098
+ ...buildOptions,
9099
+ uid: projectProcess.uid,
9100
+ gid: projectProcess.gid,
9101
+ confined: { ...projectProcess.env, ...compiler },
9102
+ }
9103
+ : {
9104
+ ...buildOptions,
9105
+ temporaryDirectory,
9106
+ env: {
9107
+ ...buildOptions.env,
9108
+ ...(preparation.usesObjcPrebuilt &&
9109
+ process.env.PEACH_HOME !== undefined
9110
+ ? { PEACH_HOME: process.env.PEACH_HOME }
9111
+ : {}),
9112
+ ...compiler,
9113
+ },
9114
+ }
9115
+ const unprepared = preparation.targetFailures.map(
9116
+ (failure) => `error: target ${failure}`,
9117
+ )
9118
+ // a forwarder header (`#include "../../x.hpp"`) reaches its target
9119
+ // through `..`, which clang keeps in __FILE__, while the header
9120
+ // alias overlay names the same file directly. mapping each
9121
+ // forwarder spelling to the directory it reaches makes a debug
9122
+ // assert expand alike in every module that includes the header.
9123
+ const forwarders = new Map<string, string>()
9124
+ for (const [file, text] of Object.entries(input.files)) {
9125
+ const parents = /^#include "((?:\.\.\/)+)[^"\n]+"\n$/.exec(text)?.[1]
9126
+ if (!parents) continue
9127
+ const directory = path.posix.dirname(file)
9128
+ forwarders.set(
9129
+ `${path.join(root, directory)}/${parents.slice(0, -1)}`,
9130
+ path.posix.join('build', directory, parents).replace(/\/$/, ''),
8859
9131
  )
8860
- report('framework revision changed; rebuilding the app link')
8861
- const nativeToolset = needsNativeToolset(input, prebuilt)
8862
- const preparation = writeSwiftProject(
8863
- layout,
8864
- input,
8865
- frameworkRoot,
8866
- prebuilt,
8867
- !options.project,
8868
- options.project
8869
- ? false
8870
- : (options.objcPrebuiltStage ??
8871
- (options.intermediates ? false : undefined)),
9132
+ }
9133
+ const jobs = swiftCompilerJobs()
9134
+ const incrementalPreview =
9135
+ sdkImage !== undefined &&
9136
+ !guestGraph &&
9137
+ !options.project &&
9138
+ !input.optimize &&
9139
+ !input.unoptimized
9140
+ const perFile = input.unoptimized || incrementalPreview
9141
+ const buildArgs = [
9142
+ 'build',
9143
+ ...(projectProcess?.cacheOptions ?? swiftPackageCacheOptions()),
9144
+ '--build-system',
9145
+ 'native',
9146
+ '-j',
9147
+ String(jobs),
9148
+ '--package-path',
9149
+ root,
9150
+ ...swiftCompileSdkOptions(frameworkRoot, options.toolchainBin),
9151
+ ...swiftObjCSelectorOptions(frameworkRoot),
9152
+ '--swift-sdk',
9153
+ sdk,
9154
+ ...(preparation.targetToolset
9155
+ ? ['--toolset', path.join(root, '.peach-target-toolset.json')]
9156
+ : []),
9157
+ '-c',
9158
+ 'release',
9159
+ ...(input.unoptimized ? ['-Xswiftc', '-Onone'] : []),
9160
+ ...(perFile
9161
+ ? [
9162
+ '-Xswiftc',
9163
+ '-no-whole-module-optimization',
9164
+ '-Xswiftc',
9165
+ '-j',
9166
+ '-Xswiftc',
9167
+ String(jobs),
9168
+ ]
9169
+ : []),
9170
+ ...(incrementalPreview
9171
+ ? ['-Xswiftc', '-incremental', '-Xswiftc', '-enable-batch-mode']
9172
+ : []),
9173
+ // the mirror finds a changed sdk header's readers in their
9174
+ // dependency files, which omit system headers by default
9175
+ ...(mirrorDistribution ? ['-Xswiftc', '-track-system-dependencies'] : []),
9176
+ // the link strips debug info, so none is generated (as for the framework).
9177
+ // keep -num-threads fixed across caller core caps so llbuild does not
9178
+ // rebuild every target when callers alternate --cores, and bound backend
9179
+ // fan-out under high -j.
9180
+ '-Xswiftc',
9181
+ '-gnone',
9182
+ ...(incrementalPreview
9183
+ ? []
9184
+ : [
9185
+ '-Xswiftc',
9186
+ '-num-threads',
9187
+ '-Xswiftc',
9188
+ String(perFile ? 1 : Math.min(8, os.availableParallelism())),
9189
+ ]),
9190
+ ...swiftReproducibleBuildFlags([
9191
+ [path.dirname(options.toolchainBin), 'toolchain'],
9192
+ [compileFrameworkRoot, 'framework'],
9193
+ [root, 'build'],
9194
+ ...forwarders,
9195
+ ]).flatMap((flag, index, flags) => {
9196
+ if (!nativeToolset || !flag.startsWith('-ffile-prefix-map='))
9197
+ return [flag]
9198
+ const toolchainDir = path.dirname(options.toolchainBin)
9199
+ let mapped = flag
9200
+ for (const [dir, target] of [
9201
+ [root, '/peach/build'],
9202
+ [compileFrameworkRoot, '/peach/framework'],
9203
+ [realpathSync(compileFrameworkRoot), '/peach/framework'],
9204
+ [toolchainDir, '/peach/toolchain'],
9205
+ [realpathSync(toolchainDir), '/peach/toolchain'],
9206
+ ] as const) {
9207
+ mapped = mapped.replaceAll(dir, target)
9208
+ }
9209
+ const [, from, to] = /^-ffile-prefix-map=([^=]+)=(.+)$/.exec(mapped) ?? []
9210
+ const tool = flags[index - 1]!
9211
+ // clang applies the longest prefix once without chaining: keep the
9212
+ // physical map for direct compiles and add the mapped form for
9213
+ // subpaths already rewritten by modular depscan.
9214
+ return mapped !== flag && from !== to ? [flag, tool, mapped] : [flag]
9215
+ }),
9216
+ ...macroPlugins.libraries.flatMap((plugin) => [
9217
+ '-Xswiftc',
9218
+ '-load-plugin-library',
9219
+ '-Xswiftc',
9220
+ plugin,
9221
+ ]),
9222
+ ...macroPlugins.executables.flatMap((plugin) => [
9223
+ '-Xswiftc',
9224
+ '-load-plugin-executable',
9225
+ '-Xswiftc',
9226
+ `${plugin}#ExpoModulesMacros`,
9227
+ ]),
9228
+ ]
9229
+ const linked = builtArtifact(layout)
9230
+ // every link is deferred: a build stopped after the linker wrapper wrote
9231
+ // its 8-byte placeholder would otherwise leave swiftpm seeing a fresh,
9232
+ // empty executable and skipping the link on the next build.
9233
+ rmSync(path.join(root, '.peach-link.rsp'), { force: true })
9234
+ // archive producers reuse objects across compiler recipe changes,
9235
+ // so qualify each new entry with the current linker.
9236
+ if (options.linkOnly || (existsSync(linked) && statSync(linked).size <= 8))
9237
+ rmSync(linked, { force: true })
9238
+ stage('compiling and linking Swift modules')
9239
+ const frameworkInterfaces = new Map<
9240
+ string,
9241
+ { file: string; header: string; module: boolean } | null
9242
+ >()
9243
+ const sdkFrameworks = path.join(
9244
+ swiftSdkPaths(frameworkRoot, options.toolchainBin).darwin,
9245
+ 'System/Library/Frameworks',
9246
+ )
9247
+ const generatedInterface = (source: string) =>
9248
+ withoutImportedSdkEnumForwards(
9249
+ clangInterfaceHeader(readFileSync(source, 'utf8'), frameworkRoot),
9250
+ sdkObjCDeclarationOwners(sdkFrameworks),
8872
9251
  )
8873
- // the framework objects link as inputs, so the product name its
8874
- // modules autolink has no archive to load
8875
- const productFile = path.join(frameworkRoot, SWIFT_FRAMEWORK_PRODUCT_FILE)
8876
- writeSwiftAutolinkLinker(
8877
- root,
8878
- options.toolchainBin,
8879
- existsSync(productFile)
8880
- ? [
8881
- v.parse(
8882
- swiftFrameworkProductSchema,
8883
- JSON.parse(readFileSync(productFile, 'utf8')),
8884
- ).product.name,
8885
- ]
8886
- : [],
9252
+ const nativeDeclarations = new Map<string, Set<string>>()
9253
+ const nativeHeaders = Object.entries(input.files)
9254
+ .filter(([name]) => name.endsWith('.h') && !name.endsWith('-Swift.h'))
9255
+ .map(([, source]) => source)
9256
+ for (const [file, contents] of Object.entries(input.files)) {
9257
+ if (!file.endsWith('.modulemap')) continue
9258
+ const name = moduleMapName(contents)
9259
+ const umbrella = /\bumbrella\s+header\s+"([^"]+)"/.exec(contents)?.[1]
9260
+ if (!name || !umbrella) continue
9261
+ const header =
9262
+ input.files[path.posix.join(path.posix.dirname(file), umbrella)]
9263
+ if (header === undefined) continue
9264
+ const included = new Set(
9265
+ [
9266
+ ...header.matchAll(/^\s*#\s*(?:import|include)\s*[<"]([^">]+)[">]/gm),
9267
+ ].map((match) => path.posix.basename(match[1]!)),
8887
9268
  )
8888
- // the native build system takes its C compiler from CC, never a toolset
8889
- const compiler: Record<string, string> = preparation.targetToolset
8890
- ? { CC: path.join(root, CLANG_TARGET_MODULE_WRAPPER) }
8891
- : {}
8892
- if (packageHostMacros?.length) {
8893
- // swiftpm build-tool flags skip macro targets; forward the import
8894
- // when swiftpm compiles a declared macro for the linux host.
8895
- const swiftc = path.join(root, SWIFT_HOST_COMPILER_WRAPPER)
8896
- writeBuildFile(
8897
- swiftc,
8898
- [
8899
- '#!/bin/sh',
8900
- 'target=',
8901
- 'module=',
8902
- 'compile=',
8903
- 'previous=',
8904
- 'for argument do',
8905
- ' case "$previous" in -target) target=$argument ;; -module-name) module=$argument ;; esac',
8906
- ' case "$argument" in -c|-emit-module|-scan-dependencies|-typecheck) compile=1 ;; esac',
8907
- ' previous=$argument',
8908
- 'done',
8909
- 'case "$target/$compile" in',
8910
- ' *-*-linux*/1)',
8911
- ' case ",$PEACH_SWIFT_HOST_MACROS," in',
8912
- ' *",$module,"*) set -- "$@" -Xfrontend -import-module -Xfrontend Foundation ;;',
8913
- ' esac ;;',
8914
- 'esac',
8915
- 'exec "$PEACH_SWIFTC" "$@"',
8916
- '',
8917
- ].join('\n'),
8918
- )
8919
- chmodSync(swiftc, 0o755)
8920
- compiler.SWIFT_EXEC = swiftc
8921
- compiler.PEACH_SWIFT_HOST_MACROS = packageHostMacros.join(',')
8922
- compiler.PEACH_SWIFTC = path.join(options.toolchainBin, 'swiftc')
9269
+ const declarations = nativeDeclarations.get(name) ?? new Set<string>()
9270
+ for (const declaration of swiftInterfaceDeclarations(header))
9271
+ declarations.add(declaration)
9272
+ for (const [candidate, source] of Object.entries(input.files))
9273
+ if (included.has(path.posix.basename(candidate)))
9274
+ for (const declaration of swiftInterfaceDeclarations(source))
9275
+ declarations.add(declaration)
9276
+ nativeDeclarations.set(name, declarations)
9277
+ }
9278
+ const frameworkInterface = (
9279
+ name: string,
9280
+ ): { file: string; header: string; module: boolean } | null => {
9281
+ if (frameworkInterfaces.has(name)) return frameworkInterfaces.get(name)!
9282
+ const source = distribution
9283
+ ? path.join(frameworkRoot, 'modules', `${name}-Swift.h`)
9284
+ : prebuilt!.objcHeaders.get(name)
9285
+ if (!source || !existsSync(source)) {
9286
+ frameworkInterfaces.set(name, null)
9287
+ return null
8923
9288
  }
8924
- const projectProcess = options.project
8925
- ? prepareSwiftProjectProcess(root, options.project)
8926
- : undefined
8927
- // swiftpm hashes TMPDIR into its plan. the root lock owns this scratch.
8928
- const temporaryDirectory = projectProcess
8929
- ? undefined
8930
- : path.join(root, '.build', 'peach-compiler-tmp')
8931
- const appOptions = projectProcess
8932
- ? {
8933
- ...buildOptions,
8934
- uid: projectProcess.uid,
8935
- gid: projectProcess.gid,
8936
- confined: { ...projectProcess.env, ...compiler },
8937
- }
8938
- : {
8939
- ...buildOptions,
8940
- temporaryDirectory,
8941
- env: {
8942
- ...buildOptions.env,
8943
- ...(preparation.usesObjcPrebuilt &&
8944
- process.env.PEACH_HOME !== undefined
8945
- ? { PEACH_HOME: process.env.PEACH_HOME }
8946
- : {}),
8947
- ...compiler,
8948
- },
8949
- }
8950
- const unprepared = preparation.targetFailures.map(
8951
- (failure) => `error: target ${failure}`,
9289
+ const headers = path.join(sdkFrameworks, `${name}.framework/Headers`)
9290
+ const declared = new Set<string>()
9291
+ if (existsSync(headers))
9292
+ for (const file of readdirSync(headers, {
9293
+ recursive: true,
9294
+ encoding: 'utf8',
9295
+ }))
9296
+ if (file.endsWith('.h'))
9297
+ for (const name of swiftInterfaceDeclarations(
9298
+ readFileSync(path.join(headers, file), 'utf8'),
9299
+ ))
9300
+ declared.add(name)
9301
+ for (const declaration of nativeDeclarations.get(name) ?? [])
9302
+ declared.add(declaration)
9303
+ const own = withoutSwiftDeclarations(
9304
+ generatedInterface(source),
9305
+ declared,
9306
+ nativeDeclarations.has(name)
9307
+ ? `@import ${name};`
9308
+ : `#import <${name}/${name}.h>`,
8952
9309
  )
8953
- // a forwarder header (`#include "../../x.hpp"`) reaches its target
8954
- // through `..`, which clang keeps in __FILE__, while the header
8955
- // alias overlay names the same file directly. mapping each
8956
- // forwarder spelling to the directory it reaches makes a debug
8957
- // assert expand alike in every module that includes the header.
8958
- const forwarders = new Map<string, string>()
8959
- for (const [file, text] of Object.entries(input.files)) {
8960
- const parents = /^#include "((?:\.\.\/)+)[^"\n]+"\n$/.exec(text)?.[1]
8961
- if (!parents) continue
8962
- const directory = path.posix.dirname(file)
8963
- forwarders.set(
8964
- `${path.join(root, directory)}/${parents.slice(0, -1)}`,
8965
- path.posix.join('build', directory, parents).replace(/\/$/, ''),
8966
- )
9310
+ // the swift module also implements classes another framework's headers
9311
+ // already define; clang takes those from the owning framework
9312
+ const owners = sdkObjCDeclarationOwners(sdkFrameworks)
9313
+ const foreign = new Map<string, string>()
9314
+ for (const declaration of [
9315
+ ...swiftInterfaceDeclarations(own),
9316
+ ...objcEnumerations(own),
9317
+ ...[...own.matchAll(/^\s*SWIFT_EXTERN\b[^(\n]*?\b(\w+)\s*\(/gm)].map(
9318
+ (match) => match[1]!,
9319
+ ),
9320
+ ]) {
9321
+ const owner = owners.get(declaration)
9322
+ if (owner && owner !== name) foreign.set(declaration, owner)
9323
+ }
9324
+ const header = foreign.size
9325
+ ? withoutSwiftDeclarations(
9326
+ own,
9327
+ new Set(foreign.keys()),
9328
+ [...new Set(foreign.values())]
9329
+ .map((owner) => `#import <${owner}/${owner}.h>`)
9330
+ .join('\n'),
9331
+ )
9332
+ : own
9333
+ const value = {
9334
+ file: path.join(root, '.build/peach-framework-objc', `${name}-Swift.h`),
9335
+ header,
9336
+ module: existsSync(headers),
8967
9337
  }
8968
- const jobs = swiftCompilerJobs()
8969
- const incrementalPreview =
8970
- sdkImage !== undefined &&
8971
- !guestGraph &&
8972
- !options.project &&
8973
- !input.optimize &&
8974
- !input.unoptimized
8975
- const perFile = input.unoptimized || incrementalPreview
8976
- const buildArgs = [
8977
- 'build',
8978
- ...(projectProcess?.cacheOptions ?? swiftPackageCacheOptions()),
8979
- '--build-system',
8980
- 'native',
8981
- '-j',
8982
- String(jobs),
8983
- '--package-path',
9338
+ frameworkInterfaces.set(name, value)
9339
+ writeBuildFile(
9340
+ value.file,
9341
+ (existsSync(path.join(headers, `${name}.h`))
9342
+ ? `#import <${name}/${name}.h>\n`
9343
+ : '') + swiftHeaderWithSuperclassImports(header, frameworkInterface),
9344
+ )
9345
+ return value
9346
+ }
9347
+ const headerPaths = (producer: string) => {
9348
+ const stem = path.join(
8984
9349
  root,
8985
- ...swiftCompileSdkOptions(frameworkRoot, options.toolchainBin),
8986
- ...swiftObjCSelectorOptions(frameworkRoot),
8987
- '--swift-sdk',
8988
- sdk,
8989
- ...(preparation.targetToolset
8990
- ? ['--toolset', path.join(root, '.peach-target-toolset.json')]
8991
- : []),
8992
- '-c',
8993
- 'release',
8994
- ...(input.unoptimized ? ['-Xswiftc', '-Onone'] : []),
8995
- ...(perFile
8996
- ? [
8997
- '-Xswiftc',
8998
- '-no-whole-module-optimization',
8999
- '-Xswiftc',
9000
- '-j',
9001
- '-Xswiftc',
9002
- String(jobs),
9003
- ]
9004
- : []),
9005
- ...(incrementalPreview
9006
- ? ['-Xswiftc', '-incremental', '-Xswiftc', '-enable-batch-mode']
9007
- : []),
9008
- // the mirror finds a changed sdk header's readers in their
9009
- // dependency files, which omit system headers by default
9010
- ...(mirrorDistribution ? ['-Xswiftc', '-track-system-dependencies'] : []),
9011
- // the link strips debug info, so none is generated (as for the framework).
9012
- // keep -num-threads fixed across caller core caps so llbuild does not
9013
- // rebuild every target when callers alternate --cores, and bound backend
9014
- // fan-out under high -j.
9015
- '-Xswiftc',
9016
- '-gnone',
9017
- ...(incrementalPreview
9018
- ? []
9019
- : [
9020
- '-Xswiftc',
9021
- '-num-threads',
9022
- '-Xswiftc',
9023
- String(perFile ? 1 : Math.min(8, os.availableParallelism())),
9024
- ]),
9025
- ...swiftReproducibleBuildFlags([
9026
- [path.dirname(options.toolchainBin), 'toolchain'],
9027
- [compileFrameworkRoot, 'framework'],
9028
- [root, 'build'],
9029
- ...forwarders,
9030
- ]).flatMap((flag, index, flags) => {
9031
- if (!nativeToolset || !flag.startsWith('-ffile-prefix-map='))
9032
- return [flag]
9033
- const toolchainDir = path.dirname(options.toolchainBin)
9034
- let mapped = flag
9035
- for (const [dir, target] of [
9036
- [root, '/peach/build'],
9037
- [compileFrameworkRoot, '/peach/framework'],
9038
- [realpathSync(compileFrameworkRoot), '/peach/framework'],
9039
- [toolchainDir, '/peach/toolchain'],
9040
- [realpathSync(toolchainDir), '/peach/toolchain'],
9041
- ] as const) {
9042
- mapped = mapped.replaceAll(dir, target)
9043
- }
9044
- const [, from, to] =
9045
- /^-ffile-prefix-map=([^=]+)=(.+)$/.exec(mapped) ?? []
9046
- const tool = flags[index - 1]!
9047
- // clang applies the longest prefix once without chaining: keep the
9048
- // physical map for direct compiles and add the mapped form for
9049
- // subpaths already rewritten by modular depscan.
9050
- return mapped !== flag && from !== to ? [flag, tool, mapped] : [flag]
9051
- }),
9052
- ...macroPlugins.libraries.flatMap((plugin) => [
9053
- '-Xswiftc',
9054
- '-load-plugin-library',
9055
- '-Xswiftc',
9056
- plugin,
9057
- ]),
9058
- ...macroPlugins.executables.flatMap((plugin) => [
9059
- '-Xswiftc',
9060
- '-load-plugin-executable',
9061
- '-Xswiftc',
9062
- `${plugin}#ExpoModulesMacros`,
9063
- ]),
9064
- ]
9065
- const linked = builtArtifact(layout)
9066
- // every link is deferred: a build stopped after the linker wrapper wrote
9067
- // its 8-byte placeholder would otherwise leave swiftpm seeing a fresh,
9068
- // empty executable and skipping the link on the next build.
9069
- rmSync(path.join(root, '.peach-link.rsp'), { force: true })
9070
- // archive producers reuse objects across compiler recipe changes,
9071
- // so qualify each new entry with the current linker.
9072
- if (options.linkOnly || (existsSync(linked) && statSync(linked).size <= 8))
9073
- rmSync(linked, { force: true })
9074
- report('compiling and linking Swift modules')
9075
- const frameworkInterfaces = new Map<
9076
- string,
9077
- { file: string; header: string; module: boolean } | null
9078
- >()
9079
- const sdkFrameworks = path.join(
9080
- swiftSdkPaths(frameworkRoot, options.toolchainBin).darwin,
9081
- 'System/Library/Frameworks',
9350
+ '.build',
9351
+ 'peach-cxx-headers',
9352
+ `${producer}-Swift`,
9082
9353
  )
9083
- const generatedInterface = (source: string) =>
9084
- withoutImportedSdkEnumForwards(
9085
- clangInterfaceHeader(readFileSync(source, 'utf8'), frameworkRoot),
9086
- sdkObjCDeclarationOwners(sdkFrameworks),
9087
- )
9088
- const nativeDeclarations = new Map<string, Set<string>>()
9089
- const nativeHeaders = Object.entries(input.files)
9090
- .filter(([name]) => name.endsWith('.h') && !name.endsWith('-Swift.h'))
9091
- .map(([, source]) => source)
9092
- for (const [file, contents] of Object.entries(input.files)) {
9093
- if (!file.endsWith('.modulemap')) continue
9094
- const name = moduleMapName(contents)
9095
- const umbrella = /\bumbrella\s+header\s+"([^"]+)"/.exec(contents)?.[1]
9096
- if (!name || !umbrella) continue
9097
- const header =
9098
- input.files[path.posix.join(path.posix.dirname(file), umbrella)]
9099
- if (header === undefined) continue
9100
- const included = new Set(
9101
- [
9102
- ...header.matchAll(/^\s*#\s*(?:import|include)\s*[<"]([^">]+)[">]/gm),
9103
- ].map((match) => path.posix.basename(match[1]!)),
9104
- )
9105
- const declarations = nativeDeclarations.get(name) ?? new Set<string>()
9106
- for (const declaration of swiftInterfaceDeclarations(header))
9107
- declarations.add(declaration)
9108
- for (const [candidate, source] of Object.entries(input.files))
9109
- if (included.has(path.posix.basename(candidate)))
9110
- for (const declaration of swiftInterfaceDeclarations(source))
9111
- declarations.add(declaration)
9112
- nativeDeclarations.set(name, declarations)
9113
- }
9114
- const frameworkInterface = (
9115
- name: string,
9116
- ): { file: string; header: string; module: boolean } | null => {
9117
- if (frameworkInterfaces.has(name)) return frameworkInterfaces.get(name)!
9118
- const source = distribution
9119
- ? path.join(frameworkRoot, 'modules', `${name}-Swift.h`)
9120
- : prebuilt!.objcHeaders.get(name)
9121
- if (!source || !existsSync(source)) {
9122
- frameworkInterfaces.set(name, null)
9123
- return null
9354
+ return { producer, original: `${stem}.original.h`, emitted: `${stem}.h` }
9355
+ }
9356
+ const publishHeader = ({
9357
+ producer,
9358
+ original,
9359
+ emitted,
9360
+ }: ReturnType<typeof headerPaths>) => {
9361
+ const generated = generatedInterface(original)
9362
+ writeBuildFile(
9363
+ emitted,
9364
+ withoutSwiftDeclarations(
9365
+ swiftHeaderWithSuperclassImports(generated, frameworkInterface),
9366
+ new Set([
9367
+ ...(preparation.nativeHeaderDeclarations[producer] ?? []),
9368
+ ...nativelyDeclaredFunctions(generated, nativeHeaders),
9369
+ ]),
9370
+ `#import <${producer}/${producer}.h>`,
9371
+ ),
9372
+ )
9373
+ }
9374
+ const recipe = inputHash
9375
+ .copy()
9376
+ .update(
9377
+ distribution ? swiftCompileSurfaceDigest(frameworkRoot) : moduleDigest,
9378
+ )
9379
+ .update(readFileSync(path.join(root, 'Package.swift')))
9380
+ .update(JSON.stringify(buildArgs))
9381
+ .digest('hex')
9382
+ const runApp = async (compiler?: Record<string, string>) => {
9383
+ const optionsWithCompiler = compiler
9384
+ ? { ...appOptions, env: { ...appOptions.env, ...compiler } }
9385
+ : appOptions
9386
+ // clang consumes the real emitted headers after swift finishes.
9387
+ // swiftpm's transitive swift module maps are not C declarations:
9388
+ // importing them would shadow SDK modules such as ObjectiveC.
9389
+ const stages = [
9390
+ ...(preparation.nativePrerequisiteTargets ?? []).map((target) => ({
9391
+ target,
9392
+ producers: [],
9393
+ })),
9394
+ ...preparation.headerBuilds,
9395
+ ...(preparation.nativeProductTargets ?? []).map((target) => ({
9396
+ target,
9397
+ producers: [],
9398
+ })),
9399
+ ]
9400
+ const checkpoints = path.join(root, '.build', 'peach-product-checkpoints')
9401
+ const buildDbExists = existsSync(path.join(root, '.build', 'build.db'))
9402
+ const releaseDir = path.dirname(linked)
9403
+ for (const { target, producers } of stages) {
9404
+ // pure native checkpoint stages exist only to commit build.db on cold
9405
+ // builds; when build.db and all stage objects are already warm, the
9406
+ // header stage and final full-graph build still validate every input.
9407
+ if (!options.project && producers.length === 0 && buildDbExists) {
9408
+ const expectedObjects = preparation.nativeStageObjects.get(target)
9409
+ if (
9410
+ expectedObjects &&
9411
+ expectedObjects.length > 0 &&
9412
+ expectedObjects.every((relative) =>
9413
+ statSync(path.join(releaseDir, relative), {
9414
+ throwIfNoEntry: false,
9415
+ })?.isFile(),
9416
+ )
9417
+ )
9418
+ continue
9124
9419
  }
9125
- const headers = path.join(sdkFrameworks, `${name}.framework/Headers`)
9126
- const declared = new Set<string>()
9127
- if (existsSync(headers))
9128
- for (const file of readdirSync(headers, {
9129
- recursive: true,
9130
- encoding: 'utf8',
9131
- }))
9132
- if (file.endsWith('.h'))
9133
- for (const name of swiftInterfaceDeclarations(
9134
- readFileSync(path.join(headers, file), 'utf8'),
9135
- ))
9136
- declared.add(name)
9137
- for (const declaration of nativeDeclarations.get(name) ?? [])
9138
- declared.add(declaration)
9139
- const own = withoutSwiftDeclarations(
9140
- generatedInterface(source),
9141
- declared,
9142
- nativeDeclarations.has(name)
9143
- ? `@import ${name};`
9144
- : `#import <${name}/${name}.h>`,
9420
+ const receipt = path.join(
9421
+ checkpoints,
9422
+ createHash('sha256').update(target).digest('hex'),
9145
9423
  )
9146
- // the swift module also implements classes another framework's headers
9147
- // already define; clang takes those from the owning framework
9148
- const owners = sdkObjCDeclarationOwners(sdkFrameworks)
9149
- const foreign = new Map<string, string>()
9150
- for (const declaration of [
9151
- ...swiftInterfaceDeclarations(own),
9152
- ...objcEnumerations(own),
9153
- ...[...own.matchAll(/^\s*SWIFT_EXTERN\b[^(\n]*?\b(\w+)\s*\(/gm)].map(
9154
- (match) => match[1]!,
9155
- ),
9156
- ]) {
9157
- const owner = owners.get(declaration)
9158
- if (owner && owner !== name) foreign.set(declaration, owner)
9159
- }
9160
- const header = foreign.size
9161
- ? withoutSwiftDeclarations(
9162
- own,
9163
- new Set(foreign.keys()),
9164
- [...new Set(foreign.values())]
9165
- .map((owner) => `#import <${owner}/${owner}.h>`)
9166
- .join('\n'),
9424
+ const headers = producers.map(headerPaths)
9425
+ for (const header of headers)
9426
+ if (existsSync(header.original)) publishHeader(header)
9427
+ const fingerprint = (): string | undefined => {
9428
+ const digest = createHash('sha256').update(recipe)
9429
+ for (const { original, emitted } of headers) {
9430
+ if (!existsSync(original) || !existsSync(emitted)) return
9431
+ digest.update(
9432
+ createHash('sha256').update(readFileSync(emitted)).digest(),
9167
9433
  )
9168
- : own
9169
- const value = {
9170
- file: path.join(root, '.build/peach-framework-objc', `${name}-Swift.h`),
9171
- header,
9172
- module: existsSync(headers),
9434
+ }
9435
+ return digest.digest('hex')
9173
9436
  }
9174
- frameworkInterfaces.set(name, value)
9175
- writeBuildFile(
9176
- value.file,
9177
- (existsSync(path.join(headers, `${name}.h`))
9178
- ? `#import <${name}/${name}.h>\n`
9179
- : '') + swiftHeaderWithSuperclassImports(header, frameworkInterface),
9180
- )
9181
- return value
9182
- }
9183
- const headerPaths = (producer: string) => {
9184
- const stem = path.join(
9185
- root,
9186
- '.build',
9187
- 'peach-cxx-headers',
9188
- `${producer}-Swift`,
9189
- )
9190
- return { producer, original: `${stem}.original.h`, emitted: `${stem}.h` }
9191
- }
9192
- const publishHeader = ({
9193
- producer,
9194
- original,
9195
- emitted,
9196
- }: ReturnType<typeof headerPaths>) => {
9197
- const generated = generatedInterface(original)
9198
- writeBuildFile(
9199
- emitted,
9200
- withoutSwiftDeclarations(
9201
- swiftHeaderWithSuperclassImports(generated, frameworkInterface),
9202
- new Set([
9203
- ...(preparation.nativeHeaderDeclarations[producer] ?? []),
9204
- ...nativelyDeclaredFunctions(generated, nativeHeaders),
9205
- ]),
9206
- `#import <${producer}/${producer}.h>`,
9207
- ),
9208
- )
9209
- }
9210
- const recipe = inputHash
9211
- .copy()
9212
- .update(
9213
- distribution ? swiftCompileSurfaceDigest(frameworkRoot) : moduleDigest,
9437
+ if (
9438
+ !options.project &&
9439
+ existsSync(receipt) &&
9440
+ readFileSync(receipt, 'utf8') === fingerprint()
9214
9441
  )
9215
- .update(readFileSync(path.join(root, 'Package.swift')))
9216
- .update(JSON.stringify(buildArgs))
9217
- .digest('hex')
9218
- const runApp = async (compiler?: Record<string, string>) => {
9219
- const optionsWithCompiler = compiler
9220
- ? { ...appOptions, env: { ...appOptions.env, ...compiler } }
9221
- : appOptions
9222
- // clang consumes the real emitted headers after swift finishes.
9223
- // swiftpm's transitive swift module maps are not C declarations:
9224
- // importing them would shadow SDK modules such as ObjectiveC.
9225
- const stages = [
9226
- ...(preparation.nativePrerequisiteTargets ?? []).map((target) => ({
9227
- target,
9228
- producers: [],
9229
- })),
9230
- ...preparation.headerBuilds,
9231
- ...(preparation.nativeProductTargets ?? []).map((target) => ({
9232
- target,
9233
- producers: [],
9234
- })),
9235
- ]
9236
- const checkpoints = path.join(root, '.build', 'peach-product-checkpoints')
9237
- const buildDbExists = existsSync(path.join(root, '.build', 'build.db'))
9238
- const releaseDir = path.dirname(linked)
9239
- for (const { target, producers } of stages) {
9240
- // pure native checkpoint stages exist only to commit build.db on cold
9241
- // builds; when build.db and all stage objects are already warm, the
9242
- // header stage and final full-graph build still validate every input.
9243
- if (!options.project && producers.length === 0 && buildDbExists) {
9244
- const expectedObjects = preparation.nativeStageObjects.get(target)
9245
- if (
9246
- expectedObjects &&
9247
- expectedObjects.length > 0 &&
9248
- expectedObjects.every((relative) =>
9249
- statSync(path.join(releaseDir, relative), {
9250
- throwIfNoEntry: false,
9251
- })?.isFile(),
9252
- )
9442
+ continue
9443
+ if (!options.project) rmSync(receipt, { force: true })
9444
+ // swiftpm doesn't track custom objc header paths as outputs.
9445
+ for (const header of headers) {
9446
+ if (!existsSync(header.original))
9447
+ rmSync(
9448
+ path.join(
9449
+ path.dirname(linked),
9450
+ 'Modules',
9451
+ `${swiftTargetModuleName(header.producer)}.swiftmodule`,
9452
+ ),
9453
+ { force: true },
9253
9454
  )
9254
- continue
9255
- }
9256
- const receipt = path.join(
9257
- checkpoints,
9258
- createHash('sha256').update(target).digest('hex'),
9259
- )
9260
- const headers = producers.map(headerPaths)
9261
- for (const header of headers)
9262
- if (existsSync(header.original)) publishHeader(header)
9263
- const fingerprint = (): string | undefined => {
9264
- const digest = createHash('sha256').update(recipe)
9265
- for (const { original, emitted } of headers) {
9266
- if (!existsSync(original) || !existsSync(emitted)) return
9267
- digest.update(
9268
- createHash('sha256').update(readFileSync(emitted)).digest(),
9269
- )
9270
- }
9271
- return digest.digest('hex')
9272
- }
9273
- if (
9274
- !options.project &&
9275
- existsSync(receipt) &&
9276
- readFileSync(receipt, 'utf8') === fingerprint()
9277
- )
9278
- continue
9279
- if (!options.project) rmSync(receipt, { force: true })
9280
- // swiftpm doesn't track custom objc header paths as outputs.
9281
- for (const header of headers) {
9282
- if (!existsSync(header.original))
9283
- rmSync(
9284
- path.join(
9285
- path.dirname(linked),
9286
- 'Modules',
9287
- `${swiftTargetModuleName(header.producer)}.swiftmodule`,
9288
- ),
9289
- { force: true },
9290
- )
9291
- }
9292
- await runCompiler(
9293
- swift,
9294
- [...buildArgs, '--target', target],
9295
- optionsWithCompiler,
9296
- /^(?:\[swift-prebuilt\]|\[\d+\/\d+\] )/,
9297
- SWIFTPM_NOISE,
9298
- )
9299
- if (!compiler) for (const header of headers) publishHeader(header)
9300
- if (!options.project) {
9301
- const checkpoint = fingerprint()
9302
- if (checkpoint === undefined)
9303
- throw new Error(`missing Swift headers after building ${target}`)
9304
- mkdirSync(checkpoints, { recursive: true })
9305
- writeFileSync(`${receipt}.partial`, checkpoint)
9306
- renameSync(`${receipt}.partial`, receipt)
9307
- }
9308
9455
  }
9309
- // always let swiftpm check the full graph, including missing outputs.
9310
9456
  await runCompiler(
9311
9457
  swift,
9312
- buildArgs,
9458
+ [...buildArgs, '--target', target],
9313
9459
  optionsWithCompiler,
9314
- SWIFTPM_PROGRESS,
9460
+ /^(?:\[swift-prebuilt\]|\[\d+\/\d+\] )/,
9315
9461
  SWIFTPM_NOISE,
9316
9462
  )
9463
+ if (!compiler) for (const header of headers) publishHeader(header)
9464
+ if (!options.project) {
9465
+ const checkpoint = fingerprint()
9466
+ if (checkpoint === undefined)
9467
+ throw new Error(`missing Swift headers after building ${target}`)
9468
+ mkdirSync(checkpoints, { recursive: true })
9469
+ writeFileSync(`${receipt}.partial`, checkpoint)
9470
+ renameSync(`${receipt}.partial`, receipt)
9471
+ }
9317
9472
  }
9318
- const compileApp = () =>
9319
- preparation.headerCompiler
9320
- ? withSwiftHeaderCompiler(
9321
- root,
9322
- options.toolchainBin,
9323
- recipe,
9324
- new Map(
9325
- preparation.headerBuilds[0]!.producers.map((producer) => {
9326
- const paths = headerPaths(producer)
9327
- return [
9328
- swiftTargetModuleName(producer),
9329
- {
9330
- header: paths.original,
9331
- publish: () => publishHeader(paths),
9332
- },
9333
- ]
9334
- }),
9335
- ),
9336
- runApp,
9337
- )
9338
- : runApp()
9339
- try {
9340
- if (temporaryDirectory) mkdirSync(temporaryDirectory, { recursive: true })
9341
- await compileApp()
9342
- } catch (error) {
9343
- const output = outputOf(error)
9344
- const moduleCache = path.join(
9345
- root,
9346
- '.build',
9347
- WASM_TRIPLE,
9348
- 'release',
9349
- 'ModuleCache',
9350
- )
9351
- if (
9352
- output.includes('was compiled with module cache path') &&
9353
- existsSync(moduleCache)
9354
- ) {
9355
- rmSync(moduleCache, { recursive: true, force: true })
9356
- try {
9357
- await compileApp()
9358
- } catch (retryError) {
9359
- throw new Error(
9360
- [
9361
- ...unprepared,
9362
- projectDiagnostic(outputOf(retryError), layout, input.files),
9363
- ].join('\n'),
9364
- { cause: retryError },
9365
- )
9366
- }
9367
- } else {
9368
- throw new Error(
9369
- [...unprepared, projectDiagnostic(output, layout, input.files)].join(
9370
- '\n',
9473
+ // always let swiftpm check the full graph, including missing outputs.
9474
+ await runCompiler(
9475
+ swift,
9476
+ buildArgs,
9477
+ optionsWithCompiler,
9478
+ SWIFTPM_PROGRESS,
9479
+ SWIFTPM_NOISE,
9480
+ )
9481
+ }
9482
+ const compileApp = () =>
9483
+ preparation.headerCompiler
9484
+ ? withSwiftHeaderCompiler(
9485
+ root,
9486
+ options.toolchainBin,
9487
+ recipe,
9488
+ new Map(
9489
+ preparation.headerBuilds[0]!.producers.map((producer) => {
9490
+ const paths = headerPaths(producer)
9491
+ return [
9492
+ swiftTargetModuleName(producer),
9493
+ {
9494
+ header: paths.original,
9495
+ publish: () => publishHeader(paths),
9496
+ },
9497
+ ]
9498
+ }),
9371
9499
  ),
9372
- { cause: error },
9500
+ runApp,
9501
+ )
9502
+ : runApp()
9503
+ try {
9504
+ if (temporaryDirectory) mkdirSync(temporaryDirectory, { recursive: true })
9505
+ await compileApp()
9506
+ } catch (error) {
9507
+ const output = outputOf(error)
9508
+ const moduleCache = path.join(
9509
+ root,
9510
+ '.build',
9511
+ WASM_TRIPLE,
9512
+ 'release',
9513
+ 'ModuleCache',
9514
+ )
9515
+ if (
9516
+ output.includes('was compiled with module cache path') &&
9517
+ existsSync(moduleCache)
9518
+ ) {
9519
+ rmSync(moduleCache, { recursive: true, force: true })
9520
+ try {
9521
+ await compileApp()
9522
+ } catch (retryError) {
9523
+ throw new Error(
9524
+ [
9525
+ ...unprepared,
9526
+ projectDiagnostic(outputOf(retryError), layout, input.files),
9527
+ ].join('\n'),
9528
+ { cause: retryError },
9373
9529
  )
9374
9530
  }
9375
- } finally {
9376
- if (temporaryDirectory)
9377
- rmSync(temporaryDirectory, { recursive: true, force: true })
9378
- // a manifest, macro or build tool can leave processes behind that
9379
- // outlive the compiler's own group; none runs once the host reads.
9380
- if (options.project) endSwiftProjectProcesses(options.project)
9381
- }
9382
- if (unprepared.length) throw new Error(unprepared.join('\n'))
9383
- if (!existsSync(linked)) {
9384
- const binDir = path.dirname(linked)
9385
- const found = existsSync(binDir)
9386
- ? readdirSync(binDir)
9387
- .filter((name) => name.endsWith('.wasm'))
9388
- .sort()
9389
- : []
9531
+ } else {
9390
9532
  throw new Error(
9391
- `swift-compile: the build produced no ${path.basename(linked)} (found: ${found.join(', ') || 'none'})`,
9533
+ [...unprepared, projectDiagnostic(output, layout, input.files)].join(
9534
+ '\n',
9535
+ ),
9536
+ { cause: error },
9392
9537
  )
9393
9538
  }
9394
- if (options.project) removeProjectLinks(root)
9395
- const resourceReferences = Object.values(input.resources ?? {}).map(
9396
- (value) => Buffer.from(value, 'base64'),
9539
+ } finally {
9540
+ if (temporaryDirectory)
9541
+ rmSync(temporaryDirectory, { recursive: true, force: true })
9542
+ // a manifest, macro or build tool can leave processes behind that
9543
+ // outlive the compiler's own group; none runs once the host reads.
9544
+ if (options.project) endSwiftProjectProcesses(options.project)
9545
+ }
9546
+ if (unprepared.length) throw new Error(unprepared.join('\n'))
9547
+ if (!existsSync(linked)) {
9548
+ const binDir = path.dirname(linked)
9549
+ const found = existsSync(binDir)
9550
+ ? readdirSync(binDir)
9551
+ .filter((name) => name.endsWith('.wasm'))
9552
+ .sort()
9553
+ : []
9554
+ throw new Error(
9555
+ `swift-compile: the build produced no ${path.basename(linked)} (found: ${found.join(', ') || 'none'})`,
9397
9556
  )
9398
- // the guest link prunes and links the response file itself.
9399
- if (!guestGraph)
9400
- pruneSwiftWasmLink(
9401
- root,
9402
- options.toolchainBin,
9403
- prebuilt?.root ?? frameworkRoot,
9404
- input.staticClangTargets,
9405
- options.project,
9406
- undefined,
9407
- resourceReferences,
9408
- )
9409
- if (options.linkOnly) {
9410
- if (statSync(linked).size <= 8)
9411
- throw new Error('swift-compile: deferred linker produced no executable')
9412
- report('project link verified')
9413
- return
9414
- }
9415
- const output = options.project
9416
- ? projectOutputFile(root, linked, options.project)
9417
- : linked
9418
- const optimized = `${output}.optimized`
9419
- if (sdkImage && options.project) rmSync(optimized, { force: true })
9420
- let sdkAsset: SwiftSdkModuleAsset | undefined
9421
- if (guestGraph) {
9422
- const binding = await compileGuestLink({
9423
- graph: guestGraph,
9424
- buildDirectory: root,
9425
- releaseDirectory: path.dirname(linked),
9426
- moduleRoot: frameworkRoot,
9427
- toolchainBin: options.toolchainBin,
9428
- swiftCompiler: preparation.headerCompiler
9429
- ? path.join(root, SWIFT_HEADER_COMPILER_WRAPPER)
9430
- : (compiler.SWIFT_EXEC ?? path.join(options.toolchainBin, 'swiftc')),
9431
- sysroot: swiftSdkPaths(frameworkRoot, options.toolchainBin).sysroot,
9432
- sdk: swiftModuleSdk(frameworkRoot),
9433
- sdkImage,
9434
- compilerDigest: compilerSourceDigest,
9435
- project: options.project && {
9436
- ...options.project,
9437
- env: { ...options.project.env, ...projectProcess?.env },
9438
- },
9439
- staticClangTargets: input.staticClangTargets ?? [],
9440
- resourceReferences,
9441
- resourceBundles: input.resourceBundles ?? [],
9442
- generatedOwners: preparation.generatedOwners,
9443
- output,
9444
- optimized,
9445
- optimize: input.optimize === true,
9446
- jobs: swiftBuildJobs(),
9447
- })
9448
- if (sdkImage && binding)
9449
- sdkAsset = { key: sdkImage.key, sha256: sdkImage.sha256, binding }
9450
- } else if (sdkImage) {
9451
- const { buildSwiftAppModule } = await import('./swift-sdk-app-module')
9452
- const binding = await buildSwiftAppModule({
9453
- buildRoot: root,
9454
- toolchainBin: options.toolchainBin,
9455
- sdk: sdkImage,
9456
- output: optimized,
9457
- optimize: input.optimize === true,
9458
- project: options.project && {
9459
- ...options.project,
9460
- env: { ...options.project.env, ...projectProcess?.env },
9461
- sdkRoot: path.dirname(
9462
- swiftSdkPaths(frameworkRoot, options.toolchainBin).sysroot,
9463
- ),
9464
- linked: output,
9465
- },
9466
- })
9467
- sdkAsset = { key: sdkImage.key, sha256: sdkImage.sha256, binding }
9468
- } else {
9469
- const bytes = readFileSync(output)
9470
- const ordered = orderObjCConstructors(bytes)
9471
- if (ordered !== bytes) writeFileSync(output, ordered)
9472
- await lowerWasm(output, optimized, { optimize: input.optimize === true })
9473
- }
9474
- if (!sdkImage)
9475
- await runCompiler(
9476
- path.join(options.toolchainBin, 'llvm-objcopy'),
9477
- ['--remove-section=.swift1_autolink_entries', optimized],
9478
- buildOptions,
9479
- )
9480
- const artifact = {
9481
- hash,
9482
- bytes: readFileSync(optimized),
9483
- icu: await icu!,
9484
- sdk: sdkAsset,
9485
- }
9486
- if (artifact.bytes.length <= 8)
9557
+ }
9558
+ if (options.project) removeProjectLinks(root)
9559
+ const resourceReferences = Object.values(input.resources ?? {}).map((value) =>
9560
+ Buffer.from(value, 'base64'),
9561
+ )
9562
+ // the guest link prunes and links the response file itself.
9563
+ if (!guestGraph)
9564
+ pruneSwiftWasmLink(
9565
+ root,
9566
+ options.toolchainBin,
9567
+ prebuilt?.root ?? frameworkRoot,
9568
+ input.staticClangTargets,
9569
+ options.project,
9570
+ undefined,
9571
+ resourceReferences,
9572
+ )
9573
+ if (options.linkOnly) {
9574
+ if (statSync(linked).size <= 8)
9487
9575
  throw new Error('swift-compile: deferred linker produced no executable')
9488
- if (!options.project) saveCompiledArtifact(root, artifact)
9489
- saveSharedArtifact(sharedRoot, artifact)
9490
- report('compiled artifact verified')
9491
- return retain(root, artifact)
9492
- } finally {
9493
- readHold?.release()
9576
+ stage('project link verified')
9577
+ return
9494
9578
  }
9495
- },
9496
- budget.signal,
9497
- )
9579
+ const output = options.project
9580
+ ? projectOutputFile(root, linked, options.project)
9581
+ : linked
9582
+ const optimized = `${output}.optimized`
9583
+ if (sdkImage && options.project) rmSync(optimized, { force: true })
9584
+ let sdkAsset: SwiftSdkModuleAsset | undefined
9585
+ stage('linking the app image')
9586
+ if (guestGraph) {
9587
+ const binding = await compileGuestLink({
9588
+ graph: guestGraph,
9589
+ buildDirectory: root,
9590
+ releaseDirectory: path.dirname(linked),
9591
+ moduleRoot: frameworkRoot,
9592
+ toolchainBin: options.toolchainBin,
9593
+ swiftCompiler: preparation.headerCompiler
9594
+ ? path.join(root, SWIFT_HEADER_COMPILER_WRAPPER)
9595
+ : (compiler.SWIFT_EXEC ?? path.join(options.toolchainBin, 'swiftc')),
9596
+ sysroot: swiftSdkPaths(frameworkRoot, options.toolchainBin).sysroot,
9597
+ sdk: swiftModuleSdk(frameworkRoot),
9598
+ sdkImage,
9599
+ compilerDigest: compilerSourceDigest,
9600
+ project: options.project && {
9601
+ ...options.project,
9602
+ env: { ...options.project.env, ...projectProcess?.env },
9603
+ },
9604
+ staticClangTargets: input.staticClangTargets ?? [],
9605
+ resourceReferences,
9606
+ resourceBundles: input.resourceBundles ?? [],
9607
+ generatedOwners: preparation.generatedOwners,
9608
+ output,
9609
+ optimized,
9610
+ optimize: input.optimize === true,
9611
+ jobs: swiftBuildJobs(),
9612
+ onStage: stage,
9613
+ })
9614
+ if (sdkImage && binding)
9615
+ sdkAsset = { key: sdkImage.key, sha256: sdkImage.sha256, binding }
9616
+ } else if (sdkImage) {
9617
+ const { buildSwiftAppModule } = await import('./swift-sdk-app-module')
9618
+ const binding = await buildSwiftAppModule({
9619
+ buildRoot: root,
9620
+ toolchainBin: options.toolchainBin,
9621
+ sdk: sdkImage,
9622
+ output: optimized,
9623
+ optimize: input.optimize === true,
9624
+ project: options.project && {
9625
+ ...options.project,
9626
+ env: { ...options.project.env, ...projectProcess?.env },
9627
+ sdkRoot: path.dirname(
9628
+ swiftSdkPaths(frameworkRoot, options.toolchainBin).sysroot,
9629
+ ),
9630
+ linked: output,
9631
+ },
9632
+ })
9633
+ sdkAsset = { key: sdkImage.key, sha256: sdkImage.sha256, binding }
9634
+ } else {
9635
+ const bytes = readFileSync(output)
9636
+ const ordered = orderObjCConstructors(bytes)
9637
+ if (ordered !== bytes) writeFileSync(output, ordered)
9638
+ stage('lowering the app image')
9639
+ await lowerWasm(output, optimized, { optimize: input.optimize === true })
9640
+ }
9641
+ if (!sdkImage)
9642
+ await runCompiler(
9643
+ path.join(options.toolchainBin, 'llvm-objcopy'),
9644
+ ['--remove-section=.swift1_autolink_entries', optimized],
9645
+ buildOptions,
9646
+ )
9647
+ const artifact = {
9648
+ hash,
9649
+ bytes: readFileSync(optimized),
9650
+ icu: await icu!,
9651
+ sdk: sdkAsset,
9652
+ }
9653
+ if (artifact.bytes.length <= 8)
9654
+ throw new Error('swift-compile: deferred linker produced no executable')
9655
+ if (!options.project) saveCompiledArtifact(root, artifact)
9656
+ saveSharedArtifact(sharedRoot, artifact)
9657
+ stage('compiled artifact verified')
9658
+ return retain(baseRoot, artifact)
9659
+ } finally {
9660
+ readHold?.release()
9661
+ }
9662
+ })
9498
9663
  })
9499
9664
  },
9500
9665
  options.signal,