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
package/dist/index.js CHANGED
@@ -126512,60 +126512,6 @@ var init_internal_symbols = __esm({
126512
126512
  }
126513
126513
  });
126514
126514
 
126515
- // packages/safe-js/src/interp/generator-properties.ts
126516
- function getGeneratorProperties(value) {
126517
- let properties = generatorGuestProperties.get(value);
126518
- if (properties === void 0) {
126519
- properties = /* @__PURE__ */ Object.create(null);
126520
- generatorGuestProperties.set(value, properties);
126521
- }
126522
- return properties;
126523
- }
126524
- var generatorGuestProperties;
126525
- var init_generator_properties = __esm({
126526
- "packages/safe-js/src/interp/generator-properties.ts"() {
126527
- "use strict";
126528
- generatorGuestProperties = /* @__PURE__ */ new WeakMap();
126529
- }
126530
- });
126531
-
126532
- // packages/safe-js/src/interp/regexp-properties.ts
126533
- function getRegexProperties(value) {
126534
- const properties = regexGuestProperties.get(value);
126535
- if (properties === void 0) throw new TypeError("Invalid sandbox RegExp storage.");
126536
- return properties;
126537
- }
126538
- var regexGuestProperties;
126539
- var init_regexp_properties = __esm({
126540
- "packages/safe-js/src/interp/regexp-properties.ts"() {
126541
- "use strict";
126542
- regexGuestProperties = /* @__PURE__ */ new WeakMap();
126543
- }
126544
- });
126545
-
126546
- // packages/safe-js/src/interp/collection-properties.ts
126547
- function getCollectionProperties(value) {
126548
- const properties = collectionGuestProperties.get(value);
126549
- if (properties === void 0) throw new TypeError("Invalid sandbox collection storage.");
126550
- return properties;
126551
- }
126552
- function copyCollectionProperties(source, target, encode) {
126553
- const properties = collectionGuestProperties.get(source) ?? source;
126554
- for (const key3 of Reflect.ownKeys(properties)) {
126555
- const descriptor = Object.getOwnPropertyDescriptor(properties, key3);
126556
- if (!("value" in descriptor)) throw new TypeError("Collection accessor properties cannot be copied as data.");
126557
- Object.defineProperty(target, key3, { ...descriptor, value: encode(descriptor.value) });
126558
- }
126559
- if (!Object.isExtensible(properties)) Object.preventExtensions(target);
126560
- }
126561
- var collectionGuestProperties;
126562
- var init_collection_properties = __esm({
126563
- "packages/safe-js/src/interp/collection-properties.ts"() {
126564
- "use strict";
126565
- collectionGuestProperties = /* @__PURE__ */ new WeakMap();
126566
- }
126567
- });
126568
-
126569
126515
  // packages/safe-js/src/interp/accessors.ts
