Skip to content

Commit 4ba8964

Browse files
committed
Added isMainThread and isWorkerThread runtime variables
1 parent ca1df1e commit 4ba8964

File tree

2 files changed

+27
-3
lines changed

2 files changed

+27
-3
lines changed

src/lib/lib.ts

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -123,3 +123,9 @@ export function shutdown() {
123123
globalPool.terminate();
124124
}
125125
}
126+
127+
const isWorker = typeof globalThis.WorkerGlobalScope !== "undefined" &&
128+
self instanceof globalThis.WorkerGlobalScope;
129+
130+
export const isMainThread = !isWorker;
131+
export const isWorkerThread = isWorker;

src/node/polyfill.ts

Lines changed: 21 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ import {
88

99
globalThis.self = globalThis;
1010

11+
// Polyfill ErrorEvent globally as it is used in both contexts
1112
globalThis.ErrorEvent = class ErrorEvent extends Event {
1213
public message: string;
1314
public filename: string;
@@ -25,6 +26,9 @@ globalThis.ErrorEvent = class ErrorEvent extends Event {
2526
}
2627
};
2728

29+
/**
30+
* Main Thread Implementation
31+
*/
2832
if (isMainThread) {
2933
// Directly overwrite global Worker
3034
globalThis.Worker = class Worker extends EventTarget {
@@ -78,7 +82,20 @@ if (isMainThread) {
7882
};
7983
}
8084

85+
/**
86+
* Worker Thread Implementation
87+
*/
8188
if (!isMainThread && parentPort) {
89+
// We use Symbol.hasInstance so that "self instanceof WorkerGlobalScope" returns true
90+
// even though we can't easily change the prototype of the global Node object.
91+
class WorkerGlobalScope extends EventTarget {
92+
static [Symbol.hasInstance](instance) {
93+
return instance === globalThis;
94+
}
95+
}
96+
97+
globalThis.WorkerGlobalScope = WorkerGlobalScope;
98+
8299
// Polyfill postMessage
83100
globalThis.postMessage = (message: any, transfer?: Transferable[]) => {
84101
parentPort.postMessage(message, transfer);
@@ -88,9 +105,10 @@ if (!isMainThread && parentPort) {
88105
let currentHandler = globalThis.onmessage;
89106

90107
parentPort.on("message", (data) => {
91-
if (currentHandler) {
92-
const event = new MessageEvent("message", { data });
93-
currentHandler(event);
108+
const event = new MessageEvent("message", { data });
109+
110+
if (typeof globalThis.onmessage === "function") {
111+
globalThis.onmessage(event);
94112
}
95113
});
96114

0 commit comments

Comments
 (0)