1/// <reference lib="webworker" />
2/**
3 * Web Worker that owns a numbl instance. One run at a time; the host cancels a
4 * run by terminating the worker, which is why nothing here needs to be
5 * interruptible.
6 */
7import { executeBundle, numblVersion } from "./execute";
8import { collectBuffers } from "./plain";
9import type { FromWorker, ToWorker } from "./protocol";
10import type { BackendInfo } from "./types";
12const backend: BackendInfo = { engine: "numbl", version: numblVersion(), optimization: "1", host: "web-worker" };
14const post = (msg: FromWorker, transfer: ArrayBuffer[] = []) => self.postMessage(msg, transfer);
16self.onmessage = (e: MessageEvent<ToWorker>) => {
17 const msg = e.data;
18 if (msg.type === "info") {
19 post({ type: "info", id: msg.id, backend });
20 return;
21 }
22 const result = executeBundle({ bundle: msg.bundle, inputs: msg.inputs }, backend, (text) =>
23 post({ type: "output", id: msg.id, text }),
24 );
25 const transfer = result.ok ? collectBuffers(result.value) : [];
26 post({ type: "done", id: msg.id, result }, transfer);
27};