@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/ztcl.mjs CHANGED
@@ -16,7 +16,7 @@
16
16
  const encoder = new TextEncoder();
17
17
  const decoder = new TextDecoder();
18
18
 
19
- // The step limit of the C ABI is a u64. This value is "no limit".
19
+ // The compute limit of the C ABI is a u64. This value is "no limit".
20
20
  const NO_LIMIT = 0xffffffffffffffffn;
21
21
 
22
22
  /// The URL of the ztcl.wasm file next to this file.
@@ -61,24 +61,169 @@ export async function compile(source = wasmURL()) {
61
61
  return WebAssembly.compile(source);
62
62
  }
63
63
 
64
+ // The orders of the columns of ztcl_point_run (`point.Field` and `point.Out`).
65
+ const POINT_FIELDS = ["x", "y", "z", "width", "height", "speed", "flow", "feature", "layer", "path", "dist"];
66
+ const POINT_OUTS = ["offset", "move_x", "move_y", "width", "flow", "speed", "skip"];
67
+
64
68
  export class Interp {
65
69
  /// Makes an interpreter in a new instance of `module`. `module` is a
66
70
  /// source as for compile(), and it can be left out.
67
- /// Options: stepLimit (steps for each eval, null for no limit),
68
- /// memLimit (bytes), onOutput (a function that gets the `puts` text).
71
+ /// Options: computeLimit (compute units for each eval, null for no limit),
72
+ /// memLimit (bytes), onOutput (a function that gets the `puts` text),
73
+ /// allow (a list of capabilities: "file" for the files of a bundle;
74
+ /// "clock", "event", "dom", "dom-html", and the groups of the Web
75
+ /// APIs, for example "web:serial", with ztcl-host.wasm), webRoot (the
76
+ /// global object of `web::root`, globalThis by default), web (the
77
+ /// module web/ztcl-web.mjs, which a page imports for a group of `web:`),
78
+ /// webComputeLimit (the compute units of each script of a result or
79
+ /// an event of `web::`),
80
+ /// onEvents (a function that gets the result of each run of the
81
+ /// events of a timer), point (true adds `point proc` and the output commands), and
82
+ /// packages (a function of a file name for the `load` command of the C
83
+ /// packages, in a build with `-Dcext-wasm`: see _addLoad), and tcl
84
+ /// (the Tcl release that the commands follow: "8.6", the default, or
85
+ /// "9.1").
69
86
  static async create(module, options = {}) {
70
87
  if (isOptions(module)) [module, options] = [undefined, module];
71
- const instance = await WebAssembly.instantiate(await compile(module), {});
72
- return new Interp(instance, options);
88
+ const mod = await compile(module);
89
+ // `ztcl-host.wasm` imports the module `ztcl_host`. Its calls go to
90
+ // the Interp, which exists after the instance.
91
+ let self = null;
92
+ const imports = {};
93
+ if (WebAssembly.Module.imports(mod).some((i) => i.module === "ztcl_host")) {
94
+ imports.ztcl_host = {
95
+ output: (ptr, len) => self._live(ptr, len),
96
+ dom: (op, h, a, aLen, b, bLen) => self._dom(op, h, a, aLen, b, bLen),
97
+ web: (op, h, a, aLen, b, bLen) => self._web.call(op, h, a, aLen, b, bLen),
98
+ now_ms: () => self._now(),
99
+ zone: (ptr, len) => self._zone(ptr, len),
100
+ };
101
+ }
102
+ // A build with `-Dcext-wasm` imports `ztcl_cext.call` for the commands of
103
+ // the C packages of loadPackage().
104
+ if (WebAssembly.Module.imports(mod).some((i) => i.module === "ztcl_cext")) {
105
+ imports.ztcl_cext = {
106
+ call: (pkg, id, argc, argv, prec) => self._cextCall(pkg, id, argc, argv, prec),
107
+ // A child interp with handle `h` goes: each package frees its interp.
108
+ interp_gone: (h) => {
109
+ for (const pkg of self._pkgs ?? []) if (pkg.x?.ztcl_cext_interp_free) pkg.x.ztcl_cext_interp_free(pkg.x.ztcl_cext_interp(h));
110
+ },
111
+ };
112
+ }
113
+ const instance = await WebAssembly.instantiate(mod, imports);
114
+ self = new Interp(instance, options);
115
+ return self;
73
116
  }
74
117
 
75
- constructor(instance, { stepLimit = null, memLimit = null, onOutput = null } = {}) {
118
+ constructor(instance, { computeLimit = null, memLimit = null, onOutput = null, allow = [], point = false, domRoot = null, now = null, zone = null, packages = null, tcl = null, files = null, onEvents = null, domComputeLimit = 1000000, webComputeLimit = 1000000, webRoot = globalThis, web = null } = {}) {
76
119
  this.x = instance.exports;
77
120
  this.h = this.x.ztcl_new();
78
121
  if (!this.h) throw new Error("ztcl_new: out of memory");
79
- this.stepLimit = stepLimit;
122
+ // Without the option, the module follows Tcl 9.1, or the release that
123
+ // its bundle names.
124
+ if (tcl != null) {
125
+ const t = encoder.encode(String(tcl));
126
+ const p = this.x.ztcl_alloc(t.length || 1);
127
+ if (!p) throw new Error("ztcl_alloc: out of memory");
128
+ new Uint8Array(this.x.memory.buffer, p, t.length).set(t);
129
+ const rc = this.x.ztcl_set_tcl_version(this.h, p, t.length);
130
+ this.x.ztcl_free(p, t.length || 1);
131
+ if (rc === 1) throw new Error(`tcl: bad Tcl version "${tcl}": must be 8.6 or 9.1`);
132
+ if (rc !== 0) throw new Error("ztcl_set_tcl_version: out of memory");
133
+ }
134
+ if (point && !this.x.ztcl_point_install) throw new Error("point: this module has no point procs (use ztcl-simd.wasm)");
135
+ if (point && !this.x.ztcl_point_install(this.h)) throw new Error("ztcl_point_install: out of memory");
136
+ this.computeLimit = computeLimit;
80
137
  this.onOutput = onOutput;
81
138
  if (memLimit != null) this.memLimit = memLimit;
139
+ // `clock` reads the time of the host (`now`, milliseconds since 1970,
140
+ // Date.now by default) and the TZif bytes of a zone (`zone(name)`,
141
+ // a Uint8Array or null).
142
+ this._now = now ?? (() => Date.now());
143
+ this._zoneOf = zone;
144
+ if (allow.includes("clock")) {
145
+ if (!this.x.ztcl_clock_allow) throw new Error("clock: this module has no clock (use ztcl-host.wasm)");
146
+ if (this.x.ztcl_clock_allow(this.h) !== 0) throw new Error("ztcl_clock_allow: out of memory");
147
+ allow = allow.filter((c) => c !== "clock");
148
+ }
149
+ // `event` (`after`, `after idle`, `update`) in ztcl-host.wasm. The
150
+ // events run from setTimeout on the clock `now`, and `onEvents` gets
151
+ // the { ok, result, output } of each run.
152
+ this.onEvents = onEvents;
153
+ this._timer = null;
154
+ this._kickTimer = null;
155
+ if (allow.includes("event")) {
156
+ if (!this.x.ztcl_events_allow) throw new Error("event: this module has no event loop (use ztcl-host.wasm)");
157
+ if (this.x.ztcl_events_allow(this.h) !== 0) throw new Error("ztcl_events_allow: out of memory");
158
+ this._events = true;
159
+ allow = allow.filter((c) => c !== "event");
160
+ }
161
+ if (allow.includes("dom")) {
162
+ if (!this.x.ztcl_dom_allow) throw new Error("dom: this module has no DOM access (use ztcl-host.wasm)");
163
+ this._domRoot = domRoot ?? globalThis.document?.body;
164
+ if (!this._domRoot) throw new Error("dom: no domRoot and no document.body");
165
+ this._handles = new Map();
166
+ this._ids = new Map();
167
+ this._nextHandle = 1;
168
+ // The elements of `dom create`. A tree of them that is not in the
169
+ // document yet is in scope, so a script can build it before
170
+ // `dom append`.
171
+ this._made = new WeakSet();
172
+ this._domHtml = allow.includes("dom-html");
173
+ // The scripts of `dom on` by "handle:event", and the events that
174
+ // wait for runEvents. Each script has its own compute limit.
175
+ this._listeners = new Map();
176
+ this._domQueue = [];
177
+ this.domComputeLimit = domComputeLimit;
178
+ allow = allow.filter((c) => c !== "dom-html");
179
+ if (this.x.ztcl_dom_allow(this.h) !== 0) throw new Error("ztcl_dom_allow: out of memory");
180
+ allow = allow.filter((c) => c !== "dom");
181
+ }
182
+ const groups = allow.filter((c) => c.startsWith("web:"));
183
+ if (groups.length) {
184
+ if (!this.x.ztcl_web_allow) throw new Error(`${groups[0]}: this module has no Web API bridge (use ztcl-host.wasm)`);
185
+ if (!web?.Bridge) throw new Error(`${groups[0]}: give the module ztcl-web.mjs as the option web`);
186
+ this._webBridge = web;
187
+ this.webComputeLimit = webComputeLimit;
188
+ this._web = new web.Bridge(this, { groups: groups.map((c) => c.slice(4)), root: webRoot });
189
+ if (this.x.ztcl_web_allow(this.h) !== 0) throw new Error("ztcl_web_allow: out of memory");
190
+ if (groups.includes("web:serial") && this.x.ztcl_web_serial_allow(this.h) !== 0) throw new Error("ztcl_web_serial_allow: out of memory");
191
+ if (groups.includes("web:usb") && this.x.ztcl_web_usb_allow(this.h) !== 0) throw new Error("ztcl_web_usb_allow: out of memory");
192
+ // The Tcl wrapper of each group, such as web::bluetooth:: (src/web/).
193
+ for (const g of groups) {
194
+ const t = encoder.encode(g.slice(4));
195
+ const p = this.x.ztcl_alloc(t.length || 1);
196
+ if (!p) throw new Error("ztcl_alloc: out of memory");
197
+ new Uint8Array(this.x.memory.buffer, p, t.length).set(t);
198
+ const rc = this.x.ztcl_web_lib(this.h, p, t.length);
199
+ this.x.ztcl_free(p, t.length || 1);
200
+ if (rc === 1) throw new Error(`ztcl_web_lib ${g}: ${this._text(this.x.ztcl_result_ptr(this.h), this.x.ztcl_result_len(this.h))}`);
201
+ }
202
+ allow = allow.filter((c) => !c.startsWith("web:"));
203
+ }
204
+ if (files) this.setFiles(files);
205
+ if (allow.length) {
206
+ const bad = allow.filter((c) => c !== "file");
207
+ if (bad.length || !this.x.ztcl_allow) throw new Error(`ztcl_allow: this module has no capability ${bad.join(", ") || "file"}`);
208
+ const rc = this.x.ztcl_allow(this.h, 16);
209
+ if (rc !== 0) throw new Error("ztcl_allow: out of memory");
210
+ }
211
+ if (packages) this._addLoad(packages);
212
+ }
213
+
214
+ /// The size in bytes of the scripts and files of a bundle. Zero for a
215
+ /// module with no bundle.
216
+ get bundleSize() {
217
+ return this.x.ztcl_bundle_size?.() ?? 0;
218
+ }
219
+
220
+ /// Runs the scripts of a bundle (`ztcl build --wasm`) in order.
221
+ /// Returns { ok, result, output } as eval() does. On an error,
222
+ /// `result` is "name:line: message". The compute limit applies to all
223
+ /// the scripts of the call together.
224
+ run() {
225
+ if (!this.bundleSize) throw new Error("the module has no bundle");
226
+ return this._call(() => this.x.ztcl_bundle_run(this.h));
82
227
  }
83
228
 
84
229
  /// The memory limit in bytes. ztcl_new sets 2 GiB.
@@ -98,35 +243,800 @@ export class Interp {
98
243
  }
99
244
 
100
245
  /// Runs a script. Returns { ok, result, output }. `result` is the
101
- /// value of the script or the error message. The step limit applies
246
+ /// value of the script or the error message. The compute limit applies
102
247
  /// to each call.
103
248
  eval(script) {
104
249
  const x = this.x;
105
- if (!this.h) throw new Error("the interpreter is closed");
106
- const steps = this.stepLimit == null ? NO_LIMIT : BigInt(this.stepLimit);
107
- x.ztcl_set_step_limit(this.h, steps);
108
- const bytes = encoder.encode(script);
250
+ if (this._depth) return this._evalIn(script);
251
+ const r = this._call(() => {
252
+ const bytes = encoder.encode(script);
253
+ const ptr = x.ztcl_alloc(bytes.length || 1);
254
+ if (!ptr) throw new Error("ztcl_alloc: out of memory");
255
+ new Uint8Array(x.memory.buffer, ptr, bytes.length).set(bytes);
256
+ const rc = x.ztcl_eval(this.h, ptr, bytes.length);
257
+ x.ztcl_free(ptr, bytes.length || 1);
258
+ return rc;
259
+ });
260
+ if (this._events) this._schedule();
261
+ return r;
262
+ }
263
+
264
+ /// Runs the events that are due at `now` (milliseconds on the clock of
265
+ /// the option `now`), after `allow: ["event"]`. Returns { ok, result,
266
+ /// output }. A timer of setTimeout calls it for each due event, so a
267
+ /// page calls it only to run the events at a time of its own.
268
+ runEvents(now = this._now()) {
269
+ if (!this._events && !this._listeners && !this._web) throw new Error('runEvents: no allow: ["event"], ["dom"], or a group of "web:"');
270
+ const r = { ok: true, result: "", output: "" };
271
+ const add = (one) => {
272
+ if (!one.ok && r.ok) [r.ok, r.result] = [false, one.result];
273
+ else if (r.ok) r.result = one.result;
274
+ r.output += one.output;
275
+ };
276
+ // The DOM events of `dom on`, in the order of the page.
277
+ const queue = this._domQueue ?? [];
278
+ if (queue.length) this._domQueue = [];
279
+ for (const ev of queue) add(this._domEvent(ev));
280
+ // The results of the promises of `web::call -command` and the events
281
+ // of `web::on`, in their order.
282
+ for (const ev of this._web?.take() ?? []) add(this._webEvent(ev));
283
+ if (this._events) {
284
+ add(this._call(() => this.x.ztcl_run_events(this.h, now)));
285
+ this._schedule();
286
+ }
287
+ return r;
288
+ }
289
+
290
+ // Runs the script of one DOM event with its own compute limit.
291
+ _domEvent({ script, vals }) {
292
+ const x = this.x;
293
+ return this._call(() => {
294
+ const s = encoder.encode(script);
295
+ const v = encoder.encode(vals.join("\0"));
296
+ const sp = x.ztcl_alloc(s.length || 1);
297
+ const vp = x.ztcl_alloc(v.length || 1);
298
+ if (!sp || !vp) throw new Error("ztcl_alloc: out of memory");
299
+ new Uint8Array(x.memory.buffer, sp, s.length).set(s);
300
+ new Uint8Array(x.memory.buffer, vp, v.length).set(v);
301
+ const rc = x.ztcl_dom_event(this.h, sp, s.length, vp, v.length);
302
+ x.ztcl_free(sp, s.length || 1);
303
+ x.ztcl_free(vp, v.length || 1);
304
+ return rc;
305
+ }, this.domComputeLimit);
306
+ }
307
+
308
+ // Runs the script of one event of `web::` with its own compute limit.
309
+ _webEvent({ script, vals, subst = false }) {
310
+ const x = this.x;
311
+ return this._call(() => {
312
+ const s = encoder.encode(script);
313
+ const v = this._webBridge.encodeReply(vals);
314
+ const sp = x.ztcl_alloc(s.length || 1);
315
+ const vp = x.ztcl_alloc(v.length);
316
+ if (!sp || !vp) throw new Error("ztcl_alloc: out of memory");
317
+ new Uint8Array(x.memory.buffer, sp, s.length).set(s);
318
+ new Uint8Array(x.memory.buffer, vp, v.length).set(v);
319
+ const rc = x.ztcl_web_event(this.h, sp, s.length, vp, v.length, subst ? 1 : 0);
320
+ x.ztcl_free(sp, s.length || 1);
321
+ x.ztcl_free(vp, v.length);
322
+ return rc;
323
+ }, this.webComputeLimit);
324
+ }
325
+
326
+ // Runs the queue of DOM events from a timer of setTimeout.
327
+ _kick() {
328
+ if (this._kickTimer !== null || !this.h) return;
329
+ this._kickTimer = setTimeout(() => {
330
+ this._kickTimer = null;
331
+ if (!this.h) return;
332
+ const r = this.runEvents();
333
+ if (this.onEvents) this.onEvents(r);
334
+ }, 0);
335
+ }
336
+
337
+ // Sets the timer for the next event, or clears it when no event exists.
338
+ _schedule() {
339
+ if (this._timer !== null) clearTimeout(this._timer);
340
+ this._timer = null;
341
+ if (!this.h) return;
342
+ const left = this.x.ztcl_next_event(this.h, this._now());
343
+ if (left < 0) return;
344
+ this._timer = setTimeout(() => {
345
+ this._timer = null;
346
+ const r = this.runEvents();
347
+ if (this.onEvents) this.onEvents(r);
348
+ }, left);
349
+ }
350
+
351
+ /// The point proc `name` of a script, after `point: true`: its
352
+ /// `outputs` (the names of the columns that it writes) and its
353
+ /// run({ n, seed, inputs, feature, outputs }) runs the proc over n
354
+ /// points: `inputs` maps field names (x, y, z, width, height, speed,
355
+ /// flow, layer, path, dist) to Float64Array columns, `feature` is a
356
+ /// Uint8Array of feature numbers, and `outputs` maps output names
357
+ /// (offset, move_x, move_y, width, flow, speed, skip) to Float64Array
358
+ /// columns with the start values. run() writes the new values into
359
+ /// `outputs` and returns the compute units. The compute limit applies
360
+ /// to each call.
361
+ pointProc(name) {
362
+ const x = this.x;
363
+ const bytes = encoder.encode(name);
109
364
  const ptr = x.ztcl_alloc(bytes.length || 1);
110
- if (!ptr) throw new Error("ztcl_alloc: out of memory");
111
365
  new Uint8Array(x.memory.buffer, ptr, bytes.length).set(bytes);
112
- const rc = x.ztcl_eval(this.h, ptr, bytes.length);
366
+ const id = x.ztcl_point_compile(this.h, ptr, bytes.length);
113
367
  x.ztcl_free(ptr, bytes.length || 1);
368
+ if (!id) throw new Error(this._text(x.ztcl_result_ptr(this.h), x.ztcl_result_len(this.h)));
369
+ const mask = x.ztcl_point_outputs(this.h, id);
370
+ return { outputs: POINT_OUTS.filter((_, k) => mask & (1 << k)), run: (points) => this._pointRun(id, points) };
371
+ }
372
+
373
+ _pointRun(id, { n, seed = 1, inputs = {}, feature = null, outputs = {} }) {
374
+ const x = this.x;
375
+ const size = (POINT_FIELDS.length + POINT_OUTS.length) * n * 8 + n;
376
+ // ztcl_point_run reads f64 columns, so the block starts on 8 bytes.
377
+ const raw = x.ztcl_alloc(size + 8);
378
+ if (!raw) throw new Error("ztcl_alloc: out of memory");
379
+ const ptr = (raw + 7) & ~7;
380
+ try {
381
+ let inMask = 0;
382
+ let outMask = 0;
383
+ const f64 = new Float64Array(x.memory.buffer, ptr, (POINT_FIELDS.length + POINT_OUTS.length) * n);
384
+ POINT_FIELDS.forEach((f, k) => {
385
+ if (f === "feature") {
386
+ if (feature) {
387
+ new Uint8Array(x.memory.buffer, ptr + (POINT_FIELDS.length + POINT_OUTS.length) * n * 8, n).set(feature.subarray(0, n));
388
+ inMask |= 1 << k;
389
+ }
390
+ } else if (inputs[f]) {
391
+ f64.set(inputs[f].subarray(0, n), k * n);
392
+ inMask |= 1 << k;
393
+ }
394
+ });
395
+ POINT_OUTS.forEach((o, k) => {
396
+ if (outputs[o]) {
397
+ f64.set(outputs[o].subarray(0, n), (POINT_FIELDS.length + k) * n);
398
+ outMask |= 1 << k;
399
+ }
400
+ });
401
+ x.ztcl_set_compute_limit(this.h, this.computeLimit == null ? NO_LIMIT : BigInt(this.computeLimit));
402
+ const units = x.ztcl_point_run(this.h, id, ptr, n, seed, inMask, outMask);
403
+ if (units === -1n) throw new Error("compute limit reached");
404
+ if (units < 0n) throw new Error(`ztcl_point_run: error ${units}`);
405
+ const out = new Float64Array(x.memory.buffer, ptr, (POINT_FIELDS.length + POINT_OUTS.length) * n);
406
+ POINT_OUTS.forEach((o, k) => {
407
+ if (outputs[o]) outputs[o].set(out.subarray((POINT_FIELDS.length + k) * n, (POINT_FIELDS.length + k + 1) * n));
408
+ });
409
+ return Number(units);
410
+ } finally {
411
+ x.ztcl_free(raw, size + 8);
412
+ }
413
+ }
414
+
415
+ /// The text of one `puts` of `ztcl-host.wasm`, at the time of the call.
416
+ _live(ptr, len) {
417
+ const text = this._text(ptr, len);
418
+ this._liveOut += text;
419
+ if (this.onOutput) this.onOutput(text);
420
+ }
421
+
422
+ // The import `ztcl_host.zone`: the TZif bytes of a zone name.
423
+ _zone(ptr, len) {
424
+ const bytes = this._zoneOf?.(this._text(ptr, len));
425
+ if (!bytes || !bytes.length) return 1;
426
+ const p = this.x.ztcl_alloc(bytes.length);
427
+ if (!p) return 1;
428
+ new Uint8Array(this.x.memory.buffer, p, bytes.length).set(bytes);
429
+ const slot = new Uint32Array(this.x.memory.buffer, this.x.ztcl_zone_reply(), 2);
430
+ slot[0] = p;
431
+ slot[1] = bytes.length;
432
+ return 0;
433
+ }
434
+
435
+ // The import `ztcl_host.dom` (src/wasmdom.zig). A handle is an index
436
+ // in a table, and 0 is the root. Each element must be the root or below
437
+ // it. The reply text goes into the memory of the module.
438
+ _dom(op, h, a, aLen, b, bLen) {
439
+ const root = this._domRoot;
440
+ const reply = (text) => {
441
+ const bytes = encoder.encode(text);
442
+ if (!bytes.length) return;
443
+ const p = this.x.ztcl_alloc(bytes.length);
444
+ new Uint8Array(this.x.memory.buffer, p, bytes.length).set(bytes);
445
+ const slot = new Uint32Array(this.x.memory.buffer, this.x.ztcl_dom_reply.value, 2);
446
+ slot[0] = p;
447
+ slot[1] = bytes.length;
448
+ };
449
+ const fail = (msg) => {
450
+ reply(msg);
451
+ return -1;
452
+ };
453
+ // An element is in scope when it is the root or below it, or when
454
+ // the top of its tree is an element of `dom create` that is not in
455
+ // the document.
456
+ const inScope = (e) => {
457
+ if (e === root || root.contains(e)) return true;
458
+ let top = e;
459
+ while (top.parentNode) top = top.parentNode;
460
+ return this._made.has(top) && !top.isConnected;
461
+ };
462
+ let el = root;
463
+ if (h !== 0) {
464
+ el = this._handles.get(h);
465
+ if (!el || !inScope(el)) return fail(`invalid DOM handle "dom${h}"`);
466
+ }
467
+ const handle = (e) => {
468
+ let id = this._ids.get(e);
469
+ if (!id) {
470
+ id = this._nextHandle++;
471
+ this._handles.set(id, e);
472
+ this._ids.set(e, id);
473
+ }
474
+ return id;
475
+ };
476
+ const sa = this._text(a, aLen);
477
+ const sb = this._text(b, bLen);
478
+ // No command runs JavaScript: no element that loads or runs code,
479
+ // no event attribute, and no `javascript:` URL.
480
+ const badTags = ["script", "iframe", "frame", "frameset", "object", "embed", "base", "link", "meta", "template"];
481
+ const badAttr = (n, v) => {
482
+ n = n.toLowerCase();
483
+ if (n.startsWith("on") || n === "srcdoc" || n === "is") return true;
484
+ const url = String(v).replace(/[\s\x00-\x1f]/g, "").toLowerCase();
485
+ return url.startsWith("javascript:") || url.startsWith("vbscript:");
486
+ };
487
+ try {
488
+ switch (op) {
489
+ case 1: {
490
+ const e = el.querySelector(sa);
491
+ return e ? handle(e) : 0;
492
+ }
493
+ case 2:
494
+ reply(Array.from(el.querySelectorAll(sa), (e) => handle(e)).join(" "));
495
+ return 0;
496
+ case 3:
497
+ reply(el.textContent ?? "");
498
+ return 0;
499
+ case 4:
500
+ el.textContent = sa;
501
+ return 0;
502
+ case 5:
503
+ reply(el.getAttribute(sa) ?? "");
504
+ return 0;
505
+ case 6:
506
+ if (badAttr(sa, sb)) return fail(`dom attr: the attribute "${sa}" can run code`);
507
+ el.setAttribute(sa, sb);
508
+ return 0;
509
+ case 7: // class: `sa` is add, remove, toggle, or has.
510
+ if (sa === "add") el.classList.add(sb);
511
+ else if (sa === "remove") el.classList.remove(sb);
512
+ else if (sa === "toggle") return el.classList.toggle(sb) ? 1 : 0;
513
+ else return el.classList.contains(sb) ? 1 : 0;
514
+ return 0;
515
+ case 8:
516
+ reply(el.style.getPropertyValue(sa));
517
+ return 0;
518
+ case 9:
519
+ el.style.setProperty(sa, sb);
520
+ return 0;
521
+ case 10:
522
+ reply(String(el.type === "checkbox" || el.type === "radio" ? (el.checked ? 1 : 0) : (el.value ?? "")));
523
+ return 0;
524
+ case 11:
525
+ if (el.type === "checkbox" || el.type === "radio") el.checked = sa !== "" && sa !== "0";
526
+ else el.value = sa;
527
+ return 0;
528
+ case 12:
529
+ el.focus();
530
+ return 0;
531
+ case 13: {
532
+ const tag = sa.toLowerCase();
533
+ if (!/^[a-z][a-z0-9-]*$/.test(tag) || badTags.includes(tag)) return fail(`dom create: the element "${sa}" is not allowed`);
534
+ const e = (root.ownerDocument ?? document).createElement(tag);
535
+ this._made.add(e);
536
+ return handle(e);
537
+ }
538
+ case 14: {
539
+ // append: `b` is the handle of the child as text.
540
+ const kid = this._handles.get(Number(sb));
541
+ if (!kid || !inScope(kid)) return fail(`invalid DOM handle "dom${sb}"`);
542
+ if (kid === root || kid.contains(el)) return fail("dom append: an element cannot go below itself");
543
+ el.appendChild(kid);
544
+ return 0;
545
+ }
546
+ case 15:
547
+ if (el === root) return fail("dom remove: the root stays");
548
+ // The tree of the element leaves the scope with it.
549
+ el.remove();
550
+ for (const [k, l] of this._listeners) {
551
+ if (l.el !== el) continue;
552
+ el.removeEventListener(l.type, l.fn);
553
+ this._listeners.delete(k);
554
+ }
555
+ this._made.delete(el);
556
+ this._handles.delete(h);
557
+ this._ids.delete(el);
558
+ return 0;
559
+ case 16:
560
+ reply(el.innerHTML);
561
+ return 0;
562
+ case 17:
563
+ if (!this._domHtml) return fail('dom html: setting HTML needs the grant "dom-html"');
564
+ el.innerHTML = sa;
565
+ return 0;
566
+ case 18: {
567
+ // on: `sa` is the event type and `sb` the script.
568
+ if (!/^[a-z][a-z0-9_-]*$/.test(sa)) return fail(`dom on: bad event "${sa}"`);
569
+ const key = `${h}:${sa}`;
570
+ const old = this._listeners.get(key);
571
+ if (old) el.removeEventListener(sa, old.fn);
572
+ const fn = (ev) => {
573
+ // An element that left the scope runs no script.
574
+ if (!inScope(el)) return;
575
+ const t = ev.target;
576
+ const value = t && (t.type === "checkbox" || t.type === "radio") ? (t.checked ? "1" : "0") : String(t?.value ?? "");
577
+ const target = t && t.nodeType === 1 && inScope(t) ? `dom${handle(t)}` : "";
578
+ const num = (n) => (typeof n === "number" ? String(n) : "");
579
+ this._domQueue.push({ script: sb, vals: [num(ev.clientX), num(ev.clientY), String(ev.key ?? ""), value, target] });
580
+ this._kick();
581
+ };
582
+ el.addEventListener(sa, fn);
583
+ this._listeners.set(key, { el, type: sa, fn });
584
+ return 0;
585
+ }
586
+ case 19: {
587
+ const key = `${h}:${sa}`;
588
+ const old = this._listeners.get(key);
589
+ if (old) el.removeEventListener(sa, old.fn);
590
+ this._listeners.delete(key);
591
+ return 0;
592
+ }
593
+ }
594
+ return fail(`dom: unknown operation ${op}`);
595
+ } catch (e) {
596
+ return fail(String(e.message || e));
597
+ }
598
+ }
599
+
600
+ _call(f, limit = this.computeLimit) {
601
+ const x = this.x;
602
+ if (!this.h) throw new Error("the interpreter is closed");
603
+ const units = limit == null ? NO_LIMIT : BigInt(limit);
604
+ x.ztcl_set_compute_limit(this.h, units);
605
+ this._liveOut = "";
606
+ const rc = f();
114
607
  const result = this._text(x.ztcl_result_ptr(this.h), x.ztcl_result_len(this.h));
115
- const output = this._text(x.ztcl_output_ptr(this.h), x.ztcl_output_len(this.h));
608
+ const kept = this._text(x.ztcl_output_ptr(this.h), x.ztcl_output_len(this.h));
116
609
  x.ztcl_output_clear(this.h);
117
- if (output && this.onOutput) this.onOutput(output);
118
- return { ok: rc === 0, result, output };
610
+ if (kept && this.onOutput) this.onOutput(kept);
611
+ return { ok: rc === 0, result, output: this._liveOut + kept };
612
+ }
613
+
614
+ /// Loads a C package that `zig cc -target wasm32-wasi` built with
615
+ /// libztclstubs.a (docs/dev/cext-tasks/04w-wasm-bridge.md), and runs
616
+ /// its init function, for example "Sqlite3_Init". The module needs a
617
+ /// ztcl library built with `-Dcext-wasm`. `wasi` is the import object of
618
+ /// `wasi_snapshot_preview1`, for example the wasiImport of a WASI of
619
+ /// Node.js. With no `wasi`, the package gets no files: each call of
620
+ /// WASI gives ENOSYS, except the clock, random bytes, and an empty list
621
+ /// of preopened folders.
622
+ async loadPackage(source, { init, wasi = null } = {}) {
623
+ const mod = source instanceof WebAssembly.Module ? source : await WebAssembly.compile(source);
624
+ const r = this._loadModule(mod, init, wasi);
625
+ if (!r.ok) throw new Error(`${init}: ${r.result}`);
626
+ }
627
+
628
+ // Makes an instance of the package module `mod` and runs `init`. The
629
+ // instance is made at once, so the `load` command can call it. Gives
630
+ // { ok, result } with the result of the init function.
631
+ _loadModule(mod, init, wasi) {
632
+ if (!this.x.ztcl_cext_command) throw new Error("loadPackage: this module has no C packages (build with -Dcext-wasm)");
633
+ if (!init) throw new Error("loadPackage: no init function");
634
+ const index = (this._pkgs ??= []).length;
635
+ const pkg = { x: null, index };
636
+ const imports = { ztcl: this._cextImports(pkg), wasi_snapshot_preview1: wasi ?? noWasi(pkg) };
637
+ const instance = new WebAssembly.Instance(mod, imports);
638
+ pkg.x = instance.exports;
639
+ if (typeof pkg.x[init] !== "function") throw new Error(`loadPackage: the module has no export ${init}`);
640
+ pkg.side = this._side(pkg.x);
641
+ if (wasi?.initialize) wasi.initialize(instance);
642
+ else pkg.x._initialize?.();
643
+ this._pkgs.push(pkg);
644
+ const ip = pkg.x.ztcl_cext_interp(this.h);
645
+ pkg.ip = ip;
646
+ const rc = pkg.x[init](ip);
647
+ // ztcl_cext_result can grow the memory, so the view comes after it.
648
+ const r = pkg.x.ztcl_cext_result(ip);
649
+ return { ok: rc === 0, result: this._argText(pkg.side, r >>> 2, 0) };
650
+ }
651
+
652
+ /// Makes command `name` that runs `fn(args)` in JavaScript. The module
653
+ /// needs a ztcl library built with `-Dcext-wasm`. `args` has the words
654
+ /// after the name, as strings. `fn` gives the result, or throws an
655
+ /// Error for a Tcl error with its message. In `fn`, eval() runs the
656
+ /// script in the frame of the caller of the command.
657
+ defineCommand(name, fn) {
658
+ if (!this.x.ztcl_cext_command) throw new Error("defineCommand: this module has no C packages (build with -Dcext-wasm)");
659
+ this._zside ??= this._side(this.x);
660
+ const index = (this._pkgs ??= []).length;
661
+ this._pkgs.push({ js: fn, index });
662
+ const bytes = encoder.encode(name);
663
+ const p = this._zside.xbuf(bytes.length);
664
+ this._zside.view().u8.set(bytes, p);
665
+ if (this.x.ztcl_cext_command(this.h, index, 0, p, bytes.length) !== 0) throw new Error("defineCommand: out of memory");
666
+ }
667
+
668
+ // Adds the command `load FILE ?PREFIX?` for the C packages of the
669
+ // option `packages`. packages(file) gives a WebAssembly.Module, bytes,
670
+ // or { module, wasi }, or null for no package.
671
+ _addLoad(packages) {
672
+ // The prefix of each loaded file. A file loads one time per interp.
673
+ const loaded = new Map();
674
+ this.defineCommand("load", (args) => {
675
+ if (args.length < 1 || args.length > 3) throw new Error('wrong # args: should be "load fileName ?prefix? ?interp?"');
676
+ const file = args[0];
677
+ const init = initName(file, args[1]);
678
+ const prefix = init.slice(0, -5);
679
+ const had = loaded.get(file);
680
+ if (had !== undefined) {
681
+ if (!args[1] || had.toLowerCase() === prefix.toLowerCase()) return "";
682
+ throw new Error(`file "${file}" is already loaded for package "${had}"`);
683
+ }
684
+ let got;
685
+ try {
686
+ got = packages(file);
687
+ } catch (e) {
688
+ throw new Error(`couldn't load file "${file}": ${e?.message ?? e}`);
689
+ }
690
+ if (!got) throw new Error(`couldn't load file "${file}": no such package`);
691
+ if (got instanceof WebAssembly.Module || ArrayBuffer.isView(got) || got instanceof ArrayBuffer) got = { module: got };
692
+ const mod = got.module instanceof WebAssembly.Module ? got.module : new WebAssembly.Module(got.module);
693
+ const r = this._loadModule(mod, init, got.wasi ?? null);
694
+ if (!r.ok) throw new Error(r.result);
695
+ loaded.set(file, prefix);
696
+ return r.result;
697
+ });
698
+ }
699
+
700
+ // The text of argument `i` of an `Arg` array at word `w0` of `side`.
701
+ // A list (kind 3) gives the text of a Tcl list.
702
+ _argText(side, w0, i) {
703
+ const v = side.view(), w = w0 + i * 4;
704
+ const kind = v.u32[w], len = v.u32[w + 1];
705
+ if (kind === 0) return tclDecode(v.u8.subarray(v.u32[w + 2], v.u32[w + 2] + len));
706
+ if (kind === 3) {
707
+ const e0 = v.u32[w + 2] >>> 2, parts = [];
708
+ for (let j = 0; j < len; j++) {
709
+ const k = side.view().u32[e0 + j * 4];
710
+ const t = this._argText(side, e0, j);
711
+ parts.push(k === 1 || k === 2 ? t : tclElement(t, j === 0));
712
+ }
713
+ return parts.join(" ");
714
+ }
715
+ const dv = new DataView(side.buf, (w + 2) << 2, 8);
716
+ if (kind === 1) return String(dv.getBigInt64(0, true));
717
+ return doubleText(dv.getFloat64(0, true));
718
+ }
719
+
720
+ // The bytes that `n` `Arg` records at word `w` of `side` need in the
721
+ // other memory: the text, and the arrays of lists with room to align.
722
+ _argSize(side, w, n) {
723
+ const u32 = side.view().u32;
724
+ let size = 0;
725
+ for (let i = 0; i < n; i++) {
726
+ const k = u32[w + i * 4], len = u32[w + i * 4 + 1];
727
+ if (k === 0) size += len;
728
+ else if (k === 3) size += 7 + len * 16 + this._argSize(side, u32[w + i * 4 + 2] >>> 2, len);
729
+ }
730
+ return size;
731
+ }
732
+
733
+ // Copies `n` `Arg` records at word `w` of `from` to word `d` of `to`.
734
+ // Text and the arrays of lists go to byte `off` of `to` and after.
735
+ // Gives the byte after the last copy.
736
+ _argCopy(from, w, n, to, d, off) {
737
+ const f = from.view(), t = to.view();
738
+ for (let i = 0; i < n; i++) {
739
+ const si = w + i * 4, di = d + i * 4;
740
+ const k = f.u32[si], len = f.u32[si + 1], a = f.u32[si + 2];
741
+ t.u32[di] = k; t.u32[di + 1] = len;
742
+ if (k === 0) {
743
+ t.u8.set(f.u8.subarray(a, a + len), off);
744
+ t.u32[di + 2] = off; t.u32[di + 3] = 0;
745
+ off += len;
746
+ } else if (k === 3) {
747
+ const at = (off + 7) & ~7;
748
+ t.u32[di + 2] = at; t.u32[di + 3] = 0;
749
+ off = this._argCopy(from, a >>> 2, len, to, at >>> 2, at + len * 16);
750
+ } else {
751
+ t.u32[di + 2] = a; t.u32[di + 3] = f.u32[si + 3];
752
+ }
753
+ }
754
+ return off;
755
+ }
756
+
757
+ // Runs JavaScript command `fn` with the arguments at `argv` in ztcl.
758
+ _jsCall(fn, argc, argv) {
759
+ const zs = this._zside, w0 = argv >>> 2;
760
+ const args = [];
761
+ for (let i = 1; i < argc; i++) args.push(this._argText(zs, w0, i));
762
+ let rc = 0, out;
763
+ this._depth = (this._depth ?? 0) + 1;
764
+ try {
765
+ out = String(fn(args) ?? "");
766
+ } catch (e) {
767
+ rc = 1;
768
+ out = String(e?.message ?? e);
769
+ } finally {
770
+ this._depth--;
771
+ }
772
+ const bytes = encoder.encode(out);
773
+ const p = zs.xbuf(bytes.length);
774
+ const v = zs.view();
775
+ v.u8.set(bytes, p);
776
+ v.u32[zs.reply] = 0; v.u32[zs.reply + 1] = bytes.length; v.u32[zs.reply + 2] = p; v.u32[zs.reply + 3] = 0;
777
+ return rc;
778
+ }
779
+
780
+ // eval() inside a command of defineCommand: the script runs in the
781
+ // frame of the caller, and the codes of Tcl stay.
782
+ _evalIn(script) {
783
+ const zs = this._zside;
784
+ const bytes = encoder.encode(script);
785
+ const p = zs.xbuf(bytes.length);
786
+ zs.view().u8.set(bytes, p);
787
+ const code = this.x.ztcl_cext_eval(this.h, p, bytes.length, 0);
788
+ const result = this._argText(zs, zs.reply, 0);
789
+ return { ok: code === 0, code, result, output: "" };
119
790
  }
120
791
 
121
792
  /// Frees the interpreter. Drop the Interp after this call.
122
793
  close() {
794
+ if (this._timer !== null) clearTimeout(this._timer);
795
+ this._timer = null;
796
+ if (this._kickTimer) clearTimeout(this._kickTimer);
797
+ this._kickTimer = null;
798
+ for (const l of this._listeners?.values() ?? []) l.el.removeEventListener(l.type, l.fn);
799
+ this._listeners?.clear();
800
+ // The interp of each package goes first, so the delete procs of its
801
+ // assoc data run.
802
+ for (const pkg of this._pkgs ?? []) if (pkg.ip) pkg.x.ztcl_cext_interp_free(pkg.ip);
803
+ this._pkgs = [];
123
804
  if (this.h) this.x.ztcl_delete(this.h);
124
805
  this.h = 0;
125
806
  }
126
807
 
808
+ // The views of the memory of a side of the bridge (`side.x` is the
809
+ // instance). A view is made again after the memory grows. The reply
810
+ // record has a fixed address, and the exchange buffer moves only when
811
+ // it grows, so the glue keeps both.
812
+ _side(x) {
813
+ const side = { x, buf: null, u8: null, u32: null, reply: x.ztcl_cext_reply() >>> 2, xb: 0, xcap: -1, args: 0, acap: -1 };
814
+ side.view = () => {
815
+ if (side.buf !== x.memory.buffer) {
816
+ side.buf = x.memory.buffer;
817
+ side.u8 = new Uint8Array(side.buf);
818
+ side.u32 = new Uint32Array(side.buf);
819
+ }
820
+ return side;
821
+ };
822
+ // The address of an exchange buffer of at least `len` bytes.
823
+ side.xbuf = (len) => {
824
+ if (len > side.xcap) {
825
+ side.xb = x.ztcl_cext_buf(Math.max(len, 2 * side.xcap, 256));
826
+ side.xcap = Math.max(len, 2 * side.xcap, 256);
827
+ }
828
+ return side.xb;
829
+ };
830
+ return side;
831
+ }
832
+
833
+ // Copies the reply record of `from` to the reply of `to`. Text goes
834
+ // into the exchange buffer of `to`.
835
+ _cextReply(from, to) {
836
+ const f = from.view().u32, r = from.reply;
837
+ const kind = f[r], len = f[r + 1];
838
+ if (kind === 3) {
839
+ const off = to.xbuf(this._argSize(from, r, 1));
840
+ this._argCopy(from, r, 1, to, to.reply, off);
841
+ return;
842
+ }
843
+ if (kind === 0) {
844
+ const p = f[r + 2];
845
+ const dst = to.xbuf(len);
846
+ const t = to.view();
847
+ t.u8.set(from.u8.subarray(p, p + len), dst);
848
+ const tr = to.reply;
849
+ t.u32[tr] = 0; t.u32[tr + 1] = len; t.u32[tr + 2] = dst; t.u32[tr + 3] = 0;
850
+ return;
851
+ }
852
+ const t = to.view().u32, tr = to.reply;
853
+ t[tr] = kind; t[tr + 1] = len; t[tr + 2] = f[r + 2]; t[tr + 3] = f[r + 3];
854
+ }
855
+
856
+ // Copies `len` bytes at `ptr` of the package into the exchange buffer
857
+ // of ztcl, with `extra` bytes of room after them.
858
+ _toZtcl(p, ptr, len, extra = 0) {
859
+ const z = this._zside;
860
+ const zb = z.xbuf(len + extra);
861
+ z.view().u8.set(p.view().u8.subarray(ptr, ptr + len), zb);
862
+ return zb;
863
+ }
864
+
865
+ _cextImports(pkg) {
866
+ const z = this.x;
867
+ this._zside ??= this._side(z);
868
+ const zs = this._zside;
869
+ return {
870
+ cmd_create: (h, id, ptr, len) => z.ztcl_cext_command(h, pkg.index, id, this._toZtcl(pkg.side, ptr, len), len),
871
+ cmd_delete: (h, ptr, len) => {
872
+ const rc = z.ztcl_cext_delete(h, this._toZtcl(pkg.side, ptr, len), len);
873
+ if (rc !== 0) this._cextReply(zs, pkg.side);
874
+ return rc;
875
+ },
876
+ eval: (h, ptr, len, flags) => {
877
+ const rc = z.ztcl_cext_eval(h, this._toZtcl(pkg.side, ptr, len), len, flags);
878
+ this._cextReply(zs, pkg.side);
879
+ return rc;
880
+ },
881
+ var_get: (h, ptr, len, flags) => {
882
+ const rc = z.ztcl_cext_var_get(h, this._toZtcl(pkg.side, ptr, len), len, flags);
883
+ this._cextReply(zs, pkg.side);
884
+ return rc;
885
+ },
886
+ var_set: (h, ptr, len, arg, flags) => {
887
+ const ps = pkg.side;
888
+ const a = arg >>> 2;
889
+ const zb = this._toZtcl(ps, ptr, len, this._argSize(ps, a, 1));
890
+ this._argCopy(ps, a, 1, zs, zs.reply, zb + len);
891
+ const rc = z.ztcl_cext_var_set(h, zb, len, zs.reply << 2, flags);
892
+ if (rc !== 0) this._cextReply(zs, ps);
893
+ return rc;
894
+ },
895
+ // The error state of ztcl after an error, into the reply.
896
+ err_get: (h) => {
897
+ if (!z.ztcl_cext_err_get || z.ztcl_cext_err_get(h) !== 0) return 1;
898
+ this._cextReply(zs, pkg.side);
899
+ return 0;
900
+ },
901
+ // The error state of a command of the package: a list Arg.
902
+ err_set: (h, arg) => {
903
+ if (!z.ztcl_cext_err_set) return 1;
904
+ const ps = pkg.side, a = arg >>> 2;
905
+ const zb = zs.xbuf(this._argSize(ps, a, 1));
906
+ this._argCopy(ps, a, 1, zs, zs.reply, zb);
907
+ return z.ztcl_cext_err_set(h, zs.reply << 2);
908
+ },
909
+ // An operation of the interp tree (zside.InterpOp) with a list Arg.
910
+ interp_op: (h, op, arg) => {
911
+ if (!z.ztcl_cext_interp_op) return 1;
912
+ const ps = pkg.side, a = arg >>> 2;
913
+ const zb = zs.xbuf(this._argSize(ps, a, 1));
914
+ this._argCopy(ps, a, 1, zs, zs.reply, zb);
915
+ const rc = z.ztcl_cext_interp_op(h, op, zs.reply << 2);
916
+ this._cextReply(zs, pkg.side);
917
+ return rc;
918
+ },
919
+ pkg_provide: (h, ptr, len, vptr, vlen) => {
920
+ if (!z.ztcl_cext_provide) return 0;
921
+ const zb = this._toZtcl(pkg.side, ptr, len, vlen);
922
+ zs.view().u8.set(pkg.side.view().u8.subarray(vptr, vptr + vlen), zb + len);
923
+ const rc = z.ztcl_cext_provide(h, zb, len, zb + len, vlen);
924
+ if (rc !== 0) this._cextReply(zs, pkg.side);
925
+ return rc;
926
+ },
927
+ };
928
+ }
929
+
930
+ // The import `ztcl_cext.call`: copies the arguments into the package
931
+ // and runs the command there.
932
+ _cextCall(pkgIndex, id, argc, argv, prec) {
933
+ const pkg = this._pkgs[pkgIndex];
934
+ if (pkg.js) return this._jsCall(pkg.js, argc, argv);
935
+ const ps = pkg.side;
936
+ // The package keeps its own copy of `tcl_precision`.
937
+ if (ps.prec !== prec) {
938
+ ps.x.ztcl_cext_precision?.(prec);
939
+ ps.prec = prec;
940
+ }
941
+ const zs = this._zside.view();
942
+ const src = zs.u32, s0 = argv >>> 2;
943
+ let total = 0;
944
+ for (let i = 0; i < argc; i++) {
945
+ const k = src[s0 + i * 4];
946
+ if (k === 0) total += src[s0 + i * 4 + 1];
947
+ else if (k === 3) total += this._argSize(this._zside, s0 + i * 4, 1);
948
+ }
949
+ let off = ps.xbuf(total);
950
+ if (argc > ps.acap) {
951
+ ps.acap = Math.max(argc, 16);
952
+ ps.args = ps.x.ztcl_cext_args(ps.acap);
953
+ }
954
+ const p = ps.view();
955
+ const dst = p.u32, d0 = ps.args >>> 2;
956
+ const zu8 = zs.u8, pu8 = p.u8;
957
+ for (let i = 0; i < argc; i++) {
958
+ const si = s0 + i * 4, di = d0 + i * 4;
959
+ const k = src[si], len = src[si + 1];
960
+ dst[di] = k; dst[di + 1] = len;
961
+ if (k === 0) {
962
+ const a = src[si + 2];
963
+ if (len < 16) for (let j = 0; j < len; j++) pu8[off + j] = zu8[a + j];
964
+ else pu8.set(zu8.subarray(a, a + len), off);
965
+ dst[di + 2] = off; dst[di + 3] = 0;
966
+ off += len;
967
+ } else if (k === 3) {
968
+ off = this._argCopy(this._zside, si, 1, ps, di, off);
969
+ } else {
970
+ dst[di + 2] = src[si + 2]; dst[di + 3] = src[si + 3];
971
+ }
972
+ }
973
+ const rc = ps.x.ztcl_cext_dispatch(id, argc);
974
+ this._cextReply(ps, this._zside);
975
+ return rc;
976
+ }
977
+
127
978
  _text(ptr, len) {
128
979
  return decoder.decode(new Uint8Array(this.x.memory.buffer, ptr, len));
129
980
  }
981
+
982
+ /// Gives the scripts the files of `files`, an object of names and
983
+ /// bytes (a Uint8Array or an ArrayBuffer), for the capability `file`:
984
+ /// `open name rb` reads them. They take the place of the files of a
985
+ /// bundle.
986
+ setFiles(files) {
987
+ const x = this.x;
988
+ if (!x.ztcl_files_set) throw new Error("files: this module has no ztcl_files_set");
989
+ const parts = [encoder.encode("ZTB1")];
990
+ const names = Object.keys(files);
991
+ const u32 = (n) => { const b = new Uint8Array(4); new DataView(b.buffer).setUint32(0, n, true); return b; };
992
+ parts.push(u32(names.length));
993
+ for (const n of names) {
994
+ const name = encoder.encode(n);
995
+ const data = files[n] instanceof Uint8Array ? files[n] : new Uint8Array(files[n]);
996
+ parts.push(Uint8Array.of(1), u32(name.length), u32(data.length), name, data);
997
+ }
998
+ const len = parts.reduce((s, p) => s + p.length, 0);
999
+ const p = x.ztcl_alloc(len || 1);
1000
+ if (!p) throw new Error("ztcl_alloc: out of memory");
1001
+ let at = p;
1002
+ for (const part of parts) { new Uint8Array(x.memory.buffer, at, part.length).set(part); at += part.length; }
1003
+ const rc = x.ztcl_files_set(this.h, p, len);
1004
+ x.ztcl_free(p, len || 1);
1005
+ if (rc !== 0) throw new Error("ztcl_files_set: out of memory");
1006
+ }
1007
+
1008
+ /// The names of the files that the scripts wrote, in a build with
1009
+ /// files in memory (ztcl-shell.wasm).
1010
+ fileNames() {
1011
+ const x = this.x;
1012
+ if (!x.ztcl_file_names || x.ztcl_file_names(this.h) !== 0) return [];
1013
+ return this._text(x.ztcl_result_ptr(this.h), x.ztcl_result_len(this.h)).split("\n").filter(Boolean);
1014
+ }
1015
+
1016
+ /// A copy of the bytes of a file that a script wrote, or null.
1017
+ readFile(name) {
1018
+ const x = this.x;
1019
+ if (!x.ztcl_file_get) return null;
1020
+ const t = encoder.encode(name);
1021
+ const p = x.ztcl_alloc(t.length || 1);
1022
+ new Uint8Array(x.memory.buffer, p, t.length).set(t);
1023
+ const rc = x.ztcl_file_get(this.h, p, t.length);
1024
+ x.ztcl_free(p, t.length || 1);
1025
+ if (rc !== 0) return null;
1026
+ return new Uint8Array(x.memory.buffer, x.ztcl_result_ptr(this.h), x.ztcl_result_len(this.h)).slice();
1027
+ }
1028
+ }
1029
+
1030
+ /// Runs the scripts of a bundle in a new interpreter and closes it.
1031
+ /// `module` is a source as for compile(). Options are as for
1032
+ /// Interp.create. Returns { ok, result, output }.
1033
+ export async function run(module, options = {}) {
1034
+ const tcl = await Interp.create(module, options);
1035
+ try {
1036
+ return tcl.run();
1037
+ } finally {
1038
+ tcl.close();
1039
+ }
130
1040
  }
131
1041
 
132
1042
  /// Runs scripts in a Web Worker, so a long script does not block the
@@ -137,9 +1047,11 @@ export class WorkerInterp {
137
1047
  /// are as for Interp.create.
138
1048
  constructor(wasm, options = {}) {
139
1049
  if (isOptions(wasm)) [wasm, options] = [undefined, wasm];
140
- const { stepLimit = null, memLimit = null, onOutput = null } = options;
1050
+ const { computeLimit = null, memLimit = null, onOutput = null, allow = [], files = null } = options;
141
1051
  this.wasm = new URL(wasm ?? wasmURL(), globalThis.location?.href).href;
142
- this.stepLimit = stepLimit;
1052
+ // The capabilities and the files of the interpreter in the worker.
1053
+ this.setup = { allow, files };
1054
+ this.computeLimit = computeLimit;
143
1055
  this.memLimit = memLimit;
144
1056
  this.onOutput = onOutput;
145
1057
  this.worker = null;
@@ -166,21 +1078,23 @@ export class WorkerInterp {
166
1078
  if (data.error) p.reject(new Error(data.error));
167
1079
  else {
168
1080
  if (data.output && this.onOutput) this.onOutput(data.output);
169
- p.resolve({ ok: data.ok, result: data.result, output: data.output, memorySize: data.memorySize });
1081
+ p.resolve({ ok: data.ok, result: data.result, output: data.output, memorySize: data.memorySize, files: data.files });
170
1082
  }
171
1083
  };
172
1084
  this.worker.onerror = (e) => this._fail(e.message || "the worker failed");
173
- this.worker.postMessage({ init: this.wasm });
1085
+ this.worker.postMessage({ init: this.wasm, setup: this.setup });
174
1086
  }
175
1087
 
176
1088
  /// Runs a script in the worker. Returns a promise of
177
- /// { ok, result, output, memorySize }.
178
- eval(script) {
1089
+ /// { ok, result, output, memorySize, files }. With `{ collect: true }`,
1090
+ /// `files` is an object of the names and the bytes of the files that
1091
+ /// the scripts wrote (in ztcl-shell.wasm).
1092
+ eval(script, { collect = false } = {}) {
179
1093
  if (!this.worker) this._start();
180
1094
  const id = this.next++;
181
1095
  return new Promise((resolve, reject) => {
182
1096
  this.pending.set(id, { resolve, reject });
183
- this.worker.postMessage({ id, script, stepLimit: this.stepLimit, memLimit: this.memLimit });
1097
+ this.worker.postMessage({ id, script, collect, computeLimit: this.computeLimit, memLimit: this.memLimit });
184
1098
  });
185
1099
  }
186
1100
 
@@ -207,3 +1121,93 @@ export class WorkerInterp {
207
1121
  this.pending.clear();
208
1122
  }
209
1123
  }
1124
+
1125
+ // The WASI imports of a package with no files: ENOSYS (52) for each
1126
+ // call, except the clock, random bytes, and empty arguments and
1127
+ // environment. `pkg.x` is the instance after instantiate().
1128
+ // The init function of `load FILE ?PREFIX?`, by the rule of Tcl: with
1129
+ // no prefix, the letters and underscores at the start of the file name,
1130
+ // after "lib". The first letter is upper case and the rest lower case.
1131
+ function initName(file, prefix) {
1132
+ let p = prefix;
1133
+ if (!p) {
1134
+ let tail = file.slice(file.lastIndexOf("/") + 1);
1135
+ if (tail.startsWith("lib")) tail = tail.slice(3);
1136
+ p = /^[A-Za-z_]*/.exec(tail)[0];
1137
+ }
1138
+ return p.charAt(0).toUpperCase() + p.slice(1).toLowerCase() + "_Init";
1139
+ }
1140
+
1141
+ // The text of a double for a JavaScript command. A whole number keeps
1142
+ // its ".0", as in Tcl.
1143
+ // The text of the modified UTF-8 of Tcl, where U+0000 is C0 80.
1144
+ function tclDecode(bytes) {
1145
+ if (!bytes.includes(0xc0)) return decoder.decode(bytes);
1146
+ const out = new Uint8Array(bytes.length);
1147
+ let n = 0;
1148
+ for (let i = 0; i < bytes.length; i++) {
1149
+ if (bytes[i] === 0xc0 && bytes[i + 1] === 0x80) {
1150
+ out[n++] = 0;
1151
+ i++;
1152
+ } else out[n++] = bytes[i];
1153
+ }
1154
+ return decoder.decode(out.subarray(0, n));
1155
+ }
1156
+
1157
+ // The element `s` of the text of a Tcl list, quoted by the rules of
1158
+ // value.appendElement in ztcl.
1159
+ function tclElement(s, first) {
1160
+ if (s.length === 0) return "{}";
1161
+ let brace = (first && s[0] === "#") || s[0] === "{" || s[0] === '"';
1162
+ let escape = false, depth = 0, balanced = true;
1163
+ for (let i = 0; i < s.length; i++) {
1164
+ const c = s[i];
1165
+ if (c === "{") depth++;
1166
+ else if (c === "}") { if (--depth < 0) balanced = false; }
1167
+ else if (c === "\\") {
1168
+ brace = true;
1169
+ if (i + 1 >= s.length || s[i + 1] === "\n") balanced = false;
1170
+ i++;
1171
+ } else if (" \t\n\r\v\f;$[".includes(c)) brace = true;
1172
+ else if (c === "]" || c === '"') escape = true;
1173
+ }
1174
+ if (depth !== 0) balanced = false;
1175
+ if (!brace && !escape && balanced) return s;
1176
+ if (balanced && (brace || !escape)) return "{" + s + "}";
1177
+ const names = { "\t": "\\t", "\n": "\\n", "\r": "\\r", "\v": "\\v", "\f": "\\f" };
1178
+ let out = "";
1179
+ for (const c of s) {
1180
+ if (c === "{" || c === "}") out += balanced ? c : "\\" + c;
1181
+ else if ("\\ ;\"$[]".includes(c)) out += "\\" + c;
1182
+ else out += names[c] ?? c;
1183
+ }
1184
+ return out;
1185
+ }
1186
+
1187
+ function doubleText(d) {
1188
+ if (Number.isNaN(d)) return "NaN";
1189
+ if (!Number.isFinite(d)) return d > 0 ? "Inf" : "-Inf";
1190
+ const s = String(d);
1191
+ return /^-?\d+$/.test(s) ? s + ".0" : s;
1192
+ }
1193
+
1194
+ function noWasi(pkg) {
1195
+ const mem = () => pkg.x.memory.buffer;
1196
+ const own = {
1197
+ clock_time_get: (id, prec, out) => {
1198
+ new DataView(mem()).setBigUint64(out, BigInt(Date.now()) * 1000000n, true);
1199
+ return 0;
1200
+ },
1201
+ random_get: (ptr, len) => {
1202
+ globalThis.crypto.getRandomValues(new Uint8Array(mem(), ptr, len));
1203
+ return 0;
1204
+ },
1205
+ args_sizes_get: (argc, size) => { new Uint32Array(mem(), argc, 1)[0] = 0; new Uint32Array(mem(), size, 1)[0] = 0; return 0; },
1206
+ environ_sizes_get: (n, size) => { new Uint32Array(mem(), n, 1)[0] = 0; new Uint32Array(mem(), size, 1)[0] = 0; return 0; },
1207
+ proc_exit: (code) => { throw new Error(`the package called proc_exit(${code})`); },
1208
+ // EBADF: the package has no preopened folders. The startup of the
1209
+ // C library stops at the first EBADF.
1210
+ fd_prestat_get: () => 8,
1211
+ };
1212
+ return new Proxy({}, { get: (_, name) => own[name] ?? (() => 52) });
1213
+ }