microsoft/qdk

Public

mirrored from https://github.com/microsoft/qdkAvailable

CodeCommitsIssuesPull requestsActionsInsightsSecurity
fedimser/memory-re

Branches

Tags

  • No tags available.
0Branches0Tags
Go to file
Add file
Code

Clone

HTTPS

Download ZIP

source/npm/qsharp/src/workers/adapters/browser.ts

41lines · modecode

1// Copyright (c) Microsoft Corporation.
2// Licensed under the MIT License.
3
4import type { IWorkerHost } from "./types.js";
5
6export class BrowserWorkerHost implements IWorkerHost {
7 private worker: Worker;
8
9 constructor(url: string | URL) {
10 // Resolve to an absolute URL because importScripts inside a blob worker
11 // cannot resolve relative URLs (there is no base URL to resolve against).
12 // Note: import.meta.url is replaced with document.URL by the bundler.
13 const scriptUrl =
14 typeof url === "string" ? new URL(url, import.meta.url).href : url.href;
15 const bootstrap = `
16 self.WorkerSelf = {
17 postMessage(msg) { self.postMessage(msg); },
18 onMessage(handler) { self.addEventListener("message", handler); }
19 };
20 importScripts("${scriptUrl}");
21 `;
22 const blob = new Blob([bootstrap], { type: "application/javascript" });
23 this.worker = new Worker(URL.createObjectURL(blob));
24 }
25
26 postMessage(msg: unknown): void {
27 this.worker.postMessage(msg);
28 }
29
30 onMessage(handler: (e: MessageEvent) => void): void {
31 this.worker.onmessage = handler;
32 }
33
34 onError(handler: (e: Event) => void): void {
35 this.worker.onerror = handler;
36 }
37
38 terminate(): void {
39 this.worker.terminate();
40 }
41}
42