import { spawnSync } from 'node:child_process'; import { createConnection } from 'node:net'; import { mkdir, readdir, readFile, rename, rm, stat, writeFile } from 'node:fs/promises'; import { randomUUID } from 'node:crypto'; import path from 'node:path'; export function portOccupied(host, port, timeoutMs = 1000) { return new Promise((resolve, reject) => { const socket = createConnection({ host, port }); const finish = (error, occupied) => { socket.destroy(); error ? reject(error) : resolve(occupied); }; socket.once('connect', () => finish(undefined, true)); socket.once('error', error => ['ECONNREFUSED', 'EHOSTUNREACH', 'ENETUNREACH', 'EAFNOSUPPORT'].includes(error.code) ? finish(undefined, false) : finish(new Error('Cannot establish whether the local web listener is stopped')), ); socket.setTimeout(timeoutMs, () => finish(new Error('Timed out checking the local web listener; build refused'))); }); } export async function assertWebOffline(port, host = '0.0.0.0') { if (!Number.isInteger(port) || port < 1 || port > 65535) throw new Error('Invalid local web port'); if (process.platform === 'darwin') { const registered = spawnSync( '/bin/launchctl', ['print', `gui/${process.getuid()}/cc.d-robotics.wishforge.local-poc`], { encoding: 'utf8', timeout: 3000 }, ); if (registered.error) throw new Error('Cannot determine LaunchAgent state; build refused'); if (registered.status === 0) throw new Error('Stop the local POC LaunchAgent before rebuilding the web application'); } const addresses = [ ...new Set(['127.0.0.1', '::1', ...(!['0.0.0.0', '::', 'localhost'].includes(host) ? [host] : [])]), ]; if ((await Promise.all(addresses.map(address => portOccupied(address, port)))).some(Boolean)) throw new Error(`Port ${port} is still in use; stop the web process before rebuilding`); } /** Earlier builds kept besides the one just replaced, and failed builds kept for inspection. */ const KEEP_EARLIER = 1; const KEEP_FAILED = 1; /** * After a successful build, removes all but the newest archived builds: the one it replaced (the * receipt's rollback target), one earlier build and the newest failed build. Each is a full Next * build of 50 to 200 MB. Best effort: a directory that cannot be removed is left for the next build. */ async function pruneArchive(archive, replaced) { const entries = await readdir(archive, { withFileTypes: true }).catch(() => []); const dated = async prefix => ( await Promise.all( entries .filter(entry => entry.isDirectory() && entry.name.startsWith(prefix)) .map(entry => { const location = path.join(archive, entry.name); return stat(location).then( info => ({ location, time: info.mtimeMs }), () => undefined, ); }), ) ) .filter(Boolean) .sort((a, b) => b.time - a.time); const earlier = (await dated('previous-')).filter(build => build.location !== replaced).slice(KEEP_EARLIER); const failed = (await dated('failed-')).slice(KEEP_FAILED); const pruned = []; for (const { location } of [...earlier, ...failed]) await rm(location, { recursive: true, force: true }).then( () => pruned.push(location), () => undefined, ); return pruned; } export async function buildWithRollback( root, build, { port = 3000, host = '0.0.0.0', offline = assertWebOffline } = {}, ) { await offline(port, host); const state = path.join(root, '.wishforge/local-poc'); await mkdir(state, { recursive: true, mode: 0o700 }); const lock = path.join(state, 'web-build.lock'); try { await mkdir(lock, { mode: 0o700 }); } catch (error) { if (error.code === 'EEXIST') throw new Error('Another protected web build is in progress'); throw error; } const current = path.join(root, 'apps/web/.next'); const archive = path.join(state, 'web-builds'); const id = randomUUID(); const previous = path.join(archive, `previous-${id}`); const failed = path.join(archive, `failed-${id}`); let saved = false, started = false; try { await writeFile( path.join(lock, 'owner.json'), JSON.stringify({ pid: process.pid, startedAt: new Date().toISOString() }), { mode: 0o600 }, ); await offline(port, host); await mkdir(archive, { recursive: true, mode: 0o700 }); if ( await stat(current).then( () => true, error => { if (error.code === 'ENOENT') return false; throw error; }, ) ) { await rename(current, previous); saved = true; } started = true; await build(); const buildId = (await readFile(path.join(current, 'BUILD_ID'), 'utf8')).trim(); if (!buildId || !(await stat(path.join(current, 'server'))).isDirectory()) throw new Error('Next did not produce a complete production web build'); const receipt = { buildId: buildId.slice(0, 200), completedAt: new Date().toISOString(), previousBuild: saved ? previous : null, currentBuild: current, prunedBuilds: await pruneArchive(archive, saved ? previous : undefined), }; await writeFile(path.join(state, 'last-web-build.json'), `${JSON.stringify(receipt, null, 2)}\n`, { mode: 0o600 }); return receipt; } catch (error) { if (started) { if ( await stat(current).then( () => true, () => false, ) ) await rename(current, failed); if (saved) await rename(previous, current); } throw error; } finally { await rm(lock, { recursive: true, force: true }); } }