diff --git a/cli/tests/fix_worker_dispatchevent.ts b/cli/tests/fix_worker_dispatchevent.ts new file mode 100644 index 0000000000..1b73b52dcb --- /dev/null +++ b/cli/tests/fix_worker_dispatchevent.ts @@ -0,0 +1,43 @@ +const code = ` +addEventListener("message", () => { + postMessage("pong"); +}); + +const context = new EventTarget(); + +Object.defineProperty(globalThis, "dispatchEvent", { + value: context.dispatchEvent.bind(context), + writable: true, + enumerable: true, + configurable: true, +}); + +postMessage("start"); +`; + +const blob = new Blob([code], { type: "application/javascript" }); + +const url = URL.createObjectURL(blob); + +const worker = new Worker(url, { type: "module" }); + +let terminated = false; + +worker.addEventListener("message", (evt) => { + if (evt.data === "start") { + worker.postMessage("ping"); + } else if (evt.data === "pong") { + worker.terminate(); + terminated = true; + console.log("success"); + } else { + throw new Error("unexpected message from worker"); + } +}); + +setTimeout(() => { + if (!terminated) { + worker.terminate(); + throw new Error("did not receive message from worker in time"); + } +}, 2000); diff --git a/cli/tests/fix_worker_dispatchevent.ts.out b/cli/tests/fix_worker_dispatchevent.ts.out new file mode 100644 index 0000000000..2e9ba477f8 --- /dev/null +++ b/cli/tests/fix_worker_dispatchevent.ts.out @@ -0,0 +1 @@ +success diff --git a/cli/tests/integration_tests.rs b/cli/tests/integration_tests.rs index bc67d54799..3d606b2a59 100644 --- a/cli/tests/integration_tests.rs +++ b/cli/tests/integration_tests.rs @@ -3972,6 +3972,11 @@ console.log("finish"); output: "fix_tsc_file_exists.out", }); + itest!(fix_worker_dispatchevent { + args: "run --quiet --reload fix_worker_dispatchevent.ts", + output: "fix_worker_dispatchevent.ts.out", + }); + itest!(es_private_fields { args: "run --quiet --reload es_private_fields.js", output: "es_private_fields.js.out", diff --git a/runtime/js/99_main.js b/runtime/js/99_main.js index f196f3008e..aac6fc0ead 100644 --- a/runtime/js/99_main.js +++ b/runtime/js/99_main.js @@ -82,7 +82,12 @@ delete Object.prototype.__proto__; } let isClosing = false; + let globalDispatchEvent; + async function pollForMessages() { + if (!globalDispatchEvent) { + globalDispatchEvent = globalThis.dispatchEvent.bind(globalThis); + } while (!isClosing) { const bufferMsg = await core.opAsync("op_worker_get_message"); const data = core.deserialize(bufferMsg); @@ -96,7 +101,7 @@ delete Object.prototype.__proto__; if (globalThis.onmessage) { await globalThis.onmessage(msgEvent); } - globalThis.dispatchEvent(msgEvent); + globalDispatchEvent(msgEvent); } catch (e) { let handled = false; @@ -120,7 +125,7 @@ delete Object.prototype.__proto__; handled = ret === true; } - globalThis.dispatchEvent(errorEvent); + globalDispatchEvent(errorEvent); if (errorEvent.defaultPrevented) { handled = true; }