@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/esm/worker.mjs
CHANGED
|
@@ -116,11 +116,65 @@ function readProperty(object, key) {
|
|
|
116
116
|
if (key === "__proto__" || BLOCKED_KEYS.has(key)) throw new InterpreterError(`Forbidden property access: ${key}`);
|
|
117
117
|
return object[key];
|
|
118
118
|
}
|
|
119
|
+
var ENGINE_CALLED_KEYS = /* @__PURE__ */ new Set(["then", "toString", "valueOf", "toJSON", "toLocaleString", "toISOString"]);
|
|
120
|
+
function isEngineCalledKey(key) {
|
|
121
|
+
return ENGINE_CALLED_KEYS.has(key);
|
|
122
|
+
}
|
|
123
|
+
function assertStorable(target, key, value) {
|
|
124
|
+
if (typeof value !== "function") return;
|
|
125
|
+
if (ENGINE_CALLED_KEYS.has(key) || key === "join" && Array.isArray(target)) {
|
|
126
|
+
throw new InterpreterError(
|
|
127
|
+
`A function cannot be stored under '${key}': the sandbox runs a function only where the script calls it`
|
|
128
|
+
);
|
|
129
|
+
}
|
|
130
|
+
}
|
|
119
131
|
var MAX_STRING_OP_LENGTH = 1e6;
|
|
120
132
|
var MAX_JOIN_LENGTH = 16e6;
|
|
121
133
|
var MAX_TEXT_NESTING = 64;
|
|
122
134
|
var MAX_TEXT_ITEMS = 8e6;
|
|
123
135
|
var MAX_ARRAY_LENGTH = 1e6;
|
|
136
|
+
var CLOCK_CHECK_STEPS = 256;
|
|
137
|
+
var WORK_PER_STEP = 16384;
|
|
138
|
+
var WRITE_WORK = 8;
|
|
139
|
+
var LOCALE_COMPARE_WORK = 64;
|
|
140
|
+
var SEARCH_PIECE_WORK = 2 ** 20;
|
|
141
|
+
var LONG_SEARCH_TEXT = 64;
|
|
142
|
+
var MAX_CALL_WORK = 2 ** 33;
|
|
143
|
+
var MAX_BIGINT_BITS = 2 ** 20;
|
|
144
|
+
var MAX_BIGINT_DIGITS = Math.ceil(MAX_BIGINT_BITS * Math.log10(2)) + 1;
|
|
145
|
+
var WORD_BITS = 64;
|
|
146
|
+
var BIGINT_WORK = 64;
|
|
147
|
+
var BIGINT_TEXT_WORK = 1024;
|
|
148
|
+
var COMPARISONS = /* @__PURE__ */ new Set(["==", "!=", "<", "<=", ">", ">="]);
|
|
149
|
+
function bitsOf(value) {
|
|
150
|
+
const hex = value.toString(16);
|
|
151
|
+
const start = value < 0n ? 1 : 0;
|
|
152
|
+
return (hex.length - start - 1) * 4 + (32 - Math.clz32(Number.parseInt(hex[start], 16)));
|
|
153
|
+
}
|
|
154
|
+
function bigIntTooLarge() {
|
|
155
|
+
return new InterpreterError(`A BigInt cannot be larger than ${MAX_BIGINT_BITS} bits`);
|
|
156
|
+
}
|
|
157
|
+
var CONSTANT_STRING_METHODS = /* @__PURE__ */ new Set([
|
|
158
|
+
"at",
|
|
159
|
+
"charAt",
|
|
160
|
+
"charCodeAt",
|
|
161
|
+
"codePointAt",
|
|
162
|
+
"valueOf",
|
|
163
|
+
"toString",
|
|
164
|
+
"slice",
|
|
165
|
+
"substring",
|
|
166
|
+
"substr",
|
|
167
|
+
"concat",
|
|
168
|
+
"startsWith",
|
|
169
|
+
"endsWith",
|
|
170
|
+
"padStart",
|
|
171
|
+
"padEnd",
|
|
172
|
+
"repeat"
|
|
173
|
+
]);
|
|
174
|
+
var CONSTANT_ARRAY_METHODS = /* @__PURE__ */ new Set(["at", "push", "pop", "slice", "keys", "values", "entries"]);
|
|
175
|
+
var TEXT_SEARCHES = /* @__PURE__ */ new Set(["indexOf", "lastIndexOf", "includes", "split", "replace", "replaceAll"]);
|
|
176
|
+
var ARRAY_SEARCHES = /* @__PURE__ */ new Set(["indexOf", "lastIndexOf", "includes"]);
|
|
177
|
+
var NOT_SEARCHED = /* @__PURE__ */ Symbol("not searched");
|
|
124
178
|
var HIGHER_ORDER_ARRAY_METHODS = /* @__PURE__ */ new Set([
|
|
125
179
|
"map",
|
|
126
180
|
"flatMap",
|
|
@@ -141,10 +195,12 @@ var FunctionProtoCall = Function.prototype.call;
|
|
|
141
195
|
var FunctionProtoApply = Function.prototype.apply;
|
|
142
196
|
var FunctionProtoBind = Function.prototype.bind;
|
|
143
197
|
var FunctionProtoToString = Function.prototype.toString;
|
|
198
|
+
var ArrayProtoToLocaleString = Array.prototype.toLocaleString;
|
|
199
|
+
var StringProtoIndexOf = String.prototype.indexOf;
|
|
144
200
|
function methodsOf(prototype) {
|
|
145
201
|
const methods = /* @__PURE__ */ new Map();
|
|
146
202
|
for (const name of Object.getOwnPropertyNames(prototype)) {
|
|
147
|
-
if (name
|
|
203
|
+
if (isBlockedKey(name)) continue;
|
|
148
204
|
const descriptor = Object.getOwnPropertyDescriptor(prototype, name);
|
|
149
205
|
if (descriptor && typeof descriptor.value === "function") methods.set(descriptor.value, name);
|
|
150
206
|
}
|
|
@@ -152,6 +208,34 @@ function methodsOf(prototype) {
|
|
|
152
208
|
}
|
|
153
209
|
var ARRAY_METHODS = methodsOf(Array.prototype);
|
|
154
210
|
var STRING_METHODS = methodsOf(String.prototype);
|
|
211
|
+
var OTHER_METHODS = (() => {
|
|
212
|
+
const prototypes = [
|
|
213
|
+
["Number", Number.prototype],
|
|
214
|
+
["Boolean", Boolean.prototype],
|
|
215
|
+
["BigInt", BigInt.prototype],
|
|
216
|
+
["Date", Date.prototype],
|
|
217
|
+
["Object", Object.prototype]
|
|
218
|
+
];
|
|
219
|
+
const methods = /* @__PURE__ */ new Map();
|
|
220
|
+
for (const [kind, prototype] of prototypes) {
|
|
221
|
+
for (const [method, name] of methodsOf(prototype)) {
|
|
222
|
+
if (!methods.has(method)) methods.set(method, { kind, name });
|
|
223
|
+
}
|
|
224
|
+
}
|
|
225
|
+
return methods;
|
|
226
|
+
})();
|
|
227
|
+
var RECEIVERS = {
|
|
228
|
+
Number: { noun: "a number", accepts: (receiver) => typeof receiver === "number" },
|
|
229
|
+
Boolean: { noun: "a boolean", accepts: (receiver) => typeof receiver === "boolean" },
|
|
230
|
+
BigInt: { noun: "a BigInt", accepts: (receiver) => typeof receiver === "bigint" },
|
|
231
|
+
Date: { noun: "a date", accepts: (receiver) => receiver instanceof Date },
|
|
232
|
+
Object: {
|
|
233
|
+
noun: "an object",
|
|
234
|
+
accepts: (receiver, name) => name !== "valueOf" || receiver !== null && (typeof receiver === "object" || typeof receiver === "function")
|
|
235
|
+
}
|
|
236
|
+
};
|
|
237
|
+
var ARRAY_ITERATOR_NEXT = Object.getPrototypeOf([][Symbol.iterator]()).next;
|
|
238
|
+
var LIBRARY_FUNCTIONS = /* @__PURE__ */ new WeakSet();
|
|
155
239
|
var ARRAY_DATA_ARGUMENTS = /* @__PURE__ */ new Map([
|
|
156
240
|
["push", () => true],
|
|
157
241
|
["unshift", () => true],
|
|
@@ -176,13 +260,18 @@ function convertsArguments(fn, count) {
|
|
|
176
260
|
CONVERTED_ARGUMENTS.set(fn, count);
|
|
177
261
|
return fn;
|
|
178
262
|
}
|
|
263
|
+
var ARGUMENT_CONVERSIONS = /* @__PURE__ */ new WeakMap();
|
|
264
|
+
function convertsBeforeCall(fn, convert) {
|
|
265
|
+
ARGUMENT_CONVERSIONS.set(fn, convert);
|
|
266
|
+
return fn;
|
|
267
|
+
}
|
|
179
268
|
var CALL_COSTS = /* @__PURE__ */ new WeakMap();
|
|
180
269
|
function chargedBeforeCall(fn, cost) {
|
|
181
270
|
CALL_COSTS.set(fn, cost);
|
|
182
271
|
return fn;
|
|
183
272
|
}
|
|
184
273
|
function newTextMeasure() {
|
|
185
|
-
return { length: 0, items: 0, active: /* @__PURE__ */ new Set(), functions: /* @__PURE__ */ new Map() };
|
|
274
|
+
return { length: 0, items: 0, active: /* @__PURE__ */ new Set(), functions: /* @__PURE__ */ new Map(), work: 0 };
|
|
186
275
|
}
|
|
187
276
|
function scalarTextLength(item, measure) {
|
|
188
277
|
switch (typeof item) {
|
|
@@ -190,8 +279,11 @@ function scalarTextLength(item, measure) {
|
|
|
190
279
|
case "boolean":
|
|
191
280
|
return 32;
|
|
192
281
|
// also covers a number in the longest locale format
|
|
193
|
-
case "bigint":
|
|
194
|
-
|
|
282
|
+
case "bigint": {
|
|
283
|
+
const bits = bitsOf(item);
|
|
284
|
+
if (bits > WORD_BITS) measure.work += bits * BIGINT_TEXT_WORK;
|
|
285
|
+
return Math.ceil(bits * Math.log10(2)) + 2;
|
|
286
|
+
}
|
|
195
287
|
case "function": {
|
|
196
288
|
let length = measure.functions.get(item);
|
|
197
289
|
if (length === void 0) {
|
|
@@ -255,6 +347,7 @@ function assertArrayTextWithinLimit(...values) {
|
|
|
255
347
|
measureArrayText(value, 1, measure, 0);
|
|
256
348
|
if (measure.length > MAX_JOIN_LENGTH) throw new InterpreterError(TEXT_TOO_LONG);
|
|
257
349
|
}
|
|
350
|
+
return measure?.length ?? 0;
|
|
258
351
|
}
|
|
259
352
|
var StepLimitError = class extends Error {
|
|
260
353
|
constructor(limit) {
|
|
@@ -262,12 +355,24 @@ var StepLimitError = class extends Error {
|
|
|
262
355
|
this.name = "StepLimitError";
|
|
263
356
|
}
|
|
264
357
|
};
|
|
358
|
+
var DeadlineError = class extends Error {
|
|
359
|
+
constructor() {
|
|
360
|
+
super("Execution deadline exceeded");
|
|
361
|
+
this.name = "TimeoutError";
|
|
362
|
+
}
|
|
363
|
+
};
|
|
265
364
|
var InterpreterError = class extends Error {
|
|
266
365
|
constructor(message) {
|
|
267
366
|
super(message);
|
|
268
367
|
this.name = "InterpreterError";
|
|
269
368
|
}
|
|
270
369
|
};
|
|
370
|
+
var AccumulatedText = class {
|
|
371
|
+
constructor(value, owed) {
|
|
372
|
+
this.value = value;
|
|
373
|
+
this.owed = owed;
|
|
374
|
+
}
|
|
375
|
+
};
|
|
271
376
|
var ReturnSignal = class {
|
|
272
377
|
constructor(value) {
|
|
273
378
|
this.value = value;
|
|
@@ -288,12 +393,11 @@ function createScriptError(name, message, code) {
|
|
|
288
393
|
error["name"] = name;
|
|
289
394
|
error["message"] = message;
|
|
290
395
|
if (code !== void 0) error["code"] = code;
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
});
|
|
396
|
+
const toString = function toString2() {
|
|
397
|
+
return message ? `${name}: ${message}` : name;
|
|
398
|
+
};
|
|
399
|
+
LIBRARY_FUNCTIONS.add(toString);
|
|
400
|
+
Object.defineProperty(error, "toString", { value: toString, enumerable: false });
|
|
297
401
|
SCRIPT_ERRORS.add(error);
|
|
298
402
|
return Object.freeze(error);
|
|
299
403
|
}
|
|
@@ -301,9 +405,10 @@ function isScriptError(value) {
|
|
|
301
405
|
return typeof value === "object" && value !== null && SCRIPT_ERRORS.has(value);
|
|
302
406
|
}
|
|
303
407
|
var Scope = class _Scope {
|
|
304
|
-
constructor(parent, depth) {
|
|
408
|
+
constructor(parent, depth, settle) {
|
|
305
409
|
this.parent = parent;
|
|
306
410
|
this.depth = depth ?? parent?.depth ?? 0;
|
|
411
|
+
this.settle = settle ?? parent?.settle ?? (() => void 0);
|
|
307
412
|
}
|
|
308
413
|
vars = /* @__PURE__ */ new Map();
|
|
309
414
|
/**
|
|
@@ -311,39 +416,69 @@ var Scope = class _Scope {
|
|
|
311
416
|
* function one more than where it was called from. A block inside has the depth around it.
|
|
312
417
|
*/
|
|
313
418
|
depth;
|
|
419
|
+
/** Charges what is still owed for the value of a variable that is read */
|
|
420
|
+
settle;
|
|
421
|
+
/**
|
|
422
|
+
* In the body of a callback that `reduce` called with a text: the name of the parameter that
|
|
423
|
+
* holds it. A block inside has the name around it; a function inside does not.
|
|
424
|
+
*/
|
|
425
|
+
accumulator;
|
|
314
426
|
child() {
|
|
315
|
-
|
|
427
|
+
const scope = new _Scope(this);
|
|
428
|
+
scope.accumulator = this.accumulator;
|
|
429
|
+
return scope;
|
|
316
430
|
}
|
|
317
431
|
/** The scope of one call of a function defined in this scope, running `depth` calls deep. */
|
|
318
432
|
activation(depth) {
|
|
319
433
|
return new _Scope(this, depth);
|
|
320
434
|
}
|
|
321
435
|
declare(name, value, mutable) {
|
|
322
|
-
this.vars.set(name, { value, mutable });
|
|
436
|
+
this.vars.set(name, { value, mutable, owed: 0 });
|
|
323
437
|
}
|
|
324
438
|
has(name) {
|
|
325
439
|
return this.vars.has(name) || (this.parent?.has(name) ?? false);
|
|
326
440
|
}
|
|
441
|
+
/**
|
|
442
|
+
* The variable as it is stored, or nothing when there is none. For the few readers that
|
|
443
|
+
* neither keep its value nor look into a text (its length, whether it is empty, appending to
|
|
444
|
+
* it): everything else reads through {@link get}.
|
|
445
|
+
*/
|
|
446
|
+
slot(name) {
|
|
447
|
+
return this.vars.get(name) ?? this.parent?.slot(name);
|
|
448
|
+
}
|
|
449
|
+
/** The value of a variable, for any use: what is still owed for it is charged first. */
|
|
327
450
|
get(name) {
|
|
328
|
-
const slot = this.
|
|
329
|
-
if (slot)
|
|
330
|
-
if (
|
|
331
|
-
|
|
451
|
+
const slot = this.slot(name);
|
|
452
|
+
if (!slot) throw new InterpreterError(`'${name}' is not defined`);
|
|
453
|
+
if (slot.owed > 0) {
|
|
454
|
+
const owed = slot.owed;
|
|
455
|
+
slot.owed = 0;
|
|
456
|
+
this.settle(owed);
|
|
457
|
+
}
|
|
458
|
+
return slot.value;
|
|
332
459
|
}
|
|
333
460
|
set(name, value) {
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
}
|
|
340
|
-
if (
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
}
|
|
344
|
-
throw new InterpreterError(`'${name}' is not defined`);
|
|
461
|
+
this.append(name, value, 0);
|
|
462
|
+
}
|
|
463
|
+
/** Assign a variable a text that was appended to its value, with what a reader still owes for it. */
|
|
464
|
+
append(name, value, owed) {
|
|
465
|
+
const slot = this.slot(name);
|
|
466
|
+
if (!slot) throw new InterpreterError(`'${name}' is not defined`);
|
|
467
|
+
if (!slot.mutable) throw new InterpreterError(`Assignment to constant '${name}'`);
|
|
468
|
+
slot.value = value;
|
|
469
|
+
slot.owed = owed;
|
|
345
470
|
}
|
|
346
471
|
};
|
|
472
|
+
function appendedTo(name, node) {
|
|
473
|
+
const operands = [];
|
|
474
|
+
let first = node;
|
|
475
|
+
while (first.type === "BinaryExpression" && first.operator === "+") {
|
|
476
|
+
operands.push(first.right);
|
|
477
|
+
first = first.left;
|
|
478
|
+
}
|
|
479
|
+
if (operands.length === 0 || first.type !== "Identifier" || first.name !== name) return void 0;
|
|
480
|
+
return operands.reverse();
|
|
481
|
+
}
|
|
347
482
|
var DEFAULT_MAX_PENDING_CALLS = 4096;
|
|
348
483
|
function ignoreRejection2() {
|
|
349
484
|
}
|
|
@@ -352,6 +487,7 @@ var Interpreter = class {
|
|
|
352
487
|
this.options = options;
|
|
353
488
|
this.globals = options.globals;
|
|
354
489
|
this.maxPendingCalls = options.maxPendingCalls ?? DEFAULT_MAX_PENDING_CALLS;
|
|
490
|
+
this.provide(this.globals, 2);
|
|
355
491
|
}
|
|
356
492
|
steps = 0;
|
|
357
493
|
/** Calls that have not returned: the running ones and the ones waiting on an `await` */
|
|
@@ -367,16 +503,46 @@ var Interpreter = class {
|
|
|
367
503
|
callerDepth = 0;
|
|
368
504
|
maxPendingCalls;
|
|
369
505
|
globals;
|
|
370
|
-
/**
|
|
506
|
+
/**
|
|
507
|
+
* What is owed for the text `reduce` is handing to its callback, for that function to read as
|
|
508
|
+
* it starts (in the same synchronous step, like {@link callerDepth}); otherwise nothing.
|
|
509
|
+
*/
|
|
510
|
+
accumulatorOwed;
|
|
511
|
+
/** The step count at which the clock is read next */
|
|
512
|
+
nextClockCheck = CLOCK_CHECK_STEPS;
|
|
513
|
+
/** What built-ins worked through that has not made a full step yet (see {@link work}) */
|
|
514
|
+
workDone = 0;
|
|
515
|
+
/** The error that ended the run (step budget, deadline, abort, allocation budget); set once, never caught */
|
|
371
516
|
fatal;
|
|
372
517
|
interpretedFunctions = /* @__PURE__ */ new WeakSet();
|
|
518
|
+
/** The functions the host provides: the globals, their members, and what `bind` made of them */
|
|
519
|
+
provided = /* @__PURE__ */ new WeakSet();
|
|
373
520
|
errorCopies = /* @__PURE__ */ new WeakMap();
|
|
521
|
+
/** BigInt literals of the program that were found to be within the size a BigInt may have */
|
|
522
|
+
checkedLiterals = /* @__PURE__ */ new WeakSet();
|
|
523
|
+
/**
|
|
524
|
+
* Remember the functions among the properties of `holder`, `depth` levels down: a global
|
|
525
|
+
* (`parseInt`) or a member of one (`Math.max`, a method of a tool namespace). Read from the
|
|
526
|
+
* property itself, so that nothing of the host runs for it. An array holds data.
|
|
527
|
+
*/
|
|
528
|
+
provide(holder, depth) {
|
|
529
|
+
if (holder === null || typeof holder !== "object" && typeof holder !== "function" || Array.isArray(holder))
|
|
530
|
+
return;
|
|
531
|
+
for (const name of Object.getOwnPropertyNames(holder)) {
|
|
532
|
+
const descriptor = Object.getOwnPropertyDescriptor(holder, name);
|
|
533
|
+
if (!descriptor || !("value" in descriptor)) continue;
|
|
534
|
+
const value = descriptor.value;
|
|
535
|
+
if (typeof value === "function") this.provided.add(value);
|
|
536
|
+
if (depth > 1) this.provide(value, depth - 1);
|
|
537
|
+
}
|
|
538
|
+
}
|
|
374
539
|
/**
|
|
375
540
|
* Call a function for a script, with the checks that apply to a call the script writes itself.
|
|
376
541
|
* For a host helper that is handed a callback (`parallel(items, fn)`): `fn` may be a function
|
|
377
542
|
* of the script, or a built-in or host function the script passed along.
|
|
378
543
|
*/
|
|
379
544
|
call(fn, args) {
|
|
545
|
+
if (this.fatal !== void 0) throw this.fatal;
|
|
380
546
|
if (typeof fn !== "function") throw new InterpreterError("Attempted to call a non-function");
|
|
381
547
|
if (this.interpretedFunctions.has(fn)) return fn(...args);
|
|
382
548
|
return this.callFunction(fn, void 0, args, this.callerDepth);
|
|
@@ -386,7 +552,7 @@ var Interpreter = class {
|
|
|
386
552
|
return this.steps;
|
|
387
553
|
}
|
|
388
554
|
async run(program) {
|
|
389
|
-
const root = new Scope();
|
|
555
|
+
const root = new Scope(void 0, 0, (bytes) => this.charge(bytes));
|
|
390
556
|
for (const stmt of program.body) {
|
|
391
557
|
if (stmt.type === "FunctionDeclaration" && stmt.id) {
|
|
392
558
|
root.declare(stmt.id.name, this.makeFunction(stmt, root), false);
|
|
@@ -404,13 +570,23 @@ var Interpreter = class {
|
|
|
404
570
|
return last;
|
|
405
571
|
}
|
|
406
572
|
/**
|
|
407
|
-
* End the run from outside: whatever of the script is still going (a
|
|
408
|
-
*
|
|
409
|
-
* host calls this when the execution has returned, so that no
|
|
573
|
+
* End the run from outside: whatever of the script is still going (a callback waiting for a
|
|
574
|
+
* tool call, a run that timed out while it waited) stops at its next step or its next call,
|
|
575
|
+
* whichever comes first. The host calls this when the execution has returned, so that no
|
|
576
|
+
* script code runs and no host function is called after it.
|
|
410
577
|
*/
|
|
411
578
|
stop() {
|
|
412
579
|
if (this.fatal === void 0) this.fatal = new InterpreterError("Execution ended");
|
|
413
580
|
}
|
|
581
|
+
/**
|
|
582
|
+
* Charge an allocation that a runtime helper of the host made for the script (the helpers a
|
|
583
|
+
* transformed `+` or template literal calls). The budget is one budget wherever it is asked:
|
|
584
|
+
* a refusal ends the run here as it does for what the interpreter charges itself, and no
|
|
585
|
+
* `catch` or `finally` of the script runs after it.
|
|
586
|
+
*/
|
|
587
|
+
chargeAllocation(bytes) {
|
|
588
|
+
this.charge(bytes);
|
|
589
|
+
}
|
|
414
590
|
/** End the run with an error no `catch` of the script can stop. */
|
|
415
591
|
end(error) {
|
|
416
592
|
if (this.fatal === void 0) this.fatal = error;
|
|
@@ -420,6 +596,90 @@ var Interpreter = class {
|
|
|
420
596
|
if (this.fatal !== void 0) throw this.fatal;
|
|
421
597
|
if (this.options.signal?.aborted) this.end(new InterpreterError("Execution aborted"));
|
|
422
598
|
if (++this.steps > this.options.maxSteps) this.end(new StepLimitError(this.options.maxSteps));
|
|
599
|
+
if (this.steps >= this.nextClockCheck) this.checkClock();
|
|
600
|
+
}
|
|
601
|
+
/** End the run when its deadline has passed. */
|
|
602
|
+
checkClock() {
|
|
603
|
+
this.nextClockCheck = this.steps + CLOCK_CHECK_STEPS;
|
|
604
|
+
const deadline = this.options.deadline;
|
|
605
|
+
if (deadline !== void 0 && Date.now() >= deadline) this.end(new DeadlineError());
|
|
606
|
+
}
|
|
607
|
+
/**
|
|
608
|
+
* Count what a built-in works through for the script, in chars or items: the engine does it
|
|
609
|
+
* in one step of its own, however large the operands are. {@link WORK_PER_STEP} units are a
|
|
610
|
+
* step of the budget, and the clock is read whenever that adds a step.
|
|
611
|
+
*/
|
|
612
|
+
work(units) {
|
|
613
|
+
if (!(units > 0)) return;
|
|
614
|
+
this.workDone += units;
|
|
615
|
+
if (this.workDone < WORK_PER_STEP) return;
|
|
616
|
+
const steps = Math.floor(this.workDone / WORK_PER_STEP);
|
|
617
|
+
this.workDone -= steps * WORK_PER_STEP;
|
|
618
|
+
this.steps += steps;
|
|
619
|
+
if (this.steps > this.options.maxSteps) this.end(new StepLimitError(this.options.maxSteps));
|
|
620
|
+
this.checkClock();
|
|
621
|
+
}
|
|
622
|
+
/** {@link assertArrayTextWithinLimit}, and the text the arrays are written as counted as work. */
|
|
623
|
+
arrayOperands(...values) {
|
|
624
|
+
let measure;
|
|
625
|
+
for (const value of values) {
|
|
626
|
+
if (!Array.isArray(value)) continue;
|
|
627
|
+
measure ??= newTextMeasure();
|
|
628
|
+
measureArrayText(value, 1, measure, 0);
|
|
629
|
+
if (measure.length > MAX_JOIN_LENGTH) throw new InterpreterError(TEXT_TOO_LONG);
|
|
630
|
+
}
|
|
631
|
+
if (measure) this.work(measure.length * WRITE_WORK + measure.work);
|
|
632
|
+
}
|
|
633
|
+
/**
|
|
634
|
+
* Count a BigInt an operation made: it is held to the size a BigInt may have, and beyond the
|
|
635
|
+
* size of a number what it holds is charged to the budget and making it counts as work. Also
|
|
636
|
+
* for the runtime helper that adds for a transformed `+`.
|
|
637
|
+
*
|
|
638
|
+
* @throws InterpreterError when the value is larger than {@link MAX_BIGINT_BITS}
|
|
639
|
+
*/
|
|
640
|
+
countBigInt(value) {
|
|
641
|
+
const bits = bitsOf(value);
|
|
642
|
+
if (bits > MAX_BIGINT_BITS) throw bigIntTooLarge();
|
|
643
|
+
if (bits <= WORD_BITS) return;
|
|
644
|
+
this.work(bits * BIGINT_WORK);
|
|
645
|
+
this.charge(Math.ceil(bits / 8));
|
|
646
|
+
}
|
|
647
|
+
/** Count the work of writing a value as text, when it is a BigInt: the engine writes it in decimal. */
|
|
648
|
+
bigIntAsText(value) {
|
|
649
|
+
if (typeof value !== "bigint") return;
|
|
650
|
+
const bits = bitsOf(value);
|
|
651
|
+
if (bits > WORD_BITS) this.work(bits * BIGINT_TEXT_WORK);
|
|
652
|
+
}
|
|
653
|
+
/**
|
|
654
|
+
* What is checked before an operator is applied to a BigInt: the operations whose result can
|
|
655
|
+
* be far larger than their operands are refused from the operands, and what the engine reads
|
|
656
|
+
* to compare a BigInt with a text is bounded and counted.
|
|
657
|
+
*/
|
|
658
|
+
checkBigIntOperands(operator, left, right) {
|
|
659
|
+
if (typeof left === "bigint" && typeof right === "bigint") {
|
|
660
|
+
if (operator === "<<" || operator === ">>") {
|
|
661
|
+
const count = Number(operator === "<<" ? right : -right);
|
|
662
|
+
if (count > 0 && left !== 0n && bitsOf(left) + count > MAX_BIGINT_BITS) throw bigIntTooLarge();
|
|
663
|
+
} else if (operator === "**") {
|
|
664
|
+
const bits = bitsOf(left);
|
|
665
|
+
if (bits > 1 && (bits - 1) * Number(right) + 1 > MAX_BIGINT_BITS) throw bigIntTooLarge();
|
|
666
|
+
} else if (operator === "/" || operator === "%") {
|
|
667
|
+
const bits = bitsOf(left);
|
|
668
|
+
if (bits > WORD_BITS) this.work(bits * BIGINT_WORK);
|
|
669
|
+
}
|
|
670
|
+
return;
|
|
671
|
+
}
|
|
672
|
+
const other = typeof left === "bigint" ? right : left;
|
|
673
|
+
if (COMPARISONS.has(operator)) {
|
|
674
|
+
const chars = typeof other === "string" ? other.length : assertArrayTextWithinLimit(other);
|
|
675
|
+
if (chars > MAX_BIGINT_DIGITS) {
|
|
676
|
+
throw new InterpreterError(`A BigInt cannot be compared with a text of more than ${MAX_BIGINT_DIGITS} chars`);
|
|
677
|
+
}
|
|
678
|
+
this.work(chars * BIGINT_TEXT_WORK);
|
|
679
|
+
} else if (operator === "+") {
|
|
680
|
+
this.bigIntAsText(left);
|
|
681
|
+
this.bigIntAsText(right);
|
|
682
|
+
}
|
|
423
683
|
}
|
|
424
684
|
/** Charge an allocation to the host's budget. */
|
|
425
685
|
charge(bytes) {
|
|
@@ -451,12 +711,19 @@ var Interpreter = class {
|
|
|
451
711
|
case "FunctionDeclaration":
|
|
452
712
|
if (node.id) scope.declare(node.id.name, this.makeFunction(node, scope), false);
|
|
453
713
|
return void 0;
|
|
454
|
-
case "ExpressionStatement":
|
|
455
|
-
|
|
714
|
+
case "ExpressionStatement": {
|
|
715
|
+
const expression = node.expression;
|
|
716
|
+
if (expression.type === "AssignmentExpression" && expression.left.type === "Identifier") {
|
|
717
|
+
const name = expression.left.name;
|
|
718
|
+
const appended = expression.operator === "+=" ? [expression.right] : expression.operator === "=" ? appendedTo(name, expression.right) : void 0;
|
|
719
|
+
if (appended !== void 0 && scope.has(name)) return this.execAppend(name, appended, scope);
|
|
720
|
+
}
|
|
721
|
+
return this.evalExpr(expression, scope);
|
|
722
|
+
}
|
|
456
723
|
case "BlockStatement":
|
|
457
724
|
return this.execBlock(node.body, scope.child());
|
|
458
725
|
case "IfStatement":
|
|
459
|
-
if (
|
|
726
|
+
if (await this.evalTest(node.test, scope)) return this.execStatement(node.consequent, scope);
|
|
460
727
|
if (node.alternate) return this.execStatement(node.alternate, scope);
|
|
461
728
|
return void 0;
|
|
462
729
|
case "ForOfStatement":
|
|
@@ -476,7 +743,7 @@ var Interpreter = class {
|
|
|
476
743
|
case "ThrowStatement":
|
|
477
744
|
throw await this.evalExpr(node.argument, scope);
|
|
478
745
|
case "ReturnStatement":
|
|
479
|
-
throw new ReturnSignal(node.argument ? await this.
|
|
746
|
+
throw new ReturnSignal(node.argument ? await this.evalReturned(node.argument, scope) : void 0);
|
|
480
747
|
case "BreakStatement":
|
|
481
748
|
if (node.label) throw new InterpreterError("Labeled break is not supported");
|
|
482
749
|
throw new BreakSignal();
|
|
@@ -547,14 +814,14 @@ var Interpreter = class {
|
|
|
547
814
|
if (node.init.type === "VariableDeclaration") await this.execStatement(node.init, inner);
|
|
548
815
|
else await this.evalExpr(node.init, inner);
|
|
549
816
|
}
|
|
550
|
-
while (node.test ?
|
|
817
|
+
while (node.test ? await this.evalTest(node.test, inner) : true) {
|
|
551
818
|
this.tick();
|
|
552
819
|
if (!await this.runLoopBody(node.body, inner.child())) break;
|
|
553
820
|
if (node.update) await this.evalExpr(node.update, inner);
|
|
554
821
|
}
|
|
555
822
|
}
|
|
556
823
|
async execWhile(node, scope) {
|
|
557
|
-
while (
|
|
824
|
+
while (await this.evalTest(node.test, scope)) {
|
|
558
825
|
this.tick();
|
|
559
826
|
if (!await this.runLoopBody(node.body, scope.child())) break;
|
|
560
827
|
}
|
|
@@ -563,7 +830,7 @@ var Interpreter = class {
|
|
|
563
830
|
do {
|
|
564
831
|
this.tick();
|
|
565
832
|
if (!await this.runLoopBody(node.body, scope.child())) break;
|
|
566
|
-
} while (
|
|
833
|
+
} while (await this.evalTest(node.test, scope));
|
|
567
834
|
}
|
|
568
835
|
async execSwitch(node, scope) {
|
|
569
836
|
const value = await this.evalExpr(node.discriminant, scope);
|
|
@@ -621,6 +888,10 @@ var Interpreter = class {
|
|
|
621
888
|
if (node.regex) {
|
|
622
889
|
throw new InterpreterError("Regular expressions are not supported");
|
|
623
890
|
}
|
|
891
|
+
if (typeof node.value === "bigint" && !this.checkedLiterals.has(node)) {
|
|
892
|
+
if (bitsOf(node.value) > MAX_BIGINT_BITS) throw bigIntTooLarge();
|
|
893
|
+
this.checkedLiterals.add(node);
|
|
894
|
+
}
|
|
624
895
|
return node.value;
|
|
625
896
|
case "Identifier":
|
|
626
897
|
return scope.has(node.name) ? scope.get(node.name) : this.readGlobal(node.name);
|
|
@@ -650,6 +921,7 @@ var Interpreter = class {
|
|
|
650
921
|
for (const [k, v] of Object.entries(spread)) {
|
|
651
922
|
this.tick();
|
|
652
923
|
if (!BLOCKED_KEYS.has(k)) {
|
|
924
|
+
assertStorable(obj, k, v);
|
|
653
925
|
obj[k] = v;
|
|
654
926
|
count++;
|
|
655
927
|
}
|
|
@@ -660,7 +932,9 @@ var Interpreter = class {
|
|
|
660
932
|
if (prop.kind !== "init") throw new InterpreterError("Getters and setters are not supported");
|
|
661
933
|
const key = await this.propKey(prop, scope);
|
|
662
934
|
if (BLOCKED_KEYS.has(key)) throw new InterpreterError(`Forbidden property key: ${key}`);
|
|
663
|
-
|
|
935
|
+
const member = await this.evalExpr(prop.value, scope);
|
|
936
|
+
assertStorable(obj, key, member);
|
|
937
|
+
obj[key] = member;
|
|
664
938
|
count++;
|
|
665
939
|
}
|
|
666
940
|
this.charge(count * 16);
|
|
@@ -671,7 +945,8 @@ var Interpreter = class {
|
|
|
671
945
|
case "UpdateExpression": {
|
|
672
946
|
const ref = await this.resolveReference(node.argument, scope);
|
|
673
947
|
const current = ref.get();
|
|
674
|
-
|
|
948
|
+
this.arrayOperands(current);
|
|
949
|
+
this.work(operandSize(current));
|
|
675
950
|
const before = Number(current);
|
|
676
951
|
const after = node.operator === "++" ? before + 1 : before - 1;
|
|
677
952
|
ref.set(after);
|
|
@@ -686,7 +961,7 @@ var Interpreter = class {
|
|
|
686
961
|
return left ?? await this.evalExpr(node.right, scope);
|
|
687
962
|
}
|
|
688
963
|
case "ConditionalExpression":
|
|
689
|
-
return
|
|
964
|
+
return await this.evalTest(node.test, scope) ? this.evalExpr(node.consequent, scope) : this.evalExpr(node.alternate, scope);
|
|
690
965
|
case "SequenceExpression": {
|
|
691
966
|
let last;
|
|
692
967
|
for (const expression of node.expressions) last = await this.evalExpr(expression, scope);
|
|
@@ -718,17 +993,107 @@ var Interpreter = class {
|
|
|
718
993
|
throw new InterpreterError(`Unsupported expression: ${node.type}`);
|
|
719
994
|
}
|
|
720
995
|
}
|
|
996
|
+
/**
|
|
997
|
+
* `s += x` or `s = s + x…` as a statement: append to a variable.
|
|
998
|
+
*
|
|
999
|
+
* The engine does not copy a text to append to it: the new text links to the old one, and is
|
|
1000
|
+
* written out as a text of its own when something first looks into it. A loop that appends to
|
|
1001
|
+
* one variable therefore allocates what it appends, and is charged that. What is not charged
|
|
1002
|
+
* yet, the length of the text that was appended to, stays owed on the variable: it is paid by
|
|
1003
|
+
* the first read that could look into the new text or keep it (`Scope.get`), because from then
|
|
1004
|
+
* on it can exist as a full copy next to the texts it was built from. Nothing else can get
|
|
1005
|
+
* hold of the new text: as a statement, the assignment has no value.
|
|
1006
|
+
*/
|
|
1007
|
+
async execAppend(name, operands, scope) {
|
|
1008
|
+
this.tick();
|
|
1009
|
+
const { sum, owed } = await this.appendTo(name, operands, scope);
|
|
1010
|
+
scope.append(name, sum, owed);
|
|
1011
|
+
return sum;
|
|
1012
|
+
}
|
|
1013
|
+
/**
|
|
1014
|
+
* The value of the variable `name` with the operands appended, charged for what is appended.
|
|
1015
|
+
*
|
|
1016
|
+
* @returns The sum, and what is still owed for it when it is a text that was appended to a text
|
|
1017
|
+
*/
|
|
1018
|
+
async appendTo(name, operands, scope) {
|
|
1019
|
+
const variable = scope.slot(name);
|
|
1020
|
+
if (!variable) throw new InterpreterError(`'${name}' is not defined`);
|
|
1021
|
+
const start = variable.value;
|
|
1022
|
+
const owedAtStart = variable.owed;
|
|
1023
|
+
let sum = start;
|
|
1024
|
+
for (const operand of operands) {
|
|
1025
|
+
this.tick();
|
|
1026
|
+
const right = await this.evalExpr(operand, scope);
|
|
1027
|
+
const left = sum;
|
|
1028
|
+
sum = this.binary("+", left, right, true);
|
|
1029
|
+
if (typeof sum === "string") this.charge((sum.length - (typeof left === "string" ? left.length : 0)) * 2);
|
|
1030
|
+
}
|
|
1031
|
+
let owed = 0;
|
|
1032
|
+
if (typeof sum === "string" && typeof start === "string") {
|
|
1033
|
+
owed = owedAtStart > 0 && variable.owed === owedAtStart ? owedAtStart : start.length * 2;
|
|
1034
|
+
}
|
|
1035
|
+
return { sum, owed };
|
|
1036
|
+
}
|
|
1037
|
+
/**
|
|
1038
|
+
* The value a function returns. In a callback that `reduce` called with a text, the
|
|
1039
|
+
* accumulator itself and what is appended to it (`return text + item`) are returned as an
|
|
1040
|
+
* {@link AccumulatedText}, without paying what is owed for them: `reduce` carries it on.
|
|
1041
|
+
*/
|
|
1042
|
+
async evalReturned(node, scope) {
|
|
1043
|
+
const name = scope.accumulator;
|
|
1044
|
+
if (name === void 0) return this.evalExpr(node, scope);
|
|
1045
|
+
if (node.type === "ConditionalExpression") {
|
|
1046
|
+
this.tick();
|
|
1047
|
+
const branch = await this.evalTest(node.test, scope) ? node.consequent : node.alternate;
|
|
1048
|
+
return this.evalReturned(branch, scope);
|
|
1049
|
+
}
|
|
1050
|
+
if (node.type === "Identifier" && node.name === name) {
|
|
1051
|
+
const variable = scope.slot(name);
|
|
1052
|
+
if (variable !== void 0 && typeof variable.value === "string") {
|
|
1053
|
+
this.tick();
|
|
1054
|
+
return new AccumulatedText(variable.value, variable.owed);
|
|
1055
|
+
}
|
|
1056
|
+
} else {
|
|
1057
|
+
const appended = appendedTo(name, node);
|
|
1058
|
+
if (appended !== void 0 && scope.has(name)) {
|
|
1059
|
+
this.tick();
|
|
1060
|
+
const { sum, owed } = await this.appendTo(name, appended, scope);
|
|
1061
|
+
return typeof sum === "string" ? new AccumulatedText(sum, owed) : sum;
|
|
1062
|
+
}
|
|
1063
|
+
}
|
|
1064
|
+
return this.evalExpr(node, scope);
|
|
1065
|
+
}
|
|
1066
|
+
/**
|
|
1067
|
+
* The variable an identifier names when it holds an appended text that is still owed for.
|
|
1068
|
+
* For the readers that learn nothing but its length or that it is a text.
|
|
1069
|
+
*/
|
|
1070
|
+
appendedText(node, scope) {
|
|
1071
|
+
if (node.type !== "Identifier") return void 0;
|
|
1072
|
+
const variable = scope.slot(node.name);
|
|
1073
|
+
return variable !== void 0 && variable.owed > 0 && typeof variable.value === "string" ? variable.value : void 0;
|
|
1074
|
+
}
|
|
1075
|
+
/** Evaluate a condition. Whether a text is empty is known from its length. */
|
|
1076
|
+
async evalTest(node, scope) {
|
|
1077
|
+
const text = this.appendedText(node, scope);
|
|
1078
|
+
if (text !== void 0) {
|
|
1079
|
+
this.tick();
|
|
1080
|
+
return text.length > 0;
|
|
1081
|
+
}
|
|
1082
|
+
return truthy(await this.evalExpr(node, scope));
|
|
1083
|
+
}
|
|
721
1084
|
async evalTemplate(node, scope) {
|
|
722
1085
|
let out = "";
|
|
723
1086
|
for (let i = 0; i < node.quasis.length; i++) {
|
|
724
1087
|
out += node.quasis[i].value.cooked ?? "";
|
|
725
1088
|
if (i < node.expressions.length) {
|
|
726
1089
|
const value = await this.evalExpr(node.expressions[i], scope);
|
|
727
|
-
|
|
1090
|
+
this.arrayOperands(value);
|
|
1091
|
+
this.bigIntAsText(value);
|
|
728
1092
|
out += String(value);
|
|
729
1093
|
if (out.length > MAX_JOIN_LENGTH) throw new InterpreterError(TEXT_TOO_LONG);
|
|
730
1094
|
}
|
|
731
1095
|
}
|
|
1096
|
+
this.work(out.length * WRITE_WORK);
|
|
732
1097
|
this.charge(out.length * 2);
|
|
733
1098
|
return out;
|
|
734
1099
|
}
|
|
@@ -743,37 +1108,67 @@ var Interpreter = class {
|
|
|
743
1108
|
assertKeyAllowed(key);
|
|
744
1109
|
return delete object[key];
|
|
745
1110
|
}
|
|
1111
|
+
if (node.operator === "!" || node.operator === "typeof") {
|
|
1112
|
+
const text = this.appendedText(node.argument, scope);
|
|
1113
|
+
if (text !== void 0) {
|
|
1114
|
+
this.tick();
|
|
1115
|
+
return node.operator === "!" ? text.length === 0 : "string";
|
|
1116
|
+
}
|
|
1117
|
+
}
|
|
746
1118
|
const v = await this.evalExpr(node.argument, scope);
|
|
747
1119
|
switch (node.operator) {
|
|
748
1120
|
case "!":
|
|
749
1121
|
return !truthy(v);
|
|
750
|
-
case "-":
|
|
751
|
-
|
|
752
|
-
|
|
1122
|
+
case "-": {
|
|
1123
|
+
this.numericOperand(v);
|
|
1124
|
+
const negated = -v;
|
|
1125
|
+
if (typeof negated === "bigint") this.countBigInt(negated);
|
|
1126
|
+
return negated;
|
|
1127
|
+
}
|
|
753
1128
|
case "+":
|
|
754
|
-
|
|
1129
|
+
this.numericOperand(v);
|
|
755
1130
|
return +v;
|
|
756
1131
|
case "typeof":
|
|
757
1132
|
return typeof v;
|
|
758
|
-
case "~":
|
|
759
|
-
|
|
760
|
-
|
|
1133
|
+
case "~": {
|
|
1134
|
+
this.numericOperand(v);
|
|
1135
|
+
const inverted = ~v;
|
|
1136
|
+
if (typeof inverted === "bigint") this.countBigInt(inverted);
|
|
1137
|
+
return inverted;
|
|
1138
|
+
}
|
|
761
1139
|
case "void":
|
|
762
1140
|
return void 0;
|
|
763
1141
|
default:
|
|
764
1142
|
throw new InterpreterError(`Unsupported unary operator: ${node.operator}`);
|
|
765
1143
|
}
|
|
766
1144
|
}
|
|
1145
|
+
/** An operand the engine reads a number from: an array is joined first, a text is read through. */
|
|
1146
|
+
numericOperand(value) {
|
|
1147
|
+
this.arrayOperands(value);
|
|
1148
|
+
this.work(operandSize(value));
|
|
1149
|
+
}
|
|
767
1150
|
async evalBinary(node, scope) {
|
|
768
1151
|
if (node.left.type === "PrivateIdentifier") throw new InterpreterError("Private names are not supported");
|
|
1152
|
+
if (node.operator === "+") return this.evalSum(node, scope);
|
|
1153
|
+
if (node.operator === "===" || node.operator === "!==") {
|
|
1154
|
+
const literal = node.left.type === "Literal" ? node.left : node.right.type === "Literal" ? node.right : void 0;
|
|
1155
|
+
const text = this.appendedText(literal === node.left ? node.right : node.left, scope);
|
|
1156
|
+
if (literal !== void 0 && text !== void 0 && !literal.regex) {
|
|
1157
|
+
const value = literal.value;
|
|
1158
|
+
if (typeof value !== "string" || value.length !== text.length) {
|
|
1159
|
+
this.tick();
|
|
1160
|
+
this.tick();
|
|
1161
|
+
return node.operator === "!==";
|
|
1162
|
+
}
|
|
1163
|
+
}
|
|
1164
|
+
}
|
|
769
1165
|
const l = await this.evalExpr(node.left, scope);
|
|
770
1166
|
const r = await this.evalExpr(node.right, scope);
|
|
771
1167
|
if (node.operator === "in") {
|
|
772
1168
|
if (r === null || typeof r !== "object" && typeof r !== "function") {
|
|
773
1169
|
throw new InterpreterError("Cannot use 'in' on a value that is not an object");
|
|
774
1170
|
}
|
|
775
|
-
|
|
776
|
-
const key = String(l);
|
|
1171
|
+
const key = this.keyText(l);
|
|
777
1172
|
if (BLOCKED_KEYS.has(key)) throw new InterpreterError(`Forbidden property access: ${key}`);
|
|
778
1173
|
return key in r;
|
|
779
1174
|
}
|
|
@@ -784,15 +1179,56 @@ var Interpreter = class {
|
|
|
784
1179
|
}
|
|
785
1180
|
return this.binary(node.operator, l, r);
|
|
786
1181
|
}
|
|
787
|
-
/**
|
|
788
|
-
|
|
789
|
-
|
|
1182
|
+
/**
|
|
1183
|
+
* `a + b + c`: the operands from left to right, and one sum after the other. Only the last
|
|
1184
|
+
* sum is a value the script gets hold of, and it is charged in full; the ones before it are
|
|
1185
|
+
* part of it.
|
|
1186
|
+
*/
|
|
1187
|
+
async evalSum(node, scope) {
|
|
1188
|
+
const operands = [];
|
|
1189
|
+
let first = node;
|
|
1190
|
+
while (first.type === "BinaryExpression" && first.operator === "+") {
|
|
1191
|
+
operands.push(first.right);
|
|
1192
|
+
first = first.left;
|
|
1193
|
+
}
|
|
1194
|
+
if (first.type === "PrivateIdentifier") throw new InterpreterError("Private names are not supported");
|
|
1195
|
+
let sum = await this.evalExpr(first, scope);
|
|
1196
|
+
for (let i = operands.length - 1; i >= 0; i--) {
|
|
1197
|
+
if (i < operands.length - 1) this.tick();
|
|
1198
|
+
const right = await this.evalExpr(operands[i], scope);
|
|
1199
|
+
sum = this.binary("+", sum, right, i > 0);
|
|
1200
|
+
}
|
|
1201
|
+
return sum;
|
|
1202
|
+
}
|
|
1203
|
+
/**
|
|
1204
|
+
* Apply a binary operator to two values.
|
|
1205
|
+
*
|
|
1206
|
+
* @param partOfSum - The result of `+` is an operand of the next `+` and nothing else: the
|
|
1207
|
+
* caller charges for the text that comes of it
|
|
1208
|
+
*/
|
|
1209
|
+
binary(operator, left, right, partOfSum = false) {
|
|
1210
|
+
if (typeof left !== "bigint" && typeof right !== "bigint") return this.operate(operator, left, right, partOfSum);
|
|
1211
|
+
this.checkBigIntOperands(operator, left, right);
|
|
1212
|
+
const result = this.operate(operator, left, right, partOfSum);
|
|
1213
|
+
if (typeof result === "bigint") this.countBigInt(result);
|
|
1214
|
+
return result;
|
|
1215
|
+
}
|
|
1216
|
+
operate(operator, left, right, partOfSum) {
|
|
1217
|
+
const strict = operator === "===" || operator === "!==";
|
|
1218
|
+
const loose = operator === "==" || operator === "!=";
|
|
1219
|
+
const convertsNextTo = (other) => !strict && (!loose || other !== null && other !== void 0 && typeof other !== "object" && typeof other !== "function");
|
|
1220
|
+
this.arrayOperands(convertsNextTo(right) ? left : void 0, convertsNextTo(left) ? right : void 0);
|
|
1221
|
+
if (operator !== "+") {
|
|
1222
|
+
if (typeof left === "string" && typeof right === "string") this.work(Math.min(left.length, right.length));
|
|
1223
|
+
else if (typeof left === "string" && convertsNextTo(right)) this.work(left.length);
|
|
1224
|
+
else if (typeof right === "string" && convertsNextTo(left)) this.work(right.length);
|
|
1225
|
+
}
|
|
790
1226
|
const l = left;
|
|
791
1227
|
const r = right;
|
|
792
1228
|
switch (operator) {
|
|
793
1229
|
case "+": {
|
|
794
1230
|
const sum = l + r;
|
|
795
|
-
if (typeof sum === "string") this.charge(
|
|
1231
|
+
if (typeof sum === "string" && !partOfSum) this.charge(sum.length * 2);
|
|
796
1232
|
return sum;
|
|
797
1233
|
}
|
|
798
1234
|
case "-":
|
|
@@ -843,6 +1279,11 @@ var Interpreter = class {
|
|
|
843
1279
|
*/
|
|
844
1280
|
async evalMemberTarget(node, scope) {
|
|
845
1281
|
if (node.object.type === "Super") throw new InterpreterError("super is not supported");
|
|
1282
|
+
const text = !node.computed && node.property.type === "Identifier" && node.property.name === "length" ? this.appendedText(node.object, scope) : void 0;
|
|
1283
|
+
if (text !== void 0) {
|
|
1284
|
+
this.tick();
|
|
1285
|
+
return { object: text, key: "length" };
|
|
1286
|
+
}
|
|
846
1287
|
const object = await this.evalExpr(node.object, scope);
|
|
847
1288
|
if (node.optional && (object === null || object === void 0)) throw new ChainShortCircuit();
|
|
848
1289
|
if (node.property.type === "PrivateIdentifier") throw new InterpreterError("Private names are not supported");
|
|
@@ -883,12 +1324,11 @@ var Interpreter = class {
|
|
|
883
1324
|
writeMember(object, key, value) {
|
|
884
1325
|
this.assertChangeable(object);
|
|
885
1326
|
assertKeyAllowed(key);
|
|
1327
|
+
assertStorable(object, key, value);
|
|
886
1328
|
if (Array.isArray(object)) {
|
|
887
|
-
const
|
|
888
|
-
if (
|
|
889
|
-
|
|
890
|
-
}
|
|
891
|
-
if (grownTo > object.length) this.charge((grownTo - object.length) * 8);
|
|
1329
|
+
const checked = checkArrayWrite(object, key, value);
|
|
1330
|
+
if (checked.length > object.length) this.charge((checked.length - object.length) * 8);
|
|
1331
|
+
value = checked.value;
|
|
892
1332
|
}
|
|
893
1333
|
object[key] = value;
|
|
894
1334
|
}
|
|
@@ -917,7 +1357,10 @@ var Interpreter = class {
|
|
|
917
1357
|
const construct = this.options.constructors?.get(callee);
|
|
918
1358
|
if (!construct) throw new InterpreterError("new works with the built-in types the sandbox provides only");
|
|
919
1359
|
const args = await this.evalArguments(node.arguments, scope);
|
|
920
|
-
if (!ARRAY_DATA_FUNCTIONS.has(callee))
|
|
1360
|
+
if (!ARRAY_DATA_FUNCTIONS.has(callee)) {
|
|
1361
|
+
this.arrayOperands(...args);
|
|
1362
|
+
for (const arg of args) this.work(typeof arg === "string" ? arg.length : 0);
|
|
1363
|
+
}
|
|
921
1364
|
const value = construct(args);
|
|
922
1365
|
this.chargeValue(value);
|
|
923
1366
|
return value;
|
|
@@ -952,6 +1395,7 @@ var Interpreter = class {
|
|
|
952
1395
|
* @param depth - How many calls deep the code that makes this call runs
|
|
953
1396
|
*/
|
|
954
1397
|
async callFunction(fn, thisArg, args, depth) {
|
|
1398
|
+
if (this.fatal !== void 0) throw this.fatal;
|
|
955
1399
|
for (let hops = 0; fn === FunctionProtoCall || fn === FunctionProtoApply || fn === FunctionProtoBind; hops++) {
|
|
956
1400
|
const name = fn === FunctionProtoCall ? "call" : fn === FunctionProtoApply ? "apply" : "bind";
|
|
957
1401
|
if (typeof thisArg !== "function" || hops >= 8) {
|
|
@@ -971,6 +1415,7 @@ var Interpreter = class {
|
|
|
971
1415
|
const interpreted = fn;
|
|
972
1416
|
return await this.withCallerDepth(depth, () => interpreted.apply(thisArg, args));
|
|
973
1417
|
}
|
|
1418
|
+
this.checkClock();
|
|
974
1419
|
const own = this.enterCall(depth);
|
|
975
1420
|
try {
|
|
976
1421
|
args = this.checkBuiltinCall(fn, thisArg, args);
|
|
@@ -978,20 +1423,228 @@ var Interpreter = class {
|
|
|
978
1423
|
if (arrayMethod !== void 0 && HIGHER_ORDER_ARRAY_METHODS.has(arrayMethod) && typeof args[0] === "function") {
|
|
979
1424
|
return await this.callArrayMethod(thisArg, arrayMethod, args, own);
|
|
980
1425
|
}
|
|
981
|
-
|
|
982
|
-
|
|
983
|
-
|
|
984
|
-
|
|
1426
|
+
if (arrayMethod === "toLocaleString") {
|
|
1427
|
+
const text = this.arrayLocaleText(thisArg, args, /* @__PURE__ */ new Set(), { length: 0 }, 0);
|
|
1428
|
+
this.chargeValue(text);
|
|
1429
|
+
return text;
|
|
1430
|
+
}
|
|
1431
|
+
const stringMethod = arrayMethod === void 0 ? STRING_METHODS.get(fn) : void 0;
|
|
1432
|
+
this.countRead(fn, arrayMethod, stringMethod, thisArg, args);
|
|
1433
|
+
let result = this.searchInPieces(arrayMethod, stringMethod, thisArg, args);
|
|
1434
|
+
if (result === NOT_SEARCHED) {
|
|
1435
|
+
const asIndex = stringMethod === "includes" && typeof thisArg === "string";
|
|
1436
|
+
const builtin = asIndex ? StringProtoIndexOf : fn;
|
|
1437
|
+
const builtinArgs = args;
|
|
1438
|
+
result = await this.withCallerDepth(own, () => builtin.apply(thisArg, builtinArgs));
|
|
1439
|
+
this.countSearched(arrayMethod, stringMethod, thisArg, args, result);
|
|
1440
|
+
if (asIndex) result = result !== -1;
|
|
1441
|
+
}
|
|
1442
|
+
if (stringMethod === "split" && Array.isArray(result)) {
|
|
985
1443
|
if (result.length > MAX_ARRAY_LENGTH) {
|
|
986
1444
|
throw new InterpreterError(`An array cannot be longer than ${MAX_ARRAY_LENGTH} items`);
|
|
987
1445
|
}
|
|
988
1446
|
}
|
|
1447
|
+
this.work(typeof result === "string" ? result.length * WRITE_WORK : operandSize(result));
|
|
989
1448
|
this.chargeValue(result);
|
|
990
1449
|
return result;
|
|
991
1450
|
} finally {
|
|
992
1451
|
this.pendingCalls--;
|
|
993
1452
|
}
|
|
994
1453
|
}
|
|
1454
|
+
/**
|
|
1455
|
+
* Count what a built-in or host function reads before it is called: its receiver, where the
|
|
1456
|
+
* method goes through it (a search, a conversion, a copy; not a method that reads one char or
|
|
1457
|
+
* works at the end of an array), and the texts among the arguments it converts or searches
|
|
1458
|
+
* for. A value a function only keeps is not read: an item to push, the array a callback is
|
|
1459
|
+
* handed with every item. An array that is read as text was counted where it was measured,
|
|
1460
|
+
* and what the call makes is counted when it returns.
|
|
1461
|
+
*/
|
|
1462
|
+
countRead(fn, arrayMethod, stringMethod, receiver, args) {
|
|
1463
|
+
let read = 0;
|
|
1464
|
+
if (typeof receiver === "string") {
|
|
1465
|
+
const counted = stringMethod === void 0 || !ARRAY_SEARCHES.has(stringMethod);
|
|
1466
|
+
if (counted && (stringMethod === void 0 || !CONSTANT_STRING_METHODS.has(stringMethod))) {
|
|
1467
|
+
read += receiver.length;
|
|
1468
|
+
}
|
|
1469
|
+
} else if (Array.isArray(receiver)) {
|
|
1470
|
+
const counted = arrayMethod !== "indexOf" && arrayMethod !== "lastIndexOf";
|
|
1471
|
+
if (counted && (arrayMethod === void 0 || !CONSTANT_ARRAY_METHODS.has(arrayMethod))) read += receiver.length;
|
|
1472
|
+
} else if (typeof receiver === "bigint") {
|
|
1473
|
+
this.bigIntAsText(receiver);
|
|
1474
|
+
}
|
|
1475
|
+
if (!ARRAY_DATA_FUNCTIONS.has(fn)) {
|
|
1476
|
+
const isData = arrayMethod === void 0 ? void 0 : ARRAY_DATA_ARGUMENTS.get(arrayMethod);
|
|
1477
|
+
const converted = CONVERTED_ARGUMENTS.get(fn) ?? args.length;
|
|
1478
|
+
for (let i = 0; i < args.length && i < converted; i++) {
|
|
1479
|
+
if (isData?.(i)) continue;
|
|
1480
|
+
const arg = args[i];
|
|
1481
|
+
if (typeof arg === "string") read += arg.length;
|
|
1482
|
+
else this.bigIntAsText(arg);
|
|
1483
|
+
}
|
|
1484
|
+
}
|
|
1485
|
+
if (stringMethod === "localeCompare" && typeof receiver === "string") {
|
|
1486
|
+
const other = args[0];
|
|
1487
|
+
read = Math.min(receiver.length, typeof other === "string" ? other.length : receiver.length) * LOCALE_COMPARE_WORK;
|
|
1488
|
+
}
|
|
1489
|
+
this.work(read);
|
|
1490
|
+
}
|
|
1491
|
+
/**
|
|
1492
|
+
* Count a search for a place by how far the engine went: from where it started to where it
|
|
1493
|
+
* found what it looked for, or to the end. A script that goes through a long text with
|
|
1494
|
+
* `indexOf(text, position)` pays for the text once, not once per call.
|
|
1495
|
+
*
|
|
1496
|
+
* @param index - What the engine answered: the place, or -1
|
|
1497
|
+
*/
|
|
1498
|
+
countSearched(arrayMethod, stringMethod, receiver, args, index) {
|
|
1499
|
+
if (typeof index !== "number") return;
|
|
1500
|
+
const position = args[1];
|
|
1501
|
+
if (typeof receiver === "string" && stringMethod !== void 0 && ARRAY_SEARCHES.has(stringMethod)) {
|
|
1502
|
+
const length = receiver.length;
|
|
1503
|
+
if (stringMethod === "lastIndexOf") {
|
|
1504
|
+
const given = Number(position);
|
|
1505
|
+
const from = Number.isNaN(given) ? length : Math.min(Math.max(Math.trunc(given), 0), length);
|
|
1506
|
+
this.work(index === -1 ? from : from - index);
|
|
1507
|
+
} else {
|
|
1508
|
+
const from = Math.min(Math.max(integerOf(position), 0), length);
|
|
1509
|
+
this.work(index === -1 ? length - from : index - from);
|
|
1510
|
+
}
|
|
1511
|
+
} else if (Array.isArray(receiver) && (arrayMethod === "indexOf" || arrayMethod === "lastIndexOf")) {
|
|
1512
|
+
const length = receiver.length;
|
|
1513
|
+
if (arrayMethod === "lastIndexOf") {
|
|
1514
|
+
const given = args.length > 1 ? integerOf(position) : length - 1;
|
|
1515
|
+
const from = given >= 0 ? Math.min(given, length - 1) : length + given;
|
|
1516
|
+
this.work(index === -1 ? from + 1 : from - index);
|
|
1517
|
+
} else {
|
|
1518
|
+
const given = integerOf(position);
|
|
1519
|
+
const from = Math.min(given >= 0 ? given : Math.max(length + given, 0), length);
|
|
1520
|
+
this.work(index === -1 ? length - from : index - from);
|
|
1521
|
+
}
|
|
1522
|
+
}
|
|
1523
|
+
}
|
|
1524
|
+
/**
|
|
1525
|
+
* Make a search whose cost in the engine is the product of two lengths, piece by piece: a text
|
|
1526
|
+
* in a text (the engine can need a comparison of the whole pattern at every position of a
|
|
1527
|
+
* text that nearly matches everywhere), or a long text among the items of an array (every
|
|
1528
|
+
* item of the same length can be compared to its end). Between the pieces a step is counted
|
|
1529
|
+
* and the clock is read, so that one such call ends with the budget or the deadline like any
|
|
1530
|
+
* other code. The answer is the engine's.
|
|
1531
|
+
*
|
|
1532
|
+
* @returns The result, or {@link NOT_SEARCHED} for a call that is not such a search or small
|
|
1533
|
+
* enough to be one piece: the engine makes it
|
|
1534
|
+
*/
|
|
1535
|
+
searchInPieces(arrayMethod, stringMethod, receiver, args) {
|
|
1536
|
+
const wanted = args[0];
|
|
1537
|
+
if (typeof wanted !== "string") return NOT_SEARCHED;
|
|
1538
|
+
const method = arrayMethod ?? stringMethod;
|
|
1539
|
+
if (typeof args[1] === "bigint" && method !== void 0 && ARRAY_SEARCHES.has(method)) return NOT_SEARCHED;
|
|
1540
|
+
if (stringMethod !== void 0 && typeof receiver === "string" && TEXT_SEARCHES.has(stringMethod)) {
|
|
1541
|
+
const small = receiver.length * wanted.length <= SEARCH_PIECE_WORK;
|
|
1542
|
+
if (small || wanted.length === 0 || wanted.length > receiver.length) return NOT_SEARCHED;
|
|
1543
|
+
return this.searchText(stringMethod, receiver, wanted, args);
|
|
1544
|
+
}
|
|
1545
|
+
if (arrayMethod !== void 0 && Array.isArray(receiver) && ARRAY_SEARCHES.has(arrayMethod)) {
|
|
1546
|
+
const small = receiver.length * wanted.length <= SEARCH_PIECE_WORK;
|
|
1547
|
+
if (small || wanted.length <= LONG_SEARCH_TEXT) return NOT_SEARCHED;
|
|
1548
|
+
return this.searchArray(arrayMethod, receiver, wanted, args);
|
|
1549
|
+
}
|
|
1550
|
+
return NOT_SEARCHED;
|
|
1551
|
+
}
|
|
1552
|
+
/** The first place at or after `from` where `pattern` starts in `text`, or -1. */
|
|
1553
|
+
findForward(text, pattern, from) {
|
|
1554
|
+
const last = text.length - pattern.length;
|
|
1555
|
+
const starts = Math.max(1, Math.floor(SEARCH_PIECE_WORK / pattern.length));
|
|
1556
|
+
for (let at = from; at <= last; at += starts) {
|
|
1557
|
+
if (at !== from) {
|
|
1558
|
+
this.tick();
|
|
1559
|
+
this.checkClock();
|
|
1560
|
+
}
|
|
1561
|
+
const end = Math.min(at + starts - 1, last) + pattern.length;
|
|
1562
|
+
const found = text.substring(at, end).indexOf(pattern);
|
|
1563
|
+
this.work(found === -1 ? end - at : found + pattern.length);
|
|
1564
|
+
if (found !== -1) return at + found;
|
|
1565
|
+
}
|
|
1566
|
+
return -1;
|
|
1567
|
+
}
|
|
1568
|
+
/** The last place at or before `from` where `pattern` starts in `text`, or -1. */
|
|
1569
|
+
findBackward(text, pattern, from) {
|
|
1570
|
+
const starts = Math.max(1, Math.floor(SEARCH_PIECE_WORK / pattern.length));
|
|
1571
|
+
for (let high = from; high >= 0; high -= starts) {
|
|
1572
|
+
if (high !== from) {
|
|
1573
|
+
this.tick();
|
|
1574
|
+
this.checkClock();
|
|
1575
|
+
}
|
|
1576
|
+
const low = Math.max(0, high - starts + 1);
|
|
1577
|
+
const end = high + pattern.length;
|
|
1578
|
+
const found = text.substring(low, end).lastIndexOf(pattern);
|
|
1579
|
+
this.work(found === -1 ? end - low : end - low - found);
|
|
1580
|
+
if (found !== -1) return low + found;
|
|
1581
|
+
}
|
|
1582
|
+
return -1;
|
|
1583
|
+
}
|
|
1584
|
+
/** `text.indexOf(pattern)` and the other searches for a text in a text, as the engine answers them. */
|
|
1585
|
+
searchText(name, text, pattern, args) {
|
|
1586
|
+
const length = text.length;
|
|
1587
|
+
const patternLength = pattern.length;
|
|
1588
|
+
switch (name) {
|
|
1589
|
+
case "indexOf":
|
|
1590
|
+
return this.findForward(text, pattern, Math.min(Math.max(integerOf(args[1]), 0), length));
|
|
1591
|
+
case "includes":
|
|
1592
|
+
return this.findForward(text, pattern, Math.min(Math.max(integerOf(args[1]), 0), length)) !== -1;
|
|
1593
|
+
case "lastIndexOf": {
|
|
1594
|
+
const position = Number(args[1]);
|
|
1595
|
+
const from = Number.isNaN(position) ? Number.POSITIVE_INFINITY : Math.trunc(position);
|
|
1596
|
+
return this.findBackward(text, pattern, Math.min(Math.max(from, 0), length - patternLength));
|
|
1597
|
+
}
|
|
1598
|
+
case "split": {
|
|
1599
|
+
const limit = args[1];
|
|
1600
|
+
const pieces = [];
|
|
1601
|
+
if (limit === 0) return pieces;
|
|
1602
|
+
let at = 0;
|
|
1603
|
+
for (let hit = this.findForward(text, pattern, 0); hit !== -1; hit = this.findForward(text, pattern, at)) {
|
|
1604
|
+
pieces.push(text.substring(at, hit));
|
|
1605
|
+
if (pieces.length >= limit) return pieces;
|
|
1606
|
+
at = hit + patternLength;
|
|
1607
|
+
}
|
|
1608
|
+
pieces.push(text.substring(at));
|
|
1609
|
+
return pieces;
|
|
1610
|
+
}
|
|
1611
|
+
default: {
|
|
1612
|
+
const replacement = String(args[1]);
|
|
1613
|
+
const parts = [];
|
|
1614
|
+
let at = 0;
|
|
1615
|
+
let hit = this.findForward(text, pattern, 0);
|
|
1616
|
+
while (hit !== -1) {
|
|
1617
|
+
parts.push(text.substring(at, hit), expandReplacement(replacement, text, hit, pattern));
|
|
1618
|
+
at = hit + patternLength;
|
|
1619
|
+
hit = name === "replace" ? -1 : this.findForward(text, pattern, at);
|
|
1620
|
+
}
|
|
1621
|
+
parts.push(text.substring(at));
|
|
1622
|
+
return parts.join("");
|
|
1623
|
+
}
|
|
1624
|
+
}
|
|
1625
|
+
}
|
|
1626
|
+
/** `array.indexOf(text)`, `lastIndexOf` and `includes` for a long text, as the engine answers them. */
|
|
1627
|
+
searchArray(name, array, wanted, args) {
|
|
1628
|
+
const length = array.length;
|
|
1629
|
+
const same = (item) => {
|
|
1630
|
+
if (typeof item !== "string" || item.length !== wanted.length) {
|
|
1631
|
+
this.work(1);
|
|
1632
|
+
return false;
|
|
1633
|
+
}
|
|
1634
|
+
this.work(wanted.length);
|
|
1635
|
+
return item === wanted;
|
|
1636
|
+
};
|
|
1637
|
+
if (name === "lastIndexOf") {
|
|
1638
|
+
let index2 = args.length > 1 ? integerOf(args[1]) : length - 1;
|
|
1639
|
+
index2 = index2 >= 0 ? Math.min(index2, length - 1) : length + index2;
|
|
1640
|
+
for (; index2 >= 0; index2--) if (same(array[index2])) return index2;
|
|
1641
|
+
return -1;
|
|
1642
|
+
}
|
|
1643
|
+
let index = integerOf(args[1]);
|
|
1644
|
+
if (index < 0) index = Math.max(length + index, 0);
|
|
1645
|
+
for (; index < length; index++) if (same(array[index])) return name === "includes" ? true : index;
|
|
1646
|
+
return name === "includes" ? false : -1;
|
|
1647
|
+
}
|
|
995
1648
|
/**
|
|
996
1649
|
* Count a call that starts `callerDepth` calls deep, until it returns.
|
|
997
1650
|
*
|
|
@@ -1034,11 +1687,13 @@ var Interpreter = class {
|
|
|
1034
1687
|
*/
|
|
1035
1688
|
bindFunction(target, boundThis, boundArgs) {
|
|
1036
1689
|
this.charge((boundArgs.length + 2) * 8);
|
|
1037
|
-
|
|
1690
|
+
const bound = (...rest) => {
|
|
1038
1691
|
const result = this.callFunction(target, boundThis, [...boundArgs, ...rest], this.callerDepth);
|
|
1039
1692
|
result.then(void 0, ignoreRejection2);
|
|
1040
1693
|
return result;
|
|
1041
1694
|
};
|
|
1695
|
+
this.provided.add(bound);
|
|
1696
|
+
return bound;
|
|
1042
1697
|
}
|
|
1043
1698
|
/**
|
|
1044
1699
|
* The checks before a built-in or host function runs. The engine performs such a call in one
|
|
@@ -1050,6 +1705,15 @@ var Interpreter = class {
|
|
|
1050
1705
|
checkBuiltinCall(fn, thisArg, args) {
|
|
1051
1706
|
const arrayMethod = ARRAY_METHODS.get(fn);
|
|
1052
1707
|
const stringMethod = arrayMethod === void 0 ? STRING_METHODS.get(fn) : void 0;
|
|
1708
|
+
const otherMethod = arrayMethod === void 0 && stringMethod === void 0 ? OTHER_METHODS.get(fn) : void 0;
|
|
1709
|
+
const engineMethod = arrayMethod !== void 0 || stringMethod !== void 0 || otherMethod !== void 0;
|
|
1710
|
+
if (!engineMethod && fn !== ARRAY_ITERATOR_NEXT && fn !== FunctionProtoToString && !this.provided.has(fn) && !LIBRARY_FUNCTIONS.has(fn)) {
|
|
1711
|
+
throw new InterpreterError("This built-in function is not available in the sandbox");
|
|
1712
|
+
}
|
|
1713
|
+
if (otherMethod !== void 0 && !RECEIVERS[otherMethod.kind].accepts(thisArg, otherMethod.name)) {
|
|
1714
|
+
const { kind, name } = otherMethod;
|
|
1715
|
+
throw new InterpreterError(`${kind} '${name}' works on ${RECEIVERS[kind].noun} only`);
|
|
1716
|
+
}
|
|
1053
1717
|
let arrayText = 0;
|
|
1054
1718
|
if (!ARRAY_DATA_FUNCTIONS.has(fn)) {
|
|
1055
1719
|
const isData = arrayMethod === void 0 ? void 0 : ARRAY_DATA_ARGUMENTS.get(arrayMethod);
|
|
@@ -1065,10 +1729,24 @@ var Interpreter = class {
|
|
|
1065
1729
|
if (Array.isArray(arg) && !isData?.(i)) measureArray(arg);
|
|
1066
1730
|
}
|
|
1067
1731
|
if (arrayMethod === void 0 && stringMethod === void 0 && Array.isArray(thisArg)) measureArray(thisArg);
|
|
1068
|
-
|
|
1732
|
+
const measured = measure;
|
|
1733
|
+
arrayText = measured?.length ?? 0;
|
|
1734
|
+
this.work(arrayText * WRITE_WORK + (measured?.work ?? 0));
|
|
1069
1735
|
}
|
|
1070
1736
|
if (stringMethod !== void 0) args = this.checkStringMethod(stringMethod, thisArg, args, arrayText);
|
|
1071
|
-
else if (arrayMethod !== void 0) this.checkArrayMethod(arrayMethod, thisArg, args);
|
|
1737
|
+
else if (arrayMethod !== void 0) args = this.checkArrayMethod(arrayMethod, thisArg, args);
|
|
1738
|
+
const callbackTaken = arrayMethod !== void 0 && HIGHER_ORDER_ARRAY_METHODS.has(arrayMethod) && typeof args[0] === "function";
|
|
1739
|
+
if (engineMethod && !callbackTaken) {
|
|
1740
|
+
const isData = arrayMethod === void 0 ? void 0 : ARRAY_DATA_ARGUMENTS.get(arrayMethod);
|
|
1741
|
+
for (let i = 0; i < args.length; i++) {
|
|
1742
|
+
if (typeof args[i] !== "function" || isData?.(i)) continue;
|
|
1743
|
+
const kind = arrayMethod !== void 0 ? "Array" : stringMethod !== void 0 ? "String" : otherMethod?.kind;
|
|
1744
|
+
const name = arrayMethod ?? stringMethod ?? otherMethod?.name;
|
|
1745
|
+
throw new InterpreterError(`${kind} '${name}' does not take a function in the sandbox`);
|
|
1746
|
+
}
|
|
1747
|
+
}
|
|
1748
|
+
const convert = ARGUMENT_CONVERSIONS.get(fn);
|
|
1749
|
+
if (convert) args = convert(args);
|
|
1072
1750
|
const cost = CALL_COSTS.get(fn);
|
|
1073
1751
|
if (cost) this.charge(cost(args));
|
|
1074
1752
|
return args;
|
|
@@ -1078,6 +1756,10 @@ var Interpreter = class {
|
|
|
1078
1756
|
if (name === "match" || name === "matchAll" || name === "search") {
|
|
1079
1757
|
throw new InterpreterError(`String '${name}' is not supported: it runs a regular expression`);
|
|
1080
1758
|
}
|
|
1759
|
+
if (TEXT_SEARCHES.has(name) && args.length > 0) {
|
|
1760
|
+
const pattern = convertedOnce(args[0], String);
|
|
1761
|
+
if (pattern !== args[0]) args = [pattern, ...args.slice(1)];
|
|
1762
|
+
}
|
|
1081
1763
|
if (name === "replace" || name === "replaceAll") {
|
|
1082
1764
|
const replacement = args[1];
|
|
1083
1765
|
if (typeof replacement === "function") {
|
|
@@ -1101,14 +1783,15 @@ var Interpreter = class {
|
|
|
1101
1783
|
return args;
|
|
1102
1784
|
}
|
|
1103
1785
|
if (name === "repeat" || name === "padStart" || name === "padEnd") {
|
|
1104
|
-
const
|
|
1786
|
+
const count = convertedOnce(args[0], Number);
|
|
1787
|
+
const n = Number(count);
|
|
1105
1788
|
const produced = name === "repeat" ? receiver.length * (n > 0 ? n : 0) : Math.max(receiver.length, n > 0 ? n : 0);
|
|
1106
1789
|
if (produced > MAX_STRING_OP_LENGTH) {
|
|
1107
1790
|
throw new InterpreterError(
|
|
1108
1791
|
`String '${name}' would produce ${produced} chars, exceeding the ${MAX_STRING_OP_LENGTH} limit`
|
|
1109
1792
|
);
|
|
1110
1793
|
}
|
|
1111
|
-
return args;
|
|
1794
|
+
return args.length === 0 ? args : [count, ...args.slice(1)];
|
|
1112
1795
|
}
|
|
1113
1796
|
if (name === "concat") {
|
|
1114
1797
|
let produced = receiver.length + arrayText;
|
|
@@ -1122,6 +1805,20 @@ var Interpreter = class {
|
|
|
1122
1805
|
}
|
|
1123
1806
|
return args;
|
|
1124
1807
|
}
|
|
1808
|
+
if (name === "normalize") {
|
|
1809
|
+
const form = convertedOnce(args[0], String);
|
|
1810
|
+
const growth = form === "NFKC" || form === "NFKD" ? 18 : 4;
|
|
1811
|
+
if (receiver.length * growth > MAX_JOIN_LENGTH) {
|
|
1812
|
+
let produced = 0;
|
|
1813
|
+
for (let i = 0; i < receiver.length && produced <= MAX_JOIN_LENGTH; i++) {
|
|
1814
|
+
produced += receiver.charCodeAt(i) < 128 ? 1 : growth;
|
|
1815
|
+
}
|
|
1816
|
+
if (produced > MAX_JOIN_LENGTH) {
|
|
1817
|
+
throw new InterpreterError(`String 'normalize' could produce more than ${MAX_JOIN_LENGTH} chars`);
|
|
1818
|
+
}
|
|
1819
|
+
}
|
|
1820
|
+
return args.length === 0 ? args : [form, ...args.slice(1)];
|
|
1821
|
+
}
|
|
1125
1822
|
if (name === "split") {
|
|
1126
1823
|
const asked = args[1] === void 0 ? Number.POSITIVE_INFINITY : Number(args[1]) >>> 0;
|
|
1127
1824
|
return [args[0], Math.min(asked, MAX_ARRAY_LENGTH + 1)];
|
|
@@ -1134,44 +1831,56 @@ var Interpreter = class {
|
|
|
1134
1831
|
throw new InterpreterError(`An array cannot be longer than ${MAX_ARRAY_LENGTH} items`);
|
|
1135
1832
|
};
|
|
1136
1833
|
switch (name) {
|
|
1834
|
+
// Written by the interpreter itself, one item at a time (see arrayLocaleText): how long
|
|
1835
|
+
// the text of a number or a date is depends on the locale and the options.
|
|
1836
|
+
case "toLocaleString":
|
|
1837
|
+
return args;
|
|
1137
1838
|
// `join` writes every item and a separator between them into one string, in one step; so
|
|
1138
|
-
//
|
|
1839
|
+
// does the conversion to text.
|
|
1139
1840
|
case "join":
|
|
1140
|
-
case "toString":
|
|
1141
|
-
|
|
1142
|
-
const separator =
|
|
1841
|
+
case "toString": {
|
|
1842
|
+
const given = name !== "join" || args.length === 0 ? void 0 : convertedOnce(args[0], String);
|
|
1843
|
+
const separator = given === void 0 ? "," : String(given);
|
|
1143
1844
|
const measure = newTextMeasure();
|
|
1144
1845
|
measureArrayText(receiver, separator.length, measure, 0);
|
|
1145
1846
|
if (measure.length > MAX_JOIN_LENGTH) {
|
|
1146
1847
|
throw new InterpreterError(`Array '${name}' would produce more than ${MAX_JOIN_LENGTH} chars`);
|
|
1147
1848
|
}
|
|
1148
|
-
|
|
1849
|
+
this.work(measure.work);
|
|
1850
|
+
return name === "join" && args.length > 0 ? [given, ...args.slice(1)] : args;
|
|
1149
1851
|
}
|
|
1150
1852
|
// Without a comparison function the engine compares the items as text: strings as they
|
|
1151
1853
|
// are, and an array among the items joined, again for every comparison.
|
|
1152
1854
|
case "sort":
|
|
1153
1855
|
case "toSorted": {
|
|
1154
|
-
if (typeof args[0] === "function") return;
|
|
1856
|
+
if (typeof args[0] === "function") return args;
|
|
1155
1857
|
const measure = newTextMeasure();
|
|
1858
|
+
let chars = 0;
|
|
1156
1859
|
for (let i = 0; i < receiver.length && measure.length <= MAX_JOIN_LENGTH; i++) {
|
|
1157
1860
|
const item = receiver[i];
|
|
1158
1861
|
if (Array.isArray(item)) measureArrayText(item, 1, measure, 1);
|
|
1862
|
+
else chars += typeof item === "string" ? item.length : 32;
|
|
1159
1863
|
}
|
|
1160
1864
|
if (measure.length > MAX_JOIN_LENGTH) throw new InterpreterError(TEXT_TOO_LONG);
|
|
1161
|
-
|
|
1865
|
+
const compared = (chars + measure.length) * (Math.ceil(Math.log2(receiver.length + 1)) + 6);
|
|
1866
|
+
if (compared > MAX_CALL_WORK) {
|
|
1867
|
+
throw new InterpreterError(`Array '${name}' would compare more text than one call may`);
|
|
1868
|
+
}
|
|
1869
|
+
this.work(compared);
|
|
1870
|
+
return args;
|
|
1162
1871
|
}
|
|
1163
1872
|
// Growth by the arguments (a spread makes them many): charged before it happens.
|
|
1164
1873
|
case "push":
|
|
1165
1874
|
case "unshift":
|
|
1166
1875
|
if (receiver.length + args.length > MAX_ARRAY_LENGTH) tooLong2();
|
|
1167
1876
|
this.charge(args.length * 8);
|
|
1168
|
-
return;
|
|
1877
|
+
return args;
|
|
1169
1878
|
case "splice":
|
|
1170
1879
|
case "toSpliced": {
|
|
1171
1880
|
const added = Math.max(0, args.length - 2);
|
|
1172
1881
|
if (receiver.length + added > MAX_ARRAY_LENGTH) tooLong2();
|
|
1173
1882
|
if (name === "splice") this.charge(added * 8);
|
|
1174
|
-
return;
|
|
1883
|
+
return args;
|
|
1175
1884
|
}
|
|
1176
1885
|
// A new array of the receiver and every array among the arguments: one array, given many
|
|
1177
1886
|
// times, is small in memory and large once copied.
|
|
@@ -1182,16 +1891,50 @@ var Interpreter = class {
|
|
|
1182
1891
|
length += Array.isArray(arg) ? arg.length : 1;
|
|
1183
1892
|
}
|
|
1184
1893
|
if (length > MAX_ARRAY_LENGTH) tooLong2();
|
|
1185
|
-
return;
|
|
1894
|
+
return args;
|
|
1186
1895
|
}
|
|
1187
1896
|
case "flat": {
|
|
1188
|
-
const
|
|
1897
|
+
const given = convertedOnce(args[0], Number);
|
|
1898
|
+
const depth = given === void 0 ? 1 : Number(given);
|
|
1189
1899
|
if (flatLength(receiver, Number.isNaN(depth) ? 0 : depth, MAX_ARRAY_LENGTH) > MAX_ARRAY_LENGTH) tooLong2();
|
|
1190
|
-
return;
|
|
1900
|
+
return args.length === 0 ? args : [given, ...args.slice(1)];
|
|
1191
1901
|
}
|
|
1192
1902
|
default:
|
|
1193
|
-
return;
|
|
1903
|
+
return args;
|
|
1904
|
+
}
|
|
1905
|
+
}
|
|
1906
|
+
/**
|
|
1907
|
+
* `array.toLocaleString(locales, options)`: the text of every item in the locale's format,
|
|
1908
|
+
* joined by commas, as the engine writes it. The engine does it in one step and the length of
|
|
1909
|
+
* what an item becomes is not known beforehand (a number can take hundreds of chars with the
|
|
1910
|
+
* right options), so the items are converted here one at a time: each counts as a step, and
|
|
1911
|
+
* the text is refused as soon as it is longer than a script's longest text.
|
|
1912
|
+
*/
|
|
1913
|
+
arrayLocaleText(array, args, active, written, depth) {
|
|
1914
|
+
if (depth > MAX_TEXT_NESTING) throw new InterpreterError(TEXT_TOO_LONG);
|
|
1915
|
+
const parts = [];
|
|
1916
|
+
active.add(array);
|
|
1917
|
+
try {
|
|
1918
|
+
for (let i = 0; i < array.length; i++) {
|
|
1919
|
+
this.tick();
|
|
1920
|
+
const item = array[i];
|
|
1921
|
+
let text = "";
|
|
1922
|
+
if (Array.isArray(item) && item.toLocaleString === ArrayProtoToLocaleString) {
|
|
1923
|
+
if (!active.has(item)) text = this.arrayLocaleText(item, args, active, written, depth + 1);
|
|
1924
|
+
} else if (item !== null && item !== void 0) {
|
|
1925
|
+
text = String(item.toLocaleString(...args));
|
|
1926
|
+
written.length += text.length;
|
|
1927
|
+
}
|
|
1928
|
+
if (i > 0) written.length += 1;
|
|
1929
|
+
if (written.length > MAX_JOIN_LENGTH) {
|
|
1930
|
+
throw new InterpreterError(`Array 'toLocaleString' would produce more than ${MAX_JOIN_LENGTH} chars`);
|
|
1931
|
+
}
|
|
1932
|
+
parts.push(text);
|
|
1933
|
+
}
|
|
1934
|
+
} finally {
|
|
1935
|
+
active.delete(array);
|
|
1194
1936
|
}
|
|
1937
|
+
return parts.join(",");
|
|
1195
1938
|
}
|
|
1196
1939
|
/**
|
|
1197
1940
|
* Async implementations of the higher-order array methods, so interpreter
|
|
@@ -1264,10 +2007,30 @@ var Interpreter = class {
|
|
|
1264
2007
|
acc = arr[order[0]];
|
|
1265
2008
|
start = 1;
|
|
1266
2009
|
}
|
|
2010
|
+
let owed = 0;
|
|
1267
2011
|
for (let n = start; n < order.length; n++) {
|
|
1268
2012
|
this.tick();
|
|
1269
|
-
|
|
2013
|
+
let pending;
|
|
2014
|
+
if (interpreted !== void 0 && typeof acc === "string") {
|
|
2015
|
+
this.accumulatorOwed = owed;
|
|
2016
|
+
try {
|
|
2017
|
+
pending = reducer(acc, arr[order[n]], order[n], arr);
|
|
2018
|
+
} finally {
|
|
2019
|
+
this.accumulatorOwed = void 0;
|
|
2020
|
+
}
|
|
2021
|
+
} else {
|
|
2022
|
+
pending = reducer(acc, arr[order[n]], order[n], arr);
|
|
2023
|
+
}
|
|
2024
|
+
const next = await pending;
|
|
2025
|
+
if (next instanceof AccumulatedText) {
|
|
2026
|
+
acc = next.value;
|
|
2027
|
+
owed = next.owed;
|
|
2028
|
+
} else {
|
|
2029
|
+
acc = next;
|
|
2030
|
+
owed = 0;
|
|
2031
|
+
}
|
|
1270
2032
|
}
|
|
2033
|
+
if (owed > 0) this.charge(owed);
|
|
1271
2034
|
return acc;
|
|
1272
2035
|
}
|
|
1273
2036
|
case "sort":
|
|
@@ -1365,7 +2128,9 @@ var Interpreter = class {
|
|
|
1365
2128
|
const rest = {};
|
|
1366
2129
|
for (const key2 of Object.keys(source)) {
|
|
1367
2130
|
this.tick();
|
|
1368
|
-
if (
|
|
2131
|
+
if (taken.has(key2) || BLOCKED_KEYS.has(key2)) continue;
|
|
2132
|
+
assertStorable(rest, key2, source[key2]);
|
|
2133
|
+
rest[key2] = source[key2];
|
|
1369
2134
|
}
|
|
1370
2135
|
await this.applyPattern(prop.argument, rest, scope, mode);
|
|
1371
2136
|
continue;
|
|
@@ -1390,7 +2155,7 @@ var Interpreter = class {
|
|
|
1390
2155
|
if (node.generator) throw new InterpreterError("Generator functions are not supported");
|
|
1391
2156
|
const selfName = node.type === "FunctionExpression" && node.id ? node.id.name : void 0;
|
|
1392
2157
|
const outer = selfName === void 0 ? closure : closure.child();
|
|
1393
|
-
const call = async (args, callerDepth) => {
|
|
2158
|
+
const call = async (args, callerDepth, accumulatorOwed) => {
|
|
1394
2159
|
const fnScope = outer.activation(this.enterCall(callerDepth));
|
|
1395
2160
|
try {
|
|
1396
2161
|
for (let i = 0; i < node.params.length; i++) {
|
|
@@ -1401,11 +2166,19 @@ var Interpreter = class {
|
|
|
1401
2166
|
}
|
|
1402
2167
|
await this.applyPattern(param, args[i], fnScope, "let");
|
|
1403
2168
|
}
|
|
2169
|
+
const first = node.params[0];
|
|
2170
|
+
if (accumulatorOwed !== void 0 && first?.type === "Identifier" && typeof args[0] === "string") {
|
|
2171
|
+
const accumulator = fnScope.slot(first.name);
|
|
2172
|
+
if (accumulator !== void 0) {
|
|
2173
|
+
accumulator.owed = accumulatorOwed;
|
|
2174
|
+
fnScope.accumulator = first.name;
|
|
2175
|
+
}
|
|
2176
|
+
}
|
|
1404
2177
|
if (node.body.type === "BlockStatement") {
|
|
1405
2178
|
await this.execBlock(node.body.body, fnScope);
|
|
1406
2179
|
return void 0;
|
|
1407
2180
|
}
|
|
1408
|
-
return await this.
|
|
2181
|
+
return await this.evalReturned(node.body, fnScope);
|
|
1409
2182
|
} catch (e) {
|
|
1410
2183
|
if (e instanceof ReturnSignal) return e.value;
|
|
1411
2184
|
throw e;
|
|
@@ -1414,8 +2187,13 @@ var Interpreter = class {
|
|
|
1414
2187
|
}
|
|
1415
2188
|
};
|
|
1416
2189
|
const depthOfCaller = () => this.callerDepth;
|
|
2190
|
+
const takeAccumulatorOwed = () => {
|
|
2191
|
+
const owed = this.accumulatorOwed;
|
|
2192
|
+
this.accumulatorOwed = void 0;
|
|
2193
|
+
return owed;
|
|
2194
|
+
};
|
|
1417
2195
|
const interpreted = function interpreted2(...args) {
|
|
1418
|
-
const result = call(args, depthOfCaller());
|
|
2196
|
+
const result = call(args, depthOfCaller(), takeAccumulatorOwed());
|
|
1419
2197
|
result.then(void 0, ignoreRejection2);
|
|
1420
2198
|
return result;
|
|
1421
2199
|
};
|
|
@@ -1425,7 +2203,9 @@ var Interpreter = class {
|
|
|
1425
2203
|
}
|
|
1426
2204
|
/** A computed property key as text. An array as a key is its items, joined. */
|
|
1427
2205
|
keyText(value) {
|
|
1428
|
-
|
|
2206
|
+
this.arrayOperands(value);
|
|
2207
|
+
this.bigIntAsText(value);
|
|
2208
|
+
this.work(operandSize(value));
|
|
1429
2209
|
return String(value);
|
|
1430
2210
|
}
|
|
1431
2211
|
async propKey(prop, scope) {
|
|
@@ -1452,6 +2232,41 @@ function isScriptData(value) {
|
|
|
1452
2232
|
const prototype = Object.getPrototypeOf(value);
|
|
1453
2233
|
return prototype === Object.prototype || prototype === null;
|
|
1454
2234
|
}
|
|
2235
|
+
function operandSize(value) {
|
|
2236
|
+
return typeof value === "string" || Array.isArray(value) ? value.length : 0;
|
|
2237
|
+
}
|
|
2238
|
+
function integerOf(value) {
|
|
2239
|
+
const number = Number(value);
|
|
2240
|
+
return Number.isNaN(number) ? 0 : Math.trunc(number);
|
|
2241
|
+
}
|
|
2242
|
+
function expandReplacement(template, text, at, matched) {
|
|
2243
|
+
if (!template.includes("$")) return template;
|
|
2244
|
+
let out = "";
|
|
2245
|
+
for (let i = 0; i < template.length; i++) {
|
|
2246
|
+
const next = template[i] === "$" ? template[i + 1] : void 0;
|
|
2247
|
+
if (next === "$") out += "$";
|
|
2248
|
+
else if (next === "&") out += matched;
|
|
2249
|
+
else if (next === "`") out += text.substring(0, at);
|
|
2250
|
+
else if (next === "'") out += text.substring(at + matched.length);
|
|
2251
|
+
else {
|
|
2252
|
+
out += template[i];
|
|
2253
|
+
continue;
|
|
2254
|
+
}
|
|
2255
|
+
i++;
|
|
2256
|
+
}
|
|
2257
|
+
return out;
|
|
2258
|
+
}
|
|
2259
|
+
function convertedOnce(value, convert) {
|
|
2260
|
+
return typeof value === "object" && value !== null ? convert(value) : value;
|
|
2261
|
+
}
|
|
2262
|
+
function checkArrayWrite(array, key, value) {
|
|
2263
|
+
if (key === "length") value = convertedOnce(value, Number);
|
|
2264
|
+
const length = arrayLengthAfterWrite(array, key, value);
|
|
2265
|
+
if (length > MAX_ARRAY_LENGTH) {
|
|
2266
|
+
throw new InterpreterError(`An array cannot be longer than ${MAX_ARRAY_LENGTH} items`);
|
|
2267
|
+
}
|
|
2268
|
+
return { value, length };
|
|
2269
|
+
}
|
|
1455
2270
|
function arrayLengthAfterWrite(array, key, value) {
|
|
1456
2271
|
if (key === "length") {
|
|
1457
2272
|
const length = Number(value);
|
|
@@ -1513,8 +2328,6 @@ function isPlainObject(value) {
|
|
|
1513
2328
|
function sanitizeValue(value, options = {}, depth = 0, context = { propCount: { count: 0 }, visited: /* @__PURE__ */ new WeakSet() }) {
|
|
1514
2329
|
const maxDepth = options.maxDepth ?? 20;
|
|
1515
2330
|
const maxProperties = options.maxProperties ?? 1e4;
|
|
1516
|
-
const allowDates = options.allowDates ?? true;
|
|
1517
|
-
const allowErrors = options.allowErrors ?? true;
|
|
1518
2331
|
if (depth > maxDepth) {
|
|
1519
2332
|
throw new Error(
|
|
1520
2333
|
`Tool handler return value exceeds maximum depth (${maxDepth}). This limit prevents deeply nested objects that could cause stack overflow.`
|
|
@@ -1550,7 +2363,19 @@ function sanitizeValue(value, options = {}, depth = 0, context = { propCount: {
|
|
|
1550
2363
|
return "[Circular]";
|
|
1551
2364
|
}
|
|
1552
2365
|
context.visited.add(value);
|
|
2366
|
+
try {
|
|
2367
|
+
return sanitizeObjectValue(value, options, depth, context);
|
|
2368
|
+
} finally {
|
|
2369
|
+
context.visited.delete(value);
|
|
2370
|
+
}
|
|
1553
2371
|
}
|
|
2372
|
+
return String(value);
|
|
2373
|
+
}
|
|
2374
|
+
function sanitizeObjectValue(value, options, depth, context) {
|
|
2375
|
+
const maxProperties = options.maxProperties ?? 1e4;
|
|
2376
|
+
const allowDates = options.allowDates ?? true;
|
|
2377
|
+
const allowErrors = options.allowErrors ?? true;
|
|
2378
|
+
const type = typeof value;
|
|
1554
2379
|
if (ArrayIsArray(value)) {
|
|
1555
2380
|
const rawLen = ReflectGet(value, "length");
|
|
1556
2381
|
const len = typeof rawLen === "number" && NumberIsFinite(rawLen) && rawLen >= 0 ? MathFloor(rawLen) : 0;
|
|
@@ -1905,7 +2730,8 @@ var SafeJSON = frozenRecord({
|
|
|
1905
2730
|
}
|
|
1906
2731
|
const size = checkSerializedSize(value, MAX_JSON_TEXT_BYTES);
|
|
1907
2732
|
if (!size.ok) throw new RangeError(`JSON.stringify: the text would be too large (${size.error})`);
|
|
1908
|
-
const
|
|
2733
|
+
const indentation = typeof space === "number" || typeof space === "string" ? space : void 0;
|
|
2734
|
+
const indent = indentOf(indentation);
|
|
1909
2735
|
if (indent > 0) {
|
|
1910
2736
|
const budget = MAX_JSON_TEXT_BYTES - size.estimatedBytes;
|
|
1911
2737
|
if (indentationSize(value, indent, budget, 0, /* @__PURE__ */ new Set()) > budget) {
|
|
@@ -1915,10 +2741,14 @@ var SafeJSON = frozenRecord({
|
|
|
1915
2741
|
return JSON.stringify(
|
|
1916
2742
|
value,
|
|
1917
2743
|
Array.isArray(replacer) ? replacer : void 0,
|
|
1918
|
-
|
|
2744
|
+
indentation
|
|
1919
2745
|
);
|
|
1920
2746
|
}
|
|
1921
2747
|
});
|
|
2748
|
+
convertsBeforeCall(
|
|
2749
|
+
SafeJSON["parse"],
|
|
2750
|
+
(args) => args.length === 0 ? args : [String(args[0]), ...args.slice(1)]
|
|
2751
|
+
);
|
|
1922
2752
|
chargedBeforeCall(SafeJSON["parse"], (args) => parsedJsonCost(String(args[0])));
|
|
1923
2753
|
takesArraysAsData(SafeJSON["stringify"]);
|
|
1924
2754
|
var SafeObject = frozenRecord({
|
|
@@ -1933,7 +2763,10 @@ var SafeObject = frozenRecord({
|
|
|
1933
2763
|
if (entry === null || typeof entry !== "object") throw new TypeError("Each entry must be a [key, value] pair");
|
|
1934
2764
|
assertArrayTextWithinLimit(entry[0]);
|
|
1935
2765
|
const key = String(entry[0]);
|
|
1936
|
-
if (
|
|
2766
|
+
if (isBlockedKey(key)) continue;
|
|
2767
|
+
const value = entry[1];
|
|
2768
|
+
assertStorable(result, key, value);
|
|
2769
|
+
result[key] = value;
|
|
1937
2770
|
}
|
|
1938
2771
|
return result;
|
|
1939
2772
|
},
|
|
@@ -1944,7 +2777,10 @@ var SafeObject = frozenRecord({
|
|
|
1944
2777
|
for (const source of sources) {
|
|
1945
2778
|
if (source === null || source === void 0) continue;
|
|
1946
2779
|
for (const key of dataKeys(source)) {
|
|
1947
|
-
|
|
2780
|
+
let value = source[key];
|
|
2781
|
+
assertStorable(target, key, value);
|
|
2782
|
+
if (Array.isArray(target)) value = checkArrayWrite(target, key, value).value;
|
|
2783
|
+
target[key] = value;
|
|
1948
2784
|
}
|
|
1949
2785
|
}
|
|
1950
2786
|
return target;
|
|
@@ -2019,6 +2855,23 @@ var SafeDate = frozenFunction(() => (/* @__PURE__ */ new Date()).toString(), {
|
|
|
2019
2855
|
parse: (text) => Date.parse(String(text)),
|
|
2020
2856
|
UTC: (...parts) => Date.UTC(...parts)
|
|
2021
2857
|
});
|
|
2858
|
+
function encodedText(encode, value) {
|
|
2859
|
+
const text = String(value);
|
|
2860
|
+
if (text.length * 9 > MAX_JOIN_LENGTH) {
|
|
2861
|
+
let produced = 0;
|
|
2862
|
+
for (let index = 0; index < text.length && produced <= MAX_JOIN_LENGTH; index++) {
|
|
2863
|
+
const code = text.charCodeAt(index);
|
|
2864
|
+
if (code >= 2048) produced += 9;
|
|
2865
|
+
else if (code >= 128) produced += 6;
|
|
2866
|
+
else if (code >= 48 && code <= 57 || code >= 65 && code <= 90 || code >= 97 && code <= 122) produced += 1;
|
|
2867
|
+
else produced += 3;
|
|
2868
|
+
}
|
|
2869
|
+
if (produced > MAX_JOIN_LENGTH) {
|
|
2870
|
+
throw new RangeError(`The encoded text would be too long (more than ${MAX_JOIN_LENGTH} chars)`);
|
|
2871
|
+
}
|
|
2872
|
+
}
|
|
2873
|
+
return encode(text);
|
|
2874
|
+
}
|
|
2022
2875
|
var ERROR_TYPES = ["Error", "TypeError", "RangeError", "SyntaxError", "ReferenceError", "EvalError", "URIError"];
|
|
2023
2876
|
function errorType(name) {
|
|
2024
2877
|
const make = (args) => createScriptError(name, args.length === 0 || args[0] === void 0 ? "" : toStringValue(args[0]));
|
|
@@ -2049,8 +2902,8 @@ var SAFE_GLOBALS = Object.freeze({
|
|
|
2049
2902
|
parseInt: Object.freeze(
|
|
2050
2903
|
(value, radix) => Number.parseInt(String(value), radix)
|
|
2051
2904
|
),
|
|
2052
|
-
encodeURI: Object.freeze((value) => encodeURI
|
|
2053
|
-
encodeURIComponent: Object.freeze((value) => encodeURIComponent
|
|
2905
|
+
encodeURI: Object.freeze((value) => encodedText(encodeURI, value)),
|
|
2906
|
+
encodeURIComponent: Object.freeze((value) => encodedText(encodeURIComponent, value)),
|
|
2054
2907
|
decodeURI: Object.freeze((value) => decodeURI(String(value))),
|
|
2055
2908
|
decodeURIComponent: Object.freeze((value) => decodeURIComponent(String(value)))
|
|
2056
2909
|
});
|
|
@@ -2164,6 +3017,8 @@ var MemoryTracker = class {
|
|
|
2164
3017
|
trackedBytes = 0;
|
|
2165
3018
|
peakTrackedBytes = 0;
|
|
2166
3019
|
allocationCount = 0;
|
|
3020
|
+
/** Whether this tracker has refused an allocation since it was started */
|
|
3021
|
+
limitExceeded = false;
|
|
2167
3022
|
config;
|
|
2168
3023
|
constructor(config = {}) {
|
|
2169
3024
|
this.config = {
|
|
@@ -2180,6 +3035,14 @@ var MemoryTracker = class {
|
|
|
2180
3035
|
this.trackedBytes = 0;
|
|
2181
3036
|
this.peakTrackedBytes = 0;
|
|
2182
3037
|
this.allocationCount = 0;
|
|
3038
|
+
this.limitExceeded = false;
|
|
3039
|
+
}
|
|
3040
|
+
/**
|
|
3041
|
+
* Whether the limit was exceeded since tracking started: the tracker itself refused an
|
|
3042
|
+
* allocation. An error that only says so about itself is not evidence of that.
|
|
3043
|
+
*/
|
|
3044
|
+
hasExceededLimit() {
|
|
3045
|
+
return this.limitExceeded;
|
|
2183
3046
|
}
|
|
2184
3047
|
/**
|
|
2185
3048
|
* Track an allocation
|
|
@@ -2190,6 +3053,7 @@ var MemoryTracker = class {
|
|
|
2190
3053
|
track(bytes) {
|
|
2191
3054
|
if (typeof bytes !== "number" || Number.isNaN(bytes)) {
|
|
2192
3055
|
if (this.config.memoryLimit > 0) {
|
|
3056
|
+
this.limitExceeded = true;
|
|
2193
3057
|
throw new MemoryLimitError(
|
|
2194
3058
|
"Memory limit exceeded: allocation size is not a number",
|
|
2195
3059
|
this.trackedBytes,
|
|
@@ -2205,6 +3069,7 @@ var MemoryTracker = class {
|
|
|
2205
3069
|
this.peakTrackedBytes = this.trackedBytes;
|
|
2206
3070
|
}
|
|
2207
3071
|
if (this.config.memoryLimit > 0 && this.trackedBytes > this.config.memoryLimit) {
|
|
3072
|
+
this.limitExceeded = true;
|
|
2208
3073
|
throw new MemoryLimitError(
|
|
2209
3074
|
`Memory limit exceeded: ${this.formatBytes(this.trackedBytes)} used > ${this.formatBytes(
|
|
2210
3075
|
this.config.memoryLimit
|
|
@@ -2396,6 +3261,18 @@ function isReferenceId(value) {
|
|
|
2396
3261
|
return typeof value === "string" && REF_ID_PATTERN.test(value);
|
|
2397
3262
|
}
|
|
2398
3263
|
|
|
3264
|
+
// libs/core/src/sidecar/reference-sidecar.ts
|
|
3265
|
+
var SidecarLimitError = class _SidecarLimitError extends Error {
|
|
3266
|
+
constructor(message, code, limit, current) {
|
|
3267
|
+
super(message);
|
|
3268
|
+
this.code = code;
|
|
3269
|
+
this.limit = limit;
|
|
3270
|
+
this.current = current;
|
|
3271
|
+
this.name = "SidecarLimitError";
|
|
3272
|
+
Object.setPrototypeOf(this, _SidecarLimitError.prototype);
|
|
3273
|
+
}
|
|
3274
|
+
};
|
|
3275
|
+
|
|
2399
3276
|
// libs/core/src/sidecar/reference-resolver.ts
|
|
2400
3277
|
var ReflectGet2 = Reflect.get;
|
|
2401
3278
|
var NumberIsFinite2 = Number.isFinite;
|
|
@@ -2503,17 +3380,88 @@ var ReferenceResolver = class {
|
|
|
2503
3380
|
/**
|
|
2504
3381
|
* Check if resolution would exceed size limits
|
|
2505
3382
|
*
|
|
3383
|
+
* Two limits apply: `maxResolvedSize` to what this value expands to, and
|
|
3384
|
+
* `maxTotalResolvedSize` to what the execution has had resolved so far plus what resolving
|
|
3385
|
+
* this value would add (see `predictAddedSize`).
|
|
3386
|
+
*
|
|
2506
3387
|
* @param value - The value to check
|
|
2507
|
-
* @returns true if resolution would exceed maxResolvedSize
|
|
3388
|
+
* @returns true if resolution would exceed maxResolvedSize or the execution's total
|
|
2508
3389
|
*/
|
|
2509
3390
|
wouldExceedLimit(value) {
|
|
2510
3391
|
try {
|
|
2511
3392
|
const size = this.predictExpandedSize(value);
|
|
2512
|
-
|
|
3393
|
+
if (size > this.config.maxResolvedSize) {
|
|
3394
|
+
return true;
|
|
3395
|
+
}
|
|
3396
|
+
return !this.sidecar.canResolve(this.predictAddedSize(value, 0, /* @__PURE__ */ new Set()));
|
|
2513
3397
|
} catch {
|
|
2514
3398
|
return true;
|
|
2515
3399
|
}
|
|
2516
3400
|
}
|
|
3401
|
+
/**
|
|
3402
|
+
* Predict what resolving a value would add to the execution's total of resolved data,
|
|
3403
|
+
* WITHOUT allocating memory
|
|
3404
|
+
*
|
|
3405
|
+
* A stored value adds its size the first time it is resolved in the execution and nothing
|
|
3406
|
+
* afterwards (`counted` holds the ones this walk has seen). A composite adds the size of the
|
|
3407
|
+
* string it is joined into, every time, besides what its parts add.
|
|
3408
|
+
*/
|
|
3409
|
+
predictAddedSize(value, depth, counted) {
|
|
3410
|
+
if (depth > this.config.maxResolutionDepth) {
|
|
3411
|
+
throw new ResolutionLimitError(
|
|
3412
|
+
`Maximum resolution depth exceeded (${this.config.maxResolutionDepth})`,
|
|
3413
|
+
"MAX_RESOLUTION_DEPTH",
|
|
3414
|
+
this.config.maxResolutionDepth,
|
|
3415
|
+
depth
|
|
3416
|
+
);
|
|
3417
|
+
}
|
|
3418
|
+
if (isReferenceId(value)) {
|
|
3419
|
+
if (counted.has(value) || this.sidecar.isResolved(value)) {
|
|
3420
|
+
return 0;
|
|
3421
|
+
}
|
|
3422
|
+
counted.add(value);
|
|
3423
|
+
return this.sidecar.getSize(value) ?? 0;
|
|
3424
|
+
}
|
|
3425
|
+
if (isCompositeHandle(value)) {
|
|
3426
|
+
const parts = value.__parts;
|
|
3427
|
+
const len = untrustedLength(parts);
|
|
3428
|
+
let sum = this.predictExpandedSize(value, depth);
|
|
3429
|
+
for (let i = 0; i < len; i++) {
|
|
3430
|
+
sum += this.predictAddedSize(untrustedAt(parts, i), depth + 1, counted);
|
|
3431
|
+
}
|
|
3432
|
+
return sum;
|
|
3433
|
+
}
|
|
3434
|
+
if (Array.isArray(value)) {
|
|
3435
|
+
const len = untrustedLength(value);
|
|
3436
|
+
let sum = 0;
|
|
3437
|
+
for (let i = 0; i < len; i++) {
|
|
3438
|
+
sum += this.predictAddedSize(untrustedAt(value, i), depth + 1, counted);
|
|
3439
|
+
}
|
|
3440
|
+
return sum;
|
|
3441
|
+
}
|
|
3442
|
+
if (value !== null && typeof value === "object") {
|
|
3443
|
+
let sum = 0;
|
|
3444
|
+
for (const val of Object.values(value)) {
|
|
3445
|
+
sum += this.predictAddedSize(val, depth + 1, counted);
|
|
3446
|
+
}
|
|
3447
|
+
return sum;
|
|
3448
|
+
}
|
|
3449
|
+
return 0;
|
|
3450
|
+
}
|
|
3451
|
+
/**
|
|
3452
|
+
* Run a step that counts resolved data against the execution's total; when the sidecar
|
|
3453
|
+
* refuses it, the refusal is thrown as the resolution error callers of `resolve` handle
|
|
3454
|
+
*/
|
|
3455
|
+
withinTotal(count) {
|
|
3456
|
+
try {
|
|
3457
|
+
count();
|
|
3458
|
+
} catch (error) {
|
|
3459
|
+
if (error instanceof SidecarLimitError) {
|
|
3460
|
+
throw new ResolutionLimitError(error.message, error.code, error.limit, error.current);
|
|
3461
|
+
}
|
|
3462
|
+
throw error;
|
|
3463
|
+
}
|
|
3464
|
+
}
|
|
2517
3465
|
/**
|
|
2518
3466
|
* Resolve all reference IDs in a value tree
|
|
2519
3467
|
*
|
|
@@ -2536,7 +3484,10 @@ var ReferenceResolver = class {
|
|
|
2536
3484
|
);
|
|
2537
3485
|
}
|
|
2538
3486
|
if (isReferenceId(value)) {
|
|
2539
|
-
|
|
3487
|
+
let data;
|
|
3488
|
+
this.withinTotal(() => {
|
|
3489
|
+
data = this.sidecar.resolveString(value);
|
|
3490
|
+
});
|
|
2540
3491
|
if (data === void 0) {
|
|
2541
3492
|
throw new Error(`Unknown reference: ${value}`);
|
|
2542
3493
|
}
|
|
@@ -2574,6 +3525,8 @@ var ReferenceResolver = class {
|
|
|
2574
3525
|
* Resolve a composite handle by concatenating its parts
|
|
2575
3526
|
*/
|
|
2576
3527
|
resolveComposite(handle, depth) {
|
|
3528
|
+
const joinedSize = this.predictExpandedSize(handle, depth);
|
|
3529
|
+
this.withinTotal(() => this.sidecar.countResolved(joinedSize));
|
|
2577
3530
|
const out = [];
|
|
2578
3531
|
const source = handle.__parts;
|
|
2579
3532
|
const len = untrustedLength(source);
|
|
@@ -3219,12 +4172,29 @@ var MAX_PARALLEL_ITEMS = 100;
|
|
|
3219
4172
|
var MAX_SERIALIZED_RESULT_BYTES = 50 * 1024 * 1024;
|
|
3220
4173
|
var DEFAULT_MAX_CONSOLE_CALLS = 100;
|
|
3221
4174
|
var DEFAULT_MAX_CONSOLE_OUTPUT_BYTES = 64 * 1024;
|
|
4175
|
+
var DEFAULT_MAX_TOOL_PAYLOAD_BYTES = 5 * 1024 * 1024;
|
|
4176
|
+
function certainlyLargerThan(value, bytes) {
|
|
4177
|
+
if (!Number.isFinite(bytes) || bytes <= 0) return false;
|
|
4178
|
+
return !checkSerializedSize(value, bytes).ok;
|
|
4179
|
+
}
|
|
4180
|
+
function executionOver() {
|
|
4181
|
+
return sandboxError("Execution ended");
|
|
4182
|
+
}
|
|
3222
4183
|
function sandboxError(message, name = "Error", code) {
|
|
3223
4184
|
const error = new Error(message);
|
|
3224
4185
|
error.name = name;
|
|
3225
4186
|
if (code !== void 0) error.code = code;
|
|
3226
4187
|
return error;
|
|
3227
4188
|
}
|
|
4189
|
+
function ignoreRejection3() {
|
|
4190
|
+
}
|
|
4191
|
+
function observed(helper) {
|
|
4192
|
+
return (...args) => {
|
|
4193
|
+
const result = helper(...args);
|
|
4194
|
+
result.then(void 0, ignoreRejection3);
|
|
4195
|
+
return result;
|
|
4196
|
+
};
|
|
4197
|
+
}
|
|
3228
4198
|
function frozenRecord2(members) {
|
|
3229
4199
|
const record = /* @__PURE__ */ Object.create(null);
|
|
3230
4200
|
for (const key of Object.keys(members)) record[key] = members[key];
|
|
@@ -3291,15 +4261,20 @@ var InterpreterAdapter = class {
|
|
|
3291
4261
|
const allocationLimit = typeof memoryLimit === "number" && memoryLimit > 0 ? Math.min(memoryLimit, adapterLimit) : adapterLimit;
|
|
3292
4262
|
const tracker = new MemoryTracker({ memoryLimit: Number.isFinite(allocationLimit) ? allocationLimit : 0 });
|
|
3293
4263
|
const charge = (bytes) => tracker.track(bytes);
|
|
4264
|
+
let chargeForHelper = (_bytes) => {
|
|
4265
|
+
throw sandboxError("The interpreter is not running");
|
|
4266
|
+
};
|
|
4267
|
+
const timeout = context.config.timeout;
|
|
4268
|
+
const deadlineAt = timeout && timeout > 0 ? Date.now() + timeout : void 0;
|
|
3294
4269
|
let interpreter;
|
|
4270
|
+
const callbacks = {
|
|
4271
|
+
call: () => {
|
|
4272
|
+
throw sandboxError("The interpreter is not running");
|
|
4273
|
+
}
|
|
4274
|
+
};
|
|
3295
4275
|
try {
|
|
3296
4276
|
const safe = createSafeGlobals();
|
|
3297
|
-
const
|
|
3298
|
-
call: () => {
|
|
3299
|
-
throw sandboxError("The interpreter is not running");
|
|
3300
|
-
}
|
|
3301
|
-
};
|
|
3302
|
-
const runtime = this.runtimeGlobals(context, charge, callbacks);
|
|
4277
|
+
const runtime = this.runtimeGlobals(context, (bytes) => chargeForHelper(bytes), callbacks);
|
|
3303
4278
|
for (const name of Object.keys(runtime)) {
|
|
3304
4279
|
if (!Object.prototype.hasOwnProperty.call(safe.globals, name)) safe.globals[name] = runtime[name];
|
|
3305
4280
|
}
|
|
@@ -3311,37 +4286,40 @@ var InterpreterAdapter = class {
|
|
|
3311
4286
|
maxCallDepth: this.options.maxCallDepth ?? DEFAULT_MAX_CALL_DEPTH,
|
|
3312
4287
|
maxPendingCalls: this.options.maxPendingCalls,
|
|
3313
4288
|
signal: context.abortController.signal,
|
|
4289
|
+
deadline: deadlineAt,
|
|
3314
4290
|
charge
|
|
3315
4291
|
});
|
|
3316
|
-
const
|
|
3317
|
-
callbacks.call = (fn, args) =>
|
|
4292
|
+
const running2 = interpreter;
|
|
4293
|
+
callbacks.call = (fn, args) => running2.call(fn, args);
|
|
4294
|
+
callbacks.countBigInt = (value) => running2.countBigInt(value);
|
|
4295
|
+
chargeForHelper = (bytes) => running2.chargeAllocation(bytes);
|
|
3318
4296
|
} catch (error) {
|
|
3319
4297
|
return this.fail(error, startTime, stats.toolCallCount, 0, sanitizeStacks);
|
|
3320
4298
|
}
|
|
3321
|
-
const timeout = context.config.timeout;
|
|
3322
4299
|
const timer = timeout && timeout > 0 ? setTimeout(() => context.abortController.abort(), timeout) : void 0;
|
|
3323
4300
|
let timeoutHandle;
|
|
3324
4301
|
const TIMED_OUT = /* @__PURE__ */ Symbol("timeout");
|
|
3325
4302
|
const deadline = timeout && timeout > 0 ? new Promise((resolve) => {
|
|
3326
4303
|
timeoutHandle = setTimeout(() => resolve(TIMED_OUT), timeout);
|
|
3327
4304
|
}) : void 0;
|
|
4305
|
+
const running = interpreter;
|
|
4306
|
+
const timedOut = () => this.fail(
|
|
4307
|
+
new Error(`Execution timed out after ${timeout}ms`),
|
|
4308
|
+
startTime,
|
|
4309
|
+
stats.toolCallCount,
|
|
4310
|
+
running.stepCount,
|
|
4311
|
+
sanitizeStacks,
|
|
4312
|
+
"TimeoutError",
|
|
4313
|
+
"EXECUTION_TIMEOUT"
|
|
4314
|
+
);
|
|
3328
4315
|
try {
|
|
3329
4316
|
const run = interpreter.run(program);
|
|
3330
4317
|
run.catch(() => void 0);
|
|
3331
4318
|
const outcome = deadline ? await Promise.race([run, deadline]) : await run;
|
|
3332
|
-
if (outcome === TIMED_OUT)
|
|
3333
|
-
return this.fail(
|
|
3334
|
-
new Error(`Execution timed out after ${timeout}ms`),
|
|
3335
|
-
startTime,
|
|
3336
|
-
stats.toolCallCount,
|
|
3337
|
-
interpreter.stepCount,
|
|
3338
|
-
sanitizeStacks,
|
|
3339
|
-
"TimeoutError",
|
|
3340
|
-
"EXECUTION_TIMEOUT"
|
|
3341
|
-
);
|
|
3342
|
-
}
|
|
4319
|
+
if (outcome === TIMED_OUT) return timedOut();
|
|
3343
4320
|
return this.succeed(outcome, context, startTime, stats.toolCallCount, interpreter.stepCount);
|
|
3344
4321
|
} catch (error) {
|
|
4322
|
+
if (error instanceof DeadlineError) return timedOut();
|
|
3345
4323
|
const code2 = error instanceof StepLimitError ? "STEP_LIMIT_EXCEEDED" : void 0;
|
|
3346
4324
|
return this.fail(
|
|
3347
4325
|
error,
|
|
@@ -3355,6 +4333,7 @@ var InterpreterAdapter = class {
|
|
|
3355
4333
|
} finally {
|
|
3356
4334
|
if (timer) clearTimeout(timer);
|
|
3357
4335
|
if (timeoutHandle) clearTimeout(timeoutHandle);
|
|
4336
|
+
callbacks.over = true;
|
|
3358
4337
|
interpreter.stop();
|
|
3359
4338
|
}
|
|
3360
4339
|
}
|
|
@@ -3366,7 +4345,7 @@ var InterpreterAdapter = class {
|
|
|
3366
4345
|
*/
|
|
3367
4346
|
runtimeGlobals(context, charge, callbacks) {
|
|
3368
4347
|
const { config } = context;
|
|
3369
|
-
const callTool = this.createCallTool(context);
|
|
4348
|
+
const callTool = observed(this.createCallTool(context, callbacks));
|
|
3370
4349
|
const resolver = context.sidecar && context.referenceConfig ? new ReferenceResolver(context.sidecar, context.referenceConfig) : void 0;
|
|
3371
4350
|
const joinReferences = (parts) => {
|
|
3372
4351
|
if (!resolver) {
|
|
@@ -3384,6 +4363,8 @@ var InterpreterAdapter = class {
|
|
|
3384
4363
|
const result = left + right;
|
|
3385
4364
|
if (typeof result === "string") {
|
|
3386
4365
|
charge((result.length - (typeof left === "string" ? left.length : 0)) * 2);
|
|
4366
|
+
} else if (typeof result === "bigint") {
|
|
4367
|
+
callbacks.countBigInt?.(result);
|
|
3387
4368
|
}
|
|
3388
4369
|
return result;
|
|
3389
4370
|
};
|
|
@@ -3391,12 +4372,20 @@ var InterpreterAdapter = class {
|
|
|
3391
4372
|
if (!Array.isArray(quasis)) throw sandboxError("Template pieces must be an array", "TypeError");
|
|
3392
4373
|
const parts = [];
|
|
3393
4374
|
let hasReference = false;
|
|
4375
|
+
let length = 0;
|
|
4376
|
+
const add = (part) => {
|
|
4377
|
+
length += part.length;
|
|
4378
|
+
if (length > MAX_JOIN_LENGTH) {
|
|
4379
|
+
throw sandboxError(`A template literal cannot produce more than ${MAX_JOIN_LENGTH} chars`, "RangeError");
|
|
4380
|
+
}
|
|
4381
|
+
parts.push(part);
|
|
4382
|
+
};
|
|
3394
4383
|
for (let i = 0; i < quasis.length; i++) {
|
|
3395
|
-
|
|
4384
|
+
add(String(quasis[i]));
|
|
3396
4385
|
if (i < values.length) {
|
|
3397
4386
|
const value = values[i];
|
|
3398
4387
|
if (typeof value === "string" && isReferenceId(value)) hasReference = true;
|
|
3399
|
-
|
|
4388
|
+
add(String(value));
|
|
3400
4389
|
}
|
|
3401
4390
|
}
|
|
3402
4391
|
if (hasReference) return joinReferences(parts.filter((part) => part !== ""));
|
|
@@ -3418,7 +4407,7 @@ var InterpreterAdapter = class {
|
|
|
3418
4407
|
yield item;
|
|
3419
4408
|
}
|
|
3420
4409
|
}
|
|
3421
|
-
const parallel = async (first, second) => {
|
|
4410
|
+
const parallel = observed(async (first, second) => {
|
|
3422
4411
|
let tasks;
|
|
3423
4412
|
if (typeof second === "function") {
|
|
3424
4413
|
if (!Array.isArray(first)) throw sandboxError("parallel requires an array of items", "TypeError");
|
|
@@ -3443,7 +4432,7 @@ var InterpreterAdapter = class {
|
|
|
3443
4432
|
${messages}`);
|
|
3444
4433
|
}
|
|
3445
4434
|
return settled.map((result) => result.value);
|
|
3446
|
-
};
|
|
4435
|
+
});
|
|
3447
4436
|
const globals = {
|
|
3448
4437
|
__safe_callTool: callTool,
|
|
3449
4438
|
__safe_concat: concat,
|
|
@@ -3461,19 +4450,23 @@ ${messages}`);
|
|
|
3461
4450
|
let consoleCalls = 0;
|
|
3462
4451
|
let consoleLength = 0;
|
|
3463
4452
|
const write = (level) => (...args) => {
|
|
4453
|
+
if (callbacks.over) throw executionOver();
|
|
3464
4454
|
consoleCalls++;
|
|
3465
4455
|
if (consoleCalls > maxConsoleCalls) {
|
|
3466
4456
|
throw sandboxError(
|
|
3467
4457
|
`Console call limit exceeded (max: ${maxConsoleCalls}). This limit prevents I/O flood attacks.`
|
|
3468
4458
|
);
|
|
3469
4459
|
}
|
|
4460
|
+
const outputLimit = () => sandboxError(
|
|
4461
|
+
`Console output size limit exceeded (max: ${maxConsoleOutputBytes} bytes). This limit prevents I/O flood attacks.`
|
|
4462
|
+
);
|
|
4463
|
+
const room = (maxConsoleOutputBytes - consoleLength) * 16 + 64 * 1024;
|
|
4464
|
+
for (const arg of args) {
|
|
4465
|
+
if (arg !== null && typeof arg === "object" && certainlyLargerThan(arg, room)) throw outputLimit();
|
|
4466
|
+
}
|
|
3470
4467
|
const line = args.map(consoleText).join(" ");
|
|
3471
4468
|
consoleLength += line.length;
|
|
3472
|
-
if (consoleLength > maxConsoleOutputBytes)
|
|
3473
|
-
throw sandboxError(
|
|
3474
|
-
`Console output size limit exceeded (max: ${maxConsoleOutputBytes} bytes). This limit prevents I/O flood attacks.`
|
|
3475
|
-
);
|
|
3476
|
-
}
|
|
4469
|
+
if (consoleLength > maxConsoleOutputBytes) throw outputLimit();
|
|
3477
4470
|
sink(level, line);
|
|
3478
4471
|
};
|
|
3479
4472
|
globals["__safe_console"] = frozenRecord2({
|
|
@@ -3486,7 +4479,7 @@ ${messages}`);
|
|
|
3486
4479
|
for (const namespace of context.toolNamespaces ?? []) {
|
|
3487
4480
|
const methods = {};
|
|
3488
4481
|
for (const method of namespace.methods) {
|
|
3489
|
-
if (isBlockedKey(method.name)) continue;
|
|
4482
|
+
if (isBlockedKey(method.name) || isEngineCalledKey(method.name)) continue;
|
|
3490
4483
|
methods[method.name] = (args, options) => callTool(method.toolName, args === void 0 ? {} : args, options);
|
|
3491
4484
|
}
|
|
3492
4485
|
globals[namespace.name] = frozenRecord2(methods);
|
|
@@ -3505,11 +4498,13 @@ ${messages}`);
|
|
|
3505
4498
|
* and the response cross as JSON, so the handler never receives a value of the script and the
|
|
3506
4499
|
* script never receives an object of the handler.
|
|
3507
4500
|
*/
|
|
3508
|
-
createCallTool(context) {
|
|
4501
|
+
createCallTool(context, execution) {
|
|
3509
4502
|
const configured = context.config.toolHandler;
|
|
3510
4503
|
const bridgeContext = context.toolHandler === void 0 && typeof configured === "function" ? Object.create(context, { toolHandler: { value: configured } }) : context;
|
|
3511
4504
|
const bridge = createHostToolBridge(bridgeContext, { updateStats: true });
|
|
4505
|
+
const maxPayloadBytes = context.config.toolBridge?.maxPayloadBytes ?? DEFAULT_MAX_TOOL_PAYLOAD_BYTES;
|
|
3512
4506
|
return async (toolName, args, options) => {
|
|
4507
|
+
if (execution.over) throw executionOver();
|
|
3513
4508
|
let throwOnError = true;
|
|
3514
4509
|
if (options !== void 0 && options !== null) {
|
|
3515
4510
|
if (typeof options !== "object") throw sandboxError("callTool options must be an object", "TypeError");
|
|
@@ -3521,6 +4516,13 @@ ${messages}`);
|
|
|
3521
4516
|
if (typeof args !== "object" || args === null || Array.isArray(args)) {
|
|
3522
4517
|
throw sandboxError("Tool arguments must be an object", "TypeError");
|
|
3523
4518
|
}
|
|
4519
|
+
if (certainlyLargerThan(args, maxPayloadBytes * 2 + 1024)) {
|
|
4520
|
+
throw sandboxError(
|
|
4521
|
+
`Tool request exceeds maximum size (${maxPayloadBytes} bytes)`,
|
|
4522
|
+
"ToolBridgeError",
|
|
4523
|
+
"TOOL_BRIDGE_REQUEST_TOO_LARGE"
|
|
4524
|
+
);
|
|
4525
|
+
}
|
|
3524
4526
|
let requestJson;
|
|
3525
4527
|
try {
|
|
3526
4528
|
requestJson = encodeToolBridgeRequest(toolName, args);
|