88
99globalThis . self = globalThis ;
1010
11+ // Polyfill ErrorEvent globally as it is used in both contexts
1112globalThis . 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+ */
2832if ( 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+ */
8188if ( ! 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