From 79b6f1682e571cb42b49ebbb9419b4c693ee9e0d Mon Sep 17 00:00:00 2001 From: Hiroki Osame Date: Sat, 25 Nov 2023 11:56:05 +0900 Subject: [PATCH] fix: prevent preflight from running in loader --- src/preflight.cts | 63 ++++++++++++++++++++++++++--------------------- 1 file changed, 35 insertions(+), 28 deletions(-) diff --git a/src/preflight.cts b/src/preflight.cts index 396825e43..461896daa 100644 --- a/src/preflight.cts +++ b/src/preflight.cts @@ -1,21 +1,9 @@ +import { isMainThread } from 'node:worker_threads'; import { constants as osConstants } from 'os'; import './suppress-warnings.cts'; type BaseEventListener = () => void; -/** - * 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/no-unresolved -require('./cjs/index.cjs'); - const bindHiddenSignalsHandler = ( signals: NodeJS.Signals[], handler: NodeJS.SignalsListener, @@ -47,20 +35,39 @@ const bindHiddenSignalsHandler = ( }; }; -// If a parent process is detected -if (process.send) { - bindHiddenSignalsHandler(['SIGINT', 'SIGTERM'], (signal: NodeJS.Signals) => { - process.send!({ - type: 'kill', - signal, - }); +/** + * 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/no-unresolved + require('./cjs/index.cjs'); - /** - * 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) { - process.exit(128 + osConstants.signals[signal]); - } - }); + // If a parent process is detected + if (process.send) { + bindHiddenSignalsHandler(['SIGINT', 'SIGTERM'], (signal: NodeJS.Signals) => { + process.send!({ + type: 'kill', + signal, + }); + + /** + * 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) { + process.exit(128 + osConstants.signals[signal]); + } + }); + } }