126570
126516
  function accessorAdapter(closure, kind) {
126571
126517
  if (kind === "get") {
@@ -126630,6 +126576,144 @@ var init_accessors = __esm({
126630
126576
  }
126631
126577
  });
126632
126578
 
126579
+ // packages/safe-js/src/interp/symbols.ts
126580
+ var wellKnownSymbols;
126581
+ var init_symbols2 = __esm({
126582
+ "packages/safe-js/src/interp/symbols.ts"() {
126583
+ "use strict";
126584
+ wellKnownSymbols = Object.freeze({
126585
+ iterator: Symbol.iterator,
126586
+ asyncIterator: Symbol.asyncIterator,
126587
+ hasInstance: Symbol.hasInstance,
126588
+ isConcatSpreadable: Symbol.isConcatSpreadable,
126589
+ match: Symbol.match,
126590
+ matchAll: Symbol.matchAll,
126591
+ replace: Symbol.replace,
126592
+ search: Symbol.search,
126593
+ species: Symbol.species,
126594
+ split: Symbol.split,
126595
+ toPrimitive: Symbol.toPrimitive,
126596
+ toStringTag: Symbol.toStringTag,
126597
+ unscopables: Symbol.unscopables
126598
+ });
126599
+ }
126600
+ });
126601
+
126602
+ // packages/safe-js/src/interp/intrinsics.ts
126603
+ function registerBuiltinIdentities(budget, bindings) {
126604
+ let realm = realms2.get(budget);
126605
+ if (realm === void 0) realms2.set(budget, realm = /* @__PURE__ */ new Map());
126606
+ const pending = Object.entries(bindings).map(([name, value]) => [[name], value]);
126607
+ const visited = /* @__PURE__ */ new WeakSet();
126608
+ for (let index = 0; index < pending.length; index++) {
126609
+ const [path193, value] = pending[index];
126610
+ if (value === null || typeof value !== "object") continue;
126611
+ const id = JSON.stringify(path193);
126612
+ const previous = realm.get(id);
126613
+ if (previous !== void 0 && previous !== value)
126614
+ throw new TypeError(`Duplicate intrinsic identity: ${id}`);
126615
+ realm.set(id, value);
126616
+ if (!identities.has(value)) identities.set(value, id);
126617
+ if (visited.has(value)) continue;
126618
+ visited.add(value);
126619
+ const owner = isSandboxClosure(value) ? value.properties : value;
126620
+ if (owner === void 0) continue;
126621
+ for (const key3 of Reflect.ownKeys(owner)) {
126622
+ if (typeof key3 === "symbol" && internalSymbols.has(key3)) continue;
126623
+ const descriptor = Object.getOwnPropertyDescriptor(owner, key3);
126624
+ const symbolName = typeof key3 === "symbol" ? Object.entries(wellKnownSymbols).find(([, symbol2]) => symbol2 === key3)?.[0] : void 0;
126625
+ if (typeof key3 === "symbol" && symbolName === void 0)
126626
+ throw new TypeError("Intrinsic symbol keys must be well-known symbols.");
126627
+ const member = [...path193, typeof key3 === "string" ? key3 : { symbol: symbolName }];
126628
+ if ("value" in descriptor) pending.push([member, descriptor.value]);
126629
+ for (const kind of ["get", "set"]) {
126630
+ const closure = accessorClosure(descriptor[kind]);
126631
+ if (closure !== void 0) pending.push([[...member, kind], closure]);
126632
+ }
126633
+ }
126634
+ }
126635
+ }
126636
+ function getIntrinsicIdentity(value) {
126637
+ return identities.get(value);
126638
+ }
126639
+ function resolveIntrinsicIdentity(budget, id) {
126640
+ const value = realms2.get(budget)?.get(id);
126641
+ if (value === void 0) throw new TypeError(`Unknown intrinsic identity: ${id}`);
126642
+ return value;
126643
+ }
126644
+ function listIntrinsicIdentities(budget) {
126645
+ return [...realms2.get(budget)?.keys() ?? []];
126646
+ }
126647
+ function releaseIntrinsicIdentities(budget) {
126648
+ realms2.delete(budget);
126649
+ }
126650
+ var identities, realms2;
126651
+ var init_intrinsics = __esm({
126652
+ "packages/safe-js/src/interp/intrinsics.ts"() {
126653
+ "use strict";
126654
+ init_accessors();
126655
+ init_symbols2();
126656
+ init_internal_symbols();
126657
+ init_values();
126658
+ identities = /* @__PURE__ */ new WeakMap();
126659
+ realms2 = /* @__PURE__ */ new WeakMap();
126660
+ }
126661
+ });
126662
+
126663
+ // packages/safe-js/src/interp/generator-properties.ts
126664
+ function getGeneratorProperties(value) {
126665
+ let properties = generatorGuestProperties.get(value);
126666
+ if (properties === void 0) {
126667
+ properties = /* @__PURE__ */ Object.create(null);
126668
+ generatorGuestProperties.set(value, properties);
126669
+ }
126670
+ return properties;
126671
+ }
126672
+ var generatorGuestProperties;
126673
+ var init_generator_properties = __esm({
126674
+ "packages/safe-js/src/interp/generator-properties.ts"() {
126675
+ "use strict";
126676
+ generatorGuestProperties = /* @__PURE__ */ new WeakMap();
126677
+ }
126678
+ });
126679
+
126680
+ // packages/safe-js/src/interp/regexp-properties.ts
126681
+ function getRegexProperties(value) {
126682
+ const properties = regexGuestProperties.get(value);
126683
+ if (properties === void 0) throw new TypeError("Invalid sandbox RegExp storage.");
126684
+ return properties;
126685
+ }
126686
+ var regexGuestProperties;
126687
+ var init_regexp_properties = __esm({
126688
+ "packages/safe-js/src/interp/regexp-properties.ts"() {
126689
+ "use strict";
126690
+ regexGuestProperties = /* @__PURE__ */ new WeakMap();
126691
+ }
126692
+ });
126693
+
126694
+ // packages/safe-js/src/interp/collection-properties.ts
126695
+ function getCollectionProperties(value) {
126696
+ const properties = collectionGuestProperties.get(value);
126697
+ if (properties === void 0) throw new TypeError("Invalid sandbox collection storage.");
126698
+ return properties;
126699
+ }
126700
+ function copyCollectionProperties(source, target, encode) {
126701
+ const properties = collectionGuestProperties.get(source) ?? source;
126702
+ for (const key3 of Reflect.ownKeys(properties)) {
126703
+ const descriptor = Object.getOwnPropertyDescriptor(properties, key3);
126704
+ if (!("value" in descriptor)) throw new TypeError("Collection accessor properties cannot be copied as data.");
126705
+ Object.defineProperty(target, key3, { ...descriptor, value: encode(descriptor.value) });
126706
+ }
126707
+ if (!Object.isExtensible(properties)) Object.preventExtensions(target);
126708
+ }
126709
+ var collectionGuestProperties;
126710
+ var init_collection_properties = __esm({
126711
+ "packages/safe-js/src/interp/collection-properties.ts"() {
126712
+ "use strict";
126713
+ collectionGuestProperties = /* @__PURE__ */ new WeakMap();
126714
+ }
126715
+ });
126716
+
126633
126717
  // packages/safe-js/src/interp/collection-brands.ts
126634
126718
  function isSandboxMap(value) {
126635
126719
  return typeof value === "object" && value !== null && sandboxMapBrand in value;
@@ -127116,6 +127200,15 @@ var init_graph_depth = __esm({
127116
127200
  }
127117
127201
  });
127118
127202
 
127203
+ // packages/safe-js/src/interp/generator-prototypes.ts
127204
+ var generatorPrototypes;
127205
+ var init_generator_prototypes = __esm({
127206
+ "packages/safe-js/src/interp/generator-prototypes.ts"() {
127207
+ "use strict";
127208
+ generatorPrototypes = /* @__PURE__ */ new WeakMap();
127209
+ }
127210
+ });
127211
+
127119
127212
  // packages/safe-js/src/interp/resources.ts
127120
127213
  import { AsyncLocalStorage as AsyncLocalStorage4 } from "node:async_hooks";
127121
127214
  function retainValues(budget, values) {
@@ -127171,90 +127264,6 @@ var init_resources = __esm({
127171
127264
  }
127172
127265
  });
127173
127266
 
127174
- // packages/safe-js/src/interp/symbols.ts
127175
- var wellKnownSymbols;
127176
- var init_symbols2 = __esm({
127177
- "packages/safe-js/src/interp/symbols.ts"() {
127178
- "use strict";
127179
- wellKnownSymbols = Object.freeze({
127180
- iterator: Symbol.iterator,
127181
- asyncIterator: Symbol.asyncIterator,
127182
- hasInstance: Symbol.hasInstance,
127183
- isConcatSpreadable: Symbol.isConcatSpreadable,
127184
- match: Symbol.match,
127185
- matchAll: Symbol.matchAll,
127186
- replace: Symbol.replace,
127187
- search: Symbol.search,
127188
- species: Symbol.species,
127189
- split: Symbol.split,
127190
- toPrimitive: Symbol.toPrimitive,
127191
- toStringTag: Symbol.toStringTag,
127192
- unscopables: Symbol.unscopables
127193
- });
127194
- }
127195
- });
127196
-
127197
- // packages/safe-js/src/interp/intrinsics.ts
127198
- function registerBuiltinIdentities(budget, bindings) {
127199
- let realm = realms2.get(budget);
127200
- if (realm === void 0) realms2.set(budget, realm = /* @__PURE__ */ new Map());
127201
- const pending = Object.entries(bindings).map(([name, value]) => [[name], value]);
127202
- const visited = /* @__PURE__ */ new WeakSet();
127203
- for (let index = 0; index < pending.length; index++) {
127204
- const [path193, value] = pending[index];
127205
- if (value === null || typeof value !== "object") continue;
127206
- const id = JSON.stringify(path193);
127207
- const previous = realm.get(id);
127208
- if (previous !== void 0 && previous !== value)
127209
- throw new TypeError(`Duplicate intrinsic identity: ${id}`);
127210
- realm.set(id, value);
127211
- if (!identities.has(value)) identities.set(value, id);
127212
- if (visited.has(value)) continue;
127213
- visited.add(value);
127214
- const owner = isSandboxClosure(value) ? value.properties : value;
127215
- if (owner === void 0) continue;
127216
- for (const key3 of Reflect.ownKeys(owner)) {
127217
- if (typeof key3 === "symbol" && internalSymbols.has(key3)) continue;
127218
- const descriptor = Object.getOwnPropertyDescriptor(owner, key3);
127219
- const symbolName = typeof key3 === "symbol" ? Object.entries(wellKnownSymbols).find(([, symbol2]) => symbol2 === key3)?.[0] : void 0;
127220
- if (typeof key3 === "symbol" && symbolName === void 0)
127221
- throw new TypeError("Intrinsic symbol keys must be well-known symbols.");
127222
- const member = [...path193, typeof key3 === "string" ? key3 : { symbol: symbolName }];
127223
- if ("value" in descriptor) pending.push([member, descriptor.value]);
127224
- for (const kind of ["get", "set"]) {
127225
- const closure = accessorClosure(descriptor[kind]);
127226
- if (closure !== void 0) pending.push([[...member, kind], closure]);
127227
- }
127228
- }
127229
- }
127230
- }
127231
- function getIntrinsicIdentity(value) {
127232
- return identities.get(value);
127233
- }
127234
- function resolveIntrinsicIdentity(budget, id) {
127235
- const value = realms2.get(budget)?.get(id);
127236
- if (value === void 0) throw new TypeError(`Unknown intrinsic identity: ${id}`);
127237
- return value;
127238
- }
127239
- function listIntrinsicIdentities(budget) {
127240
- return [...realms2.get(budget)?.keys() ?? []];
127241
- }
127242
- function releaseIntrinsicIdentities(budget) {
127243
- realms2.delete(budget);
127244
- }
127245
- var identities, realms2;
127246
- var init_intrinsics = __esm({
127247
- "packages/safe-js/src/interp/intrinsics.ts"() {
127248
- "use strict";
127249
- init_accessors();
127250
- init_symbols2();
127251
- init_internal_symbols();
127252
- init_values();
127253
- identities = /* @__PURE__ */ new WeakMap();
127254
- realms2 = /* @__PURE__ */ new WeakMap();
127255
- }
127256
- });
127257
-
127258
127267
  // packages/safe-js/src/extensions.ts
127259
127268
  import { types as types3 } from "node:util";
127260
127269
  function readDataRecord(value, label) {
@@ -127659,6 +127668,15 @@ var init_host_capabilities = __esm({
127659
127668
  }
127660
127669
  });
127661
127670
 
127671
+ // packages/safe-js/src/interp/error-prototypes.ts
127672
+ var errorPrototypes;
127673
+ var init_error_prototypes = __esm({
127674
+ "packages/safe-js/src/interp/error-prototypes.ts"() {
127675
+ "use strict";
127676
+ errorPrototypes = /* @__PURE__ */ new WeakMap();
127677
+ }
127678
+ });
127679
+
127662
127680
  // packages/safe-js/src/interp/object-model.ts
127663
127681
  function registerGuestClosure(closure) {
127664
127682
  guestClosures.add(closure);
@@ -127863,11 +127881,18 @@ function releaseObjectPrototype(budget) {
127863
127881
  datePrototypes.delete(budget);
127864
127882
  arrayPrototypes.delete(budget);
127865
127883
  functionPrototypes.delete(budget);
127884
+ generatorPrototypes.delete(budget);
127885
+ errorPrototypes.delete(budget);
127866
127886
  initialRegexDescriptors.delete(budget);
127867
127887
  intrinsicPrototypes.delete(budget);
127868
127888
  }
127869
127889
  function getSandboxPrototype(value, budget) {
127870
127890
  if (prototypes.has(value)) return prototypes.get(value) ?? null;
127891
+ const errorType = sandboxErrorTypes.get(value);
127892
+ if (budget !== void 0 && errorType !== void 0) {
127893
+ const prototype = errorPrototypes.get(budget)?.get(errorType);
127894
+ if (prototype !== void 0) return prototype;
127895
+ }
127871
127896
  if (budget !== void 0 && isGuestClosure(value) && runResources.getStore()?.functionSourceText !== false)
127872
127897
  return functionPrototypes.get(budget) ?? null;
127873
127898
  if (budget !== void 0 && Array.isArray(value)) return arrayPrototypes.get(budget) ?? null;
@@ -127997,12 +128022,15 @@ var init_object_model = __esm({
127997
128022
  "use strict";
127998
128023
  init_graph_depth();
127999
128024
  init_generator_properties();
128025
+ init_generator_prototypes();
128000
128026
  init_resources();
128001
128027
  init_intrinsics();
128002
128028
  init_template_objects();
128003
128029
  init_date();
128004
128030
  init_accessors();
128005
128031
  init_host_capabilities();
128032
+ init_error_prototypes();
128033
+ init_shape();
128006
128034
  init_boxed();
128007
128035
  init_values();
128008
128036
  guestClosures = /* @__PURE__ */ new WeakSet();
@@ -130945,13 +130973,12 @@ async function acquireSandboxIterator(value, budget, context, asyncProtocol = fa
130945
130973
  return asyncProtocol ? getSandboxAsyncIterator(value, budget, context, signal) : getSandboxIterator(value, budget, context);
130946
130974
  if (getSandboxPropertyDescriptor(value, key3, budget) === void 0 && !(isSandboxRegExpIterator(value) && !asyncProtocol && getSandboxPropertyDescriptor(value, "next", budget) !== void 0)) {
130947
130975
  if (isSandboxGenerator(value)) {
130948
- if (hasExplicitSandboxPrototype(value)) return void 0;
130949
- if (value.async === true === asyncProtocol && getSandboxPropertyDescriptor(value, "next", budget) !== void 0)
130976
+ if (!hasExplicitSandboxPrototype(value) && value.async === true === asyncProtocol && getSandboxPropertyDescriptor(value, "next", budget) !== void 0)
130950
130977
  return guestIterator(value, await context.getProperty(value, "next"), asyncProtocol, budget, context, signal);
130951
130978
  }
130952
130979
  if (!asyncProtocol && Array.isArray(value) && getSandboxPrototype(value, budget) !== null) return void 0;
130953
130980
  if (!asyncProtocol) return getSandboxIterator(value, budget, context);
130954
- if (isSandboxGenerator(value) && value.async)
130981
+ if (isSandboxGenerator(value) && value.async && !hasExplicitSandboxPrototype(value))
130955
130982
  return getSandboxAsyncIterator(value, budget, context, signal);
130956
130983
  const iterator2 = await acquireSandboxIterator(value, budget, context);
130957
130984
  return iterator2 === void 0 ? void 0 : asyncFromSyncIterator(iterator2, budget, signal, context);
@@ -131013,7 +131040,7 @@ async function readIteratorResult(iterator, result, property) {
131013
131040
  }
131014
131041
  function getSandboxAsyncIterator(value, budget, context, signal) {
131015
131042
  if (isSandboxGenerator(value) && value.async) {
131016
- return hasExplicitSandboxPrototype(value) ? void 0 : { ...generatorObjectIterator(value, budget, context), asyncProtocol: true };
131043
+ return hasExplicitSandboxPrototype(value) ? context?.getProperty === void 0 ? generatorProtocolAdapter(value, budget, context, true, signal) : void 0 : { ...generatorObjectIterator(value, budget, context), asyncProtocol: true };
131017
131044
  }
131018
131045
  if (value !== null && (typeof value === "object" || typeof value === "function") && !isGuestHostObject(value)) {
131019
131046
  const method = value[Symbol.asyncIterator];
@@ -131163,7 +131190,9 @@ function getSandboxIterator(value, budget, context) {
131163
131190
  return syncIterator(Float32Array.prototype.values.call(value));
131164
131191
  }
131165
131192
  if (isSandboxGenerator(value)) {
131166
- return value.async || hasExplicitSandboxPrototype(value) ? void 0 : generatorObjectIterator(value, budget, context);
131193
+ if (value.async) return void 0;
131194
+ if (hasExplicitSandboxPrototype(value)) return context?.getProperty === void 0 ? generatorProtocolAdapter(value, budget ?? new Budget(), context, false) : void 0;
131195
+ return generatorObjectIterator(value, budget, context);
131167
131196
  }
131168
131197
  if (typeof value === "string") {
131169
131198
  const iterator2 = value[Symbol.iterator]();
@@ -131239,6 +131268,38 @@ function collectionIterator(collection, value) {
131239
131268
  adapter.snapshot = () => ({ kind: "builtin", value, index: adapter.snapshotIndex() });
131240
131269
  return adapter;
131241
131270
  }
131271
+ function generatorProtocolAdapter(value, budget, context, asyncProtocol, signal) {
131272
+ const bridge = {
131273
+ ...context,
131274
+ stack: context?.stack ?? [],
131275
+ thisValue: value,
131276
+ invokeClosure: (closure, args, receiver, construct) => invokeBuiltinClosure(closure, args, budget, context, receiver, construct),
131277
+ getProperty: (target, key3) => {
131278
+ const descriptor = getSandboxPropertyDescriptor(target, key3, budget);
131279
+ return descriptor === void 0 ? void 0 : readPropertyDescriptor(descriptor, target, bridge, true);
131280
+ }
131281
+ };
131282
+ let resolved;
131283
+ let pending;
131284
+ const initialize = () => pending ??= acquireSandboxIterator(value, budget, bridge, asyncProtocol, signal).then((iterator) => {
131285
+ if (iterator === void 0) throw new TypeError("Generator does not provide an iterator protocol.");
131286
+ return resolved = iterator;
131287
+ });
131288
+ return {
131289
+ asynchronous: true,
131290
+ ...asyncProtocol ? { asyncProtocol: true } : {},
131291
+ get retainedValue() {
131292
+ return [value, resolved?.retainedValue];
131293
+ },
131294
+ snapshot: () => resolved?.snapshot?.() ?? { kind: "unsupported" },
131295
+ next: async (...args) => (await initialize()).next(...args),
131296
+ getOperation: async (method) => {
131297
+ const iterator = await initialize();
131298
+ return iterator.getOperation === void 0 ? iterator[method] : iterator.getOperation(method);
131299
+ },
131300
+ readResultProperty: async (result, property) => readIteratorResult(await initialize(), result, property)
131301
+ };
131302
+ }
131242
131303
  function generatorObjectIterator(generator, budget, context) {
131243
131304
  const iterator = generatorIterator(generator, budget, context);
131244
131305
  if (context?.getProperty === void 0) return iterator;
@@ -131343,6 +131404,7 @@ var init_iteration = __esm({
131343
131404
  init_builtin_call();
131344
131405
  init_object_model();
131345
131406
  init_intrinsics();
131407
+ init_accessors();
131346
131408
  asyncGeneratorRequests = /* @__PURE__ */ new WeakMap();
131347
131409
  }
131348
131410
  });
@@ -131759,12 +131821,12 @@ async function evaluateFunctionExpression(node, context, evaluateNode3) {
131759
131821
  value: closure
131760
131822
  };
131761
131823
  }
131762
- function createInterpretedClosure(node, context, evaluateNode3, homeObject) {
131824
+ function createInterpretedClosure(node, context, evaluateNode3, homeObject, initializeGeneratorPrototype = true) {
131763
131825
  if (node.type !== "ArrowFunctionExpression") {
131764
131826
  context = { ...context, functionEnvironment: { homeObject } };
131765
131827
  }
131766
131828
  if (node.type !== "ArrowFunctionExpression" && node.generator) {
131767
- return createGeneratorClosure(node, context, evaluateNode3);
131829
+ return createGeneratorClosure(node, context, evaluateNode3, initializeGeneratorPrototype);
131768
131830
  }
131769
131831
  const construct = node.type !== "ArrowFunctionExpression" && !(node.type === "FunctionExpression" && node.method === true) && !node.async ? async (args, callContext) => {
131770
131832
  const thisValue = {};
@@ -131851,7 +131913,8 @@ function executeAsyncFunction(execute2, budget, signal, callContext) {
131851
131913
  });
131852
131914
  return createSandboxPromise(promise, { synchronousPrefix });
131853
131915
  }
131854
- function createGeneratorClosure(node, context, evaluateNode3) {
131916
+ function createGeneratorClosure(node, context, evaluateNode3, initializePrototype) {
131917
+ const prototypes2 = !initializePrototype || runResources.getStore()?.functionSourceText === false ? void 0 : generatorPrototypes.get(context.budget)?.get(node.async === true);
131855
131918
  const closure = createSandboxClosure({
131856
131919
  sourceRange: functionSources.get(node),
131857
131920
  guest: true,
@@ -131861,54 +131924,69 @@ function createGeneratorClosure(node, context, evaluateNode3) {
131861
131924
  ...node.id === void 0 ? { name: context.inferredName } : { name: node.id.name },
131862
131925
  retainedValues: () => [...context.scope.retainedValues(), context.functionEnvironment?.homeObject, context.functionEnvironment?.newTarget],
131863
131926
  call: async (args, callContext) => {
131864
- const closureContext = {
131865
- ...context,
131866
- compilation: callContext?.compilation ?? context.compilation,
131867
- callStack: [...callContext?.stack ?? context.callStack]
131868
- };
131869
- const scope = await createClosureScope(
131870
- node,
131871
- args,
131872
- callContext?.thisValue,
131873
- closureContext,
131874
- evaluateNode3
131875
- );
131876
- const channel = createGeneratorChannel((generatorYield) => {
131877
- const execute2 = async () => {
131878
- const result = await evaluateNode3(node.body, {
131879
- ...closureContext,
131880
- functionBody: node.body,
131881
- asyncGenerator: node.async,
131882
- generatorBlockScopes: /* @__PURE__ */ new Map(),
131883
- generatorExpressionStates: /* @__PURE__ */ new Map(),
131884
- captureGeneratorScope: (suspendedScope, blocks, completions, expressions) => {
131885
- origin.suspendedScope = suspendedScope;
131886
- origin.blockScopes = blocks;
131887
- origin.finallyCompletions = completions;
131888
- origin.expressionStates = expressions;
131889
- },
131890
- generatorYield: (value2, yieldNodeId) => {
131891
- generator.state = "suspended";
131892
- return generatorYield(value2, yieldNodeId);
131893
- },
131894
- scope
131895
- });
131896
- if (result.kind === "error") {
131897
- throw result.error;
131898
- }
131899
- if (result.kind === "throw") {
131900
- throw result.value;
131901
- }
131902
- const value = result.hasValue ? result.value : void 0;
131903
- return node.async ? awaitSandboxValue(value, context.signal, context.budget, createCoercionContext(context)) : value;
131927
+ const candidate = prototypes2 === void 0 ? void 0 : getGuestFunctionProperty(closure, "prototype");
131928
+ const prototype = typeof candidate === "object" && candidate !== null ? candidate : prototypes2?.instancePrototype;
131929
+ const releasePrototype = prototype === void 0 ? void 0 : retainValues(context.budget, () => [prototype]);
131930
+ try {
131931
+ const closureContext = {
131932
+ ...context,
131933
+ compilation: callContext?.compilation ?? context.compilation,
131934
+ callStack: [...callContext?.stack ?? context.callStack]
131904
131935
  };
131905
- return node.async ? runAsyncPrefix(execute2) : execute2();
131906
- });
131907
- const generator = createSandboxGenerator(channel, { async: node.async });
131908
- const origin = registerGeneratorOrigin(generator, node, scope, closureContext);
131909
- return generator;
131936
+ const scope = await createClosureScope(
131937
+ node,
131938
+ args,
131939
+ callContext?.thisValue,
131940
+ closureContext,
131941
+ evaluateNode3
131942
+ );
131943
+ const channel = createGeneratorChannel((generatorYield) => {
131944
+ const execute2 = async () => {
131945
+ const result = await evaluateNode3(node.body, {
131946
+ ...closureContext,
131947
+ functionBody: node.body,
131948
+ asyncGenerator: node.async,
131949
+ generatorBlockScopes: /* @__PURE__ */ new Map(),
131950
+ generatorExpressionStates: /* @__PURE__ */ new Map(),
131951
+ captureGeneratorScope: (suspendedScope, blocks, completions, expressions) => {
131952
+ origin.suspendedScope = suspendedScope;
131953
+ origin.blockScopes = blocks;
131954
+ origin.finallyCompletions = completions;
131955
+ origin.expressionStates = expressions;
131956
+ },
131957
+ generatorYield: (value2, yieldNodeId) => {
131958
+ generator.state = "suspended";
131959
+ return generatorYield(value2, yieldNodeId);
131960
+ },
131961
+ scope
131962
+ });
131963
+ if (result.kind === "error") {
131964
+ throw result.error;
131965
+ }
131966
+ if (result.kind === "throw") {
131967
+ throw result.value;
131968
+ }
131969
+ const value = result.hasValue ? result.value : void 0;
131970
+ return node.async ? awaitSandboxValue(value, context.signal, context.budget, createCoercionContext(context)) : value;
131971
+ };
131972
+ return node.async ? runAsyncPrefix(execute2) : execute2();
131973
+ });
131974
+ const generator = createSandboxGenerator(channel, { async: node.async });
131975
+ if (prototype !== void 0) setSandboxPrototype(generator, prototype, context.budget);
131976
+ const origin = registerGeneratorOrigin(generator, node, scope, closureContext);
131977
+ return generator;
131978
+ } finally {
131979
+ releasePrototype?.();
131980
+ }
131910
131981
  }
131911
131982
  });
131983
+ if (prototypes2 !== void 0) {
131984
+ const prototype = /* @__PURE__ */ Object.create(null);
131985
+ markDescriptorObject(prototype);
131986
+ setSandboxPrototype(prototype, prototypes2.instancePrototype);
131987
+ Object.defineProperty(materializeFunctionProperties(closure), "prototype", { value: prototype, writable: true });
131988
+ setSandboxPrototype(closure, prototypes2.functionPrototype);
131989
+ }
131912
131990
  registerClosureOrigin(closure, node, context);
131913
131991
  return closure;
131914
131992
  }
@@ -132065,6 +132143,8 @@ var init_async = __esm({
132065
132143
  init_var_hoist();
132066
132144
  init_interpreter();
132067
132145
  init_object_model();
132146
+ init_generator_prototypes();
132147
+ init_resources();
132068
132148
  init_function_source();
132069
132149
  init_closure_origin();
132070
132150
  init_bindings();
@@ -134924,6 +135004,32 @@ function createArrayGlobal(budget) {
134924
135004
  length: 0,
134925
135005
  call: (_args, context) => context?.thisValue
134926
135006
  }), writable: true, configurable: true });
135007
+ const iteratorTagGetter = createSandboxClosure({
135008
+ guest: true,
135009
+ sandbox: true,
135010
+ name: "get [Symbol.toStringTag]",
135011
+ length: 0,
135012
+ call: () => "Iterator"
135013
+ });
135014
+ const iteratorTagSetter = createSandboxClosure({
135015
+ guest: true,
135016
+ sandbox: true,
135017
+ name: "set [Symbol.toStringTag]",
135018
+ length: 1,
135019
+ call: ([value], context) => {
135020
+ const receiver = context?.thisValue;
135021
+ if (receiver === iterablePrototype || receiver === null || typeof receiver !== "object")
135022
+ throw new TypeError("Iterator tag setter requires a distinct object receiver.");
135023
+ defineOwnDataProperty(objectProperties(receiver, true), Symbol.toStringTag, value);
135024
+ createDataCheckpoint(budget, context)(receiver, 0, true);
135025
+ return void 0;
135026
+ }
135027
+ });
135028
+ Object.defineProperty(iterablePrototype, Symbol.toStringTag, {
135029
+ get: accessorAdapter(iteratorTagGetter, "get"),
135030
+ set: accessorAdapter(iteratorTagSetter, "set"),
135031
+ configurable: true
135032
+ });
134927
135033
  setSandboxPrototype(iterablePrototype, getSandboxPrototype(/* @__PURE__ */ Object.create(null), budget));
134928
135034
  setSandboxPrototype(iteratorPrototype, iterablePrototype);
134929
135035
  Object.defineProperties(iteratorPrototype, {
@@ -134937,6 +135043,9 @@ function createArrayGlobal(budget) {
134937
135043
  [Symbol.toStringTag]: { value: "Array Iterator", configurable: true }
134938
135044
  });
134939
135045
  registerBuiltinIdentities(budget, { "%ArrayIteratorPrototype%": iteratorPrototype, "%IteratorPrototype%": iterablePrototype });
135046
+ registerIntrinsicFunction(budget, iterablePrototype[Symbol.iterator]);
135047
+ registerIntrinsicFunction(budget, iteratorTagGetter);
135048
+ registerIntrinsicFunction(budget, iteratorTagSetter);
134940
135049
  registerIntrinsicObject(budget, iterablePrototype);
134941
135050
  registerIntrinsicObject(budget, iteratorPrototype);
134942
135051
  for (const method of ["keys", "values", "entries"]) {
@@ -135718,6 +135827,47 @@ var init_function_string = __esm({
135718
135827
  }
135719
135828
  });
135720
135829
 
135830
+ // packages/safe-js/src/interp/bound-function-state.ts
135831
+ var boundFunctionStates;
135832
+ var init_bound_function_state = __esm({
135833
+ "packages/safe-js/src/interp/bound-function-state.ts"() {
135834
+ "use strict";
135835
+ boundFunctionStates = /* @__PURE__ */ new WeakMap();
135836
+ }
135837
+ });
135838
+
135839
+ // packages/safe-js/src/interp/bound-function.ts
135840
+ function createBoundFunction(state, name, length, callClosure) {
135841
+ const bound = createSandboxClosure({
135842
+ guest: true,
135843
+ sandbox: true,
135844
+ name,
135845
+ length,
135846
+ boundTarget: state.target,
135847
+ retainedValues: () => [state.target, state.thisValue, ...state.args, bound.name],
135848
+ call: (args, context) => callClosure(state.target, [...state.args, ...args], context?.stack ?? [], state.thisValue),
135849
+ ...state.target.construct === void 0 ? {} : {
135850
+ construct: (args, context) => callClosure(
135851
+ state.target,
135852
+ [...state.args, ...args],
135853
+ context?.stack ?? [],
135854
+ void 0,
135855
+ true,
135856
+ context?.newTarget === bound ? state.target : context?.newTarget
135857
+ )
135858
+ }
135859
+ });
135860
+ boundFunctionStates.set(bound, state);
135861
+ return bound;
135862
+ }
135863
+ var init_bound_function = __esm({
135864
+ "packages/safe-js/src/interp/bound-function.ts"() {
135865
+ "use strict";
135866
+ init_values();
135867
+ init_bound_function_state();
135868
+ }
135869
+ });
135870
+
135721
135871
  // packages/safe-js/src/interp/methods/function.ts
135722
135872
  function getFunctionMember(target, property, options) {
135723
135873
  let current = target;
@@ -135768,28 +135918,11 @@ function callFunctionMethod(target, methodName, args, options, stack, context) {
135768
135918
  const thisValue = args[0];
135769
135919
  if (methodName === "bind") {
135770
135920
  const boundArgs = args.slice(1);
135921
+ const explicitPrototype = hasExplicitSandboxPrototype(target);
135922
+ const prototype = getSandboxPrototype(target, options.budget);
135771
135923
  const bind2 = (length, name) => {
135772
- const bound = createSandboxClosure({
135773
- guest: true,
135774
- sandbox: true,
135775
- name: `bound ${name}`,
135776
- length,
135777
- boundTarget: target,
135778
- retainedValues: () => [target, thisValue, ...boundArgs, bound.name],
135779
- call: (callArgs, context2) => options.callClosure(target, [...boundArgs, ...callArgs], context2?.stack ?? [], thisValue),
135780
- ...target.construct === void 0 ? {} : {
135781
- construct: (callArgs, context2) => options.callClosure(
135782
- target,
135783
- [...boundArgs, ...callArgs],
135784
- context2?.stack ?? [],
135785
- void 0,
135786
- true,
135787
- context2?.newTarget === bound ? target : context2?.newTarget
135788
- )
135789
- }
135790
- });
135791
- if (hasExplicitSandboxPrototype(target))
135792
- setSandboxPrototype(bound, getSandboxPrototype(target, options.budget), options.budget);
135924
+ const bound = createBoundFunction({ target, thisValue, args: boundArgs }, `bound ${name}`, length, options.callClosure);
135925
+ if (explicitPrototype) setSandboxPrototype(bound, prototype, options.budget);
135793
135926
  return bound;
135794
135927
  };
135795
135928
  if (context?.getProperty === void 0)
@@ -135798,15 +135931,20 @@ function callFunctionMethod(target, methodName, args, options, stack, context) {
135798
135931
  target.name ?? ""
135799
135932
  );
135800
135933
  return (async () => {
135801
- const properties = target.properties;
135802
- const defaultName = target.name;
135803
- const hasLength = !isGuestClosure(target) || target.properties === void 0 || Object.hasOwn(target.properties, "length");
135804
- const length = hasLength ? await context.getProperty(target, "length") : void 0;
135805
- const name = !isGuestClosure(target) && !Object.hasOwn(properties ?? {}, "name") ? defaultName : await context.getProperty(target, "name");
135806
- return bind2(
135807
- typeof length === "number" && !Number.isNaN(length) ? Math.max(0, Math.trunc(length) - boundArgs.length) : 0,
135808
- typeof name === "string" ? name : ""
135809
- );
135934
+ const release2 = options.budget !== void 0 && explicitPrototype && prototype !== null ? retainValues(options.budget, () => [prototype]) : void 0;
135935
+ try {
135936
+ const properties = target.properties;
135937
+ const defaultName = target.name;
135938
+ const hasLength = !isGuestClosure(target) || target.properties === void 0 || Object.hasOwn(target.properties, "length");
135939
+ const length = hasLength ? await context.getProperty(target, "length") : void 0;
135940
+ const name = !isGuestClosure(target) && !Object.hasOwn(properties ?? {}, "name") ? defaultName : await context.getProperty(target, "name");
135941
+ return bind2(
135942
+ typeof length === "number" && !Number.isNaN(length) ? Math.max(0, Math.trunc(length) - boundArgs.length) : 0,
135943
+ typeof name === "string" ? name : ""
135944
+ );
135945
+ } finally {
135946
+ release2?.();
135947
+ }
135810
135948
  })();
135811
135949
  }
135812
135950
  if (methodName === "call") {
@@ -135816,25 +135954,37 @@ function callFunctionMethod(target, methodName, args, options, stack, context) {
135816
135954
  if (applyArgs === null || applyArgs === void 0) {
135817
135955
  return options.callClosure(target, [], stack, thisValue);
135818
135956
  }
135819
- if (!Array.isArray(applyArgs)) {
135820
- throw new TypeError("Function#apply requires an array or nullish arguments value.");
135957
+ if (typeof applyArgs !== "object") {
135958
+ throw new TypeError("Function#apply requires an object or nullish arguments value.");
135821
135959
  }
135822
- if (context?.getProperty === void 0)
135960
+ if (context?.getProperty === void 0 && Array.isArray(applyArgs))
135823
135961
  return options.callClosure(target, applyArgs, stack, thisValue);
135824
135962
  return (async () => {
135963
+ const budget = options.budget ?? new Budget();
135964
+ const invocationContext = {
135965
+ ...context,
135966
+ stack,
135967
+ thisValue: context?.thisValue,
135968
+ invokeClosure: context?.invokeClosure ?? ((callee, values2, receiver) => Promise.resolve(options.callClosure(callee, values2, stack, receiver)))
135969
+ };
135970
+ const read = (value, key3) => {
135971
+ if (context?.getProperty !== void 0) return context.getProperty(value, key3);
135972
+ const descriptor = getSandboxPropertyDescriptor(value, key3, budget);
135973
+ return descriptor === void 0 ? void 0 : readPropertyDescriptor(descriptor, value, invocationContext);
135974
+ };
135825
135975
  const values = [];
135826
- const length = applyArgs.length;
135827
- options.budget?.allocateArrayLength(length);
135828
- const retained = {};
135829
- options.budget?.setRetainedValues(retained, () => values);
135976
+ const release2 = retainValues(budget, () => [applyArgs, ...values]);
135830
135977
  try {
135978
+ const number = await sandboxNumber(await read(applyArgs, "length"), budget, invocationContext);
135979
+ const length = Number.isNaN(number) || number <= 0 ? 0 : Math.min(Math.trunc(number), Number.MAX_SAFE_INTEGER);
135980
+ budget.allocateArrayLength(length);
135831
135981
  for (let index = 0; index < length; index++) {
135832
- options.budget?.visitNode();
135833
- values.push(await context.getProperty(applyArgs, index));
135982
+ budget.visitNode();
135983
+ values.push(await read(applyArgs, String(index)));
135834
135984
  }
135835
135985
  return await options.callClosure(target, values, stack, thisValue);
135836
135986
  } finally {
135837
- options.budget?.setRetainedValues(retained, void 0);
135987
+ release2();
135838
135988
  }
135839
135989
  })();
135840
135990
  }
@@ -135845,8 +135995,12 @@ var init_function = __esm({
135845
135995
  init_values();
135846
135996
  init_object_model();
135847
135997
  init_graph_depth();
135998
+ init_budget2();
135848
135999
  init_function_string();
135849
136000
  init_resources();
136001
+ init_bound_function();
136002
+ init_string_coercion();
136003
+ init_accessors();
135850
136004
  functionMethodNames = /* @__PURE__ */ new Set(["apply", "bind", "call", "toString"]);
135851
136005
  }
135852
136006
  });
@@ -136019,16 +136173,19 @@ function getGeneratorMember(target, property, budget) {
136019
136173
  return createSandboxClosure({
136020
136174
  sandbox: true,
136021
136175
  name: property,
136022
- call: ([value], context) => {
136023
- const iterator = generatorIterator(target, budget, context);
136024
- const result = Promise.resolve(iterator[property](value)).then((result2) => allocateProducedSandboxValue(
136025
- { value: result2.value, done: result2.done === true },
136026
- budget
136027
- ));
136028
- return target.async ? createSandboxPromise(result) : result;
136029
- }
136176
+ call: ([value], context) => callGeneratorMethod(target, property, value, budget, context, target.async === true)
136030
136177
  });
136031
136178
  }
136179
+ function callGeneratorMethod(target, method, value, budget, context, async) {
136180
+ const result = (async () => {
136181
+ if (!isSandboxGenerator(target) || target.async === true !== async)
136182
+ throw new TypeError(`${async ? "AsyncGenerator" : "Generator"}.${method} requires a matching generator receiver.`);
136183
+ const iterator = generatorIterator(target, budget, context);
136184
+ const result2 = await iterator[method](value);
136185
+ return allocateProducedSandboxValue({ value: result2.value, done: result2.done === true }, budget);
136186
+ })();
136187
+ return async ? createSandboxPromise(result) : result;
136188
+ }
136032
136189
  var generatorMethodNames;
136033
136190
  var init_generator2 = __esm({
136034
136191
  "packages/safe-js/src/interp/methods/generator.ts"() {
@@ -136100,113 +136257,30 @@ async function callSetMethod(target, methodName, args, options, stack = []) {
136100
136257
  }
136101
136258
  return void 0;
136102
136259
  }
136103
- case "keys":
136104
- case "values":
136105
- case "entries":
136106
- return createSandboxCollectionIterator(target, methodName);
136107
- }
136108
- }
136109
- var setMethodNames;
136110
- var init_set = __esm({
136111
- "packages/safe-js/src/interp/methods/set.ts"() {
136112
- "use strict";
136113
- init_values();
136114
- init_running_state();
136115
- init_collection_callback();
136116
- init_collection_iterator();
136117
- setMethodNames = /* @__PURE__ */ new Set([
136118
- "add",
136119
- "has",
136120
- "delete",
136121
- "clear",
136122
- "forEach",
136123
- "keys",
136124
- "values",
136125
- "entries"
136126
- ]);
136127
- }
136128
- });
136129
-
136130
- // packages/safe-js/src/interp/globals/error.ts
136131
- function createErrorGlobals(options) {
136132
- return Object.fromEntries(
136133
- errorNames.map((name) => [name, createErrorConstructor(name, options.budget)])
136134
- );
136135
- }
136136
- function isSandboxErrorConstructorInstance2(value, constructor) {
136137
- if (!isSandboxClosure(constructor)) {
136138
- throw new TypeError("Right-hand side of 'instanceof' is not a function.");
136139
- }
136140
- const name = errorConstructorNames.get(constructor);
136141
- if (name === void 0) {
136142
- return false;
136143
- }
136144
- return isSandboxErrorConstructorInstance(value, name);
136145
- }
136146
- function createErrorConstructor(name, budget) {
136147
- const call = (args, context) => createSubsetError(name, args, context?.stack ?? [], budget);
136148
- const closure = createSandboxClosure({ sandbox: true, call, construct: call, name });
136149
- errorConstructorNames.set(closure, name);
136150
- return closure;
136151
- }
136152
- function createSubsetError(name, args, stackFrames, budget) {
136153
- const message2 = name === "AggregateError" ? args[1] : args[0];
136154
- const options = name === "AggregateError" ? args[2] : args[1];
136155
- const error3 = createSubsetErrorValue(name, message2, stackFrames, budget);
136156
- if (name === "AggregateError") {
136157
- const errors2 = Array.isArray(args[0]) ? [...args[0]] : [];
136158
- budget.allocateArrayLength(errors2.length);
136159
- error3.errors = errors2;
136160
- }
136161
- if (isObjectLike(options) && Object.prototype.hasOwnProperty.call(options, "cause")) {
136162
- error3.cause = options.cause;
136163
- }
136164
- return error3;
136165
- }
136166
- function isObjectLike(value) {
136167
- return typeof value === "object" && value !== null;
136168
- }
136169
- var errorConstructorNames, errorNames;
136170
- var init_error = __esm({
136171
- "packages/safe-js/src/interp/globals/error.ts"() {
136172
- "use strict";
136173
- init_exceptions();
136174
- init_values();
136175
- errorConstructorNames = /* @__PURE__ */ new WeakMap();
136176
- errorNames = [
136177
- "Error",
136178
- "TypeError",
136179
- "RangeError",
136180
- "ReferenceError",
136181
- "SyntaxError",
136182
- "URIError",
136183
- "EvalError",
136184
- "AggregateError"
136185
- ];
136186
- }
136187
- });
136188
-
136189
- // packages/safe-js/src/interp/methods/collection-iterator.ts
136190
- function getCollectionIteratorMember(target, property, budget) {
136191
- if (Object.hasOwn(target, property)) return target[property];
136192
- if (property !== "next") return void 0;
136193
- const { collectionKind } = collectionIteratorState(target);
136194
- return createSandboxClosure({
136195
- sandbox: true,
136196
- name: "next",
136197
- call: (_args, context) => {
136198
- const receiver = context?.thisValue;
136199
- if (!isSandboxCollectionIterator(receiver) || collectionIteratorState(receiver).collectionKind !== collectionKind)
136200
- throw new TypeError("Iterator next requires a matching collection iterator receiver.");
136201
- return nextCollectionIterator(receiver, budget);
136202
- }
136203
- });
136260
+ case "keys":
136261
+ case "values":
136262
+ case "entries":
136263
+ return createSandboxCollectionIterator(target, methodName);
136264
+ }
136204
136265
  }
136205
- var init_collection_iterator2 = __esm({
136206
- "packages/safe-js/src/interp/methods/collection-iterator.ts"() {
136266
+ var setMethodNames;
136267
+ var init_set = __esm({
136268
+ "packages/safe-js/src/interp/methods/set.ts"() {
136207
136269
  "use strict";
136208
- init_collection_iterator();
136209
136270
  init_values();
136271
+ init_running_state();
136272
+ init_collection_callback();
136273
+ init_collection_iterator();
136274
+ setMethodNames = /* @__PURE__ */ new Set([
136275
+ "add",
136276
+ "has",
136277
+ "delete",
136278
+ "clear",
136279
+ "forEach",
136280
+ "keys",
136281
+ "values",
136282
+ "entries"
136283
+ ]);
136210
136284
  }
136211
136285
  });
136212
136286
 
@@ -136343,6 +136417,242 @@ var init_float32array2 = __esm({
136343
136417
  }
136344
136418
  });
136345
136419
 
136420
+ // packages/safe-js/src/interp/globals/error.ts
136421
+ function createErrorGlobals(options) {
136422
+ return Object.fromEntries(
136423
+ errorNames.map((name) => [name, createErrorConstructor(name, options.budget, options.errorPrototypes === true)])
136424
+ );
136425
+ }
136426
+ function isSandboxErrorConstructorInstance2(value, constructor) {
136427
+ if (!isSandboxClosure(constructor)) {
136428
+ throw new TypeError("Right-hand side of 'instanceof' is not a function.");
136429
+ }
136430
+ const name = errorConstructorNames.get(constructor);
136431
+ if (name === void 0) {
136432
+ return false;
136433
+ }
136434
+ return isSandboxErrorConstructorInstance(value, name);
136435
+ }
136436
+ function createErrorConstructor(name, budget, guest) {
136437
+ const call = (args, context) => errorPrototypes.has(budget) ? createNativeError(name, args, budget, context, closure) : createSubsetError(name, args, context?.stack ?? [], budget);
136438
+ const closure = createSandboxClosure({ guest, sandbox: true, call, construct: call, name, length: name === "AggregateError" ? 2 : 1 });
136439
+ errorConstructorNames.set(closure, name);
136440
+ return closure;
136441
+ }
136442
+ function createErrorPrototypes(budget, constructors2) {
136443
+ const prototypes2 = /* @__PURE__ */ new Map();
136444
+ for (const name of errorNames) prototypes2.set(name, /* @__PURE__ */ Object.create(null));
136445
+ errorPrototypes.set(budget, prototypes2);
136446
+ for (const name of errorNames) {
136447
+ const constructor = constructors2[name];
136448
+ const prototype = prototypes2.get(name);
136449
+ Object.defineProperties(prototype, {
136450
+ name: { value: name, writable: true, configurable: true },
136451
+ message: { value: "", writable: true, configurable: true },
136452
+ constructor: { value: constructor, writable: true, configurable: true }
136453
+ });
136454
+ Object.defineProperty(materializeFunctionProperties(constructor), "prototype", { value: prototype, writable: false });
136455
+ setSandboxPrototype(prototype, name === "Error" ? getSandboxPrototype(/* @__PURE__ */ Object.create(null), budget) : prototypes2.get("Error"));
136456
+ if (name !== "Error") setSandboxPrototype(constructor, constructors2.Error);
136457
+ }
136458
+ Object.defineProperty(prototypes2.get("Error"), "toString", {
136459
+ writable: true,
136460
+ configurable: true,
136461
+ value: createSandboxClosure({
136462
+ guest: true,
136463
+ sandbox: true,
136464
+ name: "toString",
136465
+ length: 0,
136466
+ call: async (_args, context) => {
136467
+ const receiver = context?.thisValue;
136468
+ if (receiver === null || typeof receiver !== "object") throw new TypeError("Error.prototype.toString requires an object.");
136469
+ let name;
136470
+ const release2 = retainValues(budget, () => [receiver, name]);
136471
+ try {
136472
+ const rawName = await readErrorProperty(receiver, "name", budget, context);
136473
+ name = rawName === void 0 ? "Error" : await sandboxString(rawName, budget, context);
136474
+ const rawMessage = await readErrorProperty(receiver, "message", budget, context);
136475
+ const message2 = rawMessage === void 0 ? "" : await sandboxString(rawMessage, budget, context);
136476
+ return budget.allocateString(name === "" ? message2 : message2 === "" ? name : `${name}: ${message2}`);
136477
+ } finally {
136478
+ release2();
136479
+ }
136480
+ }
136481
+ })
136482
+ });
136483
+ registerBuiltinIdentities(budget, Object.fromEntries(errorNames.map((name) => [name, constructors2[name]])));
136484
+ for (const name of errorNames) {
136485
+ registerIntrinsicFunction(budget, constructors2[name]);
136486
+ registerIntrinsicObject(budget, prototypes2.get(name));
136487
+ }
136488
+ }
136489
+ async function readErrorProperty(value, key3, budget, context) {
136490
+ if (context?.getProperty !== void 0) return context.getProperty(value, key3);
136491
+ const descriptor = getSandboxPropertyDescriptor(value, key3, budget);
136492
+ return descriptor === void 0 ? void 0 : readPropertyDescriptor(descriptor, value, context);
136493
+ }
136494
+ async function createNativeError(name, args, budget, context, constructor) {
136495
+ const newTarget = context?.newTarget ?? constructor;
136496
+ const candidate = await readErrorProperty(newTarget, "prototype", budget, context);
136497
+ const prototype = candidate !== null && typeof candidate === "object" ? candidate : errorPrototypes.get(budget).get(name);
136498
+ let error3;
136499
+ let iterator;
136500
+ const errors2 = [];
136501
+ const release2 = retainValues(budget, () => [prototype, error3, iterator?.retainedValue, ...errors2, ...args]);
136502
+ try {
136503
+ const message2 = name === "AggregateError" ? args[1] : args[0];
136504
+ const options = name === "AggregateError" ? args[2] : args[1];
136505
+ const text5 = message2 === void 0 ? void 0 : await sandboxString(message2, budget, context);
136506
+ error3 = createSubsetErrorValue(name, text5, context?.stack ?? [], budget);
136507
+ setSandboxPrototype(error3, prototype, budget);
136508
+ if (options !== null && typeof options === "object" && getSandboxPropertyDescriptor(options, "cause", budget) !== void 0) {
136509
+ const cause = await readErrorProperty(options, "cause", budget, context);
136510
+ Object.defineProperty(error3, "cause", { value: cause, writable: true, configurable: true });
136511
+ }
136512
+ if (name === "AggregateError") {
136513
+ iterator = context === void 0 ? getSandboxIterator(args[0], budget) : await acquireSandboxIterator(args[0], budget, context);
136514
+ if (iterator === void 0) throw new TypeError("AggregateError errors must be iterable.");
136515
+ while (true) {
136516
+ budget.visitNode();
136517
+ const result = await iterator.next();
136518
+ if (result === null || typeof result !== "object") throw new TypeError("Iterator result must be an object.");
136519
+ if ((await readIteratorResult(iterator, result, "done")).value) break;
136520
+ budget.allocateArrayLength(errors2.length + 1);
136521
+ errors2.push((await readIteratorResult(iterator, result, "value")).value);
136522
+ }
136523
+ Object.defineProperty(error3, "errors", { value: errors2, writable: true, configurable: true });
136524
+ }
136525
+ return error3;
136526
+ } finally {
136527
+ release2();
136528
+ }
136529
+ }
136530
+ function createSubsetError(name, args, stackFrames, budget) {
136531
+ const message2 = name === "AggregateError" ? args[1] : args[0];
136532
+ const options = name === "AggregateError" ? args[2] : args[1];
136533
+ const error3 = createSubsetErrorValue(name, message2, stackFrames, budget);
136534
+ if (name === "AggregateError") {
136535
+ const errors2 = Array.isArray(args[0]) ? [...args[0]] : [];
136536
+ budget.allocateArrayLength(errors2.length);
136537
+ error3.errors = errors2;
136538
+ }
136539
+ if (isObjectLike(options) && Object.prototype.hasOwnProperty.call(options, "cause")) {
136540
+ error3.cause = options.cause;
136541
+ }
136542
+ return error3;
136543
+ }
136544
+ function isObjectLike(value) {
136545
+ return typeof value === "object" && value !== null;
136546
+ }
136547
+ var errorConstructorNames, errorNames;
136548
+ var init_error = __esm({
136549
+ "packages/safe-js/src/interp/globals/error.ts"() {
136550
+ "use strict";
136551
+ init_error_prototypes();
136552
+ init_object_model();
136553
+ init_intrinsics();
136554
+ init_string_coercion();
136555
+ init_resources();
136556
+ init_accessors();
136557
+ init_iteration();
136558
+ init_exceptions();
136559
+ init_values();
136560
+ errorConstructorNames = /* @__PURE__ */ new WeakMap();
136561
+ errorNames = [
136562
+ "Error",
136563
+ "TypeError",
136564
+ "RangeError",
136565
+ "ReferenceError",
136566
+ "SyntaxError",
136567
+ "URIError",
136568
+ "EvalError",
136569
+ "AggregateError"
136570
+ ];
136571
+ }
136572
+ });
136573
+
136574
+ // packages/safe-js/src/interp/instanceof.ts
136575
+ async function evaluateInstanceof(value, constructor, budget, context) {
136576
+ if (constructor === null || typeof constructor !== "object")
136577
+ throw new TypeError("Right-hand side of 'instanceof' must be an object.");
136578
+ const method = await readInstanceProperty(constructor, Symbol.hasInstance, budget, context);
136579
+ if (method !== void 0 && method !== null) {
136580
+ if (!isSandboxClosure(method)) throw new TypeError("Symbol.hasInstance must be callable.");
136581
+ return Boolean(await invokeBuiltinClosure(method, [value], budget, context, constructor));
136582
+ }
136583
+ if (!isSandboxClosure(constructor))
136584
+ throw new TypeError("Right-hand side of 'instanceof' is not a function.");
136585
+ return ordinaryHasInstance(value, constructor, budget, context);
136586
+ }
136587
+ async function ordinaryHasInstance(value, constructor, budget, context) {
136588
+ if (!isSandboxClosure(constructor)) return false;
136589
+ if (constructor.boundTarget !== void 0) {
136590
+ budget.visitNode();
136591
+ return evaluateInstanceof(value, constructor.boundTarget, budget, context);
136592
+ }
136593
+ if (isFloat32ArrayConstructor(constructor)) return isFloat32Array(value);
136594
+ if ((!isGuestClosure(constructor) || value !== null && typeof value === "object" && !hasExplicitSandboxPrototype(value)) && isSandboxErrorConstructorInstance2(value, constructor)) return true;
136595
+ if (!isGuestClosure(constructor) || typeof value !== "object" || value === null) return false;
136596
+ const prototype = await readInstanceProperty(constructor, "prototype", budget, context);
136597
+ if (typeof prototype !== "object" || prototype === null)
136598
+ throw new TypeError("Function has a non-object prototype in instanceof check.");
136599
+ let depth = 0;
136600
+ for (let current = getSandboxPrototype(value, budget); current !== null; current = getSandboxPrototype(current, budget)) {
136601
+ budget.visitNode();
136602
+ assertSandboxDataDepth(depth++);
136603
+ if (current === prototype) return true;
136604
+ }
136605
+ return false;
136606
+ }
136607
+ async function readInstanceProperty(value, key3, budget, context) {
136608
+ if (context?.getProperty !== void 0) return context.getProperty(value, key3);
136609
+ const descriptor = getSandboxPropertyDescriptor(value, key3, budget);
136610
+ if (descriptor === void 0) return void 0;
136611
+ return readPropertyDescriptor(descriptor, value, {
136612
+ ...context,
136613
+ stack: context?.stack ?? [],
136614
+ thisValue: value,
136615
+ invokeClosure: context?.invokeClosure ?? ((closure, args, receiver) => invokeBuiltinClosure(closure, args, budget, context, receiver))
136616
+ });
136617
+ }
136618
+ var init_instanceof = __esm({
136619
+ "packages/safe-js/src/interp/instanceof.ts"() {
136620
+ "use strict";
136621
+ init_graph_depth();
136622
+ init_accessors();
136623
+ init_builtin_call();
136624
+ init_float32();
136625
+ init_float32array2();
136626
+ init_error();
136627
+ init_object_model();
136628
+ init_values();
136629
+ }
136630
+ });
136631
+
136632
+ // packages/safe-js/src/interp/methods/collection-iterator.ts
136633
+ function getCollectionIteratorMember(target, property, budget) {
136634
+ if (Object.hasOwn(target, property)) return target[property];
136635
+ if (property !== "next") return void 0;
136636
+ const { collectionKind } = collectionIteratorState(target);
136637
+ return createSandboxClosure({
136638
+ sandbox: true,
136639
+ name: "next",
136640
+ call: (_args, context) => {
136641
+ const receiver = context?.thisValue;
136642
+ if (!isSandboxCollectionIterator(receiver) || collectionIteratorState(receiver).collectionKind !== collectionKind)
136643
+ throw new TypeError("Iterator next requires a matching collection iterator receiver.");
136644
+ return nextCollectionIterator(receiver, budget);
136645
+ }
136646
+ });
136647
+ }
136648
+ var init_collection_iterator2 = __esm({
136649
+ "packages/safe-js/src/interp/methods/collection-iterator.ts"() {
136650
+ "use strict";
136651
+ init_collection_iterator();
136652
+ init_values();
136653
+ }
136654
+ });
136655
+
136346
136656
  // packages/safe-js/src/interp/scope.ts
136347
136657
  function defineSnapshotBinding(target, name, value) {
136348
136658
  Object.defineProperty(target, name, {
@@ -139147,42 +139457,11 @@ function applyBinaryOperator(node, left, right, context) {
139147
139457
  case ">>>":
139148
139458
  return toNumber(left) >>> toNumber(right);
139149
139459
  case "instanceof":
139150
- return evaluateInstanceof(left, right, context);
139460
+ return evaluateInstanceof(left, right, context.budget, createCoercionContext(context));
139151
139461
  case "in":
139152
139462
  return hasSandboxProperty(right, left, context);
139153
139463
  }
139154
139464
  }
139155
- async function evaluateInstanceof(left, right, context) {
139156
- while (true) {
139157
- if (right === null || typeof right !== "object" && typeof right !== "function")
139158
- throw new TypeError("Right-hand side of 'instanceof' must be an object.");
139159
- const method = await getPropertyValue(right, Symbol.hasInstance, context);
139160
- if (method !== void 0 && method !== null) {
139161
- if (!isSandboxClosure(method)) throw new TypeError("Symbol.hasInstance must be callable.");
139162
- return Boolean(await invokeSandboxClosure(method, [left], context, context.callStack, void 0, right));
139163
- }
139164
- if (!isSandboxClosure(right))
139165
- throw new TypeError("Right-hand side of 'instanceof' is not a function.");
139166
- if (right.boundTarget === void 0) break;
139167
- context.budget.visitNode();
139168
- right = right.boundTarget;
139169
- }
139170
- if (isFloat32ArrayConstructor(right)) return isFloat32Array(left);
139171
- if (isSandboxErrorConstructorInstance2(left, right)) return true;
139172
- if (isGuestClosure(right)) {
139173
- if (typeof left !== "object" || left === null) return false;
139174
- const prototype = await getPropertyValue(right, "prototype", context);
139175
- if (typeof prototype !== "object" || prototype === null)
139176
- throw new TypeError("Function has a non-object prototype in instanceof check.");
139177
- let depth = 0;
139178
- for (let current = getSandboxPrototype(left, context.budget); current !== null; current = getSandboxPrototype(current, context.budget)) {
139179
- context.budget.visitNode();
139180
- assertSandboxDataDepth(depth++);
139181
- if (current === prototype) return true;
139182
- }
139183
- }
139184
- return false;
139185
- }
139186
139465
  function createCoercionContext(context) {
139187
139466
  return {
139188
139467
  stack: context.callStack,
@@ -139844,7 +140123,7 @@ var init_interpreter = __esm({
139844
140123
  init_patterns();
139845
140124
  init_string();
139846
140125
  init_set();
139847
- init_error();
140126
+ init_instanceof();
139848
140127
  init_object2();
139849
140128
  init_collection_iterator();
139850
140129
  init_collection_iterator2();
@@ -140653,11 +140932,10 @@ function surfaceThrownValue(reason, budget, stackFrames = [], span) {
140653
140932
  throw reason;
140654
140933
  }
140655
140934
  if (isSubsetErrorValue(reason)) {
140656
- normalizeSurfacedSubsetError(reason, budget, stackFrames, span);
140657
- return reason;
140935
+ return normalizeSurfacedSubsetError(reason, budget, stackFrames, span);
140658
140936
  }
140659
140937
  if (reason instanceof Error) {
140660
- const error3 = createSubsetErrorValue(
140938
+ const error4 = createSubsetErrorValue(
140661
140939
  reason.name || "Error",
140662
140940
  reason.message,
140663
140941
  stackFrames,
@@ -140668,11 +140946,10 @@ function surfaceThrownValue(reason, budget, stackFrames = [], span) {
140668
140946
  span
140669
140947
  }
140670
140948
  );
140671
- normalizeSurfacedSubsetError(error3, budget, stackFrames, span);
140672
- return error3;
140949
+ return normalizeSurfacedSubsetError(error4, budget, stackFrames, span);
140673
140950
  }
140674
140951
  if (isErrorLikeValue(reason)) {
140675
- const error3 = createSubsetErrorValue(
140952
+ const error4 = createSubsetErrorValue(
140676
140953
  reason.name || "Error",
140677
140954
  reason.message,
140678
140955
  stackFrames,
@@ -140683,13 +140960,13 @@ function surfaceThrownValue(reason, budget, stackFrames = [], span) {
140683
140960
  span
140684
140961
  }
140685
140962
  );
140686
- normalizeSurfacedSubsetError(error3, budget, stackFrames, span);
140687
- return error3;
140963
+ return normalizeSurfacedSubsetError(error4, budget, stackFrames, span);
140688
140964
  }
140689
- return createSubsetErrorValue("Error", describeThrownValue(reason), stackFrames, budget, {
140965
+ const error3 = createSubsetErrorValue("Error", describeThrownValue(reason), stackFrames, budget, {
140690
140966
  chargeBudget: false,
140691
140967
  span
140692
140968
  });
140969
+ return normalizeSurfacedSubsetError(error3, budget, stackFrames, span);
140693
140970
  }
140694
140971
  function createSubsetErrorValue(name, message2, stackFrames, budget, options = {}) {
140695
140972
  const resumeChecks = options.chargeBudget === false ? budget.suspendChecks() : void 0;
@@ -140698,11 +140975,15 @@ function createSubsetErrorValue(name, message2, stackFrames, budget, options = {
140698
140975
  const errorMessage9 = budget.allocateString(coerceErrorMessage(message2));
140699
140976
  const header = errorMessage9 === "" ? errorName : `${errorName}: ${errorMessage9}`;
140700
140977
  const stack = budget.allocateString([header, ...[...stackFrames].reverse()].join("\n"));
140701
- const error3 = {
140702
- name: errorName,
140703
- message: errorMessage9,
140704
- stack
140705
- };
140978
+ const prototype = options.transport ? void 0 : errorPrototypes.get(budget)?.get(toSandboxErrorName(errorName));
140979
+ const error3 = prototype === void 0 ? { name: errorName, message: errorMessage9, stack } : {};
140980
+ if (prototype !== void 0) {
140981
+ if (message2 !== void 0) Object.defineProperty(error3, "message", { value: errorMessage9, writable: true, configurable: true });
140982
+ if (!errorPrototypes.get(budget).has(errorName))
140983
+ Object.defineProperty(error3, "name", { value: errorName, writable: true, configurable: true });
140984
+ Object.defineProperty(error3, "stack", { value: stack, writable: true, configurable: true });
140985
+ setSandboxPrototype(error3, prototype, budget);
140986
+ }
140706
140987
  sandboxErrorTypes.set(error3, toSandboxErrorName(errorName));
140707
140988
  attachErrorSpan(error3, options.span);
140708
140989
  attachWrappedErrorCause(error3, options.cause);
@@ -140723,6 +141004,7 @@ function isSubsetErrorValue(value) {
140723
141004
  if (typeof value !== "object" || value === null) {
140724
141005
  return false;
140725
141006
  }
141007
+ if (sandboxErrorTypes.has(value)) return true;
140726
141008
  const prototype = Object.getPrototypeOf(value);
140727
141009
  return (prototype === Object.prototype || prototype === null) && typeof value.name === "string" && typeof value.message === "string" && typeof value.stack === "string";
140728
141010
  }
@@ -140732,21 +141014,37 @@ function normalizeSurfacedSubsetError(error3, budget, stackFrames, span) {
140732
141014
  const name = budget.allocateString(toSandboxErrorName(readErrorName(error3)));
140733
141015
  const message2 = budget.allocateString(readSurfacedErrorMessage(error3, name));
140734
141016
  const frames = readSandboxStackFrames(error3.stack);
141017
+ if (!Object.isExtensible(error3) || ["name", "message", "stack"].some((key3) => {
141018
+ const descriptor = Object.getOwnPropertyDescriptor(error3, key3);
141019
+ return descriptor !== void 0 && (!("value" in descriptor) || !descriptor.writable);
141020
+ })) {
141021
+ const original = error3;
141022
+ const descriptors2 = Object.getOwnPropertyDescriptors(original);
141023
+ delete descriptors2.name;
141024
+ delete descriptors2.message;
141025
+ delete descriptors2.stack;
141026
+ error3 = Object.defineProperties({}, descriptors2);
141027
+ const errorType = sandboxErrorTypes.get(original);
141028
+ if (errorType !== void 0) sandboxErrorTypes.set(error3, errorType);
141029
+ }
140735
141030
  error3.name = name;
140736
141031
  error3.message = message2;
140737
141032
  error3.stack = budget.allocateString(
140738
141033
  formatErrorStack(name, message2, frames.length > 0 ? frames : [...stackFrames].reverse())
140739
141034
  );
140740
141035
  attachErrorSpan(error3, readErrorSpan(error3) ?? span);
141036
+ return error3;
140741
141037
  } finally {
140742
141038
  resumeChecks();
140743
141039
  }
140744
141040
  }
140745
141041
  function readErrorName(error3) {
140746
- return typeof error3.name === "string" && error3.name.length > 0 ? error3.name : "Error";
141042
+ const name = getSandboxDataProperty(error3, "name");
141043
+ return typeof name === "string" && name.length > 0 ? name : sandboxErrorTypes.get(error3) ?? "Error";
140747
141044
  }
140748
141045
  function readSurfacedErrorMessage(error3, name) {
140749
- const message2 = typeof error3.message === "string" ? error3.message : "";
141046
+ const value = getSandboxDataProperty(error3, "message");
141047
+ const message2 = typeof value === "string" ? value : "";
140750
141048
  if (message2 === "") {
140751
141049
  return `${name} thrown`;
140752
141050
  }
@@ -141035,6 +141333,7 @@ var init_exceptions = __esm({
141035
141333
  init_object2();
141036
141334
  init_resources();
141037
141335
  init_object_model();
141336
+ init_error_prototypes();
141038
141337
  init_property_key();
141039
141338
  init_internal_symbols();
141040
141339
  init_resume_target();
@@ -142691,7 +142990,7 @@ function measureSandboxData(values, options = {}) {
142691
142990
  const descriptor = Object.getOwnPropertyDescriptor(value, key3);
142692
142991
  if (descriptor !== void 0) descriptors2.push([key3, descriptor]);
142693
142992
  }
142694
- const includeNonEnumerable = isSandboxDate(value) || hasManagedDescriptors(value);
142993
+ const includeNonEnumerable = isSandboxDate(value) || sandboxErrorTypes.has(value) || hasManagedDescriptors(value);
142695
142994
  for (const [key3, descriptor] of descriptors2) {
142696
142995
  if (!descriptor.enumerable && !includeNonEnumerable) continue;
142697
142996
  usage += 1 + key3.length;
@@ -143024,6 +143323,53 @@ function copyFromSandbox(value, state, path193 = "<root>", options, depth = 0) {
143024
143323
  return options.unwrapHostObject(value);
143025
143324
  }
143026
143325
  if (nodeTypes.isProxy(value)) throw new TypeError("Unsupported proxy sandbox value.");
143326
+ if (sandboxErrorTypes.has(value) && hasExplicitSandboxPrototype(value)) {
143327
+ const prototype = getSandboxPrototype(value);
143328
+ let nativePrototype = null;
143329
+ if (prototype !== null) {
143330
+ const identity = getIntrinsicIdentity(prototype);
143331
+ const nativePrototypes = {
143332
+ Error: Error.prototype,
143333
+ TypeError: TypeError.prototype,
143334
+ RangeError: RangeError.prototype,
143335
+ ReferenceError: ReferenceError.prototype,
143336
+ SyntaxError: SyntaxError.prototype,
143337
+ URIError: URIError.prototype,
143338
+ EvalError: EvalError.prototype,
143339
+ AggregateError: AggregateError.prototype
143340
+ };
143341
+ const path194 = identity === void 0 ? [] : JSON.parse(identity);
143342
+ if (path194.length !== 2 || typeof path194[0] !== "string" || path194[1] !== "prototype" || !Object.hasOwn(nativePrototypes, path194[0]))
143343
+ throw new TypeError("Custom Error prototype links cannot be copied as data.");
143344
+ nativePrototype = nativePrototypes[path194[0]];
143345
+ let current = prototype;
143346
+ let prototypeDepth = 0;
143347
+ while (current !== null) {
143348
+ assertSandboxDataDepth(++prototypeDepth);
143349
+ const objectPrototype = getIntrinsicIdentity(current) === '["Object","prototype"]';
143350
+ const owner = objectPrototype ? Object.getOwnPropertyDescriptor(current, "constructor")?.value : current;
143351
+ if (owner === null || typeof owner !== "object" || objectPrototype && getIntrinsicIdentity(owner) !== '["Object"]' || hasGuestObjectState(owner))
143352
+ throw new TypeError("Modified Error prototype links cannot be copied as data.");
143353
+ current = getSandboxPrototype(current);
143354
+ }
143355
+ }
143356
+ const existing = state.seen.get(value);
143357
+ if (existing !== void 0) return existing;
143358
+ const descriptors2 = Reflect.ownKeys(value).filter((key3) => typeof key3 !== "symbol" || !internalSymbols.has(key3)).map((key3) => [key3, Object.getOwnPropertyDescriptor(value, key3)]);
143359
+ if (descriptors2.some(([, descriptor]) => !("value" in descriptor)))
143360
+ throw new TypeError("Error accessor properties cannot be copied as data.");
143361
+ const copy = new Error();
143362
+ delete copy.stack;
143363
+ Object.setPrototypeOf(copy, nativePrototype);
143364
+ state.seen.set(value, copy);
143365
+ for (const [key3, descriptor] of descriptors2)
143366
+ Object.defineProperty(copy, key3, {
143367
+ ...descriptor,
143368
+ value: copyFromSandbox(descriptor.value, state, joinPath(path193, key3), options, depth + 1)
143369
+ });
143370
+ if (!Object.isExtensible(value)) Object.preventExtensions(copy);
143371
+ return copy;
143372
+ }
143027
143373
  if (!isSandboxClosure(value) && hasGuestObjectState(value)) {
143028
143374
  throw new TypeError("Guest prototype links and custom descriptors cannot be copied as data.");
143029
143375
  }
@@ -143410,6 +143756,7 @@ var init_values = __esm({
143410
143756
  "use strict";
143411
143757
  init_otel2();
143412
143758
  init_internal_symbols();
143759
+ init_intrinsics();
143413
143760
  init_generator_properties();
143414
143761
  init_regexp_properties();
143415
143762
  init_collection_properties();
@@ -143518,6 +143865,18 @@ function captureGuestHeapNode(value, encode) {
143518
143865
  const state2 = captureObjectState(value, encode);
143519
143866
  return { kind: "intrinsic", id: intrinsic, ...state2 === void 0 ? {} : { state: state2 } };
143520
143867
  }
143868
+ const bound = boundFunctionStates.get(value);
143869
+ if (bound !== void 0 && isSandboxClosure(value)) {
143870
+ return {
143871
+ kind: "bound-function",
143872
+ target: encode(bound.target),
143873
+ thisValue: encode(bound.thisValue),
143874
+ args: bound.args.map(encode),
143875
+ length: encode(value.length),
143876
+ ...value.name === void 0 ? {} : { name: value.name },
143877
+ state: captureObjectState(value, encode)
143878
+ };
143879
+ }
143521
143880
  if (isSandboxMap(value)) return { kind: "map", entries: [...value.entries].map(([key3, entry]) => [encode(key3), encode(entry)]), ...serializeCollectionProperties(value, encode) };
143522
143881
  if (isSandboxSet(value)) return { kind: "set", values: [...value.values].map(encode), ...serializeCollectionProperties(value, encode) };
143523
143882
  if (isSandboxArrayIterator(value)) {
@@ -143661,8 +144020,14 @@ function captureGuestHeapNode(value, encode) {
143661
144020
  }
143662
144021
  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;
143663
144022
  const prototype = Object.getPrototypeOf(value);
143664
- if ((prototype === null || prototype === Object.prototype) && hasGuestObjectState(value))
143665
- return { kind: "guest-object", state: captureObjectState(value, encode) };
144023
+ if ((prototype === null || prototype === Object.prototype) && hasGuestObjectState(value)) {
144024
+ const errorType = sandboxErrorTypes.get(value);
144025
+ return {
144026
+ kind: "guest-object",
144027
+ state: captureObjectState(value, encode),
144028
+ ...errorType === void 0 ? {} : { errorType }
144029
+ };
144030
+ }
143666
144031
  return void 0;
143667
144032
  }
143668
144033
  if (origin.node.nodeId === void 0) throw new TypeError("Guest closures require an AST node identity.");
@@ -143699,6 +144064,8 @@ var init_guest_heap = __esm({
143699
144064
  "packages/safe-js/src/snapshot/guest-heap.ts"() {
143700
144065
  "use strict";
143701
144066
  init_closure_origin();
144067
+ init_bound_function_state();
144068
+ init_shape();
143702
144069
  init_generator_properties();
143703
144070
  init_intrinsics();
143704
144071
  init_object_model();
@@ -144730,9 +145097,11 @@ function createHostErrorValue(reason, stackFrames, budget, span, state = { seen:
144730
145097
  }
144731
145098
  const error3 = reason instanceof Error ? createSubsetErrorValue(reason.name, reason.message, stackFrames, budget, {
144732
145099
  cause: reason,
144733
- chargeBudget
145100
+ chargeBudget,
145101
+ transport: true
144734
145102
  }) : createSubsetErrorValue("Error", describeThrownReason(reason), stackFrames, budget, {
144735
- chargeBudget: false
145103
+ chargeBudget: false,
145104
+ transport: true
144736
145105
  });
144737
145106
  if (reason instanceof Error) {
144738
145107
  state.seen.set(reason, error3);
@@ -146915,7 +147284,7 @@ var init_uri = __esm({
146915
147284
  });
146916
147285
 
146917
147286
  // packages/safe-js/src/interp/globals/function.ts
146918
- function createFunctionPrototype(budget) {
147287
+ function createFunctionPrototype(budget, installHasInstance = true) {
146919
147288
  const prototype = createSandboxClosure({ guest: true, sandbox: true, name: "", length: 0, call: () => void 0 });
146920
147289
  const properties = materializeFunctionProperties(prototype);
146921
147290
  Object.defineProperty(properties, "constructor", { value: void 0, writable: true, configurable: true });
@@ -146935,8 +147304,17 @@ function createFunctionPrototype(budget) {
146935
147304
  })
146936
147305
  });
146937
147306
  }
147307
+ const hasInstance = installHasInstance ? createSandboxClosure({
147308
+ guest: true,
147309
+ sandbox: true,
147310
+ name: "[Symbol.hasInstance]",
147311
+ length: 1,
147312
+ call: ([value], context) => ordinaryHasInstance(value, context?.thisValue, budget, context)
147313
+ }) : void 0;
147314
+ if (hasInstance !== void 0) Object.defineProperty(properties, Symbol.hasInstance, { value: hasInstance });
146938
147315
  setSandboxPrototype(prototype, getSandboxPrototype(/* @__PURE__ */ Object.create(null), budget));
146939
147316
  installFunctionPrototype(budget, prototype);
147317
+ if (hasInstance !== void 0) registerIntrinsicFunction(budget, hasInstance);
146940
147318
  }
146941
147319
  var init_function2 = __esm({
146942
147320
  "packages/safe-js/src/interp/globals/function.ts"() {
@@ -146945,6 +147323,77 @@ var init_function2 = __esm({
146945
147323
  init_function();
146946
147324
  init_object_model();
146947
147325
  init_values();
147326
+ init_instanceof();
147327
+ }
147328
+ });
147329
+
147330
+ // packages/safe-js/src/interp/globals/generator.ts
147331
+ function createGeneratorPrototypes(budget) {
147332
+ const asyncIteratorPrototype = /* @__PURE__ */ Object.create(null);
147333
+ const asyncIterator = createSandboxClosure({
147334
+ guest: true,
147335
+ sandbox: true,
147336
+ name: "[Symbol.asyncIterator]",
147337
+ length: 0,
147338
+ call: (_args, context) => context?.thisValue
147339
+ });
147340
+ Object.defineProperty(asyncIteratorPrototype, Symbol.asyncIterator, {
147341
+ value: asyncIterator,
147342
+ writable: true,
147343
+ configurable: true
147344
+ });
147345
+ setSandboxPrototype(asyncIteratorPrototype, getSandboxPrototype(/* @__PURE__ */ Object.create(null), budget));
147346
+ registerBuiltinIdentities(budget, { "%AsyncIteratorPrototype%": asyncIteratorPrototype });
147347
+ registerIntrinsicObject(budget, asyncIteratorPrototype);
147348
+ registerIntrinsicFunction(budget, asyncIterator);
147349
+ const state = /* @__PURE__ */ new Map();
147350
+ for (const async of [false, true]) {
147351
+ const tag = async ? "AsyncGenerator" : "Generator";
147352
+ const functionPrototype = /* @__PURE__ */ Object.create(null);
147353
+ const instancePrototype = /* @__PURE__ */ Object.create(null);
147354
+ setSandboxPrototype(functionPrototype, resolveIntrinsicIdentity(budget, JSON.stringify(["%FunctionPrototype%"])));
147355
+ setSandboxPrototype(instancePrototype, async ? asyncIteratorPrototype : resolveIntrinsicIdentity(budget, JSON.stringify(["%IteratorPrototype%"])));
147356
+ Object.defineProperties(functionPrototype, {
147357
+ prototype: { value: instancePrototype, configurable: true },
147358
+ // Do not expose native dynamic-source constructors through this graph.
147359
+ constructor: { value: void 0, configurable: true },
147360
+ [Symbol.toStringTag]: { value: `${tag}Function`, configurable: true }
147361
+ });
147362
+ Object.defineProperties(instancePrototype, {
147363
+ constructor: { value: functionPrototype, configurable: true },
147364
+ [Symbol.toStringTag]: { value: tag, configurable: true }
147365
+ });
147366
+ for (const method of ["next", "return", "throw"]) {
147367
+ Object.defineProperty(instancePrototype, method, {
147368
+ writable: true,
147369
+ configurable: true,
147370
+ value: createSandboxClosure({
147371
+ guest: true,
147372
+ sandbox: true,
147373
+ name: method,
147374
+ length: 1,
147375
+ call: ([value], context) => callGeneratorMethod(context?.thisValue, method, value, budget, context, async)
147376
+ })
147377
+ });
147378
+ }
147379
+ registerBuiltinIdentities(budget, {
147380
+ [`%${tag}Prototype%`]: instancePrototype,
147381
+ [`%${tag}FunctionPrototype%`]: functionPrototype
147382
+ });
147383
+ registerIntrinsicObject(budget, functionPrototype);
147384
+ registerIntrinsicObject(budget, instancePrototype);
147385
+ state.set(async, { functionPrototype, instancePrototype });
147386
+ }
147387
+ generatorPrototypes.set(budget, state);
147388
+ }
147389
+ var init_generator3 = __esm({
147390
+ "packages/safe-js/src/interp/globals/generator.ts"() {
147391
+ "use strict";
147392
+ init_generator_prototypes();
147393
+ init_intrinsics();
147394
+ init_generator2();
147395
+ init_object_model();
147396
+ init_values();
146948
147397
  }
146949
147398
  });
146950
147399
 
@@ -147192,7 +147641,7 @@ function createBuiltinBindings(options) {
147192
147641
  Date: createDateGlobal(options),
147193
147642
  Symbol: createSymbolGlobal(options.budget),
147194
147643
  BigInt: createBigIntGlobal(options.budget),
147195
- ...createErrorGlobals(options),
147644
+ ...createErrorGlobals({ ...options, errorPrototypes: options.errorPrototypes !== false }),
147196
147645
  ...createMathGlobals({ random: options.random, budget: options.budget }),
147197
147646
  ...createObjectArrayGlobals(options),
147198
147647
  ...createMiscGlobals(options),
@@ -147200,7 +147649,9 @@ function createBuiltinBindings(options) {
147200
147649
  ...createPromiseGlobals(options),
147201
147650
  ...createRegexGlobals(options)
147202
147651
  };
147203
- createFunctionPrototype(options.budget);
147652
+ createFunctionPrototype(options.budget, options.functionHasInstance);
147653
+ if (options.errorPrototypes !== false) createErrorPrototypes(options.budget, bindings);
147654
+ createGeneratorPrototypes(options.budget);
147204
147655
  registerBuiltinIdentities(options.budget, bindings);
147205
147656
  return bindings;
147206
147657
  }
@@ -147217,6 +147668,7 @@ var init_globals = __esm({
147217
147668
  init_uri();
147218
147669
  init_object_array();
147219
147670
  init_function2();
147671
+ init_generator3();
147220
147672
  init_promise();
147221
147673
  init_date2();
147222
147674
  init_symbol();
@@ -147270,7 +147722,7 @@ function validateGuestHeapNode(raw, heap, maxArrayLength = 4294967295) {
147270
147722
  createRawJson(node.text);
147271
147723
  return true;
147272
147724
  }
147273
- if (!["intrinsic", "guest-function", "guest-class", "guest-generator", "scope-frame", "guest-object", "guest-array", "array-iterator", "map", "set"].includes(String(node.kind))) return false;
147725
+ 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;
147274
147726
  const reference = (value, kinds) => {
147275
147727
  const ref = record3(value);
147276
147728
  fields(ref, ["kind", "id"]);
@@ -147281,7 +147733,7 @@ function validateGuestHeapNode(raw, heap, maxArrayLength = 4294967295) {
147281
147733
  };
147282
147734
  const callable = (value) => {
147283
147735
  if (absent(value)) return;
147284
- const target = reference(value, ["intrinsic", "guest-function", "guest-class"]);
147736
+ const target = reference(value, ["intrinsic", "bound-function", "guest-function", "guest-class"]);
147285
147737
  if (target.kind === "intrinsic" && intrinsicCatalogue().get(String(target.id)) !== true)
147286
147738
  throw new TypeError("Guest accessor reference is not callable.");
147287
147739
  };
@@ -147338,7 +147790,9 @@ function validateGuestHeapNode(raw, heap, maxArrayLength = 4294967295) {
147338
147790
  }
147339
147791
  state(node.state);
147340
147792
  } else if (node.kind === "guest-object" || node.kind === "guest-array") {
147341
- fields(node, ["kind", "state"], node.kind === "guest-array" ? ["templateNodeId", "templateOwner"] : []);
147793
+ fields(node, ["kind", "state"], node.kind === "guest-array" ? ["templateNodeId", "templateOwner"] : ["errorType"]);
147794
+ if (Object.hasOwn(node, "errorType") && !sandboxErrorNames.includes(node.errorType))
147795
+ throw new TypeError("Invalid guest error type.");
147342
147796
  if (Object.hasOwn(node, "templateOwner")) reference(node.templateOwner, ["guest-array"]);
147343
147797
  if (Object.hasOwn(node, "templateNodeId") && integer2(node.templateNodeId) < 1)
147344
147798
  throw new TypeError("Invalid template source identity.");
@@ -147377,6 +147831,22 @@ function validateGuestHeapNode(raw, heap, maxArrayLength = 4294967295) {
147377
147831
  if (descriptor.kind !== "data" || descriptor.writable !== false || descriptor.enumerable !== false || descriptor.configurable !== false)
147378
147832
  throw new TypeError("Invalid class prototype descriptor.");
147379
147833
  reference(descriptor.value, ["object", "guest-object"]);
147834
+ } else if (node.kind === "bound-function") {
147835
+ fields(node, ["kind", "target", "thisValue", "args", "length", "state"], ["name"]);
147836
+ if (Object.hasOwn(node, "name") && typeof node.name !== "string") throw new TypeError("Invalid bound function name.");
147837
+ if (array(node.args).length > maxArrayLength) throw new TypeError("Bound arguments exceed allocation limit.");
147838
+ if (!absent(node.length) && !(typeof node.length === "number" && node.length >= 0) && !(record3(node.length).kind === "number" && record3(node.length).value === "Infinity"))
147839
+ throw new TypeError("Invalid bound function length.");
147840
+ const visited = /* @__PURE__ */ new Set([raw]);
147841
+ let current = node;
147842
+ while (current.kind === "bound-function") {
147843
+ assertSnapshotDataDepth(visited.size, "<bound-target>");
147844
+ callable(current.target);
147845
+ current = reference(current.target);
147846
+ if (visited.has(current)) throw new TypeError("Cyclic bound function target.");
147847
+ visited.add(current);
147848
+ }
147849
+ state(node.state);
147380
147850
  } else if (node.kind === "guest-function") {
147381
147851
  fields(node, ["kind", "astNodeId", "scope", "state"], ["name", "environment"]);
147382
147852
  if (integer2(node.astNodeId) < 1) throw new TypeError("Invalid guest AST identity.");
@@ -147607,11 +148077,13 @@ var init_guest_heap_validation = __esm({
147607
148077
  "packages/safe-js/src/snapshot/guest-heap-validation.ts"() {
147608
148078
  "use strict";
147609
148079
  init_budget2();
148080
+ init_shape();
147610
148081
  init_raw_json();
147611
148082
  init_globals();
147612
148083
  init_intrinsics();
147613
148084
  init_object_model();
147614
148085
  init_values();
148086
+ init_graph_depth();
147615
148087
  }
147616
148088
  });
147617
148089
 
@@ -148285,7 +148757,7 @@ function validateArrayHeap(record4, path193, state) {
148285
148757
  }
148286
148758
  function validateErrorType(record4, path193) {
148287
148759
  if (!Object.hasOwn(record4, "errorType")) return;
148288
- if (record4.kind !== "object" || !sandboxErrorNames.includes(record4.errorType)) {
148760
+ if (record4.kind !== "object" && record4.kind !== "guest-object" || !sandboxErrorNames.includes(record4.errorType)) {
148289
148761
  fail2("invalidValue", `${path193}.errorType`, "invalid error metadata");
148290
148762
  }
148291
148763
  }