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-12 09:47:13 +00:00
|
|
|
import { AssetBundle } from "../asset_bundle/bundle.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) => {
|
2022-10-12 09:47:13 +00:00
|
|
|
const data = evt.data;
|
2022-03-20 08:56:28 +00:00
|
|
|
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-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",
|
2022-10-17 13:56:47 +00:00
|
|
|
deno: {
|
|
|
|
permissions: {
|
2023-01-08 11:24:12 +00:00
|
|
|
// Disallow network access
|
|
|
|
net: false,
|
2022-10-28 14:17:40 +00:00
|
|
|
// This is required for console logging to work, apparently?
|
2022-10-17 13:56:47 +00:00
|
|
|
env: true,
|
|
|
|
// No talking to native code
|
|
|
|
ffi: false,
|
|
|
|
// No invocation of shell commands
|
|
|
|
run: false,
|
|
|
|
// No read access to the file system
|
|
|
|
read: false,
|
|
|
|
// No write access to the file system
|
|
|
|
write: false,
|
|
|
|
},
|
|
|
|
},
|
|
|
|
// Have to do this because the "deno" option is not standard and doesn't typecheck yet
|
|
|
|
} as any,
|
2022-10-12 09:47:13 +00:00
|
|
|
);
|
|
|
|
return new Sandbox(plug, new DenoWorkerWrapper(worker));
|
2022-03-20 08:56:28 +00:00
|
|
|
}
|