@poe-platform/safe-js 0.1.138 → 0.1.140

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.
@@ -3408,7 +3408,7 @@ var Parser = class {
3408
3408
  });
3409
3409
  });
3410
3410
  }
3411
- parseFunctionParts(generator, lexicalContext) {
3411
+ parseFunctionParts(generator, lexicalContext, accessor) {
3412
3412
  return this.withLexicalContext(lexicalContext, () => {
3413
3413
  const params = this.withScope(() => {
3414
3414
  const parsed = this.parseArrowParameters();
@@ -3416,7 +3416,24 @@ var Parser = class {
3416
3416
  for (const identifier of boundIdentifiers(param)) this.declareBinding(identifier);
3417
3417
  return parsed;
3418
3418
  });
3419
+ if (accessor === "get" && params.length !== 0)
3420
+ throw new Error("A getter cannot have parameters.");
3421
+ if (accessor === "set" && (params.length !== 1 || params[0]?.type === "RestElement"))
3422
+ throw new Error("A setter must have exactly one non-rest parameter.");
3423
+ const bodyTokenIndex = this.index;
3419
3424
  const body = this.withFunctionContext(generator ? "generator" : "normal", () => this.parseBlockStatement(params));
3425
+ if (accessor === "set" && params[0]?.type !== "Identifier") {
3426
+ let directiveTokenIndex = bodyTokenIndex + 1;
3427
+ for (const statement of body.body) {
3428
+ const token = this.tokens[directiveTokenIndex];
3429
+ if (statement.type !== "ExpressionStatement" || statement.expression.type !== "StringLiteral" || token?.type !== "string" || statement.span.start.offset !== token.start.offset || statement.span.end.offset !== token.end.offset) break;
3430
+ if (statement.expression.raw === '"use strict"' || statement.expression.raw === "'use strict'")
3431
+ throw new Error(
3432
+ "A setter with a non-simple parameter cannot contain a use strict directive."
3433
+ );
3434
+ directiveTokenIndex += this.tokens[directiveTokenIndex + 1]?.value === ";" ? 2 : 1;
3435
+ }
3436
+ }
3420
3437
  return { params, body };
3421
3438
  });
3422
3439
  }
@@ -3447,8 +3464,14 @@ var Parser = class {
3447
3464
  }
3448
3465
  const generator = this.consumePunctuator("*") !== void 0;
3449
3466
  if (async && generator) throw new DisallowedSyntaxError("async generator", methodStart.start);
3450
- if ((this.currentToken().value === "get" || this.currentToken().value === "set") && this.isObjectMethodStart())
3451
- throw new DisallowedSyntaxError("class accessor", this.currentToken().start);
3467
+ let accessor;
3468
+ const modifier = this.currentToken();
3469
+ if ((modifier.value === "get" || modifier.value === "set") && this.isObjectMethodStart()) {
3470
+ if (async || generator || modifier.end.offset - modifier.start.offset !== modifier.value.length)
3471
+ throw unexpectedTokenError(modifier);
3472
+ accessor = modifier.value;
3473
+ this.index++;
3474
+ }
3452
3475
  const computed = this.consumePunctuator("[") !== void 0;
3453
3476
  const key = computed ? this.parseExpression({ allowSequence: true }).node : this.currentToken().type === "string" ? createStringLiteral(this.tokens[this.index++]) : this.currentToken().type === "numeric" ? createNumericLiteral(this.tokens[this.index++]) : this.parseIdentifierName();
3454
3477
  if (computed) this.expectPunctuator("]");
@@ -3456,7 +3479,7 @@ var Parser = class {
3456
3479
  if (isStatic && name === "prototype") throw new Error("A static class element cannot be named prototype.");
3457
3480
  if (this.currentToken().value === "(") {
3458
3481
  const constructor = !isStatic && name === "constructor";
3459
- if (constructor && (async || generator)) throw new Error("A class constructor cannot be async or a generator.");
3482
+ if (constructor && (async || generator || accessor !== void 0)) throw new Error("A class constructor must be an ordinary method.");
3460
3483
  const { params, body } = this.parseFunctionParts(generator, {
3461
3484
  newTarget: true,
3462
3485
  superProperty: true,
@@ -3465,7 +3488,7 @@ var Parser = class {
3465
3488
  return: true,
3466
3489
  await: async,
3467
3490
  strictAwait: true
3468
- });
3491
+ }, accessor);
3469
3492
  const value2 = this.withFunctionSource({
3470
3493
  type: "FunctionExpression",
3471
3494
  async,
@@ -3480,7 +3503,7 @@ var Parser = class {
3480
3503
  key,
3481
3504
  computed,
3482
3505
  static: isStatic,
3483
- kind: constructor ? "constructor" : "method",
3506
+ kind: accessor ?? (constructor ? "constructor" : "method"),
3484
3507
  value: value2,
3485
3508
  span: createSpan2(start.start, value2.span.end)
3486
3509
  };
@@ -6527,6 +6550,64 @@ function serializedDateTime(value) {
6527
6550
  return Number.isNaN(time) ? null : time;
6528
6551
  }
6529
6552
 
6553
+ // packages/safe-js/src/interp/accessors.ts
6554
+ var accessorClosures = /* @__PURE__ */ new WeakMap();
6555
+ var getterAdapters = /* @__PURE__ */ new WeakMap();
6556
+ var setterAdapters = /* @__PURE__ */ new WeakMap();
6557
+ function accessorAdapter(closure, kind) {
6558
+ if (kind === "get") {
6559
+ let adapter2 = getterAdapters.get(closure);
6560
+ if (adapter2 === void 0) {
6561
+ adapter2 = () => void 0;
6562
+ getterAdapters.set(closure, adapter2);
6563
+ accessorClosures.set(adapter2, closure);
6564
+ }
6565
+ return adapter2;
6566
+ }
6567
+ let adapter = setterAdapters.get(closure);
6568
+ if (adapter === void 0) {
6569
+ adapter = () => {
6570
+ throw new TypeError("Accessor writes require sandbox execution.");
6571
+ };
6572
+ setterAdapters.set(closure, adapter);
6573
+ accessorClosures.set(adapter, closure);
6574
+ }
6575
+ return adapter;
6576
+ }
6577
+ function accessorClosure(adapter) {
6578
+ if (adapter === void 0) return void 0;
6579
+ const closure = accessorClosures.get(adapter);
6580
+ if (closure === void 0) throw new TypeError("Native accessors cannot execute in the sandbox.");
6581
+ return closure;
6582
+ }
6583
+ function retainedAccessorClosures(descriptor) {
6584
+ const closures = [];
6585
+ for (const adapter of [descriptor.get, descriptor.set]) {
6586
+ const closure = adapter === void 0 ? void 0 : accessorClosures.get(adapter);
6587
+ if (closure !== void 0) closures.push(closure);
6588
+ }
6589
+ return closures;
6590
+ }
6591
+ function readPropertyDescriptor(descriptor, receiver, context, allowNativeGetter = false) {
6592
+ if ("value" in descriptor) return descriptor.value;
6593
+ if (descriptor.get === void 0) return void 0;
6594
+ const getter = accessorClosures.get(descriptor.get);
6595
+ if (getter === void 0) {
6596
+ if (!allowNativeGetter) throw new TypeError("Native accessors cannot execute in the sandbox.");
6597
+ return Reflect.apply(descriptor.get, receiver, []);
6598
+ }
6599
+ if (context?.invokeClosure === void 0)
6600
+ throw new TypeError("Accessor reads require sandbox execution.");
6601
+ return context.invokeClosure(getter, [], receiver);
6602
+ }
6603
+ function writePropertyDescriptor(descriptor, receiver, value, context) {
6604
+ const setter = accessorClosure(descriptor.set);
6605
+ if (setter === void 0) throw new TypeError("Cannot assign to a getter-only property.");
6606
+ if (context?.invokeClosure === void 0)
6607
+ throw new TypeError("Accessor writes require sandbox execution.");
6608
+ return context.invokeClosure(setter, [value], receiver).then(() => void 0);
6609
+ }
6610
+
6530
6611
  // packages/safe-js/src/interp/collection-brands.ts
6531
6612
  var sandboxMapBrand = /* @__PURE__ */ Symbol("SandboxMap");
6532
6613
  var sandboxSetBrand = /* @__PURE__ */ Symbol("SandboxSet");
@@ -7317,15 +7398,23 @@ function registerIntrinsicPrototype(budget, prototype, constructor) {
7317
7398
  ...record2,
7318
7399
  descriptors: new Map(Object.entries(Object.getOwnPropertyDescriptors(record2.value)))
7319
7400
  }));
7320
- const unchanged = (before, after) => before !== void 0 && after !== void 0 && Object.is(before.value, after.value) && before.writable === after.writable && before.configurable === after.configurable && before.enumerable === after.enumerable;
7321
- intrinsicConstructors.set(constructor, () => records.every(({ target, value, descriptors, prototype: parent, explicit }) => {
7322
- const current = Object.getOwnPropertyDescriptors(value);
7323
- return getSandboxPrototype(target) === parent && hasExplicitSandboxPrototype(target) === explicit && Object.keys(current).length === descriptors.size && Object.keys(current).every((key) => unchanged(descriptors.get(key), current[key]));
7324
- }));
7325
- budget.setRetainedValues(prototype, () => records.flatMap(({ target, value, descriptors, prototype: parent }) => [
7326
- ...getSandboxPrototype(target) === parent ? [] : [getSandboxPrototype(target)],
7327
- ...Object.entries(Object.getOwnPropertyDescriptors(value)).flatMap(([key, descriptor]) => unchanged(descriptors.get(key), descriptor) ? [] : [key, descriptor.value])
7328
- ]));
7401
+ const unchanged = (before, after) => before !== void 0 && after !== void 0 && Object.is(before.value, after.value) && before.get === after.get && before.set === after.set && before.writable === after.writable && before.configurable === after.configurable && before.enumerable === after.enumerable;
7402
+ intrinsicConstructors.set(
7403
+ constructor,
7404
+ () => records.every(({ target, value, descriptors, prototype: parent, explicit }) => {
7405
+ const current = Object.getOwnPropertyDescriptors(value);
7406
+ return getSandboxPrototype(target) === parent && hasExplicitSandboxPrototype(target) === explicit && Object.keys(current).length === descriptors.size && Object.keys(current).every((key) => unchanged(descriptors.get(key), current[key]));
7407
+ })
7408
+ );
7409
+ budget.setRetainedValues(
7410
+ prototype,
7411
+ () => records.flatMap(({ target, value, descriptors, prototype: parent }) => [
7412
+ ...getSandboxPrototype(target) === parent ? [] : [getSandboxPrototype(target)],
7413
+ ...Object.entries(Object.getOwnPropertyDescriptors(value)).flatMap(
7414
+ ([key, descriptor]) => unchanged(descriptors.get(key), descriptor) ? [] : [key, descriptor.value, ...retainedAccessorClosures(descriptor)]
7415
+ )
7416
+ ])
7417
+ );
7329
7418
  }
7330
7419
  function releaseObjectPrototype(budget) {
7331
7420
  for (const prototype of intrinsicPrototypeRoots.get(budget) ?? []) budget.setRetainedValues(prototype, void 0);
@@ -7344,6 +7433,24 @@ function getSandboxPrototype(value, budget) {
7344
7433
  function hasExplicitSandboxPrototype(value) {
7345
7434
  return prototypes.has(value);
7346
7435
  }
7436
+ function getSandboxPropertyDescriptor(value, key, budget) {
7437
+ const hostProperties = isSandboxClosure(value) ? value.properties : void 0;
7438
+ if (isSandboxClosure(value) && !isGuestClosure(value))
7439
+ return hostProperties === void 0 ? void 0 : Object.getOwnPropertyDescriptor(hostProperties, key);
7440
+ let current = value;
7441
+ let depth = 0;
7442
+ while (typeof current === "object" && current !== null && (Array.isArray(current) || isPrototypeRecord(current))) {
7443
+ const properties = isGuestClosure(current) ? getGuestFunctionProperties(current) : current;
7444
+ const descriptor = properties === void 0 ? void 0 : Object.getOwnPropertyDescriptor(properties, key);
7445
+ if (descriptor !== void 0) return descriptor;
7446
+ current = getSandboxPrototype(current, budget);
7447
+ if (current !== null) {
7448
+ budget?.visitNode();
7449
+ assertSandboxDataDepth(++depth);
7450
+ }
7451
+ }
7452
+ return void 0;
7453
+ }
7347
7454
  function getSandboxDataProperty(value, key, budget) {
7348
7455
  let current = value;
7349
7456
  let depth = 0;
@@ -8907,7 +9014,7 @@ async function callRegexMethod(target, methodName, args, budget, context) {
8907
9014
  try {
8908
9015
  const input = await sandboxString(args[0], budget, context);
8909
9016
  if (methodName === "test") {
8910
- const exec = context?.getProperty === void 0 ? getSandboxDataProperty(target, "exec", budget) : context.getProperty(target, "exec");
9017
+ const exec = context?.getProperty === void 0 ? getSandboxDataProperty(target, "exec", budget) : await context.getProperty(target, "exec");
8911
9018
  if (isSandboxClosure(exec)) {
8912
9019
  const result = await invokeBuiltinClosure(exec, [input], budget, context, target);
8913
9020
  if (result !== null && typeof result !== "object") {
@@ -9011,6 +9118,7 @@ function functionString(value) {
9011
9118
  // packages/safe-js/src/interp/string-coercion.ts
9012
9119
  var defaultStringHook = /* @__PURE__ */ Symbol("defaultStringHook");
9013
9120
  var defaultValueHook = /* @__PURE__ */ Symbol("defaultValueHook");
9121
+ var joiningArrays = /* @__PURE__ */ new WeakSet();
9014
9122
  function sandboxNumber(value, budget, context) {
9015
9123
  if (value === null || typeof value !== "object") {
9016
9124
  if (typeof value === "function") throw new TypeError("Expected a sandbox value.");
@@ -9025,12 +9133,30 @@ function sandboxString(value, budget, context, joining = /* @__PURE__ */ new Set
9025
9133
  }
9026
9134
  return objectToPrimitive(value, budget, context, joining, "string").then((primitive) => budget.allocateString(String(primitive)));
9027
9135
  }
9136
+ async function joinSandboxArray(value, length, separator, budget, context, joining = /* @__PURE__ */ new Set()) {
9137
+ if (joiningArrays.has(value)) return "";
9138
+ joiningArrays.add(value);
9139
+ let text = "";
9140
+ const release = retainValues(budget, () => [value, text, separator]);
9141
+ try {
9142
+ for (let index = 0; index < length; index++) {
9143
+ budget.visitNode();
9144
+ const element = await readCoercionProperty(value, String(index), context);
9145
+ const part = element === null || element === void 0 ? "" : await sandboxString(element, budget, context, joining);
9146
+ text = budget.allocateString(text + (index === 0 ? "" : separator) + part);
9147
+ }
9148
+ return text;
9149
+ } finally {
9150
+ release();
9151
+ joiningArrays.delete(value);
9152
+ }
9153
+ }
9028
9154
  async function objectToPrimitive(value, budget, context, joining, hint) {
9029
9155
  const leaveCall = budget.enterCall();
9030
9156
  try {
9031
9157
  budget.visitNode();
9032
9158
  for (const name of hint === "string" ? ["toString", "valueOf"] : ["valueOf", "toString"]) {
9033
- const hook = conversionHook(value, name, budget);
9159
+ const hook = await conversionHook(value, name, budget, context);
9034
9160
  let result;
9035
9161
  if (hook === defaultStringHook) {
9036
9162
  result = await defaultToString(value, budget, context, joining);
@@ -9050,7 +9176,7 @@ async function objectToPrimitive(value, budget, context, joining, hint) {
9050
9176
  leaveCall();
9051
9177
  }
9052
9178
  }
9053
- function conversionHook(value, name, budget) {
9179
+ function conversionHook(value, name, budget, context) {
9054
9180
  const implicitBuiltin = !hasExplicitSandboxPrototype(value) && (Array.isArray(value) || isSandboxDate(value) || isFloat32Array(value) || sandboxErrorTypes.has(value) || isSandboxClosure(value) || isSandboxMap(value) || isSandboxSet(value) || isSandboxCollectionIterator(value) || isSandboxPromise(value) || isSandboxRegex(value) || isSandboxGenerator(value) || isGuestHostObject(value));
9055
9181
  let current = value;
9056
9182
  let depth = 0;
@@ -9058,9 +9184,7 @@ function conversionHook(value, name, budget) {
9058
9184
  const properties = isGuestClosure(current) ? getGuestFunctionProperties(current) : current;
9059
9185
  const descriptor = properties === void 0 ? void 0 : Object.getOwnPropertyDescriptor(properties, name);
9060
9186
  if (descriptor !== void 0) {
9061
- if (!Object.hasOwn(descriptor, "value"))
9062
- throw new TypeError("String conversion requires sandbox data properties.");
9063
- return descriptor.value;
9187
+ return readPropertyDescriptor(descriptor, value, context);
9064
9188
  }
9065
9189
  const parent = getSandboxPrototype(current, budget);
9066
9190
  if (current === value && (implicitBuiltin || parent === null && !hasExplicitSandboxPrototype(value))) {
@@ -9079,7 +9203,8 @@ async function defaultToString(value, budget, context, joining) {
9079
9203
  if (isSandboxClosure(value)) return budget.allocateString(functionString(value));
9080
9204
  if (isSandboxMap(value)) return "[object Map]";
9081
9205
  if (isSandboxSet(value)) return "[object Set]";
9082
- if (isSandboxCollectionIterator(value)) return collectionIteratorState(value).collectionKind === "map" ? "[object Map Iterator]" : "[object Set Iterator]";
9206
+ if (isSandboxCollectionIterator(value))
9207
+ return collectionIteratorState(value).collectionKind === "map" ? "[object Map Iterator]" : "[object Set Iterator]";
9083
9208
  if (isSandboxGenerator(value)) return "[object Generator]";
9084
9209
  if (isSandboxRegex(value)) {
9085
9210
  return budget.allocateString(
@@ -9089,35 +9214,20 @@ async function defaultToString(value, budget, context, joining) {
9089
9214
  if (isSandboxDate(value)) return budget.allocateString(dateString(value));
9090
9215
  if (Array.isArray(value) || isFloat32Array(value)) {
9091
9216
  if (Object.hasOwn(value, "join")) {
9092
- const join = ownDataValue(value, "join");
9217
+ const join = await readCoercionProperty(value, "join", context);
9093
9218
  if (!isSandboxClosure(join))
9094
9219
  return isFloat32Array(value) ? "[object Float32Array]" : "[object Array]";
9095
9220
  return invokeBuiltinClosure(join, [], budget, context, value);
9096
9221
  }
9097
- if (joining.has(value)) return "";
9098
- joining.add(value);
9099
- let text = "";
9100
- const release = retainValues(budget, () => [text]);
9101
- try {
9102
- const length = isFloat32Array(value) ? float32Storage(value).length : value.length;
9103
- for (let index = 0; index < length; index++) {
9104
- budget.visitNode();
9105
- const element = ownDataValue(value, String(index));
9106
- const part = element === null || element === void 0 ? "" : await sandboxString(element, budget, context, joining);
9107
- text = budget.allocateString(text + (index === 0 ? "" : ",") + part);
9108
- }
9109
- return text;
9110
- } finally {
9111
- release();
9112
- joining.delete(value);
9113
- }
9222
+ const length = isFloat32Array(value) ? float32Storage(value).length : value.length;
9223
+ return joinSandboxArray(value, length, ",", budget, context, joining);
9114
9224
  }
9115
9225
  if (sandboxErrorTypes.has(value)) {
9116
- const nameValue = ownDataValue(value, "name");
9226
+ const nameValue = await readCoercionProperty(value, "name", context);
9117
9227
  const name = nameValue === void 0 ? "Error" : await sandboxString(nameValue, budget, context, joining);
9118
9228
  const release = retainValues(budget, () => [name]);
9119
9229
  try {
9120
- const messageValue = ownDataValue(value, "message");
9230
+ const messageValue = await readCoercionProperty(value, "message", context);
9121
9231
  const message = messageValue === void 0 ? "" : await sandboxString(messageValue, budget, context, joining);
9122
9232
  return name === "" ? message : message === "" ? name : `${name}: ${message}`;
9123
9233
  } finally {
@@ -9126,12 +9236,153 @@ async function defaultToString(value, budget, context, joining) {
9126
9236
  }
9127
9237
  return isSandboxPromise(value) ? "[object Promise]" : "[object Object]";
9128
9238
  }
9129
- function ownDataValue(value, name) {
9239
+ function readCoercionProperty(value, name, context) {
9240
+ if (context?.getProperty !== void 0) return context.getProperty(value, name);
9130
9241
  const descriptor = Object.getOwnPropertyDescriptor(value, name);
9131
- if (descriptor !== void 0 && !Object.hasOwn(descriptor, "value")) {
9132
- throw new TypeError("String conversion requires sandbox data properties.");
9242
+ return descriptor === void 0 ? void 0 : readPropertyDescriptor(descriptor, value, context);
9243
+ }
9244
+
9245
+ // packages/safe-js/src/interp/globals/object.ts
9246
+ function createObjectGlobal(methods, budget) {
9247
+ const construct = ([value]) => {
9248
+ if (value === null || value === void 0) {
9249
+ budget.chargeDataUsage(1);
9250
+ return /* @__PURE__ */ Object.create(null);
9251
+ }
9252
+ if (typeof value !== "object") {
9253
+ const box = createSandboxBox(value);
9254
+ budget.chargeDataUsage(measureSandboxData([box]));
9255
+ return box;
9256
+ }
9257
+ return value;
9258
+ };
9259
+ const constructor = createSandboxClosure({
9260
+ guest: true,
9261
+ sandbox: true,
9262
+ name: "Object",
9263
+ length: 1,
9264
+ call: construct,
9265
+ construct: (args, context) => {
9266
+ if (context?.newTarget === void 0 || context.newTarget === constructor)
9267
+ return construct(args);
9268
+ const value = construct([]);
9269
+ const prototype2 = context.getProperty(context.newTarget, "prototype");
9270
+ const finish = (prototype3) => {
9271
+ if (typeof prototype3 === "object" && prototype3 !== null)
9272
+ setSandboxPrototype(value, prototype3, budget);
9273
+ return value;
9274
+ };
9275
+ return prototype2 instanceof Promise ? prototype2.then(finish) : finish(prototype2);
9276
+ }
9277
+ });
9278
+ const properties = materializeFunctionProperties(constructor);
9279
+ const prototype = properties.prototype;
9280
+ Object.defineProperty(properties, "prototype", { writable: false });
9281
+ for (const [name, method] of Object.entries(methods)) {
9282
+ Object.defineProperty(properties, name, { value: method, writable: true, configurable: true });
9283
+ }
9284
+ const prototypeMethods = {
9285
+ toString: createSandboxClosure({
9286
+ sandbox: true,
9287
+ name: "toString",
9288
+ length: 0,
9289
+ call: (_args, context) => budget.allocateString(`[object ${typeTag(context?.thisValue)}]`)
9290
+ }),
9291
+ valueOf: createSandboxClosure({
9292
+ sandbox: true,
9293
+ name: "valueOf",
9294
+ length: 0,
9295
+ call: (_args, context) => {
9296
+ const value = requireReceiver(context?.thisValue);
9297
+ return construct([value]);
9298
+ }
9299
+ }),
9300
+ hasOwnProperty: createSandboxClosure({
9301
+ sandbox: true,
9302
+ name: "hasOwnProperty",
9303
+ length: 1,
9304
+ call: async ([key], context) => hasOwnSandboxProperty(
9305
+ requireReceiver(context?.thisValue),
9306
+ await sandboxString(key, budget, context),
9307
+ false
9308
+ )
9309
+ }),
9310
+ propertyIsEnumerable: createSandboxClosure({
9311
+ sandbox: true,
9312
+ name: "propertyIsEnumerable",
9313
+ length: 1,
9314
+ call: async ([key], context) => hasOwnSandboxProperty(
9315
+ requireReceiver(context?.thisValue),
9316
+ await sandboxString(key, budget, context),
9317
+ true
9318
+ )
9319
+ }),
9320
+ isPrototypeOf: createSandboxClosure({
9321
+ sandbox: true,
9322
+ name: "isPrototypeOf",
9323
+ length: 1,
9324
+ call: ([value], context) => {
9325
+ if (typeof value !== "object" || value === null) return false;
9326
+ const receiver = requireReceiver(context?.thisValue);
9327
+ let depth = 0;
9328
+ for (let current = getSandboxPrototype(value, budget); current !== null; current = getSandboxPrototype(current, budget)) {
9329
+ budget.visitNode();
9330
+ assertSandboxDataDepth(depth++);
9331
+ if (current === receiver) return true;
9332
+ }
9333
+ return false;
9334
+ }
9335
+ })
9336
+ };
9337
+ for (const [name, method] of Object.entries(prototypeMethods)) {
9338
+ Object.defineProperty(prototype, name, { value: method, writable: true, configurable: true });
9339
+ }
9340
+ markDescriptorObject(prototype);
9341
+ installObjectPrototype(budget, prototype, constructor);
9342
+ return constructor;
9343
+ }
9344
+ function requireReceiver(value) {
9345
+ if (value === null || value === void 0)
9346
+ throw new TypeError("Object method requires a non-null receiver.");
9347
+ return value;
9348
+ }
9349
+ function hasOwnSandboxProperty(value, key, enumerable) {
9350
+ requireReceiver(value);
9351
+ if (isGuestHostObject(value)) return hasHostObjectMember(value, key, enumerable);
9352
+ let properties;
9353
+ if (isGuestClosure(value)) properties = materializeFunctionProperties(value);
9354
+ else if (isSandboxClosure(value)) {
9355
+ if (key === "length" || key === "name") return !enumerable;
9356
+ properties = value.properties ?? /* @__PURE__ */ Object.create(null);
9357
+ } else if (isSandboxMap(value) || isSandboxSet(value) || isSandboxPromise(value) || isSandboxGenerator(value))
9358
+ return false;
9359
+ else if (isSandboxRegex(value)) return key === "lastIndex" && !enumerable;
9360
+ else properties = Object(value);
9361
+ const descriptor = Object.getOwnPropertyDescriptor(properties, key);
9362
+ return descriptor !== void 0 && (!enumerable || descriptor.enumerable === true);
9363
+ }
9364
+ function typeTag(value) {
9365
+ if (isSandboxBox(value)) value = boxedValue(value);
9366
+ if (value === void 0) return "Undefined";
9367
+ if (value === null) return "Null";
9368
+ if (typeof value === "string") return "String";
9369
+ if (typeof value === "number") return "Number";
9370
+ if (typeof value === "boolean") return "Boolean";
9371
+ if (isSandboxClosure(value)) {
9372
+ while (value.boundTarget !== void 0) value = value.boundTarget;
9373
+ return value.generator ? "GeneratorFunction" : value.async ? "AsyncFunction" : "Function";
9133
9374
  }
9134
- return descriptor?.value;
9375
+ if (Array.isArray(value)) return "Array";
9376
+ if (isSandboxDate(value)) return "Date";
9377
+ if (isSandboxErrorConstructorInstance(value, "Error")) return "Error";
9378
+ if (isSandboxRegex(value)) return "RegExp";
9379
+ if (isSandboxMap(value)) return "Map";
9380
+ if (isSandboxSet(value)) return "Set";
9381
+ if (isSandboxCollectionIterator(value)) return collectionIteratorState(value).collectionKind === "map" ? "Map Iterator" : "Set Iterator";
9382
+ if (isSandboxPromise(value)) return "Promise";
9383
+ if (isSandboxGenerator(value)) return "Generator";
9384
+ if (isFloat32Array(value)) return "Float32Array";
9385
+ return "Object";
9135
9386
  }
9136
9387
 
9137
9388
  // packages/safe-js/src/interp/property-key.ts
@@ -9514,12 +9765,34 @@ async function bindArrayPattern(pattern, value, context, evaluateNode2) {
9514
9765
  if (!Array.isArray(value)) {
9515
9766
  throw new TypeError("Array catch bindings require an array value.");
9516
9767
  }
9768
+ let cursor = 0;
9769
+ let done = false;
9770
+ const next = async () => {
9771
+ if (done || cursor >= value.length) {
9772
+ done = true;
9773
+ return { done: true, value: void 0 };
9774
+ }
9775
+ const key = cursor++;
9776
+ return {
9777
+ done: false,
9778
+ value: context.getProperty === void 0 ? getSandboxDataProperty(value, key, context.budget) : await context.getProperty(value, key)
9779
+ };
9780
+ };
9517
9781
  for (let index = 0; index < pattern.elements.length; index += 1) {
9518
9782
  const element = pattern.elements[index];
9519
9783
  if (element === null) {
9784
+ await next();
9520
9785
  continue;
9521
9786
  }
9522
- const elementValue = element.type === "RestElement" ? value.slice(index) : value[index];
9787
+ let elementValue;
9788
+ if (element.type === "RestElement") {
9789
+ const rest = [];
9790
+ for (let entry = await next(); !entry.done; entry = await next()) {
9791
+ context.budget.allocateArrayLength(rest.length + 1);
9792
+ rest.push(entry.value);
9793
+ }
9794
+ elementValue = rest;
9795
+ } else elementValue = (await next()).value;
9523
9796
  const binding = await bindPattern(element, elementValue, context, evaluateNode2);
9524
9797
  if (!binding.ok) {
9525
9798
  return binding;
@@ -9534,7 +9807,7 @@ async function bindObjectPattern(pattern, value, context, evaluateNode2) {
9534
9807
  const excludedKeys = /* @__PURE__ */ new Set();
9535
9808
  for (const property of pattern.properties) {
9536
9809
  if (property.type === "RestElement") {
9537
- const restValue = copyObjectRest(value, excludedKeys);
9810
+ const restValue = await copyObjectRest(value, excludedKeys, context);
9538
9811
  const binding2 = await bindPattern(property, restValue, context, evaluateNode2);
9539
9812
  if (!binding2.ok) {
9540
9813
  return binding2;
@@ -9548,7 +9821,7 @@ async function bindObjectPattern(pattern, value, context, evaluateNode2) {
9548
9821
  excludedKeys.add(String(key.value));
9549
9822
  const binding = await bindPattern(
9550
9823
  property.value,
9551
- context.getProperty === void 0 ? getSandboxDataProperty(value, key.value, context.budget) : context.getProperty(value, key.value),
9824
+ context.getProperty === void 0 ? getSandboxDataProperty(value, key.value, context.budget) : await context.getProperty(value, key.value),
9552
9825
  context,
9553
9826
  evaluateNode2
9554
9827
  );
@@ -9592,12 +9865,18 @@ function getStaticPropertyKey(property) {
9592
9865
  throw new TypeError(`Unsupported catch binding property key '${property.type}'.`);
9593
9866
  }
9594
9867
  }
9595
- function copyObjectRest(value, excludedKeys) {
9868
+ async function copyObjectRest(value, excludedKeys, context) {
9596
9869
  const rest = /* @__PURE__ */ Object.create(null);
9597
- for (const [key, entryValue] of ownEnumerableSandboxEntries(value, excludedKeys)) {
9598
- rest[key] = entryValue;
9870
+ const release = retainValues(context.budget, () => [value, rest]);
9871
+ try {
9872
+ for (const key of ownEnumerableSandboxKeys(value)) {
9873
+ if (excludedKeys.has(key) || !hasOwnSandboxProperty(value, key, true)) continue;
9874
+ rest[key] = context.getProperty === void 0 ? getSandboxDataProperty(value, key, context.budget) : await context.getProperty(value, key);
9875
+ }
9876
+ return rest;
9877
+ } finally {
9878
+ release();
9599
9879
  }
9600
- return rest;
9601
9880
  }
9602
9881
 
9603
9882
  // packages/safe-js/src/interp/running-state.ts
@@ -9673,6 +9952,18 @@ function getSandboxIterator(value, budget, context) {
9673
9952
  if (isSandboxSet(value)) {
9674
9953
  return collectionIterator(value.values);
9675
9954
  }
9955
+ if (Array.isArray(value) && context?.getProperty !== void 0) {
9956
+ let index = 0;
9957
+ return {
9958
+ asynchronous: true,
9959
+ snapshotIndex: () => index,
9960
+ next: async () => {
9961
+ if (index >= value.length) return { done: true, value: void 0 };
9962
+ budget?.visitNode();
9963
+ return { done: false, value: await context.getProperty(value, index++) };
9964
+ }
9965
+ };
9966
+ }
9676
9967
  if (typeof value !== "object" && typeof value !== "function" || value === null) {
9677
9968
  return void 0;
9678
9969
  }
@@ -10067,7 +10358,7 @@ async function callPromiseClosure(callback, args, thisValue, budget, context) {
10067
10358
  const values = args.map(
10068
10359
  (value) => value instanceof Error && !(value instanceof SandboxError) ? coerceThrownValue(value, budget, stack) : value
10069
10360
  );
10070
- let result = callback.call(values, { stack, thisValue });
10361
+ let result = callback.call(values, { ...context, stack, thisValue, newTarget: void 0 });
10071
10362
  if (callback.async !== true) result = await result;
10072
10363
  else if (isPromiseLike(result)) result = createSandboxPromise(Promise.resolve(result));
10073
10364
  if (isSandboxPromise(result) && result.synchronousPrefix !== void 0) {
@@ -10094,11 +10385,11 @@ function getPromisePrototype(budget) {
10094
10385
  target.promise.then(
10095
10386
  (value) => {
10096
10387
  consumeSettledHostCall(target);
10097
- return runPromiseReaction(onFulfilled, value, "fulfilled", budget, chained);
10388
+ return runPromiseReaction(onFulfilled, value, "fulfilled", budget, chained, context);
10098
10389
  },
10099
10390
  (reason) => {
10100
10391
  consumeSettledHostCall(target);
10101
- return runPromiseReaction(onRejected, reason, "rejected", budget, chained);
10392
+ return runPromiseReaction(onRejected, reason, "rejected", budget, chained, context);
10102
10393
  }
10103
10394
  )
10104
10395
  );
@@ -10110,12 +10401,18 @@ function getPromisePrototype(budget) {
10110
10401
  sandbox: true,
10111
10402
  call: ([onRejected], context) => {
10112
10403
  const target = context?.thisValue;
10113
- const then = readPromiseReceiverProperty(target, "then", prototype);
10114
- if (!isSandboxClosure(then)) throw new TypeError("Promise.catch requires a callable then.");
10115
- return then.call([void 0, onRejected], {
10116
- stack: context?.stack ?? [],
10117
- thisValue: target
10118
- });
10404
+ const invoke = (then2) => {
10405
+ if (!isSandboxClosure(then2))
10406
+ throw new TypeError("Promise.catch requires a callable then.");
10407
+ return then2.call([void 0, onRejected], {
10408
+ ...context,
10409
+ stack: context?.stack ?? [],
10410
+ thisValue: target,
10411
+ newTarget: void 0
10412
+ });
10413
+ };
10414
+ const then = readPromiseReceiverProperty(target, "then", prototype, context);
10415
+ return then instanceof Promise ? then.then(invoke) : invoke(then);
10119
10416
  },
10120
10417
  name: "catch"
10121
10418
  }),
@@ -10126,46 +10423,57 @@ function getPromisePrototype(budget) {
10126
10423
  if (typeof target !== "object" || target === null) {
10127
10424
  throw new TypeError("Promise.finally requires an object receiver.");
10128
10425
  }
10129
- validatePromiseConstructorProperty(target, prototype);
10130
- const then = readPromiseReceiverProperty(target, "then", prototype);
10131
- if (!isSandboxClosure(then))
10132
- throw new TypeError("Promise.finally requires a callable then.");
10133
- const handlers = isSandboxClosure(onFinally) ? ["fulfilled", "rejected"].map(
10134
- (state) => createSandboxClosure({
10135
- sandbox: true,
10136
- retainedValues: () => [onFinally],
10137
- call: async ([value]) => {
10138
- const result = await callPromiseClosure(
10139
- onFinally,
10140
- [],
10141
- void 0,
10142
- budget,
10143
- context
10144
- );
10145
- const pending = isSandboxPromise(result) && getPromiseMember("constructor", budget) === intrinsicPromiseConstructors.get(budget) ? result : createSandboxPromise(resolveSandboxValue(result, { budget }));
10146
- const cleanupThen = getPromiseMember("then", budget);
10147
- if (!isSandboxClosure(cleanupThen))
10148
- throw new TypeError("Promise cleanup requires a callable then.");
10149
- return callPromiseClosure(
10150
- cleanupThen,
10151
- [
10152
- createSandboxClosure({
10153
- sandbox: true,
10154
- retainedValues: () => [value],
10155
- call: () => {
10156
- if (state === "rejected") throw value;
10157
- return value;
10158
- }
10159
- })
10160
- ],
10161
- pending,
10162
- budget,
10163
- context
10164
- );
10165
- }
10166
- })
10167
- ) : [onFinally, onFinally];
10168
- return then.call(handlers, { stack: context?.stack ?? [], thisValue: target });
10426
+ const invoke = (then) => {
10427
+ if (!isSandboxClosure(then))
10428
+ throw new TypeError("Promise.finally requires a callable then.");
10429
+ const handlers = isSandboxClosure(onFinally) ? ["fulfilled", "rejected"].map(
10430
+ (state) => createSandboxClosure({
10431
+ sandbox: true,
10432
+ retainedValues: () => [onFinally],
10433
+ call: async ([value]) => {
10434
+ const result = await callPromiseClosure(
10435
+ onFinally,
10436
+ [],
10437
+ void 0,
10438
+ budget,
10439
+ context
10440
+ );
10441
+ const pending = isSandboxPromise(result) && getPromiseMember("constructor", budget) === intrinsicPromiseConstructors.get(budget) ? result : createSandboxPromise(resolveSandboxValue(result, { budget }));
10442
+ const cleanupThen = getPromiseMember("then", budget);
10443
+ if (!isSandboxClosure(cleanupThen))
10444
+ throw new TypeError("Promise cleanup requires a callable then.");
10445
+ return callPromiseClosure(
10446
+ cleanupThen,
10447
+ [
10448
+ createSandboxClosure({
10449
+ sandbox: true,
10450
+ retainedValues: () => [value],
10451
+ call: () => {
10452
+ if (state === "rejected") throw value;
10453
+ return value;
10454
+ }
10455
+ })
10456
+ ],
10457
+ pending,
10458
+ budget,
10459
+ context
10460
+ );
10461
+ }
10462
+ })
10463
+ ) : [onFinally, onFinally];
10464
+ return then.call(handlers, {
10465
+ ...context,
10466
+ stack: context?.stack ?? [],
10467
+ thisValue: target,
10468
+ newTarget: void 0
10469
+ });
10470
+ };
10471
+ const finish = () => {
10472
+ const then = readPromiseReceiverProperty(target, "then", prototype, context);
10473
+ return then instanceof Promise ? then.then(invoke) : invoke(then);
10474
+ };
10475
+ const validation = validatePromiseConstructorProperty(target, prototype, context);
10476
+ return validation instanceof Promise ? validation.then(finish) : finish();
10169
10477
  },
10170
10478
  name: "finally"
10171
10479
  })
@@ -10176,15 +10484,19 @@ function getPromisePrototype(budget) {
10176
10484
  promisePrototypes.set(budget, prototype);
10177
10485
  return prototype;
10178
10486
  }
10179
- function readPromiseReceiverProperty(receiver, property, prototype) {
10487
+ function readPromiseReceiverProperty(receiver, property, prototype, context) {
10488
+ if (!isSandboxPromise(receiver) && context?.getProperty !== void 0)
10489
+ return context.getProperty(receiver, property);
10180
10490
  const properties = isSandboxPromise(receiver) ? prototype : isSandboxClosure(receiver) ? receiver.properties : receiver;
10181
10491
  return typeof properties === "object" && properties !== null && Object.hasOwn(properties, property) ? properties[property] : void 0;
10182
10492
  }
10183
- function validatePromiseConstructorProperty(receiver, prototype) {
10184
- const constructor = readPromiseReceiverProperty(receiver, "constructor", prototype);
10185
- if (constructor !== void 0 && (typeof constructor !== "object" || constructor === null)) {
10186
- throw new TypeError("Promise constructor property must be an object.");
10187
- }
10493
+ function validatePromiseConstructorProperty(receiver, prototype, context) {
10494
+ const validate = (constructor2) => {
10495
+ if (constructor2 !== void 0 && (typeof constructor2 !== "object" || constructor2 === null))
10496
+ throw new TypeError("Promise constructor property must be an object.");
10497
+ };
10498
+ const constructor = readPromiseReceiverProperty(receiver, "constructor", prototype, context);
10499
+ return constructor instanceof Promise ? constructor.then(validate) : validate(constructor);
10188
10500
  }
10189
10501
  async function settleIterable(iterable, method, budget, constructor, context) {
10190
10502
  const capability = await createPromiseCapability(constructor, budget, context);
@@ -10219,7 +10531,7 @@ async function settleIterable(iterable, method, budget, constructor, context) {
10219
10531
  }
10220
10532
  };
10221
10533
  try {
10222
- const promiseResolve = readPromiseReceiverProperty(constructor, "resolve", prototype);
10534
+ const promiseResolve = await readPromiseReceiverProperty(constructor, "resolve", prototype, context);
10223
10535
  if (!isSandboxClosure(promiseResolve))
10224
10536
  throw new TypeError("Promise constructor requires a callable resolve.");
10225
10537
  const iterator = getSandboxIterator(iterable, budget, context);
@@ -10269,7 +10581,7 @@ async function settleIterable(iterable, method, budget, constructor, context) {
10269
10581
  });
10270
10582
  });
10271
10583
  remaining++;
10272
- const then = readPromiseReceiverProperty(entry, "then", prototype);
10584
+ const then = await readPromiseReceiverProperty(entry, "then", prototype, context);
10273
10585
  if (!isSandboxClosure(then))
10274
10586
  throw new TypeError("Promise resolver result requires a callable then.");
10275
10587
  await callPromiseClosure(then, handlers, entry, budget, context);
@@ -10356,7 +10668,11 @@ function resolveSandboxValueNow(value, options) {
10356
10668
  }
10357
10669
  );
10358
10670
  }
10359
- const then = getThenable(value);
10671
+ const then = getThenable(value, options.budget);
10672
+ if (then instanceof Promise)
10673
+ return then.then(
10674
+ (method) => method === void 0 ? budgetIfNeeded(value, options.budget) : resolveThenable(value, method, options)
10675
+ );
10360
10676
  if (then !== void 0) {
10361
10677
  return resolveThenable(value, then, options);
10362
10678
  }
@@ -10376,7 +10692,7 @@ function resolveThenable(value, then, options) {
10376
10692
  try {
10377
10693
  if (settlement.state === "fulfilled") {
10378
10694
  resolve(
10379
- isSandboxPromise(settlement.value) || getThenable(settlement.value) !== void 0 ? resolveSandboxValueNow(settlement.value, options) : budgetIfNeeded(settlement.value, options.budget)
10695
+ requiresPromiseResolution(settlement.value, options.budget) ? resolveSandboxValueNow(settlement.value, options) : budgetIfNeeded(settlement.value, options.budget)
10380
10696
  );
10381
10697
  } else {
10382
10698
  reject(budgetIfNeeded(settlement.value, options.budget));
@@ -10432,7 +10748,7 @@ function resolveThenable(value, then, options) {
10432
10748
  ).catch(reject);
10433
10749
  });
10434
10750
  }
10435
- function runPromiseReaction(handler, value, state, budget, self) {
10751
+ function runPromiseReaction(handler, value, state, budget, self, context) {
10436
10752
  return new Promise((resolve, reject) => {
10437
10753
  if (state === "rejected" && value instanceof SandboxError && (value.code === "budgetExceeded" || value.code === "reentry")) {
10438
10754
  reject(value);
@@ -10446,14 +10762,14 @@ function runPromiseReaction(handler, value, state, budget, self) {
10446
10762
  reject(
10447
10763
  createSubsetErrorValue("TypeError", "Promise cannot resolve to itself.", [], budget)
10448
10764
  );
10449
- } else if (isSandboxPromise(result) || getThenable(result) !== void 0) {
10765
+ } else if (requiresPromiseResolution(result, budget)) {
10450
10766
  resolve(resolvePromiseResult(result, budget, self));
10451
10767
  } else {
10452
10768
  resolve(budgetSandboxValue(result, budget));
10453
10769
  }
10454
10770
  };
10455
10771
  if (isSandboxClosure(handler)) {
10456
- callInPromiseJob(handler, [argument], void 0, { fulfilled, rejected: reject }).catch(
10772
+ callInPromiseJob(handler, [argument], void 0, { fulfilled, rejected: reject }, context).catch(
10457
10773
  reject
10458
10774
  );
10459
10775
  } else {
@@ -10464,10 +10780,10 @@ function runPromiseReaction(handler, value, state, budget, self) {
10464
10780
  }
10465
10781
  });
10466
10782
  }
10467
- function callInPromiseJob(handler, args, thisValue = void 0, completion) {
10783
+ function callInPromiseJob(handler, args, thisValue = void 0, completion, context) {
10468
10784
  return runPromiseJob(async () => {
10469
10785
  try {
10470
- let result = handler.call(args, { stack: [], thisValue });
10786
+ let result = handler.call(args, { ...context, stack: [], thisValue, newTarget: void 0 });
10471
10787
  if (handler.async !== true) result = await result;
10472
10788
  if (isSandboxPromise(result) && result.synchronousPrefix !== void 0) {
10473
10789
  await result.synchronousPrefix;
@@ -10500,7 +10816,7 @@ function resolvePromiseResult(result, budget, self) {
10500
10816
  settled = true;
10501
10817
  try {
10502
10818
  if (state === "rejected") reject(budgetSandboxValue(value, budget));
10503
- else if (isSandboxPromise(value) || getThenable(value) !== void 0) {
10819
+ else if (requiresPromiseResolution(value, budget)) {
10504
10820
  resolve(resolvePromiseResult(value, budget, self));
10505
10821
  } else {
10506
10822
  resolve(budgetSandboxValue(value, budget));
@@ -10548,11 +10864,23 @@ function resolvePromiseResult(result, budget, self) {
10548
10864
  function isSelfResolution(result, self) {
10549
10865
  return self !== void 0 && (result === self || isSandboxPromise(result) && result.promise === self.promise);
10550
10866
  }
10551
- function getThenable(value) {
10867
+ function requiresPromiseResolution(value, budget) {
10868
+ if (isSandboxPromise(value)) return true;
10869
+ const descriptor = getSandboxPropertyDescriptor(value, "then", budget);
10870
+ return descriptor !== void 0 && (!("value" in descriptor) || isSandboxClosure(descriptor.value));
10871
+ }
10872
+ function getThenable(value, budget) {
10552
10873
  if (typeof value !== "object" || value === null || isSandboxPromise(value)) {
10553
10874
  return void 0;
10554
10875
  }
10555
- const then = isSandboxClosure(value) ? value.properties?.then : value.then;
10876
+ const descriptor = getSandboxPropertyDescriptor(value, "then", budget);
10877
+ if (descriptor !== void 0 && !("value" in descriptor)) {
10878
+ const getter = accessorClosure(descriptor.get);
10879
+ if (getter === void 0) return void 0;
10880
+ const result = budget === void 0 ? getter.call([], { stack: [], thisValue: value }) : callPromiseClosure(getter, [], value, budget);
10881
+ return Promise.resolve(result).then((then2) => isSandboxClosure(then2) ? then2 : void 0);
10882
+ }
10883
+ const then = descriptor?.value;
10556
10884
  return isSandboxClosure(then) ? then : void 0;
10557
10885
  }
10558
10886
  function budgetIfNeeded(value, budget) {
@@ -10843,6 +11171,13 @@ function ownEnumerableSandboxEntries(value, excludedKeys) {
10843
11171
  else entries = Object.entries(Object(value));
10844
11172
  return excludedKeys === void 0 ? entries : entries.filter(([key]) => !excludedKeys.has(key));
10845
11173
  }
11174
+ function ownEnumerableSandboxKeys(value) {
11175
+ if (isGuestHostObject(value)) return getHostObjectKeys(value);
11176
+ if (value === null || value === void 0) throw new TypeError("Cannot convert undefined or null to object.");
11177
+ if (isGuestClosure(value)) return Object.keys(value.properties ?? {});
11178
+ if (isSandboxClosure(value) || isSandboxGenerator(value) || isSandboxMap(value) || isSandboxSet(value) || isSandboxPromise(value) || isSandboxRegex(value)) return [];
11179
+ return Object.keys(Object(value));
11180
+ }
10846
11181
  function createSandboxPromise(promise, metadata = {}) {
10847
11182
  const original = metadata.trackReplay === false ? promise : promiseReplayContext.getStore()?.track(promise) ?? promise;
10848
11183
  const sandboxPromise = {
@@ -10997,6 +11332,7 @@ function measureSandboxData(values, options = {}) {
10997
11332
  for (const [key, descriptor] of boxedDataProperties(value)) {
10998
11333
  usage += key.length + 1;
10999
11334
  if ("value" in descriptor) visit(descriptor.value, depth + 1);
11335
+ else for (const closure of retainedAccessorClosures(descriptor)) visit(closure, depth + 1);
11000
11336
  }
11001
11337
  return;
11002
11338
  }
@@ -11029,6 +11365,7 @@ function measureSandboxData(values, options = {}) {
11029
11365
  if (key === "length") continue;
11030
11366
  usage += key.length + 1;
11031
11367
  if ("value" in descriptor) visit(descriptor.value, depth + 1);
11368
+ else for (const closure of retainedAccessorClosures(descriptor)) visit(closure, depth + 1);
11032
11369
  }
11033
11370
  return;
11034
11371
  }
@@ -11067,6 +11404,7 @@ function measureSandboxData(values, options = {}) {
11067
11404
  if (key === "prototype" || key === "name" || key === "length") continue;
11068
11405
  usage += key.length + 1;
11069
11406
  if ("value" in descriptor) visit(descriptor.value, depth + 1);
11407
+ else for (const closure of retainedAccessorClosures(descriptor)) visit(closure, depth + 1);
11070
11408
  }
11071
11409
  } else visit(value.properties, depth + 1);
11072
11410
  }
@@ -11110,7 +11448,8 @@ function measureSandboxData(values, options = {}) {
11110
11448
  const descriptor = descriptors[key];
11111
11449
  if (!descriptor.enumerable && !hasManagedDescriptors(value)) continue;
11112
11450
  usage += key.length;
11113
- visit("value" in descriptor ? descriptor.value : void 0, depth + 1);
11451
+ if ("value" in descriptor) visit(descriptor.value, depth + 1);
11452
+ else for (const closure of retainedAccessorClosures(descriptor)) visit(closure, depth + 1);
11114
11453
  }
11115
11454
  };
11116
11455
  for (const value of values) visit(value);
@@ -24466,24 +24805,32 @@ async function bindAssignmentPattern2(pattern, value, target, scope, context) {
24466
24805
  async function bindArrayPattern2(pattern, value, target, scope, context) {
24467
24806
  const iterator = isSandboxCollectionIterator(value) ? value : void 0;
24468
24807
  const values = iterator === void 0 ? getArrayPatternValues(value) : void 0;
24808
+ let cursor = 0;
24809
+ let done = false;
24810
+ const next = async () => {
24811
+ if (iterator !== void 0) return nextCollectionIterator(iterator, context.budget);
24812
+ if (done || cursor >= values.length) {
24813
+ done = true;
24814
+ return { done: true, value: void 0 };
24815
+ }
24816
+ return { done: false, value: await context.getProperty(values, cursor++) };
24817
+ };
24469
24818
  for (let index = 0; index < pattern.elements.length; index += 1) {
24470
24819
  const element = pattern.elements[index];
24471
24820
  if (element === null) {
24472
- if (iterator !== void 0) nextCollectionIterator(iterator, context.budget);
24821
+ await next();
24473
24822
  continue;
24474
24823
  }
24475
24824
  let elementValue;
24476
- if (iterator === void 0) {
24477
- elementValue = element.type === "RestElement" ? values.slice(index) : values[index];
24478
- } else if (element.type === "RestElement") {
24825
+ if (element.type === "RestElement") {
24479
24826
  const rest = [];
24480
- for (let entry = nextCollectionIterator(iterator, context.budget); !entry.done; entry = nextCollectionIterator(iterator, context.budget)) {
24827
+ for (let entry = await next(); !entry.done; entry = await next()) {
24481
24828
  context.budget?.allocateArrayLength(rest.length + 1);
24482
24829
  rest.push(entry.value);
24483
24830
  }
24484
24831
  elementValue = rest;
24485
24832
  } else {
24486
- elementValue = nextCollectionIterator(iterator, context.budget).value;
24833
+ elementValue = (await next()).value;
24487
24834
  }
24488
24835
  const binding = await bindPattern2(element, elementValue, target, scope, context);
24489
24836
  if (!binding.ok) {
@@ -24501,7 +24848,7 @@ async function bindObjectPattern2(pattern, value, target, scope, context) {
24501
24848
  if (property.type === "RestElement") {
24502
24849
  const binding2 = await bindPattern2(
24503
24850
  property,
24504
- copyObjectRestValue(value, excludedKeys),
24851
+ await copyObjectRestValue(value, excludedKeys, context),
24505
24852
  target,
24506
24853
  scope,
24507
24854
  context
@@ -24518,7 +24865,7 @@ async function bindObjectPattern2(pattern, value, target, scope, context) {
24518
24865
  excludedKeys.add(String(key.value));
24519
24866
  const binding = await bindPattern2(
24520
24867
  property.value,
24521
- context.getProperty(value, key.value),
24868
+ await context.getProperty(value, key.value),
24522
24869
  target,
24523
24870
  scope,
24524
24871
  context
@@ -24544,7 +24891,7 @@ async function bindMemberExpression(pattern, value, scope, context) {
24544
24891
  if (!isIndexableValue(object.value)) {
24545
24892
  throw new TypeError("Assignment expressions require a sandbox object property.");
24546
24893
  }
24547
- context.setProperty(object.value, await context.toPropertyKey(property.value), value);
24894
+ await context.setProperty(object.value, await context.toPropertyKey(property.value), value);
24548
24895
  return { ok: true };
24549
24896
  }
24550
24897
  async function evaluatePatternKey(property, context) {
@@ -24595,12 +24942,18 @@ function describeRuntimeValue(value) {
24595
24942
  if (typeof value === "object") return value.constructor?.name ?? "Object";
24596
24943
  return typeof value;
24597
24944
  }
24598
- function copyObjectRestValue(value, excludedKeys) {
24945
+ async function copyObjectRestValue(value, excludedKeys, context) {
24599
24946
  const rest = /* @__PURE__ */ Object.create(null);
24600
- for (const [key, entryValue] of ownEnumerableSandboxEntries(value, excludedKeys)) {
24601
- defineProperty(rest, key, entryValue);
24947
+ const release = context.budget === void 0 ? () => void 0 : retainValues(context.budget, () => [value, rest]);
24948
+ try {
24949
+ for (const key of ownEnumerableSandboxKeys(value)) {
24950
+ if (excludedKeys.has(key) || !hasOwnSandboxProperty(value, key, true)) continue;
24951
+ defineProperty(rest, key, await context.getProperty(value, key));
24952
+ }
24953
+ return rest;
24954
+ } finally {
24955
+ release();
24602
24956
  }
24603
- return rest;
24604
24957
  }
24605
24958
  function isIndexableValue(value) {
24606
24959
  return typeof value === "object" && value !== null;
@@ -24734,144 +25087,6 @@ function getDatePrototype(value, budget, owner) {
24734
25087
  return prototype === value ? null : prototype ?? null;
24735
25088
  }
24736
25089
 
24737
- // packages/safe-js/src/interp/globals/object.ts
24738
- function createObjectGlobal(methods, budget) {
24739
- const construct = ([value]) => {
24740
- if (value === null || value === void 0) {
24741
- budget.chargeDataUsage(1);
24742
- return /* @__PURE__ */ Object.create(null);
24743
- }
24744
- if (typeof value !== "object") {
24745
- const box = createSandboxBox(value);
24746
- budget.chargeDataUsage(measureSandboxData([box]));
24747
- return box;
24748
- }
24749
- return value;
24750
- };
24751
- const constructor = createSandboxClosure({
24752
- guest: true,
24753
- sandbox: true,
24754
- name: "Object",
24755
- length: 1,
24756
- call: construct,
24757
- construct: (args, context) => {
24758
- if (context?.newTarget === void 0 || context.newTarget === constructor) return construct(args);
24759
- const value = construct([]);
24760
- const prototype2 = context.getProperty(context.newTarget, "prototype");
24761
- if (typeof prototype2 === "object" && prototype2 !== null) setSandboxPrototype(value, prototype2, budget);
24762
- return value;
24763
- }
24764
- });
24765
- const properties = materializeFunctionProperties(constructor);
24766
- const prototype = properties.prototype;
24767
- Object.defineProperty(properties, "prototype", { writable: false });
24768
- for (const [name, method] of Object.entries(methods)) {
24769
- Object.defineProperty(properties, name, { value: method, writable: true, configurable: true });
24770
- }
24771
- const prototypeMethods = {
24772
- toString: createSandboxClosure({
24773
- sandbox: true,
24774
- name: "toString",
24775
- length: 0,
24776
- call: (_args, context) => budget.allocateString(`[object ${typeTag(context?.thisValue)}]`)
24777
- }),
24778
- valueOf: createSandboxClosure({
24779
- sandbox: true,
24780
- name: "valueOf",
24781
- length: 0,
24782
- call: (_args, context) => {
24783
- const value = requireReceiver(context?.thisValue);
24784
- return construct([value]);
24785
- }
24786
- }),
24787
- hasOwnProperty: createSandboxClosure({
24788
- sandbox: true,
24789
- name: "hasOwnProperty",
24790
- length: 1,
24791
- call: async ([key], context) => hasOwnSandboxProperty(
24792
- requireReceiver(context?.thisValue),
24793
- await sandboxString(key, budget, context),
24794
- false
24795
- )
24796
- }),
24797
- propertyIsEnumerable: createSandboxClosure({
24798
- sandbox: true,
24799
- name: "propertyIsEnumerable",
24800
- length: 1,
24801
- call: async ([key], context) => hasOwnSandboxProperty(
24802
- requireReceiver(context?.thisValue),
24803
- await sandboxString(key, budget, context),
24804
- true
24805
- )
24806
- }),
24807
- isPrototypeOf: createSandboxClosure({
24808
- sandbox: true,
24809
- name: "isPrototypeOf",
24810
- length: 1,
24811
- call: ([value], context) => {
24812
- if (typeof value !== "object" || value === null) return false;
24813
- const receiver = requireReceiver(context?.thisValue);
24814
- let depth = 0;
24815
- for (let current = getSandboxPrototype(value, budget); current !== null; current = getSandboxPrototype(current, budget)) {
24816
- budget.visitNode();
24817
- assertSandboxDataDepth(depth++);
24818
- if (current === receiver) return true;
24819
- }
24820
- return false;
24821
- }
24822
- })
24823
- };
24824
- for (const [name, method] of Object.entries(prototypeMethods)) {
24825
- Object.defineProperty(prototype, name, { value: method, writable: true, configurable: true });
24826
- }
24827
- markDescriptorObject(prototype);
24828
- installObjectPrototype(budget, prototype, constructor);
24829
- return constructor;
24830
- }
24831
- function requireReceiver(value) {
24832
- if (value === null || value === void 0)
24833
- throw new TypeError("Object method requires a non-null receiver.");
24834
- return value;
24835
- }
24836
- function hasOwnSandboxProperty(value, key, enumerable) {
24837
- requireReceiver(value);
24838
- if (isGuestHostObject(value)) return hasHostObjectMember(value, key, enumerable);
24839
- let properties;
24840
- if (isGuestClosure(value)) properties = materializeFunctionProperties(value);
24841
- else if (isSandboxClosure(value)) {
24842
- if (key === "length" || key === "name") return !enumerable;
24843
- properties = value.properties ?? /* @__PURE__ */ Object.create(null);
24844
- } else if (isSandboxMap(value) || isSandboxSet(value) || isSandboxPromise(value) || isSandboxGenerator(value))
24845
- return false;
24846
- else if (isSandboxRegex(value)) return key === "lastIndex" && !enumerable;
24847
- else properties = Object(value);
24848
- const descriptor = Object.getOwnPropertyDescriptor(properties, key);
24849
- return descriptor !== void 0 && (!enumerable || descriptor.enumerable === true);
24850
- }
24851
- function typeTag(value) {
24852
- if (isSandboxBox(value)) value = boxedValue(value);
24853
- if (value === void 0) return "Undefined";
24854
- if (value === null) return "Null";
24855
- if (typeof value === "string") return "String";
24856
- if (typeof value === "number") return "Number";
24857
- if (typeof value === "boolean") return "Boolean";
24858
- if (isSandboxClosure(value)) {
24859
- while (value.boundTarget !== void 0) value = value.boundTarget;
24860
- return value.generator ? "GeneratorFunction" : value.async ? "AsyncFunction" : "Function";
24861
- }
24862
- if (Array.isArray(value)) return "Array";
24863
- if (isSandboxDate(value)) return "Date";
24864
- if (isSandboxErrorConstructorInstance(value, "Error")) return "Error";
24865
- if (isSandboxRegex(value)) return "RegExp";
24866
- if (isSandboxMap(value)) return "Map";
24867
- if (isSandboxSet(value)) return "Set";
24868
- if (isSandboxCollectionIterator(value)) return collectionIteratorState(value).collectionKind === "map" ? "Map Iterator" : "Set Iterator";
24869
- if (isSandboxPromise(value)) return "Promise";
24870
- if (isSandboxGenerator(value)) return "Generator";
24871
- if (isFloat32Array(value)) return "Float32Array";
24872
- return "Object";
24873
- }
24874
-
24875
25090
  // packages/safe-js/src/interp/globals/numeric-parsers.ts
24876
25091
  function createNumericParsers(budget) {
24877
25092
  return {
@@ -25477,12 +25692,17 @@ function createPrimitiveConstructor(options, budget) {
25477
25692
  const prototype = createSandboxBox(initial);
25478
25693
  const allocate = (value, context) => {
25479
25694
  const box = createSandboxBox(value);
25695
+ const finish = (prototype2) => {
25696
+ if (typeof prototype2 === "object" && prototype2 !== null)
25697
+ setSandboxPrototype(box, prototype2, budget);
25698
+ budget.chargeDataUsage(measureSandboxData([box]));
25699
+ return box;
25700
+ };
25480
25701
  if (context?.newTarget !== void 0 && context.newTarget !== constructor) {
25481
25702
  const prototype2 = context.getProperty(context.newTarget, "prototype");
25482
- if (typeof prototype2 === "object" && prototype2 !== null) setSandboxPrototype(box, prototype2, budget);
25703
+ return prototype2 instanceof Promise ? prototype2.then(finish) : finish(prototype2);
25483
25704
  }
25484
- budget.chargeDataUsage(measureSandboxData([box]));
25485
- return box;
25705
+ return finish(void 0);
25486
25706
  };
25487
25707
  const constructor = createSandboxClosure({
25488
25708
  guest: true,
@@ -25543,147 +25763,185 @@ function createPrimitiveConstructor(options, budget) {
25543
25763
  // packages/safe-js/src/interp/globals/object-array.ts
25544
25764
  function createObjectArrayGlobals(options) {
25545
25765
  return {
25546
- Object: createObjectGlobal({
25547
- keys: createSandboxClosure({
25548
- sandbox: true,
25549
- call: ([value]) => budgetSandboxValue2(getOwnEnumerableKeys(value), options.budget),
25550
- name: "keys"
25551
- }),
25552
- values: createSandboxClosure({
25553
- sandbox: true,
25554
- call: ([value]) => allocateProducedSandboxValue(getOwnEnumerableValues(value), options.budget),
25555
- name: "values"
25556
- }),
25557
- entries: createSandboxClosure({
25558
- sandbox: true,
25559
- call: ([value]) => allocateProducedSandboxValue(ownEnumerableSandboxEntries(value), options.budget),
25560
- name: "entries"
25561
- }),
25562
- hasOwn: createSandboxClosure({
25563
- sandbox: true,
25564
- call: ([value, key], context) => {
25565
- if (value === null || value === void 0) throw new TypeError("Cannot convert undefined or null to object.");
25566
- const name = sandboxString(key, options.budget, context);
25567
- return typeof name === "string" ? hasOwnSandboxProperty(value, name, false) : name.then((property) => hasOwnSandboxProperty(value, property, false));
25568
- },
25569
- name: "hasOwn"
25570
- }),
25571
- getOwnPropertyDescriptor: createSandboxClosure({
25572
- sandbox: true,
25573
- call: async ([value, key], context) => {
25574
- const descriptor = Object.getOwnPropertyDescriptor(objectProperties(value), await sandboxString(key, options.budget, context));
25575
- if (descriptor !== void 0 && !("value" in descriptor)) throw new TypeError("Only data property descriptors are supported.");
25576
- return descriptor === void 0 ? void 0 : allocateProducedSandboxValue(descriptor, options.budget);
25577
- },
25578
- name: "getOwnPropertyDescriptor"
25579
- }),
25580
- getOwnPropertyNames: createSandboxClosure({
25581
- sandbox: true,
25582
- call: ([value]) => budgetSandboxValue2(Object.getOwnPropertyNames(objectProperties(value)), options.budget),
25583
- name: "getOwnPropertyNames"
25584
- }),
25585
- defineProperty: createSandboxClosure({
25586
- sandbox: true,
25587
- call: async ([value, key, descriptor], context) => {
25588
- defineDataProperty(value, await sandboxString(key, options.budget, context), dataDescriptor(descriptor), options.budget);
25589
- return value;
25590
- },
25591
- name: "defineProperty"
25592
- }),
25593
- defineProperties: createSandboxClosure({
25594
- sandbox: true,
25595
- call: ([value, descriptors]) => {
25596
- const properties = ownEnumerableSandboxEntries(descriptors).map(([key, descriptor]) => [key, dataDescriptor(descriptor)]);
25597
- for (const [key, descriptor] of properties) {
25598
- defineDataProperty(value, key, descriptor, options.budget);
25599
- }
25600
- return value;
25601
- },
25602
- name: "defineProperties"
25603
- }),
25604
- getPrototypeOf: createSandboxClosure({
25605
- sandbox: true,
25606
- call: ([value]) => {
25607
- if (isSandboxDate(value)) return getDatePrototype(value, options.budget, options.compileOwner);
25608
- if (value !== null && value !== void 0 && typeof value !== "object") value = createSandboxBox(value);
25609
- objectProperties(value);
25610
- return getSandboxPrototype(value, options.budget);
25611
- },
25612
- name: "getPrototypeOf"
25613
- }),
25614
- setPrototypeOf: createSandboxClosure({
25615
- sandbox: true,
25616
- call: ([value, prototype]) => {
25617
- objectProperties(value, true);
25618
- if (prototype !== null) objectProperties(prototype);
25619
- setSandboxPrototype(value, prototype, options.budget);
25620
- return value;
25621
- },
25622
- name: "setPrototypeOf"
25623
- }),
25624
- create: createSandboxClosure({
25625
- sandbox: true,
25626
- call: ([prototype, descriptors]) => {
25627
- if (prototype !== null) objectProperties(prototype);
25628
- const value = /* @__PURE__ */ Object.create(null);
25629
- setSandboxPrototype(value, prototype, options.budget);
25630
- if (descriptors !== void 0) {
25631
- const properties = ownEnumerableSandboxEntries(descriptors).map(([key, descriptor]) => [key, dataDescriptor(descriptor)]);
25632
- for (const [key, descriptor] of properties) {
25633
- defineDataProperty(value, key, descriptor, options.budget);
25634
- }
25635
- }
25636
- return allocateProducedSandboxValue(value, options.budget);
25637
- },
25638
- name: "create"
25639
- }),
25640
- is: createSandboxClosure({
25641
- sandbox: true,
25642
- call: ([left, right]) => Reflect.apply(Object.is, Object, [left, right]),
25643
- name: "is"
25644
- }),
25645
- fromEntries: createSandboxClosure({
25646
- sandbox: true,
25647
- call: ([value], context) => {
25648
- const iterator = getSandboxIterator(value, options.budget, context);
25649
- if (iterator === void 0) {
25650
- throw new TypeError("Object.fromEntries requires an iterable.");
25651
- }
25652
- if (context === void 0 && !iterator.generator && !iterator.asynchronous) {
25766
+ Object: createObjectGlobal(
25767
+ {
25768
+ keys: createSandboxClosure({
25769
+ sandbox: true,
25770
+ call: ([value]) => budgetSandboxValue2(ownEnumerableSandboxKeys(value), options.budget),
25771
+ name: "keys"
25772
+ }),
25773
+ values: createSandboxClosure({
25774
+ sandbox: true,
25775
+ call: ([value], context) => context === void 0 ? allocateProducedSandboxValue(
25776
+ ownEnumerableSandboxEntries(value).map(([, entry]) => entry),
25777
+ options.budget
25778
+ ) : getOwnEnumerableEntries(value, options.budget, context).then(
25779
+ (entries) => allocateProducedSandboxValue(
25780
+ entries.map(([, entry]) => entry),
25781
+ options.budget
25782
+ )
25783
+ ),
25784
+ name: "values"
25785
+ }),
25786
+ entries: createSandboxClosure({
25787
+ sandbox: true,
25788
+ call: ([value], context) => context === void 0 ? allocateProducedSandboxValue(ownEnumerableSandboxEntries(value), options.budget) : getOwnEnumerableEntries(value, options.budget, context).then(
25789
+ (entries) => allocateProducedSandboxValue(entries, options.budget)
25790
+ ),
25791
+ name: "entries"
25792
+ }),
25793
+ hasOwn: createSandboxClosure({
25794
+ sandbox: true,
25795
+ call: ([value, key], context) => {
25796
+ if (value === null || value === void 0)
25797
+ throw new TypeError("Cannot convert undefined or null to object.");
25798
+ const name = sandboxString(key, options.budget, context);
25799
+ return typeof name === "string" ? hasOwnSandboxProperty(value, name, false) : name.then((property) => hasOwnSandboxProperty(value, property, false));
25800
+ },
25801
+ name: "hasOwn"
25802
+ }),
25803
+ getOwnPropertyDescriptor: createSandboxClosure({
25804
+ sandbox: true,
25805
+ call: async ([value, key], context) => {
25806
+ const descriptor = Object.getOwnPropertyDescriptor(
25807
+ objectProperties(value),
25808
+ await sandboxString(key, options.budget, context)
25809
+ );
25810
+ if (descriptor === void 0) return void 0;
25653
25811
  return allocateProducedSandboxValue(
25654
- Object.setPrototypeOf(
25655
- Reflect.apply(Object.fromEntries, Object, [{ [Symbol.iterator]: () => iterator }]),
25656
- null
25657
- ),
25812
+ exposePropertyDescriptor(descriptor),
25658
25813
  options.budget
25659
25814
  );
25660
- }
25661
- return objectFromSandboxEntries(value, iterator, options.budget, context);
25662
- },
25663
- name: "fromEntries"
25664
- }),
25665
- freeze: createSandboxClosure({
25666
- sandbox: true,
25667
- call: ([value]) => {
25668
- if (isGuestHostObject(value)) throw new TypeError("Live host objects cannot be frozen.");
25669
- if (typeof value === "object" && value !== null) {
25670
- Object.freeze(isGuestClosure(value) ? materializeFunctionProperties(value) : value);
25671
- }
25672
- return value;
25673
- },
25674
- name: "freeze"
25675
- }),
25676
- isFrozen: createSandboxClosure({
25677
- sandbox: true,
25678
- call: ([value]) => Object.isFrozen(isGuestClosure(value) ? materializeFunctionProperties(value) : value),
25679
- name: "isFrozen"
25680
- }),
25681
- assign: createSandboxClosure({
25682
- sandbox: true,
25683
- call: ([target, ...sources]) => assignSandboxValues(target, sources, options.budget),
25684
- name: "assign"
25685
- })
25686
- }, options.budget),
25815
+ },
25816
+ name: "getOwnPropertyDescriptor"
25817
+ }),
25818
+ getOwnPropertyDescriptors: createSandboxClosure({
25819
+ sandbox: true,
25820
+ call: ([value]) => {
25821
+ const descriptors = /* @__PURE__ */ Object.create(null);
25822
+ for (const [key, descriptor] of Object.entries(
25823
+ Object.getOwnPropertyDescriptors(objectProperties(value))
25824
+ ))
25825
+ defineOwnDataProperty(descriptors, key, exposePropertyDescriptor(descriptor));
25826
+ return allocateProducedSandboxValue(descriptors, options.budget);
25827
+ },
25828
+ name: "getOwnPropertyDescriptors"
25829
+ }),
25830
+ getOwnPropertyNames: createSandboxClosure({
25831
+ sandbox: true,
25832
+ call: ([value]) => budgetSandboxValue2(Object.getOwnPropertyNames(objectProperties(value)), options.budget),
25833
+ name: "getOwnPropertyNames"
25834
+ }),
25835
+ defineProperty: createSandboxClosure({
25836
+ sandbox: true,
25837
+ call: async ([value, key, descriptor], context) => {
25838
+ objectProperties(value, true);
25839
+ const property = await sandboxString(key, options.budget, context);
25840
+ defineDataProperty(
25841
+ value,
25842
+ property,
25843
+ await propertyDescriptor(descriptor, options.budget, context),
25844
+ options.budget
25845
+ );
25846
+ return value;
25847
+ },
25848
+ name: "defineProperty"
25849
+ }),
25850
+ defineProperties: createSandboxClosure({
25851
+ sandbox: true,
25852
+ call: async ([value, descriptors], context) => {
25853
+ await definePropertiesFromObject(value, descriptors, options.budget, context);
25854
+ return value;
25855
+ },
25856
+ name: "defineProperties"
25857
+ }),
25858
+ getPrototypeOf: createSandboxClosure({
25859
+ sandbox: true,
25860
+ call: ([value]) => {
25861
+ if (isSandboxDate(value))
25862
+ return getDatePrototype(value, options.budget, options.compileOwner);
25863
+ if (value !== null && value !== void 0 && typeof value !== "object")
25864
+ value = createSandboxBox(value);
25865
+ objectProperties(value);
25866
+ return getSandboxPrototype(value, options.budget);
25867
+ },
25868
+ name: "getPrototypeOf"
25869
+ }),
25870
+ setPrototypeOf: createSandboxClosure({
25871
+ sandbox: true,
25872
+ call: ([value, prototype]) => {
25873
+ objectProperties(value, true);
25874
+ if (prototype !== null) objectProperties(prototype);
25875
+ setSandboxPrototype(value, prototype, options.budget);
25876
+ return value;
25877
+ },
25878
+ name: "setPrototypeOf"
25879
+ }),
25880
+ create: createSandboxClosure({
25881
+ sandbox: true,
25882
+ call: async ([prototype, descriptors], context) => {
25883
+ if (prototype !== null) objectProperties(prototype);
25884
+ const value = /* @__PURE__ */ Object.create(null);
25885
+ setSandboxPrototype(value, prototype, options.budget);
25886
+ if (descriptors !== void 0) {
25887
+ await definePropertiesFromObject(value, descriptors, options.budget, context);
25888
+ }
25889
+ return allocateProducedSandboxValue(value, options.budget);
25890
+ },
25891
+ name: "create"
25892
+ }),
25893
+ is: createSandboxClosure({
25894
+ sandbox: true,
25895
+ call: ([left, right]) => Reflect.apply(Object.is, Object, [left, right]),
25896
+ name: "is"
25897
+ }),
25898
+ fromEntries: createSandboxClosure({
25899
+ sandbox: true,
25900
+ call: ([value], context) => {
25901
+ const iterator = getSandboxIterator(value, options.budget, context);
25902
+ if (iterator === void 0) {
25903
+ throw new TypeError("Object.fromEntries requires an iterable.");
25904
+ }
25905
+ if (context === void 0 && !iterator.generator && !iterator.asynchronous) {
25906
+ return allocateProducedSandboxValue(
25907
+ Object.setPrototypeOf(
25908
+ Reflect.apply(Object.fromEntries, Object, [
25909
+ { [Symbol.iterator]: () => iterator }
25910
+ ]),
25911
+ null
25912
+ ),
25913
+ options.budget
25914
+ );
25915
+ }
25916
+ return objectFromSandboxEntries(value, iterator, options.budget, context);
25917
+ },
25918
+ name: "fromEntries"
25919
+ }),
25920
+ freeze: createSandboxClosure({
25921
+ sandbox: true,
25922
+ call: ([value]) => {
25923
+ if (isGuestHostObject(value))
25924
+ throw new TypeError("Live host objects cannot be frozen.");
25925
+ if (typeof value === "object" && value !== null) {
25926
+ Object.freeze(isGuestClosure(value) ? materializeFunctionProperties(value) : value);
25927
+ }
25928
+ return value;
25929
+ },
25930
+ name: "freeze"
25931
+ }),
25932
+ isFrozen: createSandboxClosure({
25933
+ sandbox: true,
25934
+ call: ([value]) => Object.isFrozen(isGuestClosure(value) ? materializeFunctionProperties(value) : value),
25935
+ name: "isFrozen"
25936
+ }),
25937
+ assign: createSandboxClosure({
25938
+ sandbox: true,
25939
+ call: ([target, ...sources], context) => assignSandboxValues(target, sources, options.budget, context),
25940
+ name: "assign"
25941
+ })
25942
+ },
25943
+ options.budget
25944
+ ),
25687
25945
  Array: createSandboxClosure({
25688
25946
  sandbox: true,
25689
25947
  call: (args) => createArrayFromConstructorArgs(args, options.budget),
@@ -25707,66 +25965,75 @@ function createObjectArrayGlobals(options) {
25707
25965
  })
25708
25966
  }
25709
25967
  }),
25710
- String: createPrimitiveConstructor({
25711
- call: (args, context) => sandboxString(args.length === 0 ? "" : args[0], options.budget, context),
25712
- name: "String",
25713
- properties: {
25714
- raw: createSandboxClosure({
25715
- sandbox: true,
25716
- call: (args) => stringRaw(args, options.budget),
25717
- name: "raw"
25718
- }),
25719
- fromCharCode: createSandboxClosure({
25720
- sandbox: true,
25721
- call: (args) => options.budget.allocateString(Reflect.apply(String.fromCharCode, String, [...args])),
25722
- name: "fromCharCode"
25723
- }),
25724
- fromCodePoint: createSandboxClosure({
25725
- sandbox: true,
25726
- call: (args) => options.budget.allocateString(Reflect.apply(String.fromCodePoint, String, [...args])),
25727
- name: "fromCodePoint"
25728
- })
25729
- }
25730
- }, options.budget),
25731
- Number: createPrimitiveConstructor({
25732
- call: (args, context) => sandboxNumber(args.length === 0 ? 0 : args[0], options.budget, context),
25733
- name: "Number",
25734
- properties: {
25735
- isFinite: createSandboxClosure({
25736
- sandbox: true,
25737
- call: ([value]) => typeof value === "number" && Number.isFinite(value),
25738
- name: "isFinite"
25739
- }),
25740
- isNaN: createSandboxClosure({
25741
- sandbox: true,
25742
- call: ([value]) => typeof value === "number" && Number.isNaN(value),
25743
- name: "isNaN"
25744
- }),
25745
- isInteger: createSandboxClosure({
25746
- sandbox: true,
25747
- call: ([value]) => typeof value === "number" && Number.isInteger(value),
25748
- name: "isInteger"
25749
- }),
25750
- ...createNumericParsers(options.budget),
25751
- isSafeInteger: createSandboxClosure({
25752
- sandbox: true,
25753
- call: ([value]) => typeof value === "number" && Number.isSafeInteger(value),
25754
- name: "isSafeInteger"
25755
- }),
25756
- MAX_SAFE_INTEGER: Number.MAX_SAFE_INTEGER,
25757
- MIN_SAFE_INTEGER: Number.MIN_SAFE_INTEGER,
25758
- EPSILON: Number.EPSILON,
25759
- MAX_VALUE: Number.MAX_VALUE,
25760
- MIN_VALUE: Number.MIN_VALUE,
25761
- NaN: Number.NaN,
25762
- NEGATIVE_INFINITY: Number.NEGATIVE_INFINITY,
25763
- POSITIVE_INFINITY: Number.POSITIVE_INFINITY
25764
- }
25765
- }, options.budget),
25766
- Boolean: createPrimitiveConstructor({
25767
- call: ([value]) => Boolean(value),
25768
- name: "Boolean"
25769
- }, options.budget)
25968
+ String: createPrimitiveConstructor(
25969
+ {
25970
+ call: (args, context) => sandboxString(args.length === 0 ? "" : args[0], options.budget, context),
25971
+ name: "String",
25972
+ properties: {
25973
+ raw: createSandboxClosure({
25974
+ sandbox: true,
25975
+ call: (args, context) => stringRaw(args, options.budget, context),
25976
+ name: "raw"
25977
+ }),
25978
+ fromCharCode: createSandboxClosure({
25979
+ sandbox: true,
25980
+ call: (args) => options.budget.allocateString(Reflect.apply(String.fromCharCode, String, [...args])),
25981
+ name: "fromCharCode"
25982
+ }),
25983
+ fromCodePoint: createSandboxClosure({
25984
+ sandbox: true,
25985
+ call: (args) => options.budget.allocateString(Reflect.apply(String.fromCodePoint, String, [...args])),
25986
+ name: "fromCodePoint"
25987
+ })
25988
+ }
25989
+ },
25990
+ options.budget
25991
+ ),
25992
+ Number: createPrimitiveConstructor(
25993
+ {
25994
+ call: (args, context) => sandboxNumber(args.length === 0 ? 0 : args[0], options.budget, context),
25995
+ name: "Number",
25996
+ properties: {
25997
+ isFinite: createSandboxClosure({
25998
+ sandbox: true,
25999
+ call: ([value]) => typeof value === "number" && Number.isFinite(value),
26000
+ name: "isFinite"
26001
+ }),
26002
+ isNaN: createSandboxClosure({
26003
+ sandbox: true,
26004
+ call: ([value]) => typeof value === "number" && Number.isNaN(value),
26005
+ name: "isNaN"
26006
+ }),
26007
+ isInteger: createSandboxClosure({
26008
+ sandbox: true,
26009
+ call: ([value]) => typeof value === "number" && Number.isInteger(value),
26010
+ name: "isInteger"
26011
+ }),
26012
+ ...createNumericParsers(options.budget),
26013
+ isSafeInteger: createSandboxClosure({
26014
+ sandbox: true,
26015
+ call: ([value]) => typeof value === "number" && Number.isSafeInteger(value),
26016
+ name: "isSafeInteger"
26017
+ }),
26018
+ MAX_SAFE_INTEGER: Number.MAX_SAFE_INTEGER,
26019
+ MIN_SAFE_INTEGER: Number.MIN_SAFE_INTEGER,
26020
+ EPSILON: Number.EPSILON,
26021
+ MAX_VALUE: Number.MAX_VALUE,
26022
+ MIN_VALUE: Number.MIN_VALUE,
26023
+ NaN: Number.NaN,
26024
+ NEGATIVE_INFINITY: Number.NEGATIVE_INFINITY,
26025
+ POSITIVE_INFINITY: Number.POSITIVE_INFINITY
26026
+ }
26027
+ },
26028
+ options.budget
26029
+ ),
26030
+ Boolean: createPrimitiveConstructor(
26031
+ {
26032
+ call: ([value]) => Boolean(value),
26033
+ name: "Boolean"
26034
+ },
26035
+ options.budget
26036
+ )
25770
26037
  };
25771
26038
  }
25772
26039
  async function objectFromSandboxEntries(items, iterator, budget, context) {
@@ -25776,7 +26043,15 @@ async function objectFromSandboxEntries(items, iterator, budget, context) {
25776
26043
  let value;
25777
26044
  let failure;
25778
26045
  const retained = {};
25779
- budget.setRetainedValues(retained, () => [items, iterator.retainedValue, object, entry, key, value, failure]);
26046
+ budget.setRetainedValues(retained, () => [
26047
+ items,
26048
+ iterator.retainedValue,
26049
+ object,
26050
+ entry,
26051
+ key,
26052
+ value,
26053
+ failure
26054
+ ]);
25780
26055
  const checkData = createDataCheckpoint(budget, context);
25781
26056
  const closeOnThrow = async (error) => {
25782
26057
  failure = isCapturedException(error) ? error.reason : error;
@@ -25805,8 +26080,8 @@ async function objectFromSandboxEntries(items, iterator, budget, context) {
25805
26080
  if (typeof entry !== "object" || entry === null) {
25806
26081
  throw new TypeError("Object.fromEntries requires entry objects.");
25807
26082
  }
25808
- key = context?.getProperty !== void 0 ? context.getProperty(entry, 0) : getSandboxDataProperty(entry, 0, budget);
25809
- value = context?.getProperty !== void 0 ? context.getProperty(entry, 1) : getSandboxDataProperty(entry, 1, budget);
26083
+ key = context?.getProperty !== void 0 ? await context.getProperty(entry, 0) : getSandboxDataProperty(entry, 0, budget);
26084
+ value = context?.getProperty !== void 0 ? await context.getProperty(entry, 1) : getSandboxDataProperty(entry, 1, budget);
25810
26085
  const property = await sandboxString(key, budget, context);
25811
26086
  const growth = property.length + 1 + (budget.limits.dataSize === void 0 ? 0 : measureSandboxData([value]));
25812
26087
  budget.visitNode();
@@ -25823,7 +26098,7 @@ async function objectFromSandboxEntries(items, iterator, budget, context) {
25823
26098
  budget.setRetainedValues(retained, void 0);
25824
26099
  }
25825
26100
  }
25826
- function assignSandboxValues(target, sources, budget) {
26101
+ function assignSandboxValues(target, sources, budget, context) {
25827
26102
  if (target === null || target === void 0) {
25828
26103
  throw new TypeError("Object.assign(target, ...sources) requires a non-null target.");
25829
26104
  }
@@ -25834,50 +26109,120 @@ function assignSandboxValues(target, sources, budget) {
25834
26109
  if (!isGuestClosure(target) && !isAssignableSandboxTarget(target)) {
25835
26110
  throw new TypeError("Object.assign(target, ...sources) requires an object or array target.");
25836
26111
  }
25837
- for (const source of sources) {
25838
- if (source === null || source === void 0) {
25839
- continue;
25840
- }
25841
- for (const [key, value] of ownEnumerableSandboxEntries(source)) {
25842
- setSandboxProperty(target, key, value, budget);
26112
+ if (context === void 0) {
26113
+ for (const source of sources) {
26114
+ if (source === null || source === void 0) continue;
26115
+ for (const [key, value] of ownEnumerableSandboxEntries(source))
26116
+ setSandboxProperty(target, key, value, budget);
25843
26117
  }
26118
+ return target;
25844
26119
  }
25845
- return target;
26120
+ return (async () => {
26121
+ const release = retainValues(budget, () => [target, ...sources]);
26122
+ try {
26123
+ for (const source of sources) {
26124
+ if (source === null || source === void 0) continue;
26125
+ for (const key of ownEnumerableSandboxKeys(source)) {
26126
+ if (!hasOwnSandboxProperty(source, key, true)) continue;
26127
+ const value = await (context.getProperty !== void 0 ? context.getProperty(source, key) : getSandboxDataProperty(source, key, budget));
26128
+ await setSandboxProperty(target, key, value, budget, true, context);
26129
+ }
26130
+ }
26131
+ return target;
26132
+ } finally {
26133
+ release();
26134
+ }
26135
+ })();
25846
26136
  }
25847
26137
  function objectProperties(value, mutable = false) {
25848
26138
  if (isSandboxDate(value)) {
25849
26139
  if (mutable) throw new TypeError("Date own properties and prototypes are not supported.");
25850
26140
  return value;
25851
26141
  }
25852
- if (isGuestHostObject(value)) throw new TypeError("Live host object descriptors are not supported.");
26142
+ if (isGuestHostObject(value))
26143
+ throw new TypeError("Live host object descriptors are not supported.");
25853
26144
  if (isGuestClosure(value)) return materializeFunctionProperties(value);
25854
26145
  if (isSandboxClosure(value)) {
25855
26146
  if (mutable) throw new TypeError("Host function properties are read only.");
25856
26147
  return value.properties ?? /* @__PURE__ */ Object.create(null);
25857
26148
  }
25858
- if (!isAssignableSandboxTarget(value)) throw new TypeError("Expected a sandbox object or function.");
26149
+ if (!isAssignableSandboxTarget(value))
26150
+ throw new TypeError("Expected a sandbox object or function.");
25859
26151
  return value;
25860
26152
  }
25861
- function dataDescriptor(input) {
25862
- const source = objectProperties(input);
26153
+ function exposePropertyDescriptor(descriptor) {
26154
+ return "value" in descriptor ? descriptor : {
26155
+ get: accessorClosure(descriptor.get),
26156
+ set: accessorClosure(descriptor.set),
26157
+ enumerable: descriptor.enumerable,
26158
+ configurable: descriptor.configurable
26159
+ };
26160
+ }
26161
+ async function propertyDescriptor(input, budget, context) {
26162
+ objectProperties(input);
25863
26163
  const descriptor = {};
25864
- for (const field of ["get", "set", "value", "writable", "enumerable", "configurable"]) {
25865
- const entry = Object.getOwnPropertyDescriptor(source, field);
25866
- if (entry === void 0) continue;
25867
- if (!("value" in entry) || field === "get" || field === "set") {
25868
- throw new TypeError("Only data property descriptors are supported.");
26164
+ const release = retainValues(budget, () => [
26165
+ input,
26166
+ descriptor.value,
26167
+ ...retainedAccessorClosures(descriptor)
26168
+ ]);
26169
+ try {
26170
+ for (const field of [
26171
+ "enumerable",
26172
+ "configurable",
26173
+ "value",
26174
+ "writable",
26175
+ "get",
26176
+ "set"
26177
+ ]) {
26178
+ if (getSandboxPropertyDescriptor(input, field, budget) === void 0 && !hasOwnSandboxProperty(input, field, false))
26179
+ continue;
26180
+ const value = await (context?.getProperty !== void 0 ? context.getProperty(input, field) : getSandboxDataProperty(input, field, budget));
26181
+ if (field === "get" || field === "set") {
26182
+ if (value !== void 0 && !isSandboxClosure(value))
26183
+ throw new TypeError("Accessor must be a function or undefined.");
26184
+ descriptor[field] = value === void 0 ? void 0 : accessorAdapter(value, field);
26185
+ } else if (field === "value") {
26186
+ descriptor.value = value;
26187
+ } else {
26188
+ descriptor[field] = Boolean(value);
26189
+ }
25869
26190
  }
25870
- if (field === "value") descriptor.value = entry.value;
25871
- else descriptor[field] = Boolean(entry.value);
26191
+ if (("get" in descriptor || "set" in descriptor) && ("value" in descriptor || "writable" in descriptor))
26192
+ throw new TypeError("A property cannot be both a data property and an accessor.");
26193
+ return descriptor;
26194
+ } finally {
26195
+ release();
26196
+ }
26197
+ }
26198
+ async function definePropertiesFromObject(target, descriptors, budget, context) {
26199
+ objectProperties(target, true);
26200
+ const properties = [];
26201
+ const release = retainValues(budget, () => [
26202
+ target,
26203
+ descriptors,
26204
+ properties,
26205
+ ...properties.flatMap(([, descriptor]) => retainedAccessorClosures(descriptor))
26206
+ ]);
26207
+ try {
26208
+ for (const key of ownEnumerableSandboxKeys(descriptors)) {
26209
+ if (!hasOwnSandboxProperty(descriptors, key, true)) continue;
26210
+ const descriptor = await (context?.getProperty !== void 0 ? context.getProperty(descriptors, key) : getSandboxDataProperty(descriptors, key, budget));
26211
+ properties.push([key, await propertyDescriptor(descriptor, budget, context)]);
26212
+ }
26213
+ for (const [key, descriptor] of properties) defineDataProperty(target, key, descriptor, budget);
26214
+ } finally {
26215
+ release();
25872
26216
  }
25873
- return descriptor;
25874
26217
  }
25875
26218
  function defineDataProperty(target, key, descriptor, budget) {
25876
26219
  budget.visitNode();
25877
- if (isFloat32Array(target)) throw new TypeError("Typed array property descriptors are not supported.");
26220
+ if (isFloat32Array(target))
26221
+ throw new TypeError("Typed array property descriptors are not supported.");
25878
26222
  const properties = objectProperties(target, true);
25879
26223
  if (Array.isArray(properties)) {
25880
- if (key === "length" && "value" in descriptor) budget.allocateArrayLength(Number(descriptor.value));
26224
+ if (key === "length" && "value" in descriptor)
26225
+ budget.allocateArrayLength(Number(descriptor.value));
25881
26226
  else {
25882
26227
  const index = Number(key);
25883
26228
  if (Number.isInteger(index) && index >= 0 && index < 4294967295 && String(index) === key) {
@@ -25906,7 +26251,15 @@ async function arrayFromSandboxValues(args, budget, context) {
25906
26251
  let currentValue;
25907
26252
  let failure;
25908
26253
  const retained = {};
25909
- budget.setRetainedValues(retained, () => [items, iterator?.retainedValue, mapFn, constructor, result, currentValue, failure]);
26254
+ budget.setRetainedValues(retained, () => [
26255
+ items,
26256
+ iterator?.retainedValue,
26257
+ mapFn,
26258
+ constructor,
26259
+ result,
26260
+ currentValue,
26261
+ failure
26262
+ ]);
25910
26263
  const checkData = createDataCheckpoint(budget, context);
25911
26264
  const closeOnThrow = async (error) => {
25912
26265
  failure = isCapturedException(error) ? error.reason : error;
@@ -25920,30 +26273,46 @@ async function arrayFromSandboxValues(args, budget, context) {
25920
26273
  try {
25921
26274
  let length = 0;
25922
26275
  if (iterator === void 0) {
25923
- const number = await sandboxNumber(read("length"), budget, context);
26276
+ const number = await sandboxNumber(await read("length"), budget, context);
25924
26277
  length = Number.isNaN(number) || number <= 0 ? 0 : Math.min(Math.trunc(number), Number.MAX_SAFE_INTEGER);
25925
26278
  }
25926
- result = isSandboxClosure(constructor) && constructor.construct !== void 0 ? await invokeBuiltinClosure(constructor, iterator === void 0 ? [length] : [], budget, context, void 0, true) : createArrayFromConstructorArgs([length], budget);
26279
+ result = isSandboxClosure(constructor) && constructor.construct !== void 0 ? await invokeBuiltinClosure(
26280
+ constructor,
26281
+ iterator === void 0 ? [length] : [],
26282
+ budget,
26283
+ context,
26284
+ void 0,
26285
+ true
26286
+ ) : createArrayFromConstructorArgs([length], budget);
25927
26287
  checkData(result, 0, true);
25928
26288
  let index = 0;
25929
26289
  while (iterator !== void 0 || index < length) {
25930
26290
  try {
25931
26291
  budget.visitNode();
25932
- if (iterator !== void 0 && index >= Number.MAX_SAFE_INTEGER) throw new TypeError("Array.from input is too long.");
26292
+ if (iterator !== void 0 && index >= Number.MAX_SAFE_INTEGER)
26293
+ throw new TypeError("Array.from input is too long.");
25933
26294
  } catch (error) {
25934
26295
  await closeOnThrow(error);
25935
26296
  }
25936
26297
  if (iterator !== void 0) {
25937
26298
  const next = await iterator.next();
25938
- if (typeof next !== "object" || next === null) throw new TypeError("Iterator result must be an object.");
26299
+ if (typeof next !== "object" || next === null)
26300
+ throw new TypeError("Iterator result must be an object.");
25939
26301
  if (next.done) break;
25940
26302
  currentValue = next.value;
25941
26303
  } else {
25942
- currentValue = read(index);
26304
+ currentValue = await read(index);
25943
26305
  }
25944
26306
  try {
25945
26307
  if (Array.isArray(result)) budget.allocateArrayLength(index + 1);
25946
- if (mapFn !== void 0) currentValue = await invokeBuiltinClosure(mapFn, [currentValue, index], budget, context, thisValue);
26308
+ if (mapFn !== void 0)
26309
+ currentValue = await invokeBuiltinClosure(
26310
+ mapFn,
26311
+ [currentValue, index],
26312
+ budget,
26313
+ context,
26314
+ thisValue
26315
+ );
25947
26316
  const key = String(index);
25948
26317
  const growth = key.length + 1 + (Array.isArray(result) ? Math.max(0, index + 1 - result.length) : 0) + (budget.limits.dataSize === void 0 ? 0 : measureSandboxData([currentValue]));
25949
26318
  budget.visitNode();
@@ -25981,19 +26350,60 @@ function createArrayFromConstructorArgs(args, budget) {
25981
26350
  release();
25982
26351
  }
25983
26352
  }
25984
- function getOwnEnumerableKeys(value) {
25985
- if (isGuestHostObject(value)) return getHostObjectKeys(value);
25986
- return ownEnumerableSandboxEntries(value).map(([key]) => key);
25987
- }
25988
- function getOwnEnumerableValues(value) {
25989
- return ownEnumerableSandboxEntries(value).map(([, entryValue]) => entryValue);
26353
+ async function getOwnEnumerableEntries(value, budget, context) {
26354
+ const entries = [];
26355
+ const release = retainValues(budget, () => [value, entries]);
26356
+ try {
26357
+ for (const key of ownEnumerableSandboxKeys(value)) {
26358
+ if (!hasOwnSandboxProperty(value, key, true)) continue;
26359
+ entries.push([
26360
+ key,
26361
+ await (context?.getProperty !== void 0 ? context.getProperty(value, key) : getSandboxDataProperty(value, key, budget))
26362
+ ]);
26363
+ }
26364
+ return entries;
26365
+ } finally {
26366
+ release();
26367
+ }
25990
26368
  }
25991
26369
  function budgetSandboxValue2(value, budget) {
25992
26370
  const sandboxValue = deepCopyToSandbox(value);
25993
26371
  return allocateProducedSandboxValue(sandboxValue, budget);
25994
26372
  }
25995
- function stringRaw(args, budget) {
26373
+ function stringRaw(args, budget, context) {
25996
26374
  const [template, ...substitutions] = args;
26375
+ if (context?.getProperty !== void 0)
26376
+ return (async () => {
26377
+ if (template === null || template === void 0)
26378
+ throw new TypeError("String.raw requires a template object.");
26379
+ const raw2 = await context.getProperty(template, "raw");
26380
+ if (raw2 === null || raw2 === void 0)
26381
+ throw new TypeError("String.raw requires raw strings.");
26382
+ const number = await sandboxNumber(
26383
+ await context.getProperty(raw2, "length"),
26384
+ budget,
26385
+ context
26386
+ );
26387
+ const length = Number.isNaN(number) || number <= 0 ? 0 : Math.min(Math.trunc(number), Number.MAX_SAFE_INTEGER);
26388
+ let result2 = "";
26389
+ const retained = {};
26390
+ budget.setRetainedValues(retained, () => [raw2, result2]);
26391
+ try {
26392
+ for (let index = 0; index < length; index++) {
26393
+ budget.visitNode();
26394
+ result2 = budget.allocateString(
26395
+ result2 + await sandboxString(await context.getProperty(raw2, index), budget, context)
26396
+ );
26397
+ if (index + 1 < length && index < substitutions.length)
26398
+ result2 = budget.allocateString(
26399
+ result2 + await sandboxString(substitutions[index], budget, context)
26400
+ );
26401
+ }
26402
+ return result2;
26403
+ } finally {
26404
+ budget.setRetainedValues(retained, void 0);
26405
+ }
26406
+ })();
25997
26407
  const raw = getTemplateRawParts(template);
25998
26408
  let result = "";
25999
26409
  for (let index = 0; index < raw.length; index += 1) {
@@ -26030,7 +26440,7 @@ async function evaluateClass(node, context, evaluateNode2, callContext) {
26030
26440
  parent = result.value;
26031
26441
  if (parent !== null && (!isSandboxClosure(parent) || parent.construct === void 0))
26032
26442
  throw new TypeError("Class extends value is not a constructor or null.");
26033
- prototypeParent = parent === null ? null : callContext.getProperty(parent, "prototype");
26443
+ prototypeParent = parent === null ? null : await callContext.getProperty(parent, "prototype");
26034
26444
  if (prototypeParent !== null && typeof prototypeParent !== "object")
26035
26445
  throw new TypeError("Class extends value has an invalid prototype.");
26036
26446
  }
@@ -26070,7 +26480,7 @@ async function evaluateClass(node, context, evaluateNode2, callContext) {
26070
26480
  };
26071
26481
  if (!derived) {
26072
26482
  thisValue = {};
26073
- const targetPrototype = invocation.getProperty(newTarget, "prototype");
26483
+ const targetPrototype = await invocation.getProperty(newTarget, "prototype");
26074
26484
  if (typeof targetPrototype === "object" && targetPrototype !== null)
26075
26485
  setSandboxPrototype(thisValue, targetPrototype, context.budget);
26076
26486
  }
@@ -26129,8 +26539,15 @@ async function evaluateClass(node, context, evaluateNode2, callContext) {
26129
26539
  } else {
26130
26540
  const home = element.static ? constructor : prototype;
26131
26541
  const method = createInterpretedClosure(element.value, classContext, evaluateNode2, home);
26132
- Object.defineProperty(materializeFunctionProperties(method), "name", { value: key });
26133
- Object.defineProperty(element.static ? properties : prototype, key, { value: method, configurable: true, writable: true, enumerable: false });
26542
+ const accessor = element.kind === "get" || element.kind === "set" ? element.kind : void 0;
26543
+ Object.defineProperty(materializeFunctionProperties(method), "name", {
26544
+ value: accessor === void 0 ? key : `${accessor} ${key}`
26545
+ });
26546
+ Object.defineProperty(
26547
+ element.static ? properties : prototype,
26548
+ key,
26549
+ accessor === void 0 ? { value: method, configurable: true, writable: true, enumerable: false } : { [accessor]: accessorAdapter(method, accessor), configurable: true, enumerable: false }
26550
+ );
26134
26551
  }
26135
26552
  }
26136
26553
  if (node.id !== void 0) scope.declare(node.id.name, "const", constructor);
@@ -26215,7 +26632,13 @@ function getArrayMember(value, property, options) {
26215
26632
  return createSandboxClosure({
26216
26633
  sandbox: true,
26217
26634
  name: `Array#${property}`,
26218
- call: (args, context) => callArrayMethod(context?.thisValue, property, args, { ...options, context }, context?.stack ?? [])
26635
+ call: (args, context) => callArrayMethod(
26636
+ context?.thisValue,
26637
+ property,
26638
+ args,
26639
+ { ...options, context },
26640
+ context?.stack ?? []
26641
+ )
26219
26642
  });
26220
26643
  }
26221
26644
  return void 0;
@@ -26231,7 +26654,8 @@ function isArrayMethodName(property) {
26231
26654
  return typeof property === "string" && arrayMethodNames.has(property);
26232
26655
  }
26233
26656
  async function callArrayMethod(receiver, methodName, args, options, stack = []) {
26234
- if (receiver === null || receiver === void 0) throw new TypeError("Array method requires a receiver.");
26657
+ if (receiver === null || receiver === void 0)
26658
+ throw new TypeError("Array method requires a receiver.");
26235
26659
  if (typeof receiver !== "object") {
26236
26660
  receiver = createSandboxBox(receiver);
26237
26661
  options.budget.chargeDataUsage(measureSandboxData([receiver]));
@@ -26268,38 +26692,44 @@ async function callArrayMethod(receiver, methodName, args, options, stack = [])
26268
26692
  }
26269
26693
  }
26270
26694
  async function arrayLikeView(receiver, options) {
26271
- const rawLength = options.context?.getProperty !== void 0 ? options.context.getProperty(receiver, "length") : getSandboxDataProperty(receiver, "length", options.budget);
26695
+ const rawLength = options.context?.getProperty !== void 0 ? await options.context.getProperty(receiver, "length") : getSandboxDataProperty(receiver, "length", options.budget);
26272
26696
  const number = await sandboxNumber(rawLength, options.budget, options.context);
26273
26697
  const length = Number.isNaN(number) || number <= 0 ? 0 : Math.min(Math.trunc(number), Number.MAX_SAFE_INTEGER);
26274
- const view = new Proxy(/* @__PURE__ */ Object.create(null), {
26275
- get: (_target, key) => {
26276
- options.budget.visitNode();
26277
- if (key === "length") return length;
26278
- if (typeof key !== "string") return void 0;
26279
- return options.context?.getProperty !== void 0 ? options.context.getProperty(receiver, key) : getSandboxDataProperty(receiver, key, options.budget);
26280
- },
26281
- has: (_target, key) => {
26282
- options.budget.visitNode();
26283
- if (typeof key === "string" && options.hasProperty !== void 0) return options.hasProperty(receiver, key);
26284
- for (let current = receiver; current !== null; current = getSandboxPrototype(current, options.budget)) {
26698
+ const view = new Proxy(
26699
+ /* @__PURE__ */ Object.create(null),
26700
+ {
26701
+ get: (_target, key) => {
26702
+ options.budget.visitNode();
26703
+ if (key === "length") return length;
26704
+ if (typeof key !== "string") return void 0;
26705
+ return options.context?.getProperty !== void 0 ? options.context.getProperty(receiver, key) : getSandboxDataProperty(receiver, key, options.budget);
26706
+ },
26707
+ has: (_target, key) => {
26285
26708
  options.budget.visitNode();
26286
- if (Object.hasOwn(current, key)) return true;
26709
+ if (typeof key === "string" && options.hasProperty !== void 0)
26710
+ return options.hasProperty(receiver, key);
26711
+ for (let current = receiver; current !== null; current = getSandboxPrototype(current, options.budget)) {
26712
+ options.budget.visitNode();
26713
+ if (Object.hasOwn(current, key)) return true;
26714
+ }
26715
+ return false;
26716
+ },
26717
+ set: (_target, key, entry) => {
26718
+ options.budget.visitNode();
26719
+ if (typeof key !== "string") throw new TypeError("Array indices must be string keys.");
26720
+ if (options.setProperty !== void 0) options.setProperty(receiver, key, entry);
26721
+ else if (!Reflect.set(receiver, key, entry))
26722
+ throw new TypeError(`Cannot assign property '${key}'.`);
26723
+ return true;
26724
+ },
26725
+ deleteProperty: (_target, key) => {
26726
+ options.budget.visitNode();
26727
+ if (typeof key === "string" && options.deleteProperty !== void 0)
26728
+ return options.deleteProperty(receiver, key);
26729
+ return Reflect.deleteProperty(receiver, key);
26287
26730
  }
26288
- return false;
26289
- },
26290
- set: (_target, key, entry) => {
26291
- options.budget.visitNode();
26292
- if (typeof key !== "string") throw new TypeError("Array indices must be string keys.");
26293
- if (options.setProperty !== void 0) options.setProperty(receiver, key, entry);
26294
- else if (!Reflect.set(receiver, key, entry)) throw new TypeError(`Cannot assign property '${key}'.`);
26295
- return true;
26296
- },
26297
- deleteProperty: (_target, key) => {
26298
- options.budget.visitNode();
26299
- if (typeof key === "string" && options.deleteProperty !== void 0) return options.deleteProperty(receiver, key);
26300
- return Reflect.deleteProperty(receiver, key);
26301
26731
  }
26302
- });
26732
+ );
26303
26733
  arrayLikeSources.set(view, receiver);
26304
26734
  return view;
26305
26735
  }
@@ -26403,166 +26833,371 @@ async function callArrayMethodUnlocked(value, methodName, args, options, stack)
26403
26833
  );
26404
26834
  case "flat":
26405
26835
  return budgetProducedValue(
26406
- flattenArray(value, toIntegerOrInfinity(args[0] ?? 1), options.budget),
26836
+ await flattenArray(
26837
+ value,
26838
+ args[0] === void 0 ? 1 : toIntegerOrInfinity(await sandboxNumber(args[0], options.budget, options.context)),
26839
+ options
26840
+ ),
26407
26841
  options.budget
26408
26842
  );
26409
26843
  case "includes":
26410
- return Reflect.apply(Array.prototype.includes, value, [...args]);
26411
26844
  case "indexOf":
26412
- return Reflect.apply(Array.prototype.indexOf, value, [...args]);
26413
- case "lastIndexOf":
26414
- return Reflect.apply(Array.prototype.lastIndexOf, value, [...args]);
26415
- case "join":
26416
- return options.budget.allocateString(Reflect.apply(Array.prototype.join, value, [...args]));
26845
+ case "lastIndexOf": {
26846
+ const length = value.length;
26847
+ if (length === 0) return methodName === "includes" ? false : -1;
26848
+ const reverse = methodName === "lastIndexOf";
26849
+ const start = reverse && args.length < 2 ? length - 1 : toIntegerOrInfinity(await sandboxNumber(args[1], options.budget, options.context));
26850
+ let index = reverse ? Math.min(start < 0 ? length + start : start, length - 1) : start < 0 ? Math.max(length + start, 0) : start;
26851
+ for (; index >= 0 && index < length; index += reverse ? -1 : 1) {
26852
+ options.budget.visitNode();
26853
+ if (methodName !== "includes" && !(index in value)) continue;
26854
+ const entry = await readArrayElement(value, index, options);
26855
+ if (entry === args[0] || methodName === "includes" && Number.isNaN(entry) && Number.isNaN(args[0]))
26856
+ return methodName === "includes" ? true : index;
26857
+ }
26858
+ return methodName === "includes" ? false : -1;
26859
+ }
26860
+ case "join": {
26861
+ const length = value.length;
26862
+ const separator = args[0] === void 0 ? "," : await sandboxString(args[0], options.budget, options.context);
26863
+ return joinSandboxArray(
26864
+ arrayLikeSources.get(value) ?? value,
26865
+ length,
26866
+ separator,
26867
+ options.budget,
26868
+ options.context
26869
+ );
26870
+ }
26417
26871
  case "slice": {
26418
26872
  const length = value.length;
26419
- const start = toIntegerOrInfinity(await sandboxNumber(args[0], options.budget, options.context));
26873
+ const start = toIntegerOrInfinity(
26874
+ await sandboxNumber(args[0], options.budget, options.context)
26875
+ );
26420
26876
  const end = args[1] === void 0 ? length : toIntegerOrInfinity(await sandboxNumber(args[1], options.budget, options.context));
26421
26877
  const first = start < 0 ? Math.max(length + start, 0) : Math.min(start, length);
26422
26878
  const final = end < 0 ? Math.max(length + end, 0) : Math.min(end, length);
26423
26879
  const count = Math.max(final - first, 0);
26424
26880
  options.budget.allocateArrayLength(count);
26425
26881
  const result = new Array(count);
26426
- for (let index = 0; index < count; index += 1) {
26427
- options.budget.visitNode();
26428
- if (first + index in value) result[index] = value[first + index];
26882
+ const release = retainValues(options.budget, () => [result]);
26883
+ try {
26884
+ for (let index = 0; index < count; index += 1) {
26885
+ options.budget.visitNode();
26886
+ if (first + index in value)
26887
+ result[index] = await readArrayElement(value, first + index, options);
26888
+ }
26889
+ return budgetProducedValue(result, options.budget);
26890
+ } finally {
26891
+ release();
26892
+ }
26893
+ }
26894
+ case "concat": {
26895
+ const result = [];
26896
+ const retained = {};
26897
+ options.budget.setRetainedValues(retained, () => [result]);
26898
+ try {
26899
+ for (const entry of [value, ...args]) {
26900
+ if (!Array.isArray(entry)) {
26901
+ options.budget.allocateArrayLength(result.length + 1);
26902
+ result.push(entry);
26903
+ continue;
26904
+ }
26905
+ const start = result.length;
26906
+ const length = entry.length;
26907
+ options.budget.allocateArrayLength(start + length);
26908
+ result.length += length;
26909
+ for (let index = 0; index < length; index++) {
26910
+ options.budget.visitNode();
26911
+ if (index in entry)
26912
+ result[start + index] = await readArrayElement(entry, index, options);
26913
+ }
26914
+ }
26915
+ return budgetProducedValue(result, options.budget);
26916
+ } finally {
26917
+ options.budget.setRetainedValues(retained, void 0);
26429
26918
  }
26430
- return budgetProducedValue(result, options.budget);
26431
26919
  }
26432
- case "concat":
26433
- return budgetProducedValue(
26434
- Reflect.apply(Array.prototype.concat, value, [...args]),
26435
- options.budget
26436
- );
26437
26920
  case "splice": {
26438
- const removed = Reflect.apply(Array.prototype.splice, value, [...args]);
26921
+ const length = value.length;
26922
+ const start = toIntegerOrInfinity(
26923
+ await sandboxNumber(args[0], options.budget, options.context)
26924
+ );
26925
+ const first = start < 0 ? Math.max(length + start, 0) : Math.min(start, length);
26926
+ const inserted = Math.max(args.length - 2, 0);
26927
+ const deleted = args.length === 0 ? 0 : args.length === 1 ? length - first : Math.min(
26928
+ Math.max(
26929
+ toIntegerOrInfinity(
26930
+ await sandboxNumber(args[1], options.budget, options.context)
26931
+ ),
26932
+ 0
26933
+ ),
26934
+ length - first
26935
+ );
26936
+ const nextLength = length + inserted - deleted;
26937
+ if (nextLength > Number.MAX_SAFE_INTEGER)
26938
+ throw new TypeError("Array-like length exceeds the safe integer limit.");
26939
+ options.budget.allocateArrayLength(deleted);
26940
+ const removed = new Array(deleted);
26941
+ const retained = {};
26942
+ options.budget.setRetainedValues(retained, () => [removed]);
26943
+ try {
26944
+ for (let index = 0; index < deleted; index++) {
26945
+ options.budget.visitNode();
26946
+ if (first + index in value)
26947
+ removed[index] = await readArrayElement(value, first + index, options);
26948
+ }
26949
+ if (inserted < deleted) {
26950
+ for (let index = first; index < length - deleted; index++)
26951
+ await moveArrayElement(value, index + deleted, index + inserted, options);
26952
+ for (let index = length; index > nextLength; index--)
26953
+ deleteArrayElement(value, index - 1, options);
26954
+ } else if (inserted > deleted) {
26955
+ for (let index = length - deleted; index > first; index--)
26956
+ await moveArrayElement(value, index + deleted - 1, index + inserted - 1, options);
26957
+ }
26958
+ for (let index = 0; index < inserted; index++)
26959
+ await writeArrayProperty(value, first + index, args[index + 2], options);
26960
+ await writeArrayProperty(value, "length", nextLength, options);
26961
+ } finally {
26962
+ options.budget.setRetainedValues(retained, void 0);
26963
+ }
26439
26964
  budgetProducedValue(removed, options.budget);
26440
26965
  budgetProducedValue(value, options.budget);
26441
26966
  return removed;
26442
26967
  }
26443
- case "fill":
26444
- Reflect.apply(Array.prototype.fill, value, [...args]);
26968
+ case "fill": {
26969
+ const length = value.length;
26970
+ const start = toIntegerOrInfinity(
26971
+ await sandboxNumber(args[1], options.budget, options.context)
26972
+ );
26973
+ const end = args[2] === void 0 ? length : toIntegerOrInfinity(await sandboxNumber(args[2], options.budget, options.context));
26974
+ const first = start < 0 ? Math.max(length + start, 0) : Math.min(start, length);
26975
+ const final = end < 0 ? Math.max(length + end, 0) : Math.min(end, length);
26976
+ for (let index = first; index < final; index++)
26977
+ await writeArrayProperty(value, index, args[0], options);
26445
26978
  budgetProducedValue(value, options.budget);
26446
26979
  return value;
26447
- case "copyWithin":
26448
- Reflect.apply(Array.prototype.copyWithin, value, [...args]);
26980
+ }
26981
+ case "copyWithin": {
26982
+ const length = value.length;
26983
+ const target = toIntegerOrInfinity(
26984
+ await sandboxNumber(args[0], options.budget, options.context)
26985
+ );
26986
+ const start = toIntegerOrInfinity(
26987
+ await sandboxNumber(args[1], options.budget, options.context)
26988
+ );
26989
+ const end = args[2] === void 0 ? length : toIntegerOrInfinity(await sandboxNumber(args[2], options.budget, options.context));
26990
+ let to = target < 0 ? Math.max(length + target, 0) : Math.min(target, length);
26991
+ let from = start < 0 ? Math.max(length + start, 0) : Math.min(start, length);
26992
+ const final = end < 0 ? Math.max(length + end, 0) : Math.min(end, length);
26993
+ let count = Math.min(final - from, length - to);
26994
+ const direction = from < to && to < from + count ? -1 : 1;
26995
+ if (direction < 0) {
26996
+ from += count - 1;
26997
+ to += count - 1;
26998
+ }
26999
+ while (count-- > 0) {
27000
+ await moveArrayElement(value, from, to, options);
27001
+ from += direction;
27002
+ to += direction;
27003
+ }
26449
27004
  budgetProducedValue(value, options.budget);
26450
27005
  return value;
26451
- case "at":
26452
- return budgetProducedValue(
26453
- Reflect.apply(Array.prototype.at, value, [...args]),
26454
- options.budget
27006
+ }
27007
+ case "at": {
27008
+ const length = value.length;
27009
+ const index = toIntegerOrInfinity(
27010
+ await sandboxNumber(args[0], options.budget, options.context)
26455
27011
  );
27012
+ const actual = index < 0 ? length + index : index;
27013
+ return actual < 0 || actual >= length ? void 0 : budgetProducedValue(await readArrayElement(value, actual, options), options.budget);
27014
+ }
26456
27015
  case "sort":
26457
- if (args[0] === void 0) {
26458
- Reflect.apply(Array.prototype.sort, value, []);
27016
+ await sortArray(
27017
+ value,
27018
+ args[0] === void 0 ? void 0 : getRequiredCallback(methodName, args[0]),
27019
+ options,
27020
+ stack
27021
+ );
27022
+ budgetProducedValue(value, options.budget);
27023
+ return value;
27024
+ case "reverse": {
27025
+ const length = value.length;
27026
+ let lowerValue;
27027
+ let upperValue;
27028
+ const release = retainValues(options.budget, () => [lowerValue, upperValue]);
27029
+ try {
27030
+ for (let lower = 0; lower < Math.floor(length / 2); lower++) {
27031
+ options.budget.visitNode();
27032
+ lowerValue = upperValue = void 0;
27033
+ const upper = length - lower - 1;
27034
+ const lowerExists = lower in value;
27035
+ lowerValue = lowerExists ? await readArrayElement(value, lower, options) : void 0;
27036
+ const upperExists = upper in value;
27037
+ upperValue = upperExists ? await readArrayElement(value, upper, options) : void 0;
27038
+ if (lowerExists && upperExists) {
27039
+ await writeArrayProperty(value, lower, upperValue, options);
27040
+ await writeArrayProperty(value, upper, lowerValue, options);
27041
+ } else if (!lowerExists && upperExists) {
27042
+ await writeArrayProperty(value, lower, upperValue, options);
27043
+ deleteArrayElement(value, upper, options);
27044
+ } else if (lowerExists) {
27045
+ deleteArrayElement(value, lower, options);
27046
+ await writeArrayProperty(value, upper, lowerValue, options);
27047
+ }
27048
+ }
26459
27049
  budgetProducedValue(value, options.budget);
26460
27050
  return value;
27051
+ } finally {
27052
+ release();
26461
27053
  }
26462
- await sortArray(value, getRequiredCallback(methodName, args[0]), options, stack);
26463
- budgetProducedValue(value, options.budget);
26464
- return value;
26465
- case "reverse":
26466
- Reflect.apply(Array.prototype.reverse, value, []);
26467
- budgetProducedValue(value, options.budget);
26468
- return value;
27054
+ }
26469
27055
  case "toSorted": {
26470
27056
  const length = value.length;
26471
27057
  options.budget.allocateArrayLength(length);
26472
27058
  const result = new Array(length);
26473
- for (let index = 0; index < length; index += 1) {
26474
- options.budget.visitNode();
26475
- result[index] = value[index];
26476
- }
26477
- if (args[0] === void 0) {
26478
- result.sort();
26479
- } else {
26480
- await sortArray(result, getRequiredCallback(methodName, args[0]), options, stack);
27059
+ const release = retainValues(options.budget, () => [result]);
27060
+ try {
27061
+ for (let index = 0; index < length; index += 1) {
27062
+ options.budget.visitNode();
27063
+ result[index] = await readArrayElement(value, index, options);
27064
+ }
27065
+ await sortArray(
27066
+ result,
27067
+ args[0] === void 0 ? void 0 : getRequiredCallback(methodName, args[0]),
27068
+ options,
27069
+ stack
27070
+ );
27071
+ return budgetProducedValue(result, options.budget);
27072
+ } finally {
27073
+ release();
26481
27074
  }
26482
- return budgetProducedValue(result, options.budget);
26483
27075
  }
26484
27076
  case "toReversed": {
26485
27077
  const length = value.length;
26486
27078
  options.budget.allocateArrayLength(length);
26487
27079
  const result = new Array(length);
26488
- for (let index = 0; index < length; index += 1) {
26489
- options.budget.visitNode();
26490
- result[index] = value[length - index - 1];
27080
+ const release = retainValues(options.budget, () => [result]);
27081
+ try {
27082
+ for (let index = 0; index < length; index += 1) {
27083
+ options.budget.visitNode();
27084
+ result[index] = await readArrayElement(value, length - index - 1, options);
27085
+ }
27086
+ return budgetProducedValue(result, options.budget);
27087
+ } finally {
27088
+ release();
26491
27089
  }
26492
- return budgetProducedValue(result, options.budget);
26493
27090
  }
26494
27091
  case "toSpliced": {
26495
27092
  const length = value.length;
26496
- const start = toIntegerOrInfinity(await sandboxNumber(args[0], options.budget, options.context));
27093
+ const start = toIntegerOrInfinity(
27094
+ await sandboxNumber(args[0], options.budget, options.context)
27095
+ );
26497
27096
  const first = start < 0 ? Math.max(length + start, 0) : Math.min(start, length);
26498
27097
  const inserted = Math.max(args.length - 2, 0);
26499
- const deleted = args.length === 0 ? 0 : args.length === 1 ? length - first : Math.min(Math.max(toIntegerOrInfinity(await sandboxNumber(args[1], options.budget, options.context)), 0), length - first);
27098
+ const deleted = args.length === 0 ? 0 : args.length === 1 ? length - first : Math.min(
27099
+ Math.max(
27100
+ toIntegerOrInfinity(
27101
+ await sandboxNumber(args[1], options.budget, options.context)
27102
+ ),
27103
+ 0
27104
+ ),
27105
+ length - first
27106
+ );
26500
27107
  const resultLength = length + inserted - deleted;
26501
- if (resultLength > Number.MAX_SAFE_INTEGER) throw new TypeError("Array-like length exceeds the safe integer limit.");
27108
+ if (resultLength > Number.MAX_SAFE_INTEGER)
27109
+ throw new TypeError("Array-like length exceeds the safe integer limit.");
26502
27110
  options.budget.allocateArrayLength(resultLength);
26503
27111
  const result = new Array(resultLength);
26504
- for (let index = 0; index < resultLength; index += 1) {
26505
- options.budget.visitNode();
26506
- result[index] = index < first ? value[index] : index < first + inserted ? args[index - first + 2] : value[index - inserted + deleted];
27112
+ const release = retainValues(options.budget, () => [result]);
27113
+ try {
27114
+ for (let index = 0; index < resultLength; index += 1) {
27115
+ options.budget.visitNode();
27116
+ result[index] = index < first ? await readArrayElement(value, index, options) : index < first + inserted ? args[index - first + 2] : await readArrayElement(value, index - inserted + deleted, options);
27117
+ }
27118
+ return budgetProducedValue(result, options.budget);
27119
+ } finally {
27120
+ release();
26507
27121
  }
26508
- return budgetProducedValue(result, options.budget);
26509
27122
  }
26510
27123
  case "with": {
26511
27124
  const length = value.length;
26512
- const index = toIntegerOrInfinity(args[0]);
27125
+ const index = toIntegerOrInfinity(
27126
+ options.context === void 0 ? args[0] : await sandboxNumber(args[0], options.budget, options.context)
27127
+ );
26513
27128
  const actualIndex = index < 0 ? length + index : index;
26514
27129
  if (actualIndex < 0 || actualIndex >= length) {
26515
27130
  throw new RangeError("Invalid index");
26516
27131
  }
26517
27132
  options.budget.allocateArrayLength(length);
26518
27133
  const result = [];
26519
- for (let position = 0; position < length; position += 1) {
26520
- options.budget.visitNode();
26521
- result[position] = position === actualIndex ? args[1] : Array.isArray(value) && !Object.hasOwn(value, position) ? void 0 : value[position];
27134
+ const release = retainValues(options.budget, () => [result]);
27135
+ try {
27136
+ for (let position = 0; position < length; position += 1) {
27137
+ options.budget.visitNode();
27138
+ result[position] = position === actualIndex ? args[1] : await readArrayElement(value, position, options);
27139
+ }
27140
+ return budgetProducedValue(result, options.budget);
27141
+ } finally {
27142
+ release();
26522
27143
  }
26523
- return budgetProducedValue(result, options.budget);
26524
27144
  }
26525
27145
  case "push": {
26526
- const nextLength = appendArrayValues(value, args);
27146
+ const nextLength = await appendArrayValues(value, args, options);
26527
27147
  budgetProducedValue(value, options.budget);
26528
27148
  return nextLength;
26529
27149
  }
26530
27150
  case "pop":
26531
- return budgetProducedValue(Reflect.apply(Array.prototype.pop, value, []), options.budget);
26532
- case "shift":
26533
- return budgetProducedValue(Reflect.apply(Array.prototype.shift, value, []), options.budget);
27151
+ case "shift": {
27152
+ const length = value.length;
27153
+ if (length === 0) {
27154
+ await writeArrayProperty(value, "length", 0, options);
27155
+ return void 0;
27156
+ }
27157
+ const result = await readArrayElement(value, methodName === "pop" ? length - 1 : 0, options);
27158
+ const retained = {};
27159
+ options.budget.setRetainedValues(retained, () => [result]);
27160
+ try {
27161
+ if (methodName === "shift")
27162
+ for (let index = 1; index < length; index++)
27163
+ await moveArrayElement(value, index, index - 1, options);
27164
+ deleteArrayElement(value, length - 1, options);
27165
+ await writeArrayProperty(value, "length", length - 1, options);
27166
+ return budgetProducedValue(result, options.budget);
27167
+ } finally {
27168
+ options.budget.setRetainedValues(retained, void 0);
27169
+ }
27170
+ }
26534
27171
  case "unshift": {
26535
- const nextLength = prependArrayValues(value, args);
27172
+ const nextLength = await prependArrayValues(value, args, options);
26536
27173
  budgetProducedValue(value, options.budget);
26537
27174
  return nextLength;
26538
27175
  }
26539
27176
  }
26540
27177
  }
26541
- function appendArrayValues(target, values) {
27178
+ async function appendArrayValues(target, values, options) {
26542
27179
  let length = target.length;
26543
- if (length + values.length > Number.MAX_SAFE_INTEGER) throw new TypeError("Array-like length exceeds the safe integer limit.");
27180
+ if (length + values.length > Number.MAX_SAFE_INTEGER)
27181
+ throw new TypeError("Array-like length exceeds the safe integer limit.");
26544
27182
  for (const value of values) {
26545
- target[length++] = value;
27183
+ await writeArrayProperty(target, length++, value, options);
26546
27184
  }
26547
- target.length = length;
27185
+ await writeArrayProperty(target, "length", length, options);
26548
27186
  return length;
26549
27187
  }
26550
- function prependArrayValues(target, values) {
27188
+ async function prependArrayValues(target, values, options) {
26551
27189
  const originalLength = target.length;
26552
27190
  const length = originalLength + values.length;
26553
- if (length > Number.MAX_SAFE_INTEGER) throw new TypeError("Array-like length exceeds the safe integer limit.");
27191
+ if (length > Number.MAX_SAFE_INTEGER)
27192
+ throw new TypeError("Array-like length exceeds the safe integer limit.");
26554
27193
  for (let index = values.length === 0 ? -1 : originalLength - 1; index >= 0; index -= 1) {
26555
27194
  const targetIndex = index + values.length;
26556
- if (index in target) {
26557
- target[targetIndex] = target[index];
26558
- } else {
26559
- delete target[targetIndex];
26560
- }
27195
+ await moveArrayElement(target, index, targetIndex, options);
26561
27196
  }
26562
27197
  for (let index = 0; index < values.length; index += 1) {
26563
- target[index] = values[index];
27198
+ await writeArrayProperty(target, index, values[index], options);
26564
27199
  }
26565
- target.length = length;
27200
+ await writeArrayProperty(target, "length", length, options);
26566
27201
  return length;
26567
27202
  }
26568
27203
  function isCallbackArrayMethod(methodName) {
@@ -26577,6 +27212,33 @@ function getRequiredCallback(methodName, value) {
26577
27212
  }
26578
27213
  return value;
26579
27214
  }
27215
+ function readArrayElement(value, index, options) {
27216
+ const receiver = arrayLikeSources.get(value) ?? value;
27217
+ return options.context?.getProperty !== void 0 ? options.context.getProperty(receiver, index) : getSandboxDataProperty(receiver, index, options.budget);
27218
+ }
27219
+ function writeArrayProperty(value, key, entry, options) {
27220
+ options.budget.visitNode();
27221
+ const receiver = arrayLikeSources.get(value) ?? value;
27222
+ if (Array.isArray(receiver)) {
27223
+ if (key === "length") options.budget.allocateArrayLength(Number(entry));
27224
+ else if (typeof key === "number") options.budget.allocateArrayLength(key + 1);
27225
+ }
27226
+ if (options.setProperty !== void 0) return options.setProperty(receiver, String(key), entry);
27227
+ if (!Reflect.set(receiver, key, entry))
27228
+ throw new TypeError(`Cannot assign to read only property '${key}'.`);
27229
+ }
27230
+ function deleteArrayElement(value, index, options) {
27231
+ options.budget.visitNode();
27232
+ const receiver = arrayLikeSources.get(value) ?? value;
27233
+ const deleted = options.deleteProperty === void 0 ? Reflect.deleteProperty(receiver, String(index)) : options.deleteProperty(receiver, String(index));
27234
+ if (!deleted) throw new TypeError(`Cannot delete property '${index}'.`);
27235
+ }
27236
+ async function moveArrayElement(value, from, to, options) {
27237
+ options.budget.visitNode();
27238
+ if (from in value)
27239
+ await writeArrayProperty(value, to, await readArrayElement(value, from, options), options);
27240
+ else deleteArrayElement(value, to, options);
27241
+ }
26580
27242
  async function mapArray(value, callback, options, stack, thisValue) {
26581
27243
  const length = value.length;
26582
27244
  options.budget.allocateArrayLength(length);
@@ -26590,7 +27252,7 @@ async function mapArray(value, callback, options, stack, thisValue) {
26590
27252
  }
26591
27253
  result[index] = await callArrayCallback(
26592
27254
  callback,
26593
- value[index],
27255
+ await readArrayElement(value, index, options),
26594
27256
  index,
26595
27257
  value,
26596
27258
  options,
@@ -26613,7 +27275,7 @@ async function filterArray(value, callback, options, stack, thisValue) {
26613
27275
  if (!(index in value)) {
26614
27276
  continue;
26615
27277
  }
26616
- const entry = value[index];
27278
+ const entry = await readArrayElement(value, index, options);
26617
27279
  if (await callArrayCallback(callback, entry, index, value, options, stack, thisValue)) {
26618
27280
  result.push(entry);
26619
27281
  }
@@ -26627,7 +27289,7 @@ async function findInArray(value, callback, options, stack, thisValue) {
26627
27289
  const length = value.length;
26628
27290
  for (let index = 0; index < length; index += 1) {
26629
27291
  options.budget.visitNode();
26630
- const entry = index in value ? value[index] : void 0;
27292
+ const entry = await readArrayElement(value, index, options);
26631
27293
  if (await callArrayCallback(callback, entry, index, value, options, stack, thisValue)) {
26632
27294
  return entry;
26633
27295
  }
@@ -26638,7 +27300,7 @@ async function findIndexInArray(value, callback, options, stack, thisValue) {
26638
27300
  const length = value.length;
26639
27301
  for (let index = 0; index < length; index += 1) {
26640
27302
  options.budget.visitNode();
26641
- const entry = index in value ? value[index] : void 0;
27303
+ const entry = await readArrayElement(value, index, options);
26642
27304
  if (await callArrayCallback(callback, entry, index, value, options, stack, thisValue)) {
26643
27305
  return index;
26644
27306
  }
@@ -26649,7 +27311,7 @@ async function findLastInArray(value, callback, options, stack, thisValue) {
26649
27311
  const length = value.length;
26650
27312
  for (let index = length - 1; index >= 0; index -= 1) {
26651
27313
  options.budget.visitNode();
26652
- const entry = index in value ? value[index] : void 0;
27314
+ const entry = await readArrayElement(value, index, options);
26653
27315
  if (await callArrayCallback(callback, entry, index, value, options, stack, thisValue)) {
26654
27316
  return entry;
26655
27317
  }
@@ -26660,7 +27322,7 @@ async function findLastIndexInArray(value, callback, options, stack, thisValue)
26660
27322
  const length = value.length;
26661
27323
  for (let index = length - 1; index >= 0; index -= 1) {
26662
27324
  options.budget.visitNode();
26663
- const entry = index in value ? value[index] : void 0;
27325
+ const entry = await readArrayElement(value, index, options);
26664
27326
  if (await callArrayCallback(callback, entry, index, value, options, stack, thisValue)) {
26665
27327
  return index;
26666
27328
  }
@@ -26674,7 +27336,15 @@ async function someInArray(value, callback, options, stack, thisValue) {
26674
27336
  if (!(index in value)) {
26675
27337
  continue;
26676
27338
  }
26677
- if (await callArrayCallback(callback, value[index], index, value, options, stack, thisValue)) {
27339
+ if (await callArrayCallback(
27340
+ callback,
27341
+ await readArrayElement(value, index, options),
27342
+ index,
27343
+ value,
27344
+ options,
27345
+ stack,
27346
+ thisValue
27347
+ )) {
26678
27348
  return true;
26679
27349
  }
26680
27350
  }
@@ -26687,7 +27357,15 @@ async function everyInArray(value, callback, options, stack, thisValue) {
26687
27357
  if (!(index in value)) {
26688
27358
  continue;
26689
27359
  }
26690
- if (!await callArrayCallback(callback, value[index], index, value, options, stack, thisValue)) {
27360
+ if (!await callArrayCallback(
27361
+ callback,
27362
+ await readArrayElement(value, index, options),
27363
+ index,
27364
+ value,
27365
+ options,
27366
+ stack,
27367
+ thisValue
27368
+ )) {
26691
27369
  return false;
26692
27370
  }
26693
27371
  }
@@ -26702,7 +27380,15 @@ async function reduceArray(value, callback, hasInitialValue, initialValue, optio
26702
27380
  if (start < 0) {
26703
27381
  throw new TypeError("Reduce of empty array with no initial value.");
26704
27382
  }
26705
- return reduceFromLeft(value, callback, value[start], start + 1, length, options, stack);
27383
+ return reduceFromLeft(
27384
+ value,
27385
+ callback,
27386
+ await readArrayElement(value, start, options),
27387
+ start + 1,
27388
+ length,
27389
+ options,
27390
+ stack
27391
+ );
26706
27392
  }
26707
27393
  async function reduceRightArray(value, callback, hasInitialValue, initialValue, options, stack) {
26708
27394
  const length = value.length;
@@ -26713,7 +27399,15 @@ async function reduceRightArray(value, callback, hasInitialValue, initialValue,
26713
27399
  if (start < 0) {
26714
27400
  throw new TypeError("Reduce of empty array with no initial value.");
26715
27401
  }
26716
- return reduceFromRight(value, callback, value[start], start - 1, length, options, stack);
27402
+ return reduceFromRight(
27403
+ value,
27404
+ callback,
27405
+ await readArrayElement(value, start, options),
27406
+ start - 1,
27407
+ length,
27408
+ options,
27409
+ stack
27410
+ );
26717
27411
  }
26718
27412
  async function reduceFromLeft(value, callback, accumulator, startIndex, length, options, stack) {
26719
27413
  let current = accumulator;
@@ -26725,7 +27419,16 @@ async function reduceFromLeft(value, callback, accumulator, startIndex, length,
26725
27419
  if (!(index in value)) {
26726
27420
  continue;
26727
27421
  }
26728
- current = await options.callClosure(callback, [current, value[index], index, arrayLikeSources.get(value) ?? value], stack);
27422
+ current = await options.callClosure(
27423
+ callback,
27424
+ [
27425
+ current,
27426
+ await readArrayElement(value, index, options),
27427
+ index,
27428
+ arrayLikeSources.get(value) ?? value
27429
+ ],
27430
+ stack
27431
+ );
26729
27432
  }
26730
27433
  return current;
26731
27434
  } finally {
@@ -26742,7 +27445,16 @@ async function reduceFromRight(value, callback, accumulator, startIndex, length,
26742
27445
  if (!(index in value)) {
26743
27446
  continue;
26744
27447
  }
26745
- current = await options.callClosure(callback, [current, value[index], index, arrayLikeSources.get(value) ?? value], stack);
27448
+ current = await options.callClosure(
27449
+ callback,
27450
+ [
27451
+ current,
27452
+ await readArrayElement(value, index, options),
27453
+ index,
27454
+ arrayLikeSources.get(value) ?? value
27455
+ ],
27456
+ stack
27457
+ );
26746
27458
  }
26747
27459
  return current;
26748
27460
  } finally {
@@ -26756,7 +27468,15 @@ async function forEachArray(value, callback, options, stack, thisValue) {
26756
27468
  if (!(index in value)) {
26757
27469
  continue;
26758
27470
  }
26759
- await callArrayCallback(callback, value[index], index, value, options, stack, thisValue);
27471
+ await callArrayCallback(
27472
+ callback,
27473
+ await readArrayElement(value, index, options),
27474
+ index,
27475
+ value,
27476
+ options,
27477
+ stack,
27478
+ thisValue
27479
+ );
26760
27480
  }
26761
27481
  }
26762
27482
  async function flatMapArray(value, callback, options, stack, thisValue) {
@@ -26771,7 +27491,7 @@ async function flatMapArray(value, callback, options, stack, thisValue) {
26771
27491
  }
26772
27492
  const mapped = await callArrayCallback(
26773
27493
  callback,
26774
- value[index],
27494
+ await readArrayElement(value, index, options),
26775
27495
  index,
26776
27496
  value,
26777
27497
  options,
@@ -26784,7 +27504,7 @@ async function flatMapArray(value, callback, options, stack, thisValue) {
26784
27504
  if (!(mappedIndex in mapped)) {
26785
27505
  continue;
26786
27506
  }
26787
- result.push(mapped[mappedIndex]);
27507
+ result.push(await readArrayElement(mapped, mappedIndex, options));
26788
27508
  options.budget.allocateArrayLength(result.length);
26789
27509
  }
26790
27510
  continue;
@@ -26797,23 +27517,31 @@ async function flatMapArray(value, callback, options, stack, thisValue) {
26797
27517
  options.budget.setRetainedValues(result, void 0);
26798
27518
  }
26799
27519
  }
26800
- function flattenArray(value, depth, budget) {
27520
+ async function flattenArray(value, depth, options) {
26801
27521
  const result = [];
26802
- appendFlattenedEntries(value, depth, result, budget);
26803
- return result;
27522
+ const retained = {};
27523
+ options.budget.setRetainedValues(retained, () => [result]);
27524
+ try {
27525
+ await appendFlattenedEntries(value, depth, result, options);
27526
+ return result;
27527
+ } finally {
27528
+ options.budget.setRetainedValues(retained, void 0);
27529
+ }
26804
27530
  }
26805
- function appendFlattenedEntries(value, depth, result, budget) {
26806
- for (let index = 0; index < value.length; index += 1) {
27531
+ async function appendFlattenedEntries(value, depth, result, options) {
27532
+ const length = value.length;
27533
+ for (let index = 0; index < length; index += 1) {
27534
+ options.budget.visitNode();
26807
27535
  if (!(index in value)) {
26808
27536
  continue;
26809
27537
  }
26810
- const entry = value[index];
27538
+ const entry = await readArrayElement(value, index, options);
26811
27539
  if (depth > 0 && Array.isArray(entry)) {
26812
- appendFlattenedEntries(entry, depth - 1, result, budget);
27540
+ await appendFlattenedEntries(entry, depth - 1, result, options);
26813
27541
  continue;
26814
27542
  }
26815
27543
  result.push(entry);
26816
- budget.allocateArrayLength(result.length);
27544
+ options.budget.allocateArrayLength(result.length);
26817
27545
  }
26818
27546
  }
26819
27547
  async function sortArray(value, comparator, options, stack) {
@@ -26828,7 +27556,7 @@ async function sortArray(value, comparator, options, stack) {
26828
27556
  if (!(index in value)) {
26829
27557
  continue;
26830
27558
  }
26831
- const entry = value[index];
27559
+ const entry = await readArrayElement(value, index, options);
26832
27560
  if (entry === void 0) {
26833
27561
  undefinedCount += 1;
26834
27562
  continue;
@@ -26846,14 +27574,14 @@ async function sortArray(value, comparator, options, stack) {
26846
27574
  }
26847
27575
  currentEntry = void 0;
26848
27576
  for (let index = 0; index < definedValues.length; index += 1) {
26849
- value[index] = definedValues[index];
27577
+ await writeArrayProperty(value, index, definedValues[index], options);
26850
27578
  }
26851
27579
  for (let index = 0; index < undefinedCount; index += 1) {
26852
- value[definedValues.length + index] = void 0;
27580
+ await writeArrayProperty(value, definedValues.length + index, void 0, options);
26853
27581
  }
26854
27582
  for (let index = definedValues.length + undefinedCount; index < length; index += 1) {
26855
27583
  options.budget.visitNode();
26856
- delete value[index];
27584
+ deleteArrayElement(value, index, options);
26857
27585
  }
26858
27586
  } finally {
26859
27587
  options.budget.setRetainedValues(definedValues, void 0);
@@ -26861,11 +27589,30 @@ async function sortArray(value, comparator, options, stack) {
26861
27589
  }
26862
27590
  async function compareEntries(left, right, comparator, options, stack) {
26863
27591
  options.budget.visitNode();
26864
- const result = Number(await options.callClosure(comparator, [left, right], stack));
27592
+ if (comparator === void 0) {
27593
+ const leftString = await sandboxString(left, options.budget, options.context);
27594
+ const release = retainValues(options.budget, () => [leftString]);
27595
+ try {
27596
+ const rightString = await sandboxString(right, options.budget, options.context);
27597
+ return leftString < rightString ? -1 : leftString > rightString ? 1 : 0;
27598
+ } finally {
27599
+ release();
27600
+ }
27601
+ }
27602
+ const result = await sandboxNumber(
27603
+ await options.callClosure(comparator, [left, right], stack),
27604
+ options.budget,
27605
+ options.context
27606
+ );
26865
27607
  return Number.isNaN(result) ? 0 : result;
26866
27608
  }
26867
27609
  async function callArrayCallback(callback, value, index, array, options, stack, thisValue) {
26868
- return options.callClosure(callback, [value, index, arrayLikeSources.get(array) ?? array], stack, thisValue);
27610
+ return options.callClosure(
27611
+ callback,
27612
+ [value, index, arrayLikeSources.get(array) ?? array],
27613
+ stack,
27614
+ thisValue
27615
+ );
26869
27616
  }
26870
27617
  function findNextDefinedIndex(value, startIndex, direction, length, budget) {
26871
27618
  for (let index = startIndex; direction > 0 ? index < length : index >= 0; index += direction) {
@@ -26950,7 +27697,8 @@ function getFunctionMember(target, property, options) {
26950
27697
  while (current !== null) {
26951
27698
  if (isGuestClosure(current)) {
26952
27699
  const value = getGuestFunctionProperty(current, String(property));
26953
- if (value !== void 0 || Object.hasOwn(current.properties ?? {}, String(property))) return value;
27700
+ if (value !== void 0 || Object.hasOwn(current.properties ?? {}, String(property)))
27701
+ return value;
26954
27702
  } else if (isSandboxClosure(current)) {
26955
27703
  if (current.properties !== void 0 && Object.hasOwn(current.properties, String(property)))
26956
27704
  return current.properties[String(property)];
@@ -26966,7 +27714,8 @@ function getFunctionMember(target, property, options) {
26966
27714
  }
26967
27715
  }
26968
27716
  if (current === null) return void 0;
26969
- if (property === "toString" && runResources.getStore()?.functionSourceText === false) return void 0;
27717
+ if (property === "toString" && runResources.getStore()?.functionSourceText === false)
27718
+ return void 0;
26970
27719
  if (!isFunctionMethodName(property)) {
26971
27720
  return void 0;
26972
27721
  }
@@ -26974,13 +27723,13 @@ function getFunctionMember(target, property, options) {
26974
27723
  sandbox: true,
26975
27724
  name: `Function#${property}`,
26976
27725
  ...property === "toString" ? { length: 0 } : {},
26977
- call: (args, context) => callFunctionMethod(context?.thisValue, property, args, options, context?.stack ?? [])
27726
+ call: (args, context) => callFunctionMethod(context?.thisValue, property, args, options, context?.stack ?? [], context)
26978
27727
  });
26979
27728
  }
26980
27729
  function isFunctionMethodName(property) {
26981
27730
  return typeof property === "string" && functionMethodNames.has(property);
26982
27731
  }
26983
- function callFunctionMethod(target, methodName, args, options, stack) {
27732
+ function callFunctionMethod(target, methodName, args, options, stack, context) {
26984
27733
  if (!isSandboxClosure(target)) {
26985
27734
  throw new TypeError(`Function#${methodName} requires a callable receiver.`);
26986
27735
  }
@@ -26991,28 +27740,46 @@ function callFunctionMethod(target, methodName, args, options, stack) {
26991
27740
  const thisValue = args[0];
26992
27741
  if (methodName === "bind") {
26993
27742
  const boundArgs = args.slice(1);
26994
- const bound = createSandboxClosure({
26995
- guest: true,
26996
- sandbox: true,
26997
- name: `bound ${target.name ?? ""}`,
26998
- length: target.length === void 0 ? void 0 : Math.max(0, target.length - boundArgs.length),
26999
- boundTarget: target,
27000
- retainedValues: () => [target, thisValue, ...boundArgs],
27001
- call: (callArgs, context) => options.callClosure(target, [...boundArgs, ...callArgs], context?.stack ?? [], thisValue),
27002
- ...target.construct === void 0 ? {} : {
27003
- construct: (callArgs, context) => options.callClosure(
27004
- target,
27005
- [...boundArgs, ...callArgs],
27006
- context?.stack ?? [],
27007
- void 0,
27008
- true,
27009
- context?.newTarget === bound ? target : context?.newTarget
27010
- )
27011
- }
27012
- });
27013
- if (hasExplicitSandboxPrototype(target))
27014
- setSandboxPrototype(bound, getSandboxPrototype(target, options.budget), options.budget);
27015
- return bound;
27743
+ const bind = (length, name) => {
27744
+ const bound = createSandboxClosure({
27745
+ guest: true,
27746
+ sandbox: true,
27747
+ name: `bound ${name}`,
27748
+ length,
27749
+ boundTarget: target,
27750
+ retainedValues: () => [target, thisValue, ...boundArgs, bound.name],
27751
+ call: (callArgs, context2) => options.callClosure(target, [...boundArgs, ...callArgs], context2?.stack ?? [], thisValue),
27752
+ ...target.construct === void 0 ? {} : {
27753
+ construct: (callArgs, context2) => options.callClosure(
27754
+ target,
27755
+ [...boundArgs, ...callArgs],
27756
+ context2?.stack ?? [],
27757
+ void 0,
27758
+ true,
27759
+ context2?.newTarget === bound ? target : context2?.newTarget
27760
+ )
27761
+ }
27762
+ });
27763
+ if (hasExplicitSandboxPrototype(target))
27764
+ setSandboxPrototype(bound, getSandboxPrototype(target, options.budget), options.budget);
27765
+ return bound;
27766
+ };
27767
+ if (context?.getProperty === void 0)
27768
+ return bind(
27769
+ target.length === void 0 ? void 0 : Math.max(0, target.length - boundArgs.length),
27770
+ target.name ?? ""
27771
+ );
27772
+ return (async () => {
27773
+ const properties = target.properties;
27774
+ const defaultName = target.name;
27775
+ const hasLength = !isGuestClosure(target) || target.properties === void 0 || Object.hasOwn(target.properties, "length");
27776
+ const length = hasLength ? await context.getProperty(target, "length") : void 0;
27777
+ const name = !isGuestClosure(target) && !Object.hasOwn(properties ?? {}, "name") ? defaultName : await context.getProperty(target, "name");
27778
+ return bind(
27779
+ typeof length === "number" && !Number.isNaN(length) ? Math.max(0, Math.trunc(length) - boundArgs.length) : 0,
27780
+ typeof name === "string" ? name : ""
27781
+ );
27782
+ })();
27016
27783
  }
27017
27784
  if (methodName === "call") {
27018
27785
  return options.callClosure(target, args.slice(1), stack, thisValue);
@@ -27024,7 +27791,24 @@ function callFunctionMethod(target, methodName, args, options, stack) {
27024
27791
  if (!Array.isArray(applyArgs)) {
27025
27792
  throw new TypeError("Function#apply requires an array or nullish arguments value.");
27026
27793
  }
27027
- return options.callClosure(target, applyArgs, stack, thisValue);
27794
+ if (context?.getProperty === void 0)
27795
+ return options.callClosure(target, applyArgs, stack, thisValue);
27796
+ return (async () => {
27797
+ const values = [];
27798
+ const length = applyArgs.length;
27799
+ options.budget?.allocateArrayLength(length);
27800
+ const retained = {};
27801
+ options.budget?.setRetainedValues(retained, () => values);
27802
+ try {
27803
+ for (let index = 0; index < length; index++) {
27804
+ options.budget?.visitNode();
27805
+ values.push(await context.getProperty(applyArgs, index));
27806
+ }
27807
+ return await options.callClosure(target, values, stack, thisValue);
27808
+ } finally {
27809
+ options.budget?.setRetainedValues(retained, void 0);
27810
+ }
27811
+ })();
27028
27812
  }
27029
27813
 
27030
27814
  // packages/safe-js/src/interp/methods/collection-callback.ts
@@ -27336,15 +28120,24 @@ function createCollectionGlobals(options) {
27336
28120
  context,
27337
28121
  retainedValues: () => [key, value],
27338
28122
  append: (entry) => {
27339
- if (typeof entry !== "object" || entry === null) throw new TypeError("Map constructor requires entry objects.");
27340
- key = context?.getProperty !== void 0 ? context.getProperty(entry, 0) : getSandboxDataProperty(entry, 0, options.budget);
27341
- value = context?.getProperty !== void 0 ? context.getProperty(entry, 1) : getSandboxDataProperty(entry, 1, options.budget);
27342
- const added = map.entries.has(key) ? 0 : 1;
27343
- const growth = added + (options.budget.limits.dataSize === void 0 ? 0 : measureSandboxData([key, value]));
27344
- options.budget.allocateCollectionEntries(map.entries.size + added);
27345
- map.entries.set(key, value);
27346
- key = value = void 0;
27347
- return growth;
28123
+ if (typeof entry !== "object" || entry === null)
28124
+ throw new TypeError("Map constructor requires entry objects.");
28125
+ const store = (entryValue) => {
28126
+ value = entryValue;
28127
+ const added = map.entries.has(key) ? 0 : 1;
28128
+ const growth = added + (options.budget.limits.dataSize === void 0 ? 0 : measureSandboxData([key, value]));
28129
+ options.budget.allocateCollectionEntries(map.entries.size + added);
28130
+ map.entries.set(key, value);
28131
+ key = value = void 0;
28132
+ return growth;
28133
+ };
28134
+ const readValue = (entryKey) => {
28135
+ key = entryKey;
28136
+ const result2 = context?.getProperty !== void 0 ? context.getProperty(entry, 1) : getSandboxDataProperty(entry, 1, options.budget);
28137
+ return result2 instanceof Promise ? result2.then(store) : store(result2);
28138
+ };
28139
+ const result = context?.getProperty !== void 0 ? context.getProperty(entry, 0) : getSandboxDataProperty(entry, 0, options.budget);
28140
+ return result instanceof Promise ? result.then(readValue) : readValue(result);
27348
28141
  }
27349
28142
  });
27350
28143
  },
@@ -27382,7 +28175,13 @@ function isSandboxMapConstructor(value) {
27382
28175
  function isSandboxSetConstructor(value) {
27383
28176
  return typeof value === "object" && value !== null && setConstructors.has(value);
27384
28177
  }
27385
- function populateCollection(source, collection, { name, budget, context, append, retainedValues }) {
28178
+ function populateCollection(source, collection, {
28179
+ name,
28180
+ budget,
28181
+ context,
28182
+ append,
28183
+ retainedValues
28184
+ }) {
27386
28185
  budget.allocateCollectionEntries(0);
27387
28186
  if (source === void 0 || source === null) return collection;
27388
28187
  const iterator = getSandboxIterator(source, budget, context);
@@ -27390,7 +28189,14 @@ function populateCollection(source, collection, { name, budget, context, append,
27390
28189
  let entry;
27391
28190
  let failure;
27392
28191
  const retained = {};
27393
- budget.setRetainedValues(retained, () => [source, iterator.retainedValue, collection, entry, failure, ...retainedValues?.() ?? []]);
28192
+ budget.setRetainedValues(retained, () => [
28193
+ source,
28194
+ iterator.retainedValue,
28195
+ collection,
28196
+ entry,
28197
+ failure,
28198
+ ...retainedValues?.() ?? []
28199
+ ]);
27394
28200
  const checkData = createDataCheckpoint(budget, context);
27395
28201
  const closeOnThrow = (error) => {
27396
28202
  failure = isCapturedException(error) ? error.reason : error;
@@ -27400,21 +28206,29 @@ function populateCollection(source, collection, { name, budget, context, append,
27400
28206
  };
27401
28207
  try {
27402
28208
  const closing = iterator.return?.();
27403
- if (iterator.generator || iterator.asynchronous) return Promise.resolve(closing).then(() => {
27404
- throw error;
27405
- }, rethrow);
28209
+ if (iterator.generator || iterator.asynchronous)
28210
+ return Promise.resolve(closing).then(() => {
28211
+ throw error;
28212
+ }, rethrow);
27406
28213
  } catch (closeError) {
27407
28214
  return rethrow(closeError);
27408
28215
  }
27409
28216
  throw error;
27410
28217
  };
27411
28218
  const consume = (result) => {
27412
- if (typeof result !== "object" || result === null) throw new TypeError("Iterator result must be an object.");
28219
+ if (typeof result !== "object" || result === null)
28220
+ throw new TypeError("Iterator result must be an object.");
27413
28221
  if (result.done) return true;
27414
28222
  entry = result.value;
27415
28223
  try {
27416
28224
  budget.visitNode();
27417
28225
  const growth = append(entry);
28226
+ if (growth instanceof Promise)
28227
+ return growth.then((size) => {
28228
+ entry = void 0;
28229
+ checkData(collection, size);
28230
+ return false;
28231
+ }).catch(closeOnThrow);
27418
28232
  entry = void 0;
27419
28233
  checkData(collection, growth);
27420
28234
  } catch (error) {
@@ -27422,7 +28236,7 @@ function populateCollection(source, collection, { name, budget, context, append,
27422
28236
  }
27423
28237
  return false;
27424
28238
  };
27425
- if (iterator.generator || iterator.asynchronous) {
28239
+ if (iterator.generator || iterator.asynchronous || context !== void 0) {
27426
28240
  return (async () => {
27427
28241
  try {
27428
28242
  checkData(collection, 0, true);
@@ -28226,7 +29040,8 @@ async function evaluateTaggedTemplateExpression(node, context) {
28226
29040
  if (node.tag.type === "MemberExpression") return evaluateMemberAccess(node.tag, context, async (member) => {
28227
29041
  if (member.kind === "nullish") throw new TypeError("Tagged template tag must be a function.");
28228
29042
  const key = await toPropertyKey(member.property, context.budget, createCoercionContext(context));
28229
- return invokeTag(getPropertyValue(member.object, key, context), member.superReceiver === void 0 ? member.object : member.superReceiver.value);
29043
+ const receiver = member.superReceiver === void 0 ? member.object : member.superReceiver.value;
29044
+ return invokeTag(await getPropertyValue(member.object, key, context, receiver), receiver);
28230
29045
  });
28231
29046
  const tag = await evaluateNode(node.tag, context);
28232
29047
  return tag.kind === "normal" ? invokeTag(tag.value, void 0) : tag;
@@ -28321,7 +29136,8 @@ async function evaluateBinaryExpression(node, context) {
28321
29136
  if (isSandboxBox(rightValue) && (!equality || left.value !== null && left.value !== void 0 && typeof left.value !== "object"))
28322
29137
  rightValue = await toNumericPrimitive(rightValue, context);
28323
29138
  }
28324
- const value = applyBinaryOperator(node, leftValue, rightValue, context);
29139
+ const operation = applyBinaryOperator(node, leftValue, rightValue, context);
29140
+ const value = operation instanceof Promise ? await operation : operation;
28325
29141
  return {
28326
29142
  kind: "normal",
28327
29143
  hasValue: true,
@@ -28412,8 +29228,17 @@ async function evaluateMemberAssignmentExpression(node, context) {
28412
29228
  if (member.object === null || member.object === void 0) {
28413
29229
  throw new TypeError("Cannot assign properties of null or undefined.");
28414
29230
  }
28415
- property = await toPropertyKey(member.property, context.budget, createCoercionContext(context));
28416
- current = getPropertyValue(member.object, property, context);
29231
+ property = await toPropertyKey(
29232
+ member.property,
29233
+ context.budget,
29234
+ createCoercionContext(context)
29235
+ );
29236
+ current = await getPropertyValue(
29237
+ member.object,
29238
+ property,
29239
+ context,
29240
+ member.superReceiver === void 0 ? member.object : member.superReceiver.value
29241
+ );
28417
29242
  }
28418
29243
  if (node.operator === "&&=" && !isTruthy(current)) {
28419
29244
  return {
@@ -28449,9 +29274,22 @@ async function evaluateMemberAssignmentExpression(node, context) {
28449
29274
  throw new TypeError("Cannot assign properties of null or undefined.");
28450
29275
  }
28451
29276
  operands = [value];
28452
- property ??= await toPropertyKey(member.property, context.budget, createCoercionContext(context));
28453
- if (member.superReceiver === void 0) setSandboxProperty(member.object, property, value, context.budget);
28454
- else setSuperProperty(member.object, member.superReceiver.value, property, value, context.budget);
29277
+ property ??= await toPropertyKey(
29278
+ member.property,
29279
+ context.budget,
29280
+ createCoercionContext(context)
29281
+ );
29282
+ if (member.superReceiver === void 0)
29283
+ await setSandboxProperty(
29284
+ member.object,
29285
+ property,
29286
+ value,
29287
+ context.budget,
29288
+ true,
29289
+ createCoercionContext(context)
29290
+ );
29291
+ else
29292
+ await setSuperProperty(member.object, member.superReceiver.value, property, value, context);
28455
29293
  return {
28456
29294
  kind: "normal",
28457
29295
  hasValue: true,
@@ -29526,11 +30364,11 @@ async function evaluateMemberUpdateExpression(node, context) {
29526
30364
  }
29527
30365
  const property = await toPropertyKey(member.property, context.budget, createCoercionContext(context));
29528
30366
  const current = toNumber(
29529
- await toNumericPrimitive(getPropertyValue(member.object, property, context), context)
30367
+ await toNumericPrimitive(await getPropertyValue(member.object, property, context, member.superReceiver === void 0 ? member.object : member.superReceiver.value), context)
29530
30368
  );
29531
30369
  const next = node.operator === "++" ? current + 1 : current - 1;
29532
- if (member.superReceiver === void 0) setSandboxProperty(member.object, property, next, context.budget);
29533
- else setSuperProperty(member.object, member.superReceiver.value, property, next, context.budget);
30370
+ if (member.superReceiver === void 0) await setSandboxProperty(member.object, property, next, context.budget, true, createCoercionContext(context));
30371
+ else await setSuperProperty(member.object, member.superReceiver.value, property, next, context);
29534
30372
  return {
29535
30373
  kind: "normal",
29536
30374
  hasValue: true,
@@ -29547,28 +30385,38 @@ async function evaluateMemberExpression(node, context) {
29547
30385
  return {
29548
30386
  kind: "normal",
29549
30387
  hasValue: true,
29550
- value: getPropertyValue(member.object, await toPropertyKey(member.property, context.budget, createCoercionContext(context)), context)
30388
+ value: await getPropertyValue(
30389
+ member.object,
30390
+ await toPropertyKey(member.property, context.budget, createCoercionContext(context)),
30391
+ context,
30392
+ member.superReceiver === void 0 ? member.object : member.superReceiver.value
30393
+ )
29551
30394
  };
29552
30395
  });
29553
30396
  }
29554
- function getPropertyValue(target, property, context) {
30397
+ function getPropertyValue(target, property, context, receiver = target) {
29555
30398
  if (isGuestHostObject(target)) return getHostObjectMember(target, String(property));
30399
+ const descriptor = getSandboxPropertyDescriptor(target, property, context.budget);
30400
+ if (descriptor !== void 0)
30401
+ return readPropertyDescriptor(descriptor, receiver, createCoercionContext(context), true);
29556
30402
  if (typeof target === "string" || typeof target === "number" || typeof target === "boolean") {
29557
30403
  const prototype = getBoxedPrototype(target, context.budget);
29558
30404
  if (prototype !== void 0) {
29559
30405
  if (typeof target === "string" && (property === "length" || getStringIndex(property) !== void 0))
29560
30406
  return getStringMember(target, property, context.budget);
29561
- return getMemberValue(prototype, property, context);
30407
+ return getPropertyValue(prototype, property, context, receiver);
29562
30408
  }
29563
30409
  }
29564
30410
  if (typeof target === "string") return getStringMember(target, property, context.budget);
29565
30411
  if (typeof target === "number") return getNumberMember(property, context.budget);
29566
30412
  if (typeof target === "boolean") return void 0;
29567
30413
  if (isFloat32Array(target)) return getFloat32Member(target, property, context.budget);
29568
- if (isSandboxDate(target)) return getDateMember(property, context.budget, context.compilation?.owner);
30414
+ if (isSandboxDate(target))
30415
+ return getDateMember(property, context.budget, context.compilation?.owner);
29569
30416
  if (isSandboxMap(target)) return getMapMember(target, property, createMapMethodOptions(context));
29570
30417
  if (isSandboxSet(target)) return getSetMember(target, property, createSetMethodOptions(context));
29571
- if (isSandboxCollectionIterator(target)) return getCollectionIteratorMember(target, property, context.budget);
30418
+ if (isSandboxCollectionIterator(target))
30419
+ return getCollectionIteratorMember(target, property, context.budget);
29572
30420
  if (isSandboxGenerator(target)) return getGeneratorMember(target, property, context.budget);
29573
30421
  if (isSandboxClosure(target)) return getClosureMemberValue(target, property, context);
29574
30422
  if (isSandboxPromise(target)) return getPromiseMember(property, context.budget);
@@ -29585,13 +30433,21 @@ function createPatternContext(context, scope = context.scope, evaluate = evaluat
29585
30433
  evaluate: (node, inferredName) => evaluate(node, { ...evaluationContext, inferredName }),
29586
30434
  toPropertyKey: (value) => toPropertyKey(value, context.budget, createCoercionContext(evaluationContext)),
29587
30435
  getProperty: (value, key) => getPropertyValue(value, key, evaluationContext),
29588
- setProperty: (target, key, value) => setSandboxProperty(target, key, value, context.budget)
30436
+ setProperty: (target, key, value) => setSandboxProperty(
30437
+ target,
30438
+ key,
30439
+ value,
30440
+ context.budget,
30441
+ true,
30442
+ createCoercionContext(evaluationContext)
30443
+ )
29589
30444
  };
29590
30445
  }
29591
30446
  async function evaluateCallExpression(node, context) {
29592
30447
  if (node.callee.type === "Super") {
29593
30448
  const construction = context.functionEnvironment?.construction;
29594
- if (construction === void 0) throw new ReferenceError("Super constructor binding is unavailable.");
30449
+ if (construction === void 0)
30450
+ throw new ReferenceError("Super constructor binding is unavailable.");
29595
30451
  const args = await evaluateCallArguments(node.arguments, context);
29596
30452
  if (!args.ok) return args.result;
29597
30453
  return { kind: "normal", hasValue: true, value: await construction.superCall(args.value) };
@@ -29746,7 +30602,7 @@ async function evaluateMemberCallExpression(node, context) {
29746
30602
  property: await toPropertyKey(reference.property, context.budget, createCoercionContext(context))
29747
30603
  };
29748
30604
  if (member.superReceiver !== void 0)
29749
- return evaluateResolvedCallExpression(node, getPropertyValue(member.object, member.property, context), context, member.superReceiver.value);
30605
+ return evaluateResolvedCallExpression(node, await getPropertyValue(member.object, member.property, context, member.superReceiver.value), context, member.superReceiver.value);
29750
30606
  if ((typeof member.object === "string" || typeof member.object === "number" || typeof member.object === "boolean") && getBoxedPrototype(member.object, context.budget) !== void 0) {
29751
30607
  if (isDefaultBoxedMethod(member.object, member.property, context.budget)) {
29752
30608
  if (typeof member.object === "string" && isStringMethodName(member.property))
@@ -29754,7 +30610,7 @@ async function evaluateMemberCallExpression(node, context) {
29754
30610
  if (typeof member.object === "number" && isNumberMethodName(member.property))
29755
30611
  return evaluateNumberMethodCall(node, member.object, member.property, context);
29756
30612
  }
29757
- return evaluateResolvedCallExpression(node, getPropertyValue(member.object, member.property, context), context, member.object);
30613
+ return evaluateResolvedCallExpression(node, await getPropertyValue(member.object, member.property, context), context, member.object);
29758
30614
  }
29759
30615
  if (typeof member.object === "string" && isStringMethodName(member.property)) {
29760
30616
  return evaluateStringMethodCall(node, member.object, member.property, context);
@@ -29835,7 +30691,7 @@ async function evaluateMemberCallExpression(node, context) {
29835
30691
  return evaluateResolvedCallExpression(node, memberValue, context, member.object);
29836
30692
  }
29837
30693
  if (isSandboxClosure(member.object)) {
29838
- const memberValue = getClosureMemberValue(member.object, member.property, context);
30694
+ const memberValue = await getPropertyValue(member.object, member.property, context);
29839
30695
  if (memberValue === void 0) {
29840
30696
  throw new TypeError(`Function#${String(member.property)} is not a supported method.`);
29841
30697
  }
@@ -29862,7 +30718,7 @@ async function evaluateMemberCallExpression(node, context) {
29862
30718
  }
29863
30719
  return evaluateResolvedCallExpression(
29864
30720
  node,
29865
- getMemberValue(member.object, member.property, context),
30721
+ await getPropertyValue(member.object, member.property, context),
29866
30722
  context,
29867
30723
  member.object
29868
30724
  );
@@ -30064,7 +30920,8 @@ function applyBinaryOperator(node, left, right, context) {
30064
30920
  return true;
30065
30921
  }
30066
30922
  if (isFloat32ArrayConstructor(right)) return isFloat32Array(left);
30067
- if (isDateConstructor(right)) return isSandboxDate(left) && getDatePrototype(left, context.budget, context.compilation?.owner) !== null;
30923
+ if (isDateConstructor(right))
30924
+ return isSandboxDate(left) && getDatePrototype(left, context.budget, context.compilation?.owner) !== null;
30068
30925
  if (isSandboxSetConstructor(right) && isSandboxSet(left)) {
30069
30926
  return true;
30070
30927
  }
@@ -30073,16 +30930,20 @@ function applyBinaryOperator(node, left, right, context) {
30073
30930
  }
30074
30931
  if (isGuestClosure(right)) {
30075
30932
  if (typeof left !== "object" || left === null) return false;
30076
- const prototype = getGuestFunctionProperty(right, "prototype");
30077
- if (typeof prototype !== "object" || prototype === null) {
30078
- throw new TypeError("Function has a non-object prototype in instanceof check.");
30079
- }
30080
- let depth = 0;
30081
- for (let current = getSandboxPrototype(left, context.budget); current !== null; current = getSandboxPrototype(current, context.budget)) {
30082
- context.budget.visitNode();
30083
- assertSandboxDataDepth(depth++);
30084
- if (current === prototype) return true;
30085
- }
30933
+ const check = (prototype2) => {
30934
+ if (typeof prototype2 !== "object" || prototype2 === null) {
30935
+ throw new TypeError("Function has a non-object prototype in instanceof check.");
30936
+ }
30937
+ let depth = 0;
30938
+ for (let current = getSandboxPrototype(left, context.budget); current !== null; current = getSandboxPrototype(current, context.budget)) {
30939
+ context.budget.visitNode();
30940
+ assertSandboxDataDepth(depth++);
30941
+ if (current === prototype2) return true;
30942
+ }
30943
+ return false;
30944
+ };
30945
+ const prototype = getPropertyValue(right, "prototype", context);
30946
+ return prototype instanceof Promise ? prototype.then(check) : check(prototype);
30086
30947
  }
30087
30948
  return false;
30088
30949
  case "in":
@@ -30253,7 +31114,7 @@ async function toNumericPrimitive(value, context) {
30253
31114
  }
30254
31115
  if (isIndexableSandboxValue(value)) {
30255
31116
  for (const methodName of ["valueOf", "toString"]) {
30256
- const method = getMemberValue(value, methodName, context);
31117
+ const method = await getPropertyValue(value, methodName, context);
30257
31118
  if (methodName === "toString" && method === void 0 && !Object.hasOwn(value, methodName)) {
30258
31119
  return toString(value);
30259
31120
  }
@@ -30341,13 +31202,18 @@ function getArrayMemberValue(target, property, context) {
30341
31202
  }
30342
31203
  return getArrayMember(target, property, createArrayMethodOptions(context));
30343
31204
  }
30344
- function setSandboxProperty(target, property, value, budget, checkInherited = true) {
31205
+ function setSandboxProperty(target, property, value, budget, checkInherited = true, context) {
30345
31206
  if (isSandboxDate(target)) throw new TypeError("Date own properties are not supported.");
30346
31207
  if (isGuestHostObject(target)) {
30347
31208
  setHostObjectMember(target, String(property), value);
30348
31209
  return;
30349
31210
  }
30350
31211
  const prototypeOwner = target;
31212
+ if (checkInherited) {
31213
+ const descriptor2 = getSandboxPropertyDescriptor(target, property, budget);
31214
+ if (descriptor2 !== void 0 && !("value" in descriptor2))
31215
+ return writePropertyDescriptor(descriptor2, target, value, context);
31216
+ }
30351
31217
  if (isGuestClosure(target)) target = materializeFunctionProperties(target);
30352
31218
  if (isFloat32Array(target)) {
30353
31219
  setFloat32Member(target, property, value);
@@ -30383,15 +31249,18 @@ function setSandboxProperty(target, property, value, budget, checkInherited = tr
30383
31249
  const properties = isSandboxClosure(prototype) ? prototype.properties : prototype;
30384
31250
  const inherited = properties === void 0 ? void 0 : Object.getOwnPropertyDescriptor(properties, key);
30385
31251
  if (inherited === void 0) continue;
30386
- if (inherited.writable !== true) throw new TypeError(`Cannot assign to read only property '${key}'.`);
31252
+ if (inherited.writable !== true)
31253
+ throw new TypeError(`Cannot assign to read only property '${key}'.`);
30387
31254
  break;
30388
31255
  }
30389
31256
  }
30390
31257
  defineSandboxProperty(target, key, value);
30391
31258
  }
30392
31259
  }
30393
- function setSuperProperty(base, receiver, key, value, budget) {
30394
- if (typeof base !== "object" || base === null) throw new TypeError("Cannot assign a property of null.");
31260
+ function setSuperProperty(base, receiver, key, value, context) {
31261
+ const budget = context.budget;
31262
+ if (typeof base !== "object" || base === null)
31263
+ throw new TypeError("Cannot assign a property of null.");
30395
31264
  let depth = 0;
30396
31265
  for (let current = base; current !== null; current = getSandboxPrototype(current, budget)) {
30397
31266
  budget.visitNode();
@@ -30399,11 +31268,15 @@ function setSuperProperty(base, receiver, key, value, budget) {
30399
31268
  const properties = isSandboxClosure(current) ? current.properties : current;
30400
31269
  const descriptor = properties === void 0 ? void 0 : Object.getOwnPropertyDescriptor(properties, key);
30401
31270
  if (descriptor === void 0) continue;
30402
- if (descriptor.writable !== true) throw new TypeError(`Cannot assign to read only property '${key}'.`);
31271
+ if (!("value" in descriptor))
31272
+ return writePropertyDescriptor(descriptor, receiver, value, createCoercionContext(context));
31273
+ if (descriptor.writable !== true)
31274
+ throw new TypeError(`Cannot assign to read only property '${key}'.`);
30403
31275
  break;
30404
31276
  }
30405
- if (typeof receiver !== "object" || receiver === null) throw new TypeError("Super assignment requires an object receiver.");
30406
- setSandboxProperty(receiver, key, value, budget, false);
31277
+ if (typeof receiver !== "object" || receiver === null)
31278
+ throw new TypeError("Super assignment requires an object receiver.");
31279
+ return setSandboxProperty(receiver, key, value, budget, false);
30407
31280
  }
30408
31281
  function deleteSandboxProperty(target, property) {
30409
31282
  if (isGuestHostObject(target)) return deleteHostObjectMember(target, String(property));
@@ -30467,7 +31340,7 @@ function createArrayMethodOptions(context) {
30467
31340
  budget: context.budget,
30468
31341
  context: createCoercionContext(context),
30469
31342
  hasProperty: (value, property) => hasSandboxProperty(value, property, context),
30470
- setProperty: (value, property, entry) => setSandboxProperty(value, property, entry, context.budget),
31343
+ setProperty: (value, property, entry) => setSandboxProperty(value, property, entry, context.budget, true, createCoercionContext(context)),
30471
31344
  deleteProperty: deleteSandboxProperty,
30472
31345
  callClosure: (closure, args, stack, thisValue) => invokeSandboxClosure(closure, args, context, stack, void 0, thisValue)
30473
31346
  };
@@ -30605,11 +31478,12 @@ async function evaluateObjectSpread(node, context) {
30605
31478
  };
30606
31479
  }
30607
31480
  if (isGuestHostObject(value.value)) {
30608
- const entries = [];
31481
+ const entries2 = [];
30609
31482
  for (const key of getHostObjectKeys(value.value)) {
30610
- if (hasHostObjectMember(value.value, key, true)) entries.push([key, getHostObjectMember(value.value, key)]);
31483
+ if (hasHostObjectMember(value.value, key, true))
31484
+ entries2.push([key, getHostObjectMember(value.value, key)]);
30611
31485
  }
30612
- return { ok: true, value: entries };
31486
+ return { ok: true, value: entries2 };
30613
31487
  }
30614
31488
  if (isSandboxClosure(value.value) && !isGuestClosure(value.value) || isSandboxPromise(value.value)) {
30615
31489
  throw new TypeError(
@@ -30619,10 +31493,17 @@ async function evaluateObjectSpread(node, context) {
30619
31493
  const spreadValue = isGuestClosure(value.value) ? value.value.properties ?? {} : Object(value.value);
30620
31494
  const keys = Object.keys(spreadValue);
30621
31495
  context.budget.allocateArrayLength(keys.length);
30622
- return {
30623
- ok: true,
30624
- value: keys.map((key) => [key, spreadValue[key]])
30625
- };
31496
+ const entries = [];
31497
+ const release = retainValues(context.budget, () => [value.value, entries]);
31498
+ try {
31499
+ for (const key of keys) {
31500
+ if (!hasOwnSandboxProperty(value.value, key, true)) continue;
31501
+ entries.push([key, await getPropertyValue(value.value, key, context)]);
31502
+ }
31503
+ return { ok: true, value: entries };
31504
+ } finally {
31505
+ release();
31506
+ }
30626
31507
  }
30627
31508
  function describeObjectSpreadValue(value) {
30628
31509
  if (value === null) {
@@ -30771,7 +31652,7 @@ function executeAsyncFunction(execute, budget, signal) {
30771
31652
  try {
30772
31653
  const value = await execute(completePrefix);
30773
31654
  resolve(
30774
- isSandboxPromise(value) || getThenable(value) !== void 0 ? awaitSandboxValue(
31655
+ requiresPromiseResolution(value, budget) ? awaitSandboxValue(
30775
31656
  createSandboxPromise(resolveSandboxValue(value, { budget }), {
30776
31657
  trackReplay: false
30777
31658
  }),
@@ -32197,19 +33078,29 @@ async function stringifyJson(value, replacer, indent, budget, context) {
32197
33078
  return budget.allocateString(output);
32198
33079
  }
32199
33080
  async function stringifyProperty(key, holder, state, indent = "") {
32200
- let value = getOwnDataValue(holder, key);
32201
- if (isSandboxDate(value)) {
32202
- value = dateMethods.get("toJSON").invoke(value, []);
32203
- } else if (isStringifyContainer(value)) {
32204
- const toJSON = getOwnDataValue(value, "toJSON");
32205
- if (isSandboxClosure(toJSON)) {
32206
- value = await callStringifyClosure(toJSON, [key], value, state);
33081
+ let value = await getStringifyProperty(holder, key, state);
33082
+ const release = retainValues(state.budget, () => [holder, value]);
33083
+ try {
33084
+ if (isSandboxDate(value)) {
33085
+ value = dateMethods.get("toJSON").invoke(value, []);
33086
+ } else if (isStringifyContainer(value)) {
33087
+ const toJSON = await getStringifyProperty(value, "toJSON", state);
33088
+ if (isSandboxClosure(toJSON)) {
33089
+ value = await callStringifyClosure(toJSON, [key], value, state);
33090
+ }
33091
+ }
33092
+ if (state.replacer !== void 0) {
33093
+ value = await callStringifyClosure(
33094
+ state.replacer,
33095
+ [key, toSandboxValue(value)],
33096
+ holder,
33097
+ state
33098
+ );
32207
33099
  }
33100
+ return await stringifyValue(value, state, indent);
33101
+ } finally {
33102
+ release();
32208
33103
  }
32209
- if (state.replacer !== void 0) {
32210
- value = await callStringifyClosure(state.replacer, [key, toSandboxValue(value)], holder, state);
32211
- }
32212
- return stringifyValue(value, state, indent);
32213
33104
  }
32214
33105
  async function stringifyValue(value, state, indent) {
32215
33106
  if (isSandboxBox(value)) {
@@ -32245,10 +33136,12 @@ async function stringifyValue(value, state, indent) {
32245
33136
  }
32246
33137
  async function stringifyArray(value, state, indent) {
32247
33138
  enterStringifyObject(value, state);
33139
+ const entries = [];
33140
+ const release = retainValues(state.budget, () => entries);
32248
33141
  try {
32249
33142
  const nextIndent = indent + state.gap;
32250
- const entries = [];
32251
- for (let index = 0; index < value.length; index += 1) {
33143
+ const length = value.length;
33144
+ for (let index = 0; index < length; index += 1) {
32252
33145
  entries.push(await stringifyProperty(String(index), value, state, nextIndent) ?? "null");
32253
33146
  }
32254
33147
  if (entries.length === 0) {
@@ -32262,14 +33155,16 @@ ${nextIndent}${entries.join(`,
32262
33155
  ${nextIndent}`)}
32263
33156
  ${indent}]`;
32264
33157
  } finally {
33158
+ release();
32265
33159
  leaveStringifyObject(value, state);
32266
33160
  }
32267
33161
  }
32268
33162
  async function stringifyObject(value, state, indent) {
32269
33163
  enterStringifyObject(value, state);
33164
+ const entries = [];
33165
+ const release = retainValues(state.budget, () => entries);
32270
33166
  try {
32271
33167
  const nextIndent = indent + state.gap;
32272
- const entries = [];
32273
33168
  for (const key of Object.keys(value)) {
32274
33169
  const serialized = await stringifyProperty(key, value, state, nextIndent);
32275
33170
  if (serialized !== void 0) {
@@ -32287,6 +33182,7 @@ ${nextIndent}${entries.join(`,
32287
33182
  ${nextIndent}`)}
32288
33183
  ${indent}}`;
32289
33184
  } finally {
33185
+ release();
32290
33186
  leaveStringifyObject(value, state);
32291
33187
  }
32292
33188
  }
@@ -32342,15 +33238,10 @@ function toSandboxValue(value) {
32342
33238
  `JSON.stringify(value) produced an unsupported value of type ${typeof value}.`
32343
33239
  );
32344
33240
  }
32345
- function getOwnDataValue(target, key) {
32346
- const descriptor = Object.getOwnPropertyDescriptor(target, key);
32347
- if (descriptor === void 0) {
32348
- return void 0;
32349
- }
32350
- if ("get" in descriptor || "set" in descriptor) {
32351
- throw new TypeError(`JSON.stringify(value) cannot serialize accessor property ${key}.`);
32352
- }
32353
- return descriptor.value;
33241
+ function getStringifyProperty(target, key, state) {
33242
+ if (state.context?.getProperty !== void 0) return state.context.getProperty(target, key);
33243
+ const descriptor = getSandboxPropertyDescriptor(target, key, state.budget);
33244
+ return descriptor === void 0 ? void 0 : readPropertyDescriptor(descriptor, target, state.context);
32354
33245
  }
32355
33246
  function copyJsonToSandbox(value, budget) {
32356
33247
  if (value === null || value === void 0 || typeof value === "boolean" || typeof value === "number") {
@@ -34608,4 +35499,4 @@ export {
34608
35499
  FileSnapshotBackend,
34609
35500
  run
34610
35501
  };
34611
- //# sourceMappingURL=chunk-WBWD7ZCM.js.map
35502
+ //# sourceMappingURL=chunk-FYPACPSN.js.map