poe-code 14.0.61 → 14.0.63

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 (67) hide show
  1. package/dist/index.js +1147 -574
  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-VAYQP2VZ.js → chunk-KMTTD3BL.js} +7 -3
  6. package/packages/safe-js/dist/chunks/chunk-KMTTD3BL.js.map +7 -0
  7. package/packages/safe-js/dist/chunks/{chunk-ZTGKRKQH.js → chunk-RU2BCN4G.js} +1069 -577
  8. package/packages/safe-js/dist/chunks/chunk-RU2BCN4G.js.map +7 -0
  9. package/packages/safe-js/dist/cli.js +2 -2
  10. package/packages/safe-js/dist/core.js +1 -1
  11. package/packages/safe-js/dist/graph-depth.js +3 -0
  12. package/packages/safe-js/dist/index.js +2 -2
  13. package/packages/safe-js/dist/interp/async.js +3 -0
  14. package/packages/safe-js/dist/interp/boxed.d.ts +14 -0
  15. package/packages/safe-js/dist/interp/boxed.js +50 -0
  16. package/packages/safe-js/dist/interp/function-string.d.ts +2 -0
  17. package/packages/safe-js/dist/interp/function-string.js +21 -0
  18. package/packages/safe-js/dist/interp/globals/collections.js +4 -4
  19. package/packages/safe-js/dist/interp/globals/console-json.js +15 -18
  20. package/packages/safe-js/dist/interp/globals/misc.js +12 -13
  21. package/packages/safe-js/dist/interp/globals/numeric-parsers.d.ts +5 -0
  22. package/packages/safe-js/dist/interp/globals/numeric-parsers.js +47 -0
  23. package/packages/safe-js/dist/interp/globals/object-array.js +21 -24
  24. package/packages/safe-js/dist/interp/globals/object.js +10 -5
  25. package/packages/safe-js/dist/interp/globals/primitives.d.ts +8 -0
  26. package/packages/safe-js/dist/interp/globals/primitives.js +69 -0
  27. package/packages/safe-js/dist/interp/host-bridge.js +22 -0
  28. package/packages/safe-js/dist/interp/interpreter.js +173 -120
  29. package/packages/safe-js/dist/interp/iteration.d.ts +5 -3
  30. package/packages/safe-js/dist/interp/iteration.js +22 -1
  31. package/packages/safe-js/dist/interp/methods/array.js +6 -3
  32. package/packages/safe-js/dist/interp/methods/function.d.ts +2 -0
  33. package/packages/safe-js/dist/interp/methods/function.js +10 -1
  34. package/packages/safe-js/dist/interp/methods/number.d.ts +1 -0
  35. package/packages/safe-js/dist/interp/methods/number.js +4 -1
  36. package/packages/safe-js/dist/interp/methods/string.d.ts +2 -0
  37. package/packages/safe-js/dist/interp/methods/string.js +2 -2
  38. package/packages/safe-js/dist/interp/object-model.d.ts +5 -0
  39. package/packages/safe-js/dist/interp/object-model.js +41 -3
  40. package/packages/safe-js/dist/interp/promise.js +68 -61
  41. package/packages/safe-js/dist/interp/resources.d.ts +1 -0
  42. package/packages/safe-js/dist/interp/string-coercion.js +7 -1
  43. package/packages/safe-js/dist/interp/values.d.ts +4 -0
  44. package/packages/safe-js/dist/interp/values.js +81 -3
  45. package/packages/safe-js/dist/migrate.d.ts +2 -2
  46. package/packages/safe-js/dist/migrate.js +1 -1
  47. package/packages/safe-js/dist/migration-file.d.ts +4 -4
  48. package/packages/safe-js/dist/parse/function-source.d.ts +7 -0
  49. package/packages/safe-js/dist/parse/function-source.js +1 -0
  50. package/packages/safe-js/dist/parse/hash.d.ts +2 -2
  51. package/packages/safe-js/dist/parse/hash.js +23 -9
  52. package/packages/safe-js/dist/parse/parser.js +36 -23
  53. package/packages/safe-js/dist/restore.js +2 -1
  54. package/packages/safe-js/dist/run.js +16 -5
  55. package/packages/safe-js/dist/snapshot/boxed.d.ts +16 -0
  56. package/packages/safe-js/dist/snapshot/boxed.js +52 -0
  57. package/packages/safe-js/dist/snapshot/dump-format.d.ts +1 -1
  58. package/packages/safe-js/dist/snapshot/dump-format.js +19 -6
  59. package/packages/safe-js/dist/snapshot/migration.js +2 -2
  60. package/packages/safe-js/dist/snapshot/replay-data.d.ts +5 -0
  61. package/packages/safe-js/dist/snapshot/replay-data.js +24 -0
  62. package/packages/safe-js/dist/snapshot/restore.js +10 -0
  63. package/packages/safe-js/dist/snapshot/serialize.d.ts +4 -2
  64. package/packages/safe-js/dist/snapshot/serialize.js +18 -10
  65. package/packages/safe-js/dist/snapshot/validation.js +22 -1
  66. package/packages/safe-js/dist/chunks/chunk-VAYQP2VZ.js.map +0 -7
  67. package/packages/safe-js/dist/chunks/chunk-ZTGKRKQH.js.map +0 -7
package/dist/index.js CHANGED
@@ -50271,8 +50271,8 @@ function assertNonNegativeInteger3(value, keyword) {
50271
50271
  }
