import { existsSync, realpathSync } from 'node:fs'; import { basename } from 'node:path'; import type { StimContext } from '@stim-cli/core'; import { machineCapacity, placementWord } from '@stim-cli/core/state'; import { OffloadRefusal } from '../build-placement.ts'; import { filesystemBuildCapability } from '../cache/build-cache.ts'; import { skippedMissReason } from '../cache/miss-reason.ts'; import { processContext } from '../cli-operation.ts'; import { planFlagRefusal, planPayload } from '../commands/build-plan.ts'; import { DEFAULT_DEPS } from '../commands/ios/dependencies.ts'; import { hostedIosSelectors } from '../commands/ios/remote.ts'; import { iosProcessRuntime } from '../commands/ios/launch.ts'; import { deviceModelRefusal, resolveConfiguration, resolveDeviceType, resolveRuntime, } from '../commands/ios/support.ts'; import type { FailArgs, IosCommandOptions } from '../commands/ios/types.ts'; import type { DoctorContext, Finding } from '../diagnostics/doctor.ts'; import { runCaptured } from '../engine/deps.ts'; import { statsProjectKey } from '../engine/stats.ts'; import { COMPILATION_CACHE_UNAVAILABLE, HEARTBEAT_INTERVAL_MS, readBundleId } from '../engine/xcode.ts'; import { iosToolchainAsync, type BuildTarget } from '../engine/toolchain.ts'; import { planHostedDevice } from '../device-host/plan-placement.ts'; import { getExecutor } from '../exec.ts'; import type { NdjsonWriter } from '../ndjson.ts'; import { manifestDigest } from '../offload/manifest.ts'; import { sourceManifest } from '../offload/native-source.ts'; import { iosSyncPlan } from '../offload/signing-files.ts'; import { parseIosRemote, remoteIosSetting, type ResolvedProjectSettings, SETTING_SHAPE_REMEDY, settingShapeErrors, } from '../workspace/settings.ts'; import { readHostedNative } from '../workspace/placement-state.ts'; import { repoRootAsync } from '../workspace/worktree.ts'; import { IosRecipeRefusal, type IosArtifactContext, type IosArtifactRecipe, type IosCompileResult, type IosProject, } from './ios-project.ts'; import { pluginCheckoutParam } from './plugin-offload.ts'; import type { ProjectDoctor } from './project-doctor.ts'; import type { PlanRefusal, ProjectPlanResult } from './project-plan.ts'; /** An iOS project type's own facts, as plain functions over plain data; the host builds the run, plan and doctor. */ export interface IosPlugin { /** Why the host never caches this project's builds. */ cacheIneligible: string; configurationProblem( scheme: string | undefined, configuration: string | null | undefined, ): { message: string; remedy: string } | null; bundleId(root: string): string | null; /** Why a build needs a simulator of its own; the host then refuses a hosted target and a build-only run. */ simulator(root: string): { reason: string; buildOnly: { message: string; remedy: string } } | null; /** Whether a build compiles on output an earlier build left; undefined when the project cannot tell. */ incremental(root: string, configuration: string | null, env: NodeJS.ProcessEnv): boolean | undefined; /** The build to run, with no shell; `simulator` is the udid the build runs next to, or null for none. */ build(input: { root: string; configuration: string | null; simulator: string | null; env: NodeJS.ProcessEnv }): { argv: [string, ...string[]]; env: NodeJS.ProcessEnv; }; /** The built app's path and the failure diagnostics, read from the build's output and exit; `error` is a spawn failure. */ result(run: { lines: readonly string[]; exitCode: number | null; error: string | null }): { app: string | null; diagnostics: string[]; }; doctor(): Finding[]; } /** The checkout an offloaded build asks for: the folder a repository-root app builds in, and the app's path to a second checkout. */ export interface IosPluginCheckout { name: string; sibling: string | null; } /** How a project type's iOS builds go to a build machine, run by the client, the machine's job and its build. */ export interface IosPluginOffload< Pins extends Record = Record, Payload extends Record = Record, > { /** What an offloaded build of the app at `root` carries, or why it builds on this Mac. */ plan( root: string, env: NodeJS.ProcessEnv, ): { pins: Pins; payload: Payload; checkout: IosPluginCheckout } | { unsupported: string }; /** The pins a request carries as this Stim reads them; null when they are malformed. */ pins(value: unknown): Pins | null; /** The payload a build request carries as this Stim reads it; null when it is malformed. */ payload(value: unknown): Payload | null; /** Why a machine refuses a malformed offer or build request. */ malformed: { offer: string; start: string }; /** What this machine lacks of the toolchain `pins` need, each with the commands that install it. */ tools(pins: Pins, env: NodeJS.ProcessEnv): Array<{ reason: string; commands: string[] }>; /** This machine's checkout for `pins`, and the commit a second checkout beside the app is placed at. */ source(pins: Pins): { dir: string; commit: string }; /** Why the synced project at `root` cannot build with `payload`, as a build refusal; null when it can. */ project(root: string, payload: Payload): { code: string; message: string } | null; /** The environment the build runs with, from this machine's; `sibling` is the placed second checkout, or null. */ env(input: { root: string; payload: Payload; env: NodeJS.ProcessEnv; source: string; sibling: string | null; }): NodeJS.ProcessEnv; } export interface IosPluginSource { id: string; name: string; version: string; ios: IosPlugin; offload: IosPluginOffload; } type Planned = Exclude, { unsupported: string }>; /** `offload.plan`, with the checkout layout a build machine would refuse turned into a reason to build here. */ function pluginOffloadPlan( { name, offload }: IosPluginSource, root: string, env: NodeJS.ProcessEnv, ): Planned | { unsupported: string } { const planned = offload.plan(root, env); if ('unsupported' in planned || pluginCheckoutParam(planned.checkout)) return planned; return { unsupported: `${name} asks for a checkout layout a build machine does not place` }; } async function pluginOffloadTarget( root: string, { id, version }: IosPluginSource, { pins }: Planned, ): Promise { return { platform: 'ios', local: await iosToolchainAsync(root, null), runtime: null, cocoapodsPinned: false, plugin: { id, version, pins }, }; } export async function runPluginIosBuild( { id, ios }: IosPluginSource, { root, configuration, simulator, env, logWriter, onHeartbeat, estimateMs, }: { root: string; configuration: string | null; simulator: string | null; env: NodeJS.ProcessEnv; logWriter: NdjsonWriter; onHeartbeat: (line: string) => void; estimateMs: number | null; }, ): Promise { const { argv, env: buildEnv } = ios.build({ root, configuration, simulator, env }); const run = await runCaptured({ cmd: argv[0], args: argv.slice(1), cwd: root, env: buildEnv, spawn: (file, args, opts) => getExecutor().spawn(file, args, opts), now: Date.now, heartbeatMs: HEARTBEAT_INTERVAL_MS, onHeartbeat, logWriter, event: `${id}_build`, label: 'build', estimateMs, }); const common = { durationMs: run.durationMs, transcriptLines: run.transcript.length, compilationCache: COMPILATION_CACHE_UNAVAILABLE, }; const { app: appPath, diagnostics: errors } = ios.result({ lines: run.transcript, exitCode: run.code, error: run.error ? String(run.error) : null, }); if (appPath && existsSync(appPath)) { const bundleId = await readBundleId(appPath); if (bundleId) return { ...common, ok: true, appPath, bundleId }; } return { ...common, ok: false, code: 'STIM_BUILD_FAILED', diagnostics: errors.slice(0, 10).map((message) => ({ message })), truncated: Math.max(0, errors.length - 10), exitCode: run.code, tail: run.transcript.slice(-20), }; } async function compile( root: string, source: IosPluginSource, context: IosArtifactContext, booting: ReturnType> | null, ): Promise { const run = (simulator: string | null) => runPluginIosBuild(source, { root, configuration: context.configuration, simulator, env: context.operation?.env ?? {}, logWriter: context.logWriter(), onHeartbeat: context.note, estimateMs: context.estimates().coldBuildMs, }); if (!booting) { const needs = source.ios.simulator(root); if (needs) throw new IosRecipeRefusal({ code: 'STIM_BAD_ARG', ...needs.buildOnly }); return run(null); } const booted = await booting; if (!booted.ok) throw new IosRecipeRefusal({ code: 'STIM_NO_DEVICE', message: booted.reason, remedy: 'Run stim ios again to re-establish an owned simulator for this workspace.', }); return run(booted.udid); } function pluginRecipe(root: string, source: IosPluginSource, context: IosArtifactContext): IosArtifactRecipe { const { ios } = source; let booting: ReturnType> | null = null; const boot = () => (booting ??= context.target.booted?.() ?? null); let plan: Planned | { unsupported: string } | null = null; const offloadPlan = () => (plan ??= pluginOffloadPlan(source, root, context.operation?.env ?? {})); const offloaded = (): Planned => { const planned = offloadPlan(); if ('unsupported' in planned) throw new Error(`An ${source.name} offload has no plan: ${planned.unsupported}`); return planned; }; return { buildTool: basename(ios.build({ root, configuration: context.configuration, simulator: null, env: {} }).argv[0]), identity: async () => { const incremental = ios.incremental(root, context.configuration, context.operation?.env ?? {}); return { cacheIneligible: ios.cacheIneligible, ...(incremental === undefined ? {} : { incremental }) }; }, cache: () => filesystemBuildCapability({ context: context.operation, sources: null, readAppId: (path) => readBundleId(path), }), beforeLocalBuild: async () => { await boot(); }, prepare: async () => {}, reconcile: async () => ({ identity: null, rekeyedBy: [], mutationLabel: '' }), validate: async () => null, validateExternal() { throw new IosRecipeRefusal({ code: 'STIM_BAD_ARG', message: `The ${source.name} integration does not use external builds.`, remedy: 'Build the app with stim ios.', }); }, materialize: async (path) => path, compile: () => compile(root, source, context, boot()), explain: () => ({ reason: skippedMissReason(ios.cacheIneligible), diff: null }), untrackedLine: () => null, expoCache: null, offload: { uncached: true, context: () => { const runtime = context.target.offloadRuntime(); const planned = context.target.offloadRefusal || !runtime ? null : offloadPlan(); return { runtime, unsupported: context.target.offloadRefusal ?? (!runtime ? 'no simulator runtime is available for worker selection' : planned && 'unsupported' in planned ? planned.unsupported : null), }; }, target: () => pluginOffloadTarget(root, source, offloaded()), request: (runtime) => { const { pins, payload, checkout } = offloaded(); return { platform: 'ios', runtime, configuration: context.configuration, scheme: null, isExpo: false, optimizations: null, plugin: { id: source.id, version: source.version, pins, payload, checkout }, }; }, syncPlan: iosSyncPlan, unchanged: async (sourceDigest) => { const signal = context.operation?.signal; const found = await repoRootAsync(root, { env: context.operation?.env, signal }); if (found === null) return false; const repoRoot = realpathSync(found); const files = await sourceManifest(repoRoot, false, signal); const synced = await iosSyncPlan( repoRoot, files.map((file) => file.path), ); return sourceDigest === manifestDigest(files.filter((file) => !synced.omit.has(file.path))); }, }, }; } function schemeProblem( ios: IosPlugin, scheme: string | undefined, configuration: string | null | undefined, ): FailArgs | null { const problem = ios.configurationProblem(scheme, configuration); return problem ? { code: 'STIM_BAD_ARG', ...problem } : null; } async function pluginBuildPlacement( root: string, source: IosPluginSource, preference: string, env: NodeJS.ProcessEnv, ): Promise<{ refusal: PlanRefusal } | { buildPlacement: { preference: string; reason: string } } | null> { if (placementWord(preference) === 'local') return null; const planned = pluginOffloadPlan(source, root, env); if (!('unsupported' in planned)) return null; const { buildPlacementCandidates, offloadPlacement } = await import('../offload/client.ts'); const { machines, localEnabled } = buildPlacementCandidates(preference); try { const placement = offloadPlacement({ machines: machines.length, here: machineCapacity(), unsupported: planned.unsupported, localEnabled, selected: preference, }); return { buildPlacement: { preference, reason: `builds on this machine: ${placement.reason}` } }; } catch (error) { if (!(error instanceof OffloadRefusal)) throw error; return { refusal: { code: error.code, message: error.message, remedy: error.remedy } }; } } async function planPluginIos( root: string, source: IosPluginSource, options: IosCommandOptions, { context, settings }: ResolvedProjectSettings, operation: StimContext, ): Promise { if (options.easProfile !== undefined) return { refusal: planFlagRefusal('--eas-profile') }; const [shapeError, ...moreShapeErrors] = settingShapeErrors(settings); if (shapeError) return { refusal: { code: 'STIM_BAD_ARG', message: shapeError, remedy: SETTING_SHAPE_REMEDY }, lines: moreShapeErrors, }; const remote = options.remote !== undefined ? parseIosRemote(options.remote) : remoteIosSetting(settings); if (remote?.kind === 'backend') return { refusal: { code: 'STIM_BAD_ARG', message: 'This project integration does not support the remote iOS target.', remedy: 'Use a local iOS simulator for this integration.', }, }; const { ios } = source; const hostedUnsupported = ios.simulator(root)?.reason; if (remote && hostedUnsupported && (remote.machine !== 'auto' || remote.placement === 'remote-only')) return { refusal: { code: 'STIM_BAD_ARG', message: `This app cannot run on a hosted iOS simulator: ${hostedUnsupported}.`, remedy: 'Run it on a simulator on this Mac with --remote local, or unset ios.remote.', }, }; const layers = DEFAULT_DEPS.settingsLayers(context); const slot = options.slot ?? 'default'; const modelRefusal = await deviceModelRefusal({ slot, deviceTypeFlag: options.deviceType, runtimeFlag: options.runtime, deviceType: resolveDeviceType(options.deviceType, settings), runtime: resolveRuntime(options.runtime, settings), deviceTypeOrigin: DEFAULT_DEPS.settingOriginScope(layers, 'ios.deviceType'), runtimeOrigin: DEFAULT_DEPS.settingOriginScope(layers, 'ios.runtime'), physical: false, hosted: remote !== null && !hostedUnsupported, remoteBackend: null, listRuntimes: DEFAULT_DEPS.listIosRuntimes, signal: operation.signal, }); if (modelRefusal) return { refusal: modelRefusal }; let recorded; try { recorded = remote && hostedUnsupported ? readHostedNative(root, 'ios', slot)[slot] : undefined; } catch (error) { return { refusal: { code: 'STIM_HOSTING_REFUSED', message: error instanceof Error ? error.message : String(error), remedy: error instanceof Error && 'remedy' in error && typeof error.remedy === 'string' ? error.remedy : 'Run stim stop to reconcile the recorded hosted placement, then plan again.', }, }; } if (recorded) return { refusal: { code: 'STIM_BAD_ARG', message: `This workspace's iOS simulator runs on ${recorded.machine}; run stim stop first.`, remedy: 'Run stim stop, then stim ios to run it on this Mac.', }, }; const configuration = resolveConfiguration(options.configuration, settings); const configurationProblem = schemeProblem(ios, options.scheme, configuration); if (configurationProblem) return { refusal: { code: configurationProblem.code, message: configurationProblem.message ?? '', remedy: configurationProblem.remedy ?? '', }, }; let devicePlacement = remote && hostedUnsupported ? `this machine; ${hostedUnsupported}` : 'this machine'; if (remote && !hostedUnsupported) { const planned = await planHostedDevice({ operation, root, slot, platform: 'ios', machine: remote.machine, buildMachine: options.remoteBuild, ...(remote.placement ? { placement: remote.placement } : {}), selectors: hostedIosSelectors( resolveDeviceType(options.deviceType, settings), resolveRuntime(options.runtime, settings), ), sameKey: () => true, }); if (planned.kind === 'refused') return { refusal: { code: planned.code, message: planned.message, remedy: planned.remedy } }; devicePlacement = planned.kind === 'unknown' ? `unknown; ${planned.reason}` : planned.placement; } const placement = await pluginBuildPlacement(root, source, options.remoteBuild ?? 'auto', operation.env); const plan = planPayload( { platform: 'ios', slot, root, projectKey: statsProjectKey({ root, commonDir: context.gitCommonDir, repoRoot: context.repoRoot }), }, { fingerprint: null, cacheKey: null, cacheHit: false, provider: null, cacheSkipped: false, prebuild: null, missReason: skippedMissReason(ios.cacheIneligible), refusal: placement && 'refusal' in placement ? placement.refusal : null, }, ios.incremental(root, configuration, operation.env), ); const bundleId = ios.bundleId(root); return { ...plan, placement: devicePlacement, ...(placement && 'buildPlacement' in placement ? { buildPlacement: placement.buildPlacement } : {}), ...(bundleId ? { bundleId } : {}), }; } export function pluginIosProject(root: string, source: IosPluginSource): IosProject { const { ios } = source; const hostedUnsupported = ios.simulator(root)?.reason; return { plan: (options, resolved, operation) => planPluginIos(root, source, options, resolved, operation ?? processContext(root)), isExpo: false, targets: hostedUnsupported ? ['simulator'] : ['simulator', 'hosted'], ...(hostedUnsupported ? { hostedUnsupported } : {}), eas: false, runtimeKind: () => 'process', bundleId: () => ios.bundleId(root), schemeProblem: (scheme, configuration) => schemeProblem(ios, scheme, configuration), runtime: () => iosProcessRuntime(async () => ({ ok: true, prepared: { metroPort: null } })), artifact: (context) => pluginRecipe(root, source, context), }; } /** `hostFindings` are the findings the host still computes for this project type, after the plugin's own. */ export function pluginIosDoctor( source: IosPluginSource, hostFindings: (context: DoctorContext) => Finding[], ): ProjectDoctor { return { inspect: (context) => context.options.platform && context.options.platform !== 'ios' ? [] : [...source.ios.doctor(), ...hostFindings(context)], offloadTargets: ({ root, options: { platform, operation, remoteEnv } }) => { if (platform && platform !== 'ios') return null; const plan = pluginOffloadPlan(source, root, operation?.env ?? remoteEnv ?? {}); return 'unsupported' in plan ? null : async () => [await pluginOffloadTarget(root, source, plan)]; }, }; }