"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.wireChildProcessSignals = exports.forwardSignals = void 0;
/**
 * Forward SIGINT, SIGTERM, SIGHUP to a child process.
 * Returns a cleanup function to remove the handlers.
 */
function forwardSignals(child) {
    const forwardSigInt = () => {
        if (!child.killed)
            child.kill('SIGINT');
    };
    const forwardSigTerm = () => {
        if (!child.killed)
            child.kill('SIGTERM');
    };
    const forwardSighup = () => {
        if (!child.killed)
            child.kill('SIGHUP');
    };
    process.on('SIGINT', forwardSigInt);
    process.on('SIGTERM', forwardSigTerm);
    process.on('SIGHUP', forwardSighup);
    return () => {
        process.removeListener('SIGINT', forwardSigInt);
        process.removeListener('SIGTERM', forwardSigTerm);
        process.removeListener('SIGHUP', forwardSighup);
    };
}
exports.forwardSignals = forwardSignals;
function defaultExitHandler(code, signal) {
    if (signal)
        process.kill(process.pid, signal);
    else
        process.exit(code || 0);
}
/**
 * Attach shared signal-forwarding lifecycle handlers to a child process.
 * Ensures signal listeners are always cleaned up on child exit/error.
 */
function wireChildProcessSignals(child, onError, onExit = defaultExitHandler) {
    const cleanupSignalHandlers = forwardSignals(child);
    let settled = false;
    const settle = () => {
        if (settled)
            return false;
        settled = true;
        cleanupSignalHandlers();
        return true;
    };
    child.on('exit', (code, signal) => {
        if (!settle())
            return;
        onExit(code, signal);
    });
    child.on('error', async (err) => {
        if (!settle())
            return;
        try {
            await onError(err);
        }
        catch (handlerErr) {
            const message = handlerErr instanceof Error ? handlerErr.message : String(handlerErr);
            console.error(`[X] Failed to handle child process error: ${message}`);
            process.exit(1);
        }
    });
}
exports.wireChildProcessSignals = wireChildProcessSignals;
//# sourceMappingURL=signal-forwarder.js.map