diff --git a/packages/next/src/lib/worker.ts b/packages/next/src/lib/worker.ts index 2581fbbad80bb..edba72894e76f 100644 --- a/packages/next/src/lib/worker.ts +++ b/packages/next/src/lib/worker.ts @@ -14,6 +14,7 @@ export class Worker { timeout?: number onRestart?: (method: string, args: any[], attempts: number) => void exposedMethods: ReadonlyArray + enableWorkerThreads?: boolean } ) { let { timeout, onRestart, ...farmOptions } = options @@ -44,18 +45,29 @@ export class Worker { (resolve) => (resolveRestartPromise = resolve) ) - for (const worker of ((this._worker as any)._workerPool?._workers || - []) as { - _child: ChildProcess - }[]) { - worker._child.on('exit', (code, signal) => { - // log unexpected exit if .end() wasn't called - if ((code || signal) && this._worker) { - console.error( - `Static worker unexpectedly exited with code: ${code} and signal: ${signal}` - ) - } - }) + /** + * Jest Worker has two worker types, ChildProcessWorker (uses child_process) and NodeThreadWorker (uses worker_threads) + * Next.js uses ChildProcessWorker by default, but it can be switched to NodeThreadWorker with an experimental flag + * + * We only want to handle ChildProcessWorker's orphan process issue, so we access the private property "_child": + * https://github.com/facebook/jest/blob/b38d7d345a81d97d1dc3b68b8458b1837fbf19be/packages/jest-worker/src/workers/ChildProcessWorker.ts + * + * But this property is not available in NodeThreadWorker, so we need to check if we are using ChildProcessWorker + */ + if (!farmOptions.enableWorkerThreads) { + for (const worker of ((this._worker as any)._workerPool?._workers || + []) as { + _child?: ChildProcess + }[]) { + worker._child?.on('exit', (code, signal) => { + // log unexpected exit if .end() wasn't called + if ((code || signal) && this._worker) { + console.error( + `Static worker unexpectedly exited with code: ${code} and signal: ${signal}` + ) + } + }) + } } this._worker.getStdout().pipe(process.stdout)