poe-code 14.0.80 → 14.0.82

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (49) hide show
  1. package/dist/index.js +876 -404
  2. package/dist/index.js.map +4 -4
  3. package/dist/metafile.json +1 -1
  4. package/package.json +1 -1
  5. package/packages/safe-js/dist/chunks/{chunk-34G5WW2O.js → chunk-7LGBDF56.js} +2 -2
  6. package/packages/safe-js/dist/chunks/{chunk-M4L3EZHL.js → chunk-V6LQP64H.js} +733 -334
  7. package/packages/safe-js/dist/chunks/chunk-V6LQP64H.js.map +7 -0
  8. package/packages/safe-js/dist/cli.js +2 -2
  9. package/packages/safe-js/dist/core.js +1 -1
  10. package/packages/safe-js/dist/index.js +2 -2
  11. package/packages/safe-js/dist/interp/async.d.ts +1 -1
  12. package/packages/safe-js/dist/interp/async.js +65 -43
  13. package/packages/safe-js/dist/interp/bound-function-state.d.ts +7 -0
  14. package/packages/safe-js/dist/interp/bound-function-state.js +1 -0
  15. package/packages/safe-js/dist/interp/bound-function.d.ts +4 -0
  16. package/packages/safe-js/dist/interp/bound-function.js +18 -0
  17. package/packages/safe-js/dist/interp/error-prototypes.d.ts +3 -0
  18. package/packages/safe-js/dist/interp/error-prototypes.js +1 -0
  19. package/packages/safe-js/dist/interp/exceptions.d.ts +1 -0
  20. package/packages/safe-js/dist/interp/exceptions.js +39 -15
  21. package/packages/safe-js/dist/interp/generator-prototypes.d.ts +6 -0
  22. package/packages/safe-js/dist/interp/generator-prototypes.js +1 -0
  23. package/packages/safe-js/dist/interp/globals/error.d.ts +2 -0
  24. package/packages/safe-js/dist/interp/globals/error.js +104 -4
  25. package/packages/safe-js/dist/interp/globals/function.d.ts +1 -1
  26. package/packages/safe-js/dist/interp/globals/function.js +10 -2
  27. package/packages/safe-js/dist/interp/globals/generator.d.ts +2 -0
  28. package/packages/safe-js/dist/interp/globals/generator.js +51 -0
  29. package/packages/safe-js/dist/interp/globals/object-array.js +19 -1
  30. package/packages/safe-js/dist/interp/globals.d.ts +2 -0
  31. package/packages/safe-js/dist/interp/globals.js +7 -3
  32. package/packages/safe-js/dist/interp/host-bridge.js +4 -2
  33. package/packages/safe-js/dist/interp/instanceof.d.ts +4 -0
  34. package/packages/safe-js/dist/interp/instanceof.js +59 -0
  35. package/packages/safe-js/dist/interp/interpreter.js +3 -40
  36. package/packages/safe-js/dist/interp/iteration.js +44 -6
  37. package/packages/safe-js/dist/interp/methods/function.d.ts +1 -1
  38. package/packages/safe-js/dist/interp/methods/function.js +53 -40
  39. package/packages/safe-js/dist/interp/methods/generator.d.ts +4 -1
  40. package/packages/safe-js/dist/interp/methods/generator.js +12 -6
  41. package/packages/safe-js/dist/interp/object-model.js +13 -0
  42. package/packages/safe-js/dist/interp/values.js +47 -2
  43. package/packages/safe-js/dist/snapshot/guest-heap-validation.js +28 -3
  44. package/packages/safe-js/dist/snapshot/guest-heap.d.ts +10 -0
  45. package/packages/safe-js/dist/snapshot/guest-heap.js +13 -2
  46. package/packages/safe-js/dist/snapshot/restore.js +69 -8
  47. package/packages/safe-js/dist/snapshot/validation.js +1 -1
  48. package/packages/safe-js/dist/chunks/chunk-M4L3EZHL.js.map +0 -7
  49. /package/packages/safe-js/dist/chunks/{chunk-34G5WW2O.js.map → chunk-7LGBDF56.js.map} +0 -0
@@ -7013,42 +7013,6 @@ function serializedDateTime(value) {
7013
7013
  // packages/safe-js/src/interp/internal-symbols.ts
7014
7014
  var internalSymbols = /* @__PURE__ */ new Set();
7015
7015
 
7016
- // packages/safe-js/src/interp/generator-properties.ts
7017
- var generatorGuestProperties = /* @__PURE__ */ new WeakMap();
7018
- function getGeneratorProperties(value) {
7019
- let properties = generatorGuestProperties.get(value);
7020
- if (properties === void 0) {
7021
- properties = /* @__PURE__ */ Object.create(null);
7022
- generatorGuestProperties.set(value, properties);
7023
- }
7024
- return properties;
7025
- }
7026
-
7027
- // packages/safe-js/src/interp/regexp-properties.ts
7028
- var regexGuestProperties = /* @__PURE__ */ new WeakMap();
7029
- function getRegexProperties(value) {
7030
- const properties = regexGuestProperties.get(value);
7031
- if (properties === void 0) throw new TypeError("Invalid sandbox RegExp storage.");
7032
- return properties;
7033
- }
7034
-
7035
- // packages/safe-js/src/interp/collection-properties.ts
7036
- var collectionGuestProperties = /* @__PURE__ */ new WeakMap();
7037
- function getCollectionProperties(value) {
7038
- const properties = collectionGuestProperties.get(value);
7039
- if (properties === void 0) throw new TypeError("Invalid sandbox collection storage.");
7040
- return properties;
7041
- }
7042
- function copyCollectionProperties(source, target, encode) {
7043
- const properties = collectionGuestProperties.get(source) ?? source;
7044
- for (const key of Reflect.ownKeys(properties)) {
7045
- const descriptor = Object.getOwnPropertyDescriptor(properties, key);
7046
- if (!("value" in descriptor)) throw new TypeError("Collection accessor properties cannot be copied as data.");
7047
- Object.defineProperty(target, key, { ...descriptor, value: encode(descriptor.value) });
7048
- }
7049
- if (!Object.isExtensible(properties)) Object.preventExtensions(target);
7050
- }
7051
-
7052
7016
  // packages/safe-js/src/interp/accessors.ts
7053
7017
  var accessorClosures = /* @__PURE__ */ new WeakMap();
7054
7018
  var getterAdapters = /* @__PURE__ */ new WeakMap();
@@ -7107,6 +7071,110 @@ function writePropertyDescriptor(descriptor, receiver, value, context) {
7107
7071
  return context.invokeClosure(setter, [value], receiver).then(() => void 0);
7108
7072
  }
7109
7073
 
7074
+ // packages/safe-js/src/interp/symbols.ts
7075
+ var wellKnownSymbols = Object.freeze({
7076
+ iterator: Symbol.iterator,
7077
+ asyncIterator: Symbol.asyncIterator,
7078
+ hasInstance: Symbol.hasInstance,
7079
+ isConcatSpreadable: Symbol.isConcatSpreadable,
7080
+ match: Symbol.match,
7081
+ matchAll: Symbol.matchAll,
7082
+ replace: Symbol.replace,
7083
+ search: Symbol.search,
7084
+ species: Symbol.species,
7085
+ split: Symbol.split,
7086
+ toPrimitive: Symbol.toPrimitive,
7087
+ toStringTag: Symbol.toStringTag,
7088
+ unscopables: Symbol.unscopables
7089
+ });
7090
+
7091
+ // packages/safe-js/src/interp/intrinsics.ts
7092
+ var identities = /* @__PURE__ */ new WeakMap();
7093
+ var realms2 = /* @__PURE__ */ new WeakMap();
7094
+ function registerBuiltinIdentities(budget, bindings) {
7095
+ let realm = realms2.get(budget);
7096
+ if (realm === void 0) realms2.set(budget, realm = /* @__PURE__ */ new Map());
7097
+ const pending = Object.entries(bindings).map(([name, value]) => [[name], value]);
7098
+ const visited = /* @__PURE__ */ new WeakSet();
7099
+ for (let index = 0; index < pending.length; index++) {
7100
+ const [path, value] = pending[index];
7101
+ if (value === null || typeof value !== "object") continue;
7102
+ const id = JSON.stringify(path);
7103
+ const previous = realm.get(id);
7104
+ if (previous !== void 0 && previous !== value)
7105
+ throw new TypeError(`Duplicate intrinsic identity: ${id}`);
7106
+ realm.set(id, value);
7107
+ if (!identities.has(value)) identities.set(value, id);
7108
+ if (visited.has(value)) continue;
7109
+ visited.add(value);
7110
+ const owner = isSandboxClosure(value) ? value.properties : value;
7111
+ if (owner === void 0) continue;
7112
+ for (const key of Reflect.ownKeys(owner)) {
7113
+ if (typeof key === "symbol" && internalSymbols.has(key)) continue;
7114
+ const descriptor = Object.getOwnPropertyDescriptor(owner, key);
7115
+ const symbolName = typeof key === "symbol" ? Object.entries(wellKnownSymbols).find(([, symbol]) => symbol === key)?.[0] : void 0;
7116
+ if (typeof key === "symbol" && symbolName === void 0)
7117
+ throw new TypeError("Intrinsic symbol keys must be well-known symbols.");
7118
+ const member = [...path, typeof key === "string" ? key : { symbol: symbolName }];
7119
+ if ("value" in descriptor) pending.push([member, descriptor.value]);
7120
+ for (const kind of ["get", "set"]) {
7121
+ const closure = accessorClosure(descriptor[kind]);
7122
+ if (closure !== void 0) pending.push([[...member, kind], closure]);
7123
+ }
7124
+ }
7125
+ }
7126
+ }
7127
+ function getIntrinsicIdentity(value) {
7128
+ return identities.get(value);
7129
+ }
7130
+ function resolveIntrinsicIdentity(budget, id) {
7131
+ const value = realms2.get(budget)?.get(id);
7132
+ if (value === void 0) throw new TypeError(`Unknown intrinsic identity: ${id}`);
7133
+ return value;
7134
+ }
7135
+ function listIntrinsicIdentities(budget) {
7136
+ return [...realms2.get(budget)?.keys() ?? []];
7137
+ }
7138
+ function releaseIntrinsicIdentities(budget) {
7139
+ realms2.delete(budget);
7140
+ }
7141
+
7142
+ // packages/safe-js/src/interp/generator-properties.ts
7143
+ var generatorGuestProperties = /* @__PURE__ */ new WeakMap();
7144
+ function getGeneratorProperties(value) {
7145
+ let properties = generatorGuestProperties.get(value);
7146
+ if (properties === void 0) {
7147
+ properties = /* @__PURE__ */ Object.create(null);
7148
+ generatorGuestProperties.set(value, properties);
7149
+ }
7150
+ return properties;
7151
+ }
7152
+
7153
+ // packages/safe-js/src/interp/regexp-properties.ts
7154
+ var regexGuestProperties = /* @__PURE__ */ new WeakMap();
7155
+ function getRegexProperties(value) {
7156
+ const properties = regexGuestProperties.get(value);
7157
+ if (properties === void 0) throw new TypeError("Invalid sandbox RegExp storage.");
7158
+ return properties;
7159
+ }
7160
+
7161
+ // packages/safe-js/src/interp/collection-properties.ts
7162
+ var collectionGuestProperties = /* @__PURE__ */ new WeakMap();
7163
+ function getCollectionProperties(value) {
7164
+ const properties = collectionGuestProperties.get(value);
7165
+ if (properties === void 0) throw new TypeError("Invalid sandbox collection storage.");
7166
+ return properties;
7167
+ }
7168
+ function copyCollectionProperties(source, target, encode) {
7169
+ const properties = collectionGuestProperties.get(source) ?? source;
7170
+ for (const key of Reflect.ownKeys(properties)) {
7171
+ const descriptor = Object.getOwnPropertyDescriptor(properties, key);
7172
+ if (!("value" in descriptor)) throw new TypeError("Collection accessor properties cannot be copied as data.");
7173
+ Object.defineProperty(target, key, { ...descriptor, value: encode(descriptor.value) });
7174
+ }
7175
+ if (!Object.isExtensible(properties)) Object.preventExtensions(target);
7176
+ }
7177
+
7110
7178
  // packages/safe-js/src/interp/collection-brands.ts
7111
7179
  var sandboxMapBrand = /* @__PURE__ */ Symbol("SandboxMap");
7112
7180
  var sandboxSetBrand = /* @__PURE__ */ Symbol("SandboxSet");
@@ -7398,6 +7466,9 @@ function graphEntries(value) {
7398
7466
  return entries;
7399
7467
  }
7400
7468
 
7469
+ // packages/safe-js/src/interp/generator-prototypes.ts
7470
+ var generatorPrototypes = /* @__PURE__ */ new WeakMap();
7471
+
7401
7472
  // packages/safe-js/src/interp/resources.ts
7402
7473
  import { AsyncLocalStorage } from "node:async_hooks";
7403
7474
  var runResources = new AsyncLocalStorage();
@@ -7447,74 +7518,6 @@ async function withRunResources(signal, execute) {
7447
7518
  return result;
7448
7519
  }
7449
7520
 
7450
- // packages/safe-js/src/interp/symbols.ts
7451
- var wellKnownSymbols = Object.freeze({
7452
- iterator: Symbol.iterator,
7453
- asyncIterator: Symbol.asyncIterator,
7454
- hasInstance: Symbol.hasInstance,
7455
- isConcatSpreadable: Symbol.isConcatSpreadable,
7456
- match: Symbol.match,
7457
- matchAll: Symbol.matchAll,
7458
- replace: Symbol.replace,
7459
- search: Symbol.search,
7460
- species: Symbol.species,
7461
- split: Symbol.split,
7462
- toPrimitive: Symbol.toPrimitive,
7463
- toStringTag: Symbol.toStringTag,
7464
- unscopables: Symbol.unscopables
7465
- });
7466
-
7467
- // packages/safe-js/src/interp/intrinsics.ts
7468
- var identities = /* @__PURE__ */ new WeakMap();
7469
- var realms2 = /* @__PURE__ */ new WeakMap();
7470
- function registerBuiltinIdentities(budget, bindings) {
7471
- let realm = realms2.get(budget);
7472
- if (realm === void 0) realms2.set(budget, realm = /* @__PURE__ */ new Map());
7473
- const pending = Object.entries(bindings).map(([name, value]) => [[name], value]);
7474
- const visited = /* @__PURE__ */ new WeakSet();
7475
- for (let index = 0; index < pending.length; index++) {
7476
- const [path, value] = pending[index];
7477
- if (value === null || typeof value !== "object") continue;
7478
- const id = JSON.stringify(path);
7479
- const previous = realm.get(id);
7480
- if (previous !== void 0 && previous !== value)
7481
- throw new TypeError(`Duplicate intrinsic identity: ${id}`);
7482
- realm.set(id, value);
7483
- if (!identities.has(value)) identities.set(value, id);
7484
- if (visited.has(value)) continue;
7485
- visited.add(value);
7486
- const owner = isSandboxClosure(value) ? value.properties : value;
7487
- if (owner === void 0) continue;
7488
- for (const key of Reflect.ownKeys(owner)) {
7489
- if (typeof key === "symbol" && internalSymbols.has(key)) continue;
7490
- const descriptor = Object.getOwnPropertyDescriptor(owner, key);
7491
- const symbolName = typeof key === "symbol" ? Object.entries(wellKnownSymbols).find(([, symbol]) => symbol === key)?.[0] : void 0;
7492
- if (typeof key === "symbol" && symbolName === void 0)
7493
- throw new TypeError("Intrinsic symbol keys must be well-known symbols.");
7494
- const member = [...path, typeof key === "string" ? key : { symbol: symbolName }];
7495
- if ("value" in descriptor) pending.push([member, descriptor.value]);
7496
- for (const kind of ["get", "set"]) {
7497
- const closure = accessorClosure(descriptor[kind]);
7498
- if (closure !== void 0) pending.push([[...member, kind], closure]);
7499
- }
7500
- }
7501
- }
7502
- }
7503
- function getIntrinsicIdentity(value) {
7504
- return identities.get(value);
7505
- }
7506
- function resolveIntrinsicIdentity(budget, id) {
7507
- const value = realms2.get(budget)?.get(id);
7508
- if (value === void 0) throw new TypeError(`Unknown intrinsic identity: ${id}`);
7509
- return value;
7510
- }
7511
- function listIntrinsicIdentities(budget) {
7512
- return [...realms2.get(budget)?.keys() ?? []];
7513
- }
7514
- function releaseIntrinsicIdentities(budget) {
7515
- realms2.delete(budget);
7516
- }
7517
-
7518
7521
  // packages/safe-js/src/interp/host-capabilities.ts
7519
7522
  import { types as types4 } from "node:util";
7520
7523
  var MAX_INDEXED_LENGTH = 65536;
@@ -7859,6 +7862,9 @@ function namedKeys(state) {
7859
7862
  });
