// expo's own autolinker selects app-owned Swift modules; the common Swift host
// links their registrations together and isolates namespaces only when that fails.
import { AsyncLocalStorage } from 'node:async_hooks'
import { execFile } from 'node:child_process'
import { createHash } from 'node:crypto'
import fs from 'node:fs'
import { createRequire } from 'node:module'
import os from 'node:os'
import path from 'node:path'
import { fileURLToPath } from 'node:url'
import { promisify } from 'node:util'
import { EXPO_EAGER_NATIVE_VIEWS } from '../../peach-compat/src/stubs/native-seams/expo-eager-seam-contract'
import { resolveAppProject } from '../cli/app-project'
import { peachAnsweredNativePackages } from './answeredNativePackages'
import { loadRNXAppConfig } from './app-config'
import { isLoopbackHost } from './backend-origin'
import { autolinkerAppleFlags } from './expo-autolinking'
import {
  expoDiscoveryKey,
  readExpoDiscovery,
  writeExpoDiscovery,
} from './expo-discovery-cache'
import { prebuiltExpoNative, prebuiltExpoSwiftResult } from './expo-native-prebuilt'
import {
  nativeWorkspaceAvailable,
  prepareExpoNativeWorkspace,
} from './expo-native-workspace'
import { PEACH_FORKED_SCRIPT_ENV } from './forked-script-contract'
import { cacheDir } from './home-paths'
import { isRecord } from './is-record'
import { readExpoConfigAsync } from './native-firebase-config'
import { NativePreparationReceipts } from './native-preparation'
import {
  combineNativeStaticLibraries,
  nonmodularFrameworkLibraries,
} from './native-static-libraries'
import {
  NATIVE_PREPARE_QUERY_PARAM,
  NATIVE_PREPARED_QUERY_PARAM,
} from './nativePreparationContract'
import { preparedXcodeInterfaces } from './prepared-xcode-phases'
import {
  BRIDGE_MODULE_FILE_PREFIX,
  collectBridgeModuleSources,
} from './react-native-bridge-modules'
import { prebuiltReactNativeCore } from './react-native-core'
import { swiftBinaryModules } from './swift-binary-modules'
import {
  swiftAvailableModules,
  swiftCodeMask,
  swiftImportNames,
  swiftPeachModules,
  swiftModuleInterface,
  swiftSourceClosure,
  swiftTargetDependencies,
  syncSwiftTree,
  withoutSwiftDeclarations,
} from './swift-compile'
import {
  ensureSwiftToolchain,
  resolveSwiftModule,
  swiftModuleToolchain,
} from './swift-distribution'
import {
  artifactFor,
  icuUrl,
  installedWorkspaceInput,
  withXcodeProject,
  projectFor,
  serveSwiftPackageAsset,
  sourceContentStamp,
  swiftProjectAppInfo,
  standinLibraries,
  SwiftMissingModulesError,
  prepareXcodeSwiftPackages,
} from './swift-host'
import { iosDeploymentMinimum } from './swift-objc-standin'
import {
  clangImportNames,
  isSwiftNativeTranslationUnit,
  manifestCalls,
  moduleMapName,
  swiftManifestTargets,
  swiftManifestSettings,
  swiftNativeSupportFiles,
  SWIFT_STANDINS_DIR,
  type SwiftPackageTarget,
} from './swift-package'
import { swiftRootLocksDir } from './swift-root-lock'
import { standinGenerationInputs, swiftStandins } from './swift-standins'
import { MAX_SWIFT_COMPILE_FILES, MAX_SWIFT_COMPILE_SOURCE_BYTES } from './swift-submit'
import { swiftCacheDir } from './swift-toolchain'
import { registersReactModule } from './turbo-source'
import type { PeachConfig } from './config'
import type {
  ExpoSwiftSourceUnit,
  ExpoSwiftCompilationResult,
  ExpoSwiftDiscoveryResult,
  ExpoSwiftPreparationOptions,
  ExpoSwiftSourceOptions,
} from './expoSwiftContract'
import type { NativeAppIdentity } from './native-app-identity'
import type { SwiftPackageBinary } from './swift-packages'
import type { SwiftStandin } from './swift-standins'
import type { SwiftNativeTarget } from './swiftContract'
import type { IncomingMessage, ServerResponse } from 'node:http'

const run = promisify(execFile)
// the compiled CLI's execPath is peach itself, which runs a forked `.js` as a
// script only with this set; node and bun ignore it.
const scriptEnv = { ...process.env, [PEACH_FORKED_SCRIPT_ENV]: '1' }
export const EXPO_SWIFT_ROUTE = '/__peach/expo-swift'
export const EXPO_SWIFT_ENTRY = 'Sources/PeachExpoApp/PeachExpoEntry.swift'

// discovery walks the prepared workspace on the calling thread. each input is
// stamped just before it is read and never restamped, so a stamp is never newer
// than what was consumed. a later call stats the stamps and returns the same
// units when nothing changed; an input that moved while the run was in flight
// leaves the entry uncached.
const WITNESS_BATCH = 200
const traceStore = new AsyncLocalStorage<Witness>()
const discoveryCache = new Map<string, DiscoveryEntry>()
const preparedCache = new Map<string, PreparedEntry>()

type MissingMark = { missing: true }
type PresentMark = {
  lstatMtimeNs: string
  lstatSize: number
  statMtimeNs: string
  statSize: number
  link: boolean
  dangling: boolean
  names?: string
  recursive?: boolean
}
type FileMark = MissingMark | PresentMark
type Witness = {
  marks: Map<string, FileMark>
  // set when an input was seen in two different states during one run
  tainted: boolean
}
type DiscoveryEntry = {
  witness: Witness
  units: ExpoSwiftSourceUnit[] | null
}
type PreparedEntry = {
  witness: Witness
  base: string
  result: ExpoSwiftCompilationResult
}
type SavedFs = {
  readFileSync: typeof fs.readFileSync
  readdirSync: typeof fs.readdirSync
  existsSync: typeof fs.existsSync
  statSync: typeof fs.statSync
  lstatSync: typeof fs.lstatSync
  realpathSync: typeof fs.realpathSync
  realpathNative: typeof fs.realpathSync.native
  readlinkSync: typeof fs.readlinkSync
}

let savedFs: SavedFs | null = null
let ignoredRoots: string[] = []
// a directory this process made with mkdtemp holds its own scratch output (an
// evaluated config, a staged bundle), never an input a later discovery reads.
const ownTemporaryRoots = new Set<string>()

function isEnoent(error: unknown): boolean {
  return error instanceof Error && 'code' in error && error.code === 'ENOENT'
}

function isAbsent(error: unknown): boolean {
  return (
    error instanceof Error &&
    'code' in error &&
    (error.code === 'ENOENT' || error.code === 'ENOTDIR')
  )
}

function mtimeNs(stat: fs.Stats): string {
  const precise = Reflect.get(stat, 'mtimeNs')
  return typeof precise === 'bigint' ? precise.toString() : String(stat.mtimeMs)
}

function tracedPath(value: unknown): string | null {
  if (typeof value === 'number' || value == null) return null
  if (typeof value === 'string') return value.length === 0 ? null : path.resolve(value)
  if (value instanceof URL)
    return value.protocol === 'file:' ? fileURLToPath(value) : null
  if (Buffer.isBuffer(value)) return path.resolve(value.toString())
  return null
}

function ignoredInput(file: string): boolean {
  if (
    file.includes(`${path.sep}peach-expo-swift${path.sep}`) ||
    file.endsWith(`${path.sep}peach-expo-swift`)
  )
    return true
  const within = (root: string) => file === root || file.startsWith(`${root}${path.sep}`)
  if (ignoredRoots.some(within)) return true
  for (const root of ownTemporaryRoots) if (within(root)) return true
  return false
}

function noteMissing(file: string): void {
  const witness = traceStore.getStore()
  if (!witness || ignoredInput(file)) return
  const prior = witness.marks.get(file)
  if (prior === undefined) witness.marks.set(file, { missing: true })
  else if (!('missing' in prior)) witness.tainted = true
}

// the stamp is taken before the read it covers and kept for the whole run.
function notePresent(file: string): void {
  const witness = traceStore.getStore()
  const saved = savedFs
  if (!witness || !saved || ignoredInput(file)) return
  const prior = witness.marks.get(file)
  if (prior !== undefined) {
    // an input first seen missing must still be missing when it is read again.
    if ('missing' in prior && saved.existsSync(file)) witness.tainted = true
    return
  }
  let lstat: fs.Stats
  try {
    lstat = saved.lstatSync(file)
  } catch (error) {
    // a path joined onto a file is absent the same way a missing path is
    if (isAbsent(error)) {
      noteMissing(file)
      return
    }
    throw error
  }
  let followed: fs.Stats | null = null
  try {
    followed = saved.statSync(file)
  } catch (error) {
    if (!isAbsent(error)) throw error
  }
  witness.marks.set(file, {
    lstatMtimeNs: mtimeNs(lstat),
    lstatSize: lstat.size,
    statMtimeNs: mtimeNs(followed ?? lstat),
    statSize: (followed ?? lstat).size,
    link: lstat.isSymbolicLink(),
    dangling: followed === null,
  })
}

// a recursive listing's names are compared on top of the directory stamp,
// because an entry added below the top directory leaves its timestamp alone.
function noteListing(file: string, names: string): void {
  const witness = traceStore.getStore()
  if (!witness || ignoredInput(file)) return
  const mark = witness.marks.get(file)
  if (mark === undefined || 'missing' in mark) {
    witness.tainted = true
    return
  }
  if (mark.names === undefined) {
    mark.names = names
    mark.recursive = true
  } else if (mark.names !== names) witness.tainted = true
}

// an input stamped only after a child consumed it is bound to the child's
// start: a later modification time means the stamp may describe newer bytes.
function noteChangedSince(file: string, startMs: number): void {
  const witness = traceStore.getStore()
  if (witness && fs.statSync(file).mtimeMs >= startMs) witness.tainted = true
}

function noteRead(target: unknown): void {
  const file = tracedPath(target)
  if (file) notePresent(file)
}

function listsRecursively(options: unknown): boolean {
  return (
    options !== null &&
    typeof options === 'object' &&
    Reflect.get(options, 'recursive') === true
  )
}

function namesFromListing(dir: string, entries: readonly unknown[]): string {
  const names: string[] = []
  for (const entry of entries) {
    if (typeof entry === 'string' || Buffer.isBuffer(entry)) {
      names.push(entry.toString().split(path.sep).join('/'))
      continue
    }
    if (!entry || typeof entry !== 'object' || !('name' in entry)) continue
    const name = String(Reflect.get(entry, 'name'))
    const parent = Reflect.get(entry, 'parentPath')
    const base = typeof parent === 'string' && parent.length > 0 ? parent : dir
    names.push(path.relative(dir, path.join(base, name)).split(path.sep).join('/'))
  }
  names.sort()
  return names.join('\0')
}

function installSwiftInputTrace(): void {
  if (savedFs) return
  const realpathNative = fs.realpathSync.native
  const saved: SavedFs = {
    readFileSync: fs.readFileSync,
    readdirSync: fs.readdirSync,
    existsSync: fs.existsSync,
    statSync: fs.statSync,
    lstatSync: fs.lstatSync,
    realpathSync: fs.realpathSync,
    realpathNative,
    readlinkSync: fs.readlinkSync,
  }
  savedFs = saved
  const prefixes = [
    path.join(cacheDir(), 'swift-builds'),
    path.join(swiftCacheDir(), 'swift-builds'),
    path.join(swiftCacheDir(), 'swift-sdk-views'),
    swiftRootLocksDir(),
    path.join(cacheDir(), 'swift-tmp'),
  ].filter((prefix, index, all) => all.indexOf(prefix) === index)
  ignoredRoots = prefixes.flatMap((root) => {
    try {
      const real = saved.realpathSync(root)
      return real === root ? [root] : [root, real]
    } catch {
      return [root]
    }
  })
  const traced =
    (method: Function) =>
    (...args: unknown[]) => {
      noteRead(args[0])
      return Reflect.apply(method, undefined, args)
    }
  const realpath = traced(saved.realpathSync)
  Reflect.set(realpath, 'native', traced(saved.realpathNative))
  Reflect.set(fs, 'readFileSync', traced(saved.readFileSync))
  Reflect.set(fs, 'statSync', traced(saved.statSync))
  Reflect.set(fs, 'lstatSync', traced(saved.lstatSync))
  Reflect.set(fs, 'readlinkSync', traced(saved.readlinkSync))
  Reflect.set(fs, 'realpathSync', realpath)
  const mkdtempSync = fs.mkdtempSync
  Reflect.set(fs, 'mkdtempSync', (...args: unknown[]): unknown => {
    const made: unknown = Reflect.apply(mkdtempSync, undefined, args)
    if (typeof made === 'string' && traceStore.getStore()) {
      // a removed root's unique name never returns, so forgetting it is safe.
      for (const root of ownTemporaryRoots)
        if (!saved.existsSync(root)) ownTemporaryRoots.delete(root)
      ownTemporaryRoots.add(path.resolve(made))
    }
    return made
  })
  Reflect.set(fs, 'existsSync', (targetPath: fs.PathLike): boolean => {
    const file = tracedPath(targetPath)
    const witness = traceStore.getStore()
    if (!file || !witness || ignoredInput(file)) return saved.existsSync(targetPath)
    notePresent(file)
    const mark = witness.marks.get(file)
    const present = saved.existsSync(targetPath)
    if (mark && present !== ('missing' in mark ? false : !mark.dangling))
      witness.tainted = true
    return present
  })
  Reflect.set(fs, 'readdirSync', (directory: fs.PathLike, options?: unknown): unknown => {
    const file = tracedPath(directory)
    if (file) notePresent(file)
    try {
      const listed: unknown =
        options === undefined
          ? saved.readdirSync(directory)
          : Reflect.apply(saved.readdirSync, undefined, [directory, options])
      if (file && listsRecursively(options) && Array.isArray(listed))
        noteListing(file, namesFromListing(file, listed))
      return listed
    } catch (error) {
      if (file && isEnoent(error)) noteMissing(file)
      throw error
    }
  })
}

async function markMatches(file: string, mark: FileMark): Promise<boolean> {
  if ('missing' in mark) {
    try {
      await fs.promises.lstat(file)
      return false
    } catch {
      return true
    }
  }
  let lstat: fs.Stats
  try {
    lstat = await fs.promises.lstat(file)
  } catch {
    return false
  }
  if (mtimeNs(lstat) !== mark.lstatMtimeNs || lstat.size !== mark.lstatSize) return false
  if (mark.names !== undefined) {
    try {
      const listing = await fs.promises.readdir(file, {
        withFileTypes: true,
        recursive: true,
      })
      if (namesFromListing(file, listing) !== mark.names) return false
    } catch {
      return false
    }
  }
  if (!mark.link && !mark.dangling && !lstat.isSymbolicLink()) return true
  try {
    const stat = await fs.promises.stat(file)
    if (mark.dangling) return false
    return mtimeNs(stat) === mark.statMtimeNs && stat.size === mark.statSize
  } catch (error) {
    return mark.dangling && isEnoent(error)
  }
}

