-
-
Notifications
You must be signed in to change notification settings - Fork 154
/
preflight.cts
80 lines (71 loc) · 2.17 KB
/
preflight.cts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
import { constants as osConstants } from 'node:os';
import { isMainThread } from 'node:worker_threads';
import { connectingToServer } from './utils/ipc/client.js';
import './suppress-warnings.cjs';
type BaseEventListener = () => void;
const bindHiddenSignalsHandler = (
signals: NodeJS.Signals[],
handler: NodeJS.SignalsListener,
) => {
type RelaySignals = typeof signals[number];
for (const signal of signals) {
process.on(signal, (receivedSignal) => {
handler(receivedSignal);
/**
* Since we're setting a custom signal handler, we need to emulate the
* default behavior when there are no other handlers set
*/
if (process.listenerCount(signal) === 0) {
// eslint-disable-next-line n/no-process-exit
process.exit(128 + osConstants.signals[signal]);
}
});
}
/**
* Hide relaySignal from process.listeners() and process.listenerCount()
*/
const { listenerCount, listeners } = process;
process.listenerCount = function (eventName) {
let count = Reflect.apply(listenerCount, this, arguments);
if (signals.includes(eventName as RelaySignals)) {
count -= 1;
}
return count;
};
process.listeners = function (eventName) {
const result: BaseEventListener[] = Reflect.apply(listeners, this, arguments);
if (signals.includes(eventName as RelaySignals)) {
return result.filter(listener => listener !== handler);
}
return result;
};
};
/**
* Seems module.register() calls the loader with the same Node arguments
* which causes this preflight to be loaded in the loader thread
*/
if (isMainThread) {
/**
* Hook require() to transform to CJS
*
* This needs to be loaded via --require flag so subsequent --require
* flags can support TypeScript.
*
* This is also added in loader.ts for the loader API.
* Although it is required twice, it's not executed twice because
* it's cached.
*/
// eslint-disable-next-line import-x/no-unresolved, n/global-require
require('./cjs/index.cjs');
(async () => {
const sendToParent = await connectingToServer;
if (sendToParent) {
bindHiddenSignalsHandler(['SIGINT', 'SIGTERM'], (signal: NodeJS.Signals) => {
sendToParent({
type: 'signal',
signal,
});
});
}
})();
}