@fuzdev/fuz_util 0.45.2 → 0.46.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/dist/array.d.ts +1 -1
- package/dist/array.js +1 -1
- package/dist/async.d.ts +18 -0
- package/dist/async.d.ts.map +1 -1
- package/dist/async.js +63 -3
- package/dist/dom.d.ts +2 -2
- package/dist/dom.js +2 -2
- package/dist/fetch.d.ts +1 -1
- package/dist/fetch.js +1 -1
- package/dist/git.d.ts.map +1 -1
- package/dist/git.js +10 -10
- package/dist/path.d.ts +1 -1
- package/dist/path.js +2 -2
- package/dist/print.d.ts +1 -1
- package/dist/print.js +1 -1
- package/dist/process.d.ts +303 -43
- package/dist/process.d.ts.map +1 -1
- package/dist/process.js +475 -108
- package/dist/random.d.ts +1 -1
- package/dist/random.js +1 -1
- package/dist/regexp.d.ts +1 -1
- package/dist/regexp.js +1 -1
- package/package.json +6 -5
- package/src/lib/array.ts +1 -1
- package/src/lib/async.ts +72 -3
- package/src/lib/dom.ts +2 -2
- package/src/lib/fetch.ts +1 -1
- package/src/lib/git.ts +20 -10
- package/src/lib/path.ts +2 -2
- package/src/lib/print.ts +1 -1
- package/src/lib/process.ts +681 -135
- package/src/lib/random.ts +1 -1
- package/src/lib/regexp.ts +1 -1
package/src/lib/process.ts
CHANGED
|
@@ -7,215 +7,761 @@ import {styleText as st} from 'node:util';
|
|
|
7
7
|
|
|
8
8
|
import {Logger} from './log.js';
|
|
9
9
|
import {print_error, print_key_value} from './print.js';
|
|
10
|
-
import
|
|
10
|
+
import {noop} from './function.js';
|
|
11
11
|
|
|
12
12
|
const log = new Logger('process');
|
|
13
13
|
|
|
14
|
-
|
|
14
|
+
//
|
|
15
|
+
// Spawn Result Types
|
|
16
|
+
//
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* Spawn failed before the process could run.
|
|
20
|
+
*
|
|
21
|
+
* @example ENOENT when command not found
|
|
22
|
+
*/
|
|
23
|
+
export interface SpawnResultError {
|
|
24
|
+
ok: false;
|
|
15
25
|
child: ChildProcess;
|
|
16
|
-
|
|
26
|
+
error: Error;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* Process ran and exited with a code.
|
|
31
|
+
* `ok` is true when `code` is 0.
|
|
32
|
+
*/
|
|
33
|
+
export interface SpawnResultExited {
|
|
34
|
+
ok: boolean;
|
|
35
|
+
child: ChildProcess;
|
|
36
|
+
code: number;
|
|
37
|
+
signal: null;
|
|
17
38
|
}
|
|
18
39
|
|
|
19
|
-
|
|
40
|
+
/**
|
|
41
|
+
* Process was terminated by a signal (e.g., SIGTERM, SIGKILL).
|
|
42
|
+
*/
|
|
43
|
+
export interface SpawnResultSignaled {
|
|
44
|
+
ok: false;
|
|
20
45
|
child: ChildProcess;
|
|
21
|
-
|
|
22
|
-
|
|
46
|
+
code: null;
|
|
47
|
+
signal: NodeJS.Signals;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/**
|
|
51
|
+
* Discriminated union representing all possible spawn outcomes.
|
|
52
|
+
* Use type guards `spawn_result_is_error`, `spawn_result_is_signaled`,
|
|
53
|
+
* and `spawn_result_is_exited` to narrow the type.
|
|
54
|
+
*/
|
|
55
|
+
export type SpawnResult = SpawnResultError | SpawnResultExited | SpawnResultSignaled;
|
|
56
|
+
|
|
57
|
+
//
|
|
58
|
+
// Type Guards
|
|
59
|
+
//
|
|
60
|
+
|
|
61
|
+
/**
|
|
62
|
+
* Type guard for spawn errors (process failed to start).
|
|
63
|
+
*/
|
|
64
|
+
export const spawn_result_is_error = (result: SpawnResult): result is SpawnResultError =>
|
|
65
|
+
'error' in result;
|
|
66
|
+
|
|
67
|
+
/**
|
|
68
|
+
* Type guard for signal termination.
|
|
69
|
+
*/
|
|
70
|
+
export const spawn_result_is_signaled = (result: SpawnResult): result is SpawnResultSignaled =>
|
|
71
|
+
'signal' in result && result.signal !== null;
|
|
72
|
+
|
|
73
|
+
/**
|
|
74
|
+
* Type guard for normal exit with code.
|
|
75
|
+
*/
|
|
76
|
+
export const spawn_result_is_exited = (result: SpawnResult): result is SpawnResultExited =>
|
|
77
|
+
'code' in result && result.code !== null;
|
|
78
|
+
|
|
79
|
+
//
|
|
80
|
+
// Spawn Options
|
|
81
|
+
//
|
|
82
|
+
|
|
83
|
+
/**
|
|
84
|
+
* Options for spawning processes, extending Node's `SpawnOptions`.
|
|
85
|
+
*/
|
|
86
|
+
export interface SpawnProcessOptions extends SpawnOptions {
|
|
87
|
+
/**
|
|
88
|
+
* AbortSignal to cancel the process.
|
|
89
|
+
* When aborted, sends SIGTERM to the child.
|
|
90
|
+
*/
|
|
91
|
+
signal?: AbortSignal;
|
|
92
|
+
/**
|
|
93
|
+
* Timeout in milliseconds. Must be non-negative.
|
|
94
|
+
* Sends SIGTERM when exceeded. A value of 0 triggers immediate SIGTERM.
|
|
95
|
+
*/
|
|
96
|
+
timeout_ms?: number;
|
|
23
97
|
}
|
|
24
98
|
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
99
|
+
/**
|
|
100
|
+
* Options for killing processes.
|
|
101
|
+
*/
|
|
102
|
+
export interface DespawnOptions {
|
|
103
|
+
/**
|
|
104
|
+
* Signal to send.
|
|
105
|
+
* @default 'SIGTERM'
|
|
106
|
+
*/
|
|
107
|
+
signal?: NodeJS.Signals;
|
|
108
|
+
/**
|
|
109
|
+
* Timeout in ms before escalating to SIGKILL. Must be non-negative.
|
|
110
|
+
* Useful for processes that may ignore SIGTERM. A value of 0 triggers immediate SIGKILL escalation.
|
|
111
|
+
*/
|
|
112
|
+
timeout_ms?: number;
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
//
|
|
116
|
+
// Process Handle Types
|
|
117
|
+
//
|
|
28
118
|
|
|
29
119
|
/**
|
|
30
|
-
*
|
|
31
|
-
* intended for commands that have an end, not long running-processes like watchers.
|
|
32
|
-
* Any more advanced usage should use `spawn_process` directly for access to the `child` process.
|
|
120
|
+
* Handle for a spawned process with access to the child and completion promise.
|
|
33
121
|
*/
|
|
34
|
-
export
|
|
35
|
-
|
|
122
|
+
export interface SpawnedProcess {
|
|
123
|
+
/** The underlying Node.js ChildProcess */
|
|
124
|
+
child: ChildProcess;
|
|
125
|
+
/** Resolves when the process exits */
|
|
126
|
+
closed: Promise<SpawnResult>;
|
|
127
|
+
}
|
|
36
128
|
|
|
129
|
+
/**
|
|
130
|
+
* Result of `spawn_out` with captured output streams.
|
|
131
|
+
*/
|
|
37
132
|
export interface SpawnedOut {
|
|
38
133
|
result: SpawnResult;
|
|
134
|
+
/** Captured stdout, or null if stream unavailable */
|
|
39
135
|
stdout: string | null;
|
|
136
|
+
/** Captured stderr, or null if stream unavailable */
|
|
40
137
|
stderr: string | null;
|
|
41
138
|
}
|
|
42
139
|
|
|
140
|
+
//
|
|
141
|
+
// Internal Helpers
|
|
142
|
+
//
|
|
143
|
+
|
|
43
144
|
/**
|
|
44
|
-
*
|
|
145
|
+
* Creates a promise that resolves when the child process closes.
|
|
146
|
+
*
|
|
147
|
+
* Handles both 'error' and 'close' events with deduplication because Node.js
|
|
148
|
+
* can emit both for certain failures (e.g., spawn ENOENT emits 'error' then 'close').
|
|
149
|
+
* The `resolved` flag ensures we only resolve once with the first event's data.
|
|
45
150
|
*/
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
151
|
+
const create_closed_promise = (child: ChildProcess): Promise<SpawnResult> => {
|
|
152
|
+
let resolve: (v: SpawnResult) => void;
|
|
153
|
+
let resolved = false;
|
|
154
|
+
const closed: Promise<SpawnResult> = new Promise((r) => (resolve = r));
|
|
155
|
+
|
|
156
|
+
child.once('error', (err) => {
|
|
157
|
+
if (resolved) return;
|
|
158
|
+
resolved = true;
|
|
159
|
+
resolve({ok: false, child, error: err});
|
|
55
160
|
});
|
|
56
|
-
|
|
57
|
-
child.
|
|
58
|
-
|
|
161
|
+
|
|
162
|
+
child.once('close', (code, signal) => {
|
|
163
|
+
if (resolved) return;
|
|
164
|
+
resolved = true;
|
|
165
|
+
if (signal !== null) {
|
|
166
|
+
resolve({ok: false, child, code: null, signal});
|
|
167
|
+
} else {
|
|
168
|
+
resolve({ok: code === 0, child, code: code ?? 0, signal: null});
|
|
169
|
+
}
|
|
59
170
|
});
|
|
60
|
-
|
|
61
|
-
return
|
|
171
|
+
|
|
172
|
+
return closed;
|
|
62
173
|
};
|
|
63
174
|
|
|
64
175
|
/**
|
|
65
|
-
*
|
|
66
|
-
*
|
|
67
|
-
* If you only need `closed`, prefer the shorthand function `spawn`.
|
|
68
|
-
* @mutates global_spawn calls `register_global_spawn()` which adds to the module-level Set
|
|
176
|
+
* Sets up abort signal handling for a child process.
|
|
177
|
+
* @returns cleanup function to remove the listener
|
|
69
178
|
*/
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
const unregister = register_global_spawn(child);
|
|
79
|
-
child.once('close', (code, signal) => {
|
|
80
|
-
unregister();
|
|
81
|
-
resolve(code ? {ok: false, child, code, signal} : {ok: true, child, code, signal});
|
|
82
|
-
});
|
|
83
|
-
return {closed, child};
|
|
179
|
+
const setup_abort_signal = (child: ChildProcess, signal: AbortSignal): (() => void) => {
|
|
180
|
+
if (signal.aborted) {
|
|
181
|
+
child.kill();
|
|
182
|
+
return noop;
|
|
183
|
+
}
|
|
184
|
+
const on_abort = () => child.kill();
|
|
185
|
+
signal.addEventListener('abort', on_abort, {once: true});
|
|
186
|
+
return () => signal.removeEventListener('abort', on_abort);
|
|
84
187
|
};
|
|
85
188
|
|
|
86
|
-
|
|
87
|
-
|
|
189
|
+
/**
|
|
190
|
+
* Validates timeout_ms option.
|
|
191
|
+
* @throws if timeout_ms is negative
|
|
192
|
+
*/
|
|
193
|
+
const validate_timeout_ms = (timeout_ms: number | undefined): void => {
|
|
194
|
+
if (timeout_ms !== undefined && timeout_ms < 0) {
|
|
195
|
+
throw new Error(`timeout_ms must be non-negative, got ${timeout_ms}`);
|
|
196
|
+
}
|
|
197
|
+
};
|
|
88
198
|
|
|
89
199
|
/**
|
|
90
|
-
*
|
|
91
|
-
*
|
|
200
|
+
* Sets up timeout handling for a child process.
|
|
201
|
+
* Note: timeout_ms of 0 triggers immediate SIGTERM (use with caution).
|
|
202
|
+
* @returns cleanup function to clear the timeout
|
|
92
203
|
*/
|
|
93
|
-
|
|
204
|
+
const setup_timeout = (child: ChildProcess, timeout_ms: number): (() => void) => {
|
|
205
|
+
const timeout_id = setTimeout(() => child.kill('SIGTERM'), timeout_ms);
|
|
206
|
+
return () => clearTimeout(timeout_id);
|
|
207
|
+
};
|
|
208
|
+
|
|
209
|
+
//
|
|
210
|
+
// Process Registry
|
|
211
|
+
//
|
|
94
212
|
|
|
95
213
|
/**
|
|
96
|
-
*
|
|
97
|
-
*
|
|
98
|
-
*
|
|
99
|
-
*
|
|
214
|
+
* Manages a collection of spawned processes for lifecycle tracking and cleanup.
|
|
215
|
+
*
|
|
216
|
+
* The default instance `process_registry_default` is used by module-level functions.
|
|
217
|
+
* Create separate instances for isolated process groups or testing.
|
|
218
|
+
*
|
|
219
|
+
* @example
|
|
220
|
+
* ```ts
|
|
221
|
+
* // Use default registry via module functions
|
|
222
|
+
* const result = await spawn('echo', ['hello']);
|
|
223
|
+
*
|
|
224
|
+
* // Or create isolated registry for testing
|
|
225
|
+
* const registry = new ProcessRegistry();
|
|
226
|
+
* const {child, closed} = registry.spawn('node', ['server.js']);
|
|
227
|
+
* await registry.despawn_all();
|
|
228
|
+
* ```
|
|
100
229
|
*/
|
|
101
|
-
export
|
|
102
|
-
|
|
103
|
-
|
|
230
|
+
export class ProcessRegistry {
|
|
231
|
+
/** All currently tracked child processes */
|
|
232
|
+
readonly processes: Set<ChildProcess> = new Set();
|
|
233
|
+
|
|
234
|
+
#error_handler: ((err: Error, origin: NodeJS.UncaughtExceptionOrigin) => void) | null = null;
|
|
235
|
+
|
|
236
|
+
/**
|
|
237
|
+
* Spawns a process and tracks it in this registry.
|
|
238
|
+
* The process is automatically unregistered when it exits.
|
|
239
|
+
*
|
|
240
|
+
* @param command - The command to run
|
|
241
|
+
* @param args - Arguments to pass to the command
|
|
242
|
+
* @param options - Spawn options including `signal` and `timeout_ms`
|
|
243
|
+
* @returns Handle with `child` process and `closed` promise
|
|
244
|
+
*/
|
|
245
|
+
spawn(
|
|
246
|
+
command: string,
|
|
247
|
+
args: ReadonlyArray<string> = [],
|
|
248
|
+
options?: SpawnProcessOptions,
|
|
249
|
+
): SpawnedProcess {
|
|
250
|
+
const {signal, timeout_ms, ...spawn_options} = options ?? {};
|
|
251
|
+
validate_timeout_ms(timeout_ms);
|
|
252
|
+
const child = spawn_child_process(command, args, {stdio: 'inherit', ...spawn_options});
|
|
253
|
+
|
|
254
|
+
this.processes.add(child);
|
|
255
|
+
const closed = create_closed_promise(child);
|
|
256
|
+
|
|
257
|
+
let cleanup_abort: (() => void) | undefined;
|
|
258
|
+
if (signal) {
|
|
259
|
+
cleanup_abort = setup_abort_signal(child, signal);
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
let cleanup_timeout: (() => void) | undefined;
|
|
263
|
+
if (timeout_ms !== undefined) {
|
|
264
|
+
cleanup_timeout = setup_timeout(child, timeout_ms);
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
void closed.then(() => {
|
|
268
|
+
this.processes.delete(child);
|
|
269
|
+
cleanup_abort?.();
|
|
270
|
+
cleanup_timeout?.();
|
|
271
|
+
});
|
|
272
|
+
|
|
273
|
+
return {child, closed};
|
|
104
274
|
}
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
275
|
+
|
|
276
|
+
/**
|
|
277
|
+
* Spawns a process and captures stdout/stderr as strings.
|
|
278
|
+
* Sets `stdio: 'pipe'` automatically.
|
|
279
|
+
*
|
|
280
|
+
* @param command - The command to run
|
|
281
|
+
* @param args - Arguments to pass to the command
|
|
282
|
+
* @param options - Spawn options
|
|
283
|
+
* @returns Result with captured `stdout` and `stderr`.
|
|
284
|
+
* - `null` means spawn failed (ENOENT, etc.) or stream was unavailable
|
|
285
|
+
* - `''` (empty string) means process ran but produced no output
|
|
286
|
+
* - non-empty string contains the captured output
|
|
287
|
+
*/
|
|
288
|
+
async spawn_out(
|
|
289
|
+
command: string,
|
|
290
|
+
args: ReadonlyArray<string> = [],
|
|
291
|
+
options?: SpawnProcessOptions,
|
|
292
|
+
): Promise<SpawnedOut> {
|
|
293
|
+
const {child, closed} = this.spawn(command, args, {...options, stdio: 'pipe'});
|
|
294
|
+
const stdout_chunks: Array<string> = [];
|
|
295
|
+
const stderr_chunks: Array<string> = [];
|
|
296
|
+
// Track whether streams were available (not null)
|
|
297
|
+
const stdout_available = child.stdout !== null;
|
|
298
|
+
const stderr_available = child.stderr !== null;
|
|
299
|
+
const on_stdout = (data: Buffer): void => {
|
|
300
|
+
stdout_chunks.push(data.toString());
|
|
301
|
+
};
|
|
302
|
+
const on_stderr = (data: Buffer): void => {
|
|
303
|
+
stderr_chunks.push(data.toString());
|
|
304
|
+
};
|
|
305
|
+
child.stdout?.on('data', on_stdout);
|
|
306
|
+
child.stderr?.on('data', on_stderr);
|
|
307
|
+
const result = await closed;
|
|
308
|
+
// Clean up listeners explicitly
|
|
309
|
+
child.stdout?.off('data', on_stdout);
|
|
310
|
+
child.stderr?.off('data', on_stderr);
|
|
311
|
+
// If spawn failed (error result), streams are meaningless - return null
|
|
312
|
+
// Otherwise: '' = available but empty, string = has content
|
|
313
|
+
const spawn_failed = spawn_result_is_error(result);
|
|
314
|
+
const stdout = spawn_failed || !stdout_available ? null : stdout_chunks.join('');
|
|
315
|
+
const stderr = spawn_failed || !stderr_available ? null : stderr_chunks.join('');
|
|
316
|
+
return {result, stdout, stderr};
|
|
317
|
+
}
|
|
318
|
+
|
|
319
|
+
/**
|
|
320
|
+
* Kills a child process and waits for it to exit.
|
|
321
|
+
*
|
|
322
|
+
* @param child - The child process to kill
|
|
323
|
+
* @param options - Kill options including signal and timeout
|
|
324
|
+
* @returns The spawn result after the process exits
|
|
325
|
+
*/
|
|
326
|
+
async despawn(child: ChildProcess, options?: DespawnOptions): Promise<SpawnResult> {
|
|
327
|
+
const {signal = 'SIGTERM', timeout_ms} = options ?? {};
|
|
328
|
+
validate_timeout_ms(timeout_ms);
|
|
329
|
+
|
|
330
|
+
// Already exited with code
|
|
331
|
+
if (child.exitCode !== null) {
|
|
332
|
+
return {
|
|
333
|
+
ok: child.exitCode === 0,
|
|
334
|
+
child,
|
|
335
|
+
code: child.exitCode,
|
|
336
|
+
signal: null,
|
|
337
|
+
};
|
|
109
338
|
}
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
339
|
+
// Already terminated by signal
|
|
340
|
+
if (child.signalCode !== null) {
|
|
341
|
+
return {
|
|
342
|
+
ok: false,
|
|
343
|
+
child,
|
|
344
|
+
code: null,
|
|
345
|
+
signal: child.signalCode,
|
|
346
|
+
};
|
|
347
|
+
}
|
|
348
|
+
|
|
349
|
+
log.debug('despawning', print_child_process(child));
|
|
350
|
+
const closed = create_closed_promise(child);
|
|
351
|
+
|
|
352
|
+
// Escalate to SIGKILL after timeout
|
|
353
|
+
if (timeout_ms !== undefined) {
|
|
354
|
+
const timeout_id = setTimeout(() => child.kill('SIGKILL'), timeout_ms);
|
|
355
|
+
void closed.then(() => clearTimeout(timeout_id));
|
|
356
|
+
}
|
|
357
|
+
|
|
358
|
+
child.kill(signal);
|
|
359
|
+
return closed;
|
|
360
|
+
}
|
|
361
|
+
|
|
362
|
+
/**
|
|
363
|
+
* Kills all processes in this registry.
|
|
364
|
+
*
|
|
365
|
+
* @param options - Kill options applied to all processes
|
|
366
|
+
* @returns Array of spawn results
|
|
367
|
+
*/
|
|
368
|
+
async despawn_all(options?: DespawnOptions): Promise<Array<SpawnResult>> {
|
|
369
|
+
return Promise.all([...this.processes].map((child) => this.despawn(child, options)));
|
|
370
|
+
}
|
|
371
|
+
|
|
372
|
+
/**
|
|
373
|
+
* Attaches an `uncaughtException` handler that kills all processes before exiting.
|
|
374
|
+
* Prevents zombie processes when the parent crashes.
|
|
375
|
+
*
|
|
376
|
+
* By default uses SIGKILL for immediate termination. Set `graceful_timeout_ms`
|
|
377
|
+
* to attempt SIGTERM first (allowing processes to clean up) before escalating
|
|
378
|
+
* to SIGKILL after the timeout.
|
|
379
|
+
*
|
|
380
|
+
* Note: Node's uncaughtException handler cannot await async operations, so
|
|
381
|
+
* graceful shutdown uses a blocking busy-wait. This may not be sufficient
|
|
382
|
+
* for processes that need significant cleanup time.
|
|
383
|
+
*
|
|
384
|
+
* @param options - Configuration options
|
|
385
|
+
* @param options.to_error_label - Customize error label, return `null` for default
|
|
386
|
+
* @param options.map_error_text - Customize error text, return `''` to silence
|
|
387
|
+
* @param options.handle_error - Called after cleanup, defaults to `process.exit(1)`
|
|
388
|
+
* @param options.graceful_timeout_ms - If set, sends SIGTERM first and waits this
|
|
389
|
+
* many ms before SIGKILL. Recommended: 100-500ms. If null/undefined, uses
|
|
390
|
+
* immediate SIGKILL (default).
|
|
391
|
+
* @returns Cleanup function to remove the handler
|
|
392
|
+
*/
|
|
393
|
+
attach_error_handler(options?: {
|
|
394
|
+
to_error_label?: (err: Error, origin: NodeJS.UncaughtExceptionOrigin) => string | null;
|
|
395
|
+
map_error_text?: (err: Error, origin: NodeJS.UncaughtExceptionOrigin) => string | null;
|
|
396
|
+
handle_error?: (err: Error, origin: NodeJS.UncaughtExceptionOrigin) => void;
|
|
397
|
+
graceful_timeout_ms?: number | null;
|
|
398
|
+
}): () => void {
|
|
399
|
+
if (this.#error_handler) {
|
|
400
|
+
throw new Error('Error handler already attached to this registry');
|
|
401
|
+
}
|
|
402
|
+
|
|
403
|
+
const {
|
|
404
|
+
to_error_label,
|
|
405
|
+
map_error_text,
|
|
406
|
+
handle_error = () => process.exit(1),
|
|
407
|
+
graceful_timeout_ms,
|
|
408
|
+
} = options ?? {};
|
|
409
|
+
|
|
410
|
+
this.#error_handler = (err, origin): void => {
|
|
411
|
+
const label = to_error_label?.(err, origin) ?? origin;
|
|
412
|
+
if (label) {
|
|
413
|
+
const error_text = map_error_text?.(err, origin) ?? print_error(err);
|
|
414
|
+
if (error_text) {
|
|
415
|
+
new Logger(label).error(error_text);
|
|
416
|
+
}
|
|
417
|
+
}
|
|
418
|
+
|
|
419
|
+
if (graceful_timeout_ms != null && graceful_timeout_ms > 0) {
|
|
420
|
+
// Attempt graceful shutdown with SIGTERM first
|
|
421
|
+
for (const child of this.processes) {
|
|
422
|
+
child.kill('SIGTERM');
|
|
423
|
+
}
|
|
424
|
+
// Busy-wait (blocking) - only option in sync handler.
|
|
425
|
+
// Warning: This will peg the CPU during the wait period.
|
|
426
|
+
const deadline = Date.now() + graceful_timeout_ms;
|
|
427
|
+
while (Date.now() < deadline) {
|
|
428
|
+
// spin
|
|
429
|
+
}
|
|
430
|
+
}
|
|
431
|
+
|
|
432
|
+
// Force kill all (including any that survived SIGTERM)
|
|
433
|
+
for (const child of this.processes) {
|
|
434
|
+
child.kill('SIGKILL');
|
|
435
|
+
}
|
|
436
|
+
this.processes.clear();
|
|
437
|
+
handle_error(err, origin);
|
|
438
|
+
};
|
|
439
|
+
|
|
440
|
+
process.on('uncaughtException', this.#error_handler);
|
|
441
|
+
|
|
442
|
+
return () => {
|
|
443
|
+
if (this.#error_handler) {
|
|
444
|
+
process.off('uncaughtException', this.#error_handler);
|
|
445
|
+
this.#error_handler = null;
|
|
446
|
+
}
|
|
447
|
+
};
|
|
448
|
+
}
|
|
449
|
+
}
|
|
450
|
+
|
|
451
|
+
//
|
|
452
|
+
// Default Registry
|
|
453
|
+
//
|
|
113
454
|
|
|
114
455
|
/**
|
|
115
|
-
*
|
|
456
|
+
* Default process registry used by module-level spawn functions.
|
|
457
|
+
* For testing or isolated process groups, create a new `ProcessRegistry` instance.
|
|
116
458
|
*/
|
|
117
|
-
export const
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
resolve(code ? {ok: false, child, code, signal} : {ok: true, child, code, signal});
|
|
123
|
-
});
|
|
124
|
-
child.kill();
|
|
125
|
-
return closed;
|
|
126
|
-
};
|
|
459
|
+
export const process_registry_default = new ProcessRegistry();
|
|
460
|
+
|
|
461
|
+
//
|
|
462
|
+
// Module-Level Spawn Functions
|
|
463
|
+
//
|
|
127
464
|
|
|
128
465
|
/**
|
|
129
|
-
*
|
|
130
|
-
*
|
|
466
|
+
* Spawns a process with graceful shutdown behavior.
|
|
467
|
+
* Returns a handle with access to the `child` process and `closed` promise.
|
|
468
|
+
*
|
|
469
|
+
* @example
|
|
470
|
+
* ```ts
|
|
471
|
+
* const {child, closed} = spawn_process('node', ['server.js']);
|
|
472
|
+
* // Later...
|
|
473
|
+
* child.kill();
|
|
474
|
+
* const result = await closed;
|
|
475
|
+
* ```
|
|
131
476
|
*/
|
|
132
|
-
export const
|
|
133
|
-
|
|
477
|
+
export const spawn_process = (
|
|
478
|
+
command: string,
|
|
479
|
+
args: ReadonlyArray<string> = [],
|
|
480
|
+
options?: SpawnProcessOptions,
|
|
481
|
+
): SpawnedProcess => process_registry_default.spawn(command, args, options);
|
|
134
482
|
|
|
135
483
|
/**
|
|
136
|
-
*
|
|
137
|
-
*
|
|
138
|
-
*
|
|
139
|
-
* @
|
|
484
|
+
* Spawns a process and returns a promise that resolves when it exits.
|
|
485
|
+
* Use this for commands that complete (not long-running processes).
|
|
486
|
+
*
|
|
487
|
+
* @example
|
|
488
|
+
* ```ts
|
|
489
|
+
* const result = await spawn('npm', ['install']);
|
|
490
|
+
* if (!result.ok) console.error('Install failed');
|
|
491
|
+
* ```
|
|
140
492
|
*/
|
|
141
|
-
export const
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
): void => {
|
|
147
|
-
process.on('uncaughtException', async (err, origin): Promise<void> => {
|
|
148
|
-
const label = to_error_label?.(err, origin) ?? origin;
|
|
149
|
-
if (label) {
|
|
150
|
-
const error_text = map_error_text?.(err, origin) ?? print_error(err);
|
|
151
|
-
if (error_text) {
|
|
152
|
-
new Logger(label).error(error_text);
|
|
153
|
-
}
|
|
154
|
-
}
|
|
155
|
-
await despawn_all();
|
|
156
|
-
handle_error(err, origin);
|
|
157
|
-
});
|
|
158
|
-
};
|
|
493
|
+
export const spawn = (
|
|
494
|
+
command: string,
|
|
495
|
+
args: ReadonlyArray<string> = [],
|
|
496
|
+
options?: SpawnProcessOptions,
|
|
497
|
+
): Promise<SpawnResult> => spawn_process(command, args, options).closed;
|
|
159
498
|
|
|
160
499
|
/**
|
|
161
|
-
*
|
|
500
|
+
* Spawns a process and captures stdout/stderr as strings.
|
|
501
|
+
*
|
|
502
|
+
* @example
|
|
503
|
+
* ```ts
|
|
504
|
+
* const {result, stdout} = await spawn_out('git', ['status', '--porcelain']);
|
|
505
|
+
* if (result.ok && stdout) console.log(stdout);
|
|
506
|
+
* ```
|
|
507
|
+
*/
|
|
508
|
+
export const spawn_out = (
|
|
509
|
+
command: string,
|
|
510
|
+
args: ReadonlyArray<string> = [],
|
|
511
|
+
options?: SpawnProcessOptions,
|
|
512
|
+
): Promise<SpawnedOut> => process_registry_default.spawn_out(command, args, options);
|
|
513
|
+
|
|
514
|
+
/**
|
|
515
|
+
* Kills a child process and returns the result.
|
|
516
|
+
*
|
|
517
|
+
* @example
|
|
518
|
+
* ```ts
|
|
519
|
+
* const result = await despawn(child, {timeout_ms: 5000});
|
|
520
|
+
* // If process ignores SIGTERM, SIGKILL sent after 5s
|
|
521
|
+
* ```
|
|
522
|
+
*/
|
|
523
|
+
export const despawn = (child: ChildProcess, options?: DespawnOptions): Promise<SpawnResult> =>
|
|
524
|
+
process_registry_default.despawn(child, options);
|
|
525
|
+
|
|
526
|
+
/**
|
|
527
|
+
* Kills all processes in the default registry.
|
|
528
|
+
*/
|
|
529
|
+
export const despawn_all = (options?: DespawnOptions): Promise<Array<SpawnResult>> =>
|
|
530
|
+
process_registry_default.despawn_all(options);
|
|
531
|
+
|
|
532
|
+
/**
|
|
533
|
+
* Attaches an `uncaughtException` handler to the default registry.
|
|
534
|
+
*
|
|
535
|
+
* @see ProcessRegistry.attach_error_handler
|
|
536
|
+
*/
|
|
537
|
+
export const attach_process_error_handler = (
|
|
538
|
+
options?: Parameters<ProcessRegistry['attach_error_handler']>[0],
|
|
539
|
+
): (() => void) => process_registry_default.attach_error_handler(options);
|
|
540
|
+
|
|
541
|
+
//
|
|
542
|
+
// Formatting Utilities
|
|
543
|
+
//
|
|
544
|
+
|
|
545
|
+
/**
|
|
546
|
+
* Formats a child process for display.
|
|
547
|
+
*
|
|
548
|
+
* @example `pid(1234) <- node server.js`
|
|
549
|
+
*/
|
|
550
|
+
export const print_child_process = (child: ChildProcess): string =>
|
|
551
|
+
`${st('gray', 'pid(')}${child.pid ?? 'none'}${st('gray', ')')} ← ${st('green', child.spawnargs.join(' '))}`;
|
|
552
|
+
|
|
553
|
+
/**
|
|
554
|
+
* Formats a spawn result for display.
|
|
555
|
+
* Returns `'ok'` for success, or the error/signal/code for failures.
|
|
162
556
|
*/
|
|
163
557
|
export const print_spawn_result = (result: SpawnResult): string => {
|
|
164
558
|
if (result.ok) return 'ok';
|
|
165
|
-
|
|
166
|
-
if (result
|
|
167
|
-
return
|
|
559
|
+
if (spawn_result_is_error(result)) return result.error.message;
|
|
560
|
+
if (spawn_result_is_signaled(result)) return print_key_value('signal', result.signal);
|
|
561
|
+
return print_key_value('code', result.code);
|
|
168
562
|
};
|
|
169
563
|
|
|
170
|
-
|
|
564
|
+
/**
|
|
565
|
+
* Formats a spawn result for use in error messages.
|
|
566
|
+
*/
|
|
567
|
+
export const spawn_result_to_message = (result: SpawnResult): string => {
|
|
568
|
+
if (spawn_result_is_error(result)) return `error: ${result.error.message}`;
|
|
569
|
+
if (spawn_result_is_signaled(result)) return `signal ${result.signal}`;
|
|
570
|
+
return `code ${result.code}`;
|
|
571
|
+
};
|
|
572
|
+
|
|
573
|
+
//
|
|
574
|
+
// Restartable Process
|
|
575
|
+
//
|
|
576
|
+
|
|
577
|
+
/**
|
|
578
|
+
* Handle for a process that can be restarted.
|
|
579
|
+
* Exposes `closed` promise for observing exits and implementing restart policies.
|
|
580
|
+
*/
|
|
171
581
|
export interface RestartableProcess {
|
|
172
|
-
|
|
582
|
+
/**
|
|
583
|
+
* Restart the process, killing the current one if active.
|
|
584
|
+
* Concurrent calls are coalesced - multiple calls before the first completes
|
|
585
|
+
* will share the same restart operation.
|
|
586
|
+
*/
|
|
587
|
+
restart: () => Promise<void>;
|
|
588
|
+
/** Kill the process and set `active` to false */
|
|
173
589
|
kill: () => Promise<void>;
|
|
590
|
+
/**
|
|
591
|
+
* Whether this handle is managing a process.
|
|
592
|
+
*
|
|
593
|
+
* Note: This reflects handle state, not whether the underlying OS process is executing.
|
|
594
|
+
* Remains `true` after a process exits naturally until `kill()` or `restart()` is called.
|
|
595
|
+
* To check if the process actually exited, await `closed`.
|
|
596
|
+
*/
|
|
597
|
+
readonly active: boolean;
|
|
598
|
+
/** The current child process, or null if not active */
|
|
599
|
+
readonly child: ChildProcess | null;
|
|
600
|
+
/** Promise that resolves when the current process exits */
|
|
601
|
+
readonly closed: Promise<SpawnResult>;
|
|
602
|
+
/**
|
|
603
|
+
* Promise that resolves when the initial `spawn_process()` call completes.
|
|
604
|
+
*
|
|
605
|
+
* Note: This resolves when the spawn syscall returns, NOT when the process
|
|
606
|
+
* is "ready" or has produced output. For commands that fail immediately
|
|
607
|
+
* (e.g., ENOENT), `spawned` still resolves - check `closed` for errors.
|
|
608
|
+
*
|
|
609
|
+
* @example
|
|
610
|
+
* ```ts
|
|
611
|
+
* const rp = spawn_restartable_process('node', ['server.js']);
|
|
612
|
+
* await rp.spawned; // Safe to access rp.child now
|
|
613
|
+
* ```
|
|
614
|
+
*/
|
|
615
|
+
readonly spawned: Promise<void>;
|
|
174
616
|
}
|
|
175
617
|
|
|
176
618
|
/**
|
|
177
|
-
*
|
|
178
|
-
*
|
|
619
|
+
* Spawns a process that can be restarted.
|
|
620
|
+
* Handles concurrent restart calls gracefully.
|
|
621
|
+
*
|
|
622
|
+
* Note: The `signal` and `timeout_ms` options are reapplied on each restart.
|
|
623
|
+
* If the AbortSignal is already aborted when `restart()` is called, the new
|
|
624
|
+
* process will be killed immediately.
|
|
625
|
+
*
|
|
626
|
+
* @example Simple restart on crash
|
|
627
|
+
* ```ts
|
|
628
|
+
* const rp = spawn_restartable_process('node', ['server.js']);
|
|
629
|
+
*
|
|
630
|
+
* while (rp.active) {
|
|
631
|
+
* const result = await rp.closed;
|
|
632
|
+
* if (result.ok) break; // Clean exit
|
|
633
|
+
* await rp.restart();
|
|
634
|
+
* }
|
|
635
|
+
* ```
|
|
636
|
+
*
|
|
637
|
+
* @example Restart with backoff
|
|
638
|
+
* ```ts
|
|
639
|
+
* const rp = spawn_restartable_process('node', ['server.js']);
|
|
640
|
+
* let failures = 0;
|
|
641
|
+
*
|
|
642
|
+
* while (rp.active) {
|
|
643
|
+
* const result = await rp.closed;
|
|
644
|
+
* if (result.ok || ++failures > 5) break;
|
|
645
|
+
* await new Promise((r) => setTimeout(r, 1000 * failures));
|
|
646
|
+
* await rp.restart();
|
|
647
|
+
* }
|
|
648
|
+
* ```
|
|
179
649
|
*/
|
|
180
650
|
export const spawn_restartable_process = (
|
|
181
651
|
command: string,
|
|
182
652
|
args: ReadonlyArray<string> = [],
|
|
183
|
-
options?:
|
|
653
|
+
options?: SpawnProcessOptions,
|
|
184
654
|
): RestartableProcess => {
|
|
185
|
-
let
|
|
186
|
-
let
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
655
|
+
let spawned_process: SpawnedProcess | null = null;
|
|
656
|
+
let pending_close: Promise<SpawnResult> | null = null;
|
|
657
|
+
let pending_restart: Promise<void> | null = null;
|
|
658
|
+
let pending_kill: Promise<void> | null = null;
|
|
659
|
+
// Deferred promise - resolves when first process spawns
|
|
660
|
+
let closed_promise: Promise<SpawnResult>;
|
|
661
|
+
let resolve_closed: (result: SpawnResult) => void;
|
|
662
|
+
const reset_closed_promise = (): void => {
|
|
663
|
+
closed_promise = new Promise((r) => (resolve_closed = r));
|
|
194
664
|
};
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
665
|
+
reset_closed_promise();
|
|
666
|
+
|
|
667
|
+
// Resolve when first spawn completes to avoid race conditions
|
|
668
|
+
let resolve_spawned: () => void;
|
|
669
|
+
const spawned: Promise<void> = new Promise((r) => (resolve_spawned = r));
|
|
670
|
+
|
|
671
|
+
const do_close = async (): Promise<void> => {
|
|
672
|
+
if (!spawned_process) return;
|
|
673
|
+
pending_close = spawned_process.closed;
|
|
674
|
+
spawned_process.child.kill();
|
|
675
|
+
spawned_process = null;
|
|
676
|
+
await pending_close;
|
|
677
|
+
pending_close = null;
|
|
678
|
+
};
|
|
679
|
+
|
|
680
|
+
const do_restart = async (): Promise<void> => {
|
|
681
|
+
// Wait for any in-progress kill or close before restarting
|
|
682
|
+
if (pending_kill) await pending_kill;
|
|
683
|
+
if (pending_close) await pending_close;
|
|
684
|
+
if (spawned_process) await do_close();
|
|
685
|
+
spawned_process = spawn_process(command, args, {stdio: 'inherit', ...options});
|
|
686
|
+
// Forward the spawned process's closed promise to our exposed one
|
|
687
|
+
void spawned_process.closed.then((result) => {
|
|
688
|
+
resolve_closed(result);
|
|
689
|
+
});
|
|
199
690
|
};
|
|
691
|
+
|
|
692
|
+
// Coalesce concurrent restart calls - multiple calls share one restart
|
|
693
|
+
const restart = (): Promise<void> => {
|
|
694
|
+
if (!pending_restart) {
|
|
695
|
+
// Reset the closed promise for the new process
|
|
696
|
+
reset_closed_promise();
|
|
697
|
+
pending_restart = do_restart().finally(() => {
|
|
698
|
+
pending_restart = null;
|
|
699
|
+
});
|
|
700
|
+
}
|
|
701
|
+
return pending_restart;
|
|
702
|
+
};
|
|
703
|
+
|
|
704
|
+
// Wait for any pending restart to complete first, ensuring we kill
|
|
705
|
+
// the newly spawned process rather than racing with it
|
|
200
706
|
const kill = async (): Promise<void> => {
|
|
201
|
-
if (
|
|
202
|
-
|
|
707
|
+
if (pending_kill) return pending_kill;
|
|
708
|
+
pending_kill = (async () => {
|
|
709
|
+
if (pending_restart) await pending_restart;
|
|
710
|
+
if (pending_close) await pending_close;
|
|
711
|
+
await do_close();
|
|
712
|
+
})();
|
|
713
|
+
try {
|
|
714
|
+
await pending_kill;
|
|
715
|
+
} finally {
|
|
716
|
+
pending_kill = null;
|
|
717
|
+
}
|
|
718
|
+
};
|
|
719
|
+
|
|
720
|
+
// Start immediately and resolve spawned promise when done
|
|
721
|
+
void restart().then(() => resolve_spawned());
|
|
722
|
+
|
|
723
|
+
return {
|
|
724
|
+
restart,
|
|
725
|
+
kill,
|
|
726
|
+
get active() {
|
|
727
|
+
return spawned_process !== null;
|
|
728
|
+
},
|
|
729
|
+
get child() {
|
|
730
|
+
return spawned_process?.child ?? null;
|
|
731
|
+
},
|
|
732
|
+
get closed() {
|
|
733
|
+
return closed_promise;
|
|
734
|
+
},
|
|
735
|
+
get spawned() {
|
|
736
|
+
return spawned;
|
|
737
|
+
},
|
|
203
738
|
};
|
|
204
|
-
// Start immediately -- it sychronously starts the process so there's no need to await.
|
|
205
|
-
void restart();
|
|
206
|
-
return {restart, kill};
|
|
207
739
|
};
|
|
208
740
|
|
|
741
|
+
//
|
|
742
|
+
// Utility Functions
|
|
743
|
+
//
|
|
744
|
+
|
|
209
745
|
/**
|
|
210
|
-
*
|
|
746
|
+
* Checks if a process with the given PID is running.
|
|
747
|
+
* Uses signal 0 which checks existence without sending a signal.
|
|
748
|
+
*
|
|
749
|
+
* @param pid - The process ID to check (must be a positive integer)
|
|
750
|
+
* @returns `true` if the process exists (even without permission to signal it),
|
|
751
|
+
* `false` if the process doesn't exist or if pid is invalid (non-positive, non-integer, NaN, Infinity)
|
|
211
752
|
*/
|
|
212
753
|
export const process_is_pid_running = (pid: number): boolean => {
|
|
754
|
+
// Handle NaN, Infinity, negative, zero, non-integers, and fractional values
|
|
755
|
+
if (!Number.isInteger(pid) || pid <= 0) return false;
|
|
213
756
|
try {
|
|
214
|
-
// Sending signal 0 doesn't actually send a signal, just checks if process exists
|
|
215
757
|
process.kill(pid, 0);
|
|
216
758
|
return true;
|
|
217
|
-
} catch (err:
|
|
218
|
-
// ESRCH = no such process
|
|
219
|
-
|
|
759
|
+
} catch (err: unknown) {
|
|
760
|
+
// ESRCH = no such process
|
|
761
|
+
// EPERM = process exists but we lack permission to signal it
|
|
762
|
+
// Safely access .code in case of unexpected error types
|
|
763
|
+
const code =
|
|
764
|
+
err && typeof err === 'object' && 'code' in err ? (err as {code: string}).code : undefined;
|
|
765
|
+
return code === 'EPERM';
|
|
220
766
|
}
|
|
221
767
|
};
|