async function witnessMatches(witness: Witness): Promise<boolean> {
  if (witness.tainted) return false
  const entries = [...witness.marks]
  for (let index = 0; index < entries.length; index += WITNESS_BATCH) {
    await new Promise((resolve) => setImmediate(resolve))
    const batch = entries.slice(index, index + WITNESS_BATCH)
    const matches = await Promise.all(
      batch.map(([file, mark]) => markMatches(file, mark)),
    )
    if (matches.some((match) => !match)) return false
  }
  return true
}

// the evaluated Expo config is a key input: a child process evaluates it from
// app config, plugins and env files the witness cannot see, and its result file
// is new on every run, so it is read untraced and compared here instead.
async function discoveryKey(
  root: string,
  installedWorkspace: string | undefined,
  prepareNative: boolean,
  iosTarget: string | undefined,
  moduleRoot?: string,
): Promise<string> {
  const [config, expoConfig] = await Promise.all([
    loadRNXAppConfig(resolveAppProject(root)),
    readExpoConfigAsync(root),
  ])
  return `${fs.realpathSync(root)}\0${installedWorkspace ?? ''}\0${iosTarget ?? ''}\0${moduleRoot ?? ''}\0${prepareNative ? '1' : '0'}\0${JSON.stringify(config)}\0${JSON.stringify(expoConfig)}`
}

function cloneNativeTarget(target: SwiftNativeTarget): SwiftNativeTarget {
  return {
    ...target,
    headers: target.headers.slice(),
    publicHeaders: target.publicHeaders.slice(),
    headerSearchPaths: target.headerSearchPaths.slice(),
    userHeaderSearchPaths: target.userHeaderSearchPaths.slice(),
    frameworkSearchPaths: target.frameworkSearchPaths.slice(),
    flags: target.flags.slice(),
    importerFlags: target.importerFlags.slice(),
    cxxFlags: target.cxxFlags.slice(),
    headerMaps: target.headerMaps.map((map) => ({
      flag: map.flag,
      entries: map.entries.map((entry): [string, string] => [entry[0], entry[1]]),
    })),
    productHeaders: { ...target.productHeaders },
    fileFlags: Object.fromEntries(
      Object.entries(target.fileFlags).map(([name, flags]) => [name, flags.slice()]),
    ),
    sourceDirectories: { ...target.sourceDirectories },
  }
}

// a podspec without a platform declaration is available everywhere; otherwise
// only the platforms it names are, through platforms, platform or a
// per-platform deployment target. ruby beyond those literals is not evaluated.
function podSupportsIOS(pod: unknown): boolean {
  if (
    !isRecord(pod) ||
    typeof pod.podName !== 'string' ||
    typeof pod.podspecDir !== 'string'
  )
    throw new Error('invalid Expo autolinking pod')
  const base = path.join(pod.podspecDir, pod.podName)
  if (fs.existsSync(`${base}.podspec.json`)) {
    const platforms: unknown = JSON.parse(
      fs.readFileSync(`${base}.podspec.json`, 'utf8'),
    ).platforms
    return !isRecord(platforms) || 'ios' in platforms
  }
  if (!fs.existsSync(`${base}.podspec`)) return true
  const spec = fs.readFileSync(`${base}.podspec`, 'utf8')
  const names = new Set<string>()
  for (const [, hash] of spec.matchAll(/\.platforms\s*=\s*\{([^}]*)\}/g))
    for (const [, a, b, c] of hash!.matchAll(
      /:(\w+)\s*=>|\b(\w+):\s|['"](\w+)['"]\s*=>/g,
    ))
      names.add((a ?? b ?? c)!)
  for (const [, name] of spec.matchAll(/\.platform\s*=\s*:(\w+)/g)) names.add(name!)
  for (const [, name] of spec.matchAll(/\.(\w+)\.deployment_target\s*=/g))
    names.add(name!)
  return names.size === 0 || names.has('ios')
}

// a deployment entry for a target the adapter synthesizes: no clang inputs
// of its own, only an inherited floor.
function synthesizedNativeTarget(
  name: string,
  deploymentTarget: string,
): SwiftNativeTarget {
  return {
    name,
    deploymentTarget,
    headers: [],
    publicHeaders: [],
    flattensPublicHeaders: false,
    bridgingHeader: null,
    prefixHeader: null,
    headerSearchPaths: [],
    userHeaderSearchPaths: [],
    frameworkSearchPaths: [],
    headerMaps: [],
    productHeaders: {},
    flags: [],
    importerFlags: [],
    cxxFlags: [],
    fileFlags: {},
    sourceDirectories: {},
  }
}

// a deployment entry for a generated stand-in target carries its real clang
// inputs, so native preparation stages the hand-written module map and
// headers exactly like a swiftpm clang target. a bare entry fails
// preparation and the pure-c target compiles as an empty swift module,
// hiding every c declaration from its swift importers.
function standinNativeTarget(
  standin: SwiftStandin,
  deploymentTarget: string,
): SwiftNativeTarget {
  const prefix = `${SWIFT_STANDINS_DIR}/${standin.module}/`
  const headers = Object.keys(standin.files)
    .filter((file) => /\.(?:h|hpp|hh|hxx)$/.test(file))
    .map((file) => `${prefix}${file}`)
    .sort()
  const modulemap = Object.keys(standin.files).find(
    (file) => file === 'module.modulemap' || file.endsWith('/module.modulemap'),
  )
  const headerDir =
    (modulemap ? path.posix.dirname(`${prefix}${modulemap}`) : null) ??
    commonStandinHeaderDir(prefix, headers) ??
    `${prefix}include`
  return {
    ...synthesizedNativeTarget(standin.module, deploymentTarget),
    headers,
    publicHeaders: headers.filter((file) => file.startsWith(`${headerDir}/`)),
    headerSearchPaths: [headerDir],
  }
}

// the deepest stand-in directory holding every header, or null when the
// headers span disjoint trees. both paths share the stand-in prefix, so the
// climb always stops at or under it.
function commonStandinHeaderDir(prefix: string, headers: string[]): string | null {
  if (headers.length === 0) return null
  let common = path.posix.dirname(headers[0]!)
  for (const header of headers.slice(1)) {
    const dir = path.posix.dirname(header)
    while (dir !== common && !dir.startsWith(`${common}/`))
      common = path.posix.dirname(common)
  }
  return common === prefix.slice(0, -1) || common.startsWith(prefix) ? common : null
}

// the synthesized executable stands in for the app itself; without a pod of
// its own it builds at the minimum resolved floor of the targets it links,
// so it runs everywhere its modules run.
function inheritExecutableFloor(
  targets: SwiftNativeTarget[] | undefined,
): SwiftNativeTarget[] | undefined {
  if (!targets || targets.some((target) => target.name === 'PeachExpoApp')) return targets
  let floor: string | null = null
  let floorNumber = Number.POSITIVE_INFINITY
  for (const target of targets) {
    const minimum = iosDeploymentMinimum(target.deploymentTarget)
    if (minimum === undefined || minimum >= floorNumber) continue
    floorNumber = minimum
    floor = target.deploymentTarget
  }
  if (floor === null) return targets
  return [...targets, synthesizedNativeTarget('PeachExpoApp', floor)]
}

function cloneUnits(units: ExpoSwiftSourceUnit[] | null): ExpoSwiftSourceUnit[] | null {
  if (!units) return null
  return units.map((unit) => ({
    ...unit,
    classes: unit.classes.slice(),
    bridgeModules: unit.bridgeModules.slice(),
    appDelegateSubscribers: unit.appDelegateSubscribers.slice(),
    reactDelegateHandlers: unit.reactDelegateHandlers.slice(),
    frameworks: unit.frameworks.slice(),
    ...(unit.workspaceSources ? { workspaceSources: unit.workspaceSources.slice() } : {}),
    files: { ...unit.files },
    ...(unit.nativeFiles ? { nativeFiles: { ...unit.nativeFiles } } : {}),
    ...(unit.headerAliases ? { headerAliases: { ...unit.headerAliases } } : {}),
    ...(unit.resources ? { resources: { ...unit.resources } } : {}),
    ...(unit.resourceBundles
      ? {
          resourceBundles: unit.resourceBundles.map((bundle) => ({
            ...bundle,
          })),
        }
      : {}),
    ...(unit.nativeTargets
      ? { nativeTargets: unit.nativeTargets.map(cloneNativeTarget) }
      : {}),
  }))
}

function cloneResult(result: ExpoSwiftCompilationResult): ExpoSwiftCompilationResult {
  return {
    ...(result.nativeAppIdentity ? { nativeAppIdentity: result.nativeAppIdentity } : {}),
    namespaces: result.namespaces.slice(),
    ...(result.bridgeModules ? { bridgeModules: result.bridgeModules.slice() } : {}),
    modules: result.modules.map((module) => ({
      ...module,
      namespaces: module.namespaces.slice(),
    })),
    failures: result.failures.map((failure) => ({ ...failure })),
  }
}

function replaceBase(value: string, from: string, to: string): string {
  if (value === from) return to
  if (!value.startsWith(`${from}/`)) return value
  return `${to}${value.slice(from.length)}`
}

function retarget(cached: PreparedEntry, base: string): ExpoSwiftCompilationResult {
  const result = cloneResult(cached.result)
  if (cached.base === base) return result
  for (const module of result.modules) {
    module.url = replaceBase(module.url, cached.base, base)
    module.icuUrl = replaceBase(module.icuUrl, cached.base, base)
  }
  return result
}

