@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.
package/NOTICE CHANGED
@@ -11,6 +11,8 @@ Zig standard library All of ztcl licenses/zig-std-MIT
11
11
  musl libc Math functions of std.math licenses/musl-MIT.txt
12
12
  Go std.fmt.parseFloat, std.math.pow licenses/go-BSD-3-Clause.txt
13
13
  ARM optimized-routines std.math.acos, std.math.atan licenses/arm-optimized-routines.txt
14
+ libghostty-vt (Ghostty) The terminal state of ztcl::vt licenses/ghostty-MIT.txt
15
+ uucode The Unicode tables of libghostty licenses/uucode-MIT.txt
14
16
 
15
17
  ztcl follows the language rules and the command behavior of Tcl. It has
16
18
  no code of Tcl. The Tcl/Tk License is in licenses/tcl-license.txt.
package/README.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # @beetlebug/ztcl
2
2
 
3
- ztcl is a Tcl interpreter in Zig. This package has the WebAssembly build and a small ES module over it. A page or a Node.js program runs Tcl scripts with an exact step limit and a memory limit, so it can run scripts that its users write.
3
+ ztcl is a Tcl interpreter in Zig. This package has the WebAssembly build and a small ES module over it. A page or a Node.js program runs Tcl scripts with an exact compute limit and a memory limit, so it can run scripts that its users write.
4
4
 
5
5
  - The module is 871 KB, or about 300 KB with gzip. It has no imports.
6
6
  - It runs in a browser, in a Web Worker, and in Node.js 22.3 or later.
@@ -18,9 +18,9 @@ npm install @beetlebug/ztcl
18
18
 
19
19
  ```html
20
20
  <script type="module">
21
- import { Interp } from "https://cdn.jsdelivr.net/npm/@beetlebug/ztcl@0.2.0-beta/ztcl.mjs";
21
+ import { Interp } from "https://cdn.jsdelivr.net/npm/@beetlebug/ztcl@1.0.0-beta.1/ztcl.mjs";
22
22
 
23
- const tcl = await Interp.create({ stepLimit: 1_000_000, memLimit: 64 << 20 });
23
+ const tcl = await Interp.create({ computeLimit: 1_000_000, memLimit: 64 << 20 });
24
24
  console.log(tcl.eval("expr {6 * 7}").result); // 42
25
25
  </script>
26
26
  ```
@@ -33,7 +33,7 @@ The module loads `ztcl.wasm` from its own folder on the CDN. `WorkerInterp` also
33
33
  import { Interp, WorkerInterp } from "@beetlebug/ztcl";
34
34
 
35
35
  const tcl = await Interp.create({
36
- stepLimit: 1_000_000,
36
+ computeLimit: 1_000_000,
37
37
  memLimit: 64 << 20,
38
38
  onOutput: (text) => console.log(text),
39
39
  });
@@ -55,7 +55,7 @@ The tests of the package run Vite 7. Webpack 5 and Rollup also have support for
55
55
  ```js
56
56
  import { Interp } from "@beetlebug/ztcl";
57
57
 
58
- const tcl = await Interp.create({ stepLimit: 1_000_000, memLimit: 64 << 20 });
58
+ const tcl = await Interp.create({ computeLimit: 1_000_000, memLimit: 64 << 20 });
59
59
  const r = tcl.eval("proc sq {x} {expr {$x * $x}}; sq 12");
60
60
  console.log(r.result); // 144
61
61
  tcl.close();
@@ -81,22 +81,47 @@ The next `eval` after `stop` starts a new worker with a new interpreter. `@beetl
81
81
  |---|---|
82
82
  | `Interp.create(source?, options?)` | Makes an interpreter in a new WebAssembly instance. |
83
83
  | `interp.eval(script)` | Runs a script. Returns `{ ok, result, output }`. `result` is the value, or the error message when `ok` is false. |
