@alchemy.run/node-utils 0.0.2 → 0.0.4
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/lib/foreground-child.d.ts +57 -0
- package/lib/foreground-child.d.ts.map +1 -0
- package/lib/foreground-child.js +201 -0
- package/lib/foreground-child.js.map +1 -0
- package/lib/index.d.ts +1 -0
- package/lib/index.d.ts.map +1 -1
- package/lib/index.js +1 -0
- package/lib/index.js.map +1 -1
- package/package.json +21 -1
- package/src/foreground-child.ts +243 -0
- package/src/index.ts +1 -0
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Run a child process in the foreground: proxy signals to it, forward stdio,
|
|
3
|
+
* bridge IPC, and exit with the child's code/signal. A watchdog process
|
|
4
|
+
* ensures the child is killed if the parent dies unexpectedly.
|
|
5
|
+
*
|
|
6
|
+
* Adapted from `foreground-child@4.0.3` (© Isaac Z. Schlueter et al.):
|
|
7
|
+
* https://github.com/tapjs/foreground-child
|
|
8
|
+
* Licensed under the Blue Oak Model License 1.0.0:
|
|
9
|
+
* https://blueoakcouncil.org/license/1.0.0
|
|
10
|
+
*
|
|
11
|
+
* The behavioral additions on top of upstream are:
|
|
12
|
+
* 1. Optional `stderrFilter` — upstream hardcodes `stdio = [0, 1, 2]`,
|
|
13
|
+
* which makes intercepting child stderr impossible without forking.
|
|
14
|
+
* When `stderrFilter` is provided, the child's stderr is piped,
|
|
15
|
+
* line-buffered, and each line is passed through the filter
|
|
16
|
+
* (return `false` to drop, `true` to forward).
|
|
17
|
+
* 2. Uses the in-tree {@link exitHook} instead of `signal-exit`, so this
|
|
18
|
+
* package has no external runtime dependencies.
|
|
19
|
+
*
|
|
20
|
+
* Everything else — signal proxying, the watchdog, IPC bridging, exit-code
|
|
21
|
+
* forwarding — is preserved verbatim from upstream.
|
|
22
|
+
*/
|
|
23
|
+
import { type ChildProcess } from "node:child_process";
|
|
24
|
+
type SyncCleanupResult = void | undefined | null | boolean | number | string | NodeJS.Signals;
|
|
25
|
+
export type CleanupResult = SyncCleanupResult | Promise<SyncCleanupResult>;
|
|
26
|
+
export interface ForegroundChildOptions {
|
|
27
|
+
/**
|
|
28
|
+
* Line-level filter for the child's stderr. Return `true` to forward the
|
|
29
|
+
* line to the parent's stderr, `false` to drop it. When omitted, the
|
|
30
|
+
* child's stderr is inherited directly (no buffering, no filtering).
|
|
31
|
+
*/
|
|
32
|
+
stderrFilter?: (line: string) => boolean;
|
|
33
|
+
/**
|
|
34
|
+
* Called when the child closes. May return:
|
|
35
|
+
* - `false` — suppress propagation of the child's exit
|
|
36
|
+
* - `number` — override the parent's exit code
|
|
37
|
+
* - `string` (a signal name) — kill the parent with that signal
|
|
38
|
+
* - `void` / `undefined` — propagate the child's code/signal verbatim
|
|
39
|
+
* Async (Promise-returning) cleanup is supported.
|
|
40
|
+
*/
|
|
41
|
+
cleanup?: (code: number | null, signal: NodeJS.Signals | null, extra: {
|
|
42
|
+
watchdogPid: number | undefined;
|
|
43
|
+
}) => CleanupResult;
|
|
44
|
+
}
|
|
45
|
+
/**
|
|
46
|
+
* Run `program` with `args` as a foreground child of the current process.
|
|
47
|
+
*
|
|
48
|
+
* Signals received by the parent are proxied to the child, the child's stdio
|
|
49
|
+
* is connected to the parent's (with optional stderr filtering via
|
|
50
|
+
* {@link ForegroundChildOptions.stderrFilter}), IPC messages are bridged in
|
|
51
|
+
* both directions, and the parent exits with the child's exit code or
|
|
52
|
+
* signal. A watchdog subprocess ensures the child is force-killed if the
|
|
53
|
+
* parent dies unexpectedly.
|
|
54
|
+
*/
|
|
55
|
+
export declare function foregroundChild(program: string, args: ReadonlyArray<string>, opts?: ForegroundChildOptions): ChildProcess;
|
|
56
|
+
export {};
|
|
57
|
+
//# sourceMappingURL=foreground-child.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"foreground-child.d.ts","sourceRoot":"","sources":["../src/foreground-child.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;GAqBG;AACH,OAAO,EAAE,KAAK,YAAY,EAAS,MAAM,oBAAoB,CAAC;AAgF9D,KAAK,iBAAiB,GAClB,IAAI,GACJ,SAAS,GACT,IAAI,GACJ,OAAO,GACP,MAAM,GACN,MAAM,GACN,MAAM,CAAC,OAAO,CAAC;AAEnB,MAAM,MAAM,aAAa,GAAG,iBAAiB,GAAG,OAAO,CAAC,iBAAiB,CAAC,CAAC;AAE3E,MAAM,WAAW,sBAAsB;IACrC;;;;OAIG;IACH,YAAY,CAAC,EAAE,CAAC,IAAI,EAAE,MAAM,KAAK,OAAO,CAAC;IACzC;;;;;;;OAOG;IACH,OAAO,CAAC,EAAE,CACR,IAAI,EAAE,MAAM,GAAG,IAAI,EACnB,MAAM,EAAE,MAAM,CAAC,OAAO,GAAG,IAAI,EAC7B,KAAK,EAAE;QAAE,WAAW,EAAE,MAAM,GAAG,SAAS,CAAA;KAAE,KACvC,aAAa,CAAC;CACpB;AAED;;;;;;;;;GASG;AACH,wBAAgB,eAAe,CAC7B,OAAO,EAAE,MAAM,EACf,IAAI,EAAE,aAAa,CAAC,MAAM,CAAC,EAC3B,IAAI,GAAE,sBAA2B,GAChC,YAAY,CA6Fd"}
|
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Run a child process in the foreground: proxy signals to it, forward stdio,
|
|
3
|
+
* bridge IPC, and exit with the child's code/signal. A watchdog process
|
|
4
|
+
* ensures the child is killed if the parent dies unexpectedly.
|
|
5
|
+
*
|
|
6
|
+
* Adapted from `foreground-child@4.0.3` (© Isaac Z. Schlueter et al.):
|
|
7
|
+
* https://github.com/tapjs/foreground-child
|
|
8
|
+
* Licensed under the Blue Oak Model License 1.0.0:
|
|
9
|
+
* https://blueoakcouncil.org/license/1.0.0
|
|
10
|
+
*
|
|
11
|
+
* The behavioral additions on top of upstream are:
|
|
12
|
+
* 1. Optional `stderrFilter` — upstream hardcodes `stdio = [0, 1, 2]`,
|
|
13
|
+
* which makes intercepting child stderr impossible without forking.
|
|
14
|
+
* When `stderrFilter` is provided, the child's stderr is piped,
|
|
15
|
+
* line-buffered, and each line is passed through the filter
|
|
16
|
+
* (return `false` to drop, `true` to forward).
|
|
17
|
+
* 2. Uses the in-tree {@link exitHook} instead of `signal-exit`, so this
|
|
18
|
+
* package has no external runtime dependencies.
|
|
19
|
+
*
|
|
20
|
+
* Everything else — signal proxying, the watchdog, IPC bridging, exit-code
|
|
21
|
+
* forwarding — is preserved verbatim from upstream.
|
|
22
|
+
*/
|
|
23
|
+
import { spawn } from "node:child_process";
|
|
24
|
+
import constants from "node:constants";
|
|
25
|
+
import { exitHook } from "./exit-hook.js";
|
|
26
|
+
const allSignals = Object.keys(constants).filter((k) => k.startsWith("SIG") && k !== "SIGPROF" && k !== "SIGKILL");
|
|
27
|
+
function proxySignals(child) {
|
|
28
|
+
const listeners = new Map();
|
|
29
|
+
for (const sig of allSignals) {
|
|
30
|
+
const listener = () => {
|
|
31
|
+
try {
|
|
32
|
+
child.kill(sig);
|
|
33
|
+
}
|
|
34
|
+
catch (_) { }
|
|
35
|
+
};
|
|
36
|
+
try {
|
|
37
|
+
process.on(sig, listener);
|
|
38
|
+
listeners.set(sig, listener);
|
|
39
|
+
}
|
|
40
|
+
catch (_) { }
|
|
41
|
+
}
|
|
42
|
+
const unproxy = () => {
|
|
43
|
+
for (const [sig, listener] of listeners) {
|
|
44
|
+
process.removeListener(sig, listener);
|
|
45
|
+
}
|
|
46
|
+
};
|
|
47
|
+
child.on("exit", unproxy);
|
|
48
|
+
return unproxy;
|
|
49
|
+
}
|
|
50
|
+
const watchdogCode = String.raw `
|
|
51
|
+
const pid = parseInt(process.argv[1], 10)
|
|
52
|
+
process.title = 'node (foreground-child watchdog pid=' + pid + ')'
|
|
53
|
+
if (!isNaN(pid)) {
|
|
54
|
+
let barked = false
|
|
55
|
+
const interval = setInterval(() => {}, 60000)
|
|
56
|
+
const bark = () => {
|
|
57
|
+
clearInterval(interval)
|
|
58
|
+
if (barked) return
|
|
59
|
+
barked = true
|
|
60
|
+
process.removeListener('SIGHUP', bark)
|
|
61
|
+
setTimeout(() => {
|
|
62
|
+
try {
|
|
63
|
+
process.kill(pid, 'SIGKILL')
|
|
64
|
+
setTimeout(() => process.exit(), 200)
|
|
65
|
+
} catch (_) {}
|
|
66
|
+
}, 500)
|
|
67
|
+
}
|
|
68
|
+
process.on('SIGHUP', bark)
|
|
69
|
+
}
|
|
70
|
+
`;
|
|
71
|
+
function watchdog(child) {
|
|
72
|
+
let dogExited = false;
|
|
73
|
+
const dog = spawn(process.execPath, ["-e", watchdogCode, String(child.pid)], {
|
|
74
|
+
stdio: ["ignore", "ignore", "pipe"],
|
|
75
|
+
});
|
|
76
|
+
dog.on("exit", () => {
|
|
77
|
+
dogExited = true;
|
|
78
|
+
});
|
|
79
|
+
dog.stderr?.pipe(process.stderr, { end: false });
|
|
80
|
+
child.on("exit", () => {
|
|
81
|
+
if (!dogExited)
|
|
82
|
+
dog.kill("SIGKILL");
|
|
83
|
+
});
|
|
84
|
+
process.on("exit", () => {
|
|
85
|
+
if (!dogExited)
|
|
86
|
+
dog.kill("SIGKILL");
|
|
87
|
+
});
|
|
88
|
+
return dog;
|
|
89
|
+
}
|
|
90
|
+
function isPromise(o) {
|
|
91
|
+
return (!!o &&
|
|
92
|
+
typeof o === "object" &&
|
|
93
|
+
typeof o.then === "function");
|
|
94
|
+
}
|
|
95
|
+
/**
|
|
96
|
+
* Run `program` with `args` as a foreground child of the current process.
|
|
97
|
+
*
|
|
98
|
+
* Signals received by the parent are proxied to the child, the child's stdio
|
|
99
|
+
* is connected to the parent's (with optional stderr filtering via
|
|
100
|
+
* {@link ForegroundChildOptions.stderrFilter}), IPC messages are bridged in
|
|
101
|
+
* both directions, and the parent exits with the child's exit code or
|
|
102
|
+
* signal. A watchdog subprocess ensures the child is force-killed if the
|
|
103
|
+
* parent dies unexpectedly.
|
|
104
|
+
*/
|
|
105
|
+
export function foregroundChild(program, args, opts = {}) {
|
|
106
|
+
const { stderrFilter, cleanup = () => { } } = opts;
|
|
107
|
+
const stdio = stderrFilter
|
|
108
|
+
? [0, 1, "pipe"]
|
|
109
|
+
: [0, 1, 2];
|
|
110
|
+
if (process.send)
|
|
111
|
+
stdio.push("ipc");
|
|
112
|
+
const child = spawn(program, args, { stdio });
|
|
113
|
+
if (stderrFilter && child.stderr) {
|
|
114
|
+
let buf = "";
|
|
115
|
+
child.stderr.on("data", (chunk) => {
|
|
116
|
+
buf += chunk.toString();
|
|
117
|
+
let nl;
|
|
118
|
+
while ((nl = buf.search(/\r?\n/)) !== -1) {
|
|
119
|
+
const eol = buf.startsWith("\r\n", nl) ? 2 : 1;
|
|
120
|
+
const line = buf.slice(0, nl + eol);
|
|
121
|
+
buf = buf.slice(nl + eol);
|
|
122
|
+
if (stderrFilter(line))
|
|
123
|
+
process.stderr.write(line);
|
|
124
|
+
}
|
|
125
|
+
});
|
|
126
|
+
child.stderr.on("end", () => {
|
|
127
|
+
if (buf && stderrFilter(buf))
|
|
128
|
+
process.stderr.write(buf);
|
|
129
|
+
});
|
|
130
|
+
}
|
|
131
|
+
const childHangup = () => {
|
|
132
|
+
try {
|
|
133
|
+
child.kill("SIGHUP");
|
|
134
|
+
}
|
|
135
|
+
catch (_) {
|
|
136
|
+
child.kill("SIGTERM");
|
|
137
|
+
}
|
|
138
|
+
};
|
|
139
|
+
const removeOnExit = exitHook(childHangup);
|
|
140
|
+
proxySignals(child);
|
|
141
|
+
const dog = watchdog(child);
|
|
142
|
+
let done = false;
|
|
143
|
+
dog.on("close", (code, signal) => {
|
|
144
|
+
if (done)
|
|
145
|
+
return;
|
|
146
|
+
child.kill("SIGKILL");
|
|
147
|
+
throw new Error("foreground-child watchdog process died unexpectedly!", {
|
|
148
|
+
cause: {
|
|
149
|
+
pid: dog.pid,
|
|
150
|
+
code,
|
|
151
|
+
signal,
|
|
152
|
+
watchedProcess: { cmd: program, args, pid: child.pid },
|
|
153
|
+
},
|
|
154
|
+
});
|
|
155
|
+
});
|
|
156
|
+
child.on("close", async (code, signal) => {
|
|
157
|
+
if (done)
|
|
158
|
+
return;
|
|
159
|
+
done = true;
|
|
160
|
+
const result = cleanup(code, signal, { watchdogPid: dog.pid });
|
|
161
|
+
const res = isPromise(result) ? await result : result;
|
|
162
|
+
removeOnExit();
|
|
163
|
+
if (res === false)
|
|
164
|
+
return;
|
|
165
|
+
let finalCode = code;
|
|
166
|
+
let finalSignal = signal;
|
|
167
|
+
if (typeof res === "string") {
|
|
168
|
+
finalSignal = res;
|
|
169
|
+
finalCode = null;
|
|
170
|
+
}
|
|
171
|
+
else if (typeof res === "number") {
|
|
172
|
+
finalCode = res;
|
|
173
|
+
finalSignal = null;
|
|
174
|
+
}
|
|
175
|
+
if (finalSignal) {
|
|
176
|
+
setTimeout(() => { }, 2000);
|
|
177
|
+
try {
|
|
178
|
+
process.kill(process.pid, finalSignal);
|
|
179
|
+
}
|
|
180
|
+
catch (_) {
|
|
181
|
+
process.kill(process.pid, "SIGTERM");
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
else {
|
|
185
|
+
process.exit(finalCode ?? 0);
|
|
186
|
+
}
|
|
187
|
+
});
|
|
188
|
+
if (process.send) {
|
|
189
|
+
process.removeAllListeners("message");
|
|
190
|
+
child.on("message", (message, sendHandle) => {
|
|
191
|
+
process.send?.(message, sendHandle);
|
|
192
|
+
});
|
|
193
|
+
process.on("message", (message, sendHandle) => {
|
|
194
|
+
if (message === null)
|
|
195
|
+
return;
|
|
196
|
+
child.send(message, sendHandle);
|
|
197
|
+
});
|
|
198
|
+
}
|
|
199
|
+
return child;
|
|
200
|
+
}
|
|
201
|
+
//# sourceMappingURL=foreground-child.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"foreground-child.js","sourceRoot":"","sources":["../src/foreground-child.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;GAqBG;AACH,OAAO,EAAqB,KAAK,EAAE,MA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AAC;QAClC,CAAC,CAAC,CAAC;IACL,CAAC;IAED,OAAO,KAAK,CAAC;AACf,CAAC"}
|
package/lib/index.d.ts
CHANGED
package/lib/index.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,cAAc,gBAAgB,CAAC;AAC/B,cAAc,aAAa,CAAC;AAC5B,cAAc,qBAAqB,CAAC;AACpC,cAAc,YAAY,CAAC"}
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,cAAc,gBAAgB,CAAC;AAC/B,cAAc,uBAAuB,CAAC;AACtC,cAAc,aAAa,CAAC;AAC5B,cAAc,qBAAqB,CAAC;AACpC,cAAc,YAAY,CAAC"}
|
package/lib/index.js
CHANGED
package/lib/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,cAAc,gBAAgB,CAAC;AAC/B,cAAc,aAAa,CAAC;AAC5B,cAAc,qBAAqB,CAAC;AACpC,cAAc,YAAY,CAAC"}
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,cAAc,gBAAgB,CAAC;AAC/B,cAAc,uBAAuB,CAAC;AACtC,cAAc,aAAa,CAAC;AAC5B,cAAc,qBAAqB,CAAC;AACpC,cAAc,YAAY,CAAC"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@alchemy.run/node-utils",
|
|
3
|
-
"version": "0.0.
|
|
3
|
+
"version": "0.0.4",
|
|
4
4
|
"author": "Sam Goodwin (sam@alchemy.run)",
|
|
5
5
|
"repository": {
|
|
6
6
|
"type": "git",
|
|
@@ -16,6 +16,26 @@
|
|
|
16
16
|
"bun": "./src/index.ts",
|
|
17
17
|
"types": "./lib/index.d.ts",
|
|
18
18
|
"default": "./lib/index.js"
|
|
19
|
+
},
|
|
20
|
+
"./exit-hook": {
|
|
21
|
+
"bun": "./src/exit-hook.ts",
|
|
22
|
+
"types": "./lib/exit-hook.d.ts",
|
|
23
|
+
"default": "./lib/exit-hook.js"
|
|
24
|
+
},
|
|
25
|
+
"./ignore": {
|
|
26
|
+
"bun": "./src/ignore.ts",
|
|
27
|
+
"types": "./lib/ignore.d.ts",
|
|
28
|
+
"default": "./lib/ignore.js"
|
|
29
|
+
},
|
|
30
|
+
"./lockfile": {
|
|
31
|
+
"bun": "./src/lockfile-async.ts",
|
|
32
|
+
"types": "./lib/lockfile-async.d.ts",
|
|
33
|
+
"default": "./lib/lockfile-async.js"
|
|
34
|
+
},
|
|
35
|
+
"./retry": {
|
|
36
|
+
"bun": "./src/retry.ts",
|
|
37
|
+
"types": "./lib/retry.d.ts",
|
|
38
|
+
"default": "./lib/retry.js"
|
|
19
39
|
}
|
|
20
40
|
},
|
|
21
41
|
"scripts": {
|
|
@@ -0,0 +1,243 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Run a child process in the foreground: proxy signals to it, forward stdio,
|
|
3
|
+
* bridge IPC, and exit with the child's code/signal. A watchdog process
|
|
4
|
+
* ensures the child is killed if the parent dies unexpectedly.
|
|
5
|
+
*
|
|
6
|
+
* Adapted from `foreground-child@4.0.3` (© Isaac Z. Schlueter et al.):
|
|
7
|
+
* https://github.com/tapjs/foreground-child
|
|
8
|
+
* Licensed under the Blue Oak Model License 1.0.0:
|
|
9
|
+
* https://blueoakcouncil.org/license/1.0.0
|
|
10
|
+
*
|
|
11
|
+
* The behavioral additions on top of upstream are:
|
|
12
|
+
* 1. Optional `stderrFilter` — upstream hardcodes `stdio = [0, 1, 2]`,
|
|
13
|
+
* which makes intercepting child stderr impossible without forking.
|
|
14
|
+
* When `stderrFilter` is provided, the child's stderr is piped,
|
|
15
|
+
* line-buffered, and each line is passed through the filter
|
|
16
|
+
* (return `false` to drop, `true` to forward).
|
|
17
|
+
* 2. Uses the in-tree {@link exitHook} instead of `signal-exit`, so this
|
|
18
|
+
* package has no external runtime dependencies.
|
|
19
|
+
*
|
|
20
|
+
* Everything else — signal proxying, the watchdog, IPC bridging, exit-code
|
|
21
|
+
* forwarding — is preserved verbatim from upstream.
|
|
22
|
+
*/
|
|
23
|
+
import { type ChildProcess, spawn } from "node:child_process";
|
|
24
|
+
import constants from "node:constants";
|
|
25
|
+
import { exitHook } from "./exit-hook.ts";
|
|
26
|
+
|
|
27
|
+
type Signal = NodeJS.Signals;
|
|
28
|
+
|
|
29
|
+
const allSignals = Object.keys(constants).filter(
|
|
30
|
+
(k) => k.startsWith("SIG") && k !== "SIGPROF" && k !== "SIGKILL",
|
|
31
|
+
) as Signal[];
|
|
32
|
+
|
|
33
|
+
function proxySignals(child: ChildProcess): () => void {
|
|
34
|
+
const listeners = new Map<Signal, () => void>();
|
|
35
|
+
for (const sig of allSignals) {
|
|
36
|
+
const listener = (): void => {
|
|
37
|
+
try {
|
|
38
|
+
child.kill(sig);
|
|
39
|
+
} catch (_) {}
|
|
40
|
+
};
|
|
41
|
+
try {
|
|
42
|
+
process.on(sig, listener);
|
|
43
|
+
listeners.set(sig, listener);
|
|
44
|
+
} catch (_) {}
|
|
45
|
+
}
|
|
46
|
+
const unproxy = (): void => {
|
|
47
|
+
for (const [sig, listener] of listeners) {
|
|
48
|
+
process.removeListener(sig, listener);
|
|
49
|
+
}
|
|
50
|
+
};
|
|
51
|
+
child.on("exit", unproxy);
|
|
52
|
+
return unproxy;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
const watchdogCode = String.raw`
|
|
56
|
+
const pid = parseInt(process.argv[1], 10)
|
|
57
|
+
process.title = 'node (foreground-child watchdog pid=' + pid + ')'
|
|
58
|
+
if (!isNaN(pid)) {
|
|
59
|
+
let barked = false
|
|
60
|
+
const interval = setInterval(() => {}, 60000)
|
|
61
|
+
const bark = () => {
|
|
62
|
+
clearInterval(interval)
|
|
63
|
+
if (barked) return
|
|
64
|
+
barked = true
|
|
65
|
+
process.removeListener('SIGHUP', bark)
|
|
66
|
+
setTimeout(() => {
|
|
67
|
+
try {
|
|
68
|
+
process.kill(pid, 'SIGKILL')
|
|
69
|
+
setTimeout(() => process.exit(), 200)
|
|
70
|
+
} catch (_) {}
|
|
71
|
+
}, 500)
|
|
72
|
+
}
|
|
73
|
+
process.on('SIGHUP', bark)
|
|
74
|
+
}
|
|
75
|
+
`;
|
|
76
|
+
|
|
77
|
+
function watchdog(child: ChildProcess): ChildProcess {
|
|
78
|
+
let dogExited = false;
|
|
79
|
+
const dog = spawn(process.execPath, ["-e", watchdogCode, String(child.pid)], {
|
|
80
|
+
stdio: ["ignore", "ignore", "pipe"],
|
|
81
|
+
});
|
|
82
|
+
dog.on("exit", () => {
|
|
83
|
+
dogExited = true;
|
|
84
|
+
});
|
|
85
|
+
dog.stderr?.pipe(process.stderr, { end: false });
|
|
86
|
+
child.on("exit", () => {
|
|
87
|
+
if (!dogExited) dog.kill("SIGKILL");
|
|
88
|
+
});
|
|
89
|
+
process.on("exit", () => {
|
|
90
|
+
if (!dogExited) dog.kill("SIGKILL");
|
|
91
|
+
});
|
|
92
|
+
return dog;
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
function isPromise<T>(o: unknown): o is Promise<T> {
|
|
96
|
+
return (
|
|
97
|
+
!!o &&
|
|
98
|
+
typeof o === "object" &&
|
|
99
|
+
typeof (o as { then?: unknown }).then === "function"
|
|
100
|
+
);
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
type SyncCleanupResult =
|
|
104
|
+
| void
|
|
105
|
+
| undefined
|
|
106
|
+
| null
|
|
107
|
+
| boolean
|
|
108
|
+
| number
|
|
109
|
+
| string
|
|
110
|
+
| NodeJS.Signals;
|
|
111
|
+
|
|
112
|
+
export type CleanupResult = SyncCleanupResult | Promise<SyncCleanupResult>;
|
|
113
|
+
|
|
114
|
+
export interface ForegroundChildOptions {
|
|
115
|
+
/**
|
|
116
|
+
* Line-level filter for the child's stderr. Return `true` to forward the
|
|
117
|
+
* line to the parent's stderr, `false` to drop it. When omitted, the
|
|
118
|
+
* child's stderr is inherited directly (no buffering, no filtering).
|
|
119
|
+
*/
|
|
120
|
+
stderrFilter?: (line: string) => boolean;
|
|
121
|
+
/**
|
|
122
|
+
* Called when the child closes. May return:
|
|
123
|
+
* - `false` — suppress propagation of the child's exit
|
|
124
|
+
* - `number` — override the parent's exit code
|
|
125
|
+
* - `string` (a signal name) — kill the parent with that signal
|
|
126
|
+
* - `void` / `undefined` — propagate the child's code/signal verbatim
|
|
127
|
+
* Async (Promise-returning) cleanup is supported.
|
|
128
|
+
*/
|
|
129
|
+
cleanup?: (
|
|
130
|
+
code: number | null,
|
|
131
|
+
signal: NodeJS.Signals | null,
|
|
132
|
+
extra: { watchdogPid: number | undefined },
|
|
133
|
+
) => CleanupResult;
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
/**
|
|
137
|
+
* Run `program` with `args` as a foreground child of the current process.
|
|
138
|
+
*
|
|
139
|
+
* Signals received by the parent are proxied to the child, the child's stdio
|
|
140
|
+
* is connected to the parent's (with optional stderr filtering via
|
|
141
|
+
* {@link ForegroundChildOptions.stderrFilter}), IPC messages are bridged in
|
|
142
|
+
* both directions, and the parent exits with the child's exit code or
|
|
143
|
+
* signal. A watchdog subprocess ensures the child is force-killed if the
|
|
144
|
+
* parent dies unexpectedly.
|
|
145
|
+
*/
|
|
146
|
+
export function foregroundChild(
|
|
147
|
+
program: string,
|
|
148
|
+
args: ReadonlyArray<string>,
|
|
149
|
+
opts: ForegroundChildOptions = {},
|
|
150
|
+
): ChildProcess {
|
|
151
|
+
const { stderrFilter, cleanup = (): void => {} } = opts;
|
|
152
|
+
|
|
153
|
+
const stdio: Array<"pipe" | "ignore" | "inherit" | number> = stderrFilter
|
|
154
|
+
? [0, 1, "pipe"]
|
|
155
|
+
: [0, 1, 2];
|
|
156
|
+
if (process.send) stdio.push("ipc" as unknown as number);
|
|
157
|
+
|
|
158
|
+
const child = spawn(program, args as string[], { stdio });
|
|
159
|
+
|
|
160
|
+
if (stderrFilter && child.stderr) {
|
|
161
|
+
let buf = "";
|
|
162
|
+
child.stderr.on("data", (chunk: Buffer | string) => {
|
|
163
|
+
buf += chunk.toString();
|
|
164
|
+
let nl: number;
|
|
165
|
+
while ((nl = buf.search(/\r?\n/)) !== -1) {
|
|
166
|
+
const eol = buf.startsWith("\r\n", nl) ? 2 : 1;
|
|
167
|
+
const line = buf.slice(0, nl + eol);
|
|
168
|
+
buf = buf.slice(nl + eol);
|
|
169
|
+
if (stderrFilter(line)) process.stderr.write(line);
|
|
170
|
+
}
|
|
171
|
+
});
|
|
172
|
+
child.stderr.on("end", () => {
|
|
173
|
+
if (buf && stderrFilter(buf)) process.stderr.write(buf);
|
|
174
|
+
});
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
const childHangup = (): void => {
|
|
178
|
+
try {
|
|
179
|
+
child.kill("SIGHUP");
|
|
180
|
+
} catch (_) {
|
|
181
|
+
child.kill("SIGTERM");
|
|
182
|
+
}
|
|
183
|
+
};
|
|
184
|
+
const removeOnExit = exitHook(childHangup);
|
|
185
|
+
|
|
186
|
+
proxySignals(child);
|
|
187
|
+
const dog = watchdog(child);
|
|
188
|
+
|
|
189
|
+
let done = false;
|
|
190
|
+
dog.on("close", (code, signal) => {
|
|
191
|
+
if (done) return;
|
|
192
|
+
child.kill("SIGKILL");
|
|
193
|
+
throw new Error("foreground-child watchdog process died unexpectedly!", {
|
|
194
|
+
cause: {
|
|
195
|
+
pid: dog.pid,
|
|
196
|
+
code,
|
|
197
|
+
signal,
|
|
198
|
+
watchedProcess: { cmd: program, args, pid: child.pid },
|
|
199
|
+
},
|
|
200
|
+
});
|
|
201
|
+
});
|
|
202
|
+
|
|
203
|
+
child.on("close", async (code, signal) => {
|
|
204
|
+
if (done) return;
|
|
205
|
+
done = true;
|
|
206
|
+
const result = cleanup(code, signal, { watchdogPid: dog.pid });
|
|
207
|
+
const res = isPromise<SyncCleanupResult>(result) ? await result : result;
|
|
208
|
+
removeOnExit();
|
|
209
|
+
if (res === false) return;
|
|
210
|
+
let finalCode: number | null = code;
|
|
211
|
+
let finalSignal: NodeJS.Signals | null = signal;
|
|
212
|
+
if (typeof res === "string") {
|
|
213
|
+
finalSignal = res as NodeJS.Signals;
|
|
214
|
+
finalCode = null;
|
|
215
|
+
} else if (typeof res === "number") {
|
|
216
|
+
finalCode = res;
|
|
217
|
+
finalSignal = null;
|
|
218
|
+
}
|
|
219
|
+
if (finalSignal) {
|
|
220
|
+
setTimeout(() => {}, 2000);
|
|
221
|
+
try {
|
|
222
|
+
process.kill(process.pid, finalSignal);
|
|
223
|
+
} catch (_) {
|
|
224
|
+
process.kill(process.pid, "SIGTERM");
|
|
225
|
+
}
|
|
226
|
+
} else {
|
|
227
|
+
process.exit(finalCode ?? 0);
|
|
228
|
+
}
|
|
229
|
+
});
|
|
230
|
+
|
|
231
|
+
if (process.send) {
|
|
232
|
+
process.removeAllListeners("message");
|
|
233
|
+
child.on("message", (message, sendHandle) => {
|
|
234
|
+
process.send?.(message, sendHandle);
|
|
235
|
+
});
|
|
236
|
+
process.on("message", (message, sendHandle) => {
|
|
237
|
+
if (message === null) return;
|
|
238
|
+
child.send(message, sendHandle);
|
|
239
|
+
});
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
return child;
|
|
243
|
+
}
|