Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
sagemathinc
GitHub Repository: sagemathinc/wapython
Path: blob/main/core/kernel/src/wasm/import-node.ts
1067 views
1
import { Options, WasmInstanceAbstractBaseClass, WorkerThread } from "./import";
2
import { Worker } from "worker_threads";
3
import { join } from "path";
4
import process from "node:process";
5
import debug from "debug";
6
import IOProviderUsingAtomics from "./io-using-atomics";
7
import type { WasmInstanceAsync } from "./types";
8
9
const log = debug("wasm:import-node");
10
11
export class WasmInstance extends WasmInstanceAbstractBaseClass {
12
protected initWorker(): WorkerThread {
13
const path = join(__dirname, "worker", "node.js");
14
return new Worker(path, {
15
trackUnmanagedFds: false, // this seems incompatible with our use of unionfs/memfs (lots of warnings).
16
});
17
}
18
19
protected configureTerminal() {
20
const stdinListeners: any[] = process.stdin.listeners("data");
21
for (const f of stdinListeners) {
22
// save listeners on stdin so we can restore them
23
// when the terminal finishes
24
process.stdin.removeListener("data", f);
25
}
26
if (this.worker == null) throw Error("configureTerminal - bug");
27
this.worker.on("exit", () => {
28
// put back the original listeners on stdin
29
for (const f of stdinListeners) {
30
process.stdin.addListener("data", f);
31
}
32
});
33
process.stdin.on("data", (data) => {
34
if (log.enabled) {
35
log("stdin", data.toString());
36
}
37
this.writeToStdin(data);
38
});
39
}
40
}
41
42
export default async function wasmImportNodeWorker(
43
wasmSource: string, // name of the wasm file
44
options: Options
45
): Promise<WasmInstanceAsync> {
46
return new WasmInstance(wasmSource, options, IOProviderUsingAtomics);
47
}
48
49