// only omit a class when its module and every declared view have app-owned
// answers. an unresolved definition stays native, including partial overrides.
function configuredExpoSwiftModule(
  files: Record<string, string>,
  className: string,
  registrationName: string | null,
  config: PeachConfig | undefined,
): boolean {
  for (const source of Object.values(files)) {
    const code = swiftCodeMask(source)
    const declaration = new RegExp(`\\bclass\\s+${className}\\b[^{}]*\\{`).exec(code)
    if (!declaration) continue
    const start = declaration.index + declaration[0].length
    let depth = 1
    let end = start
    while (end < code.length && depth > 0) {
      if (code[end] === '{') depth++
      else if (code[end] === '}') depth--
      end++
    }
    const body = source.slice(start, end - 1)
    const mask = code.slice(start, end - 1)
    const names = [...body.matchAll(/\bName\s*\(\s*"([A-Za-z_]\w*)"\s*\)/g)].filter(
      (match) => mask.startsWith('Name', match.index),
    )
    if (names.length > 1) return false
    const name = registrationName ?? names[0]?.[1]
    if (!name) return false
    const builtInView =
      config?.nativeModules?.[name] === false
        ? undefined
        : EXPO_EAGER_NATIVE_VIEWS.get(name)
    if (!config?.nativeModules?.[name] && !builtInView) return false
    const views = [
      ...mask.matchAll(/\bView\s*\(\s*([A-Za-z_]\w*(?:\.[A-Za-z_]\w*)*)\.self\s*\)/g),
    ]
    if ([...mask.matchAll(/\bView\s*\(/g)].length !== views.length) return false
    return views.every(
      (view) =>
        Boolean(config?.nativeViews?.[`${name}_${view[1]!.split('.').pop()!}`]) ||
        builtInView === `${name}_${view[1]!.split('.').pop()!}` ||
        (views.length === 1 && Boolean(config?.nativeViews?.[name])),
    )
  }
  return false
}

function enrichInstalledUnits(
  units: ExpoSwiftSourceUnit[],
  installed: Awaited<ReturnType<typeof installedWorkspaceInput>>,
  namespaceGroups: Map<string, string[]>,
  provided: ReadonlySet<string>,
  moduleRoot: string,
  appRoot: string,
  bridgeNamespaces: ReadonlySet<string> = new Set(),
  interfaceRoot?: string,
): void {
  const { input, binaryFrameworks } = installed
  // each unit generates its own binary stand-ins, so the workspace's are not re-mapped
  const installedTargets = swiftManifestTargets(
    input.files['Package.swift'] ?? '',
  ).filter((target) => !target.path.startsWith(`${SWIFT_STANDINS_DIR}/`))
  const targetByName = new Map(installedTargets.map((target) => [target.name, target]))
  const importedTargets = swiftTargetDependencies(input.files, installedTargets)
  const sourceImports = swiftTargetDependencies(
    input.files,
    installedTargets.map((target) => ({ ...target, dependencies: undefined })),
  )
  const byPath = [...installedTargets].sort((a, b) => b.path.length - a.path.length)
  const reactNativeRoot =
    fs.realpathSync(
      path.dirname(
        createRequire(path.join(appRoot, 'package.json')).resolve(
          'react-native/package.json',
        ),
      ),
    ) + path.sep
  const reactTargets = new Set(
    (input.nativeTargets ?? []).flatMap((target) => {
      const originals = Object.keys(target.sourceDirectories).flatMap((file) =>
        installed.sourcePaths[file] ? [installed.sourcePaths[file]!] : [],
      )
      return originals.some((file) => fs.realpathSync(file).startsWith(reactNativeRoot))
        ? [target.name]
        : []
    }),
  )
  const requiresReact = (name: string, seen = new Set<string>()): boolean => {
    if (name === 'React' || reactTargets.has(name)) return true
    if (seen.has(name)) return false
    seen.add(name)
    return (importedTargets.get(name) ?? []).some((dependency) =>
      requiresReact(dependency, seen),
    )
  }
  const map = (file: string) => {
    const target = byPath.find(
      (target) => file === target.path || file.startsWith(`${target.path}/`),
    )
    return target
      ? file === target.path
        ? `Sources/${target.name}`
        : `Sources/${target.name}/${file.slice(target.path.length + 1).replace(/^(?:.*\/)?node_modules\//, '')}`
      : file
  }
  for (const unit of units) {
    if (bridgeNamespaces.size > 0 && !bridgeNamespaces.has(unit.namespace)) continue
    // native modules resolve the installed workspace resource products through Bundle.
    unit.resources = input.resources
    unit.resourceBundles = input.resourceBundles?.map((bundle) => ({
      ...bundle,
      sourcePath: map(bundle.sourcePath),
    }))
    unit.frameworks = [...new Set([...unit.frameworks, ...binaryFrameworks])]
    const target = targetByName.get(unit.namespace)
    if (!target) {
      if (bridgeNamespaces.has(unit.namespace))
        throw new Error(
          `React Native pod target ${unit.namespace} is absent from the installed workspace`,
        )
      continue
    }
    const bridge = bridgeNamespaces.has(unit.namespace)
    if (bridge)
      for (const file of Object.keys(unit.files)) {
        if (!path.posix.basename(file).startsWith(BRIDGE_MODULE_FILE_PREFIX))
          delete unit.files[file]
      }
    unit.swiftLanguageMode = target.languageMode
    const included = new Set<string>()
    const visit = (name: string, root = false) => {
      if (!root && (name === 'React' || reactTargets.has(name))) {
        unit.reactNativeProvider = true
        return
      }
      if (included.has(name) || (!root && provided.has(name))) return
      const dependency = targetByName.get(name)
      if (!dependency) return
      included.add(name)
      for (const name of importedTargets.get(dependency.name) ?? []) {
        if (
          name === 'ReactCodegen' &&
          !sourceImports.get(dependency.name)?.includes(name)
        )
          continue
        visit(name)
      }
    }
    for (const name of namespaceGroups.get(unit.namespace) ?? [unit.namespace]) {
      if (requiresReact(name)) unit.reactNativeProvider = true
      visit(name, true)
    }
    // a unit lays each included target out at Sources/<name>, where its Bundle.module accessor reads the assignment
    unit.resourceBundles = input.resourceBundles?.map((bundle) =>
      targetByName.has(bundle.target)
        ? { ...bundle, sourcePath: `Sources/${bundle.target}` }
        : bundle,
    )
    for (const [file, source] of Object.entries(input.files)) {
      const owner = byPath.find((target) => file.startsWith(`${target.path}/`))
      if (
        owner &&
        included.has(owner.name) &&
        (file.endsWith('.swift') || isSwiftNativeTranslationUnit(file)) &&
        !(bridge && /RCT_EXTERN_(?:REMAP_)?MODULE\s*\(/.test(source)) &&
        // the turbo route owns an autolinked pod's React-registering units.
        !(
          !file.endsWith('.swift') &&
          !/(?:^|\/)node_modules\/react-native\//.test(file) &&
          registersReactModule(source)
        )
      )
        unit.files[map(file)] =
          bridge && owner.name === unit.namespace && file.endsWith('.swift')
            ? `import Foundation\nimport UIKit\nimport React\n${source}`
            : source
    }
    if (
      Object.entries(unit.files).some(([file, source]) =>
        (file.endsWith('.swift')
          ? swiftImportNames(source)
          : isSwiftNativeTranslationUnit(file)
            ? clangImportNames(source)
            : []
        ).includes('React'),
      )
    )
      unit.reactNativeProvider = true
    if (bridge) {
      const sources = swiftSourceClosure(
        unit.files,
        unit.bridgeModules.map((registration) =>
          registration.slice(registration.lastIndexOf('.') + 1).replace(/\(\)$/, ''),
        ),
      )
      for (const file of Object.keys(unit.files))
        if (
          file.startsWith(`Sources/${unit.namespace}/`) &&
          file.endsWith('.swift') &&
          !Object.hasOwn(sources, file)
        )
          delete unit.files[file]
    }
    unit.nativeFiles = Object.fromEntries(
      Object.entries(swiftNativeSupportFiles(input.files, installedTargets)).map(
        ([file, source]) => [map(file), source],
      ),
    )
    unit.headerAliases = Object.fromEntries(
      Object.entries(input.headerAliases ?? {}).map(([alias, file]) => [
        map(alias),
        map(file),
      ]),
    )
    const podspecTargets = unit.nativeTargets ?? []
    unit.nativeTargets = (input.nativeTargets ?? [])
      .filter((native) => included.has(native.name))
      .map((native) => ({
        ...native,
        headers: native.headers.map(map),
        publicHeaders: native.publicHeaders.map(map),
        bridgingHeader: native.bridgingHeader ? map(native.bridgingHeader) : null,
        prefixHeader: native.prefixHeader ? map(native.prefixHeader) : null,
        fileFlags: Object.fromEntries(
          Object.entries(native.fileFlags).map(([file, flags]) => [map(file), flags]),
        ),
        sourceDirectories: Object.fromEntries(
          Object.entries(native.sourceDirectories).map(([file, directory]) => [
            map(file),
            directory,
          ]),
        ),
      }))
    // the installed workspace lists only targets with clang inputs; the
    // podspec's floor is the one CocoaPods builds the pod at.
    for (const podspecTarget of podspecTargets) {
      const installedTarget = unit.nativeTargets.find(
        (native) => native.name === podspecTarget.name,
      )
      if (!installedTarget) unit.nativeTargets.push(podspecTarget)
      else installedTarget.deploymentTarget ??= podspecTarget.deploymentTarget
    }
    unit.files['Package.swift'] = expoManifest(
      unit.files,
      '',
      new Map([
        ...installedTargets
          .filter((target) => included.has(target.name))
          .map((target) => [target.name, target] satisfies [string, SwiftPackageTarget]),
        ...installedTargets
          .filter((target) => target.executable)
          .map(
            (target) => ['PeachExpoApp', target] satisfies [string, SwiftPackageTarget],
          ),
      ]),
    )
  }
  // the runtime already supplies these modules. their CocoaPods umbrella
  // includes every public header, including headers unrelated to this target.
  // keep the original headers, but build clang submodules for the headers
  // actually reached by this target and their transitive includes.
  const support: Record<string, string> = Object.assign(
    {},
    ...units.map((unit) => unit.nativeFiles),
  )
  const aliases = new Map(
    units.flatMap((unit) => Object.entries(unit.headerAliases ?? {})),
  )
  const maps = Object.entries(support).flatMap(([file, text]) => {
    if (!file.endsWith('.modulemap')) return []
    const name = moduleMapName(text)
    return name && provided.has(name) && /\bumbrella\s+header\s+"[^"]+"/.test(text)
      ? [{ file, text, name, reached: new Set<string>() }]
      : []
  })
  const pending: [string, string][] = [
    ...units.flatMap((unit) => Object.entries(unit.files)),
    ...units.flatMap((unit) =>
      (unit.nativeTargets ?? []).flatMap((native) =>
        [
          ...Object.keys(native.sourceDirectories),
          ...native.publicHeaders,
          native.prefixHeader,
          native.bridgingHeader,
        ].flatMap((file): [string, string][] =>
          file && support[file] !== undefined ? [[file, support[file]!]] : [],
        ),
      ),
    ),
  ]
  const visited = new Set<string>()
  while (pending.length) {
    const [file, source] = pending.pop()!
    if (visited.has(file)) continue
    visited.add(file)
    for (const match of source.matchAll(/#\s*(?:import|include)\s*[<"]([^>"]+)[>"]/g)) {
      const include = match[1]!
      for (const map of maps) {
        if (!include.startsWith(`${map.name}/`)) continue
        const header = include.slice(map.name.length + 1)
        const candidate = path.posix.join(path.posix.dirname(map.file), include)
        if (support[candidate] === undefined) continue
        map.reached.add(header)
        pending.push([candidate, support[candidate]!])
      }
      const relative = path.posix.normalize(
        path.posix.join(path.posix.dirname(file), include),
      )
      if (support[relative] !== undefined) pending.push([relative, support[relative]!])
    }
  }
  for (const map of maps) {
    if (!map.reached.size) continue
    const swift = swiftModuleInterface(moduleRoot, map.name, interfaceRoot)
    const mapDirectory = path.posix.dirname(map.file)
    if (swift) {
      const header = `${map.name}-Swift.h`
      support[path.posix.join(mapDirectory, map.name, header)] = swift.header
      const queue = [...map.reached].map((file) =>
        path.posix.join(mapDirectory, map.name, file),
      )
      const seen = new Set<string>()
      while (queue.length) {
        const file = queue.pop()!
        if (seen.has(file) || support[file] === undefined) continue
        seen.add(file)
        const source = support[file]!
        for (const match of source.matchAll(
          /#\s*(?:import|include)\s*[<"]([^>"]+)[>"]/g,
        )) {
          const include = match[1]!
          const next = include.startsWith(`${map.name}/`)
            ? path.posix.join(mapDirectory, include)
            : path.posix.normalize(path.posix.join(path.posix.dirname(file), include))
          if (support[next] !== undefined) queue.push(next)
        }
        const contents = withoutSwiftDeclarations(
          source,
          swift.declared,
          `#import <${map.name}/${header}>`,
        )
        support[file] = contents
        // the header overlay reads the canonical file behind a pod symlink.
        let canonical = file
        while (aliases.has(canonical)) canonical = aliases.get(canonical)!
        support[canonical] = contents
      }
    }
    const submodules = [
      ...(swift
        ? [`  module Swift { header "${map.name}/${map.name}-Swift.h" export * }`]
        : []),
      ...[...map.reached]
        .sort()
        .filter((header) => !map.text.includes(`textual header "${header}"`))
        .map(
          (header, index) =>
            `  module Header${index} { header "${map.name}/${header}" export * }`,
        ),
    ]
    if (!/^\s*module\s+\*\s*\{[^}]*\}\s*$/m.test(map.text))
      throw new Error(`${map.file}: cannot stage an umbrella without wildcard submodules`)
    support[map.file] = map.text
      .replace(/^\s*umbrella\s+header\s+"[^"]+"\s*\n/m, '')
      .replace(/^\s*module\s+\*\s*\{[^}]*\}\s*\n/m, `${submodules.join('\n')}\n`)
  }
  for (const unit of units) unit.nativeFiles = { ...unit.nativeFiles, ...support }
}

// Swift compiled without the pod's Objective-C still names those classes.
// A requester keeps the protocol its header declares, so the generic
// constraint can infer. The prepared workspace compiles the real .m files.
function swiftAloneObjCClasses(
  ios: string,
  swift: string,
  resolveSource: (file: string) => string,
): string | null {
  if (!fs.existsSync(ios)) return null
  const interfaces = new Map<string, { superName?: string; protocols: string[] }>()
  const visit = (dir: string) => {
    for (const child of fs.readdirSync(resolveSource(dir), { withFileTypes: true })) {
      if (
        child.name.startsWith('.') ||
        child.name === 'build' ||
        child.name === 'node_modules' ||
        /\.(?:xcframework|framework)$/.test(child.name)
      )
        continue
      const file = path.join(dir, child.name)
      const resolved = resolveSource(file)
      const stat = fs.statSync(resolved)
      if (stat.isDirectory()) {
        visit(file)
        continue
      }
      if (!stat.isFile() || !child.name.endsWith('.h')) continue
      const text = fs.readFileSync(resolved, 'utf8')
      for (const match of text.matchAll(
        /@interface\s+(\w+)\s*(\([^)\n]*\))?\s*(?::\s*(\w+))?\s*(?:<([^>\n]+)>)?/g,
      )) {
        if (match[2]) continue
        interfaces.set(match[1]!, {
          ...(match[3] ? { superName: match[3] } : {}),
          protocols: (match[4] ?? '')
            .split(',')
            .map((name) => name.trim())
            .filter((name) => name.length > 0),
        })
      }
    }
  }
  visit(ios)
  if (interfaces.size === 0) return null
  const code = swiftCodeMask(swift)
  const declared = new Set(
    [
      ...code.matchAll(
        /\b(?:class|struct|enum|protocol|actor|typealias)\s+([A-Za-z_]\w*)/g,
      ),
    ].map((match) => match[1]!),
  )
  const referenced = new Set(code.match(/[A-Za-z_]\w*/g) ?? [])
  const needed = [...interfaces.keys()]
    .filter((name) => referenced.has(name) && !declared.has(name))
    .sort()
  if (needed.length === 0) return null
  const protocolsOf = (name: string, seen = new Set<string>()): string[] => {
    if (seen.has(name)) return []
    seen.add(name)
    const item = interfaces.get(name)
    if (!item) return []
    return [
      ...item.protocols,
      ...(item.superName ? protocolsOf(item.superName, seen) : []),
    ]
  }
  const classes = needed.map((name) => {
    if (!new Set(protocolsOf(name)).has('EXPermissionsRequester'))
      return `public class ${name}: NSObject {}`
    return `public class ${name}: NSObject, EXPermissionsRequester {
  public static func permissionType() -> String { "" }
  public func getPermissions() -> [AnyHashable: Any] { [:] }
  public func requestPermissions(
    resolver resolve: @escaping EXPromiseResolveBlock,
    rejecter reject: @escaping EXPromiseRejectBlock
  ) {}
}`
  })
  return `import ExpoModulesCore\nimport Foundation\n\n${classes.join('\n\n')}\n`
}

export async function collectExpoSwiftSources(
  appRoot: string,
  signal?: AbortSignal,
  installedWorkspace?: string,
  prepareNative = false,
  iosTarget?: string,
  options: ExpoSwiftSourceOptions = {},
): Promise<ExpoSwiftSourceUnit[] | null> {
  if (traceStore.getStore())
    return collectExpoSwiftSourcesUncached(
      appRoot,
      signal,
      installedWorkspace,
      prepareNative,
      iosTarget,
      options,
    )
  signal?.throwIfAborted()
  installSwiftInputTrace()
  const key =
    (await discoveryKey(
      appRoot,
      installedWorkspace,
      prepareNative,
      iosTarget,
      options.moduleRoot,
    )) +
    '\0' +
    (options.metadataOnly ?? false)
  const cached = discoveryCache.get(key)
  if (cached && (await witnessMatches(cached.witness))) {
    signal?.throwIfAborted()
    return cloneUnits(cached.units)
  }
  const witness: Witness = { marks: new Map(), tainted: false }
  const units = await traceStore.run(witness, () =>
    collectExpoSwiftSourcesUncached(
      appRoot,
      signal,
      installedWorkspace,
      prepareNative,
      iosTarget,
      options,
    ),
  )
  if (witness.marks.size > 0 && (await witnessMatches(witness)))
    discoveryCache.set(key, { witness, units: cloneUnits(units) })
  return cloneUnits(units)
}

