t0n 0.20261012.0 → 0.20261016.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/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.20261012.0",
4
+ "version": "0.20261016.0",
5
5
  "type": "module",
6
6
  "main": "./src/index.ts",
7
7
  "files": ["src"],
package/src/event.ts CHANGED
@@ -21,7 +21,6 @@ export const emit = <D = unknown>(
21
21
  ) => emitter.dispatchEvent(new CustomEvent(event, detail !== undefined ? { detail } : undefined))
22
22
 
23
23
 
24
- // Overload tipado para eventos nativos do window
25
24
  export function on<K extends keyof WindowEventMap>(
26
25
  event: K,
27
26
  callback: (e: WindowEventMap[K]) => void
package/src/func.ts ADDED
@@ -0,0 +1,5 @@
1
+ export function isAsync(value: any): value is Promise<any> {
2
+ return value && typeof value.then === 'function'
3
+ }
4
+
5
+ export const isPromise = isAsync
package/src/index.ts CHANGED
@@ -7,6 +7,7 @@ export * from './enum'
7
7
  export * from './env'
8
8
  export * from './envir'
9
9
  export * from './event'
10
+ export * from './func'
10
11
  export * from './id'
11
12
  export * from './import'
12
13
  export * from './json'
package/src/port.ts CHANGED
@@ -1,50 +1,65 @@
1
- import net from 'node:net'
2
- import { exec } from 'node:child_process'
1
+ import { exec, execFile } from 'node:child_process'
3
2
  import { error, warn } from './log'
4
3
 
5
- export function withPort(desiredPort: number, cb: (port: number) => void, maxAttempts = 10) {
6
- getAvailablePort(desiredPort)
4
+ export function withPort(
5
+ desiredPort: number,
6
+ cb: (port: number) => void,
7
+ maxAttempts = 10,
8
+ ) {
9
+ getAvailablePort(desiredPort, maxAttempts)
7
10
  .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
- )
11
+ if (port !== desiredPort) {
12
+ warn(`Port ${desiredPort} is in use by ${
13
+ pid ? `process ${pid}` : 'an unknown process'
14
+ }, using available port ${port} instead`)
15
+ }
12
16
 
13
- cb(Number(port))
14
- }).catch(e => error('Error finding available port:', e))
17
+ cb(port)
18
+ })
19
+ .catch(e => error('Error finding available port:', e))
15
20
  }
16
21
 
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)
22
+ export async function isPortInUse(port: number): Promise<boolean> {
23
+ return new Promise((resolve, reject) => {
24
+ execFile(
25
+ 'lsof',
26
+ ['-nP', `-iTCP:${port}`, '-sTCP:LISTEN', '-t'],
27
+ { timeout: 1000 },
28
+ (err, stdout) => {
29
+ if (stdout.trim())
30
+ return resolve(true)
31
+
32
+ if (err && 'code' in err && err.code === 1)
33
+ return resolve(false)
34
+
35
+ if (err)
36
+ return reject(err)
37
+
38
+ resolve(false)
39
+ },
40
+ )
25
41
  })
26
42
  }
27
43
 
28
- export async function getAvailablePort(startPort: number, maxAttempts = 10) {
29
- let port = startPort
30
- let attempts = 0
44
+ export async function getAvailablePort(
45
+ startPort: number,
46
+ maxAttempts = 10,
47
+ ): Promise<[number, string | null]> {
48
+ for (let i = 0; i < maxAttempts; i++) {
49
+ const port = startPort + i
31
50
 
32
- while (attempts < maxAttempts) {
33
- const inUse = await isPortInUse(port)
51
+ if (!await isPortInUse(port)) {
52
+ const pid = port === startPort
53
+ ? null
54
+ : await getProcessIdUsingPort(startPort)
34
55
 
35
- if (!inUse && attempts) {
36
- const pid = await getProcessIdUsingPort(startPort)
37
56
  return [port, pid]
38
57
  }
39
-
40
- if (!inUse)
41
- return [port, null]
42
-
43
- port++
44
- attempts++
45
58
  }
46
59
 
47
- throw new Error(`No available ports found after ${maxAttempts} attempts`)
60
+ throw new Error(
61
+ `No available ports found after ${maxAttempts} attempts`,
62
+ )
48
63
  }
49
64
 
50
65
  export async function getProcessIdUsingPort(port: number): Promise<string | null> {
@@ -53,35 +68,32 @@ export async function getProcessIdUsingPort(port: number): Promise<string | null
53
68
 
54
69
  const pidPromise = new Promise<string | null>((resolve) => {
55
70
  const handleError = (e: Error) => {
71
+ if ((e as any).name === 'AbortError')
72
+ return resolve(null)
73
+
56
74
  error('Failed to get process ID for port', port, e)
57
75
  resolve(null)
58
76
  }
59
77
 
60
- try { // Use lsof on Unix-like systems (macOS, Linux)
78
+ try { // use lsof on Unix-like systems (macOS, Linux)
61
79
  if (process.platform !== 'win32') {
62
80
  exec(
63
- `lsof -ti:${port} -sTCP:LISTEN`,
64
- { signal: processLookupController.signal },
81
+ `lsof -nP -iTCP:${port} -sTCP:LISTEN -t`,
82
+ { signal: processLookupController.signal, timeout: 2000 },
65
83
  (error, stdout) => {
66
- if (error) {
67
- handleError(error)
68
- return
69
- }
84
+ if (error) return handleError(error)
70
85
  // `-sTCP` will ensure there's only one port, clean up output
71
86
  const pid = stdout.trim()
72
87
  resolve(pid || null)
73
88
  }
74
89
  )
75
- } else { // Use netstat on Windows
90
+ } else { // use netstat on Windows
76
91
  exec(
77
92
  `netstat -ano | findstr /C:":${port} " | findstr LISTENING`,
78
93
  { signal: processLookupController.signal },
79
94
  (error, stdout) => {
80
- if (error) {
81
- handleError(error)
82
- return
83
- }
84
- // Clean up output and extract PID
95
+ if (error) return handleError(error)
96
+ // clean up output and extract PID
85
97
  const cleanOutput = stdout.replace(/\s+/g, ' ').trim()
86
98
  if (cleanOutput) {
87
99
  const lines = cleanOutput.split('\n')
@@ -100,16 +112,12 @@ export async function getProcessIdUsingPort(port: number): Promise<string | null
100
112
  )
101
113
  }
102
114
  } catch (cause) {
103
- handleError(
104
- new Error('Unexpected error during process lookup', { cause })
105
- )
115
+ handleError(new Error('Unexpected error during process lookup', { cause }))
106
116
  }
107
117
  })
108
118
 
109
119
  const timeoutId = setTimeout(() => {
110
- processLookupController.abort(
111
- `PID detection timed out after ${timeoutMs}ms for port ${port}.`
112
- )
120
+ processLookupController.abort(`PID detection timed out after ${timeoutMs}ms for port ${port}.`)
113
121
  }, timeoutMs)
114
122
 
115
123
  pidPromise.finally(() => clearTimeout(timeoutId))