net.ts 3.29 KB
import { execSync } from 'node:child_process';
import os from 'node:os';

/** LAN IPv4 address, or 'localhost' if none found. Shared by the preview / project runners. */
export function getLanIp(): string {
    const nets = os.networkInterfaces();
    for (const name of Object.keys(nets)) {
        for (const ni of nets[name] ?? []) {
            if (ni.family === 'IPv4' && !ni.internal) return ni.address;
        }
    }
    return 'localhost';
}

/** Parse `netstat -ano` into a map of listening TCP ports -> owning PIDs. */
export function listListeningPorts(): Map<number, number[]> {
    const map = new Map<number, number[]>();
    try {
        const out = execSync('netstat -ano', { stdio: ['ignore', 'pipe', 'ignore'] }).toString();
        const re = /^\s*TCP\s+\S+:(\d+)\s+\S+\s+LISTENING\s+(\d+)/i;
        for (const line of out.split('\n')) {
            const m = line.match(re);
            if (m) {
                const port = parseInt(m[1], 10);
                const pid = parseInt(m[2], 10);
                const arr = map.get(port) ?? [];
                arr.push(pid);
                map.set(port, arr);
            }
        }
    } catch {
        /* ignore */
    }
    return map;
}

/** Kill the process tree (if any) listening on `port`. */
export function killProcessOnPort(port: number): void {
    if (!port) return;
    for (const pid of listListeningPorts().get(port) ?? []) {
        try {
            execSync(`taskkill /pid ${pid} /f /t`, { stdio: 'ignore' });
        } catch {
            /* ignore */
        }
    }
}

/** Kill a spawned process tree by PID (used to terminate the package-manager shell). */
export function killProcess(pid: number): void {
    if (!pid) return;
    try {
        execSync(`taskkill /pid ${pid} /f /t`, { stdio: 'ignore' });
    } catch {
        /* ignore */
    }
}

/** Kill every listener on `port` except `excludePid` (free a port before re-binding). */
export function killOtherListenersOnPort(port: number, excludePid: number): void {
    for (const pid of listListeningPorts().get(port) ?? []) {
        if (pid && pid !== excludePid) {
            try {
                execSync(`taskkill /pid ${pid} /f /t`, { stdio: 'ignore' });
                // eslint-disable-next-line no-console
                console.warn(`  ⚠ 已清理端口 ${port} 上的陈旧监听进程 (pid ${pid})`);
            } catch {
                /* ignore */
            }
        }
    }
}

/**
 * Kill leaked dev servers on the Coderio-managed ranges:
 *  - 5180–5195 : preview service (`npm run dev -- --port 5180`)
 *  - 5200–6199 : validation internal dev server (`calculateHashPort`, base 5200)
 * The front-end's 5173 is deliberately NOT covered (would kill the UI).
 */
export function killStalePreviewPorts(): void {
    const re = /:5(?:18[0-9]|19[0-5]|[2-9]\d\d|6[01]\d\d)\s+\S+\s+LISTENING\s+(\d+)/g;
    try {
        const out = execSync('netstat -ano', { stdio: ['ignore', 'pipe', 'ignore'] }).toString();
        const pids = new Set<string>();
        let m: RegExpExecArray | null;
        while ((m = re.exec(out))) pids.add(m[1]);
        for (const pid of pids) {
            try {
                execSync(`taskkill /pid ${pid} /f /t`, { stdio: 'ignore' });
            } catch {
                /* ignore */
            }
        }
    } catch {
        /* ignore */
    }
}