import { spawn } from "node:child_process";
//#region src/infra/run-command.ts
const MAX_CAPTURE_BYTES = 512 * 1024;
function appendCaptured(current, chunk) {
	const next = current + chunk.toString();
	if (next.length <= MAX_CAPTURE_BYTES) return next;
	return next.slice(-MAX_CAPTURE_BYTES);
}
function createDefaultCommandRunner() {
	return (argv, options) => runCommandWithTimeout(argv, options);
}
function runCommandWithTimeout(argv, options) {
	const [command, ...args] = argv;
	if (!command) return Promise.resolve({
		code: 1,
		stdout: "",
		stderr: "empty argv"
	});
	return new Promise((resolve) => {
		const child = spawn(command, args, {
			cwd: options.cwd,
			env: options.env ?? process.env,
			stdio: [
				"ignore",
				"pipe",
				"pipe"
			],
			...process.platform === "win32" ? { shell: process.env.ComSpec && process.env.ComSpec.trim() || "cmd.exe" } : {}
		});
		let stdout = "";
		let stderr = "";
		let settled = false;
		const finish = (result) => {
			if (settled) return;
			settled = true;
			clearTimeout(timeoutId);
			resolve(result);
		};
		const timeoutId = setTimeout(() => {
			child.kill("SIGTERM");
		}, options.timeoutMs);
		child.stdout?.on("data", (chunk) => {
			stdout = appendCaptured(stdout, chunk);
		});
		child.stderr?.on("data", (chunk) => {
			stderr = appendCaptured(stderr, chunk);
		});
		child.on("error", (err) => {
			finish({
				code: null,
				stdout,
				stderr: stderr || err.message
			});
		});
		child.on("close", (code) => {
			finish({
				code,
				stdout,
				stderr
			});
		});
	});
}
//#endregion
export { createDefaultCommandRunner, runCommandWithTimeout };

//# sourceMappingURL=run-command.js.map