50272
50272
  function validateSchemaObject(schema, dialect) {
50273
50273
  if (schema.type !== void 0) {
50274
- const types6 = Array.isArray(schema.type) ? schema.type : [schema.type];
50275
- if (types6.length === 0 || !types6.every((type) => typeof type === "string" && draftTypeSet.has(type)) || new Set(types6).size !== types6.length) {
50274
+ const types7 = Array.isArray(schema.type) ? schema.type : [schema.type];
50275
+ if (types7.length === 0 || !types7.every((type) => typeof type === "string" && draftTypeSet.has(type)) || new Set(types7).size !== types7.length) {
50276
50276
  throw new Error("type must be a JSON Schema type or a unique array of JSON Schema types.");
50277
50277
  }
50278
50278
  }
@@ -50991,9 +50991,9 @@ function evaluateValidationKeywords(node, schema, value, path193) {
50991
50991
  if (schema.nullable === true && value === null) {
50992
50992
  return results;
50993
50993
  }
50994
- const types6 = typeof schema.type === "string" ? [schema.type] : Array.isArray(schema.type) ? schema.type : [];
50995
- if (types6.length > 0 && !types6.some((type) => typeof type === "string" && typeMatches(type, value))) {
50996
- results.push(invalidResult(issue(path193, types6.join(","), value, `must be ${types6.join(",")}`)));
50994
+ const types7 = typeof schema.type === "string" ? [schema.type] : Array.isArray(schema.type) ? schema.type : [];
50995
+ if (types7.length > 0 && !types7.some((type) => typeof type === "string" && typeMatches(type, value))) {
50996
+ results.push(invalidResult(issue(path193, types7.join(","), value, `must be ${types7.join(",")}`)));
50997
50997
  return results;
50998
50998
  }
50999
50999
  if (schema.const !== void 0 && !deepEqual(schema.const, value)) {
@@ -80409,18 +80409,18 @@ function readNumber3(value, fallback, field) {
80409
80409
  return value;
80410
80410
  }
80411
80411
  function readPositiveInteger(value, fallback, field) {
80412
- const numberValue2 = readNumber3(value, fallback, field);
80413
- if (!Number.isInteger(numberValue2) || numberValue2 <= 0) {
80412
+ const numberValue3 = readNumber3(value, fallback, field);
80413
+ if (!Number.isInteger(numberValue3) || numberValue3 <= 0) {
80414
80414
  throw new Error(`Expected "${field}" to be a positive integer.`);
80415
80415
  }
80416
- return numberValue2;
80416
+ return numberValue3;
80417
80417
  }
80418
80418
  function readNonNegativeInteger(value, fallback, field) {
80419
- const numberValue2 = readNumber3(value, fallback, field);
80420
- if (!Number.isInteger(numberValue2) || numberValue2 < 0) {
80419
+ const numberValue3 = readNumber3(value, fallback, field);
80420
+ if (!Number.isInteger(numberValue3) || numberValue3 < 0) {
80421
80421
  throw new Error(`Expected "${field}" to be a non-negative integer.`);
80422
80422
  }
80423
- return numberValue2;
80423
+ return numberValue3;
80424
80424
  }
80425
80425
  function readOptionalString3(value, field) {
80426
80426
  if (value === void 0) {
@@ -107711,7 +107711,7 @@ function registerUsageCommand(program, container) {
107711
107711
  const modelName = entry.bot_name.length > modelMaxWidth ? entry.bot_name.slice(0, modelMaxWidth - 1) + "\u2026" : entry.bot_name;
107712
107712
  const costText = `$${entry.cost_usd} (${entry.cost_points} points)`;
107713
107713
  const bd = entry.cost_breakdown_in_points;
107714
- const parseTokens2 = (s) => {
107714
+ const parseTokens = (s) => {
107715
107715
  if (!s) return "-";
107716
107716
  const start = s.indexOf("(");
107717
107717
  const end = s.indexOf(" tokens");
@@ -107722,9 +107722,9 @@ function registerUsageCommand(program, container) {
107722
107722
  Date: theme.muted(formatted),
107723
107723
  Model: theme.accent(modelName),
107724
107724
  Cost: entry.cost_points < 0 ? theme.error(costText) : theme.success(costText),
107725
- Input: theme.muted(parseTokens2(bd?.Input)),
107726
- Output: theme.muted(parseTokens2(bd?.Output)),
107727
- Cached: theme.muted(parseTokens2(bd?.["Cache discount"]))
107725
+ Input: theme.muted(parseTokens(bd?.Input)),
107726
+ Output: theme.muted(parseTokens(bd?.Output)),
107727
+ Cached: theme.muted(parseTokens(bd?.["Cache discount"]))
107728
107728
  };
107729
107729
  };
107730
107730
  let totalFetched = 0;
@@ -121455,6 +121455,15 @@ var init_assign_ids = __esm({
121455
121455
  }
121456
121456
  });
121457
121457
 
121458
+ // packages/safe-js/src/parse/function-source.ts
121459
+ var functionSources;
121460
+ var init_function_source = __esm({
121461
+ "packages/safe-js/src/parse/function-source.ts"() {
121462
+ "use strict";
121463
+ functionSources = /* @__PURE__ */ new WeakMap();
121464
+ }
121465
+ });
121466
+
121458
121467
  // packages/safe-js/src/parse/format-error.ts
121459
121468
  function formatParseError(source, filename, error3) {
121460
121469
  const location = parseErrorLocation(error3.message);
@@ -122095,7 +122104,11 @@ function parse15(source, filename = "<input>", owner) {
122095
122104
  const compilation = new CompileScope(owner);
122096
122105
  try {
122097
122106
  const result = assignIds(
122098
- parseTokens(tokenize3(source, { allowRegexLiterals: true, compilation }), compilation)
122107
+ new Parser(
122108
+ tokenize3(source, { allowRegexLiterals: true, compilation }),
122109
+ source,
122110
+ compilation
122111
+ ).parseTopLevel()
122099
122112
  );
122100
122113
  const regexLiteral = findRegexLiteral(result);
122101
122114
  if (regexLiteral !== void 0) {
@@ -122121,7 +122134,11 @@ function parseModule(source, filename = "<input>", owner) {
122121
122134
  const compilation = new CompileScope(owner);
122122
122135
  try {
122123
122136
  return assignIds(
122124
- parseModuleTokens(tokenize3(source, { allowRegexLiterals: true, compilation }), compilation)
122137
+ new Parser(
122138
+ tokenize3(source, { allowRegexLiterals: true, compilation }),
122139
+ source,
122140
+ compilation
122141
+ ).parseModule()
122125
122142
  );
122126
122143
  } catch (error3) {
122127
122144
  if (error3 instanceof DisallowedSyntaxError || error3 instanceof SandboxError) {
@@ -122139,7 +122156,11 @@ function parseExecutableModule(source, filename = "<input>", owner) {
122139
122156
  const compilation = new CompileScope(owner);
122140
122157
  try {
122141
122158
  const result = assignIds(
122142
- parseModuleTokens(tokenize3(source, { allowRegexLiterals: true, compilation }), compilation)
122159
+ new Parser(
122160
+ tokenize3(source, { allowRegexLiterals: true, compilation }),
122161
+ source,
122162
+ compilation
122163
+ ).parseModule()
122143
122164
  );
122144
122165
  throwIfImportMetaAssignment(result);
122145
122166
  return result;
@@ -122155,12 +122176,6 @@ function parseExecutableModule(source, filename = "<input>", owner) {
122155
122176
  compilation.dispose();
122156
122177
  }
122157
122178
  }
122158
- function parseTokens(tokens, compilation) {
122159
- return new Parser(tokens, compilation).parseTopLevel();
122160
- }
122161
- function parseModuleTokens(tokens, compilation) {
122162
- return new Parser(tokens, compilation).parseModule();
122163
- }
122164
122179
  function createIdentifier2(token) {
122165
122180
  return {
122166
122181
  type: "Identifier",
@@ -122469,6 +122484,7 @@ function createTemplateLiteral(token, options, compilation) {
122469
122484
  raw.slice(expressionStart, expressionEnd),
122470
122485
  positionWithinRaw(token.start, raw, expressionStart),
122471
122486
  options.functionContext,
122487
+ options.source,
122472
122488
  compilation
122473
122489
  )
122474
122490
  );
@@ -122831,13 +122847,13 @@ function decodeHexEscape(value, start) {
122831
122847
  end: index + 2
122832
122848
  };
122833
122849
  }
122834
- function parseEmbeddedExpression(source, base, functionContext, compilation) {
122850
+ function parseEmbeddedExpression(source, base, functionContext, fullSource, compilation) {
122835
122851
  const tokens = tokenize3(source, { allowRegexLiterals: true, compilation }).map((token) => ({
122836
122852
  ...token,
122837
122853
  start: rebasePosition(token.start, base),
122838
122854
  end: rebasePosition(token.end, base)
122839
122855
  }));
122840
- return new Parser(tokens, compilation, functionContext).parseExpressionOnly();
122856
+ return new Parser(tokens, fullSource, compilation, functionContext).parseExpressionOnly();
122841
122857
  }
122842
122858
  function findRegexLiteral(node) {
122843
122859
  if (node === null || node === void 0) {
@@ -122983,6 +122999,7 @@ var init_parser3 = __esm({
122983
122999
  init_bindings();
122984
123000
  init_tokenizer2();
122985
123001
  init_assign_ids();
123002
+ init_function_source();
122986
123003
  init_format_error();
122987
123004
  init_parse_export();
122988
123005
  init_parse_import_meta();
@@ -123022,13 +123039,15 @@ var init_parser3 = __esm({
123022
123039
  "while"
123023
123040
  ]);
123024
123041
  Parser = class {
123025
- constructor(tokens, compilation, functionContext = "normal") {
123042
+ constructor(tokens, source, compilation, functionContext = "normal") {
123026
123043
  this.tokens = tokens;
123044
+ this.source = source;
123027
123045
  this.compilation = compilation;
123028
123046
  this.functionContext = functionContext;
123029
123047
  this.functionScopes.add(this.scopes[0]);
123030
123048
  }
123031
123049
  tokens;
123050
+ source;
123032
123051
  compilation;
123033
123052
  functionContext;
123034
123053
  index = 0;
@@ -123039,6 +123058,14 @@ var init_parser3 = __esm({
123039
123058
  scopes = [/* @__PURE__ */ new Map()];
123040
123059
  functionScopes = /* @__PURE__ */ new WeakSet();
123041
123060
  varNames = /* @__PURE__ */ new WeakMap();
123061
+ withFunctionSource(node) {
123062
+ functionSources.set(node, {
123063
+ text: this.source,
123064
+ start: node.span.start.offset,
123065
+ end: node.span.end.offset
123066
+ });
123067
+ return node;
123068
+ }
123042
123069
  parseTopLevel() {
123043
123070
  if (this.isExportToken(this.currentToken())) {
123044
123071
  throw new DisallowedSyntaxError("export", this.currentToken().start);
@@ -123180,14 +123207,14 @@ var init_parser3 = __esm({
123180
123207
  });
123181
123208
  this.expectPunctuator("=>");
123182
123209
  const body = this.parseArrowFunctionBody(params);
123183
- return {
123210
+ return this.withFunctionSource({
123184
123211
  type: "ArrowFunctionExpression",
123185
123212
  async: isAsync,
123186
123213
  body,
123187
123214
  expression: body.type !== "BlockStatement",
123188
123215
  params,
123189
123216
  span: createSpan2(start, body.span.end)
123190
- };
123217
+ });
123191
123218
  }
123192
123219
  parseConditionalExpression() {
123193
123220
  if (this.conditionalExpressionDepth >= MAX_CONDITIONAL_EXPRESSION_DEPTH) {
@@ -123827,8 +123854,11 @@ var init_parser3 = __esm({
123827
123854
  return parsedParams;
123828
123855
  });
123829
123856
  const generator = generatorToken !== void 0;
123830
- const body = this.withFunctionContext(generator ? "generator" : "normal", () => this.parseBlockStatement(params));
123831
- return {
123857
+ const body = this.withFunctionContext(
123858
+ generator ? "generator" : "normal",
123859
+ () => this.parseBlockStatement(params)
123860
+ );
123861
+ return this.withFunctionSource({
123832
123862
  type: "FunctionDeclaration",
123833
123863
  async: asyncToken !== void 0,
123834
123864
  body,
@@ -123836,7 +123866,7 @@ var init_parser3 = __esm({
123836
123866
  id,
123837
123867
  params,
123838
123868
  span: createSpan2(asyncToken?.start ?? functionToken.start, body.span.end)
123839
- };
123869
+ });
123840
123870
  }
123841
123871
  parseVariableDeclarator(kind) {
123842
123872
  const id = this.parseBindingTarget();
@@ -124604,7 +124634,11 @@ var init_parser3 = __esm({
124604
124634
  if (this.currentToken().type === "template") {
124605
124635
  const quasi = createTemplateLiteral(
124606
124636
  this.currentToken(),
124607
- { allowMalformedEscapes: true, functionContext: this.functionContext },
124637
+ {
124638
+ allowMalformedEscapes: true,
124639
+ functionContext: this.functionContext,
124640
+ source: this.source
124641
+ },
124608
124642
  this.compilation
124609
124643
  );
124610
124644
  this.index += 1;
@@ -124693,7 +124727,11 @@ var init_parser3 = __esm({
124693
124727
  return {
124694
124728
  node: createTemplateLiteral(
124695
124729
  token,
124696
- { allowMalformedEscapes: false, functionContext: this.functionContext },
124730
+ {
124731
+ allowMalformedEscapes: false,
124732
+ functionContext: this.functionContext,
124733
+ source: this.source
124734
+ },
124697
124735
  this.compilation
124698
124736
  ),
124699
124737
  parenthesized: false
@@ -124778,7 +124816,8 @@ var init_parser3 = __esm({
124778
124816
  break;
124779
124817
  }
124780
124818
  const optional = this.consumePunctuator("?.");
124781
- if (optional !== void 0) throw new DisallowedSyntaxError("new optional chain", optional.start);
124819
+ if (optional !== void 0)
124820
+ throw new DisallowedSyntaxError("new optional chain", optional.start);
124782
124821
  const args = this.consumePunctuator("(") === void 0 ? [] : this.parseArguments();
124783
124822
  const end = this.previousToken();
124784
124823
  return {
@@ -124811,8 +124850,11 @@ var init_parser3 = __esm({
124811
124850
  return parsedParams;
124812
124851
  });
124813
124852
  const generator = generatorToken !== void 0;
124814
- const body = this.withFunctionContext(generator ? "generator" : "normal", () => this.parseBlockStatement(params));
124815
- return {
124853
+ const body = this.withFunctionContext(
124854
+ generator ? "generator" : "normal",
124855
+ () => this.parseBlockStatement(params)
124856
+ );
124857
+ return this.withFunctionSource({
124816
124858
  type: "FunctionExpression",
124817
124859
  async: asyncToken !== void 0,
124818
124860
  body,
@@ -124820,7 +124862,7 @@ var init_parser3 = __esm({
124820
124862
  id,
124821
124863
  params,
124822
124864
  span: createSpan2(asyncToken?.start ?? functionToken.start, body.span.end)
124823
- };
124865
+ });
124824
124866
  }
124825
124867
  parseArrayExpression() {
124826
124868
  const start = this.expectPunctuator("[");
@@ -125056,7 +125098,7 @@ var init_parser3 = __esm({
125056
125098
  return parsedParams;
125057
125099
  });
125058
125100
  const body = this.withFunctionContext("normal", () => this.parseBlockStatement(params));
125059
- return {
125101
+ return this.withFunctionSource({
125060
125102
  type: "FunctionExpression",
125061
125103
  async: asyncToken !== void 0,
125062
125104
  body,
@@ -125065,7 +125107,7 @@ var init_parser3 = __esm({
125065
125107
  method: true,
125066
125108
  params,
125067
125109
  span: createSpan2(asyncToken?.start ?? methodStart, body.span.end)
125068
- };
125110
+ });
125069
125111
  }
125070
125112
  parseIdentifierName() {
125071
125113
  const token = this.currentToken();
@@ -125624,19 +125666,19 @@ var init_parser3 = __esm({
125624
125666
  });
125625
125667
 
125626
125668
  // packages/safe-js/src/parse/hash.ts
125627
- function hashSource(source, owner) {
125669
+ function hashSource(source, owner, includeFunctionSource = true) {
125628
125670
  try {
125629
- return hashParsedAst(parse15(source, "<input>", owner));
125671
+ return hashParsedAst(parse15(source, "<input>", owner), includeFunctionSource);
125630
125672
  } catch (error3) {
125631
125673
  if (error3 instanceof SandboxError) throw error3;
125632
- return hashParsedAst(parseModule(source, "<input>", owner));
125674
+ return hashParsedAst(parseModule(source, "<input>", owner), includeFunctionSource);
125633
125675
  }
125634
125676
  }
125635
- function hashParsedAst(ast) {
125677
+ function hashParsedAst(ast, includeFunctionSource = true) {
125636
125678
  let hash = FNV_OFFSET_BASIS;
125637
125679
  visit(ast);
125638
125680
  return hash.toString(16).padStart(8, "0");
125639
- function visit(value, includeTemplateRaw = false) {
125681
+ function visit(value, includeTemplateRaw = false, enclosingSource) {
125640
125682
  if (value === null) {
125641
125683
  write2("null");
125642
125684
  return;
@@ -125648,7 +125690,7 @@ function hashParsedAst(ast) {
125648
125690
  if (Array.isArray(value)) {
125649
125691
  write2("[");
125650
125692
  for (const entry of value) {
125651
- visit(entry, includeTemplateRaw);
125693
+ visit(entry, includeTemplateRaw, enclosingSource);
125652
125694
  write2(",");
125653
125695
  }
125654
125696
  write2("]");
@@ -125666,12 +125708,23 @@ function hashParsedAst(ast) {
125666
125708
  return;
125667
125709
  case "object": {
125668
125710
  const record2 = value;
125711
+ const source = includeFunctionSource ? functionSources.get(value) : void 0;
125712
+ if (source !== void 0 && !(enclosingSource !== void 0 && source.text === enclosingSource.text && source.start >= enclosingSource.start && source.end <= enclosingSource.end)) {
125713
+ write2("function-source:");
125714
+ write2(String(source.end - source.start));
125715
+ write2(":");
125716
+ write2(source.text, source.start, source.end);
125717
+ }
125669
125718
  const keys = Object.keys(value).filter((key3) => shouldHashKey(record2, key3, includeTemplateRaw)).sort();
125670
125719
  write2("{");
125671
125720
  for (const key3 of keys) {
125672
125721
  write2(JSON.stringify(key3));
125673
125722
  write2(":");
125674
- visit(record2[key3], shouldIncludeTemplateRaw(record2, key3, includeTemplateRaw));
125723
+ visit(
125724
+ record2[key3],
125725
+ shouldIncludeTemplateRaw(record2, key3, includeTemplateRaw),
125726
+ source ?? enclosingSource
125727
+ );
125675
125728
  write2(",");
125676
125729
  }
125677
125730
  write2("}");
@@ -125681,8 +125734,8 @@ function hashParsedAst(ast) {
125681
125734
  throw new TypeError(`Unsupported AST value type: ${typeof value}`);
125682
125735
  }
125683
125736
  }
125684
- function write2(chunk) {
125685
- for (let index = 0; index < chunk.length; index += 1) {
125737
+ function write2(chunk, start = 0, end = chunk.length) {
125738
+ for (let index = start; index < end; index += 1) {
125686
125739
  hash ^= chunk.charCodeAt(index);
125687
125740
  hash = Math.imul(hash, FNV_PRIME) >>> 0;
125688
125741
  }
@@ -125712,6 +125765,7 @@ var init_hash = __esm({
125712
125765
  "use strict";
125713
125766
  init_parser3();
125714
125767
  init_budget2();
125768
+ init_function_source();
125715
125769
  FNV_OFFSET_BASIS = 2166136261;
125716
125770
  FNV_PRIME = 16777619;
125717
125771
  IGNORED_KEYS = /* @__PURE__ */ new Set(["nodeId", "raw", "span"]);
@@ -125847,6 +125901,54 @@ var init_collection_brands = __esm({
125847
125901
  }
125848
125902
  });
125849
125903
 
125904
+ // packages/safe-js/src/interp/boxed.ts
125905
+ import { types } from "node:util";
125906
+ function nativeBoxedValue(value) {
125907
+ if (types.isNumberObject(value)) return Reflect.apply(numberValue2, value, []);
125908
+ if (types.isStringObject(value)) return Reflect.apply(stringValue2, value, []);
125909
+ if (types.isBooleanObject(value)) return Reflect.apply(booleanValue, value, []);
125910
+ return void 0;
125911
+ }
125912
+ function createSandboxBox(value) {
125913
+ if (typeof value !== "number" && typeof value !== "string" && typeof value !== "boolean")
125914
+ throw new TypeError("Invalid boxed primitive payload.");
125915
+ const box = Object(value);
125916
+ Object.setPrototypeOf(box, null);
125917
+ boxes.add(box);
125918
+ return box;
125919
+ }
125920
+ function isSandboxBox(value) {
125921
+ return typeof value === "object" && value !== null && boxes.has(value);
125922
+ }
125923
+ function boxedValue(value) {
125924
+ if (!boxes.has(value)) throw new TypeError("Expected a sandbox boxed primitive.");
125925
+ return nativeBoxedValue(value);
125926
+ }
125927
+ function primitiveReceiver(value, kind) {
125928
+ const primitive = isSandboxBox(value) ? boxedValue(value) : value;
125929
+ if (typeof primitive !== kind) throw new TypeError(`${kind} method requires a ${kind} receiver.`);
125930
+ return primitive;
125931
+ }
125932
+ function boxedDataProperties(value) {
125933
+ const primitive = nativeBoxedValue(value);
125934
+ return Object.entries(Object.getOwnPropertyDescriptors(value)).filter(([key3]) => {
125935
+ if (typeof primitive !== "string") return true;
125936
+ if (key3 === "length") return false;
125937
+ const index = Number(key3);
125938
+ return !(Number.isInteger(index) && index >= 0 && index < primitive.length && String(index) === key3);
125939
+ });
125940
+ }
125941
+ var boxes, numberValue2, stringValue2, booleanValue;
125942
+ var init_boxed = __esm({
125943
+ "packages/safe-js/src/interp/boxed.ts"() {
125944
+ "use strict";
125945
+ boxes = /* @__PURE__ */ new WeakSet();
125946
+ numberValue2 = Number.prototype.valueOf;
125947
+ stringValue2 = String.prototype.valueOf;
125948
+ booleanValue = Boolean.prototype.valueOf;
125949
+ }
125950
+ });
125951
+
125850
125952
  // packages/safe-js/src/graph-depth.ts
125851
125953
  function assertSandboxDataDepth(depth) {
125852
125954
  if (depth > MAX_DATA_DEPTH) {
@@ -125889,6 +125991,7 @@ function walkGraphDepth(root, rootPath, assertDepth) {
125889
125991
  }
125890
125992
  }
125891
125993
  function graphEntries(value) {
125994
+ if (isSandboxBox(value)) return boxedDataProperties(value).map(([key3, descriptor]) => [`.${key3}`, descriptor.value]);
125892
125995
  if (isSandboxArguments(value)) {
125893
125996
  return getSandboxArgumentEntries(value).map(([key3, entry]) => [`.${key3}`, entry]);
125894
125997
  }
@@ -125921,6 +126024,7 @@ var init_graph_depth = __esm({
125921
126024
  init_arguments();
125922
126025
  init_collection_iterator();
125923
126026
  init_collection_brands();
126027
+ init_boxed();
125924
126028
  MAX_DATA_DEPTH = 1024;
125925
126029
  SnapshotBudgetError = class extends Error {
125926
126030
  code = "budgetExceeded";
@@ -125941,9 +126045,9 @@ var init_graph_depth = __esm({
125941
126045
  });
125942
126046
 
125943
126047
  // packages/safe-js/src/extensions.ts
125944
- import { types } from "node:util";
126048
+ import { types as types2 } from "node:util";
125945
126049
  function readDataRecord(value, label) {
125946
- if (typeof value !== "object" || value === null || types.isProxy(value)) {
126050
+ if (typeof value !== "object" || value === null || types2.isProxy(value)) {
125947
126051
  throw new TypeError(`${label} must be a plain data record.`);
125948
126052
  }
125949
126053
  const prototype = Object.getPrototypeOf(value);
@@ -125963,7 +126067,7 @@ function readDataRecord(value, label) {
125963
126067
  return result;
125964
126068
  }
125965
126069
  function readStringList(value, label) {
125966
- if (!Array.isArray(value) || types.isProxy(value) || value.length > 4096) {
126070
+ if (!Array.isArray(value) || types2.isProxy(value) || value.length > 4096) {
125967
126071
  throw new TypeError(`${label} must be a bounded string array.`);
125968
126072
  }
125969
126073
  const result = [];
@@ -125994,7 +126098,7 @@ var init_extensions = __esm({
125994
126098
  });
125995
126099
 
125996
126100
  // packages/safe-js/src/interp/host-capabilities.ts
125997
- import { types as types2 } from "node:util";
126101
+ import { types as types3 } from "node:util";
125998
126102
  function createGuestReference(root, owner, assertActive) {
125999
126103
  const reference = Object.freeze(/* @__PURE__ */ Object.create(null));
126000
126104
  guestReferences.set(reference, { root, owner, assertActive });
@@ -126042,7 +126146,7 @@ function createLiveHostObject(definition, controller) {
126042
126146
  for (const name of ["keys", "get", "set", "delete"]) {
126043
126147
  const operation = data[name];
126044
126148
  if (operation === void 0 && (name === "set" || name === "delete")) continue;
126045
- if (typeof operation !== "function" || types2.isProxy(operation) || types2.isAsyncFunction(operation) || types2.isGeneratorFunction(operation))
126149
+ if (typeof operation !== "function" || types3.isProxy(operation) || types3.isAsyncFunction(operation) || types3.isGeneratorFunction(operation))
126046
126150
  throw new TypeError(`Named ${name} must be a synchronous non-generator function, not a proxy.`);
126047
126151
  }
126048
126152
  if (typeof data.maxKeys !== "number" || !Number.isInteger(data.maxKeys) || data.maxKeys < 1 || data.maxKeys > MAX_NAMED_KEYS)
@@ -126297,7 +126401,7 @@ function namedMutationKeys(state, key3, create) {
126297
126401
  function namedKeys2(state) {
126298
126402
  const named = state.named;
126299
126403
  return state.controller.read(named.keys, (value) => {
126300
- if (!Array.isArray(value) || types2.isProxy(value))
126404
+ if (!Array.isArray(value) || types3.isProxy(value))
126301
126405
  throw new TypeError("Named keys must be a dense own-data array of strings, not a proxy.");
126302
126406
  const length = Object.getOwnPropertyDescriptor(value, "length").value;
126303
126407
  if (length > named.maxKeys) throw new RangeError("Named keys exceed maxKeys.");
@@ -126438,7 +126542,7 @@ var init_otel2 = __esm({
126438
126542
  });
126439
126543
 
126440
126544
  // packages/safe-js/src/interp/date.ts
126441
- import { types as types3 } from "node:util";
126545
+ import { types as types4 } from "node:util";
126442
126546
  function isSandboxDate(value) {
126443
126547
  return typeof value === "object" && value !== null && dates.has(value);
126444
126548
  }
@@ -126451,7 +126555,7 @@ function dateTime(value) {
126451
126555
  return Reflect.apply(readTime, value, []);
126452
126556
  }
126453
126557
  function copyNativeDate(value) {
126454
- if (!types3.isDate(value)) return void 0;
126558
+ if (!types4.isDate(value)) return void 0;
126455
126559
  if (Object.getPrototypeOf(value) !== NativeDate.prototype || Reflect.ownKeys(value).length > 0)
126456
126560
  throw new TypeError("Date subclasses and own properties are not supported.");
126457
126561
  return createSandboxDate(dateTime(value));
@@ -127149,6 +127253,40 @@ var init_float32array = __esm({
127149
127253
  }
127150
127254
  });
127151
127255
 
127256
+ // packages/safe-js/src/snapshot/boxed.ts
127257
+ function encodeBoxedData(value, encode) {
127258
+ const properties = /* @__PURE__ */ Object.create(null);
127259
+ for (const [key3, descriptor] of boxedDataProperties(value)) {
127260
+ if (!("value" in descriptor)) throw new TypeError("Boxed data cannot contain accessors.");
127261
+ properties[key3] = {
127262
+ value: encode(descriptor.value, key3),
127263
+ configurable: descriptor.configurable === true,
127264
+ enumerable: descriptor.enumerable === true,
127265
+ writable: descriptor.writable === true
127266
+ };
127267
+ }
127268
+ return {
127269
+ kind: "boxed",
127270
+ value: encode(boxedValue(value), "<payload>"),
127271
+ properties,
127272
+ extensible: Object.isExtensible(value)
127273
+ };
127274
+ }
127275
+ function validateBoxedProperties(data) {
127276
+ if (!Object.hasOwn(data, "kind") || data.kind !== "boxed" || !Object.hasOwn(data, "value") || !Object.hasOwn(data, "extensible") || !Object.hasOwn(data, "properties") || Object.keys(data).length !== 4 || typeof data.extensible !== "boolean" || typeof data.properties !== "object" || data.properties === null || Array.isArray(data.properties))
127277
+ throw new TypeError("Invalid boxed primitive properties.");
127278
+ for (const descriptor of Object.values(data.properties)) {
127279
+ if (typeof descriptor !== "object" || descriptor === null || !Object.hasOwn(descriptor, "value") || !Object.hasOwn(descriptor, "writable") || !Object.hasOwn(descriptor, "enumerable") || !Object.hasOwn(descriptor, "configurable") || typeof descriptor.writable !== "boolean" || typeof descriptor.enumerable !== "boolean" || typeof descriptor.configurable !== "boolean" || Object.keys(descriptor).length !== 4)
127280
+ throw new TypeError("Invalid boxed primitive descriptor.");
127281
+ }
127282
+ }
127283
+ var init_boxed2 = __esm({
127284
+ "packages/safe-js/src/snapshot/boxed.ts"() {
127285
+ "use strict";
127286
+ init_boxed();
127287
+ }
127288
+ });
127289
+
127152
127290
  // packages/safe-js/src/snapshot/arguments.ts
127153
127291
  function serializeArguments(value, serializeValue) {
127154
127292
  const properties = /* @__PURE__ */ Object.create(null);
@@ -127235,6 +127373,13 @@ function encodeReplayData(value, options = {}) {
127235
127373
  id: capabilityId,
127236
127374
  properties: child(entry.properties, "properties")
127237
127375
  };
127376
+ } else if (nativeBoxedValue(entry) !== void 0) {
127377
+ const properties = /* @__PURE__ */ Object.create(null);
127378
+ nodes[id] = { kind: "boxed", value: child(nativeBoxedValue(entry), "<payload>"), properties, extensible: Object.isExtensible(entry) };
127379
+ for (const [key3, descriptor] of boxedDataProperties(entry)) {
127380
+ if (!("value" in descriptor)) throw new TypeError(`Cannot record replay data accessor '${key3}'.`);
127381
+ properties[key3] = { value: child(descriptor.value, JSON.stringify(["property", key3])), configurable: descriptor.configurable === true, enumerable: descriptor.enumerable === true, writable: descriptor.writable === true };
127382
+ }
127238
127383
  } else if (isSandboxDate(entry)) {
127239
127384
  nodes[id] = { kind: "date", time: serializedDateTime(entry) };
127240
127385
  } else if (isFloat32Array(entry)) {
@@ -127396,6 +127541,17 @@ function decodeReplayData(input, options = {}, parent) {
127396
127541
  options.onCapabilityRestored?.(capability, copy);
127397
127542
  return copy;
127398
127543
  }
127544
+ if (kind === "boxed") {
127545
+ validateBoxedProperties(node);
127546
+ const payload = own(node, "value");
127547
+ if (typeof payload !== "number" && typeof payload !== "string" && typeof payload !== "boolean" && (payload === null || typeof payload !== "object" || own(record(payload), "tag") !== "number"))
127548
+ throw new TypeError("Invalid boxed primitive payload.");
127549
+ const result3 = createSandboxBox(child(payload));
127550
+ restored.set(id, result3);
127551
+ defineProperties(result3, record(own(node, "properties")), child);
127552
+ if (!node.extensible) Object.preventExtensions(result3);
127553
+ return result3;
127554
+ }
127399
127555
  if (kind === "date") {
127400
127556
  if (Object.keys(node).length !== 2) throw new TypeError("Invalid serialized Date fields.");
127401
127557
  const result3 = restoreDateTime(own(node, "time"));
@@ -127534,6 +127690,8 @@ var init_replay_data = __esm({
127534
127690
  init_float32();
127535
127691
  init_float32array();
127536
127692
  init_date();
127693
+ init_boxed();
127694
+ init_boxed2();
127537
127695
  init_shape();
127538
127696
  init_values();
127539
127697
  init_arguments2();
@@ -128668,6 +128826,28 @@ var init_resources = __esm({
128668
128826
  }
128669
128827
  });
128670
128828
 
128829
+ // packages/safe-js/src/interp/function-string.ts
128830
+ function functionString(value) {
128831
+ if (runResources.getStore()?.functionSourceText === false) return "[object Object]";
128832
+ const source = value.sourceRange;
128833
+ if (source !== void 0) return source.text.slice(source.start, source.end);
128834
+ let name = value.boundTarget === void 0 ? value.name?.split("#").at(-1) ?? "" : "";
128835
+ for (let index = 0; index < name.length; index++) {
128836
+ const code = name.charCodeAt(index);
128837
+ if (!(code >= 65 && code <= 90 || code >= 97 && code <= 122 || code === 36 || code === 95 || index > 0 && code >= 48 && code <= 57)) {
128838
+ name = "";
128839
+ break;
128840
+ }
128841
+ }
128842
+ return `function ${name}() { [native code] }`;
128843
+ }
128844
+ var init_function_string = __esm({
128845
+ "packages/safe-js/src/interp/function-string.ts"() {
128846
+ "use strict";
128847
+ init_resources();
128848
+ }
128849
+ });
128850
+
128671
128851
  // packages/safe-js/src/interp/string-coercion.ts
128672
128852
  function sandboxNumber(value, budget, context) {
128673
128853
  if (value === null || typeof value !== "object") {
@@ -128693,7 +128873,7 @@ async function objectToPrimitive(value, budget, context, joining, hint) {
128693
128873
  if (hook === defaultStringHook) {
128694
128874
  result = await defaultToString(value, budget, context, joining);
128695
128875
  } else if (hook === defaultValueHook) {
128696
- result = isSandboxDate(value) ? dateTime(value) : value;
128876
+ result = isSandboxDate(value) ? dateTime(value) : isSandboxBox(value) ? boxedValue(value) : value;
128697
128877
  } else {
128698
128878
  if (!isSandboxClosure(hook)) continue;
128699
128879
  result = await invokeBuiltinClosure(hook, [], budget, context, value);
@@ -128733,6 +128913,8 @@ function conversionHook(value, name, budget) {
128733
128913
  return void 0;
128734
128914
  }
128735
128915
  async function defaultToString(value, budget, context, joining) {
128916
+ if (isSandboxBox(value)) return budget.allocateString(String(boxedValue(value)));
128917
+ if (isSandboxClosure(value)) return budget.allocateString(functionString(value));
128736
128918
  if (isSandboxMap(value)) return "[object Map]";
128737
128919
  if (isSandboxSet(value)) return "[object Set]";
128738
128920
  if (isSandboxCollectionIterator(value)) return collectionIteratorState(value).collectionKind === "map" ? "[object Map Iterator]" : "[object Set Iterator]";
@@ -128803,6 +128985,8 @@ var init_string_coercion = __esm({
128803
128985
  init_object_model();
128804
128986
  init_regex();
128805
128987
  init_resources();
128988
+ init_function_string();
128989
+ init_boxed();
128806
128990
  init_values();
128807
128991
  defaultStringHook = /* @__PURE__ */ Symbol("defaultStringHook");
128808
128992
  defaultValueHook = /* @__PURE__ */ Symbol("defaultValueHook");
@@ -129333,7 +129517,27 @@ var init_running_state = __esm({
129333
129517
  });
129334
129518
 
129335
129519
  // packages/safe-js/src/interp/iteration.ts
129336
- function getSandboxIterator(value, budget) {
129520
+ function getSandboxIterator(value, budget, context) {
129521
+ if (isSandboxBox(value) && typeof boxedValue(value) === "string") {
129522
+ const primitive = boxedValue(value);
129523
+ let text5;
129524
+ let iterator;
129525
+ let initialized;
129526
+ return {
129527
+ asynchronous: true,
129528
+ get retainedValue() {
129529
+ return text5 === primitive ? void 0 : text5;
129530
+ },
129531
+ next: async () => {
129532
+ initialized ??= Promise.resolve(sandboxString(value, budget ?? new Budget(), context)).then((converted) => {
129533
+ text5 = converted;
129534
+ iterator = syncIterator(converted[Symbol.iterator]());
129535
+ });
129536
+ await initialized;
129537
+ return iterator.next();
129538
+ }
129539
+ };
129540
+ }
129337
129541
  if (isSandboxCollectionIterator(value)) return { next: () => nextCollectionIterator(value, budget), snapshotIndex: () => 0 };
129338
129542
  if (isGuestHostObject(value)) return getHostObjectIterator(value);
129339
129543
  if (isFloat32Array(value)) {
@@ -129437,8 +129641,11 @@ var init_iteration = __esm({
129437
129641
  init_values();
129438
129642
  init_running_state();
129439
129643
  init_float32();
129644
+ init_boxed();
129440
129645
  init_host_capabilities();
129441
129646
  init_collection_iterator();
129647
+ init_budget2();
129648
+ init_string_coercion();
129442
129649
  }
129443
129650
  });
129444
129651
 
@@ -129913,67 +130120,72 @@ async function settleIterable(iterable, method, budget, constructor, context) {
129913
130120
  const promiseResolve = readPromiseReceiverProperty(constructor, "resolve", prototype);
129914
130121
  if (!isSandboxClosure(promiseResolve))
129915
130122
  throw new TypeError("Promise constructor requires a callable resolve.");
129916
- const iterator = getSandboxIterator(iterable, budget);
130123
+ const iterator = getSandboxIterator(iterable, budget, context);
129917
130124
  if (iterator === void 0) throw new TypeError("Promise helpers require an iterable.");
129918
- let index = 0;
129919
- while (true) {
129920
- budget.visitNode();
129921
- const next = iterator.generator ? await iterator.next() : iterator.next();
129922
- if (typeof next !== "object" || next === null)
129923
- throw new TypeError("Iterator result must be an object.");
129924
- if (next.done) break;
129925
- const value = next.value;
129926
- try {
129927
- budget.allocateArrayLength(index + 1);
129928
- const entryIndex = index++;
129929
- if (method !== "race") values.push(void 0);
129930
- const entry = await callPromiseClosure(
129931
- promiseResolve,
129932
- [value],
129933
- constructor,
129934
- budget,
129935
- context
129936
- );
129937
- let called = false;
129938
- const handlers = ["fulfilled", "rejected"].map((state) => {
129939
- if (method === "race" || method === "any" && state === "fulfilled")
129940
- return state === "fulfilled" ? capability.resolve : capability.reject;
129941
- if (method === "all" && state === "rejected") return capability.reject;
129942
- return createSandboxClosure({
129943
- sandbox: true,
129944
- retainedValues: () => [
129945
- capability.promise,
129946
- capability.resolve,
129947
- capability.reject,
129948
- values
129949
- ],
129950
- call: async ([settlement]) => {
129951
- if (called) return void 0;
129952
- called = true;
129953
- values[entryIndex] = method === "allSettled" ? state === "fulfilled" ? { status: state, value: settlement } : { status: state, reason: settlement } : settlement;
129954
- remaining--;
129955
- await complete();
129956
- return void 0;
129957
- }
129958
- });
129959
- });
129960
- remaining++;
129961
- const then = readPromiseReceiverProperty(entry, "then", prototype);
129962
- if (!isSandboxClosure(then))
129963
- throw new TypeError("Promise resolver result requires a callable then.");
129964
- await callPromiseClosure(then, handlers, entry, budget, context);
129965
- } catch (error3) {
130125
+ const releaseIterator = retainValues(budget, () => [iterator.retainedValue]);
130126
+ try {
130127
+ let index = 0;
130128
+ while (true) {
130129
+ budget.visitNode();
130130
+ const next = iterator.generator || iterator.asynchronous ? await iterator.next() : iterator.next();
130131
+ if (typeof next !== "object" || next === null)
130132
+ throw new TypeError("Iterator result must be an object.");
130133
+ if (next.done) break;
130134
+ const value = next.value;
129966
130135
  try {
129967
- const closed = iterator.return?.();
129968
- if (iterator.generator) await closed;
129969
- } catch {
130136
+ budget.allocateArrayLength(index + 1);
130137
+ const entryIndex = index++;
130138
+ if (method !== "race") values.push(void 0);
130139
+ const entry = await callPromiseClosure(
130140
+ promiseResolve,
130141
+ [value],
130142
+ constructor,
130143
+ budget,
130144
+ context
130145
+ );
130146
+ let called = false;
130147
+ const handlers = ["fulfilled", "rejected"].map((state) => {
130148
+ if (method === "race" || method === "any" && state === "fulfilled")
130149
+ return state === "fulfilled" ? capability.resolve : capability.reject;
130150
+ if (method === "all" && state === "rejected") return capability.reject;
130151
+ return createSandboxClosure({
130152
+ sandbox: true,
130153
+ retainedValues: () => [
130154
+ capability.promise,
130155
+ capability.resolve,
130156
+ capability.reject,
130157
+ values
130158
+ ],
130159
+ call: async ([settlement]) => {
130160
+ if (called) return void 0;
130161
+ called = true;
130162
+ values[entryIndex] = method === "allSettled" ? state === "fulfilled" ? { status: state, value: settlement } : { status: state, reason: settlement } : settlement;
130163
+ remaining--;
130164
+ await complete();
130165
+ return void 0;
130166
+ }
130167
+ });
130168
+ });
130169
+ remaining++;
130170
+ const then = readPromiseReceiverProperty(entry, "then", prototype);
130171
+ if (!isSandboxClosure(then))
130172
+ throw new TypeError("Promise resolver result requires a callable then.");
130173
+ await callPromiseClosure(then, handlers, entry, budget, context);
130174
+ } catch (error3) {
130175
+ try {
130176
+ const closed = iterator.return?.();
130177
+ if (iterator.generator || iterator.asynchronous) await closed;
130178
+ } catch {
130179
+ throw error3;
130180
+ }
129970
130181
  throw error3;
129971
130182
  }
129972
- throw error3;
129973
130183
  }
130184
+ remaining--;
130185
+ await complete();
130186
+ } finally {
130187
+ releaseIterator();
129974
130188
  }
129975
- remaining--;
129976
- await complete();
129977
130189
  } catch (error3) {
129978
130190
  if (error3 instanceof SandboxError && (error3.code === "budgetExceeded" || error3.code === "reentry")) {
129979
130191
  if (isSandboxPromise(capability.promise)) observeSandboxPromise(capability.promise);
@@ -130281,6 +130493,7 @@ var init_promise = __esm({
130281
130493
  init_budget2();
130282
130494
  init_exceptions();
130283
130495
  init_iteration();
130496
+ init_resources();
130284
130497
  init_jobs4();
130285
130498
  init_promise_tracker();
130286
130499
  init_values();
@@ -130498,6 +130711,9 @@ function createSandboxClosure(input) {
130498
130711
  enumerable: false,
130499
130712
  value: true
130500
130713
  });
130714
+ if (input.sourceRange !== void 0) {
130715
+ Object.defineProperty(closure, "sourceRange", { value: input.sourceRange });
130716
+ }
130501
130717
  if (input.sandbox === true) {
130502
130718
  Object.defineProperty(closure, "sandbox", { value: true });
130503
130719
  }
@@ -130695,6 +130911,17 @@ function measureSandboxData(values, options = {}) {
130695
130911
  assertSandboxDataDepth(depth);
130696
130912
  seen.add(value);
130697
130913
  usage += 1;
130914
+ if (isSandboxBox(value)) {
130915
+ const primitive = boxedValue(value);
130916
+ usage += typeof primitive === "string" ? primitive.length : 8;
130917
+ const prototype2 = getSandboxPrototype(value);
130918
+ if (prototype2 !== null) visit(prototype2, depth + 1);
130919
+ for (const [key3, descriptor] of boxedDataProperties(value)) {
130920
+ usage += key3.length + 1;
130921
+ if ("value" in descriptor) visit(descriptor.value, depth + 1);
130922
+ }
130923
+ return;
130924
+ }
130698
130925
  if (isSandboxDate(value)) {
130699
130926
  usage += 8;
130700
130927
  return;
@@ -130756,7 +130983,15 @@ function measureSandboxData(values, options = {}) {
130756
130983
  }
130757
130984
  if (isSandboxClosure(value)) {
130758
130985
  if (options.ignoreClosures) return;
130759
- if (value.properties !== void 0) visit(value.properties, depth + 1);
130986
+ if (value.properties !== void 0) {
130987
+ if (isIntrinsicConstructor(value)) {
130988
+ for (const [key3, descriptor] of Object.entries(Object.getOwnPropertyDescriptors(value.properties))) {
130989
+ if (key3 === "prototype" || key3 === "name" || key3 === "length") continue;
130990
+ usage += key3.length + 1;
130991
+ if ("value" in descriptor) visit(descriptor.value, depth + 1);
130992
+ }
130993
+ } else visit(value.properties, depth + 1);
130994
+ }
130760
130995
  if (!options.ignoreClosureCaptures)
130761
130996
  for (const retained of value[sandboxRetainedValues]?.() ?? []) visit(retained, depth + 1);
130762
130997
  return;
@@ -130888,6 +131123,24 @@ function copyToSandbox(value, state, path193 = "<root>", cloneSandboxCollections
130888
131123
  if (typeof value === "object" && value !== null && hasGuestObjectState(value)) {
130889
131124
  throw new TypeError("Guest prototype links and custom descriptors cannot be copied as data.");
130890
131125
  }
131126
+ const primitive = nativeBoxedValue(value);
131127
+ if (primitive !== void 0) {
131128
+ const original = value;
131129
+ const existing = state.seen.get(original);
131130
+ if (existing !== void 0) return existing;
131131
+ const copy = createSandboxBox(primitive);
131132
+ state.seen.set(original, copy);
131133
+ if (!state.structuredClone) {
131134
+ for (const [key3, descriptor] of boxedDataProperties(original)) {
131135
+ if (!("value" in descriptor)) throw new TypeError("Boxed data cannot contain accessors.");
131136
+ Object.defineProperty(copy, key3, {
131137
+ ...descriptor,
131138
+ value: copyToSandbox(descriptor.value, state, joinPath(path193, key3), cloneSandboxCollections, depth + 1)
131139
+ });
131140
+ }
131141
+ }
131142
+ return copy;
131143
+ }
130891
131144
  if (isSandboxMap(value)) {
130892
131145
  if (!cloneSandboxCollections) return value;
130893
131146
  const existing = state.seen.get(value);
@@ -131060,6 +131313,20 @@ function copyFromSandbox(value, state, path193 = "<root>", options, depth = 0) {
131060
131313
  if (!isSandboxClosure(value) && hasGuestObjectState(value)) {
131061
131314
  throw new TypeError("Guest prototype links and custom descriptors cannot be copied as data.");
131062
131315
  }
131316
+ if (isSandboxBox(value)) {
131317
+ const existing = state.seen.get(value);
131318
+ if (existing !== void 0) return existing;
131319
+ const copy = Object(boxedValue(value));
131320
+ state.seen.set(value, copy);
131321
+ for (const [key3, descriptor] of boxedDataProperties(value)) {
131322
+ if (!("value" in descriptor)) throw new TypeError("Boxed data cannot contain accessors.");
131323
+ Object.defineProperty(copy, key3, {
131324
+ ...descriptor,
131325
+ value: copyFromSandbox(descriptor.value, state, joinPath(path193, key3), options, depth + 1)
131326
+ });
131327
+ }
131328
+ return copy;
131329
+ }
131063
131330
  const regexBrand = Object.getOwnPropertyDescriptor(value, sandboxRegexBrand);
131064
131331
  if (regexBrand !== void 0) {
131065
131332
  if (!("value" in regexBrand) || regexBrand.value !== true) {
@@ -131230,6 +131497,17 @@ function allocateSandboxValue2(value, budget, seen) {
131230
131497
  budget.allocateString(value);
131231
131498
  return;
131232
131499
  }
131500
+ if (isSandboxBox(value)) {
131501
+ if (seen.has(value)) return;
131502
+ seen.add(value);
131503
+ const primitive = boxedValue(value);
131504
+ if (typeof primitive === "string") budget.allocateString(primitive);
131505
+ for (const [key3, descriptor] of boxedDataProperties(value)) {
131506
+ budget.allocateString(key3);
131507
+ if ("value" in descriptor) allocateSandboxValue2(descriptor.value, budget, seen);
131508
+ }
131509
+ return;
131510
+ }
131233
131511
  if (isFloat32Array(value)) {
131234
131512
  if (seen.has(value)) return;
131235
131513
  seen.add(value);
@@ -131376,6 +131654,7 @@ var init_values = __esm({
131376
131654
  init_collection_brands();
131377
131655
  init_collection_iterator();
131378
131656
  init_date();
131657
+ init_boxed();
131379
131658
  init_host_capabilities();
131380
131659
  init_compile_guard();
131381
131660
  init_float32();
@@ -131446,11 +131725,34 @@ function getGuestFunctionProperty(closure, key3) {
131446
131725
  function installObjectPrototype(budget, prototype, constructor) {
131447
131726
  prototypes.set(prototype, null);
131448
131727
  intrinsicPrototypes.set(budget, prototype);
131728
+ registerIntrinsicPrototype(budget, prototype, constructor);
131729
+ }
131730
+ function installBoxedPrototype(budget, prototype, constructor) {
131731
+ let state = boxedPrototypes.get(budget);
131732
+ if (state === void 0) boxedPrototypes.set(budget, state = /* @__PURE__ */ new Map());
131733
+ state.set(typeof boxedValue(prototype), prototype);
131734
+ initialBoxedMethods.set(prototype, new Map(Object.entries(Object.getOwnPropertyDescriptors(prototype)).map(([key3, descriptor]) => [key3, descriptor.value])));
131735
+ registerIntrinsicPrototype(budget, prototype, constructor);
131736
+ }
131737
+ function getBoxedPrototype(value, budget) {
131738
+ return boxedPrototypes.get(budget)?.get(typeof value);
131739
+ }
131740
+ function isDefaultBoxedMethod(value, key3, budget) {
131741
+ const prototype = getBoxedPrototype(value, budget);
131742
+ return prototype !== void 0 && initialBoxedMethods.get(prototype)?.has(key3) === true && Object.getOwnPropertyDescriptor(prototype, key3)?.value === initialBoxedMethods.get(prototype)?.get(key3);
131743
+ }
131744
+ function isIntrinsicConstructor(value) {
131745
+ return intrinsicConstructors.has(value);
131746
+ }
131747
+ function registerIntrinsicPrototype(budget, prototype, constructor) {
131748
+ let roots = intrinsicPrototypeRoots.get(budget);
131749
+ if (roots === void 0) intrinsicPrototypeRoots.set(budget, roots = /* @__PURE__ */ new Set());
131750
+ roots.add(prototype);
131449
131751
  const records = [prototype, materializeFunctionProperties(constructor)].map((value) => ({
131450
131752
  value,
131451
131753
  descriptors: new Map(Object.entries(Object.getOwnPropertyDescriptors(value)))
131452
131754
  }));
131453
- const unchanged = (before, after) => before !== void 0 && after !== void 0 && before.value === after.value && before.writable === after.writable && before.configurable === after.configurable && before.enumerable === after.enumerable;
131755
+ const unchanged = (before, after) => before !== void 0 && after !== void 0 && Object.is(before.value, after.value) && before.writable === after.writable && before.configurable === after.configurable && before.enumerable === after.enumerable;
131454
131756
  intrinsicConstructors.set(constructor, () => records.every(({ value, descriptors }) => {
131455
131757
  const current = Object.getOwnPropertyDescriptors(value);
131456
131758
  return Object.keys(current).length === descriptors.size && Object.keys(current).every((key3) => unchanged(descriptors.get(key3), current[key3]));
@@ -131458,12 +131760,17 @@ function installObjectPrototype(budget, prototype, constructor) {
131458
131760
  budget.setRetainedValues(prototype, () => records.flatMap(({ value, descriptors }) => Object.entries(Object.getOwnPropertyDescriptors(value)).flatMap(([key3, descriptor]) => unchanged(descriptors.get(key3), descriptor) ? [] : [key3, descriptor.value])));
131459
131761
  }
131460
131762
  function releaseObjectPrototype(budget) {
131461
- const prototype = intrinsicPrototypes.get(budget);
131462
- if (prototype !== void 0) budget.setRetainedValues(prototype, void 0);
131763
+ for (const prototype of intrinsicPrototypeRoots.get(budget) ?? []) budget.setRetainedValues(prototype, void 0);
131764
+ intrinsicPrototypeRoots.delete(budget);
131765
+ boxedPrototypes.delete(budget);
131463
131766
  intrinsicPrototypes.delete(budget);
131464
131767
  }
131465
131768
  function getSandboxPrototype(value, budget) {
131466
131769
  if (prototypes.has(value)) return prototypes.get(value) ?? null;
131770
+ if (budget !== void 0 && isSandboxBox(value)) {
131771
+ const prototype = getBoxedPrototype(boxedValue(value), budget);
131772
+ if (prototype !== void 0 && prototype !== value) return prototype;
131773
+ }
131467
131774
  return budget !== void 0 && isPrototypeRecord(value) ? intrinsicPrototypes.get(budget) ?? null : null;
131468
131775
  }
131469
131776
  function hasExplicitSandboxPrototype(value) {
@@ -131529,22 +131836,27 @@ function hasGuestObjectState(value) {
131529
131836
  if (intrinsicUnchanged !== void 0) return !intrinsicUnchanged();
131530
131837
  if (isLiveCapability(value)) return true;
131531
131838
  if (functionProperties.has(value) || prototypes.has(value)) return true;
131839
+ if (isSandboxBox(value)) return false;
131532
131840
  return descriptorObjects.has(value) && Object.values(Object.getOwnPropertyDescriptors(value)).some(
131533
131841
  (descriptor) => !descriptor.enumerable || !descriptor.configurable || !descriptor.writable
131534
131842
  );
131535
131843
  }
131536
- var guestClosures, functionProperties, prototypes, intrinsicPrototypes, intrinsicConstructors, descriptorObjects;
131844
+ var guestClosures, functionProperties, prototypes, intrinsicPrototypes, boxedPrototypes, intrinsicPrototypeRoots, intrinsicConstructors, initialBoxedMethods, descriptorObjects;
131537
131845
  var init_object_model = __esm({
131538
131846
  "packages/safe-js/src/interp/object-model.ts"() {
131539
131847
  "use strict";
131540
131848
  init_graph_depth();
131541
131849
  init_host_capabilities();
131850
+ init_boxed();
131542
131851
  init_values();
131543
131852
  guestClosures = /* @__PURE__ */ new WeakSet();
131544
131853
  functionProperties = /* @__PURE__ */ new WeakMap();
131545
131854
  prototypes = /* @__PURE__ */ new WeakMap();
131546
131855
  intrinsicPrototypes = /* @__PURE__ */ new WeakMap();
131856
+ boxedPrototypes = /* @__PURE__ */ new WeakMap();
131857
+ intrinsicPrototypeRoots = /* @__PURE__ */ new WeakMap();
131547
131858
  intrinsicConstructors = /* @__PURE__ */ new WeakMap();
131859
+ initialBoxedMethods = /* @__PURE__ */ new WeakMap();
131548
131860
  descriptorObjects = /* @__PURE__ */ new WeakSet();
131549
131861
  }
131550
131862
  });
@@ -131641,7 +131953,7 @@ function serializeDumpValue(value, path193, state) {
131641
131953
  if (hasGuestObjectState(value)) {
131642
131954
  throw new TypeError("Guest function properties and prototype links cannot be serialized.");
131643
131955
  }
131644
- if (isSandboxDate(value) || isFloat32Array(value)) return serializeHeapReference(value, path193, state);
131956
+ if (isSandboxBox(value) || isSandboxDate(value) || isFloat32Array(value)) return serializeHeapReference(value, path193, state);
131645
131957
  if (Array.isArray(value)) {
131646
131958
  const reference2 = serializeHeapReference(value, path193, state);
131647
131959
  if (reference2 !== void 0) {
@@ -131665,7 +131977,13 @@ function serializeHeapReference(value, path193, state) {
131665
131977
  }
131666
131978
  if (!state.serializedHeapIds.has(id)) {
131667
131979
  state.serializedHeapIds.add(id);
131668
- if (isSandboxDate(value)) {
131980
+ if (isSandboxBox(value)) {
131981
+ state.heap[String(id)] = encodeBoxedData(value, (entry, key3) => {
131982
+ if (Object.is(entry, -0)) return { kind: "number", value: "-0" };
131983
+ const serialized = serializeDumpValue(entry, `${path193}.${key3}`, state);
131984
+ return serialized === SKIP_VALUE ? { kind: "undefined" } : serialized;
131985
+ });
131986
+ } else if (isSandboxDate(value)) {
131669
131987
  state.heap[String(id)] = { kind: "date", time: serializedDateTime(value) };
131670
131988
  } else if (isFloat32Array(value)) {
131671
131989
  const storage2 = encodeFloat32Storage(value, id, state.float32Buffers, (id2) => ({
@@ -131724,7 +132042,7 @@ function indexHeapContainers(snapshot2) {
131724
132042
  const heapIds = /* @__PURE__ */ new WeakMap();
131725
132043
  let nextId = 1;
131726
132044
  for (const [value, stat35] of stats2.entries()) {
131727
- if (stat35.count > 1 || stat35.cyclic || isSandboxDate(value) || isFloat32Array(value) || Array.isArray(value) && requiresArrayEntries(value) || isSandboxArguments(value) || sandboxErrorTypes.has(value)) {
132045
+ if (stat35.count > 1 || stat35.cyclic || isSandboxBox(value) || isSandboxDate(value) || isFloat32Array(value) || Array.isArray(value) && requiresArrayEntries(value) || isSandboxArguments(value) || sandboxErrorTypes.has(value)) {
131728
132046
  heapIds.set(value, nextId);
131729
132047
  nextId += 1;
131730
132048
  }
@@ -131757,7 +132075,7 @@ function collectContainerStats(value, stats2, ancestors) {
131757
132075
  }
131758
132076
  stat35.expanded = true;
131759
132077
  ancestors.add(value);
131760
- const entries = isSandboxArguments(value) ? getSandboxArgumentEntries(value).map(([, entry]) => entry) : getEnumerableDataValues(value);
132078
+ const entries = isSandboxBox(value) ? boxedDataProperties(value).map(([, descriptor]) => descriptor.value) : isSandboxArguments(value) ? getSandboxArgumentEntries(value).map(([, entry]) => entry) : getEnumerableDataValues(value);
131761
132079
  for (const entry of entries) {
131762
132080
  collectContainerStats(entry, stats2, ancestors);
131763
132081
  }
@@ -131807,14 +132125,16 @@ var init_dump_format = __esm({
131807
132125
  init_float32();
131808
132126
  init_float32array();
131809
132127
  init_date();
132128
+ init_boxed();
132129
+ init_boxed2();
131810
132130
  DUMP_FORMAT_VERSION = 1;
131811
- EXECUTION_SEMANTICS = "jobs-v7";
132131
+ EXECUTION_SEMANTICS = "jobs-v8";
131812
132132
  SKIP_VALUE = /* @__PURE__ */ Symbol("SafeJS.skip-dump-value");
131813
132133
  }
131814
132134
  });
131815
132135
 
131816
132136
  // packages/safe-js/src/snapshot/validation.ts
131817
- import { types as types4 } from "node:util";
132137
+ import { types as types5 } from "node:util";
131818
132138
  function validateSnapshotData(value) {
131819
132139
  validateGenericValue(value, "$", 0, {
131820
132140
  allowFunctions: false,
@@ -131860,6 +132180,10 @@ function validateDumpHeap(root, state) {
131860
132180
  addUnique2(heapIds, id, path193);
131861
132181
  const entry = requireRecord3(value, path193);
131862
132182
  validateErrorType(entry, path193);
132183
+ if (entry.kind === "boxed") {
132184
+ validateBoxedRecord(entry, path193);
132185
+ continue;
132186
+ }
131863
132187
  if (entry.kind === "date") {
131864
132188
  validateDateRecord(entry, path193);
131865
132189
  continue;
@@ -132027,6 +132351,18 @@ function validateGeneratorShape(record2, path193, state) {
132027
132351
  }
132028
132352
  });
132029
132353
  }
132354
+ function validateBoxedRecord(record2, path193) {
132355
+ try {
132356
+ validateBoxedProperties(record2);
132357
+ } catch {
132358
+ fail2("invalidValue", path193, "invalid boxed primitive properties");
132359
+ }
132360
+ const value = record2.value;
132361
+ if (typeof value === "number" || typeof value === "string" || typeof value === "boolean") return;
132362
+ const number = requireRecord3(value, `${path193}.value`);
132363
+ if (number.kind !== "number" || !["NaN", "Infinity", "-Infinity", "-0"].includes(String(number.value)))
132364
+ fail2("invalidValue", `${path193}.value`, "invalid boxed primitive payload");
132365
+ }
132030
132366
  function validateDateRecord(record2, path193) {
132031
132367
  if (Object.keys(record2).length !== 2) fail2("invalidValue", path193, "invalid Date fields");
132032
132368
  try {
@@ -132118,7 +132454,7 @@ function validateGenericValue(value, path193, depth, state) {
132118
132454
  if (typeof value === "object" && value !== null && hasGuestObjectState(value)) {
132119
132455
  fail2("invalidState", path193, "guest function properties, prototype links and custom descriptors cannot be restored");
132120
132456
  }
132121
- if (state.dataPropertiesOnly && types4.isProxy(value)) {
132457
+ if (state.dataPropertiesOnly && types5.isProxy(value)) {
132122
132458
  fail2("invalidType", path193, "proxy objects are not snapshot data");
132123
132459
  }
132124
132460
  if (depth > state.limits.maxDepth)
@@ -132253,6 +132589,7 @@ var init_validation = __esm({
132253
132589
  init_graph_depth();
132254
132590
  init_float32array();
132255
132591
  init_date();
132592
+ init_boxed2();
132256
132593
  init_object_model();
132257
132594
  DEFAULT_MAX_DEPTH = MAX_DATA_DEPTH;
132258
132595
  DEFAULT_MAX_ENTRIES = 1e5;
@@ -132289,11 +132626,11 @@ var init_validation = __esm({
132289
132626
 
132290
132627
  // packages/safe-js/src/snapshot/migration.ts
132291
132628
  function validateMigrationSemantics(value) {
132292
- if (!["jobs-v1", "jobs-v2", "jobs-v3", "jobs-v4", "jobs-v5", "jobs-v6", "jobs-v7"].includes(
132629
+ if (!["jobs-v1", "jobs-v2", "jobs-v3", "jobs-v4", "jobs-v5", "jobs-v6", "jobs-v7", "jobs-v8"].includes(
132293
132630
  value
132294
132631
  ))
132295
132632
  throw new TypeError(
132296
- "Migration requires a supported execution-semantics marker (jobs-v1 through jobs-v7)."
132633
+ "Migration requires a supported execution-semantics marker (jobs-v1 through jobs-v8)."
132297
132634
  );
132298
132635
  }
132299
132636
  function validateMigrationJournal(sourceHash, replay, hostCalls = [], owner) {
@@ -132398,14 +132735,18 @@ function restore2(snapshot2, options, owner) {
132398
132735
  assertSnapshotInactive(snapshot2);
132399
132736
  validateDumpEnvelope(snapshot2);
132400
132737
  validateSnapshotMigration(snapshot2.migration, snapshot2.sourceHash, owner);
132401
- if (snapshot2.executionSemantics !== EXECUTION_SEMANTICS && snapshot2.executionSemantics !== "jobs-v6" && (snapshot2.executionSemantics !== void 0 || snapshot2.promiseReplay !== void 0 || snapshot2.replay !== void 0 || snapshot2.initialInputs !== void 0)) {
132738
+ if (snapshot2.executionSemantics !== EXECUTION_SEMANTICS && snapshot2.executionSemantics !== "jobs-v6" && snapshot2.executionSemantics !== "jobs-v7" && (snapshot2.executionSemantics !== void 0 || snapshot2.promiseReplay !== void 0 || snapshot2.replay !== void 0 || snapshot2.initialInputs !== void 0)) {
132402
132739
  throw new SnapshotValidationError(
132403
132740
  "unsupportedVersion",
132404
132741
  "$.executionSemantics",
132405
132742
  "incompatible execution semantics; resume with the SafeJS version that created this snapshot. Migration requires explicit reconciliation, not changing its version marker."
132406
132743
  );
132407
132744
  }
132408
- const currentSourceHash = hashSource(options.source, owner);
132745
+ const currentSourceHash = hashSource(
132746
+ options.source,
132747
+ owner,
132748
+ snapshot2.executionSemantics !== "jobs-v6" && snapshot2.executionSemantics !== "jobs-v7"
132749
+ );
132409
132750
  if (snapshot2.sourceHash !== currentSourceHash) {
132410
132751
  throw new SnapshotMismatchError(snapshot2.sourceHash, currentSourceHash);
132411
132752
  }
@@ -144190,7 +144531,10 @@ function isArrayMethodName(property) {
144190
144531
  }
144191
144532
  async function callArrayMethod(receiver, methodName, args, options, stack = []) {
144192
144533
  if (receiver === null || receiver === void 0) throw new TypeError("Array method requires a receiver.");
144193
- if (typeof receiver !== "object") throw new TypeError("Object primitive boxing is not supported.");
144534
+ if (typeof receiver !== "object") {
144535
+ receiver = createSandboxBox(receiver);
144536
+ options.budget.chargeDataUsage(measureSandboxData([receiver]));
144537
+ }
144194
144538
  const retainedReceiver = {};
144195
144539
  options.budget.setRetainedValues(retainedReceiver, () => [receiver]);
144196
144540
  try {
@@ -144900,6 +145244,7 @@ var arrayLikeSources, activeArrayCallbacks, arrayMethodNames;
144900
145244
  var init_array = __esm({
144901
145245
  "packages/safe-js/src/interp/methods/array.ts"() {
144902
145246
  "use strict";
145247
+ init_boxed();
144903
145248
  init_values();
144904
145249
  init_running_state();
144905
145250
  init_object_model();
@@ -144958,12 +145303,14 @@ function getFunctionMember(target, property, options) {
144958
145303
  if (property === "length") {
144959
145304
  return target.length;
144960
145305
  }
145306
+ if (property === "toString" && runResources.getStore()?.functionSourceText === false) return void 0;
144961
145307
  if (!isFunctionMethodName(property)) {
144962
145308
  return void 0;
144963
145309
  }
144964
145310
  return createSandboxClosure({
144965
145311
  sandbox: true,
144966
145312
  name: `Function#${property}`,
145313
+ ...property === "toString" ? { length: 0 } : {},
144967
145314
  call: (args, context) => callFunctionMethod(context?.thisValue, property, args, options, context?.stack ?? [])
144968
145315
  });
144969
145316
  }
@@ -144974,6 +145321,10 @@ function callFunctionMethod(target, methodName, args, options, stack) {
144974
145321
  if (!isSandboxClosure(target)) {
144975
145322
  throw new TypeError(`Function#${methodName} requires a callable receiver.`);
144976
145323
  }
145324
+ if (methodName === "toString") {
145325
+ const text5 = functionString(target);
145326
+ return options.budget?.allocateString(text5) ?? text5;
145327
+ }
144977
145328
  const thisValue = args[0];
144978
145329
  if (methodName === "bind") {
144979
145330
  const boundArgs = args.slice(1);
@@ -145014,255 +145365,9 @@ var init_function = __esm({
145014
145365
  "use strict";
145015
145366
  init_values();
145016
145367
  init_object_model();
145017
- functionMethodNames = /* @__PURE__ */ new Set(["apply", "bind", "call"]);
145018
- }
145019
- });
145020
-
145021
- // packages/safe-js/src/interp/methods/collection-callback.ts
145022
- function enterKeyedCollectionCallback(target, keys, budget) {
145023
- let state = activeCallbacks.get(target);
145024
- if (state === void 0) {
145025
- state = { cursors: /* @__PURE__ */ new Set(), leaveRunning: enterRunningState(target) };
145026
- activeCallbacks.set(target, state);
145027
- }
145028
- const cursor2 = { budget, pending: /* @__PURE__ */ new Set() };
145029
- state.cursors.add(cursor2);
145030
- const leave = () => {
145031
- if (!state.cursors.delete(cursor2)) return;
145032
- cursor2.pending.clear();
145033
- budget.setRetainedDataUsage(cursor2, 0);
145034
- budget.setRetainedValues(cursor2, void 0);
145035
- if (state.cursors.size === 0) {
145036
- activeCallbacks.delete(target);
145037
- state.leaveRunning();
145038
- }
145039
- };
145040
- try {
145041
- budget.setRetainedDataUsage(cursor2, 1);
145042
- budget.setRetainedValues(cursor2, () => cursor2.pending);
145043
- for (const key3 of keys) updatePendingKeys(cursor2, "add", key3);
145044
- } catch (error3) {
145045
- leave();
145046
- throw error3;
145047
- }
145048
- return {
145049
- next: () => {
145050
- budget.visitNode();
145051
- for (const key3 of cursor2.pending) {
145052
- cursor2.pending.delete(key3);
145053
- budget.setRetainedDataUsage(cursor2, 1 + cursor2.pending.size);
145054
- return { done: false, value: key3 };
145055
- }
145056
- return { done: true, value: void 0 };
145057
- },
145058
- leave
145059
- };
145060
- }
145061
- function updateKeyedCollectionCallbacks(target, mutation, key3) {
145062
- const state = activeCallbacks.get(target);
145063
- if (state === void 0) return;
145064
- for (const cursor2 of state.cursors) updatePendingKeys(cursor2, mutation, key3);
145065
- }
145066
- function updatePendingKeys(cursor2, mutation, key3) {
145067
- const { budget, pending } = cursor2;
145068
- budget.visitNode();
145069
- if (mutation === "add") {
145070
- const nextSize = pending.has(key3) ? pending.size : pending.size + 1;
145071
- budget.allocateCollectionEntries(nextSize);
145072
- budget.setRetainedDataUsage(cursor2, 1 + nextSize);
145073
- pending.add(key3);
145074
- } else {
145075
- if (mutation === "delete") pending.delete(key3);
145076
- else pending.clear();
145077
- budget.setRetainedDataUsage(cursor2, 1 + pending.size);
145078
- }
145079
- }
145080
- var activeCallbacks;
145081
- var init_collection_callback = __esm({
145082
- "packages/safe-js/src/interp/methods/collection-callback.ts"() {
145083
- "use strict";
145084
- init_running_state();
145085
- activeCallbacks = /* @__PURE__ */ new WeakMap();
145086
- }
145087
- });
145088
-
145089
- // packages/safe-js/src/interp/methods/map.ts
145090
- function isMapMethodName(value) {
145091
- return typeof value === "string" && mapMethodNames.has(value);
145092
- }
145093
- function getMapMember(target, property, options) {
145094
- if (property === "size") {
145095
- return target.entries.size;
145096
- }
145097
- if (!isMapMethodName(property)) {
145098
- return void 0;
145099
- }
145100
- return createSandboxClosure({
145101
- sandbox: true,
145102
- call: (args, context) => {
145103
- const receiver = context?.thisValue;
145104
- if (!isSandboxMap(receiver)) throw new TypeError(`Map#${property} requires a Map receiver.`);
145105
- return callMapMethod(receiver, property, args, options, context?.stack ?? []);
145106
- },
145107
- name: property
145108
- });
145109
- }
145110
- async function callMapMethod(target, methodName, args, options, stack = []) {
145111
- switch (methodName) {
145112
- case "get":
145113
- return target.entries.get(args[0]);
145114
- case "set": {
145115
- assertCollectionMutable(target);
145116
- const exists4 = target.entries.has(args[0]);
145117
- const nextSize = exists4 ? target.entries.size : target.entries.size + 1;
145118
- options.budget.allocateCollectionEntries(nextSize);
145119
- if (!exists4) updateKeyedCollectionCallbacks(target, "add", args[0]);
145120
- target.entries.set(args[0], args[1]);
145121
- return target;
145122
- }
145123
- case "has":
145124
- return target.entries.has(args[0]);
145125
- case "delete": {
145126
- assertCollectionMutable(target);
145127
- const deleted = target.entries.delete(args[0]);
145128
- if (deleted) updateKeyedCollectionCallbacks(target, "delete", args[0]);
145129
- return deleted;
145130
- }
145131
- case "clear":
145132
- assertCollectionMutable(target);
145133
- target.entries.clear();
145134
- updateKeyedCollectionCallbacks(target, "clear");
145135
- return void 0;
145136
- case "forEach": {
145137
- const callback = args[0];
145138
- if (!isSandboxClosure(callback)) {
145139
- throw new TypeError("Map.prototype.forEach requires a callback function.");
145140
- }
145141
- const cursor2 = enterKeyedCollectionCallback(target, target.entries.keys(), options.budget);
145142
- try {
145143
- for (let entry = cursor2.next(); !entry.done; entry = cursor2.next()) {
145144
- const key3 = entry.value;
145145
- const value = target.entries.get(key3);
145146
- await options.callClosure(callback, [value, key3, target], stack, args[1]);
145147
- }
145148
- } finally {
145149
- cursor2.leave();
145150
- }
145151
- return void 0;
145152
- }
145153
- case "keys":
145154
- case "values":
145155
- case "entries":
145156
- return createSandboxCollectionIterator(target, methodName);
145157
- }
145158
- }
145159
- var mapMethodNames;
145160
- var init_map = __esm({
145161
- "packages/safe-js/src/interp/methods/map.ts"() {
145162
- "use strict";
145163
- init_values();
145164
- init_running_state();
145165
- init_collection_callback();
145166
- init_collection_iterator();
145167
- mapMethodNames = /* @__PURE__ */ new Set([
145168
- "get",
145169
- "set",
145170
- "has",
145171
- "delete",
145172
- "clear",
145173
- "forEach",
145174
- "keys",
145175
- "values",
145176
- "entries"
145177
- ]);
145178
- }
145179
- });
145180
-
145181
- // packages/safe-js/src/interp/methods/number.ts
145182
- function getNumberMember(property, budget) {
145183
- if (!isNumberMethodName(property)) {
145184
- return void 0;
145185
- }
145186
- return createSandboxClosure({
145187
- sandbox: true,
145188
- name: `Number#${property}`,
145189
- call: (args, context) => callNumberMethod(context?.thisValue, property, args, budget, context)
145190
- });
145191
- }
145192
- function isNumberMethodName(property) {
145193
- return typeof property === "string" && numberMethodNames.has(property);
145194
- }
145195
- function callNumberMethod(value, methodName, args, budget, context) {
145196
- if (typeof value !== "number") {
145197
- throw new TypeError(`Number#${methodName} requires a number receiver.`);
145198
- }
145199
- const argument = args[0];
145200
- if (argument !== null && typeof argument === "object") {
145201
- return formatObjectArgument(value, methodName, argument, budget, context);
145202
- }
145203
- return formatNumber3(value, methodName, argument === void 0 ? void 0 : Number(argument), budget);
145204
- }
145205
- async function formatObjectArgument(value, methodName, argument, budget, context) {
145206
- const retainedArgument = {};
145207
- budget.setRetainedValues(retainedArgument, () => [argument]);
145208
- try {
145209
- const number = await sandboxNumber(argument, budget, context);
145210
- return formatNumber3(value, methodName, number, budget);
145211
- } finally {
145212
- budget.setRetainedValues(retainedArgument, void 0);
145213
- }
145214
- }
145215
- function formatNumber3(value, methodName, argument, budget) {
145216
- let result;
145217
- try {
145218
- result = value[methodName](argument);
145219
- } catch (error3) {
145220
- if (!(error3 instanceof RangeError)) throw error3;
145221
- const detail = methodName === "toString" ? "radix must be between 2 and 36." : methodName === "toPrecision" ? "precision must be between 1 and 100." : "digits must be between 0 and 100.";
145222
- throw new RangeError(`Number#${methodName} ${detail}`);
145223
- }
145224
- return budget.allocateString(result);
145225
- }
145226
- var numberMethodNames;
145227
- var init_number = __esm({
145228
- "packages/safe-js/src/interp/methods/number.ts"() {
145229
- "use strict";
145230
- init_string_coercion();
145231
- init_values();
145232
- numberMethodNames = /* @__PURE__ */ new Set([
145233
- "toExponential",
145234
- "toFixed",
145235
- "toPrecision",
145236
- "toString"
145237
- ]);
145238
- }
145239
- });
145240
-
145241
- // packages/safe-js/src/interp/methods/generator.ts
145242
- function getGeneratorMember(target, property, budget) {
145243
- if (typeof property !== "string" || !generatorMethodNames.has(property)) {
145244
- return void 0;
145245
- }
145246
- return createSandboxClosure({
145247
- sandbox: true,
145248
- name: property,
145249
- call: async ([value]) => {
145250
- const iterator = getSandboxIterator(target);
145251
- const result = await iterator[property](value);
145252
- return allocateProducedSandboxValue(
145253
- { value: result.value, done: result.done === true },
145254
- budget
145255
- );
145256
- }
145257
- });
145258
- }
145259
- var generatorMethodNames;
145260
- var init_generator2 = __esm({
145261
- "packages/safe-js/src/interp/methods/generator.ts"() {
145262
- "use strict";
145263
- init_iteration();
145264
- init_values();
145265
- generatorMethodNames = /* @__PURE__ */ new Set(["next", "return", "throw"]);
145368
+ init_function_string();
145369
+ init_resources();
145370
+ functionMethodNames = /* @__PURE__ */ new Set(["apply", "bind", "call", "toString"]);
145266
145371
  }
145267
145372
  });
145268
145373
 
@@ -145784,6 +145889,256 @@ var init_string = __esm({
145784
145889
  }
145785
145890
  });
145786
145891
 
145892
+ // packages/safe-js/src/interp/methods/collection-callback.ts
145893
+ function enterKeyedCollectionCallback(target, keys, budget) {
145894
+ let state = activeCallbacks.get(target);
145895
+ if (state === void 0) {
145896
+ state = { cursors: /* @__PURE__ */ new Set(), leaveRunning: enterRunningState(target) };
145897
+ activeCallbacks.set(target, state);
145898
+ }
145899
+ const cursor2 = { budget, pending: /* @__PURE__ */ new Set() };
145900
+ state.cursors.add(cursor2);
145901
+ const leave = () => {
145902
+ if (!state.cursors.delete(cursor2)) return;
145903
+ cursor2.pending.clear();
145904
+ budget.setRetainedDataUsage(cursor2, 0);
145905
+ budget.setRetainedValues(cursor2, void 0);
145906
+ if (state.cursors.size === 0) {
145907
+ activeCallbacks.delete(target);
145908
+ state.leaveRunning();
145909
+ }
145910
+ };
145911
+ try {
145912
+ budget.setRetainedDataUsage(cursor2, 1);
145913
+ budget.setRetainedValues(cursor2, () => cursor2.pending);
145914
+ for (const key3 of keys) updatePendingKeys(cursor2, "add", key3);
145915
+ } catch (error3) {
145916
+ leave();
145917
+ throw error3;
145918
+ }
145919
+ return {
145920
+ next: () => {
145921
+ budget.visitNode();
145922
+ for (const key3 of cursor2.pending) {
145923
+ cursor2.pending.delete(key3);
145924
+ budget.setRetainedDataUsage(cursor2, 1 + cursor2.pending.size);
145925
+ return { done: false, value: key3 };
145926
+ }
145927
+ return { done: true, value: void 0 };
145928
+ },
145929
+ leave
145930
+ };
145931
+ }
145932
+ function updateKeyedCollectionCallbacks(target, mutation, key3) {
145933
+ const state = activeCallbacks.get(target);
145934
+ if (state === void 0) return;
145935
+ for (const cursor2 of state.cursors) updatePendingKeys(cursor2, mutation, key3);
145936
+ }
145937
+ function updatePendingKeys(cursor2, mutation, key3) {
145938
+ const { budget, pending } = cursor2;
145939
+ budget.visitNode();
145940
+ if (mutation === "add") {
145941
+ const nextSize = pending.has(key3) ? pending.size : pending.size + 1;
145942
+ budget.allocateCollectionEntries(nextSize);
145943
+ budget.setRetainedDataUsage(cursor2, 1 + nextSize);
145944
+ pending.add(key3);
145945
+ } else {
145946
+ if (mutation === "delete") pending.delete(key3);
145947
+ else pending.clear();
145948
+ budget.setRetainedDataUsage(cursor2, 1 + pending.size);
145949
+ }
145950
+ }
145951
+ var activeCallbacks;
145952
+ var init_collection_callback = __esm({
145953
+ "packages/safe-js/src/interp/methods/collection-callback.ts"() {
145954
+ "use strict";
145955
+ init_running_state();
145956
+ activeCallbacks = /* @__PURE__ */ new WeakMap();
145957
+ }
145958
+ });
145959
+
145960
+ // packages/safe-js/src/interp/methods/map.ts
145961
+ function isMapMethodName(value) {
145962
+ return typeof value === "string" && mapMethodNames.has(value);
145963
+ }
145964
+ function getMapMember(target, property, options) {
145965
+ if (property === "size") {
145966
+ return target.entries.size;
145967
+ }
145968
+ if (!isMapMethodName(property)) {
145969
+ return void 0;
145970
+ }
145971
+ return createSandboxClosure({
145972
+ sandbox: true,
145973
+ call: (args, context) => {
145974
+ const receiver = context?.thisValue;
145975
+ if (!isSandboxMap(receiver)) throw new TypeError(`Map#${property} requires a Map receiver.`);
145976
+ return callMapMethod(receiver, property, args, options, context?.stack ?? []);
145977
+ },
145978
+ name: property
145979
+ });
145980
+ }
145981
+ async function callMapMethod(target, methodName, args, options, stack = []) {
145982
+ switch (methodName) {
145983
+ case "get":
145984
+ return target.entries.get(args[0]);
145985
+ case "set": {
145986
+ assertCollectionMutable(target);
145987
+ const exists4 = target.entries.has(args[0]);
145988
+ const nextSize = exists4 ? target.entries.size : target.entries.size + 1;
145989
+ options.budget.allocateCollectionEntries(nextSize);
145990
+ if (!exists4) updateKeyedCollectionCallbacks(target, "add", args[0]);
145991
+ target.entries.set(args[0], args[1]);
145992
+ return target;
145993
+ }
145994
+ case "has":
145995
+ return target.entries.has(args[0]);
145996
+ case "delete": {
145997
+ assertCollectionMutable(target);
145998
+ const deleted = target.entries.delete(args[0]);
145999
+ if (deleted) updateKeyedCollectionCallbacks(target, "delete", args[0]);
146000
+ return deleted;
146001
+ }
146002
+ case "clear":
146003
+ assertCollectionMutable(target);
146004
+ target.entries.clear();
146005
+ updateKeyedCollectionCallbacks(target, "clear");
146006
+ return void 0;
146007
+ case "forEach": {
146008
+ const callback = args[0];
146009
+ if (!isSandboxClosure(callback)) {
146010
+ throw new TypeError("Map.prototype.forEach requires a callback function.");
146011
+ }
146012
+ const cursor2 = enterKeyedCollectionCallback(target, target.entries.keys(), options.budget);
146013
+ try {
146014
+ for (let entry = cursor2.next(); !entry.done; entry = cursor2.next()) {
146015
+ const key3 = entry.value;
146016
+ const value = target.entries.get(key3);
146017
+ await options.callClosure(callback, [value, key3, target], stack, args[1]);
146018
+ }
146019
+ } finally {
146020
+ cursor2.leave();
146021
+ }
146022
+ return void 0;
146023
+ }
146024
+ case "keys":
146025
+ case "values":
146026
+ case "entries":
146027
+ return createSandboxCollectionIterator(target, methodName);
146028
+ }
146029
+ }
146030
+ var mapMethodNames;
146031
+ var init_map = __esm({
146032
+ "packages/safe-js/src/interp/methods/map.ts"() {
146033
+ "use strict";
146034
+ init_values();
146035
+ init_running_state();
146036
+ init_collection_callback();
146037
+ init_collection_iterator();
146038
+ mapMethodNames = /* @__PURE__ */ new Set([
146039
+ "get",
146040
+ "set",
146041
+ "has",
146042
+ "delete",
146043
+ "clear",
146044
+ "forEach",
146045
+ "keys",
146046
+ "values",
146047
+ "entries"
146048
+ ]);
146049
+ }
146050
+ });
146051
+
146052
+ // packages/safe-js/src/interp/methods/number.ts
146053
+ function getNumberMember(property, budget) {
146054
+ if (!isNumberMethodName(property)) {
146055
+ return void 0;
146056
+ }
146057
+ return createSandboxClosure({
146058
+ sandbox: true,
146059
+ name: `Number#${property}`,
146060
+ call: (args, context) => callNumberMethod(context?.thisValue, property, args, budget, context)
146061
+ });
146062
+ }
146063
+ function isNumberMethodName(property) {
146064
+ return typeof property === "string" && numberMethodNames.has(property);
146065
+ }
146066
+ function callNumberMethod(value, methodName, args, budget, context) {
146067
+ if (isSandboxBox(value)) value = boxedValue(value);
146068
+ if (typeof value !== "number") {
146069
+ throw new TypeError(`Number#${methodName} requires a number receiver.`);
146070
+ }
146071
+ const argument = args[0];
146072
+ if (argument !== null && typeof argument === "object") {
146073
+ return formatObjectArgument(value, methodName, argument, budget, context);
146074
+ }
146075
+ return formatNumber3(value, methodName, argument === void 0 ? void 0 : Number(argument), budget);
146076
+ }
146077
+ async function formatObjectArgument(value, methodName, argument, budget, context) {
146078
+ const retainedArgument = {};
146079
+ budget.setRetainedValues(retainedArgument, () => [argument]);
146080
+ try {
146081
+ const number = await sandboxNumber(argument, budget, context);
146082
+ return formatNumber3(value, methodName, number, budget);
146083
+ } finally {
146084
+ budget.setRetainedValues(retainedArgument, void 0);
146085
+ }
146086
+ }
146087
+ function formatNumber3(value, methodName, argument, budget) {
146088
+ let result;
146089
+ try {
146090
+ result = value[methodName](argument);
146091
+ } catch (error3) {
146092
+ if (!(error3 instanceof RangeError)) throw error3;
146093
+ const detail = methodName === "toString" ? "radix must be between 2 and 36." : methodName === "toPrecision" ? "precision must be between 1 and 100." : "digits must be between 0 and 100.";
146094
+ throw new RangeError(`Number#${methodName} ${detail}`);
146095
+ }
146096
+ return budget.allocateString(result);
146097
+ }
146098
+ var numberMethodNames;
146099
+ var init_number = __esm({
146100
+ "packages/safe-js/src/interp/methods/number.ts"() {
146101
+ "use strict";
146102
+ init_string_coercion();
146103
+ init_boxed();
146104
+ init_values();
146105
+ numberMethodNames = /* @__PURE__ */ new Set([
146106
+ "toExponential",
146107
+ "toFixed",
146108
+ "toPrecision",
146109
+ "toString"
146110
+ ]);
146111
+ }
146112
+ });
146113
+
146114
+ // packages/safe-js/src/interp/methods/generator.ts
146115
+ function getGeneratorMember(target, property, budget) {
146116
+ if (typeof property !== "string" || !generatorMethodNames.has(property)) {
146117
+ return void 0;
146118
+ }
146119
+ return createSandboxClosure({
146120
+ sandbox: true,
146121
+ name: property,
146122
+ call: async ([value]) => {
146123
+ const iterator = getSandboxIterator(target);
146124
+ const result = await iterator[property](value);
146125
+ return allocateProducedSandboxValue(
146126
+ { value: result.value, done: result.done === true },
146127
+ budget
146128
+ );
146129
+ }
146130
+ });
146131
+ }
146132
+ var generatorMethodNames;
146133
+ var init_generator2 = __esm({
146134
+ "packages/safe-js/src/interp/methods/generator.ts"() {
146135
+ "use strict";
146136
+ init_iteration();
146137
+ init_values();
146138
+ generatorMethodNames = /* @__PURE__ */ new Set(["next", "return", "throw"]);
146139
+ }
146140
+ });
146141
+
145787
146142
  // packages/safe-js/src/interp/methods/set.ts
145788
146143
  function isSetMethodName(value) {
145789
146144
  return typeof value === "string" && setMethodNames.has(value);
@@ -145936,7 +146291,11 @@ function createObjectGlobal(methods, budget) {
145936
146291
  budget.chargeDataUsage(1);
145937
146292
  return /* @__PURE__ */ Object.create(null);
145938
146293
  }
145939
- if (typeof value !== "object") throw new TypeError("Object primitive boxing is not supported.");
146294
+ if (typeof value !== "object") {
146295
+ const box = createSandboxBox(value);
146296
+ budget.chargeDataUsage(measureSandboxData([box]));
146297
+ return box;
146298
+ }
145940
146299
  return value;
145941
146300
  };
145942
146301
  const constructor = createSandboxClosure({
@@ -145966,9 +146325,7 @@ function createObjectGlobal(methods, budget) {
145966
146325
  length: 0,
145967
146326
  call: (_args, context) => {
145968
146327
  const value = requireReceiver(context?.thisValue);
145969
- if (typeof value !== "object")
145970
- throw new TypeError("Object primitive boxing is not supported.");
145971
- return value;
146328
+ return construct([value]);
145972
146329
  }
145973
146330
  }),
145974
146331
  hasOwnProperty: createSandboxClosure({
@@ -146036,6 +146393,7 @@ function hasOwnSandboxProperty(value, key3, enumerable) {
146036
146393
  return descriptor !== void 0 && (!enumerable || descriptor.enumerable === true);
146037
146394
  }
146038
146395
  function typeTag(value) {
146396
+ if (isSandboxBox(value)) value = boxedValue(value);
146039
146397
  if (value === void 0) return "Undefined";
146040
146398
  if (value === null) return "Null";
146041
146399
  if (typeof value === "string") return "String";
@@ -146062,6 +146420,7 @@ var init_object2 = __esm({
146062
146420
  "use strict";
146063
146421
  init_graph_depth();
146064
146422
  init_date();
146423
+ init_boxed();
146065
146424
  init_exceptions();
146066
146425
  init_float32();
146067
146426
  init_host_capabilities();
@@ -146069,6 +146428,7 @@ var init_object2 = __esm({
146069
146428
  init_object_model();
146070
146429
  init_string_coercion();
146071
146430
  init_values();
146431
+ init_values();
146072
146432
  }
146073
146433
  });
146074
146434
 
@@ -146158,12 +146518,12 @@ function isSandboxSetConstructor(value) {
146158
146518
  function populateCollection(source, collection, { name, budget, context, append, retainedValues }) {
146159
146519
  budget.allocateCollectionEntries(0);
146160
146520
  if (source === void 0 || source === null) return collection;
146161
- const iterator = getSandboxIterator(source, budget);
146521
+ const iterator = getSandboxIterator(source, budget, context);
146162
146522
  if (iterator === void 0) throw new TypeError(`${name} constructor requires an iterable.`);
146163
146523
  let entry;
146164
146524
  let failure;
146165
146525
  const retained = {};
146166
- budget.setRetainedValues(retained, () => [source, collection, entry, failure, ...retainedValues?.() ?? []]);
146526
+ budget.setRetainedValues(retained, () => [source, iterator.retainedValue, collection, entry, failure, ...retainedValues?.() ?? []]);
146167
146527
  const checkData = createDataCheckpoint(budget, context);
146168
146528
  const closeOnThrow = (error3) => {
146169
146529
  failure = isCapturedException(error3) ? error3.reason : error3;
@@ -146173,7 +146533,7 @@ function populateCollection(source, collection, { name, budget, context, append,
146173
146533
  };
146174
146534
  try {
146175
146535
  const closing = iterator.return?.();
146176
- if (iterator.generator) return Promise.resolve(closing).then(() => {
146536
+ if (iterator.generator || iterator.asynchronous) return Promise.resolve(closing).then(() => {
146177
146537
  throw error3;
146178
146538
  }, rethrow);
146179
146539
  } catch (closeError) {
@@ -146195,7 +146555,7 @@ function populateCollection(source, collection, { name, budget, context, append,
146195
146555
  }
146196
146556
  return false;
146197
146557
  };
146198
- if (iterator.generator) {
146558
+ if (iterator.generator || iterator.asynchronous) {
146199
146559
  return (async () => {
146200
146560
  try {
146201
146561
  checkData(collection, 0, true);
@@ -147145,22 +147505,29 @@ async function evaluateBinaryExpression(node, context) {
147145
147505
  if (left.kind !== "normal") {
147146
147506
  return left;
147147
147507
  }
147508
+ let leftValue = left.value;
147148
147509
  let rightValue;
147149
- const release2 = retainValues(context.budget, () => [left.value, rightValue]);
147510
+ const release2 = retainValues(context.budget, () => [leftValue, rightValue]);
147150
147511
  try {
147151
147512
  const right = await evaluateNode2(node.right, context);
147152
147513
  if (right.kind !== "normal") {
147153
147514
  return right;
147154
147515
  }
147155
147516
  rightValue = right.value;
147156
- let leftValue = left.value;
147157
147517
  if (node.operator === "in") {
147158
147518
  if (typeof right.value !== "object" || right.value === null) {
147159
147519
  throw new TypeError("Right-hand side of 'in' must be an object.");
147160
147520
  }
147161
147521
  leftValue = await toPropertyKey(leftValue, context.budget, createCoercionContext(context));
147162
147522
  }
147163
- const value = applyBinaryOperator(node, leftValue, right.value, context);
147523
+ if (!["in", "instanceof", "===", "!=="].includes(node.operator)) {
147524
+ const equality = node.operator === "==" || node.operator === "!=";
147525
+ if (isSandboxBox(leftValue) && (!equality || rightValue !== null && rightValue !== void 0 && typeof rightValue !== "object"))
147526
+ leftValue = await toNumericPrimitive(leftValue, context);
147527
+ if (isSandboxBox(rightValue) && (!equality || left.value !== null && left.value !== void 0 && typeof left.value !== "object"))
147528
+ rightValue = await toNumericPrimitive(rightValue, context);
147529
+ }
147530
+ const value = applyBinaryOperator(node, leftValue, rightValue, context);
147164
147531
  return {
147165
147532
  kind: "normal",
147166
147533
  hasValue: true,
@@ -147748,63 +148115,68 @@ async function evaluateForOfStatement(node, context) {
147748
148115
  };
147749
148116
  }
147750
148117
  async function evaluateForOfIterator(node, value, context, restoredEntry) {
147751
- const iterator = getSandboxIterator(value, context.budget);
148118
+ const iterator = getSandboxIterator(value, context.budget, createCoercionContext(context));
147752
148119
  if (iterator === void 0) {
147753
148120
  throw new TypeError(`${String(value)} is not a supported iterable`);
147754
148121
  }
147755
- const nodeId = node.nodeId ?? -1;
147756
- let index = consumeRestoredLoopIterationIndex(node, context);
147757
- for (let skipped = 0; skipped < index; skipped += 1) {
147758
- const skippedIteration = await iterator.next();
147759
- if (typeof skippedIteration !== "object" || skippedIteration === null) {
147760
- throw new TypeError("Iterator result must be an object.");
147761
- }
147762
- if (skippedIteration.done) {
147763
- return normalEmptyResult();
147764
- }
147765
- }
147766
- while (true) {
147767
- const iteration = restoredEntry ?? await iterator.next();
147768
- restoredEntry = void 0;
147769
- if (typeof iteration !== "object" || iteration === null) {
147770
- throw new TypeError("Iterator result must be an object.");
147771
- }
147772
- if (iteration.done) {
147773
- context.activeLoopIterations.delete(nodeId);
147774
- return normalEmptyResult();
147775
- }
147776
- context.activeLoopIterations.set(
147777
- nodeId,
147778
- iterator.snapshotIndex === void 0 ? index : {
147779
- get index() {
147780
- return iterator.snapshotIndex();
147781
- },
147782
- values: [value, iteration.value]
148122
+ const releaseIterator = retainValues(context.budget, () => [value, iterator.retainedValue]);
148123
+ try {
148124
+ const nodeId = node.nodeId ?? -1;
148125
+ let index = consumeRestoredLoopIterationIndex(node, context);
148126
+ for (let skipped = 0; skipped < index; skipped += 1) {
148127
+ const skippedIteration = await iterator.next();
148128
+ if (typeof skippedIteration !== "object" || skippedIteration === null) {
148129
+ throw new TypeError("Iterator result must be an object.");
148130
+ }
148131
+ if (skippedIteration.done) {
148132
+ return normalEmptyResult();
147783
148133
  }
147784
- );
147785
- const scope = context.scope.child();
147786
- const binding = await bindForOfLoopVariable(node.left, iteration.value, scope, context);
147787
- if (!binding.ok) {
147788
- return binding.result;
147789
- }
147790
- const iterationContext = createLoopIterationContext(context, scope);
147791
- emitLoopIterationBreakpoint(node, iterationContext);
147792
- const result = await evaluateNode2(node.body, iterationContext);
147793
- if (isMatchingBreak(result, loopLabels(node))) {
147794
- context.activeLoopIterations.delete(nodeId);
147795
- await closeIterator(iterator);
147796
- return normalEmptyResult();
147797
148134
  }
147798
- if (isMatchingContinue(result, loopLabels(node))) {
148135
+ while (true) {
148136
+ const iteration = restoredEntry ?? await iterator.next();
148137
+ restoredEntry = void 0;
148138
+ if (typeof iteration !== "object" || iteration === null) {
148139
+ throw new TypeError("Iterator result must be an object.");
148140
+ }
148141
+ if (iteration.done) {
148142
+ context.activeLoopIterations.delete(nodeId);
148143
+ return normalEmptyResult();
148144
+ }
148145
+ context.activeLoopIterations.set(
148146
+ nodeId,
148147
+ iterator.snapshotIndex === void 0 ? index : {
148148
+ get index() {
148149
+ return iterator.snapshotIndex();
148150
+ },
148151
+ values: [value, iteration.value]
148152
+ }
148153
+ );
148154
+ const scope = context.scope.child();
148155
+ const binding = await bindForOfLoopVariable(node.left, iteration.value, scope, context);
148156
+ if (!binding.ok) {
148157
+ return binding.result;
148158
+ }
148159
+ const iterationContext = createLoopIterationContext(context, scope);
148160
+ emitLoopIterationBreakpoint(node, iterationContext);
148161
+ const result = await evaluateNode2(node.body, iterationContext);
148162
+ if (isMatchingBreak(result, loopLabels(node))) {
148163
+ context.activeLoopIterations.delete(nodeId);
148164
+ await closeIterator(iterator);
148165
+ return normalEmptyResult();
148166
+ }
148167
+ if (isMatchingContinue(result, loopLabels(node))) {
148168
+ index += 1;
148169
+ continue;
148170
+ }
148171
+ if (result.kind !== "normal") {
148172
+ context.activeLoopIterations.delete(nodeId);
148173
+ await closeIterator(iterator);
148174
+ return result;
148175
+ }
147799
148176
  index += 1;
147800
- continue;
147801
- }
147802
- if (result.kind !== "normal") {
147803
- context.activeLoopIterations.delete(nodeId);
147804
- await closeIterator(iterator);
147805
- return result;
147806
148177
  }
147807
- index += 1;
148178
+ } finally {
148179
+ releaseIterator();
147808
148180
  }
147809
148181
  }
147810
148182
  async function evaluateForInStatement(node, context) {
@@ -148174,52 +148546,64 @@ async function evaluateYieldDelegate(node, context) {
148174
148546
  if (argument.kind !== "normal") {
148175
148547
  return argument;
148176
148548
  }
148177
- const iterator = getSandboxIterator(argument.value, context.budget);
148549
+ const iterator = getSandboxIterator(
148550
+ argument.value,
148551
+ context.budget,
148552
+ createCoercionContext(context)
148553
+ );
148178
148554
  if (iterator === void 0) {
148179
148555
  throw new TypeError(`${String(argument.value)} is not a supported iterable`);
148180
148556
  }
148181
- let completion = {
148182
- type: "normal",
148183
- value: void 0
148184
- };
148185
- const replay = context.generatorResume?.sent ?? [];
148186
- let replayIndex = 0;
148187
- while (true) {
148188
- const method = completion.type === "normal" ? "next" : completion.type;
148189
- const iteratorMethod = iterator[method];
148190
- if (iteratorMethod === void 0) {
148191
- if (completion.type === "throw") {
148192
- throw completion.value;
148557
+ const releaseIterator = retainValues(context.budget, () => [
148558
+ argument.value,
148559
+ iterator.retainedValue
148560
+ ]);
148561
+ try {
148562
+ let completion = {
148563
+ type: "normal",
148564
+ value: void 0
148565
+ };
148566
+ const replay = context.generatorResume?.sent ?? [];
148567
+ let replayIndex = 0;
148568
+ while (true) {
148569
+ const method = completion.type === "normal" ? "next" : completion.type;
148570
+ const iteratorMethod = iterator[method];
148571
+ if (iteratorMethod === void 0) {
148572
+ if (completion.type === "throw") {
148573
+ throw completion.value;
148574
+ }
148575
+ return generatorCompletionResult(completion);
148193
148576
  }
148194
- return generatorCompletionResult(completion);
148195
- }
148196
- const result = await iteratorMethod(completion.value);
148197
- if (result.done) {
148198
- if (completion.type === "return") {
148199
- return generatorCompletionResult({ type: "return", value: result.value });
148577
+ const result = await iteratorMethod(completion.value);
148578
+ if (result.done) {
148579
+ if (completion.type === "return") {
148580
+ return generatorCompletionResult({ type: "return", value: result.value });
148581
+ }
148582
+ return {
148583
+ kind: "normal",
148584
+ hasValue: true,
148585
+ value: result.value
148586
+ };
148200
148587
  }
148201
- return {
148202
- kind: "normal",
148203
- hasValue: true,
148204
- value: result.value
148205
- };
148206
- }
148207
- if (replayIndex < replay.length - 1) {
148208
- completion = replay[replayIndex + 1];
148209
- replayIndex += 1;
148210
- continue;
148588
+ if (replayIndex < replay.length - 1) {
148589
+ completion = replay[replayIndex + 1];
148590
+ replayIndex += 1;
148591
+ continue;
148592
+ }
148593
+ const completionPromise = context.generatorYield(
148594
+ allocateProducedSandboxValue(result.value, context.budget),
148595
+ node.nodeId
148596
+ );
148597
+ emitResumeBreakpoint(context, {
148598
+ kind: "generator-yield",
148599
+ nodeId: node.nodeId,
148600
+ span: node.span
148601
+ });
148602
+ completion = await completionPromise;
148603
+ context.generatorResume = void 0;
148211
148604
  }
148212
- const completionPromise = context.generatorYield(
148213
- allocateProducedSandboxValue(result.value, context.budget),
148214
- node.nodeId
148215
- );
148216
- emitResumeBreakpoint(context, {
148217
- kind: "generator-yield",
148218
- nodeId: node.nodeId,
148219
- span: node.span
148220
- });
148221
- completion = await completionPromise;
148222
- context.generatorResume = void 0;
148605
+ } finally {
148606
+ releaseIterator();
148223
148607
  }
148224
148608
  }
148225
148609
  function generatorCompletionResult(completion) {
@@ -148366,6 +148750,14 @@ async function evaluateMemberExpression(node, context) {
148366
148750
  }
148367
148751
  function getPropertyValue(target, property, context) {
148368
148752
  if (isGuestHostObject(target)) return getHostObjectMember(target, String(property));
148753
+ if (typeof target === "string" || typeof target === "number" || typeof target === "boolean") {
148754
+ const prototype = getBoxedPrototype(target, context.budget);
148755
+ if (prototype !== void 0) {
148756
+ if (typeof target === "string" && (property === "length" || getStringIndex(property) !== void 0))
148757
+ return getStringMember(target, property, context.budget);
148758
+ return getMemberValue(prototype, property, context);
148759
+ }
148760
+ }
148369
148761
  if (typeof target === "string") return getStringMember(target, property, context.budget);
148370
148762
  if (typeof target === "number") return getNumberMember(property, context.budget);
148371
148763
  if (typeof target === "boolean") return void 0;
@@ -148537,6 +148929,15 @@ async function evaluateMemberCallExpression(node, context) {
148537
148929
  ...reference,
148538
148930
  property: await toPropertyKey(reference.property, context.budget, createCoercionContext(context))
148539
148931
  };
148932
+ if ((typeof member.object === "string" || typeof member.object === "number" || typeof member.object === "boolean") && getBoxedPrototype(member.object, context.budget) !== void 0) {
148933
+ if (isDefaultBoxedMethod(member.object, member.property, context.budget)) {
148934
+ if (typeof member.object === "string" && isStringMethodName(member.property))
148935
+ return evaluateStringMethodCall(node, member.object, member.property, context);
148936
+ if (typeof member.object === "number" && isNumberMethodName(member.property))
148937
+ return evaluateNumberMethodCall(node, member.object, member.property, context);
148938
+ }
148939
+ return evaluateResolvedCallExpression(node, getPropertyValue(member.object, member.property, context), context, member.object);
148940
+ }
148540
148941
  if (typeof member.object === "string" && isStringMethodName(member.property)) {
148541
148942
  return evaluateStringMethodCall(node, member.object, member.property, context);
148542
148943
  }
@@ -148898,33 +149299,41 @@ function hasSandboxProperty(value, key3, context) {
148898
149299
  return false;
148899
149300
  }
148900
149301
  async function applyCompoundAssignmentOperator(operator, left, right, context) {
148901
- left = await toNumericPrimitive(left, context);
148902
- right = await toNumericPrimitive(right, context);
148903
- switch (operator) {
148904
- case "+=":
148905
- return applyAdditionOperator(left, right, context);
148906
- case "-=":
148907
- return toNumber(left) - toNumber(right);
148908
- case "*=":
148909
- return toNumber(left) * toNumber(right);
148910
- case "/=":
148911
- return toNumber(left) / toNumber(right);
148912
- case "%=":
148913
- return toNumber(left) % toNumber(right);
148914
- case "**=":
148915
- return toNumber(left) ** toNumber(right);
148916
- case "&=":
148917
- return toNumber(left) & toNumber(right);
148918
- case "|=":
148919
- return toNumber(left) | toNumber(right);
148920
- case "^=":
148921
- return toNumber(left) ^ toNumber(right);
148922
- case "<<=":
148923
- return toNumber(left) << toNumber(right);
148924
- case ">>=":
148925
- return toNumber(left) >> toNumber(right);
148926
- case ">>>=":
148927
- return toNumber(left) >>> toNumber(right);
149302
+ const convertingObject = typeof left === "object" && left !== null;
149303
+ let convertedLeft;
149304
+ const release2 = retainValues(context.budget, () => [convertedLeft]);
149305
+ try {
149306
+ left = await toNumericPrimitive(left, context);
149307
+ if (convertingObject) convertedLeft = left;
149308
+ right = await toNumericPrimitive(right, context);
149309
+ switch (operator) {
149310
+ case "+=":
149311
+ return applyAdditionOperator(left, right, context);
149312
+ case "-=":
149313
+ return toNumber(left) - toNumber(right);
149314
+ case "*=":
149315
+ return toNumber(left) * toNumber(right);
149316
+ case "/=":
149317
+ return toNumber(left) / toNumber(right);
149318
+ case "%=":
149319
+ return toNumber(left) % toNumber(right);
149320
+ case "**=":
149321
+ return toNumber(left) ** toNumber(right);
149322
+ case "&=":
149323
+ return toNumber(left) & toNumber(right);
149324
+ case "|=":
149325
+ return toNumber(left) | toNumber(right);
149326
+ case "^=":
149327
+ return toNumber(left) ^ toNumber(right);
149328
+ case "<<=":
149329
+ return toNumber(left) << toNumber(right);
149330
+ case ">>=":
149331
+ return toNumber(left) >> toNumber(right);
149332
+ case ">>>=":
149333
+ return toNumber(left) >>> toNumber(right);
149334
+ }
149335
+ } finally {
149336
+ release2();
148928
149337
  }
148929
149338
  }
148930
149339
  function applyAdditionOperator(left, right, context) {
@@ -149244,6 +149653,7 @@ function createSetMethodOptions(context) {
149244
149653
  }
149245
149654
  function createFunctionMethodOptions(context) {
149246
149655
  return {
149656
+ budget: context.budget,
149247
149657
  callClosure: (closure, args, stack, thisValue, construct) => invokeSandboxClosure(closure, args, context, stack, void 0, thisValue, construct)
149248
149658
  };
149249
149659
  }
@@ -149320,12 +149730,12 @@ async function evaluateSpreadElement(node, context) {
149320
149730
  result: value
149321
149731
  };
149322
149732
  }
149323
- const iterator = getSandboxIterator(value.value, context.budget);
149733
+ const iterator = getSandboxIterator(value.value, context.budget, createCoercionContext(context));
149324
149734
  if (iterator === void 0) {
149325
149735
  throw new TypeError("Spread arguments must evaluate to an iterable.");
149326
149736
  }
149327
149737
  const spreadValues = [];
149328
- const release2 = retainValues(context.budget, () => [value.value, ...spreadValues]);
149738
+ const release2 = retainValues(context.budget, () => [value.value, iterator.retainedValue, ...spreadValues]);
149329
149739
  try {
149330
149740
  while (true) {
149331
149741
  const next = await iterator.next();
@@ -149446,6 +149856,7 @@ var init_interpreter = __esm({
149446
149856
  init_array();
149447
149857
  init_function();
149448
149858
  init_object_model();
149859
+ init_string();
149449
149860
  init_graph_depth();
149450
149861
  init_map();
149451
149862
  init_number();
@@ -149465,6 +149876,7 @@ var init_interpreter = __esm({
149465
149876
  init_float32array2();
149466
149877
  init_float32();
149467
149878
  init_date();
149879
+ init_boxed();
149468
149880
  init_date2();
149469
149881
  init_values();
149470
149882
  init_scope();
@@ -149577,6 +149989,7 @@ function createInterpretedClosure(node, context, evaluateNode3) {
149577
149989
  return isConstructResult(result) ? result : thisValue;
149578
149990
  } : void 0;
149579
149991
  const closure = createSandboxClosure({
149992
+ sourceRange: functionSources.get(node),
149580
149993
  guest: true,
149581
149994
  sandbox: true,
149582
149995
  length: getFunctionLength(node.params),
@@ -149639,6 +150052,7 @@ function executeAsyncFunction(execute2, budget, signal) {
149639
150052
  }
149640
150053
  function createGeneratorClosure(node, context, evaluateNode3) {
149641
150054
  return createSandboxClosure({
150055
+ sourceRange: functionSources.get(node),
149642
150056
  guest: true,
149643
150057
  generator: true,
149644
150058
  sandbox: true,
@@ -149830,6 +150244,7 @@ var init_async = __esm({
149830
150244
  init_var_hoist();
149831
150245
  init_interpreter();
149832
150246
  init_object_model();
150247
+ init_function_source();
149833
150248
  init_bindings();
149834
150249
  init_values();
149835
150250
  }
@@ -150506,6 +150921,30 @@ function copyHostValueToSandbox(value, stackFrames, options, state, path193) {
150506
150921
  state
150507
150922
  );
150508
150923
  }
150924
+ const primitive = nativeBoxedValue(value);
150925
+ if (primitive !== void 0) {
150926
+ if (typeof primitive === "string") budget.allocateString(primitive);
150927
+ const original = value;
150928
+ const existing = state.seen.get(original);
150929
+ if (existing !== void 0) return existing;
150930
+ const copy = createSandboxBox(primitive);
150931
+ state.seen.set(original, copy);
150932
+ budget.chargeDataUsage(measureSandboxData([copy]));
150933
+ for (const [key3, descriptor] of boxedDataProperties(original)) {
150934
+ if (!("value" in descriptor)) throw new TypeError(`Unsupported sandbox value at ${joinPath2(path193, key3)}: accessor property`);
150935
+ Object.defineProperty(copy, budget.allocateString(key3), {
150936
+ ...descriptor,
150937
+ value: copyHostValueToSandbox(
150938
+ descriptor.value,
150939
+ stackFrames,
150940
+ { ...options, capabilityPath: [...options.capabilityPath ?? [], key3] },
150941
+ state,
150942
+ joinPath2(path193, key3)
150943
+ )
150944
+ });
150945
+ }
150946
+ return copy;
150947
+ }
150509
150948
  const date = copyNativeDate(value);
150510
150949
  if (date !== void 0) {
150511
150950
  const existing = state.seen.get(value);
@@ -150796,6 +151235,7 @@ var init_host_bridge = __esm({
150796
151235
  "use strict";
150797
151236
  init_async();
150798
151237
  init_date();
151238
+ init_boxed();
150799
151239
  init_host_capabilities();
150800
151240
  init_shape();
150801
151241
  init_budget2();
@@ -150830,12 +151270,18 @@ function createConsoleJsonGlobals(options) {
150830
151270
  JSON: {
150831
151271
  parse: createSandboxClosure({
150832
151272
  sandbox: true,
150833
- call: async ([text5]) => parseJson4(text5, options.budget),
151273
+ call: async ([text5], context) => {
151274
+ const converted = sandboxString(text5, options.budget, context);
151275
+ return copyJsonToSandbox(
151276
+ JSON.parse(converted instanceof Promise ? await converted : converted),
151277
+ options.budget
151278
+ );
151279
+ },
150834
151280
  name: "parse"
150835
151281
  }),
150836
151282
  stringify: createSandboxClosure({
150837
151283
  sandbox: true,
150838
- call: async ([value, replacer, indent]) => stringifyJson4(value, replacer, indent, options.budget),
151284
+ call: async ([value, replacer, indent], context) => stringifyJson4(value, replacer, indent, options.budget, context),
150839
151285
  name: "stringify"
150840
151286
  })
150841
151287
  },
@@ -150896,11 +151342,7 @@ function createConsoleJsonGlobals(options) {
150896
151342
  )
150897
151343
  };
150898
151344
  }
150899
- function parseJson4(input, budget) {
150900
- const text5 = budget.allocateString(toJsonParseText(input));
150901
- return copyJsonToSandbox(JSON.parse(text5), budget);
150902
- }
150903
- async function stringifyJson4(value, replacer, indent, budget) {
151345
+ async function stringifyJson4(value, replacer, indent, budget, context) {
150904
151346
  if (replacer !== void 0 && replacer !== null && !isSandboxClosure(replacer)) {
150905
151347
  throw new TypeError(
150906
151348
  "JSON.stringify(value, replacer, indent) only supports function, null, or undefined replacers."
@@ -150915,6 +151357,7 @@ async function stringifyJson4(value, replacer, indent, budget) {
150915
151357
  defineDataProperty8(holder, "", value);
150916
151358
  const output = await stringifyProperty("", holder, {
150917
151359
  budget,
151360
+ context,
150918
151361
  gap: normalizeStringifyGap(indent),
150919
151362
  replacer: isSandboxClosure(replacer) ? replacer : void 0,
150920
151363
  stack: []
@@ -150924,15 +151367,6 @@ async function stringifyJson4(value, replacer, indent, budget) {
150924
151367
  }
150925
151368
  return budget.allocateString(output);
150926
151369
  }
150927
- function toJsonParseText(input) {
150928
- if (Array.isArray(input)) {
150929
- return input.map((entry) => entry === null || entry === void 0 ? "" : toJsonParseText(entry)).join(",");
150930
- }
150931
- if (typeof input === "object" && input !== null) {
150932
- return "[object Object]";
150933
- }
150934
- return String(input);
150935
- }
150936
151370
  async function stringifyProperty(key3, holder, state, indent = "") {
150937
151371
  let value = getOwnDataValue(holder, key3);
150938
151372
  if (isSandboxDate(value)) {
@@ -150949,6 +151383,10 @@ async function stringifyProperty(key3, holder, state, indent = "") {
150949
151383
  return stringifyValue3(value, state, indent);
150950
151384
  }
150951
151385
  async function stringifyValue3(value, state, indent) {
151386
+ if (isSandboxBox(value)) {
151387
+ const primitive = boxedValue(value);
151388
+ value = typeof primitive === "number" ? await sandboxNumber(value, state.budget, state.context) : typeof primitive === "string" ? await sandboxString(value, state.budget, state.context) : primitive;
151389
+ }
150952
151390
  if (value === null) {
150953
151391
  return "null";
150954
151392
  }
@@ -151124,6 +151562,8 @@ var init_console_json = __esm({
151124
151562
  "packages/safe-js/src/interp/globals/console-json.ts"() {
151125
151563
  "use strict";
151126
151564
  init_date();
151565
+ init_boxed();
151566
+ init_string_coercion();
151127
151567
  init_compile_guard();
151128
151568
  init_host_bridge();
151129
151569
  init_values();
@@ -151292,6 +151732,54 @@ var init_regex2 = __esm({
151292
151732
  }
151293
151733
  });
151294
151734
 
151735
+ // packages/safe-js/src/interp/globals/numeric-parsers.ts
151736
+ function createNumericParsers(budget) {
151737
+ return {
151738
+ parseInt: createSandboxClosure({
151739
+ sandbox: true,
151740
+ name: "parseInt",
151741
+ call: ([value, radix], context) => {
151742
+ const parse18 = (text6) => {
151743
+ const release2 = retainValues(budget, () => [text6]);
151744
+ let convertedRadix;
151745
+ try {
151746
+ convertedRadix = sandboxNumber(radix, budget, context);
151747
+ } catch (error3) {
151748
+ release2();
151749
+ throw error3;
151750
+ }
151751
+ if (typeof convertedRadix === "number") {
151752
+ try {
151753
+ return globalThis.parseInt(text6, convertedRadix);
151754
+ } finally {
151755
+ release2();
151756
+ }
151757
+ }
151758
+ return convertedRadix.then((number) => globalThis.parseInt(text6, number)).finally(release2);
151759
+ };
151760
+ const text5 = sandboxString(value, budget, context);
151761
+ return typeof text5 === "string" ? parse18(text5) : text5.then(parse18);
151762
+ }
151763
+ }),
151764
+ parseFloat: createSandboxClosure({
151765
+ sandbox: true,
151766
+ name: "parseFloat",
151767
+ call: ([value], context) => {
151768
+ const text5 = sandboxString(value, budget, context);
151769
+ return typeof text5 === "string" ? globalThis.parseFloat(text5) : text5.then(globalThis.parseFloat);
151770
+ }
151771
+ })
151772
+ };
151773
+ }
151774
+ var init_numeric_parsers = __esm({
151775
+ "packages/safe-js/src/interp/globals/numeric-parsers.ts"() {
151776
+ "use strict";
151777
+ init_resources();
151778
+ init_string_coercion();
151779
+ init_values();
151780
+ }
151781
+ });
151782
+
151295
151783
  // packages/safe-js/src/interp/globals/misc.ts
151296
151784
  function createMiscGlobals(options) {
151297
151785
  return {
@@ -151300,24 +151788,21 @@ function createMiscGlobals(options) {
151300
151788
  call: ([value], context) => structuredCloneSandboxValue(value, options.budget, context?.compilation),
151301
151789
  name: "structuredClone"
151302
151790
  }),
151303
- parseInt: createSandboxClosure({
151304
- sandbox: true,
151305
- call: (args) => Reflect.apply(globalThis.parseInt, globalThis, [...args]),
151306
- name: "parseInt"
151307
- }),
151308
- parseFloat: createSandboxClosure({
151309
- sandbox: true,
151310
- call: (args) => Reflect.apply(globalThis.parseFloat, globalThis, [...args]),
151311
- name: "parseFloat"
151312
- }),
151791
+ ...createNumericParsers(options.budget),
151313
151792
  isNaN: createSandboxClosure({
151314
151793
  sandbox: true,
151315
- call: ([value]) => globalThis.isNaN(value),
151794
+ call: ([value], context) => {
151795
+ const number = sandboxNumber(value, options.budget, context);
151796
+ return typeof number === "number" ? Number.isNaN(number) : number.then(Number.isNaN);
151797
+ },
151316
151798
  name: "isNaN"
151317
151799
  }),
151318
151800
  isFinite: createSandboxClosure({
151319
151801
  sandbox: true,
151320
- call: ([value]) => globalThis.isFinite(value),
151802
+ call: ([value], context) => {
151803
+ const number = sandboxNumber(value, options.budget, context);
151804
+ return typeof number === "number" ? Number.isFinite(number) : number.then(Number.isFinite);
151805
+ },
151321
151806
  name: "isFinite"
151322
151807
  })
151323
151808
  };
@@ -151326,7 +151811,7 @@ function structuredCloneSandboxValue(value, budget, parent) {
151326
151811
  const operation = budget.acquireCompileOwner(false, parent?.owner);
151327
151812
  const compilation = parent?.owner === operation.owner ? parent : new CompileScope(operation.owner);
151328
151813
  try {
151329
- const clone = cloneSandboxValue(value, { compilation, resetRegexLastIndex: true });
151814
+ const clone = cloneSandboxValue(value, { compilation, resetRegexLastIndex: true, structuredClone: true });
151330
151815
  assertSandboxGraphDepth(clone);
151331
151816
  assertStructuredCloneable(clone, /* @__PURE__ */ new WeakSet());
151332
151817
  allocateProducedSandboxValue(clone, budget);
@@ -151368,6 +151853,84 @@ var init_misc = __esm({
151368
151853
  init_collection_iterator();
151369
151854
  init_graph_depth();
151370
151855
  init_compile_guard();
151856
+ init_numeric_parsers();
151857
+ init_string_coercion();
151858
+ init_values();
151859
+ }
151860
+ });
151861
+
151862
+ // packages/safe-js/src/interp/globals/primitives.ts
151863
+ function createPrimitiveConstructor(options, budget) {
151864
+ const initial = { Number: 0, String: "", Boolean: false }[options.name];
151865
+ const kind = typeof initial;
151866
+ const prototype = createSandboxBox(initial);
151867
+ const allocate = (value) => {
151868
+ const box = createSandboxBox(value);
151869
+ budget.chargeDataUsage(measureSandboxData([box]));
151870
+ return box;
151871
+ };
151872
+ const constructor = createSandboxClosure({
151873
+ guest: true,
151874
+ sandbox: true,
151875
+ name: options.name,
151876
+ length: 1,
151877
+ call: options.call,
151878
+ construct: (args, context) => {
151879
+ const value = options.call(args, context);
151880
+ return value instanceof Promise ? value.then(allocate) : allocate(value);
151881
+ }
151882
+ });
151883
+ const properties = materializeFunctionProperties(constructor);
151884
+ Object.defineProperty(properties, "prototype", { value: prototype, writable: false });
151885
+ Object.defineProperty(prototype, "constructor", {
151886
+ value: constructor,
151887
+ writable: true,
151888
+ configurable: true
151889
+ });
151890
+ for (const [name, value] of Object.entries(options.properties ?? {}))
151891
+ Object.defineProperty(properties, name, {
151892
+ value,
151893
+ writable: isSandboxClosure(value),
151894
+ configurable: isSandboxClosure(value)
151895
+ });
151896
+ const methods = /* @__PURE__ */ new Map([
151897
+ [
151898
+ "valueOf",
151899
+ createSandboxClosure({
151900
+ sandbox: true,
151901
+ name: "valueOf",
151902
+ length: 0,
151903
+ call: (_args, context) => primitiveReceiver(context?.thisValue, kind)
151904
+ })
151905
+ ]
151906
+ ]);
151907
+ if (kind === "number") {
151908
+ for (const name of numberMethodNames) methods.set(name, getNumberMember(name, budget));
151909
+ } else {
151910
+ methods.set(
151911
+ "toString",
151912
+ createSandboxClosure({
151913
+ sandbox: true,
151914
+ name: "toString",
151915
+ length: 0,
151916
+ call: (_args, context) => budget.allocateString(String(primitiveReceiver(context?.thisValue, kind)))
151917
+ })
151918
+ );
151919
+ if (kind === "string")
151920
+ for (const name of stringMethodNames) methods.set(name, getStringMember("", name, budget));
151921
+ }
151922
+ for (const [name, value] of methods)
151923
+ Object.defineProperty(prototype, name, { value, writable: true, configurable: true });
151924
+ installBoxedPrototype(budget, prototype, constructor);
151925
+ return constructor;
151926
+ }
151927
+ var init_primitives = __esm({
151928
+ "packages/safe-js/src/interp/globals/primitives.ts"() {
151929
+ "use strict";
151930
+ init_boxed();
151931
+ init_object_model();
151932
+ init_number();
151933
+ init_string();
151371
151934
  init_values();
151372
151935
  }
151373
151936
  });
@@ -151437,6 +152000,7 @@ function createObjectArrayGlobals(options) {
151437
152000
  sandbox: true,
151438
152001
  call: ([value]) => {
151439
152002
  if (isSandboxDate(value)) return getDatePrototype(value, options.budget, options.compileOwner);
152003
+ if (value !== null && value !== void 0 && typeof value !== "object") value = createSandboxBox(value);
151440
152004
  objectProperties(value);
151441
152005
  return getSandboxPrototype(value, options.budget);
151442
152006
  },
@@ -151476,11 +152040,11 @@ function createObjectArrayGlobals(options) {
151476
152040
  fromEntries: createSandboxClosure({
151477
152041
  sandbox: true,
151478
152042
  call: ([value], context) => {
151479
- const iterator = getSandboxIterator(value, options.budget);
152043
+ const iterator = getSandboxIterator(value, options.budget, context);
151480
152044
  if (iterator === void 0) {
151481
152045
  throw new TypeError("Object.fromEntries requires an iterable.");
151482
152046
  }
151483
- if (context === void 0 && !iterator.generator) {
152047
+ if (context === void 0 && !iterator.generator && !iterator.asynchronous) {
151484
152048
  return allocateProducedSandboxValue(
151485
152049
  Object.setPrototypeOf(
151486
152050
  Reflect.apply(Object.fromEntries, Object, [{ [Symbol.iterator]: () => iterator }]),
@@ -151538,8 +152102,7 @@ function createObjectArrayGlobals(options) {
151538
152102
  })
151539
152103
  }
151540
152104
  }),
151541
- String: createSandboxClosure({
151542
- sandbox: true,
152105
+ String: createPrimitiveConstructor({
151543
152106
  call: (args, context) => sandboxString(args.length === 0 ? "" : args[0], options.budget, context),
151544
152107
  name: "String",
151545
152108
  properties: {
@@ -151559,9 +152122,8 @@ function createObjectArrayGlobals(options) {
151559
152122
  name: "fromCodePoint"
151560
152123
  })
151561
152124
  }
151562
- }),
151563
- Number: createSandboxClosure({
151564
- sandbox: true,
152125
+ }, options.budget),
152126
+ Number: createPrimitiveConstructor({
151565
152127
  call: (args, context) => sandboxNumber(args.length === 0 ? 0 : args[0], options.budget, context),
151566
152128
  name: "Number",
151567
152129
  properties: {
@@ -151580,16 +152142,7 @@ function createObjectArrayGlobals(options) {
151580
152142
  call: ([value]) => typeof value === "number" && Number.isInteger(value),
151581
152143
  name: "isInteger"
151582
152144
  }),
151583
- parseInt: createSandboxClosure({
151584
- sandbox: true,
151585
- call: (args) => Reflect.apply(Number.parseInt, Number, [...args]),
151586
- name: "parseInt"
151587
- }),
151588
- parseFloat: createSandboxClosure({
151589
- sandbox: true,
151590
- call: (args) => Reflect.apply(Number.parseFloat, Number, [...args]),
151591
- name: "parseFloat"
151592
- }),
152145
+ ...createNumericParsers(options.budget),
151593
152146
  isSafeInteger: createSandboxClosure({
151594
152147
  sandbox: true,
151595
152148
  call: ([value]) => typeof value === "number" && Number.isSafeInteger(value),
@@ -151604,12 +152157,11 @@ function createObjectArrayGlobals(options) {
151604
152157
  NEGATIVE_INFINITY: Number.NEGATIVE_INFINITY,
151605
152158
  POSITIVE_INFINITY: Number.POSITIVE_INFINITY
151606
152159
  }
151607
- }),
151608
- Boolean: createSandboxClosure({
151609
- sandbox: true,
152160
+ }, options.budget),
152161
+ Boolean: createPrimitiveConstructor({
151610
152162
  call: ([value]) => Boolean(value),
151611
152163
  name: "Boolean"
151612
- })
152164
+ }, options.budget)
151613
152165
  };
151614
152166
  }
151615
152167
  async function objectFromSandboxEntries(items, iterator, budget, context) {
@@ -151619,7 +152171,7 @@ async function objectFromSandboxEntries(items, iterator, budget, context) {
151619
152171
  let value;
151620
152172
  let failure;
151621
152173
  const retained = {};
151622
- budget.setRetainedValues(retained, () => [items, object, entry, key3, value, failure]);
152174
+ budget.setRetainedValues(retained, () => [items, iterator.retainedValue, object, entry, key3, value, failure]);
151623
152175
  const checkData = createDataCheckpoint(budget, context);
151624
152176
  const closeOnThrow = async (error3) => {
151625
152177
  failure = isCapturedException(error3) ? error3.reason : error3;
@@ -151670,6 +152222,10 @@ function assignSandboxValues(target, sources, budget) {
151670
152222
  if (target === null || target === void 0) {
151671
152223
  throw new TypeError("Object.assign(target, ...sources) requires a non-null target.");
151672
152224
  }
152225
+ if (typeof target !== "object") {
152226
+ target = createSandboxBox(target);
152227
+ budget.chargeDataUsage(measureSandboxData([target]));
152228
+ }
151673
152229
  if (!isGuestClosure(target) && !isAssignableSandboxTarget(target)) {
151674
152230
  throw new TypeError("Object.assign(target, ...sources) requires an object or array target.");
151675
152231
  }
@@ -151739,13 +152295,13 @@ async function arrayFromSandboxValues(args, budget, context) {
151739
152295
  throw new TypeError("Array.from requires a non-null input.");
151740
152296
  }
151741
152297
  const read = (property) => context?.getProperty !== void 0 ? context.getProperty(items, property) : getSandboxDataProperty(items, property, budget);
151742
- const iterator = getSandboxIterator(items, budget);
152298
+ const iterator = getSandboxIterator(items, budget, context);
151743
152299
  const constructor = context?.thisValue;
151744
152300
  let result;
151745
152301
  let currentValue;
151746
152302
  let failure;
151747
152303
  const retained = {};
151748
- budget.setRetainedValues(retained, () => [items, mapFn, constructor, result, currentValue, failure]);
152304
+ budget.setRetainedValues(retained, () => [items, iterator?.retainedValue, mapFn, constructor, result, currentValue, failure]);
151749
152305
  const checkData = createDataCheckpoint(budget, context);
151750
152306
  const closeOnThrow = async (error3) => {
151751
152307
  failure = isCapturedException(error3) ? error3.reason : error3;
@@ -151858,6 +152414,7 @@ var init_object_array = __esm({
151858
152414
  init_data_checkpoint();
151859
152415
  init_exceptions();
151860
152416
  init_date();
152417
+ init_boxed();
151861
152418
  init_date2();
151862
152419
  init_object2();
151863
152420
  init_host_capabilities();
@@ -151865,6 +152422,8 @@ var init_object_array = __esm({
151865
152422
  init_interpreter();
151866
152423
  init_iteration();
151867
152424
  init_string_coercion();
152425
+ init_numeric_parsers();
152426
+ init_primitives();
151868
152427
  init_object_model();
151869
152428
  init_values();
151870
152429
  }
@@ -152052,10 +152611,10 @@ var init_random = __esm({
152052
152611
 
152053
152612
  // packages/safe-js/src/realm.ts
152054
152613
  import { AsyncLocalStorage as AsyncLocalStorage9 } from "node:async_hooks";
152055
- import { types as types5 } from "node:util";
152614
+ import { types as types6 } from "node:util";
152056
152615
  function readModules(input) {
152057
152616
  const entries = (value, label) => {
152058
- if (types5.isMap(value) && !types5.isProxy(value)) {
152617
+ if (types6.isMap(value) && !types6.isProxy(value)) {
152059
152618
  const result = [...Map.prototype.entries.call(value)];
152060
152619
  if (result.length > 4096 || result.some(([key3]) => typeof key3 !== "string" || key3.length === 0))
152061
152620
  throw new TypeError(`${label} requires bounded string keys.`);
@@ -152169,7 +152728,7 @@ var init_realm = __esm({
152169
152728
  throw new TypeError("Realm limits must be positive safe integers with supported names.");
152170
152729
  this.limits[name] = Number(value);
152171
152730
  }
152172
- if (options.extensions !== void 0 && (!Array.isArray(options.extensions) || types5.isProxy(options.extensions)))
152731
+ if (options.extensions !== void 0 && (!Array.isArray(options.extensions) || types6.isProxy(options.extensions)))
152173
152732
  throw new TypeError("Extensions must be a registration array.");
152174
152733
  const registrations = options.extensions ?? [];
152175
152734
  const extensions = [];
@@ -152404,7 +152963,7 @@ var init_realm = __esm({
152404
152963
  return this.phase.run(phase, () => {
152405
152964
  try {
152406
152965
  const result = call();
152407
- if (types5.isPromise(result) || phase.pending.size > 0 || phase.failure !== void 0) {
152966
+ if (types6.isPromise(result) || phase.pending.size > 0 || phase.failure !== void 0) {
152408
152967
  return Promise.resolve(result).then(
152409
152968
  async (value) => {
152410
152969
  await Promise.allSettled(phase.pending);
@@ -152473,7 +153032,7 @@ var init_realm = __esm({
152473
153032
  },
152474
153033
  read: (operation, validate2) => {
152475
153034
  const value = this.invokeHost(operation, operation);
152476
- if (types5.isPromise(value)) {
153035
+ if (types6.isPromise(value)) {
152477
153036
  void Promise.resolve(value).catch(() => void 0);
152478
153037
  throw new TypeError("Live property operations must be synchronous.");
152479
153038
  }
@@ -152481,7 +153040,7 @@ var init_realm = __esm({
152481
153040
  },
152482
153041
  write: (operation, value) => {
152483
153042
  const result = this.invokeHost(operation, () => operation(this.exportValue(value)));
152484
- if (types5.isPromise(result)) {
153043
+ if (types6.isPromise(result)) {
152485
153044
  void Promise.resolve(result).catch(() => void 0);
152486
153045
  throw new TypeError("Live property setters must be synchronous.");
152487
153046
  }
@@ -152690,7 +153249,7 @@ var init_realm = __esm({
152690
153249
  }
152691
153250
  });
152692
153251
  const output = getExtensionSetup(extension)(context);
152693
- if (types5.isPromise(output)) {
153252
+ if (types6.isPromise(output)) {
152694
153253
  void Promise.resolve(output).catch(() => void 0);
152695
153254
  throw new TypeError("Extension setup must be synchronous.");
152696
153255
  }
@@ -153319,6 +153878,8 @@ var init_serialize = __esm({
153319
153878
  init_float32();
153320
153879
  init_float32array();
153321
153880
  init_date();
153881
+ init_boxed();
153882
+ init_boxed2();
153322
153883
  init_values();
153323
153884
  UnsnapshotableValueError = class extends Error {
153324
153885
  path;
@@ -153502,7 +154063,8 @@ function run(source, options = {}) {
153502
154063
  options.signal?.addEventListener("abort", captureCancellationSnapshot, { once: true });
153503
154064
  try {
153504
154065
  const restoredSnapshot = options.snapshot === void 0 ? void 0 : restore2(options.snapshot, { source }, operation.owner);
153505
- const executionSemantics = restoredSnapshot?.executionSemantics === "jobs-v6" ? "jobs-v6" : EXECUTION_SEMANTICS;
154066
+ const executionSemantics = restoredSnapshot?.executionSemantics === "jobs-v6" || restoredSnapshot?.executionSemantics === "jobs-v7" ? restoredSnapshot.executionSemantics : EXECUTION_SEMANTICS;
154067
+ runResources.getStore().functionSourceText = executionSemantics === EXECUTION_SEMANTICS;
153506
154068
  const convertInitialInput = (convert) => executionSemantics === "jobs-v6" ? convert() : promiseReplayContext.exit(convert);
153507
154069
  if (restoredSnapshot !== void 0) {
153508
154070
  leaveSnapshotRun = enterSnapshotRun(restoredSnapshot);
@@ -153511,7 +154073,7 @@ function run(source, options = {}) {
153511
154073
  const filename = options.filename ?? "<input>";
153512
154074
  const module = parseExecutableModule(source, filename, operation.owner);
153513
154075
  promiseReplay.validateNodes(module);
153514
- const sourceHash = findRegexLiteral(module) === void 0 ? hashSource(source, operation.owner) : hashParsedAst(module);
154076
+ const sourceHash = findRegexLiteral(module) === void 0 ? hashSource(source, operation.owner, executionSemantics === EXECUTION_SEMANTICS) : hashParsedAst(module, executionSemantics === EXECUTION_SEMANTICS);
153515
154077
  const hostCalls = new HostCallJournal(
153516
154078
  sourceHash,
153517
154079
  readHostCallSnapshot(restoredSnapshot),
@@ -153538,7 +154100,14 @@ function run(source, options = {}) {
153538
154100
  lifecycle
153539
154101
  })
153540
154102
  );
153541
- const builtinBindings = createBuiltinBindings({ compileOwner: operation.owner, budget, hostCalls, sink: options.sink, random: random?.generator.next, clock: options.clock });
154103
+ const builtinBindings = createBuiltinBindings({
154104
+ compileOwner: operation.owner,
154105
+ budget,
154106
+ hostCalls,
154107
+ sink: options.sink,
154108
+ random: random?.generator.next,
154109
+ clock: options.clock
154110
+ });
153542
154111
  const importMeta = convertInitialInput(
153543
154112
  () => deepCopyToSandbox(options.importMeta ?? {})
153544
154113
  );
@@ -154053,7 +154622,11 @@ function inspectSnapshotMigration(snapshot2, options) {
154053
154622
  validateSnapshotData(snapshot2);
154054
154623
  validateDumpEnvelope(snapshot2);
154055
154624
  validateMigrationSemantics(snapshot2.executionSemantics);
154056
- const sourceHash = hashSource(options.source);
154625
+ const sourceHash = hashSource(
154626
+ options.source,
154627
+ void 0,
154628
+ snapshot2.executionSemantics === EXECUTION_SEMANTICS
154629
+ );
154057
154630
  if (snapshot2.sourceHash !== sourceHash)
154058
154631
  throw new TypeError(
154059
154632
  `Migration requires the original executable source (checkpoint hash ${snapshot2.sourceHash}, supplied ${sourceHash}). Preserve the checkpoint; do not replace its hash.`