port-reclaim 0.2.1 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -36,15 +36,15 @@ Requires Node.js 18 or newer. Supports macOS, Linux, Windows, WSL, PowerShell, a
36
36
  port-reclaim <PORT> [PORT ...]
37
37
  ```
38
38
 
39
- If the port is free, the command exits successfully. If the process working directory matches the current project, the process is terminated automatically. Processes from another directory, system services, and processes whose working directory cannot be read require explicit confirmation. Confirmation prompts show the process name, working directory, and uptime.
39
+ If the port is free, the command verifies it by briefly binding the port, then exits successfully. If the port is in use but no owning process is visible to the current user, the command reports that instead of claiming success. If the process working directory matches the current project, the process is terminated automatically. Processes from another directory, system services, and processes whose working directory cannot be read require explicit confirmation. Confirmation prompts show the process name, working directory, and uptime.
40
40
 
41
41
  The command uses a graceful termination signal first on Unix-like systems and falls back to a forceful signal if the process remains alive. Windows uses `taskkill /F`.
42
42
 
43
43
  If confirmation is required in a non-interactive environment, the command declines safely and exits with status `1` (rerun with `--yes` to override).
44
44
 
45
- Ports held by Docker processes (for example `docker-proxy` or Docker Desktop) are never killed. The tool explains that the port looks like Docker and suggests stopping the container instead.
45
+ Ports held by Docker processes (for example `docker-proxy` or Docker Desktop) are never killed. The tool explains that the port looks like Docker and suggests stopping the container instead. The same refusal applies to operating-system PIDs (0–4, such as `System`/HTTP.sys on Windows or `systemd` on Linux), which are never signalled.
46
46
 
47
- Both TCP and UDP listeners are discovered.
47
+ Both TCP and UDP listeners are discovered. Discovery costs one `netstat`/`lsof` call per port, with process names and uptimes fetched in a single batched query. Measured on Windows 11: ~0.1s for a free port, ~0.4s to identify a busy one, ~0.6s for a full reclaim.
48
48
 
49
49
  ### Options
50
50
 
@@ -105,8 +105,8 @@ The same command can be used from Python, Ruby, Go, Make, or shell scripts.
105
105
 
106
106
  | Code | Meaning |
107
107
  | --- | --- |
108
- | `0` | The port was free, listed with `--list`, or successfully released. |
109
- | `1` | The port is still in use, the user declined, or an operation failed. |
108
+ | `0` | The port was free (verified by binding), listed with `--list`, or successfully released. |
109
+ | `1` | The port is still in use: the user declined, the owner is not visible to the current user, a protected process refused the kill, or an operation failed. |
110
110
  | `2` | Invalid command-line input. |
111
111
 
112
112
  ## Programmatic Use
@@ -119,16 +119,21 @@ import { createProcessRunner } from "port-reclaim";
119
119
  const runner = createProcessRunner();
120
120
  const found = await runner.discover(3000);
121
121
  for (const process of found) {
122
- console.log(process.name, process.cwd, process.ageMs);
122
+ console.log(process.name, process.cwd, process.ageMs, process.refusal);
123
123
  }
124
- if (found.length > 0) {
124
+ if (found.length > 0 && !found[0].refusal) {
125
125
  await runner.terminate(found[0].pid);
126
126
  }
127
+ if (found.length === 0 && (await runner.probe(3000)) === "occupied") {
128
+ console.log("in use by a process this user cannot see");
129
+ }
127
130
  ```
128
131
 
132
+ `discover()` reports what is on a port, `terminate()` ends one PID, and `probe()` answers whether the port is bindable at all — `"free"`, `"occupied"`, or `"unknown"` when the OS refuses to say. A `refusal` reason on a discovered process means `port-reclaim` will not kill it, whatever the caller asks; `terminate()` is still available if you decide otherwise.
133
+
129
134
  ## Security Notes
130
135
 
