/** @import { ProjectPluginHost, ProjectPluginIosOffload } from 'stim/plugin' */ /** @import { ToolProblem } from './toolchain.mjs' */ import { existsSync, readFileSync, realpathSync } from 'node:fs'; import { basename, isAbsolute, join, relative, resolve, sep } from 'node:path'; import { parseEnv } from 'node:util'; import { SHA, bunInstall, git, homeOf, isObject, launcherPins, readLauncher, readManifest, run, rustChannel, rustProblems, setupRan, shownPath, } from './toolchain.mjs'; const BUN_VERSION = /^\d{1,4}\.\d{1,4}\.\d{1,4}$/; const RUST_CHANNEL = /^[0-9A-Za-z][0-9A-Za-z.-]{0,39}$/; const APP_NAME = /^[A-Za-z0-9][A-Za-z0-9._-]{0,99}$/; const SETTING = /^[A-Z][A-Z0-9_]*$/; const REMOTE_URL = /^(?:https:\/\/[A-Za-z0-9.-]+(?::\d{1,5})?|ssh:\/\/(?:[A-Za-z0-9._-]+@)?[A-Za-z0-9.-]+(?::\d{1,5})?|[A-Za-z0-9._-]+@[A-Za-z0-9.-]+:)[A-Za-z0-9._~/-]{1,300}$/; const LINK = /^(?:\.\.\/){1,16}(?:(?!\.\.?\/)[A-Za-z0-9._-]{1,100}\/){0,16}(?!\.\.?$)[A-Za-z0-9._-]{1,100}$/; const MAX_SETTINGS = 64; const MAX_SETTING_BYTES = 16 * 1024; const TOOL_TIMEOUT_MS = 15_000; /** * The versions of Bun, Rust and exact2 an Exact app builds with, the name of the folder that holds that exact2 checkout, * and a remote URL that has the exact2 commit, when one is known. * @typedef {{ exact2: string, bun: string, rust: string, checkout: string, url: string | null }} ExactPins */ // Stim's build machine keeps these names at the top of a repository's build area (job/offload/worker.ts), and refuses // to place a second checkout on one; a plan whose exact2 path lands there builds on the client instead. const AREA_ENTRIES = new Set([ 'src', 'checkout', 'home', 'out', 'cache', 'area.json', 'fingerprint-work', 'mirror.json', 'build.ndjson', 'artifact-cache', 'macos', 'lockfile', 'gradle-outputs.json', 'last-used', ]); /** @param {string} name */ const reservedAreaEntry = (name) => AREA_ENTRIES.has(name) || name.startsWith('.artifact-fetch-') || name.startsWith('.stim-exact2-'); /** * @param {Record} manifest * @returns {string[]} */ function declaredSettings(manifest) { return Array.isArray(manifest.env) ? [...new Set(manifest.env.filter((name) => typeof name === 'string' && SETTING.test(name)))] : []; } /** * The declared settings' values in Exact's order: this process's environment, then `.env.local`, then `.env`, each in * Node's dotenv grammar as Exact parses them. * @param {readonly string[]} names * @param {NodeJS.ProcessEnv} env * @param {readonly string[]} files */ function settingValues(names, env, files) { const parsed = files.map((text) => parseEnv(text)); /** @type {Record} */ const values = {}; for (const name of names) { const value = env[name] ?? parsed.find((file) => Object.hasOwn(file, name))?.[name]; if (value !== undefined) values[name] = value; } return values; } /** * The path from the app directory to exact2 as the app's Cargo manifests name it, when it leaves the repository: Exact * writes it relative when the two share their top directory and absolute otherwise (exact2 `scripts/app.mjs` * `pathFrom`). Null when exact2 is inside the repository. * @param {ProjectPluginHost} host * @param {string} app * @param {string} exact2Dir * @returns {Promise} */ async function exact2Link(host, app, exact2Dir) { const top = await git(host, app, ['rev-parse', '--show-toplevel']); const repo = top ? realpathSync(top) : app; const inRepo = relative(repo, exact2Dir); if (inRepo === '' || (!inRepo.startsWith('..') && !isAbsolute(inRepo))) return null; if (app.split(sep)[1] !== exact2Dir.split(sep)[1]) return { unsupported: `the exact2 checkout at ${exact2Dir} shares no top directory with the app, so its Cargo manifests name it by an absolute path a build machine does not have`, }; const link = relative(app, exact2Dir).split(sep).join('/'); if (!LINK.test(link)) return { unsupported: `the path ${link} from the app to exact2 is not one Stim places` }; const depth = relative(repo, app).split(sep).filter(Boolean).length; const above = link.split('/').filter((part) => part === '..').length - depth; if (depth > 0 && above > 1) return { unsupported: `exact2 sits ${above} folders above the repository of this app in a subdirectory, and a build machine places it at most one above`, }; const parts = link.split('/'); const climbs = parts.length - parts.filter((part) => part !== '..').length; const lands = (depth === 0 ? climbs >= 2 : climbs === depth + 1) ? parts[climbs] : undefined; if (lands !== undefined && reservedAreaEntry(lands) && !(lands === 'checkout' && parts.length > climbs + 1)) return { unsupported: `the path ${link} from the app to exact2 lands on ${lands}, which a build machine keeps for itself`, }; return link; } /** * A remote URL of the exact2 checkout whose fetched branches hold its commit, without credentials; null when none does. * @param {ProjectPluginHost} host * @param {string} exact2Dir */ async function remoteUrl(host, exact2Dir) { const branches = await git(host, exact2Dir, ['branch', '-r', '--contains', 'HEAD', '--format=%(refname:lstrip=2)']); const remotes = ((await git(host, exact2Dir, ['remote'])) ?? '').split('\n').filter(Boolean); for (const branch of (branches ?? '').split('\n')) { const remote = remotes.find((each) => branch.startsWith(`${each}/`)); const url = remote ? (await git(host, exact2Dir, ['remote', 'get-url', remote]))?.replace(/^git@github\.com:/, 'https://github.com/') : null; if (url && REMOTE_URL.test(url)) return url; } return null; } /** * The pins a request carries, as a build machine reads them; null when they are malformed. * @param {unknown} value * @returns {ExactPins | null} */ function readPins(value) { if (!isObject(value)) return null; const { exact2, bun, rust, checkout = exact2, url = null } = value; return typeof exact2 === 'string' && SHA.test(exact2) && typeof bun === 'string' && BUN_VERSION.test(bun) && typeof rust === 'string' && RUST_CHANNEL.test(rust) && typeof checkout === 'string' && APP_NAME.test(checkout) && (url === null || (typeof url === 'string' && REMOTE_URL.test(url))) ? { exact2, bun, rust, checkout, url } : null; } /** * The settings' values a build request carries; null when malformed. * @param {unknown} value * @returns {Record | null} */ function readSettings(value) { if (!isObject(value) || !isObject(value.env)) return null; const entries = Object.entries(value.env); /** @type {Record} */ const settings = {}; if (entries.length > MAX_SETTINGS) return null; for (const [key, setting] of entries) { if ( !SETTING.test(key) || typeof setting !== 'string' || setting.includes('\0') || Buffer.byteLength(setting) > MAX_SETTING_BYTES ) return null; settings[key] = setting; } return settings; } /** * The folders a build machine may keep exact2 for `pins` in, under Exact's own `~/.exact/exact2`: one named by the * commit, then one named like the client's checkout folder. * @param {ExactPins} pins * @param {string} home */ const checkoutCandidates = (pins, home) => [...new Set([pins.exact2, pins.checkout])].map((name) => join(home, '.exact', 'exact2', name)); /** * The first candidate folder at the pinned commit. * @param {ProjectPluginHost} host * @param {ExactPins} pins * @param {string} home */ async function pinnedCheckout(host, pins, home) { for (const dir of checkoutCandidates(pins, home)) if ( existsSync(join(dir, 'scripts', 'app-cli.mjs')) && (await git(host, dir, ['rev-parse', 'HEAD'])) === pins.exact2 ) return dir; return undefined; } /** * What keeps a build machine from building with exact2 for `pins`: no candidate folder holds the commit cleanly and set * up. The remedy fetches the commit from the client's remote, which may be a fork of exact2. * @param {ProjectPluginHost} host * @param {ExactPins} pins * @param {string} home * @param {string} cargoHome * @returns {Promise} */ async function exact2Problem(host, pins, home, cargoHome) { const short = pins.exact2.slice(0, 10); const source = pins.url ?? 'https://github.com/expo/exact'; /** @param {string} shown */ const setup = (shown) => `cd ${shown} && ~/.bun-${pins.bun}/bin/bun scripts/exact.mjs setup`; const ready = await pinnedCheckout(host, pins, home); if (!ready) { const dir = join(home, '.exact', 'exact2', pins.exact2); const shown = shownPath(dir, home); const checkout = [ `git -C ${shown} fetch ${source} ${pins.exact2}`, `git -C ${shown} checkout --detach ${pins.exact2}`, ]; const unpushed = pins.url ? '' : `; the client's exact2 checkout has ${short} on no remote branch whose URL Stim passes on, so push it where this machine can fetch it`; const named = join(home, '.exact', 'exact2', pins.checkout); const elsewhere = named !== dir && existsSync(join(named, 'scripts', 'app-cli.mjs')) ? ` (${shownPath(named, home)} is at another commit)` : ''; return existsSync(join(dir, 'scripts', 'app-cli.mjs')) ? { reason: `${shown} is not at commit ${short}${unpushed}`, commands: [...checkout, setup(shown)] } : { reason: `no exact2 ${short} at ${shown}${named === dir ? '' : ` or ${shownPath(named, home)}`}${elsewhere}${unpushed}`, commands: [`git clone ${source} ${shown}`, ...checkout, setup(shown)], }; } const shown = shownPath(ready, home); if ((await git(host, ready, ['status', '--porcelain', '--untracked-files=no'])) !== '') return { reason: `${shown} has local changes; Stim builds only a clean checkout of the pin`, commands: [`git -C ${shown} status`], }; if (!setupRan(ready, cargoHome)) return { reason: `Exact's setup has not run for exact2 ${short} at ${shown}`, commands: [setup(shown)] }; return null; } /** * How an Exact app's iOS build goes to a build machine. * @param {ProjectPluginHost} host * @returns {ProjectPluginIosOffload} */ export function exactOffload(host) { return { async plan(root, env) { const manifest = readManifest(root); if (!manifest) return { unsupported: 'app.json is not a JSON object' }; const launcher = readLauncher(root); if (launcher === null) return { unsupported: 'exact.mjs is not readable' }; const { bun, exact2Default } = launcherPins(launcher); const exact2Path = env.EXACT2 ?? exact2Default; if (!bun || exact2Path === null) return { unsupported: 'exact.mjs does not name its Bun version and exact2 checkout the way Stim reads them' }; let exact2Dir; try { exact2Dir = realpathSync(resolve(root, exact2Path)); } catch { return { unsupported: `there is no exact2 checkout at ${resolve(root, exact2Path)} (set EXACT2)` }; } let rust = null; try { rust = rustChannel(readFileSync(join(exact2Dir, 'rust-toolchain.toml'), 'utf8')); } catch {} if (!rust) return { unsupported: `${exact2Dir}/rust-toolchain.toml names no Rust channel` }; const exact2 = await git(host, exact2Dir, ['rev-parse', 'HEAD']); if (!exact2 || !SHA.test(exact2)) return { unsupported: `${exact2Dir} is not a git checkout of exact2` }; const changes = await git(host, exact2Dir, ['status', '--porcelain', '--untracked-files=no']); if (changes === null || changes !== '') return { unsupported: `the exact2 checkout at ${exact2Dir} has local changes a build machine would not have` }; const checkout = basename(exact2Dir); if (!APP_NAME.test(checkout)) return { unsupported: `the exact2 checkout folder name ${JSON.stringify(checkout)} is not a plain ASCII file name`, }; const canonicalRoot = realpathSync(root); let name = basename(canonicalRoot); if (!APP_NAME.test(name)) { if (!(await git(host, canonicalRoot, ['rev-parse', '--show-prefix']))) return { unsupported: `the app directory name ${JSON.stringify(name)} is not a plain ASCII file name` }; // A build machine reads this required field only when the app is at the Git root. name = 'app'; } const link = await exact2Link(host, canonicalRoot, exact2Dir); if (typeof link === 'object' && link !== null) return link; /** @type {string[]} */ const files = []; for (const file of ['.env.local', '.env']) { try { if (existsSync(join(root, file))) files.push(readFileSync(join(root, file), 'utf8')); } catch { return { unsupported: `${file} is not readable` }; } } return { pins: { exact2, bun, rust, checkout, url: await remoteUrl(host, exact2Dir) }, payload: { env: settingValues(declaredSettings(manifest), env, files) }, checkout: { name, sibling: link }, }; }, check(pins, payload) { if (payload === null) return readPins(pins) ? null : 'An Exact offer needs the exact2 commit and the Bun and Rust versions.'; return readPins(pins) && readSettings(payload) ? null : 'An Exact build needs an iOS request with its app name, pins and settings.'; }, async tools(value, env) { const pins = readPins(value); if (!pins) return []; const home = homeOf(env); const bun = join(home, `.bun-${pins.bun}`, 'bin', 'bun'); const cargoHome = env.CARGO_HOME ?? join(home, '.cargo'); const rustup = join(cargoHome, 'bin', 'rustup'); const [bunVersion, rusts, exact2] = await Promise.all([ existsSync(bun) ? run(host, bun, ['--version'], TOOL_TIMEOUT_MS) : Promise.resolve(null), rustProblems(host, pins.rust, existsSync(rustup) ? rustup : null, TOOL_TIMEOUT_MS), exact2Problem(host, pins, home, cargoHome), ]); /** @type {ToolProblem[]} */ const problems = []; if (bunVersion !== pins.bun) problems.push({ reason: `no Bun ${pins.bun} at ~/.bun-${pins.bun}${bunVersion ? ` (it runs ${bunVersion})` : ''}`, commands: [bunInstall(pins.bun)], }); problems.push(...rusts); if (exact2) problems.push(exact2); return problems; }, async source(value) { const pins = readPins(value); if (!pins) throw new Error('An Exact build needs the exact2 commit.'); const home = homeOf(process.env); return { dir: (await pinnedCheckout(host, pins, home)) ?? join(home, '.exact', 'exact2', pins.exact2), commit: pins.exact2, }; }, project(root, payload) { /** @type {unknown} */ let manifest; try { manifest = JSON.parse(readFileSync(join(root, 'app.json'), 'utf8')); } catch { return { code: 'bad-project', message: 'The Exact app has no readable app.json.' }; } if (!isObject(manifest)) return { code: 'bad-project', message: 'app.json is not a JSON object.' }; const declared = declaredSettings(manifest); const undeclared = Object.keys(readSettings(payload) ?? {}).filter((name) => !declared.includes(name)); return undeclared.length ? { code: 'bad-request', message: `app.json does not declare ${undeclared.join(', ')}.` } : null; }, env({ root, payload, env, source, sibling }) { const declared = declaredSettings(readManifest(root) ?? {}); /** @type {NodeJS.ProcessEnv} */ const built = {}; for (const [key, value] of Object.entries(env)) if ( !declared.includes(key) && key !== 'BUN' && key !== 'CARGO_TARGET_DIR' && key !== 'EXACT2' && !key.startsWith('EXACT_') ) built[key] = value; Object.assign(built, readSettings(payload) ?? {}); if (source) built.EXACT2 = source; if (sibling) built.EXACT2 = sibling; delete built.EXACT_SIM; return built; }, }; }