async function collectExpoSwiftSourcesUncached(
  appRoot: string,
  signal?: AbortSignal,
  installedWorkspace?: string,
  prepareNative = false,
  iosTarget?: string,
  { moduleRoot: moduleRootOverride, metadataOnly = false }: ExpoSwiftSourceOptions = {},
): Promise<ExpoSwiftSourceUnit[] | null> {
  const started = performance.now()
  const report = (message: string) =>
    console.error(`[expo-swift ${Math.round(performance.now() - started)}ms] ${message}`)
  signal?.throwIfAborted()
  appRoot = fs.realpathSync(appRoot)
  const appConfig = await loadRNXAppConfig(resolveAppProject(appRoot))
  const appRequire = createRequire(path.join(appRoot, 'package.json'))
  let expoRoot: string | undefined
  try {
    expoRoot = path.dirname(appRequire.resolve('expo/package.json'))
  } catch (error) {
    if (
      !error ||
      typeof error !== 'object' ||
      Reflect.get(error, 'code') !== 'MODULE_NOT_FOUND'
    )
      throw error
  }
  let autolinker: string
  try {
    autolinker = appRequire.resolve('expo-modules-autolinking/package.json', {
      paths: expoRoot ? [appRoot, expoRoot] : [appRoot],
    })
  } catch (error) {
    if (
      error &&
      typeof error === 'object' &&
      Reflect.get(error, 'code') === 'MODULE_NOT_FOUND'
    )
      return null
    throw error
  }
  // autolinkers before 1.0 predate app-owned Swift modules and `--project-root`.
  const autolinkerVersion: unknown = JSON.parse(
    fs.readFileSync(autolinker, 'utf8'),
  ).version
  if (typeof autolinkerVersion === 'string' && Number.parseInt(autolinkerVersion, 10) < 1)
    return null
  const cli = path.join(path.dirname(autolinker), 'bin/expo-modules-autolinking.js')
  const flags = autolinkerAppleFlags(autolinker, appRoot)
  // the children read the app manifest and its native modules directory
  // themselves, so both are stamped before either child starts.
  const appManifest: unknown = JSON.parse(
    fs.readFileSync(path.join(appRoot, 'package.json'), 'utf8'),
  )
  const expoConfig =
    appManifest && typeof appManifest === 'object'
      ? Reflect.get(appManifest, 'expo')
      : null
  const autolinking =
    expoConfig && typeof expoConfig === 'object'
      ? Reflect.get(expoConfig, 'autolinking')
      : null
  const modulesDir =
    autolinking && typeof autolinking === 'object'
      ? Reflect.get(autolinking, 'nativeModulesDir')
      : null
  fs.existsSync(
    path.resolve(appRoot, typeof modulesDir === 'string' ? modulesDir : 'modules'),
  )
  const childStart = performance.timeOrigin + performance.now()
  // both upstream commands discover their inputs independently. settle both
  // before propagating errors so a failed request leaves no child running.
  const [searched, resolvedModules] = await Promise.allSettled(
    ['search', 'resolve'].map((command) =>
      run(process.execPath, [cli, command, ...flags, '--json'], {
        timeout: 120_000,
        maxBuffer: 8 * 1024 * 1024,
        env: scriptEnv,
        // autolinkers call process.cwd() at startup, which throws when the
        // bridge's inherited cwd was deleted.
        cwd: appRoot,
        signal,
      }),
    ),
  )
  if (searched.status === 'rejected') throw searched.reason
  const search: unknown = JSON.parse(searched.value.stdout)
  if (!isRecord(search)) throw new Error('invalid Expo autolinking result')
  if (resolvedModules.status === 'rejected') throw resolvedModules.reason
  report('expo autolinking done')
  const resolvedText = resolvedModules.value.stdout
  const resolved: unknown = JSON.parse(resolvedText)
  const resolutions =
    resolved && typeof resolved === 'object' ? Reflect.get(resolved, 'modules') : null
  if (!Array.isArray(resolutions)) throw new Error('invalid Expo Apple resolution')
  // `resolve` does not run upstream's macro scanner, so a package that leaves
  // `apple.modules` undeclared and annotates its classes with `@ExpoModule` is
  // linked from the same scan the generated provider uses. autolinking before
  // 58 has no macro scanner, so those apps link only what `resolve` reports.
  const scan: unknown = Reflect.get(
    appRequire(path.join(path.dirname(autolinker), 'build/platforms/apple')),
    'scanNativeModulesAsync',
  )
  const scanned: unknown = typeof scan === 'function' ? await scan(search, 'apple') : null
  if (isRecord(scanned)) {
    for (const resolution of resolutions) {
      if (!isRecord(resolution)) continue
      const name = resolution.packageName
      const entry = typeof name === 'string' ? search[name] : null
      const config = isRecord(entry) ? entry.config : null
      const apple = isRecord(config) ? (config.apple ?? config.ios) : null
      if (isRecord(apple) && apple.modules != null) continue
      const found = typeof name === 'string' ? scanned[name] : null
      if (Array.isArray(found)) resolution.modules = found
    }
  }
  let installed: Awaited<ReturnType<typeof installedWorkspaceInput>> | undefined
  let provided: ReadonlySet<string> = new Set()
  let moduleRoot = ''
  let nativeAppIdentity: NativeAppIdentity | undefined
  if (installedWorkspace) {
    report(`reading installed workspace ${installedWorkspace}`)
    const module = moduleRootOverride
      ? { root: moduleRootOverride, ...swiftModuleToolchain(moduleRootOverride) }
      : await resolveSwiftModule({ signal })
    moduleRoot = module.root
    provided = new Set(swiftPeachModules(module.root))
    await prepareXcodeSwiftPackages(installedWorkspace, iosTarget, undefined, signal)
    moduleRoot = module.root
    provided = new Set(swiftPeachModules(module.root))
    const snapshot = await withXcodeProject(
      installedWorkspace,
      {
        target: iosTarget,
        configuration: 'Debug',
        interfaceRoot: module.root,
        moduleRoot: module.root,
        nativeModules: resolutions.flatMap((resolution) =>
          isRecord(resolution) && Array.isArray(resolution.swiftModuleNames)
            ? resolution.swiftModuleNames.filter(
                (name): name is string => typeof name === 'string',
              )
            : [],
        ),
      },
      async (projectRoot) => {
        const installed = await installedWorkspaceInput(
          projectRoot,
          'main.swift',
          module.root,
        )
        const identity = swiftProjectAppInfo(projectRoot).identity
        if (!identity)
          throw new Error('prepared Expo workspace has no native app identity')
        return { installed, identity }
      },
    )
    installed = snapshot.installed
    nativeAppIdentity = snapshot.identity
    report('installed workspace read')
  }
  const installedTargets = swiftManifestTargets(
    installed?.input.files['Package.swift'] ?? '',
  )
  const units: ExpoSwiftSourceUnit[] = []
  const dependencyUnits: ExpoSwiftSourceUnit[] = []
  const processed = new Set<string>()
  const namespacesSeen = new Set<string>()
  const namespaceGroups = new Map<string, string[]>()
  let answeredInstalled = false
  let needsNativeWorkspace = false
  let bytes = 0
  let fileCount = 0
  // native Expo resolves packages by name before generating its Apple provider.
  // the search result is keyed by that name; older autolinkers add no name field.
  const entries = Object.entries(search).sort(([a], [b]) => a.localeCompare(b))
  const queue = entries.slice()
  const queued = new Set(entries.map(([name]) => name))
  const reconsider = () => {
    for (const entry of entries)
      if (!processed.has(entry[0]) && !queued.has(entry[0])) {
        queue.push(entry)
        queued.add(entry[0])
      }
  }
  for (const [packageName, entry] of queue) {
    queued.delete(packageName)
    if (processed.has(packageName)) continue
    if (!entry || typeof entry !== 'object')
      throw new Error('invalid Expo autolinking entry')
    const sourceRoot = Reflect.get(entry, 'path')
    if (typeof sourceRoot !== 'string')
      throw new Error('Expo autolinking entry has no path')
    const canonical = fs.realpathSync(sourceRoot)
    // an installed package with a native seam keeps it; one without compiles
    // through the same autolinker-selected route as app-local modules.
    const answered =
      canonical.split(path.sep).includes('node_modules') &&
      peachAnsweredNativePackages().has(packageName)
    if (answered) {
      answeredInstalled = true
      if (installed || prepareNative || metadataOnly) {
        processed.add(packageName)
        continue
      }
    }
    // the autolinker read these in a child, so the parent can only stamp them
    // afterwards. one modified since the child started may be newer than what
    // the child consumed, and so may a module directory that gained or lost one.
    for (const name of ['expo-module.config.json', 'unimodule.json']) {
      const descriptor = path.join(canonical, name)
      if (fs.existsSync(descriptor)) {
        fs.readFileSync(descriptor)
        noteChangedSince(descriptor, childStart)
      }
    }
    noteChangedSince(canonical, childStart)
    const resolution = resolutions.find(
      (candidate) =>
        candidate &&
        typeof candidate === 'object' &&
        Reflect.get(candidate, 'packageName') === packageName,
    )
    const namespaces =
      resolution && typeof resolution === 'object'
        ? Reflect.get(resolution, 'swiftModuleNames')
        : null
    const modules =
      resolution && typeof resolution === 'object'
        ? Reflect.get(resolution, 'modules')
        : null
    const pods =
      resolution && typeof resolution === 'object'
        ? Reflect.get(resolution, 'pods')
        : null
    // expo links a package into an iOS target only when one of its pods
    // supports iOS (autolinking_manager.rb packages_to_generate).
    if (Array.isArray(pods) && pods.length > 0 && !pods.some(podSupportsIOS)) {
      report(`${packageName} was not linked: no pod supports iOS`)
      continue
    }
    const delegateNames = (key: string): unknown[] => {
      const names =
        resolution && typeof resolution === 'object' ? Reflect.get(resolution, key) : null
      return Array.isArray(names) ? names : []
    }
    const subscriberNames = delegateNames('appDelegateSubscribers')
    const handlerNames = delegateNames('reactDelegateHandlers')
    // a package with pods is rediscovered in the prepared workspace, which has no caps.
    const deferredToWorkspace =
      prepareNative && !installedWorkspace && Array.isArray(pods) && pods.length > 0
    const dependencyOnly =
      answered ||
      ((!Array.isArray(modules) || modules.length === 0) &&
        subscriberNames.length === 0 &&
        handlerNames.length === 0)
    if (dependencyOnly) {
      if (installed || prepareNative || metadataOnly || !Array.isArray(namespaces)) {
        processed.add(packageName)
        continue
      }
      const imports = new Set(
        [...units, ...dependencyUnits].flatMap((unit) =>
          Object.values(unit.files).flatMap((source) => swiftImportNames(source)),
        ),
      )
      if (!namespaces.some((name) => typeof name === 'string' && imports.has(name)))
        continue
      if (!moduleRoot) {
        const module = moduleRootOverride
          ? { root: moduleRootOverride, ...swiftModuleToolchain(moduleRootOverride) }
          : await resolveSwiftModule({ signal })
        moduleRoot = module.root
        provided = new Set(swiftPeachModules(module.root))
      }
      if (namespaces.every((name) => typeof name === 'string' && provided.has(name))) {
        processed.add(packageName)
        continue
      }
    }
    processed.add(packageName)
    if (
      !Array.isArray(namespaces) ||
      namespaces.length === 0 ||
      !namespaces.every(
        (name): name is string =>
          typeof name === 'string' && /^[A-Za-z_][A-Za-z0-9_]*$/.test(name),
      )
    )
      throw new Error(`${sourceRoot}: invalid Expo Apple Swift modules`)
    // pod source membership comes from CocoaPods, including packages whose
    // Apple sources live outside an ios directory or exclude sibling sources.
    if (deferredToWorkspace) {
      // every selected pod uses its real prepared graph. non-Mac hosts intake
      // the portable workspace instead of silently dropping its registration.
      needsNativeWorkspace = true
      continue
    }
    // cocoapods assigns each class to a target. multiple pods cannot be
    // partitioned by directory because their source globs may overlap.
    if (namespaces.length > 1 && !installed) {
      // without that membership the package's natives cannot be split, so it
      // stays unbuilt and the app reports it like any module Peach lacks.
      if (!prepareNative) {
        if (!answered)
          report(
            `${packageName}: ${namespaces.join(', ')} need CocoaPods target membership, which only a Mac prepares; not compiled`,
          )
        continue
      }
      const prepared = await prepareExpoNativeWorkspace(appRoot, signal, iosTarget)
      return collectExpoSwiftSources(
        prepared.app,
        signal,
        prepared.workspace,
        false,
        iosTarget,
        { moduleRoot: moduleRootOverride, metadataOnly },
      )
    }
    const declarations: {
      reference: string
      nativeName: string | null
      module: boolean
      subscriber: boolean
      handler: boolean
    }[] = []
    for (const descriptor of Array.isArray(modules) ? modules : []) {
      const reference =
        typeof descriptor === 'string'
          ? descriptor
          : isRecord(descriptor)
            ? descriptor.class
            : null
      const nativeName =
        typeof descriptor === 'string'
          ? null
          : isRecord(descriptor)
            ? descriptor.name
            : null
      if (
        typeof reference !== 'string' ||
        !/^[A-Za-z_]\w*(\.[A-Za-z_]\w*)*$/.test(reference) ||
        (nativeName !== null && typeof nativeName !== 'string')
      )
        throw new Error(`${sourceRoot}: invalid Expo Apple module descriptor`)
      declarations.push({
        reference,
        nativeName,
        module: true,
        subscriber: false,
        handler: false,
      })
    }
    for (const [names, role] of [
      [subscriberNames, 'subscriber'],
      [handlerNames, 'handler'],
    ] as const) {
      for (const reference of names) {
        if (
          typeof reference !== 'string' ||
          !/^[A-Za-z_]\w*(\.[A-Za-z_]\w*)*$/.test(reference)
        )
          throw new Error(`${sourceRoot}: invalid Expo Apple delegate descriptor`)
        const existing = declarations.find((item) => item.reference === reference)
        if (existing) existing[role] = true
        else
          declarations.push({
            reference,
            nativeName: null,
            module: false,
            subscriber: role === 'subscriber',
            handler: role === 'handler',
          })
      }
    }
    const owners = new Map<string, Set<string>>()
    for (const namespace of namespaces) {
      namespaceGroups.set(namespace, namespaces)
      if (namespacesSeen.has(namespace))
        throw new Error(`duplicate local Expo Swift module ${namespace}`)
      namespacesSeen.add(namespace)
      const files: Record<string, string> = {}
      const frameworks = new Set<string>()
      const ios = path.join(canonical, 'ios')
      // an app's own module may share sources with its other native targets
      // through links that stay inside the app; installed packages stay sealed.
      const appOwned = !canonical.split(path.sep).includes('node_modules')
      const withinApp = path.relative(appRoot, canonical)
      const sourceBoundary =
        appOwned && withinApp !== '..' && !withinApp.startsWith(`..${path.sep}`)
          ? appRoot
          : canonical
      const boundaryName = sourceBoundary === appRoot ? 'app root' : 'module root'
      const directories = new Set<string>()
      const sources = new Set<string>()
      const nativeSources = new Set<string>()
      const resolveSource = (file: string) => {
        let target: string
        try {
          target = fs.realpathSync(file)
        } catch (cause) {
          throw new Error(`Cannot resolve Expo Swift source: ${file}`, {
            cause,
          })
        }
        const relative = path.relative(sourceBoundary, target)
        if (
          relative === '..' ||
          relative.startsWith(`..${path.sep}`) ||
          path.isAbsolute(relative)
        )
          throw new Error(
            `Expo Swift source escapes ${boundaryName}: ${file} -> ${target}`,
          )
        return target
      }
      const walk = (dir: string, binary = false) => {
        signal?.throwIfAborted()
        // versioned frameworks expose the same directory through several links.
        const directory = resolveSource(dir)
        if (directories.has(directory)) return
        directories.add(directory)
        for (const child of fs
          .readdirSync(dir, { withFileTypes: true })
          .sort((a, b) => a.name.localeCompare(b.name))) {
          const file = path.join(dir, child.name)
          const linked = child.isSymbolicLink() ? resolveSource(file) : null
          const target = linked ? fs.statSync(linked) : child
          if (target.isDirectory()) {
            const framework = /\.(xcframework|framework)$/.test(child.name)
            if (framework && !binary) frameworks.add(linked ?? resolveSource(file))
            if (!child.name.startsWith('.') && child.name !== 'build')
              walk(file, binary || framework)
            continue
          }
          if (!binary && target.isFile() && /\.(?:mm?|c|cc|cpp)$/.test(child.name)) {
            const source = linked ?? resolveSource(file)
            if (
              fs.statSync(source).size > 4096 ||
              !/^(?:\s|\/\/[^\n]*|\/\*[\s\S]*?\*\/)*$/.test(
                fs.readFileSync(source, 'utf8'),
              )
            )
              nativeSources.add(path.relative(ios, file))
          }
          if (!target.isFile() || !child.name.endsWith('.swift')) continue
          const source = linked ?? resolveSource(file)
          if (sources.has(source)) continue
          sources.add(source)
          bytes += fs.statSync(source).size
          fileCount++
          if (
            !installedWorkspace &&
            (fileCount > MAX_SWIFT_COMPILE_FILES - 2 ||
              bytes > MAX_SWIFT_COMPILE_SOURCE_BYTES)
          )
            throw new Error('Expo Swift sources exceed compile service caps')
          files[
            `Sources/${namespace}/${path.relative(ios, file).split(path.sep).join('/')}`
          ] = expoSwiftSourceWithPrelude(file, fs.readFileSync(source, 'utf8'))
        }
      }
      const walkFrameworks = (dir: string) => {
        signal?.throwIfAborted()
        const directory = resolveSource(dir)
        if (directories.has(directory)) return
        directories.add(directory)
        for (const child of fs
          .readdirSync(dir, { withFileTypes: true })
          .sort((a, b) => a.name.localeCompare(b.name))) {
          if (
            child.name.startsWith('.') ||
            child.name === 'build' ||
            child.name === 'node_modules' ||
            child.name === 'android' ||
            child.name === 'web' ||
            child.name === 'src'
          )
            continue
          const file = path.join(dir, child.name)
          const linked = child.isSymbolicLink() ? resolveSource(file) : null
          const target = linked ? fs.statSync(linked) : child
          if (!target.isDirectory()) continue
          if (/\.(xcframework|framework)$/.test(child.name)) {
            frameworks.add(linked ?? resolveSource(file))
            continue
          }
          walkFrameworks(file)
        }
      }
      if (installed) {
        const target = installedTargets.find((item) => item.name === namespace)
        if (!target)
          throw new Error(
            `Expo pod target ${namespace} is absent from the installed workspace`,
          )
        for (const [file, source] of Object.entries(installed.input.files)) {
          if (file.startsWith(`${target.path}/`) && file.endsWith('.swift'))
            files[
              `Sources/${namespace}/${file.slice(target.path.length + 1).replace(/^(?:.*\/)?node_modules\//, '')}`
            ] = source
        }
      } else {
        walk(ios)
        walkFrameworks(canonical)
        // this path compiles Swift alone; the report names the cause when a
        // Swift file then fails on the pod's own Objective-C or C types.
        if (nativeSources.size > 0 && !prepareNative && !metadataOnly) {
          report(
            `${packageName}: ${namespace} has Objective-C or C sources (${[...nativeSources].sort()[0]}), which compile only from a CocoaPods workspace a Mac prepares; compiling its Swift alone`,
          )
          const surface = swiftAloneObjCClasses(
            ios,
            Object.values(files).join('\n'),
            resolveSource,
          )
          if (surface) files[`Sources/${namespace}/PeachObjCSurface.swift`] = surface
        }
      }
      // a module compiled from its own source declares its iOS floor in its
      // podspec; CocoaPods builds the pod at that floor.
      const podspec = fs.existsSync(ios)
        ? fs.readdirSync(ios).find((name) => name.endsWith('.podspec'))
        : undefined
      const absentFrameworks: string[] = []
      if (podspec && !installed) {
        // the declared paths are read as written; podspec Ruby beyond literal
        // strings is not evaluated, as with the floor below.
        const declared = [
          ...fs
            .readFileSync(path.join(ios, podspec), 'utf8')
            .matchAll(/\bvendored_frameworks\s*=\s*(\[[^\]]*\]|'[^'\n]*'|"[^"\n]*")/g),
        ].flatMap(([, value]) =>
          [...value!.matchAll(/'([^'\n]*)'|"([^"\n#]*)"/g)].map(
            (match) => match[1] ?? match[2]!,
          ),
        )
        for (const entry of declared) {
          const base = path.dirname(path.resolve(ios, entry))
          const name = new RegExp(
            `^${path
              .basename(entry)
              .replace(/[.+^${}()|[\]\\]/g, '\\$&')
              .replaceAll('*', '[^/]*')}$`,
          )
          const found = fs.existsSync(base)
            ? fs.readdirSync(base).filter((child) => name.test(child))
            : []
          if (found.length === 0)
            absentFrameworks.push(path.relative(appRoot, path.resolve(ios, entry)))
          for (const child of found) frameworks.add(resolveSource(path.join(base, child)))
        }
      }
      const podspecFloor = podspec
        ? /\.platforms\s*=\s*\{\s*:ios\s*=>\s*['"](\d+(?:\.\d+){0,2})['"]/.exec(
            fs.readFileSync(path.join(ios, podspec), 'utf8'),
          )?.[1]
        : undefined
      if (dependencyOnly && Object.keys(files).length > 0) {
        dependencyUnits.push({
          namespace,
          moduleId: namespace,
          classes: [],
          bridgeModules: [],
          appDelegateSubscribers: [],
          reactDelegateHandlers: [],
          files,
          frameworks: [...frameworks],
          ...(nativeSources.size ? { workspaceSources: [namespace] } : {}),
          ...(podspecFloor
            ? {
                nativeTargets: [synthesizedNativeTarget(namespace, podspecFloor)],
              }
            : {}),
        })
        reconsider()
      }
      if (dependencyOnly) continue
      for (const declaration of declarations) {
        const className = declaration.reference
        const owner = className.split('.')[0]!
        if (className.includes('.') && namespaces.includes(owner) && owner !== namespace)
          continue
        const name = className.split('.').pop()!
        // a class with its module's name shadows that module in Swift lookup.
        const reference =
          className.includes('.') || className === namespace
            ? className
            : `${namespace}.${className}`
        const module = {
          name,
          nativeName: declaration.nativeName,
          registration: declaration.module
            ? `(${reference}.self, ${declaration.nativeName === null ? 'nil' : JSON.stringify(declaration.nativeName)})`
            : null,
          subscriber: declaration.subscriber ? `${reference}.self` : null,
          handler: declaration.handler
            ? `(packageName: ${JSON.stringify(packageName)}, handler: ${reference}.self)`
            : null,
        }
        const closure = swiftSourceClosure(files, [module.name])
        if (namespaces.length > 1 && Object.keys(closure).length === 0) continue
        const classOwners = owners.get(className) ?? new Set<string>()
        classOwners.add(namespace)
        owners.set(className, classOwners)
        const configured =
          module.registration !== null &&
          configuredExpoSwiftModule(closure, module.name, module.nativeName, appConfig)
        if (configured && !module.subscriber && !module.handler) continue
        if (Array.isArray(pods) && pods.length > 0) needsNativeWorkspace = true
        const unit: ExpoSwiftSourceUnit = {
          namespace,
          moduleId: `${namespace}.${module.name}`,
          classes: module.registration && !configured ? [module.registration] : [],
          bridgeModules: [],
          appDelegateSubscribers: module.subscriber ? [module.subscriber] : [],
          reactDelegateHandlers: module.handler ? [module.handler] : [],
          files: closure,
          frameworks: [...frameworks],
          ...(absentFrameworks.length > 0 ? { absentFrameworks } : {}),
          ...(podspecFloor
            ? {
                nativeTargets: [synthesizedNativeTarget(namespace, podspecFloor)],
              }
            : {}),
        }
        unit.files[EXPO_SWIFT_ENTRY] = expoEntry([unit])
        units.push(unit)
        reconsider()
      }
    }
    if (namespaces.length > 1) {
      for (const declaration of declarations) {
        const classOwners = owners.get(declaration.reference)
        if (classOwners?.size !== 1)
          throw new Error(
            `${sourceRoot}: Expo class ${declaration.reference} belongs to ${classOwners?.size ?? 0} installed Apple targets`,
          )
      }
    }
  }
  if (prepareNative && !installedWorkspace && needsNativeWorkspace) {
    const discovery = await expoDiscoveryKey({
      appRoot,
      searchText: searched.value.stdout,
      resolveText: resolvedText,
      configuration: appConfig,
      signal,
    })
    const cached = readExpoDiscovery(discovery.key)
    if (!moduleRootOverride && cached !== undefined) return cached
    const prepared = await prepareExpoNativeWorkspace(appRoot, signal, iosTarget)
    const discovered = await collectExpoSwiftSources(
      prepared.app,
      signal,
      prepared.workspace,
      false,
      iosTarget,
      { moduleRoot: moduleRootOverride, metadataOnly },
    )
    if (moduleRootOverride) return discovered
    const stored = writeExpoDiscovery({
      key: discovery.key,
      units: discovered,
      sourceRoot: discovery.root,
      preparedRoot: prepared.work,
      signal,
    })
    if (typeof stored === 'string') {
      report(`discovery cache refused the entry: ${stored}`)
      return discovered
    }
    return stored
  }
  // inline modules belong to the app target, including non-module intent files.
  // use Expo's scanner so its watched directories and class selection stay native.
  const config = await traceStore.exit(() => readExpoConfigAsync(appRoot))
  signal?.throwIfAborted()
  const experiments = config.experiments
  const inlineConfig = isRecord(experiments) ? experiments.inlineModules : undefined
  const directories = isRecord(inlineConfig) ? inlineConfig.watchedDirectories : undefined
  if (
    directories !== undefined &&
    (!Array.isArray(directories) ||
      !directories.every((directory) => typeof directory === 'string'))
  )
    throw new Error('invalid Expo inline watched directories')
  if (directories !== undefined && directories.length > 0) {
    const scanInline: unknown = Reflect.get(
      appRequire(
        path.join(path.dirname(autolinker), 'build/inlineModules/inlineModules.js'),
      ),
      'getMirrorStateObject',
    )
    if (typeof scanInline !== 'function')
      throw new Error('Expo autolinker does not expose its inline module scanner')
    const inline: unknown = await scanInline({
      appRoot,
      watchedDirectories: directories,
    })
    signal?.throwIfAborted()
    if (!inline || typeof inline !== 'object')
      throw new Error('invalid Expo inline modules')
    const inlineFiles = Reflect.get(inline, 'files')
    const inlineClasses = Reflect.get(inline, 'swiftModuleClassNames')
    if (
      !Array.isArray(inlineFiles) ||
      !Array.isArray(inlineClasses) ||
      !inlineClasses.every(
        (name) => typeof name === 'string' && /^[A-Za-z_][A-Za-z0-9_]*$/.test(name),
      )
    )
      throw new Error('invalid Expo inline modules')
    const appFiles: Record<string, string> = {}
    for (const entry of inlineFiles) {
      const file: unknown =
        entry && typeof entry === 'object' ? Reflect.get(entry, 'filePath') : null
      if (typeof file !== 'string') throw new Error('invalid Expo inline source')
      if (!file.endsWith('.swift')) continue
      const relative = path.relative(appRoot, fs.realpathSync(file))
      if (
        relative === '..' ||
        relative.startsWith(`..${path.sep}`) ||
        path.isAbsolute(relative)
      )
        throw new Error(`Expo inline source escapes app root: ${file}`)
      bytes += fs.statSync(file).size
      fileCount++
      if (
        fileCount > MAX_SWIFT_COMPILE_FILES - 2 ||
        bytes > MAX_SWIFT_COMPILE_SOURCE_BYTES
      )
        throw new Error('Expo Swift sources exceed compile service caps')
      appFiles[`Sources/PeachExpoApp/Inline/${relative.split(path.sep).join('/')}`] =
        expoSwiftSourceWithPrelude(file, fs.readFileSync(file, 'utf8'))
    }
    if (Object.keys(appFiles).length > 0) {
      const inlineUnit: ExpoSwiftSourceUnit = {
        namespace: 'PeachExpoApp',
        moduleId: 'PeachExpoApp',
        classes: inlineClasses.map((name) => `(${name}.self, nil)`),
        bridgeModules: [],
        appDelegateSubscribers: [],
        reactDelegateHandlers: [],
        files: appFiles,
        frameworks: [],
      }
      inlineUnit.files[EXPO_SWIFT_ENTRY] = expoEntry([inlineUnit])
      units.push(inlineUnit)
    }
  }
  // an app whose installed modules a seam answers still links native modules.
  if (units.length === 0) return answeredInstalled ? [] : null
  if (metadataOnly) return units
  if (installed)
    enrichInstalledUnits(
      units,
      installed,
      namespaceGroups,
      provided,
      moduleRoot,
      appRoot,
      new Set(),
      installedWorkspace ? preparedXcodeInterfaces(installedWorkspace) : undefined,
    )
  const allFiles: Record<string, string> = Object.assign(
    {},
    ...[...units, ...dependencyUnits].map((unit) => unit.files),
  )
  const targets = [
    ...new Set([...units, ...dependencyUnits].map((unit) => unit.namespace)),
  ].map((namespace) => ({
    name: namespace,
    path: `Sources/${namespace}`,
  }))
  const dependencies = swiftTargetDependencies(allFiles, targets)
  const byNamespace = new Map<string, ExpoSwiftSourceUnit[]>()
  for (const unit of [...units, ...dependencyUnits]) {
    const entries = byNamespace.get(unit.namespace) ?? []
    entries.push(unit)
    byNamespace.set(unit.namespace, entries)
  }
  for (const unit of units) {
    const included = new Set([unit.namespace])
    const ownDependencies =
      swiftTargetDependencies(unit.files, targets).get(unit.namespace) ?? []
    const visit = (namespace: string) => {
      for (const dependency of namespace === unit.namespace
        ? ownDependencies
        : (dependencies.get(namespace) ?? [])) {
        if (!byNamespace.has(dependency) || included.has(dependency)) continue
        included.add(dependency)
        visit(dependency)
      }
    }
    visit(unit.namespace)
    for (const namespace of included) {
      if (namespace === unit.namespace) continue
      const dependency = byNamespace.get(namespace)
      if (!dependency) throw new Error(`missing local Swift namespace ${namespace}`)
      unit.frameworks = [
        ...new Set([
          ...unit.frameworks,
          ...dependency.flatMap((item) => item.frameworks),
        ]),
      ]
      unit.workspaceSources = [
        ...new Set([
          ...(unit.workspaceSources ?? []),
          ...dependency.flatMap((item) => item.workspaceSources ?? []),
        ]),
      ]
      unit.nativeTargets = [
        ...new Map(
          [
            ...(unit.nativeTargets ?? []),
            ...dependency.flatMap((item) => item.nativeTargets ?? []),
          ].map((target) => [target.name, target] satisfies [string, typeof target]),
        ).values(),
      ]
      unit.nativeFiles = Object.assign(
        {},
        unit.nativeFiles,
        ...dependency.map((item) => item.nativeFiles),
      )
      unit.headerAliases = Object.assign(
        {},
        unit.headerAliases,
        ...dependency.map((item) => item.headerAliases),
      )
      for (const [name, source] of Object.entries(allFiles)) {
        if (name.startsWith(`Sources/${namespace}/`)) unit.files[name] = source
      }
    }
    const settings = targetSettings(
      [...included].flatMap((namespace) => byNamespace.get(namespace)!),
    )
    if (!installed)
      for (const namespace of included)
        settings.set(namespace, {
          languageMode: 5,
          mainActorIsolation: false,
          resources: false,
          ...settings.get(namespace),
          dependencies: (namespace === unit.namespace
            ? ownDependencies
            : (dependencies.get(namespace) ?? [])
          )
            .filter((name) => included.has(name))
            .map((name) => ({ kind: 'target', name })),
        })
    unit.files['Package.swift'] = expoManifest(unit.files, '', settings)
  }
  if (nativeAppIdentity)
    for (const unit of units) unit.nativeAppIdentity = nativeAppIdentity
  return units
}

