|
3 | 3 |
|
4 | 4 | void (async () => { |
5 | 5 | const Module = require('node:module') |
| 6 | + const os = require('node:os') |
6 | 7 | const path = require('node:path') |
7 | 8 | const rootPath = path.join(__dirname, '..') |
8 | 9 | Module.enableCompileCache?.(path.join(rootPath, '.cache')) |
@@ -38,10 +39,41 @@ void (async () => { |
38 | 39 | }, |
39 | 40 | ) |
40 | 41 |
|
| 42 | + // The child shares our process group and handles the signal itself; wait briefly for it |
| 43 | + // to exit (so its final output isn't printed after the prompt returns) and mirror its |
| 44 | + // exit below. SIGKILL and leave if it outlasts the grace, or on a second signal. |
| 45 | + const SHUTDOWN_GRACE_MS = 3_000 |
| 46 | + const hardAbort = signalName => { |
| 47 | + const child = spawnPromise.process |
| 48 | + if (child.exitCode === null && child.signalCode === null) { |
| 49 | + child.kill('SIGKILL') |
| 50 | + } |
| 51 | + // eslint-disable-next-line n/no-process-exit |
| 52 | + process.exit(signalName === 'SIGTERM' ? 143 : 130) |
| 53 | + } |
| 54 | + let sawSignal = false |
| 55 | + const onSignal = signalName => { |
| 56 | + if (sawSignal) { |
| 57 | + hardAbort(signalName) |
| 58 | + return |
| 59 | + } |
| 60 | + sawSignal = true |
| 61 | + setTimeout(() => hardAbort(signalName), SHUTDOWN_GRACE_MS).unref?.() |
| 62 | + } |
| 63 | + const onSigint = () => onSignal('SIGINT') |
| 64 | + const onSigterm = () => onSignal('SIGTERM') |
| 65 | + process.on('SIGINT', onSigint) |
| 66 | + process.on('SIGTERM', onSigterm) |
| 67 | + |
41 | 68 | // See https://nodejs.org/api/child_process.html#event-exit. |
42 | 69 | spawnPromise.process.on('exit', (code, signalName) => { |
43 | 70 | if (signalName) { |
44 | | - process.kill(process.pid, signalName) |
| 71 | + // Mirror a signal death as the conventional 128 + signum exit code. Exit explicitly |
| 72 | + // rather than re-raising the signal: with our handlers installed the re-raise would |
| 73 | + // race `await spawnPromise` resolving and could leave the default exitCode of 1. |
| 74 | + const signum = os.constants.signals[signalName] ?? 0 |
| 75 | + // eslint-disable-next-line n/no-process-exit |
| 76 | + process.exit(128 + signum) |
45 | 77 | } else if (typeof code === 'number') { |
46 | 78 | // eslint-disable-next-line n/no-process-exit |
47 | 79 | process.exit(code) |
|
0 commit comments