// Execução de subprocessos sem shell: argumentos vão como lista (espaços em // caminhos funcionam e nada do JSON vira comando). Um código de saída diferente // de zero, timeout, cancelamento ou falha ao iniciar NUNCA conta como sucesso. import { spawn, spawnSync, type ChildProcess } from "node:child_process"; export type RunOptions = { cwd?: string; timeoutMs?: number; /** Recebe cada pedaço de stdout/stderr conforme chega (para o render.log). */ onOutput?: (stream: "stdout" | "stderr", chunk: string) => void; /** Herda o terminal (prévia interativa). */ inheritStdio?: boolean; }; export type RunResult = { command: string; args: string[]; exitCode: number | null; signal: NodeJS.Signals | null; stdout: string; stderr: string; timedOut: boolean; cancelled: boolean; spawnError?: string; durationMs: number; }; const MAX_CAPTURE = 8 * 1024 * 1024; const active = new Set(); let cancelRequested = false; export function runProcess(command: string, args: string[], options: RunOptions = {}): Promise { const started = Date.now(); return new Promise((resolve) => { let stdout = ""; let stderr = ""; let timedOut = false; let settled = false; const result = (partial: Partial): RunResult => ({ command, args, exitCode: null, signal: null, stdout, stderr, timedOut, cancelled: cancelRequested, durationMs: Date.now() - started, ...partial, }); if (cancelRequested) { resolve(result({ cancelled: true, spawnError: "cancelado antes de iniciar" })); return; } let child: ChildProcess; try { child = spawn(command, args, { cwd: options.cwd, shell: false, windowsHide: !options.inheritStdio, stdio: options.inheritStdio ? "inherit" : ["ignore", "pipe", "pipe"], }); } catch (error) { resolve(result({ spawnError: (error as Error).message })); return; } active.add(child); const timer = options.timeoutMs ? setTimeout(() => { timedOut = true; killTree(child); }, options.timeoutMs) : undefined; child.stdout?.setEncoding("utf8"); child.stderr?.setEncoding("utf8"); child.stdout?.on("data", (chunk: string) => { if (stdout.length < MAX_CAPTURE) stdout += chunk; options.onOutput?.("stdout", chunk); }); child.stderr?.on("data", (chunk: string) => { if (stderr.length < MAX_CAPTURE) stderr += chunk; options.onOutput?.("stderr", chunk); }); const finish = (partial: Partial) => { if (settled) return; settled = true; if (timer) clearTimeout(timer); active.delete(child); resolve(result(partial)); }; child.on("error", (error) => finish({ spawnError: error.message })); child.on("close", (code, signal) => finish({ exitCode: code, signal })); }); } export function succeeded(r: RunResult): boolean { return r.exitCode === 0 && !r.timedOut && !r.cancelled && r.spawnError === undefined; } /** Mensagem curta e útil para o usuário, com o fim do stderr. */ export function describeFailure(label: string, r: RunResult): string { let reason: string; if (r.cancelled) reason = "cancelado pelo usuário"; else if (r.spawnError) reason = `não iniciou: ${r.spawnError}`; else if (r.timedOut) reason = `excedeu o tempo limite (${Math.round(r.durationMs / 1000)} s)`; else reason = `saiu com código ${r.exitCode}${r.signal ? ` (sinal ${r.signal})` : ""}`; const tail = (r.stderr || r.stdout).trim().split(/\r?\n/).slice(-8).join("\n"); return `${label} ${reason}${tail ? `\n${tail}` : ""}`; } /** Cancelamento (Ctrl+C): encerra todos os subprocessos ativos e impede novos. */ export function cancelActiveProcesses(): void { cancelRequested = true; for (const child of active) killTree(child); } export function resetCancellation(): void { cancelRequested = false; } function killTree(child: ChildProcess): void { if (child.pid === undefined || child.exitCode !== null) return; if (process.platform === "win32") { spawnSync("taskkill", ["/pid", String(child.pid), "/T", "/F"], { windowsHide: true, stdio: "ignore" }); } else { child.kill("SIGTERM"); setTimeout(() => child.exitCode === null && child.kill("SIGKILL"), 3000).unref(); } }