// target settings follow their installed CocoaPods build configuration.
export function expoManifest(
  files: Record<string, string>,
  generation = '',
  settings: ReturnType<typeof targetSettings> = new Map(),
): string {
  const targets = new Map<string, string>()
  for (const file of Object.keys(files)) {
    const match = /^(Sources|__standins__)\/([^/]+)\//.exec(file)
    if (!match || match[2] === 'PeachExpoApp') continue
    const dir = `${match[1]}/${match[2]}`
    if (targets.has(match[2]!) && targets.get(match[2]!) !== dir)
      throw new Error(`duplicate Expo Swift compile target ${match[2]}`)
    targets.set(match[2]!, dir)
  }
  const declarations = [...targets].map(([name, dir]) => {
    const declared = settings.get(name)
    const configuration = dir.startsWith(`${SWIFT_STANDINS_DIR}/`)
      ? { languageMode: 5, mainActorIsolation: false }
      : declared
    const dependencies = (declared?.dependencies ?? []).flatMap((dependency) =>
      dependency.kind === 'target' && targets.has(dependency.name)
        ? [dependency.name]
        : [],
    )
    return `.target(name: ${JSON.stringify(name)}, dependencies: ${JSON.stringify(dependencies)}, path: ${JSON.stringify(dir)}${declared?.resources ? ', resources: []' : ''}${configuration ? ', ' + swiftManifestSettings(configuration) : ''})`
  })
  // the entry imports every module target, and a declared dependency list is
  // what the compiler reads for import flags such as a pod's clang module map.
  const appProducts = [...targets.keys()].map((name) => JSON.stringify(name))
  // the sdk frameworks the original app links ride the entry target.
  appProducts.push(
    ...(settings.get('PeachExpoApp')?.dependencies ?? []).flatMap((dependency) =>
      dependency.kind === 'product' && dependency.package === 'sootsim-swift'
        ? [`.product(name: ${JSON.stringify(dependency.name)}, package: "sootsim-swift")`]
        : [],
    ),
  )
  return `// swift-tools-version: 6.0\nimport PackageDescription\nlet package = Package(name: "PeachExpo", targets: [${declarations.join(', ')}, .executableTarget(name: "PeachExpoApp", dependencies: [${appProducts.join(', ')}], path: "Sources/PeachExpoApp")])\n// stand-in inputs: ${generation}\n`
}

