@beetlebug/ztcl 0.0.0-stage → 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/LICENSE +24 -0
- package/NOTICE +18 -0
- package/README.md +132 -2
- package/licenses/arm-optimized-routines.txt +249 -0
- package/licenses/ghostty-MIT.txt +21 -0
- package/licenses/go-BSD-3-Clause.txt +27 -0
- package/licenses/musl-MIT.txt +193 -0
- package/licenses/simdjson-NOTICE.txt +20 -0
- package/licenses/tcl-license.txt +40 -0
- package/licenses/unicode-license.txt +39 -0
- package/licenses/uucode-MIT.txt +30 -0
- package/licenses/wasi-W3C-CLA.md +8 -0
- package/licenses/zig-std-MIT.txt +21 -0
- package/package.json +61 -4
- package/ztcl-async.wasm +0 -0
- package/ztcl-thread-worker.mjs +204 -0
- package/ztcl-threads.d.ts +55 -0
- package/ztcl-threads.mjs +224 -0
- package/ztcl-threads.wasm +0 -0
- package/ztcl-worker.d.ts +33 -0
- package/ztcl-worker.mjs +48 -0
- package/ztcl.d.ts +220 -0
- package/ztcl.mjs +1213 -0
- package/ztcl.wasm +0 -0
package/ztcl-threads.mjs
ADDED
|
@@ -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
ADDED
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
// Types of ztcl-worker.mjs: the script that runs in a Web Worker.
|
|
2
|
+
// SPDX-License-Identifier: BSD-2-Clause
|
|
3
|
+
//
|
|
4
|
+
// The module has no exports. Load it as a module worker. WorkerInterp
|
|
5
|
+
// in the main entry does this for you. Use this entry only to make the
|
|
6
|
+
// worker yourself, for example with `new Worker(url, { type: "module" })`.
|
|
7
|
+
// The worker runs the messages in order.
|
|
8
|
+
|
|
9
|
+
/** The first message: the URL of `ztcl.wasm`. */
|
|
10
|
+
export interface InitMessage {
|
|
11
|
+
init: string;
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
/** Runs a script. The limits apply to this script. */
|
|
15
|
+
export interface EvalMessage {
|
|
16
|
+
id: number;
|
|
17
|
+
script: string;
|
|
18
|
+
computeLimit?: number | bigint | null;
|
|
19
|
+
memLimit?: number | null;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/** Makes a new interpreter for the next script. */
|
|
23
|
+
export interface ResetMessage {
|
|
24
|
+
reset: true;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/** A message to the worker. */
|
|
28
|
+
export type WorkerRequest = InitMessage | EvalMessage | ResetMessage;
|
|
29
|
+
|
|
30
|
+
/** The answer to an {@link EvalMessage}, with the same `id`. */
|
|
31
|
+
export type WorkerResponse =
|
|
32
|
+
| { id: number; ok: boolean; result: string; output: string; memorySize: number }
|
|
33
|
+
| { id: number; error: string };
|
package/ztcl-worker.mjs
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
// The worker of WorkerInterp in ztcl.mjs. It holds one interpreter and
|
|
2
|
+
// runs one script for each message.
|
|
3
|
+
// SPDX-License-Identifier: BSD-2-Clause
|
|
4
|
+
import { compile, Interp } from "./ztcl.mjs";
|
|
5
|
+
|
|
6
|
+
let module = null;
|
|
7
|
+
// The capabilities and the files of the interpreter (WorkerInterp).
|
|
8
|
+
let setup = {};
|
|
9
|
+
let interp = null;
|
|
10
|
+
|
|
11
|
+
async function current() {
|
|
12
|
+
if (!interp) interp = await Interp.create(await module, { allow: setup.allow ?? [], files: setup.files ?? null });
|
|
13
|
+
return interp;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
// The messages run in order, because each one waits for the one before.
|
|
17
|
+
let queue = Promise.resolve();
|
|
18
|
+
self.onmessage = ({ data }) => {
|
|
19
|
+
queue = queue.then(() => handle(data));
|
|
20
|
+
};
|
|
21
|
+
|
|
22
|
+
async function handle(data) {
|
|
23
|
+
if (data.init) {
|
|
24
|
+
module = compile(data.init);
|
|
25
|
+
setup = data.setup ?? {};
|
|
26
|
+
return;
|
|
27
|
+
}
|
|
28
|
+
if (data.reset) {
|
|
29
|
+
interp?.close();
|
|
30
|
+
interp = null;
|
|
31
|
+
return;
|
|
32
|
+
}
|
|
33
|
+
try {
|
|
34
|
+
const it = await current();
|
|
35
|
+
it.computeLimit = data.computeLimit;
|
|
36
|
+
if (data.memLimit != null) it.memLimit = data.memLimit;
|
|
37
|
+
const r = it.eval(data.script);
|
|
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) : []);
|
|
45
|
+
} catch (e) {
|
|
46
|
+
self.postMessage({ id: data.id, error: String(e && e.message ? e.message : e) });
|
|
47
|
+
}
|
|
48
|
+
}
|
package/ztcl.d.ts
ADDED
|
@@ -0,0 +1,220 @@
|
|
|
1
|
+
// Types of ztcl.mjs: the Tcl interpreter in WebAssembly.
|
|
2
|
+
// SPDX-License-Identifier: BSD-2-Clause
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* A source of the WebAssembly module.
|
|
6
|
+
*
|
|
7
|
+
* - A URL or a URL string. In Node.js, a string with no scheme is a file path.
|
|
8
|
+
* - A `Response` from `fetch`.
|
|
9
|
+
* - The bytes of the file.
|
|
10
|
+
* - A `WebAssembly.Module` from {@link compile}.
|
|
11
|
+
*/
|
|
12
|
+
export type WasmSource = string | URL | Response | BufferSource | WebAssembly.Module;
|
|
13
|
+
|
|
14
|
+
/** The options of an interpreter. */
|
|
15
|
+
export interface InterpOptions {
|
|
16
|
+
/**
|
|
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
|
+
*/
|
|
21
|
+
computeLimit?: number | bigint | null;
|
|
22
|
+
/**
|
|
23
|
+
* The memory limit in bytes. At the limit, the script stops with the
|
|
24
|
+
* error `the script used too much memory`. The default is 2 GiB.
|
|
25
|
+
*/
|
|
26
|
+
memLimit?: number | null;
|
|
27
|
+
/** Gets the text of `puts` when each `eval` ends. */
|
|
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;
|
|
64
|
+
}
|
|
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
|
+
|
|
69
|
+
/** The result of one `eval`. */
|
|
70
|
+
export interface EvalResult {
|
|
71
|
+
/** True when the script ended with no error. */
|
|
72
|
+
ok: boolean;
|
|
73
|
+
/** The value of the script, or the error message when `ok` is false. */
|
|
74
|
+
result: string;
|
|
75
|
+
/** The text of `puts` from this script. */
|
|
76
|
+
output: string;
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/** The result of one `eval` in a worker. */
|
|
80
|
+
export interface WorkerEvalResult extends EvalResult {
|
|
81
|
+
/** The size of the linear memory of the worker interpreter in bytes. */
|
|
82
|
+
memorySize?: number;
|
|
83
|
+
/** With `collect`, the files that the scripts wrote (ztcl-shell.wasm). */
|
|
84
|
+
files?: Record<string, Uint8Array>;
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/** The URL of the `ztcl.wasm` file next to `ztcl.mjs`. It is the default source. */
|
|
88
|
+
export function wasmURL(): URL;
|
|
89
|
+
|
|
90
|
+
/**
|
|
91
|
+
* Compiles `ztcl.wasm`. Compile one time and give the module to
|
|
92
|
+
* {@link Interp.create} to make many interpreters.
|
|
93
|
+
* @param source The module. The default is {@link wasmURL}.
|
|
94
|
+
*/
|
|
95
|
+
export function compile(source?: WasmSource): Promise<WebAssembly.Module>;
|
|
96
|
+
|
|
97
|
+
/**
|
|
98
|
+
* A Tcl interpreter in its own WebAssembly instance. The interpreter
|
|
99
|
+
* keeps its procs and variables from one `eval` to the next. It has no
|
|
100
|
+
* files, sockets, `exec`, `clock`, or event loop.
|
|
101
|
+
*
|
|
102
|
+
* @example
|
|
103
|
+
* const tcl = await Interp.create({ computeLimit: 1_000_000, memLimit: 64 << 20 });
|
|
104
|
+
* tcl.eval("expr {6 * 7}"); // { ok: true, result: "42", output: "" }
|
|
105
|
+
*/
|
|
106
|
+
export class Interp {
|
|
107
|
+
/**
|
|
108
|
+
* Makes an interpreter in a new WebAssembly instance.
|
|
109
|
+
* @param source The module, as for {@link compile}. Leave it out for the default.
|
|
110
|
+
* @param options The limits and the output function.
|
|
111
|
+
*/
|
|
112
|
+
static create(source?: WasmSource, options?: InterpOptions): Promise<Interp>;
|
|
113
|
+
/** Makes an interpreter with the default module. */
|
|
114
|
+
static create(options: InterpOptions): Promise<Interp>;
|
|
115
|
+
|
|
116
|
+
/** Makes an interpreter in an instance of `ztcl.wasm`. Use {@link Interp.create}. */
|
|
117
|
+
constructor(instance: WebAssembly.Instance, options?: InterpOptions);
|
|
118
|
+
|
|
119
|
+
/** The compute units of each `eval`. `null` is no limit. A change applies to the next `eval`. */
|
|
120
|
+
computeLimit: number | bigint | null;
|
|
121
|
+
/** The memory limit in bytes. A change applies to the next `eval`. */
|
|
122
|
+
memLimit: number;
|
|
123
|
+
/** Gets the text of `puts` when each `eval` ends. */
|
|
124
|
+
onOutput: ((text: string) => void) | null;
|
|
125
|
+
/**
|
|
126
|
+
* The size of the linear memory in bytes. The memory never shrinks,
|
|
127
|
+
* so this is the peak of the instance.
|
|
128
|
+
*/
|
|
129
|
+
readonly memorySize: number;
|
|
130
|
+
|
|
131
|
+
/**
|
|
132
|
+
* Runs a script on the calling thread. The compute limit applies to
|
|
133
|
+
* this call. A script blocks the page until it ends or hits a limit.
|
|
134
|
+
*/
|
|
135
|
+
eval(script: string): EvalResult;
|
|
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
|
+
|
|
167
|
+
/** Frees the interpreter. Drop the object after this call. */
|
|
168
|
+
close(): void;
|
|
169
|
+
}
|
|
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
|
+
|
|
182
|
+
/**
|
|
183
|
+
* Runs scripts in a Web Worker, so a long script does not block the
|
|
184
|
+
* page. `stop()` ends the worker and the script in it. The next `eval()`
|
|
185
|
+
* starts a new worker with a new interpreter. It works in a browser.
|
|
186
|
+
*
|
|
187
|
+
* @example
|
|
188
|
+
* const tcl = new WorkerInterp({ memLimit: 64 << 20 });
|
|
189
|
+
* const r = await tcl.eval("set n 0; while 1 {incr n}");
|
|
190
|
+
* // Another handler calls tcl.stop(), and r is { ok: false, result: "stopped" }.
|
|
191
|
+
*/
|
|
192
|
+
export class WorkerInterp {
|
|
193
|
+
/**
|
|
194
|
+
* @param wasm The URL of `ztcl.wasm`. Leave it out for the default.
|
|
195
|
+
* @param options The limits and the output function.
|
|
196
|
+
*/
|
|
197
|
+
constructor(wasm?: string | URL, options?: InterpOptions);
|
|
198
|
+
/** Uses the default module. */
|
|
199
|
+
constructor(options: InterpOptions);
|
|
200
|
+
|
|
201
|
+
/** The compute units of each `eval`. `null` is no limit. */
|
|
202
|
+
computeLimit: number | bigint | null;
|
|
203
|
+
/** The memory limit in bytes. `null` keeps the default. */
|
|
204
|
+
memLimit: number | null;
|
|
205
|
+
/** Gets the text of `puts` when each `eval` ends. */
|
|
206
|
+
onOutput: ((text: string) => void) | null;
|
|
207
|
+
|
|
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>;
|
|
213
|
+
/** Makes a new interpreter in the worker for the next `eval`. */
|
|
214
|
+
reset(): void;
|
|
215
|
+
/**
|
|
216
|
+
* Ends the worker. Each pending `eval` resolves with
|
|
217
|
+
* `{ ok: false, result: "stopped" }`. The procs and variables go away.
|
|
218
|
+
*/
|
|
219
|
+
stop(): void;
|
|
220
|
+
}
|