@tinysandbox/js-runtime 0.1.0
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-APACHE +202 -0
- package/LICENSE-MIT +21 -0
- package/README.md +98 -0
- package/dist/index.d.ts +80 -0
- package/dist/index.js +764 -0
- package/package.json +41 -0
- package/quickjs.wasm +0 -0
package/LICENSE-APACHE
ADDED
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
|
|
2
|
+
Apache License
|
|
3
|
+
Version 2.0, January 2004
|
|
4
|
+
http://www.apache.org/licenses/
|
|
5
|
+
|
|
6
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
7
|
+
|
|
8
|
+
1. Definitions.
|
|
9
|
+
|
|
10
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
11
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
12
|
+
|
|
13
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
14
|
+
the copyright owner that is granting the License.
|
|
15
|
+
|
|
16
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
17
|
+
other entities that control, are controlled by, or are under common
|
|
18
|
+
control with that entity. For the purposes of this definition,
|
|
19
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
20
|
+
direction or management of such entity, whether by contract or
|
|
21
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
22
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
23
|
+
|
|
24
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
25
|
+
exercising permissions granted by this License.
|
|
26
|
+
|
|
27
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
28
|
+
including but not limited to software source code, documentation
|
|
29
|
+
source, and configuration files.
|
|
30
|
+
|
|
31
|
+
"Object" form shall mean any form resulting from mechanical
|
|
32
|
+
transformation or translation of a Source form, including but
|
|
33
|
+
not limited to compiled object code, generated documentation,
|
|
34
|
+
and conversions to other media types.
|
|
35
|
+
|
|
36
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
37
|
+
Object form, made available under the License, as indicated by a
|
|
38
|
+
copyright notice that is included in or attached to the work
|
|
39
|
+
(an example is provided in the Appendix below).
|
|
40
|
+
|
|
41
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
42
|
+
form, that is based on (or derived from) the Work and for which the
|
|
43
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
44
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
45
|
+
of this License, Derivative Works shall not include works that remain
|
|
46
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
47
|
+
the Work and Derivative Works thereof.
|
|
48
|
+
|
|
49
|
+
"Contribution" shall mean any work of authorship, including
|
|
50
|
+
the original version of the Work and any modifications or additions
|
|
51
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
52
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
53
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
54
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
55
|
+
means any form of electronic, verbal, or written communication sent
|
|
56
|
+
to the Licensor or its representatives, including but not limited to
|
|
57
|
+
communication on electronic mailing lists, source code control systems,
|
|
58
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
59
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
60
|
+
excluding communication that is conspicuously marked or otherwise
|
|
61
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
62
|
+
|
|
63
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
64
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
65
|
+
subsequently incorporated within the Work.
|
|
66
|
+
|
|
67
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
68
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
69
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
70
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
71
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
72
|
+
Work and such Derivative Works in Source or Object form.
|
|
73
|
+
|
|
74
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
75
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
76
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
77
|
+
(except as stated in this section) patent license to make, have made,
|
|
78
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
79
|
+
where such license applies only to those patent claims licensable
|
|
80
|
+
by such Contributor that are necessarily infringed by their
|
|
81
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
82
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
83
|
+
institute patent litigation against any entity (including a
|
|
84
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
85
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
86
|
+
or contributory patent infringement, then any patent licenses
|
|
87
|
+
granted to You under this License for that Work shall terminate
|
|
88
|
+
as of the date such litigation is filed.
|
|
89
|
+
|
|
90
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
91
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
92
|
+
modifications, and in Source or Object form, provided that You
|
|
93
|
+
meet the following conditions:
|
|
94
|
+
|
|
95
|
+
(a) You must give any other recipients of the Work or
|
|
96
|
+
Derivative Works a copy of this License; and
|
|
97
|
+
|
|
98
|
+
(b) You must cause any modified files to carry prominent notices
|
|
99
|
+
stating that You changed the files; and
|
|
100
|
+
|
|
101
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
102
|
+
that You distribute, all copyright, patent, trademark, and
|
|
103
|
+
attribution notices from the Source form of the Work,
|
|
104
|
+
excluding those notices that do not pertain to any part of
|
|
105
|
+
the Derivative Works; and
|
|
106
|
+
|
|
107
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
108
|
+
distribution, then any Derivative Works that You distribute must
|
|
109
|
+
include a readable copy of the attribution notices contained
|
|
110
|
+
within such NOTICE file, excluding those notices that do not
|
|
111
|
+
pertain to any part of the Derivative Works, in at least one
|
|
112
|
+
of the following places: within a NOTICE text file distributed
|
|
113
|
+
as part of the Derivative Works; within the Source form or
|
|
114
|
+
documentation, if provided along with the Derivative Works; or,
|
|
115
|
+
within a display generated by the Derivative Works, if and
|
|
116
|
+
wherever such third-party notices normally appear. The contents
|
|
117
|
+
of the NOTICE file are for informational purposes only and
|
|
118
|
+
do not modify the License. You may add Your own attribution
|
|
119
|
+
notices within Derivative Works that You distribute, alongside
|
|
120
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
121
|
+
that such additional attribution notices cannot be construed
|
|
122
|
+
as modifying the License.
|
|
123
|
+
|
|
124
|
+
You may add Your own copyright statement to Your modifications and
|
|
125
|
+
may provide additional or different license terms and conditions
|
|
126
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
127
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
128
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
129
|
+
the conditions stated in this License.
|
|
130
|
+
|
|
131
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
132
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
133
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
134
|
+
this License, without any additional terms or conditions.
|
|
135
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
136
|
+
the terms of any separate license agreement you may have executed
|
|
137
|
+
with Licensor regarding such Contributions.
|
|
138
|
+
|
|
139
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
140
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
141
|
+
except as required for reasonable and customary use in describing the
|
|
142
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
143
|
+
|
|
144
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
145
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
146
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
147
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
148
|
+
implied, including, without limitation, any warranties or conditions
|
|
149
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
150
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
151
|
+
appropriateness of using or redistributing the Work and assume any
|
|
152
|
+
risks associated with Your exercise of permissions under this License.
|
|
153
|
+
|
|
154
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
155
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
156
|
+
unless required by applicable law (such as deliberate and grossly
|
|
157
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
158
|
+
liable to You for damages, including any direct, indirect, special,
|
|
159
|
+
incidental, or consequential damages of any character arising as a
|
|
160
|
+
result of this License or out of the use or inability to use the
|
|
161
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
162
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
163
|
+
other commercial damages or losses), even if such Contributor
|
|
164
|
+
has been advised of the possibility of such damages.
|
|
165
|
+
|
|
166
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
167
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
168
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
169
|
+
or other liability obligations and/or rights consistent with this
|
|
170
|
+
License. However, in accepting such obligations, You may act only
|
|
171
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
172
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
173
|
+
defend, and hold each Contributor harmless for any liability
|
|
174
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
175
|
+
of your accepting any such warranty or additional liability.
|
|
176
|
+
|
|
177
|
+
END OF TERMS AND CONDITIONS
|
|
178
|
+
|
|
179
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
180
|
+
|
|
181
|
+
To apply the Apache License to your work, attach the following
|
|
182
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
183
|
+
replaced with your own identifying information. (Don't include
|
|
184
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
185
|
+
comment syntax for the file format. We also recommend that a
|
|
186
|
+
file or class name and description of purpose be included on the
|
|
187
|
+
same "printed page" as the copyright notice for easier
|
|
188
|
+
identification within third-party archives.
|
|
189
|
+
|
|
190
|
+
Copyright [yyyy] [name of copyright owner]
|
|
191
|
+
|
|
192
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
193
|
+
you may not use this file except in compliance with the License.
|
|
194
|
+
You may obtain a copy of the License at
|
|
195
|
+
|
|
196
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
197
|
+
|
|
198
|
+
Unless required by applicable law or agreed to in writing, software
|
|
199
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
200
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
201
|
+
See the License for the specific language governing permissions and
|
|
202
|
+
limitations under the License.
|
package/LICENSE-MIT
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Dan Goodman
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
ADDED
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
# `@tinysandbox/js-runtime`
|
|
2
|
+
|
|
3
|
+
A small, stateless QuickJS runtime for standard WebAssembly hosts. It has no
|
|
4
|
+
runtime dependencies and uses the same checked-in QuickJS-ng artifact and guest
|
|
5
|
+
glue as tinysandbox's Rust/Wasmtime `js` command.
|
|
6
|
+
|
|
7
|
+
The package never reads a file or calls `fetch` itself. Supply the wasm bytes or
|
|
8
|
+
a compiled `WebAssembly.Module` explicitly, compile an engine once, and call
|
|
9
|
+
`runCode()` as needed. Every call creates a new bounded linear memory, wasm
|
|
10
|
+
instance, QuickJS runtime, and context; no guest state survives the call.
|
|
11
|
+
|
|
12
|
+
```js
|
|
13
|
+
import { readFile } from "node:fs/promises";
|
|
14
|
+
import { createEngine } from "@tinysandbox/js-runtime";
|
|
15
|
+
|
|
16
|
+
const bytes = await readFile(new URL(
|
|
17
|
+
"./node_modules/@tinysandbox/js-runtime/quickjs.wasm",
|
|
18
|
+
import.meta.url,
|
|
19
|
+
));
|
|
20
|
+
const engine = await createEngine(bytes);
|
|
21
|
+
|
|
22
|
+
const result = engine.runCode("console.log(tools.search({ query: 'hello' }))", {
|
|
23
|
+
globals: {
|
|
24
|
+
"tools.search": ({ query }) => ({ query, hits: 1 }),
|
|
25
|
+
},
|
|
26
|
+
timeoutMs: 1000,
|
|
27
|
+
wasmMemoryBytes: 16 * 1024 * 1024,
|
|
28
|
+
quickjsHeapBytes: 8 * 1024 * 1024,
|
|
29
|
+
});
|
|
30
|
+
```
|
|
31
|
+
|
|
32
|
+
Browser callers can fetch the exported `quickjs.wasm` asset themselves. Hosts
|
|
33
|
+
such as Convex that compile `.wasm` imports use the exported subpath directly:
|
|
34
|
+
|
|
35
|
+
```ts
|
|
36
|
+
import { createEngine } from "@tinysandbox/js-runtime";
|
|
37
|
+
import quickjsModule from "@tinysandbox/js-runtime/quickjs.wasm";
|
|
38
|
+
|
|
39
|
+
const value = await doConvexWork();
|
|
40
|
+
const engine = await createEngine(quickjsModule);
|
|
41
|
+
const result = engine.runCode("console.log(context.value(null))", {
|
|
42
|
+
globals: { "context.value": () => value },
|
|
43
|
+
});
|
|
44
|
+
```
|
|
45
|
+
|
|
46
|
+
`runCode(code, options)` returns `exitCode`, UTF-8 `stdout` and `stderr`, and
|
|
47
|
+
initial/peak wasm memory bytes. Its defaults are a 64 MiB wasm maximum, 32 MiB
|
|
48
|
+
QuickJS heap, 30 second monotonic deadline, and 1 MiB each for source, serialized
|
|
49
|
+
host responses, stdout, and stderr. A `wasmMemoryBytes` value below the artifact
|
|
50
|
+
minimum of 1,245,184 bytes is rejected before instantiation. Non-page-aligned
|
|
51
|
+
values are rounded down for the actual WebAssembly maximum.
|
|
52
|
+
|
|
53
|
+
Global names use dot-separated JavaScript identifier segments. Each value must
|
|
54
|
+
be a synchronous one-argument function. Guest arguments cross the boundary
|
|
55
|
+
with JavaScript's normal `JSON.stringify` semantics (including its omission and
|
|
56
|
+
coercion rules); host return values must already be strict JSON values and are
|
|
57
|
+
validated without coercion. Promises, invalid returns, invalid names, namespace
|
|
58
|
+
conflicts, and runtime-global shadowing fail deterministically. Complete awaited
|
|
59
|
+
host work before calling `runCode()`; wasm execution is synchronous and blocks
|
|
60
|
+
the V8 event loop until it finishes.
|
|
61
|
+
|
|
62
|
+
## Optional filesystem capability
|
|
63
|
+
|
|
64
|
+
Pass a synchronous `Vfs` implementation to enable the same `Buffer`, `fs`
|
|
65
|
+
subset, and relative/absolute CommonJS loader as tinysandbox's `/bin/js`:
|
|
66
|
+
|
|
67
|
+
```ts
|
|
68
|
+
const result = engine.runFile("main.js", {
|
|
69
|
+
vfs,
|
|
70
|
+
cwd: "/app",
|
|
71
|
+
argv: ["js", "main.js", "one"],
|
|
72
|
+
});
|
|
73
|
+
```
|
|
74
|
+
|
|
75
|
+
`runFile()` resolves the entry against `cwd`, reads it through
|
|
76
|
+
`open`/`readAt`/`close`, rejects invalid UTF-8, and evaluates it with the
|
|
77
|
+
resolved path as `__filename` and the stack filename. If `argv` is omitted, it
|
|
78
|
+
defaults to `["js", originalPath]`, preserving the path string passed by the
|
|
79
|
+
caller. Relative `require()` resolves from the requiring module; direct `fs`
|
|
80
|
+
paths resolve from `cwd`.
|
|
81
|
+
|
|
82
|
+
The exported `Vfs` interface is deliberately small and synchronous: `stat`,
|
|
83
|
+
`readdir`, `mkdir`, `rename`, `unlink`, `rmdir`, `open`, `readAt`, `writeAt`,
|
|
84
|
+
`truncate`, and `close`. Paths delivered to it are normalized absolute paths;
|
|
85
|
+
handles and offsets are non-negative safe integers, and positional operations
|
|
86
|
+
do not change the guest fd cursor. Implementations report one of the exported
|
|
87
|
+
`VfsErrno` strings by throwing `new VfsError(code)`. Quotas and storage
|
|
88
|
+
accounting belong to the supplied implementation. The package provides no
|
|
89
|
+
production filesystem or storage backend; the repository's `TestVfs` exists
|
|
90
|
+
only under `test/` for examples and conformance tests.
|
|
91
|
+
|
|
92
|
+
Omitting `vfs` leaves the run storage-independent: `Buffer` is absent and both
|
|
93
|
+
`require("fs")` and file-module requests throw
|
|
94
|
+
`ERR_CAPABILITY_UNAVAILABLE` before any filesystem host call. This stateless
|
|
95
|
+
package also does not provide network access, timers, guest ESM, TypeScript
|
|
96
|
+
transpilation, Asyncify/JSPI, or persistent isolates. The compatibility glue's
|
|
97
|
+
`fetch` never reaches ambient V8 networking and fails with unavailable-host
|
|
98
|
+
capability behavior.
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
export type JsonValue = null | boolean | number | string | JsonValue[] | { [key: string]: JsonValue };
|
|
2
|
+
|
|
3
|
+
export type HostGlobal = (argument: JsonValue) => JsonValue;
|
|
4
|
+
|
|
5
|
+
export type VfsErrno = "EBADF" | "EBUSY" | "EXDEV" | "EACCES" | "EEXIST" | "EFBIG" | "EIO" | "EINVAL" | "EISDIR" | "ENOENT" | "ENOSPC" | "ENOTDIR" | "ENOTEMPTY";
|
|
6
|
+
|
|
7
|
+
export declare class VfsError extends Error {
|
|
8
|
+
readonly code: VfsErrno;
|
|
9
|
+
constructor(code: VfsErrno, message?: string);
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
export interface VfsMetadata {
|
|
13
|
+
fileType: "file" | "directory";
|
|
14
|
+
len: number;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
export interface VfsDirEntry {
|
|
18
|
+
name: string;
|
|
19
|
+
metadata: VfsMetadata;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export interface VfsOpenMode {
|
|
23
|
+
read: boolean;
|
|
24
|
+
write: boolean;
|
|
25
|
+
create: boolean;
|
|
26
|
+
createNew: boolean;
|
|
27
|
+
truncate: boolean;
|
|
28
|
+
append: boolean;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/** Synchronous, absolute-path, handle-and-offset filesystem capability. */
|
|
32
|
+
export interface Vfs {
|
|
33
|
+
stat(path: string): VfsMetadata;
|
|
34
|
+
readdir(path: string): VfsDirEntry[];
|
|
35
|
+
mkdir(path: string): void;
|
|
36
|
+
rename(from: string, to: string): void;
|
|
37
|
+
unlink(path: string): void;
|
|
38
|
+
rmdir(path: string): void;
|
|
39
|
+
open(path: string, mode: VfsOpenMode): number;
|
|
40
|
+
readAt(handle: number, offset: number, buffer: Uint8Array): number;
|
|
41
|
+
writeAt(handle: number, offset: number, data: Uint8Array): number;
|
|
42
|
+
truncate(handle: number, len: number): void;
|
|
43
|
+
close(handle: number): void;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
export interface RunCodeOptions {
|
|
47
|
+
globals?: Record<string, HostGlobal>;
|
|
48
|
+
vfs?: Vfs;
|
|
49
|
+
wasmMemoryBytes?: number;
|
|
50
|
+
quickjsHeapBytes?: number;
|
|
51
|
+
timeoutMs?: number;
|
|
52
|
+
sourceBytes?: number;
|
|
53
|
+
hostResponseBytes?: number;
|
|
54
|
+
stdoutBytes?: number;
|
|
55
|
+
stderrBytes?: number;
|
|
56
|
+
scriptPath?: string;
|
|
57
|
+
argv?: string[];
|
|
58
|
+
env?: Record<string, string>;
|
|
59
|
+
cwd?: string;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
export interface RunFileOptions extends Omit<RunCodeOptions, "vfs" | "scriptPath"> {
|
|
63
|
+
vfs: Vfs;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
export interface RunResult {
|
|
67
|
+
exitCode: number;
|
|
68
|
+
stdout: string;
|
|
69
|
+
stderr: string;
|
|
70
|
+
initialWasmMemoryBytes: number;
|
|
71
|
+
peakWasmMemoryBytes: number;
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
export interface JsEngine {
|
|
75
|
+
runCode(code: string, options?: RunCodeOptions): RunResult;
|
|
76
|
+
runFile(path: string, options: RunFileOptions): RunResult;
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
export declare const QUICKJS_INITIAL_MEMORY_BYTES: number;
|
|
80
|
+
export declare function createEngine(wasm: BufferSource | WebAssembly.Module): Promise<JsEngine>;
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,764 @@
|
|
|
1
|
+
// @ts-nocheck -- this source intentionally uses only JavaScript syntax so the
|
|
2
|
+
// zero-dependency build can copy it verbatim to the ESM distribution.
|
|
3
|
+
const PAGE_BYTES = 64 * 1024;
|
|
4
|
+
const INITIAL_PAGES = 19;
|
|
5
|
+
const DEFAULT_WASM_MEMORY_BYTES = 64 * 1024 * 1024;
|
|
6
|
+
const DEFAULT_QUICKJS_HEAP_BYTES = 32 * 1024 * 1024;
|
|
7
|
+
const DEFAULT_TIMEOUT_MS = 30_000;
|
|
8
|
+
const DEFAULT_SOURCE_BYTES = 1024 * 1024;
|
|
9
|
+
const DEFAULT_HOST_RESPONSE_BYTES = 1024 * 1024;
|
|
10
|
+
const DEFAULT_OUTPUT_BYTES = 1024 * 1024;
|
|
11
|
+
const MAX_HOST_READ_BYTES = 16 * 1024 * 1024;
|
|
12
|
+
const VFS_OPERATIONS = new Set([
|
|
13
|
+
"readFile", "writeFile", "appendFile", "mkdir", "readdir", "stat", "rename",
|
|
14
|
+
"rm", "unlink", "rmdir", "exists", "open", "read", "write", "ftruncate",
|
|
15
|
+
"close", "copyFile",
|
|
16
|
+
]);
|
|
17
|
+
const RESERVED_GLOBALS = new Set([
|
|
18
|
+
"Buffer", "Headers", "Response", "__dirname", "__filename", "console",
|
|
19
|
+
"exports", "fetch", "globalThis", "module", "process", "require",
|
|
20
|
+
]);
|
|
21
|
+
const ABI_VERSION = 12;
|
|
22
|
+
const REQUIRED_IMPORTS = [
|
|
23
|
+
"env.memory:memory",
|
|
24
|
+
"tinysandbox.host_call:function",
|
|
25
|
+
"tinysandbox.host_response_len:function",
|
|
26
|
+
"tinysandbox.host_response_read:function",
|
|
27
|
+
"tinysandbox.should_interrupt:function",
|
|
28
|
+
"tinysandbox.write_stderr:function",
|
|
29
|
+
"tinysandbox.write_stdout:function",
|
|
30
|
+
"wasi_snapshot_preview1.clock_time_get:function",
|
|
31
|
+
"wasi_snapshot_preview1.fd_close:function",
|
|
32
|
+
"wasi_snapshot_preview1.fd_fdstat_get:function",
|
|
33
|
+
"wasi_snapshot_preview1.fd_seek:function",
|
|
34
|
+
"wasi_snapshot_preview1.fd_write:function",
|
|
35
|
+
].sort();
|
|
36
|
+
const REQUIRED_EXPORTS = [
|
|
37
|
+
"_initialize:function",
|
|
38
|
+
"memory:memory",
|
|
39
|
+
"tinysandbox_abi_version:function",
|
|
40
|
+
"tinysandbox_alloc:function",
|
|
41
|
+
"tinysandbox_free:function",
|
|
42
|
+
"tinysandbox_run:function",
|
|
43
|
+
].sort();
|
|
44
|
+
const encoder = new TextEncoder();
|
|
45
|
+
const decoder = new TextDecoder();
|
|
46
|
+
const fatalDecoder = new TextDecoder("utf-8", { fatal: true });
|
|
47
|
+
|
|
48
|
+
export const QUICKJS_INITIAL_MEMORY_BYTES = INITIAL_PAGES * PAGE_BYTES;
|
|
49
|
+
|
|
50
|
+
const VFS_ERRNOS = Object.freeze({
|
|
51
|
+
EBADF: [-9, "bad file descriptor"],
|
|
52
|
+
EBUSY: [-16, "resource busy or locked"],
|
|
53
|
+
EXDEV: [-18, "cross-device link not permitted"],
|
|
54
|
+
EACCES: [-13, "permission denied"],
|
|
55
|
+
EEXIST: [-17, "file already exists"],
|
|
56
|
+
EFBIG: [-27, "file too large"],
|
|
57
|
+
EIO: [-5, "i/o error"],
|
|
58
|
+
EINVAL: [-22, "invalid argument"],
|
|
59
|
+
EISDIR: [-21, "illegal operation on a directory"],
|
|
60
|
+
ENOENT: [-2, "no such file or directory"],
|
|
61
|
+
ENOSPC: [-28, "no space left on device"],
|
|
62
|
+
ENOTDIR: [-20, "not a directory"],
|
|
63
|
+
ENOTEMPTY: [-66, "directory not empty"],
|
|
64
|
+
});
|
|
65
|
+
|
|
66
|
+
export class VfsError extends Error {
|
|
67
|
+
constructor(code, message = code) {
|
|
68
|
+
if (!Object.hasOwn(VFS_ERRNOS, code)) throw new TypeError(`unsupported VFS errno '${String(code)}'`);
|
|
69
|
+
super(message);
|
|
70
|
+
this.name = "VfsError";
|
|
71
|
+
this.code = code;
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
class RunLimitError extends Error {
|
|
76
|
+
constructor(kind, message) {
|
|
77
|
+
super(message);
|
|
78
|
+
this.kind = kind;
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
function integerOption(name, value, fallback, minimum = 0) {
|
|
83
|
+
const result = value === undefined ? fallback : value;
|
|
84
|
+
if (!Number.isSafeInteger(result) || result < minimum) {
|
|
85
|
+
throw new TypeError(`${name} must be a safe integer of at least ${minimum}`);
|
|
86
|
+
}
|
|
87
|
+
return result;
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
function validateGlobals(globals) {
|
|
91
|
+
if (globals === undefined) return [];
|
|
92
|
+
if (globals === null || typeof globals !== "object" || Array.isArray(globals)) {
|
|
93
|
+
throw new TypeError("globals must be an object of synchronous functions");
|
|
94
|
+
}
|
|
95
|
+
const names = Object.keys(globals).sort();
|
|
96
|
+
for (const name of names) {
|
|
97
|
+
if (typeof globals[name] !== "function") {
|
|
98
|
+
throw new TypeError(`global '${name}' must be a function`);
|
|
99
|
+
}
|
|
100
|
+
const parts = name.split(".");
|
|
101
|
+
if (parts.some((part) => !/^[A-Za-z_][A-Za-z0-9_]*$/.test(part))) {
|
|
102
|
+
throw new TypeError(`cannot register invalid name '${name}'; names are dot-separated paths of [A-Za-z_][A-Za-z0-9_]* segments`);
|
|
103
|
+
}
|
|
104
|
+
if (RESERVED_GLOBALS.has(parts[0])) {
|
|
105
|
+
throw new TypeError(`cannot register reserved name '${name}'; '${parts[0]}' is provided by the JavaScript runtime`);
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
for (let index = 1; index < names.length; index++) {
|
|
109
|
+
const previous = names[index - 1];
|
|
110
|
+
const current = names[index];
|
|
111
|
+
if (current.startsWith(`${previous}.`)) {
|
|
112
|
+
throw new TypeError(`cannot register '${current}'; it conflicts with '${previous}'`);
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
return names;
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
function requireArtifactAbi(module) {
|
|
119
|
+
const imports = WebAssembly.Module.imports(module);
|
|
120
|
+
const actualImports = imports.map((entry) => `${entry.module}.${entry.name}:${entry.kind}`).sort();
|
|
121
|
+
const actualExports = WebAssembly.Module.exports(module).map((entry) => `${entry.name}:${entry.kind}`).sort();
|
|
122
|
+
if (JSON.stringify(actualImports) !== JSON.stringify(REQUIRED_IMPORTS)) throw new TypeError(`incompatible QuickJS wasm imports: ${actualImports.join(", ")}`);
|
|
123
|
+
if (JSON.stringify(actualExports) !== JSON.stringify(REQUIRED_EXPORTS)) throw new TypeError(`incompatible QuickJS wasm exports: ${actualExports.join(", ")}`);
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
function probeArtifactAbi(module) {
|
|
127
|
+
const memory = new WebAssembly.Memory({ initial: INITIAL_PAGES, maximum: 65_536 });
|
|
128
|
+
const zero = () => 0;
|
|
129
|
+
let instance;
|
|
130
|
+
try {
|
|
131
|
+
instance = new WebAssembly.Instance(module, {
|
|
132
|
+
env: { memory },
|
|
133
|
+
tinysandbox: { host_call: zero, host_response_len: zero, host_response_read: zero, should_interrupt: zero, write_stderr: zero, write_stdout: zero },
|
|
134
|
+
wasi_snapshot_preview1: { clock_time_get: zero, fd_close: zero, fd_fdstat_get: zero, fd_seek: zero, fd_write: zero },
|
|
135
|
+
});
|
|
136
|
+
} catch (error) {
|
|
137
|
+
throw new TypeError(`incompatible QuickJS wasm memory contract: ${error instanceof Error ? error.message : String(error)}`);
|
|
138
|
+
}
|
|
139
|
+
if (instance.exports.memory !== memory) throw new TypeError("incompatible QuickJS wasm: env.memory is not re-exported");
|
|
140
|
+
for (const [name, arity] of [["tinysandbox_abi_version", 0], ["tinysandbox_alloc", 1], ["tinysandbox_free", 1], ["tinysandbox_run", 3]]) {
|
|
141
|
+
if (instance.exports[name].length !== arity) throw new TypeError(`incompatible QuickJS wasm export signature '${name}'`);
|
|
142
|
+
}
|
|
143
|
+
if (instance.exports.tinysandbox_abi_version() !== ABI_VERSION) throw new TypeError(`incompatible QuickJS wasm ABI version; expected ${ABI_VERSION}`);
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
function writeU32(memory, pointer, value) {
|
|
147
|
+
new DataView(memory.buffer).setUint32(pointer, value >>> 0, true);
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
function monotonicNow() {
|
|
151
|
+
const now = globalThis.performance?.now;
|
|
152
|
+
if (typeof now !== "function") {
|
|
153
|
+
throw new Error("@tinysandbox/js-runtime requires performance.now() for monotonic deadlines");
|
|
154
|
+
}
|
|
155
|
+
return now.call(globalThis.performance);
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
function jsonError(error) {
|
|
159
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
160
|
+
const code = error && typeof error === "object" && typeof error.code === "string" ? error.code : undefined;
|
|
161
|
+
return code === undefined ? { message } : { message, code };
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
function assertJsonValue(value, path = "value", seen = new Set()) {
|
|
165
|
+
if (value === null || typeof value === "string" || typeof value === "boolean") return;
|
|
166
|
+
if (typeof value === "number") {
|
|
167
|
+
if (Number.isFinite(value)) return;
|
|
168
|
+
throw new TypeError(`${path} must contain only finite JSON numbers`);
|
|
169
|
+
}
|
|
170
|
+
if (typeof value !== "object") throw new TypeError(`${path} must contain only JSON-safe values`);
|
|
171
|
+
if (seen.has(value)) throw new TypeError(`${path} must not contain cycles`);
|
|
172
|
+
const prototype = Object.getPrototypeOf(value);
|
|
173
|
+
if (!Array.isArray(value) && prototype !== Object.prototype && prototype !== null) {
|
|
174
|
+
throw new TypeError(`${path} must contain only plain objects and arrays`);
|
|
175
|
+
}
|
|
176
|
+
if (Object.getOwnPropertySymbols(value).length !== 0) throw new TypeError(`${path} must not contain symbol keys`);
|
|
177
|
+
seen.add(value);
|
|
178
|
+
if (Array.isArray(value)) {
|
|
179
|
+
for (let index = 0; index < value.length; index++) {
|
|
180
|
+
if (!Object.hasOwn(value, index)) throw new TypeError(`${path} must not contain array holes`);
|
|
181
|
+
assertJsonValue(value[index], `${path}[${index}]`, seen);
|
|
182
|
+
}
|
|
183
|
+
} else {
|
|
184
|
+
for (const key of Object.keys(value)) assertJsonValue(value[key], `${path}.${key}`, seen);
|
|
185
|
+
}
|
|
186
|
+
seen.delete(value);
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
class HostCallFailure extends Error {
|
|
190
|
+
constructor(payload) {
|
|
191
|
+
super(payload.message);
|
|
192
|
+
this.payload = payload;
|
|
193
|
+
}
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
function vfsFailure(error, syscall, path) {
|
|
197
|
+
const code = error && typeof error === "object" && typeof error.code === "string" && Object.hasOwn(VFS_ERRNOS, error.code)
|
|
198
|
+
? error.code
|
|
199
|
+
: "EIO";
|
|
200
|
+
const [errno, message] = VFS_ERRNOS[code];
|
|
201
|
+
return new HostCallFailure({ code, errno, message, syscall, ...(path === undefined ? {} : { path }) });
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
function invalidVfsCall(syscall, path) {
|
|
205
|
+
return vfsFailure(new VfsError("EINVAL"), syscall, path);
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
function validateVfs(vfs) {
|
|
209
|
+
if (vfs === null || typeof vfs !== "object") throw new TypeError("vfs must be an object implementing the synchronous Vfs interface");
|
|
210
|
+
for (const method of ["stat", "readdir", "mkdir", "rename", "unlink", "rmdir", "open", "readAt", "writeAt", "truncate", "close"]) {
|
|
211
|
+
if (typeof vfs[method] !== "function") throw new TypeError(`vfs.${method} must be a function`);
|
|
212
|
+
}
|
|
213
|
+
return vfs;
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
function callVfs(vfs, method, args, syscall, path) {
|
|
217
|
+
try {
|
|
218
|
+
const value = vfs[method](...args);
|
|
219
|
+
if (value && typeof value === "object" && typeof value.then === "function") {
|
|
220
|
+
// Async VFS methods are unsupported, but attach a rejection handler so a
|
|
221
|
+
// mistaken async implementation cannot escape this deterministic error.
|
|
222
|
+
try { value.then(() => {}, () => {}); } catch {}
|
|
223
|
+
throw new TypeError(`vfs.${method} returned a Promise; Vfs methods must be synchronous`);
|
|
224
|
+
}
|
|
225
|
+
return value;
|
|
226
|
+
} catch (error) {
|
|
227
|
+
throw vfsFailure(error, syscall, path);
|
|
228
|
+
}
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
function normalizeAbsolute(path) {
|
|
232
|
+
const parts = [];
|
|
233
|
+
for (const part of String(path).split("/")) {
|
|
234
|
+
if (part === "" || part === ".") continue;
|
|
235
|
+
if (part === "..") parts.pop();
|
|
236
|
+
else parts.push(part);
|
|
237
|
+
}
|
|
238
|
+
return parts.length === 0 ? "/" : `/${parts.join("/")}`;
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
function resolvePath(cwd, path) {
|
|
242
|
+
return normalizeAbsolute(String(path).startsWith("/") ? path : cwd === "/" ? `/${path}` : `${cwd}/${path}`);
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
function checkedInteger(value, syscall, path, nullable = false) {
|
|
246
|
+
if (nullable && (value === null || value === undefined)) return null;
|
|
247
|
+
if (!Number.isSafeInteger(value) || value < 0) throw invalidVfsCall(syscall, path);
|
|
248
|
+
return value;
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
function checkedMetadata(value, syscall, path) {
|
|
252
|
+
if (!value || typeof value !== "object" || !["file", "directory"].includes(value.fileType) || !Number.isSafeInteger(value.len) || value.len < 0) {
|
|
253
|
+
throw vfsFailure(new Error("invalid VFS metadata"), syscall, path);
|
|
254
|
+
}
|
|
255
|
+
return value;
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
function encodeBase64(data) {
|
|
259
|
+
const chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
|
|
260
|
+
let output = "";
|
|
261
|
+
for (let index = 0; index < data.byteLength; index += 3) {
|
|
262
|
+
const first = data[index];
|
|
263
|
+
const second = index + 1 < data.byteLength ? data[index + 1] : 0;
|
|
264
|
+
const third = index + 2 < data.byteLength ? data[index + 2] : 0;
|
|
265
|
+
const bits = (first << 16) | (second << 8) | third;
|
|
266
|
+
output += chars[(bits >>> 18) & 63] + chars[(bits >>> 12) & 63]
|
|
267
|
+
+ (index + 1 < data.byteLength ? chars[(bits >>> 6) & 63] : "=")
|
|
268
|
+
+ (index + 2 < data.byteLength ? chars[bits & 63] : "=");
|
|
269
|
+
}
|
|
270
|
+
return output;
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
function decodeBase64(value) {
|
|
274
|
+
const input = String(value);
|
|
275
|
+
if (input.length === 0) return new Uint8Array();
|
|
276
|
+
if (input.length % 4 !== 0 || !/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(input)) {
|
|
277
|
+
throw invalidVfsCall("tinysandbox");
|
|
278
|
+
}
|
|
279
|
+
const chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
|
|
280
|
+
const padding = input.endsWith("==") ? 2 : input.endsWith("=") ? 1 : 0;
|
|
281
|
+
const output = new Uint8Array(input.length / 4 * 3 - padding);
|
|
282
|
+
let outputIndex = 0;
|
|
283
|
+
for (let index = 0; index < input.length; index += 4) {
|
|
284
|
+
const bits = (chars.indexOf(input[index]) << 18) | (chars.indexOf(input[index + 1]) << 12)
|
|
285
|
+
| ((input[index + 2] === "=" ? 0 : chars.indexOf(input[index + 2])) << 6)
|
|
286
|
+
| (input[index + 3] === "=" ? 0 : chars.indexOf(input[index + 3]));
|
|
287
|
+
output[outputIndex++] = (bits >>> 16) & 255;
|
|
288
|
+
if (outputIndex < output.length) output[outputIndex++] = (bits >>> 8) & 255;
|
|
289
|
+
if (outputIndex < output.length) output[outputIndex++] = bits & 255;
|
|
290
|
+
}
|
|
291
|
+
return output;
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
function openMode(flags, path) {
|
|
295
|
+
switch (flags) {
|
|
296
|
+
case "r": return { read: true, write: false, create: false, createNew: false, truncate: false, append: false };
|
|
297
|
+
case "r+": return { read: true, write: true, create: false, createNew: false, truncate: false, append: false };
|
|
298
|
+
case "w": return { read: false, write: true, create: true, createNew: false, truncate: true, append: false };
|
|
299
|
+
case "wx": case "xw": return { read: false, write: true, create: true, createNew: true, truncate: true, append: false };
|
|
300
|
+
case "w+": return { read: true, write: true, create: true, createNew: false, truncate: true, append: false };
|
|
301
|
+
case "wx+": case "w+x": case "xw+": case "x+w": return { read: true, write: true, create: true, createNew: true, truncate: true, append: false };
|
|
302
|
+
case "a": return { read: false, write: true, create: true, createNew: false, truncate: false, append: true };
|
|
303
|
+
case "ax": case "xa": return { read: false, write: true, create: true, createNew: true, truncate: false, append: true };
|
|
304
|
+
case "a+": return { read: true, write: true, create: true, createNew: false, truncate: false, append: true };
|
|
305
|
+
case "ax+": case "a+x": case "xa+": case "x+a": return { read: true, write: true, create: true, createNew: true, truncate: false, append: true };
|
|
306
|
+
default: throw invalidVfsCall("open", path);
|
|
307
|
+
}
|
|
308
|
+
}
|
|
309
|
+
|
|
310
|
+
function openVfs(vfs, path, mode) {
|
|
311
|
+
const handle = callVfs(vfs, "open", [path, mode], "open", path);
|
|
312
|
+
if (!Number.isSafeInteger(handle) || handle < 0) {
|
|
313
|
+
try { callVfs(vfs, "close", [handle], "close"); } catch {}
|
|
314
|
+
throw vfsFailure(new Error("invalid VFS handle"), "open", path);
|
|
315
|
+
}
|
|
316
|
+
return handle;
|
|
317
|
+
}
|
|
318
|
+
|
|
319
|
+
function readAll(vfs, path, maximumBytes = Number.MAX_SAFE_INTEGER) {
|
|
320
|
+
const handle = openVfs(vfs, path, openMode("r", path));
|
|
321
|
+
const chunks = [];
|
|
322
|
+
let length = 0;
|
|
323
|
+
let failure;
|
|
324
|
+
try {
|
|
325
|
+
for (;;) {
|
|
326
|
+
const buffer = new Uint8Array(Math.min(8192, maximumBytes - Math.min(length, maximumBytes) + 1));
|
|
327
|
+
const count = callVfs(vfs, "readAt", [handle, length, buffer], "read");
|
|
328
|
+
if (!Number.isSafeInteger(count) || count < 0 || count > buffer.byteLength) throw vfsFailure(new Error("invalid VFS read count"), "read");
|
|
329
|
+
if (count === 0) break;
|
|
330
|
+
chunks.push(buffer.slice(0, count));
|
|
331
|
+
length += count;
|
|
332
|
+
if (length > maximumBytes) throw new RangeError(`source exceeded limit of ${maximumBytes} bytes`);
|
|
333
|
+
}
|
|
334
|
+
} catch (error) {
|
|
335
|
+
failure = error;
|
|
336
|
+
}
|
|
337
|
+
try {
|
|
338
|
+
callVfs(vfs, "close", [handle], "close");
|
|
339
|
+
} catch (error) {
|
|
340
|
+
if (failure === undefined) failure = error;
|
|
341
|
+
}
|
|
342
|
+
if (failure !== undefined) throw failure;
|
|
343
|
+
return join(chunks, length);
|
|
344
|
+
}
|
|
345
|
+
|
|
346
|
+
function writeAll(vfs, path, data, append) {
|
|
347
|
+
const mode = openMode(append ? "a" : "w", path);
|
|
348
|
+
const handle = openVfs(vfs, path, mode);
|
|
349
|
+
let written = 0;
|
|
350
|
+
let failure;
|
|
351
|
+
try {
|
|
352
|
+
while (written < data.byteLength) {
|
|
353
|
+
const count = callVfs(vfs, "writeAt", [handle, written, data.subarray(written)], "write");
|
|
354
|
+
if (!Number.isSafeInteger(count) || count < 0 || count > data.byteLength - written) throw vfsFailure(new Error("invalid VFS write count"), "write");
|
|
355
|
+
if (count === 0) throw vfsFailure(new VfsError("ENOSPC"), "write");
|
|
356
|
+
written += count;
|
|
357
|
+
}
|
|
358
|
+
} catch (error) {
|
|
359
|
+
failure = error;
|
|
360
|
+
}
|
|
361
|
+
try {
|
|
362
|
+
callVfs(vfs, "close", [handle], "close");
|
|
363
|
+
} catch (error) {
|
|
364
|
+
if (failure === undefined) failure = error;
|
|
365
|
+
}
|
|
366
|
+
if (failure !== undefined) throw failure;
|
|
367
|
+
}
|
|
368
|
+
|
|
369
|
+
function createVfsDispatcher(vfs, cwd) {
|
|
370
|
+
validateVfs(vfs);
|
|
371
|
+
const files = new Map();
|
|
372
|
+
let nextFd = 3;
|
|
373
|
+
const absolute = (value) => {
|
|
374
|
+
if (typeof value !== "string") throw invalidVfsCall("tinysandbox");
|
|
375
|
+
return resolvePath(cwd, value);
|
|
376
|
+
};
|
|
377
|
+
const metadata = (path, syscall = "stat") => checkedMetadata(callVfs(vfs, "stat", [path], syscall, path), syscall, path);
|
|
378
|
+
const mkdirRecursive = (path) => {
|
|
379
|
+
if (path === "/") return;
|
|
380
|
+
let current = "";
|
|
381
|
+
for (const part of path.slice(1).split("/")) {
|
|
382
|
+
current += `/${part}`;
|
|
383
|
+
try {
|
|
384
|
+
callVfs(vfs, "mkdir", [current], "mkdir", path);
|
|
385
|
+
} catch (error) {
|
|
386
|
+
if (!(error instanceof HostCallFailure) || error.payload.code !== "EEXIST" || metadata(current).fileType !== "directory") throw error;
|
|
387
|
+
}
|
|
388
|
+
}
|
|
389
|
+
};
|
|
390
|
+
const removePath = (path, recursive) => {
|
|
391
|
+
const info = metadata(path, "rm");
|
|
392
|
+
if (info.fileType === "file") return callVfs(vfs, "unlink", [path], "unlink", path);
|
|
393
|
+
if (!recursive) throw vfsFailure(new VfsError("EISDIR"), "rm", path);
|
|
394
|
+
const entries = callVfs(vfs, "readdir", [path], "scandir", path);
|
|
395
|
+
if (!Array.isArray(entries)) throw vfsFailure(new Error("invalid VFS directory entries"), "scandir", path);
|
|
396
|
+
for (const entry of entries) {
|
|
397
|
+
if (!entry || typeof entry.name !== "string" || entry.name.includes("/")) throw vfsFailure(new Error("invalid VFS directory entry"), "scandir", path);
|
|
398
|
+
removePath(path === "/" ? `/${entry.name}` : `${path}/${entry.name}`, true);
|
|
399
|
+
}
|
|
400
|
+
return callVfs(vfs, "rmdir", [path], "rmdir", path);
|
|
401
|
+
};
|
|
402
|
+
const dispatch = (op, args) => {
|
|
403
|
+
switch (op) {
|
|
404
|
+
case "readFile": {
|
|
405
|
+
const path = absolute(args?.path);
|
|
406
|
+
return encodeBase64(remapHostFailure(() => readAll(vfs, path), "open", path));
|
|
407
|
+
}
|
|
408
|
+
case "writeFile": {
|
|
409
|
+
const path = absolute(args?.path);
|
|
410
|
+
remapHostFailure(() => writeAll(vfs, path, decodeBase64(args?.data), false), "open", path);
|
|
411
|
+
return null;
|
|
412
|
+
}
|
|
413
|
+
case "appendFile": {
|
|
414
|
+
const path = absolute(args?.path);
|
|
415
|
+
remapHostFailure(() => writeAll(vfs, path, decodeBase64(args?.data), true), "open", path);
|
|
416
|
+
return null;
|
|
417
|
+
}
|
|
418
|
+
case "mkdir": { const path = absolute(args?.path); args?.recursive ? mkdirRecursive(path) : callVfs(vfs, "mkdir", [path], "mkdir", path); return null; }
|
|
419
|
+
case "readdir": {
|
|
420
|
+
const path = absolute(args?.path);
|
|
421
|
+
const entries = callVfs(vfs, "readdir", [path], "scandir", path);
|
|
422
|
+
if (!Array.isArray(entries)) throw vfsFailure(new Error("invalid VFS directory entries"), "scandir", path);
|
|
423
|
+
return entries.map((entry) => {
|
|
424
|
+
if (!entry || typeof entry.name !== "string" || entry.name.includes("/")) throw vfsFailure(new Error("invalid VFS directory entry"), "scandir", path);
|
|
425
|
+
if (!args?.withFileTypes) return entry.name;
|
|
426
|
+
const info = checkedMetadata(entry.metadata, "scandir", path);
|
|
427
|
+
return { name: entry.name, isFile: info.fileType === "file", isDirectory: info.fileType === "directory" };
|
|
428
|
+
});
|
|
429
|
+
}
|
|
430
|
+
case "stat": { const info = metadata(absolute(args?.path)); return { size: info.len, isFile: info.fileType === "file", isDirectory: info.fileType === "directory" }; }
|
|
431
|
+
case "rename": { const from = absolute(args?.from); const to = absolute(args?.to); callVfs(vfs, "rename", [from, to], "rename", from); return null; }
|
|
432
|
+
case "rm": {
|
|
433
|
+
const path = absolute(args?.path);
|
|
434
|
+
try { removePath(path, !!args?.recursive); } catch (error) { if (!(args?.force && error instanceof HostCallFailure && error.payload.code === "ENOENT")) throw error; }
|
|
435
|
+
return null;
|
|
436
|
+
}
|
|
437
|
+
case "unlink": { const path = absolute(args?.path); callVfs(vfs, "unlink", [path], "unlink", path); return null; }
|
|
438
|
+
case "rmdir": { const path = absolute(args?.path); args?.recursive ? removePath(path, true) : callVfs(vfs, "rmdir", [path], "rmdir", path); return null; }
|
|
439
|
+
case "exists": { try { metadata(absolute(args?.path)); return true; } catch { return false; } }
|
|
440
|
+
case "open": {
|
|
441
|
+
const path = absolute(args?.path);
|
|
442
|
+
const handle = openVfs(vfs, path, openMode(args?.flags, path));
|
|
443
|
+
const fd = nextFd++;
|
|
444
|
+
files.set(fd, { handle, position: 0, path });
|
|
445
|
+
return fd;
|
|
446
|
+
}
|
|
447
|
+
case "read": {
|
|
448
|
+
const fd = checkedInteger(args?.fd, "tinysandbox");
|
|
449
|
+
const file = files.get(fd);
|
|
450
|
+
if (!file) throw vfsFailure(new VfsError("EBADF"), "read");
|
|
451
|
+
const position = checkedInteger(args?.position, "tinysandbox", undefined, true);
|
|
452
|
+
const offset = position ?? file.position;
|
|
453
|
+
let length = Math.min(MAX_HOST_READ_BYTES, checkedInteger(args?.length, "tinysandbox"));
|
|
454
|
+
try { const info = metadata(file.path); if (info.fileType === "file") length = Math.min(length, Math.max(0, info.len - offset)); } catch {}
|
|
455
|
+
const buffer = new Uint8Array(length);
|
|
456
|
+
const count = callVfs(vfs, "readAt", [file.handle, offset, buffer], "read");
|
|
457
|
+
if (!Number.isSafeInteger(count) || count < 0 || count > length) throw vfsFailure(new Error("invalid VFS read count"), "read");
|
|
458
|
+
if (position === null) file.position += count;
|
|
459
|
+
return { bytesRead: count, data: encodeBase64(buffer.subarray(0, count)) };
|
|
460
|
+
}
|
|
461
|
+
case "write": {
|
|
462
|
+
const fd = checkedInteger(args?.fd, "tinysandbox");
|
|
463
|
+
const file = files.get(fd);
|
|
464
|
+
if (!file) throw vfsFailure(new VfsError("EBADF"), "write");
|
|
465
|
+
const position = checkedInteger(args?.position, "tinysandbox", undefined, true);
|
|
466
|
+
const offset = position ?? file.position;
|
|
467
|
+
const data = decodeBase64(args?.data);
|
|
468
|
+
const count = callVfs(vfs, "writeAt", [file.handle, offset, data], "write");
|
|
469
|
+
if (!Number.isSafeInteger(count) || count < 0 || count > data.byteLength) throw vfsFailure(new Error("invalid VFS write count"), "write");
|
|
470
|
+
if (position === null) file.position += count;
|
|
471
|
+
return count;
|
|
472
|
+
}
|
|
473
|
+
case "ftruncate": {
|
|
474
|
+
const fd = checkedInteger(args?.fd, "tinysandbox");
|
|
475
|
+
const file = files.get(fd);
|
|
476
|
+
if (!file) throw vfsFailure(new VfsError("EBADF"), "ftruncate");
|
|
477
|
+
callVfs(vfs, "truncate", [file.handle, checkedInteger(args?.len ?? 0, "tinysandbox")], "ftruncate");
|
|
478
|
+
return null;
|
|
479
|
+
}
|
|
480
|
+
case "close": {
|
|
481
|
+
const fd = checkedInteger(args?.fd, "tinysandbox");
|
|
482
|
+
const file = files.get(fd);
|
|
483
|
+
if (!file) throw vfsFailure(new VfsError("EBADF"), "close");
|
|
484
|
+
files.delete(fd);
|
|
485
|
+
callVfs(vfs, "close", [file.handle], "close");
|
|
486
|
+
return null;
|
|
487
|
+
}
|
|
488
|
+
case "copyFile": {
|
|
489
|
+
const source = absolute(args?.src);
|
|
490
|
+
const destination = absolute(args?.dest);
|
|
491
|
+
const data = remapHostFailure(() => readAll(vfs, source), "copyfile", source);
|
|
492
|
+
remapHostFailure(() => writeAll(vfs, destination, data, false), "copyfile", destination);
|
|
493
|
+
return null;
|
|
494
|
+
}
|
|
495
|
+
default: throw invalidVfsCall("tinysandbox");
|
|
496
|
+
}
|
|
497
|
+
};
|
|
498
|
+
const closeAll = () => {
|
|
499
|
+
for (const { handle } of files.values()) {
|
|
500
|
+
try { callVfs(vfs, "close", [handle], "close"); } catch {}
|
|
501
|
+
}
|
|
502
|
+
files.clear();
|
|
503
|
+
};
|
|
504
|
+
return { dispatch, closeAll };
|
|
505
|
+
}
|
|
506
|
+
|
|
507
|
+
function exposedHostError(payload) {
|
|
508
|
+
const where = payload.path === undefined ? (payload.syscall ? `, ${payload.syscall}` : "") : `, ${payload.syscall} '${payload.path}'`;
|
|
509
|
+
const error = new Error(`${payload.code}: ${payload.message}${where}`);
|
|
510
|
+
error.code = payload.code;
|
|
511
|
+
error.errno = payload.errno;
|
|
512
|
+
error.syscall = payload.syscall;
|
|
513
|
+
if (payload.path !== undefined) error.path = payload.path;
|
|
514
|
+
return error;
|
|
515
|
+
}
|
|
516
|
+
|
|
517
|
+
function remapHostFailure(operation, syscall, path) {
|
|
518
|
+
try {
|
|
519
|
+
return operation();
|
|
520
|
+
} catch (error) {
|
|
521
|
+
if (error instanceof HostCallFailure) throw vfsFailure(new VfsError(error.payload.code), syscall, path);
|
|
522
|
+
throw error;
|
|
523
|
+
}
|
|
524
|
+
}
|
|
525
|
+
|
|
526
|
+
export async function createEngine(wasm) {
|
|
527
|
+
let module;
|
|
528
|
+
if (wasm instanceof WebAssembly.Module) {
|
|
529
|
+
module = wasm;
|
|
530
|
+
} else if (ArrayBuffer.isView(wasm) || wasm instanceof ArrayBuffer) {
|
|
531
|
+
module = await WebAssembly.compile(wasm);
|
|
532
|
+
} else {
|
|
533
|
+
throw new TypeError("createEngine expects wasm bytes or a WebAssembly.Module");
|
|
534
|
+
}
|
|
535
|
+
requireArtifactAbi(module);
|
|
536
|
+
probeArtifactAbi(module);
|
|
537
|
+
|
|
538
|
+
const engine = {
|
|
539
|
+
runCode(code, options = {}) {
|
|
540
|
+
if (typeof code !== "string") throw new TypeError("code must be a string");
|
|
541
|
+
if (options === null || typeof options !== "object") throw new TypeError("options must be an object");
|
|
542
|
+
|
|
543
|
+
const wasmMemoryBytes = integerOption("wasmMemoryBytes", options.wasmMemoryBytes, DEFAULT_WASM_MEMORY_BYTES);
|
|
544
|
+
const maximumPages = Math.min(65_536, Math.floor(wasmMemoryBytes / PAGE_BYTES));
|
|
545
|
+
if (maximumPages < INITIAL_PAGES) {
|
|
546
|
+
throw new RangeError(`wasmMemoryBytes must be at least ${QUICKJS_INITIAL_MEMORY_BYTES} bytes`);
|
|
547
|
+
}
|
|
548
|
+
const quickjsHeapBytes = integerOption("quickjsHeapBytes", options.quickjsHeapBytes, DEFAULT_QUICKJS_HEAP_BYTES, 1);
|
|
549
|
+
if (quickjsHeapBytes > 0x7fff_ffff) throw new RangeError("quickjsHeapBytes must be at most 2147483647");
|
|
550
|
+
const timeoutMs = integerOption("timeoutMs", options.timeoutMs, DEFAULT_TIMEOUT_MS, 1);
|
|
551
|
+
const sourceBytes = integerOption("sourceBytes", options.sourceBytes, DEFAULT_SOURCE_BYTES);
|
|
552
|
+
const hostResponseBytes = integerOption("hostResponseBytes", options.hostResponseBytes, DEFAULT_HOST_RESPONSE_BYTES);
|
|
553
|
+
const stdoutBytes = integerOption("stdoutBytes", options.stdoutBytes, DEFAULT_OUTPUT_BYTES);
|
|
554
|
+
const stderrBytes = integerOption("stderrBytes", options.stderrBytes, DEFAULT_OUTPUT_BYTES);
|
|
555
|
+
const sourceLength = encoder.encode(code).byteLength;
|
|
556
|
+
if (sourceLength > sourceBytes) throw new RangeError(`source exceeded limit of ${sourceBytes} bytes`);
|
|
557
|
+
const globals = options.globals ?? {};
|
|
558
|
+
const globalNames = validateGlobals(globals);
|
|
559
|
+
const vfs = options.vfs === undefined ? undefined : validateVfs(options.vfs);
|
|
560
|
+
const started = monotonicNow();
|
|
561
|
+
const deadline = started + timeoutMs;
|
|
562
|
+
const memory = new WebAssembly.Memory({ initial: INITIAL_PAGES, maximum: maximumPages });
|
|
563
|
+
const stdout = [];
|
|
564
|
+
const stderr = [];
|
|
565
|
+
let stdoutLength = 0;
|
|
566
|
+
let stderrLength = 0;
|
|
567
|
+
let response = new Uint8Array();
|
|
568
|
+
let timedOut = false;
|
|
569
|
+
let limitFailure;
|
|
570
|
+
const vfsDispatcher = vfs === undefined ? undefined : createVfsDispatcher(vfs, resolvePath("/", options.cwd ?? "/"));
|
|
571
|
+
|
|
572
|
+
const read = (pointer, length) => {
|
|
573
|
+
if (!Number.isInteger(pointer) || !Number.isInteger(length) || pointer < 0 || length < 0 || pointer + length > memory.buffer.byteLength) {
|
|
574
|
+
throw new WebAssembly.RuntimeError("guest memory access out of bounds");
|
|
575
|
+
}
|
|
576
|
+
return new Uint8Array(memory.buffer, pointer, length);
|
|
577
|
+
};
|
|
578
|
+
const capture = (target, pointer, length, cap, stream) => {
|
|
579
|
+
const current = stream === "stdout" ? stdoutLength : stderrLength;
|
|
580
|
+
if (length > cap - current) {
|
|
581
|
+
limitFailure = new RunLimitError(stream, `${stream} exceeded limit of ${cap} bytes`);
|
|
582
|
+
throw limitFailure;
|
|
583
|
+
}
|
|
584
|
+
target.push(read(pointer, length).slice());
|
|
585
|
+
if (stream === "stdout") stdoutLength += length;
|
|
586
|
+
else stderrLength += length;
|
|
587
|
+
return length;
|
|
588
|
+
};
|
|
589
|
+
const setResponse = (value) => {
|
|
590
|
+
let bytes;
|
|
591
|
+
try {
|
|
592
|
+
bytes = encoder.encode(JSON.stringify(value));
|
|
593
|
+
} catch (error) {
|
|
594
|
+
bytes = encoder.encode(JSON.stringify({ error: jsonError(error) }));
|
|
595
|
+
}
|
|
596
|
+
if (bytes.byteLength > hostResponseBytes) {
|
|
597
|
+
bytes = encoder.encode(JSON.stringify({ error: { code: "E2BIG", message: `host response exceeded limit of ${hostResponseBytes} bytes` } }));
|
|
598
|
+
if (bytes.byteLength > hostResponseBytes) {
|
|
599
|
+
limitFailure = new RunLimitError("hostResponse", `host response exceeded limit of ${hostResponseBytes} bytes`);
|
|
600
|
+
throw limitFailure;
|
|
601
|
+
}
|
|
602
|
+
}
|
|
603
|
+
response = bytes;
|
|
604
|
+
};
|
|
605
|
+
const tinysandbox = {
|
|
606
|
+
should_interrupt() {
|
|
607
|
+
if (monotonicNow() >= deadline) timedOut = true;
|
|
608
|
+
return timedOut ? 1 : 0;
|
|
609
|
+
},
|
|
610
|
+
host_call(opPointer, opLength, jsonPointer, jsonLength) {
|
|
611
|
+
const op = decoder.decode(read(opPointer, opLength));
|
|
612
|
+
let argument;
|
|
613
|
+
try {
|
|
614
|
+
argument = JSON.parse(decoder.decode(read(jsonPointer, jsonLength)));
|
|
615
|
+
} catch (error) {
|
|
616
|
+
setResponse({ error: { code: "EINVAL", message: `invalid host call JSON: ${error instanceof Error ? error.message : String(error)}` } });
|
|
617
|
+
return 0;
|
|
618
|
+
}
|
|
619
|
+
if (op !== "global" && (!VFS_OPERATIONS.has(op) || vfsDispatcher === undefined)) {
|
|
620
|
+
setResponse({ error: { code: "ENOSYS", message: `host capability '${op}' is not available` } });
|
|
621
|
+
return 0;
|
|
622
|
+
}
|
|
623
|
+
if (op !== "global") {
|
|
624
|
+
try {
|
|
625
|
+
setResponse({ value: vfsDispatcher.dispatch(op, argument) });
|
|
626
|
+
} catch (error) {
|
|
627
|
+
setResponse({ error: error instanceof HostCallFailure ? error.payload : jsonError(error) });
|
|
628
|
+
}
|
|
629
|
+
return 0;
|
|
630
|
+
}
|
|
631
|
+
const name = argument?.name;
|
|
632
|
+
const handler = typeof name === "string" ? globals[name] : undefined;
|
|
633
|
+
if (typeof handler !== "function") {
|
|
634
|
+
setResponse({ error: { message: `unknown global '${String(name)}'` } });
|
|
635
|
+
return 0;
|
|
636
|
+
}
|
|
637
|
+
try {
|
|
638
|
+
const value = handler(argument.args ?? null);
|
|
639
|
+
if (value && typeof value === "object" && typeof value.then === "function") {
|
|
640
|
+
throw new TypeError(`global '${name}' returned a Promise; host globals must be synchronous`);
|
|
641
|
+
}
|
|
642
|
+
assertJsonValue(value, `global '${name}' response`);
|
|
643
|
+
setResponse({ value });
|
|
644
|
+
} catch (error) {
|
|
645
|
+
setResponse({ error: jsonError(error) });
|
|
646
|
+
}
|
|
647
|
+
return 0;
|
|
648
|
+
},
|
|
649
|
+
host_response_len() { return response.byteLength; },
|
|
650
|
+
host_response_read(pointer, length) {
|
|
651
|
+
const count = Math.min(length, response.byteLength);
|
|
652
|
+
read(pointer, count).set(response.subarray(0, count));
|
|
653
|
+
return count;
|
|
654
|
+
},
|
|
655
|
+
write_stdout(pointer, length) { return capture(stdout, pointer, length, stdoutBytes, "stdout"); },
|
|
656
|
+
write_stderr(pointer, length) { return capture(stderr, pointer, length, stderrBytes, "stderr"); },
|
|
657
|
+
};
|
|
658
|
+
const wasi = {
|
|
659
|
+
clock_time_get(clockId, _precision, pointer) {
|
|
660
|
+
const nanos = clockId === 1 ? BigInt(Math.floor((monotonicNow() - started) * 1_000_000)) : BigInt(Date.now()) * 1_000_000n;
|
|
661
|
+
new DataView(memory.buffer).setBigUint64(pointer, nanos, true);
|
|
662
|
+
return 0;
|
|
663
|
+
},
|
|
664
|
+
fd_close() { return 0; },
|
|
665
|
+
fd_fdstat_get() { return 8; },
|
|
666
|
+
fd_seek() { return 8; },
|
|
667
|
+
fd_write(fd, iovs, iovsLength, writtenPointer) {
|
|
668
|
+
if (fd !== 1 && fd !== 2) return 8;
|
|
669
|
+
let total = 0;
|
|
670
|
+
for (let index = 0; index < iovsLength; index++) {
|
|
671
|
+
const view = new DataView(memory.buffer);
|
|
672
|
+
const pointer = view.getUint32(iovs + index * 8, true);
|
|
673
|
+
const length = view.getUint32(iovs + index * 8 + 4, true);
|
|
674
|
+
capture(fd === 1 ? stdout : stderr, pointer, length, fd === 1 ? stdoutBytes : stderrBytes, fd === 1 ? "stdout" : "stderr");
|
|
675
|
+
total += length;
|
|
676
|
+
}
|
|
677
|
+
writeU32(memory, writtenPointer, total);
|
|
678
|
+
return 0;
|
|
679
|
+
},
|
|
680
|
+
};
|
|
681
|
+
|
|
682
|
+
let instance;
|
|
683
|
+
let exitCode = 1;
|
|
684
|
+
try {
|
|
685
|
+
instance = new WebAssembly.Instance(module, { env: { memory }, tinysandbox, wasi_snapshot_preview1: wasi });
|
|
686
|
+
if (instance.exports.memory !== memory) throw new TypeError("QuickJS wasm did not re-export env.memory");
|
|
687
|
+
if (typeof instance.exports._initialize === "function") instance.exports._initialize();
|
|
688
|
+
const configBytes = encoder.encode(JSON.stringify({
|
|
689
|
+
code,
|
|
690
|
+
scriptPath: options.scriptPath ?? "[eval]",
|
|
691
|
+
argv: options.argv ?? ["js", "-e"],
|
|
692
|
+
env: options.env ?? {},
|
|
693
|
+
cwd: options.cwd ?? "/",
|
|
694
|
+
globals: globalNames,
|
|
695
|
+
prelude: "",
|
|
696
|
+
vfs: vfs !== undefined,
|
|
697
|
+
}));
|
|
698
|
+
const pointer = instance.exports.tinysandbox_alloc(configBytes.byteLength);
|
|
699
|
+
if (!pointer) throw new WebAssembly.RuntimeError("QuickJS input allocation failed");
|
|
700
|
+
read(pointer, configBytes.byteLength).set(configBytes);
|
|
701
|
+
exitCode = instance.exports.tinysandbox_run(pointer, configBytes.byteLength, quickjsHeapBytes);
|
|
702
|
+
if (timedOut) {
|
|
703
|
+
return { exitCode: 124, stdout: "", stderr: "js: command timed out\n", initialWasmMemoryBytes: QUICKJS_INITIAL_MEMORY_BYTES, peakWasmMemoryBytes: memory.buffer.byteLength };
|
|
704
|
+
}
|
|
705
|
+
instance.exports.tinysandbox_free(pointer);
|
|
706
|
+
} catch (error) {
|
|
707
|
+
if (timedOut) {
|
|
708
|
+
return { exitCode: 124, stdout: "", stderr: "js: command timed out\n", initialWasmMemoryBytes: QUICKJS_INITIAL_MEMORY_BYTES, peakWasmMemoryBytes: memory.buffer.byteLength };
|
|
709
|
+
}
|
|
710
|
+
const isMemory = error instanceof WebAssembly.RuntimeError && /memory|allocation|out of bounds/i.test(error.message);
|
|
711
|
+
const message = limitFailure?.message ?? (isMemory ? "wasm memory limit exceeded" : `runtime trap: ${error instanceof Error ? error.message : String(error)}`);
|
|
712
|
+
return { exitCode: 1, stdout: decoder.decode(join(stdout, stdoutLength)), stderr: `js: ${message}\n`, initialWasmMemoryBytes: QUICKJS_INITIAL_MEMORY_BYTES, peakWasmMemoryBytes: memory.buffer.byteLength };
|
|
713
|
+
} finally {
|
|
714
|
+
vfsDispatcher?.closeAll();
|
|
715
|
+
}
|
|
716
|
+
return {
|
|
717
|
+
exitCode,
|
|
718
|
+
stdout: decoder.decode(join(stdout, stdoutLength)),
|
|
719
|
+
stderr: decoder.decode(join(stderr, stderrLength)),
|
|
720
|
+
initialWasmMemoryBytes: QUICKJS_INITIAL_MEMORY_BYTES,
|
|
721
|
+
peakWasmMemoryBytes: memory.buffer.byteLength,
|
|
722
|
+
};
|
|
723
|
+
},
|
|
724
|
+
runFile(path, options = {}) {
|
|
725
|
+
if (typeof path !== "string") throw new TypeError("path must be a string");
|
|
726
|
+
if (options === null || typeof options !== "object") throw new TypeError("options must be an object");
|
|
727
|
+
const vfs = validateVfs(options.vfs);
|
|
728
|
+
const cwd = resolvePath("/", options.cwd ?? "/");
|
|
729
|
+
const resolved = resolvePath(cwd, path);
|
|
730
|
+
const sourceBytes = integerOption("sourceBytes", options.sourceBytes, DEFAULT_SOURCE_BYTES);
|
|
731
|
+
let bytes;
|
|
732
|
+
try {
|
|
733
|
+
bytes = remapHostFailure(() => readAll(vfs, resolved, sourceBytes), "open", resolved);
|
|
734
|
+
} catch (error) {
|
|
735
|
+
if (error instanceof HostCallFailure) throw exposedHostError(error.payload);
|
|
736
|
+
throw error;
|
|
737
|
+
}
|
|
738
|
+
let code;
|
|
739
|
+
try {
|
|
740
|
+
code = fatalDecoder.decode(bytes);
|
|
741
|
+
} catch {
|
|
742
|
+
throw new TypeError(`runFile entry '${resolved}' is not valid UTF-8`);
|
|
743
|
+
}
|
|
744
|
+
return engine.runCode(code, {
|
|
745
|
+
...options,
|
|
746
|
+
vfs,
|
|
747
|
+
cwd,
|
|
748
|
+
scriptPath: resolved,
|
|
749
|
+
argv: options.argv ?? ["js", path],
|
|
750
|
+
});
|
|
751
|
+
},
|
|
752
|
+
};
|
|
753
|
+
return Object.freeze(engine);
|
|
754
|
+
}
|
|
755
|
+
|
|
756
|
+
function join(chunks, length) {
|
|
757
|
+
const result = new Uint8Array(length);
|
|
758
|
+
let offset = 0;
|
|
759
|
+
for (const chunk of chunks) {
|
|
760
|
+
result.set(chunk, offset);
|
|
761
|
+
offset += chunk.byteLength;
|
|
762
|
+
}
|
|
763
|
+
return result;
|
|
764
|
+
}
|
package/package.json
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@tinysandbox/js-runtime",
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "Stateless QuickJS runtime for standard WebAssembly hosts",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"exports": {
|
|
7
|
+
".": {
|
|
8
|
+
"types": "./dist/index.d.ts",
|
|
9
|
+
"default": "./dist/index.js"
|
|
10
|
+
},
|
|
11
|
+
"./quickjs.wasm": "./quickjs.wasm"
|
|
12
|
+
},
|
|
13
|
+
"files": [
|
|
14
|
+
"dist/",
|
|
15
|
+
"quickjs.wasm",
|
|
16
|
+
"README.md",
|
|
17
|
+
"LICENSE-APACHE",
|
|
18
|
+
"LICENSE-MIT"
|
|
19
|
+
],
|
|
20
|
+
"sideEffects": false,
|
|
21
|
+
"engines": {
|
|
22
|
+
"node": ">=20"
|
|
23
|
+
},
|
|
24
|
+
"scripts": {
|
|
25
|
+
"build": "node scripts/build.mjs",
|
|
26
|
+
"test": "npm run build && npm run typecheck && node --test test/*.test.mjs",
|
|
27
|
+
"typecheck": "tsc -p tsconfig.json",
|
|
28
|
+
"test:browser": "node test/browser-smoke.mjs",
|
|
29
|
+
"test:convex": "npm run build && npm run typecheck && node test/convex-smoke.mjs"
|
|
30
|
+
},
|
|
31
|
+
"license": "MIT OR Apache-2.0",
|
|
32
|
+
"repository": {
|
|
33
|
+
"type": "git",
|
|
34
|
+
"url": "git+https://github.com/danthegoodman1/tinysandbox.git",
|
|
35
|
+
"directory": "tinysandbox-js-runtime"
|
|
36
|
+
},
|
|
37
|
+
"devDependencies": {
|
|
38
|
+
"esbuild": "^0.28.2",
|
|
39
|
+
"typescript": "^7.0.2"
|
|
40
|
+
}
|
|
41
|
+
}
|
package/quickjs.wasm
ADDED
|
Binary file
|