@jini-ai/sandbox 0.4.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/CHANGELOG.md +16 -0
- package/LICENSE +201 -0
- package/README.md +209 -0
- package/dist/cjs/core/errors.d.ts +56 -0
- package/dist/cjs/core/errors.js +40 -0
- package/dist/cjs/core/index.d.ts +20 -0
- package/dist/cjs/core/index.js +22 -0
- package/dist/cjs/core/ports.d.ts +232 -0
- package/dist/cjs/core/ports.js +55 -0
- package/dist/cjs/e2b/categorize-e2b-error.d.ts +21 -0
- package/dist/cjs/e2b/categorize-e2b-error.js +27 -0
- package/dist/cjs/e2b/default-vite-react-template.d.ts +26 -0
- package/dist/cjs/e2b/default-vite-react-template.js +122 -0
- package/dist/cjs/e2b/e2b-sandbox-handle.d.ts +131 -0
- package/dist/cjs/e2b/e2b-sandbox-handle.js +28 -0
- package/dist/cjs/e2b/index.d.ts +18 -0
- package/dist/cjs/e2b/index.js +25 -0
- package/dist/cjs/e2b/provider.d.ts +63 -0
- package/dist/cjs/e2b/provider.js +92 -0
- package/dist/cjs/e2b/shell-quote.d.ts +21 -0
- package/dist/cjs/e2b/shell-quote.js +24 -0
- package/dist/cjs/e2b/to-array-buffer.d.ts +18 -0
- package/dist/cjs/e2b/to-array-buffer.js +21 -0
- package/dist/cjs/e2b/wrap-e2b-sandbox.d.ts +31 -0
- package/dist/cjs/e2b/wrap-e2b-sandbox.js +347 -0
- package/dist/cjs/node-worker.d.ts +111 -0
- package/dist/cjs/node-worker.js +157 -0
- package/dist/cjs/package.json +1 -0
- package/dist/core/errors.d.ts +56 -0
- package/dist/core/errors.js +36 -0
- package/dist/core/index.d.ts +20 -0
- package/dist/core/index.js +18 -0
- package/dist/core/ports.d.ts +232 -0
- package/dist/core/ports.js +54 -0
- package/dist/e2b/categorize-e2b-error.d.ts +21 -0
- package/dist/e2b/categorize-e2b-error.js +24 -0
- package/dist/e2b/default-vite-react-template.d.ts +26 -0
- package/dist/e2b/default-vite-react-template.js +119 -0
- package/dist/e2b/e2b-sandbox-handle.d.ts +131 -0
- package/dist/e2b/e2b-sandbox-handle.js +27 -0
- package/dist/e2b/index.d.ts +18 -0
- package/dist/e2b/index.js +15 -0
- package/dist/e2b/provider.d.ts +63 -0
- package/dist/e2b/provider.js +88 -0
- package/dist/e2b/shell-quote.d.ts +21 -0
- package/dist/e2b/shell-quote.js +21 -0
- package/dist/e2b/to-array-buffer.d.ts +18 -0
- package/dist/e2b/to-array-buffer.js +18 -0
- package/dist/e2b/wrap-e2b-sandbox.d.ts +31 -0
- package/dist/e2b/wrap-e2b-sandbox.js +343 -0
- package/dist/node-worker.d.ts +111 -0
- package/dist/node-worker.js +150 -0
- package/package.json +106 -0
|
@@ -0,0 +1,347 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.mapE2bFileChangeKind = mapE2bFileChangeKind;
|
|
4
|
+
exports.wrapE2bSandbox = wrapE2bSandbox;
|
|
5
|
+
/**
|
|
6
|
+
* @file Wraps a raw E2B sandbox handle into a `SandboxSession`.
|
|
7
|
+
*
|
|
8
|
+
* Purpose:
|
|
9
|
+
* All of the E2B-specific translation lives here: building shell command strings from
|
|
10
|
+
* `command`/`args`, mapping E2B's filesystem event vocabulary onto core's `FileChangeKind`,
|
|
11
|
+
* converting binary content to what E2B's `files.write` accepts, and turning every failure into
|
|
12
|
+
* a `SandboxOperationError`. Deliberately separated from `provider.ts`'s `Sandbox.create()` call
|
|
13
|
+
* so this logic is testable against a plain object literal — no network call, no API key, and
|
|
14
|
+
* (per `categorize-e2b-error.ts`'s own doc) no import of the real SDK at all.
|
|
15
|
+
*
|
|
16
|
+
* Architectural role:
|
|
17
|
+
* Driver-side implementation of `@jini-ai/sandbox/core`'s `SandboxProviderPort`/`SandboxSession`
|
|
18
|
+
* ports. Imports from `../core/*`, never the reverse.
|
|
19
|
+
*/
|
|
20
|
+
const node_crypto_1 = require("node:crypto");
|
|
21
|
+
const node_path_1 = require("node:path");
|
|
22
|
+
const errors_js_1 = require("../core/errors.js");
|
|
23
|
+
const categorize_e2b_error_js_1 = require("./categorize-e2b-error.js");
|
|
24
|
+
const shell_quote_js_1 = require("./shell-quote.js");
|
|
25
|
+
const to_array_buffer_js_1 = require("./to-array-buffer.js");
|
|
26
|
+
/**
|
|
27
|
+
* Bound on `files.list`'s server-side recursion depth. A theme project's own tree is small, but
|
|
28
|
+
* nothing stops `listFiles` from being pointed at a directory containing a much larger one — an
|
|
29
|
+
* unbounded walk is exactly the kind of external-call resource risk that needs a cap rather than
|
|
30
|
+
* an assumption that inputs stay small. 20 is generous for a theme's own files while still being
|
|
31
|
+
* a real bound, not `Infinity` spelled differently.
|
|
32
|
+
*/
|
|
33
|
+
const MAX_LIST_DEPTH = 20;
|
|
34
|
+
/** Directory names `listFiles` excludes from its results — dependency/build/VCS noise a caller
|
|
35
|
+
* asking "what's in this theme" almost never wants, and `node_modules` specifically can be
|
|
36
|
+
* enormous. Mirrors the filter open-lovable's own `listFiles` implementation used. */
|
|
37
|
+
const EXCLUDED_DIR_NAMES = new Set(['node_modules', '.git', 'dist', 'build', '.next']);
|
|
38
|
+
/** Thrown by `getPreview` when a single check finds nothing listening on `previewPort` yet. Not
|
|
39
|
+
* a retry loop — callers that want to poll do so by calling `getPreview` again. */
|
|
40
|
+
function previewNotReadyError(url, cause) {
|
|
41
|
+
return new errors_js_1.SandboxOperationError({ category: 'timeout', message: `Sandbox preview at ${url} is not responding yet` }, {
|
|
42
|
+
cause,
|
|
43
|
+
});
|
|
44
|
+
}
|
|
45
|
+
/** Wraps anything caught from an `E2bSandboxHandle` call into a `SandboxOperationError`. */
|
|
46
|
+
function wrapE2bError(error, message) {
|
|
47
|
+
return new errors_js_1.SandboxOperationError({ category: (0, categorize_e2b_error_js_1.categorizeE2bError)({ error }), message }, { cause: error });
|
|
48
|
+
}
|
|
49
|
+
/** Builds one shell command string from a program name and shell-quoted arguments. The program
|
|
50
|
+
* name itself is not quoted — see `shell-quote.ts` for why. */
|
|
51
|
+
function buildCommand(command, args) {
|
|
52
|
+
return args.length === 0 ? command : `${command} ${args.map((value) => (0, shell_quote_js_1.shellQuote)({ value })).join(' ')}`;
|
|
53
|
+
}
|
|
54
|
+
function toCommandResult(result) {
|
|
55
|
+
return { stdout: result.stdout, stderr: result.stderr, exitCode: result.exitCode };
|
|
56
|
+
}
|
|
57
|
+
/** Converts `SandboxFile.content` into what E2B's `files.write` actually accepts (`string |
|
|
58
|
+
* ArrayBuffer`, no `Uint8Array` overload). */
|
|
59
|
+
function toE2bWriteData(content) {
|
|
60
|
+
return typeof content === 'string' ? content : (0, to_array_buffer_js_1.toArrayBuffer)({ bytes: content });
|
|
61
|
+
}
|
|
62
|
+
/**
|
|
63
|
+
* The `onStdout`/`onStderr` fragment to spread into an E2B `commands.run` call — present only
|
|
64
|
+
* when `options.onOutput` is given. Built with a conditional spread rather than
|
|
65
|
+
* `onStdout: options?.onOutput ? fn : undefined` because this package's `exactOptionalPropertyTypes`
|
|
66
|
+
* makes an explicit `undefined` on an optional key a type error distinct from the key being
|
|
67
|
+
* absent; omitting the keys entirely is both what's needed and what compiles.
|
|
68
|
+
*/
|
|
69
|
+
function streamingOptsFor(options) {
|
|
70
|
+
const onOutput = options?.onOutput;
|
|
71
|
+
if (!onOutput)
|
|
72
|
+
return {};
|
|
73
|
+
return {
|
|
74
|
+
onStdout: ({ data }) => onOutput({ stream: 'stdout', text: data }),
|
|
75
|
+
onStderr: ({ data }) => onOutput({ stream: 'stderr', text: data }),
|
|
76
|
+
};
|
|
77
|
+
}
|
|
78
|
+
/**
|
|
79
|
+
* Maps one E2B filesystem event kind onto core's three-way `FileChangeKind`, or `null` to mean
|
|
80
|
+
* "don't surface this one." `'chmod'` is a permissions change, not a content change, and is
|
|
81
|
+
* dropped for that reason. `'rename'` is mapped to `modified` rather than guessed as
|
|
82
|
+
* create/delete because E2B's event carries only the one path this adapter sees, not an old/new
|
|
83
|
+
* pair — a wrong create-or-delete guess would be more misleading than the conservative
|
|
84
|
+
* "something at this path changed."
|
|
85
|
+
*/
|
|
86
|
+
function mapE2bFileChangeKind({ type }) {
|
|
87
|
+
switch (type) {
|
|
88
|
+
case 'create':
|
|
89
|
+
return 'created';
|
|
90
|
+
case 'write':
|
|
91
|
+
case 'rename':
|
|
92
|
+
return 'modified';
|
|
93
|
+
case 'remove':
|
|
94
|
+
return 'deleted';
|
|
95
|
+
case 'chmod':
|
|
96
|
+
return null;
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
/**
|
|
100
|
+
* Strips a `projectRoot` prefix off an absolute E2B path, producing the project-root-relative
|
|
101
|
+
* path convention `SandboxFile.path`/`FileChangeEvent.path` use.
|
|
102
|
+
*
|
|
103
|
+
* Assumption flagged for verification: E2B's `EntryInfo.path` is treated here as absolute,
|
|
104
|
+
* inferred from its type-level doc ("Path to the filesystem object") plus this adapter always
|
|
105
|
+
* calling `write`/`list` with absolute paths — not confirmed against a live sandbox, since
|
|
106
|
+
* building this adapter didn't include real E2B credentials. If a real sandbox's `list()` turns
|
|
107
|
+
* out to echo paths relative to the queried directory instead, this function is the one place
|
|
108
|
+
* that needs to change.
|
|
109
|
+
*/
|
|
110
|
+
function relativeToRoot(absolutePath, projectRoot) {
|
|
111
|
+
const prefix = projectRoot.endsWith('/') ? projectRoot : `${projectRoot}/`;
|
|
112
|
+
return absolutePath.startsWith(prefix) ? absolutePath.slice(prefix.length) : absolutePath;
|
|
113
|
+
}
|
|
114
|
+
/** True if any path segment matches one of `EXCLUDED_DIR_NAMES`. */
|
|
115
|
+
function isExcludedPath(relativePath) {
|
|
116
|
+
return relativePath.split('/').some((segment) => EXCLUDED_DIR_NAMES.has(segment));
|
|
117
|
+
}
|
|
118
|
+
async function wrapE2bSandbox({ handle, config }, { fetchImpl = fetch } = {}) {
|
|
119
|
+
const { projectRoot, previewPort, previewCheckTimeoutMs } = config;
|
|
120
|
+
try {
|
|
121
|
+
await handle.commands.run({ command: `mkdir -p ${(0, shell_quote_js_1.shellQuote)({ value: projectRoot })}` });
|
|
122
|
+
}
|
|
123
|
+
catch (error) {
|
|
124
|
+
throw wrapE2bError(error, 'Failed to create the sandbox project root');
|
|
125
|
+
}
|
|
126
|
+
const fileChangeListeners = new Set();
|
|
127
|
+
// The watcher carries no writer identity and can deliver echoes after write() resolves.
|
|
128
|
+
// Keep content fingerprints, not file bodies, to suppress those delayed host echoes while
|
|
129
|
+
// still reporting subsequent sandbox edits. Same-content rewrites are indistinguishable.
|
|
130
|
+
const mountedFiles = new Map();
|
|
131
|
+
const mountingPaths = new Map();
|
|
132
|
+
const fingerprint = (content) => (0, node_crypto_1.createHash)('sha256').update(content).digest('hex');
|
|
133
|
+
let watchHandle;
|
|
134
|
+
try {
|
|
135
|
+
watchHandle = await handle.files.watchDir({ path: projectRoot, onEvent: (event) => {
|
|
136
|
+
const kind = mapE2bFileChangeKind({ type: event.type });
|
|
137
|
+
if (kind === null)
|
|
138
|
+
return;
|
|
139
|
+
const path = node_path_1.posix.normalize(event.name);
|
|
140
|
+
const deliver = () => {
|
|
141
|
+
const changeEvent = { path: event.name, kind };
|
|
142
|
+
for (const listener of fileChangeListeners)
|
|
143
|
+
listener(changeEvent);
|
|
144
|
+
};
|
|
145
|
+
if (mountingPaths.has(path) && (event.type === 'create' || event.type === 'write'))
|
|
146
|
+
return;
|
|
147
|
+
if (mountedFiles.has(path) && (event.type === 'create' || event.type === 'write')) {
|
|
148
|
+
void handle.files.read({ path: node_path_1.posix.join(projectRoot, path), format: 'bytes' }).then(bytes => {
|
|
149
|
+
if (mountingPaths.has(path))
|
|
150
|
+
return;
|
|
151
|
+
if (mountedFiles.get(path)?.fingerprint === fingerprint(bytes))
|
|
152
|
+
return;
|
|
153
|
+
mountedFiles.delete(path);
|
|
154
|
+
deliver();
|
|
155
|
+
}, () => {
|
|
156
|
+
if (mountingPaths.has(path))
|
|
157
|
+
return;
|
|
158
|
+
mountedFiles.delete(path);
|
|
159
|
+
deliver();
|
|
160
|
+
});
|
|
161
|
+
return;
|
|
162
|
+
}
|
|
163
|
+
mountedFiles.delete(path);
|
|
164
|
+
deliver();
|
|
165
|
+
} }, { recursive: true });
|
|
166
|
+
}
|
|
167
|
+
catch (error) {
|
|
168
|
+
throw wrapE2bError(error, 'Failed to start watching the sandbox project root');
|
|
169
|
+
}
|
|
170
|
+
/** Every process this session has started via `startProcess`, so `teardown` can kill them
|
|
171
|
+
* all — see `SandboxSession.teardown`'s doc for why an orphaned dev server on `local` is a
|
|
172
|
+
* real liability, not just untidy. A process removes itself once its own `kill()` succeeds,
|
|
173
|
+
* so `teardown` doesn't redundantly re-kill it; failed kills stay tracked for a retry. */
|
|
174
|
+
const trackedProcesses = new Set();
|
|
175
|
+
return {
|
|
176
|
+
async mountFiles({ files }) {
|
|
177
|
+
if (files.length === 0)
|
|
178
|
+
return;
|
|
179
|
+
const mounted = new Map();
|
|
180
|
+
for (const file of files) {
|
|
181
|
+
const path = relativeToRoot(node_path_1.posix.join(projectRoot, file.path), projectRoot);
|
|
182
|
+
mounted.set(path, { fingerprint: fingerprint(file.content) });
|
|
183
|
+
}
|
|
184
|
+
for (const [path, entry] of mounted) {
|
|
185
|
+
mountedFiles.set(path, entry);
|
|
186
|
+
mountingPaths.set(path, (mountingPaths.get(path) ?? 0) + 1);
|
|
187
|
+
}
|
|
188
|
+
try {
|
|
189
|
+
await handle.files.write({ files: files.map((file) => ({
|
|
190
|
+
path: node_path_1.posix.join(projectRoot, file.path),
|
|
191
|
+
data: toE2bWriteData(file.content),
|
|
192
|
+
})) });
|
|
193
|
+
}
|
|
194
|
+
catch (error) {
|
|
195
|
+
for (const [path, entry] of mounted) {
|
|
196
|
+
if (mountedFiles.get(path) === entry)
|
|
197
|
+
mountedFiles.delete(path);
|
|
198
|
+
}
|
|
199
|
+
throw wrapE2bError(error, 'Failed to write files into the sandbox');
|
|
200
|
+
}
|
|
201
|
+
finally {
|
|
202
|
+
for (const path of mounted.keys()) {
|
|
203
|
+
const remaining = mountingPaths.get(path) - 1;
|
|
204
|
+
if (remaining === 0)
|
|
205
|
+
mountingPaths.delete(path);
|
|
206
|
+
else
|
|
207
|
+
mountingPaths.set(path, remaining);
|
|
208
|
+
}
|
|
209
|
+
}
|
|
210
|
+
},
|
|
211
|
+
async readFile({ path }) {
|
|
212
|
+
try {
|
|
213
|
+
return await handle.files.read({ path: node_path_1.posix.join(projectRoot, path), format: 'bytes' });
|
|
214
|
+
}
|
|
215
|
+
catch (error) {
|
|
216
|
+
throw wrapE2bError(error, `Failed to read ${path}`);
|
|
217
|
+
}
|
|
218
|
+
},
|
|
219
|
+
async listFiles(_required, { directory } = {}) {
|
|
220
|
+
const base = directory ? node_path_1.posix.join(projectRoot, directory) : projectRoot;
|
|
221
|
+
let entries;
|
|
222
|
+
try {
|
|
223
|
+
entries = await handle.files.list({ path: base }, { depth: MAX_LIST_DEPTH });
|
|
224
|
+
}
|
|
225
|
+
catch (error) {
|
|
226
|
+
throw wrapE2bError(error, `Failed to list files under ${directory ?? '.'}`);
|
|
227
|
+
}
|
|
228
|
+
return entries
|
|
229
|
+
.filter((entry) => entry.type === 'file')
|
|
230
|
+
.map((entry) => relativeToRoot(entry.path, projectRoot))
|
|
231
|
+
.filter((relativePath) => !isExcludedPath(relativePath));
|
|
232
|
+
},
|
|
233
|
+
async runCommand({ command }, options = {}) {
|
|
234
|
+
try {
|
|
235
|
+
const result = await handle.commands.run({ command: buildCommand(command, options.args ?? []) }, {
|
|
236
|
+
cwd: projectRoot,
|
|
237
|
+
...streamingOptsFor(options),
|
|
238
|
+
});
|
|
239
|
+
return toCommandResult(result);
|
|
240
|
+
}
|
|
241
|
+
catch (error) {
|
|
242
|
+
throw wrapE2bError(error, `Command failed: ${command}`);
|
|
243
|
+
}
|
|
244
|
+
},
|
|
245
|
+
async installDependencies(_required, options = {}) {
|
|
246
|
+
const { packages } = options;
|
|
247
|
+
const command = packages && packages.length > 0
|
|
248
|
+
? `npm install ${packages.map((value) => (0, shell_quote_js_1.shellQuote)({ value })).join(' ')}`
|
|
249
|
+
: 'npm install';
|
|
250
|
+
try {
|
|
251
|
+
const result = await handle.commands.run({ command }, {
|
|
252
|
+
cwd: projectRoot,
|
|
253
|
+
...streamingOptsFor(options),
|
|
254
|
+
});
|
|
255
|
+
return toCommandResult(result);
|
|
256
|
+
}
|
|
257
|
+
catch (error) {
|
|
258
|
+
throw wrapE2bError(error, 'npm install failed');
|
|
259
|
+
}
|
|
260
|
+
},
|
|
261
|
+
async startProcess({ command }, { args = [] } = {}) {
|
|
262
|
+
const outputListeners = new Set();
|
|
263
|
+
let e2bHandle;
|
|
264
|
+
try {
|
|
265
|
+
e2bHandle = await handle.commands.run({ command: buildCommand(command, args), background: true }, {
|
|
266
|
+
cwd: projectRoot,
|
|
267
|
+
onStdout: ({ data }) => {
|
|
268
|
+
for (const listener of outputListeners)
|
|
269
|
+
listener({ stream: 'stdout', text: data });
|
|
270
|
+
},
|
|
271
|
+
onStderr: ({ data }) => {
|
|
272
|
+
for (const listener of outputListeners)
|
|
273
|
+
listener({ stream: 'stderr', text: data });
|
|
274
|
+
},
|
|
275
|
+
});
|
|
276
|
+
}
|
|
277
|
+
catch (error) {
|
|
278
|
+
throw wrapE2bError(error, `Failed to start process: ${command}`);
|
|
279
|
+
}
|
|
280
|
+
const processHandle = {
|
|
281
|
+
async kill() {
|
|
282
|
+
try {
|
|
283
|
+
await e2bHandle.kill();
|
|
284
|
+
trackedProcesses.delete(processHandle);
|
|
285
|
+
}
|
|
286
|
+
catch (error) {
|
|
287
|
+
throw wrapE2bError(error, 'Failed to kill process');
|
|
288
|
+
}
|
|
289
|
+
},
|
|
290
|
+
onOutput({ listener }) {
|
|
291
|
+
outputListeners.add(listener);
|
|
292
|
+
return () => outputListeners.delete(listener);
|
|
293
|
+
},
|
|
294
|
+
};
|
|
295
|
+
trackedProcesses.add(processHandle);
|
|
296
|
+
return processHandle;
|
|
297
|
+
},
|
|
298
|
+
async getPreview() {
|
|
299
|
+
const url = `https://${handle.getHost({ port: previewPort })}`;
|
|
300
|
+
const controller = new AbortController();
|
|
301
|
+
const timer = setTimeout(() => controller.abort(), previewCheckTimeoutMs);
|
|
302
|
+
try {
|
|
303
|
+
await fetchImpl(url, { method: 'HEAD', signal: controller.signal });
|
|
304
|
+
}
|
|
305
|
+
catch (error) {
|
|
306
|
+
throw previewNotReadyError(url, error);
|
|
307
|
+
}
|
|
308
|
+
finally {
|
|
309
|
+
clearTimeout(timer);
|
|
310
|
+
}
|
|
311
|
+
return { url };
|
|
312
|
+
},
|
|
313
|
+
onFileChange({ listener }) {
|
|
314
|
+
fileChangeListeners.add(listener);
|
|
315
|
+
return () => fileChangeListeners.delete(listener);
|
|
316
|
+
},
|
|
317
|
+
async teardown() {
|
|
318
|
+
// Best-effort: every tracked process gets a kill attempt regardless of whether another
|
|
319
|
+
// one fails. A process that refuses to die is a different problem than this adapter can
|
|
320
|
+
// solve; what teardown promises is that killing was attempted, not that it's leakproof
|
|
321
|
+
// against a hung process ignoring SIGKILL.
|
|
322
|
+
await Promise.allSettled([...trackedProcesses].map((process) => process.kill()));
|
|
323
|
+
let watchStopError;
|
|
324
|
+
try {
|
|
325
|
+
await watchHandle.stop();
|
|
326
|
+
}
|
|
327
|
+
catch (error) {
|
|
328
|
+
watchStopError = error;
|
|
329
|
+
}
|
|
330
|
+
try {
|
|
331
|
+
await handle.kill();
|
|
332
|
+
// Successful VM termination also confirms any remaining processes are gone.
|
|
333
|
+
trackedProcesses.clear();
|
|
334
|
+
mountedFiles.clear();
|
|
335
|
+
}
|
|
336
|
+
catch (error) {
|
|
337
|
+
// The sandbox failing to terminate is the more severe of the two possible failures
|
|
338
|
+
// here (an un-torn-down VM vs. a watch handle that didn't clean up) — surfaced first.
|
|
339
|
+
throw wrapE2bError(error, 'Failed to terminate the sandbox');
|
|
340
|
+
}
|
|
341
|
+
if (watchStopError !== undefined) {
|
|
342
|
+
throw wrapE2bError(watchStopError, 'Failed to stop watching the sandbox project root');
|
|
343
|
+
}
|
|
344
|
+
},
|
|
345
|
+
};
|
|
346
|
+
}
|
|
347
|
+
//# sourceMappingURL=wrap-e2b-sandbox.js.map
|
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
import type { ResourceLimits } from "node:worker_threads";
|
|
2
|
+
export type WorkerSubscription = {
|
|
3
|
+
event: "message";
|
|
4
|
+
listener: (input: {
|
|
5
|
+
message: unknown;
|
|
6
|
+
}) => void;
|
|
7
|
+
} | {
|
|
8
|
+
event: "error";
|
|
9
|
+
listener: (input: {
|
|
10
|
+
error: Error;
|
|
11
|
+
}) => void;
|
|
12
|
+
} | {
|
|
13
|
+
event: "exit";
|
|
14
|
+
listener: (input: {
|
|
15
|
+
code: number;
|
|
16
|
+
}) => void;
|
|
17
|
+
};
|
|
18
|
+
export interface WorkerHandle {
|
|
19
|
+
once(input: WorkerSubscription): void;
|
|
20
|
+
terminate(): Promise<number>;
|
|
21
|
+
}
|
|
22
|
+
export interface WorkerFactory {
|
|
23
|
+
spawn<TPayload>(input: {
|
|
24
|
+
workerEntry: string | URL;
|
|
25
|
+
payload: TPayload;
|
|
26
|
+
resourceLimits: ResourceLimits;
|
|
27
|
+
}): WorkerHandle;
|
|
28
|
+
}
|
|
29
|
+
/** Scheduling must defer run until after schedule returns; the returned function cancels it. */
|
|
30
|
+
export interface WorkerScheduler {
|
|
31
|
+
schedule(input: {
|
|
32
|
+
delayMs: number;
|
|
33
|
+
run: () => void;
|
|
34
|
+
}): () => void;
|
|
35
|
+
}
|
|
36
|
+
export interface WorkerSandboxRequired<TPayload> {
|
|
37
|
+
workerEntry: string | URL;
|
|
38
|
+
input: TPayload;
|
|
39
|
+
errorLabel: string;
|
|
40
|
+
defaultTimeoutMs: number;
|
|
41
|
+
defaultResourceLimits: ResourceLimits;
|
|
42
|
+
workerFactory: WorkerFactory;
|
|
43
|
+
scheduler: WorkerScheduler;
|
|
44
|
+
}
|
|
45
|
+
export interface WorkerSandboxOptions {
|
|
46
|
+
timeoutMs?: number;
|
|
47
|
+
resourceLimits?: ResourceLimits;
|
|
48
|
+
}
|
|
49
|
+
export type SandboxRenderResult = {
|
|
50
|
+
ok: true;
|
|
51
|
+
html: string;
|
|
52
|
+
} | {
|
|
53
|
+
ok: false;
|
|
54
|
+
error: string;
|
|
55
|
+
};
|
|
56
|
+
/**
|
|
57
|
+
* Strictly parse a host-supplied timeout value, falling back on malformed or out-of-range values.
|
|
58
|
+
* @param required Raw configuration and explicit default/maximum budgets in milliseconds.
|
|
59
|
+
* @returns Valid positive integer timeout; no environment is read.
|
|
60
|
+
* @complexity O(n) for n characters in rawValue.
|
|
61
|
+
*/
|
|
62
|
+
export declare function resolveDefaultTimeoutMs({ rawValue, defaultTimeoutMs, maxTimeoutMs }: {
|
|
63
|
+
rawValue: string | undefined;
|
|
64
|
+
defaultTimeoutMs: number;
|
|
65
|
+
maxTimeoutMs: number;
|
|
66
|
+
}): number;
|
|
67
|
+
/**
|
|
68
|
+
* Run structured-cloneable payloads in a fresh bounded worker using a caller-owned result codec.
|
|
69
|
+
* @param required Entry, payload, budgets and worker/timer/decoder ports.
|
|
70
|
+
* @param options Per-invocation timeout and resource limits.
|
|
71
|
+
* @returns Decoded first reply; rejects on timeout, error, exit-without-reply or codec failure.
|
|
72
|
+
* @throws RangeError (as a rejected promise) for an invalid timeout.
|
|
73
|
+
* @complexity O(1) harness work, excluding structured clone, worker execution and decoding.
|
|
74
|
+
*/
|
|
75
|
+
export declare function runInWorkerSandbox<TPayload, TResult>(required: WorkerSandboxRequired<TPayload> & {
|
|
76
|
+
decodeResult: (input: {
|
|
77
|
+
message: unknown;
|
|
78
|
+
}) => TResult;
|
|
79
|
+
}, options?: WorkerSandboxOptions): Promise<TResult>;
|
|
80
|
+
/**
|
|
81
|
+
* Render-protocol convenience adapter; payloads are generic and host context types stay outside.
|
|
82
|
+
* @param required Worker harness ports/settings and a structured-cloneable application payload.
|
|
83
|
+
* @param options Per-render budgets.
|
|
84
|
+
* @returns HTML from the existing {ok, html/error} wire shape.
|
|
85
|
+
* @complexity O(1) protocol validation plus worker harness work.
|
|
86
|
+
*/
|
|
87
|
+
export declare function renderInWorkerSandbox<TPayload>(required: WorkerSandboxRequired<TPayload>, options?: WorkerSandboxOptions): Promise<string>;
|
|
88
|
+
export interface NodeWorkerFactoryOptions {
|
|
89
|
+
/** Explicit CommonJS registration module path for TypeScript entries (e.g. tsx/cjs/api). */
|
|
90
|
+
typescriptBootstrap?: {
|
|
91
|
+
registerModulePath: string;
|
|
92
|
+
};
|
|
93
|
+
}
|
|
94
|
+
/**
|
|
95
|
+
* Native Node worker factory. TypeScript bootstrap configuration is explicit and host-owned.
|
|
96
|
+
* @param required Environment copied to each worker; nothing reads the parent environment.
|
|
97
|
+
* @param options Optional TypeScript registration module; its eval entry suppresses V8 coverage.
|
|
98
|
+
* @returns WorkerFactory for caller-owned JS/TS entry paths, with no package-relative lookup.
|
|
99
|
+
* @complexity O(e) environment copying for e variables, excluding native worker startup.
|
|
100
|
+
*/
|
|
101
|
+
export declare function createNodeWorkerFactory({ env }: {
|
|
102
|
+
env: NodeJS.ProcessEnv;
|
|
103
|
+
}, options?: NodeWorkerFactoryOptions): WorkerFactory;
|
|
104
|
+
/**
|
|
105
|
+
* Create the Node timeout adapter; construction has no timer effects.
|
|
106
|
+
* @param required Empty required arguments object.
|
|
107
|
+
* @returns WorkerScheduler using native timers.
|
|
108
|
+
* @complexity O(1) per schedule/cancel.
|
|
109
|
+
*/
|
|
110
|
+
export declare function createNodeWorkerScheduler(_required: Record<string, never>): WorkerScheduler;
|
|
111
|
+
//# sourceMappingURL=node-worker.d.ts.map
|
|
@@ -0,0 +1,157 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.resolveDefaultTimeoutMs = resolveDefaultTimeoutMs;
|
|
4
|
+
exports.runInWorkerSandbox = runInWorkerSandbox;
|
|
5
|
+
exports.renderInWorkerSandbox = renderInWorkerSandbox;
|
|
6
|
+
exports.createNodeWorkerFactory = createNodeWorkerFactory;
|
|
7
|
+
exports.createNodeWorkerScheduler = createNodeWorkerScheduler;
|
|
8
|
+
/**
|
|
9
|
+
* CPU-bound synchronous work cannot be pre-empted by a Promise.race timer on that same
|
|
10
|
+
* thread. A fresh worker lets the parent terminate runaway work and apply V8 heap limits
|
|
11
|
+
* without wedging or exhausting the main server. Node workers avoid a native sandbox
|
|
12
|
+
* build dependency and the known escape vulnerabilities of vm2.
|
|
13
|
+
*/
|
|
14
|
+
const node_worker_threads_1 = require("node:worker_threads");
|
|
15
|
+
const node_path_1 = require("node:path");
|
|
16
|
+
/**
|
|
17
|
+
* Strictly parse a host-supplied timeout value, falling back on malformed or out-of-range values.
|
|
18
|
+
* @param required Raw configuration and explicit default/maximum budgets in milliseconds.
|
|
19
|
+
* @returns Valid positive integer timeout; no environment is read.
|
|
20
|
+
* @complexity O(n) for n characters in rawValue.
|
|
21
|
+
*/
|
|
22
|
+
// Do not use parseInt: "5e3" becomes 5 milliseconds and "60000ms" silently becomes
|
|
23
|
+
// 60000. A malformed configuration must fall back, never masquerade as a deliberate budget.
|
|
24
|
+
function resolveDefaultTimeoutMs({ rawValue, defaultTimeoutMs, maxTimeoutMs }) {
|
|
25
|
+
if (rawValue === undefined || !/^\d+$/.test(rawValue.trim()))
|
|
26
|
+
return defaultTimeoutMs;
|
|
27
|
+
const parsed = Number(rawValue.trim());
|
|
28
|
+
if (!Number.isSafeInteger(parsed) || parsed <= 0 || parsed > maxTimeoutMs)
|
|
29
|
+
return defaultTimeoutMs;
|
|
30
|
+
return parsed;
|
|
31
|
+
}
|
|
32
|
+
/**
|
|
33
|
+
* Run structured-cloneable payloads in a fresh bounded worker using a caller-owned result codec.
|
|
34
|
+
* @param required Entry, payload, budgets and worker/timer/decoder ports.
|
|
35
|
+
* @param options Per-invocation timeout and resource limits.
|
|
36
|
+
* @returns Decoded first reply; rejects on timeout, error, exit-without-reply or codec failure.
|
|
37
|
+
* @throws RangeError (as a rejected promise) for an invalid timeout.
|
|
38
|
+
* @complexity O(1) harness work, excluding structured clone, worker execution and decoding.
|
|
39
|
+
*/
|
|
40
|
+
function runInWorkerSandbox(required, options = {}) {
|
|
41
|
+
const timeoutMs = options.timeoutMs ?? required.defaultTimeoutMs;
|
|
42
|
+
if (!Number.isSafeInteger(timeoutMs) || timeoutMs <= 0 || timeoutMs > 2147483647) {
|
|
43
|
+
return Promise.reject(new RangeError("timeoutMs must be a positive integer within the Node timer range"));
|
|
44
|
+
}
|
|
45
|
+
return new Promise((resolve, reject) => {
|
|
46
|
+
const worker = required.workerFactory.spawn({ workerEntry: required.workerEntry, payload: required.input, resourceLimits: options.resourceLimits ?? required.defaultResourceLimits });
|
|
47
|
+
let settled = false;
|
|
48
|
+
let cancelTimer;
|
|
49
|
+
function terminate() {
|
|
50
|
+
// Teardown must never create a second rejection after the result has already settled.
|
|
51
|
+
try {
|
|
52
|
+
void worker.terminate().catch(() => { });
|
|
53
|
+
}
|
|
54
|
+
catch { /* best effort */ }
|
|
55
|
+
}
|
|
56
|
+
function finish(run) {
|
|
57
|
+
if (settled)
|
|
58
|
+
return;
|
|
59
|
+
settled = true;
|
|
60
|
+
cancelTimer?.();
|
|
61
|
+
try {
|
|
62
|
+
run();
|
|
63
|
+
}
|
|
64
|
+
catch (error) {
|
|
65
|
+
reject(error);
|
|
66
|
+
}
|
|
67
|
+
terminate();
|
|
68
|
+
}
|
|
69
|
+
try {
|
|
70
|
+
worker.once({ event: "message", listener: ({ message }) => finish(() => resolve(required.decodeResult({ message }))) });
|
|
71
|
+
worker.once({ event: "error", listener: ({ error }) => finish(() => reject(error)) });
|
|
72
|
+
worker.once({ event: "exit", listener: ({ code }) => finish(() => reject(new Error(`${required.errorLabel} worker exited with code ${code}`))) });
|
|
73
|
+
cancelTimer = required.scheduler.schedule({ delayMs: timeoutMs, run: () => finish(() => reject(new Error(`${required.errorLabel} exceeded ${timeoutMs}ms timeout`))) });
|
|
74
|
+
}
|
|
75
|
+
catch (error) {
|
|
76
|
+
finish(() => reject(error));
|
|
77
|
+
}
|
|
78
|
+
});
|
|
79
|
+
}
|
|
80
|
+
/**
|
|
81
|
+
* Render-protocol convenience adapter; payloads are generic and host context types stay outside.
|
|
82
|
+
* @param required Worker harness ports/settings and a structured-cloneable application payload.
|
|
83
|
+
* @param options Per-render budgets.
|
|
84
|
+
* @returns HTML from the existing {ok, html/error} wire shape.
|
|
85
|
+
* @complexity O(1) protocol validation plus worker harness work.
|
|
86
|
+
*/
|
|
87
|
+
function renderInWorkerSandbox(required, options = {}) {
|
|
88
|
+
return runInWorkerSandbox({
|
|
89
|
+
...required, errorLabel: `${required.errorLabel} render`,
|
|
90
|
+
decodeResult: ({ message }) => {
|
|
91
|
+
if (message === null || typeof message !== "object")
|
|
92
|
+
throw new Error("invalid worker render reply");
|
|
93
|
+
const reply = message;
|
|
94
|
+
if (reply.ok === true && "html" in reply && typeof reply.html === "string")
|
|
95
|
+
return reply.html;
|
|
96
|
+
if (reply.ok === false && "error" in reply && typeof reply.error === "string")
|
|
97
|
+
throw new Error(reply.error);
|
|
98
|
+
throw new Error("invalid worker render reply");
|
|
99
|
+
},
|
|
100
|
+
}, options);
|
|
101
|
+
}
|
|
102
|
+
/**
|
|
103
|
+
* Native Node worker factory. TypeScript bootstrap configuration is explicit and host-owned.
|
|
104
|
+
* @param required Environment copied to each worker; nothing reads the parent environment.
|
|
105
|
+
* @param options Optional TypeScript registration module; its eval entry suppresses V8 coverage.
|
|
106
|
+
* @returns WorkerFactory for caller-owned JS/TS entry paths, with no package-relative lookup.
|
|
107
|
+
* @complexity O(e) environment copying for e variables, excluding native worker startup.
|
|
108
|
+
*/
|
|
109
|
+
function createNodeWorkerFactory({ env }, options = {}) {
|
|
110
|
+
return {
|
|
111
|
+
spawn({ workerEntry, payload, resourceLimits }) {
|
|
112
|
+
const workerEnv = { ...env };
|
|
113
|
+
let worker;
|
|
114
|
+
// A CommonJS-typed TS entry bypasses --import loader hooks for its first file and
|
|
115
|
+
// can fail with "Cannot use import statement outside a module" despite the flag.
|
|
116
|
+
// Register inside an eval CommonJS bootstrap before requiring the absolute TS path,
|
|
117
|
+
// so that first file travels through an already registered tsx require hook.
|
|
118
|
+
if (options.typescriptBootstrap !== undefined) {
|
|
119
|
+
if (typeof workerEntry !== "string" || !(0, node_path_1.isAbsolute)(workerEntry))
|
|
120
|
+
throw new TypeError("TypeScript bootstrap requires an absolute filesystem entry path");
|
|
121
|
+
// Eval/tsx loads a CJS image of files the parent covers as ESM. Merging both V8
|
|
122
|
+
// profiles concatenates function tables and can clobber parent line hits with the
|
|
123
|
+
// worker copy, corrupting coverage. Suppress only this TS worker profile; compiled
|
|
124
|
+
// ESM workers retain coverage because their module image matches the parent.
|
|
125
|
+
// Worker-only entries consequently need their own verification; no scratch profile
|
|
126
|
+
// directory is created merely to leave cleanup behind.
|
|
127
|
+
delete workerEnv.NODE_V8_COVERAGE;
|
|
128
|
+
const bootstrap = `require(${JSON.stringify(options.typescriptBootstrap.registerModulePath)}).register();\nrequire(${JSON.stringify(workerEntry)});\n`;
|
|
129
|
+
worker = new node_worker_threads_1.Worker(bootstrap, { eval: true, workerData: payload, resourceLimits, env: workerEnv, execArgv: [] });
|
|
130
|
+
}
|
|
131
|
+
else {
|
|
132
|
+
worker = new node_worker_threads_1.Worker(workerEntry, { workerData: payload, resourceLimits, env: workerEnv, execArgv: [] });
|
|
133
|
+
}
|
|
134
|
+
return {
|
|
135
|
+
once(input) {
|
|
136
|
+
if (input.event === "message")
|
|
137
|
+
worker.once("message", (message) => input.listener({ message }));
|
|
138
|
+
else if (input.event === "error")
|
|
139
|
+
worker.once("error", (error) => input.listener({ error }));
|
|
140
|
+
else
|
|
141
|
+
worker.once("exit", (code) => input.listener({ code }));
|
|
142
|
+
},
|
|
143
|
+
terminate: () => worker.terminate(),
|
|
144
|
+
};
|
|
145
|
+
},
|
|
146
|
+
};
|
|
147
|
+
}
|
|
148
|
+
/**
|
|
149
|
+
* Create the Node timeout adapter; construction has no timer effects.
|
|
150
|
+
* @param required Empty required arguments object.
|
|
151
|
+
* @returns WorkerScheduler using native timers.
|
|
152
|
+
* @complexity O(1) per schedule/cancel.
|
|
153
|
+
*/
|
|
154
|
+
function createNodeWorkerScheduler(_required) {
|
|
155
|
+
return { schedule: ({ delayMs, run }) => { const timer = setTimeout(run, delayMs); return () => clearTimeout(timer); } };
|
|
156
|
+
}
|
|
157
|
+
//# sourceMappingURL=node-worker.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"type":"commonjs"}
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @file The one error type every `SandboxSession`/`SandboxProviderPort` method rejects with.
|
|
3
|
+
*
|
|
4
|
+
* Purpose:
|
|
5
|
+
* Separated from `ports.ts` on purpose — everything in `ports.ts` is an `interface`/`type` that
|
|
6
|
+
* erases at compile time, and a category a caller can branch on has to exist somewhere at
|
|
7
|
+
* runtime, not just in a type annotation. Keeping the one real class in its own file lets
|
|
8
|
+
* `ports.ts` keep its zero-runtime-statement property (and the literal truth of its own header
|
|
9
|
+
* comment) rather than being "mostly types, plus one class" and quietly stopping being either.
|
|
10
|
+
*
|
|
11
|
+
* Architectural role:
|
|
12
|
+
* Still `./core` — re-exported alongside everything in `ports.ts` from `index.ts`, so nothing
|
|
13
|
+
* changes for a consumer importing `@jini-ai/sandbox/core`. `pnpm guard`'s R12 check scopes to
|
|
14
|
+
* `src/core` as a whole (see `jini.neutralEntries` in `package.json`), not to `ports.ts`
|
|
15
|
+
* specifically, so this file inherits the same "no adapter import, ever" enforcement.
|
|
16
|
+
*/
|
|
17
|
+
/**
|
|
18
|
+
* Backend-neutral reasons a sandbox operation can fail. A caller handles one of these six
|
|
19
|
+
* categories, never a backend name — "network down" (E2B) and "node isn't installed" (local) are
|
|
20
|
+
* different causes for the same category, `'unavailable'`, and neither should force a caller to
|
|
21
|
+
* branch on which adapter it's talking to.
|
|
22
|
+
*/
|
|
23
|
+
export type SandboxErrorCategory =
|
|
24
|
+
/** The backend itself could not be reached or started: network failure, quota exceeded, a
|
|
25
|
+
* required local runtime/binary missing. */
|
|
26
|
+
'unavailable'
|
|
27
|
+
/** The operation was refused for lack of rights: an invalid/rejected API key or access token,
|
|
28
|
+
* no filesystem write permission. */
|
|
29
|
+
| 'permission-denied'
|
|
30
|
+
/** The requested port was already bound. */
|
|
31
|
+
| 'port-in-use'
|
|
32
|
+
/** The requested resource doesn't exist — a file path, a session that's already torn down. */
|
|
33
|
+
| 'not-found'
|
|
34
|
+
/** The operation didn't complete within its bound. */
|
|
35
|
+
| 'timeout'
|
|
36
|
+
/** Any other backend-specific failure. `cause` carries the detail. */
|
|
37
|
+
| 'unknown';
|
|
38
|
+
/**
|
|
39
|
+
* The one error type every `SandboxSession`/`SandboxProviderPort` method rejects with. Named
|
|
40
|
+
* `SandboxOperationError` rather than `SandboxError` because `@e2b/code-interpreter`'s own base
|
|
41
|
+
* SDK (`e2b`) already exports a class literally called `SandboxError` — importing both into the
|
|
42
|
+
* same adapter file under the obvious names would collide.
|
|
43
|
+
*
|
|
44
|
+
* `cause` (the standard `Error` field, via `ErrorOptions`) is the escape hatch for the backend's
|
|
45
|
+
* own detail — the original E2B SDK error, the Node `ENOENT`, whatever a specific adapter caught.
|
|
46
|
+
* `category` is what a caller is expected to actually branch on; `cause` is for logging and
|
|
47
|
+
* debugging, not for a caller to inspect to figure out what really happened per backend.
|
|
48
|
+
*/
|
|
49
|
+
export declare class SandboxOperationError extends Error {
|
|
50
|
+
readonly category: SandboxErrorCategory;
|
|
51
|
+
constructor({ category, message }: {
|
|
52
|
+
category: SandboxErrorCategory;
|
|
53
|
+
message: string;
|
|
54
|
+
}, options?: ErrorOptions);
|
|
55
|
+
}
|
|
56
|
+
//# sourceMappingURL=errors.d.ts.map
|