84
- | `interp.stepLimit`, `interp.memLimit` | The limits of the next `eval`. |
84
+ | `interp.computeLimit`, `interp.memLimit` | The limits of the next `eval`. |
85
85
  | `interp.memorySize` | The size of the linear memory in bytes. The memory never shrinks, so this is the peak. |
86
86
  | `interp.close()` | Frees the interpreter. |
87
87
  | `new WorkerInterp(wasmUrl?, options?)` | An interpreter in a Web Worker. `eval` returns a promise. `reset()` makes a new interpreter. `stop()` ends the worker. |
88
88
  | `compile(source?)` | Compiles the module one time, for many interpreters. |
89
89
  | `wasmURL()` | The URL of the `ztcl.wasm` file of the package. |
90
+ | `run(source, options?)` | Runs the scripts of a bundle from `ztcl build --wasm` in a new interpreter. |
91
+ | `interp.run()` | Runs the scripts of a bundle. Returns `{ ok, result, output }`. |
90
92
 
91
- The options are `stepLimit`, `memLimit`, and `onOutput`. `stepLimit` is the steps of each `eval`, and `null` (the default) is no limit. `memLimit` is in bytes, and the default is 2 GiB. `onOutput(text)` gets the text of `puts` when each `eval` ends.
93
+ The options are `computeLimit`, `memLimit`, `onOutput`, and `allow`. `allow: ["file"]` turns on `source` and `open` for reading on the files of a bundle. `computeLimit` is the compute units of each `eval`, and `null` (the default) is no limit. `memLimit` is in bytes, and the default is 2 GiB. `onOutput(text)` gets the text of `puts` when each `eval` ends.
92
94
 
93
95
  A source is a URL, a file path in Node.js, a `Response`, bytes, or a `WebAssembly.Module`. With no source, the module is the `ztcl.wasm` file of the package.
94
96
 
95
97
  One interpreter keeps its procs and variables from one `eval` to the next. Each `Interp` has its own instance and its own memory, so `close` and a new `Interp` give the memory back.
96
98
 
