"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.sleepMs = sleepMs;
exports.buildWindowsTaskkillArgs = buildWindowsTaskkillArgs;
exports.bestEffortKillWindowsProcessTree = bestEffortKillWindowsProcessTree;
exports.bestEffortKillPid = bestEffortKillPid;
const node_child_process_1 = require("node:child_process");
const node_util_1 = require("node:util");
const execFileAsync = (0, node_util_1.promisify)(node_child_process_1.execFile);
function sleepMs(milliseconds) {
    return new Promise((resolve) => setTimeout(resolve, milliseconds));
}
function buildWindowsTaskkillArgs(pid, force) {
    assertValidPid(pid);
    return force ? ['/PID', String(pid), '/T', '/F'] : ['/PID', String(pid), '/T'];
}
function assertValidPid(pid) {
    if (!Number.isInteger(pid) || pid <= 0) {
        throw new Error(`Invalid process pid: ${String(pid)}`);
    }
}
async function bestEffortTaskkill(pid, force) {
    try {
        await execFileAsync('taskkill.exe', buildWindowsTaskkillArgs(pid, force), {
            windowsHide: true,
            maxBuffer: 1024 * 1024,
        });
    }
    catch {
        // Best effort only.
    }
}
async function bestEffortKillWindowsProcessTree(pid) {
    assertValidPid(pid);
    await bestEffortTaskkill(pid, false);
    await sleepMs(1_000);
    await bestEffortTaskkill(pid, true);
    bestEffortKillPid(pid);
}
function bestEffortKillPid(pid) {
    assertValidPid(pid);
    try {
        process.kill(pid, 'SIGKILL');
    }
    catch {
        // Best effort only.
    }
}
