2022-10-10 12:50:21 +00:00
|
|
|
import { safeRun } from "../util.ts";
|
2022-03-20 08:56:28 +00:00
|
|
|
|
2022-10-10 12:50:21 +00:00
|
|
|
import { Sandbox } from "../sandbox.ts";
|
|
|
|
import { WorkerLike } from "./worker.ts";
|
|
|
|
import { Plug } from "../plug.ts";
|
2022-10-11 09:38:10 +00:00
|
|
|
import { AssetBundle, assetReadTextFileSync } from "../asset_bundle_reader.ts";
|
2022-10-10 12:50:21 +00:00
|
|
|
|
|
|
|
class DenoWorkerWrapper implements WorkerLike {
|
2022-03-20 08:56:28 +00:00
|
|
|
private worker: Worker;
|
|
|
|
onMessage?: (message: any) => Promise<void>;
|
2022-03-21 14:21:34 +00:00
|
|
|
ready: Promise<void>;
|
2022-03-20 08:56:28 +00:00
|
|
|
|
|
|
|
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();
|
2022-03-20 08:56:28 +00:00
|
|
|
}
|
|
|
|
postMessage(message: any): void {
|
|
|
|
this.worker.postMessage(message);
|
|
|
|
}
|
|
|
|
|
|
|
|
terminate() {
|
|
|
|
return this.worker.terminate();
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-10-11 09:38:10 +00:00
|
|
|
export function sanboxFactory(
|
|
|
|
assetBundle: AssetBundle,
|
|
|
|
): (plug: Plug<any>) => Sandbox {
|
|
|
|
return (plug: Plug<any>) => {
|
|
|
|
const workerHref = URL.createObjectURL(
|
|
|
|
new Blob([
|
|
|
|
assetReadTextFileSync(assetBundle, "web/worker.js"),
|
|
|
|
], {
|
|
|
|
type: "application/javascript",
|
|
|
|
}),
|
|
|
|
);
|
|
|
|
let worker = new Worker(
|
|
|
|
workerHref,
|
|
|
|
{
|
|
|
|
type: "module",
|
|
|
|
},
|
|
|
|
);
|
|
|
|
return new Sandbox(plug, new DenoWorkerWrapper(worker));
|
|
|
|
};
|
2022-03-20 08:56:28 +00:00
|
|
|
}
|