export function targetSettings(units: ExpoSwiftSourceUnit[]) {
  const settings = new Map<
    string,
    Parameters<typeof swiftManifestSettings>[0] &
      Pick<SwiftPackageTarget, 'dependencies'> &
      Partial<Pick<SwiftPackageTarget, 'resources'>>
  >()
  for (const unit of units) {
    for (const target of swiftManifestTargets(unit.files['Package.swift'] ?? '')) {
      const previous = settings.get(target.name)
      const dependencies = [
        ...(previous?.dependencies ?? []),
        ...(target.dependencies ?? []),
      ]
      settings.set(target.name, {
        ...target,
        dependencies: [
          ...new Map(
            dependencies.map((dependency) => [JSON.stringify(dependency), dependency]),
          ).values(),
        ],
      })
    }
    if (unit.swiftLanguageMode !== undefined)
      settings.set(unit.namespace, {
        ...settings.get(unit.namespace),
        languageMode: unit.swiftLanguageMode,
        mainActorIsolation: settings.get(unit.namespace)?.mainActorIsolation ?? false,
        resources: settings.get(unit.namespace)?.resources ?? false,
      })
  }
  return settings
}

function oneSDKStamp(oneSDK: ExpoSwiftPreparationOptions['oneSDK']): string {
  if (!oneSDK) return ''
  const hash = createHash('sha256')
  for (const files of [oneSDK.targets, oneSDK.entry])
    for (const [name, source] of [...files].sort(([a], [b]) => a.localeCompare(b)))
      hash.update(`${name}\0${source}\0`)
  return hash.digest('hex')
}

// CocoaPods' iOS umbrella header imports UIKit into every Swift file through
// the underlying module; these source units have no clang pod, and sources
// calling UIImageWriteToSavedPhotosAlbum also need the SwiftUI re-export until
// UIKit re-exports it in the published distribution.
export function expoSwiftSourceWithPrelude(file: string, rawSource: string): string {
  const extraImport = /\bUIImageWriteToSavedPhotosAlbum\b/.test(rawSource)
    ? 'import func SwiftUI.UIImageWriteToSavedPhotosAlbum\n'
    : ''
  return `import UIKit\n${extraImport}#sourceLocation(file: ${JSON.stringify(file)}, line: 1)\n${rawSource}`
}