99
+ ## A bundle
100
+
101
+ `ztcl build --wasm -o app.wasm app.tcl` writes a copy of the `ztcl.wasm` of the package with the script in it. `--embed PATH` adds read-only files under `//zipfs:/app/`. The limits apply as for `eval`. See [Bundle a script](https://beetlebug.org/ztcl/webassembly/#bundle-a-script).
102
+
103
+ ```js
104
+ import { run } from "@beetlebug/ztcl";
105
+
106
+ const r = await run(new URL("./app.wasm", import.meta.url), { computeLimit: 1_000_000, allow: ["file"] });
107
+ console.log(r.output);
108
+ ```
109
+
110
+ ## Threads
111
+
112
+ The entry `@beetlebug/ztcl/threads` runs the capability `thread` with one worker for each ztcl thread. In Node.js and on a cross-origin isolated page, each command of the Thread package works. On a page without cross-origin isolation, only the commands that do not wait work. The option `allow` turns on capabilities: `thread` is the default, and `clock`, `package`, `interp`, and in the shared mode `event` can also be on. `clock` and the event loop read the clock of the host. See [WebAssembly](https://beetlebug.org/ztcl/webassembly/#threads).
113
+
114
+ ```js
115
+ import { ThreadInterp } from "@beetlebug/ztcl/threads";
116
+
117
+ const t = await ThreadInterp.create({ allow: ["thread"] });
118
+ const r = await t.eval("thread::send [thread::create] {expr {6 * 7}}");
119
+ t.close();
120
+ ```
121
+
97
122
  ## Limits and capabilities
98
123
 
99
- - **Steps.** Each command and each loop pass uses one step. At the limit, the script stops with the error `step limit reached`. `catch` and `try` cannot catch it. The same script stops at the same step in each browser and in Node.js.
124
+ - **Compute units.** Each command and each loop pass uses one compute unit. At the limit, the script stops with the error `compute limit reached`. `catch` and `try` cannot catch it. The same script stops at the same point in each browser and in Node.js.
100
125
  - **Memory.** At the limit, the script stops with the error `the script used too much memory`. `catch` cannot catch it. The linear memory can grow to about twice the limit.
101
126
  - **No host access.** The module has the interpreter only, with no JIT. It has no command that reaches the host: no files, sockets, `exec`, `clock`, `interp`, or event loop. `coroutine` returns an error.
102
127
  - **Output.** `puts` goes into a buffer. `eval` returns the text, and `onOutput` gets it when the script ends.
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2024 Mitchell Hashimoto, Ghostty contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,20 @@
1
+ simdjson
2
+
3
+ The JSON parser of ztcl (src/json/) implements the simdjson algorithm
4
+ in Zig. simdjson is at https://github.com/simdjson/simdjson. Its license
5
+ is the Apache License 2.0 or the MIT license, at the choice of the user.
6
+
7
+ ztcl copies no code, no lookup table, and no constant set from
8
+ simdjson. The Zig code is new, written from the descriptions of the
9
+ method in these papers:
10
+
11
+ - Geoff Langdale and Daniel Lemire, "Parsing Gigabytes of JSON per
12
+ Second", The VLDB Journal 28 (2019).
13
+ - John Keiser and Daniel Lemire, "Validating UTF-8 In Less Than One
14
+ Instruction Per Byte", Software: Practice and Experience 51 (2021).
15
+ - Daniel Lemire, "Number Parsing at a Gigabyte per Second", Software:
16
+ Practice and Experience 51 (2021). ztcl uses the Eisel-Lemire method
17
+ through std.fmt.parseFloat of the Zig standard library.
18
+
19
+ docs/references/stdlib.md says what each part of src/json/ takes from
20
+ each source.
@@ -0,0 +1,39 @@
1
+ UNICODE LICENSE V3
2
+
3
+ COPYRIGHT AND PERMISSION NOTICE
4
+
5
+ Copyright © 1991-2026 Unicode, Inc.
6
+
7
+ NOTICE TO USER: Carefully read the following legal agreement. BY
8
+ DOWNLOADING, INSTALLING, COPYING OR OTHERWISE USING DATA FILES, AND/OR
9
+ SOFTWARE, YOU UNEQUIVOCALLY ACCEPT, AND AGREE TO BE BOUND BY, ALL OF THE
10
+ TERMS AND CONDITIONS OF THIS AGREEMENT. IF YOU DO NOT AGREE, DO NOT
11
+ DOWNLOAD, INSTALL, COPY, DISTRIBUTE OR USE THE DATA FILES OR SOFTWARE.
12
+
13
+ Permission is hereby granted, free of charge, to any person obtaining a
14
+ copy of data files and any associated documentation (the "Data Files") or
15
+ software and any associated documentation (the "Software") to deal in the
16
+ Data Files or Software without restriction, including without limitation
17
+ the rights to use, copy, modify, merge, publish, distribute, and/or sell
18
+ copies of the Data Files or Software, and to permit persons to whom the
19
+ Data Files or Software are furnished to do so, provided that either (a)
20
+ this copyright and permission notice appear with all copies of the Data
21
+ Files or Software, or (b) this copyright and permission notice appear in
22
+ associated Documentation.
23
+
24
+ THE DATA FILES AND SOFTWARE ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY
25
+ KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
26
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF
27
+ THIRD PARTY RIGHTS.
28
+
29
+ IN NO EVENT SHALL THE COPYRIGHT HOLDER OR HOLDERS INCLUDED IN THIS NOTICE
30
+ BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL INDIRECT OR CONSEQUENTIAL DAMAGES,
31
+ OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
32
+ WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION,
33
+ ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THE DATA
34
+ FILES OR SOFTWARE.
35
+
36
+ Except as contained in this notice, the name of a copyright holder shall
37
+ not be used in advertising or otherwise to promote the sale, use or other
38
+ dealings in these Data Files or Software without prior written
39
+ authorization of the copyright holder.
@@ -0,0 +1,30 @@
1
+ # uucode license
2
+
3
+ MIT License
4
+
5
+ Copyright (c) 2026 Jacob Sandlund
6
+
7
+ Permission is hereby granted, free of charge, to any person obtaining a copy of
8
+ this software and associated documentation files (the "Software"), to deal in
9
+ the Software without restriction, including without limitation the rights to
10
+ use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
11
+ of the Software, and to permit persons to whom the Software is furnished to do
12
+ so, subject to the following conditions:
13
+
14
+ The above copyright notice and this permission notice shall be included in all
15
+ copies or substantial portions of the Software.
16
+
17
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
20
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
23
+ SOFTWARE.
24
+
25
+ ## Other licenses
26
+
27
+ See [./licenses](./licenses) for licenses of code being used in the repo:
28
+
29
+ * [LICENSE_Bjoern_Hoehrmann](./licenses/LICENSE_Bjoern_Hoehrmann)
30
+ * [LICENSE_unicode](./licenses/LICENSE_unicode)
@@ -0,0 +1,8 @@
1
+ Copyright © 2019-2024 the Contributors to the WASI Specification, published
2
+ by the [WebAssembly Community Group][cg] under the
3
+ [W3C Community Contributor License Agreement (CLA)][cla]. A human-readable
4
+ [summary][summary] is available.
5
+
6
+ [cg]: https://www.w3.org/community/webassembly/
7
+ [cla]: https://www.w3.org/community/about/agreements/cla/
8
+ [summary]: https://www.w3.org/community/about/agreements/cla-deed/
package/package.json CHANGED
@@ -1,9 +1,9 @@
1
1
  {
2
2
  "name": "@beetlebug/ztcl",
3
- "version": "0.2.0-beta",
4
- "description": "A Tcl interpreter in WebAssembly, with a step limit and a memory limit for untrusted scripts",
3
+ "version": "1.0.0-beta.1",
4
+ "description": "A Tcl interpreter in WebAssembly, with a compute limit and a memory limit for untrusted scripts",
5
5
  "license": "BSD-2-Clause",
6
- "author": "The ztcl authors",
6
+ "author": "The ztcl authors <opensource@beetlebug.org>",
7
7
  "homepage": "https://beetlebug.org/ztcl/",
8
8
  "repository": {
9
9
  "type": "git",
@@ -30,7 +30,13 @@
30
30
  "types": "./ztcl-worker.d.ts",
31
31
  "default": "./ztcl-worker.mjs"
32
32
  },
33
+ "./threads": {
34
+ "types": "./ztcl-threads.d.ts",
35
+ "default": "./ztcl-threads.mjs"
36
+ },
33
37
  "./ztcl.wasm": "./ztcl.wasm",
38
+ "./ztcl-threads.wasm": "./ztcl-threads.wasm",
39
+ "./ztcl-async.wasm": "./ztcl-async.wasm",
34
40
  "./package.json": "./package.json"
35
41
  },
36
42
  "files": [
@@ -39,11 +45,17 @@
39
45
  "ztcl.wasm",
40
46
  "ztcl.d.ts",
41
47
  "ztcl-worker.d.ts",
48
+ "ztcl-threads.mjs",
49
+ "ztcl-thread-worker.mjs",
50
+ "ztcl-threads.wasm",
51
+ "ztcl-async.wasm",
52
+ "ztcl-threads.d.ts",
42
53
  "NOTICE",
43
54
  "licenses/"
44
55
  ],
45
56
  "sideEffects": [
46
- "./ztcl-worker.mjs"
57
+ "./ztcl-worker.mjs",
58
+ "./ztcl-thread-worker.mjs"
47
59
  ],
48
60
  "engines": {
49
61
  "node": ">=22.3"
Binary file
@@ -0,0 +1,204 @@
1
+ // The worker of web/ztcl-threads.mjs. One worker runs one ztcl thread:
2
+ // the main interpreter or a thread of a script.
3
+ //
4
+ // The build with one shared memory (ztcl-threads.wasm): each worker
5
+ // makes an instance of the module on the shared memory of the host. A
6
+ // thread worker calls ztcl_thread_start, which runs the whole thread.
7
+ // The waits of the thread are Atomics waits on the shared memory.
8
+ //
9
+ // The build with a memory in each worker (ztcl-async.wasm): each worker
10
+ // has its own memory. A message is a script, and a reply is the result
11
+ // as bytes. The host routes them with postMessage. The worker runs one
12
+ // message at a time, between the turns of its event loop.
13
+ // SPDX-License-Identifier: BSD-2-Clause
14
+
15
+ const node = typeof WorkerGlobalScope === "undefined";
16
+ const port = node ? (await import("node:worker_threads")).parentPort : self;
17
+ const post = (m) => port.postMessage(m);
18
+ const listen = (f) => (node ? port.on("message", f) : (port.onmessage = ({ data }) => f(data)));
19
+
20
+ const encoder = new TextEncoder();
21
+ const decoder = new TextDecoder();
22
+ const NO_LIMIT = 0xffffffffffffffffn;
23
+ const now = () => performance.timeOrigin + performance.now();
24
+
25
+ let x = null; // the exports of the instance
26
+ let h = 0; // the interpreter of a main worker or of an async thread
27
+ let shared = false;
28
+
29
+ function bytesIn(bytes) {
30
+ const p = x.ztcl_alloc(bytes.length || 1);
31
+ if (!p) throw new Error("ztcl_alloc: out of memory");
32
+ new Uint8Array(x.memory.buffer, p, bytes.length).set(bytes);
33
+ return p;
34
+ }
35
+
36
+ function bytesOut(ptr, len) {
37
+ // A copy: TextDecoder does not read a SharedArrayBuffer. An empty
38
+ // slice can have an address outside the memory.
39
+ if (len === 0) return new Uint8Array(0);
40
+ return new Uint8Array(x.memory.buffer, ptr, len).slice();
41
+ }
42
+
43
+ function output() {
44
+ if (x.ztcl_output_take) x.ztcl_output_take(h);
45
+ const text = decoder.decode(bytesOut(x.ztcl_output_ptr(h), x.ztcl_output_len(h)));
46
+ x.ztcl_output_clear(h);
47
+ return text;
48
+ }
49
+
50
+ function evalScript(script, computeLimit) {
51
+ x.ztcl_set_compute_limit(h, computeLimit == null ? NO_LIMIT : BigInt(computeLimit));
52
+ const bytes = encoder.encode(script);
53
+ const p = bytesIn(bytes);
54
+ const rc = x.ztcl_eval(h, p, bytes.length);
55
+ x.ztcl_free(p, bytes.length || 1);
56
+ const result = decoder.decode(bytesOut(x.ztcl_result_ptr(h), x.ztcl_result_len(h)));
57
+ return { ok: rc === 0, result, output: output() };
58
+ }
59
+
60
+ // Sends the output of the threads while the main interpreter waits for
61
+ // an eval.
62
+ let poll = null;
63
+ function startPoll() {
64
+ poll = setInterval(() => {
65
+ const text = output();
66
+ if (text) post({ output: text });
67
+ }, 50);
68
+ }
69
+
70
+ function setup(init) {
71
+ const limits = init.limits ?? {};
72
+ const n = (v) => (v == null ? 0 : v);
73
+ const big = (v) => (v == null ? 0n : BigInt(v));
74
+ x.ztcl_set_thread_limits(h, n(limits.maxThreads), big(limits.computeLimit), n(limits.memLimit), big(limits.totalCompute), n(limits.totalMem), n(limits.maxQueue));
75
+ if (init.memLimit != null) x.ztcl_set_mem_limit(h, init.memLimit);
76
+ const rc = x.ztcl_allow(h, init.caps);
77
+ if (rc !== 0) throw new Error(rc === 2 ? "the build does not have one of these capabilities" : "ztcl_allow: out of memory");
78
+ }
79
+
80
+ // ---- The build with one shared memory ----
81
+
82
+ async function startShared(init) {
83
+ shared = true;
84
+ const imports = {
85
+ env: { memory: init.memory },
86
+ ztcl: {
87
+ now_ms: now,
88
+ thread_spawn: (arg) => {
89
+ post({ spawn: arg });
90
+ return 0;
91
+ },
92
+ },
93
+ };
94
+ const instance = await WebAssembly.instantiate(init.module, imports);
95
+ x = { ...instance.exports, memory: init.memory };
96
+ if (init.role === "thread") return runThread(init.arg);
97
+ h = x.ztcl_new();
98
+ setup(init);
99
+ startPoll();
100
+ }
101
+
102
+ // Runs one thread on the instance of this worker. After the return the
103
+ // host can give the worker the next thread, so a new thread needs no
104
+ // new worker and no new instance.
105
+ function runThread(arg) {
106
+ try {
107
+ x.ztcl_thread_start(arg);
108
+ } finally {
109
+ // The thread returned: its stack is free for `join`.
110
+ const done = new Int32Array(x.memory.buffer);
111
+ const i = x.ztcl_thread_done(arg) >> 2;
112
+ Atomics.store(done, i, 1);
113
+ Atomics.notify(done, i);
114
+ post({ idle: true });
115
+ }
116
+ }
117
+
118
+ // ---- The build with a memory in each worker ----
119
+
120
+ let self_id = 0;
121
+ let ending = false;
122
+
123
+ function asyncImports() {
124
+ const text = (p, len) => decoder.decode(bytesOut(p, len));
125
+ return {
126
+ ztcl: {
127
+ now_ms: now,
128
+ thread_create: (id, p, len) => post({ create: { id, script: text(p, len) } }),
129
+ thread_send: (id, p, len, token) => post({ send: { to: id, token, script: text(p, len) } }),
130
+ thread_end: () => {
131
+ ending = true;
132
+ },
133
+ },
134
+ };
135
+ }
136
+
137
+ async function startAsync(init) {
138
+ const instance = await WebAssembly.instantiate(init.module, asyncImports());
139
+ x = instance.exports;
140
+ h = x.ztcl_new();
141
+ self_id = init.id;
142
+ x.ztcl_web_init(h, init.id, init.role === "main" ? 1 : 0);
143
+ setup(init);
144
+ if (init.role === "thread") {
145
+ const r = evalScript(init.script, init.computeLimit);
146
+ if (r.output) post({ output: r.output });
147
+ if (!r.ok) post({ output: `Error from thread tid0x${init.id.toString(16)}\n${r.result}\n` });
148
+ if (ending || !x.ztcl_web_waiting(h)) end();
149
+ }
150
+ }
151
+
152
+ function end() {
153
+ post({ exit: true });
154
+ ending = true;
155
+ }
156
+
157
+ // A script from another thread. A token asks for a reply.
158
+ function deliver({ from, token, script }) {
159
+ const bytes = encoder.encode(script);
160
+ const p = bytesIn(bytes);
161
+ const code = x.ztcl_web_recv(h, from, token, p, bytes.length);
162
+ x.ztcl_free(p, bytes.length || 1);
163
+ const out = output();
164
+ if (out) post({ output: out });
165
+ if (token) post({ reply: { to: from, token, code, bytes: bytesOut(x.ztcl_web_msg_ptr(h), x.ztcl_web_msg_len(h)) } });
166
+ if (ending) end();
167
+ }
168
+
169
+ function reply({ token, code, bytes }) {
170
+ const p = bytesIn(bytes);
171
+ x.ztcl_web_reply(h, token, code, p, bytes.length);
172
+ x.ztcl_free(p, bytes.length || 1);
173
+ const out = output();
174
+ if (out) post({ output: out });
175
+ }
176
+
177
+ // ---- Messages of the host ----
178
+
179
+ let queue = Promise.resolve();
180
+ listen((data) => {
181
+ queue = queue.then(() => handle(data)).catch((e) => post({ fatal: String(e?.message ?? e) }));
182
+ });
183
+
184
+ async function handle(data) {
185
+ if (data.init) {
186
+ if (data.init.memory) await startShared(data.init);
187
+ else await startAsync(data.init);
188
+ post({ ready: true });
189
+ return;
190
+ }
191
+ if (data.run != null) return runThread(data.run);
192
+ if (ending) return;
193
+ if (data.deliver) return deliver(data.deliver);
194
+ if (data.reply) return reply(data.reply);
195
+ if (data.gone) return x.ztcl_web_gone(h, data.gone);
196
+ if (data.eval != null) {
197
+ try {
198
+ const r = evalScript(data.script, data.computeLimit);
199
+ post({ id: data.eval, ...r });
200
+ } catch (e) {
201
+ post({ id: data.eval, error: String(e?.message ?? e) });
202
+ }
203
+ }
204
+ }
@@ -0,0 +1,55 @@
1
+ // Types of ztcl-threads.mjs: ztcl with the capability `thread`.
2
+ // SPDX-License-Identifier: BSD-2-Clause
3
+
4
+ /** The capabilities that a thread interpreter can turn on. */
5
+ export type ThreadCapability = "thread" | "event" | "clock" | "package" | "interp";
6
+
7
+ /** The limits of the threads. A missing field keeps its default. */
8
+ export interface ThreadLimits {
9
+ maxThreads?: number;
10
+ computeLimit?: number;
11
+ memLimit?: number;
12
+ totalCompute?: number;
13
+ totalMem?: number;
14
+ maxQueue?: number;
15
+ }
16
+
17
+ export interface ThreadInterpOptions {
18
+ /** "shared" needs Node.js or a cross-origin isolated page. "auto" picks "shared" when it can. */
19
+ mode?: "auto" | "shared" | "async";
20
+ /** The URL or path of ztcl-threads.wasm. */
21
+ wasm?: string | URL;
22
+ /** The URL or path of ztcl-async.wasm. */
23
+ asyncWasm?: string | URL;
24
+ /** The default is ["thread"]. "event" works only in the shared mode. */
25
+ allow?: ThreadCapability[];
26
+ limits?: ThreadLimits;
27
+ /** The compute units of each eval of the main interpreter. */
28
+ computeLimit?: number | null;
29
+ memLimit?: number | null;
30
+ /** The text of `puts` of each thread. */
31
+ onOutput?: ((text: string) => void) | null;
32
+ }
33
+
34
+ export interface ThreadEvalResult {
35
+ ok: boolean;
36
+ result: string;
37
+ output: string;
38
+ }
39
+
40
+ /** True in Node.js and on a cross-origin isolated page. */
41
+ export function isolated(): boolean;
42
+ export function threadsURL(): URL;
43
+ export function asyncURL(): URL;
44
+
45
+ /** A main interpreter in a worker, with one worker for each thread. */
46
+ export class ThreadInterp {
47
+ static create(options?: ThreadInterpOptions): Promise<ThreadInterp>;
48
+ readonly mode: "shared" | "async";
49
+ computeLimit: number | null;
50
+ onOutput: ((text: string) => void) | null;
51
+ /** Runs a script in the main interpreter. */
52
+ eval(script: string): Promise<ThreadEvalResult>;
53
+ /** Stops each worker. */
54
+ close(): void;
55
+ }