/** @import { ProjectPluginHost, ProjectPluginOutputClean, ProjectPluginOutputUse } from 'stim/plugin' */ import { lstatSync, readFileSync } from 'node:fs'; import { dirname, join } from 'node:path'; import { homeOf, isObject } from './toolchain.mjs'; const LEDGER = '.exact-sweep.json'; const RECENT = "Exact's ledger stamps a unit in that time"; const BUN_VERSION = /^\d{1,4}\.\d{1,4}\.\d{1,4}$/; const HELP_TIMEOUT_MS = 60_000; // Exact's clean waits up to 60 seconds for its sweep's lock before it reports busy. Stim gives one cleanOutput call // 240 seconds, the help run included. const CLEAN_TIMEOUT_MS = 170_000; /** * The newest stamp per profile in Exact's `.exact-sweep.json` ledger (`{ units: { "#": ms } }`), which * Exact refreshes from the fingerprint files a build read. Null when the text is not that shape. * @param {string} text * @returns {Record | null} */ function newestPerProfile(text) { /** @type {unknown} */ let parsed; try { parsed = JSON.parse(text); } catch { return null; } const units = isObject(parsed) ? parsed.units : undefined; if (!isObject(units)) return null; /** @type {Record} */ const newest = {}; for (const [key, at] of Object.entries(units)) { const profile = key.split('#')[0]; if (!profile || typeof at !== 'number' || !Number.isFinite(at)) return null; newest[profile] = Math.max(newest[profile] ?? 0, at); } return newest; } /** * When each Cargo profile of the `target/` `dir` was last used, by Exact's ledger. * @param {string} dir * @returns {ProjectPluginOutputUse} */ export function exactOutputUse(dir) { const ledgerPath = join(dir, LEDGER); if (!lstatSync(ledgerPath, { throwIfNoEntry: false })) return { lastUse: {}, recent: RECENT }; let text; try { text = readFileSync(ledgerPath, 'utf8'); } catch { return { unknown: `Exact's ${ledgerPath} cannot be read` }; } const newest = newestPerProfile(text); return newest ? { lastUse: newest, recent: RECENT } : { unknown: `Exact's ${ledgerPath} is not a unit ledger` }; } /** * @param {unknown} value * @returns {value is string[]} */ const isStrings = (value) => Array.isArray(value) && value.every((entry) => typeof entry === 'string'); /** * The report in `stdout` when it is exactly one version 1 object of Exact's `sweep.mjs clean --json` * (appandflow/exact#41), or null. * @param {string} stdout * @returns {ProjectPluginOutputClean | null} */ function parseReport(stdout) { /** @type {unknown} */ let parsed; try { parsed = JSON.parse(stdout.trim()); } catch { return null; } if (!isObject(parsed) || parsed.version !== 1) return null; const { status, remove, kept, held, error } = parsed; if ( (status !== 'ok' && status !== 'busy' && status !== 'refused' && status !== 'failed') || !isStrings(remove) || !isStrings(held) || !Array.isArray(kept) ) return null; /** @type {{ path: string, why: string }[]} */ const keptEntries = []; for (const entry of kept) { if (!isObject(entry) || typeof entry.path !== 'string' || typeof entry.why !== 'string') return null; keptEntries.push({ path: entry.path, why: entry.why }); } return { status, remove, kept: keptEntries, held, ...(typeof error === 'string' ? { error } : {}) }; } /** @param {unknown} error */ const firstLine = (error) => (error instanceof Error ? error.message : String(error)).split('\n')[0] ?? ''; /** * Runs Exact's own cleaner on the idle Exact app that holds the `target/` `dir`: ` /scripts/sweep.mjs * clean [--dry-run] --json`. The checkout is the one the app's `exact.mjs` resolves, which its `help` names on its * last line (`Exact checkout: at `), run with the Bun its launcher pins; the cleaner runs with the Bun the * checkout's `package.json` pins, both from `~/.bun-`. A dry run without one version 1 report, such as an * older checkout that prints no JSON, is `unsupported`, which keeps the target. A clean that ends without one is * `unknown`: it may have removed part. * @param {ProjectPluginHost} host * @param {string} dir * @param {{ dryRun: boolean }} options * @returns {Promise} */ export async function exactCleanOutput(host, dir, { dryRun }) { const app = dirname(dir); const home = homeOf(process.env); /** @param {string} version */ const bunAt = (version) => join(home, `.bun-${version}`, 'bin', 'bun'); let launcher; try { launcher = readFileSync(join(app, 'exact.mjs'), 'utf8'); } catch { return { unsupported: `${app}/exact.mjs cannot be read` }; } const launcherBun = /ensureBun\(\s*["'](\d+\.\d+\.\d+)["']\s*\)/.exec(launcher)?.[1]; if (!launcherBun) return { unsupported: `${app}/exact.mjs names no Bun version the way Stim reads it` }; let help; try { const ran = await host.exec(bunAt(launcherBun), [join(app, 'exact.mjs'), 'help'], { timeoutMs: HELP_TIMEOUT_MS }); if (ran.code !== 0) return { unsupported: `bun exact.mjs help failed: it exited with ${ran.code ?? 'a signal'}` }; help = ran.stdout; } catch (error) { host.signal.throwIfAborted(); return { unsupported: `bun exact.mjs help failed: ${firstLine(error)}` }; } const checkout = /^Exact checkout: (\/.*) at [0-9a-f]+$/m.exec(help.trim().split('\n').at(-1) ?? '')?.[1]; if (!checkout) return { unsupported: 'bun exact.mjs help does not name its Exact checkout' }; /** @type {unknown} */ let pinned; try { pinned = JSON.parse(readFileSync(join(checkout, 'package.json'), 'utf8')); } catch { return { unsupported: `${checkout}/package.json cannot be read` }; } const manager = isObject(pinned) ? pinned.packageManager : null; const version = typeof manager === 'string' && manager.startsWith('bun@') ? manager.slice('bun@'.length) : ''; if (!BUN_VERSION.test(version)) return { unsupported: `${checkout}/package.json pins no Bun version` }; let stdout = ''; let why = 'it printed no version 1 report'; try { const ran = await host.exec( bunAt(version), [join(checkout, 'scripts', 'sweep.mjs'), 'clean', app, ...(dryRun ? ['--dry-run'] : []), '--json'], { timeoutMs: CLEAN_TIMEOUT_MS }, ); stdout = ran.stdout; if (ran.code !== 0) why = `it exited with ${ran.code ?? 'a signal'}`; } catch (error) { host.signal.throwIfAborted(); why = firstLine(error); } const report = parseReport(stdout); if (report) return report; return dryRun ? { unsupported: `the Exact checkout at ${checkout} has no clean that reports version 1 JSON (appandflow/exact#41): ${why}`, } : { unknown: why }; }