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