1
0
silverbullet/plugos/environments/deno_sandbox.ts

53 lines
1.3 KiB
TypeScript
Raw Normal View History

import { safeRun } from "../util.ts";
import { Sandbox } from "../sandbox.ts";
import { WorkerLike } from "./worker.ts";
import { Plug } from "../plug.ts";
2022-10-12 09:47:13 +00:00
import { AssetBundle } from "../asset_bundle/bundle.ts";
class DenoWorkerWrapper 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) => {
2022-10-12 09:47:13 +00:00
const 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-10-12 09:47:13 +00:00
import workerBundleJson from "./worker_bundle.json" assert { type: "json" };
const workerBundle = new AssetBundle(workerBundleJson);
export function createSandbox(plug: Plug<any>) {
const workerHref = URL.createObjectURL(
new Blob([
workerBundle.readFileSync("worker.js"),
], {
type: "application/javascript",
}),
);
const worker = new Worker(
workerHref,
{
type: "module",
},
);
return new Sandbox(plug, new DenoWorkerWrapper(worker));
}