@beetlebug/ztcl 0.0.0-stage → 0.2.0-beta

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 ADDED
@@ -0,0 +1,24 @@
1
+ BSD 2-Clause License
2
+
3
+ Copyright (c) 2026 The ztcl authors
4
+
5
+ Redistribution and use in source and binary forms, with or without
6
+ modification, are permitted provided that the following conditions are met:
7
+
8
+ 1. Redistributions of source code must retain the above copyright notice, this
9
+ list of conditions and the following disclaimer.
10
+
11
+ 2. Redistributions in binary form must reproduce the above copyright notice,
12
+ this list of conditions and the following disclaimer in the documentation
13
+ and/or other materials provided with the distribution.
14
+
15
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
16
+ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
17
+ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
18
+ DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
19
+ FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
20
+ DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
21
+ SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
22
+ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
23
+ OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
24
+ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
package/NOTICE ADDED
@@ -0,0 +1,16 @@
1
+ ztcl
2
+ Copyright (c) 2026 The ztcl authors
3
+ Licensed under the BSD 2-Clause License. See LICENSE.
4
+
5
+ ztcl.wasm contains the Zig standard library. The Zig standard library
6
+ has ports of code from other projects. The license texts are in the
7
+ licenses/ folder.
8
+
9
+ Source Use License text
10
+ Zig standard library All of ztcl licenses/zig-std-MIT.txt
11
+ musl libc Math functions of std.math licenses/musl-MIT.txt
12
+ Go std.fmt.parseFloat, std.math.pow licenses/go-BSD-3-Clause.txt
13
+ ARM optimized-routines std.math.acos, std.math.atan licenses/arm-optimized-routines.txt
14
+
15
+ ztcl follows the language rules and the command behavior of Tcl. It has
16
+ no code of Tcl. The Tcl/Tk License is in licenses/tcl-license.txt.
package/README.md CHANGED
@@ -1,3 +1,108 @@
1
- # Temporary Holding Version
1
+ # @beetlebug/ztcl
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
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.
4
+
5
+ - The module is 871 KB, or about 300 KB with gzip. It has no imports.
6
+ - It runs in a browser, in a Web Worker, and in Node.js 22.3 or later.
7
+ - It has types for TypeScript.
8
+
9
+ The docs are at [beetlebug.org/ztcl](https://beetlebug.org/ztcl/webassembly/). The source is at [github.com/beetlebugorg/ztcl](https://github.com/beetlebugorg/ztcl).
10
+
11
+ ## Install
12
+
13
+ ```sh
14
+ npm install @beetlebug/ztcl
15
+ ```
16
+
17
+ ## In a page with no build step
18
+
19
+ ```html
20
+ <script type="module">
21
+ import { Interp } from "https://cdn.jsdelivr.net/npm/@beetlebug/ztcl@0.2.0-beta/ztcl.mjs";
22
+
23
+ const tcl = await Interp.create({ stepLimit: 1_000_000, memLimit: 64 << 20 });
24
+ console.log(tcl.eval("expr {6 * 7}").result); // 42
25
+ </script>
26
+ ```
27
+
28
+ The module loads `ztcl.wasm` from its own folder on the CDN. `WorkerInterp` also works from the CDN: it starts its worker from a small blob script that imports `ztcl-worker.mjs`. The jsDelivr form `https://cdn.jsdelivr.net/npm/@beetlebug/ztcl/+esm` resolves `ztcl.wasm` in the same folder, but no test runs it.
29
+
30
+ ## With a bundler
31
+
32
+ ```js
33
+ import { Interp, WorkerInterp } from "@beetlebug/ztcl";
34
+
35
+ const tcl = await Interp.create({
36
+ stepLimit: 1_000_000,
37
+ memLimit: 64 << 20,
38
+ onOutput: (text) => console.log(text),
39
+ });
40
+ const r = tcl.eval("puts hello; expr {6 * 7}");
41
+ // r is { ok: true, result: "42", output: "hello\n" }
42
+ ```
43
+
44
+ The module finds `ztcl.wasm` with `new URL("./ztcl.wasm", import.meta.url)`, and `WorkerInterp` starts its worker with `new Worker(new URL("./ztcl-worker.mjs", import.meta.url))`. `vite build` copies both files. For the Vite dev server, keep the package out of the dependency step, so the two files stay together:
45
+
46
+ ```js
47
+ // vite.config.js
48
+ export default { optimizeDeps: { exclude: ["@beetlebug/ztcl"] } };
49
+ ```
50
+
51
+ The tests of the package run Vite 7. Webpack 5 and Rollup also have support for the `new URL` form, but no test runs them. With another tool, copy `ztcl.wasm` to your site and give its URL to `Interp.create(url, options)`.
52
+
53
+ ## In Node.js
54
+
55
+ ```js
56
+ import { Interp } from "@beetlebug/ztcl";
57
+
58
+ const tcl = await Interp.create({ stepLimit: 1_000_000, memLimit: 64 << 20 });
59
+ const r = tcl.eval("proc sq {x} {expr {$x * $x}}; sq 12");
60
+ console.log(r.result); // 144
61
+ tcl.close();
62
+ ```
63
+
64
+ ## A worker that a person can stop
65
+
66
+ A script on the main thread blocks the page until it ends or hits a limit. `WorkerInterp` runs scripts in a Web Worker, and `stop()` ends the script at once.
67
+
68
+ ```js
69
+ import { WorkerInterp } from "@beetlebug/ztcl";
70
+
71
+ const tcl = new WorkerInterp({ memLimit: 64 << 20 });
72
+ const r = await tcl.eval(code); // the page stays live
73
+ cancel.onclick = () => tcl.stop(); // r is { ok: false, result: "stopped" }
74
+ ```
75
+
76
+ The next `eval` after `stop` starts a new worker with a new interpreter. `@beetlebug/ztcl/worker` is the worker script, for a page that makes the worker itself.
77
+
78
+ ## API
79
+
80
+ | Export | Use |
81
+ |---|---|
82
+ | `Interp.create(source?, options?)` | Makes an interpreter in a new WebAssembly instance. |
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`. |
85
+ | `interp.memorySize` | The size of the linear memory in bytes. The memory never shrinks, so this is the peak. |
86
+ | `interp.close()` | Frees the interpreter. |
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
+ | `compile(source?)` | Compiles the module one time, for many interpreters. |
89
+ | `wasmURL()` | The URL of the `ztcl.wasm` file of the package. |
90
+
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.
92
+
93
+ 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
+
95
+ 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
+
97
+ ## Limits and capabilities
98
+
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.
100
+ - **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
+ - **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
+ - **Output.** `puts` goes into a buffer. `eval` returns the text, and `onOutput` gets it when the script ends.
103
+
104
+ Put only numbers or quoted lists into the text of a command. A value from a user can contain `[`, `$`, or `;`.
105
+
106
+ ## License
107
+
108
+ BSD-2-Clause. `ztcl.wasm` contains the Zig standard library, with ports of code from musl, Go, and ARM optimized-routines. See `NOTICE` and the `licenses` folder.
@@ -0,0 +1,249 @@
1
+ MIT OR Apache-2.0 WITH LLVM-exception
2
+ =====================================
3
+
4
+
5
+ MIT License
6
+ -----------
7
+
8
+ Copyright (c) 1999-2022, Arm Limited.
9
+
10
+ Permission is hereby granted, free of charge, to any person obtaining a copy
11
+ of this software and associated documentation files (the "Software"), to deal
12
+ in the Software without restriction, including without limitation the rights
13
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
14
+ copies of the Software, and to permit persons to whom the Software is
15
+ furnished to do so, subject to the following conditions:
16
+
17
+ The above copyright notice and this permission notice shall be included in all
18
+ copies or substantial portions of the Software.
19
+
20
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
21
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
22
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
23
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
24
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
25
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
26
+ SOFTWARE.
27
+
28
+
29
+ Apache-2.0 WITH LLVM-exception
30
+ ------------------------------
31
+
32
+ Apache License
33
+ Version 2.0, January 2004
34
+ http://www.apache.org/licenses/
35
+
36
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
37
+
38
+ 1. Definitions.
39
+
40
+ "License" shall mean the terms and conditions for use, reproduction,
41
+ and distribution as defined by Sections 1 through 9 of this document.
42
+
43
+ "Licensor" shall mean the copyright owner or entity authorized by
44
+ the copyright owner that is granting the License.
45
+
46
+ "Legal Entity" shall mean the union of the acting entity and all
47
+ other entities that control, are controlled by, or are under common
48
+ control with that entity. For the purposes of this definition,
49
+ "control" means (i) the power, direct or indirect, to cause the
50
+ direction or management of such entity, whether by contract or
51
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
52
+ outstanding shares, or (iii) beneficial ownership of such entity.
53
+
54
+ "You" (or "Your") shall mean an individual or Legal Entity
55
+ exercising permissions granted by this License.
56
+
57
+ "Source" form shall mean the preferred form for making modifications,
58
+ including but not limited to software source code, documentation
59
+ source, and configuration files.
60
+
61
+ "Object" form shall mean any form resulting from mechanical
62
+ transformation or translation of a Source form, including but
63
+ not limited to compiled object code, generated documentation,
64
+ and conversions to other media types.
65
+
66
+ "Work" shall mean the work of authorship, whether in Source or
67
+ Object form, made available under the License, as indicated by a
68
+ copyright notice that is included in or attached to the work
69
+ (an example is provided in the Appendix below).
70
+
71
+ "Derivative Works" shall mean any work, whether in Source or Object
72
+ form, that is based on (or derived from) the Work and for which the
73
+ editorial revisions, annotations, elaborations, or other modifications
74
+ represent, as a whole, an original work of authorship. For the purposes
75
+ of this License, Derivative Works shall not include works that remain
76
+ separable from, or merely link (or bind by name) to the interfaces of,
77
+ the Work and Derivative Works thereof.
78
+
79
+ "Contribution" shall mean any work of authorship, including
80
+ the original version of the Work and any modifications or additions
81
+ to that Work or Derivative Works thereof, that is intentionally
82
+ submitted to Licensor for inclusion in the Work by the copyright owner
83
+ or by an individual or Legal Entity authorized to submit on behalf of
84
+ the copyright owner. For the purposes of this definition, "submitted"
85
+ means any form of electronic, verbal, or written communication sent
86
+ to the Licensor or its representatives, including but not limited to
87
+ communication on electronic mailing lists, source code control systems,
88
+ and issue tracking systems that are managed by, or on behalf of, the
89
+ Licensor for the purpose of discussing and improving the Work, but
90
+ excluding communication that is conspicuously marked or otherwise
91
+ designated in writing by the copyright owner as "Not a Contribution."
92
+
93
+ "Contributor" shall mean Licensor and any individual or Legal Entity
94
+ on behalf of whom a Contribution has been received by Licensor and
95
+ subsequently incorporated within the Work.
96
+
97
+ 2. Grant of Copyright License. Subject to the terms and conditions of
98
+ this License, each Contributor hereby grants to You a perpetual,
99
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
100
+ copyright license to reproduce, prepare Derivative Works of,
101
+ publicly display, publicly perform, sublicense, and distribute the
102
+ Work and such Derivative Works in Source or Object form.
103
+
104
+ 3. Grant of Patent License. Subject to the terms and conditions of
105
+ this License, each Contributor hereby grants to You a perpetual,
106
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
107
+ (except as stated in this section) patent license to make, have made,
108
+ use, offer to sell, sell, import, and otherwise transfer the Work,
109
+ where such license applies only to those patent claims licensable
110
+ by such Contributor that are necessarily infringed by their
111
+ Contribution(s) alone or by combination of their Contribution(s)
112
+ with the Work to which such Contribution(s) was submitted. If You
113
+ institute patent litigation against any entity (including a
114
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
115
+ or a Contribution incorporated within the Work constitutes direct
116
+ or contributory patent infringement, then any patent licenses
117
+ granted to You under this License for that Work shall terminate
118
+ as of the date such litigation is filed.
119
+
120
+ 4. Redistribution. You may reproduce and distribute copies of the
121
+ Work or Derivative Works thereof in any medium, with or without
122
+ modifications, and in Source or Object form, provided that You
123
+ meet the following conditions:
124
+
125
+ (a) You must give any other recipients of the Work or
126
+ Derivative Works a copy of this License; and
127
+
128
+ (b) You must cause any modified files to carry prominent notices
129
+ stating that You changed the files; and
130
+
131
+ (c) You must retain, in the Source form of any Derivative Works
132
+ that You distribute, all copyright, patent, trademark, and
133
+ attribution notices from the Source form of the Work,
134
+ excluding those notices that do not pertain to any part of
135
+ the Derivative Works; and
136
+
137
+ (d) If the Work includes a "NOTICE" text file as part of its
138
+ distribution, then any Derivative Works that You distribute must
139
+ include a readable copy of the attribution notices contained
140
+ within such NOTICE file, excluding those notices that do not
141
+ pertain to any part of the Derivative Works, in at least one
142
+ of the following places: within a NOTICE text file distributed
143
+ as part of the Derivative Works; within the Source form or
144
+ documentation, if provided along with the Derivative Works; or,
145
+ within a display generated by the Derivative Works, if and
146
+ wherever such third-party notices normally appear. The contents
147
+ of the NOTICE file are for informational purposes only and
148
+ do not modify the License. You may add Your own attribution
149
+ notices within Derivative Works that You distribute, alongside
150
+ or as an addendum to the NOTICE text from the Work, provided
151
+ that such additional attribution notices cannot be construed
152
+ as modifying the License.
153
+
154
+ You may add Your own copyright statement to Your modifications and
155
+ may provide additional or different license terms and conditions
156
+ for use, reproduction, or distribution of Your modifications, or
157
+ for any such Derivative Works as a whole, provided Your use,
158
+ reproduction, and distribution of the Work otherwise complies with
159
+ the conditions stated in this License.
160
+
161
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
162
+ any Contribution intentionally submitted for inclusion in the Work
163
+ by You to the Licensor shall be under the terms and conditions of
164
+ this License, without any additional terms or conditions.
165
+ Notwithstanding the above, nothing herein shall supersede or modify
166
+ the terms of any separate license agreement you may have executed
167
+ with Licensor regarding such Contributions.
168
+
169
+ 6. Trademarks. This License does not grant permission to use the trade
170
+ names, trademarks, service marks, or product names of the Licensor,
171
+ except as required for reasonable and customary use in describing the
172
+ origin of the Work and reproducing the content of the NOTICE file.
173
+
174
+ 7. Disclaimer of Warranty. Unless required by applicable law or
175
+ agreed to in writing, Licensor provides the Work (and each
176
+ Contributor provides its Contributions) on an "AS IS" BASIS,
177
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
178
+ implied, including, without limitation, any warranties or conditions
179
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
180
+ PARTICULAR PURPOSE. You are solely responsible for determining the
181
+ appropriateness of using or redistributing the Work and assume any
182
+ risks associated with Your exercise of permissions under this License.
183
+
184
+ 8. Limitation of Liability. In no event and under no legal theory,
185
+ whether in tort (including negligence), contract, or otherwise,
186
+ unless required by applicable law (such as deliberate and grossly
187
+ negligent acts) or agreed to in writing, shall any Contributor be
188
+ liable to You for damages, including any direct, indirect, special,
189
+ incidental, or consequential damages of any character arising as a
190
+ result of this License or out of the use or inability to use the
191
+ Work (including but not limited to damages for loss of goodwill,
192
+ work stoppage, computer failure or malfunction, or any and all
193
+ other commercial damages or losses), even if such Contributor
194
+ has been advised of the possibility of such damages.
195
+
196
+ 9. Accepting Warranty or Additional Liability. While redistributing
197
+ the Work or Derivative Works thereof, You may choose to offer,
198
+ and charge a fee for, acceptance of support, warranty, indemnity,
199
+ or other liability obligations and/or rights consistent with this
200
+ License. However, in accepting such obligations, You may act only
201
+ on Your own behalf and on Your sole responsibility, not on behalf
202
+ of any other Contributor, and only if You agree to indemnify,
203
+ defend, and hold each Contributor harmless for any liability
204
+ incurred by, or claims asserted against, such Contributor by reason
205
+ of your accepting any such warranty or additional liability.
206
+
207
+ END OF TERMS AND CONDITIONS
208
+
209
+ APPENDIX: How to apply the Apache License to your work.
210
+
211
+ To apply the Apache License to your work, attach the following
212
+ boilerplate notice, with the fields enclosed by brackets "[]"
213
+ replaced with your own identifying information. (Don't include
214
+ the brackets!) The text should be enclosed in the appropriate
215
+ comment syntax for the file format. We also recommend that a
216
+ file or class name and description of purpose be included on the
217
+ same "printed page" as the copyright notice for easier
218
+ identification within third-party archives.
219
+
220
+ Copyright [yyyy] [name of copyright owner]
221
+
222
+ Licensed under the Apache License, Version 2.0 (the "License");
223
+ you may not use this file except in compliance with the License.
224
+ You may obtain a copy of the License at
225
+
226
+ http://www.apache.org/licenses/LICENSE-2.0
227
+
228
+ Unless required by applicable law or agreed to in writing, software
229
+ distributed under the License is distributed on an "AS IS" BASIS,
230
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
231
+ See the License for the specific language governing permissions and
232
+ limitations under the License.
233
+
234
+
235
+ --- LLVM Exceptions to the Apache 2.0 License ----
236
+
237
+ As an exception, if, as a result of your compiling your source code, portions
238
+ of this Software are embedded into an Object form of such source code, you
239
+ may redistribute such embedded portions in such Object form without complying
240
+ with the conditions of Sections 4(a), 4(b) and 4(d) of the License.
241
+
242
+ In addition, if you combine or link compiled forms of this Software with
243
+ software that is licensed under the GPLv2 ("Combined Software") and if a
244
+ court of competent jurisdiction determines that the patent provision (Section
245
+ 3), the indemnity provision (Section 9) or other Section of the License
246
+ conflicts with the conditions of the GPLv2, you may retroactively and
247
+ prospectively choose to deem waived or otherwise exclude such Section(s) of
248
+ the License, but only in their entirety and only with respect to the Combined
249
+ Software.
@@ -0,0 +1,27 @@
1
+ Copyright 2009 The Go Authors.
2
+
3
+ Redistribution and use in source and binary forms, with or without
4
+ modification, are permitted provided that the following conditions are
5
+ met:
6
+
7
+ * Redistributions of source code must retain the above copyright
8
+ notice, this list of conditions and the following disclaimer.
9
+ * Redistributions in binary form must reproduce the above
10
+ copyright notice, this list of conditions and the following disclaimer
11
+ in the documentation and/or other materials provided with the
12
+ distribution.
13
+ * Neither the name of Google LLC nor the names of its
14
+ contributors may be used to endorse or promote products derived from
15
+ this software without specific prior written permission.
16
+
17
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
18
+ "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
19
+ LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
20
+ A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
21
+ OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
22
+ SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
23
+ LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
24
+ DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
25
+ THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
26
+ (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
27
+ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
@@ -0,0 +1,193 @@
1
+ musl as a whole is licensed under the following standard MIT license:
2
+
3
+ ----------------------------------------------------------------------
4
+ Copyright © 2005-2020 Rich Felker, et al.
5
+
6
+ Permission is hereby granted, free of charge, to any person obtaining
7
+ a copy of this software and associated documentation files (the
8
+ "Software"), to deal in the Software without restriction, including
9
+ without limitation the rights to use, copy, modify, merge, publish,
10
+ distribute, sublicense, and/or sell copies of the Software, and to
11
+ permit persons to whom the Software is furnished to do so, subject to
12
+ the following conditions:
13
+
14
+ The above copyright notice and this permission notice shall be
15
+ included in all copies or substantial portions of the Software.
16
+
17
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
18
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
19
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
20
+ IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
21
+ CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
22
+ TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
23
+ SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
24
+ ----------------------------------------------------------------------
25
+
26
+ Authors/contributors include:
27
+
28
+ A. Wilcox
29
+ Ada Worcester
30
+ Alex Dowad
31
+ Alex Suykov
32
+ Alexander Monakov
33
+ Andre McCurdy
34
+ Andrew Kelley
35
+ Anthony G. Basile
36
+ Aric Belsito
37
+ Arvid Picciani
38
+ Bartosz Brachaczek
39
+ Benjamin Peterson
40
+ Bobby Bingham
41
+ Boris Brezillon
42
+ Brent Cook
43
+ Chris Spiegel
44
+ Clément Vasseur
45
+ Daniel Micay
46
+ Daniel Sabogal
47
+ Daurnimator
48
+ David Carlier
49
+ David Edelsohn
50
+ Denys Vlasenko
51
+ Dmitry Ivanov
52
+ Dmitry V. Levin
53
+ Drew DeVault
54
+ Emil Renner Berthing
55
+ Fangrui Song
56
+ Felix Fietkau
57
+ Felix Janda
58
+ Gianluca Anzolin
59
+ Hauke Mehrtens
60
+ He X
61
+ Hiltjo Posthuma
62
+ Isaac Dunham
63
+ Jaydeep Patil
64
+ Jens Gustedt
65
+ Jeremy Huntwork
66
+ Jo-Philipp Wich
67
+ Joakim Sindholt
68
+ John Spencer
69
+ Julien Ramseier
70
+ Justin Cormack
71
+ Kaarle Ritvanen
72
+ Khem Raj
73
+ Kylie McClain
74
+ Leah Neukirchen
75
+ Luca Barbato
76
+ Luka Perkov
77
+ M Farkas-Dyck (Strake)
78
+ Mahesh Bodapati
79
+ Markus Wichmann
80
+ Masanori Ogino
81
+ Michael Clark
82
+ Michael Forney
83
+ Mikhail Kremnyov
84
+ Natanael Copa
85
+ Nicholas J. Kain
86
+ orc
87
+ Pascal Cuoq
88
+ Patrick Oppenlander
89
+ Petr Hosek
90
+ Petr Skocik
91
+ Pierre Carrier
92
+ Reini Urban
93
+ Rich Felker
94
+ Richard Pennington
95
+ Ryan Fairfax
96
+ Samuel Holland
97
+ Segev Finer
98
+ Shiz
99
+ sin
100
+ Solar Designer
101
+ Stefan Kristiansson
102
+ Stefan O'Rear
103
+ Szabolcs Nagy
104
+ Timo Teräs
105
+ Trutz Behn
106
+ Valentin Ochs
107
+ Will Dietz
108
+ William Haddon
109
+ William Pitcock
110
+
111
+ Portions of this software are derived from third-party works licensed
112
+ under terms compatible with the above MIT license:
113
+
114
+ The TRE regular expression implementation (src/regex/reg* and
115
+ src/regex/tre*) is Copyright © 2001-2008 Ville Laurikari and licensed
116
+ under a 2-clause BSD license (license text in the source files). The
117
+ included version has been heavily modified by Rich Felker in 2012, in
118
+ the interests of size, simplicity, and namespace cleanliness.
119
+
120
+ Much of the math library code (src/math/* and src/complex/*) is
121
+ Copyright © 1993,2004 Sun Microsystems or
122
+ Copyright © 2003-2011 David Schultz or
123
+ Copyright © 2003-2009 Steven G. Kargl or
124
+ Copyright © 2003-2009 Bruce D. Evans or
125
+ Copyright © 2008 Stephen L. Moshier or
126
+ Copyright © 2017-2018 Arm Limited
127
+ and labelled as such in comments in the individual source files. All
128
+ have been licensed under extremely permissive terms.
129
+
130
+ The ARM memcpy code (src/string/arm/memcpy.S) is Copyright © 2008
131
+ The Android Open Source Project and is licensed under a two-clause BSD
132
+ license. It was taken from Bionic libc, used on Android.
133
+
134
+ The AArch64 memcpy and memset code (src/string/aarch64/*) are
135
+ Copyright © 1999-2019, Arm Limited.
136
+
137
+ The implementation of DES for crypt (src/crypt/crypt_des.c) is
138
+ Copyright © 1994 David Burren. It is licensed under a BSD license.
139
+
140
+ The implementation of blowfish crypt (src/crypt/crypt_blowfish.c) was
141
+ originally written by Solar Designer and placed into the public
142
+ domain. The code also comes with a fallback permissive license for use
143
+ in jurisdictions that may not recognize the public domain.
144
+
145
+ The smoothsort implementation (src/stdlib/qsort.c) is Copyright © 2011
146
+ Valentin Ochs and is licensed under an MIT-style license.
147
+
148
+ The x86_64 port was written by Nicholas J. Kain and is licensed under
149
+ the standard MIT terms.
150
+
151
+ The mips and microblaze ports were originally written by Richard
152
+ Pennington for use in the ellcc project. The original code was adapted
153
+ by Rich Felker for build system and code conventions during upstream
154
+ integration. It is licensed under the standard MIT terms.
155
+
156
+ The mips64 port was contributed by Imagination Technologies and is
157
+ licensed under the standard MIT terms.
158
+
159
+ The powerpc port was also originally written by Richard Pennington,
160
+ and later supplemented and integrated by John Spencer. It is licensed
161
+ under the standard MIT terms.
162
+
163
+ All other files which have no copyright comments are original works
164
+ produced specifically for use as part of this library, written either
165
+ by Rich Felker, the main author of the library, or by one or more
166
+ contibutors listed above. Details on authorship of individual files
167
+ can be found in the git version control history of the project. The
168
+ omission of copyright and license comments in each file is in the
169
+ interest of source tree size.
170
+
171
+ In addition, permission is hereby granted for all public header files
172
+ (include/* and arch/*/bits/*) and crt files intended to be linked into
173
+ applications (crt/*, ldso/dlstart.c, and arch/*/crt_arch.h) to omit
174
+ the copyright notice and permission notice otherwise required by the
175
+ license, and to use these files without any requirement of
176
+ attribution. These files include substantial contributions from:
177
+
178
+ Bobby Bingham
179
+ John Spencer
180
+ Nicholas J. Kain
181
+ Rich Felker
182
+ Richard Pennington
183
+ Stefan Kristiansson
184
+ Szabolcs Nagy
185
+
186
+ all of whom have explicitly granted such permission.
187
+
188
+ This file previously contained text expressing a belief that most of
189
+ the files covered by the above exception were sufficiently trivial not
190
+ to be subject to copyright, resulting in confusion over whether it
191
+ negated the permissions granted in the license. In the spirit of
192
+ permissive licensing, and of not having licensing issues being an
193
+ obstacle to adoption, that text has been removed.
@@ -0,0 +1,40 @@
1
+ This software is copyrighted by the Regents of the University of
2
+ California, Sun Microsystems, Inc., Scriptics Corporation, ActiveState
3
+ Corporation and other parties. The following terms apply to all files
4
+ associated with the software unless explicitly disclaimed in
5
+ individual files.
6
+
7
+ The authors hereby grant permission to use, copy, modify, distribute,
8
+ and license this software and its documentation for any purpose, provided
9
+ that existing copyright notices are retained in all copies and that this
10
+ notice is included verbatim in any distributions. No written agreement,
11
+ license, or royalty fee is required for any of the authorized uses.
12
+ Modifications to this software may be copyrighted by their authors
13
+ and need not follow the licensing terms described here, provided that
14
+ the new terms are clearly indicated on the first page of each file where
15
+ they apply.
16
+
17
+ IN NO EVENT SHALL THE AUTHORS OR DISTRIBUTORS BE LIABLE TO ANY PARTY
18
+ FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES
19
+ ARISING OUT OF THE USE OF THIS SOFTWARE, ITS DOCUMENTATION, OR ANY
20
+ DERIVATIVES THEREOF, EVEN IF THE AUTHORS HAVE BEEN ADVISED OF THE
21
+ POSSIBILITY OF SUCH DAMAGE.
22
+
23
+ THE AUTHORS AND DISTRIBUTORS SPECIFICALLY DISCLAIM ANY WARRANTIES,
24
+ INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY,
25
+ FITNESS FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT. THIS SOFTWARE
26
+ IS PROVIDED ON AN "AS IS" BASIS, AND THE AUTHORS AND DISTRIBUTORS HAVE
27
+ NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR
28
+ MODIFICATIONS.
29
+
30
+ GOVERNMENT USE: If you are acquiring this software on behalf of the
31
+ U.S. government, the Government shall have only "Restricted Rights"
32
+ in the software and related documentation as defined in the Federal
33
+ Acquisition Regulations (FARs) in Clause 52.227.19 (c) (2). If you
34
+ are acquiring the software on behalf of the Department of Defense, the
35
+ software shall be classified as "Commercial Computer Software" and the
36
+ Government shall have only "Restricted Rights" as defined in Clause
37
+ 252.227-7014 (b) (3) of DFARs. Notwithstanding the foregoing, the
38
+ authors grant the U.S. Government and others acting in its behalf
39
+ permission to use and distribute the software in accordance with the
40
+ terms specified in this license.
@@ -0,0 +1,21 @@
1
+ The MIT License (Expat)
2
+
3
+ Copyright (c) Zig 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
13
+ all 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
21
+ THE SOFTWARE.
package/package.json CHANGED
@@ -1,6 +1,51 @@
1
1
  {
2
2
  "name": "@beetlebug/ztcl",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.2.0-beta",
4
+ "description": "A Tcl interpreter in WebAssembly, with a step limit and a memory limit for untrusted scripts",
5
+ "license": "BSD-2-Clause",
6
+ "author": "The ztcl authors",
7
+ "homepage": "https://beetlebug.org/ztcl/",
8
+ "repository": {
9
+ "type": "git",
10
+ "url": "git+https://github.com/beetlebugorg/ztcl.git"
11
+ },
12
+ "bugs": "https://github.com/beetlebugorg/ztcl/issues",
13
+ "keywords": [
14
+ "tcl",
15
+ "interpreter",
16
+ "webassembly",
17
+ "wasm",
18
+ "sandbox",
19
+ "scripting"
20
+ ],
21
+ "type": "module",
22
+ "main": "./ztcl.mjs",
23
+ "types": "./ztcl.d.ts",
24
+ "exports": {
25
+ ".": {
26
+ "types": "./ztcl.d.ts",
27
+ "default": "./ztcl.mjs"
28
+ },
29
+ "./worker": {
30
+ "types": "./ztcl-worker.d.ts",
31
+ "default": "./ztcl-worker.mjs"
32
+ },
33
+ "./ztcl.wasm": "./ztcl.wasm",
34
+ "./package.json": "./package.json"
35
+ },
36
+ "files": [
37
+ "ztcl.mjs",
38
+ "ztcl-worker.mjs",
39
+ "ztcl.wasm",
40
+ "ztcl.d.ts",
41
+ "ztcl-worker.d.ts",
42
+ "NOTICE",
43
+ "licenses/"
44
+ ],
45
+ "sideEffects": [
46
+ "./ztcl-worker.mjs"
47
+ ],
48
+ "engines": {
49
+ "node": ">=22.3"
50
+ }
51
+ }
@@ -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
+ stepLimit?: 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 };
@@ -0,0 +1,39 @@
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
+ let interp = null;
8
+
9
+ async function current() {
10
+ if (!interp) interp = await Interp.create(await module);
11
+ return interp;
12
+ }
13
+
14
+ // The messages run in order, because each one waits for the one before.
15
+ let queue = Promise.resolve();
16
+ self.onmessage = ({ data }) => {
17
+ queue = queue.then(() => handle(data));
18
+ };
19
+
20
+ async function handle(data) {
21
+ if (data.init) {
22
+ module = compile(data.init);
23
+ return;
24
+ }
25
+ if (data.reset) {
26
+ interp?.close();
27
+ interp = null;
28
+ return;
29
+ }
30
+ try {
31
+ const it = await current();
32
+ it.stepLimit = data.stepLimit;
33
+ if (data.memLimit != null) it.memLimit = data.memLimit;
34
+ const r = it.eval(data.script);
35
+ self.postMessage({ id: data.id, ...r, memorySize: it.memorySize });
36
+ } catch (e) {
37
+ self.postMessage({ id: data.id, error: String(e && e.message ? e.message : e) });
38
+ }
39
+ }
package/ztcl.d.ts ADDED
@@ -0,0 +1,136 @@
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 steps of each `eval`. Each command and each loop pass uses one
18
+ * step. At the limit, the script stops with the error
19
+ * `step limit reached`. `null` is no limit, and it is the default.
20
+ */
21
+ stepLimit?: 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
+
31
+ /** The result of one `eval`. */
32
+ export interface EvalResult {
33
+ /** True when the script ended with no error. */
34
+ ok: boolean;
35
+ /** The value of the script, or the error message when `ok` is false. */
36
+ result: string;
37
+ /** The text of `puts` from this script. */
38
+ output: string;
39
+ }
40
+
41
+ /** The result of one `eval` in a worker. */
42
+ export interface WorkerEvalResult extends EvalResult {
43
+ /** The size of the linear memory of the worker interpreter in bytes. */
44
+ memorySize?: number;
45
+ }
46
+
47
+ /** The URL of the `ztcl.wasm` file next to `ztcl.mjs`. It is the default source. */
48
+ export function wasmURL(): URL;
49
+
50
+ /**
51
+ * Compiles `ztcl.wasm`. Compile one time and give the module to
52
+ * {@link Interp.create} to make many interpreters.
53
+ * @param source The module. The default is {@link wasmURL}.
54
+ */
55
+ export function compile(source?: WasmSource): Promise<WebAssembly.Module>;
56
+
57
+ /**
58
+ * A Tcl interpreter in its own WebAssembly instance. The interpreter
59
+ * keeps its procs and variables from one `eval` to the next. It has no
60
+ * files, sockets, `exec`, `clock`, or event loop.
61
+ *
62
+ * @example
63
+ * const tcl = await Interp.create({ stepLimit: 1_000_000, memLimit: 64 << 20 });
64
+ * tcl.eval("expr {6 * 7}"); // { ok: true, result: "42", output: "" }
65
+ */
66
+ export class Interp {
67
+ /**
68
+ * Makes an interpreter in a new WebAssembly instance.
69
+ * @param source The module, as for {@link compile}. Leave it out for the default.
70
+ * @param options The limits and the output function.
71
+ */
72
+ static create(source?: WasmSource, options?: InterpOptions): Promise<Interp>;
73
+ /** Makes an interpreter with the default module. */
74
+ static create(options: InterpOptions): Promise<Interp>;
75
+
76
+ /** Makes an interpreter in an instance of `ztcl.wasm`. Use {@link Interp.create}. */
77
+ constructor(instance: WebAssembly.Instance, options?: InterpOptions);
78
+
79
+ /** The steps of each `eval`. `null` is no limit. A change applies to the next `eval`. */
80
+ stepLimit: number | bigint | null;
81
+ /** The memory limit in bytes. A change applies to the next `eval`. */
82
+ memLimit: number;
83
+ /** Gets the text of `puts` when each `eval` ends. */
84
+ onOutput: ((text: string) => void) | null;
85
+ /**
86
+ * The size of the linear memory in bytes. The memory never shrinks,
87
+ * so this is the peak of the instance.
88
+ */
89
+ readonly memorySize: number;
90
+
91
+ /**
92
+ * Runs a script on the calling thread. The step limit applies to
93
+ * this call. A script blocks the page until it ends or hits a limit.
94
+ */
95
+ eval(script: string): EvalResult;
96
+
97
+ /** Frees the interpreter. Drop the object after this call. */
98
+ close(): void;
99
+ }
100
+
101
+ /**
102
+ * Runs scripts in a Web Worker, so a long script does not block the
103
+ * page. `stop()` ends the worker and the script in it. The next `eval()`
104
+ * starts a new worker with a new interpreter. It works in a browser.
105
+ *
106
+ * @example
107
+ * const tcl = new WorkerInterp({ memLimit: 64 << 20 });
108
+ * const r = await tcl.eval("set n 0; while 1 {incr n}");
109
+ * // Another handler calls tcl.stop(), and r is { ok: false, result: "stopped" }.
110
+ */
111
+ export class WorkerInterp {
112
+ /**
113
+ * @param wasm The URL of `ztcl.wasm`. Leave it out for the default.
114
+ * @param options The limits and the output function.
115
+ */
116
+ constructor(wasm?: string | URL, options?: InterpOptions);
117
+ /** Uses the default module. */
118
+ constructor(options: InterpOptions);
119
+
120
+ /** The steps of each `eval`. `null` is no limit. */
121
+ stepLimit: number | bigint | null;
122
+ /** The memory limit in bytes. `null` keeps the default. */
123
+ memLimit: number | null;
124
+ /** Gets the text of `puts` when each `eval` ends. */
125
+ onOutput: ((text: string) => void) | null;
126
+
127
+ /** Runs a script in the worker. */
128
+ eval(script: string): Promise<WorkerEvalResult>;
129
+ /** Makes a new interpreter in the worker for the next `eval`. */
130
+ reset(): void;
131
+ /**
132
+ * Ends the worker. Each pending `eval` resolves with
133
+ * `{ ok: false, result: "stopped" }`. The procs and variables go away.
134
+ */
135
+ stop(): void;
136
+ }
package/ztcl.mjs ADDED
@@ -0,0 +1,209 @@
1
+ // A small ES module over the C ABI of ztcl.wasm. It runs in a browser,
2
+ // in a Web Worker, and in Node.js.
3
+ //
4
+ // Each Interp has its own WebAssembly instance. The linear memory of an
5
+ // instance never shrinks, so close() and a new Interp give the memory
6
+ // back to the host. ztcl.wasm has no imports. The text of `puts` goes
7
+ // into a buffer, and eval() passes it to `onOutput` when the script ends.
8
+ //
9
+ // The default module is the ztcl.wasm file next to this file. Bundlers
10
+ // (Vite, webpack 5, esbuild, Rollup) find it through the
11
+ // `new URL("./ztcl.wasm", import.meta.url)` form, and a CDN serves it
12
+ // from the folder of this file.
13
+ //
14
+ // SPDX-License-Identifier: BSD-2-Clause
15
+
16
+ const encoder = new TextEncoder();
17
+ const decoder = new TextDecoder();
18
+
19
+ // The step limit of the C ABI is a u64. This value is "no limit".
20
+ const NO_LIMIT = 0xffffffffffffffffn;
21
+
22
+ /// The URL of the ztcl.wasm file next to this file.
23
+ export function wasmURL() {
24
+ return new URL("./ztcl.wasm", import.meta.url);
25
+ }
26
+
27
+ // The built-in modules of Node.js, through process.getBuiltinModule
28
+ // (Node.js 22.3 and later). The file has no `node:` import, so a
29
+ // bundler for the browser needs no shim.
30
+ function nodeModule(name) {
31
+ return globalThis.process?.getBuiltinModule?.(name);
32
+ }
33
+
34
+ // True when `x` is an options object and not a source.
35
+ function isOptions(x) {
36
+ return x != null && Object.getPrototypeOf(x) === Object.prototype;
37
+ }
38
+
39
+ /// Compiles ztcl.wasm. `source` is a URL, a Response, bytes, or a
40
+ /// WebAssembly.Module. With no source, it is the ztcl.wasm file next
41
+ /// to this file.
42
+ export async function compile(source = wasmURL()) {
43
+ if (source instanceof WebAssembly.Module) return source;
44
+ if (typeof source === "string" || source instanceof URL) {
45
+ // In Node.js, a string with no scheme is a file path.
46
+ const fs = nodeModule("node:fs/promises");
47
+ const path = typeof source === "string" && fs && !globalThis.location && !/^[a-z][a-z0-9+.-]*:/i.test(source);
48
+ const url = path ? nodeModule("node:url").pathToFileURL(source) : new URL(source, globalThis.location?.href);
49
+ if (url.protocol === "file:" && fs) {
50
+ return WebAssembly.compile(await fs.readFile(url));
51
+ }
52
+ source = await fetch(url);
53
+ }
54
+ if (typeof Response !== "undefined" && source instanceof Response) {
55
+ if (!source.ok) throw new Error(`ztcl.wasm: HTTP ${source.status}`);
56
+ if (WebAssembly.compileStreaming && source.headers.get("content-type") === "application/wasm") {
57
+ return WebAssembly.compileStreaming(source);
58
+ }
59
+ source = await source.arrayBuffer();
60
+ }
61
+ return WebAssembly.compile(source);
62
+ }
63
+
64
+ export class Interp {
65
+ /// Makes an interpreter in a new instance of `module`. `module` is a
66
+ /// 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).
69
+ static async create(module, options = {}) {
70
+ if (isOptions(module)) [module, options] = [undefined, module];
71
+ const instance = await WebAssembly.instantiate(await compile(module), {});
72
+ return new Interp(instance, options);
73
+ }
74
+
75
+ constructor(instance, { stepLimit = null, memLimit = null, onOutput = null } = {}) {
76
+ this.x = instance.exports;
77
+ this.h = this.x.ztcl_new();
78
+ if (!this.h) throw new Error("ztcl_new: out of memory");
79
+ this.stepLimit = stepLimit;
80
+ this.onOutput = onOutput;
81
+ if (memLimit != null) this.memLimit = memLimit;
82
+ }
83
+
84
+ /// The memory limit in bytes. ztcl_new sets 2 GiB.
85
+ set memLimit(bytes) {
86
+ this.x.ztcl_set_mem_limit(this.h, bytes);
87
+ this._mem = bytes;
88
+ }
89
+
90
+ get memLimit() {
91
+ return this._mem ?? 2 ** 31;
92
+ }
93
+
94
+ /// The size of the linear memory in bytes. It is the peak of the
95
+ /// instance, because the memory never shrinks.
96
+ get memorySize() {
97
+ return this.x.memory.buffer.byteLength;
98
+ }
99
+
100
+ /// Runs a script. Returns { ok, result, output }. `result` is the
101
+ /// value of the script or the error message. The step limit applies
102
+ /// to each call.
103
+ eval(script) {
104
+ 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);
109
+ const ptr = x.ztcl_alloc(bytes.length || 1);
110
+ if (!ptr) throw new Error("ztcl_alloc: out of memory");
111
+ new Uint8Array(x.memory.buffer, ptr, bytes.length).set(bytes);
112
+ const rc = x.ztcl_eval(this.h, ptr, bytes.length);
113
+ x.ztcl_free(ptr, bytes.length || 1);
114
+ 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));
116
+ x.ztcl_output_clear(this.h);
117
+ if (output && this.onOutput) this.onOutput(output);
118
+ return { ok: rc === 0, result, output };
119
+ }
120
+
121
+ /// Frees the interpreter. Drop the Interp after this call.
122
+ close() {
123
+ if (this.h) this.x.ztcl_delete(this.h);
124
+ this.h = 0;
125
+ }
126
+
127
+ _text(ptr, len) {
128
+ return decoder.decode(new Uint8Array(this.x.memory.buffer, ptr, len));
129
+ }
130
+ }
131
+
132
+ /// Runs scripts in a Web Worker, so a long script does not block the
133
+ /// page. stop() ends the worker and the script in it. The next eval()
134
+ /// starts a new worker with a new interpreter.
135
+ export class WorkerInterp {
136
+ /// `wasm` is the URL of ztcl.wasm, and it can be left out. Options
137
+ /// are as for Interp.create.
138
+ constructor(wasm, options = {}) {
139
+ if (isOptions(wasm)) [wasm, options] = [undefined, wasm];
140
+ const { stepLimit = null, memLimit = null, onOutput = null } = options;
141
+ this.wasm = new URL(wasm ?? wasmURL(), globalThis.location?.href).href;
142
+ this.stepLimit = stepLimit;
143
+ this.memLimit = memLimit;
144
+ this.onOutput = onOutput;
145
+ this.worker = null;
146
+ this.pending = new Map();
147
+ this.next = 1;
148
+ }
149
+
150
+ _start() {
151
+ // A browser starts a worker only from a URL of the same origin as
152
+ // the page. When this file comes from a CDN, a small worker from a
153
+ // blob URL imports the worker file. Bundlers find the second form.
154
+ const here = new URL(import.meta.url);
155
+ if (globalThis.location && here.origin !== globalThis.location.origin) {
156
+ const url = new URL("ztcl-worker.mjs", here.href.replace(/[^/]*$/, ""));
157
+ const blob = new Blob([`import ${JSON.stringify(url.href)};`], { type: "text/javascript" });
158
+ this.worker = new Worker(URL.createObjectURL(blob), { type: "module" });
159
+ } else {
160
+ this.worker = new Worker(new URL("./ztcl-worker.mjs", import.meta.url), { type: "module" });
161
+ }
162
+ this.worker.onmessage = ({ data }) => {
163
+ const p = this.pending.get(data.id);
164
+ if (!p) return;
165
+ this.pending.delete(data.id);
166
+ if (data.error) p.reject(new Error(data.error));
167
+ else {
168
+ if (data.output && this.onOutput) this.onOutput(data.output);
169
+ p.resolve({ ok: data.ok, result: data.result, output: data.output, memorySize: data.memorySize });
170
+ }
171
+ };
172
+ this.worker.onerror = (e) => this._fail(e.message || "the worker failed");
173
+ this.worker.postMessage({ init: this.wasm });
174
+ }
175
+
176
+ /// Runs a script in the worker. Returns a promise of
177
+ /// { ok, result, output, memorySize }.
178
+ eval(script) {
179
+ if (!this.worker) this._start();
180
+ const id = this.next++;
181
+ return new Promise((resolve, reject) => {
182
+ this.pending.set(id, { resolve, reject });
183
+ this.worker.postMessage({ id, script, stepLimit: this.stepLimit, memLimit: this.memLimit });
184
+ });
185
+ }
186
+
187
+ /// Makes a new interpreter in the worker for the next eval(). The
188
+ /// old one and its memory go away.
189
+ reset() {
190
+ if (this.worker) this.worker.postMessage({ reset: true });
191
+ }
192
+
193
+ /// Ends the worker. Each pending eval() resolves with
194
+ /// { ok: false, result: "stopped" }. The variables and procs go away.
195
+ stop() {
196
+ if (!this.worker) return;
197
+ this.worker.terminate();
198
+ this.worker = null;
199
+ for (const p of this.pending.values()) p.resolve({ ok: false, result: "stopped", output: "" });
200
+ this.pending.clear();
201
+ }
202
+
203
+ _fail(message) {
204
+ this.worker?.terminate();
205
+ this.worker = null;
206
+ for (const p of this.pending.values()) p.reject(new Error(message));
207
+ this.pending.clear();
208
+ }
209
+ }
package/ztcl.wasm ADDED
Binary file