t0n 0.20260702.0 → 0.20260703.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.
Files changed (2) hide show
  1. package/package.json +3 -2
  2. package/src/port.ts +118 -0
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "t0n",
3
3
  "description": "Collection of elegant typescript resources for web artisans",
4
- "version": "0.20260702.0",
4
+ "version": "0.20260703.0",
5
5
  "type": "module",
6
6
  "main": "./src/index.ts",
7
7
  "files": ["src"],
@@ -10,7 +10,8 @@
10
10
  "./cli": "./src/cli.ts",
11
11
  "./color": "./src/color.ts",
12
12
  "./event": "./src/event.ts",
13
- "./log": "./src/log.ts"
13
+ "./log": "./src/log.ts",
14
+ "./port": "./src/port.ts"
14
15
  },
15
16
  "scripts": {
16
17
  "bench": "tsx tests/benchmark/*.bench.ts"
package/src/port.ts ADDED
@@ -0,0 +1,118 @@
1
+ import net from 'node:net'
2
+ import { exec } from 'node:child_process'
3
+ import { error, warn } from './log'
4
+
5
+ export function withPort(desiredPort: number, cb: (port: number) => void, maxAttempts = 10) {
6
+ getAvailablePort(desiredPort)
7
+ .then(([port, pid]) => {
8
+ if (port !== desiredPort)
9
+ warn(
10
+ `Port ${desiredPort} is in use by ${pid ? 'process '+ pid : 'an unknown process'}, using available port ${port} instead`
11
+ )
12
+
13
+ cb(Number(port))
14
+ }).catch(e => error('Error finding available port:', e))
15
+ }
16
+
17
+ export async function isPortInUse(port: number) {
18
+ return new Promise(resolve => {
19
+ const server = net.createServer()
20
+ .once('error', () => resolve(true))
21
+ .once('listening', () => {
22
+ server.close(() => resolve(false))
23
+ })
24
+ .listen(port)
25
+ })
26
+ }
27
+
28
+ export async function getAvailablePort(startPort: number, maxAttempts = 10) {
29
+ let port = startPort
30
+ let attempts = 0
31
+
32
+ while (attempts < maxAttempts) {
33
+ const inUse = await isPortInUse(port)
34
+
35
+ if (!inUse && attempts) {
36
+ const pid = await getProcessIdUsingPort(startPort)
37
+ return [port, pid]
38
+ }
39
+
40
+ if (!inUse)
41
+ return [port, null]
42
+
43
+ port++
44
+ attempts++
45
+ }
46
+
47
+ throw new Error(`No available ports found after ${maxAttempts} attempts`)
48
+ }
49
+
50
+ export async function getProcessIdUsingPort(port: number): Promise<string | null> {
51
+ const timeoutMs = 250
52
+ const processLookupController = new AbortController()
53
+
54
+ const pidPromise = new Promise<string | null>((resolve) => {
55
+ const handleError = (e: Error) => {
56
+ error('Failed to get process ID for port', port, e)
57
+ resolve(null)
58
+ }
59
+
60
+ try { // Use lsof on Unix-like systems (macOS, Linux)
61
+ if (process.platform !== 'win32') {
62
+ exec(
63
+ `lsof -ti:${port} -sTCP:LISTEN`,
64
+ { signal: processLookupController.signal },
65
+ (error, stdout) => {
66
+ if (error) {
67
+ handleError(error)
68
+ return
69
+ }
70
+ // `-sTCP` will ensure there's only one port, clean up output
71
+ const pid = stdout.trim()
72
+ resolve(pid || null)
73
+ }
74
+ )
75
+ } else { // Use netstat on Windows
76
+ exec(
77
+ `netstat -ano | findstr /C:":${port} " | findstr LISTENING`,
78
+ { signal: processLookupController.signal },
79
+ (error, stdout) => {
80
+ if (error) {
81
+ handleError(error)
82
+ return
83
+ }
84
+ // Clean up output and extract PID
85
+ const cleanOutput = stdout.replace(/\s+/g, ' ').trim()
86
+ if (cleanOutput) {
87
+ const lines = cleanOutput.split('\n')
88
+ const firstLine = lines[0].trim()
89
+ if (firstLine) {
90
+ const parts = firstLine.split(' ')
91
+ const pid = parts[parts.length - 1]
92
+ resolve(pid || null)
93
+ } else {
94
+ resolve(null)
95
+ }
96
+ } else {
97
+ resolve(null)
98
+ }
99
+ }
100
+ )
101
+ }
102
+ } catch (cause) {
103
+ handleError(
104
+ new Error('Unexpected error during process lookup', { cause })
105
+ )
106
+ }
107
+ })
108
+
109
+ const timeoutId = setTimeout(() => {
110
+ processLookupController.abort(
111
+ `PID detection timed out after ${timeoutMs}ms for port ${port}.`
112
+ )
113
+ }, timeoutMs)
114
+
115
+ pidPromise.finally(() => clearTimeout(timeoutId))
116
+
117
+ return pidPromise
118
+ }