@enclave-vm/core 2.19.0 → 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/interpreter-adapter.d.ts +10 -1
- 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 +4796 -852
- package/esm/worker.mjs +1236 -165
- package/execution-deadline.d.ts +6 -0
- package/global-function-gate.d.ts +34 -1
- package/index.d.ts +3 -3
- package/index.js +4836 -892
- package/interpreter/interpreter.d.ts +247 -8
- 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 +1236 -165
package/esm/worker.mjs
CHANGED
|
@@ -107,13 +107,74 @@ var BLOCKED_KEYS = /* @__PURE__ */ new Set([
|
|
|
107
107
|
"__lookupSetter__"
|
|
108
108
|
]);
|
|
109
109
|
function isBlockedKey(key) {
|
|
110
|
-
return BLOCKED_KEYS.has(key);
|
|
110
|
+
return key === "__proto__" || BLOCKED_KEYS.has(key);
|
|
111
|
+
}
|
|
112
|
+
function assertKeyAllowed(key) {
|
|
113
|
+
if (isBlockedKey(key)) throw new InterpreterError(`Forbidden property access: ${key}`);
|
|
114
|
+
}
|
|
115
|
+
function readProperty(object, key) {
|
|
116
|
+
if (key === "__proto__" || BLOCKED_KEYS.has(key)) throw new InterpreterError(`Forbidden property access: ${key}`);
|
|
117
|
+
return object[key];
|
|
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
|
+
}
|
|
111
130
|
}
|
|
112
131
|
var MAX_STRING_OP_LENGTH = 1e6;
|
|
113
132
|
var MAX_JOIN_LENGTH = 16e6;
|
|
114
133
|
var MAX_TEXT_NESTING = 64;
|
|
115
134
|
var MAX_TEXT_ITEMS = 8e6;
|
|
116
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");
|
|
117
178
|
var HIGHER_ORDER_ARRAY_METHODS = /* @__PURE__ */ new Set([
|
|
118
179
|
"map",
|
|
119
180
|
"flatMap",
|
|
@@ -134,10 +195,12 @@ var FunctionProtoCall = Function.prototype.call;
|
|
|
134
195
|
var FunctionProtoApply = Function.prototype.apply;
|
|
135
196
|
var FunctionProtoBind = Function.prototype.bind;
|
|
136
197
|
var FunctionProtoToString = Function.prototype.toString;
|
|
198
|
+
var ArrayProtoToLocaleString = Array.prototype.toLocaleString;
|
|
199
|
+
var StringProtoIndexOf = String.prototype.indexOf;
|
|
137
200
|
function methodsOf(prototype) {
|
|
138
201
|
const methods = /* @__PURE__ */ new Map();
|
|
139
202
|
for (const name of Object.getOwnPropertyNames(prototype)) {
|
|
140
|
-
if (name
|
|
203
|
+
if (isBlockedKey(name)) continue;
|
|
141
204
|
const descriptor = Object.getOwnPropertyDescriptor(prototype, name);
|
|
142
205
|
if (descriptor && typeof descriptor.value === "function") methods.set(descriptor.value, name);
|
|
143
206
|
}
|
|
@@ -145,6 +208,34 @@ function methodsOf(prototype) {
|
|
|
145
208
|
}
|
|
146
209
|
var ARRAY_METHODS = methodsOf(Array.prototype);
|
|
147
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();
|
|
148
239
|
var ARRAY_DATA_ARGUMENTS = /* @__PURE__ */ new Map([
|
|
149
240
|
["push", () => true],
|
|
150
241
|
["unshift", () => true],
|
|
@@ -169,13 +260,18 @@ function convertsArguments(fn, count) {
|
|
|
169
260
|
CONVERTED_ARGUMENTS.set(fn, count);
|
|
170
261
|
return fn;
|
|
171
262
|
}
|
|
263
|
+
var ARGUMENT_CONVERSIONS = /* @__PURE__ */ new WeakMap();
|
|
264
|
+
function convertsBeforeCall(fn, convert) {
|
|
265
|
+
ARGUMENT_CONVERSIONS.set(fn, convert);
|
|
266
|
+
return fn;
|
|
267
|
+
}
|
|
172
268
|
var CALL_COSTS = /* @__PURE__ */ new WeakMap();
|
|
173
269
|
function chargedBeforeCall(fn, cost) {
|
|
174
270
|
CALL_COSTS.set(fn, cost);
|
|
175
271
|
return fn;
|
|
176
272
|
}
|
|
177
273
|
function newTextMeasure() {
|
|
178
|
-
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 };
|
|
179
275
|
}
|
|
180
276
|
function scalarTextLength(item, measure) {
|
|
181
277
|
switch (typeof item) {
|
|
@@ -183,8 +279,11 @@ function scalarTextLength(item, measure) {
|
|
|
183
279
|
case "boolean":
|
|
184
280
|
return 32;
|
|
185
281
|
// also covers a number in the longest locale format
|
|
186
|
-
case "bigint":
|
|
187
|
-
|
|
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
|
+
}
|
|
188
287
|
case "function": {
|
|
189
288
|
let length = measure.functions.get(item);
|
|
190
289
|
if (length === void 0) {
|
|
@@ -248,6 +347,7 @@ function assertArrayTextWithinLimit(...values) {
|
|
|
248
347
|
measureArrayText(value, 1, measure, 0);
|
|
249
348
|
if (measure.length > MAX_JOIN_LENGTH) throw new InterpreterError(TEXT_TOO_LONG);
|
|
250
349
|
}
|
|
350
|
+
return measure?.length ?? 0;
|
|
251
351
|
}
|
|
252
352
|
var StepLimitError = class extends Error {
|
|
253
353
|
constructor(limit) {
|
|
@@ -255,12 +355,24 @@ var StepLimitError = class extends Error {
|
|
|
255
355
|
this.name = "StepLimitError";
|
|
256
356
|
}
|
|
257
357
|
};
|
|
358
|
+
var DeadlineError = class extends Error {
|
|
359
|
+
constructor() {
|
|
360
|
+
super("Execution deadline exceeded");
|
|
361
|
+
this.name = "TimeoutError";
|
|
362
|
+
}
|
|
363
|
+
};
|
|
258
364
|
var InterpreterError = class extends Error {
|
|
259
365
|
constructor(message) {
|
|
260
366
|
super(message);
|
|
261
367
|
this.name = "InterpreterError";
|
|
262
368
|
}
|
|
263
369
|
};
|
|
370
|
+
var AccumulatedText = class {
|
|
371
|
+
constructor(value, owed) {
|
|
372
|
+
this.value = value;
|
|
373
|
+
this.owed = owed;
|
|
374
|
+
}
|
|
375
|
+
};
|
|
264
376
|
var ReturnSignal = class {
|
|
265
377
|
constructor(value) {
|
|
266
378
|
this.value = value;
|
|
@@ -281,12 +393,11 @@ function createScriptError(name, message, code) {
|
|
|
281
393
|
error["name"] = name;
|
|
282
394
|
error["message"] = message;
|
|
283
395
|
if (code !== void 0) error["code"] = code;
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
});
|
|
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 });
|
|
290
401
|
SCRIPT_ERRORS.add(error);
|
|
291
402
|
return Object.freeze(error);
|
|
292
403
|
}
|
|
@@ -294,69 +405,154 @@ function isScriptError(value) {
|
|
|
294
405
|
return typeof value === "object" && value !== null && SCRIPT_ERRORS.has(value);
|
|
295
406
|
}
|
|
296
407
|
var Scope = class _Scope {
|
|
297
|
-
constructor(parent) {
|
|
408
|
+
constructor(parent, depth, settle) {
|
|
298
409
|
this.parent = parent;
|
|
410
|
+
this.depth = depth ?? parent?.depth ?? 0;
|
|
411
|
+
this.settle = settle ?? parent?.settle ?? (() => void 0);
|
|
299
412
|
}
|
|
300
413
|
vars = /* @__PURE__ */ new Map();
|
|
414
|
+
/**
|
|
415
|
+
* How many calls deep the code of this scope runs: 0 for the program, and for the body of a
|
|
416
|
+
* function one more than where it was called from. A block inside has the depth around it.
|
|
417
|
+
*/
|
|
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;
|
|
301
426
|
child() {
|
|
302
|
-
|
|
427
|
+
const scope = new _Scope(this);
|
|
428
|
+
scope.accumulator = this.accumulator;
|
|
429
|
+
return scope;
|
|
430
|
+
}
|
|
431
|
+
/** The scope of one call of a function defined in this scope, running `depth` calls deep. */
|
|
432
|
+
activation(depth) {
|
|
433
|
+
return new _Scope(this, depth);
|
|
303
434
|
}
|
|
304
435
|
declare(name, value, mutable) {
|
|
305
|
-
this.vars.set(name, { value, mutable });
|
|
436
|
+
this.vars.set(name, { value, mutable, owed: 0 });
|
|
306
437
|
}
|
|
307
438
|
has(name) {
|
|
308
439
|
return this.vars.has(name) || (this.parent?.has(name) ?? false);
|
|
309
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. */
|
|
310
450
|
get(name) {
|
|
311
|
-
const slot = this.
|
|
312
|
-
if (slot)
|
|
313
|
-
if (
|
|
314
|
-
|
|
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;
|
|
315
459
|
}
|
|
316
460
|
set(name, value) {
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
}
|
|
323
|
-
if (
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
}
|
|
327
|
-
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;
|
|
328
470
|
}
|
|
329
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
|
+
}
|
|
482
|
+
var DEFAULT_MAX_PENDING_CALLS = 4096;
|
|
330
483
|
function ignoreRejection2() {
|
|
331
484
|
}
|
|
332
485
|
var Interpreter = class {
|
|
333
486
|
constructor(options) {
|
|
334
487
|
this.options = options;
|
|
335
488
|
this.globals = options.globals;
|
|
489
|
+
this.maxPendingCalls = options.maxPendingCalls ?? DEFAULT_MAX_PENDING_CALLS;
|
|
490
|
+
this.provide(this.globals, 2);
|
|
336
491
|
}
|
|
337
492
|
steps = 0;
|
|
338
|
-
|
|
493
|
+
/** Calls that have not returned: the running ones and the ones waiting on an `await` */
|
|
494
|
+
pendingCalls = 0;
|
|
495
|
+
/**
|
|
496
|
+
* The depth of whatever is making a call right now, for the function of the script that call
|
|
497
|
+
* starts. A function of the script is a host function too, and a built-in, `parallel` or a
|
|
498
|
+
* bound function invokes it without saying how deep it is: it reads this as it starts, in the
|
|
499
|
+
* same synchronous step as the call, and runs one deeper. Set by {@link withCallerDepth} for
|
|
500
|
+
* the synchronous part of a call only; a call that is waiting does not hold it, which is what
|
|
501
|
+
* keeps the depth of one chain apart from the depth of another. 0 when the host itself calls.
|
|
502
|
+
*/
|
|
503
|
+
callerDepth = 0;
|
|
504
|
+
maxPendingCalls;
|
|
339
505
|
globals;
|
|
340
|
-
/**
|
|
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 */
|
|
341
516
|
fatal;
|
|
342
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();
|
|
343
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
|
+
}
|
|
344
539
|
/**
|
|
345
540
|
* Call a function for a script, with the checks that apply to a call the script writes itself.
|
|
346
541
|
* For a host helper that is handed a callback (`parallel(items, fn)`): `fn` may be a function
|
|
347
542
|
* of the script, or a built-in or host function the script passed along.
|
|
348
543
|
*/
|
|
349
544
|
call(fn, args) {
|
|
545
|
+
if (this.fatal !== void 0) throw this.fatal;
|
|
350
546
|
if (typeof fn !== "function") throw new InterpreterError("Attempted to call a non-function");
|
|
351
547
|
if (this.interpretedFunctions.has(fn)) return fn(...args);
|
|
352
|
-
return this.callFunction(fn, void 0, args);
|
|
548
|
+
return this.callFunction(fn, void 0, args, this.callerDepth);
|
|
353
549
|
}
|
|
354
550
|
/** Number of AST nodes evaluated so far (for execution stats). */
|
|
355
551
|
get stepCount() {
|
|
356
552
|
return this.steps;
|
|
357
553
|
}
|
|
358
554
|
async run(program) {
|
|
359
|
-
const root = new Scope();
|
|
555
|
+
const root = new Scope(void 0, 0, (bytes) => this.charge(bytes));
|
|
360
556
|
for (const stmt of program.body) {
|
|
361
557
|
if (stmt.type === "FunctionDeclaration" && stmt.id) {
|
|
362
558
|
root.declare(stmt.id.name, this.makeFunction(stmt, root), false);
|
|
@@ -374,13 +570,23 @@ var Interpreter = class {
|
|
|
374
570
|
return last;
|
|
375
571
|
}
|
|
376
572
|
/**
|
|
377
|
-
* End the run from outside: whatever of the script is still going (a
|
|
378
|
-
*
|
|
379
|
-
* 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.
|
|
380
577
|
*/
|
|
381
578
|
stop() {
|
|
382
579
|
if (this.fatal === void 0) this.fatal = new InterpreterError("Execution ended");
|
|
383
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
|
+
}
|
|
384
590
|
/** End the run with an error no `catch` of the script can stop. */
|
|
385
591
|
end(error) {
|
|
386
592
|
if (this.fatal === void 0) this.fatal = error;
|
|
@@ -390,6 +596,90 @@ var Interpreter = class {
|
|
|
390
596
|
if (this.fatal !== void 0) throw this.fatal;
|
|
391
597
|
if (this.options.signal?.aborted) this.end(new InterpreterError("Execution aborted"));
|
|
392
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
|
+
}
|
|
393
683
|
}
|
|
394
684
|
/** Charge an allocation to the host's budget. */
|
|
395
685
|
charge(bytes) {
|
|
@@ -421,12 +711,19 @@ var Interpreter = class {
|
|
|
421
711
|
case "FunctionDeclaration":
|
|
422
712
|
if (node.id) scope.declare(node.id.name, this.makeFunction(node, scope), false);
|
|
423
713
|
return void 0;
|
|
424
|
-
case "ExpressionStatement":
|
|
425
|
-
|
|
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
|
+
}
|
|
426
723
|
case "BlockStatement":
|
|
427
724
|
return this.execBlock(node.body, scope.child());
|
|
428
725
|
case "IfStatement":
|
|
429
|
-
if (
|
|
726
|
+
if (await this.evalTest(node.test, scope)) return this.execStatement(node.consequent, scope);
|
|
430
727
|
if (node.alternate) return this.execStatement(node.alternate, scope);
|
|
431
728
|
return void 0;
|
|
432
729
|
case "ForOfStatement":
|
|
@@ -446,7 +743,7 @@ var Interpreter = class {
|
|
|
446
743
|
case "ThrowStatement":
|
|
447
744
|
throw await this.evalExpr(node.argument, scope);
|
|
448
745
|
case "ReturnStatement":
|
|
449
|
-
throw new ReturnSignal(node.argument ? await this.
|
|
746
|
+
throw new ReturnSignal(node.argument ? await this.evalReturned(node.argument, scope) : void 0);
|
|
450
747
|
case "BreakStatement":
|
|
451
748
|
if (node.label) throw new InterpreterError("Labeled break is not supported");
|
|
452
749
|
throw new BreakSignal();
|
|
@@ -517,14 +814,14 @@ var Interpreter = class {
|
|
|
517
814
|
if (node.init.type === "VariableDeclaration") await this.execStatement(node.init, inner);
|
|
518
815
|
else await this.evalExpr(node.init, inner);
|
|
519
816
|
}
|
|
520
|
-
while (node.test ?
|
|
817
|
+
while (node.test ? await this.evalTest(node.test, inner) : true) {
|
|
521
818
|
this.tick();
|
|
522
819
|
if (!await this.runLoopBody(node.body, inner.child())) break;
|
|
523
820
|
if (node.update) await this.evalExpr(node.update, inner);
|
|
524
821
|
}
|
|
525
822
|
}
|
|
526
823
|
async execWhile(node, scope) {
|
|
527
|
-
while (
|
|
824
|
+
while (await this.evalTest(node.test, scope)) {
|
|
528
825
|
this.tick();
|
|
529
826
|
if (!await this.runLoopBody(node.body, scope.child())) break;
|
|
530
827
|
}
|
|
@@ -533,7 +830,7 @@ var Interpreter = class {
|
|
|
533
830
|
do {
|
|
534
831
|
this.tick();
|
|
535
832
|
if (!await this.runLoopBody(node.body, scope.child())) break;
|
|
536
|
-
} while (
|
|
833
|
+
} while (await this.evalTest(node.test, scope));
|
|
537
834
|
}
|
|
538
835
|
async execSwitch(node, scope) {
|
|
539
836
|
const value = await this.evalExpr(node.discriminant, scope);
|
|
@@ -591,6 +888,10 @@ var Interpreter = class {
|
|
|
591
888
|
if (node.regex) {
|
|
592
889
|
throw new InterpreterError("Regular expressions are not supported");
|
|
593
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
|
+
}
|
|
594
895
|
return node.value;
|
|
595
896
|
case "Identifier":
|
|
596
897
|
return scope.has(node.name) ? scope.get(node.name) : this.readGlobal(node.name);
|
|
@@ -620,6 +921,7 @@ var Interpreter = class {
|
|
|
620
921
|
for (const [k, v] of Object.entries(spread)) {
|
|
621
922
|
this.tick();
|
|
622
923
|
if (!BLOCKED_KEYS.has(k)) {
|
|
924
|
+
assertStorable(obj, k, v);
|
|
623
925
|
obj[k] = v;
|
|
624
926
|
count++;
|
|
625
927
|
}
|
|
@@ -630,7 +932,9 @@ var Interpreter = class {
|
|
|
630
932
|
if (prop.kind !== "init") throw new InterpreterError("Getters and setters are not supported");
|
|
631
933
|
const key = await this.propKey(prop, scope);
|
|
632
934
|
if (BLOCKED_KEYS.has(key)) throw new InterpreterError(`Forbidden property key: ${key}`);
|
|
633
|
-
|
|
935
|
+
const member = await this.evalExpr(prop.value, scope);
|
|
936
|
+
assertStorable(obj, key, member);
|
|
937
|
+
obj[key] = member;
|
|
634
938
|
count++;
|
|
635
939
|
}
|
|
636
940
|
this.charge(count * 16);
|
|
@@ -641,7 +945,8 @@ var Interpreter = class {
|
|
|
641
945
|
case "UpdateExpression": {
|
|
642
946
|
const ref = await this.resolveReference(node.argument, scope);
|
|
643
947
|
const current = ref.get();
|
|
644
|
-
|
|
948
|
+
this.arrayOperands(current);
|
|
949
|
+
this.work(operandSize(current));
|
|
645
950
|
const before = Number(current);
|
|
646
951
|
const after = node.operator === "++" ? before + 1 : before - 1;
|
|
647
952
|
ref.set(after);
|
|
@@ -656,7 +961,7 @@ var Interpreter = class {
|
|
|
656
961
|
return left ?? await this.evalExpr(node.right, scope);
|
|
657
962
|
}
|
|
658
963
|
case "ConditionalExpression":
|
|
659
|
-
return
|
|
964
|
+
return await this.evalTest(node.test, scope) ? this.evalExpr(node.consequent, scope) : this.evalExpr(node.alternate, scope);
|
|
660
965
|
case "SequenceExpression": {
|
|
661
966
|
let last;
|
|
662
967
|
for (const expression of node.expressions) last = await this.evalExpr(expression, scope);
|
|
@@ -671,7 +976,7 @@ var Interpreter = class {
|
|
|
671
976
|
}
|
|
672
977
|
case "MemberExpression": {
|
|
673
978
|
const { object, key } = await this.evalMemberTarget(node, scope);
|
|
674
|
-
return object
|
|
979
|
+
return readProperty(object, key);
|
|
675
980
|
}
|
|
676
981
|
case "CallExpression":
|
|
677
982
|
return this.evalCall(node, scope);
|
|
@@ -688,17 +993,107 @@ var Interpreter = class {
|
|
|
688
993
|
throw new InterpreterError(`Unsupported expression: ${node.type}`);
|
|
689
994
|
}
|
|
690
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
|
+
}
|
|
691
1084
|
async evalTemplate(node, scope) {
|
|
692
1085
|
let out = "";
|
|
693
1086
|
for (let i = 0; i < node.quasis.length; i++) {
|
|
694
1087
|
out += node.quasis[i].value.cooked ?? "";
|
|
695
1088
|
if (i < node.expressions.length) {
|
|
696
1089
|
const value = await this.evalExpr(node.expressions[i], scope);
|
|
697
|
-
|
|
1090
|
+
this.arrayOperands(value);
|
|
1091
|
+
this.bigIntAsText(value);
|
|
698
1092
|
out += String(value);
|
|
699
1093
|
if (out.length > MAX_JOIN_LENGTH) throw new InterpreterError(TEXT_TOO_LONG);
|
|
700
1094
|
}
|
|
701
1095
|
}
|
|
1096
|
+
this.work(out.length * WRITE_WORK);
|
|
702
1097
|
this.charge(out.length * 2);
|
|
703
1098
|
return out;
|
|
704
1099
|
}
|
|
@@ -710,39 +1105,70 @@ var Interpreter = class {
|
|
|
710
1105
|
if (node.argument.type !== "MemberExpression") throw new InterpreterError("Only a property can be deleted");
|
|
711
1106
|
const { object, key } = await this.evalMemberTarget(node.argument, scope);
|
|
712
1107
|
this.assertChangeable(object);
|
|
1108
|
+
assertKeyAllowed(key);
|
|
713
1109
|
return delete object[key];
|
|
714
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
|
+
}
|
|
715
1118
|
const v = await this.evalExpr(node.argument, scope);
|
|
716
1119
|
switch (node.operator) {
|
|
717
1120
|
case "!":
|
|
718
1121
|
return !truthy(v);
|
|
719
|
-
case "-":
|
|
720
|
-
|
|
721
|
-
|
|
1122
|
+
case "-": {
|
|
1123
|
+
this.numericOperand(v);
|
|
1124
|
+
const negated = -v;
|
|
1125
|
+
if (typeof negated === "bigint") this.countBigInt(negated);
|
|
1126
|
+
return negated;
|
|
1127
|
+
}
|
|
722
1128
|
case "+":
|
|
723
|
-
|
|
1129
|
+
this.numericOperand(v);
|
|
724
1130
|
return +v;
|
|
725
1131
|
case "typeof":
|
|
726
1132
|
return typeof v;
|
|
727
|
-
case "~":
|
|
728
|
-
|
|
729
|
-
|
|
1133
|
+
case "~": {
|
|
1134
|
+
this.numericOperand(v);
|
|
1135
|
+
const inverted = ~v;
|
|
1136
|
+
if (typeof inverted === "bigint") this.countBigInt(inverted);
|
|
1137
|
+
return inverted;
|
|
1138
|
+
}
|
|
730
1139
|
case "void":
|
|
731
1140
|
return void 0;
|
|
732
1141
|
default:
|
|
733
1142
|
throw new InterpreterError(`Unsupported unary operator: ${node.operator}`);
|
|
734
1143
|
}
|
|
735
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
|
+
}
|
|
736
1150
|
async evalBinary(node, scope) {
|
|
737
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
|
+
}
|
|
738
1165
|
const l = await this.evalExpr(node.left, scope);
|
|
739
1166
|
const r = await this.evalExpr(node.right, scope);
|
|
740
1167
|
if (node.operator === "in") {
|
|
741
1168
|
if (r === null || typeof r !== "object" && typeof r !== "function") {
|
|
742
1169
|
throw new InterpreterError("Cannot use 'in' on a value that is not an object");
|
|
743
1170
|
}
|
|
744
|
-
|
|
745
|
-
const key = String(l);
|
|
1171
|
+
const key = this.keyText(l);
|
|
746
1172
|
if (BLOCKED_KEYS.has(key)) throw new InterpreterError(`Forbidden property access: ${key}`);
|
|
747
1173
|
return key in r;
|
|
748
1174
|
}
|
|
@@ -753,15 +1179,56 @@ var Interpreter = class {
|
|
|
753
1179
|
}
|
|
754
1180
|
return this.binary(node.operator, l, r);
|
|
755
1181
|
}
|
|
756
|
-
/**
|
|
757
|
-
|
|
758
|
-
|
|
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
|
+
}
|
|
759
1226
|
const l = left;
|
|
760
1227
|
const r = right;
|
|
761
1228
|
switch (operator) {
|
|
762
1229
|
case "+": {
|
|
763
1230
|
const sum = l + r;
|
|
764
|
-
if (typeof sum === "string") this.charge(
|
|
1231
|
+
if (typeof sum === "string" && !partOfSum) this.charge(sum.length * 2);
|
|
765
1232
|
return sum;
|
|
766
1233
|
}
|
|
767
1234
|
case "-":
|
|
@@ -812,6 +1279,11 @@ var Interpreter = class {
|
|
|
812
1279
|
*/
|
|
813
1280
|
async evalMemberTarget(node, scope) {
|
|
814
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
|
+
}
|
|
815
1287
|
const object = await this.evalExpr(node.object, scope);
|
|
816
1288
|
if (node.optional && (object === null || object === void 0)) throw new ChainShortCircuit();
|
|
817
1289
|
if (node.property.type === "PrivateIdentifier") throw new InterpreterError("Private names are not supported");
|
|
@@ -832,7 +1304,7 @@ var Interpreter = class {
|
|
|
832
1304
|
if (node.type === "MemberExpression") {
|
|
833
1305
|
const { object, key } = await this.evalMemberTarget(node, scope);
|
|
834
1306
|
return {
|
|
835
|
-
get: () => object
|
|
1307
|
+
get: () => readProperty(object, key),
|
|
836
1308
|
set: (value) => this.writeMember(object, key, value)
|
|
837
1309
|
};
|
|
838
1310
|
}
|
|
@@ -851,12 +1323,12 @@ var Interpreter = class {
|
|
|
851
1323
|
}
|
|
852
1324
|
writeMember(object, key, value) {
|
|
853
1325
|
this.assertChangeable(object);
|
|
1326
|
+
assertKeyAllowed(key);
|
|
1327
|
+
assertStorable(object, key, value);
|
|
854
1328
|
if (Array.isArray(object)) {
|
|
855
|
-
const
|
|
856
|
-
if (
|
|
857
|
-
|
|
858
|
-
}
|
|
859
|
-
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;
|
|
860
1332
|
}
|
|
861
1333
|
object[key] = value;
|
|
862
1334
|
}
|
|
@@ -885,7 +1357,10 @@ var Interpreter = class {
|
|
|
885
1357
|
const construct = this.options.constructors?.get(callee);
|
|
886
1358
|
if (!construct) throw new InterpreterError("new works with the built-in types the sandbox provides only");
|
|
887
1359
|
const args = await this.evalArguments(node.arguments, scope);
|
|
888
|
-
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
|
+
}
|
|
889
1364
|
const value = construct(args);
|
|
890
1365
|
this.chargeValue(value);
|
|
891
1366
|
return value;
|
|
@@ -896,7 +1371,7 @@ var Interpreter = class {
|
|
|
896
1371
|
let member;
|
|
897
1372
|
if (node.callee.type === "MemberExpression") {
|
|
898
1373
|
const target = await this.evalMemberTarget(node.callee, scope);
|
|
899
|
-
member = { ...target, value: target.object
|
|
1374
|
+
member = { ...target, value: readProperty(target.object, target.key) };
|
|
900
1375
|
fn = member.value;
|
|
901
1376
|
thisArg = member.object;
|
|
902
1377
|
} else if (node.callee.type === "Super") {
|
|
@@ -910,14 +1385,17 @@ var Interpreter = class {
|
|
|
910
1385
|
}
|
|
911
1386
|
const args = await this.evalArguments(node.arguments, scope);
|
|
912
1387
|
if (typeof fn !== "function") throw new InterpreterError("Attempted to call a non-function");
|
|
913
|
-
return this.callFunction(fn, thisArg, args);
|
|
1388
|
+
return this.callFunction(fn, thisArg, args, scope.depth);
|
|
914
1389
|
}
|
|
915
1390
|
/**
|
|
916
1391
|
* Call a function with a receiver and arguments: an interpreted function, or a built-in or host
|
|
917
1392
|
* function after the checks that apply to it. `call` and `apply` are resolved to the function
|
|
918
1393
|
* they invoke first, so those checks cannot be passed by the way a call is written.
|
|
1394
|
+
*
|
|
1395
|
+
* @param depth - How many calls deep the code that makes this call runs
|
|
919
1396
|
*/
|
|
920
|
-
async callFunction(fn, thisArg, args) {
|
|
1397
|
+
async callFunction(fn, thisArg, args, depth) {
|
|
1398
|
+
if (this.fatal !== void 0) throw this.fatal;
|
|
921
1399
|
for (let hops = 0; fn === FunctionProtoCall || fn === FunctionProtoApply || fn === FunctionProtoBind; hops++) {
|
|
922
1400
|
const name = fn === FunctionProtoCall ? "call" : fn === FunctionProtoApply ? "apply" : "bind";
|
|
923
1401
|
if (typeof thisArg !== "function" || hops >= 8) {
|
|
@@ -933,29 +1411,267 @@ var Interpreter = class {
|
|
|
933
1411
|
fn = target;
|
|
934
1412
|
}
|
|
935
1413
|
if (typeof fn !== "function") throw new InterpreterError("Attempted to call a non-function");
|
|
936
|
-
if (
|
|
937
|
-
|
|
938
|
-
|
|
1414
|
+
if (this.interpretedFunctions.has(fn)) {
|
|
1415
|
+
const interpreted = fn;
|
|
1416
|
+
return await this.withCallerDepth(depth, () => interpreted.apply(thisArg, args));
|
|
939
1417
|
}
|
|
1418
|
+
this.checkClock();
|
|
1419
|
+
const own = this.enterCall(depth);
|
|
940
1420
|
try {
|
|
941
|
-
if (this.interpretedFunctions.has(fn)) {
|
|
942
|
-
return await fn.apply(thisArg, args);
|
|
943
|
-
}
|
|
944
1421
|
args = this.checkBuiltinCall(fn, thisArg, args);
|
|
945
1422
|
const arrayMethod = ARRAY_METHODS.get(fn);
|
|
946
1423
|
if (arrayMethod !== void 0 && HIGHER_ORDER_ARRAY_METHODS.has(arrayMethod) && typeof args[0] === "function") {
|
|
947
|
-
return await this.callArrayMethod(thisArg, arrayMethod, args);
|
|
1424
|
+
return await this.callArrayMethod(thisArg, arrayMethod, args, own);
|
|
948
1425
|
}
|
|
949
|
-
|
|
950
|
-
|
|
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)) {
|
|
951
1443
|
if (result.length > MAX_ARRAY_LENGTH) {
|
|
952
1444
|
throw new InterpreterError(`An array cannot be longer than ${MAX_ARRAY_LENGTH} items`);
|
|
953
1445
|
}
|
|
954
1446
|
}
|
|
1447
|
+
this.work(typeof result === "string" ? result.length * WRITE_WORK : operandSize(result));
|
|
955
1448
|
this.chargeValue(result);
|
|
956
1449
|
return result;
|
|
957
1450
|
} finally {
|
|
958
|
-
this.
|
|
1451
|
+
this.pendingCalls--;
|
|
1452
|
+
}
|
|
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
|
+
}
|
|
1648
|
+
/**
|
|
1649
|
+
* Count a call that starts `callerDepth` calls deep, until it returns.
|
|
1650
|
+
*
|
|
1651
|
+
* @returns The depth the call itself runs at
|
|
1652
|
+
*/
|
|
1653
|
+
enterCall(callerDepth) {
|
|
1654
|
+
const depth = callerDepth + 1;
|
|
1655
|
+
if (depth > this.options.maxCallDepth) {
|
|
1656
|
+
throw new InterpreterError(`Max call depth exceeded (${this.options.maxCallDepth})`);
|
|
1657
|
+
}
|
|
1658
|
+
if (this.pendingCalls >= this.maxPendingCalls) {
|
|
1659
|
+
throw new InterpreterError(`Too many calls in progress at once (${this.maxPendingCalls})`);
|
|
1660
|
+
}
|
|
1661
|
+
this.pendingCalls++;
|
|
1662
|
+
return depth;
|
|
1663
|
+
}
|
|
1664
|
+
/**
|
|
1665
|
+
* Make a call with `depth` as the depth a function of the script is called from, if one starts
|
|
1666
|
+
* during it. It covers the synchronous part of the call, which is where a function starts.
|
|
1667
|
+
*/
|
|
1668
|
+
withCallerDepth(depth, call) {
|
|
1669
|
+
const previous = this.callerDepth;
|
|
1670
|
+
this.callerDepth = depth;
|
|
1671
|
+
try {
|
|
1672
|
+
return call();
|
|
1673
|
+
} finally {
|
|
1674
|
+
this.callerDepth = previous;
|
|
959
1675
|
}
|
|
960
1676
|
}
|
|
961
1677
|
/** The argument list of `apply`: an array, or nothing. */
|
|
@@ -971,11 +1687,13 @@ var Interpreter = class {
|
|
|
971
1687
|
*/
|
|
972
1688
|
bindFunction(target, boundThis, boundArgs) {
|
|
973
1689
|
this.charge((boundArgs.length + 2) * 8);
|
|
974
|
-
|
|
975
|
-
const result = this.callFunction(target, boundThis, [...boundArgs, ...rest]);
|
|
1690
|
+
const bound = (...rest) => {
|
|
1691
|
+
const result = this.callFunction(target, boundThis, [...boundArgs, ...rest], this.callerDepth);
|
|
976
1692
|
result.then(void 0, ignoreRejection2);
|
|
977
1693
|
return result;
|
|
978
1694
|
};
|
|
1695
|
+
this.provided.add(bound);
|
|
1696
|
+
return bound;
|
|
979
1697
|
}
|
|
980
1698
|
/**
|
|
981
1699
|
* The checks before a built-in or host function runs. The engine performs such a call in one
|
|
@@ -987,6 +1705,15 @@ var Interpreter = class {
|
|
|
987
1705
|
checkBuiltinCall(fn, thisArg, args) {
|
|
988
1706
|
const arrayMethod = ARRAY_METHODS.get(fn);
|
|
989
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
|
+
}
|
|
990
1717
|
let arrayText = 0;
|
|
991
1718
|
if (!ARRAY_DATA_FUNCTIONS.has(fn)) {
|
|
992
1719
|
const isData = arrayMethod === void 0 ? void 0 : ARRAY_DATA_ARGUMENTS.get(arrayMethod);
|
|
@@ -1002,10 +1729,24 @@ var Interpreter = class {
|
|
|
1002
1729
|
if (Array.isArray(arg) && !isData?.(i)) measureArray(arg);
|
|
1003
1730
|
}
|
|
1004
1731
|
if (arrayMethod === void 0 && stringMethod === void 0 && Array.isArray(thisArg)) measureArray(thisArg);
|
|
1005
|
-
|
|
1732
|
+
const measured = measure;
|
|
1733
|
+
arrayText = measured?.length ?? 0;
|
|
1734
|
+
this.work(arrayText * WRITE_WORK + (measured?.work ?? 0));
|
|
1006
1735
|
}
|
|
1007
1736
|
if (stringMethod !== void 0) args = this.checkStringMethod(stringMethod, thisArg, args, arrayText);
|
|
1008
|
-
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);
|
|
1009
1750
|
const cost = CALL_COSTS.get(fn);
|
|
1010
1751
|
if (cost) this.charge(cost(args));
|
|
1011
1752
|
return args;
|
|
@@ -1015,6 +1756,10 @@ var Interpreter = class {
|
|
|
1015
1756
|
if (name === "match" || name === "matchAll" || name === "search") {
|
|
1016
1757
|
throw new InterpreterError(`String '${name}' is not supported: it runs a regular expression`);
|
|
1017
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
|
+
}
|
|
1018
1763
|
if (name === "replace" || name === "replaceAll") {
|
|
1019
1764
|
const replacement = args[1];
|
|
1020
1765
|
if (typeof replacement === "function") {
|
|
@@ -1038,14 +1783,15 @@ var Interpreter = class {
|
|
|
1038
1783
|
return args;
|
|
1039
1784
|
}
|
|
1040
1785
|
if (name === "repeat" || name === "padStart" || name === "padEnd") {
|
|
1041
|
-
const
|
|
1786
|
+
const count = convertedOnce(args[0], Number);
|
|
1787
|
+
const n = Number(count);
|
|
1042
1788
|
const produced = name === "repeat" ? receiver.length * (n > 0 ? n : 0) : Math.max(receiver.length, n > 0 ? n : 0);
|
|
1043
1789
|
if (produced > MAX_STRING_OP_LENGTH) {
|
|
1044
1790
|
throw new InterpreterError(
|
|
1045
1791
|
`String '${name}' would produce ${produced} chars, exceeding the ${MAX_STRING_OP_LENGTH} limit`
|
|
1046
1792
|
);
|
|
1047
1793
|
}
|
|
1048
|
-
return args;
|
|
1794
|
+
return args.length === 0 ? args : [count, ...args.slice(1)];
|
|
1049
1795
|
}
|
|
1050
1796
|
if (name === "concat") {
|
|
1051
1797
|
let produced = receiver.length + arrayText;
|
|
@@ -1059,6 +1805,20 @@ var Interpreter = class {
|
|
|
1059
1805
|
}
|
|
1060
1806
|
return args;
|
|
1061
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
|
+
}
|
|
1062
1822
|
if (name === "split") {
|
|
1063
1823
|
const asked = args[1] === void 0 ? Number.POSITIVE_INFINITY : Number(args[1]) >>> 0;
|
|
1064
1824
|
return [args[0], Math.min(asked, MAX_ARRAY_LENGTH + 1)];
|
|
@@ -1071,44 +1831,56 @@ var Interpreter = class {
|
|
|
1071
1831
|
throw new InterpreterError(`An array cannot be longer than ${MAX_ARRAY_LENGTH} items`);
|
|
1072
1832
|
};
|
|
1073
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;
|
|
1074
1838
|
// `join` writes every item and a separator between them into one string, in one step; so
|
|
1075
|
-
//
|
|
1839
|
+
// does the conversion to text.
|
|
1076
1840
|
case "join":
|
|
1077
|
-
case "toString":
|
|
1078
|
-
|
|
1079
|
-
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);
|
|
1080
1844
|
const measure = newTextMeasure();
|
|
1081
1845
|
measureArrayText(receiver, separator.length, measure, 0);
|
|
1082
1846
|
if (measure.length > MAX_JOIN_LENGTH) {
|
|
1083
1847
|
throw new InterpreterError(`Array '${name}' would produce more than ${MAX_JOIN_LENGTH} chars`);
|
|
1084
1848
|
}
|
|
1085
|
-
|
|
1849
|
+
this.work(measure.work);
|
|
1850
|
+
return name === "join" && args.length > 0 ? [given, ...args.slice(1)] : args;
|
|
1086
1851
|
}
|
|
1087
1852
|
// Without a comparison function the engine compares the items as text: strings as they
|
|
1088
1853
|
// are, and an array among the items joined, again for every comparison.
|
|
1089
1854
|
case "sort":
|
|
1090
1855
|
case "toSorted": {
|
|
1091
|
-
if (typeof args[0] === "function") return;
|
|
1856
|
+
if (typeof args[0] === "function") return args;
|
|
1092
1857
|
const measure = newTextMeasure();
|
|
1858
|
+
let chars = 0;
|
|
1093
1859
|
for (let i = 0; i < receiver.length && measure.length <= MAX_JOIN_LENGTH; i++) {
|
|
1094
1860
|
const item = receiver[i];
|
|
1095
1861
|
if (Array.isArray(item)) measureArrayText(item, 1, measure, 1);
|
|
1862
|
+
else chars += typeof item === "string" ? item.length : 32;
|
|
1096
1863
|
}
|
|
1097
1864
|
if (measure.length > MAX_JOIN_LENGTH) throw new InterpreterError(TEXT_TOO_LONG);
|
|
1098
|
-
|
|
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;
|
|
1099
1871
|
}
|
|
1100
1872
|
// Growth by the arguments (a spread makes them many): charged before it happens.
|
|
1101
1873
|
case "push":
|
|
1102
1874
|
case "unshift":
|
|
1103
1875
|
if (receiver.length + args.length > MAX_ARRAY_LENGTH) tooLong2();
|
|
1104
1876
|
this.charge(args.length * 8);
|
|
1105
|
-
return;
|
|
1877
|
+
return args;
|
|
1106
1878
|
case "splice":
|
|
1107
1879
|
case "toSpliced": {
|
|
1108
1880
|
const added = Math.max(0, args.length - 2);
|
|
1109
1881
|
if (receiver.length + added > MAX_ARRAY_LENGTH) tooLong2();
|
|
1110
1882
|
if (name === "splice") this.charge(added * 8);
|
|
1111
|
-
return;
|
|
1883
|
+
return args;
|
|
1112
1884
|
}
|
|
1113
1885
|
// A new array of the receiver and every array among the arguments: one array, given many
|
|
1114
1886
|
// times, is small in memory and large once copied.
|
|
@@ -1119,25 +1891,60 @@ var Interpreter = class {
|
|
|
1119
1891
|
length += Array.isArray(arg) ? arg.length : 1;
|
|
1120
1892
|
}
|
|
1121
1893
|
if (length > MAX_ARRAY_LENGTH) tooLong2();
|
|
1122
|
-
return;
|
|
1894
|
+
return args;
|
|
1123
1895
|
}
|
|
1124
1896
|
case "flat": {
|
|
1125
|
-
const
|
|
1897
|
+
const given = convertedOnce(args[0], Number);
|
|
1898
|
+
const depth = given === void 0 ? 1 : Number(given);
|
|
1126
1899
|
if (flatLength(receiver, Number.isNaN(depth) ? 0 : depth, MAX_ARRAY_LENGTH) > MAX_ARRAY_LENGTH) tooLong2();
|
|
1127
|
-
return;
|
|
1900
|
+
return args.length === 0 ? args : [given, ...args.slice(1)];
|
|
1128
1901
|
}
|
|
1129
1902
|
default:
|
|
1130
|
-
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);
|
|
1131
1936
|
}
|
|
1937
|
+
return parts.join(",");
|
|
1132
1938
|
}
|
|
1133
1939
|
/**
|
|
1134
1940
|
* Async implementations of the higher-order array methods, so interpreter
|
|
1135
1941
|
* callbacks (which are async — they may `await` tool calls) are awaited. Each
|
|
1136
1942
|
* iteration ticks the step budget.
|
|
1137
1943
|
*/
|
|
1138
|
-
async callArrayMethod(arr, method, args) {
|
|
1944
|
+
async callArrayMethod(arr, method, args, depth) {
|
|
1139
1945
|
const callback = args[0];
|
|
1140
|
-
const
|
|
1946
|
+
const interpreted = this.interpretedFunctions.has(callback) ? callback : void 0;
|
|
1947
|
+
const invoke = interpreted ? (...callbackArgs) => this.withCallerDepth(depth, () => interpreted(...callbackArgs)) : (...callbackArgs) => this.callFunction(callback, void 0, callbackArgs, depth);
|
|
1141
1948
|
const cb = invoke;
|
|
1142
1949
|
const each = (i) => {
|
|
1143
1950
|
this.tick();
|
|
@@ -1200,10 +2007,30 @@ var Interpreter = class {
|
|
|
1200
2007
|
acc = arr[order[0]];
|
|
1201
2008
|
start = 1;
|
|
1202
2009
|
}
|
|
2010
|
+
let owed = 0;
|
|
1203
2011
|
for (let n = start; n < order.length; n++) {
|
|
1204
2012
|
this.tick();
|
|
1205
|
-
|
|
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
|
+
}
|
|
1206
2032
|
}
|
|
2033
|
+
if (owed > 0) this.charge(owed);
|
|
1207
2034
|
return acc;
|
|
1208
2035
|
}
|
|
1209
2036
|
case "sort":
|
|
@@ -1301,7 +2128,9 @@ var Interpreter = class {
|
|
|
1301
2128
|
const rest = {};
|
|
1302
2129
|
for (const key2 of Object.keys(source)) {
|
|
1303
2130
|
this.tick();
|
|
1304
|
-
if (
|
|
2131
|
+
if (taken.has(key2) || BLOCKED_KEYS.has(key2)) continue;
|
|
2132
|
+
assertStorable(rest, key2, source[key2]);
|
|
2133
|
+
rest[key2] = source[key2];
|
|
1305
2134
|
}
|
|
1306
2135
|
await this.applyPattern(prop.argument, rest, scope, mode);
|
|
1307
2136
|
continue;
|
|
@@ -1313,7 +2142,7 @@ var Interpreter = class {
|
|
|
1313
2142
|
else throw new InterpreterError("Unsupported destructuring key");
|
|
1314
2143
|
if (BLOCKED_KEYS.has(key)) throw new InterpreterError(`Forbidden destructured key: ${key}`);
|
|
1315
2144
|
taken.add(key);
|
|
1316
|
-
await this.applyPattern(prop.value, source
|
|
2145
|
+
await this.applyPattern(prop.value, readProperty(source, key), scope, mode);
|
|
1317
2146
|
}
|
|
1318
2147
|
return;
|
|
1319
2148
|
}
|
|
@@ -1326,29 +2155,45 @@ var Interpreter = class {
|
|
|
1326
2155
|
if (node.generator) throw new InterpreterError("Generator functions are not supported");
|
|
1327
2156
|
const selfName = node.type === "FunctionExpression" && node.id ? node.id.name : void 0;
|
|
1328
2157
|
const outer = selfName === void 0 ? closure : closure.child();
|
|
1329
|
-
const call = async (args) => {
|
|
1330
|
-
const fnScope = outer.
|
|
1331
|
-
for (let i = 0; i < node.params.length; i++) {
|
|
1332
|
-
const param = node.params[i];
|
|
1333
|
-
if (param.type === "RestElement") {
|
|
1334
|
-
await this.applyPattern(param.argument, args.slice(i), fnScope, "let");
|
|
1335
|
-
break;
|
|
1336
|
-
}
|
|
1337
|
-
await this.applyPattern(param, args[i], fnScope, "let");
|
|
1338
|
-
}
|
|
2158
|
+
const call = async (args, callerDepth, accumulatorOwed) => {
|
|
2159
|
+
const fnScope = outer.activation(this.enterCall(callerDepth));
|
|
1339
2160
|
try {
|
|
2161
|
+
for (let i = 0; i < node.params.length; i++) {
|
|
2162
|
+
const param = node.params[i];
|
|
2163
|
+
if (param.type === "RestElement") {
|
|
2164
|
+
await this.applyPattern(param.argument, args.slice(i), fnScope, "let");
|
|
2165
|
+
break;
|
|
2166
|
+
}
|
|
2167
|
+
await this.applyPattern(param, args[i], fnScope, "let");
|
|
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
|
+
}
|
|
1340
2177
|
if (node.body.type === "BlockStatement") {
|
|
1341
2178
|
await this.execBlock(node.body.body, fnScope);
|
|
1342
2179
|
return void 0;
|
|
1343
2180
|
}
|
|
1344
|
-
return await this.
|
|
2181
|
+
return await this.evalReturned(node.body, fnScope);
|
|
1345
2182
|
} catch (e) {
|
|
1346
2183
|
if (e instanceof ReturnSignal) return e.value;
|
|
1347
2184
|
throw e;
|
|
2185
|
+
} finally {
|
|
2186
|
+
this.pendingCalls--;
|
|
1348
2187
|
}
|
|
1349
2188
|
};
|
|
2189
|
+
const depthOfCaller = () => this.callerDepth;
|
|
2190
|
+
const takeAccumulatorOwed = () => {
|
|
2191
|
+
const owed = this.accumulatorOwed;
|
|
2192
|
+
this.accumulatorOwed = void 0;
|
|
2193
|
+
return owed;
|
|
2194
|
+
};
|
|
1350
2195
|
const interpreted = function interpreted2(...args) {
|
|
1351
|
-
const result = call(args);
|
|
2196
|
+
const result = call(args, depthOfCaller(), takeAccumulatorOwed());
|
|
1352
2197
|
result.then(void 0, ignoreRejection2);
|
|
1353
2198
|
return result;
|
|
1354
2199
|
};
|
|
@@ -1358,7 +2203,9 @@ var Interpreter = class {
|
|
|
1358
2203
|
}
|
|
1359
2204
|
/** A computed property key as text. An array as a key is its items, joined. */
|
|
1360
2205
|
keyText(value) {
|
|
1361
|
-
|
|
2206
|
+
this.arrayOperands(value);
|
|
2207
|
+
this.bigIntAsText(value);
|
|
2208
|
+
this.work(operandSize(value));
|
|
1362
2209
|
return String(value);
|
|
1363
2210
|
}
|
|
1364
2211
|
async propKey(prop, scope) {
|
|
@@ -1368,7 +2215,7 @@ var Interpreter = class {
|
|
|
1368
2215
|
throw new InterpreterError("Unsupported property key");
|
|
1369
2216
|
}
|
|
1370
2217
|
readGlobal(name) {
|
|
1371
|
-
if (Object.prototype.hasOwnProperty.call(this.globals, name)) return this.globals[name];
|
|
2218
|
+
if (name !== "__proto__" && Object.prototype.hasOwnProperty.call(this.globals, name)) return this.globals[name];
|
|
1372
2219
|
throw new InterpreterError(`'${name}' is not defined`);
|
|
1373
2220
|
}
|
|
1374
2221
|
};
|
|
@@ -1379,11 +2226,47 @@ function isIterable(v) {
|
|
|
1379
2226
|
return v != null && typeof v[Symbol.iterator] === "function";
|
|
1380
2227
|
}
|
|
1381
2228
|
function isScriptData(value) {
|
|
2229
|
+
if (value === Object.prototype || value === Array.prototype) return false;
|
|
1382
2230
|
if (Array.isArray(value)) return true;
|
|
1383
2231
|
if (value === null || typeof value !== "object") return false;
|
|
1384
2232
|
const prototype = Object.getPrototypeOf(value);
|
|
1385
2233
|
return prototype === Object.prototype || prototype === null;
|
|
1386
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
|
+
}
|
|
1387
2270
|
function arrayLengthAfterWrite(array, key, value) {
|
|
1388
2271
|
if (key === "length") {
|
|
1389
2272
|
const length = Number(value);
|
|
@@ -1445,8 +2328,6 @@ function isPlainObject(value) {
|
|
|
1445
2328
|
function sanitizeValue(value, options = {}, depth = 0, context = { propCount: { count: 0 }, visited: /* @__PURE__ */ new WeakSet() }) {
|
|
1446
2329
|
const maxDepth = options.maxDepth ?? 20;
|
|
1447
2330
|
const maxProperties = options.maxProperties ?? 1e4;
|
|
1448
|
-
const allowDates = options.allowDates ?? true;
|
|
1449
|
-
const allowErrors = options.allowErrors ?? true;
|
|
1450
2331
|
if (depth > maxDepth) {
|
|
1451
2332
|
throw new Error(
|
|
1452
2333
|
`Tool handler return value exceeds maximum depth (${maxDepth}). This limit prevents deeply nested objects that could cause stack overflow.`
|
|
@@ -1482,7 +2363,19 @@ function sanitizeValue(value, options = {}, depth = 0, context = { propCount: {
|
|
|
1482
2363
|
return "[Circular]";
|
|
1483
2364
|
}
|
|
1484
2365
|
context.visited.add(value);
|
|
2366
|
+
try {
|
|
2367
|
+
return sanitizeObjectValue(value, options, depth, context);
|
|
2368
|
+
} finally {
|
|
2369
|
+
context.visited.delete(value);
|
|
2370
|
+
}
|
|
1485
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;
|
|
1486
2379
|
if (ArrayIsArray(value)) {
|
|
1487
2380
|
const rawLen = ReflectGet(value, "length");
|
|
1488
2381
|
const len = typeof rawLen === "number" && NumberIsFinite(rawLen) && rawLen >= 0 ? MathFloor(rawLen) : 0;
|
|
@@ -1635,12 +2528,12 @@ function estimateSerializedSize(value, maxBytes = 0, depth = 0, maxDepth = 2e3,
|
|
|
1635
2528
|
}
|
|
1636
2529
|
currentPath.add(value);
|
|
1637
2530
|
try {
|
|
1638
|
-
const rawLength =
|
|
2531
|
+
const rawLength = readProperty2(value, "length");
|
|
1639
2532
|
const length = typeof rawLength === "number" && NumberIsFinite(rawLength) && rawLength >= 0 ? MathFloor(rawLength) : 0;
|
|
1640
2533
|
let size = 2;
|
|
1641
2534
|
for (let i = 0; i < length; i++) {
|
|
1642
2535
|
if (i > 0) size += 1;
|
|
1643
|
-
let elementSize = estimateSerializedSize(
|
|
2536
|
+
let elementSize = estimateSerializedSize(readProperty2(value, i), maxBytes, depth + 1, maxDepth, currentPath);
|
|
1644
2537
|
if (elementSize === 0) elementSize = 4;
|
|
1645
2538
|
size += elementSize;
|
|
1646
2539
|
if (maxBytes > 0 && size > maxBytes) {
|
|
@@ -1733,7 +2626,7 @@ function estimateSerializedSize(value, maxBytes = 0, depth = 0, maxDepth = 2e3,
|
|
|
1733
2626
|
}
|
|
1734
2627
|
return 0;
|
|
1735
2628
|
}
|
|
1736
|
-
function
|
|
2629
|
+
function readProperty2(target, key) {
|
|
1737
2630
|
try {
|
|
1738
2631
|
return ReflectGet(target, key);
|
|
1739
2632
|
} catch {
|
|
@@ -1837,7 +2730,8 @@ var SafeJSON = frozenRecord({
|
|
|
1837
2730
|
}
|
|
1838
2731
|
const size = checkSerializedSize(value, MAX_JSON_TEXT_BYTES);
|
|
1839
2732
|
if (!size.ok) throw new RangeError(`JSON.stringify: the text would be too large (${size.error})`);
|
|
1840
|
-
const
|
|
2733
|
+
const indentation = typeof space === "number" || typeof space === "string" ? space : void 0;
|
|
2734
|
+
const indent = indentOf(indentation);
|
|
1841
2735
|
if (indent > 0) {
|
|
1842
2736
|
const budget = MAX_JSON_TEXT_BYTES - size.estimatedBytes;
|
|
1843
2737
|
if (indentationSize(value, indent, budget, 0, /* @__PURE__ */ new Set()) > budget) {
|
|
@@ -1847,10 +2741,14 @@ var SafeJSON = frozenRecord({
|
|
|
1847
2741
|
return JSON.stringify(
|
|
1848
2742
|
value,
|
|
1849
2743
|
Array.isArray(replacer) ? replacer : void 0,
|
|
1850
|
-
|
|
2744
|
+
indentation
|
|
1851
2745
|
);
|
|
1852
2746
|
}
|
|
1853
2747
|
});
|
|
2748
|
+
convertsBeforeCall(
|
|
2749
|
+
SafeJSON["parse"],
|
|
2750
|
+
(args) => args.length === 0 ? args : [String(args[0]), ...args.slice(1)]
|
|
2751
|
+
);
|
|
1854
2752
|
chargedBeforeCall(SafeJSON["parse"], (args) => parsedJsonCost(String(args[0])));
|
|
1855
2753
|
takesArraysAsData(SafeJSON["stringify"]);
|
|
1856
2754
|
var SafeObject = frozenRecord({
|
|
@@ -1865,7 +2763,10 @@ var SafeObject = frozenRecord({
|
|
|
1865
2763
|
if (entry === null || typeof entry !== "object") throw new TypeError("Each entry must be a [key, value] pair");
|
|
1866
2764
|
assertArrayTextWithinLimit(entry[0]);
|
|
1867
2765
|
const key = String(entry[0]);
|
|
1868
|
-
if (
|
|
2766
|
+
if (isBlockedKey(key)) continue;
|
|
2767
|
+
const value = entry[1];
|
|
2768
|
+
assertStorable(result, key, value);
|
|
2769
|
+
result[key] = value;
|
|
1869
2770
|
}
|
|
1870
2771
|
return result;
|
|
1871
2772
|
},
|
|
@@ -1876,7 +2777,10 @@ var SafeObject = frozenRecord({
|
|
|
1876
2777
|
for (const source of sources) {
|
|
1877
2778
|
if (source === null || source === void 0) continue;
|
|
1878
2779
|
for (const key of dataKeys(source)) {
|
|
1879
|
-
|
|
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;
|
|
1880
2784
|
}
|
|
1881
2785
|
}
|
|
1882
2786
|
return target;
|
|
@@ -1951,6 +2855,23 @@ var SafeDate = frozenFunction(() => (/* @__PURE__ */ new Date()).toString(), {
|
|
|
1951
2855
|
parse: (text) => Date.parse(String(text)),
|
|
1952
2856
|
UTC: (...parts) => Date.UTC(...parts)
|
|
1953
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
|
+
}
|
|
1954
2875
|
var ERROR_TYPES = ["Error", "TypeError", "RangeError", "SyntaxError", "ReferenceError", "EvalError", "URIError"];
|
|
1955
2876
|
function errorType(name) {
|
|
1956
2877
|
const make = (args) => createScriptError(name, args.length === 0 || args[0] === void 0 ? "" : toStringValue(args[0]));
|
|
@@ -1981,8 +2902,8 @@ var SAFE_GLOBALS = Object.freeze({
|
|
|
1981
2902
|
parseInt: Object.freeze(
|
|
1982
2903
|
(value, radix) => Number.parseInt(String(value), radix)
|
|
1983
2904
|
),
|
|
1984
|
-
encodeURI: Object.freeze((value) => encodeURI
|
|
1985
|
-
encodeURIComponent: Object.freeze((value) => encodeURIComponent
|
|
2905
|
+
encodeURI: Object.freeze((value) => encodedText(encodeURI, value)),
|
|
2906
|
+
encodeURIComponent: Object.freeze((value) => encodedText(encodeURIComponent, value)),
|
|
1986
2907
|
decodeURI: Object.freeze((value) => decodeURI(String(value))),
|
|
1987
2908
|
decodeURIComponent: Object.freeze((value) => decodeURIComponent(String(value)))
|
|
1988
2909
|
});
|
|
@@ -2096,6 +3017,8 @@ var MemoryTracker = class {
|
|
|
2096
3017
|
trackedBytes = 0;
|
|
2097
3018
|
peakTrackedBytes = 0;
|
|
2098
3019
|
allocationCount = 0;
|
|
3020
|
+
/** Whether this tracker has refused an allocation since it was started */
|
|
3021
|
+
limitExceeded = false;
|
|
2099
3022
|
config;
|
|
2100
3023
|
constructor(config = {}) {
|
|
2101
3024
|
this.config = {
|
|
@@ -2112,6 +3035,14 @@ var MemoryTracker = class {
|
|
|
2112
3035
|
this.trackedBytes = 0;
|
|
2113
3036
|
this.peakTrackedBytes = 0;
|
|
2114
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;
|
|
2115
3046
|
}
|
|
2116
3047
|
/**
|
|
2117
3048
|
* Track an allocation
|
|
@@ -2122,6 +3053,7 @@ var MemoryTracker = class {
|
|
|
2122
3053
|
track(bytes) {
|
|
2123
3054
|
if (typeof bytes !== "number" || Number.isNaN(bytes)) {
|
|
2124
3055
|
if (this.config.memoryLimit > 0) {
|
|
3056
|
+
this.limitExceeded = true;
|
|
2125
3057
|
throw new MemoryLimitError(
|
|
2126
3058
|
"Memory limit exceeded: allocation size is not a number",
|
|
2127
3059
|
this.trackedBytes,
|
|
@@ -2137,6 +3069,7 @@ var MemoryTracker = class {
|
|
|
2137
3069
|
this.peakTrackedBytes = this.trackedBytes;
|
|
2138
3070
|
}
|
|
2139
3071
|
if (this.config.memoryLimit > 0 && this.trackedBytes > this.config.memoryLimit) {
|
|
3072
|
+
this.limitExceeded = true;
|
|
2140
3073
|
throw new MemoryLimitError(
|
|
2141
3074
|
`Memory limit exceeded: ${this.formatBytes(this.trackedBytes)} used > ${this.formatBytes(
|
|
2142
3075
|
this.config.memoryLimit
|
|
@@ -2328,6 +3261,18 @@ function isReferenceId(value) {
|
|
|
2328
3261
|
return typeof value === "string" && REF_ID_PATTERN.test(value);
|
|
2329
3262
|
}
|
|
2330
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
|
+
|
|
2331
3276
|
// libs/core/src/sidecar/reference-resolver.ts
|
|
2332
3277
|
var ReflectGet2 = Reflect.get;
|
|
2333
3278
|
var NumberIsFinite2 = Number.isFinite;
|
|
@@ -2435,17 +3380,88 @@ var ReferenceResolver = class {
|
|
|
2435
3380
|
/**
|
|
2436
3381
|
* Check if resolution would exceed size limits
|
|
2437
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
|
+
*
|
|
2438
3387
|
* @param value - The value to check
|
|
2439
|
-
* @returns true if resolution would exceed maxResolvedSize
|
|
3388
|
+
* @returns true if resolution would exceed maxResolvedSize or the execution's total
|
|
2440
3389
|
*/
|
|
2441
3390
|
wouldExceedLimit(value) {
|
|
2442
3391
|
try {
|
|
2443
3392
|
const size = this.predictExpandedSize(value);
|
|
2444
|
-
|
|
3393
|
+
if (size > this.config.maxResolvedSize) {
|
|
3394
|
+
return true;
|
|
3395
|
+
}
|
|
3396
|
+
return !this.sidecar.canResolve(this.predictAddedSize(value, 0, /* @__PURE__ */ new Set()));
|
|
2445
3397
|
} catch {
|
|
2446
3398
|
return true;
|
|
2447
3399
|
}
|
|
2448
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
|
+
}
|
|
2449
3465
|
/**
|
|
2450
3466
|
* Resolve all reference IDs in a value tree
|
|
2451
3467
|
*
|
|
@@ -2468,7 +3484,10 @@ var ReferenceResolver = class {
|
|
|
2468
3484
|
);
|
|
2469
3485
|
}
|
|
2470
3486
|
if (isReferenceId(value)) {
|
|
2471
|
-
|
|
3487
|
+
let data;
|
|
3488
|
+
this.withinTotal(() => {
|
|
3489
|
+
data = this.sidecar.resolveString(value);
|
|
3490
|
+
});
|
|
2472
3491
|
if (data === void 0) {
|
|
2473
3492
|
throw new Error(`Unknown reference: ${value}`);
|
|
2474
3493
|
}
|
|
@@ -2506,6 +3525,8 @@ var ReferenceResolver = class {
|
|
|
2506
3525
|
* Resolve a composite handle by concatenating its parts
|
|
2507
3526
|
*/
|
|
2508
3527
|
resolveComposite(handle, depth) {
|
|
3528
|
+
const joinedSize = this.predictExpandedSize(handle, depth);
|
|
3529
|
+
this.withinTotal(() => this.sidecar.countResolved(joinedSize));
|
|
2509
3530
|
const out = [];
|
|
2510
3531
|
const source = handle.__parts;
|
|
2511
3532
|
const len = untrustedLength(source);
|
|
@@ -3151,12 +4172,29 @@ var MAX_PARALLEL_ITEMS = 100;
|
|
|
3151
4172
|
var MAX_SERIALIZED_RESULT_BYTES = 50 * 1024 * 1024;
|
|
3152
4173
|
var DEFAULT_MAX_CONSOLE_CALLS = 100;
|
|
3153
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
|
+
}
|
|
3154
4183
|
function sandboxError(message, name = "Error", code) {
|
|
3155
4184
|
const error = new Error(message);
|
|
3156
4185
|
error.name = name;
|
|
3157
4186
|
if (code !== void 0) error.code = code;
|
|
3158
4187
|
return error;
|
|
3159
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
|
+
}
|
|
3160
4198
|
function frozenRecord2(members) {
|
|
3161
4199
|
const record = /* @__PURE__ */ Object.create(null);
|
|
3162
4200
|
for (const key of Object.keys(members)) record[key] = members[key];
|
|
@@ -3223,15 +4261,20 @@ var InterpreterAdapter = class {
|
|
|
3223
4261
|
const allocationLimit = typeof memoryLimit === "number" && memoryLimit > 0 ? Math.min(memoryLimit, adapterLimit) : adapterLimit;
|
|
3224
4262
|
const tracker = new MemoryTracker({ memoryLimit: Number.isFinite(allocationLimit) ? allocationLimit : 0 });
|
|
3225
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;
|
|
3226
4269
|
let interpreter;
|
|
4270
|
+
const callbacks = {
|
|
4271
|
+
call: () => {
|
|
4272
|
+
throw sandboxError("The interpreter is not running");
|
|
4273
|
+
}
|
|
4274
|
+
};
|
|
3227
4275
|
try {
|
|
3228
4276
|
const safe = createSafeGlobals();
|
|
3229
|
-
const
|
|
3230
|
-
call: () => {
|
|
3231
|
-
throw sandboxError("The interpreter is not running");
|
|
3232
|
-
}
|
|
3233
|
-
};
|
|
3234
|
-
const runtime = this.runtimeGlobals(context, charge, callbacks);
|
|
4277
|
+
const runtime = this.runtimeGlobals(context, (bytes) => chargeForHelper(bytes), callbacks);
|
|
3235
4278
|
for (const name of Object.keys(runtime)) {
|
|
3236
4279
|
if (!Object.prototype.hasOwnProperty.call(safe.globals, name)) safe.globals[name] = runtime[name];
|
|
3237
4280
|
}
|
|
@@ -3241,38 +4284,42 @@ var InterpreterAdapter = class {
|
|
|
3241
4284
|
instanceChecks: safe.instanceChecks,
|
|
3242
4285
|
maxSteps: this.options.maxSteps ?? DEFAULT_MAX_STEPS,
|
|
3243
4286
|
maxCallDepth: this.options.maxCallDepth ?? DEFAULT_MAX_CALL_DEPTH,
|
|
4287
|
+
maxPendingCalls: this.options.maxPendingCalls,
|
|
3244
4288
|
signal: context.abortController.signal,
|
|
4289
|
+
deadline: deadlineAt,
|
|
3245
4290
|
charge
|
|
3246
4291
|
});
|
|
3247
|
-
const
|
|
3248
|
-
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);
|
|
3249
4296
|
} catch (error) {
|
|
3250
4297
|
return this.fail(error, startTime, stats.toolCallCount, 0, sanitizeStacks);
|
|
3251
4298
|
}
|
|
3252
|
-
const timeout = context.config.timeout;
|
|
3253
4299
|
const timer = timeout && timeout > 0 ? setTimeout(() => context.abortController.abort(), timeout) : void 0;
|
|
3254
4300
|
let timeoutHandle;
|
|
3255
4301
|
const TIMED_OUT = /* @__PURE__ */ Symbol("timeout");
|
|
3256
4302
|
const deadline = timeout && timeout > 0 ? new Promise((resolve) => {
|
|
3257
4303
|
timeoutHandle = setTimeout(() => resolve(TIMED_OUT), timeout);
|
|
3258
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
|
+
);
|
|
3259
4315
|
try {
|
|
3260
4316
|
const run = interpreter.run(program);
|
|
3261
4317
|
run.catch(() => void 0);
|
|
3262
4318
|
const outcome = deadline ? await Promise.race([run, deadline]) : await run;
|
|
3263
|
-
if (outcome === TIMED_OUT)
|
|
3264
|
-
return this.fail(
|
|
3265
|
-
new Error(`Execution timed out after ${timeout}ms`),
|
|
3266
|
-
startTime,
|
|
3267
|
-
stats.toolCallCount,
|
|
3268
|
-
interpreter.stepCount,
|
|
3269
|
-
sanitizeStacks,
|
|
3270
|
-
"TimeoutError",
|
|
3271
|
-
"EXECUTION_TIMEOUT"
|
|
3272
|
-
);
|
|
3273
|
-
}
|
|
4319
|
+
if (outcome === TIMED_OUT) return timedOut();
|
|
3274
4320
|
return this.succeed(outcome, context, startTime, stats.toolCallCount, interpreter.stepCount);
|
|
3275
4321
|
} catch (error) {
|
|
4322
|
+
if (error instanceof DeadlineError) return timedOut();
|
|
3276
4323
|
const code2 = error instanceof StepLimitError ? "STEP_LIMIT_EXCEEDED" : void 0;
|
|
3277
4324
|
return this.fail(
|
|
3278
4325
|
error,
|
|
@@ -3286,6 +4333,7 @@ var InterpreterAdapter = class {
|
|
|
3286
4333
|
} finally {
|
|
3287
4334
|
if (timer) clearTimeout(timer);
|
|
3288
4335
|
if (timeoutHandle) clearTimeout(timeoutHandle);
|
|
4336
|
+
callbacks.over = true;
|
|
3289
4337
|
interpreter.stop();
|
|
3290
4338
|
}
|
|
3291
4339
|
}
|
|
@@ -3297,7 +4345,7 @@ var InterpreterAdapter = class {
|
|
|
3297
4345
|
*/
|
|
3298
4346
|
runtimeGlobals(context, charge, callbacks) {
|
|
3299
4347
|
const { config } = context;
|
|
3300
|
-
const callTool = this.createCallTool(context);
|
|
4348
|
+
const callTool = observed(this.createCallTool(context, callbacks));
|
|
3301
4349
|
const resolver = context.sidecar && context.referenceConfig ? new ReferenceResolver(context.sidecar, context.referenceConfig) : void 0;
|
|
3302
4350
|
const joinReferences = (parts) => {
|
|
3303
4351
|
if (!resolver) {
|
|
@@ -3315,6 +4363,8 @@ var InterpreterAdapter = class {
|
|
|
3315
4363
|
const result = left + right;
|
|
3316
4364
|
if (typeof result === "string") {
|
|
3317
4365
|
charge((result.length - (typeof left === "string" ? left.length : 0)) * 2);
|
|
4366
|
+
} else if (typeof result === "bigint") {
|
|
4367
|
+
callbacks.countBigInt?.(result);
|
|
3318
4368
|
}
|
|
3319
4369
|
return result;
|
|
3320
4370
|
};
|
|
@@ -3322,12 +4372,20 @@ var InterpreterAdapter = class {
|
|
|
3322
4372
|
if (!Array.isArray(quasis)) throw sandboxError("Template pieces must be an array", "TypeError");
|
|
3323
4373
|
const parts = [];
|
|
3324
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
|
+
};
|
|
3325
4383
|
for (let i = 0; i < quasis.length; i++) {
|
|
3326
|
-
|
|
4384
|
+
add(String(quasis[i]));
|
|
3327
4385
|
if (i < values.length) {
|
|
3328
4386
|
const value = values[i];
|
|
3329
4387
|
if (typeof value === "string" && isReferenceId(value)) hasReference = true;
|
|
3330
|
-
|
|
4388
|
+
add(String(value));
|
|
3331
4389
|
}
|
|
3332
4390
|
}
|
|
3333
4391
|
if (hasReference) return joinReferences(parts.filter((part) => part !== ""));
|
|
@@ -3349,7 +4407,7 @@ var InterpreterAdapter = class {
|
|
|
3349
4407
|
yield item;
|
|
3350
4408
|
}
|
|
3351
4409
|
}
|
|
3352
|
-
const parallel = async (first, second) => {
|
|
4410
|
+
const parallel = observed(async (first, second) => {
|
|
3353
4411
|
let tasks;
|
|
3354
4412
|
if (typeof second === "function") {
|
|
3355
4413
|
if (!Array.isArray(first)) throw sandboxError("parallel requires an array of items", "TypeError");
|
|
@@ -3374,7 +4432,7 @@ var InterpreterAdapter = class {
|
|
|
3374
4432
|
${messages}`);
|
|
3375
4433
|
}
|
|
3376
4434
|
return settled.map((result) => result.value);
|
|
3377
|
-
};
|
|
4435
|
+
});
|
|
3378
4436
|
const globals = {
|
|
3379
4437
|
__safe_callTool: callTool,
|
|
3380
4438
|
__safe_concat: concat,
|
|
@@ -3392,19 +4450,23 @@ ${messages}`);
|
|
|
3392
4450
|
let consoleCalls = 0;
|
|
3393
4451
|
let consoleLength = 0;
|
|
3394
4452
|
const write = (level) => (...args) => {
|
|
4453
|
+
if (callbacks.over) throw executionOver();
|
|
3395
4454
|
consoleCalls++;
|
|
3396
4455
|
if (consoleCalls > maxConsoleCalls) {
|
|
3397
4456
|
throw sandboxError(
|
|
3398
4457
|
`Console call limit exceeded (max: ${maxConsoleCalls}). This limit prevents I/O flood attacks.`
|
|
3399
4458
|
);
|
|
3400
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
|
+
}
|
|
3401
4467
|
const line = args.map(consoleText).join(" ");
|
|
3402
4468
|
consoleLength += line.length;
|
|
3403
|
-
if (consoleLength > maxConsoleOutputBytes)
|
|
3404
|
-
throw sandboxError(
|
|
3405
|
-
`Console output size limit exceeded (max: ${maxConsoleOutputBytes} bytes). This limit prevents I/O flood attacks.`
|
|
3406
|
-
);
|
|
3407
|
-
}
|
|
4469
|
+
if (consoleLength > maxConsoleOutputBytes) throw outputLimit();
|
|
3408
4470
|
sink(level, line);
|
|
3409
4471
|
};
|
|
3410
4472
|
globals["__safe_console"] = frozenRecord2({
|
|
@@ -3417,7 +4479,7 @@ ${messages}`);
|
|
|
3417
4479
|
for (const namespace of context.toolNamespaces ?? []) {
|
|
3418
4480
|
const methods = {};
|
|
3419
4481
|
for (const method of namespace.methods) {
|
|
3420
|
-
if (isBlockedKey(method.name)) continue;
|
|
4482
|
+
if (isBlockedKey(method.name) || isEngineCalledKey(method.name)) continue;
|
|
3421
4483
|
methods[method.name] = (args, options) => callTool(method.toolName, args === void 0 ? {} : args, options);
|
|
3422
4484
|
}
|
|
3423
4485
|
globals[namespace.name] = frozenRecord2(methods);
|
|
@@ -3436,11 +4498,13 @@ ${messages}`);
|
|
|
3436
4498
|
* and the response cross as JSON, so the handler never receives a value of the script and the
|
|
3437
4499
|
* script never receives an object of the handler.
|
|
3438
4500
|
*/
|
|
3439
|
-
createCallTool(context) {
|
|
4501
|
+
createCallTool(context, execution) {
|
|
3440
4502
|
const configured = context.config.toolHandler;
|
|
3441
4503
|
const bridgeContext = context.toolHandler === void 0 && typeof configured === "function" ? Object.create(context, { toolHandler: { value: configured } }) : context;
|
|
3442
4504
|
const bridge = createHostToolBridge(bridgeContext, { updateStats: true });
|
|
4505
|
+
const maxPayloadBytes = context.config.toolBridge?.maxPayloadBytes ?? DEFAULT_MAX_TOOL_PAYLOAD_BYTES;
|
|
3443
4506
|
return async (toolName, args, options) => {
|
|
4507
|
+
if (execution.over) throw executionOver();
|
|
3444
4508
|
let throwOnError = true;
|
|
3445
4509
|
if (options !== void 0 && options !== null) {
|
|
3446
4510
|
if (typeof options !== "object") throw sandboxError("callTool options must be an object", "TypeError");
|
|
@@ -3452,6 +4516,13 @@ ${messages}`);
|
|
|
3452
4516
|
if (typeof args !== "object" || args === null || Array.isArray(args)) {
|
|
3453
4517
|
throw sandboxError("Tool arguments must be an object", "TypeError");
|
|
3454
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
|
+
}
|
|
3455
4526
|
let requestJson;
|
|
3456
4527
|
try {
|
|
3457
4528
|
requestJson = encodeToolBridgeRequest(toolName, args);
|