131
- `port-reclaim` only acts on processes listening on the port you provide. It does not scan remote hosts, and it refuses to kill Docker processes — stop those containers yourself. Ports protected by `.reclaimignore` or the `ignore` config are always skipped. Review the process name and working directory before confirming a process from another project. UDP matches are heuristic: a UDP socket on a port can belong to a client as well as a server.
136
+ `port-reclaim` only acts on processes listening on the port you provide. It does not scan remote hosts, and it refuses to kill Docker processes and operating-system PIDs (0–4) — stop those containers and services yourself. Ports protected by `.reclaimignore` or the `ignore` config are always skipped. Review the process name and working directory before confirming a process from another project. UDP matches are heuristic: a UDP socket on a port can belong to a client as well as a server. To confirm a port is free, the tool binds it momentarily and releases it, so a connection arriving in that instant can be reported as in use.
132
137
 
133
138
  ## Development
134
139
 
package/dist/src/cli.js CHANGED
@@ -75,8 +75,14 @@ async function version() {
75
75
  async function reclaimPort(port, runner, options) {
76
76
  const portProcesses = await runner.discover(port);
77
77
  if (portProcesses.length === 0) {
78
- if (options.list)
79
- console.log(`Port ${port} is free.`);
78
+ const state = await runner.probe(port);
79
+ if (state === "occupied") {
80
+ console.error(`Port ${port} is in use by a process port-reclaim cannot see — it may belong to another user or an elevated process, or be a socket still closing. Rerun with sudo or from an elevated PowerShell session, or inspect it with 'netstat -ano | findstr :${port}'.`);
81
+ return false;
82
+ }
83
+ if (options.list) {
84
+ console.log(state === "free" ? `Port ${port} is free.` : `Port ${port} appears free but could not be verified.`);
85
+ }
80
86
  return true;
81
87
  }
82
88
  let free = true;
@@ -86,12 +92,12 @@ async function reclaimPort(port, runner, options) {
86
92
  const origin = sameDirectory(portProcess.cwd, currentDirectory)
87
93
  ? "matches the current directory"
88
94
  : portProcess.cwd ? `'${portProcess.cwd}'` : "an unreadable working directory";
89
- const docker = portProcess.docker ? " [docker]" : "";
90
- console.log(`Port ${port} is used by ${describe(portProcess)}${docker} — ${origin}.`);
95
+ const refusal = portProcess.refusal ? " [refused]" : "";
96
+ console.log(`Port ${port} is used by ${describe(portProcess)}${refusal} — ${origin}.`);
91
97
  continue;
92
98
  }
93
- if (portProcess.docker) {
94
- console.error(`Port ${port} is used by ${describe(portProcess)}, which appears to be a Docker process. Refusing to kill it — stop the container instead (for example 'docker stop <container>').`);
99
+ if (portProcess.refusal) {
100
+ console.error(`Port ${port} is used by ${describe(portProcess)}. Refusing to kill it — ${portProcess.refusal}`);
95
101
  free = false;
96
102
  continue;
97
103
  }
@@ -1,5 +1,5 @@
1
- export { createProcessRunner, parseEtime, parseNetstatPids, parseUnixLsof, parseWindowsPids } from "./process.js";
2
- export type { NetstatPid, PortProcess, ProcessRunner, Protocol } from "./process.js";
1
+ export { createProcessRunner, parseEtime, parseNetstatPids, parsePipeTable, parsePsTable, parseUnixLsof, refusalReason, } from "./process.js";
2
+ export type { NetstatPid, PortProcess, PortState, ProcessRow, ProcessRunner, Protocol, } from "./process.js";
3
3
  export { loadConfig, parsePackageConfig, parseReclaimignore } from "./config.js";
4
4
  export type { ReclaimConfig } from "./config.js";
5
5
  export { parseArgs } from "./args.js";
package/dist/src/index.js CHANGED
@@ -1,3 +1,3 @@
1
- export { createProcessRunner, parseEtime, parseNetstatPids, parseUnixLsof, parseWindowsPids } from "./process.js";
1
+ export { createProcessRunner, parseEtime, parseNetstatPids, parsePipeTable, parsePsTable, parseUnixLsof, refusalReason, } from "./process.js";
2
2
  export { loadConfig, parsePackageConfig, parseReclaimignore } from "./config.js";
3
3
  export { parseArgs } from "./args.js";
@@ -1,17 +1,19 @@
1
1
  export type Protocol = "tcp" | "udp";
2
+ export type PortState = "free" | "occupied" | "unknown";
2
3
  export interface PortProcess {
3
4
  pid: number;
4
5
  name: string;
5
6
  cwd?: string;
6
7
  protocol?: Protocol;
7
8
  ageMs?: number;
8
- docker?: boolean;
9
+ refusal?: string;
9
10
  }
10
11
  export interface ProcessRunner {
11
12
  discover(port: number): Promise<PortProcess[]>;
12
13
  terminate(pid: number): Promise<void>;
14
+ probe(port: number): Promise<PortState>;
13
15
  }
14
- export declare function parseWindowsPids(output: string): number[];
16
+ export declare function refusalReason(pid: number, name: string): string | undefined;
15
17
  export declare function parseUnixLsof(output: string): number[];
16
18
  export declare function parseEtime(value: string): number | undefined;
17
19
  export interface NetstatPid {
@@ -19,4 +21,12 @@ export interface NetstatPid {
19
21
  protocol: Protocol;
20
22
  }
21
23
  export declare function parseNetstatPids(output: string, port: number): NetstatPid[];
24
+ export interface ProcessRow {
25
+ pid: number;
26
+ name: string;
27
+ ageMs?: number;
28
+ protocol?: Protocol;
29
+ }
30
+ export declare function parsePipeTable(output: string): ProcessRow[];
31
+ export declare function parsePsTable(output: string): ProcessRow[];
22
32
  export declare function createProcessRunner(): ProcessRunner;
@@ -1,17 +1,20 @@
1
1
  import { execFile } from "node:child_process";
2
2
  import { promisify } from "node:util";
3
3
  import process from "node:process";
4
+ import net from "node:net";
5
+ import dgram from "node:dgram";
4
6
  import pidCwd from "pid-cwd";
5
7
  const execFileAsync = promisify(execFile);
6
8
  const DOCKER_PROCESS = /docker|vpnkit/i;
7
- function isDockerProcess(name) {
8
- return DOCKER_PROCESS.test(name);
9
- }
10
- function parsePidList(output) {
11
- return [...new Set(output.split(/\r?\n/).map((line) => Number(line.trim())).filter((pid) => Number.isInteger(pid) && pid > 0))];
12
- }
13
- export function parseWindowsPids(output) {
14
- return parsePidList(output);
9
+ const SYSTEM_PID_CEILING = 4;
10
+ export function refusalReason(pid, name) {
11
+ if (DOCKER_PROCESS.test(name)) {
12
+ return "it appears to be a Docker process — stop the container instead (for example 'docker stop <container>').";
13
+ }
14
+ if (pid <= SYSTEM_PID_CEILING) {
15
+ return `PID ${pid} and below belong to the operating system itself — stop the service that owns the port instead.`;
16
+ }
17
+ return undefined;
15
18
  }
16
19
  export function parseUnixLsof(output) {
17
20
  return [...new Set([...output.matchAll(/^p(\d+)$/gm)].map((match) => Number(match[1])))];
@@ -58,6 +61,46 @@ export function parseNetstatPids(output, port) {
58
61
  }
59
62
  return results;
60
63
  }
64
+ function readProtocol(value) {
65
+ const normalized = value?.trim().toLowerCase();
66
+ if (normalized === "tcp" || normalized === "udp")
67
+ return normalized;
68
+ return undefined;
69
+ }
70
+ function readAge(value) {
71
+ const ageMs = Number(value);
72
+ return Number.isFinite(ageMs) && ageMs > 0 ? ageMs : undefined;
73
+ }
74
+ export function parsePipeTable(output) {
75
+ const rows = [];
76
+ const seen = new Set();
77
+ for (const line of output.split(/\r?\n/)) {
78
+ const columns = line.trim().split("|");
79
+ if (columns.length < 2)
80
+ continue;
81
+ const pid = Number(columns[0]);
82
+ if (!Number.isInteger(pid) || pid <= 0 || seen.has(pid))
83
+ continue;
84
+ seen.add(pid);
85
+ rows.push({ pid, name: columns[1].trim() || "unknown", ageMs: readAge(columns[2]), protocol: readProtocol(columns[3]) });
86
+ }
87
+ return rows;
88
+ }
89
+ export function parsePsTable(output) {
90
+ const rows = [];
91
+ const seen = new Set();
92
+ for (const line of output.split(/\r?\n/)) {
93
+ const match = /^\s*(\d+)\s+(.+?)\s+(\S+)\s*$/.exec(line);
94
+ if (!match)
95
+ continue;
96
+ const pid = Number(match[1]);
97
+ if (!Number.isInteger(pid) || pid <= 0 || seen.has(pid))
98
+ continue;
99
+ seen.add(pid);
100
+ rows.push({ pid, name: match[2].trim(), ageMs: parseEtime(match[3]) });
101
+ }
102
+ return rows;
103
+ }
61
104
  async function run(command, args, checked = false) {
62
105
  try {
63
106
  const result = await execFileAsync(command, args, { windowsHide: true, maxBuffer: 1024 * 1024 });
@@ -77,71 +120,73 @@ async function run(command, args, checked = false) {
77
120
  return "";
78
121
  }
79
122
  }
80
- async function unixPortProcesses(port) {
81
- const merged = new Map();
82
- const udp = await run("lsof", ["-nP", "-iUDP:" + port, "-Fp"]);
83
- for (const pid of parseUnixLsof(udp))
84
- merged.set(pid, "udp");
85
- const tcp = await run("lsof", ["-nP", "-a", "-iTCP:" + port, "-sTCP:LISTEN", "-Fp"]);
86
- for (const pid of parseUnixLsof(tcp))
87
- merged.set(pid, "tcp");
88
- return merged;
89
- }
90
- async function windowsPortProcesses(port) {
91
- const merged = new Map();
92
- const tcpScript = `$ErrorActionPreference = 'SilentlyContinue'; Get-NetTCPConnection -LocalPort ${port} -State Listen | Select-Object -ExpandProperty OwningProcess`;
93
- for (const pid of parseWindowsPids(await run("powershell.exe", ["-NoProfile", "-NonInteractive", "-Command", tcpScript]))) {
94
- merged.set(pid, "tcp");
95
- }
96
- const udpScript = `$ErrorActionPreference = 'SilentlyContinue'; Get-NetUDPConnection -LocalPort ${port} | Select-Object -ExpandProperty OwningProcess`;
97
- for (const pid of parseWindowsPids(await run("powershell.exe", ["-NoProfile", "-NonInteractive", "-Command", udpScript]))) {
98
- if (!merged.has(pid))
99
- merged.set(pid, "udp");
100
- }
101
- if (merged.size > 0)
102
- return merged;
103
- const netstat = await run("netstat.exe", ["-ano"]);
104
- for (const entry of parseNetstatPids(netstat, port)) {
105
- if (!merged.has(entry.pid))
106
- merged.set(entry.pid, entry.protocol);
107
- }
108
- return merged;
109
- }
110
- async function processInfo(pid) {
111
- if (process.platform === "win32") {
112
- const script = `$ErrorActionPreference = 'SilentlyContinue'; $p = Get-Process -Id ${pid}; if ($p) { $p.ProcessName; if ($p.StartTime) { [DateTime]::UtcNow.Subtract($p.StartTime).TotalMilliseconds } }`;
113
- const output = await run("powershell.exe", ["-NoProfile", "-NonInteractive", "-Command", script]);
114
- const [name, age] = output.split(/\r?\n/);
115
- const ageMs = Number(age?.trim());
116
- return { name: name?.trim() || "unknown", ageMs: Number.isFinite(ageMs) && ageMs > 0 ? ageMs : undefined };
117
- }
118
- const output = await run("ps", ["-p", String(pid), "-o", "comm=", "-o", "etime="]);
119
- const trimmed = output.trim();
120
- if (!trimmed)
121
- return { name: "unknown" };
122
- const match = /^(.*?)\s+(\S+)$/.exec(trimmed);
123
- if (!match)
124
- return { name: trimmed };
125
- return { name: match[1].trim(), ageMs: parseEtime(match[2]) };
123
+ function byPid(rows) {
124
+ return new Map(rows.map((row) => [row.pid, row]));
125
+ }
126
+ function describe(pid, protocol, info) {
127
+ return { pid, protocol, name: info?.name ?? "unknown", ageMs: info?.ageMs };
126
128
  }
127
- async function processCwd(pid) {
128
- return (await pidCwd(pid)) ?? undefined;
129
+ async function discoverUnix(port) {
130
+ const protocols = new Map();
131
+ for (const pid of parseUnixLsof(await run("lsof", ["-nP", "-iUDP:" + port, "-Fp"])))
132
+ protocols.set(pid, "udp");
133
+ for (const pid of parseUnixLsof(await run("lsof", ["-nP", "-a", "-iTCP:" + port, "-sTCP:LISTEN", "-Fp"])))
134
+ protocols.set(pid, "tcp");
135
+ if (protocols.size === 0)
136
+ return [];
137
+ const output = await run("ps", ["-p", [...protocols.keys()].join(","), "-o", "pid=,comm=,etime="]);
138
+ const infos = byPid(parsePsTable(output));
139
+ return [...protocols].map(([pid, protocol]) => describe(pid, protocol, infos.get(pid)));
140
+ }
141
+ function windowsNameLoop(protocol) {
142
+ // StartTime is local-time, so compare against Now rather than UtcNow or the age comes out negative.
143
+ return `foreach ($id in $pids) { $proc = Get-Process -Id $id; if ($proc) { $age = ''; try { $age = [DateTime]::Now.Subtract($proc.StartTime).TotalMilliseconds } catch { }; Write-Output "$id|$($proc.ProcessName)|$age|${protocol}" } else { Write-Output "$id|unknown||${protocol}" } }`;
144
+ }
145
+ function windowsNamesScript(pids) {
146
+ return [`$pids = @(${pids.join(",")})`, windowsNameLoop("")].join("; ");
147
+ }
148
+ async function discoverWindows(port) {
149
+ // netstat is an order of magnitude cheaper than a PowerShell cold start, so it decides
150
+ // whether anything is on the port; PowerShell is only paid for when a name is needed.
151
+ const entries = parseNetstatPids(await run("netstat.exe", ["-ano"]), port);
152
+ if (entries.length === 0)
153
+ return [];
154
+ const infos = byPid(parsePipeTable(await run("powershell.exe", ["-NoProfile", "-NonInteractive", "-Command", windowsNamesScript(entries.map((entry) => entry.pid))])));
155
+ return entries.map((entry) => describe(entry.pid, entry.protocol, infos.get(entry.pid)));
156
+ }
157
+ function probePort(port, protocol) {
158
+ return new Promise((resolve) => {
159
+ if (protocol === "tcp") {
160
+ const server = net.createServer();
161
+ server.once("error", (error) => resolve(error.code === "EADDRINUSE" ? "occupied" : "unknown"));
162
+ server.once("listening", () => server.close(() => resolve("free")));
163
+ server.listen(port);
164
+ return;
165
+ }
166
+ const socket = dgram.createSocket("udp4");
167
+ socket.once("error", (error) => resolve(error.code === "EADDRINUSE" ? "occupied" : "unknown"));
168
+ socket.once("listening", () => socket.close(() => resolve("free")));
169
+ socket.bind(port);
170
+ });
171
+ }
172
+ async function probePortState(port) {
173
+ const tcp = await probePort(port, "tcp");
174
+ if (tcp === "occupied")
175
+ return "occupied";
176
+ const udp = await probePort(port, "udp");
177
+ if (udp === "occupied")
178
+ return "occupied";
179
+ return tcp === "free" && udp === "free" ? "free" : "unknown";
129
180
  }
130
181
  export function createProcessRunner() {
131
182
  return {
132
183
  async discover(port) {
133
- const entries = process.platform === "win32" ? await windowsPortProcesses(port) : await unixPortProcesses(port);
134
- return Promise.all([...entries].map(async ([pid, protocol]) => {
135
- const info = await processInfo(pid);
136
- return {
137
- pid,
138
- name: info.name,
139
- protocol,
140
- cwd: await processCwd(pid),
141
- ageMs: info.ageMs,
142
- docker: isDockerProcess(info.name),
143
- };
144
- }));
184
+ const discovered = process.platform === "win32" ? await discoverWindows(port) : await discoverUnix(port);
185
+ return Promise.all(discovered.map(async (entry) => ({
186
+ ...entry,
187
+ cwd: (await pidCwd(entry.pid)) ?? undefined,
188
+ refusal: refusalReason(entry.pid, entry.name),
189
+ })));
145
190
  },
146
191
  async terminate(pid) {
147
192
  if (process.platform === "win32") {
@@ -158,6 +203,7 @@ export function createProcessRunner() {
158
203
  catch {
159
204
  // The process exited after SIGTERM.
160
205
  }
161
- }
206
+ },
207
+ probe: probePortState,
162
208
  };
163
209
  }
@@ -5,8 +5,9 @@ import { mkdtemp, rm, writeFile } from "node:fs/promises";
5
5
  import { tmpdir } from "node:os";
6
6
  import path from "node:path";
7
7
  import { main } from "../src/cli.js";
8
- function fakeRunner(byPort) {
9
- const calls = { discovered: [], terminated: [] };
8
+ import { refusalReason } from "../src/process.js";
9
+ function fakeRunner(byPort, probeState = "free") {
10
+ const calls = { discovered: [], terminated: [], probed: [] };
10
11
  return {
11
12
  calls,
12
13
  runner: {
@@ -17,6 +18,10 @@ function fakeRunner(byPort) {
17
18
  async terminate(pid) {
18
19
  calls.terminated.push(pid);
19
20
  },
21
+ async probe(port) {
22
+ calls.probed.push(port);
23
+ return probeState;
24
+ },
20
25
  },
21
26
  };
22
27
  }
@@ -48,6 +53,30 @@ test("exits 0 when all ports are free", async () => {
48
53
  output.restore();
49
54
  }
50
55
  });
56
+ test("reports a port held by a process it cannot see and exits 1", async () => {
57
+ const { runner, calls } = fakeRunner({}, "occupied");
58
+ const output = capture();
59
+ try {
60
+ assert.equal(await main(["3000"], runner), 1);
61
+ assert.deepEqual(calls.probed, [3000]);
62
+ assert.match(output.error.join("\n"), /cannot see/);
63
+ }
64
+ finally {
65
+ output.restore();
66
+ }
67
+ });
68
+ test("does not probe ports that already have visible processes", async () => {
69
+ const { runner, calls } = fakeRunner({ 3000: [{ pid: 42, name: "node", cwd: process.cwd() }] });
70
+ const output = capture();
71
+ try {
72
+ assert.equal(await main(["3000"], runner), 0);
73
+ assert.deepEqual(calls.probed, []);
74
+ assert.deepEqual(calls.terminated, [42]);
75
+ }
76
+ finally {
77
+ output.restore();
78
+ }
79
+ });
51
80
  test("terminates processes from the current directory without prompting", async () => {
52
81
  const { runner, calls } = fakeRunner({ 3000: [{ pid: 42, name: "node", cwd: process.cwd() }] });
53
82
  const output = capture();
@@ -102,7 +131,7 @@ test("--list reports without terminating", async () => {
102
131
  }
103
132
  });
104
133
  test("refuses to kill Docker processes even with --yes", async () => {
105
- const { runner, calls } = fakeRunner({ 3000: [{ pid: 9, name: "docker-proxy", docker: true }] });
134
+ const { runner, calls } = fakeRunner({ 3000: [{ pid: 9, name: "docker-proxy", refusal: refusalReason(9, "docker-proxy") }] });
106
135
  const output = capture();
107
136
  try {
108
137
  assert.equal(await main(["3000", "--yes"], runner), 1);
@@ -113,6 +142,18 @@ test("refuses to kill Docker processes even with --yes", async () => {
113
142
  output.restore();
114
143
  }
115
144
  });
145
+ test("refuses to kill operating-system PIDs even with --yes", async () => {
146
+ const { runner, calls } = fakeRunner({ 8080: [{ pid: 4, name: "System", refusal: refusalReason(4, "System") }] });
147
+ const output = capture();
148
+ try {
149
+ assert.equal(await main(["8080", "--yes"], runner), 1);
150
+ assert.deepEqual(calls.terminated, []);
151
+ assert.match(output.error.join("\n"), /operating system/);
152
+ }
153
+ finally {
154
+ output.restore();
155
+ }
156
+ });
116
157
  test("skips ports protected by .reclaimignore in the current directory", async () => {
117
158
  const dir = await mkdtemp(path.join(tmpdir(), "port-reclaim-"));
118
159
  const originalCwd = process.cwd();
@@ -1,9 +1,6 @@
1
1
  import test from "node:test";
2
2
  import assert from "node:assert/strict";
3
- import { parseEtime, parseNetstatPids, parseUnixLsof, parseWindowsPids } from "../src/process.js";
4
- test("parses unique Windows PIDs", () => {
5
- assert.deepEqual(parseWindowsPids("1234\r\n5678\r\n1234\r\n"), [1234, 5678]);
6
- });
3
+ import { parseEtime, parseNetstatPids, parsePipeTable, parsePsTable, parseUnixLsof, refusalReason, } from "../src/process.js";
7
4
  test("parses lsof PID records", () => {
8
5
  assert.deepEqual(parseUnixLsof("p1234\ncnode\np5678\np1234\n"), [1234, 5678]);
9
6
  });
@@ -16,6 +13,36 @@ test("parses ps etime durations", () => {
16
13
  assert.equal(parseEtime("abc"), undefined);
17
14
  assert.equal(parseEtime("1:2:3:4"), undefined);
18
15
  });
16
+ test("parses one batched ps table, keeping spaces in command names", () => {
17
+ const output = [
18
+ " 1234 node 01:02:03",
19
+ " 5678 Google Chrome 45:00",
20
+ "ps: unknown process 9999",
21
+ ].join("\n");
22
+ assert.deepEqual(parsePsTable(output), [
23
+ { pid: 1234, name: "node", ageMs: 3723000 },
24
+ { pid: 5678, name: "Google Chrome", ageMs: 2700000 },
25
+ ]);
26
+ });
27
+ test("parses pipe-delimited process rows", () => {
28
+ assert.deepEqual(parsePipeTable("7|node|1500.5|udp\r\n8|python||\r\n"), [
29
+ { pid: 7, name: "node", ageMs: 1500.5, protocol: "udp" },
30
+ { pid: 8, name: "python", ageMs: undefined, protocol: undefined },
31
+ ]);
32
+ });
33
+ test("drops PID 0, keeps PID 4 for the refusal layer, and deduplicates rows", () => {
34
+ assert.deepEqual(parsePipeTable(["0|Idle|10|", "4|System|20|", "77|node|30|", "77|node|30|", "junk"].join("\r\n")), [
35
+ { pid: 4, name: "System", ageMs: 20, protocol: undefined },
36
+ { pid: 77, name: "node", ageMs: 30, protocol: undefined },
37
+ ]);
38
+ });
39
+ test("refuses Docker-named processes and operating-system PIDs", () => {
40
+ assert.match(refusalReason(9, "docker-proxy") ?? "", /Docker/);
41
+ assert.match(refusalReason(9, "vpnkit") ?? "", /Docker/);
42
+ assert.match(refusalReason(4, "System") ?? "", /operating system/);
43
+ assert.match(refusalReason(1, "systemd") ?? "", /operating system/);
44
+ assert.equal(refusalReason(4242, "node"), undefined);
45
+ });
19
46
  test("parses netstat TCP listeners and UDP sockets for an exact port", () => {
20
47
  const output = [
21
48
  "Active Connections",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "port-reclaim",
3
- "version": "0.2.1",
3
+ "version": "0.3.0",
4
4
  "description": "Free up a port already in use: find and kill the process holding it (EADDRINUSE). Cross-platform, zero-config, Docker-safe.",
5
5
  "author": "princegoel0",
6
6
  "license": "MIT",