import { execFile } from "node:child_process"; import { addAbortListener } from "node:events"; interface ProbeCommandOptions { timeout: number; maxBuffer: number; env?: NodeJS.ProcessEnv; killSignal?: "SIGKILL"; } export function execMuxProbeAsync( command: string, args: string[], options: ProbeCommandOptions, signal?: AbortSignal, ): Promise { return new Promise((resolve, reject) => { signal?.throwIfAborted(); let subscription: ReturnType | undefined; let finished = false; const child = execFile( command, args, { ...options, encoding: "utf8", shell: false, ...(signal ? { killSignal: "SIGKILL" } : {}), }, (error, output) => { finished = true; subscription?.[Symbol.dispose](); if (error) reject(error); else resolve(output); }, ); if (signal && !finished) { // execFile uses killSignal for its timer, not for its spawn's abort. subscription = addAbortListener(signal, () => { subscription?.[Symbol.dispose](); try { child.kill("SIGKILL"); } catch { // The child may have exited just before retirement. } child.stdin?.destroy(); child.stdout?.destroy(); child.stderr?.destroy(); reject(signal.reason); }); } child?.stdin?.end(); }); }