/** @import { ProjectPluginHost } from 'stim/plugin' */ import { accessSync, constants, existsSync, readFileSync } from 'node:fs'; import { homedir } from 'node:os'; import { basename, delimiter, join, resolve } from 'node:path'; /** The Rust target an Exact iOS simulator build compiles for; Exact's own setup does not install it. */ export const EXACT_SIM_TARGET = 'aarch64-apple-ios-sim'; export const SHA = /^[0-9a-f]{40}$/; const RUST_CHANNEL = /^[0-9A-Za-z][0-9A-Za-z.-]{0,39}$/; const GIT_TIMEOUT_MS = 10_000; /** @typedef {{ reason: string, commands: string[] }} ToolProblem */ /** * @param {unknown} value * @returns {value is Record} */ export const isObject = (value) => typeof value === 'object' && value !== null && !Array.isArray(value); /** * The app's `app.json` as an object, or null. * @param {string} root * @returns {Record | null} */ export function readManifest(root) { try { /** @type {unknown} */ const manifest = JSON.parse(readFileSync(join(root, 'app.json'), 'utf8')); return isObject(manifest) ? manifest : null; } catch { return null; } } /** * @param {string} root * @returns {string | null} */ export function readLauncher(root) { try { return readFileSync(join(root, 'exact.mjs'), 'utf8'); } catch { return null; } } /** * The Bun version and default exact2 path the app's `exact.mjs` launcher pins. * @param {string} launcher */ export function launcherPins(launcher) { return { bun: /ensureBun\(\s*["'](\d+\.\d+\.\d+)["']\s*\)/.exec(launcher)?.[1] ?? null, exact2Default: /process\.env\.EXACT2\s*\?\?\s*(["'])([^"'\n]+)\1/.exec(launcher)?.[2] ?? null, }; } /** * @param {string} toolchain * @returns {string | null} */ export function rustChannel(toolchain) { const channel = /^\s*channel\s*=\s*"([^"]+)"/m.exec(toolchain)?.[1]; return channel && RUST_CHANNEL.test(channel) ? channel : null; } /** @param {NodeJS.ProcessEnv} env */ export const homeOf = (env) => env.HOME ?? homedir(); /** * @param {string} path * @param {string} home */ export const shownPath = (path, home) => path === home || path.startsWith(`${home}/`) ? `~${path.slice(home.length)}` : path; /** @param {string} pin */ export const bunInstall = (pin) => `curl -fsSL https://bun.sh/install | BUN_INSTALL="$HOME/.bun-${pin}" bash -s "bun-v${pin}"`; /** * @param {string} checkout * @param {string} cargoHome */ export const setupRan = (checkout, cargoHome) => existsSync(join(checkout, 'node_modules')) && existsSync(join(cargoHome, 'hermes-lean-sys')); /** * Runs `file` through the host and returns its trimmed output when it exits 0, else null. A cancelled operation throws. * @param {ProjectPluginHost} host * @param {string} file * @param {string[]} args * @param {number} timeoutMs * @param {Record} [env] * @returns {Promise} */ export async function run(host, file, args, timeoutMs, env) { try { const { code, stdout } = await host.exec(file, args, { timeoutMs, ...(env ? { env } : {}) }); return code === 0 ? stdout.trim() : null; } catch (error) { host.signal.throwIfAborted(); if (error instanceof Error && 'reportCleanup' in error) throw error; return null; } } /** * Read-only git in `dir`, without optional locks, hooks or fsmonitor. * @param {ProjectPluginHost} host * @param {string} dir * @param {string[]} args */ export const git = (host, dir, args) => run( host, 'git', ['--no-optional-locks', '-c', 'core.hooksPath=/dev/null', '-c', 'core.fsmonitor=false', '-C', dir, ...args], GIT_TIMEOUT_MS, ); /** * The absolute path of the executable `name` on `env.PATH`, or null. * @param {string} name * @param {NodeJS.ProcessEnv} env * @returns {string | null} */ function onPath(name, env) { for (const dir of (env.PATH ?? '').split(delimiter).filter(Boolean)) { const path = resolve(dir, name); try { accessSync(path, constants.X_OK); return path; } catch {} } return null; } /** * @param {ProjectPluginHost} host * @param {string | null} rust * @param {string | null} rustup * @param {number} timeoutMs * @returns {Promise} */ export async function rustProblems(host, rust, rustup, timeoutMs) { const installToolchain = `rustup toolchain install ${rust ?? 'stable'} --profile minimal --target ${EXACT_SIM_TARGET}`; if (!rustup) return [ { reason: 'no rustup', commands: [ "curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y --no-modify-path --default-toolchain none", `~/.cargo/bin/${installToolchain}`, ], }, ]; if (rust === null) return []; const targets = await run(host, rustup, ['target', 'list', '--installed', '--toolchain', rust], timeoutMs, { RUSTUP_AUTO_INSTALL: '0', }); if (targets === null) return [{ reason: `no Rust ${rust}`, commands: [installToolchain] }]; if (!targets.split('\n').includes(EXACT_SIM_TARGET)) return [ { reason: `no Rust ${rust} target ${EXACT_SIM_TARGET}`, commands: [`rustup target add --toolchain ${rust} ${EXACT_SIM_TARGET}`], }, ]; return []; } /** @param {string} launcher */ function launcherFallbackBun(launcher) { const fallback = /else exec ('(?:[^']|'\\'')*'|\S+) "\$0"/.exec(launcher)?.[1] ?? 'bun'; return fallback.startsWith("'") ? fallback.slice(1, -1).replaceAll("'\\''", "'") : fallback; } /** * @param {string} have * @param {string} want */ function olderVersion(have, want) { const a = have.split('.').map(Number); const b = want.split('.').map(Number); if (a.length < 3 || a.some((n) => !Number.isFinite(n))) return true; const different = b.findIndex((n, i) => n !== a[i]); return different >= 0 && (a[different] ?? 0) < (b[different] ?? 0); } /** * What this Mac lacks for `./exact.mjs ios` in the Exact app at `root`, found the way its launcher looks: Bun from * `$BUN`, then `~/.bun-`, then the launcher's fallback, at the pinned version or newer; exact2 at `EXACT2` or * the launcher's default, set up; and rustup with `RUSTUP_TOOLCHAIN` or the app's Rust toolchain and the simulator * target. Runs only `bun --version` and `rustup`, at the same time, each within `timeoutMs`. * @param {ProjectPluginHost} host * @param {string} root * @param {NodeJS.ProcessEnv} env * @param {number} timeoutMs * @returns {Promise} */ export async function localToolProblems(host, root, env, timeoutMs) { const launcher = readLauncher(root); if (launcher === null) return []; const { bun: pin, exact2Default } = launcherPins(launcher); const exact2Path = env.EXACT2 ?? exact2Default; if (!pin || exact2Path === null) return []; const home = homeOf(env); const versioned = join(home, `.bun-${pin}`, 'bin', 'bun'); const fallback = launcherFallbackBun(launcher); const bun = env.BUN || (existsSync(versioned) ? versioned : fallback.includes('/') ? fallback : onPath(fallback, env)); const exact2Dir = resolve(root, exact2Path); const cargoHome = env.CARGO_HOME ?? join(home, '.cargo'); let rust = env.RUSTUP_TOOLCHAIN ?? null; for (const dir of rust ? [] : [root, exact2Dir]) { try { rust = rustChannel(readFileSync(join(dir, 'rust-toolchain.toml'), 'utf8')); } catch {} if (rust) break; } const rustup = join(cargoHome, 'bin', 'rustup'); const [version, rusts] = await Promise.all([ bun ? run(host, bun, ['--version'], timeoutMs) : Promise.resolve(null), rustProblems(host, rust, existsSync(rustup) ? rustup : onPath('rustup', env), timeoutMs), ]); /** @type {ToolProblem[]} */ const problems = []; let bunCommand = `~/.bun-${pin}/bin/bun`; if (!bun || version === null) problems.push({ reason: `no Bun ${pin} (exact.mjs runs ${env.BUN ? `$BUN (${env.BUN})` : `~/.bun-${pin}/bin/bun, else ${fallback.includes('/') ? shownPath(fallback, home) : `${fallback} on PATH`}`})`, commands: [bunInstall(pin)], }); else if (olderVersion(version, pin)) problems.push({ reason: `Bun ${version} at ${shownPath(bun, home)} is older than the ${pin} exact.mjs pins`, commands: [bunInstall(pin), ...(env.BUN ? ['unset BUN'] : [])], }); else bunCommand = shownPath(bun, home); const shown = shownPath(exact2Dir, home); const setup = `cd ${shown} && ${bunCommand} scripts/exact.mjs setup`; if (!existsSync(join(exact2Dir, 'scripts', 'app-cli.mjs'))) { const pinned = basename(exact2Dir); problems.push({ reason: `no exact2 checkout at ${shown} (exact.mjs reads EXACT2, else ${exact2Default ?? 'nothing'}); set EXACT2 to an exact2 checkout, or clone one there`, commands: [ `git clone https://github.com/expo/exact ${shown}`, ...(SHA.test(pinned) ? [`git -C ${shown} checkout ${pinned}`] : []), setup, ], }); } else if (!setupRan(exact2Dir, cargoHome)) problems.push({ reason: `Exact's setup has not run for the exact2 checkout at ${shown}`, commands: [setup] }); problems.push(...rusts); return problems; }