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

57 lines
1.4 KiB
TypeScript
Raw Normal View History

import { Worker } from "worker_threads";
2022-03-23 14:41:12 +00:00
import { safeRun } from "../util";
// @ts-ignore
2022-03-21 14:21:34 +00:00
import workerCode from "bundle-text:./node_worker.ts";
2022-03-23 14:41:12 +00:00
import { Sandbox } from "../sandbox";
import { WorkerLike } from "./worker";
2022-03-25 11:03:06 +00:00
import { Plug } from "../plug";
2022-03-27 07:55:29 +00:00
import path from "path";
import fs from "fs";
class NodeWorkerWrapper implements WorkerLike {
onMessage?: (message: any) => Promise<void>;
2022-03-21 14:21:34 +00:00
ready: Promise<void>;
2022-04-09 12:28:41 +00:00
private worker: Worker;
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();
}
}
2022-03-27 07:55:29 +00:00
// Look for the node_modules directory, to be passed to the worker to find e.g. the vm2 module
2022-04-25 08:33:38 +00:00
export let nodeModulesDir = __dirname;
while (!fs.existsSync(nodeModulesDir + "/node_modules/vm2")) {
2022-03-27 07:55:29 +00:00
nodeModulesDir = path.dirname(nodeModulesDir);
}
2022-04-25 08:33:38 +00:00
export function createSandbox(
plug: Plug<any>,
preloadedModules: string[] = []
) {
2022-03-21 14:21:34 +00:00
let worker = new Worker(workerCode, {
eval: true,
2022-04-25 08:33:38 +00:00
workerData: {
nodeModulesPath: path.join(nodeModulesDir, "node_modules"),
preloadedModules,
},
2022-03-21 14:21:34 +00:00
});
2022-03-27 07:55:29 +00:00
return new Sandbox(plug, new NodeWorkerWrapper(worker));
}