diff --git a/src/node/index.js b/src/node/index.js index e41d2ea..50482ea 100644 --- a/src/node/index.js +++ b/src/node/index.js @@ -23,6 +23,9 @@ import threads from 'worker_threads'; const WORKER = Symbol.for('worker'); const EVENTS = Symbol.for('events'); +// sadly we can't use a symbol here, since it can't be cloned across the thread boundary. so we use a unique string instead. +const IS_WORKER_ATTR = '__web_worker_is_worker_5ecb39d8-bb28-4239-85f5-4c508c499d39__'; + class EventTarget { constructor() { Object.defineProperty(this, EVENTS, { @@ -104,7 +107,7 @@ function mainThread() { } const worker = new threads.Worker( fileURLToPath(import.meta.url), - { workerData: { mod, name, type } } + { workerData: { mod, name, type, [IS_WORKER_ATTR]: true } } ); Object.defineProperty(this, WORKER, { value: worker @@ -138,8 +141,11 @@ function workerThread() { if (typeof global.WorkerGlobalScope === 'function') { return; } - let { mod, name, type } = threads.workerData; - if (!mod) return mainThread(); + if (typeof threads.workerData !== 'object' || !threads.workerData[IS_WORKER_ATTR]) { + return mainThread(); + } + + let { mod, name, type } = threads.workerData ?? {}; // turn global into a mock WorkerGlobalScope const self = global.self = global;