const { spawn } = require("node:child_process"); const { logger } = require("../monitoring/logger"); function run(command, args = [], options = {}) { return new Promise((resolve, reject) => { const child = spawn(command, args, { windowsHide: true, shell: false, ...options }); let stdout = ""; let stderr = ""; const timeoutMs = options.timeoutMs || 0; const timer = timeoutMs > 0 ? setTimeout(() => { child.kill("SIGTERM"); reject(new Error(`Command timed out after ${timeoutMs}ms: ${command}`)); }, timeoutMs) : null; child.stdout?.on("data", (chunk) => { stdout += chunk.toString(); options.onStdout?.(chunk.toString()); }); child.stderr?.on("data", (chunk) => { stderr += chunk.toString(); options.onStderr?.(chunk.toString()); }); child.on("error", reject); child.on("close", (code) => { if (timer) clearTimeout(timer); if (code === 0) return resolve({ stdout, stderr, code }); const error = new Error(`Command failed (${code}): ${command} ${args.join(" ")}`); error.stdout = stdout; error.stderr = stderr; error.code = code; logger.warn({ command, args, code, stderr: stderr.slice(-1000) }, "Command failed"); reject(error); }); }); } module.exports = { run };