"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.isListeningLineForPort = isListeningLineForPort;
exports.isPortAvailable = isPortAvailable;
const child_process_1 = require("child_process");
function addressHasPort(address, port) {
    const escapedPort = String(port).replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
    return new RegExp(`[:.]${escapedPort}$`).test(address.trim());
}
function isListeningLineForPort(line, port) {
    const parts = line.trim().split(/\s+/);
    if (parts.length === 0) {
        return false;
    }
    const hasListeningState = parts.some((part) => /^LISTEN(?:ING)?$/i.test(part));
    if (!hasListeningState) {
        return false;
    }
    const upperFirst = parts[0].toUpperCase();
    const localAddress = upperFirst === 'LISTEN'
        ? parts[3]
        : /^TCP\d*$/i.test(parts[0]) || /^UDP\d*$/i.test(parts[0])
            ? parts[3]?.toUpperCase() === 'LISTEN' || parts[3]?.toUpperCase() === 'LISTENING'
                ? parts[1]
                : parts[3]
            : undefined;
    return Boolean(localAddress && addressHasPort(localAddress, port));
}
function netstatOutput() {
    const args = process.platform === 'win32' ? ['-ano'] : ['-an'];
    const result = (0, child_process_1.spawnSync)('netstat', args, { encoding: 'utf8', shell: process.platform === 'win32' });
    if (result.error) {
        throw result.error;
    }
    if (result.status !== 0) {
        throw new Error(result.stderr?.trim() || 'netstat failed');
    }
    return result.stdout ?? '';
}
async function isPortAvailable(port) {
    return !netstatOutput()
        .split(/\r?\n/)
        .some((line) => isListeningLineForPort(line, port));
}
//# sourceMappingURL=port-checker.js.map