7860
7863
  }
7861
7864
 
7865
+ // packages/safe-js/src/interp/error-prototypes.ts
7866
+ var errorPrototypes = /* @__PURE__ */ new WeakMap();
7867
+
7862
7868
  // packages/safe-js/src/interp/object-model.ts
7863
7869
  var guestClosures = /* @__PURE__ */ new WeakSet();
7864
7870
  var functionProperties = /* @__PURE__ */ new WeakMap();
@@ -8082,11 +8088,18 @@ function releaseObjectPrototype(budget) {
8082
8088
  datePrototypes.delete(budget);
8083
8089
  arrayPrototypes.delete(budget);
8084
8090
  functionPrototypes.delete(budget);
8091
+ generatorPrototypes.delete(budget);
8092
+ errorPrototypes.delete(budget);
8085
8093
  initialRegexDescriptors.delete(budget);
8086
8094
  intrinsicPrototypes.delete(budget);
8087
8095
  }
8088
8096
  function getSandboxPrototype(value, budget) {
8089
8097
  if (prototypes.has(value)) return prototypes.get(value) ?? null;
8098
+ const errorType = sandboxErrorTypes.get(value);
8099
+ if (budget !== void 0 && errorType !== void 0) {
8100
+ const prototype = errorPrototypes.get(budget)?.get(errorType);
8101
+ if (prototype !== void 0) return prototype;
8102
+ }
8090
8103
  if (budget !== void 0 && isGuestClosure(value) && runResources.getStore()?.functionSourceText !== false)
8091
8104
  return functionPrototypes.get(budget) ?? null;
8092
8105
  if (budget !== void 0 && Array.isArray(value)) return arrayPrototypes.get(budget) ?? null;
@@ -9455,13 +9468,12 @@ async function acquireSandboxIterator(value, budget, context, asyncProtocol = fa
9455
9468
  return asyncProtocol ? getSandboxAsyncIterator(value, budget, context, signal) : getSandboxIterator(value, budget, context);
9456
9469
  if (getSandboxPropertyDescriptor(value, key, budget) === void 0 && !(isSandboxRegExpIterator(value) && !asyncProtocol && getSandboxPropertyDescriptor(value, "next", budget) !== void 0)) {
9457
9470
  if (isSandboxGenerator(value)) {
9458
- if (hasExplicitSandboxPrototype(value)) return void 0;
9459
- if (value.async === true === asyncProtocol && getSandboxPropertyDescriptor(value, "next", budget) !== void 0)
9471
+ if (!hasExplicitSandboxPrototype(value) && value.async === true === asyncProtocol && getSandboxPropertyDescriptor(value, "next", budget) !== void 0)
9460
9472
  return guestIterator(value, await context.getProperty(value, "next"), asyncProtocol, budget, context, signal);
9461
9473
  }
9462
9474
  if (!asyncProtocol && Array.isArray(value) && getSandboxPrototype(value, budget) !== null) return void 0;
9463
9475
  if (!asyncProtocol) return getSandboxIterator(value, budget, context);
9464
- if (isSandboxGenerator(value) && value.async)
9476
+ if (isSandboxGenerator(value) && value.async && !hasExplicitSandboxPrototype(value))
9465
9477
  return getSandboxAsyncIterator(value, budget, context, signal);
9466
9478
  const iterator2 = await acquireSandboxIterator(value, budget, context);
9467
9479
  return iterator2 === void 0 ? void 0 : asyncFromSyncIterator(iterator2, budget, signal, context);
@@ -9523,7 +9535,7 @@ async function readIteratorResult(iterator, result, property) {
9523
9535
  }
9524
9536
  function getSandboxAsyncIterator(value, budget, context, signal) {
9525
9537
  if (isSandboxGenerator(value) && value.async) {
9526
- return hasExplicitSandboxPrototype(value) ? void 0 : { ...generatorObjectIterator(value, budget, context), asyncProtocol: true };
9538
+ return hasExplicitSandboxPrototype(value) ? context?.getProperty === void 0 ? generatorProtocolAdapter(value, budget, context, true, signal) : void 0 : { ...generatorObjectIterator(value, budget, context), asyncProtocol: true };
9527
9539
  }
9528
9540
  if (value !== null && (typeof value === "object" || typeof value === "function") && !isGuestHostObject(value)) {
9529
9541
  const method = value[Symbol.asyncIterator];
@@ -9673,7 +9685,9 @@ function getSandboxIterator(value, budget, context) {
9673
9685
  return syncIterator(Float32Array.prototype.values.call(value));
9674
9686
  }
9675
9687
  if (isSandboxGenerator(value)) {
9676
- return value.async || hasExplicitSandboxPrototype(value) ? void 0 : generatorObjectIterator(value, budget, context);
9688
+ if (value.async) return void 0;
9689
+ if (hasExplicitSandboxPrototype(value)) return context?.getProperty === void 0 ? generatorProtocolAdapter(value, budget ?? new Budget(), context, false) : void 0;
9690
+ return generatorObjectIterator(value, budget, context);
9677
9691
  }
9678
9692
  if (typeof value === "string") {
9679
9693
  const iterator2 = value[Symbol.iterator]();
@@ -9750,6 +9764,38 @@ function collectionIterator(collection, value) {
9750
9764
  return adapter;
9751
9765
  }
9752
9766
  var asyncGeneratorRequests = /* @__PURE__ */ new WeakMap();
9767
+ function generatorProtocolAdapter(value, budget, context, asyncProtocol, signal) {
9768
+ const bridge = {
9769
+ ...context,
9770
+ stack: context?.stack ?? [],
9771
+ thisValue: value,
9772
+ invokeClosure: (closure, args, receiver, construct) => invokeBuiltinClosure(closure, args, budget, context, receiver, construct),
9773
+ getProperty: (target, key) => {
9774
+ const descriptor = getSandboxPropertyDescriptor(target, key, budget);
9775
+ return descriptor === void 0 ? void 0 : readPropertyDescriptor(descriptor, target, bridge, true);
9776
+ }
9777
+ };
9778
+ let resolved;
9779
+ let pending;
9780
+ const initialize = () => pending ??= acquireSandboxIterator(value, budget, bridge, asyncProtocol, signal).then((iterator) => {
9781
+ if (iterator === void 0) throw new TypeError("Generator does not provide an iterator protocol.");
9782
+ return resolved = iterator;
9783
+ });
9784
+ return {
9785
+ asynchronous: true,
9786
+ ...asyncProtocol ? { asyncProtocol: true } : {},
9787
+ get retainedValue() {
9788
+ return [value, resolved?.retainedValue];
9789
+ },
9790
+ snapshot: () => resolved?.snapshot?.() ?? { kind: "unsupported" },
9791
+ next: async (...args) => (await initialize()).next(...args),
9792
+ getOperation: async (method) => {
9793
+ const iterator = await initialize();
9794
+ return iterator.getOperation === void 0 ? iterator[method] : iterator.getOperation(method);
9795
+ },
9796
+ readResultProperty: async (result, property) => readIteratorResult(await initialize(), result, property)
9797
+ };
9798
+ }
9753
9799
  function generatorObjectIterator(generator, budget, context) {
9754
9800
  const iterator = generatorIterator(generator, budget, context);
9755
9801
  if (context?.getProperty === void 0) return iterator;
@@ -10225,12 +10271,12 @@ async function evaluateFunctionExpression(node, context, evaluateNode2) {
10225
10271
  value: closure
10226
10272
  };
10227
10273
  }
10228
- function createInterpretedClosure(node, context, evaluateNode2, homeObject) {
10274
+ function createInterpretedClosure(node, context, evaluateNode2, homeObject, initializeGeneratorPrototype = true) {
10229
10275
  if (node.type !== "ArrowFunctionExpression") {
10230
10276
  context = { ...context, functionEnvironment: { homeObject } };
10231
10277
  }
10232
10278
  if (node.type !== "ArrowFunctionExpression" && node.generator) {
10233
- return createGeneratorClosure(node, context, evaluateNode2);
10279
+ return createGeneratorClosure(node, context, evaluateNode2, initializeGeneratorPrototype);
10234
10280
  }
10235
10281
  const construct = node.type !== "ArrowFunctionExpression" && !(node.type === "FunctionExpression" && node.method === true) && !node.async ? async (args, callContext) => {
10236
10282
  const thisValue = {};
@@ -10317,7 +10363,8 @@ function executeAsyncFunction(execute, budget, signal, callContext) {
10317
10363
  });
10318
10364
  return createSandboxPromise(promise, { synchronousPrefix });
10319
10365
  }
10320
- function createGeneratorClosure(node, context, evaluateNode2) {
10366
+ function createGeneratorClosure(node, context, evaluateNode2, initializePrototype) {
10367
+ const prototypes2 = !initializePrototype || runResources.getStore()?.functionSourceText === false ? void 0 : generatorPrototypes.get(context.budget)?.get(node.async === true);
10321
10368
  const closure = createSandboxClosure({
10322
10369
  sourceRange: functionSources.get(node),
10323
10370
  guest: true,
@@ -10327,54 +10374,69 @@ function createGeneratorClosure(node, context, evaluateNode2) {
10327
10374
  ...node.id === void 0 ? { name: context.inferredName } : { name: node.id.name },
10328
10375
  retainedValues: () => [...context.scope.retainedValues(), context.functionEnvironment?.homeObject, context.functionEnvironment?.newTarget],
10329
10376
  call: async (args, callContext) => {
10330
- const closureContext = {
10331
- ...context,
10332
- compilation: callContext?.compilation ?? context.compilation,
10333
- callStack: [...callContext?.stack ?? context.callStack]
10334
- };
10335
- const scope = await createClosureScope(
10336
- node,
10337
- args,
10338
- callContext?.thisValue,
10339
- closureContext,
10340
- evaluateNode2
10341
- );
10342
- const channel = createGeneratorChannel((generatorYield) => {
10343
- const execute = async () => {
10344
- const result = await evaluateNode2(node.body, {
10345
- ...closureContext,
10346
- functionBody: node.body,
10347
- asyncGenerator: node.async,
10348
- generatorBlockScopes: /* @__PURE__ */ new Map(),
10349
- generatorExpressionStates: /* @__PURE__ */ new Map(),
10350
- captureGeneratorScope: (suspendedScope, blocks, completions, expressions) => {
10351
- origin.suspendedScope = suspendedScope;
10352
- origin.blockScopes = blocks;
10353
- origin.finallyCompletions = completions;
10354
- origin.expressionStates = expressions;
10355
- },
10356
- generatorYield: (value2, yieldNodeId) => {
10357
- generator.state = "suspended";
10358
- return generatorYield(value2, yieldNodeId);
10359
- },
10360
- scope
10361
- });
10362
- if (result.kind === "error") {
10363
- throw result.error;
10364
- }
10365
- if (result.kind === "throw") {
10366
- throw result.value;
10367
- }
10368
- const value = result.hasValue ? result.value : void 0;
10369
- return node.async ? awaitSandboxValue(value, context.signal, context.budget, createCoercionContext(context)) : value;
10377
+ const candidate = prototypes2 === void 0 ? void 0 : getGuestFunctionProperty(closure, "prototype");
10378
+ const prototype = typeof candidate === "object" && candidate !== null ? candidate : prototypes2?.instancePrototype;
10379
+ const releasePrototype = prototype === void 0 ? void 0 : retainValues(context.budget, () => [prototype]);
10380
+ try {
10381
+ const closureContext = {
10382
+ ...context,
10383
+ compilation: callContext?.compilation ?? context.compilation,
10384
+ callStack: [...callContext?.stack ?? context.callStack]
10370
10385
  };
10371
- return node.async ? runAsyncPrefix(execute) : execute();
10372
- });
10373
- const generator = createSandboxGenerator(channel, { async: node.async });
10374
- const origin = registerGeneratorOrigin(generator, node, scope, closureContext);
10375
- return generator;
10386
+ const scope = await createClosureScope(
10387
+ node,
10388
+ args,
10389
+ callContext?.thisValue,
10390
+ closureContext,
10391
+ evaluateNode2
10392
+ );
10393
+ const channel = createGeneratorChannel((generatorYield) => {
10394
+ const execute = async () => {
10395
+ const result = await evaluateNode2(node.body, {
10396
+ ...closureContext,
10397
+ functionBody: node.body,
10398
+ asyncGenerator: node.async,
10399
+ generatorBlockScopes: /* @__PURE__ */ new Map(),
10400
+ generatorExpressionStates: /* @__PURE__ */ new Map(),
10401
+ captureGeneratorScope: (suspendedScope, blocks, completions, expressions) => {
10402
+ origin.suspendedScope = suspendedScope;
10403
+ origin.blockScopes = blocks;
10404
+ origin.finallyCompletions = completions;
10405
+ origin.expressionStates = expressions;
10406
+ },
10407
+ generatorYield: (value2, yieldNodeId) => {
10408
+ generator.state = "suspended";
10409
+ return generatorYield(value2, yieldNodeId);
10410
+ },
10411
+ scope
10412
+ });
10413
+ if (result.kind === "error") {
10414
+ throw result.error;
10415
+ }
10416
+ if (result.kind === "throw") {
10417
+ throw result.value;
10418
+ }
10419
+ const value = result.hasValue ? result.value : void 0;
10420
+ return node.async ? awaitSandboxValue(value, context.signal, context.budget, createCoercionContext(context)) : value;
10421
+ };
10422
+ return node.async ? runAsyncPrefix(execute) : execute();
10423
+ });
10424
+ const generator = createSandboxGenerator(channel, { async: node.async });
10425
+ if (prototype !== void 0) setSandboxPrototype(generator, prototype, context.budget);
10426
+ const origin = registerGeneratorOrigin(generator, node, scope, closureContext);
10427
+ return generator;
10428
+ } finally {
10429
+ releasePrototype?.();
10430
+ }
10376
10431
  }
10377
10432
  });
10433
+ if (prototypes2 !== void 0) {
10434
+ const prototype = /* @__PURE__ */ Object.create(null);
10435
+ markDescriptorObject(prototype);
10436
+ setSandboxPrototype(prototype, prototypes2.instancePrototype);
10437
+ Object.defineProperty(materializeFunctionProperties(closure), "prototype", { value: prototype, writable: true });
10438
+ setSandboxPrototype(closure, prototypes2.functionPrototype);
10439
+ }
10378
10440
  registerClosureOrigin(closure, node, context);
10379
10441
  return closure;
10380
10442
  }
@@ -13261,6 +13323,32 @@ function createArrayGlobal(budget) {
13261
13323
  length: 0,
13262
13324
  call: (_args, context) => context?.thisValue
13263
13325
  }), writable: true, configurable: true });
13326
+ const iteratorTagGetter = createSandboxClosure({
13327
+ guest: true,
13328
+ sandbox: true,
13329
+ name: "get [Symbol.toStringTag]",
13330
+ length: 0,
13331
+ call: () => "Iterator"
13332
+ });
13333
+ const iteratorTagSetter = createSandboxClosure({
13334
+ guest: true,
13335
+ sandbox: true,
13336
+ name: "set [Symbol.toStringTag]",
13337
+ length: 1,
13338
+ call: ([value], context) => {
13339
+ const receiver = context?.thisValue;
13340
+ if (receiver === iterablePrototype || receiver === null || typeof receiver !== "object")
13341
+ throw new TypeError("Iterator tag setter requires a distinct object receiver.");
13342
+ defineOwnDataProperty(objectProperties(receiver, true), Symbol.toStringTag, value);
13343
+ createDataCheckpoint(budget, context)(receiver, 0, true);
13344
+ return void 0;
13345
+ }
13346
+ });
13347
+ Object.defineProperty(iterablePrototype, Symbol.toStringTag, {
13348
+ get: accessorAdapter(iteratorTagGetter, "get"),
13349
+ set: accessorAdapter(iteratorTagSetter, "set"),
13350
+ configurable: true
13351
+ });
13264
13352
  setSandboxPrototype(iterablePrototype, getSandboxPrototype(/* @__PURE__ */ Object.create(null), budget));
13265
13353
  setSandboxPrototype(iteratorPrototype, iterablePrototype);
13266
13354
  Object.defineProperties(iteratorPrototype, {
@@ -13274,6 +13362,9 @@ function createArrayGlobal(budget) {
13274
13362
  [Symbol.toStringTag]: { value: "Array Iterator", configurable: true }
13275
13363
  });
13276
13364
  registerBuiltinIdentities(budget, { "%ArrayIteratorPrototype%": iteratorPrototype, "%IteratorPrototype%": iterablePrototype });
13365
+ registerIntrinsicFunction(budget, iterablePrototype[Symbol.iterator]);
13366
+ registerIntrinsicFunction(budget, iteratorTagGetter);
13367
+ registerIntrinsicFunction(budget, iteratorTagSetter);
13277
13368
  registerIntrinsicObject(budget, iterablePrototype);
13278
13369
  registerIntrinsicObject(budget, iteratorPrototype);
13279
13370
  for (const method of ["keys", "values", "entries"]) {
@@ -13998,6 +14089,34 @@ function functionString(value) {
13998
14089
  return `function ${name}() { [native code] }`;
13999
14090
  }
14000
14091
 
14092
+ // packages/safe-js/src/interp/bound-function-state.ts
14093
+ var boundFunctionStates = /* @__PURE__ */ new WeakMap();
14094
+
14095
+ // packages/safe-js/src/interp/bound-function.ts
14096
+ function createBoundFunction(state, name, length, callClosure) {
14097
+ const bound = createSandboxClosure({
14098
+ guest: true,
14099
+ sandbox: true,
14100
+ name,
14101
+ length,
14102
+ boundTarget: state.target,
14103
+ retainedValues: () => [state.target, state.thisValue, ...state.args, bound.name],
14104
+ call: (args, context) => callClosure(state.target, [...state.args, ...args], context?.stack ?? [], state.thisValue),
14105
+ ...state.target.construct === void 0 ? {} : {
14106
+ construct: (args, context) => callClosure(
14107
+ state.target,
14108
+ [...state.args, ...args],
14109
+ context?.stack ?? [],
14110
+ void 0,
14111
+ true,
14112
+ context?.newTarget === bound ? state.target : context?.newTarget
14113
+ )
14114
+ }
14115
+ });
14116
+ boundFunctionStates.set(bound, state);
14117
+ return bound;
14118
+ }
14119
+
14001
14120
  // packages/safe-js/src/interp/methods/function.ts
14002
14121
  var functionMethodNames = /* @__PURE__ */ new Set(["apply", "bind", "call", "toString"]);
14003
14122
  function getFunctionMember(target, property, options) {
@@ -14049,28 +14168,11 @@ function callFunctionMethod(target, methodName, args, options, stack, context) {
14049
14168
  const thisValue = args[0];
14050
14169
  if (methodName === "bind") {
14051
14170
  const boundArgs = args.slice(1);
14171
+ const explicitPrototype = hasExplicitSandboxPrototype(target);
14172
+ const prototype = getSandboxPrototype(target, options.budget);
14052
14173
  const bind = (length, name) => {
14053
- const bound = createSandboxClosure({
14054
- guest: true,
14055
- sandbox: true,
14056
- name: `bound ${name}`,
14057
- length,
14058
- boundTarget: target,
14059
- retainedValues: () => [target, thisValue, ...boundArgs, bound.name],
14060
- call: (callArgs, context2) => options.callClosure(target, [...boundArgs, ...callArgs], context2?.stack ?? [], thisValue),
14061
- ...target.construct === void 0 ? {} : {
14062
- construct: (callArgs, context2) => options.callClosure(
14063
- target,
14064
- [...boundArgs, ...callArgs],
14065
- context2?.stack ?? [],
14066
- void 0,
14067
- true,
14068
- context2?.newTarget === bound ? target : context2?.newTarget
14069
- )
14070
- }
14071
- });
14072
- if (hasExplicitSandboxPrototype(target))
14073
- setSandboxPrototype(bound, getSandboxPrototype(target, options.budget), options.budget);
14174
+ const bound = createBoundFunction({ target, thisValue, args: boundArgs }, `bound ${name}`, length, options.callClosure);
14175
+ if (explicitPrototype) setSandboxPrototype(bound, prototype, options.budget);
14074
14176
  return bound;
14075
14177
  };
14076
14178
  if (context?.getProperty === void 0)
@@ -14079,15 +14181,20 @@ function callFunctionMethod(target, methodName, args, options, stack, context) {
14079
14181
  target.name ?? ""
14080
14182
  );
14081
14183
  return (async () => {
14082
- const properties = target.properties;
14083
- const defaultName = target.name;
14084
- const hasLength = !isGuestClosure(target) || target.properties === void 0 || Object.hasOwn(target.properties, "length");
14085
- const length = hasLength ? await context.getProperty(target, "length") : void 0;
14086
- const name = !isGuestClosure(target) && !Object.hasOwn(properties ?? {}, "name") ? defaultName : await context.getProperty(target, "name");
14087
- return bind(
14088
- typeof length === "number" && !Number.isNaN(length) ? Math.max(0, Math.trunc(length) - boundArgs.length) : 0,
14089
- typeof name === "string" ? name : ""
14090
- );
14184
+ const release = options.budget !== void 0 && explicitPrototype && prototype !== null ? retainValues(options.budget, () => [prototype]) : void 0;
14185
+ try {
14186
+ const properties = target.properties;
14187
+ const defaultName = target.name;
14188
+ const hasLength = !isGuestClosure(target) || target.properties === void 0 || Object.hasOwn(target.properties, "length");
14189
+ const length = hasLength ? await context.getProperty(target, "length") : void 0;
14190
+ const name = !isGuestClosure(target) && !Object.hasOwn(properties ?? {}, "name") ? defaultName : await context.getProperty(target, "name");
14191
+ return bind(
14192
+ typeof length === "number" && !Number.isNaN(length) ? Math.max(0, Math.trunc(length) - boundArgs.length) : 0,
14193
+ typeof name === "string" ? name : ""
14194
+ );
14195
+ } finally {
14196
+ release?.();
14197
+ }
14091
14198
  })();
14092
14199
  }
14093
14200
  if (methodName === "call") {
@@ -14097,25 +14204,37 @@ function callFunctionMethod(target, methodName, args, options, stack, context) {
14097
14204
  if (applyArgs === null || applyArgs === void 0) {
14098
14205
  return options.callClosure(target, [], stack, thisValue);
14099
14206
  }
14100
- if (!Array.isArray(applyArgs)) {
14101
- throw new TypeError("Function#apply requires an array or nullish arguments value.");
14207
+ if (typeof applyArgs !== "object") {
14208
+ throw new TypeError("Function#apply requires an object or nullish arguments value.");
14102
14209
  }
14103
- if (context?.getProperty === void 0)
14210
+ if (context?.getProperty === void 0 && Array.isArray(applyArgs))
14104
14211
  return options.callClosure(target, applyArgs, stack, thisValue);
14105
14212
  return (async () => {
14213
+ const budget = options.budget ?? new Budget();
14214
+ const invocationContext = {
14215
+ ...context,
14216
+ stack,
14217
+ thisValue: context?.thisValue,
14218
+ invokeClosure: context?.invokeClosure ?? ((callee, values2, receiver) => Promise.resolve(options.callClosure(callee, values2, stack, receiver)))
14219
+ };
14220
+ const read = (value, key) => {
14221
+ if (context?.getProperty !== void 0) return context.getProperty(value, key);
14222
+ const descriptor = getSandboxPropertyDescriptor(value, key, budget);
14223
+ return descriptor === void 0 ? void 0 : readPropertyDescriptor(descriptor, value, invocationContext);
14224
+ };
14106
14225
  const values = [];
14107
- const length = applyArgs.length;
14108
- options.budget?.allocateArrayLength(length);
14109
- const retained = {};
14110
- options.budget?.setRetainedValues(retained, () => values);
14226
+ const release = retainValues(budget, () => [applyArgs, ...values]);
14111
14227
  try {
14228
+ const number = await sandboxNumber(await read(applyArgs, "length"), budget, invocationContext);
14229
+ const length = Number.isNaN(number) || number <= 0 ? 0 : Math.min(Math.trunc(number), Number.MAX_SAFE_INTEGER);
14230
+ budget.allocateArrayLength(length);
14112
14231
  for (let index = 0; index < length; index++) {
14113
- options.budget?.visitNode();
14114
- values.push(await context.getProperty(applyArgs, index));
14232
+ budget.visitNode();
14233
+ values.push(await read(applyArgs, String(index)));
14115
14234
  }
14116
14235
  return await options.callClosure(target, values, stack, thisValue);
14117
14236
  } finally {
14118
- options.budget?.setRetainedValues(retained, void 0);
14237
+ release();
14119
14238
  }
14120
14239
  })();
14121
14240
  }
@@ -14272,16 +14391,19 @@ function getGeneratorMember(target, property, budget) {
14272
14391
  return createSandboxClosure({
14273
14392
  sandbox: true,
14274
14393
  name: property,
14275
- call: ([value], context) => {
14276
- const iterator = generatorIterator(target, budget, context);
14277
- const result = Promise.resolve(iterator[property](value)).then((result2) => allocateProducedSandboxValue(
14278
- { value: result2.value, done: result2.done === true },
14279
- budget
14280
- ));
14281
- return target.async ? createSandboxPromise(result) : result;
14282
- }
14394
+ call: ([value], context) => callGeneratorMethod(target, property, value, budget, context, target.async === true)
14283
14395
  });
14284
14396
  }
14397
+ function callGeneratorMethod(target, method, value, budget, context, async) {
14398
+ const result = (async () => {
14399
+ if (!isSandboxGenerator(target) || target.async === true !== async)
14400
+ throw new TypeError(`${async ? "AsyncGenerator" : "Generator"}.${method} requires a matching generator receiver.`);
14401
+ const iterator = generatorIterator(target, budget, context);
14402
+ const result2 = await iterator[method](value);
14403
+ return allocateProducedSandboxValue({ value: result2.value, done: result2.done === true }, budget);
14404
+ })();
14405
+ return async ? createSandboxPromise(result) : result;
14406
+ }
14285
14407
 
14286
14408
  // packages/safe-js/src/interp/methods/set.ts
14287
14409
  var setMethodNames = /* @__PURE__ */ new Set([
@@ -14361,74 +14483,6 @@ async function callSetMethod(target, methodName, args, options, stack = []) {
14361
14483
  }
14362
14484
  }
14363
14485
 
14364
- // packages/safe-js/src/interp/globals/error.ts
14365
- var errorConstructorNames = /* @__PURE__ */ new WeakMap();
14366
- var errorNames = [
14367
- "Error",
14368
- "TypeError",
14369
- "RangeError",
14370
- "ReferenceError",
14371
- "SyntaxError",
14372
- "URIError",
14373
- "EvalError",
14374
- "AggregateError"
14375
- ];
14376
- function createErrorGlobals(options) {
14377
- return Object.fromEntries(
14378
- errorNames.map((name) => [name, createErrorConstructor(name, options.budget)])
14379
- );
14380
- }
14381
- function isSandboxErrorConstructorInstance2(value, constructor) {
14382
- if (!isSandboxClosure(constructor)) {
14383
- throw new TypeError("Right-hand side of 'instanceof' is not a function.");
14384
- }
14385
- const name = errorConstructorNames.get(constructor);
14386
- if (name === void 0) {
14387
- return false;
14388
- }
14389
- return isSandboxErrorConstructorInstance(value, name);
14390
- }
14391
- function createErrorConstructor(name, budget) {
14392
- const call = (args, context) => createSubsetError(name, args, context?.stack ?? [], budget);
14393
- const closure = createSandboxClosure({ sandbox: true, call, construct: call, name });
14394
- errorConstructorNames.set(closure, name);
14395
- return closure;
14396
- }
14397
- function createSubsetError(name, args, stackFrames, budget) {
14398
- const message = name === "AggregateError" ? args[1] : args[0];
14399
- const options = name === "AggregateError" ? args[2] : args[1];
14400
- const error = createSubsetErrorValue(name, message, stackFrames, budget);
14401
- if (name === "AggregateError") {
14402
- const errors = Array.isArray(args[0]) ? [...args[0]] : [];
14403
- budget.allocateArrayLength(errors.length);
14404
- error.errors = errors;
14405
- }
14406
- if (isObjectLike(options) && Object.prototype.hasOwnProperty.call(options, "cause")) {
14407
- error.cause = options.cause;
14408
- }
14409
- return error;
14410
- }
14411
- function isObjectLike(value) {
14412
- return typeof value === "object" && value !== null;
14413
- }
14414
-
14415
- // packages/safe-js/src/interp/methods/collection-iterator.ts
14416
- function getCollectionIteratorMember(target, property, budget) {
14417
- if (Object.hasOwn(target, property)) return target[property];
14418
- if (property !== "next") return void 0;
14419
- const { collectionKind } = collectionIteratorState(target);
14420
- return createSandboxClosure({
14421
- sandbox: true,
14422
- name: "next",
14423
- call: (_args, context) => {
14424
- const receiver = context?.thisValue;
14425
- if (!isSandboxCollectionIterator(receiver) || collectionIteratorState(receiver).collectionKind !== collectionKind)
14426
- throw new TypeError("Iterator next requires a matching collection iterator receiver.");
14427
- return nextCollectionIterator(receiver, budget);
14428
- }
14429
- });
14430
- }
14431
-
14432
14486
  // packages/safe-js/src/interp/globals/float32array.ts
14433
14487
  var constructors = /* @__PURE__ */ new WeakSet();
14434
14488
  function createFloat32ArrayGlobal(budget) {
@@ -14554,6 +14608,207 @@ function relativeIndex(value, length, fallback) {
14554
14608
  return integer2 < 0 ? Math.max(length + integer2, 0) : Math.min(integer2, length);
14555
14609
  }
14556
14610
 
14611
+ // packages/safe-js/src/interp/globals/error.ts
14612
+ var errorConstructorNames = /* @__PURE__ */ new WeakMap();
14613
+ var errorNames = [
14614
+ "Error",
14615
+ "TypeError",
14616
+ "RangeError",
14617
+ "ReferenceError",
14618
+ "SyntaxError",
14619
+ "URIError",
14620
+ "EvalError",
14621
+ "AggregateError"
14622
+ ];
14623
+ function createErrorGlobals(options) {
14624
+ return Object.fromEntries(
14625
+ errorNames.map((name) => [name, createErrorConstructor(name, options.budget, options.errorPrototypes === true)])
14626
+ );
14627
+ }
14628
+ function isSandboxErrorConstructorInstance2(value, constructor) {
14629
+ if (!isSandboxClosure(constructor)) {
14630
+ throw new TypeError("Right-hand side of 'instanceof' is not a function.");
14631
+ }
14632
+ const name = errorConstructorNames.get(constructor);
14633
+ if (name === void 0) {
14634
+ return false;
14635
+ }
14636
+ return isSandboxErrorConstructorInstance(value, name);
14637
+ }
14638
+ function createErrorConstructor(name, budget, guest) {
14639
+ const call = (args, context) => errorPrototypes.has(budget) ? createNativeError(name, args, budget, context, closure) : createSubsetError(name, args, context?.stack ?? [], budget);
14640
+ const closure = createSandboxClosure({ guest, sandbox: true, call, construct: call, name, length: name === "AggregateError" ? 2 : 1 });
14641
+ errorConstructorNames.set(closure, name);
14642
+ return closure;
14643
+ }
14644
+ function createErrorPrototypes(budget, constructors2) {
14645
+ const prototypes2 = /* @__PURE__ */ new Map();
14646
+ for (const name of errorNames) prototypes2.set(name, /* @__PURE__ */ Object.create(null));
14647
+ errorPrototypes.set(budget, prototypes2);
14648
+ for (const name of errorNames) {
14649
+ const constructor = constructors2[name];
14650
+ const prototype = prototypes2.get(name);
14651
+ Object.defineProperties(prototype, {
14652
+ name: { value: name, writable: true, configurable: true },
14653
+ message: { value: "", writable: true, configurable: true },
14654
+ constructor: { value: constructor, writable: true, configurable: true }
14655
+ });
14656
+ Object.defineProperty(materializeFunctionProperties(constructor), "prototype", { value: prototype, writable: false });
14657
+ setSandboxPrototype(prototype, name === "Error" ? getSandboxPrototype(/* @__PURE__ */ Object.create(null), budget) : prototypes2.get("Error"));
14658
+ if (name !== "Error") setSandboxPrototype(constructor, constructors2.Error);
14659
+ }
14660
+ Object.defineProperty(prototypes2.get("Error"), "toString", {
14661
+ writable: true,
14662
+ configurable: true,
14663
+ value: createSandboxClosure({
14664
+ guest: true,
14665
+ sandbox: true,
14666
+ name: "toString",
14667
+ length: 0,
14668
+ call: async (_args, context) => {
14669
+ const receiver = context?.thisValue;
14670
+ if (receiver === null || typeof receiver !== "object") throw new TypeError("Error.prototype.toString requires an object.");
14671
+ let name;
14672
+ const release = retainValues(budget, () => [receiver, name]);
14673
+ try {
14674
+ const rawName = await readErrorProperty(receiver, "name", budget, context);
14675
+ name = rawName === void 0 ? "Error" : await sandboxString(rawName, budget, context);
14676
+ const rawMessage = await readErrorProperty(receiver, "message", budget, context);
14677
+ const message = rawMessage === void 0 ? "" : await sandboxString(rawMessage, budget, context);
14678
+ return budget.allocateString(name === "" ? message : message === "" ? name : `${name}: ${message}`);
14679
+ } finally {
14680
+ release();
14681
+ }
14682
+ }
14683
+ })
14684
+ });
14685
+ registerBuiltinIdentities(budget, Object.fromEntries(errorNames.map((name) => [name, constructors2[name]])));
14686
+ for (const name of errorNames) {
14687
+ registerIntrinsicFunction(budget, constructors2[name]);
14688
+ registerIntrinsicObject(budget, prototypes2.get(name));
14689
+ }
14690
+ }
14691
+ async function readErrorProperty(value, key, budget, context) {
14692
+ if (context?.getProperty !== void 0) return context.getProperty(value, key);
14693
+ const descriptor = getSandboxPropertyDescriptor(value, key, budget);
14694
+ return descriptor === void 0 ? void 0 : readPropertyDescriptor(descriptor, value, context);
14695
+ }
14696
+ async function createNativeError(name, args, budget, context, constructor) {
14697
+ const newTarget = context?.newTarget ?? constructor;
14698
+ const candidate = await readErrorProperty(newTarget, "prototype", budget, context);
14699
+ const prototype = candidate !== null && typeof candidate === "object" ? candidate : errorPrototypes.get(budget).get(name);
14700
+ let error;
14701
+ let iterator;
14702
+ const errors = [];
14703
+ const release = retainValues(budget, () => [prototype, error, iterator?.retainedValue, ...errors, ...args]);
14704
+ try {
14705
+ const message = name === "AggregateError" ? args[1] : args[0];
14706
+ const options = name === "AggregateError" ? args[2] : args[1];
14707
+ const text = message === void 0 ? void 0 : await sandboxString(message, budget, context);
14708
+ error = createSubsetErrorValue(name, text, context?.stack ?? [], budget);
14709
+ setSandboxPrototype(error, prototype, budget);
14710
+ if (options !== null && typeof options === "object" && getSandboxPropertyDescriptor(options, "cause", budget) !== void 0) {
14711
+ const cause = await readErrorProperty(options, "cause", budget, context);
14712
+ Object.defineProperty(error, "cause", { value: cause, writable: true, configurable: true });
14713
+ }
14714
+ if (name === "AggregateError") {
14715
+ iterator = context === void 0 ? getSandboxIterator(args[0], budget) : await acquireSandboxIterator(args[0], budget, context);
14716
+ if (iterator === void 0) throw new TypeError("AggregateError errors must be iterable.");
14717
+ while (true) {
14718
+ budget.visitNode();
14719
+ const result = await iterator.next();
14720
+ if (result === null || typeof result !== "object") throw new TypeError("Iterator result must be an object.");
14721
+ if ((await readIteratorResult(iterator, result, "done")).value) break;
14722
+ budget.allocateArrayLength(errors.length + 1);
14723
+ errors.push((await readIteratorResult(iterator, result, "value")).value);
14724
+ }
14725
+ Object.defineProperty(error, "errors", { value: errors, writable: true, configurable: true });
14726
+ }
14727
+ return error;
14728
+ } finally {
14729
+ release();
14730
+ }
14731
+ }
14732
+ function createSubsetError(name, args, stackFrames, budget) {
14733
+ const message = name === "AggregateError" ? args[1] : args[0];
14734
+ const options = name === "AggregateError" ? args[2] : args[1];
14735
+ const error = createSubsetErrorValue(name, message, stackFrames, budget);
14736
+ if (name === "AggregateError") {
14737
+ const errors = Array.isArray(args[0]) ? [...args[0]] : [];
14738
+ budget.allocateArrayLength(errors.length);
14739
+ error.errors = errors;
14740
+ }
14741
+ if (isObjectLike(options) && Object.prototype.hasOwnProperty.call(options, "cause")) {
14742
+ error.cause = options.cause;
14743
+ }
14744
+ return error;
14745
+ }
14746
+ function isObjectLike(value) {
14747
+ return typeof value === "object" && value !== null;
14748
+ }
14749
+
14750
+ // packages/safe-js/src/interp/instanceof.ts
14751
+ async function evaluateInstanceof(value, constructor, budget, context) {
14752
+ if (constructor === null || typeof constructor !== "object")
14753
+ throw new TypeError("Right-hand side of 'instanceof' must be an object.");
14754
+ const method = await readInstanceProperty(constructor, Symbol.hasInstance, budget, context);
14755
+ if (method !== void 0 && method !== null) {
14756
+ if (!isSandboxClosure(method)) throw new TypeError("Symbol.hasInstance must be callable.");
14757
+ return Boolean(await invokeBuiltinClosure(method, [value], budget, context, constructor));
14758
+ }
14759
+ if (!isSandboxClosure(constructor))
14760
+ throw new TypeError("Right-hand side of 'instanceof' is not a function.");
14761
+ return ordinaryHasInstance(value, constructor, budget, context);
14762
+ }
14763
+ async function ordinaryHasInstance(value, constructor, budget, context) {
14764
+ if (!isSandboxClosure(constructor)) return false;
14765
+ if (constructor.boundTarget !== void 0) {
14766
+ budget.visitNode();
14767
+ return evaluateInstanceof(value, constructor.boundTarget, budget, context);
14768
+ }
14769
+ if (isFloat32ArrayConstructor(constructor)) return isFloat32Array(value);
14770
+ if ((!isGuestClosure(constructor) || value !== null && typeof value === "object" && !hasExplicitSandboxPrototype(value)) && isSandboxErrorConstructorInstance2(value, constructor)) return true;
14771
+ if (!isGuestClosure(constructor) || typeof value !== "object" || value === null) return false;
14772
+ const prototype = await readInstanceProperty(constructor, "prototype", budget, context);
14773
+ if (typeof prototype !== "object" || prototype === null)
14774
+ throw new TypeError("Function has a non-object prototype in instanceof check.");
14775
+ let depth = 0;
14776
+ for (let current = getSandboxPrototype(value, budget); current !== null; current = getSandboxPrototype(current, budget)) {
14777
+ budget.visitNode();
14778
+ assertSandboxDataDepth(depth++);
14779
+ if (current === prototype) return true;
14780
+ }
14781
+ return false;
14782
+ }
14783
+ async function readInstanceProperty(value, key, budget, context) {
14784
+ if (context?.getProperty !== void 0) return context.getProperty(value, key);
14785
+ const descriptor = getSandboxPropertyDescriptor(value, key, budget);
14786
+ if (descriptor === void 0) return void 0;
14787
+ return readPropertyDescriptor(descriptor, value, {
14788
+ ...context,
14789
+ stack: context?.stack ?? [],
14790
+ thisValue: value,
14791
+ invokeClosure: context?.invokeClosure ?? ((closure, args, receiver) => invokeBuiltinClosure(closure, args, budget, context, receiver))
14792
+ });
14793
+ }
14794
+
14795
+ // packages/safe-js/src/interp/methods/collection-iterator.ts
14796
+ function getCollectionIteratorMember(target, property, budget) {
14797
+ if (Object.hasOwn(target, property)) return target[property];
14798
+ if (property !== "next") return void 0;
14799
+ const { collectionKind } = collectionIteratorState(target);
14800
+ return createSandboxClosure({
14801
+ sandbox: true,
14802
+ name: "next",
14803
+ call: (_args, context) => {
14804
+ const receiver = context?.thisValue;
14805
+ if (!isSandboxCollectionIterator(receiver) || collectionIteratorState(receiver).collectionKind !== collectionKind)
14806
+ throw new TypeError("Iterator next requires a matching collection iterator receiver.");
14807
+ return nextCollectionIterator(receiver, budget);
14808
+ }
14809
+ });
14810
+ }
14811
+
14557
14812
  // packages/safe-js/src/interp/scope.ts
14558
14813
  var uninitialized = /* @__PURE__ */ Symbol("uninitialized");
14559
14814
  var Scope = class _Scope {
@@ -17418,42 +17673,11 @@ function applyBinaryOperator(node, left, right, context) {
17418
17673
  case ">>>":
17419
17674
  return toNumber(left) >>> toNumber(right);
17420
17675
  case "instanceof":
17421
- return evaluateInstanceof(left, right, context);
17676
+ return evaluateInstanceof(left, right, context.budget, createCoercionContext(context));
17422
17677
  case "in":
17423
17678
  return hasSandboxProperty(right, left, context);
17424
17679
  }
17425
17680
  }
17426
- async function evaluateInstanceof(left, right, context) {
17427
- while (true) {
17428
- if (right === null || typeof right !== "object" && typeof right !== "function")
17429
- throw new TypeError("Right-hand side of 'instanceof' must be an object.");
17430
- const method = await getPropertyValue(right, Symbol.hasInstance, context);
17431
- if (method !== void 0 && method !== null) {
17432
- if (!isSandboxClosure(method)) throw new TypeError("Symbol.hasInstance must be callable.");
17433
- return Boolean(await invokeSandboxClosure(method, [left], context, context.callStack, void 0, right));
17434
- }
17435
- if (!isSandboxClosure(right))
17436
- throw new TypeError("Right-hand side of 'instanceof' is not a function.");
17437
- if (right.boundTarget === void 0) break;
17438
- context.budget.visitNode();
17439
- right = right.boundTarget;
17440
- }
17441
- if (isFloat32ArrayConstructor(right)) return isFloat32Array(left);
17442
- if (isSandboxErrorConstructorInstance2(left, right)) return true;
17443
- if (isGuestClosure(right)) {
17444
- if (typeof left !== "object" || left === null) return false;
17445
- const prototype = await getPropertyValue(right, "prototype", context);
17446
- if (typeof prototype !== "object" || prototype === null)
17447
- throw new TypeError("Function has a non-object prototype in instanceof check.");
17448
- let depth = 0;
17449
- for (let current = getSandboxPrototype(left, context.budget); current !== null; current = getSandboxPrototype(current, context.budget)) {
17450
- context.budget.visitNode();
17451
- assertSandboxDataDepth(depth++);
17452
- if (current === prototype) return true;
17453
- }
17454
- }
17455
- return false;
17456
- }
17457
17681
  function createCoercionContext(context) {
17458
17682
  return {
17459
17683
  stack: context.callStack,
@@ -18742,11 +18966,10 @@ function surfaceThrownValue(reason, budget, stackFrames = [], span) {
18742
18966
  throw reason;
18743
18967
  }
18744
18968
  if (isSubsetErrorValue(reason)) {
18745
- normalizeSurfacedSubsetError(reason, budget, stackFrames, span);
18746
- return reason;
18969
+ return normalizeSurfacedSubsetError(reason, budget, stackFrames, span);
18747
18970
  }
18748
18971
  if (reason instanceof Error) {
18749
- const error = createSubsetErrorValue(
18972
+ const error2 = createSubsetErrorValue(
18750
18973
  reason.name || "Error",
18751
18974
  reason.message,
18752
18975
  stackFrames,
@@ -18757,11 +18980,10 @@ function surfaceThrownValue(reason, budget, stackFrames = [], span) {
18757
18980
  span
18758
18981
  }
18759
18982
  );
18760
- normalizeSurfacedSubsetError(error, budget, stackFrames, span);
18761
- return error;
18983
+ return normalizeSurfacedSubsetError(error2, budget, stackFrames, span);
18762
18984
  }
18763
18985
  if (isErrorLikeValue(reason)) {
18764
- const error = createSubsetErrorValue(
18986
+ const error2 = createSubsetErrorValue(
18765
18987
  reason.name || "Error",
18766
18988
  reason.message,
18767
18989
  stackFrames,
@@ -18772,13 +18994,13 @@ function surfaceThrownValue(reason, budget, stackFrames = [], span) {
18772
18994
  span
18773
18995
  }
18774
18996
  );
18775
- normalizeSurfacedSubsetError(error, budget, stackFrames, span);
18776
- return error;
18997
+ return normalizeSurfacedSubsetError(error2, budget, stackFrames, span);
18777
18998
  }
18778
- return createSubsetErrorValue("Error", describeThrownValue(reason), stackFrames, budget, {
18999
+ const error = createSubsetErrorValue("Error", describeThrownValue(reason), stackFrames, budget, {
18779
19000
  chargeBudget: false,
18780
19001
  span
18781
19002
  });
19003
+ return normalizeSurfacedSubsetError(error, budget, stackFrames, span);
18782
19004
  }
18783
19005
  function createSubsetErrorValue(name, message, stackFrames, budget, options = {}) {
18784
19006
  const resumeChecks = options.chargeBudget === false ? budget.suspendChecks() : void 0;
@@ -18787,11 +19009,15 @@ function createSubsetErrorValue(name, message, stackFrames, budget, options = {}
18787
19009
  const errorMessage = budget.allocateString(coerceErrorMessage(message));
18788
19010
  const header = errorMessage === "" ? errorName : `${errorName}: ${errorMessage}`;
18789
19011
  const stack = budget.allocateString([header, ...[...stackFrames].reverse()].join("\n"));
18790
- const error = {
18791
- name: errorName,
18792
- message: errorMessage,
18793
- stack
18794
- };
19012
+ const prototype = options.transport ? void 0 : errorPrototypes.get(budget)?.get(toSandboxErrorName(errorName));
19013
+ const error = prototype === void 0 ? { name: errorName, message: errorMessage, stack } : {};
19014
+ if (prototype !== void 0) {
19015
+ if (message !== void 0) Object.defineProperty(error, "message", { value: errorMessage, writable: true, configurable: true });
19016
+ if (!errorPrototypes.get(budget).has(errorName))
19017
+ Object.defineProperty(error, "name", { value: errorName, writable: true, configurable: true });
19018
+ Object.defineProperty(error, "stack", { value: stack, writable: true, configurable: true });
19019
+ setSandboxPrototype(error, prototype, budget);
19020
+ }
18795
19021
  sandboxErrorTypes.set(error, toSandboxErrorName(errorName));
18796
19022
  attachErrorSpan(error, options.span);
18797
19023
  attachWrappedErrorCause(error, options.cause);
@@ -18812,6 +19038,7 @@ function isSubsetErrorValue(value) {
18812
19038
  if (typeof value !== "object" || value === null) {
18813
19039
  return false;
18814
19040
  }
19041
+ if (sandboxErrorTypes.has(value)) return true;
18815
19042
  const prototype = Object.getPrototypeOf(value);
18816
19043
  return (prototype === Object.prototype || prototype === null) && typeof value.name === "string" && typeof value.message === "string" && typeof value.stack === "string";
18817
19044
  }
@@ -18821,21 +19048,37 @@ function normalizeSurfacedSubsetError(error, budget, stackFrames, span) {
18821
19048
  const name = budget.allocateString(toSandboxErrorName(readErrorName(error)));
18822
19049
  const message = budget.allocateString(readSurfacedErrorMessage(error, name));
18823
19050
  const frames = readSandboxStackFrames(error.stack);
19051
+ if (!Object.isExtensible(error) || ["name", "message", "stack"].some((key) => {
19052
+ const descriptor = Object.getOwnPropertyDescriptor(error, key);
19053
+ return descriptor !== void 0 && (!("value" in descriptor) || !descriptor.writable);
19054
+ })) {
19055
+ const original = error;
19056
+ const descriptors2 = Object.getOwnPropertyDescriptors(original);
19057
+ delete descriptors2.name;
19058
+ delete descriptors2.message;
19059
+ delete descriptors2.stack;
19060
+ error = Object.defineProperties({}, descriptors2);
19061
+ const errorType = sandboxErrorTypes.get(original);
19062
+ if (errorType !== void 0) sandboxErrorTypes.set(error, errorType);
19063
+ }
18824
19064
  error.name = name;
18825
19065
  error.message = message;
18826
19066
  error.stack = budget.allocateString(
18827
19067
  formatErrorStack(name, message, frames.length > 0 ? frames : [...stackFrames].reverse())
18828
19068
  );
18829
19069
  attachErrorSpan(error, readErrorSpan(error) ?? span);
19070
+ return error;
18830
19071
  } finally {
18831
19072
  resumeChecks();
18832
19073
  }
18833
19074
  }
18834
19075
  function readErrorName(error) {
18835
- return typeof error.name === "string" && error.name.length > 0 ? error.name : "Error";
19076
+ const name = getSandboxDataProperty(error, "name");
19077
+ return typeof name === "string" && name.length > 0 ? name : sandboxErrorTypes.get(error) ?? "Error";
18836
19078
  }
18837
19079
  function readSurfacedErrorMessage(error, name) {
18838
- const message = typeof error.message === "string" ? error.message : "";
19080
+ const value = getSandboxDataProperty(error, "message");
19081
+ const message = typeof value === "string" ? value : "";
18839
19082
  if (message === "") {
18840
19083
  return `${name} thrown`;
18841
19084
  }
@@ -20190,6 +20433,18 @@ function captureGuestHeapNode(value, encode) {
20190
20433
  const state2 = captureObjectState(value, encode);
20191
20434
  return { kind: "intrinsic", id: intrinsic, ...state2 === void 0 ? {} : { state: state2 } };
20192
20435
  }
20436
+ const bound = boundFunctionStates.get(value);
20437
+ if (bound !== void 0 && isSandboxClosure(value)) {
20438
+ return {
20439
+ kind: "bound-function",
20440
+ target: encode(bound.target),
20441
+ thisValue: encode(bound.thisValue),
20442
+ args: bound.args.map(encode),
20443
+ length: encode(value.length),
20444
+ ...value.name === void 0 ? {} : { name: value.name },
20445
+ state: captureObjectState(value, encode)
20446
+ };
20447
+ }
20193
20448
  if (isSandboxMap(value)) return { kind: "map", entries: [...value.entries].map(([key, entry]) => [encode(key), encode(entry)]), ...serializeCollectionProperties(value, encode) };
20194
20449
  if (isSandboxSet(value)) return { kind: "set", values: [...value.values].map(encode), ...serializeCollectionProperties(value, encode) };
20195
20450
  if (isSandboxArrayIterator(value)) {
@@ -20333,8 +20588,14 @@ function captureGuestHeapNode(value, encode) {
20333
20588
  }
20334
20589
  if (isLiveCapability(value) || isSandboxClosure(value) || isSandboxBox(value) || isSandboxDate(value) || isSandboxRegex(value) || isSandboxMap(value) || isSandboxSet(value) || isSandboxPromise(value) || isSandboxGenerator(value) || isSandboxArguments(value) || isSandboxCollectionIterator(value) || isSandboxRegExpIterator(value)) return void 0;
20335
20590
  const prototype = Object.getPrototypeOf(value);
20336
- if ((prototype === null || prototype === Object.prototype) && hasGuestObjectState(value))
20337
- return { kind: "guest-object", state: captureObjectState(value, encode) };
20591
+ if ((prototype === null || prototype === Object.prototype) && hasGuestObjectState(value)) {
20592
+ const errorType = sandboxErrorTypes.get(value);
20593
+ return {
20594
+ kind: "guest-object",
20595
+ state: captureObjectState(value, encode),
20596
+ ...errorType === void 0 ? {} : { errorType }
20597
+ };
20598
+ }
20338
20599
  return void 0;
20339
20600
  }
20340
20601
  if (origin.node.nodeId === void 0) throw new TypeError("Guest closures require an AST node identity.");
@@ -21926,9 +22187,11 @@ function createHostErrorValue(reason, stackFrames, budget, span, state = { seen:
21926
22187
  }
21927
22188
  const error = reason instanceof Error ? createSubsetErrorValue(reason.name, reason.message, stackFrames, budget, {
21928
22189
  cause: reason,
21929
- chargeBudget
22190
+ chargeBudget,
22191
+ transport: true
21930
22192
  }) : createSubsetErrorValue("Error", describeThrownReason(reason), stackFrames, budget, {
21931
- chargeBudget: false
22193
+ chargeBudget: false,
22194
+ transport: true
21932
22195
  });
21933
22196
  if (reason instanceof Error) {
21934
22197
  state.seen.set(reason, error);
@@ -23944,7 +24207,7 @@ function createUriGlobals(budget) {
23944
24207
  }
23945
24208
 
23946
24209
  // packages/safe-js/src/interp/globals/function.ts
23947
- function createFunctionPrototype(budget) {
24210
+ function createFunctionPrototype(budget, installHasInstance = true) {
23948
24211
  const prototype = createSandboxClosure({ guest: true, sandbox: true, name: "", length: 0, call: () => void 0 });
23949
24212
  const properties = materializeFunctionProperties(prototype);
23950
24213
  Object.defineProperty(properties, "constructor", { value: void 0, writable: true, configurable: true });
@@ -23964,8 +24227,77 @@ function createFunctionPrototype(budget) {
23964
24227
  })
23965
24228
  });
23966
24229
  }
24230
+ const hasInstance = installHasInstance ? createSandboxClosure({
24231
+ guest: true,
24232
+ sandbox: true,
24233
+ name: "[Symbol.hasInstance]",
24234
+ length: 1,
24235
+ call: ([value], context) => ordinaryHasInstance(value, context?.thisValue, budget, context)
24236
+ }) : void 0;
24237
+ if (hasInstance !== void 0) Object.defineProperty(properties, Symbol.hasInstance, { value: hasInstance });
23967
24238
  setSandboxPrototype(prototype, getSandboxPrototype(/* @__PURE__ */ Object.create(null), budget));
23968
24239
  installFunctionPrototype(budget, prototype);
24240
+ if (hasInstance !== void 0) registerIntrinsicFunction(budget, hasInstance);
24241
+ }
24242
+
24243
+ // packages/safe-js/src/interp/globals/generator.ts
24244
+ function createGeneratorPrototypes(budget) {
24245
+ const asyncIteratorPrototype = /* @__PURE__ */ Object.create(null);
24246
+ const asyncIterator = createSandboxClosure({
24247
+ guest: true,
24248
+ sandbox: true,
24249
+ name: "[Symbol.asyncIterator]",
24250
+ length: 0,
24251
+ call: (_args, context) => context?.thisValue
24252
+ });
24253
+ Object.defineProperty(asyncIteratorPrototype, Symbol.asyncIterator, {
24254
+ value: asyncIterator,
24255
+ writable: true,
24256
+ configurable: true
24257
+ });
24258
+ setSandboxPrototype(asyncIteratorPrototype, getSandboxPrototype(/* @__PURE__ */ Object.create(null), budget));
24259
+ registerBuiltinIdentities(budget, { "%AsyncIteratorPrototype%": asyncIteratorPrototype });
24260
+ registerIntrinsicObject(budget, asyncIteratorPrototype);
24261
+ registerIntrinsicFunction(budget, asyncIterator);
24262
+ const state = /* @__PURE__ */ new Map();
24263
+ for (const async of [false, true]) {
24264
+ const tag = async ? "AsyncGenerator" : "Generator";
24265
+ const functionPrototype = /* @__PURE__ */ Object.create(null);
24266
+ const instancePrototype = /* @__PURE__ */ Object.create(null);
24267
+ setSandboxPrototype(functionPrototype, resolveIntrinsicIdentity(budget, JSON.stringify(["%FunctionPrototype%"])));
24268
+ setSandboxPrototype(instancePrototype, async ? asyncIteratorPrototype : resolveIntrinsicIdentity(budget, JSON.stringify(["%IteratorPrototype%"])));
24269
+ Object.defineProperties(functionPrototype, {
24270
+ prototype: { value: instancePrototype, configurable: true },
24271
+ // Do not expose native dynamic-source constructors through this graph.
24272
+ constructor: { value: void 0, configurable: true },
24273
+ [Symbol.toStringTag]: { value: `${tag}Function`, configurable: true }
24274
+ });
24275
+ Object.defineProperties(instancePrototype, {
24276
+ constructor: { value: functionPrototype, configurable: true },
24277
+ [Symbol.toStringTag]: { value: tag, configurable: true }
24278
+ });
24279
+ for (const method of ["next", "return", "throw"]) {
24280
+ Object.defineProperty(instancePrototype, method, {
24281
+ writable: true,
24282
+ configurable: true,
24283
+ value: createSandboxClosure({
24284
+ guest: true,
24285
+ sandbox: true,
24286
+ name: method,
24287
+ length: 1,
24288
+ call: ([value], context) => callGeneratorMethod(context?.thisValue, method, value, budget, context, async)
24289
+ })
24290
+ });
24291
+ }
24292
+ registerBuiltinIdentities(budget, {
24293
+ [`%${tag}Prototype%`]: instancePrototype,
24294
+ [`%${tag}FunctionPrototype%`]: functionPrototype
24295
+ });
24296
+ registerIntrinsicObject(budget, functionPrototype);
24297
+ registerIntrinsicObject(budget, instancePrototype);
24298
+ state.set(async, { functionPrototype, instancePrototype });
24299
+ }
24300
+ generatorPrototypes.set(budget, state);
23969
24301
  }
23970
24302
 
23971
24303
  // packages/safe-js/src/interp/globals/symbol.ts
@@ -24190,7 +24522,7 @@ function createBuiltinBindings(options) {
24190
24522
  Date: createDateGlobal(options),
24191
24523
  Symbol: createSymbolGlobal(options.budget),
24192
24524
  BigInt: createBigIntGlobal(options.budget),
24193
- ...createErrorGlobals(options),
24525
+ ...createErrorGlobals({ ...options, errorPrototypes: options.errorPrototypes !== false }),
24194
24526
  ...createMathGlobals({ random: options.random, budget: options.budget }),
24195
24527
  ...createObjectArrayGlobals(options),
24196
24528
  ...createMiscGlobals(options),
@@ -24198,7 +24530,9 @@ function createBuiltinBindings(options) {
24198
24530
  ...createPromiseGlobals(options),
24199
24531
  ...createRegexGlobals(options)
24200
24532
  };
24201
- createFunctionPrototype(options.budget);
24533
+ createFunctionPrototype(options.budget, options.functionHasInstance);
24534
+ if (options.errorPrototypes !== false) createErrorPrototypes(options.budget, bindings);
24535
+ createGeneratorPrototypes(options.budget);
24202
24536
  registerBuiltinIdentities(options.budget, bindings);
24203
24537
  return bindings;
24204
24538
  }
@@ -24249,7 +24583,7 @@ function validateGuestHeapNode(raw, heap, maxArrayLength = 4294967295) {
24249
24583
  createRawJson(node.text);
24250
24584
  return true;
24251
24585
  }
24252
- if (!["intrinsic", "guest-function", "guest-class", "guest-generator", "scope-frame", "guest-object", "guest-array", "array-iterator", "map", "set"].includes(String(node.kind))) return false;
24586
+ if (!["intrinsic", "bound-function", "guest-function", "guest-class", "guest-generator", "scope-frame", "guest-object", "guest-array", "array-iterator", "map", "set"].includes(String(node.kind))) return false;
24253
24587
  const reference = (value, kinds) => {
24254
24588
  const ref = record3(value);
24255
24589
  fields(ref, ["kind", "id"]);
@@ -24260,7 +24594,7 @@ function validateGuestHeapNode(raw, heap, maxArrayLength = 4294967295) {
24260
24594
  };
24261
24595
  const callable = (value) => {
24262
24596
  if (absent(value)) return;
24263
- const target = reference(value, ["intrinsic", "guest-function", "guest-class"]);
24597
+ const target = reference(value, ["intrinsic", "bound-function", "guest-function", "guest-class"]);
24264
24598
  if (target.kind === "intrinsic" && intrinsicCatalogue().get(String(target.id)) !== true)
24265
24599
  throw new TypeError("Guest accessor reference is not callable.");
24266
24600
  };
@@ -24317,7 +24651,9 @@ function validateGuestHeapNode(raw, heap, maxArrayLength = 4294967295) {
24317
24651
  }
24318
24652
  state(node.state);
24319
24653
  } else if (node.kind === "guest-object" || node.kind === "guest-array") {
24320
- fields(node, ["kind", "state"], node.kind === "guest-array" ? ["templateNodeId", "templateOwner"] : []);
24654
+ fields(node, ["kind", "state"], node.kind === "guest-array" ? ["templateNodeId", "templateOwner"] : ["errorType"]);
24655
+ if (Object.hasOwn(node, "errorType") && !sandboxErrorNames.includes(node.errorType))
24656
+ throw new TypeError("Invalid guest error type.");
24321
24657
  if (Object.hasOwn(node, "templateOwner")) reference(node.templateOwner, ["guest-array"]);
24322
24658
  if (Object.hasOwn(node, "templateNodeId") && integer(node.templateNodeId) < 1)
24323
24659
  throw new TypeError("Invalid template source identity.");
@@ -24356,6 +24692,22 @@ function validateGuestHeapNode(raw, heap, maxArrayLength = 4294967295) {
24356
24692
  if (descriptor.kind !== "data" || descriptor.writable !== false || descriptor.enumerable !== false || descriptor.configurable !== false)
24357
24693
  throw new TypeError("Invalid class prototype descriptor.");
24358
24694
  reference(descriptor.value, ["object", "guest-object"]);
24695
+ } else if (node.kind === "bound-function") {
24696
+ fields(node, ["kind", "target", "thisValue", "args", "length", "state"], ["name"]);
24697
+ if (Object.hasOwn(node, "name") && typeof node.name !== "string") throw new TypeError("Invalid bound function name.");
24698
+ if (array(node.args).length > maxArrayLength) throw new TypeError("Bound arguments exceed allocation limit.");
24699
+ if (!absent(node.length) && !(typeof node.length === "number" && node.length >= 0) && !(record3(node.length).kind === "number" && record3(node.length).value === "Infinity"))
24700
+ throw new TypeError("Invalid bound function length.");
24701
+ const visited = /* @__PURE__ */ new Set([raw]);
24702
+ let current = node;
24703
+ while (current.kind === "bound-function") {
24704
+ assertSnapshotDataDepth(visited.size, "<bound-target>");
24705
+ callable(current.target);
24706
+ current = reference(current.target);
24707
+ if (visited.has(current)) throw new TypeError("Cyclic bound function target.");
24708
+ visited.add(current);
24709
+ }
24710
+ state(node.state);
24359
24711
  } else if (node.kind === "guest-function") {
24360
24712
  fields(node, ["kind", "astNodeId", "scope", "state"], ["name", "environment"]);
24361
24713
  if (integer(node.astNodeId) < 1) throw new TypeError("Invalid guest AST identity.");
@@ -25271,7 +25623,7 @@ function validateArrayHeap(record4, path, state) {
25271
25623
  }
25272
25624
  function validateErrorType(record4, path) {
25273
25625
  if (!Object.hasOwn(record4, "errorType")) return;
25274
- if (record4.kind !== "object" || !sandboxErrorNames.includes(record4.errorType)) {
25626
+ if (record4.kind !== "object" && record4.kind !== "guest-object" || !sandboxErrorNames.includes(record4.errorType)) {
25275
25627
  fail("invalidValue", `${path}.errorType`, "invalid error metadata");
25276
25628
  }
25277
25629
  }
@@ -26268,7 +26620,7 @@ function measureSandboxData(values, options = {}) {
26268
26620
  const descriptor = Object.getOwnPropertyDescriptor(value, key);
26269
26621
  if (descriptor !== void 0) descriptors2.push([key, descriptor]);
26270
26622
  }
26271
- const includeNonEnumerable = isSandboxDate(value) || hasManagedDescriptors(value);
26623
+ const includeNonEnumerable = isSandboxDate(value) || sandboxErrorTypes.has(value) || hasManagedDescriptors(value);
26272
26624
  for (const [key, descriptor] of descriptors2) {
26273
26625
  if (!descriptor.enumerable && !includeNonEnumerable) continue;
26274
26626
  usage += 1 + key.length;
@@ -26601,6 +26953,53 @@ function copyFromSandbox(value, state, path = "<root>", options, depth = 0) {
26601
26953
  return options.unwrapHostObject(value);
26602
26954
  }
26603
26955
  if (nodeTypes.isProxy(value)) throw new TypeError("Unsupported proxy sandbox value.");
26956
+ if (sandboxErrorTypes.has(value) && hasExplicitSandboxPrototype(value)) {
26957
+ const prototype = getSandboxPrototype(value);
26958
+ let nativePrototype = null;
26959
+ if (prototype !== null) {
26960
+ const identity = getIntrinsicIdentity(prototype);
26961
+ const nativePrototypes = {
26962
+ Error: Error.prototype,
26963
+ TypeError: TypeError.prototype,
26964
+ RangeError: RangeError.prototype,
26965
+ ReferenceError: ReferenceError.prototype,
26966
+ SyntaxError: SyntaxError.prototype,
26967
+ URIError: URIError.prototype,
26968
+ EvalError: EvalError.prototype,
26969
+ AggregateError: AggregateError.prototype
26970
+ };
26971
+ const path2 = identity === void 0 ? [] : JSON.parse(identity);
26972
+ if (path2.length !== 2 || typeof path2[0] !== "string" || path2[1] !== "prototype" || !Object.hasOwn(nativePrototypes, path2[0]))
26973
+ throw new TypeError("Custom Error prototype links cannot be copied as data.");
26974
+ nativePrototype = nativePrototypes[path2[0]];
26975
+ let current = prototype;
26976
+ let prototypeDepth = 0;
26977
+ while (current !== null) {
26978
+ assertSandboxDataDepth(++prototypeDepth);
26979
+ const objectPrototype = getIntrinsicIdentity(current) === '["Object","prototype"]';
26980
+ const owner = objectPrototype ? Object.getOwnPropertyDescriptor(current, "constructor")?.value : current;
26981
+ if (owner === null || typeof owner !== "object" || objectPrototype && getIntrinsicIdentity(owner) !== '["Object"]' || hasGuestObjectState(owner))
26982
+ throw new TypeError("Modified Error prototype links cannot be copied as data.");
26983
+ current = getSandboxPrototype(current);
26984
+ }
26985
+ }
26986
+ const existing = state.seen.get(value);
26987
+ if (existing !== void 0) return existing;
26988
+ const descriptors2 = Reflect.ownKeys(value).filter((key) => typeof key !== "symbol" || !internalSymbols.has(key)).map((key) => [key, Object.getOwnPropertyDescriptor(value, key)]);
26989
+ if (descriptors2.some(([, descriptor]) => !("value" in descriptor)))
26990
+ throw new TypeError("Error accessor properties cannot be copied as data.");
26991
+ const copy = new Error();
26992
+ delete copy.stack;
26993
+ Object.setPrototypeOf(copy, nativePrototype);
26994
+ state.seen.set(value, copy);
26995
+ for (const [key, descriptor] of descriptors2)
26996
+ Object.defineProperty(copy, key, {
26997
+ ...descriptor,
26998
+ value: copyFromSandbox(descriptor.value, state, joinPath2(path, key), options, depth + 1)
26999
+ });
27000
+ if (!Object.isExtensible(value)) Object.preventExtensions(copy);
27001
+ return copy;
27002
+ }
26604
27003
  if (!isSandboxClosure(value) && hasGuestObjectState(value)) {
26605
27004
  throw new TypeError("Guest prototype links and custom descriptors cannot be copied as data.");
26606
27005
  }
@@ -41049,4 +41448,4 @@ export {
41049
41448
  FileSnapshotBackend,
41050
41449
  run
41051
41450
  };
41052
- //# sourceMappingURL=chunk-M4L3EZHL.js.map
41451
+ //# sourceMappingURL=chunk-V6LQP64H.js.map