portlense 0.0.0-stage → 0.1.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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Saku0512
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,93 @@
1
- # Temporary Holding Version
1
+ # portlense
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ A CLI that shows ports in use on your local machine and the processes using them.
4
+
5
+ ```text
6
+ PORT PROTO ADDRESS STATE PID PROCESS
7
+ ──── ───── ────────────── ────── ───── ───────
8
+ 3000 TCP *:3000 LISTEN 1234 node
9
+ 5353 UDP *:5353 UNCONN 5678 example
10
+ ```
11
+
12
+ ## Installation
13
+
14
+ Node.js 18 or later is required. On macOS and Linux, portlense uses `lsof`. On Windows, it uses `netstat` and `tasklist`.
15
+
16
+ ```sh
17
+ npm install -g portlense
18
+ portlense
19
+ ```
20
+
21
+ After the package is published, you can also run it with `npx portlense`. To try it from source, run `node bin/portlense.js`.
22
+
23
+ ## Usage
24
+
25
+ ```sh
26
+ portlense # Show listening TCP ports and UDP sockets
27
+ portlense --tui # Open the interactive live monitor
28
+ portlense --port 3000 # Filter by port number
29
+ portlense --protocol tcp # Filter by tcp or udp
30
+ portlense --pid 1234 # Filter by process ID
31
+ portlense --process node # Filter by process name (case-insensitive substring)
32
+ portlense --details # Include process user and command
33
+ portlense --state LISTEN # Filter by socket state
34
+ portlense --sort process # Sort by port, protocol, pid, process, or state
35
+ portlense --color always # Force color (auto, always, or never)
36
+ portlense --all # Include non-listening TCP connections
37
+ portlense --watch # Refresh every 2 seconds; press Ctrl+C to stop
38
+ portlense --watch --interval 1 # Refresh every second
39
+ portlense --json # Output JSON
40
+ portlense check 3000 # Check TCP on 127.0.0.1 and show any conflicts
41
+ portlense check 5353 -t udp --host 0.0.0.0
42
+ portlense find --from 3000 --to 3100 # Find the first available TCP port
43
+ portlense --config ./portlense.json # Load explicit configuration
44
+ portlense --help
45
+ ```
46
+
47
+ Options can be combined. Colors are enabled automatically for terminals and disabled when `NO_COLOR` is set; `--color` explicitly overrides this behavior. JSON output is never colored. With `--watch --json`, each line is a complete JSON array, suitable for streaming. The interval must be between 0.1 and 86400 seconds. The information available depends on your OS and user permissions. Processes you cannot access may be missing, or their names may be unavailable. On Windows, `--all` displays the local address.
48
+
49
+ `check` and `find` attempt to bind the requested address and protocol (TCP and `127.0.0.1` by default), then immediately release the socket. A successful check is a snapshot, not a reservation: another process may bind the port before you do. Results for another address, IPv6, or protocol may differ. A check of an occupied port and a search with no result exit with status 1; unexpected errors also exit with status 1. Use `--json` for structured results. Conflict details depend on permissions and available system tools; the list may include sockets on other addresses using the same port.
50
+
51
+ Use `--details` to show each process's user and command. On Unix this uses `ps`; on Windows it uses PowerShell and CIM. Fields may be empty when a process exits or access is denied. In watch mode, `+` marks new sockets and `-` marks sockets that disappeared since the previous refresh; removed rows appear for one refresh. A state change appears as a removal and an addition. JSON watch output remains a stream of complete snapshots without change markers.
52
+
53
+ ## Interactive monitor
54
+
55
+ Run `portlense --tui` in an interactive terminal. The display refreshes every two seconds by default; use `--interval` to change this. Existing filters such as `--port`, `--pid`, `--process`, and `--sort` apply on startup. The selected socket's address, user, and command are shown below the list when available.
56
+
57
+ - **↑ / ↓** or **k / j**: select a socket.
58
+ - **/**: edit the case-insensitive process name filter; press Enter or Escape to finish.
59
+ - **p**: cycle through all protocols, TCP, and UDP.
60
+ - **a**: toggle inclusion of non-listening TCP connections.
61
+ - **r**: refresh now.
62
+ - **q** or **Ctrl+C**: quit and restore the terminal.
63
+
64
+ The TUI requires an interactive terminal and cannot be combined with `--json` or `--watch`. Process details are best effort and may be unavailable due to permissions.
65
+
66
+ ## Configuration
67
+
68
+ Create `~/.config/portlense/config.json` (or `$XDG_CONFIG_HOME/portlense/config.json` if `XDG_CONFIG_HOME` is set), for example:
69
+
70
+ ```json
71
+ {
72
+ "color": "auto",
73
+ "sort": "process",
74
+ "interval": 1,
75
+ "protocol": "tcp",
76
+ "all": false,
77
+ "details": false
78
+ }
79
+ ```
80
+
81
+ All fields are optional. `interval` applies to watch mode; it must be between 0.1 and 86400 seconds. CLI options override configuration values. `--config <path>` chooses a different JSON file; invalid or unknown settings are reported as errors.
82
+
83
+ ## JavaScript API
84
+
85
+ See the [JavaScript API documentation](docs/javascript-api.md) for examples, port monitoring, and TypeScript support.
86
+
87
+ ## Development
88
+
89
+ ```sh
90
+ npm test
91
+ ```
92
+
93
+ MIT License
@@ -0,0 +1,149 @@
1
+ #!/usr/bin/env node
2
+ import { getPorts, inspectPort, findPort, diffPorts, loadConfig, formatPorts, runTui } from '../src/index.js';
3
+ import { setTimeout as delay } from 'node:timers/promises';
4
+
5
+ const help = `portlense — View ports in use
6
+
7
+ Usage: portlense [options]
8
+ portlense check <port> [--protocol tcp|udp] [--host address] [--json]
9
+ portlense find --from <port> --to <port> [--protocol tcp|udp] [--host address] [--json]
10
+
11
+ -p, --port <number> Filter by port number (1–65535)
12
+ -t, --protocol <type> Filter by protocol: tcp or udp
13
+ --pid <number> Filter by process ID
14
+ --process <name> Filter by process name (case-insensitive substring)
15
+ --state <state> Filter by socket state (e.g. LISTEN)
16
+ --sort <field> Sort by port, protocol, pid, process, or state
17
+ -d, --details Include process user and command
18
+ --config <path> Use a JSON configuration file
19
+ --color <mode> Color output: auto, always, or never (default: auto)
20
+ -a, --all Include non-listening TCP connections
21
+ --tui Open the interactive terminal interface
22
+ -w, --watch Refresh continuously (press Ctrl+C to stop)
23
+ --interval <seconds> Refresh interval for watch mode (default: 2)
24
+ -j, --json Output JSON (one JSON array per line in watch mode)
25
+ -h, --help Show help
26
+ -v, --version Show version
27
+ `;
28
+
29
+
30
+ function parseArgs(args, defaults = {}) {
31
+ const options = { ...defaults };
32
+ if (['check', 'find'].includes(args[0])) options.command = args.shift();
33
+ if (options.command === 'check') {
34
+ const port = args.shift();
35
+ if (!port || !/^\d+$/.test(port) || Number(port) < 1 || Number(port) > 65535) throw new Error('check requires a port from 1 to 65535.');
36
+ options.port = Number(port);
37
+ }
38
+ for (let i = 0; i < args.length; i++) {
39
+ const arg = args[i];
40
+ if (arg === '--config') { if (!args[++i]) throw new Error('--config requires a path.'); }
41
+ else if (arg === '-d' || arg === '--details') options.details = true;
42
+ else if (arg === '--host') { const value = args[++i]; if (!value || value.startsWith('-')) throw new Error('--host requires an address.'); options.host = value; }
43
+ else if (arg === '--from' || arg === '--to') { const value = args[++i]; if (!value || !/^\d+$/.test(value) || Number(value) < 1 || Number(value) > 65535) throw new Error(`${arg} must be an integer from 1 to 65535.`); options[arg.slice(2)] = Number(value); }
44
+ else if (arg === '-h' || arg === '--help') options.help = true;
45
+ else if (arg === '-v' || arg === '--version') options.version = true;
46
+ else if (arg === '-a' || arg === '--all') options.all = true;
47
+ else if (arg === '-j' || arg === '--json') options.json = true;
48
+ else if (arg === '-w' || arg === '--watch') options.watch = true;
49
+ else if (arg === '--tui') options.tui = true;
50
+ else if (arg === '--pid') {
51
+ const value = args[++i];
52
+ if (!value || !/^\d+$/.test(value) || !Number.isSafeInteger(Number(value)) || Number(value) < 1) throw new Error('--pid must be a positive integer.');
53
+ options.pid = Number(value);
54
+ } else if (arg === '--process') {
55
+ const value = args[++i];
56
+ if (!value || value.startsWith('-')) throw new Error('--process requires a process name.');
57
+ options.process = value;
58
+ } else if (arg === '--state') {
59
+ const value = args[++i];
60
+ if (!value || value.startsWith('-')) throw new Error('--state requires a socket state.');
61
+ options.state = value;
62
+ } else if (arg === '--sort') {
63
+ const value = args[++i];
64
+ if (!['port', 'protocol', 'pid', 'process', 'state'].includes(value)) throw new Error('--sort must be port, protocol, pid, process, or state.');
65
+ options.sort = value;
66
+ } else if (arg === '--color') {
67
+ const value = args[++i];
68
+ if (!['auto', 'always', 'never'].includes(value)) throw new Error('--color must be auto, always, or never.');
69
+ options.color = value;
70
+ } else if (arg === '--interval') {
71
+ const value = args[++i];
72
+ if (!value || !/^(?:\d+(?:\.\d+)?|\.\d+)$/.test(value) || Number(value) < 0.1 || Number(value) > 86400) throw new Error('--interval must be between 0.1 and 86400 seconds.');
73
+ options.interval = Number(value);
74
+ }
75
+ else if (arg === '-p' || arg === '--port') {
76
+ const value = args[++i];
77
+ if (!value || !/^\d+$/.test(value) || Number(value) < 1 || Number(value) > 65535) throw new Error('--port must be an integer from 1 to 65535.');
78
+ options.port = Number(value);
79
+ } else if (arg === '-t' || arg === '--protocol') {
80
+ const value = args[++i]?.toUpperCase();
81
+ if (value !== 'TCP' && value !== 'UDP') throw new Error('--protocol must be tcp or udp.');
82
+ options.protocol = value;
83
+ } else throw new Error(`Unknown option: ${arg}`);
84
+ }
85
+ if (args.includes('--interval') && !options.watch && !options.tui) throw new Error('--interval requires --watch or --tui.');
86
+ if (options.tui && (options.watch || options.json || options.command)) throw new Error('--tui cannot be combined with --watch, --json, or a command.');
87
+ if (options.command) {
88
+ const allowed = new Set(['--protocol', '-t', '--host', '--json', '-j', '--config', '--color', '--help', '-h', '--version', '-v', ...(options.command === 'find' ? ['--from', '--to'] : [])]);
89
+ for (let i = 0; i < args.length; i++) {
90
+ const arg = args[i];
91
+ if (!allowed.has(arg)) throw new Error(`${arg} is not supported by ${options.command}.`);
92
+ if (['--protocol', '-t', '--host', '--config', '--color', '--from', '--to'].includes(arg)) i++;
93
+ }
94
+ }
95
+ if (!options.command && (options.from !== undefined || options.to !== undefined || options.host)) throw new Error('--from, --to and --host require check or find.');
96
+ if (options.command === 'find' && (options.from === undefined || options.to === undefined || options.from > options.to)) throw new Error('find requires a valid --from and --to range.');
97
+ if (options.command === 'check' && (options.from !== undefined || options.to !== undefined)) throw new Error('--from and --to require find.');
98
+ return options;
99
+ }
100
+
101
+
102
+ try {
103
+ const args = process.argv.slice(2);
104
+ const configIndex = args.indexOf('--config');
105
+ if (configIndex !== -1 && (!args[configIndex + 1] || args[configIndex + 1].startsWith('-'))) throw new Error('--config requires a path.');
106
+ const options = parseArgs([...args], await loadConfig(configIndex === -1 ? undefined : args[configIndex + 1]));
107
+ if (options.help) console.log(help);
108
+ else if (options.version) console.log('0.1.0');
109
+ else if (options.command) {
110
+ const protocol = (options.protocol || 'TCP').toUpperCase();
111
+ const host = options.host || '127.0.0.1';
112
+ if (options.command === 'check') {
113
+ const result = await inspectPort(options.port, { protocol, host });
114
+ const { available, conflicts } = result;
115
+ if (options.json) console.log(JSON.stringify(result, null, 2));
116
+ else {
117
+ console.log(`${protocol} ${host}:${options.port} is ${available ? 'available' : 'in use'}.`);
118
+ if (conflicts.length) console.log(formatPorts(conflicts, { color: options.color === 'always' || (options.color !== 'never' && process.stdout.isTTY && !('NO_COLOR' in process.env)), details: true }));
119
+ }
120
+ if (!available) process.exitCode = 1;
121
+ } else {
122
+ const port = await findPort({ from: options.from, to: options.to, protocol, host });
123
+ if (options.json) console.log(JSON.stringify({ port, protocol, host }, null, 2));
124
+ else console.log(port === null ? 'No available port found in the requested range.' : `Available ${protocol} port on ${host}: ${port}`);
125
+ if (port === null) process.exitCode = 1;
126
+ }
127
+ } else if (options.tui) await runTui({ ...options, interval: (options.interval ?? 2) * 1000 });
128
+ else {
129
+ let previous;
130
+ do {
131
+ const entries = await getPorts(options);
132
+ if (options.json) console.log(JSON.stringify(entries, null, options.watch ? 0 : 2));
133
+ else {
134
+ if (options.watch) {
135
+ if (process.stdout.isTTY) process.stdout.write('\x1b[2J\x1b[H');
136
+ console.log(`Updated ${new Date().toISOString()} (Ctrl+C to stop)`);
137
+ }
138
+ const useColor = options.color === 'always' || (options.color !== 'never' && process.stdout.isTTY && !('NO_COLOR' in process.env));
139
+ const changes = options.watch && previous ? diffPorts(previous, entries) : null;
140
+ console.log(formatPorts(entries, { color: useColor, details: options.details, changes }));
141
+ }
142
+ previous = entries;
143
+ if (options.watch) await delay((options.interval ?? 2) * 1000);
144
+ } while (options.watch);
145
+ }
146
+ } catch (error) {
147
+ console.error(`portlense: ${error.message}`);
148
+ process.exitCode = 1;
149
+ }
@@ -0,0 +1,93 @@
1
+ # JavaScript API
2
+
3
+ ```js
4
+ import { getPorts } from 'portlense';
5
+
6
+ const ports = await getPorts({ protocol: 'TCP', port: 3000, pid: 1234, process: 'node', state: 'LISTEN', sort: 'port', all: false });
7
+ console.log(ports);
8
+ // [{ protocol: 'TCP', port: 3000, address: '*:3000', state: 'LISTEN', pid: 1234, process: 'node' }]
9
+ ```
10
+
11
+ `protocol`, `port`, `pid`, `process`, `state`, `sort`, `all`, and `details` are optional. With `details: true`, results include `user` and `command` fields. `sort` accepts `port`, `protocol`, `pid`, `process`, or `state`. State matching is case-insensitive. The `process` filter matches a case-insensitive substring of the process name. Results are sorted by port number by default. The process name is an empty string when unavailable.
12
+
13
+ You can also check a port, find a port in a range, and compare snapshots:
14
+
15
+ ```js
16
+ import { checkPort, findPort, diffPorts } from 'portlense';
17
+
18
+ const available = await checkPort(3000, { protocol: 'TCP', host: '127.0.0.1' });
19
+ const port = await findPort({ from: 3000, to: 3100 }); // number or null
20
+ const { added, removed } = diffPorts(previousSnapshot, currentSnapshot);
21
+ ```
22
+
23
+ ## Watch port changes
24
+
25
+ `watchPorts` is an async iterator that yields an initial snapshot and then polls for changes. The initial `added` and `removed` lists are empty; later snapshots compare sockets by protocol, port, address, state, PID, and process name. Details are available with `details: true`, but changes to details alone do not count as socket changes.
26
+
27
+ ```js
28
+ import { watchPorts } from 'portlense';
29
+
30
+ const controller = new AbortController();
31
+ setTimeout(() => controller.abort(), 10_000);
32
+
33
+ for await (const { current, added, removed, timestamp } of watchPorts({
34
+ protocol: 'TCP',
35
+ interval: 1000, // milliseconds, default 2000
36
+ signal: controller.signal,
37
+ })) {
38
+ console.log(timestamp, current.length, { added, removed });
39
+ }
40
+ ```
41
+
42
+ All `getPorts` filters are supported. Polling waits for the consumer to request the next snapshot, then waits the interval; slow consumers do not accumulate events. Breaking out of the loop or aborting the signal stops monitoring. An abort during a system command takes effect after that command finishes. Errors from enumeration are propagated. TypeScript declarations are included.
43
+
44
+ ## Inspect an occupied port
45
+
46
+ ```js
47
+ import { inspectPort } from 'portlense';
48
+
49
+ const result = await inspectPort(3000, { protocol: 'TCP', host: '127.0.0.1' });
50
+ console.log(result.available, result.conflicts);
51
+ // { port, protocol, host, available, conflicts }
52
+ ```
53
+
54
+ `inspectPort` uses the same bind check and process lookup as `portlense check`. Conflict lookup is best effort: the array can be empty if enumeration is unavailable or restricted, and may include sockets on other addresses using the same port. A successful bind is not a reservation.
55
+
56
+ ## Format a table
57
+
58
+ ```js
59
+ import { formatPorts, getPorts, diffPorts } from 'portlense';
60
+
61
+ const current = await getPorts({ details: true });
62
+ console.log(formatPorts(current, { color: true, details: true }));
63
+ // To mark changes in another table:
64
+ const next = await getPorts();
65
+ const changes = diffPorts(current, next);
66
+ console.log(formatPorts(next, { changes }));
67
+ ```
68
+
69
+ `formatPorts` returns a string and writes nothing to the terminal. `color` defaults to `false` and explicitly enables ANSI colors. `details` includes the user and command columns. `changes` accepts the `added` and `removed` arrays returned by `diffPorts` or `watchPorts`; its removed entries are included in the output.
70
+
71
+ ## Load configuration
72
+
73
+ ```js
74
+ import { loadConfig, getPorts, watchPorts } from 'portlense';
75
+
76
+ const config = await loadConfig(); // Or loadConfig('./portlense.json')
77
+ const ports = await getPorts(config);
78
+ const watcher = watchPorts({ ...config, interval: (config.interval ?? 2) * 1000 });
79
+ ```
80
+
81
+ `loadConfig()` uses the same default location and validation as the CLI and returns `{}` when the default file does not exist. An explicitly specified missing or invalid file throws. Configuration is not loaded automatically by API functions. Config file intervals are in seconds; `watchPorts` and `runTui` intervals are in milliseconds.
82
+
83
+ ## Run the interactive monitor
84
+
85
+ ```js
86
+ import { runTui } from 'portlense';
87
+
88
+ await runTui({ protocol: 'TCP', interval: 1000, color: 'auto' });
89
+ ```
90
+
91
+ `runTui` accepts the `getPorts` filters plus `interval` in milliseconds and `color` (`auto`, `always`, or `never`). It uses the process's interactive standard input and output, and resolves when the user quits. It rejects when there is no interactive terminal. It temporarily controls the terminal screen and input mode.
92
+
93
+ The CLI's JSON output is standard JSON serialization; use `JSON.stringify` with the objects returned by these APIs. The TUI, formatted output, configuration, checking, searching, filtering, process details, and monitoring are also available independently.
package/package.json CHANGED
@@ -1,6 +1,31 @@
1
1
  {
2
2
  "name": "portlense",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "A clear view of ports in use on your machine",
5
+ "type": "module",
6
+ "bin": {
7
+ "portlense": "./bin/portlense.js"
8
+ },
9
+ "exports": "./src/index.js",
10
+ "files": [
11
+ "bin",
12
+ "src",
13
+ "docs",
14
+ "README.md",
15
+ "LICENSE"
16
+ ],
17
+ "scripts": {
18
+ "test": "node --test"
19
+ },
20
+ "engines": {
21
+ "node": ">=18"
22
+ },
23
+ "keywords": [
24
+ "port",
25
+ "network",
26
+ "cli",
27
+ "process"
28
+ ],
29
+ "license": "MIT",
30
+ "types": "./src/index.d.ts"
31
+ }
package/src/config.js ADDED
@@ -0,0 +1,23 @@
1
+ import { readFile } from 'node:fs/promises';
2
+ import { homedir } from 'node:os';
3
+ import { join } from 'node:path';
4
+
5
+ export async function loadConfig(path) {
6
+ const explicit = path !== undefined;
7
+ if (explicit && (typeof path !== 'string' || !path)) throw new TypeError('Config path must be a non-empty string.');
8
+ path ??= join(process.env.XDG_CONFIG_HOME || join(homedir(), '.config'), 'portlense', 'config.json');
9
+ let config;
10
+ try { config = JSON.parse(await readFile(path, 'utf8')); }
11
+ catch (error) { if (!explicit && error.code === 'ENOENT') return {}; throw new Error(`Cannot load config ${path}: ${error.message}`); }
12
+ if (!config || typeof config !== 'object' || Array.isArray(config)) throw new Error('Config must be a JSON object.');
13
+ const validators = {
14
+ color: v => ['auto', 'always', 'never'].includes(v),
15
+ sort: v => ['port', 'protocol', 'pid', 'process', 'state'].includes(v),
16
+ interval: v => typeof v === 'number' && Number.isFinite(v) && v >= 0.1 && v <= 86400,
17
+ protocol: v => typeof v === 'string' && ['tcp', 'udp'].includes(v.toLowerCase()),
18
+ all: v => typeof v === 'boolean', details: v => typeof v === 'boolean',
19
+ };
20
+ for (const [key, value] of Object.entries(config)) if (!validators[key] || !validators[key](value)) throw new Error(`Invalid config option: ${key}`);
21
+ return config;
22
+ }
23
+
package/src/format.js ADDED
@@ -0,0 +1,30 @@
1
+ export function formatPorts(entries, { color: useColor = false, details = false, changes = null } = {}) {
2
+ const color = (code, value) => useColor ? `\x1b[${code}m${value}\x1b[0m` : value;
3
+ if (!entries.length && !changes?.removed.length) return 'No matching ports found.';
4
+ const allEntries = changes ? [...entries, ...changes.removed] : entries;
5
+ const addedCounts = new Map();
6
+ const key = e => JSON.stringify([e.protocol, e.port, e.address, e.state, e.pid, e.process]);
7
+ for (const entry of changes?.added || []) addedCounts.set(key(entry), (addedCounts.get(key(entry)) || 0) + 1);
8
+ const rows = allEntries.map((e, index) => {
9
+ const k = key(e);
10
+ const added = index < entries.length && (addedCounts.get(k) || 0) > 0;
11
+ if (added) addedCounts.set(k, addedCounts.get(k) - 1);
12
+ return [...(changes ? [index >= entries.length ? '-' : added ? '+' : ' '] : []), String(e.port), e.protocol, e.address, e.state || '-', String(e.pid), e.process || '-', ...(details ? [e.user || '-', e.command || '-'] : [])];
13
+ });
14
+ const headers = [...(changes ? ['CHANGE'] : []), 'PORT', 'PROTO', 'ADDRESS', 'STATE', 'PID', 'PROCESS', ...(details ? ['USER', 'COMMAND'] : [])];
15
+ const widths = headers.map((header, i) => Math.max(header.length, ...rows.map(row => row[i].length)));
16
+ const format = (row, codes = []) => row.map((cell, i) => {
17
+ const padded = i === row.length - 1 ? cell : cell.padEnd(widths[i]);
18
+ return codes[i] ? color(codes[i], padded) : padded;
19
+ }).join(' ');
20
+ const lines = [format(headers, headers.map(() => '1;36')), color('2', format(widths.map(width => '─'.repeat(width))))];
21
+ for (const row of rows) {
22
+ const offset = changes ? 1 : 0;
23
+ const stateColor = row[offset + 3] === 'LISTEN' ? '32' : row[offset + 3] === 'UNCONN' ? '33' : '36';
24
+ const codes = ['1', row[offset + 1] === 'TCP' ? '34' : '35', '', stateColor, '2', ''];
25
+ if (changes) codes.unshift(row[0] === '+' ? '32' : row[0] === '-' ? '31' : '');
26
+ lines.push(format(row, codes));
27
+ }
28
+ return lines.join('\n');
29
+ }
30
+
package/src/index.d.ts ADDED
@@ -0,0 +1,56 @@
1
+ export type Protocol = 'TCP' | 'UDP' | 'tcp' | 'udp';
2
+ export type SortField = 'port' | 'protocol' | 'pid' | 'process' | 'state';
3
+
4
+ export interface PortEntry {
5
+ protocol: string;
6
+ port: number;
7
+ address: string;
8
+ state: string;
9
+ pid: number;
10
+ process: string;
11
+ user?: string;
12
+ command?: string;
13
+ }
14
+ export interface PortOptions {
15
+ all?: boolean;
16
+ protocol?: Protocol;
17
+ port?: number;
18
+ pid?: number;
19
+ process?: string;
20
+ state?: string;
21
+ sort?: SortField;
22
+ details?: boolean;
23
+ }
24
+ export interface BindOptions { protocol?: Protocol; host?: string }
25
+ export interface WatchOptions extends PortOptions { interval?: number; signal?: AbortSignal }
26
+ export interface PortChanges { added: PortEntry[]; removed: PortEntry[] }
27
+ export interface PortSnapshot extends PortChanges { current: PortEntry[]; timestamp: string }
28
+
29
+ export function getPorts(options?: PortOptions): Promise<PortEntry[]>;
30
+ export function checkPort(port: number, options?: BindOptions): Promise<boolean>;
31
+ export function findPort(options?: BindOptions & { from?: number; to?: number }): Promise<number | null>;
32
+ export function diffPorts(previous: PortEntry[], current: PortEntry[]): PortChanges;
33
+ export function watchPorts(options?: WatchOptions): AsyncGenerator<PortSnapshot, void, unknown>;
34
+ export function parseLsof(output: string, options?: { all?: boolean }): PortEntry[];
35
+ export function parseNetstat(output: string, options?: { all?: boolean }): PortEntry[];
36
+
37
+ export type ColorMode = 'auto' | 'always' | 'never';
38
+ export interface PortConfig {
39
+ color?: ColorMode;
40
+ sort?: SortField;
41
+ interval?: number; // Seconds, as in the CLI configuration file.
42
+ protocol?: Protocol;
43
+ all?: boolean;
44
+ details?: boolean;
45
+ }
46
+ export interface PortInspection {
47
+ port: number;
48
+ protocol: string;
49
+ host: string;
50
+ available: boolean;
51
+ conflicts: PortEntry[];
52
+ }
53
+ export function inspectPort(port: number, options?: BindOptions): Promise<PortInspection>;
54
+ export function loadConfig(path?: string): Promise<PortConfig>;
55
+ export function formatPorts(entries: PortEntry[], options?: { color?: boolean; details?: boolean; changes?: PortChanges | null }): string;
56
+ export function runTui(options?: PortOptions & { interval?: number; color?: ColorMode }): Promise<void>;
package/src/index.js ADDED
@@ -0,0 +1,188 @@
1
+ import { execFile } from 'node:child_process';
2
+ import { promisify } from 'node:util';
3
+ import { setTimeout as delay } from 'node:timers/promises';
4
+
5
+ const run = promisify(execFile);
6
+
7
+ // lsof's field format keeps process names with spaces unambiguous.
8
+ export function parseLsof(output, { all = false } = {}) {
9
+ const entries = [];
10
+ let pid, processName, entry;
11
+ const flush = () => {
12
+ if (!entry?.protocol || !entry.address) return;
13
+ if (!all && entry.protocol === 'TCP' && entry.state !== 'LISTEN') return;
14
+ const match = entry.address.match(/:(\d+)(?:->|$)/);
15
+ if (!match) return;
16
+ entries.push({ protocol: entry.protocol, port: Number(match[1]), address: entry.address, state: entry.state || (entry.protocol === 'UDP' ? 'UNCONN' : ''), pid, process: processName });
17
+ };
18
+ for (const line of output.split(/\r?\n/)) {
19
+ const value = line.slice(1);
20
+ switch (line[0]) {
21
+ case 'p': flush(); entry = undefined; pid = Number(value); processName = ''; break;
22
+ case 'c': processName = value; break;
23
+ case 'f': flush(); entry = {}; break;
24
+ case 'P': if (entry) entry.protocol = value; break;
25
+ case 'n': if (entry) entry.address = value; break;
26
+ case 'T': if (entry && value.startsWith('ST=')) entry.state = value.slice(3); break;
27
+ }
28
+ }
29
+ flush();
30
+ return entries;
31
+ }
32
+
33
+ export function parseNetstat(output, { all = false } = {}) {
34
+ const entries = [];
35
+ for (const line of output.split(/\r?\n/)) {
36
+ const parts = line.trim().split(/\s+/);
37
+ const protocol = parts[0]?.toUpperCase();
38
+ if (protocol !== 'TCP' && protocol !== 'UDP') continue;
39
+ const address = parts[1];
40
+ const match = address?.match(/:(\d+)$/);
41
+ const state = protocol === 'TCP' ? parts[3] : 'UNCONN';
42
+ const pid = Number(protocol === 'TCP' ? parts[4] : parts[3]);
43
+ if (!match || !Number.isInteger(pid) || (!all && protocol === 'TCP' && state !== 'LISTENING')) continue;
44
+ entries.push({ protocol, port: Number(match[1]), address, state: state === 'LISTENING' ? 'LISTEN' : state, pid, process: '' });
45
+ }
46
+ return entries;
47
+ }
48
+
49
+ export async function getPorts({ all = false, protocol, port, pid, process: processFilter, state, sort = 'port', details = false } = {}) {
50
+ if (protocol !== undefined && (typeof protocol !== 'string' || !['TCP', 'UDP'].includes(protocol.toUpperCase()))) throw new TypeError('Protocol must be TCP or UDP.');
51
+ if (port !== undefined && (!Number.isInteger(port) || port < 1 || port > 65535)) throw new RangeError('Port must be an integer from 1 to 65535.');
52
+ if (pid !== undefined && (!Number.isSafeInteger(pid) || pid < 1)) throw new RangeError('PID must be a positive integer.');
53
+ if (!['port', 'protocol', 'pid', 'process', 'state'].includes(sort)) throw new TypeError('Invalid sort field.');
54
+ if (typeof all !== 'boolean' || typeof details !== 'boolean') throw new TypeError('all and details must be booleans.');
55
+ if (processFilter !== undefined && typeof processFilter !== 'string') throw new TypeError('Process filter must be a string.');
56
+ if (state !== undefined && typeof state !== 'string') throw new TypeError('State filter must be a string.');
57
+ let entries;
58
+ if (process.platform === 'win32') {
59
+ const { stdout } = await run('netstat', ['-ano'], { maxBuffer: 16 * 1024 * 1024 });
60
+ entries = parseNetstat(stdout, { all });
61
+ try {
62
+ const { stdout: tasks } = await run('tasklist', ['/FO', 'CSV', '/NH'], { maxBuffer: 16 * 1024 * 1024 });
63
+ const names = new Map();
64
+ for (const line of tasks.split(/\r?\n/)) {
65
+ const match = line.match(/^"((?:[^"]|"")*)","(\d+)"/);
66
+ if (match) names.set(Number(match[2]), match[1].replace(/""/g, '"'));
67
+ }
68
+ for (const entry of entries) entry.process = names.get(entry.pid) || '';
69
+ } catch { /* Process names are optional when tasklist is unavailable. */ }
70
+ } else {
71
+ try {
72
+ const { stdout } = await run('lsof', ['-nP', '-i', '-F', 'pcfPnT'], { maxBuffer: 16 * 1024 * 1024 });
73
+ entries = parseLsof(stdout, { all });
74
+ } catch (error) {
75
+ if (error.code === 1 && !error.stderr) entries = parseLsof(error.stdout || '', { all });
76
+ else if (error.code === 'ENOENT') throw new Error('lsof was not found. Install lsof and try again.');
77
+ else throw error;
78
+ }
79
+ }
80
+ const filtered = entries.filter(entry => (!protocol || entry.protocol === protocol.toUpperCase())
81
+ && (port === undefined || entry.port === port)
82
+ && (pid === undefined || entry.pid === pid)
83
+ && (!processFilter || entry.process.toLowerCase().includes(processFilter.toLowerCase()))
84
+ && (!state || entry.state.toUpperCase() === state.toUpperCase()))
85
+ .sort((a, b) => {
86
+ const left = a[sort];
87
+ const right = b[sort];
88
+ const primary = typeof left === 'number' ? left - right : String(left ?? '').localeCompare(String(right ?? ''), undefined, { sensitivity: 'base' });
89
+ return primary || a.port - b.port || a.protocol.localeCompare(b.protocol) || a.pid - b.pid;
90
+ });
91
+ return details ? addProcessDetails(filtered) : filtered;
92
+ }
93
+
94
+ /** Test whether a port can be bound on a particular local address right now. */
95
+ export async function checkPort(port, { protocol = 'TCP', host = '127.0.0.1' } = {}) {
96
+ if (!Number.isInteger(port) || port < 1 || port > 65535) throw new Error('Port must be an integer from 1 to 65535.');
97
+ if (typeof protocol !== 'string') throw new TypeError('Protocol must be TCP or UDP.');
98
+ const type = protocol.toUpperCase();
99
+ if (!['TCP', 'UDP'].includes(type)) throw new Error('Protocol must be TCP or UDP.');
100
+ if (type === 'TCP') {
101
+ const { createServer } = await import('node:net');
102
+ return new Promise((resolve, reject) => {
103
+ const server = createServer();
104
+ server.once('error', error => error.code === 'EADDRINUSE' ? resolve(false) : reject(error));
105
+ server.listen({ port, host, exclusive: true }, () => server.close(error => error ? reject(error) : resolve(true)));
106
+ });
107
+ }
108
+ const { createSocket } = await import('node:dgram');
109
+ const { isIP } = await import('node:net');
110
+ const socket = createSocket(isIP(host) === 6 ? 'udp6' : 'udp4');
111
+ return new Promise((resolve, reject) => {
112
+ socket.once('error', error => { socket.close(); error.code === 'EADDRINUSE' ? resolve(false) : reject(error); });
113
+ socket.bind({ port, address: host, exclusive: true }, () => socket.close(() => resolve(true)));
114
+ });
115
+ }
116
+
117
+ export async function findPort({ from = 3000, to = 65535, protocol = 'TCP', host = '127.0.0.1' } = {}) {
118
+ if (!Number.isInteger(from) || !Number.isInteger(to) || from < 1 || to > 65535 || from > to) throw new Error('Invalid port range.');
119
+ for (let port = from; port <= to; port++) if (await checkPort(port, { protocol, host })) return port;
120
+ return null;
121
+ }
122
+
123
+ async function addProcessDetails(entries) {
124
+ const ids = [...new Set(entries.map(entry => entry.pid).filter(id => Number.isSafeInteger(id) && id > 0))];
125
+ const details = new Map();
126
+ if (ids.length && process.platform !== 'win32') {
127
+ // One ps invocation avoids spawning a process for every socket.
128
+ try {
129
+ const { stdout } = await run('ps', ['-p', ids.join(','), '-o', 'pid=', '-o', 'user=', '-o', 'args='], { maxBuffer: 16 * 1024 * 1024 });
130
+ for (const line of stdout.split(/\r?\n/)) {
131
+ const match = line.match(/^\s*(\d+)\s+(\S+)\s*(.*)$/);
132
+ if (match) details.set(Number(match[1]), { user: match[2], command: match[3] });
133
+ }
134
+ } catch { /* Process information may be unavailable or the process may have exited. */ }
135
+ } else if (ids.length) {
136
+ try {
137
+ const script = '$ids=@(' + ids.join(',') + '); Get-CimInstance Win32_Process | Where-Object { $ids -contains $_.ProcessId } | ForEach-Object { $owner=Invoke-CimMethod -InputObject $_ -MethodName GetOwner; [PSCustomObject]@{pid=$_.ProcessId;user=$owner.User;command=$_.CommandLine} } | ConvertTo-Json -Compress';
138
+ const { stdout } = await run('powershell.exe', ['-NoProfile', '-NonInteractive', '-Command', script], { maxBuffer: 16 * 1024 * 1024 });
139
+ const result = JSON.parse(stdout || '[]');
140
+ for (const item of Array.isArray(result) ? result : [result]) details.set(item.pid, { user: item.user || '', command: item.command || '' });
141
+ } catch { /* Details are best effort on systems without access to process information. */ }
142
+ }
143
+ return entries.map(entry => ({ ...entry, user: details.get(entry.pid)?.user || '', command: details.get(entry.pid)?.command || '' }));
144
+ }
145
+
146
+ export function diffPorts(previous, current) {
147
+ const key = entry => JSON.stringify([entry.protocol, entry.port, entry.address, entry.state, entry.pid, entry.process]);
148
+ const count = entries => { const map = new Map(); for (const entry of entries) map.set(key(entry), (map.get(key(entry)) || 0) + 1); return map; };
149
+ const difference = (left, right) => {
150
+ const available = count(right);
151
+ return left.filter(entry => { const k = key(entry); const n = available.get(k) || 0; if (!n) return true; available.set(k, n - 1); return false; });
152
+ };
153
+ return { added: difference(current, previous), removed: difference(previous, current) };
154
+ }
155
+
156
+ /** Poll port snapshots until the consumer stops or the signal is aborted. */
157
+ export async function* watchPorts({ interval = 2000, signal, ...options } = {}) {
158
+ if (!Number.isFinite(interval) || interval < 100 || interval > 86400000) throw new RangeError('Interval must be between 100 and 86400000 milliseconds.');
159
+ if (signal !== undefined && (typeof signal !== 'object' || signal === null || typeof signal.addEventListener !== 'function' || typeof signal.aborted !== 'boolean')) throw new TypeError('signal must be an AbortSignal.');
160
+ let previous;
161
+ while (!signal?.aborted) {
162
+ const current = await getPorts(options);
163
+ if (signal?.aborted) return;
164
+ const changes = previous ? diffPorts(previous, current) : { added: [], removed: [] };
165
+ // Retain a private copy so consumer mutations do not alter later comparisons.
166
+ previous = current.map(entry => ({ ...entry }));
167
+ yield { current, ...changes, timestamp: new Date().toISOString() };
168
+ if (signal?.aborted) return;
169
+ try { await delay(interval, undefined, { signal }); }
170
+ catch (error) { if (error.name === 'AbortError' && signal?.aborted) return; throw error; }
171
+ }
172
+ }
173
+
174
+ /** Check a binding and, when occupied, gather process information if available. */
175
+ export async function inspectPort(port, { protocol = 'TCP', host = '127.0.0.1' } = {}) {
176
+ const available = await checkPort(port, { protocol, host });
177
+ protocol = protocol.toUpperCase();
178
+ let conflicts = [];
179
+ if (!available) {
180
+ try { conflicts = await getPorts({ port, protocol, details: true }); }
181
+ catch { /* Binding results are still useful if process enumeration is unavailable. */ }
182
+ }
183
+ return { port, protocol, host, available, conflicts };
184
+ }
185
+
186
+ export { loadConfig } from './config.js';
187
+ export { formatPorts } from './format.js';
188
+ export { runTui } from './tui.js';
package/src/tui.js ADDED
@@ -0,0 +1,149 @@
1
+ import { getPorts } from './index.js';
2
+
3
+ const ESC = '\x1b[';
4
+ const clean = value => String(value ?? '').replace(/[\x00-\x1f\x7f-\x9f]/g, ' ');
5
+ const truncate = (value, width) => {
6
+ const text = clean(value);
7
+ if (width <= 0) return '';
8
+ return text.length <= width ? text : text.slice(0, Math.max(0, width - 1)) + '…';
9
+ };
10
+
11
+ export function renderTui({ entries, selected, protocol, all, query, editing, error, updated, width = 80, height = 24, color = true }) {
12
+ const paint = (code, value) => color ? `${ESC}${code}m${value}${ESC}0m` : value;
13
+ const columns = Math.max(1, width - 1);
14
+ const line = value => truncate(value, columns);
15
+ const pad = (value, size) => truncate(value, size).padEnd(size);
16
+ const current = entries[selected];
17
+ const details = current ? [
18
+ `Address ${clean(current.address)}`,
19
+ `User ${clean(current.user || '-')}`,
20
+ `Command ${clean(current.command || '-')}`,
21
+ ] : ['Select a socket to see its details.'];
22
+ const detailLines = [];
23
+ for (const detail of details) {
24
+ if (columns < 10) { detailLines.push(line(detail)); continue; }
25
+ let remaining = detail;
26
+ while (remaining.length > columns && detailLines.length < 4) {
27
+ detailLines.push(remaining.slice(0, columns));
28
+ remaining = ' ' + remaining.slice(columns);
29
+ }
30
+ detailLines.push(line(remaining));
31
+ }
32
+ const shortcuts = editing
33
+ ? [['Enter', 'Finish search'], ['Esc', 'Finish search'], ['Backspace', 'Delete']]
34
+ : [['↑/↓', 'Select'], ['/', 'Search'], ['p', 'Protocol'], ['a', 'TCP mode'], ['r', 'Refresh'], ['q', 'Quit']];
35
+ const helpLines = [];
36
+ let helpLine = '';
37
+ for (const [key, label] of shortcuts) {
38
+ const item = `[${key}] ${label}`;
39
+ if (helpLine && helpLine.length + 3 + item.length > columns) { helpLines.push(line(helpLine)); helpLine = ''; }
40
+ helpLine += (helpLine ? ' ' : '') + item;
41
+ }
42
+ if (helpLine) helpLines.push(line(helpLine));
43
+ const footer = [
44
+ paint('1;36', line(' DETAILS '.padEnd(columns, '─'))),
45
+ ...detailLines.map(line),
46
+ ...(error ? [paint('31', line(`Error: ${error}`))] : []),
47
+ ...helpLines.map(text => paint('36', text)),
48
+ ];
49
+ const header = [
50
+ paint('1;36', line(' PORTLENSE · LIVE PORT MONITOR '.padEnd(columns, '─'))),
51
+ line(`Protocol: ${protocol || 'ALL'} TCP: ${all ? 'all connections' : 'listening'} Search: ${query || '(none)'}${editing ? ' _' : ''} ${entries.length} sockets ${updated || 'Loading…'}`),
52
+ ];
53
+ const showAddress = columns >= 76;
54
+ const fixed = 2 + 7 + 7 + 13 + 8;
55
+ const remaining = Math.max(4, columns - fixed);
56
+ const processWidth = showAddress ? Math.max(8, Math.min(22, Math.floor(remaining * 0.32))) : remaining;
57
+ const addressWidth = showAddress ? Math.max(0, remaining - processWidth - 1) : 0;
58
+ const formatRow = (marker, port, proto, state, pid, processName, address) => line(
59
+ `${marker} ${pad(port, 7)}${pad(proto, 7)}${pad(state, 13)}${pad(pid, 8)}${pad(processName, processWidth)}${showAddress ? ` ${pad(address, addressWidth)}` : ''}`
60
+ );
61
+ header.push(paint('1', formatRow(' ', 'PORT', 'PROTO', 'STATE', 'PID', 'PROCESS', 'ADDRESS')));
62
+ const availableRows = Math.max(0, height - header.length - footer.length);
63
+ const start = Math.max(0, Math.min(selected - availableRows + 1, Math.max(0, entries.length - availableRows)));
64
+ const rows = [];
65
+ for (let i = start; i < Math.min(entries.length, start + availableRows); i++) {
66
+ const e = entries[i];
67
+ const row = formatRow(i === selected ? '›' : ' ', e.port, e.protocol, e.state || '-', e.pid, e.process || '-', e.address || '-');
68
+ rows.push(i === selected ? paint('7', row.padEnd(columns)) : row);
69
+ }
70
+ if (!entries.length && availableRows) rows.push(line(error ? 'Unable to load ports.' : 'No matching ports.'));
71
+ while (rows.length < availableRows) rows.push('');
72
+ return [...header, ...rows, ...footer].slice(0, Math.max(0, height)).join('\r\n');
73
+ }
74
+
75
+ export async function runTui(options = {}) {
76
+ if (options.interval !== undefined && (!Number.isFinite(options.interval) || options.interval < 100 || options.interval > 86400000)) throw new RangeError('Interval must be between 100 and 86400000 milliseconds.');
77
+ if (!process.stdin.isTTY || !process.stdout.isTTY || typeof process.stdin.setRawMode !== 'function') throw new Error('TUI requires an interactive terminal.');
78
+ const input = process.stdin;
79
+ const output = process.stdout;
80
+ const originalRaw = input.isRaw;
81
+ let entries = [], selected = 0, protocol = options.protocol?.toUpperCase() || '', all = !!options.all;
82
+ let query = options.process || '', editing = false, error = '', updated = '', stopped = false, pending = false, queued = false;
83
+ const color = options.color === 'always' || (options.color !== 'never' && !('NO_COLOR' in process.env));
84
+ const render = () => {
85
+ if (stopped) return;
86
+ output.write(`${ESC}H${ESC}2J${renderTui({ entries, selected, protocol, all, query, editing, error, updated, width: output.columns || 80, height: output.rows || 24, color })}`);
87
+ };
88
+ const refresh = async () => {
89
+ if (pending) { queued = true; return; }
90
+ pending = true;
91
+ try {
92
+ const result = await getPorts({ ...options, protocol: protocol || undefined, all, process: query || undefined, details: true });
93
+ if (!stopped) { entries = result; selected = Math.max(0, Math.min(selected, entries.length - 1)); error = ''; updated = new Date().toLocaleTimeString(); }
94
+ } catch (err) { if (!stopped) error = err.message; }
95
+ finally {
96
+ pending = false;
97
+ if (!stopped) render();
98
+ if (queued && !stopped) { queued = false; void refresh(); }
99
+ }
100
+ };
101
+ await new Promise((resolve, reject) => {
102
+ let timer;
103
+ const cleanup = () => {
104
+ if (stopped) return;
105
+ stopped = true;
106
+ clearInterval(timer);
107
+ input.off('data', onData);
108
+ output.off('resize', render);
109
+ process.off('SIGINT', onSignal);
110
+ process.off('SIGTERM', onSignal);
111
+ try { input.setRawMode(!!originalRaw); input.pause(); output.write(`${ESC}?25h${ESC}?1049l`); } catch { /* Terminal may already be closed. */ }
112
+ };
113
+ const finish = () => { cleanup(); resolve(); };
114
+ const onSignal = () => finish();
115
+ const handleKey = key => {
116
+ if (key === '\u0003') return finish();
117
+ if (editing) {
118
+ if (key === '\r' || key === '\n' || key === '\u001b') editing = false;
119
+ else if (key === '\u007f' || key === '\b') query = query.slice(0, -1);
120
+ else if (!/[\x00-\x1f\x7f-\x9f]/.test(key)) query += key;
121
+ selected = 0;
122
+ render();
123
+ void refresh();
124
+ } else if (key === 'q' || key === 'Q') finish();
125
+ else if (key === '\u001b[A' || key === 'k') { selected = Math.max(0, selected - 1); render(); }
126
+ else if (key === '\u001b[B' || key === 'j') { selected = Math.min(Math.max(0, entries.length - 1), selected + 1); render(); }
127
+ else if (key === '/') { editing = true; render(); }
128
+ else if (key === 'p') { protocol = protocol === '' ? 'TCP' : protocol === 'TCP' ? 'UDP' : ''; selected = 0; void refresh(); }
129
+ else if (key === 'a') { all = !all; selected = 0; void refresh(); }
130
+ else if (key === 'r') void refresh();
131
+ };
132
+ const onData = buffer => {
133
+ const keys = buffer.toString().match(/\x1b\[[AB]|[\s\S]/gu) || [];
134
+ for (const key of keys) { if (stopped) break; handleKey(key); }
135
+ };
136
+ try {
137
+ output.write(`${ESC}?1049h${ESC}?25l`);
138
+ input.setRawMode(true);
139
+ input.resume();
140
+ input.on('data', onData);
141
+ output.on('resize', render);
142
+ process.on('SIGINT', onSignal);
143
+ process.on('SIGTERM', onSignal);
144
+ timer = setInterval(() => void refresh(), options.interval ?? 2000);
145
+ render();
146
+ void refresh();
147
+ } catch (err) { cleanup(); reject(err); }
148
+ });
149
+ }