Fix Webpack erroring with worker_threads import, unref Worker so process can terminate

This commit is contained in:
Vanilagy
2026-02-17 12:34:45 +01:00
parent 4928779ba1
commit 317193452c
4 changed files with 56 additions and 10 deletions
+41 -2
View File
@@ -10,13 +10,51 @@ import { assert, type WorkerCommand, type WorkerResponse, type WorkerResponseDat
// @ts-expect-error An esbuild plugin handles this, TypeScript doesn't need to understand
import createWorker from './codec.worker';
let workerPromise: Promise<Worker> | null;
type ExtendedWorker = Worker & {
ref?: () => void;
unref?: () => void;
};
let workerPromise: Promise<ExtendedWorker> | null;
let nextMessageId = 0;
const pendingMessages = new Map<number, {
resolve: (value: WorkerResponseData) => void;
reject: (reason?: unknown) => void;
}>();
let refCount = 0;
let keepAliveInterval: ReturnType<typeof setInterval> | null = null;
export const refWorker = async () => {
refCount++;
if (refCount === 1) {
keepAliveInterval = setInterval(() => {}, 2 ** 31 - 1);
const worker = await ensureWorker();
worker.ref?.();
}
};
export const unrefWorker = async () => {
refCount--;
if (refCount === 0) {
if (keepAliveInterval !== null) {
clearInterval(keepAliveInterval);
keepAliveInterval = null;
}
const worker = await workerPromise;
if (worker) {
if (worker.unref) {
worker.unref(); // If we don't do this, then the Node process never terminates by itself
} else if (typeof window === 'undefined') {
// Non-browser environment without unref - terminate instead
worker.terminate();
workerPromise = null;
}
}
}
};
export const sendCommand = async <T extends string>(
command: WorkerCommand & { type: T },
transferables?: Transferable[],
@@ -41,7 +79,8 @@ export const sendCommand = async <T extends string>(
const ensureWorker = () => {
return workerPromise ??= (async () => {
// eslint-disable-next-line @typescript-eslint/no-unsafe-call
const worker = (await createWorker()) as Worker;
const worker = (await createWorker()) as ExtendedWorker;
worker.unref?.(); // Start unreffed
const onMessage = (data: WorkerResponse) => {
const pending = pendingMessages.get(data.id);