@dudko.dev/agent-web 0.0.37 → 0.0.38

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.
@@ -0,0 +1,745 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
28
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
+
30
+ // src/sandbox/worker.ts
31
+ var worker_exports = {};
32
+ __export(worker_exports, {
33
+ serveSandboxWorker: () => serveSandboxWorker
34
+ });
35
+ module.exports = __toCommonJS(worker_exports);
36
+
37
+ // src/sandbox/engine.ts
38
+ var RUN_JS_TOOL = "run_js";
39
+ var MIB = 1024 * 1024;
40
+ var SANDBOX_DEFAULTS = {
41
+ timeoutMs: 5e3,
42
+ memoryLimitBytes: 32 * MIB,
43
+ maxOutputChars: 8e3,
44
+ maxCodeChars: 1e5
45
+ };
46
+ var SANDBOX_CAPS = {
47
+ timeoutMs: 6e4,
48
+ memoryLimitBytes: 256 * MIB,
49
+ maxOutputChars: 1e5,
50
+ maxCodeChars: 1e6
51
+ };
52
+ var SANDBOX_FLOORS = {
53
+ timeoutMs: 50,
54
+ // What the engine's WebAssembly module asks for before it runs anything.
55
+ memoryLimitBytes: 16 * MIB,
56
+ maxOutputChars: 200,
57
+ maxCodeChars: 100
58
+ };
59
+ var SANDBOX_MAX_FILE_CHARS = 1e6;
60
+ var SANDBOX_MAX_HOST_CALLS = 500;
61
+ var SANDBOX_MODULE_EXTENSIONS = [".js", ".mjs", ".json"];
62
+ var MAX_TIMERS = 1e3;
63
+ var GUEST_STACK_BYTES = 256 * 1024;
64
+ var ERROR_NAME_CHARS = 200;
65
+ var ERROR_TEXT_CHARS = 4e3;
66
+ var SANDBOX_PLANNER_NOTE = `When the request needs code to be run, tested or checked on data, or a calculation that is easier to compute than to reason about, plan a step that calls ${RUN_JS_TOOL} for it.`;
67
+ var SANDBOX_SYNTHESIZER_NOTE = `Report the output of running code only when a ${RUN_JS_TOOL} call returned it; if the code was written but not run, say it was not run.`;
68
+ var clip = (text, max) => text.length > max ? text.slice(0, max) : text;
69
+ var errorText = (err) => {
70
+ if (err instanceof Error) {
71
+ return `${err.name}: ${err.message}`;
72
+ }
73
+ return typeof err === "string" ? err : "unknown error";
74
+ };
75
+ var dirname = (path) => {
76
+ const i = path.lastIndexOf("/");
77
+ return i <= 0 ? "/" : path.slice(0, i);
78
+ };
79
+ var resolveModulePath = (base, specifier) => {
80
+ const spec = String(specifier);
81
+ if (!/^(\.{1,2}\/|\/)/.test(spec) || /[\\\0]/.test(spec)) {
82
+ throw new Error(
83
+ `Cannot load "${clip(spec, 200)}": the sandbox has no packages and no Node or browser modules - only workspace files by path ("./lib.js")`
84
+ );
85
+ }
86
+ const parts = spec.startsWith("/") ? [] : dirname(base).split("/").filter(Boolean);
87
+ for (const seg of spec.split("/")) {
88
+ if (!seg || seg === ".") {
89
+ continue;
90
+ }
91
+ if (seg === "..") {
92
+ if (parts.length === 0) {
93
+ throw new Error(`Cannot load "${clip(spec, 200)}": the path leaves the workspace`);
94
+ }
95
+ parts.pop();
96
+ continue;
97
+ }
98
+ parts.push(seg);
99
+ }
100
+ const path = `/${parts.join("/")}`;
101
+ if (!SANDBOX_MODULE_EXTENSIONS.some((ext) => path.toLowerCase().endsWith(ext))) {
102
+ throw new Error(
103
+ `Cannot load "${clip(path, 200)}": only ${SANDBOX_MODULE_EXTENSIONS.join(", ")} files can be imported`
104
+ );
105
+ }
106
+ return path;
107
+ };
108
+ var looksLikeModule = (code) => /(^|[\n;])\s*(import\s*[\w$*{'"]|export\s+[\w$*{])/.test(code);
109
+ var EVAL_SCRIPT_ASYNC = 128;
110
+ var BOOTSTRAP = `(function (host, cfg) {
111
+ 'use strict';
112
+ var g = globalThis, J = JSON, S = String, E = Error, P = Promise, M = Map, R = Reflect;
113
+ var hostLog = host.log, hostTimer = host.timer, hostClear = host.clear;
114
+ var hostCall = host.call, hostResolve = host.resolve, hostCompile = host.compile;
115
+ function inspect(v, depth, seen) {
116
+ var t = typeof v;
117
+ if (t === 'string') return depth ? J.stringify(v) : v;
118
+ if (t === 'bigint') return S(v) + 'n';
119
+ if (t === 'function') return '[Function' + (v.name ? ': ' + v.name : '') + ']';
120
+ if (t !== 'object' || v === null) return S(v);
121
+ if (v instanceof E) return S(v.name) + ': ' + S(v.message) + (v.stack ? '\\n' + S(v.stack).replace(/\\n$/, '') : '');
122
+ if (seen.indexOf(v) >= 0) return '[Circular]';
123
+ if (depth > 4) return Array.isArray(v) ? '[Array]' : '[Object]';
124
+ if (v instanceof Date) return isNaN(v) ? 'Invalid Date' : v.toISOString();
125
+ if (v instanceof RegExp) return S(v);
126
+ seen.push(v);
127
+ var parts = [], out, i, keys;
128
+ if (Array.isArray(v)) {
129
+ for (i = 0; i < v.length && i < 100; i++) parts.push(inspect(v[i], depth + 1, seen));
130
+ if (v.length > 100) parts.push('... ' + (v.length - 100) + ' more');
131
+ out = parts.length ? '[ ' + parts.join(', ') + ' ]' : '[]';
132
+ } else if (v instanceof M) {
133
+ v.forEach(function (val, key) { if (parts.length < 50) parts.push(inspect(key, depth + 1, seen) + ' => ' + inspect(val, depth + 1, seen)); });
134
+ out = 'Map(' + v.size + ') {' + (parts.length ? ' ' + parts.join(', ') + ' ' : '') + '}';
135
+ } else if (v instanceof Set) {
136
+ v.forEach(function (val) { if (parts.length < 50) parts.push(inspect(val, depth + 1, seen)); });
137
+ out = 'Set(' + v.size + ') {' + (parts.length ? ' ' + parts.join(', ') + ' ' : '') + '}';
138
+ } else {
139
+ keys = Object.keys(v);
140
+ for (i = 0; i < keys.length && i < 50; i++) parts.push(keys[i] + ': ' + inspect(v[keys[i]], depth + 1, seen));
141
+ if (keys.length > 50) parts.push('... ' + (keys.length - 50) + ' more');
142
+ out = parts.length ? '{ ' + parts.join(', ') + ' }' : '{}';
143
+ }
144
+ seen.pop();
145
+ return out;
146
+ }
147
+ function print(level) {
148
+ return function () {
149
+ var s = '', i;
150
+ try {
151
+ for (i = 0; i < arguments.length && s.length <= cfg.max; i++) s += (i ? ' ' : '') + inspect(arguments[i], 0, []);
152
+ } catch (e) { s += '[unprintable]'; }
153
+ hostLog(level, s.length > cfg.max ? s.slice(0, cfg.max + 1) : s);
154
+ };
155
+ }
156
+ g.console = { log: print(''), info: print(''), debug: print(''), trace: print(''), warn: print('warn'), error: print('error') };
157
+ function plain(v, depth, seen, budget) {
158
+ var t = typeof v, out, i, keys;
159
+ if ((budget.n -= 1) < 0) { budget.cut = true; return '[Truncated]'; }
160
+ if (v === null || t === 'boolean' || t === 'undefined') return v;
161
+ if (t === 'string') { if (v.length > cfg.max) { budget.cut = true; return v.slice(0, cfg.max); } return v; }
162
+ if (t === 'number') return isFinite(v) ? v : S(v);
163
+ if (t === 'bigint') return S(v) + 'n';
164
+ if (t === 'symbol') return S(v);
165
+ if (t === 'function') return '[Function' + (v.name ? ': ' + v.name : '') + ']';
166
+ if (v instanceof E) return { name: S(v.name), message: S(v.message) };
167
+ if (seen.indexOf(v) >= 0) return '[Circular]';
168
+ if (depth >= 8) return Array.isArray(v) ? '[Array]' : '[Object]';
169
+ if (v instanceof Date) return isNaN(v) ? null : v.toISOString();
170
+ seen.push(v);
171
+ if (v instanceof M) { out = []; v.forEach(function (val, key) { out.push([plain(key, depth + 1, seen, budget), plain(val, depth + 1, seen, budget)]); }); }
172
+ else if (v instanceof Set) { out = []; v.forEach(function (val) { out.push(plain(val, depth + 1, seen, budget)); }); }
173
+ else if (Array.isArray(v)) { out = []; for (i = 0; i < v.length && budget.n >= 0; i++) out.push(plain(v[i], depth + 1, seen, budget)); }
174
+ else { out = {}; keys = Object.keys(v); for (i = 0; i < keys.length && budget.n >= 0; i++) out[keys[i]] = plain(v[keys[i]], depth + 1, seen, budget); }
175
+ seen.pop();
176
+ return out;
177
+ }
178
+ function serialize(v, max) {
179
+ if (v === undefined) return '';
180
+ var budget = { n: 20000, cut: false }, text;
181
+ try { text = J.stringify(plain(v, 0, [], budget)); } catch (e) { text = J.stringify('[unserializable]'); }
182
+ if (text === undefined) return '';
183
+ if (text.length > max) return 'T' + text.slice(0, max);
184
+ return (budget.cut ? 'C' : 'J') + text;
185
+ }
186
+ function describe(e) {
187
+ var name = 'Error', message = '', stack = '';
188
+ try {
189
+ if (e instanceof E || (e && typeof e === 'object' && typeof e.message === 'string')) {
190
+ name = S(e.name || 'Error'); message = S(e.message); stack = typeof e.stack === 'string' ? e.stack : '';
191
+ } else { message = 'thrown: ' + inspect(e, 1, []); }
192
+ } catch (x) { message = '[unprintable error]'; }
193
+ return J.stringify([name.slice(0, cfg.nameMax), message.slice(0, cfg.textMax), stack.slice(0, cfg.textMax)]);
194
+ }
195
+ var timers = new M(), nextTimer = 1;
196
+ function timer(repeat) {
197
+ return function (fn, ms) {
198
+ if (typeof fn !== 'function') throw new TypeError('the first argument must be a function');
199
+ if (timers.size >= cfg.maxTimers) throw new RangeError('too many timers');
200
+ var id = nextTimer++;
201
+ ms = +ms; if (!(ms >= 0)) ms = 0; if (ms > 2147483647) ms = 2147483647;
202
+ if (repeat && ms < 1) ms = 1;
203
+ timers.set(id, { fn: fn, args: Array.prototype.slice.call(arguments, 2), ms: ms, repeat: repeat });
204
+ hostTimer(id, ms);
205
+ return id;
206
+ };
207
+ }
208
+ function clear(id) { if (timers.delete(id)) hostClear(id); }
209
+ function fire(id) {
210
+ var t = timers.get(id);
211
+ if (!t) return;
212
+ if (t.repeat) hostTimer(id, t.ms); else timers.delete(id);
213
+ R.apply(t.fn, undefined, t.args);
214
+ }
215
+ g.setTimeout = timer(false); g.setInterval = timer(true);
216
+ g.clearTimeout = clear; g.clearInterval = clear;
217
+ g.queueMicrotask = function (fn) { P.resolve().then(fn); };
218
+ if (cfg.ops.length) {
219
+ var fs = {};
220
+ cfg.ops.forEach(function (op) {
221
+ fs[op] = function () {
222
+ var text;
223
+ try { text = J.stringify(Array.prototype.slice.call(arguments)); } catch (e) { return P.reject(new TypeError('fs.' + op + ': the arguments must be plain data')); }
224
+ if (text.length > cfg.maxCall) return P.reject(new RangeError('fs.' + op + ': the arguments are too large'));
225
+ return hostCall(op, text).then(function (r) { return r === '' ? undefined : J.parse(r); });
226
+ };
227
+ });
228
+ g.fs = fs;
229
+ }
230
+ var loaded = new M();
231
+ function requireFrom(base) {
232
+ return function require(spec) {
233
+ var path = hostResolve(base, S(spec)), mod = loaded.get(path), made;
234
+ if (mod) return mod.exports;
235
+ mod = { exports: {} };
236
+ loaded.set(path, mod);
237
+ made = hostCompile(path);
238
+ if (typeof made === 'string') mod.exports = J.parse(made);
239
+ else made.call(mod.exports, mod, mod.exports, requireFrom(path), path, path.slice(0, Math.max(1, path.lastIndexOf('/'))));
240
+ return mod.exports;
241
+ };
242
+ }
243
+ g.require = requireFrom(cfg.filename);
244
+ return { fire: fire, serialize: serialize, describe: describe };
245
+ })`;
246
+ var BOOTSTRAP_FILE = "<sandbox>";
247
+ var REFUSED = "refused:";
248
+ var WASM_PAGE = 65536;
249
+ var newBoundedModule = (lib, limitBytes) => {
250
+ const wasm = globalThis.WebAssembly;
251
+ const wasmMemory = new wasm.Memory({
252
+ initial: SANDBOX_FLOORS.memoryLimitBytes / WASM_PAGE,
253
+ maximum: Math.floor(limitBytes / WASM_PAGE)
254
+ });
255
+ return lib.newQuickJSWASMModuleFromVariant(lib.newVariant(lib.RELEASE_SYNC, { wasmMemory }));
256
+ };
257
+ var runGuest = async (lib, request, options = {}) => {
258
+ const { limits } = request;
259
+ const filename = request.filename ?? "/main.js";
260
+ const modules = request.modules;
261
+ const hostOps = options.hostCall ? request.hostOps ?? [] : [];
262
+ const mod = await newBoundedModule(lib, limits.memoryLimitBytes);
263
+ const rt = mod.newRuntime();
264
+ rt.setMemoryLimit(limits.memoryLimitBytes);
265
+ rt.setMaxStackSize(GUEST_STACK_BYTES);
266
+ const ctx = rt.newContext();
267
+ return new Promise((resolve) => {
268
+ const startedAt = Date.now();
269
+ let finished = false;
270
+ let interrupted = false;
271
+ let cpuMs = 0;
272
+ let entryAt = 0;
273
+ let waitMs = 0;
274
+ let waitingSince = 0;
275
+ let pendingCalls = 0;
276
+ let hostCalls = 0;
277
+ let watchdog;
278
+ const hostTimers = /* @__PURE__ */ new Map();
279
+ const out = [];
280
+ let outChars = 0;
281
+ let truncated = false;
282
+ let internals;
283
+ let main;
284
+ let mainKind = "value";
285
+ const cpuUsed = () => cpuMs + (entryAt ? Date.now() - entryAt : 0);
286
+ const wallUsed = () => Date.now() - startedAt - waitMs - (waitingSince ? Date.now() - waitingSince : 0);
287
+ const overTime = () => cpuUsed() > limits.timeoutMs || pendingCalls === 0 && wallUsed() > limits.timeoutMs;
288
+ rt.setInterruptHandler(() => {
289
+ if (finished || overTime()) {
290
+ interrupted = true;
291
+ return true;
292
+ }
293
+ return false;
294
+ });
295
+ const finish = (error, result) => {
296
+ if (finished) {
297
+ return;
298
+ }
299
+ finished = true;
300
+ if (watchdog !== void 0) {
301
+ clearTimeout(watchdog);
302
+ }
303
+ for (const t of hostTimers.values()) {
304
+ clearTimeout(t);
305
+ }
306
+ hostTimers.clear();
307
+ resolve({
308
+ ok: !error,
309
+ stdout: out.join(""),
310
+ ...result ? { result: result.value } : {},
311
+ ...error ? { error } : {},
312
+ truncated,
313
+ durationMs: Date.now() - startedAt
314
+ });
315
+ };
316
+ const timedOut = () => ({
317
+ name: "TimeoutError",
318
+ message: `the run was stopped after ${limits.timeoutMs} ms (timeoutMs)`
319
+ });
320
+ const describe = (handle) => {
321
+ if (interrupted) {
322
+ return timedOut();
323
+ }
324
+ try {
325
+ let raw;
326
+ if (internals) {
327
+ const r = ctx.callFunction(internals.describe, ctx.undefined, handle);
328
+ raw = r.error ? void 0 : JSON.parse(ctx.getString(r.value));
329
+ }
330
+ if (!Array.isArray(raw)) {
331
+ const d = ctx.dump(handle);
332
+ raw = [d?.name ?? "Error", d?.message ?? String(d), d?.stack ?? ""];
333
+ }
334
+ const [name, message, stack] = raw;
335
+ const frames = String(stack ?? "").split("\n").filter((line) => line.trim() && !line.includes(BOOTSTRAP_FILE)).join("\n");
336
+ return {
337
+ name: clip(String(name || "Error"), ERROR_NAME_CHARS),
338
+ message: clip(String(message ?? ""), ERROR_TEXT_CHARS),
339
+ ...frames ? { stack: clip(frames, ERROR_TEXT_CHARS) } : {}
340
+ };
341
+ } catch {
342
+ return interrupted ? timedOut() : { name: "Error", message: "the program threw an error that could not be read" };
343
+ }
344
+ };
345
+ const engineFailure = (err) => {
346
+ if (interrupted) {
347
+ finish(timedOut());
348
+ } else if (err instanceof RangeError) {
349
+ finish({ name: "RangeError", message: "Maximum call stack size exceeded" });
350
+ } else {
351
+ finish({ name: "SandboxError", message: clip(errorText(err), ERROR_TEXT_CHARS) });
352
+ }
353
+ };
354
+ const armWatchdog = () => {
355
+ if (watchdog !== void 0) {
356
+ clearTimeout(watchdog);
357
+ watchdog = void 0;
358
+ }
359
+ if (finished || pendingCalls > 0) {
360
+ return;
361
+ }
362
+ watchdog = setTimeout(
363
+ () => {
364
+ watchdog = void 0;
365
+ if (overTime()) {
366
+ interrupted = true;
367
+ finish(timedOut());
368
+ } else {
369
+ armWatchdog();
370
+ }
371
+ },
372
+ Math.max(1, limits.timeoutMs - wallUsed() + 1)
373
+ );
374
+ };
375
+ const settle = () => {
376
+ while (!finished) {
377
+ if (interrupted) {
378
+ finish(timedOut());
379
+ return;
380
+ }
381
+ const state = ctx.getPromiseState(main);
382
+ if (state.type === "rejected") {
383
+ finish(describe(state.error));
384
+ return;
385
+ }
386
+ if (state.type === "pending") {
387
+ if (hostTimers.size === 0 && pendingCalls === 0) {
388
+ finish({
389
+ name: "Error",
390
+ message: "the program awaits a promise that can never settle (nothing is left to run)"
391
+ });
392
+ }
393
+ return;
394
+ }
395
+ if (mainKind !== "value") {
396
+ main = ctx.getProp(state.value, mainKind === "script" ? "value" : "default");
397
+ mainKind = "value";
398
+ continue;
399
+ }
400
+ if (!state.notAPromise) {
401
+ main = state.value;
402
+ continue;
403
+ }
404
+ if (hostTimers.size > 0 || pendingCalls > 0) {
405
+ return;
406
+ }
407
+ const max = Math.max(200, limits.maxOutputChars - outChars);
408
+ const r = ctx.callFunction(
409
+ internals.serialize,
410
+ ctx.undefined,
411
+ state.value,
412
+ ctx.newNumber(max)
413
+ );
414
+ if (r.error) {
415
+ finish(describe(r.error));
416
+ return;
417
+ }
418
+ const text = ctx.getString(r.value);
419
+ if (text === "") {
420
+ finish();
421
+ } else if (text[0] === "T") {
422
+ truncated = true;
423
+ finish(void 0, { value: clip(text.slice(1), max) });
424
+ } else {
425
+ truncated ||= text[0] === "C";
426
+ finish(void 0, { value: JSON.parse(text.slice(1)) });
427
+ }
428
+ return;
429
+ }
430
+ };
431
+ const enter = (fn) => {
432
+ if (finished) {
433
+ return;
434
+ }
435
+ entryAt = Date.now();
436
+ try {
437
+ fn();
438
+ while (!finished && !interrupted) {
439
+ const jobs = rt.executePendingJobs();
440
+ if (jobs.error) {
441
+ const error = describe(jobs.error);
442
+ cpuMs += Date.now() - entryAt;
443
+ entryAt = 0;
444
+ finish(error);
445
+ return;
446
+ }
447
+ if (!rt.hasPendingJob()) {
448
+ break;
449
+ }
450
+ }
451
+ cpuMs += Date.now() - entryAt;
452
+ entryAt = 0;
453
+ settle();
454
+ } catch (err) {
455
+ cpuMs += Date.now() - entryAt;
456
+ entryAt = 0;
457
+ engineFailure(err);
458
+ }
459
+ };
460
+ const guestError = (name, message) => Object.assign(new Error(message), { name });
461
+ const host = ctx.newObject();
462
+ const expose = (name, fn) => {
463
+ ctx.setProp(host, name, ctx.newFunction(name, fn));
464
+ };
465
+ expose("log", (levelHandle, textHandle) => {
466
+ if (outChars >= limits.maxOutputChars) {
467
+ truncated = true;
468
+ return;
469
+ }
470
+ const level = ctx.getString(levelHandle);
471
+ let line = `${level ? `[${level}] ` : ""}${ctx.getString(textHandle)}
472
+ `;
473
+ if (outChars + line.length > limits.maxOutputChars) {
474
+ line = line.slice(0, limits.maxOutputChars - outChars);
475
+ truncated = true;
476
+ }
477
+ out.push(line);
478
+ outChars += line.length;
479
+ });
480
+ expose("timer", (idHandle, msHandle) => {
481
+ const id = ctx.getNumber(idHandle);
482
+ const ms = ctx.getNumber(msHandle);
483
+ const previous = hostTimers.get(id);
484
+ if (previous !== void 0) {
485
+ clearTimeout(previous);
486
+ } else if (hostTimers.size >= MAX_TIMERS) {
487
+ throw guestError("RangeError", "too many timers");
488
+ }
489
+ hostTimers.set(
490
+ id,
491
+ setTimeout(
492
+ () => {
493
+ hostTimers.delete(id);
494
+ enter(() => {
495
+ const r = ctx.callFunction(internals.fire, ctx.undefined, ctx.newNumber(id));
496
+ if (r.error) {
497
+ finish(describe(r.error));
498
+ }
499
+ });
500
+ },
501
+ // A timer past the deadline never fires: the watchdog ends the run first.
502
+ Math.min(Math.max(0, ms), limits.timeoutMs + 1)
503
+ )
504
+ );
505
+ });
506
+ expose("clear", (idHandle) => {
507
+ const id = ctx.getNumber(idHandle);
508
+ const t = hostTimers.get(id);
509
+ if (t !== void 0) {
510
+ clearTimeout(t);
511
+ hostTimers.delete(id);
512
+ }
513
+ });
514
+ expose("call", (opHandle, argsHandle) => {
515
+ const op = ctx.getString(opHandle);
516
+ if (!hostOps.includes(op) || !options.hostCall) {
517
+ throw guestError("Error", `fs.${clip(op, 40)} is not available in this sandbox`);
518
+ }
519
+ if ((hostCalls += 1) > SANDBOX_MAX_HOST_CALLS) {
520
+ throw guestError(
521
+ "RangeError",
522
+ `too many file operations in one run (limit ${SANDBOX_MAX_HOST_CALLS})`
523
+ );
524
+ }
525
+ const args = JSON.parse(ctx.getString(argsHandle));
526
+ const deferred = ctx.newPromise();
527
+ if (pendingCalls === 0) {
528
+ waitingSince = Date.now();
529
+ if (watchdog !== void 0) {
530
+ clearTimeout(watchdog);
531
+ watchdog = void 0;
532
+ }
533
+ }
534
+ pendingCalls += 1;
535
+ const done = (settleGuest) => {
536
+ pendingCalls -= 1;
537
+ if (pendingCalls === 0) {
538
+ waitMs += Date.now() - waitingSince;
539
+ waitingSince = 0;
540
+ }
541
+ if (finished) {
542
+ return;
543
+ }
544
+ armWatchdog();
545
+ enter(settleGuest);
546
+ };
547
+ options.hostCall(op, args).then(
548
+ (value) => done(() => {
549
+ const text = value === void 0 ? "" : JSON.stringify(value);
550
+ deferred.resolve(ctx.newString(text ?? ""));
551
+ }),
552
+ (err) => done(() => {
553
+ deferred.reject(
554
+ ctx.newError({
555
+ name: "Error",
556
+ message: clip(err instanceof Error ? err.message : String(err), ERROR_TEXT_CHARS)
557
+ })
558
+ );
559
+ })
560
+ );
561
+ return deferred.handle;
562
+ });
563
+ const load = (path) => {
564
+ if (!modules) {
565
+ throw guestError("Error", `Cannot load "${clip(path, 200)}": this sandbox has no files`);
566
+ }
567
+ if (!Object.hasOwn(modules, path)) {
568
+ throw guestError(
569
+ "Error",
570
+ `Cannot load "${clip(path, 200)}": no such file in the workspace (a module must exist before the run and be named by a literal path)`
571
+ );
572
+ }
573
+ return modules[path];
574
+ };
575
+ const resolvePath = (base, spec) => {
576
+ try {
577
+ return resolveModulePath(base, spec);
578
+ } catch (err) {
579
+ throw guestError("Error", err instanceof Error ? err.message : String(err));
580
+ }
581
+ };
582
+ expose(
583
+ "resolve",
584
+ (baseHandle, specHandle) => ctx.newString(
585
+ resolvePath(ctx.getString(baseHandle), ctx.getString(specHandle))
586
+ )
587
+ );
588
+ expose("compile", (pathHandle) => {
589
+ const path = ctx.getString(pathHandle);
590
+ const source = load(path);
591
+ if (path.toLowerCase().endsWith(".json")) {
592
+ return ctx.newString(source);
593
+ }
594
+ const r = ctx.evalCode(
595
+ `(function (module, exports, require, __filename, __dirname) {${source}
596
+ })`,
597
+ path
598
+ );
599
+ if (r.error) {
600
+ return { error: r.error };
601
+ }
602
+ return r.value;
603
+ });
604
+ rt.setModuleLoader(
605
+ (path) => {
606
+ try {
607
+ if (path.startsWith(REFUSED)) {
608
+ throw new Error(path.slice(REFUSED.length));
609
+ }
610
+ const source = load(path);
611
+ return path.toLowerCase().endsWith(".json") ? `export default JSON.parse(${JSON.stringify(source)})` : source;
612
+ } catch (err) {
613
+ return { error: err };
614
+ }
615
+ },
616
+ (base, spec) => {
617
+ try {
618
+ return resolveModulePath(base, spec);
619
+ } catch (err) {
620
+ return `${REFUSED}${err instanceof Error ? err.message : String(err)}`;
621
+ }
622
+ }
623
+ );
624
+ try {
625
+ const boot = ctx.evalCode(BOOTSTRAP, BOOTSTRAP_FILE);
626
+ if (boot.error) {
627
+ finish({ name: "SandboxError", message: "the sandbox runtime failed to start" });
628
+ return;
629
+ }
630
+ const made = ctx.callFunction(
631
+ boot.value,
632
+ ctx.undefined,
633
+ host,
634
+ ctx.evalCode(
635
+ `(${JSON.stringify({
636
+ max: limits.maxOutputChars,
637
+ nameMax: ERROR_NAME_CHARS,
638
+ textMax: ERROR_TEXT_CHARS,
639
+ maxTimers: MAX_TIMERS,
640
+ maxCall: SANDBOX_MAX_FILE_CHARS + 2e3,
641
+ ops: hostOps,
642
+ filename
643
+ })})`,
644
+ BOOTSTRAP_FILE
645
+ ).unwrap()
646
+ );
647
+ if (made.error) {
648
+ finish({ name: "SandboxError", message: "the sandbox runtime failed to start" });
649
+ return;
650
+ }
651
+ internals = {
652
+ fire: ctx.getProp(made.value, "fire"),
653
+ serialize: ctx.getProp(made.value, "serialize"),
654
+ describe: ctx.getProp(made.value, "describe")
655
+ };
656
+ } catch (err) {
657
+ engineFailure(err);
658
+ return;
659
+ }
660
+ options.onStart?.();
661
+ armWatchdog();
662
+ enter(() => {
663
+ let evaluated = ctx.evalCode(request.code, filename, EVAL_SCRIPT_ASYNC);
664
+ mainKind = "script";
665
+ if (evaluated.error && !interrupted && looksLikeModule(request.code)) {
666
+ evaluated = ctx.evalCode(request.code, filename, { type: "module" });
667
+ mainKind = "module";
668
+ }
669
+ if (evaluated.error) {
670
+ finish(describe(evaluated.error));
671
+ return;
672
+ }
673
+ main = evaluated.value;
674
+ });
675
+ });
676
+ };
677
+ var serveSandbox = (port, loadLib) => {
678
+ const waiting = /* @__PURE__ */ new Map();
679
+ let seq = 0;
680
+ let busy = false;
681
+ const run = async (request) => {
682
+ let lib;
683
+ try {
684
+ lib = await loadLib();
685
+ } catch (err) {
686
+ port.post({ type: "failed", code: "peer-missing", message: errorText(err) });
687
+ return;
688
+ }
689
+ try {
690
+ const result = await runGuest(lib, request, {
691
+ onStart: () => port.post({ type: "started" }),
692
+ hostCall: (op, args) => new Promise((resolve, reject) => {
693
+ const id = seq += 1;
694
+ waiting.set(id, { resolve, reject });
695
+ port.post({ type: "host-call", id, op, args });
696
+ })
697
+ });
698
+ port.post({ type: "done", result });
699
+ } catch (err) {
700
+ port.post({ type: "failed", code: "engine", message: errorText(err) });
701
+ }
702
+ };
703
+ port.listen((message) => {
704
+ const m = message;
705
+ if (m?.type === "run" && !busy) {
706
+ busy = true;
707
+ void run(m.request);
708
+ } else if (m?.type === "host-result") {
709
+ const w = waiting.get(m.id);
710
+ if (w) {
711
+ waiting.delete(m.id);
712
+ if (m.ok) {
713
+ w.resolve(m.value);
714
+ } else {
715
+ w.reject(new Error(typeof m.error === "string" ? m.error : "the file operation failed"));
716
+ }
717
+ }
718
+ }
719
+ });
720
+ };
721
+
722
+ // src/sandbox/worker.ts
723
+ var serveSandboxWorker = (opts = {}) => {
724
+ const scope = opts.scope ?? globalThis;
725
+ serveSandbox(
726
+ {
727
+ post: (message) => scope.postMessage(message),
728
+ listen: (onMessage) => {
729
+ scope.addEventListener("message", (ev) => onMessage(ev.data));
730
+ scope.start?.();
731
+ }
732
+ },
733
+ async () => await (opts.engine ? opts.engine() : import("quickjs-emscripten"))
734
+ );
735
+ };
736
+ var inWorker = () => {
737
+ const g = globalThis;
738
+ return typeof g.WorkerGlobalScope !== "undefined" && typeof g.document === "undefined";
739
+ };
740
+ if (inWorker()) serveSandboxWorker();
741
+ // Annotate the CommonJS export names for ESM import in node:
742
+ 0 && (module.exports = {
743
+ serveSandboxWorker
744
+ });
745
+ //# sourceMappingURL=sandbox-worker.cjs.map