@enclave-vm/core 2.19.1 → 2.19.2
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/README.md +262 -105
- package/adapters/worker-pool/config.d.ts +15 -5
- package/adapters/worker-pool/protocol.d.ts +27 -1
- package/adapters/worker-pool/worker-pool-adapter.d.ts +24 -0
- package/adapters/worker-pool/worker-slot.d.ts +35 -6
- package/async-context.d.ts +34 -0
- package/babel/babel-wrapper.d.ts +21 -12
- package/babel/multi-file-transform.d.ts +3 -0
- package/babel/text-scan.d.ts +54 -0
- package/deadline-guard.d.ts +16 -0
- package/dynamic-import.d.ts +25 -0
- package/enclave-options.d.ts +62 -0
- package/enclave.d.ts +31 -7
- package/esm/index.mjs +4649 -774
- package/esm/worker.mjs +1136 -134
- package/execution-deadline.d.ts +6 -0
- package/global-function-gate.d.ts +34 -1
- package/index.d.ts +3 -3
- package/index.js +4690 -815
- package/interpreter/interpreter.d.ts +204 -6
- package/memory-tracker.d.ts +7 -0
- package/package.json +3 -3
- package/realm-airlock.d.ts +6 -1
- package/realm-memory.d.ts +89 -0
- package/realm-stack.d.ts +25 -0
- package/safe-runtime.d.ts +2 -0
- package/sandbox-rejections.d.ts +3 -1
- package/scoring/feature-extractor.d.ts +52 -1
- package/scoring/index.d.ts +2 -1
- package/scoring/scorers/index.d.ts +2 -1
- package/scoring/scorers/local-llm.scorer.d.ts +9 -3
- package/scoring/scorers/progressive.scorer.d.ts +28 -1
- package/scoring/scorers/rule-based.scorer.d.ts +11 -1
- package/scoring/types.d.ts +36 -8
- package/secure-proxy.d.ts +17 -3
- package/session/session.d.ts +8 -1
- package/session-types.d.ts +6 -4
- package/sidecar/index.d.ts +1 -1
- package/sidecar/reference-config.d.ts +18 -1
- package/sidecar/reference-resolver.d.ts +19 -1
- package/sidecar/reference-sidecar.d.ts +37 -0
- package/src/adapters/worker-pool/package.json +3 -3
- package/src/adapters/worker-pool/worker-script.js +2250 -428
- package/thrown-value.d.ts +59 -0
- package/types.d.ts +75 -19
- package/value-sanitizer.d.ts +6 -1
- package/worker.js +1136 -134
package/worker.js
CHANGED
|
@@ -155,11 +155,65 @@ function readProperty(object, key) {
|
|
|
155
155
|
if (key === "__proto__" || BLOCKED_KEYS.has(key)) throw new InterpreterError(`Forbidden property access: ${key}`);
|
|
156
156
|
return object[key];
|
|
157
157
|
}
|
|
158
|
+
var ENGINE_CALLED_KEYS = /* @__PURE__ */ new Set(["then", "toString", "valueOf", "toJSON", "toLocaleString", "toISOString"]);
|
|
159
|
+
function isEngineCalledKey(key) {
|
|
160
|
+
return ENGINE_CALLED_KEYS.has(key);
|
|
161
|
+
}
|
|
162
|
+
function assertStorable(target, key, value) {
|
|
163
|
+
if (typeof value !== "function") return;
|
|
164
|
+
if (ENGINE_CALLED_KEYS.has(key) || key === "join" && Array.isArray(target)) {
|
|
165
|
+
throw new InterpreterError(
|
|
166
|
+
`A function cannot be stored under '${key}': the sandbox runs a function only where the script calls it`
|
|
167
|
+
);
|
|
168
|
+
}
|
|
169
|
+
}
|
|
158
170
|
var MAX_STRING_OP_LENGTH = 1e6;
|
|
159
171
|
var MAX_JOIN_LENGTH = 16e6;
|
|
160
172
|
var MAX_TEXT_NESTING = 64;
|
|
161
173
|
var MAX_TEXT_ITEMS = 8e6;
|
|
162
174
|
var MAX_ARRAY_LENGTH = 1e6;
|
|
175
|
+
var CLOCK_CHECK_STEPS = 256;
|
|
176
|
+
var WORK_PER_STEP = 16384;
|
|
177
|
+
var WRITE_WORK = 8;
|
|
178
|
+
var LOCALE_COMPARE_WORK = 64;
|
|
179
|
+
var SEARCH_PIECE_WORK = 2 ** 20;
|
|
180
|
+
var LONG_SEARCH_TEXT = 64;
|
|
181
|
+
var MAX_CALL_WORK = 2 ** 33;
|
|
182
|
+
var MAX_BIGINT_BITS = 2 ** 20;
|
|
183
|
+
var MAX_BIGINT_DIGITS = Math.ceil(MAX_BIGINT_BITS * Math.log10(2)) + 1;
|
|
184
|
+
var WORD_BITS = 64;
|
|
185
|
+
var BIGINT_WORK = 64;
|
|
186
|
+
var BIGINT_TEXT_WORK = 1024;
|
|
187
|
+
var COMPARISONS = /* @__PURE__ */ new Set(["==", "!=", "<", "<=", ">", ">="]);
|
|
188
|
+
function bitsOf(value) {
|
|
189
|
+
const hex = value.toString(16);
|
|
190
|
+
const start = value < 0n ? 1 : 0;
|
|
191
|
+
return (hex.length - start - 1) * 4 + (32 - Math.clz32(Number.parseInt(hex[start], 16)));
|
|
192
|
+
}
|
|
193
|
+
function bigIntTooLarge() {
|
|
194
|
+
return new InterpreterError(`A BigInt cannot be larger than ${MAX_BIGINT_BITS} bits`);
|
|
195
|
+
}
|
|
196
|
+
var CONSTANT_STRING_METHODS = /* @__PURE__ */ new Set([
|
|
197
|
+
"at",
|
|
198
|
+
"charAt",
|
|
199
|
+
"charCodeAt",
|
|
200
|
+
"codePointAt",
|
|
201
|
+
"valueOf",
|
|
202
|
+
"toString",
|
|
203
|
+
"slice",
|
|
204
|
+
"substring",
|
|
205
|
+
"substr",
|
|
206
|
+
"concat",
|
|
207
|
+
"startsWith",
|
|
208
|
+
"endsWith",
|
|
209
|
+
"padStart",
|
|
210
|
+
"padEnd",
|
|
211
|
+
"repeat"
|
|
212
|
+
]);
|
|
213
|
+
var CONSTANT_ARRAY_METHODS = /* @__PURE__ */ new Set(["at", "push", "pop", "slice", "keys", "values", "entries"]);
|
|
214
|
+
var TEXT_SEARCHES = /* @__PURE__ */ new Set(["indexOf", "lastIndexOf", "includes", "split", "replace", "replaceAll"]);
|
|
215
|
+
var ARRAY_SEARCHES = /* @__PURE__ */ new Set(["indexOf", "lastIndexOf", "includes"]);
|
|
216
|
+
var NOT_SEARCHED = /* @__PURE__ */ Symbol("not searched");
|
|
163
217
|
var HIGHER_ORDER_ARRAY_METHODS = /* @__PURE__ */ new Set([
|
|
164
218
|
"map",
|
|
165
219
|
"flatMap",
|
|
@@ -180,10 +234,12 @@ var FunctionProtoCall = Function.prototype.call;
|
|
|
180
234
|
var FunctionProtoApply = Function.prototype.apply;
|
|
181
235
|
var FunctionProtoBind = Function.prototype.bind;
|
|
182
236
|
var FunctionProtoToString = Function.prototype.toString;
|
|
237
|
+
var ArrayProtoToLocaleString = Array.prototype.toLocaleString;
|
|
238
|
+
var StringProtoIndexOf = String.prototype.indexOf;
|
|
183
239
|
function methodsOf(prototype) {
|
|
184
240
|
const methods = /* @__PURE__ */ new Map();
|
|
185
241
|
for (const name of Object.getOwnPropertyNames(prototype)) {
|
|
186
|
-
if (name
|
|
242
|
+
if (isBlockedKey(name)) continue;
|
|
187
243
|
const descriptor = Object.getOwnPropertyDescriptor(prototype, name);
|
|
188
244
|
if (descriptor && typeof descriptor.value === "function") methods.set(descriptor.value, name);
|
|
189
245
|
}
|
|
@@ -191,6 +247,34 @@ function methodsOf(prototype) {
|
|
|
191
247
|
}
|
|
192
248
|
var ARRAY_METHODS = methodsOf(Array.prototype);
|
|
193
249
|
var STRING_METHODS = methodsOf(String.prototype);
|
|
250
|
+
var OTHER_METHODS = (() => {
|
|
251
|
+
const prototypes = [
|
|
252
|
+
["Number", Number.prototype],
|
|
253
|
+
["Boolean", Boolean.prototype],
|
|
254
|
+
["BigInt", BigInt.prototype],
|
|
255
|
+
["Date", Date.prototype],
|
|
256
|
+
["Object", Object.prototype]
|
|
257
|
+
];
|
|
258
|
+
const methods = /* @__PURE__ */ new Map();
|
|
259
|
+
for (const [kind, prototype] of prototypes) {
|
|
260
|
+
for (const [method, name] of methodsOf(prototype)) {
|
|
261
|
+
if (!methods.has(method)) methods.set(method, { kind, name });
|
|
262
|
+
}
|
|
263
|
+
}
|
|
264
|
+
return methods;
|
|
265
|
+
})();
|
|
266
|
+
var RECEIVERS = {
|
|
267
|
+
Number: { noun: "a number", accepts: (receiver) => typeof receiver === "number" },
|
|
268
|
+
Boolean: { noun: "a boolean", accepts: (receiver) => typeof receiver === "boolean" },
|
|
269
|
+
BigInt: { noun: "a BigInt", accepts: (receiver) => typeof receiver === "bigint" },
|
|
270
|
+
Date: { noun: "a date", accepts: (receiver) => receiver instanceof Date },
|
|
271
|
+
Object: {
|
|
272
|
+
noun: "an object",
|
|
273
|
+
accepts: (receiver, name) => name !== "valueOf" || receiver !== null && (typeof receiver === "object" || typeof receiver === "function")
|
|
274
|
+
}
|
|
275
|
+
};
|
|
276
|
+
var ARRAY_ITERATOR_NEXT = Object.getPrototypeOf([][Symbol.iterator]()).next;
|
|
277
|
+
var LIBRARY_FUNCTIONS = /* @__PURE__ */ new WeakSet();
|
|
194
278
|
var ARRAY_DATA_ARGUMENTS = /* @__PURE__ */ new Map([
|
|
195
279
|
["push", () => true],
|
|
196
280
|
["unshift", () => true],
|
|
@@ -215,13 +299,18 @@ function convertsArguments(fn, count) {
|
|
|
215
299
|
CONVERTED_ARGUMENTS.set(fn, count);
|
|
216
300
|
return fn;
|
|
217
301
|
}
|
|
302
|
+
var ARGUMENT_CONVERSIONS = /* @__PURE__ */ new WeakMap();
|
|
303
|
+
function convertsBeforeCall(fn, convert) {
|
|
304
|
+
ARGUMENT_CONVERSIONS.set(fn, convert);
|
|
305
|
+
return fn;
|
|
306
|
+
}
|
|
218
307
|
var CALL_COSTS = /* @__PURE__ */ new WeakMap();
|
|
219
308
|
function chargedBeforeCall(fn, cost) {
|
|
220
309
|
CALL_COSTS.set(fn, cost);
|
|
221
310
|
return fn;
|
|
222
311
|
}
|
|
223
312
|
function newTextMeasure() {
|
|
224
|
-
return { length: 0, items: 0, active: /* @__PURE__ */ new Set(), functions: /* @__PURE__ */ new Map() };
|
|
313
|
+
return { length: 0, items: 0, active: /* @__PURE__ */ new Set(), functions: /* @__PURE__ */ new Map(), work: 0 };
|
|
225
314
|
}
|
|
226
315
|
function scalarTextLength(item, measure) {
|
|
227
316
|
switch (typeof item) {
|
|
@@ -229,8 +318,11 @@ function scalarTextLength(item, measure) {
|
|
|
229
318
|
case "boolean":
|
|
230
319
|
return 32;
|
|
231
320
|
// also covers a number in the longest locale format
|
|
232
|
-
case "bigint":
|
|
233
|
-
|
|
321
|
+
case "bigint": {
|
|
322
|
+
const bits = bitsOf(item);
|
|
323
|
+
if (bits > WORD_BITS) measure.work += bits * BIGINT_TEXT_WORK;
|
|
324
|
+
return Math.ceil(bits * Math.log10(2)) + 2;
|
|
325
|
+
}
|
|
234
326
|
case "function": {
|
|
235
327
|
let length = measure.functions.get(item);
|
|
236
328
|
if (length === void 0) {
|
|
@@ -294,6 +386,7 @@ function assertArrayTextWithinLimit(...values) {
|
|
|
294
386
|
measureArrayText(value, 1, measure, 0);
|
|
295
387
|
if (measure.length > MAX_JOIN_LENGTH) throw new InterpreterError(TEXT_TOO_LONG);
|
|
296
388
|
}
|
|
389
|
+
return measure?.length ?? 0;
|
|
297
390
|
}
|
|
298
391
|
var StepLimitError = class extends Error {
|
|
299
392
|
constructor(limit) {
|
|
@@ -301,12 +394,24 @@ var StepLimitError = class extends Error {
|
|
|
301
394
|
this.name = "StepLimitError";
|
|
302
395
|
}
|
|
303
396
|
};
|
|
397
|
+
var DeadlineError = class extends Error {
|
|
398
|
+
constructor() {
|
|
399
|
+
super("Execution deadline exceeded");
|
|
400
|
+
this.name = "TimeoutError";
|
|
401
|
+
}
|
|
402
|
+
};
|
|
304
403
|
var InterpreterError = class extends Error {
|
|
305
404
|
constructor(message) {
|
|
306
405
|
super(message);
|
|
307
406
|
this.name = "InterpreterError";
|
|
308
407
|
}
|
|
309
408
|
};
|
|
409
|
+
var AccumulatedText = class {
|
|
410
|
+
constructor(value, owed) {
|
|
411
|
+
this.value = value;
|
|
412
|
+
this.owed = owed;
|
|
413
|
+
}
|
|
414
|
+
};
|
|
310
415
|
var ReturnSignal = class {
|
|
311
416
|
constructor(value) {
|
|
312
417
|
this.value = value;
|
|
@@ -327,12 +432,11 @@ function createScriptError(name, message, code) {
|
|
|
327
432
|
error["name"] = name;
|
|
328
433
|
error["message"] = message;
|
|
329
434
|
if (code !== void 0) error["code"] = code;
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
});
|
|
435
|
+
const toString = function toString2() {
|
|
436
|
+
return message ? `${name}: ${message}` : name;
|
|
437
|
+
};
|
|
438
|
+
LIBRARY_FUNCTIONS.add(toString);
|
|
439
|
+
Object.defineProperty(error, "toString", { value: toString, enumerable: false });
|
|
336
440
|
SCRIPT_ERRORS.add(error);
|
|
337
441
|
return Object.freeze(error);
|
|
338
442
|
}
|
|
@@ -340,9 +444,10 @@ function isScriptError(value) {
|
|
|
340
444
|
return typeof value === "object" && value !== null && SCRIPT_ERRORS.has(value);
|
|
341
445
|
}
|
|
342
446
|
var Scope = class _Scope {
|
|
343
|
-
constructor(parent, depth) {
|
|
447
|
+
constructor(parent, depth, settle) {
|
|
344
448
|
this.parent = parent;
|
|
345
449
|
this.depth = depth ?? parent?.depth ?? 0;
|
|
450
|
+
this.settle = settle ?? parent?.settle ?? (() => void 0);
|
|
346
451
|
}
|
|
347
452
|
vars = /* @__PURE__ */ new Map();
|
|
348
453
|
/**
|
|
@@ -350,39 +455,69 @@ var Scope = class _Scope {
|
|
|
350
455
|
* function one more than where it was called from. A block inside has the depth around it.
|
|
351
456
|
*/
|
|
352
457
|
depth;
|
|
458
|
+
/** Charges what is still owed for the value of a variable that is read */
|
|
459
|
+
settle;
|
|
460
|
+
/**
|
|
461
|
+
* In the body of a callback that `reduce` called with a text: the name of the parameter that
|
|
462
|
+
* holds it. A block inside has the name around it; a function inside does not.
|
|
463
|
+
*/
|
|
464
|
+
accumulator;
|
|
353
465
|
child() {
|
|
354
|
-
|
|
466
|
+
const scope = new _Scope(this);
|
|
467
|
+
scope.accumulator = this.accumulator;
|
|
468
|
+
return scope;
|
|
355
469
|
}
|
|
356
470
|
/** The scope of one call of a function defined in this scope, running `depth` calls deep. */
|
|
357
471
|
activation(depth) {
|
|
358
472
|
return new _Scope(this, depth);
|
|
359
473
|
}
|
|
360
474
|
declare(name, value, mutable) {
|
|
361
|
-
this.vars.set(name, { value, mutable });
|
|
475
|
+
this.vars.set(name, { value, mutable, owed: 0 });
|
|
362
476
|
}
|
|
363
477
|
has(name) {
|
|
364
478
|
return this.vars.has(name) || (this.parent?.has(name) ?? false);
|
|
365
479
|
}
|
|
480
|
+
/**
|
|
481
|
+
* The variable as it is stored, or nothing when there is none. For the few readers that
|
|
482
|
+
* neither keep its value nor look into a text (its length, whether it is empty, appending to
|
|
483
|
+
* it): everything else reads through {@link get}.
|
|
484
|
+
*/
|
|
485
|
+
slot(name) {
|
|
486
|
+
return this.vars.get(name) ?? this.parent?.slot(name);
|
|
487
|
+
}
|
|
488
|
+
/** The value of a variable, for any use: what is still owed for it is charged first. */
|
|
366
489
|
get(name) {
|
|
367
|
-
const slot = this.
|
|
368
|
-
if (slot)
|
|
369
|
-
if (
|
|
370
|
-
|
|
490
|
+
const slot = this.slot(name);
|
|
491
|
+
if (!slot) throw new InterpreterError(`'${name}' is not defined`);
|
|
492
|
+
if (slot.owed > 0) {
|
|
493
|
+
const owed = slot.owed;
|
|
494
|
+
slot.owed = 0;
|
|
495
|
+
this.settle(owed);
|
|
496
|
+
}
|
|
497
|
+
return slot.value;
|
|
371
498
|
}
|
|
372
499
|
set(name, value) {
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
}
|
|
379
|
-
if (
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
}
|
|
383
|
-
throw new InterpreterError(`'${name}' is not defined`);
|
|
500
|
+
this.append(name, value, 0);
|
|
501
|
+
}
|
|
502
|
+
/** Assign a variable a text that was appended to its value, with what a reader still owes for it. */
|
|
503
|
+
append(name, value, owed) {
|
|
504
|
+
const slot = this.slot(name);
|
|
505
|
+
if (!slot) throw new InterpreterError(`'${name}' is not defined`);
|
|
506
|
+
if (!slot.mutable) throw new InterpreterError(`Assignment to constant '${name}'`);
|
|
507
|
+
slot.value = value;
|
|
508
|
+
slot.owed = owed;
|
|
384
509
|
}
|
|
385
510
|
};
|
|
511
|
+
function appendedTo(name, node) {
|
|
512
|
+
const operands = [];
|
|
513
|
+
let first = node;
|
|
514
|
+
while (first.type === "BinaryExpression" && first.operator === "+") {
|
|
515
|
+
operands.push(first.right);
|
|
516
|
+
first = first.left;
|
|
517
|
+
}
|
|
518
|
+
if (operands.length === 0 || first.type !== "Identifier" || first.name !== name) return void 0;
|
|
519
|
+
return operands.reverse();
|
|
520
|
+
}
|
|
386
521
|
var DEFAULT_MAX_PENDING_CALLS = 4096;
|
|
387
522
|
function ignoreRejection2() {
|
|
388
523
|
}
|
|
@@ -391,6 +526,7 @@ var Interpreter = class {
|
|
|
391
526
|
this.options = options;
|
|
392
527
|
this.globals = options.globals;
|
|
393
528
|
this.maxPendingCalls = options.maxPendingCalls ?? DEFAULT_MAX_PENDING_CALLS;
|
|
529
|
+
this.provide(this.globals, 2);
|
|
394
530
|
}
|
|
395
531
|
steps = 0;
|
|
396
532
|
/** Calls that have not returned: the running ones and the ones waiting on an `await` */
|
|
@@ -406,16 +542,46 @@ var Interpreter = class {
|
|
|
406
542
|
callerDepth = 0;
|
|
407
543
|
maxPendingCalls;
|
|
408
544
|
globals;
|
|
409
|
-
/**
|
|
545
|
+
/**
|
|
546
|
+
* What is owed for the text `reduce` is handing to its callback, for that function to read as
|
|
547
|
+
* it starts (in the same synchronous step, like {@link callerDepth}); otherwise nothing.
|
|
548
|
+
*/
|
|
549
|
+
accumulatorOwed;
|
|
550
|
+
/** The step count at which the clock is read next */
|
|
551
|
+
nextClockCheck = CLOCK_CHECK_STEPS;
|
|
552
|
+
/** What built-ins worked through that has not made a full step yet (see {@link work}) */
|
|
553
|
+
workDone = 0;
|
|
554
|
+
/** The error that ended the run (step budget, deadline, abort, allocation budget); set once, never caught */
|
|
410
555
|
fatal;
|
|
411
556
|
interpretedFunctions = /* @__PURE__ */ new WeakSet();
|
|
557
|
+
/** The functions the host provides: the globals, their members, and what `bind` made of them */
|
|
558
|
+
provided = /* @__PURE__ */ new WeakSet();
|
|
412
559
|
errorCopies = /* @__PURE__ */ new WeakMap();
|
|
560
|
+
/** BigInt literals of the program that were found to be within the size a BigInt may have */
|
|
561
|
+
checkedLiterals = /* @__PURE__ */ new WeakSet();
|
|
562
|
+
/**
|
|
563
|
+
* Remember the functions among the properties of `holder`, `depth` levels down: a global
|
|
564
|
+
* (`parseInt`) or a member of one (`Math.max`, a method of a tool namespace). Read from the
|
|
565
|
+
* property itself, so that nothing of the host runs for it. An array holds data.
|
|
566
|
+
*/
|
|
567
|
+
provide(holder, depth) {
|
|
568
|
+
if (holder === null || typeof holder !== "object" && typeof holder !== "function" || Array.isArray(holder))
|
|
569
|
+
return;
|
|
570
|
+
for (const name of Object.getOwnPropertyNames(holder)) {
|
|
571
|
+
const descriptor = Object.getOwnPropertyDescriptor(holder, name);
|
|
572
|
+
if (!descriptor || !("value" in descriptor)) continue;
|
|
573
|
+
const value = descriptor.value;
|
|
574
|
+
if (typeof value === "function") this.provided.add(value);
|
|
575
|
+
if (depth > 1) this.provide(value, depth - 1);
|
|
576
|
+
}
|
|
577
|
+
}
|
|
413
578
|
/**
|
|
414
579
|
* Call a function for a script, with the checks that apply to a call the script writes itself.
|
|
415
580
|
* For a host helper that is handed a callback (`parallel(items, fn)`): `fn` may be a function
|
|
416
581
|
* of the script, or a built-in or host function the script passed along.
|
|
417
582
|
*/
|
|
418
583
|
call(fn, args) {
|
|
584
|
+
if (this.fatal !== void 0) throw this.fatal;
|
|
419
585
|
if (typeof fn !== "function") throw new InterpreterError("Attempted to call a non-function");
|
|
420
586
|
if (this.interpretedFunctions.has(fn)) return fn(...args);
|
|
421
587
|
return this.callFunction(fn, void 0, args, this.callerDepth);
|
|
@@ -425,7 +591,7 @@ var Interpreter = class {
|
|
|
425
591
|
return this.steps;
|
|
426
592
|
}
|
|
427
593
|
async run(program) {
|
|
428
|
-
const root = new Scope();
|
|
594
|
+
const root = new Scope(void 0, 0, (bytes) => this.charge(bytes));
|
|
429
595
|
for (const stmt of program.body) {
|
|
430
596
|
if (stmt.type === "FunctionDeclaration" && stmt.id) {
|
|
431
597
|
root.declare(stmt.id.name, this.makeFunction(stmt, root), false);
|
|
@@ -443,13 +609,23 @@ var Interpreter = class {
|
|
|
443
609
|
return last;
|
|
444
610
|
}
|
|
445
611
|
/**
|
|
446
|
-
* End the run from outside: whatever of the script is still going (a
|
|
447
|
-
*
|
|
448
|
-
* host calls this when the execution has returned, so that no
|
|
612
|
+
* End the run from outside: whatever of the script is still going (a callback waiting for a
|
|
613
|
+
* tool call, a run that timed out while it waited) stops at its next step or its next call,
|
|
614
|
+
* whichever comes first. The host calls this when the execution has returned, so that no
|
|
615
|
+
* script code runs and no host function is called after it.
|
|
449
616
|
*/
|
|
450
617
|
stop() {
|
|
451
618
|
if (this.fatal === void 0) this.fatal = new InterpreterError("Execution ended");
|
|
452
619
|
}
|
|
620
|
+
/**
|
|
621
|
+
* Charge an allocation that a runtime helper of the host made for the script (the helpers a
|
|
622
|
+
* transformed `+` or template literal calls). The budget is one budget wherever it is asked:
|
|
623
|
+
* a refusal ends the run here as it does for what the interpreter charges itself, and no
|
|
624
|
+
* `catch` or `finally` of the script runs after it.
|
|
625
|
+
*/
|
|
626
|
+
chargeAllocation(bytes) {
|
|
627
|
+
this.charge(bytes);
|
|
628
|
+
}
|
|
453
629
|
/** End the run with an error no `catch` of the script can stop. */
|
|
454
630
|
end(error) {
|
|
455
631
|
if (this.fatal === void 0) this.fatal = error;
|
|
@@ -459,6 +635,90 @@ var Interpreter = class {
|
|
|
459
635
|
if (this.fatal !== void 0) throw this.fatal;
|
|
460
636
|
if (this.options.signal?.aborted) this.end(new InterpreterError("Execution aborted"));
|
|
461
637
|
if (++this.steps > this.options.maxSteps) this.end(new StepLimitError(this.options.maxSteps));
|
|
638
|
+
if (this.steps >= this.nextClockCheck) this.checkClock();
|
|
639
|
+
}
|
|
640
|
+
/** End the run when its deadline has passed. */
|
|
641
|
+
checkClock() {
|
|
642
|
+
this.nextClockCheck = this.steps + CLOCK_CHECK_STEPS;
|
|
643
|
+
const deadline = this.options.deadline;
|
|
644
|
+
if (deadline !== void 0 && Date.now() >= deadline) this.end(new DeadlineError());
|
|
645
|
+
}
|
|
646
|
+
/**
|
|
647
|
+
* Count what a built-in works through for the script, in chars or items: the engine does it
|
|
648
|
+
* in one step of its own, however large the operands are. {@link WORK_PER_STEP} units are a
|
|
649
|
+
* step of the budget, and the clock is read whenever that adds a step.
|
|
650
|
+
*/
|
|
651
|
+
work(units) {
|
|
652
|
+
if (!(units > 0)) return;
|
|
653
|
+
this.workDone += units;
|
|
654
|
+
if (this.workDone < WORK_PER_STEP) return;
|
|
655
|
+
const steps = Math.floor(this.workDone / WORK_PER_STEP);
|
|
656
|
+
this.workDone -= steps * WORK_PER_STEP;
|
|
657
|
+
this.steps += steps;
|
|
658
|
+
if (this.steps > this.options.maxSteps) this.end(new StepLimitError(this.options.maxSteps));
|
|
659
|
+
this.checkClock();
|
|
660
|
+
}
|
|
661
|
+
/** {@link assertArrayTextWithinLimit}, and the text the arrays are written as counted as work. */
|
|
662
|
+
arrayOperands(...values) {
|
|
663
|
+
let measure;
|
|
664
|
+
for (const value of values) {
|
|
665
|
+
if (!Array.isArray(value)) continue;
|
|
666
|
+
measure ??= newTextMeasure();
|
|
667
|
+
measureArrayText(value, 1, measure, 0);
|
|
668
|
+
if (measure.length > MAX_JOIN_LENGTH) throw new InterpreterError(TEXT_TOO_LONG);
|
|
669
|
+
}
|
|
670
|
+
if (measure) this.work(measure.length * WRITE_WORK + measure.work);
|
|
671
|
+
}
|
|
672
|
+
/**
|
|
673
|
+
* Count a BigInt an operation made: it is held to the size a BigInt may have, and beyond the
|
|
674
|
+
* size of a number what it holds is charged to the budget and making it counts as work. Also
|
|
675
|
+
* for the runtime helper that adds for a transformed `+`.
|
|
676
|
+
*
|
|
677
|
+
* @throws InterpreterError when the value is larger than {@link MAX_BIGINT_BITS}
|
|
678
|
+
*/
|
|
679
|
+
countBigInt(value) {
|
|
680
|
+
const bits = bitsOf(value);
|
|
681
|
+
if (bits > MAX_BIGINT_BITS) throw bigIntTooLarge();
|
|
682
|
+
if (bits <= WORD_BITS) return;
|
|
683
|
+
this.work(bits * BIGINT_WORK);
|
|
684
|
+
this.charge(Math.ceil(bits / 8));
|
|
685
|
+
}
|
|
686
|
+
/** Count the work of writing a value as text, when it is a BigInt: the engine writes it in decimal. */
|
|
687
|
+
bigIntAsText(value) {
|
|
688
|
+
if (typeof value !== "bigint") return;
|
|
689
|
+
const bits = bitsOf(value);
|
|
690
|
+
if (bits > WORD_BITS) this.work(bits * BIGINT_TEXT_WORK);
|
|
691
|
+
}
|
|
692
|
+
/**
|
|
693
|
+
* What is checked before an operator is applied to a BigInt: the operations whose result can
|
|
694
|
+
* be far larger than their operands are refused from the operands, and what the engine reads
|
|
695
|
+
* to compare a BigInt with a text is bounded and counted.
|
|
696
|
+
*/
|
|
697
|
+
checkBigIntOperands(operator, left, right) {
|
|
698
|
+
if (typeof left === "bigint" && typeof right === "bigint") {
|
|
699
|
+
if (operator === "<<" || operator === ">>") {
|
|
700
|
+
const count = Number(operator === "<<" ? right : -right);
|
|
701
|
+
if (count > 0 && left !== 0n && bitsOf(left) + count > MAX_BIGINT_BITS) throw bigIntTooLarge();
|
|
702
|
+
} else if (operator === "**") {
|
|
703
|
+
const bits = bitsOf(left);
|
|
704
|
+
if (bits > 1 && (bits - 1) * Number(right) + 1 > MAX_BIGINT_BITS) throw bigIntTooLarge();
|
|
705
|
+
} else if (operator === "/" || operator === "%") {
|
|
706
|
+
const bits = bitsOf(left);
|
|
707
|
+
if (bits > WORD_BITS) this.work(bits * BIGINT_WORK);
|
|
708
|
+
}
|
|
709
|
+
return;
|
|
710
|
+
}
|
|
711
|
+
const other = typeof left === "bigint" ? right : left;
|
|
712
|
+
if (COMPARISONS.has(operator)) {
|
|
713
|
+
const chars = typeof other === "string" ? other.length : assertArrayTextWithinLimit(other);
|
|
714
|
+
if (chars > MAX_BIGINT_DIGITS) {
|
|
715
|
+
throw new InterpreterError(`A BigInt cannot be compared with a text of more than ${MAX_BIGINT_DIGITS} chars`);
|
|
716
|
+
}
|
|
717
|
+
this.work(chars * BIGINT_TEXT_WORK);
|
|
718
|
+
} else if (operator === "+") {
|
|
719
|
+
this.bigIntAsText(left);
|
|
720
|
+
this.bigIntAsText(right);
|
|
721
|
+
}
|
|
462
722
|
}
|
|
463
723
|
/** Charge an allocation to the host's budget. */
|
|
464
724
|
charge(bytes) {
|
|
@@ -490,12 +750,19 @@ var Interpreter = class {
|
|
|
490
750
|
case "FunctionDeclaration":
|
|
491
751
|
if (node.id) scope.declare(node.id.name, this.makeFunction(node, scope), false);
|
|
492
752
|
return void 0;
|
|
493
|
-
case "ExpressionStatement":
|
|
494
|
-
|
|
753
|
+
case "ExpressionStatement": {
|
|
754
|
+
const expression = node.expression;
|
|
755
|
+
if (expression.type === "AssignmentExpression" && expression.left.type === "Identifier") {
|
|
756
|
+
const name = expression.left.name;
|
|
757
|
+
const appended = expression.operator === "+=" ? [expression.right] : expression.operator === "=" ? appendedTo(name, expression.right) : void 0;
|
|
758
|
+
if (appended !== void 0 && scope.has(name)) return this.execAppend(name, appended, scope);
|
|
759
|
+
}
|
|
760
|
+
return this.evalExpr(expression, scope);
|
|
761
|
+
}
|
|
495
762
|
case "BlockStatement":
|
|
496
763
|
return this.execBlock(node.body, scope.child());
|
|
497
764
|
case "IfStatement":
|
|
498
|
-
if (
|
|
765
|
+
if (await this.evalTest(node.test, scope)) return this.execStatement(node.consequent, scope);
|
|
499
766
|
if (node.alternate) return this.execStatement(node.alternate, scope);
|
|
500
767
|
return void 0;
|
|
501
768
|
case "ForOfStatement":
|
|
@@ -515,7 +782,7 @@ var Interpreter = class {
|
|
|
515
782
|
case "ThrowStatement":
|
|
516
783
|
throw await this.evalExpr(node.argument, scope);
|
|
517
784
|
case "ReturnStatement":
|
|
518
|
-
throw new ReturnSignal(node.argument ? await this.
|
|
785
|
+
throw new ReturnSignal(node.argument ? await this.evalReturned(node.argument, scope) : void 0);
|
|
519
786
|
case "BreakStatement":
|
|
520
787
|
if (node.label) throw new InterpreterError("Labeled break is not supported");
|
|
521
788
|
throw new BreakSignal();
|
|
@@ -586,14 +853,14 @@ var Interpreter = class {
|
|
|
586
853
|
if (node.init.type === "VariableDeclaration") await this.execStatement(node.init, inner);
|
|
587
854
|
else await this.evalExpr(node.init, inner);
|
|
588
855
|
}
|
|
589
|
-
while (node.test ?
|
|
856
|
+
while (node.test ? await this.evalTest(node.test, inner) : true) {
|
|
590
857
|
this.tick();
|
|
591
858
|
if (!await this.runLoopBody(node.body, inner.child())) break;
|
|
592
859
|
if (node.update) await this.evalExpr(node.update, inner);
|
|
593
860
|
}
|
|
594
861
|
}
|
|
595
862
|
async execWhile(node, scope) {
|
|
596
|
-
while (
|
|
863
|
+
while (await this.evalTest(node.test, scope)) {
|
|
597
864
|
this.tick();
|
|
598
865
|
if (!await this.runLoopBody(node.body, scope.child())) break;
|
|
599
866
|
}
|
|
@@ -602,7 +869,7 @@ var Interpreter = class {
|
|
|
602
869
|
do {
|
|
603
870
|
this.tick();
|
|
604
871
|
if (!await this.runLoopBody(node.body, scope.child())) break;
|
|
605
|
-
} while (
|
|
872
|
+
} while (await this.evalTest(node.test, scope));
|
|
606
873
|
}
|
|
607
874
|
async execSwitch(node, scope) {
|
|
608
875
|
const value = await this.evalExpr(node.discriminant, scope);
|
|
@@ -660,6 +927,10 @@ var Interpreter = class {
|
|
|
660
927
|
if (node.regex) {
|
|
661
928
|
throw new InterpreterError("Regular expressions are not supported");
|
|
662
929
|
}
|
|
930
|
+
if (typeof node.value === "bigint" && !this.checkedLiterals.has(node)) {
|
|
931
|
+
if (bitsOf(node.value) > MAX_BIGINT_BITS) throw bigIntTooLarge();
|
|
932
|
+
this.checkedLiterals.add(node);
|
|
933
|
+
}
|
|
663
934
|
return node.value;
|
|
664
935
|
case "Identifier":
|
|
665
936
|
return scope.has(node.name) ? scope.get(node.name) : this.readGlobal(node.name);
|
|
@@ -689,6 +960,7 @@ var Interpreter = class {
|
|
|
689
960
|
for (const [k, v] of Object.entries(spread)) {
|
|
690
961
|
this.tick();
|
|
691
962
|
if (!BLOCKED_KEYS.has(k)) {
|
|
963
|
+
assertStorable(obj, k, v);
|
|
692
964
|
obj[k] = v;
|
|
693
965
|
count++;
|
|
694
966
|
}
|
|
@@ -699,7 +971,9 @@ var Interpreter = class {
|
|
|
699
971
|
if (prop.kind !== "init") throw new InterpreterError("Getters and setters are not supported");
|
|
700
972
|
const key = await this.propKey(prop, scope);
|
|
701
973
|
if (BLOCKED_KEYS.has(key)) throw new InterpreterError(`Forbidden property key: ${key}`);
|
|
702
|
-
|
|
974
|
+
const member = await this.evalExpr(prop.value, scope);
|
|
975
|
+
assertStorable(obj, key, member);
|
|
976
|
+
obj[key] = member;
|
|
703
977
|
count++;
|
|
704
978
|
}
|
|
705
979
|
this.charge(count * 16);
|
|
@@ -710,7 +984,8 @@ var Interpreter = class {
|
|
|
710
984
|
case "UpdateExpression": {
|
|
711
985
|
const ref = await this.resolveReference(node.argument, scope);
|
|
712
986
|
const current = ref.get();
|
|
713
|
-
|
|
987
|
+
this.arrayOperands(current);
|
|
988
|
+
this.work(operandSize(current));
|
|
714
989
|
const before = Number(current);
|
|
715
990
|
const after = node.operator === "++" ? before + 1 : before - 1;
|
|
716
991
|
ref.set(after);
|
|
@@ -725,7 +1000,7 @@ var Interpreter = class {
|
|
|
725
1000
|
return left ?? await this.evalExpr(node.right, scope);
|
|
726
1001
|
}
|
|
727
1002
|
case "ConditionalExpression":
|
|
728
|
-
return
|
|
1003
|
+
return await this.evalTest(node.test, scope) ? this.evalExpr(node.consequent, scope) : this.evalExpr(node.alternate, scope);
|
|
729
1004
|
case "SequenceExpression": {
|
|
730
1005
|
let last;
|
|
731
1006
|
for (const expression of node.expressions) last = await this.evalExpr(expression, scope);
|
|
@@ -757,17 +1032,107 @@ var Interpreter = class {
|
|
|
757
1032
|
throw new InterpreterError(`Unsupported expression: ${node.type}`);
|
|
758
1033
|
}
|
|
759
1034
|
}
|
|
1035
|
+
/**
|
|
1036
|
+
* `s += x` or `s = s + x…` as a statement: append to a variable.
|
|
1037
|
+
*
|
|
1038
|
+
* The engine does not copy a text to append to it: the new text links to the old one, and is
|
|
1039
|
+
* written out as a text of its own when something first looks into it. A loop that appends to
|
|
1040
|
+
* one variable therefore allocates what it appends, and is charged that. What is not charged
|
|
1041
|
+
* yet, the length of the text that was appended to, stays owed on the variable: it is paid by
|
|
1042
|
+
* the first read that could look into the new text or keep it (`Scope.get`), because from then
|
|
1043
|
+
* on it can exist as a full copy next to the texts it was built from. Nothing else can get
|
|
1044
|
+
* hold of the new text: as a statement, the assignment has no value.
|
|
1045
|
+
*/
|
|
1046
|
+
async execAppend(name, operands, scope) {
|
|
1047
|
+
this.tick();
|
|
1048
|
+
const { sum, owed } = await this.appendTo(name, operands, scope);
|
|
1049
|
+
scope.append(name, sum, owed);
|
|
1050
|
+
return sum;
|
|
1051
|
+
}
|
|
1052
|
+
/**
|
|
1053
|
+
* The value of the variable `name` with the operands appended, charged for what is appended.
|
|
1054
|
+
*
|
|
1055
|
+
* @returns The sum, and what is still owed for it when it is a text that was appended to a text
|
|
1056
|
+
*/
|
|
1057
|
+
async appendTo(name, operands, scope) {
|
|
1058
|
+
const variable = scope.slot(name);
|
|
1059
|
+
if (!variable) throw new InterpreterError(`'${name}' is not defined`);
|
|
1060
|
+
const start = variable.value;
|
|
1061
|
+
const owedAtStart = variable.owed;
|
|
1062
|
+
let sum = start;
|
|
1063
|
+
for (const operand of operands) {
|
|
1064
|
+
this.tick();
|
|
1065
|
+
const right = await this.evalExpr(operand, scope);
|
|
1066
|
+
const left = sum;
|
|
1067
|
+
sum = this.binary("+", left, right, true);
|
|
1068
|
+
if (typeof sum === "string") this.charge((sum.length - (typeof left === "string" ? left.length : 0)) * 2);
|
|
1069
|
+
}
|
|
1070
|
+
let owed = 0;
|
|
1071
|
+
if (typeof sum === "string" && typeof start === "string") {
|
|
1072
|
+
owed = owedAtStart > 0 && variable.owed === owedAtStart ? owedAtStart : start.length * 2;
|
|
1073
|
+
}
|
|
1074
|
+
return { sum, owed };
|
|
1075
|
+
}
|
|
1076
|
+
/**
|
|
1077
|
+
* The value a function returns. In a callback that `reduce` called with a text, the
|
|
1078
|
+
* accumulator itself and what is appended to it (`return text + item`) are returned as an
|
|
1079
|
+
* {@link AccumulatedText}, without paying what is owed for them: `reduce` carries it on.
|
|
1080
|
+
*/
|
|
1081
|
+
async evalReturned(node, scope) {
|
|
1082
|
+
const name = scope.accumulator;
|
|
1083
|
+
if (name === void 0) return this.evalExpr(node, scope);
|
|
1084
|
+
if (node.type === "ConditionalExpression") {
|
|
1085
|
+
this.tick();
|
|
1086
|
+
const branch = await this.evalTest(node.test, scope) ? node.consequent : node.alternate;
|
|
1087
|
+
return this.evalReturned(branch, scope);
|
|
1088
|
+
}
|
|
1089
|
+
if (node.type === "Identifier" && node.name === name) {
|
|
1090
|
+
const variable = scope.slot(name);
|
|
1091
|
+
if (variable !== void 0 && typeof variable.value === "string") {
|
|
1092
|
+
this.tick();
|
|
1093
|
+
return new AccumulatedText(variable.value, variable.owed);
|
|
1094
|
+
}
|
|
1095
|
+
} else {
|
|
1096
|
+
const appended = appendedTo(name, node);
|
|
1097
|
+
if (appended !== void 0 && scope.has(name)) {
|
|
1098
|
+
this.tick();
|
|
1099
|
+
const { sum, owed } = await this.appendTo(name, appended, scope);
|
|
1100
|
+
return typeof sum === "string" ? new AccumulatedText(sum, owed) : sum;
|
|
1101
|
+
}
|
|
1102
|
+
}
|
|
1103
|
+
return this.evalExpr(node, scope);
|
|
1104
|
+
}
|
|
1105
|
+
/**
|
|
1106
|
+
* The variable an identifier names when it holds an appended text that is still owed for.
|
|
1107
|
+
* For the readers that learn nothing but its length or that it is a text.
|
|
1108
|
+
*/
|
|
1109
|
+
appendedText(node, scope) {
|
|
1110
|
+
if (node.type !== "Identifier") return void 0;
|
|
1111
|
+
const variable = scope.slot(node.name);
|
|
1112
|
+
return variable !== void 0 && variable.owed > 0 && typeof variable.value === "string" ? variable.value : void 0;
|
|
1113
|
+
}
|
|
1114
|
+
/** Evaluate a condition. Whether a text is empty is known from its length. */
|
|
1115
|
+
async evalTest(node, scope) {
|
|
1116
|
+
const text = this.appendedText(node, scope);
|
|
1117
|
+
if (text !== void 0) {
|
|
1118
|
+
this.tick();
|
|
1119
|
+
return text.length > 0;
|
|
1120
|
+
}
|
|
1121
|
+
return truthy(await this.evalExpr(node, scope));
|
|
1122
|
+
}
|
|
760
1123
|
async evalTemplate(node, scope) {
|
|
761
1124
|
let out = "";
|
|
762
1125
|
for (let i = 0; i < node.quasis.length; i++) {
|
|
763
1126
|
out += node.quasis[i].value.cooked ?? "";
|
|
764
1127
|
if (i < node.expressions.length) {
|
|
765
1128
|
const value = await this.evalExpr(node.expressions[i], scope);
|
|
766
|
-
|
|
1129
|
+
this.arrayOperands(value);
|
|
1130
|
+
this.bigIntAsText(value);
|
|
767
1131
|
out += String(value);
|
|
768
1132
|
if (out.length > MAX_JOIN_LENGTH) throw new InterpreterError(TEXT_TOO_LONG);
|
|
769
1133
|
}
|
|
770
1134
|
}
|
|
1135
|
+
this.work(out.length * WRITE_WORK);
|
|
771
1136
|
this.charge(out.length * 2);
|
|
772
1137
|
return out;
|
|
773
1138
|
}
|
|
@@ -782,37 +1147,67 @@ var Interpreter = class {
|
|
|
782
1147
|
assertKeyAllowed(key);
|
|
783
1148
|
return delete object[key];
|
|
784
1149
|
}
|
|
1150
|
+
if (node.operator === "!" || node.operator === "typeof") {
|
|
1151
|
+
const text = this.appendedText(node.argument, scope);
|
|
1152
|
+
if (text !== void 0) {
|
|
1153
|
+
this.tick();
|
|
1154
|
+
return node.operator === "!" ? text.length === 0 : "string";
|
|
1155
|
+
}
|
|
1156
|
+
}
|
|
785
1157
|
const v = await this.evalExpr(node.argument, scope);
|
|
786
1158
|
switch (node.operator) {
|
|
787
1159
|
case "!":
|
|
788
1160
|
return !truthy(v);
|
|
789
|
-
case "-":
|
|
790
|
-
|
|
791
|
-
|
|
1161
|
+
case "-": {
|
|
1162
|
+
this.numericOperand(v);
|
|
1163
|
+
const negated = -v;
|
|
1164
|
+
if (typeof negated === "bigint") this.countBigInt(negated);
|
|
1165
|
+
return negated;
|
|
1166
|
+
}
|
|
792
1167
|
case "+":
|
|
793
|
-
|
|
1168
|
+
this.numericOperand(v);
|
|
794
1169
|
return +v;
|
|
795
1170
|
case "typeof":
|
|
796
1171
|
return typeof v;
|
|
797
|
-
case "~":
|
|
798
|
-
|
|
799
|
-
|
|
1172
|
+
case "~": {
|
|
1173
|
+
this.numericOperand(v);
|
|
1174
|
+
const inverted = ~v;
|
|
1175
|
+
if (typeof inverted === "bigint") this.countBigInt(inverted);
|
|
1176
|
+
return inverted;
|
|
1177
|
+
}
|
|
800
1178
|
case "void":
|
|
801
1179
|
return void 0;
|
|
802
1180
|
default:
|
|
803
1181
|
throw new InterpreterError(`Unsupported unary operator: ${node.operator}`);
|
|
804
1182
|
}
|
|
805
1183
|
}
|
|
1184
|
+
/** An operand the engine reads a number from: an array is joined first, a text is read through. */
|
|
1185
|
+
numericOperand(value) {
|
|
1186
|
+
this.arrayOperands(value);
|
|
1187
|
+
this.work(operandSize(value));
|
|
1188
|
+
}
|
|
806
1189
|
async evalBinary(node, scope) {
|
|
807
1190
|
if (node.left.type === "PrivateIdentifier") throw new InterpreterError("Private names are not supported");
|
|
1191
|
+
if (node.operator === "+") return this.evalSum(node, scope);
|
|
1192
|
+
if (node.operator === "===" || node.operator === "!==") {
|
|
1193
|
+
const literal = node.left.type === "Literal" ? node.left : node.right.type === "Literal" ? node.right : void 0;
|
|
1194
|
+
const text = this.appendedText(literal === node.left ? node.right : node.left, scope);
|
|
1195
|
+
if (literal !== void 0 && text !== void 0 && !literal.regex) {
|
|
1196
|
+
const value = literal.value;
|
|
1197
|
+
if (typeof value !== "string" || value.length !== text.length) {
|
|
1198
|
+
this.tick();
|
|
1199
|
+
this.tick();
|
|
1200
|
+
return node.operator === "!==";
|
|
1201
|
+
}
|
|
1202
|
+
}
|
|
1203
|
+
}
|
|
808
1204
|
const l = await this.evalExpr(node.left, scope);
|
|
809
1205
|
const r = await this.evalExpr(node.right, scope);
|
|
810
1206
|
if (node.operator === "in") {
|
|
811
1207
|
if (r === null || typeof r !== "object" && typeof r !== "function") {
|
|
812
1208
|
throw new InterpreterError("Cannot use 'in' on a value that is not an object");
|
|
813
1209
|
}
|
|
814
|
-
|
|
815
|
-
const key = String(l);
|
|
1210
|
+
const key = this.keyText(l);
|
|
816
1211
|
if (BLOCKED_KEYS.has(key)) throw new InterpreterError(`Forbidden property access: ${key}`);
|
|
817
1212
|
return key in r;
|
|
818
1213
|
}
|
|
@@ -823,15 +1218,56 @@ var Interpreter = class {
|
|
|
823
1218
|
}
|
|
824
1219
|
return this.binary(node.operator, l, r);
|
|
825
1220
|
}
|
|
826
|
-
/**
|
|
827
|
-
|
|
828
|
-
|
|
1221
|
+
/**
|
|
1222
|
+
* `a + b + c`: the operands from left to right, and one sum after the other. Only the last
|
|
1223
|
+
* sum is a value the script gets hold of, and it is charged in full; the ones before it are
|
|
1224
|
+
* part of it.
|
|
1225
|
+
*/
|
|
1226
|
+
async evalSum(node, scope) {
|
|
1227
|
+
const operands = [];
|
|
1228
|
+
let first = node;
|
|
1229
|
+
while (first.type === "BinaryExpression" && first.operator === "+") {
|
|
1230
|
+
operands.push(first.right);
|
|
1231
|
+
first = first.left;
|
|
1232
|
+
}
|
|
1233
|
+
if (first.type === "PrivateIdentifier") throw new InterpreterError("Private names are not supported");
|
|
1234
|
+
let sum = await this.evalExpr(first, scope);
|
|
1235
|
+
for (let i = operands.length - 1; i >= 0; i--) {
|
|
1236
|
+
if (i < operands.length - 1) this.tick();
|
|
1237
|
+
const right = await this.evalExpr(operands[i], scope);
|
|
1238
|
+
sum = this.binary("+", sum, right, i > 0);
|
|
1239
|
+
}
|
|
1240
|
+
return sum;
|
|
1241
|
+
}
|
|
1242
|
+
/**
|
|
1243
|
+
* Apply a binary operator to two values.
|
|
1244
|
+
*
|
|
1245
|
+
* @param partOfSum - The result of `+` is an operand of the next `+` and nothing else: the
|
|
1246
|
+
* caller charges for the text that comes of it
|
|
1247
|
+
*/
|
|
1248
|
+
binary(operator, left, right, partOfSum = false) {
|
|
1249
|
+
if (typeof left !== "bigint" && typeof right !== "bigint") return this.operate(operator, left, right, partOfSum);
|
|
1250
|
+
this.checkBigIntOperands(operator, left, right);
|
|
1251
|
+
const result = this.operate(operator, left, right, partOfSum);
|
|
1252
|
+
if (typeof result === "bigint") this.countBigInt(result);
|
|
1253
|
+
return result;
|
|
1254
|
+
}
|
|
1255
|
+
operate(operator, left, right, partOfSum) {
|
|
1256
|
+
const strict = operator === "===" || operator === "!==";
|
|
1257
|
+
const loose = operator === "==" || operator === "!=";
|
|
1258
|
+
const convertsNextTo = (other) => !strict && (!loose || other !== null && other !== void 0 && typeof other !== "object" && typeof other !== "function");
|
|
1259
|
+
this.arrayOperands(convertsNextTo(right) ? left : void 0, convertsNextTo(left) ? right : void 0);
|
|
1260
|
+
if (operator !== "+") {
|
|
1261
|
+
if (typeof left === "string" && typeof right === "string") this.work(Math.min(left.length, right.length));
|
|
1262
|
+
else if (typeof left === "string" && convertsNextTo(right)) this.work(left.length);
|
|
1263
|
+
else if (typeof right === "string" && convertsNextTo(left)) this.work(right.length);
|
|
1264
|
+
}
|
|
829
1265
|
const l = left;
|
|
830
1266
|
const r = right;
|
|
831
1267
|
switch (operator) {
|
|
832
1268
|
case "+": {
|
|
833
1269
|
const sum = l + r;
|
|
834
|
-
if (typeof sum === "string") this.charge(
|
|
1270
|
+
if (typeof sum === "string" && !partOfSum) this.charge(sum.length * 2);
|
|
835
1271
|
return sum;
|
|
836
1272
|
}
|
|
837
1273
|
case "-":
|
|
@@ -882,6 +1318,11 @@ var Interpreter = class {
|
|
|
882
1318
|
*/
|
|
883
1319
|
async evalMemberTarget(node, scope) {
|
|
884
1320
|
if (node.object.type === "Super") throw new InterpreterError("super is not supported");
|
|
1321
|
+
const text = !node.computed && node.property.type === "Identifier" && node.property.name === "length" ? this.appendedText(node.object, scope) : void 0;
|
|
1322
|
+
if (text !== void 0) {
|
|
1323
|
+
this.tick();
|
|
1324
|
+
return { object: text, key: "length" };
|
|
1325
|
+
}
|
|
885
1326
|
const object = await this.evalExpr(node.object, scope);
|
|
886
1327
|
if (node.optional && (object === null || object === void 0)) throw new ChainShortCircuit();
|
|
887
1328
|
if (node.property.type === "PrivateIdentifier") throw new InterpreterError("Private names are not supported");
|
|
@@ -922,12 +1363,11 @@ var Interpreter = class {
|
|
|
922
1363
|
writeMember(object, key, value) {
|
|
923
1364
|
this.assertChangeable(object);
|
|
924
1365
|
assertKeyAllowed(key);
|
|
1366
|
+
assertStorable(object, key, value);
|
|
925
1367
|
if (Array.isArray(object)) {
|
|
926
|
-
const
|
|
927
|
-
if (
|
|
928
|
-
|
|
929
|
-
}
|
|
930
|
-
if (grownTo > object.length) this.charge((grownTo - object.length) * 8);
|
|
1368
|
+
const checked = checkArrayWrite(object, key, value);
|
|
1369
|
+
if (checked.length > object.length) this.charge((checked.length - object.length) * 8);
|
|
1370
|
+
value = checked.value;
|
|
931
1371
|
}
|
|
932
1372
|
object[key] = value;
|
|
933
1373
|
}
|
|
@@ -956,7 +1396,10 @@ var Interpreter = class {
|
|
|
956
1396
|
const construct = this.options.constructors?.get(callee);
|
|
957
1397
|
if (!construct) throw new InterpreterError("new works with the built-in types the sandbox provides only");
|
|
958
1398
|
const args = await this.evalArguments(node.arguments, scope);
|
|
959
|
-
if (!ARRAY_DATA_FUNCTIONS.has(callee))
|
|
1399
|
+
if (!ARRAY_DATA_FUNCTIONS.has(callee)) {
|
|
1400
|
+
this.arrayOperands(...args);
|
|
1401
|
+
for (const arg of args) this.work(typeof arg === "string" ? arg.length : 0);
|
|
1402
|
+
}
|
|
960
1403
|
const value = construct(args);
|
|
961
1404
|
this.chargeValue(value);
|
|
962
1405
|
return value;
|
|
@@ -991,6 +1434,7 @@ var Interpreter = class {
|
|
|
991
1434
|
* @param depth - How many calls deep the code that makes this call runs
|
|
992
1435
|
*/
|
|
993
1436
|
async callFunction(fn, thisArg, args, depth) {
|
|
1437
|
+
if (this.fatal !== void 0) throw this.fatal;
|
|
994
1438
|
for (let hops = 0; fn === FunctionProtoCall || fn === FunctionProtoApply || fn === FunctionProtoBind; hops++) {
|
|
995
1439
|
const name = fn === FunctionProtoCall ? "call" : fn === FunctionProtoApply ? "apply" : "bind";
|
|
996
1440
|
if (typeof thisArg !== "function" || hops >= 8) {
|
|
@@ -1010,6 +1454,7 @@ var Interpreter = class {
|
|
|
1010
1454
|
const interpreted = fn;
|
|
1011
1455
|
return await this.withCallerDepth(depth, () => interpreted.apply(thisArg, args));
|
|
1012
1456
|
}
|
|
1457
|
+
this.checkClock();
|
|
1013
1458
|
const own = this.enterCall(depth);
|
|
1014
1459
|
try {
|
|
1015
1460
|
args = this.checkBuiltinCall(fn, thisArg, args);
|
|
@@ -1017,20 +1462,228 @@ var Interpreter = class {
|
|
|
1017
1462
|
if (arrayMethod !== void 0 && HIGHER_ORDER_ARRAY_METHODS.has(arrayMethod) && typeof args[0] === "function") {
|
|
1018
1463
|
return await this.callArrayMethod(thisArg, arrayMethod, args, own);
|
|
1019
1464
|
}
|
|
1020
|
-
|
|
1021
|
-
|
|
1022
|
-
|
|
1023
|
-
|
|
1465
|
+
if (arrayMethod === "toLocaleString") {
|
|
1466
|
+
const text = this.arrayLocaleText(thisArg, args, /* @__PURE__ */ new Set(), { length: 0 }, 0);
|
|
1467
|
+
this.chargeValue(text);
|
|
1468
|
+
return text;
|
|
1469
|
+
}
|
|
1470
|
+
const stringMethod = arrayMethod === void 0 ? STRING_METHODS.get(fn) : void 0;
|
|
1471
|
+
this.countRead(fn, arrayMethod, stringMethod, thisArg, args);
|
|
1472
|
+
let result = this.searchInPieces(arrayMethod, stringMethod, thisArg, args);
|
|
1473
|
+
if (result === NOT_SEARCHED) {
|
|
1474
|
+
const asIndex = stringMethod === "includes" && typeof thisArg === "string";
|
|
1475
|
+
const builtin = asIndex ? StringProtoIndexOf : fn;
|
|
1476
|
+
const builtinArgs = args;
|
|
1477
|
+
result = await this.withCallerDepth(own, () => builtin.apply(thisArg, builtinArgs));
|
|
1478
|
+
this.countSearched(arrayMethod, stringMethod, thisArg, args, result);
|
|
1479
|
+
if (asIndex) result = result !== -1;
|
|
1480
|
+
}
|
|
1481
|
+
if (stringMethod === "split" && Array.isArray(result)) {
|
|
1024
1482
|
if (result.length > MAX_ARRAY_LENGTH) {
|
|
1025
1483
|
throw new InterpreterError(`An array cannot be longer than ${MAX_ARRAY_LENGTH} items`);
|
|
1026
1484
|
}
|
|
1027
1485
|
}
|
|
1486
|
+
this.work(typeof result === "string" ? result.length * WRITE_WORK : operandSize(result));
|
|
1028
1487
|
this.chargeValue(result);
|
|
1029
1488
|
return result;
|
|
1030
1489
|
} finally {
|
|
1031
1490
|
this.pendingCalls--;
|
|
1032
1491
|
}
|
|
1033
1492
|
}
|
|
1493
|
+
/**
|
|
1494
|
+
* Count what a built-in or host function reads before it is called: its receiver, where the
|
|
1495
|
+
* method goes through it (a search, a conversion, a copy; not a method that reads one char or
|
|
1496
|
+
* works at the end of an array), and the texts among the arguments it converts or searches
|
|
1497
|
+
* for. A value a function only keeps is not read: an item to push, the array a callback is
|
|
1498
|
+
* handed with every item. An array that is read as text was counted where it was measured,
|
|
1499
|
+
* and what the call makes is counted when it returns.
|
|
1500
|
+
*/
|
|
1501
|
+
countRead(fn, arrayMethod, stringMethod, receiver, args) {
|
|
1502
|
+
let read = 0;
|
|
1503
|
+
if (typeof receiver === "string") {
|
|
1504
|
+
const counted = stringMethod === void 0 || !ARRAY_SEARCHES.has(stringMethod);
|
|
1505
|
+
if (counted && (stringMethod === void 0 || !CONSTANT_STRING_METHODS.has(stringMethod))) {
|
|
1506
|
+
read += receiver.length;
|
|
1507
|
+
}
|
|
1508
|
+
} else if (Array.isArray(receiver)) {
|
|
1509
|
+
const counted = arrayMethod !== "indexOf" && arrayMethod !== "lastIndexOf";
|
|
1510
|
+
if (counted && (arrayMethod === void 0 || !CONSTANT_ARRAY_METHODS.has(arrayMethod))) read += receiver.length;
|
|
1511
|
+
} else if (typeof receiver === "bigint") {
|
|
1512
|
+
this.bigIntAsText(receiver);
|
|
1513
|
+
}
|
|
1514
|
+
if (!ARRAY_DATA_FUNCTIONS.has(fn)) {
|
|
1515
|
+
const isData = arrayMethod === void 0 ? void 0 : ARRAY_DATA_ARGUMENTS.get(arrayMethod);
|
|
1516
|
+
const converted = CONVERTED_ARGUMENTS.get(fn) ?? args.length;
|
|
1517
|
+
for (let i = 0; i < args.length && i < converted; i++) {
|
|
1518
|
+
if (isData?.(i)) continue;
|
|
1519
|
+
const arg = args[i];
|
|
1520
|
+
if (typeof arg === "string") read += arg.length;
|
|
1521
|
+
else this.bigIntAsText(arg);
|
|
1522
|
+
}
|
|
1523
|
+
}
|
|
1524
|
+
if (stringMethod === "localeCompare" && typeof receiver === "string") {
|
|
1525
|
+
const other = args[0];
|
|
1526
|
+
read = Math.min(receiver.length, typeof other === "string" ? other.length : receiver.length) * LOCALE_COMPARE_WORK;
|
|
1527
|
+
}
|
|
1528
|
+
this.work(read);
|
|
1529
|
+
}
|
|
1530
|
+
/**
|
|
1531
|
+
* Count a search for a place by how far the engine went: from where it started to where it
|
|
1532
|
+
* found what it looked for, or to the end. A script that goes through a long text with
|
|
1533
|
+
* `indexOf(text, position)` pays for the text once, not once per call.
|
|
1534
|
+
*
|
|
1535
|
+
* @param index - What the engine answered: the place, or -1
|
|
1536
|
+
*/
|
|
1537
|
+
countSearched(arrayMethod, stringMethod, receiver, args, index) {
|
|
1538
|
+
if (typeof index !== "number") return;
|
|
1539
|
+
const position = args[1];
|
|
1540
|
+
if (typeof receiver === "string" && stringMethod !== void 0 && ARRAY_SEARCHES.has(stringMethod)) {
|
|
1541
|
+
const length = receiver.length;
|
|
1542
|
+
if (stringMethod === "lastIndexOf") {
|
|
1543
|
+
const given = Number(position);
|
|
1544
|
+
const from = Number.isNaN(given) ? length : Math.min(Math.max(Math.trunc(given), 0), length);
|
|
1545
|
+
this.work(index === -1 ? from : from - index);
|
|
1546
|
+
} else {
|
|
1547
|
+
const from = Math.min(Math.max(integerOf(position), 0), length);
|
|
1548
|
+
this.work(index === -1 ? length - from : index - from);
|
|
1549
|
+
}
|
|
1550
|
+
} else if (Array.isArray(receiver) && (arrayMethod === "indexOf" || arrayMethod === "lastIndexOf")) {
|
|
1551
|
+
const length = receiver.length;
|
|
1552
|
+
if (arrayMethod === "lastIndexOf") {
|
|
1553
|
+
const given = args.length > 1 ? integerOf(position) : length - 1;
|
|
1554
|
+
const from = given >= 0 ? Math.min(given, length - 1) : length + given;
|
|
1555
|
+
this.work(index === -1 ? from + 1 : from - index);
|
|
1556
|
+
} else {
|
|
1557
|
+
const given = integerOf(position);
|
|
1558
|
+
const from = Math.min(given >= 0 ? given : Math.max(length + given, 0), length);
|
|
1559
|
+
this.work(index === -1 ? length - from : index - from);
|
|
1560
|
+
}
|
|
1561
|
+
}
|
|
1562
|
+
}
|
|
1563
|
+
/**
|
|
1564
|
+
* Make a search whose cost in the engine is the product of two lengths, piece by piece: a text
|
|
1565
|
+
* in a text (the engine can need a comparison of the whole pattern at every position of a
|
|
1566
|
+
* text that nearly matches everywhere), or a long text among the items of an array (every
|
|
1567
|
+
* item of the same length can be compared to its end). Between the pieces a step is counted
|
|
1568
|
+
* and the clock is read, so that one such call ends with the budget or the deadline like any
|
|
1569
|
+
* other code. The answer is the engine's.
|
|
1570
|
+
*
|
|
1571
|
+
* @returns The result, or {@link NOT_SEARCHED} for a call that is not such a search or small
|
|
1572
|
+
* enough to be one piece: the engine makes it
|
|
1573
|
+
*/
|
|
1574
|
+
searchInPieces(arrayMethod, stringMethod, receiver, args) {
|
|
1575
|
+
const wanted = args[0];
|
|
1576
|
+
if (typeof wanted !== "string") return NOT_SEARCHED;
|
|
1577
|
+
const method = arrayMethod ?? stringMethod;
|
|
1578
|
+
if (typeof args[1] === "bigint" && method !== void 0 && ARRAY_SEARCHES.has(method)) return NOT_SEARCHED;
|
|
1579
|
+
if (stringMethod !== void 0 && typeof receiver === "string" && TEXT_SEARCHES.has(stringMethod)) {
|
|
1580
|
+
const small = receiver.length * wanted.length <= SEARCH_PIECE_WORK;
|
|
1581
|
+
if (small || wanted.length === 0 || wanted.length > receiver.length) return NOT_SEARCHED;
|
|
1582
|
+
return this.searchText(stringMethod, receiver, wanted, args);
|
|
1583
|
+
}
|
|
1584
|
+
if (arrayMethod !== void 0 && Array.isArray(receiver) && ARRAY_SEARCHES.has(arrayMethod)) {
|
|
1585
|
+
const small = receiver.length * wanted.length <= SEARCH_PIECE_WORK;
|
|
1586
|
+
if (small || wanted.length <= LONG_SEARCH_TEXT) return NOT_SEARCHED;
|
|
1587
|
+
return this.searchArray(arrayMethod, receiver, wanted, args);
|
|
1588
|
+
}
|
|
1589
|
+
return NOT_SEARCHED;
|
|
1590
|
+
}
|
|
1591
|
+
/** The first place at or after `from` where `pattern` starts in `text`, or -1. */
|
|
1592
|
+
findForward(text, pattern, from) {
|
|
1593
|
+
const last = text.length - pattern.length;
|
|
1594
|
+
const starts = Math.max(1, Math.floor(SEARCH_PIECE_WORK / pattern.length));
|
|
1595
|
+
for (let at = from; at <= last; at += starts) {
|
|
1596
|
+
if (at !== from) {
|
|
1597
|
+
this.tick();
|
|
1598
|
+
this.checkClock();
|
|
1599
|
+
}
|
|
1600
|
+
const end = Math.min(at + starts - 1, last) + pattern.length;
|
|
1601
|
+
const found = text.substring(at, end).indexOf(pattern);
|
|
1602
|
+
this.work(found === -1 ? end - at : found + pattern.length);
|
|
1603
|
+
if (found !== -1) return at + found;
|
|
1604
|
+
}
|
|
1605
|
+
return -1;
|
|
1606
|
+
}
|
|
1607
|
+
/** The last place at or before `from` where `pattern` starts in `text`, or -1. */
|
|
1608
|
+
findBackward(text, pattern, from) {
|
|
1609
|
+
const starts = Math.max(1, Math.floor(SEARCH_PIECE_WORK / pattern.length));
|
|
1610
|
+
for (let high = from; high >= 0; high -= starts) {
|
|
1611
|
+
if (high !== from) {
|
|
1612
|
+
this.tick();
|
|
1613
|
+
this.checkClock();
|
|
1614
|
+
}
|
|
1615
|
+
const low = Math.max(0, high - starts + 1);
|
|
1616
|
+
const end = high + pattern.length;
|
|
1617
|
+
const found = text.substring(low, end).lastIndexOf(pattern);
|
|
1618
|
+
this.work(found === -1 ? end - low : end - low - found);
|
|
1619
|
+
if (found !== -1) return low + found;
|
|
1620
|
+
}
|
|
1621
|
+
return -1;
|
|
1622
|
+
}
|
|
1623
|
+
/** `text.indexOf(pattern)` and the other searches for a text in a text, as the engine answers them. */
|
|
1624
|
+
searchText(name, text, pattern, args) {
|
|
1625
|
+
const length = text.length;
|
|
1626
|
+
const patternLength = pattern.length;
|
|
1627
|
+
switch (name) {
|
|
1628
|
+
case "indexOf":
|
|
1629
|
+
return this.findForward(text, pattern, Math.min(Math.max(integerOf(args[1]), 0), length));
|
|
1630
|
+
case "includes":
|
|
1631
|
+
return this.findForward(text, pattern, Math.min(Math.max(integerOf(args[1]), 0), length)) !== -1;
|
|
1632
|
+
case "lastIndexOf": {
|
|
1633
|
+
const position = Number(args[1]);
|
|
1634
|
+
const from = Number.isNaN(position) ? Number.POSITIVE_INFINITY : Math.trunc(position);
|
|
1635
|
+
return this.findBackward(text, pattern, Math.min(Math.max(from, 0), length - patternLength));
|
|
1636
|
+
}
|
|
1637
|
+
case "split": {
|
|
1638
|
+
const limit = args[1];
|
|
1639
|
+
const pieces = [];
|
|
1640
|
+
if (limit === 0) return pieces;
|
|
1641
|
+
let at = 0;
|
|
1642
|
+
for (let hit = this.findForward(text, pattern, 0); hit !== -1; hit = this.findForward(text, pattern, at)) {
|
|
1643
|
+
pieces.push(text.substring(at, hit));
|
|
1644
|
+
if (pieces.length >= limit) return pieces;
|
|
1645
|
+
at = hit + patternLength;
|
|
1646
|
+
}
|
|
1647
|
+
pieces.push(text.substring(at));
|
|
1648
|
+
return pieces;
|
|
1649
|
+
}
|
|
1650
|
+
default: {
|
|
1651
|
+
const replacement = String(args[1]);
|
|
1652
|
+
const parts = [];
|
|
1653
|
+
let at = 0;
|
|
1654
|
+
let hit = this.findForward(text, pattern, 0);
|
|
1655
|
+
while (hit !== -1) {
|
|
1656
|
+
parts.push(text.substring(at, hit), expandReplacement(replacement, text, hit, pattern));
|
|
1657
|
+
at = hit + patternLength;
|
|
1658
|
+
hit = name === "replace" ? -1 : this.findForward(text, pattern, at);
|
|
1659
|
+
}
|
|
1660
|
+
parts.push(text.substring(at));
|
|
1661
|
+
return parts.join("");
|
|
1662
|
+
}
|
|
1663
|
+
}
|
|
1664
|
+
}
|
|
1665
|
+
/** `array.indexOf(text)`, `lastIndexOf` and `includes` for a long text, as the engine answers them. */
|
|
1666
|
+
searchArray(name, array, wanted, args) {
|
|
1667
|
+
const length = array.length;
|
|
1668
|
+
const same = (item) => {
|
|
1669
|
+
if (typeof item !== "string" || item.length !== wanted.length) {
|
|
1670
|
+
this.work(1);
|
|
1671
|
+
return false;
|
|
1672
|
+
}
|
|
1673
|
+
this.work(wanted.length);
|
|
1674
|
+
return item === wanted;
|
|
1675
|
+
};
|
|
1676
|
+
if (name === "lastIndexOf") {
|
|
1677
|
+
let index2 = args.length > 1 ? integerOf(args[1]) : length - 1;
|
|
1678
|
+
index2 = index2 >= 0 ? Math.min(index2, length - 1) : length + index2;
|
|
1679
|
+
for (; index2 >= 0; index2--) if (same(array[index2])) return index2;
|
|
1680
|
+
return -1;
|
|
1681
|
+
}
|
|
1682
|
+
let index = integerOf(args[1]);
|
|
1683
|
+
if (index < 0) index = Math.max(length + index, 0);
|
|
1684
|
+
for (; index < length; index++) if (same(array[index])) return name === "includes" ? true : index;
|
|
1685
|
+
return name === "includes" ? false : -1;
|
|
1686
|
+
}
|
|
1034
1687
|
/**
|
|
1035
1688
|
* Count a call that starts `callerDepth` calls deep, until it returns.
|
|
1036
1689
|
*
|
|
@@ -1073,11 +1726,13 @@ var Interpreter = class {
|
|
|
1073
1726
|
*/
|
|
1074
1727
|
bindFunction(target, boundThis, boundArgs) {
|
|
1075
1728
|
this.charge((boundArgs.length + 2) * 8);
|
|
1076
|
-
|
|
1729
|
+
const bound = (...rest) => {
|
|
1077
1730
|
const result = this.callFunction(target, boundThis, [...boundArgs, ...rest], this.callerDepth);
|
|
1078
1731
|
result.then(void 0, ignoreRejection2);
|
|
1079
1732
|
return result;
|
|
1080
1733
|
};
|
|
1734
|
+
this.provided.add(bound);
|
|
1735
|
+
return bound;
|
|
1081
1736
|
}
|
|
1082
1737
|
/**
|
|
1083
1738
|
* The checks before a built-in or host function runs. The engine performs such a call in one
|
|
@@ -1089,6 +1744,15 @@ var Interpreter = class {
|
|
|
1089
1744
|
checkBuiltinCall(fn, thisArg, args) {
|
|
1090
1745
|
const arrayMethod = ARRAY_METHODS.get(fn);
|
|
1091
1746
|
const stringMethod = arrayMethod === void 0 ? STRING_METHODS.get(fn) : void 0;
|
|
1747
|
+
const otherMethod = arrayMethod === void 0 && stringMethod === void 0 ? OTHER_METHODS.get(fn) : void 0;
|
|
1748
|
+
const engineMethod = arrayMethod !== void 0 || stringMethod !== void 0 || otherMethod !== void 0;
|
|
1749
|
+
if (!engineMethod && fn !== ARRAY_ITERATOR_NEXT && fn !== FunctionProtoToString && !this.provided.has(fn) && !LIBRARY_FUNCTIONS.has(fn)) {
|
|
1750
|
+
throw new InterpreterError("This built-in function is not available in the sandbox");
|
|
1751
|
+
}
|
|
1752
|
+
if (otherMethod !== void 0 && !RECEIVERS[otherMethod.kind].accepts(thisArg, otherMethod.name)) {
|
|
1753
|
+
const { kind, name } = otherMethod;
|
|
1754
|
+
throw new InterpreterError(`${kind} '${name}' works on ${RECEIVERS[kind].noun} only`);
|
|
1755
|
+
}
|
|
1092
1756
|
let arrayText = 0;
|
|
1093
1757
|
if (!ARRAY_DATA_FUNCTIONS.has(fn)) {
|
|
1094
1758
|
const isData = arrayMethod === void 0 ? void 0 : ARRAY_DATA_ARGUMENTS.get(arrayMethod);
|
|
@@ -1104,10 +1768,24 @@ var Interpreter = class {
|
|
|
1104
1768
|
if (Array.isArray(arg) && !isData?.(i)) measureArray(arg);
|
|
1105
1769
|
}
|
|
1106
1770
|
if (arrayMethod === void 0 && stringMethod === void 0 && Array.isArray(thisArg)) measureArray(thisArg);
|
|
1107
|
-
|
|
1771
|
+
const measured = measure;
|
|
1772
|
+
arrayText = measured?.length ?? 0;
|
|
1773
|
+
this.work(arrayText * WRITE_WORK + (measured?.work ?? 0));
|
|
1108
1774
|
}
|
|
1109
1775
|
if (stringMethod !== void 0) args = this.checkStringMethod(stringMethod, thisArg, args, arrayText);
|
|
1110
|
-
else if (arrayMethod !== void 0) this.checkArrayMethod(arrayMethod, thisArg, args);
|
|
1776
|
+
else if (arrayMethod !== void 0) args = this.checkArrayMethod(arrayMethod, thisArg, args);
|
|
1777
|
+
const callbackTaken = arrayMethod !== void 0 && HIGHER_ORDER_ARRAY_METHODS.has(arrayMethod) && typeof args[0] === "function";
|
|
1778
|
+
if (engineMethod && !callbackTaken) {
|
|
1779
|
+
const isData = arrayMethod === void 0 ? void 0 : ARRAY_DATA_ARGUMENTS.get(arrayMethod);
|
|
1780
|
+
for (let i = 0; i < args.length; i++) {
|
|
1781
|
+
if (typeof args[i] !== "function" || isData?.(i)) continue;
|
|
1782
|
+
const kind = arrayMethod !== void 0 ? "Array" : stringMethod !== void 0 ? "String" : otherMethod?.kind;
|
|
1783
|
+
const name = arrayMethod ?? stringMethod ?? otherMethod?.name;
|
|
1784
|
+
throw new InterpreterError(`${kind} '${name}' does not take a function in the sandbox`);
|
|
1785
|
+
}
|
|
1786
|
+
}
|
|
1787
|
+
const convert = ARGUMENT_CONVERSIONS.get(fn);
|
|
1788
|
+
if (convert) args = convert(args);
|
|
1111
1789
|
const cost = CALL_COSTS.get(fn);
|
|
1112
1790
|
if (cost) this.charge(cost(args));
|
|
1113
1791
|
return args;
|
|
@@ -1117,6 +1795,10 @@ var Interpreter = class {
|
|
|
1117
1795
|
if (name === "match" || name === "matchAll" || name === "search") {
|
|
1118
1796
|
throw new InterpreterError(`String '${name}' is not supported: it runs a regular expression`);
|
|
1119
1797
|
}
|
|
1798
|
+
if (TEXT_SEARCHES.has(name) && args.length > 0) {
|
|
1799
|
+
const pattern = convertedOnce(args[0], String);
|
|
1800
|
+
if (pattern !== args[0]) args = [pattern, ...args.slice(1)];
|
|
1801
|
+
}
|
|
1120
1802
|
if (name === "replace" || name === "replaceAll") {
|
|
1121
1803
|
const replacement = args[1];
|
|
1122
1804
|
if (typeof replacement === "function") {
|
|
@@ -1140,14 +1822,15 @@ var Interpreter = class {
|
|
|
1140
1822
|
return args;
|
|
1141
1823
|
}
|
|
1142
1824
|
if (name === "repeat" || name === "padStart" || name === "padEnd") {
|
|
1143
|
-
const
|
|
1825
|
+
const count = convertedOnce(args[0], Number);
|
|
1826
|
+
const n = Number(count);
|
|
1144
1827
|
const produced = name === "repeat" ? receiver.length * (n > 0 ? n : 0) : Math.max(receiver.length, n > 0 ? n : 0);
|
|
1145
1828
|
if (produced > MAX_STRING_OP_LENGTH) {
|
|
1146
1829
|
throw new InterpreterError(
|
|
1147
1830
|
`String '${name}' would produce ${produced} chars, exceeding the ${MAX_STRING_OP_LENGTH} limit`
|
|
1148
1831
|
);
|
|
1149
1832
|
}
|
|
1150
|
-
return args;
|
|
1833
|
+
return args.length === 0 ? args : [count, ...args.slice(1)];
|
|
1151
1834
|
}
|
|
1152
1835
|
if (name === "concat") {
|
|
1153
1836
|
let produced = receiver.length + arrayText;
|
|
@@ -1161,6 +1844,20 @@ var Interpreter = class {
|
|
|
1161
1844
|
}
|
|
1162
1845
|
return args;
|
|
1163
1846
|
}
|
|
1847
|
+
if (name === "normalize") {
|
|
1848
|
+
const form = convertedOnce(args[0], String);
|
|
1849
|
+
const growth = form === "NFKC" || form === "NFKD" ? 18 : 4;
|
|
1850
|
+
if (receiver.length * growth > MAX_JOIN_LENGTH) {
|
|
1851
|
+
let produced = 0;
|
|
1852
|
+
for (let i = 0; i < receiver.length && produced <= MAX_JOIN_LENGTH; i++) {
|
|
1853
|
+
produced += receiver.charCodeAt(i) < 128 ? 1 : growth;
|
|
1854
|
+
}
|
|
1855
|
+
if (produced > MAX_JOIN_LENGTH) {
|
|
1856
|
+
throw new InterpreterError(`String 'normalize' could produce more than ${MAX_JOIN_LENGTH} chars`);
|
|
1857
|
+
}
|
|
1858
|
+
}
|
|
1859
|
+
return args.length === 0 ? args : [form, ...args.slice(1)];
|
|
1860
|
+
}
|
|
1164
1861
|
if (name === "split") {
|
|
1165
1862
|
const asked = args[1] === void 0 ? Number.POSITIVE_INFINITY : Number(args[1]) >>> 0;
|
|
1166
1863
|
return [args[0], Math.min(asked, MAX_ARRAY_LENGTH + 1)];
|
|
@@ -1173,44 +1870,56 @@ var Interpreter = class {
|
|
|
1173
1870
|
throw new InterpreterError(`An array cannot be longer than ${MAX_ARRAY_LENGTH} items`);
|
|
1174
1871
|
};
|
|
1175
1872
|
switch (name) {
|
|
1873
|
+
// Written by the interpreter itself, one item at a time (see arrayLocaleText): how long
|
|
1874
|
+
// the text of a number or a date is depends on the locale and the options.
|
|
1875
|
+
case "toLocaleString":
|
|
1876
|
+
return args;
|
|
1176
1877
|
// `join` writes every item and a separator between them into one string, in one step; so
|
|
1177
|
-
//
|
|
1878
|
+
// does the conversion to text.
|
|
1178
1879
|
case "join":
|
|
1179
|
-
case "toString":
|
|
1180
|
-
|
|
1181
|
-
const separator =
|
|
1880
|
+
case "toString": {
|
|
1881
|
+
const given = name !== "join" || args.length === 0 ? void 0 : convertedOnce(args[0], String);
|
|
1882
|
+
const separator = given === void 0 ? "," : String(given);
|
|
1182
1883
|
const measure = newTextMeasure();
|
|
1183
1884
|
measureArrayText(receiver, separator.length, measure, 0);
|
|
1184
1885
|
if (measure.length > MAX_JOIN_LENGTH) {
|
|
1185
1886
|
throw new InterpreterError(`Array '${name}' would produce more than ${MAX_JOIN_LENGTH} chars`);
|
|
1186
1887
|
}
|
|
1187
|
-
|
|
1888
|
+
this.work(measure.work);
|
|
1889
|
+
return name === "join" && args.length > 0 ? [given, ...args.slice(1)] : args;
|
|
1188
1890
|
}
|
|
1189
1891
|
// Without a comparison function the engine compares the items as text: strings as they
|
|
1190
1892
|
// are, and an array among the items joined, again for every comparison.
|
|
1191
1893
|
case "sort":
|
|
1192
1894
|
case "toSorted": {
|
|
1193
|
-
if (typeof args[0] === "function") return;
|
|
1895
|
+
if (typeof args[0] === "function") return args;
|
|
1194
1896
|
const measure = newTextMeasure();
|
|
1897
|
+
let chars = 0;
|
|
1195
1898
|
for (let i = 0; i < receiver.length && measure.length <= MAX_JOIN_LENGTH; i++) {
|
|
1196
1899
|
const item = receiver[i];
|
|
1197
1900
|
if (Array.isArray(item)) measureArrayText(item, 1, measure, 1);
|
|
1901
|
+
else chars += typeof item === "string" ? item.length : 32;
|
|
1198
1902
|
}
|
|
1199
1903
|
if (measure.length > MAX_JOIN_LENGTH) throw new InterpreterError(TEXT_TOO_LONG);
|
|
1200
|
-
|
|
1904
|
+
const compared = (chars + measure.length) * (Math.ceil(Math.log2(receiver.length + 1)) + 6);
|
|
1905
|
+
if (compared > MAX_CALL_WORK) {
|
|
1906
|
+
throw new InterpreterError(`Array '${name}' would compare more text than one call may`);
|
|
1907
|
+
}
|
|
1908
|
+
this.work(compared);
|
|
1909
|
+
return args;
|
|
1201
1910
|
}
|
|
1202
1911
|
// Growth by the arguments (a spread makes them many): charged before it happens.
|
|
1203
1912
|
case "push":
|
|
1204
1913
|
case "unshift":
|
|
1205
1914
|
if (receiver.length + args.length > MAX_ARRAY_LENGTH) tooLong2();
|
|
1206
1915
|
this.charge(args.length * 8);
|
|
1207
|
-
return;
|
|
1916
|
+
return args;
|
|
1208
1917
|
case "splice":
|
|
1209
1918
|
case "toSpliced": {
|
|
1210
1919
|
const added = Math.max(0, args.length - 2);
|
|
1211
1920
|
if (receiver.length + added > MAX_ARRAY_LENGTH) tooLong2();
|
|
1212
1921
|
if (name === "splice") this.charge(added * 8);
|
|
1213
|
-
return;
|
|
1922
|
+
return args;
|
|
1214
1923
|
}
|
|
1215
1924
|
// A new array of the receiver and every array among the arguments: one array, given many
|
|
1216
1925
|
// times, is small in memory and large once copied.
|
|
@@ -1221,16 +1930,50 @@ var Interpreter = class {
|
|
|
1221
1930
|
length += Array.isArray(arg) ? arg.length : 1;
|
|
1222
1931
|
}
|
|
1223
1932
|
if (length > MAX_ARRAY_LENGTH) tooLong2();
|
|
1224
|
-
return;
|
|
1933
|
+
return args;
|
|
1225
1934
|
}
|
|
1226
1935
|
case "flat": {
|
|
1227
|
-
const
|
|
1936
|
+
const given = convertedOnce(args[0], Number);
|
|
1937
|
+
const depth = given === void 0 ? 1 : Number(given);
|
|
1228
1938
|
if (flatLength(receiver, Number.isNaN(depth) ? 0 : depth, MAX_ARRAY_LENGTH) > MAX_ARRAY_LENGTH) tooLong2();
|
|
1229
|
-
return;
|
|
1939
|
+
return args.length === 0 ? args : [given, ...args.slice(1)];
|
|
1230
1940
|
}
|
|
1231
1941
|
default:
|
|
1232
|
-
return;
|
|
1942
|
+
return args;
|
|
1943
|
+
}
|
|
1944
|
+
}
|
|
1945
|
+
/**
|
|
1946
|
+
* `array.toLocaleString(locales, options)`: the text of every item in the locale's format,
|
|
1947
|
+
* joined by commas, as the engine writes it. The engine does it in one step and the length of
|
|
1948
|
+
* what an item becomes is not known beforehand (a number can take hundreds of chars with the
|
|
1949
|
+
* right options), so the items are converted here one at a time: each counts as a step, and
|
|
1950
|
+
* the text is refused as soon as it is longer than a script's longest text.
|
|
1951
|
+
*/
|
|
1952
|
+
arrayLocaleText(array, args, active, written, depth) {
|
|
1953
|
+
if (depth > MAX_TEXT_NESTING) throw new InterpreterError(TEXT_TOO_LONG);
|
|
1954
|
+
const parts = [];
|
|
1955
|
+
active.add(array);
|
|
1956
|
+
try {
|
|
1957
|
+
for (let i = 0; i < array.length; i++) {
|
|
1958
|
+
this.tick();
|
|
1959
|
+
const item = array[i];
|
|
1960
|
+
let text = "";
|
|
1961
|
+
if (Array.isArray(item) && item.toLocaleString === ArrayProtoToLocaleString) {
|
|
1962
|
+
if (!active.has(item)) text = this.arrayLocaleText(item, args, active, written, depth + 1);
|
|
1963
|
+
} else if (item !== null && item !== void 0) {
|
|
1964
|
+
text = String(item.toLocaleString(...args));
|
|
1965
|
+
written.length += text.length;
|
|
1966
|
+
}
|
|
1967
|
+
if (i > 0) written.length += 1;
|
|
1968
|
+
if (written.length > MAX_JOIN_LENGTH) {
|
|
1969
|
+
throw new InterpreterError(`Array 'toLocaleString' would produce more than ${MAX_JOIN_LENGTH} chars`);
|
|
1970
|
+
}
|
|
1971
|
+
parts.push(text);
|
|
1972
|
+
}
|
|
1973
|
+
} finally {
|
|
1974
|
+
active.delete(array);
|
|
1233
1975
|
}
|
|
1976
|
+
return parts.join(",");
|
|
1234
1977
|
}
|
|
1235
1978
|
/**
|
|
1236
1979
|
* Async implementations of the higher-order array methods, so interpreter
|
|
@@ -1303,10 +2046,30 @@ var Interpreter = class {
|
|
|
1303
2046
|
acc = arr[order[0]];
|
|
1304
2047
|
start = 1;
|
|
1305
2048
|
}
|
|
2049
|
+
let owed = 0;
|
|
1306
2050
|
for (let n = start; n < order.length; n++) {
|
|
1307
2051
|
this.tick();
|
|
1308
|
-
|
|
2052
|
+
let pending;
|
|
2053
|
+
if (interpreted !== void 0 && typeof acc === "string") {
|
|
2054
|
+
this.accumulatorOwed = owed;
|
|
2055
|
+
try {
|
|
2056
|
+
pending = reducer(acc, arr[order[n]], order[n], arr);
|
|
2057
|
+
} finally {
|
|
2058
|
+
this.accumulatorOwed = void 0;
|
|
2059
|
+
}
|
|
2060
|
+
} else {
|
|
2061
|
+
pending = reducer(acc, arr[order[n]], order[n], arr);
|
|
2062
|
+
}
|
|
2063
|
+
const next = await pending;
|
|
2064
|
+
if (next instanceof AccumulatedText) {
|
|
2065
|
+
acc = next.value;
|
|
2066
|
+
owed = next.owed;
|
|
2067
|
+
} else {
|
|
2068
|
+
acc = next;
|
|
2069
|
+
owed = 0;
|
|
2070
|
+
}
|
|
1309
2071
|
}
|
|
2072
|
+
if (owed > 0) this.charge(owed);
|
|
1310
2073
|
return acc;
|
|
1311
2074
|
}
|
|
1312
2075
|
case "sort":
|
|
@@ -1404,7 +2167,9 @@ var Interpreter = class {
|
|
|
1404
2167
|
const rest = {};
|
|
1405
2168
|
for (const key2 of Object.keys(source)) {
|
|
1406
2169
|
this.tick();
|
|
1407
|
-
if (
|
|
2170
|
+
if (taken.has(key2) || BLOCKED_KEYS.has(key2)) continue;
|
|
2171
|
+
assertStorable(rest, key2, source[key2]);
|
|
2172
|
+
rest[key2] = source[key2];
|
|
1408
2173
|
}
|
|
1409
2174
|
await this.applyPattern(prop.argument, rest, scope, mode);
|
|
1410
2175
|
continue;
|
|
@@ -1429,7 +2194,7 @@ var Interpreter = class {
|
|
|
1429
2194
|
if (node.generator) throw new InterpreterError("Generator functions are not supported");
|
|
1430
2195
|
const selfName = node.type === "FunctionExpression" && node.id ? node.id.name : void 0;
|
|
1431
2196
|
const outer = selfName === void 0 ? closure : closure.child();
|
|
1432
|
-
const call = async (args, callerDepth) => {
|
|
2197
|
+
const call = async (args, callerDepth, accumulatorOwed) => {
|
|
1433
2198
|
const fnScope = outer.activation(this.enterCall(callerDepth));
|
|
1434
2199
|
try {
|
|
1435
2200
|
for (let i = 0; i < node.params.length; i++) {
|
|
@@ -1440,11 +2205,19 @@ var Interpreter = class {
|
|
|
1440
2205
|
}
|
|
1441
2206
|
await this.applyPattern(param, args[i], fnScope, "let");
|
|
1442
2207
|
}
|
|
2208
|
+
const first = node.params[0];
|
|
2209
|
+
if (accumulatorOwed !== void 0 && first?.type === "Identifier" && typeof args[0] === "string") {
|
|
2210
|
+
const accumulator = fnScope.slot(first.name);
|
|
2211
|
+
if (accumulator !== void 0) {
|
|
2212
|
+
accumulator.owed = accumulatorOwed;
|
|
2213
|
+
fnScope.accumulator = first.name;
|
|
2214
|
+
}
|
|
2215
|
+
}
|
|
1443
2216
|
if (node.body.type === "BlockStatement") {
|
|
1444
2217
|
await this.execBlock(node.body.body, fnScope);
|
|
1445
2218
|
return void 0;
|
|
1446
2219
|
}
|
|
1447
|
-
return await this.
|
|
2220
|
+
return await this.evalReturned(node.body, fnScope);
|
|
1448
2221
|
} catch (e) {
|
|
1449
2222
|
if (e instanceof ReturnSignal) return e.value;
|
|
1450
2223
|
throw e;
|
|
@@ -1453,8 +2226,13 @@ var Interpreter = class {
|
|
|
1453
2226
|
}
|
|
1454
2227
|
};
|
|
1455
2228
|
const depthOfCaller = () => this.callerDepth;
|
|
2229
|
+
const takeAccumulatorOwed = () => {
|
|
2230
|
+
const owed = this.accumulatorOwed;
|
|
2231
|
+
this.accumulatorOwed = void 0;
|
|
2232
|
+
return owed;
|
|
2233
|
+
};
|
|
1456
2234
|
const interpreted = function interpreted2(...args) {
|
|
1457
|
-
const result = call(args, depthOfCaller());
|
|
2235
|
+
const result = call(args, depthOfCaller(), takeAccumulatorOwed());
|
|
1458
2236
|
result.then(void 0, ignoreRejection2);
|
|
1459
2237
|
return result;
|
|
1460
2238
|
};
|
|
@@ -1464,7 +2242,9 @@ var Interpreter = class {
|
|
|
1464
2242
|
}
|
|
1465
2243
|
/** A computed property key as text. An array as a key is its items, joined. */
|
|
1466
2244
|
keyText(value) {
|
|
1467
|
-
|
|
2245
|
+
this.arrayOperands(value);
|
|
2246
|
+
this.bigIntAsText(value);
|
|
2247
|
+
this.work(operandSize(value));
|
|
1468
2248
|
return String(value);
|
|
1469
2249
|
}
|
|
1470
2250
|
async propKey(prop, scope) {
|
|
@@ -1491,6 +2271,41 @@ function isScriptData(value) {
|
|
|
1491
2271
|
const prototype = Object.getPrototypeOf(value);
|
|
1492
2272
|
return prototype === Object.prototype || prototype === null;
|
|
1493
2273
|
}
|
|
2274
|
+
function operandSize(value) {
|
|
2275
|
+
return typeof value === "string" || Array.isArray(value) ? value.length : 0;
|
|
2276
|
+
}
|
|
2277
|
+
function integerOf(value) {
|
|
2278
|
+
const number = Number(value);
|
|
2279
|
+
return Number.isNaN(number) ? 0 : Math.trunc(number);
|
|
2280
|
+
}
|
|
2281
|
+
function expandReplacement(template, text, at, matched) {
|
|
2282
|
+
if (!template.includes("$")) return template;
|
|
2283
|
+
let out = "";
|
|
2284
|
+
for (let i = 0; i < template.length; i++) {
|
|
2285
|
+
const next = template[i] === "$" ? template[i + 1] : void 0;
|
|
2286
|
+
if (next === "$") out += "$";
|
|
2287
|
+
else if (next === "&") out += matched;
|
|
2288
|
+
else if (next === "`") out += text.substring(0, at);
|
|
2289
|
+
else if (next === "'") out += text.substring(at + matched.length);
|
|
2290
|
+
else {
|
|
2291
|
+
out += template[i];
|
|
2292
|
+
continue;
|
|
2293
|
+
}
|
|
2294
|
+
i++;
|
|
2295
|
+
}
|
|
2296
|
+
return out;
|
|
2297
|
+
}
|
|
2298
|
+
function convertedOnce(value, convert) {
|
|
2299
|
+
return typeof value === "object" && value !== null ? convert(value) : value;
|
|
2300
|
+
}
|
|
2301
|
+
function checkArrayWrite(array, key, value) {
|
|
2302
|
+
if (key === "length") value = convertedOnce(value, Number);
|
|
2303
|
+
const length = arrayLengthAfterWrite(array, key, value);
|
|
2304
|
+
if (length > MAX_ARRAY_LENGTH) {
|
|
2305
|
+
throw new InterpreterError(`An array cannot be longer than ${MAX_ARRAY_LENGTH} items`);
|
|
2306
|
+
}
|
|
2307
|
+
return { value, length };
|
|
2308
|
+
}
|
|
1494
2309
|
function arrayLengthAfterWrite(array, key, value) {
|
|
1495
2310
|
if (key === "length") {
|
|
1496
2311
|
const length = Number(value);
|
|
@@ -1552,8 +2367,6 @@ function isPlainObject(value) {
|
|
|
1552
2367
|
function sanitizeValue(value, options = {}, depth = 0, context = { propCount: { count: 0 }, visited: /* @__PURE__ */ new WeakSet() }) {
|
|
1553
2368
|
const maxDepth = options.maxDepth ?? 20;
|
|
1554
2369
|
const maxProperties = options.maxProperties ?? 1e4;
|
|
1555
|
-
const allowDates = options.allowDates ?? true;
|
|
1556
|
-
const allowErrors = options.allowErrors ?? true;
|
|
1557
2370
|
if (depth > maxDepth) {
|
|
1558
2371
|
throw new Error(
|
|
1559
2372
|
`Tool handler return value exceeds maximum depth (${maxDepth}). This limit prevents deeply nested objects that could cause stack overflow.`
|
|
@@ -1589,7 +2402,19 @@ function sanitizeValue(value, options = {}, depth = 0, context = { propCount: {
|
|
|
1589
2402
|
return "[Circular]";
|
|
1590
2403
|
}
|
|
1591
2404
|
context.visited.add(value);
|
|
2405
|
+
try {
|
|
2406
|
+
return sanitizeObjectValue(value, options, depth, context);
|
|
2407
|
+
} finally {
|
|
2408
|
+
context.visited.delete(value);
|
|
2409
|
+
}
|
|
1592
2410
|
}
|
|
2411
|
+
return String(value);
|
|
2412
|
+
}
|
|
2413
|
+
function sanitizeObjectValue(value, options, depth, context) {
|
|
2414
|
+
const maxProperties = options.maxProperties ?? 1e4;
|
|
2415
|
+
const allowDates = options.allowDates ?? true;
|
|
2416
|
+
const allowErrors = options.allowErrors ?? true;
|
|
2417
|
+
const type = typeof value;
|
|
1593
2418
|
if (ArrayIsArray(value)) {
|
|
1594
2419
|
const rawLen = ReflectGet(value, "length");
|
|
1595
2420
|
const len = typeof rawLen === "number" && NumberIsFinite(rawLen) && rawLen >= 0 ? MathFloor(rawLen) : 0;
|
|
@@ -1944,7 +2769,8 @@ var SafeJSON = frozenRecord({
|
|
|
1944
2769
|
}
|
|
1945
2770
|
const size = checkSerializedSize(value, MAX_JSON_TEXT_BYTES);
|
|
1946
2771
|
if (!size.ok) throw new RangeError(`JSON.stringify: the text would be too large (${size.error})`);
|
|
1947
|
-
const
|
|
2772
|
+
const indentation = typeof space === "number" || typeof space === "string" ? space : void 0;
|
|
2773
|
+
const indent = indentOf(indentation);
|
|
1948
2774
|
if (indent > 0) {
|
|
1949
2775
|
const budget = MAX_JSON_TEXT_BYTES - size.estimatedBytes;
|
|
1950
2776
|
if (indentationSize(value, indent, budget, 0, /* @__PURE__ */ new Set()) > budget) {
|
|
@@ -1954,10 +2780,14 @@ var SafeJSON = frozenRecord({
|
|
|
1954
2780
|
return JSON.stringify(
|
|
1955
2781
|
value,
|
|
1956
2782
|
Array.isArray(replacer) ? replacer : void 0,
|
|
1957
|
-
|
|
2783
|
+
indentation
|
|
1958
2784
|
);
|
|
1959
2785
|
}
|
|
1960
2786
|
});
|
|
2787
|
+
convertsBeforeCall(
|
|
2788
|
+
SafeJSON["parse"],
|
|
2789
|
+
(args) => args.length === 0 ? args : [String(args[0]), ...args.slice(1)]
|
|
2790
|
+
);
|
|
1961
2791
|
chargedBeforeCall(SafeJSON["parse"], (args) => parsedJsonCost(String(args[0])));
|
|
1962
2792
|
takesArraysAsData(SafeJSON["stringify"]);
|
|
1963
2793
|
var SafeObject = frozenRecord({
|
|
@@ -1972,7 +2802,10 @@ var SafeObject = frozenRecord({
|
|
|
1972
2802
|
if (entry === null || typeof entry !== "object") throw new TypeError("Each entry must be a [key, value] pair");
|
|
1973
2803
|
assertArrayTextWithinLimit(entry[0]);
|
|
1974
2804
|
const key = String(entry[0]);
|
|
1975
|
-
if (
|
|
2805
|
+
if (isBlockedKey(key)) continue;
|
|
2806
|
+
const value = entry[1];
|
|
2807
|
+
assertStorable(result, key, value);
|
|
2808
|
+
result[key] = value;
|
|
1976
2809
|
}
|
|
1977
2810
|
return result;
|
|
1978
2811
|
},
|
|
@@ -1983,7 +2816,10 @@ var SafeObject = frozenRecord({
|
|
|
1983
2816
|
for (const source of sources) {
|
|
1984
2817
|
if (source === null || source === void 0) continue;
|
|
1985
2818
|
for (const key of dataKeys(source)) {
|
|
1986
|
-
|
|
2819
|
+
let value = source[key];
|
|
2820
|
+
assertStorable(target, key, value);
|
|
2821
|
+
if (Array.isArray(target)) value = checkArrayWrite(target, key, value).value;
|
|
2822
|
+
target[key] = value;
|
|
1987
2823
|
}
|
|
1988
2824
|
}
|
|
1989
2825
|
return target;
|
|
@@ -2058,6 +2894,23 @@ var SafeDate = frozenFunction(() => (/* @__PURE__ */ new Date()).toString(), {
|
|
|
2058
2894
|
parse: (text) => Date.parse(String(text)),
|
|
2059
2895
|
UTC: (...parts) => Date.UTC(...parts)
|
|
2060
2896
|
});
|
|
2897
|
+
function encodedText(encode, value) {
|
|
2898
|
+
const text = String(value);
|
|
2899
|
+
if (text.length * 9 > MAX_JOIN_LENGTH) {
|
|
2900
|
+
let produced = 0;
|
|
2901
|
+
for (let index = 0; index < text.length && produced <= MAX_JOIN_LENGTH; index++) {
|
|
2902
|
+
const code = text.charCodeAt(index);
|
|
2903
|
+
if (code >= 2048) produced += 9;
|
|
2904
|
+
else if (code >= 128) produced += 6;
|
|
2905
|
+
else if (code >= 48 && code <= 57 || code >= 65 && code <= 90 || code >= 97 && code <= 122) produced += 1;
|
|
2906
|
+
else produced += 3;
|
|
2907
|
+
}
|
|
2908
|
+
if (produced > MAX_JOIN_LENGTH) {
|
|
2909
|
+
throw new RangeError(`The encoded text would be too long (more than ${MAX_JOIN_LENGTH} chars)`);
|
|
2910
|
+
}
|
|
2911
|
+
}
|
|
2912
|
+
return encode(text);
|
|
2913
|
+
}
|
|
2061
2914
|
var ERROR_TYPES = ["Error", "TypeError", "RangeError", "SyntaxError", "ReferenceError", "EvalError", "URIError"];
|
|
2062
2915
|
function errorType(name) {
|
|
2063
2916
|
const make = (args) => createScriptError(name, args.length === 0 || args[0] === void 0 ? "" : toStringValue(args[0]));
|
|
@@ -2088,8 +2941,8 @@ var SAFE_GLOBALS = Object.freeze({
|
|
|
2088
2941
|
parseInt: Object.freeze(
|
|
2089
2942
|
(value, radix) => Number.parseInt(String(value), radix)
|
|
2090
2943
|
),
|
|
2091
|
-
encodeURI: Object.freeze((value) => encodeURI
|
|
2092
|
-
encodeURIComponent: Object.freeze((value) => encodeURIComponent
|
|
2944
|
+
encodeURI: Object.freeze((value) => encodedText(encodeURI, value)),
|
|
2945
|
+
encodeURIComponent: Object.freeze((value) => encodedText(encodeURIComponent, value)),
|
|
2093
2946
|
decodeURI: Object.freeze((value) => decodeURI(String(value))),
|
|
2094
2947
|
decodeURIComponent: Object.freeze((value) => decodeURIComponent(String(value)))
|
|
2095
2948
|
});
|
|
@@ -2203,6 +3056,8 @@ var MemoryTracker = class {
|
|
|
2203
3056
|
trackedBytes = 0;
|
|
2204
3057
|
peakTrackedBytes = 0;
|
|
2205
3058
|
allocationCount = 0;
|
|
3059
|
+
/** Whether this tracker has refused an allocation since it was started */
|
|
3060
|
+
limitExceeded = false;
|
|
2206
3061
|
config;
|
|
2207
3062
|
constructor(config = {}) {
|
|
2208
3063
|
this.config = {
|
|
@@ -2219,6 +3074,14 @@ var MemoryTracker = class {
|
|
|
2219
3074
|
this.trackedBytes = 0;
|
|
2220
3075
|
this.peakTrackedBytes = 0;
|
|
2221
3076
|
this.allocationCount = 0;
|
|
3077
|
+
this.limitExceeded = false;
|
|
3078
|
+
}
|
|
3079
|
+
/**
|
|
3080
|
+
* Whether the limit was exceeded since tracking started: the tracker itself refused an
|
|
3081
|
+
* allocation. An error that only says so about itself is not evidence of that.
|
|
3082
|
+
*/
|
|
3083
|
+
hasExceededLimit() {
|
|
3084
|
+
return this.limitExceeded;
|
|
2222
3085
|
}
|
|
2223
3086
|
/**
|
|
2224
3087
|
* Track an allocation
|
|
@@ -2229,6 +3092,7 @@ var MemoryTracker = class {
|
|
|
2229
3092
|
track(bytes) {
|
|
2230
3093
|
if (typeof bytes !== "number" || Number.isNaN(bytes)) {
|
|
2231
3094
|
if (this.config.memoryLimit > 0) {
|
|
3095
|
+
this.limitExceeded = true;
|
|
2232
3096
|
throw new MemoryLimitError(
|
|
2233
3097
|
"Memory limit exceeded: allocation size is not a number",
|
|
2234
3098
|
this.trackedBytes,
|
|
@@ -2244,6 +3108,7 @@ var MemoryTracker = class {
|
|
|
2244
3108
|
this.peakTrackedBytes = this.trackedBytes;
|
|
2245
3109
|
}
|
|
2246
3110
|
if (this.config.memoryLimit > 0 && this.trackedBytes > this.config.memoryLimit) {
|
|
3111
|
+
this.limitExceeded = true;
|
|
2247
3112
|
throw new MemoryLimitError(
|
|
2248
3113
|
`Memory limit exceeded: ${this.formatBytes(this.trackedBytes)} used > ${this.formatBytes(
|
|
2249
3114
|
this.config.memoryLimit
|
|
@@ -2435,6 +3300,18 @@ function isReferenceId(value) {
|
|
|
2435
3300
|
return typeof value === "string" && REF_ID_PATTERN.test(value);
|
|
2436
3301
|
}
|
|
2437
3302
|
|
|
3303
|
+
// libs/core/src/sidecar/reference-sidecar.ts
|
|
3304
|
+
var SidecarLimitError = class _SidecarLimitError extends Error {
|
|
3305
|
+
constructor(message, code, limit, current) {
|
|
3306
|
+
super(message);
|
|
3307
|
+
this.code = code;
|
|
3308
|
+
this.limit = limit;
|
|
3309
|
+
this.current = current;
|
|
3310
|
+
this.name = "SidecarLimitError";
|
|
3311
|
+
Object.setPrototypeOf(this, _SidecarLimitError.prototype);
|
|
3312
|
+
}
|
|
3313
|
+
};
|
|
3314
|
+
|
|
2438
3315
|
// libs/core/src/sidecar/reference-resolver.ts
|
|
2439
3316
|
var ReflectGet2 = Reflect.get;
|
|
2440
3317
|
var NumberIsFinite2 = Number.isFinite;
|
|
@@ -2542,17 +3419,88 @@ var ReferenceResolver = class {
|
|
|
2542
3419
|
/**
|
|
2543
3420
|
* Check if resolution would exceed size limits
|
|
2544
3421
|
*
|
|
3422
|
+
* Two limits apply: `maxResolvedSize` to what this value expands to, and
|
|
3423
|
+
* `maxTotalResolvedSize` to what the execution has had resolved so far plus what resolving
|
|
3424
|
+
* this value would add (see `predictAddedSize`).
|
|
3425
|
+
*
|
|
2545
3426
|
* @param value - The value to check
|
|
2546
|
-
* @returns true if resolution would exceed maxResolvedSize
|
|
3427
|
+
* @returns true if resolution would exceed maxResolvedSize or the execution's total
|
|
2547
3428
|
*/
|
|
2548
3429
|
wouldExceedLimit(value) {
|
|
2549
3430
|
try {
|
|
2550
3431
|
const size = this.predictExpandedSize(value);
|
|
2551
|
-
|
|
3432
|
+
if (size > this.config.maxResolvedSize) {
|
|
3433
|
+
return true;
|
|
3434
|
+
}
|
|
3435
|
+
return !this.sidecar.canResolve(this.predictAddedSize(value, 0, /* @__PURE__ */ new Set()));
|
|
2552
3436
|
} catch {
|
|
2553
3437
|
return true;
|
|
2554
3438
|
}
|
|
2555
3439
|
}
|
|
3440
|
+
/**
|
|
3441
|
+
* Predict what resolving a value would add to the execution's total of resolved data,
|
|
3442
|
+
* WITHOUT allocating memory
|
|
3443
|
+
*
|
|
3444
|
+
* A stored value adds its size the first time it is resolved in the execution and nothing
|
|
3445
|
+
* afterwards (`counted` holds the ones this walk has seen). A composite adds the size of the
|
|
3446
|
+
* string it is joined into, every time, besides what its parts add.
|
|
3447
|
+
*/
|
|
3448
|
+
predictAddedSize(value, depth, counted) {
|
|
3449
|
+
if (depth > this.config.maxResolutionDepth) {
|
|
3450
|
+
throw new ResolutionLimitError(
|
|
3451
|
+
`Maximum resolution depth exceeded (${this.config.maxResolutionDepth})`,
|
|
3452
|
+
"MAX_RESOLUTION_DEPTH",
|
|
3453
|
+
this.config.maxResolutionDepth,
|
|
3454
|
+
depth
|
|
3455
|
+
);
|
|
3456
|
+
}
|
|
3457
|
+
if (isReferenceId(value)) {
|
|
3458
|
+
if (counted.has(value) || this.sidecar.isResolved(value)) {
|
|
3459
|
+
return 0;
|
|
3460
|
+
}
|
|
3461
|
+
counted.add(value);
|
|
3462
|
+
return this.sidecar.getSize(value) ?? 0;
|
|
3463
|
+
}
|
|
3464
|
+
if (isCompositeHandle(value)) {
|
|
3465
|
+
const parts = value.__parts;
|
|
3466
|
+
const len = untrustedLength(parts);
|
|
3467
|
+
let sum = this.predictExpandedSize(value, depth);
|
|
3468
|
+
for (let i = 0; i < len; i++) {
|
|
3469
|
+
sum += this.predictAddedSize(untrustedAt(parts, i), depth + 1, counted);
|
|
3470
|
+
}
|
|
3471
|
+
return sum;
|
|
3472
|
+
}
|
|
3473
|
+
if (Array.isArray(value)) {
|
|
3474
|
+
const len = untrustedLength(value);
|
|
3475
|
+
let sum = 0;
|
|
3476
|
+
for (let i = 0; i < len; i++) {
|
|
3477
|
+
sum += this.predictAddedSize(untrustedAt(value, i), depth + 1, counted);
|
|
3478
|
+
}
|
|
3479
|
+
return sum;
|
|
3480
|
+
}
|
|
3481
|
+
if (value !== null && typeof value === "object") {
|
|
3482
|
+
let sum = 0;
|
|
3483
|
+
for (const val of Object.values(value)) {
|
|
3484
|
+
sum += this.predictAddedSize(val, depth + 1, counted);
|
|
3485
|
+
}
|
|
3486
|
+
return sum;
|
|
3487
|
+
}
|
|
3488
|
+
return 0;
|
|
3489
|
+
}
|
|
3490
|
+
/**
|
|
3491
|
+
* Run a step that counts resolved data against the execution's total; when the sidecar
|
|
3492
|
+
* refuses it, the refusal is thrown as the resolution error callers of `resolve` handle
|
|
3493
|
+
*/
|
|
3494
|
+
withinTotal(count) {
|
|
3495
|
+
try {
|
|
3496
|
+
count();
|
|
3497
|
+
} catch (error) {
|
|
3498
|
+
if (error instanceof SidecarLimitError) {
|
|
3499
|
+
throw new ResolutionLimitError(error.message, error.code, error.limit, error.current);
|
|
3500
|
+
}
|
|
3501
|
+
throw error;
|
|
3502
|
+
}
|
|
3503
|
+
}
|
|
2556
3504
|
/**
|
|
2557
3505
|
* Resolve all reference IDs in a value tree
|
|
2558
3506
|
*
|
|
@@ -2575,7 +3523,10 @@ var ReferenceResolver = class {
|
|
|
2575
3523
|
);
|
|
2576
3524
|
}
|
|
2577
3525
|
if (isReferenceId(value)) {
|
|
2578
|
-
|
|
3526
|
+
let data;
|
|
3527
|
+
this.withinTotal(() => {
|
|
3528
|
+
data = this.sidecar.resolveString(value);
|
|
3529
|
+
});
|
|
2579
3530
|
if (data === void 0) {
|
|
2580
3531
|
throw new Error(`Unknown reference: ${value}`);
|
|
2581
3532
|
}
|
|
@@ -2613,6 +3564,8 @@ var ReferenceResolver = class {
|
|
|
2613
3564
|
* Resolve a composite handle by concatenating its parts
|
|
2614
3565
|
*/
|
|
2615
3566
|
resolveComposite(handle, depth) {
|
|
3567
|
+
const joinedSize = this.predictExpandedSize(handle, depth);
|
|
3568
|
+
this.withinTotal(() => this.sidecar.countResolved(joinedSize));
|
|
2616
3569
|
const out = [];
|
|
2617
3570
|
const source = handle.__parts;
|
|
2618
3571
|
const len = untrustedLength(source);
|
|
@@ -3258,12 +4211,29 @@ var MAX_PARALLEL_ITEMS = 100;
|
|
|
3258
4211
|
var MAX_SERIALIZED_RESULT_BYTES = 50 * 1024 * 1024;
|
|
3259
4212
|
var DEFAULT_MAX_CONSOLE_CALLS = 100;
|
|
3260
4213
|
var DEFAULT_MAX_CONSOLE_OUTPUT_BYTES = 64 * 1024;
|
|
4214
|
+
var DEFAULT_MAX_TOOL_PAYLOAD_BYTES = 5 * 1024 * 1024;
|
|
4215
|
+
function certainlyLargerThan(value, bytes) {
|
|
4216
|
+
if (!Number.isFinite(bytes) || bytes <= 0) return false;
|
|
4217
|
+
return !checkSerializedSize(value, bytes).ok;
|
|
4218
|
+
}
|
|
4219
|
+
function executionOver() {
|
|
4220
|
+
return sandboxError("Execution ended");
|
|
4221
|
+
}
|
|
3261
4222
|
function sandboxError(message, name = "Error", code) {
|
|
3262
4223
|
const error = new Error(message);
|
|
3263
4224
|
error.name = name;
|
|
3264
4225
|
if (code !== void 0) error.code = code;
|
|
3265
4226
|
return error;
|
|
3266
4227
|
}
|
|
4228
|
+
function ignoreRejection3() {
|
|
4229
|
+
}
|
|
4230
|
+
function observed(helper) {
|
|
4231
|
+
return (...args) => {
|
|
4232
|
+
const result = helper(...args);
|
|
4233
|
+
result.then(void 0, ignoreRejection3);
|
|
4234
|
+
return result;
|
|
4235
|
+
};
|
|
4236
|
+
}
|
|
3267
4237
|
function frozenRecord2(members) {
|
|
3268
4238
|
const record = /* @__PURE__ */ Object.create(null);
|
|
3269
4239
|
for (const key of Object.keys(members)) record[key] = members[key];
|
|
@@ -3330,15 +4300,20 @@ var InterpreterAdapter = class {
|
|
|
3330
4300
|
const allocationLimit = typeof memoryLimit === "number" && memoryLimit > 0 ? Math.min(memoryLimit, adapterLimit) : adapterLimit;
|
|
3331
4301
|
const tracker = new MemoryTracker({ memoryLimit: Number.isFinite(allocationLimit) ? allocationLimit : 0 });
|
|
3332
4302
|
const charge = (bytes) => tracker.track(bytes);
|
|
4303
|
+
let chargeForHelper = (_bytes) => {
|
|
4304
|
+
throw sandboxError("The interpreter is not running");
|
|
4305
|
+
};
|
|
4306
|
+
const timeout = context.config.timeout;
|
|
4307
|
+
const deadlineAt = timeout && timeout > 0 ? Date.now() + timeout : void 0;
|
|
3333
4308
|
let interpreter;
|
|
4309
|
+
const callbacks = {
|
|
4310
|
+
call: () => {
|
|
4311
|
+
throw sandboxError("The interpreter is not running");
|
|
4312
|
+
}
|
|
4313
|
+
};
|
|
3334
4314
|
try {
|
|
3335
4315
|
const safe = createSafeGlobals();
|
|
3336
|
-
const
|
|
3337
|
-
call: () => {
|
|
3338
|
-
throw sandboxError("The interpreter is not running");
|
|
3339
|
-
}
|
|
3340
|
-
};
|
|
3341
|
-
const runtime = this.runtimeGlobals(context, charge, callbacks);
|
|
4316
|
+
const runtime = this.runtimeGlobals(context, (bytes) => chargeForHelper(bytes), callbacks);
|
|
3342
4317
|
for (const name of Object.keys(runtime)) {
|
|
3343
4318
|
if (!Object.prototype.hasOwnProperty.call(safe.globals, name)) safe.globals[name] = runtime[name];
|
|
3344
4319
|
}
|
|
@@ -3350,37 +4325,40 @@ var InterpreterAdapter = class {
|
|
|
3350
4325
|
maxCallDepth: this.options.maxCallDepth ?? DEFAULT_MAX_CALL_DEPTH,
|
|
3351
4326
|
maxPendingCalls: this.options.maxPendingCalls,
|
|
3352
4327
|
signal: context.abortController.signal,
|
|
4328
|
+
deadline: deadlineAt,
|
|
3353
4329
|
charge
|
|
3354
4330
|
});
|
|
3355
|
-
const
|
|
3356
|
-
callbacks.call = (fn, args) =>
|
|
4331
|
+
const running2 = interpreter;
|
|
4332
|
+
callbacks.call = (fn, args) => running2.call(fn, args);
|
|
4333
|
+
callbacks.countBigInt = (value) => running2.countBigInt(value);
|
|
4334
|
+
chargeForHelper = (bytes) => running2.chargeAllocation(bytes);
|
|
3357
4335
|
} catch (error) {
|
|
3358
4336
|
return this.fail(error, startTime, stats.toolCallCount, 0, sanitizeStacks);
|
|
3359
4337
|
}
|
|
3360
|
-
const timeout = context.config.timeout;
|
|
3361
4338
|
const timer = timeout && timeout > 0 ? setTimeout(() => context.abortController.abort(), timeout) : void 0;
|
|
3362
4339
|
let timeoutHandle;
|
|
3363
4340
|
const TIMED_OUT = /* @__PURE__ */ Symbol("timeout");
|
|
3364
4341
|
const deadline = timeout && timeout > 0 ? new Promise((resolve) => {
|
|
3365
4342
|
timeoutHandle = setTimeout(() => resolve(TIMED_OUT), timeout);
|
|
3366
4343
|
}) : void 0;
|
|
4344
|
+
const running = interpreter;
|
|
4345
|
+
const timedOut = () => this.fail(
|
|
4346
|
+
new Error(`Execution timed out after ${timeout}ms`),
|
|
4347
|
+
startTime,
|
|
4348
|
+
stats.toolCallCount,
|
|
4349
|
+
running.stepCount,
|
|
4350
|
+
sanitizeStacks,
|
|
4351
|
+
"TimeoutError",
|
|
4352
|
+
"EXECUTION_TIMEOUT"
|
|
4353
|
+
);
|
|
3367
4354
|
try {
|
|
3368
4355
|
const run = interpreter.run(program);
|
|
3369
4356
|
run.catch(() => void 0);
|
|
3370
4357
|
const outcome = deadline ? await Promise.race([run, deadline]) : await run;
|
|
3371
|
-
if (outcome === TIMED_OUT)
|
|
3372
|
-
return this.fail(
|
|
3373
|
-
new Error(`Execution timed out after ${timeout}ms`),
|
|
3374
|
-
startTime,
|
|
3375
|
-
stats.toolCallCount,
|
|
3376
|
-
interpreter.stepCount,
|
|
3377
|
-
sanitizeStacks,
|
|
3378
|
-
"TimeoutError",
|
|
3379
|
-
"EXECUTION_TIMEOUT"
|
|
3380
|
-
);
|
|
3381
|
-
}
|
|
4358
|
+
if (outcome === TIMED_OUT) return timedOut();
|
|
3382
4359
|
return this.succeed(outcome, context, startTime, stats.toolCallCount, interpreter.stepCount);
|
|
3383
4360
|
} catch (error) {
|
|
4361
|
+
if (error instanceof DeadlineError) return timedOut();
|
|
3384
4362
|
const code2 = error instanceof StepLimitError ? "STEP_LIMIT_EXCEEDED" : void 0;
|
|
3385
4363
|
return this.fail(
|
|
3386
4364
|
error,
|
|
@@ -3394,6 +4372,7 @@ var InterpreterAdapter = class {
|
|
|
3394
4372
|
} finally {
|
|
3395
4373
|
if (timer) clearTimeout(timer);
|
|
3396
4374
|
if (timeoutHandle) clearTimeout(timeoutHandle);
|
|
4375
|
+
callbacks.over = true;
|
|
3397
4376
|
interpreter.stop();
|
|
3398
4377
|
}
|
|
3399
4378
|
}
|
|
@@ -3405,7 +4384,7 @@ var InterpreterAdapter = class {
|
|
|
3405
4384
|
*/
|
|
3406
4385
|
runtimeGlobals(context, charge, callbacks) {
|
|
3407
4386
|
const { config } = context;
|
|
3408
|
-
const callTool = this.createCallTool(context);
|
|
4387
|
+
const callTool = observed(this.createCallTool(context, callbacks));
|
|
3409
4388
|
const resolver = context.sidecar && context.referenceConfig ? new ReferenceResolver(context.sidecar, context.referenceConfig) : void 0;
|
|
3410
4389
|
const joinReferences = (parts) => {
|
|
3411
4390
|
if (!resolver) {
|
|
@@ -3423,6 +4402,8 @@ var InterpreterAdapter = class {
|
|
|
3423
4402
|
const result = left + right;
|
|
3424
4403
|
if (typeof result === "string") {
|
|
3425
4404
|
charge((result.length - (typeof left === "string" ? left.length : 0)) * 2);
|
|
4405
|
+
} else if (typeof result === "bigint") {
|
|
4406
|
+
callbacks.countBigInt?.(result);
|
|
3426
4407
|
}
|
|
3427
4408
|
return result;
|
|
3428
4409
|
};
|
|
@@ -3430,12 +4411,20 @@ var InterpreterAdapter = class {
|
|
|
3430
4411
|
if (!Array.isArray(quasis)) throw sandboxError("Template pieces must be an array", "TypeError");
|
|
3431
4412
|
const parts = [];
|
|
3432
4413
|
let hasReference = false;
|
|
4414
|
+
let length = 0;
|
|
4415
|
+
const add = (part) => {
|
|
4416
|
+
length += part.length;
|
|
4417
|
+
if (length > MAX_JOIN_LENGTH) {
|
|
4418
|
+
throw sandboxError(`A template literal cannot produce more than ${MAX_JOIN_LENGTH} chars`, "RangeError");
|
|
4419
|
+
}
|
|
4420
|
+
parts.push(part);
|
|
4421
|
+
};
|
|
3433
4422
|
for (let i = 0; i < quasis.length; i++) {
|
|
3434
|
-
|
|
4423
|
+
add(String(quasis[i]));
|
|
3435
4424
|
if (i < values.length) {
|
|
3436
4425
|
const value = values[i];
|
|
3437
4426
|
if (typeof value === "string" && isReferenceId(value)) hasReference = true;
|
|
3438
|
-
|
|
4427
|
+
add(String(value));
|
|
3439
4428
|
}
|
|
3440
4429
|
}
|
|
3441
4430
|
if (hasReference) return joinReferences(parts.filter((part) => part !== ""));
|
|
@@ -3457,7 +4446,7 @@ var InterpreterAdapter = class {
|
|
|
3457
4446
|
yield item;
|
|
3458
4447
|
}
|
|
3459
4448
|
}
|
|
3460
|
-
const parallel = async (first, second) => {
|
|
4449
|
+
const parallel = observed(async (first, second) => {
|
|
3461
4450
|
let tasks;
|
|
3462
4451
|
if (typeof second === "function") {
|
|
3463
4452
|
if (!Array.isArray(first)) throw sandboxError("parallel requires an array of items", "TypeError");
|
|
@@ -3482,7 +4471,7 @@ var InterpreterAdapter = class {
|
|
|
3482
4471
|
${messages}`);
|
|
3483
4472
|
}
|
|
3484
4473
|
return settled.map((result) => result.value);
|
|
3485
|
-
};
|
|
4474
|
+
});
|
|
3486
4475
|
const globals = {
|
|
3487
4476
|
__safe_callTool: callTool,
|
|
3488
4477
|
__safe_concat: concat,
|
|
@@ -3500,19 +4489,23 @@ ${messages}`);
|
|
|
3500
4489
|
let consoleCalls = 0;
|
|
3501
4490
|
let consoleLength = 0;
|
|
3502
4491
|
const write = (level) => (...args) => {
|
|
4492
|
+
if (callbacks.over) throw executionOver();
|
|
3503
4493
|
consoleCalls++;
|
|
3504
4494
|
if (consoleCalls > maxConsoleCalls) {
|
|
3505
4495
|
throw sandboxError(
|
|
3506
4496
|
`Console call limit exceeded (max: ${maxConsoleCalls}). This limit prevents I/O flood attacks.`
|
|
3507
4497
|
);
|
|
3508
4498
|
}
|
|
4499
|
+
const outputLimit = () => sandboxError(
|
|
4500
|
+
`Console output size limit exceeded (max: ${maxConsoleOutputBytes} bytes). This limit prevents I/O flood attacks.`
|
|
4501
|
+
);
|
|
4502
|
+
const room = (maxConsoleOutputBytes - consoleLength) * 16 + 64 * 1024;
|
|
4503
|
+
for (const arg of args) {
|
|
4504
|
+
if (arg !== null && typeof arg === "object" && certainlyLargerThan(arg, room)) throw outputLimit();
|
|
4505
|
+
}
|
|
3509
4506
|
const line = args.map(consoleText).join(" ");
|
|
3510
4507
|
consoleLength += line.length;
|
|
3511
|
-
if (consoleLength > maxConsoleOutputBytes)
|
|
3512
|
-
throw sandboxError(
|
|
3513
|
-
`Console output size limit exceeded (max: ${maxConsoleOutputBytes} bytes). This limit prevents I/O flood attacks.`
|
|
3514
|
-
);
|
|
3515
|
-
}
|
|
4508
|
+
if (consoleLength > maxConsoleOutputBytes) throw outputLimit();
|
|
3516
4509
|
sink(level, line);
|
|
3517
4510
|
};
|
|
3518
4511
|
globals["__safe_console"] = frozenRecord2({
|
|
@@ -3525,7 +4518,7 @@ ${messages}`);
|
|
|
3525
4518
|
for (const namespace of context.toolNamespaces ?? []) {
|
|
3526
4519
|
const methods = {};
|
|
3527
4520
|
for (const method of namespace.methods) {
|
|
3528
|
-
if (isBlockedKey(method.name)) continue;
|
|
4521
|
+
if (isBlockedKey(method.name) || isEngineCalledKey(method.name)) continue;
|
|
3529
4522
|
methods[method.name] = (args, options) => callTool(method.toolName, args === void 0 ? {} : args, options);
|
|
3530
4523
|
}
|
|
3531
4524
|
globals[namespace.name] = frozenRecord2(methods);
|
|
@@ -3544,11 +4537,13 @@ ${messages}`);
|
|
|
3544
4537
|
* and the response cross as JSON, so the handler never receives a value of the script and the
|
|
3545
4538
|
* script never receives an object of the handler.
|
|
3546
4539
|
*/
|
|
3547
|
-
createCallTool(context) {
|
|
4540
|
+
createCallTool(context, execution) {
|
|
3548
4541
|
const configured = context.config.toolHandler;
|
|
3549
4542
|
const bridgeContext = context.toolHandler === void 0 && typeof configured === "function" ? Object.create(context, { toolHandler: { value: configured } }) : context;
|
|
3550
4543
|
const bridge = createHostToolBridge(bridgeContext, { updateStats: true });
|
|
4544
|
+
const maxPayloadBytes = context.config.toolBridge?.maxPayloadBytes ?? DEFAULT_MAX_TOOL_PAYLOAD_BYTES;
|
|
3551
4545
|
return async (toolName, args, options) => {
|
|
4546
|
+
if (execution.over) throw executionOver();
|
|
3552
4547
|
let throwOnError = true;
|
|
3553
4548
|
if (options !== void 0 && options !== null) {
|
|
3554
4549
|
if (typeof options !== "object") throw sandboxError("callTool options must be an object", "TypeError");
|
|
@@ -3560,6 +4555,13 @@ ${messages}`);
|
|
|
3560
4555
|
if (typeof args !== "object" || args === null || Array.isArray(args)) {
|
|
3561
4556
|
throw sandboxError("Tool arguments must be an object", "TypeError");
|
|
3562
4557
|
}
|
|
4558
|
+
if (certainlyLargerThan(args, maxPayloadBytes * 2 + 1024)) {
|
|
4559
|
+
throw sandboxError(
|
|
4560
|
+
`Tool request exceeds maximum size (${maxPayloadBytes} bytes)`,
|
|
4561
|
+
"ToolBridgeError",
|
|
4562
|
+
"TOOL_BRIDGE_REQUEST_TOO_LARGE"
|
|
4563
|
+
);
|
|
4564
|
+
}
|
|
3563
4565
|
let requestJson;
|
|
3564
4566
|
try {
|
|
3565
4567
|
requestJson = encodeToolBridgeRequest(toolName, args);
|