1
0
silverbullet/plugbox/node_sandbox.ts

50 lines
1.1 KiB
TypeScript
Raw Normal View History

import { ControllerMessage, WorkerLike, WorkerMessage } from "./types";
import { System, Sandbox } from "./runtime";
import { Worker } from "worker_threads";
import * as fs from "fs";
import { safeRun } from "./util";
// @ts-ignore
2022-03-21 14:21:34 +00:00
import workerCode from "bundle-text:./node_worker.ts";
class NodeWorkerWrapper implements WorkerLike {
onMessage?: (message: any) => Promise<void>;
private worker: Worker;
2022-03-21 14:21:34 +00:00
ready: Promise<void>;
constructor(worker: Worker) {
this.worker = worker;
worker.on("message", (message: any) => {
safeRun(async () => {
await this.onMessage!(message);
});
});
2022-03-21 14:21:34 +00:00
this.ready = new Promise((resolve) => {
worker.once("online", resolve);
});
}
postMessage(message: any): void {
this.worker.postMessage(message);
}
terminate(): void {
this.worker.terminate();
}
}
export function createSandbox(system: System<any>) {
2022-03-21 14:21:34 +00:00
let worker = new Worker(workerCode, {
eval: true,
});
return new Sandbox(
system,
new NodeWorkerWrapper(
new Worker(workerCode, {
eval: true,
})
)
);
}