export function expoEntry(units: ExpoSwiftSourceUnit[], oneSDK = false): string {
  // an Objective-C bridge module registers with no Swift of its own
  const namespaces = [...new Set(units.map((unit) => unit.namespace))]
    .filter((namespace) => namespace !== 'PeachExpoApp')
    .filter((namespace) =>
      units.some((unit) =>
        Object.keys(unit.files).some((file) => file.startsWith(`Sources/${namespace}/`)),
      ),
    )
  const bridgeModules = units.flatMap((unit) => unit.bridgeModules)
  const subscribers = units.flatMap((unit) => unit.appDelegateSubscribers)
  const handlers = units.flatMap((unit) => unit.reactDelegateHandlers)
  const delegates =
    subscribers.length + handlers.length > 0
      ? `; PeachExpoRuntime.registerDelegates(subscribers: [${subscribers.join(', ')}], handlers: [${handlers.join(', ')}])`
      : ''
  // omit PeachExpoNativeView when no unit declares a view so UIKit/SwiftUI view machinery stays unlinked
  const hasViews =
    oneSDK ||
    units.some((unit) =>
      Object.entries(unit.files).some(
        ([file, source]) =>
          file.endsWith('.swift') &&
          /\bView\s*\(|\bExpoView\b|\bUIViewRepresentable\b|\bExpoSwiftUI\b/.test(source),
      ),
    )
  // a One SDK host component marks its view; every other view is an Expo view
  const view = oneSDK
    ? '@ViewBuilder func view(props: PeachJSON.JSON) -> some View {\n    if props["oneSDKHost"] != nil { OneSDKUIKitHost(props: props) } else { PeachExpoNativeView(props: props) }\n  }'
    : hasViews
      ? 'func view(props: PeachJSON.JSON) -> PeachExpoNativeView { PeachExpoNativeView(props: props) }'
      : 'func view(props: PeachJSON.JSON) -> EmptyView { EmptyView() }'
  return `import SwiftUI\nimport PeachJSON\ninternal import ExpoModulesCore\n${bridgeModules.length ? 'import React\n' : ''}${oneSDK ? 'import One\nimport OneSDKBindings\n' : ''}${namespaces.map((namespace) => `import ${namespace}`).join('\n')}\n\n@main struct PeachExpoApp: PeachPackage {\n  init() { MainActor.assumeIsolated { PeachExpoRuntime.register([${units.flatMap((unit) => unit.classes).join(', ')}])${delegates}${bridgeModules.length ? `; RCTModuleHost.register([${bridgeModules.join(', ')}])` : ''} } }\n  ${view}\n}\n\n@_expose(wasm, "peach_expo_call")\n@_cdecl("peach_expo_call")\n@MainActor public func peachExpoCall(_ payload: UnsafePointer<UInt8>?, _ length: Int32) -> UnsafeMutablePointer<UInt8>? {\n  PeachExpoRuntime.dispatch(payload, length)\n}\n`
}

// a compile outlives its client: a dropped open leaves the work running so the
// next open joins it, or reuses its result, instead of starting over.
const compiling = new Map<string, Promise<ExpoSwiftCompilationResult | null>>()
// identical sources already produced a wasm that is still registered on its
// project. a second caller otherwise relinks namespaces whose failure records
// did not stick, and that link blows the flow's ready bound.
const preparedExpoSwift = new Map<string, ExpoSwiftCompilationResult>()
const openPreparations =
  new NativePreparationReceipts<ExpoSwiftCompilationResult | null>()

function expoSwiftPreparedKey(
  base: string,
  units: ExpoSwiftSourceUnit[],
  reactProviderStamp: string,
): string {
  const hash = createHash('sha256')
  hash.update(base)
  hash.update(reactProviderStamp)
  for (const unit of units) {
    hash.update('\0')
    hash.update(unit.moduleId)
    hash.update('\0')
    hash.update(JSON.stringify(unit.nativeTargets ?? []))
    hash.update(JSON.stringify(unit.headerAliases ?? {}))
    hash.update(JSON.stringify(unit.resourceBundles ?? []))
    hash.update(JSON.stringify(unit.resources ?? {}))
    hash.update(JSON.stringify(unit.nativeAppIdentity ?? null))
    hash.update(JSON.stringify(unit.reactNativeProvider ?? false))
    for (const name of Object.keys(unit.nativeFiles ?? {}).sort()) {
      hash.update('\0')
      hash.update(name)
      hash.update('\0')
      hash.update(unit.nativeFiles?.[name] ?? '')
    }
    for (const name of Object.keys(unit.files).sort()) {
      hash.update('\0')
      hash.update(name)
      hash.update('\0')
      hash.update(unit.files[name] ?? '')
    }
  }
  return hash.digest('hex')
}

// the app files a unit's build copies point back to with #sourceLocation.
function expoUnitAppPaths(unit: ExpoSwiftSourceUnit): string[] {
  return Object.values(unit.files).flatMap((source) => {
    const match = /^#sourceLocation\(file: (".*"), line: 1\)$/m.exec(source)
    if (!match) return []
    const file: unknown = JSON.parse(match[1]!)
    return typeof file === 'string' ? [file] : []
  })
}

// this process's copy of the app's expo sources. the build key covers the
// same app directory, so servers compiling the app share one warm build root.
function expoSwiftPackage(appKey: string, name: string): string {
  return path.join(os.tmpdir(), 'peach-expo-swift', appKey, `p${process.pid}`, name)
}

class ExpoSwiftLinkRefusal extends Error {}
// a failed compiler result is valid only for the exact app and framework inputs.
// it is kept at the app level, above each process's build copy, so a restarted
// dev server skips the namespace instead of relinking every namespace and
// isolating each again.
function failureRecordPath(packagePath: string) {
  const app = path.dirname(path.dirname(packagePath))
  return path.join(app, `${path.basename(packagePath)}.failed.json`)
}

function readFailedCompilation(packagePath: string) {
  let record: unknown
  try {
    record = JSON.parse(fs.readFileSync(failureRecordPath(packagePath), 'utf8'))
  } catch {
    return null
  }
  if (
    typeof record !== 'object' ||
    record === null ||
    !('stamp' in record) ||
    !('diagnostic' in record) ||
    typeof record.stamp !== 'string' ||
    typeof record.diagnostic !== 'string'
  )
    return null
  if (
    'retryAt' in record &&
    (typeof record.retryAt !== 'number' ||
      !Number.isFinite(record.retryAt) ||
      record.retryAt <= Date.now())
  )
    return null
  return { stamp: record.stamp, diagnostic: record.diagnostic }
}

// the named Swift modules and the modules they import, transitively
function onlyModules(
  units: ExpoSwiftSourceUnit[],
  only: readonly string[] | undefined,
): ExpoSwiftSourceUnit[] {
  if (!only) return units
  const wanted = new Set(only)
  const selected = new Set<ExpoSwiftSourceUnit>()
  for (let grew = true; grew; ) {
    grew = false
    for (const unit of units) {
      if (selected.has(unit) || !wanted.has(unit.namespace)) continue
      selected.add(unit)
      grew = true
      for (const source of Object.values(unit.files))
        for (const name of swiftImportNames(source)) wanted.add(name)
    }
  }
  return units.filter((unit) => selected.has(unit))
}

export async function compileExpoSwiftModules(
  root: string,
  base: string,
  publishArtifact?: (
    artifact: import('./swift-host').SwiftArtifact,
    signal: AbortSignal,
  ) => Promise<void>,
  options: ExpoSwiftPreparationOptions = {},
): Promise<ExpoSwiftCompilationResult | null> {
  if (publishArtifact || options.signal?.aborted)
    return compileExpoSwiftModulesTraced(root, base, publishArtifact, options)
  const signal = options.signal ?? new AbortController().signal
  const started = performance.now()
  const report = (message: string) =>
    console.error(`[expo-swift ${Math.round(performance.now() - started)}ms] ${message}`)
  installSwiftInputTrace()
  let key: string
  try {
    key = `${await discoveryKey(root, options.installedWorkspace, true, options.iosTarget, options.moduleRoot)}\0${options.only?.join(',') ?? ''}\0${oneSDKStamp(options.oneSDK)}`
  } catch {
    return compileExpoSwiftModulesTraced(root, base, publishArtifact, options)
  }
  const cached = preparedCache.get(key)
  if (cached && (await witnessMatches(cached.witness))) {
    signal.throwIfAborted()
    report('reusing prepared expo swift artifact')
    return retarget(cached, base)
  }
  const witness: Witness = { marks: new Map(), tainted: false }
  const result = await traceStore.run(witness, () =>
    compileExpoSwiftModulesTraced(root, base, publishArtifact, options),
  )
  if (result && witness.marks.size > 0 && (await witnessMatches(witness))) {
    preparedCache.set(key, {
      witness,
      base,
      result: cloneResult(result),
    })
  }
  return result
}

async function compileExpoSwiftModulesTraced(
  root: string,
  base: string,
  publishArtifact?: (
    artifact: import('./swift-host').SwiftArtifact,
    signal: AbortSignal,
  ) => Promise<void>,
  options: ExpoSwiftPreparationOptions = {},
): Promise<ExpoSwiftCompilationResult | null> {
  // admission and compiler owners decide build liveness; coarse stage logs do not.
  const signal = options.signal ?? new AbortController().signal
  const started = performance.now()
  const report = (message: string) =>
    console.error(`[expo-swift ${Math.round(performance.now() - started)}ms] ${message}`)
  try {
    signal.throwIfAborted()
    // a package-scoped compile is what per-package entries hold, so it never
    // reads the whole-app entry or a CocoaPods workspace
    const prebuilt =
      options.installedWorkspace || options.only || options.moduleRoot
        ? null
        : await prebuiltExpoNative(root, options.iosTarget)
    if (prebuilt) {
      report('using the published native build for this app')
      return await prebuiltExpoSwiftResult(root, prebuilt, signal)
    }
    report(`discovering app-owned modules: ${root}`)
    const expoUnits = await collectExpoSwiftSources(
      root,
      signal,
      options.installedWorkspace,
      nativeWorkspaceAvailable() && !options.only,
      options.iosTarget,
      { moduleRoot: options.moduleRoot },
    )
    signal.throwIfAborted()
    // reading the app's xcode project resolves remote swift packages with the
    // locked compiler, so install it first only when a project names one.
    const ios = path.join(root, 'ios')
    if (
      [ios, path.join(ios, 'Pods')].some(
        (dir) =>
          fs.existsSync(dir) &&
          fs.readdirSync(dir).some((entry) => {
            const project = path.join(dir, entry, 'project.pbxproj')
            return (
              entry.endsWith('.xcodeproj') &&
              fs.existsSync(project) &&
              fs.readFileSync(project, 'utf8').includes('XCRemoteSwiftPackageReference')
            )
          }),
      )
    )
      await ensureSwiftToolchain(signal)
    // app target modules are never part of an installed package
    let bridge = options.only
      ? null
      : await collectBridgeModuleSources(fs.realpathSync(root), signal)
    if (
      nativeWorkspaceAvailable() &&
      fs.existsSync(path.join(root, 'ios', 'Podfile')) &&
      bridge?.units.some((unit) =>
        unit.nativeTargets?.some((target) => target.bridgingHeader),
      )
    ) {
      const prepared = await prepareExpoNativeWorkspace(root, signal, options.iosTarget)
      bridge = await collectBridgeModuleSources(
        fs.realpathSync(prepared.app),
        signal,
        options.installedWorkspace ?? prepared.workspace,
      )
    }
    if (bridge && bridge.installedNamespaces.length > 0) {
      const workspace =
        options.installedWorkspace ??
        (await prepareExpoNativeWorkspace(root, signal, options.iosTarget)).workspace
      const module = options.moduleRoot
        ? { root: options.moduleRoot, ...swiftModuleToolchain(options.moduleRoot) }
        : await resolveSwiftModule({ signal })
      await prepareXcodeSwiftPackages(workspace, options.iosTarget, undefined, signal)
      await withXcodeProject(
        workspace,
        {
          target: options.iosTarget,
          configuration: 'Debug',
          interfaceRoot: module.root,
          nativeModules: bridge.installedNamespaces,
        },
        async (project) => {
          const installed = await installedWorkspaceInput(
            project,
            'main.swift',
            module.root,
          )
          enrichInstalledUnits(
            bridge.units,
            installed,
            new Map(),
            new Set(swiftPeachModules(module.root)),
            module.root,
            root,
            new Set(bridge.installedNamespaces),
            preparedXcodeInterfaces(workspace),
          )
        },
      )
    }
    for (const unit of bridge?.units ?? []) {
      if (expoUnits?.some((expo) => expo.namespace === unit.namespace))
        throw new Error(
          `app target ${unit.namespace} shares its Swift module name with a local Expo module`,
        )
      unit.files[EXPO_SWIFT_ENTRY] = expoEntry([unit])
      unit.files['Package.swift'] = expoManifest(unit.files, '', targetSettings([unit]))
    }
    const units = onlyModules(
      [...(expoUnits ?? []), ...(bridge?.units ?? [])],
      options.only,
    )
    const bridgeFailures = bridge?.failures ?? []
    if (units.length === 0 && bridgeFailures.length === 0 && expoUnits === null)
      return null
    report(
      `preparing ${units.length} modules: ${units.map((unit) => unit.moduleId).join(', ')}`,
    )
    const result: ExpoSwiftCompilationResult = {
      ...(expoUnits?.[0]?.nativeAppIdentity
        ? { nativeAppIdentity: expoUnits[0].nativeAppIdentity }
        : {}),
      namespaces: [
        ...units.map((unit) => unit.moduleId),
        ...bridgeFailures.map((failure) => failure.namespace),
      ],
      bridgeModules: [
        ...(bridge?.units ?? []).map((unit) => unit.moduleId),
        ...bridgeFailures.map((failure) => failure.namespace),
      ],
      modules: [],
      failures: [...bridgeFailures],
    }
    if (units.length === 0) {
      // nothing compilable: report the discovery failures without resolving
      // a toolchain, in every mode. resolving here throws in publishArtifact
      // mode when no toolchain is available, and can install or download a
      // Swift distribution just to report a failure.
      return result
    }
    // every candidate links into one app first; only a failed link compiles each
    // namespace alone to isolate the failures, so a framework change costs one build.
    const module = options.moduleRoot
      ? { root: options.moduleRoot, ...swiftModuleToolchain(options.moduleRoot) }
      : await resolveSwiftModule({ signal })
    signal.throwIfAborted()
    const reactProvider = units.some((unit) => unit.reactNativeProvider)
      ? await (async () => {
          const projectRoot = options.installedWorkspace
            ? path.dirname(path.dirname(options.installedWorkspace))
            : (await prepareExpoNativeWorkspace(root, signal, options.iosTarget)).app
          const reactNativeRoot = path.dirname(
            createRequire(path.join(projectRoot, 'package.json')).resolve(
              'react-native/package.json',
            ),
          )
          const provider = await prebuiltReactNativeCore(
            projectRoot,
            reactNativeRoot,
            module.root,
            'expo',
          )
          const headers = new Map<string, { file: string; relative: string }[]>()
          for (const [file, body] of Object.entries(provider.files)) {
            const relative = file.split('/upstream/react-native/')[1]
            if (!relative || !/\.(?:h|hh|hpp|hxx)$/.test(file)) continue
            const matches = headers.get(body) ?? []
            matches.push({ file, relative })
            headers.set(body, matches)
          }
          for (const unit of units)
            for (const [file, source] of Object.entries(unit.nativeFiles ?? {})) {
              const original = headers
                .get(source)
                ?.find(({ relative }) => file.endsWith(`/${relative}`))
              if (!original) continue
              provider.headerAliases ??= {}
              provider.headerAliases[file] = original.file
            }
          return provider
        })()
      : undefined
    const reactProviderStamp = reactProvider
      ? createHash('sha256').update(JSON.stringify(reactProvider)).digest('hex')
      : ''
    const key = createHash('sha256').update(fs.realpathSync(root)).digest('hex')
    const unitContentStamp = (unit: ExpoSwiftSourceUnit) =>
      sourceContentStamp(expoSwiftPackage(key, unit.moduleId), module.root) +
      (unit.reactNativeProvider ? `:${reactProviderStamp}` : '')
    const failures = new Map<string, string>()
    const failureRecords = new Map<
      string,
      { stamp: string; diagnostic: string; retryAt?: number }
    >()
    const candidates: ExpoSwiftSourceUnit[] = []
    const stamps = new Map<ExpoSwiftSourceUnit, string>()
    const generations = new Map<ExpoSwiftSourceUnit, string>()
    const gaps = new Map<ExpoSwiftSourceUnit, string[]>()
    const libraries = new Map<ExpoSwiftSourceUnit, Record<string, string>>()
    const binaryModules = new Map<ExpoSwiftSourceUnit, Record<string, string>>()
    const [firstSharedLibrary, ...otherSharedLibraries] = nonmodularFrameworkLibraries(
      [...new Set(units.flatMap((unit) => unit.frameworks))],
      module.root,
    )
    const sharedLibrary =
      firstSharedLibrary === undefined
        ? undefined
        : fs
            .readFileSync(
              combineNativeStaticLibraries(
                [firstSharedLibrary, ...otherSharedLibraries],
                module.root,
              ),
            )
            .toString('base64')
    function preparePackage(linked: ExpoSwiftSourceUnit[], packagePath: string): void {
      const files: Record<string, string> = {}
      for (const unit of linked)
        for (const [name, source] of Object.entries(unit.files)) {
          if (
            name.startsWith(`${SWIFT_STANDINS_DIR}/`) &&
            name in files &&
            files[name] !== source
          )
            throw new Error(`conflicting Expo Swift binary source ${name}`)
          files[name] = source
        }
      const settings = targetSettings(linked)
      if (options.oneSDK) {
        for (const [name, source] of options.oneSDK.targets) files[name] = source
        for (const [name, source] of options.oneSDK.entry)
          files[`Sources/PeachExpoApp/${name}`] = source
        settings.set('OneSDKBindings', {
          languageMode: 5,
          mainActorIsolation: false,
          swiftFlags: ['-suppress-warnings'],
          dependencies: [{ kind: 'target', name: 'One' }],
        })
      }
      files[EXPO_SWIFT_ENTRY] = expoEntry(linked, options.oneSDK !== undefined)
      files['Package.swift'] = expoManifest(
        files,
        linked.map((unit) => generations.get(unit) ?? '').join(','),
        settings,
      )
      const provider = linked.some((unit) => unit.reactNativeProvider)
        ? reactProvider
        : undefined
      if (provider) {
        for (const [file, source] of Object.entries(provider.files)) {
          if (file === 'Package.swift' || file === provider.entry) continue
          if (file in files && files[file] !== source)
            throw new Error(`conflicting Expo React provider source ${file}`)
          files[file] = source
        }
        const targets = manifestCalls(provider.files['Package.swift']!, [
          'target',
          'systemLibrary',
        ]).map(({ kind, call }) => `.${kind}(${call},`)
        const names = swiftManifestTargets(provider.files['Package.swift']!)
          .filter((target) => !target.executable)
          .map((target) => JSON.stringify(target.name))
        const floor = inheritExecutableFloor(
          linked.flatMap((unit) => unit.nativeTargets ?? []),
        )?.find((target) => target.name === 'PeachExpoApp')?.deploymentTarget
        if (!floor) throw new Error('Expo React provider has no iOS deployment target')
        files['Package.swift'] = files['Package.swift']!.replace(
          'Package(name: "PeachExpo", targets:',
          `Package(name: "PeachExpo", platforms: [.iOS(${JSON.stringify(floor)})], targets:`,
        )
          .replace('targets: [', `targets: [${targets.join('\n')}`)
          .replace(
            '.executableTarget(name: "PeachExpoApp", dependencies: [',
            `.executableTarget(name: "PeachExpoApp", dependencies: [${names.join(',')},`,
          )
          .replace(
            '])\n// stand-in inputs:',
            '], cxxLanguageStandard: .cxx20)\n// stand-in inputs:',
          )
      }
      syncSwiftTree(
        packagePath,
        new Map(
          Object.entries(files).map(([name, source]) => [
            path.join(packagePath, name),
            source,
          ]),
        ),
      )
      const linkedLibraries = new Map<string, string>(
        Object.entries(provider?.libraries ?? {}),
      )
      let linkedSharedLibrary = false
      for (const unit of linked)
        for (const [name, library] of Object.entries(libraries.get(unit) ?? {})) {
          if (name === unit.namespace && library === sharedLibrary) {
            if (linkedSharedLibrary) continue
            linkedSharedLibrary = true
          }
          if (linkedLibraries.has(name) && linkedLibraries.get(name) !== library)
            throw new Error(`conflicting Expo Swift binary libraries for ${name}`)
          linkedLibraries.set(name, library)
        }
      projectFor(packagePath).oneModule = false
      projectFor(packagePath).optimize = true
      projectFor(packagePath).staticClangTargets = provider?.staticClangTargets
      projectFor(packagePath).binaryModules = Object.fromEntries([
        ...Object.entries(provider?.binaryModules ?? {}),
        ...linked.flatMap((unit) => Object.entries(binaryModules.get(unit) ?? {})),
      ])
      projectFor(packagePath).libraries =
        linkedLibraries.size > 0 ? Object.fromEntries(linkedLibraries) : undefined
      projectFor(packagePath).nativeTargets = inheritExecutableFloor([
        ...new Map(
          [
            ...linked.flatMap((unit) => unit.nativeTargets ?? []),
            ...(provider?.nativeTargets ?? []),
          ].map((target) => [target.name, target] satisfies [string, typeof target]),
        ).values(),
      ])
      projectFor(packagePath).nativeFiles = Object.assign(
        {},
        ...linked.map((unit) => unit.nativeFiles),
        provider &&
          Object.fromEntries(
            Object.entries(provider.files).filter(
              ([file]) => file !== 'Package.swift' && file !== provider.entry,
            ),
          ),
      )
      projectFor(packagePath).headerAliases = Object.assign(
        {},
        ...linked.map((unit) => unit.headerAliases),
        provider?.headerAliases,
      )
      const resources = Object.assign({}, ...linked.map((unit) => unit.resources))
      const resourceBundles = [
        ...new Map(
          linked.flatMap((unit) =>
            (unit.resourceBundles ?? []).map(
              (bundle) => [bundle.target, bundle] satisfies [string, typeof bundle],
            ),
          ),
        ).values(),
      ]
      projectFor(packagePath).resourceBundles = resourceBundles
      projectFor(packagePath).bundleFiles = Object.keys(resources).length
        ? { files: resources, bundles: resourceBundles, watched: [] }
        : undefined
    }
    for (const unit of units) {
      signal.throwIfAborted()
      if (sharedLibrary !== undefined)
        libraries.set(unit, { [unit.namespace]: sharedLibrary })
      if (unit.absentFrameworks)
        gaps.set(
          unit,
          unit.absentFrameworks.map(
            (declared) =>
              `${unit.namespace}.podspec declares vendored framework ${declared}, which is absent`,
          ),
        )
      if (unit.frameworks.length > 0) {
        const provided = new Set(swiftPeachModules(module.root))
        const available = swiftAvailableModules(module.root, module.toolchainBin)
        const binaries = await Promise.all(
          unit.frameworks.map(async (dir) => {
            const binary: SwiftPackageBinary = {
              target: path.basename(dir).replace(/\.(xcframework|framework)$/, ''),
              source: dir,
              url: null,
              checksum: null,
              dir,
              reached: true,
            }
            return {
              binary,
              modules: dir.endsWith('.framework')
                ? [binary.target]
                : await swiftBinaryModules(binary),
            }
          }),
        )
        const importedAvailable = new Set([
          ...available,
          ...units.map((item) => item.namespace),
          ...binaries.flatMap((item) => item.modules),
        ])
        const imports = new Set(
          Object.values(unit.files).flatMap((source) =>
            swiftImportNames(source, importedAvailable),
          ),
        )
        const reached = binaries
          .filter((item) => item.modules.some((name) => imports.has(name)))
          .map((item) => item.binary)
        if (reached.length > 0) {
          const toolchain = {
            moduleRoot: module.root,
            release: module.release,
            toolchainBin: module.toolchainBin,
          }
          const generation = standinGenerationInputs(reached, toolchain)
          const built = await swiftStandins(reached, toolchain, provided)
          binaryModules.set(
            unit,
            Object.fromEntries(
              built.standins.flatMap((standin) =>
                standin.prebuilt ? [[standin.module, standin.prebuilt.module]] : [],
              ),
            ),
          )
          const linkedLibraries = standinLibraries(
            reached,
            built.standins,
            root,
            toolchain,
          )
          const linkedStandins = new Set([...linkedLibraries.values()].flat())
          for (const standin of built.standins)
            for (const [name, source] of Object.entries(standin.files)) {
              const file = `${SWIFT_STANDINS_DIR}/${standin.module}/${name}`
              const text =
                linkedStandins.has(standin) &&
                (name === `${standin.module}.c` || name === `${standin.module}.cpp`)
                  ? `// ${standin.target}'s WebAssembly library defines ${standin.module}'s functions.\n`
                  : source
              if (file in unit.files && unit.files[file] !== text)
                throw new Error(`conflicting Expo Swift binary source ${file}`)
              unit.files[file] = text
            }
          // a generated shim replaces a prebuilt binary that declares no
          // deployment floor of its own; it inherits its consuming unit's
          // resolved floor so the link compiles every target with real
          // intake versions. the entry also carries the shim's headers and
          // module map directory, so preparation stages the real clang
          // module. without a resolved floor the entry stays absent and the
          // builder keeps refusing the target honestly.
          const deploymentTarget = unit.nativeTargets?.find(
            (item) => item.name === unit.namespace,
          )?.deploymentTarget
          if (deploymentTarget)
            for (const standin of built.standins) {
              unit.nativeTargets ??= []
              if (!unit.nativeTargets.some((item) => item.name === standin.module))
                unit.nativeTargets.push(standinNativeTarget(standin, deploymentTarget))
            }
          if (linkedLibraries.size > 0)
            libraries.set(unit, {
              ...libraries.get(unit),
              ...Object.fromEntries(
                [...linkedLibraries].map(([library, [first]]) => [
                  first!.module,
                  fs.readFileSync(library).toString('base64'),
                ]),
              ),
            })
          generations.set(unit, generation)
          gaps.set(unit, [
            ...(gaps.get(unit) ?? []),
            ...[...built.gaps].map(([name, reason]) => `${name}: no stand-in: ${reason}`),
          ])
          unit.files['Package.swift'] = expoManifest(
            unit.files,
            generation,
            targetSettings([unit]),
          )
        }
      }
      const packagePath = expoSwiftPackage(key, unit.moduleId)
      preparePackage([unit], packagePath)
      const stamp = unitContentStamp(unit)
      const failed = readFailedCompilation(packagePath)
      if (failed?.stamp === stamp) {
        failures.set(unit.moduleId, failed.diagnostic)
        continue
      }
      fs.rmSync(failureRecordPath(packagePath), { force: true })
      stamps.set(unit, stamp)
      candidates.push(unit)
    }
    const preparedKey = expoSwiftPreparedKey(
      base,
      units,
      reactProviderStamp + oneSDKStamp(options.oneSDK),
    )
    if (!publishArtifact) {
      const prepared = preparedExpoSwift.get(preparedKey)
      if (prepared) {
        report('reusing prepared expo swift artifact')
        return prepared
      }
    }
    const link = async (linked: ExpoSwiftSourceUnit[]) => {
      const packagePath = expoSwiftPackage(key, 'linked-app')
      preparePackage(linked, packagePath)
      signal.throwIfAborted()
      const stamp = sourceContentStamp(packagePath, module.root)
      const refused = readFailedCompilation(packagePath)
      if (refused?.stamp === stamp) {
        report('reusing recent link refusal')
        throw new ExpoSwiftLinkRefusal(refused.diagnostic)
      }
      fs.rmSync(failureRecordPath(packagePath), { force: true })
      report(`linking ${linked.map((unit) => unit.moduleId).join(', ')}`)
      try {
        return await artifactFor(
          projectFor(packagePath),
          EXPO_SWIFT_ENTRY,
          module.root,
          signal,
        )
      } catch (error) {
        signal.throwIfAborted()
        const diagnostic = error instanceof Error ? error.message : String(error)
        if (
          error instanceof SwiftMissingModulesError ||
          /^.+:\d+(?::\d+)?: error:|^(?:ld(?:\.lld)?|wasm-ld): error:|^(?:error: )?[^\n:]+: missing or unsupported declared iOS deployment target /m.test(
            diagnostic,
          )
        )
          throw error
        // admission and interrupted builds say nothing about individual modules.
        // share their result briefly, including across dev server restarts.
        if (sourceContentStamp(packagePath, module.root) === stamp)
          fs.writeFileSync(
            failureRecordPath(packagePath),
            JSON.stringify({ stamp, diagnostic, retryAt: Date.now() + 60_000 }),
          )
        throw new ExpoSwiftLinkRefusal(diagnostic, { cause: error })
      }
    }
    let linked = candidates
    let artifact: import('./swift-host').SwiftArtifact | undefined
    if (linked.length) {
      try {
        artifact = await link(linked)
      } catch (linkError) {
        signal.throwIfAborted()
        if (linkError instanceof ExpoSwiftLinkRefusal) {
          throw linkError
        } else {
          const combined =
            linkError instanceof Error ? linkError.message : String(linkError)
          report('linked build failed; isolating module diagnostics')
          for (const line of combined.split('\n')) report(line)
          // each isolated build recompiles every native dependency, so checking
          // all namespaces costs one full build apiece. the combined diagnostic
          // names failing namespaces by build copy, app source or a module Peach
          // lacks that they import: link the rest once and
          // isolate only those, or every namespace when that link fails.
          const errorFiles = combined.match(/^.+?(?=:\d+(?::\d+)?: error:)/gm) ?? []
          // a native unit compiles from its group copy, which the error or the
          // include chain above it names; the unit holds it as Sources/<target>/<path>.
          const nativeCopies = [
            ...combined.matchAll(
              /PeachNativeSources\/([^/]+?)(?:Native|Swift)Implementation_[0-9a-f]+\/([^:\s]+)/g,
            ),
          ].map(([, target, file]) => `Sources/${target}/${file}`)
          const missing = new Set(
            linkError instanceof SwiftMissingModulesError
              ? [...combined.matchAll(/^  (\S+)/gm)].map((match) => match[1])
              : [],
          )
          const named = candidates.filter(
            (unit) =>
              [...Object.keys(unit.files), ...expoUnitAppPaths(unit)].some(
                (name) =>
                  nativeCopies.includes(name) ||
                  errorFiles.some((file) => file === name || file.endsWith(`/${name}`)),
              ) ||
              Object.values(unit.files).some((source) =>
                swiftImportNames(source).some((name) => missing.has(name)),
              ),
          )
          let checked = candidates
          linked = []
          if (named.length > 0 && named.length < candidates.length) {
            const rest = candidates.filter((unit) => !named.includes(unit))
            report(`linking ${rest.length} namespaces the diagnostic does not name`)
            try {
              artifact = await link(rest)
              linked = rest
              checked = named
            } catch (error) {
              signal.throwIfAborted()
              if (error instanceof ExpoSwiftLinkRefusal) throw error
            }
          }
          const linkedWithoutChecks = linked.length
          for (const unit of checked) {
            const packagePath = expoSwiftPackage(key, unit.moduleId)
            try {
              signal.throwIfAborted()
              report(`checking ${unit.moduleId}`)
              await artifactFor(
                projectFor(packagePath),
                EXPO_SWIFT_ENTRY,
                module.root,
                signal,
              )
              linked.push(unit)
            } catch (error) {
              signal.throwIfAborted()
              const message = error instanceof Error ? error.message : String(error)
              const missingImports = [...message.matchAll(/^  (\S+)/gm)].map(
                (match) => match[1],
              )
              const diagnostic = [
                error instanceof SwiftMissingModulesError && unit.workspaceSources?.length
                  ? `${unit.workspaceSources.map((name) => `${name} needs a Mac-prepared workspace`).join('; ')}; unresolved imports: ${missingImports.join(', ')}`
                  : message,
                ...(gaps.get(unit) ?? []),
              ].join('\n')
              // a unit from the installed workspace carries no app source
              // location, so its errors name the build copy of its own files.
              const unitFiles = [...Object.keys(unit.files), ...expoUnitAppPaths(unit)]
              const errors = diagnostic.match(/^.+:\d+(?::\d+)?: error:.*$/gm) ?? []
              const sourceErrors = errors.filter((line) => {
                const file = /^.+?(?=:\d+(?::\d+)?: error:)/.exec(line)![0]
                return (
                  unitFiles.some((name) => file === name || file.endsWith(`/${name}`)) &&
                  !/external macro implementation type|failed to load library plugin/.test(
                    line,
                  )
                )
              })
              // native preparation and link failures of a unit built alone name
              // the target or a symbol, not a file; they are input-determined
              // like a source error, so they ride with them instead of hiding
              // behind the filtered diagnostic.
              const targetErrors =
                diagnostic.match(
                  /^error: target .*$|^(?:error: )?[^\n:]+: missing or unsupported declared iOS deployment target .*$|^(?:ld(?:\.lld)?|wasm-ld): error: .*$/gm,
                ) ?? []
              const unitErrors = [...targetErrors, ...sourceErrors]
              if (
                publishArtifact &&
                targetErrors.length === 0 &&
                (sourceErrors.length === 0 || sourceErrors.length !== errors.length) &&
                !(error instanceof SwiftMissingModulesError)
              )
                throw error
              // a source, target or link error, or a module peach does not provide, holds until the
              // stamp changes. the compiler reports one error at both the app
              // source and the build copy, so either line holds it. retrying
              // either relinks every namespace and rewrites the linked package,
              // so no reload would ever reuse its artifact.
              const missing = error instanceof SwiftMissingModulesError
              if (
                (missing || unitErrors.length > 0) &&
                unitContentStamp(unit) === stamps.get(unit)
              ) {
                failureRecords.set(packagePath, {
                  stamp: stamps.get(unit)!,
                  diagnostic: missing ? diagnostic : unitErrors.join('\n'),
                })
              }
              failures.set(
                unit.moduleId,
                unitErrors.length ? unitErrors.join('\n') : diagnostic,
              )
            }
          }
          // every namespace compiles alone, so the link itself is what failed.
          if (linked.length === candidates.length) throw linkError
          if (linked.length > linkedWithoutChecks) {
            try {
              artifact = await link(linked)
            } catch (error) {
              signal.throwIfAborted()
              if (!(error instanceof SwiftMissingModulesError)) throw error
              // the merged sources import a module none of the pieces needed
              // alone. drop the pieces that import it and link the rest; a
              // miss that none of them import is still a failed link.
              const missing = new Set(
                [...error.message.matchAll(/^  (\S+)/gm)].map((match) => match[1]),
              )
              const dropped = linked.filter((unit) =>
                Object.values(unit.files).some((source) =>
                  swiftImportNames(source).some((name) => missing.has(name)),
                ),
              )
              if (dropped.length === 0) throw error
              for (const unit of dropped) failures.set(unit.moduleId, error.message)
              linked = linked.filter((unit) => !dropped.includes(unit))
              if (linked.length) artifact = await link(linked)
            }
          }
        }
      }
    }
    for (const unit of units) {
      const diagnostic = failures.get(unit.moduleId)
      if (diagnostic !== undefined)
        result.failures.push({ namespace: unit.moduleId, diagnostic })
    }
    if (artifact) {
      signal.throwIfAborted()
      await publishArtifact?.(artifact, signal)
      result.modules.push({
        namespaces: linked.map((unit) => unit.moduleId),
        url: `${base}/__peach/swift/${artifact.hash}.wasm`,
        hash: artifact.hash,
        icuUrl: icuUrl(base, artifact),
        rootId: `${key}/Expo`,
        bundleFiles: artifact.package.bundleFiles.files,
      })
    }
    signal.throwIfAborted()
    for (const [packagePath, record] of failureRecords)
      fs.writeFileSync(failureRecordPath(packagePath), JSON.stringify(record))
    report(
      `ready: ${result.modules.length} artifact, ${result.failures.length} unavailable modules`,
    )
    if (!publishArtifact) preparedExpoSwift.set(preparedKey, result)
    return result
  } catch (error) {
    const failure: unknown = signal.aborted ? signal.reason : error
    report(`failed: ${failure instanceof Error ? failure.message : String(failure)}`)
    throw failure
  }
}

export async function handleExpoSwiftRequest(
  req: IncomingMessage,
  res: ServerResponse,
): Promise<boolean> {
  const url = new URL(req.url ?? '/', 'http://localhost')
  if (!url.pathname.startsWith('/__peach/swift') && url.pathname !== EXPO_SWIFT_ROUTE)
    return false
  const remote = req.socket.remoteAddress?.replace(/^::ffff:/, '')
  const origin = req.headers.origin
  if (
    !remote ||
    !isLoopbackHost(remote) ||
    (origin && !isLoopbackHost(new URL(origin).hostname))
  ) {
    res.writeHead(403)
    res.end('Expo Swift artifacts require a loopback client')
    return true
  }
  res.setHeader('Access-Control-Allow-Origin', origin ?? '*')
  res.setHeader('Vary', 'Origin')
  res.setHeader('Cross-Origin-Resource-Policy', 'cross-origin')
  if (await serveSwiftPackageAsset(url.pathname, res)) return true
  if (url.pathname !== EXPO_SWIFT_ROUTE) return false
  if (req.method !== 'GET') {
    res.writeHead(405)
    res.end('GET required')
    return true
  }
  const root = url.searchParams.get('root')
  if (!root || !path.isAbsolute(root)) {
    res.writeHead(400)
    res.end('missing absolute app root')
    return true
  }
  let key: string
  try {
    key = fs.realpathSync(root)
  } catch (error) {
    res.writeHead(400)
    res.end(error instanceof Error ? error.message : String(error))
    return true
  }
  const host = req.headers.host
  if (!host) {
    res.writeHead(400)
    res.end('Expo Swift request has no host')
    return true
  }
  const iosTarget = url.searchParams.get('iosTarget') ?? undefined
  if (url.searchParams.get('discover') === '1') {
    try {
      const units = await collectExpoSwiftSources(
        key,
        undefined,
        undefined,
        false,
        iosTarget,
        { metadataOnly: true },
      )
      const metadata: ExpoSwiftDiscoveryResult | null = units && {
        namespaces: units.map((unit) => unit.moduleId),
      }
      res.writeHead(200, {
        'Content-Type': 'application/json',
        'Cache-Control': 'no-store',
      })
      res.end(JSON.stringify(metadata))
    } catch (error) {
      res.writeHead(500, { 'Content-Type': 'text/plain' })
      res.end(error instanceof Error ? error.message : String(error))
    }
    return true
  }
  const flightKey = `${host}\0${key}\0${iosTarget ?? ''}`
  const prepared = openPreparations.take(
    flightKey,
    url.searchParams.get(NATIVE_PREPARED_QUERY_PARAM),
  )
  if (prepared) {
    res.writeHead(200, {
      'Content-Type': 'application/json',
      'Cache-Control': 'no-store',
    })
    res.end(JSON.stringify(prepared.value))
    return true
  }
  let pending = compiling.get(flightKey)
  if (!pending) {
    pending = compileExpoSwiftModules(key, `http://${host}`, undefined, {
      iosTarget,
    }).finally(() => {
      compiling.delete(flightKey)
    })
    compiling.set(flightKey, pending)
  }
  try {
    const metadata = await pending
    if (!res.destroyed) {
      openPreparations.store(
        flightKey,
        url.searchParams.get(NATIVE_PREPARE_QUERY_PARAM),
        metadata,
      )
      res.writeHead(200, {
        'Content-Type': 'application/json',
        'Cache-Control': 'no-store',
      })
      res.end(JSON.stringify(metadata))
    }
  } catch (error) {
    if (!res.destroyed) {
      res.writeHead(500, { 'Content-Type': 'text/plain' })
      res.end(error instanceof Error ? error.message : String(error))
    }
  }
  return true
}
