import { spawn } from 'node:child_process'; export const DETACHED_PROCESS_GROUP = Symbol('detachedProcessGroup'); export function spawnWithPromise(cmd, args, options = {}) { const child = spawn(cmd, args, { stdio: 'inherit', ...options, }); if (options.detached) { child[DETACHED_PROCESS_GROUP] = true; } const promise = new Promise((resolve, reject) => { child.on('exit', (code, signal) => { if (code === 0) { resolve({ code, signal }); } else { reject( new Error( `${cmd} ${args.join(' ')} exited with ${formatExit({ code, signal })}`, ), ); } }); child.on('error', reject); }); return { child, promise }; } export async function runGuardedCommand( description, serveExitPromise, factory, isShutdownRequested = () => false, ) { const { child, promise } = factory(); const serveWatcher = serveExitPromise.then((info) => { if (isShutdownRequested()) { return info; } if (child.exitCode === null && child.signalCode === null) { sendSignal(child, 'SIGINT'); } throw new Error( `Serve process exited while ${description}: ${formatExit(info)}`, ); }); try { return await Promise.race([promise, serveWatcher]); } finally { serveWatcher.catch(() => {}); } } export async function shutdownServe(proc, exitPromise) { if (proc.exitCode !== null || proc.signalCode !== null) { return exitPromise; } const sequence = [ { signal: 'SIGINT', timeoutMs: 8000 }, { signal: 'SIGTERM', timeoutMs: 5000 }, { signal: 'SIGKILL', timeoutMs: 3000 }, ]; for (const { signal, timeoutMs } of sequence) { if (proc.exitCode !== null || proc.signalCode !== null) { break; } sendSignal(proc, signal); try { await waitWithTimeout(exitPromise, timeoutMs); break; } catch (error) { if (error.name !== 'TimeoutError') { throw error; } } } return exitPromise; } function sendSignal(proc, signal) { if (proc.exitCode !== null || proc.signalCode !== null) { return; } if (proc[DETACHED_PROCESS_GROUP]) { try { process.kill(-proc.pid, signal); return; } catch (error) { if (error.code !== 'ESRCH' && error.code !== 'EPERM') { throw error; } } } try { proc.kill(signal); } catch (error) { if (error.code !== 'ESRCH') { throw error; } } } function waitWithTimeout(promise, timeoutMs) { return new Promise((resolve, reject) => { let settled = false; const timer = setTimeout(() => { if (settled) { return; } settled = true; const timeoutError = new Error(`Timed out after ${timeoutMs}ms`); timeoutError.name = 'TimeoutError'; reject(timeoutError); }, timeoutMs); promise.then( (value) => { if (settled) { return; } settled = true; clearTimeout(timer); resolve(value); }, (error) => { if (settled) { return; } settled = true; clearTimeout(timer); reject(error); }, ); }); } export function isExpectedServeExit(info) { if (!info) { return false; } const { code, signal } = info; if (code === 0) { return true; } if (code === 130 || code === 137 || code === 143) { return true; } if (code == null && ['SIGINT', 'SIGTERM', 'SIGKILL'].includes(signal)) { return true; } return false; } export function formatExit({ code, signal } = {}) { const parts = []; if (code !== null && code !== undefined) { parts.push(`code ${code}`); } if (signal) { parts.push(`signal ${signal}`); } return parts.length > 0 ? parts.join(', ') : 'unknown status'; }