t0n 0.20261012.0 → 0.20261018.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.20261018.0",
5
5
  "type": "module",
6
6
  "main": "./src/index.ts",
7
7
  "files": ["src"],
package/src/cli.ts CHANGED
@@ -2,8 +2,6 @@ import chokidar from 'chokidar'
2
2
  import { relative } from 'pathe'
3
3
  import { wait, log, logo, error } from './log'
4
4
 
5
- export type ChokidarEventName = 'add' | 'addDir' | 'change' | 'unlink' | 'unlinkDir'
6
-
7
5
  export function getRuntime() {
8
6
  try {
9
7
  return process?.isBun || typeof Bun !== 'undefined' ? 'bun' : 'node'
@@ -32,12 +30,16 @@ export function shutdown(cb: (signal: string, e: unknown) => void | Promise<void
32
30
  // process.on('exit', down('EXIT'))
33
31
  }
34
32
 
33
+ export type ChokidarEventName = 'add' | 'addDir' | 'change' | 'unlink' | 'unlinkDir'
34
+ export type EventBatch = [ChokidarEventName, string][]
35
35
  export async function watch(
36
- cb: (e: ChokidarEventName | string, file: string) => Promise<void>,
36
+ cb: (e: EventBatch) => Promise<void>,
37
37
  paths: string | string[],
38
38
  root?: string,
39
- ignore?: string | RegExp | ((testString: string) => boolean)
39
+ ignore?: string | RegExp | ((testString: string) => boolean),
40
+ delay?: number
40
41
  ) {
42
+ delay ||= 35
41
43
  const codeWatcher = chokidar.watch(paths, {
42
44
  ignored: ignore ? ignore : /(^|[/\\])\../, // ignore hidden files
43
45
  persistent: true,
@@ -48,16 +50,19 @@ export async function watch(
48
50
  },
49
51
  })
50
52
 
51
- let restartTimeout: NodeJS.Timeout | null = null
53
+
54
+ const queue: EventBatch = []
55
+ let timer: NodeJS.Timeout | undefined
52
56
  const watcher = (e: ChokidarEventName) => async (file: string) => {
53
- log(getAssetChangeMessage(e, file, root))
57
+ log(getAssetChangeMessage(e, file, root))
54
58
 
55
- if (restartTimeout)
56
- clearTimeout(restartTimeout)
59
+ queue.push([e, file])
57
60
 
58
- restartTimeout = setTimeout(async () => {
59
- await cb(e, file)
60
- }, 300)
61
+ clearTimeout(timer)
62
+ timer = setTimeout(async () => {
63
+ await cb(queue)
64
+ queue.length = 0
65
+ }, delay)
61
66
  }
62
67
 
63
68
  codeWatcher.on('change', watcher('change'))
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/log.ts CHANGED
@@ -1,22 +1,53 @@
1
1
  import { blue, bold, gray, green, magenta, red, yellow, white } from './color'
2
2
 
3
+ const _console: Console = { ...console }
4
+
5
+ export type LogLevel = 'none' | 'verbose' | 'info' | 'warning' | 'error'
6
+
7
+ const noop = () => { }
8
+ const byLevel: Record<Exclude<LogLevel, 'none'>, string[]> = {
9
+ verbose: [],
10
+ info: ['trace', 'debug', 'log'],
11
+ warning: ['trace', 'debug', 'log', 'info', 'table', 'dir', 'group', 'groupEnd', 'time', 'timeEnd', 'assert'],
12
+ error: [
13
+ 'trace',
14
+ 'debug',
15
+ 'log',
16
+ 'info',
17
+ 'table',
18
+ 'dir',
19
+ 'group',
20
+ 'groupEnd',
21
+ 'time',
22
+ 'timeEnd',
23
+ 'assert',
24
+ 'warn',
25
+ ],
26
+ }
27
+ export const logLevel = (level: LogLevel = 'verbose') => {
28
+ const keys = Object.keys(console)
29
+ const toDisable = new Set(level === 'none' ? keys : byLevel[level])
30
+
31
+ keys.forEach(method => (console as any)[method] = toDisable.has(method) ? noop : (_console as any)[method])
32
+ }
33
+
3
34
  const _step = (color: Function, ...msg: any[]) => {
4
35
  const length = msg.length
5
36
  if (!length) return
6
37
  if (length < 2)
7
- return console.log(color('⁕') +' '+ msg[0])
38
+ return _console.log(color('⁕') +' '+ msg[0])
8
39
 
9
40
  const total = length - 1
10
41
  for (let i: number = 0; i < length; i++) {
11
42
  switch (i) {
12
43
  case 0:
13
- console.log(color('⁕') + ' ' + msg[i])
44
+ _console.log(color('⁕') + ' ' + msg[i])
14
45
  continue
15
46
  case total:
16
- console.log(` ${gray('⁕')} ${msg[i]}\t`)
47
+ _console.log(` ${gray('⁕')} ${msg[i]}\t`)
17
48
  continue
18
49
  default:
19
- console.log(` ${gray('⁕')} ` + msg[i])
50
+ _console.log(` ${gray('⁕')} ` + msg[i])
20
51
  continue
21
52
  }
22
53
  }
@@ -28,13 +59,13 @@ export const stepWarn = (...msg: any[]) => _step(yellow, ...msg)
28
59
  export const substep = (...msg: any[]) => {
29
60
  const length = msg.length
30
61
  for (let i: number = 0; i < length; i++)
31
- console.log(` ${gray('⁕')} ` + msg[i])
62
+ _console.log(` ${gray('⁕')} ` + msg[i])
32
63
  }
33
64
 
34
65
  export const repeat = (max: number = 1, ...msg: any[]) => {
35
- if (max < 2) return console.log(...msg)
66
+ if (max < 2) return _console.log(...msg)
36
67
  for (let i = 0; i < max; i++)
37
- console.log(...msg)
68
+ _console.log(...msg)
38
69
  }
39
70
  export const ln = (max: number = 1) => repeat(max, '\n')
40
71
  export const rn = (max: number = 1) => repeat(max, '\t')
@@ -68,16 +99,16 @@ function prefixedLog(prefixType: keyof typeof prefixes, ...msg: any[]) {
68
99
  : 'log'
69
100
 
70
101
  const prefix = prefixes[prefixType]
71
- // If there's no message, don't print the prefix but a new line
102
+ // if there's no message, don't print the prefix but a new line
72
103
  if (length === 0) {
73
- console[consoleMethod]('')
104
+ _console[consoleMethod]('')
74
105
  } else {
75
- // Ensure if there's ANSI escape codes it's concatenated into one string.
76
- // Chrome DevTool can only handle color if it's in one string.
106
+ // ensure if there's ANSI escape codes it's concatenated into one string.
107
+ // chrome DevTool can only handle color if it's in one string.
77
108
  if (length === 1 && typeof msg[0] === 'string') {
78
- console[consoleMethod](prefix +' '+ msg[0])
109
+ _console[consoleMethod](prefix +' '+ msg[0])
79
110
  } else {
80
- console[consoleMethod](prefix, ...msg)
111
+ _console[consoleMethod](prefix, ...msg)
81
112
  }
82
113
  }
83
114
  }
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))