1
0
silverbullet/packages/plugos/environments/webworker_sandbox.ts

38 lines
981 B
TypeScript
Raw Normal View History

2022-03-23 14:41:12 +00:00
import { safeRun } from "../util";
import { Sandbox } from "../sandbox";
import { WorkerLike } from "./worker";
2022-03-25 11:03:06 +00:00
import { Plug } from "../plug";
class WebWorkerWrapper implements WorkerLike {
private worker: Worker;
onMessage?: (message: any) => Promise<void>;
2022-03-21 14:21:34 +00:00
ready: Promise<void>;
constructor(worker: Worker) {
this.worker = worker;
this.worker.addEventListener("message", (evt: any) => {
let data = evt.data;
if (!data) return;
safeRun(async () => {
await this.onMessage!(data);
});
});
2022-03-21 14:21:34 +00:00
this.ready = Promise.resolve();
}
postMessage(message: any): void {
this.worker.postMessage(message);
}
terminate() {
return this.worker.terminate();
}
}
2022-03-25 11:03:06 +00:00
export function createSandbox(plug: Plug<any>) {
// ParcelJS will build this file into a worker.
let worker = new Worker(new URL("sandbox_worker.ts", import.meta.url), {
type: "module",
});
2022-03-25 11:03:06 +00:00
return new Sandbox(plug, new WebWorkerWrapper(worker));
}