@beetlebug/ztcl 0.2.0-beta → 1.0.0-beta.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,224 @@
1
+ // ztcl with the capability `thread` in a browser and in Node.js.
2
+ //
3
+ // import { ThreadInterp } from "./ztcl-threads.mjs";
4
+ // const t = await ThreadInterp.create({ allow: ["thread"] });
5
+ // const r = await t.eval("thread::send [thread::create] {expr 6 * 7}");
6
+ // t.close();
7
+ //
8
+ // Each ztcl thread runs in a worker (web/ztcl-thread-worker.mjs), the
9
+ // main interpreter too. This module is the host: it makes the workers
10
+ // and routes their messages. It has two modes:
11
+ //
12
+ // - shared: a cross-origin isolated page, or Node.js. The workers use
13
+ // ztcl-threads.wasm on one shared memory, and each command works.
14
+ // - async: a page without cross-origin isolation. The workers use
15
+ // ztcl-async.wasm, each with its own memory. Only the commands that
16
+ // do not wait work. A command that waits gives an error that names
17
+ // the headers COOP and COEP.
18
+ // SPDX-License-Identifier: BSD-2-Clause
19
+
20
+ import { compile } from "./ztcl.mjs";
21
+
22
+ const node = typeof process !== "undefined" && !!process.versions?.node && typeof window === "undefined";
23
+
24
+ /// The capability bits of `Capability` in src/interp.zig.
25
+ const CAPS = { package: 1, interp: 2, clock: 4, event: 32, thread: 2048 };
26
+
27
+ /// The sizes of the shared memory in pages of 64 KiB. build.zig sets the
28
+ /// same sizes for ztcl-threads.wasm.
29
+ const INITIAL_PAGES = 512;
30
+ /// The shared mode keeps at most this many workers with no thread.
31
+ const MAX_IDLE = 64;
32
+ const MAX_PAGES = 32768;
33
+
34
+ // A string in the byte form of src/webasync.zig.
35
+ function stringBytes(text) {
36
+ const t = new TextEncoder().encode(text);
37
+ const b = new Uint8Array(5 + t.length);
38
+ b[0] = 0x73; // "s"
39
+ new DataView(b.buffer).setUint32(1, t.length, true);
40
+ b.set(t, 5);
41
+ return b;
42
+ }
43
+
44
+ export function threadsURL() {
45
+ return new URL("./ztcl-threads.wasm", import.meta.url);
46
+ }
47
+
48
+ export function asyncURL() {
49
+ return new URL("./ztcl-async.wasm", import.meta.url);
50
+ }
51
+
52
+ /// True when the host can use the shared mode.
53
+ export function isolated() {
54
+ return node || globalThis.crossOriginIsolated === true;
55
+ }
56
+
57
+ const NodeWorker = node ? (await import("node:worker_threads")).Worker : null;
58
+
59
+ function makeWorker() {
60
+ const url = new URL("./ztcl-thread-worker.mjs", import.meta.url);
61
+ if (node) {
62
+ const w = new NodeWorker(url);
63
+ return { post: (m) => w.postMessage(m), on: (f) => w.on("message", f), onError: (f) => w.on("error", f), stop: () => w.terminate() };
64
+ }
65
+ let w;
66
+ if (globalThis.location && url.origin !== globalThis.location.origin) {
67
+ // A worker script must have the origin of the page.
68
+ const blob = new Blob([`import ${JSON.stringify(url.href)};`], { type: "text/javascript" });
69
+ w = new Worker(URL.createObjectURL(blob), { type: "module" });
70
+ } else {
71
+ w = new Worker(url, { type: "module" });
72
+ }
73
+ return { post: (m) => w.postMessage(m), on: (f) => (w.onmessage = ({ data }) => f(data)), onError: (f) => (w.onerror = (e) => f(e)), stop: () => w.terminate() };
74
+ }
75
+
76
+ export class ThreadInterp {
77
+ /// Options: `mode` ("auto", "shared", or "async"), `wasm` (the URL of
78
+ /// ztcl-threads.wasm), `asyncWasm` (the URL of ztcl-async.wasm),
79
+ /// `allow` (capability names: "thread", "event", "clock", "package",
80
+ /// "interp"), `limits` (maxThreads, computeLimit, memLimit, totalCompute,
81
+ /// totalMem, maxQueue), `computeLimit`, `memLimit`, and `onOutput`.
82
+ static async create(options = {}) {
83
+ const t = new ThreadInterp(options);
84
+ await t._start();
85
+ return t;
86
+ }
87
+
88
+ constructor({ mode = "auto", wasm, asyncWasm, allow = ["thread"], limits = {}, computeLimit = null, memLimit = null, onOutput = null } = {}) {
89
+ if (mode === "auto") mode = isolated() ? "shared" : "async";
90
+ if (mode === "shared" && !isolated()) throw new Error("the shared mode needs a cross-origin isolated page (COOP and COEP headers)");
91
+ this.mode = mode;
92
+ this.wasm = mode === "shared" ? (wasm ?? threadsURL()) : (asyncWasm ?? asyncURL());
93
+ this.caps = 0;
94
+ for (const c of allow) {
95
+ if (!(c in CAPS)) throw new Error(`unknown capability: ${c}`);
96
+ this.caps |= CAPS[c];
97
+ }
98
+ this.limits = limits;
99
+ this.computeLimit = computeLimit;
100
+ this.memLimit = memLimit;
101
+ this.onOutput = onOutput;
102
+ this.workers = new Map(); // id to worker; the main interpreter is 1
103
+ this.idle = []; // the shared mode: the workers with no thread
104
+ this.pending = new Map();
105
+ this.next = 1;
106
+ this.failure = null;
107
+ }
108
+
109
+ async _start() {
110
+ this.module = await compile(this.wasm);
111
+ if (this.mode === "shared") this.memory = new WebAssembly.Memory({ initial: INITIAL_PAGES, maximum: MAX_PAGES, shared: true });
112
+ this.main = await this._worker(1, { role: "main", memLimit: this.memLimit });
113
+ }
114
+
115
+ // Makes a worker and waits for its `ready`. A message to the worker
116
+ // can go before the `ready`: the worker runs its messages in order.
117
+ async _worker(id, init) {
118
+ const w = makeWorker();
119
+ this.workers.set(id, w);
120
+ // A failure before the `ready` rejects the start.
121
+ const ready = new Promise((resolve, reject) => {
122
+ w.ready = resolve;
123
+ w.failStart = reject;
124
+ });
125
+ w.on((m) => this._message(id, w, m));
126
+ w.onError((e) => {
127
+ w.failStart(new Error(e?.message ?? String(e)));
128
+ this._fail(e?.message ?? String(e));
129
+ });
130
+ const base = { module: this.module, id, caps: this.caps, limits: this.limits };
131
+ if (this.memory) base.memory = this.memory;
132
+ w.post({ init: { ...base, ...init } });
133
+ await ready;
134
+ return w;
135
+ }
136
+
137
+ _message(id, w, m) {
138
+ if (m.ready) return w.ready();
139
+ if (m.output) this.onOutput?.(m.output);
140
+ if (m.fatal) {
141
+ w.failStart(new Error(m.fatal));
142
+ return this._fail(m.fatal);
143
+ }
144
+ if (m.spawn != null) {
145
+ // The shared mode: a new thread. Its record in the shared memory
146
+ // has the rest. An idle worker runs it when one exists.
147
+ const idle = this.idle.pop();
148
+ if (idle) idle.post({ run: m.spawn });
149
+ else this._worker(`w${this.next++}`, { role: "thread", arg: m.spawn });
150
+ return;
151
+ }
152
+ if (m.idle) {
153
+ // The shared mode: the thread of the worker ended.
154
+ if (this.idle.length < MAX_IDLE) this.idle.push(w);
155
+ else {
156
+ w.stop();
157
+ this.workers.delete(id);
158
+ }
159
+ return;
160
+ }
161
+ if (m.exit) {
162
+ w.stop();
163
+ this.workers.delete(id);
164
+ if (this.mode === "async" && id !== 1) this.main?.post({ gone: id });
165
+ return;
166
+ }
167
+ if (m.create) {
168
+ // The async mode: the main interpreter made a thread.
169
+ const { id: tid, script } = m.create;
170
+ this._worker(tid, { role: "thread", script, computeLimit: this.limits.computeLimit ?? this.computeLimit, memLimit: this.limits.memLimit });
171
+ return;
172
+ }
173
+ if (m.send) {
174
+ const { to, token, script } = m.send;
175
+ const targets = to === 0 ? [...this.workers.keys()].filter((k) => k !== id) : [to];
176
+ for (const k of targets) {
177
+ const t = this.workers.get(k);
178
+ const msg = { deliver: { from: id, token, script } };
179
+ if (!t) {
180
+ if (token) w.post({ reply: { token, code: 1, bytes: stringBytes("target thread died") } });
181
+ } else t.post(msg);
182
+ }
183
+ return;
184
+ }
185
+ if (m.reply) {
186
+ this.workers.get(m.reply.to)?.post({ reply: m.reply });
187
+ return;
188
+ }
189
+ if (m.id != null) {
190
+ const p = this.pending.get(m.id);
191
+ if (!p) return;
192
+ this.pending.delete(m.id);
193
+ if (m.error) p.reject(new Error(m.error));
194
+ else p.resolve({ ok: m.ok, result: m.result, output: m.output });
195
+ }
196
+ }
197
+
198
+ /// Runs a script in the main interpreter.
199
+ eval(script) {
200
+ if (this.failure) return Promise.reject(new Error(this.failure));
201
+ if (!this.main) return Promise.reject(new Error("the interpreter is closed"));
202
+ const id = this.next++;
203
+ return new Promise((resolve, reject) => {
204
+ this.pending.set(id, { resolve, reject });
205
+ this.main.post({ eval: id, script, computeLimit: this.computeLimit });
206
+ });
207
+ }
208
+
209
+ /// Stops each worker.
210
+ close() {
211
+ for (const w of this.workers.values()) w.stop?.();
212
+ this.workers.clear();
213
+ this.idle = [];
214
+ this.main = null;
215
+ for (const p of this.pending.values()) p.resolve({ ok: false, result: "stopped", output: "" });
216
+ this.pending.clear();
217
+ }
218
+
219
+ _fail(message) {
220
+ this.failure = message;
221
+ for (const p of this.pending.values()) p.reject(new Error(message));
222
+ this.pending.clear();
223
+ }
224
+ }
Binary file
package/ztcl-worker.d.ts CHANGED
@@ -15,7 +15,7 @@ export interface InitMessage {
15
15
  export interface EvalMessage {
16
16
  id: number;
17
17
  script: string;
18
- stepLimit?: number | bigint | null;
18
+ computeLimit?: number | bigint | null;
19
19
  memLimit?: number | null;
20
20
  }
21
21
 
package/ztcl-worker.mjs CHANGED
@@ -4,10 +4,12 @@
4
4
  import { compile, Interp } from "./ztcl.mjs";
5
5
 
6
6
  let module = null;
7
+ // The capabilities and the files of the interpreter (WorkerInterp).
8
+ let setup = {};
7
9
  let interp = null;
8
10
 
9
11
  async function current() {
10
- if (!interp) interp = await Interp.create(await module);
12
+ if (!interp) interp = await Interp.create(await module, { allow: setup.allow ?? [], files: setup.files ?? null });
11
13
  return interp;
12
14
  }
13
15
 
@@ -20,6 +22,7 @@ self.onmessage = ({ data }) => {
20
22
  async function handle(data) {
21
23
  if (data.init) {
22
24
  module = compile(data.init);
25
+ setup = data.setup ?? {};
23
26
  return;
24
27
  }
25
28
  if (data.reset) {
@@ -29,10 +32,16 @@ async function handle(data) {
29
32
  }
30
33
  try {
31
34
  const it = await current();
32
- it.stepLimit = data.stepLimit;
35
+ it.computeLimit = data.computeLimit;
33
36
  if (data.memLimit != null) it.memLimit = data.memLimit;
34
37
  const r = it.eval(data.script);
35
- self.postMessage({ id: data.id, ...r, memorySize: it.memorySize });
38
+ // With `collect`, the files that the scripts wrote go back too.
39
+ let files;
40
+ if (data.collect) {
41
+ files = {};
42
+ for (const n of it.fileNames()) files[n] = it.readFile(n);
43
+ }
44
+ self.postMessage({ id: data.id, ...r, memorySize: it.memorySize, files }, files ? Object.values(files).map((b) => b.buffer) : []);
36
45
  } catch (e) {
37
46
  self.postMessage({ id: data.id, error: String(e && e.message ? e.message : e) });
38
47
  }
package/ztcl.d.ts CHANGED
@@ -14,11 +14,11 @@ export type WasmSource = string | URL | Response | BufferSource | WebAssembly.Mo
14
14
  /** The options of an interpreter. */
15
15
  export interface InterpOptions {
16
16
  /**
17
- * The steps of each `eval`. Each command and each loop pass uses one
18
- * step. At the limit, the script stops with the error
19
- * `step limit reached`. `null` is no limit, and it is the default.
17
+ * The compute units of each `eval`. Each command and each loop pass uses one
18
+ * compute unit. At the limit, the script stops with the error
19
+ * `compute limit reached`. `null` is no limit, and it is the default.
20
20
  */
21
- stepLimit?: number | bigint | null;
21
+ computeLimit?: number | bigint | null;
22
22
  /**
23
23
  * The memory limit in bytes. At the limit, the script stops with the
24
24
  * error `the script used too much memory`. The default is 2 GiB.
@@ -26,8 +26,46 @@ export interface InterpOptions {
26
26
  memLimit?: number | null;
27
27
  /** Gets the text of `puts` when each `eval` ends. */
28
28
  onOutput?: ((text: string) => void) | null;
29
+ /**
30
+ * Capabilities to turn on. `ztcl.wasm` has only `"file"`: `source`,
31
+ * `open` for reading, `read`, `gets`, `eof`, and `close` on the files
32
+ * of a bundle, under `//zipfs:/app/`. `ztcl-host.wasm` also has
33
+ * `"event"`: `after`, `after idle`, and `update`, with the events run
34
+ * from `setTimeout`, and the groups of the Web APIs, such as
35
+ * `"web:serial"`, for the commands `web::` (with the option `web`).
36
+ * The default is none.
37
+ */
38
+ allow?: ("file" | "event" | "dom" | "dom-html" | "clock" | WebGroup)[];
39
+ /**
40
+ * Files for the capability `file`, in place of the files of a bundle:
41
+ * an object of names and bytes. `open name rb` reads them.
42
+ */
43
+ files?: Record<string, Uint8Array | ArrayBuffer> | null;
44
+ /**
45
+ * The module `ztcl-web.mjs`, the bridge of the commands `web::`, for
46
+ * a group of `web:` in `allow`. A page imports it:
47
+ * `import * as web from "./ztcl-web.mjs"`.
48
+ */
49
+ web?: { Bridge: unknown } | null;
50
+ /** The global object of the paths of `web::root`. The default is `globalThis`. */
51
+ webRoot?: object;
52
+ /**
53
+ * The compute units of each script of a result of a promise or of an
54
+ * event of `web::on`. The default is 1,000,000.
55
+ */
56
+ webComputeLimit?: number | null;
57
+ /**
58
+ * The clock of the host in milliseconds, for `"event"`. The default is
59
+ * `Date.now`.
60
+ */
61
+ now?: (() => number) | null;
62
+ /** Gets the result of each run of the events from the timer. */
63
+ onEvents?: ((r: EvalResult) => void) | null;
29
64
  }
30
65
 
66
+ /** A group of the Web APIs of the commands `web::` (ztcl-host.wasm). */
67
+ export type WebGroup = "web:serial" | "web:usb" | "web:bluetooth" | "web:hid" | "web:midi" | "web:gamepad";
68
+
31
69
  /** The result of one `eval`. */
32
70
  export interface EvalResult {
33
71
  /** True when the script ended with no error. */
@@ -42,6 +80,8 @@ export interface EvalResult {
42
80
  export interface WorkerEvalResult extends EvalResult {
43
81
  /** The size of the linear memory of the worker interpreter in bytes. */
44
82
  memorySize?: number;
83
+ /** With `collect`, the files that the scripts wrote (ztcl-shell.wasm). */
84
+ files?: Record<string, Uint8Array>;
45
85
  }
46
86
 
47
87
  /** The URL of the `ztcl.wasm` file next to `ztcl.mjs`. It is the default source. */
@@ -60,7 +100,7 @@ export function compile(source?: WasmSource): Promise<WebAssembly.Module>;
60
100
  * files, sockets, `exec`, `clock`, or event loop.
61
101
  *
62
102
  * @example
63
- * const tcl = await Interp.create({ stepLimit: 1_000_000, memLimit: 64 << 20 });
103
+ * const tcl = await Interp.create({ computeLimit: 1_000_000, memLimit: 64 << 20 });
64
104
  * tcl.eval("expr {6 * 7}"); // { ok: true, result: "42", output: "" }
65
105
  */
66
106
  export class Interp {
@@ -76,8 +116,8 @@ export class Interp {
76
116
  /** Makes an interpreter in an instance of `ztcl.wasm`. Use {@link Interp.create}. */
77
117
  constructor(instance: WebAssembly.Instance, options?: InterpOptions);
78
118
 
79
- /** The steps of each `eval`. `null` is no limit. A change applies to the next `eval`. */
80
- stepLimit: number | bigint | null;
119
+ /** The compute units of each `eval`. `null` is no limit. A change applies to the next `eval`. */
120
+ computeLimit: number | bigint | null;
81
121
  /** The memory limit in bytes. A change applies to the next `eval`. */
82
122
  memLimit: number;
83
123
  /** Gets the text of `puts` when each `eval` ends. */
@@ -89,15 +129,56 @@ export class Interp {
89
129
  readonly memorySize: number;
90
130
 
91
131
  /**
92
- * Runs a script on the calling thread. The step limit applies to
132
+ * Runs a script on the calling thread. The compute limit applies to
93
133
  * this call. A script blocks the page until it ends or hits a limit.
94
134
  */
95
135
  eval(script: string): EvalResult;
96
136
 
137
+ /** Gives the scripts files for the capability `file`, as the option `files`. */
138
+ setFiles(files: Record<string, Uint8Array | ArrayBuffer>): void;
139
+ /** The names of the files that the scripts wrote (ztcl-shell.wasm). */
140
+ fileNames(): string[];
141
+ /** A copy of the bytes of a file that a script wrote, or `null`. */
142
+ readFile(name: string): Uint8Array | null;
143
+
144
+ /**
145
+ * The size in bytes of the scripts and files of a bundle from
146
+ * `ztcl build --wasm`. Zero for a module with no bundle.
147
+ */
148
+ readonly bundleSize: number;
149
+
150
+ /**
151
+ * Runs the scripts of a bundle in order, as `ztcl a.tcl b.tcl` does.
152
+ * The compute limit applies to all the scripts of the call together. On
153
+ * an error, the next scripts do not run, and `result` is
154
+ * `"name:line: message"`. Throws for a module with no bundle.
155
+ */
156
+ run(): EvalResult;
157
+
158
+ /**
159
+ * Runs the events that are due at `now` (milliseconds on the clock of
160
+ * the option `now`), after `allow: ["event"]`.
161
+ */
162
+ runEvents(now?: number): EvalResult;
163
+
164
+ /** Gets the result of each run of the events from the timer. */
165
+ onEvents: ((r: EvalResult) => void) | null;
166
+
97
167
  /** Frees the interpreter. Drop the object after this call. */
98
168
  close(): void;
99
169
  }
100
170
 
171
+ /**
172
+ * Runs the scripts of a bundle in a new interpreter, then frees it.
173
+ *
174
+ * @example
175
+ * const r = await run(new URL("./app.wasm", import.meta.url), { computeLimit: 1_000_000 });
176
+ * console.log(r.output);
177
+ * @param source The bundle, as for {@link compile}.
178
+ * @param options The limits, the output function, and the capabilities.
179
+ */
180
+ export function run(source: WasmSource, options?: InterpOptions): Promise<EvalResult>;
181
+
101
182
  /**
102
183
  * Runs scripts in a Web Worker, so a long script does not block the
103
184
  * page. `stop()` ends the worker and the script in it. The next `eval()`
@@ -117,15 +198,18 @@ export class WorkerInterp {
117
198
  /** Uses the default module. */
118
199
  constructor(options: InterpOptions);
119
200
 
120
- /** The steps of each `eval`. `null` is no limit. */
121
- stepLimit: number | bigint | null;
201
+ /** The compute units of each `eval`. `null` is no limit. */
202
+ computeLimit: number | bigint | null;
122
203
  /** The memory limit in bytes. `null` keeps the default. */
123
204
  memLimit: number | null;
124
205
  /** Gets the text of `puts` when each `eval` ends. */
125
206
  onOutput: ((text: string) => void) | null;
126
207
 
127
- /** Runs a script in the worker. */
128
- eval(script: string): Promise<WorkerEvalResult>;
208
+ /**
209
+ * Runs a script in the worker. With `collect`, the result has the
210
+ * files that the scripts wrote.
211
+ */
212
+ eval(script: string, options?: { collect?: boolean }): Promise<WorkerEvalResult>;
129
213
  /** Makes a new interpreter in the worker for the next `eval`. */
130
214
  reset(): void;
131
215
  /**