import { spawn } from "node:child_process";
export async function runHook(hook, env, cwd) {
    return await new Promise((resolve, reject) => {
        const child = spawn("/bin/bash", ["-lc", hook.command], {
            cwd,
            env: { ...process.env, ...env },
        });
        let stdout = "";
        let stderr = "";
        child.stdout.on("data", (b) => (stdout += b.toString("utf8")));
        child.stderr.on("data", (b) => (stderr += b.toString("utf8")));
        const timer = setTimeout(() => child.kill("SIGTERM"), hook.timeout_ms ?? 10_000);
        child.on("error", (err) => {
            clearTimeout(timer);
            reject(err);
        });
        child.on("close", (code) => {
            clearTimeout(timer);
            resolve({ exitCode: code ?? 0, stdout, stderr });
        });
    });
}
export async function fireHooks(event, hooks, env, cwd) {
    const matched = hooks.filter((h) => {
        if (h.event !== event)
            return false;
        if (!h.matcher)
            return true;
        const target = env.TOOL_NAME ?? "";
        try {
            return new RegExp(h.matcher).test(target);
        }
        catch {
            return target === h.matcher;
        }
    });
    const blocked = [];
    let rewrite;
    for (const hook of matched) {
        try {
            const output = await runHook(hook, env, cwd);
            if (output.exitCode === 2 && (event === "PreToolUse" || event === "UserPromptSubmit")) {
                blocked.push(output.stderr.trim() || `hook blocked (${hook.command})`);
            }
            else if (output.exitCode === 2 && event === "PostToolUse") {
                rewrite = output.stdout;
            }
        }
        catch (err) {
            blocked.push(`hook error: ${err.message}`);
        }
    }
    return { blocked, rewriteResult: rewrite };
}
//# sourceMappingURL=runner.js.map