export type CommandOptions = { input?: string; allowFailure?: boolean; env?: Record; cwd?: string; }; export type CommandResult = { out: string; err: string; code: number }; export type CommandRecord = { program: string; stdout: string; stderr: string; code: number; }; export type CommandPorts = { execute: (args: string[], options: CommandOptions) => Promise; unique: (record: CommandRecord) => Promise; last: (record: CommandRecord) => Promise; }; export function createCommandRunner(ports: CommandPorts) { if ( !ports || typeof ports.execute !== "function" || typeof ports.unique !== "function" || typeof ports.last !== "function" ) throw new Error("INVALID_COMMAND_RUNNER_PORTS"); const { execute, unique, last } = ports; return async (args: string[], options: CommandOptions = {}) => { const result = await execute(args, options); if (result.code !== 0 && !options.allowFailure) { const program = args[0] ?? "unknown", record = { program, code: result.code, stdout: result.out, stderr: result.err, }; const primary = new Error( "COMMAND_FAILED_" + program.replace(/[^a-zA-Z0-9]/g, "_") + "_" + result.code, ); await Promise.allSettled([ Promise.resolve().then(() => unique(record)), Promise.resolve().then(() => last(record)), ]); throw primary; } return result; }; }