poe-code 5.0.3 → 6.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (49) hide show
  1. package/dist/index.js +1859 -1313
  2. package/dist/index.js.map +4 -4
  3. package/dist/metafile.json +1 -1
  4. package/dist/providers/poe-agent.js +14 -2
  5. package/dist/providers/poe-agent.js.map +4 -4
  6. package/package.json +1 -1
  7. package/packages/safejs/dist/interp/async.js +31 -9
  8. package/packages/safejs/dist/interp/cancel.d.ts +7 -2
  9. package/packages/safejs/dist/interp/cancel.js +128 -92
  10. package/packages/safejs/dist/interp/exceptions.js +7 -3
  11. package/packages/safejs/dist/interp/globals/collections.js +2 -0
  12. package/packages/safejs/dist/interp/globals/console-json.js +4 -0
  13. package/packages/safejs/dist/interp/globals/error.js +1 -5
  14. package/packages/safejs/dist/interp/globals/math.js +2 -4
  15. package/packages/safejs/dist/interp/globals/misc.js +5 -0
  16. package/packages/safejs/dist/interp/globals/object-array.js +25 -0
  17. package/packages/safejs/dist/interp/globals/regex.js +1 -1
  18. package/packages/safejs/dist/interp/host-bridge.js +8 -5
  19. package/packages/safejs/dist/interp/interpreter.js +26 -32
  20. package/packages/safejs/dist/interp/iteration.d.ts +3 -3
  21. package/packages/safejs/dist/interp/iteration.js +20 -9
  22. package/packages/safejs/dist/interp/methods/array.js +1 -0
  23. package/packages/safejs/dist/interp/methods/function.d.ts +1 -1
  24. package/packages/safejs/dist/interp/methods/function.js +17 -1
  25. package/packages/safejs/dist/interp/methods/generator.js +1 -0
  26. package/packages/safejs/dist/interp/methods/map.js +1 -0
  27. package/packages/safejs/dist/interp/methods/number.js +1 -0
  28. package/packages/safejs/dist/interp/methods/regex.js +1 -0
  29. package/packages/safejs/dist/interp/methods/set.js +1 -0
  30. package/packages/safejs/dist/interp/methods/string.js +1 -0
  31. package/packages/safejs/dist/interp/promise-tracker.d.ts +12 -2
  32. package/packages/safejs/dist/interp/promise-tracker.js +65 -7
  33. package/packages/safejs/dist/interp/promise.d.ts +7 -5
  34. package/packages/safejs/dist/interp/promise.js +531 -148
  35. package/packages/safejs/dist/interp/values.d.ts +6 -0
  36. package/packages/safejs/dist/interp/values.js +25 -5
  37. package/packages/safejs/dist/lint/rules/AS001.js +0 -5
  38. package/packages/safejs/dist/snapshot/dump-format.d.ts +1 -1
  39. package/packages/safejs/dist/snapshot/dump-format.js +1 -1
  40. package/packages/safejs/dist/snapshot/replay-data.js +3 -0
  41. package/packages/toolcraft-design/dist/explorer/detail-content.d.ts +6 -0
  42. package/packages/toolcraft-design/dist/explorer/detail-content.js +32 -0
  43. package/packages/toolcraft-design/dist/explorer/layout.d.ts +1 -0
  44. package/packages/toolcraft-design/dist/explorer/layout.js +8 -0
  45. package/packages/toolcraft-design/dist/explorer/reducer.js +8 -19
  46. package/packages/toolcraft-design/dist/explorer/render/detail.d.ts +1 -1
  47. package/packages/toolcraft-design/dist/explorer/render/detail.js +8 -36
  48. package/packages/toolcraft-design/dist/explorer/render/pane.d.ts +1 -1
  49. package/packages/toolcraft-design/dist/explorer/render/pane.js +1 -8
package/dist/index.js CHANGED
@@ -10952,6 +10952,14 @@ function computeExplorerLayout(opts) {
10952
10952
  footer
10953
10953
  };
10954
10954
  }
10955
+ function paneBodyRect(rect) {
10956
+ return {
10957
+ x: rect.x + 2,
10958
+ y: rect.y + 1,
10959
+ width: Math.max(0, rect.width - 4),
10960
+ height: Math.max(0, rect.height - 2)
10961
+ };
10962
+ }
10955
10963
  function resolveMode(cols, rows) {
10956
10964
  if (cols < 60 || rows < 8) {
10957
10965
  return "too-narrow";
@@ -11302,6 +11310,43 @@ var init_ansi_text = __esm({
11302
11310
  }
11303
11311
  });
11304
11312
 
11313
+ // packages/toolcraft-design/src/explorer/detail-content.ts
11314
+ function prepareDetailContent(content, width) {
11315
+ if (content.trim().length === 0) {
11316
+ return { text: "", lines: [[]] };
11317
+ }
11318
+ width = Math.max(1, width);
11319
+ const key3 = `${contentHash(content)}:${width}`;
11320
+ const cached2 = markdownCache.get(key3);
11321
+ if (cached2 !== void 0) return cached2;
11322
+ const text5 = renderMarkdown(content, { width }).trimEnd();
11323
+ const lines = [[]];
11324
+ for (const cell2 of ansiToCells(text5)) {
11325
+ if (cell2.ch === "\n") lines.push([]);
11326
+ else lines.at(-1).push(cell2);
11327
+ }
11328
+ const prepared = { text: text5, lines };
11329
+ markdownCache.set(key3, prepared);
11330
+ return prepared;
11331
+ }
11332
+ function contentHash(content) {
11333
+ let hash = 2166136261;
11334
+ for (let index = 0; index < content.length; index += 1) {
11335
+ hash ^= content.charCodeAt(index);
11336
+ hash = Math.imul(hash, 16777619);
11337
+ }
11338
+ return hash >>> 0;
11339
+ }
11340
+ var markdownCache;
11341
+ var init_detail_content = __esm({
11342
+ "packages/toolcraft-design/src/explorer/detail-content.ts"() {
11343
+ "use strict";
11344
+ init_ansi_text();
11345
+ init_terminal_markdown();
11346
+ markdownCache = /* @__PURE__ */ new Map();
11347
+ }
11348
+ });
11349
+
11305
11350
  // packages/toolcraft-design/src/explorer/render/text.ts
11306
11351
  function cellWidth(value, startColumn = 0) {
11307
11352
  return displayWidth2(value, startColumn);
@@ -11421,18 +11466,11 @@ function drawPaneFrame(screen, rect, title2, style = {}, options = {}) {
11421
11466
  screen.put(rect.x, rect.y + rect.height - 1, `${options.focused ? "\u2517" : "\u2514"}${horizontal.repeat(innerWidth)}${options.focused ? "\u251B" : "\u2518"}`, style);
11422
11467
  }
11423
11468
  }
11424
- function paneBodyRect(rect) {
11425
- return {
11426
- x: rect.x + 2,
11427
- y: rect.y + 1,
11428
- width: Math.max(0, rect.width - 4),
11429
- height: Math.max(0, rect.height - 2)
11430
- };
11431
- }
11432
11469
  var init_pane = __esm({
11433
11470
  "packages/toolcraft-design/src/explorer/render/pane.ts"() {
11434
11471
  "use strict";
11435
11472
  init_text2();
11473
+ init_layout2();
11436
11474
  }
11437
11475
  });
11438
11476
 
@@ -11471,7 +11509,8 @@ function renderDetailBody(state, screen, rect, row) {
11471
11509
  return { start: 0, max: 0 };
11472
11510
  }
11473
11511
  if (items.length === 1 && items[0]?.title === void 0) {
11474
- return renderBlob(screen, rect, renderItemMarkdown(items[0], rect, row), state.detail.scroll);
11512
+ const content = prepareDetailContent(renderItem(items[0], rect, row), rect.width);
11513
+ return renderBlob(screen, rect, content.lines, state.detail.scroll);
11475
11514
  }
11476
11515
  return renderListMode(state, screen, rect, items, row);
11477
11516
  }
@@ -11499,7 +11538,8 @@ function renderListMode(state, screen, rect, items, row) {
11499
11538
  writeLine2(screen, rect, y, ` ${item.subtitle}`, styles.muted);
11500
11539
  y += 1;
11501
11540
  }
11502
- for (const line of renderItemMarkdown(item, rect, row).split("\n")) {
11541
+ const content = prepareDetailContent(renderItem(item, rect, row), rect.width);
11542
+ for (const line of content.text.split("\n")) {
11503
11543
  if (y >= rect.height) {
11504
11544
  break;
11505
11545
  }
@@ -11512,12 +11552,7 @@ function renderListMode(state, screen, rect, items, row) {
11512
11552
  }
11513
11553
  return { start, max };
11514
11554
  }
11515
- function renderBlob(screen, rect, text5, scroll) {
11516
- const allLines = [[]];
11517
- for (const cell2 of ansiToCells(text5)) {
11518
- if (cell2.ch === "\n") allLines.push([]);
11519
- else allLines.at(-1).push(cell2);
11520
- }
11555
+ function renderBlob(screen, rect, allLines, scroll) {
11521
11556
  const max = Math.max(0, allLines.length - rect.height);
11522
11557
  const start = clamp3(scroll, 0, max);
11523
11558
  const lines = allLines.slice(start);
@@ -11531,19 +11566,6 @@ function renderBlob(screen, rect, text5, scroll) {
11531
11566
  }
11532
11567
  return { start, max };
11533
11568
  }
11534
- function renderItemMarkdown(item, rect, row) {
11535
- const content = renderItem(item, rect, row);
11536
- if (content.trim().length === 0) {
11537
- return "";
11538
- }
11539
- const width = Math.max(1, rect.width);
11540
- const key3 = `${contentHash(content)}:${width}`;
11541
- const cached2 = markdownCache.get(key3);
11542
- if (cached2 !== void 0) return cached2;
11543
- const rendered = renderMarkdown(content, { width }).trimEnd();
11544
- markdownCache.set(key3, rendered);
11545
- return rendered;
11546
- }
11547
11569
  function renderItem(item, rect, row) {
11548
11570
  if (item.renderedContent !== void 0) {
11549
11571
  return item.renderedContent;
@@ -11573,24 +11595,14 @@ function scrollIndicator(state, start, max) {
11573
11595
  if (state.detail.loading) return "\u280B";
11574
11596
  return `${max === 0 ? 0 : Math.round(start / max * 100)}%`;
11575
11597
  }
11576
- function contentHash(content) {
11577
- let hash = 2166136261;
11578
- for (let index = 0; index < content.length; index += 1) {
11579
- hash ^= content.charCodeAt(index);
11580
- hash = Math.imul(hash, 16777619);
11581
- }
11582
- return hash >>> 0;
11583
- }
11584
- var markdownCache;
11585
11598
  var init_detail = __esm({
11586
11599
  "packages/toolcraft-design/src/explorer/render/detail.ts"() {
11587
11600
  "use strict";
11588
- init_ansi_text();
11589
- init_terminal_markdown();
11601
+ init_detail_content();
11602
+ init_layout2();
11590
11603
  init_theme();
11591
11604
  init_pane();
11592
11605
  init_text2();
11593
- markdownCache = /* @__PURE__ */ new Map();
11594
11606
  }
11595
11607
  });
11596
11608
 
@@ -12927,31 +12939,18 @@ function maxDetailScroll(state) {
12927
12939
  return 0;
12928
12940
  }
12929
12941
  if (items.length === 1 && items[0]?.title === void 0) {
12930
- const visibleHeight = detailBodyHeight(state);
12931
- if (visibleHeight <= 0) {
12942
+ const body = paneBodyRect(computeExplorerLayout({ ...state.size, focused: state.focused }).detail);
12943
+ const content = items[0]?.renderedContent;
12944
+ if (body.width <= 0 || body.height <= 0 || content === void 0) {
12932
12945
  return 0;
12933
12946
  }
12934
- return Math.max(0, detailContentLineCount(items[0]) - visibleHeight);
12947
+ return Math.max(0, prepareDetailContent(content, body.width).lines.length - body.height);
12935
12948
  }
12936
12949
  return Math.max(0, items.length - 1);
12937
12950
  }
12938
- function detailContentLineCount(item) {
12939
- return (item.renderedContent ?? "").split("\n").length;
12940
- }
12941
12951
  function detailBodyHeight(state) {
12942
- if (state.layout === "too-narrow" || state.layout === "narrow-list-only" && state.focused !== "detail") {
12943
- return 0;
12944
- }
12945
- const rows = normalizeSize6(state.size.rows);
12946
- const footerHeight = rows > 0 ? Math.min(1, rows) : 0;
12947
- const headerHeight = Math.min(3, Math.max(0, rows - footerHeight));
12948
- const contentHeight = Math.max(0, rows - headerHeight - footerHeight);
12949
- if (state.layout === "narrow-vertical") {
12950
- const listHeight = Math.ceil(contentHeight / 2);
12951
- const detailHeight = contentHeight - listHeight;
12952
- return Math.max(0, detailHeight - 2);
12953
- }
12954
- return Math.max(0, contentHeight - 2);
12952
+ const body = paneBodyRect(computeExplorerLayout({ ...state.size, focused: state.focused }).detail);
12953
+ return body.width > 0 ? body.height : 0;
12955
12954
  }
12956
12955
  function extendSelection(state, delta2) {
12957
12956
  if (!state.multiSelect) {
@@ -13270,7 +13269,9 @@ var init_reducer = __esm({
13270
13269
  "use strict";
13271
13270
  init_terminal_width();
13272
13271
  init_actions();
13272
+ init_detail_content();
13273
13273
  init_filter();
13274
+ init_layout2();
13274
13275
  init_state();
13275
13276
  NO_EFFECTS = [];
13276
13277
  DEFAULT_ACTION_HANDLES = {
@@ -124477,11 +124478,6 @@ var init_AS001 = __esm({
124477
124478
  case "with":
124478
124479
  this.report(token.value, token.start, token.end);
124479
124480
  return;
124480
- case "new":
124481
- if (!this.source.slice(this.skipTriviaFrom(token.end.offset)).startsWith("RegExp")) {
124482
- this.report(token.value, token.start, token.end);
124483
- }
124484
- return;
124485
124481
  default:
124486
124482
  return;
124487
124483
  }
@@ -136544,14 +136540,29 @@ var init_budget2 = __esm({
136544
136540
 
136545
136541
  // packages/safejs/src/interp/promise-tracker.ts
136546
136542
  import { AsyncLocalStorage as AsyncLocalStorage3 } from "node:async_hooks";
136543
+ function assertPromiseExecutionAllowed() {
136544
+ const failure = activePromiseTracker.getStore()?.failure;
136545
+ if (failure !== void 0 && fatalRejectionCleanup.getStore() !== true) throw failure;
136546
+ }
136547
+ function onFatalPromiseRejection(interrupt) {
136548
+ if (fatalRejectionCleanup.getStore() === true) return void 0;
136549
+ return activePromiseTracker.getStore()?.onFatalRejection(interrupt);
136550
+ }
136551
+ function interruptOnFatalPromiseRejection(pending) {
136552
+ if (fatalRejectionCleanup.getStore() === true) return pending;
136553
+ return activePromiseTracker.getStore()?.interruptOnFatalRejection(pending) ?? pending;
136554
+ }
136555
+ function withFatalPromiseCleanup(callback) {
136556
+ return fatalRejectionCleanup.run(true, callback);
136557
+ }
136547
136558
  function createSandboxPromiseRejectionTracker() {
136548
136559
  return new SandboxPromiseRejectionTracker();
136549
136560
  }
136550
136561
  function observeSandboxPromise(promise) {
136551
136562
  activePromiseTracker.getStore()?.observe(promise);
136552
136563
  }
136553
- function trackSandboxPromise(promise) {
136554
- activePromiseTracker.getStore()?.track(promise);
136564
+ function trackSandboxPromise(promise, outcome) {
136565
+ activePromiseTracker.getStore()?.track(promise, outcome);
136555
136566
  }
136556
136567
  function withSandboxPromiseRejectionTracker(tracker, callback) {
136557
136568
  return activePromiseTracker.run(tracker, callback);
@@ -136561,41 +136572,76 @@ async function flushPromiseJobs() {
136561
136572
  await Promise.resolve();
136562
136573
  }
136563
136574
  }
136564
- var SandboxPromiseRejectionTracker, activePromiseTracker;
136575
+ var SandboxPromiseRejectionTracker, activePromiseTracker, fatalRejectionCleanup;
136565
136576
  var init_promise_tracker = __esm({
136566
136577
  "packages/safejs/src/interp/promise-tracker.ts"() {
136567
136578
  "use strict";
136579
+ init_budget2();
136568
136580
  SandboxPromiseRejectionTracker = class {
136569
136581
  records = /* @__PURE__ */ new Set();
136570
136582
  recordsByPromise = /* @__PURE__ */ new WeakMap();
136583
+ fatalRejection;
136584
+ fatalWaiters = /* @__PURE__ */ new Set();
136585
+ get failure() {
136586
+ return this.fatalRejection;
136587
+ }
136588
+ onFatalRejection(interrupt) {
136589
+ if (this.fatalRejection === void 0) this.fatalWaiters.add(interrupt);
136590
+ else interrupt(this.fatalRejection);
136591
+ return () => this.fatalWaiters.delete(interrupt);
136592
+ }
136593
+ interruptOnFatalRejection(pending) {
136594
+ return new Promise((resolve17, reject) => {
136595
+ const detach = this.onFatalRejection(reject);
136596
+ pending.then(
136597
+ (value) => {
136598
+ detach();
136599
+ resolve17(value);
136600
+ },
136601
+ (reason) => {
136602
+ detach();
136603
+ reject(reason);
136604
+ }
136605
+ );
136606
+ });
136607
+ }
136571
136608
  observe(promise) {
136572
136609
  const record2 = this.recordsByPromise.get(promise);
136573
136610
  if (record2 !== void 0) {
136574
136611
  record2.observed = true;
136575
136612
  }
136576
136613
  }
136577
- track(promise) {
136578
- if (this.recordsByPromise.has(promise)) {
136614
+ track(promise, outcome) {
136615
+ const existing = this.recordsByPromise.get(promise);
136616
+ if (existing !== void 0 && outcome === void 0) {
136579
136617
  return;
136580
136618
  }
136581
- const record2 = {
136619
+ const record2 = existing ?? {
136582
136620
  observed: false,
136583
136621
  promise,
136584
136622
  rejected: false
136585
136623
  };
136586
136624
  this.records.add(record2);
136587
136625
  this.recordsByPromise.set(promise, record2);
136588
- promise.promise.then(
136626
+ const pending = outcome ?? promise.promise;
136627
+ pending.then(
136589
136628
  () => void 0,
136590
136629
  (reason) => {
136630
+ if (this.fatalRejection === void 0 && reason instanceof SandboxError && (reason.code === "budgetExceeded" || reason.code === "reentry")) {
136631
+ this.fatalRejection = reason;
136632
+ for (const interrupt of this.fatalWaiters) interrupt(reason);
136633
+ this.fatalWaiters.clear();
136634
+ }
136635
+ if (record2.rejected) return;
136591
136636
  record2.rejected = true;
136592
136637
  record2.rejectionReason = reason;
136593
136638
  }
136594
136639
  );
136595
- promise.promise.catch(() => void 0);
136640
+ pending.catch(() => void 0);
136596
136641
  }
136597
136642
  async findUnhandledRejection() {
136598
136643
  await flushPromiseJobs();
136644
+ if (this.fatalRejection !== void 0) throw this.fatalRejection;
136599
136645
  for (const record2 of this.records) {
136600
136646
  if (record2.rejected && !record2.observed) {
136601
136647
  return {
@@ -136608,6 +136654,7 @@ var init_promise_tracker = __esm({
136608
136654
  }
136609
136655
  };
136610
136656
  activePromiseTracker = new AsyncLocalStorage3();
136657
+ fatalRejectionCleanup = new AsyncLocalStorage3();
136611
136658
  }
136612
136659
  });
136613
136660
 
@@ -136988,7 +137035,7 @@ var init_dump_format = __esm({
136988
137035
  init_arguments();
136989
137036
  init_arguments2();
136990
137037
  DUMP_FORMAT_VERSION = 1;
136991
- EXECUTION_SEMANTICS = "jobs-v1";
137038
+ EXECUTION_SEMANTICS = "jobs-v2";
136992
137039
  SKIP_VALUE = /* @__PURE__ */ Symbol("SafeJS.skip-dump-value");
136993
137040
  }
136994
137041
  });
@@ -137753,834 +137800,6 @@ var init_promise_replay = __esm({
137753
137800
  }
137754
137801
  });
137755
137802
 
137756
- // packages/safejs/src/interp/values.ts
137757
- function createSandboxClosure(input) {
137758
- const closure = {
137759
- kind: "fn",
137760
- call: input.call,
137761
- name: input.name,
137762
- ...input.construct === void 0 ? {} : { construct: input.construct },
137763
- ...input.async === true ? { async: true } : {}
137764
- };
137765
- Object.defineProperty(closure, sandboxClosureBrand, {
137766
- enumerable: false,
137767
- value: true
137768
- });
137769
- if (input.properties !== void 0) {
137770
- Object.defineProperty(closure, "properties", {
137771
- enumerable: false,
137772
- value: Object.freeze(
137773
- typeof input.properties === "function" ? input.properties(closure) : input.properties
137774
- )
137775
- });
137776
- }
137777
- if (input.retainedValues !== void 0) {
137778
- Object.defineProperty(closure, sandboxRetainedValues, {
137779
- value: input.retainedValues
137780
- });
137781
- }
137782
- return Object.freeze(closure);
137783
- }
137784
- function createSandboxPromise(promise, metadata = {}) {
137785
- const sandboxPromise = {
137786
- kind: "promise",
137787
- promise: metadata.trackReplay === false ? promise : promiseReplayContext.getStore()?.track(promise) ?? promise
137788
- };
137789
- Object.defineProperty(sandboxPromise, sandboxPromiseBrand, {
137790
- enumerable: false,
137791
- value: true
137792
- });
137793
- Object.defineProperty(sandboxPromise, Symbol.toStringTag, { value: "Promise" });
137794
- if (metadata.span !== void 0) {
137795
- Object.defineProperty(sandboxPromise, "span", {
137796
- value: metadata.span
137797
- });
137798
- }
137799
- if (metadata.synchronousPrefix !== void 0) {
137800
- Object.defineProperty(sandboxPromise, "synchronousPrefix", {
137801
- value: metadata.synchronousPrefix
137802
- });
137803
- }
137804
- if (metadata.hostCall !== void 0) {
137805
- Object.defineProperty(sandboxPromise, "hostCall", { value: metadata.hostCall });
137806
- }
137807
- if (metadata.hostCallJournal !== void 0) {
137808
- Object.defineProperty(sandboxPromise, "hostCallJournal", {
137809
- value: metadata.hostCallJournal
137810
- });
137811
- }
137812
- trackSandboxPromise(sandboxPromise);
137813
- return Object.freeze(sandboxPromise);
137814
- }
137815
- function createSandboxGenerator(channel, metadata = void 0) {
137816
- const generator = {
137817
- kind: "generator",
137818
- state: "start",
137819
- channel,
137820
- ...metadata
137821
- };
137822
- Object.defineProperty(generator, sandboxGeneratorBrand, {
137823
- enumerable: false,
137824
- value: true
137825
- });
137826
- return generator;
137827
- }
137828
- function createSandboxMap(entries = []) {
137829
- const map = {};
137830
- Object.defineProperties(map, {
137831
- kind: {
137832
- value: "map"
137833
- },
137834
- entries: {
137835
- value: new Map(entries)
137836
- }
137837
- });
137838
- Object.defineProperty(map, sandboxMapBrand, {
137839
- enumerable: false,
137840
- value: true
137841
- });
137842
- return Object.freeze(map);
137843
- }
137844
- function createSandboxSet(values = []) {
137845
- const set = {};
137846
- Object.defineProperties(set, {
137847
- kind: {
137848
- value: "set"
137849
- },
137850
- values: {
137851
- value: new Set(values)
137852
- }
137853
- });
137854
- Object.defineProperty(set, sandboxSetBrand, {
137855
- enumerable: false,
137856
- value: true
137857
- });
137858
- return Object.freeze(set);
137859
- }
137860
- function createSandboxRegex(source, flags = "", lastIndex = 0) {
137861
- const regex = { kind: "regex", source, flags, lastIndex };
137862
- Object.defineProperties(regex, {
137863
- [sandboxRegexBrand]: { value: true },
137864
- [sandboxRegexPattern]: { value: parseRegex(source, flags) }
137865
- });
137866
- return Object.seal(regex);
137867
- }
137868
- function getSandboxRegexPattern(regex) {
137869
- return regex[sandboxRegexPattern];
137870
- }
137871
- function isSandboxClosure(value) {
137872
- return typeof value === "object" && value !== null && sandboxClosureBrand in value;
137873
- }
137874
- function isSandboxMap(value) {
137875
- return typeof value === "object" && value !== null && sandboxMapBrand in value;
137876
- }
137877
- function isSandboxPromise(value) {
137878
- return typeof value === "object" && value !== null && sandboxPromiseBrand in value;
137879
- }
137880
- function isSandboxSet(value) {
137881
- return typeof value === "object" && value !== null && sandboxSetBrand in value;
137882
- }
137883
- function isSandboxGenerator(value) {
137884
- return typeof value === "object" && value !== null && sandboxGeneratorBrand in value;
137885
- }
137886
- function isSandboxRegex(value) {
137887
- return typeof value === "object" && value !== null && sandboxRegexBrand in value;
137888
- }
137889
- function deepCopyToSandbox(value) {
137890
- return copyToSandbox(value, {
137891
- seen: /* @__PURE__ */ new WeakMap()
137892
- });
137893
- }
137894
- function cloneSandboxValue(value) {
137895
- return copyToSandbox(
137896
- value,
137897
- {
137898
- seen: /* @__PURE__ */ new WeakMap()
137899
- },
137900
- "<root>",
137901
- true
137902
- );
137903
- }
137904
- function allocateProducedSandboxValue(value, budget) {
137905
- allocateSandboxValue(value, budget, /* @__PURE__ */ new WeakSet());
137906
- return value;
137907
- }
137908
- function measureSandboxData(values, options = {}) {
137909
- const seen = /* @__PURE__ */ new WeakSet();
137910
- let usage = 0;
137911
- const visit = (value) => {
137912
- if (typeof value === "string") {
137913
- usage += value.length;
137914
- return;
137915
- }
137916
- if (typeof value !== "object" || value === null) return;
137917
- if (seen.has(value)) return;
137918
- seen.add(value);
137919
- usage += 1;
137920
- if (Array.isArray(value)) {
137921
- usage += value.length;
137922
- for (const entry of value) visit(entry);
137923
- return;
137924
- }
137925
- if (isSandboxMap(value)) {
137926
- usage += value.entries.size;
137927
- for (const [key3, entry] of value.entries) {
137928
- visit(key3);
137929
- visit(entry);
137930
- }
137931
- return;
137932
- }
137933
- if (isSandboxSet(value)) {
137934
- usage += value.values.size;
137935
- for (const entry of value.values) visit(entry);
137936
- return;
137937
- }
137938
- if (isSandboxClosure(value)) {
137939
- if (options.ignoreClosures) return;
137940
- if (value.properties !== void 0) visit(value.properties);
137941
- if (!options.ignoreClosureCaptures)
137942
- for (const retained of value[sandboxRetainedValues]?.() ?? []) visit(retained);
137943
- return;
137944
- }
137945
- if (isSandboxGenerator(value)) {
137946
- const snapshot2 = value.channel.snapshot();
137947
- usage += snapshot2.sent.length;
137948
- for (const completion of snapshot2.sent) visit(completion.value);
137949
- return;
137950
- }
137951
- if (isSandboxPromise(value)) return;
137952
- if (isSandboxRegex(value)) {
137953
- usage += value.source.length + value.flags.length;
137954
- return;
137955
- }
137956
- const entries = isSandboxArguments(value) ? getSandboxArgumentEntries(value) : Object.entries(value);
137957
- usage += entries.length;
137958
- for (const [key3, entry] of entries) {
137959
- usage += key3.length;
137960
- visit(entry);
137961
- }
137962
- };
137963
- for (const value of values) visit(value);
137964
- return usage;
137965
- }
137966
- function deepCopyFromSandbox(value, options = {}) {
137967
- return copyFromSandbox(
137968
- value,
137969
- {
137970
- seen: /* @__PURE__ */ new WeakMap()
137971
- },
137972
- "<root>",
137973
- options
137974
- );
137975
- }
137976
- function copyToSandbox(value, state, path189 = "<root>", cloneSandboxCollections = false, depth = 0) {
137977
- assertSandboxDataDepth(depth);
137978
- if (isSandboxPrimitive(value)) {
137979
- return value;
137980
- }
137981
- if (isSandboxClosure(value) || isSandboxGenerator(value) || isSandboxRegex(value) || isSandboxPromise(value)) {
137982
- return value;
137983
- }
137984
- if (isSandboxMap(value)) {
137985
- if (!cloneSandboxCollections) return value;
137986
- const existing = state.seen.get(value);
137987
- if (existing !== void 0) return existing;
137988
- const copy = createSandboxMap();
137989
- state.seen.set(value, copy);
137990
- for (const [key3, entry] of value.entries) {
137991
- copy.entries.set(
137992
- copyToSandbox(key3, state, `${path189}.<key>`, true, depth + 1),
137993
- copyToSandbox(entry, state, `${path189}.<value>`, true, depth + 1)
137994
- );
137995
- }
137996
- return copy;
137997
- }
137998
- if (isSandboxSet(value)) {
137999
- if (!cloneSandboxCollections) return value;
138000
- const existing = state.seen.get(value);
138001
- if (existing !== void 0) return existing;
138002
- const copy = createSandboxSet();
138003
- state.seen.set(value, copy);
138004
- for (const entry of value.values) {
138005
- copy.values.add(copyToSandbox(entry, state, `${path189}.<value>`, true, depth + 1));
138006
- }
138007
- return copy;
138008
- }
138009
- if (isHostPromise(value)) {
138010
- const promise = Promise.resolve(value).then(
138011
- (resolved) => copyToSandbox(resolved, { seen: /* @__PURE__ */ new WeakMap() }),
138012
- (reason) => Promise.reject(copyToSandbox(reason, { seen: /* @__PURE__ */ new WeakMap() }))
138013
- );
138014
- const sandboxPromise = createSandboxPromise(promise);
138015
- const span = getBoundOtelSpan(value);
138016
- if (span !== void 0) {
138017
- bindOtelSpan(promise, span);
138018
- bindOtelSpan(sandboxPromise, span);
138019
- }
138020
- return sandboxPromise;
138021
- }
138022
- if (value instanceof Map) {
138023
- const existing = state.seen.get(value);
138024
- if (existing !== void 0) {
138025
- return existing;
138026
- }
138027
- const copy = createSandboxMap();
138028
- state.seen.set(value, copy);
138029
- for (const [key3, entry] of value) {
138030
- copy.entries.set(
138031
- copyToSandbox(key3, state, `${path189}.<key>`, cloneSandboxCollections, depth + 1),
138032
- copyToSandbox(entry, state, `${path189}.<value>`, cloneSandboxCollections, depth + 1)
138033
- );
138034
- }
138035
- return copy;
138036
- }
138037
- if (value instanceof Set) {
138038
- const existing = state.seen.get(value);
138039
- if (existing !== void 0) {
138040
- return existing;
138041
- }
138042
- const copy = createSandboxSet();
138043
- state.seen.set(value, copy);
138044
- for (const entry of value) {
138045
- copy.values.add(
138046
- copyToSandbox(entry, state, `${path189}.<value>`, cloneSandboxCollections, depth + 1)
138047
- );
138048
- }
138049
- return copy;
138050
- }
138051
- if (isPlainArray(value)) {
138052
- const existing = state.seen.get(value);
138053
- if (existing !== void 0) {
138054
- return existing;
138055
- }
138056
- const copy = new Array(value.length);
138057
- state.seen.set(value, copy);
138058
- for (const entry of getEnumerableArrayEntries(value, path189)) {
138059
- defineOwnDataProperty(
138060
- copy,
138061
- entry.key,
138062
- copyToSandbox(
138063
- entry.value,
138064
- state,
138065
- joinArrayPath(path189, entry.key),
138066
- cloneSandboxCollections,
138067
- depth + 1
138068
- )
138069
- );
138070
- }
138071
- return copy;
138072
- }
138073
- if (isSandboxArguments(value)) {
138074
- const existing = state.seen.get(value);
138075
- if (existing !== void 0) return existing;
138076
- const copy = createSandboxArguments([]);
138077
- state.seen.set(value, copy);
138078
- copySandboxArgumentProperties(
138079
- value,
138080
- copy,
138081
- (entry, key3) => copyToSandbox(entry, state, joinPath(path189, key3), cloneSandboxCollections, depth + 1)
138082
- );
138083
- return copy;
138084
- }
138085
- if (isPlainObject10(value)) {
138086
- const existing = state.seen.get(value);
138087
- if (existing !== void 0) {
138088
- return existing;
138089
- }
138090
- const copy = createPlainObject(true);
138091
- state.seen.set(value, copy);
138092
- for (const entry of getEnumerableObjectEntries(value, path189)) {
138093
- defineOwnDataProperty(
138094
- copy,
138095
- entry.key,
138096
- copyToSandbox(
138097
- entry.value,
138098
- state,
138099
- joinPath(path189, entry.key),
138100
- cloneSandboxCollections,
138101
- depth + 1
138102
- )
138103
- );
138104
- }
138105
- return copy;
138106
- }
138107
- throw new TypeError(`Unsupported sandbox value at ${path189}: ${describeValue(value)}`);
138108
- }
138109
- function copyFromSandbox(value, state, path189 = "<root>", options, depth = 0) {
138110
- assertSandboxDataDepth(depth);
138111
- if (isSandboxPrimitive(value)) {
138112
- return value;
138113
- }
138114
- if (isSandboxClosure(value)) {
138115
- if (options.wrapClosure === void 0) {
138116
- throw new TypeError(
138117
- "Sandbox closures cannot cross into host values without an explicit wrapper."
138118
- );
138119
- }
138120
- const existing = state.seen.get(value);
138121
- if (existing !== void 0) {
138122
- return existing;
138123
- }
138124
- const wrapped = options.wrapClosure(value);
138125
- state.seen.set(value, wrapped);
138126
- return wrapped;
138127
- }
138128
- if (isSandboxPromise(value)) {
138129
- observeSandboxPromise(value);
138130
- return value.promise.then(
138131
- (resolved) => copyFromSandbox(resolved, { seen: /* @__PURE__ */ new WeakMap() }, "<root>", options),
138132
- (reason) => Promise.reject(
138133
- reason instanceof SandboxError ? reason : copyFromSandbox(reason, { seen: /* @__PURE__ */ new WeakMap() }, "<root>", options)
138134
- )
138135
- );
138136
- }
138137
- if (isSandboxGenerator(value)) {
138138
- throw new TypeError("Sandbox generators cannot cross into host values.");
138139
- }
138140
- if (isSandboxRegex(value)) {
138141
- const regex = new RegExp(value.source, value.flags);
138142
- regex.lastIndex = value.lastIndex;
138143
- return regex;
138144
- }
138145
- if (isSandboxMap(value)) {
138146
- const existing = state.seen.get(value);
138147
- if (existing !== void 0) {
138148
- return existing;
138149
- }
138150
- const copy = /* @__PURE__ */ new Map();
138151
- state.seen.set(value, copy);
138152
- for (const [key3, entry] of value.entries) {
138153
- copy.set(
138154
- copyFromSandbox(key3, state, `${path189}.<key>`, options, depth + 1),
138155
- copyFromSandbox(entry, state, `${path189}.<value>`, options, depth + 1)
138156
- );
138157
- }
138158
- return copy;
138159
- }
138160
- if (isSandboxSet(value)) {
138161
- const existing = state.seen.get(value);
138162
- if (existing !== void 0) {
138163
- return existing;
138164
- }
138165
- const copy = /* @__PURE__ */ new Set();
138166
- state.seen.set(value, copy);
138167
- for (const entry of value.values) {
138168
- copy.add(copyFromSandbox(entry, state, `${path189}.<value>`, options, depth + 1));
138169
- }
138170
- return copy;
138171
- }
138172
- if (isPlainArray(value)) {
138173
- const existing = state.seen.get(value);
138174
- if (existing !== void 0) {
138175
- return existing;
138176
- }
138177
- const copy = new Array(value.length);
138178
- state.seen.set(value, copy);
138179
- for (const entry of getEnumerableArrayEntries(value, path189)) {
138180
- defineOwnDataProperty(
138181
- copy,
138182
- entry.key,
138183
- copyFromSandbox(entry.value, state, joinArrayPath(path189, entry.key), options, depth + 1)
138184
- );
138185
- }
138186
- return copy;
138187
- }
138188
- if (isSandboxArguments(value)) {
138189
- const existing = state.seen.get(value);
138190
- if (existing !== void 0) return existing;
138191
- const copy = createSandboxArguments([]);
138192
- state.seen.set(value, copy);
138193
- copySandboxArgumentProperties(
138194
- value,
138195
- copy,
138196
- (entry, key3) => copyFromSandbox(entry, state, joinPath(path189, key3), options, depth + 1)
138197
- );
138198
- return copy;
138199
- }
138200
- if (isPlainObject10(value)) {
138201
- const existing = state.seen.get(value);
138202
- if (existing !== void 0) {
138203
- return existing;
138204
- }
138205
- const copy = createPlainObject(Object.getPrototypeOf(value) === null);
138206
- state.seen.set(value, copy);
138207
- for (const entry of getEnumerableObjectEntries(value, path189)) {
138208
- defineOwnDataProperty(
138209
- copy,
138210
- entry.key,
138211
- copyFromSandbox(entry.value, state, joinPath(path189, entry.key), options, depth + 1)
138212
- );
138213
- }
138214
- return copy;
138215
- }
138216
- throw new TypeError(`Unsupported sandbox value at ${path189}: ${describeValue(value)}`);
138217
- }
138218
- function isSandboxPrimitive(value) {
138219
- return value === null || value === void 0 || typeof value === "string" || typeof value === "number" || typeof value === "boolean";
138220
- }
138221
- function isHostPromise(value) {
138222
- return value instanceof Promise;
138223
- }
138224
- function allocateSandboxValue(value, budget, seen) {
138225
- if (typeof value === "string") {
138226
- budget.allocateString(value);
138227
- return;
138228
- }
138229
- if (Array.isArray(value)) {
138230
- if (seen.has(value)) {
138231
- return;
138232
- }
138233
- seen.add(value);
138234
- budget.allocateArrayLength(value.length);
138235
- for (const entry of value) {
138236
- allocateSandboxValue(entry, budget, seen);
138237
- }
138238
- return;
138239
- }
138240
- if (isSandboxMap(value)) {
138241
- if (seen.has(value)) {
138242
- return;
138243
- }
138244
- seen.add(value);
138245
- budget.allocateCollectionEntries(value.entries.size);
138246
- for (const [key3, entry] of value.entries) {
138247
- allocateSandboxValue(key3, budget, seen);
138248
- allocateSandboxValue(entry, budget, seen);
138249
- }
138250
- return;
138251
- }
138252
- if (isSandboxSet(value)) {
138253
- if (seen.has(value)) {
138254
- return;
138255
- }
138256
- seen.add(value);
138257
- budget.allocateCollectionEntries(value.values.size);
138258
- for (const entry of value.values) {
138259
- allocateSandboxValue(entry, budget, seen);
138260
- }
138261
- return;
138262
- }
138263
- if (typeof value !== "object" || value === null || isSandboxClosure(value) || isSandboxMap(value) || isSandboxSet(value) || isSandboxPromise(value)) {
138264
- return;
138265
- }
138266
- if (seen.has(value)) {
138267
- return;
138268
- }
138269
- seen.add(value);
138270
- const entries = isSandboxArguments(value) ? getSandboxArgumentEntries(value).map(([, entry]) => entry) : Object.values(value);
138271
- for (const entry of entries) {
138272
- allocateSandboxValue(entry, budget, seen);
138273
- }
138274
- }
138275
- function isPlainObject10(value) {
138276
- if (typeof value !== "object" || value === null || Array.isArray(value)) {
138277
- return false;
138278
- }
138279
- const prototype = Object.getPrototypeOf(value);
138280
- return prototype === Object.prototype || prototype === null;
138281
- }
138282
- function isPlainArray(value) {
138283
- return Array.isArray(value) && Object.getPrototypeOf(value) === Array.prototype;
138284
- }
138285
- function createPlainObject(useNullPrototype) {
138286
- return useNullPrototype ? /* @__PURE__ */ Object.create(null) : {};
138287
- }
138288
- function defineOwnDataProperty(target, key3, value) {
138289
- Object.defineProperty(target, key3, {
138290
- enumerable: true,
138291
- configurable: true,
138292
- writable: true,
138293
- value
138294
- });
138295
- }
138296
- function getEnumerableObjectEntries(value, path189) {
138297
- const descriptors = Object.getOwnPropertyDescriptors(value);
138298
- const entries = [];
138299
- for (const [key3, descriptor] of Object.entries(descriptors)) {
138300
- if (!descriptor.enumerable) {
138301
- continue;
138302
- }
138303
- if ("get" in descriptor || "set" in descriptor) {
138304
- throw new TypeError(`Unsupported sandbox value at ${joinPath(path189, key3)}: accessor property`);
138305
- }
138306
- entries.push({
138307
- key: key3,
138308
- value: descriptor.value
138309
- });
138310
- }
138311
- return entries;
138312
- }
138313
- function getEnumerableArrayEntries(value, path189) {
138314
- const descriptors = Object.getOwnPropertyDescriptors(value);
138315
- const entries = [];
138316
- for (const [key3, descriptor] of Object.entries(descriptors)) {
138317
- if (key3 === "length" || !descriptor.enumerable) {
138318
- continue;
138319
- }
138320
- if ("get" in descriptor || "set" in descriptor) {
138321
- throw new TypeError(
138322
- `Unsupported sandbox value at ${joinArrayPath(path189, key3)}: accessor property`
138323
- );
138324
- }
138325
- entries.push({
138326
- key: key3,
138327
- value: descriptor.value
138328
- });
138329
- }
138330
- return entries;
138331
- }
138332
- function isArrayIndexKey(value) {
138333
- if (value === "") {
138334
- return false;
138335
- }
138336
- const index = Number(value);
138337
- return Number.isInteger(index) && index >= 0 && index < 4294967295 && String(index) === value;
138338
- }
138339
- function describeValue(value) {
138340
- if (typeof value === "function") {
138341
- return "function";
138342
- }
138343
- if (typeof value === "bigint" || typeof value === "symbol") {
138344
- return typeof value;
138345
- }
138346
- if (typeof value === "object" && value !== null) {
138347
- return value.constructor?.name ?? "Object";
138348
- }
138349
- return typeof value;
138350
- }
138351
- function joinPath(path189, key3) {
138352
- return path189 === "<root>" ? `<root>.${key3}` : `${path189}.${key3}`;
138353
- }
138354
- function joinArrayPath(path189, key3) {
138355
- return isArrayIndexKey(key3) ? `${path189}[${key3}]` : joinPath(path189, key3);
138356
- }
138357
- var sandboxClosureBrand, sandboxGeneratorBrand, sandboxMapBrand, sandboxPromiseBrand, sandboxRegexBrand, sandboxRegexPattern, sandboxSetBrand, sandboxRetainedValues;
138358
- var init_values = __esm({
138359
- "packages/safejs/src/interp/values.ts"() {
138360
- "use strict";
138361
- init_otel2();
138362
- init_budget2();
138363
- init_promise_tracker();
138364
- init_promise_replay();
138365
- init_parse5();
138366
- init_graph_depth();
138367
- init_arguments();
138368
- init_arguments();
138369
- sandboxClosureBrand = /* @__PURE__ */ Symbol("SandboxClosure");
138370
- sandboxGeneratorBrand = /* @__PURE__ */ Symbol("SandboxGenerator");
138371
- sandboxMapBrand = /* @__PURE__ */ Symbol("SandboxMap");
138372
- sandboxPromiseBrand = /* @__PURE__ */ Symbol("SandboxPromise");
138373
- sandboxRegexBrand = /* @__PURE__ */ Symbol("SandboxRegex");
138374
- sandboxRegexPattern = /* @__PURE__ */ Symbol("SandboxRegexPattern");
138375
- sandboxSetBrand = /* @__PURE__ */ Symbol("SandboxSet");
138376
- sandboxRetainedValues = /* @__PURE__ */ Symbol("SandboxRetainedValues");
138377
- }
138378
- });
138379
-
138380
- // packages/safejs/src/interp/globals/math.ts
138381
- function createMathGlobals(options = {}) {
138382
- const random = options.random ?? Math.random;
138383
- const mathObject = {
138384
- E: Math.E,
138385
- LN2: Math.LN2,
138386
- LN10: Math.LN10,
138387
- LOG2E: Math.LOG2E,
138388
- LOG10E: Math.LOG10E,
138389
- PI: Math.PI,
138390
- SQRT1_2: Math.SQRT1_2,
138391
- SQRT2: Math.SQRT2,
138392
- random: createSandboxClosure({
138393
- call: () => random(),
138394
- name: "random"
138395
- })
138396
- };
138397
- for (const [name, method] of Object.entries(mathMethods)) {
138398
- mathObject[name] = createSandboxClosure({
138399
- call: (args) => Reflect.apply(method, Math, args),
138400
- name
138401
- });
138402
- }
138403
- return {
138404
- Infinity: Infinity,
138405
- Math: mathObject,
138406
- NaN: Number.NaN
138407
- };
138408
- }
138409
- function createSeededRandom(seed) {
138410
- let state = normalizeSeed(seed);
138411
- return {
138412
- next: () => {
138413
- state = Math.imul(state, 1664525) + 1013904223 >>> 0;
138414
- return state / 4294967296;
138415
- },
138416
- snapshot: () => state,
138417
- restore: (nextState) => {
138418
- state = normalizeSeed(nextState);
138419
- }
138420
- };
138421
- }
138422
- function normalizeSeed(seed) {
138423
- if (!Number.isFinite(seed)) {
138424
- throw new TypeError("Seeded random requires a finite numeric seed.");
138425
- }
138426
- return Math.trunc(seed) >>> 0;
138427
- }
138428
- var mathMethods;
138429
- var init_math = __esm({
138430
- "packages/safejs/src/interp/globals/math.ts"() {
138431
- "use strict";
138432
- init_values();
138433
- mathMethods = {
138434
- abs: Math.abs,
138435
- acos: Math.acos,
138436
- acosh: Math.acosh,
138437
- asin: Math.asin,
138438
- asinh: Math.asinh,
138439
- atan: Math.atan,
138440
- atan2: Math.atan2,
138441
- atanh: Math.atanh,
138442
- ceil: Math.ceil,
138443
- cbrt: Math.cbrt,
138444
- clz32: Math.clz32,
138445
- cos: Math.cos,
138446
- cosh: Math.cosh,
138447
- exp: Math.exp,
138448
- expm1: Math.expm1,
138449
- floor: Math.floor,
138450
- fround: Math.fround,
138451
- hypot: Math.hypot,
138452
- imul: Math.imul,
138453
- log: Math.log,
138454
- log1p: Math.log1p,
138455
- log10: Math.log10,
138456
- log2: Math.log2,
138457
- max: Math.max,
138458
- min: Math.min,
138459
- pow: Math.pow,
138460
- round: Math.round,
138461
- sign: Math.sign,
138462
- sin: Math.sin,
138463
- sinh: Math.sinh,
138464
- sqrt: Math.sqrt,
138465
- tan: Math.tan,
138466
- tanh: Math.tanh,
138467
- trunc: Math.trunc
138468
- };
138469
- }
138470
- });
138471
-
138472
- // packages/safejs/src/random.ts
138473
- import { randomInt } from "node:crypto";
138474
- function createReplayableRandom(options = {}) {
138475
- const snapshot2 = options.snapshot;
138476
- const saved = snapshot2?.random;
138477
- let initialState = options.seed;
138478
- if (saved !== void 0) {
138479
- const hasLoopState = typeof snapshot2?.loopIterations === "object" && snapshot2.loopIterations !== null && Object.keys(snapshot2.loopIterations).length > 0;
138480
- const replaysFromStart = snapshot2?.replay !== void 0 || Array.isArray(snapshot2?.pendingAwaits) && snapshot2.pendingAwaits.length > 0 && !hasLoopState;
138481
- initialState = replaysFromStart ? saved.initialState ?? saved.seed : saved.resumeState ?? saved.state;
138482
- }
138483
- const generator = createSeededRandom(initialState ?? randomInt(4294967296));
138484
- return { seed: saved?.seed ?? generator.snapshot(), ...generator };
138485
- }
138486
- var init_random = __esm({
138487
- "packages/safejs/src/random.ts"() {
138488
- "use strict";
138489
- init_math();
138490
- }
138491
- });
138492
-
138493
- // packages/safejs/src/interp/running-state.ts
138494
- function enterRunningState(object) {
138495
- if (runningObjects.has(object)) {
138496
- throw new SandboxError("reentry");
138497
- }
138498
- runningObjects.add(object);
138499
- let active = true;
138500
- return () => {
138501
- if (!active) return;
138502
- active = false;
138503
- runningObjects.delete(object);
138504
- };
138505
- }
138506
- function enterCollectionCallback(object) {
138507
- const leaveRunning = enterRunningState(object);
138508
- lockedCollections.add(object);
138509
- return () => {
138510
- lockedCollections.delete(object);
138511
- leaveRunning();
138512
- };
138513
- }
138514
- function assertCollectionMutable(object) {
138515
- if (lockedCollections.has(object)) {
138516
- throw new SandboxError("reentry");
138517
- }
138518
- }
138519
- function enterSnapshotRun(snapshot2) {
138520
- if (activeSnapshots.has(snapshot2)) {
138521
- throw new SandboxError("reentry");
138522
- }
138523
- activeSnapshots.add(snapshot2);
138524
- return () => activeSnapshots.delete(snapshot2);
138525
- }
138526
- function assertSnapshotInactive(snapshot2) {
138527
- if (activeSnapshots.has(snapshot2)) {
138528
- throw new SandboxError("reentry");
138529
- }
138530
- }
138531
- var runningObjects, lockedCollections, activeSnapshots;
138532
- var init_running_state = __esm({
138533
- "packages/safejs/src/interp/running-state.ts"() {
138534
- "use strict";
138535
- init_budget2();
138536
- runningObjects = /* @__PURE__ */ new WeakSet();
138537
- lockedCollections = /* @__PURE__ */ new WeakSet();
138538
- activeSnapshots = /* @__PURE__ */ new WeakSet();
138539
- }
138540
- });
138541
-
138542
- // packages/safejs/src/restore.ts
138543
- function restore2(snapshot2, options) {
138544
- assertSnapshotInactive(snapshot2);
138545
- validateDumpEnvelope(snapshot2);
138546
- if (snapshot2.executionSemantics !== EXECUTION_SEMANTICS && (snapshot2.executionSemantics !== void 0 || snapshot2.promiseReplay !== void 0 || snapshot2.replay !== void 0 || snapshot2.initialInputs !== void 0)) {
138547
- throw new SnapshotValidationError(
138548
- "unsupportedVersion",
138549
- "$.executionSemantics",
138550
- "incompatible execution semantics; resume with the SafeJS version that created this snapshot. Migration requires explicit reconciliation, not changing its version marker."
138551
- );
138552
- }
138553
- const currentSourceHash = hashSource(options.source);
138554
- if (snapshot2.sourceHash !== currentSourceHash) {
138555
- throw new SnapshotMismatchError(snapshot2.sourceHash, currentSourceHash);
138556
- }
138557
- return snapshot2;
138558
- }
138559
- var SnapshotMismatchError;
138560
- var init_restore = __esm({
138561
- "packages/safejs/src/restore.ts"() {
138562
- "use strict";
138563
- init_hash();
138564
- init_shape();
138565
- init_validation();
138566
- init_dump_format();
138567
- init_running_state();
138568
- SnapshotMismatchError = class extends Error {
138569
- actualHash;
138570
- expectedHash;
138571
- constructor(expectedHash, actualHash) {
138572
- super(
138573
- `source changed since snapshot was taken (hash ${expectedHash} expected, got ${actualHash}); pass --reset to discard`
138574
- );
138575
- this.name = "SnapshotMismatchError";
138576
- this.actualHash = actualHash;
138577
- this.expectedHash = expectedHash;
138578
- replaceErrorStack(this);
138579
- }
138580
- };
138581
- }
138582
- });
138583
-
138584
137803
  // packages/safejs/src/snapshot/replay-data.ts
138585
137804
  function encodeReplayData(value, options = {}) {
138586
137805
  const nodes = [];
@@ -138737,6 +137956,9 @@ function decodeReplayData(input, options = {}) {
138737
137956
  }
138738
137957
  return createSandboxClosure({
138739
137958
  ...capability,
137959
+ boundTarget: capability.boundTarget,
137960
+ cancellationSignal: capability.cancellationSignal,
137961
+ sandbox: capability.sandbox,
138740
137962
  retainedValues: () => [capability],
138741
137963
  properties: (closure) => {
138742
137964
  restored.set(id, closure);
@@ -139443,10 +138665,11 @@ async function evaluateTryStatement(node, context, evaluateNode3) {
139443
138665
  if (node.finalizer === void 0 || tryOrCatchResult.kind === "error") {
139444
138666
  return tryOrCatchResult;
139445
138667
  }
139446
- const finalizerResult = fatalBudgetError?.budget === "deadline" ? await evaluateWithoutDeadlineChecks(
138668
+ const evaluateFinalizer = () => fatalBudgetError?.budget === "deadline" ? evaluateWithoutDeadlineChecks(
139447
138669
  context,
139448
138670
  () => evaluateBlockCompletion(node.finalizer, context, evaluateNode3)
139449
- ) : await evaluateBlockCompletion(node.finalizer, context, evaluateNode3);
138671
+ ) : evaluateBlockCompletion(node.finalizer, context, evaluateNode3);
138672
+ const finalizerResult = await (fatalBudgetError === void 0 ? evaluateFinalizer() : withFatalPromiseCleanup(evaluateFinalizer));
139450
138673
  if (fatalBudgetError !== void 0) {
139451
138674
  throw fatalBudgetError;
139452
138675
  }
@@ -139843,6 +139066,7 @@ var init_exceptions = __esm({
139843
139066
  init_shape();
139844
139067
  init_budget2();
139845
139068
  init_host_call();
139069
+ init_promise_tracker();
139846
139070
  init_values();
139847
139071
  capturedExceptionBrand = /* @__PURE__ */ Symbol("CapturedException");
139848
139072
  sandboxErrorBrand = /* @__PURE__ */ Symbol("SandboxError");
@@ -139859,6 +139083,136 @@ var init_exceptions = __esm({
139859
139083
  }
139860
139084
  });
139861
139085
 
139086
+ // packages/safejs/src/interp/running-state.ts
139087
+ function enterRunningState(object) {
139088
+ if (runningObjects.has(object)) {
139089
+ throw new SandboxError("reentry");
139090
+ }
139091
+ runningObjects.add(object);
139092
+ let active = true;
139093
+ return () => {
139094
+ if (!active) return;
139095
+ active = false;
139096
+ runningObjects.delete(object);
139097
+ };
139098
+ }
139099
+ function enterCollectionCallback(object) {
139100
+ const leaveRunning = enterRunningState(object);
139101
+ lockedCollections.add(object);
139102
+ return () => {
139103
+ lockedCollections.delete(object);
139104
+ leaveRunning();
139105
+ };
139106
+ }
139107
+ function assertCollectionMutable(object) {
139108
+ if (lockedCollections.has(object)) {
139109
+ throw new SandboxError("reentry");
139110
+ }
139111
+ }
139112
+ function enterSnapshotRun(snapshot2) {
139113
+ if (activeSnapshots.has(snapshot2)) {
139114
+ throw new SandboxError("reentry");
139115
+ }
139116
+ activeSnapshots.add(snapshot2);
139117
+ return () => activeSnapshots.delete(snapshot2);
139118
+ }
139119
+ function assertSnapshotInactive(snapshot2) {
139120
+ if (activeSnapshots.has(snapshot2)) {
139121
+ throw new SandboxError("reentry");
139122
+ }
139123
+ }
139124
+ var runningObjects, lockedCollections, activeSnapshots;
139125
+ var init_running_state = __esm({
139126
+ "packages/safejs/src/interp/running-state.ts"() {
139127
+ "use strict";
139128
+ init_budget2();
139129
+ runningObjects = /* @__PURE__ */ new WeakSet();
139130
+ lockedCollections = /* @__PURE__ */ new WeakSet();
139131
+ activeSnapshots = /* @__PURE__ */ new WeakSet();
139132
+ }
139133
+ });
139134
+
139135
+ // packages/safejs/src/interp/iteration.ts
139136
+ function getSandboxIterator(value) {
139137
+ if (isSandboxGenerator(value)) {
139138
+ return generatorIterator(value);
139139
+ }
139140
+ if (typeof value === "string") {
139141
+ return syncIterator(value[Symbol.iterator]());
139142
+ }
139143
+ if (isSandboxMap(value)) {
139144
+ return syncIterator(
139145
+ Array.from(value.entries, ([key3, entry]) => [key3, entry])[Symbol.iterator]()
139146
+ );
139147
+ }
139148
+ if (isSandboxSet(value)) {
139149
+ return syncIterator(value.values[Symbol.iterator]());
139150
+ }
139151
+ if (typeof value !== "object" && typeof value !== "function" || value === null) {
139152
+ return void 0;
139153
+ }
139154
+ const iteratorMethod = value[Symbol.iterator];
139155
+ if (typeof iteratorMethod !== "function") {
139156
+ return void 0;
139157
+ }
139158
+ return syncIterator(Reflect.apply(iteratorMethod, value, []));
139159
+ }
139160
+ function generatorIterator(generator) {
139161
+ const invoke2 = async (method, value) => {
139162
+ const leaveRunning = enterRunningState(generator);
139163
+ generator.state = "running";
139164
+ try {
139165
+ const result = await generator.channel[method](value);
139166
+ generator.state = result.done ? "done" : "suspended";
139167
+ return result;
139168
+ } catch (error3) {
139169
+ generator.state = "done";
139170
+ throw error3;
139171
+ } finally {
139172
+ leaveRunning();
139173
+ }
139174
+ };
139175
+ return {
139176
+ generator: true,
139177
+ next: (value) => invoke2("next", value),
139178
+ return: (value) => invoke2("return", value),
139179
+ throw: (error3) => invoke2("throw", error3)
139180
+ };
139181
+ }
139182
+ function syncIterator(iterator) {
139183
+ const next = iterator.next;
139184
+ const invoke2 = (method, args) => {
139185
+ const leaveRunning = enterRunningState(iterator);
139186
+ try {
139187
+ return Reflect.apply(method, iterator, args);
139188
+ } finally {
139189
+ leaveRunning();
139190
+ }
139191
+ };
139192
+ return {
139193
+ next: (...args) => invoke2(next, args),
139194
+ get return() {
139195
+ const method = iterator.return;
139196
+ if (method === void 0 || method === null) return void 0;
139197
+ if (typeof method !== "function") throw new TypeError("Iterator return must be callable.");
139198
+ return (...args) => invoke2(method, args);
139199
+ },
139200
+ get throw() {
139201
+ const method = iterator.throw;
139202
+ if (method === void 0 || method === null) return void 0;
139203
+ if (typeof method !== "function") throw new TypeError("Iterator throw must be callable.");
139204
+ return (...args) => invoke2(method, args);
139205
+ }
139206
+ };
139207
+ }
139208
+ var init_iteration = __esm({
139209
+ "packages/safejs/src/interp/iteration.ts"() {
139210
+ "use strict";
139211
+ init_values();
139212
+ init_running_state();
139213
+ }
139214
+ });
139215
+
139862
139216
  // packages/safejs/src/interp/jobs.ts
139863
139217
  import { AsyncLocalStorage as AsyncLocalStorage5 } from "node:async_hooks";
139864
139218
  function runPromiseJob(task) {
@@ -139952,177 +139306,453 @@ var init_jobs4 = __esm({
139952
139306
  });
139953
139307
 
139954
139308
  // packages/safejs/src/interp/promise.ts
139309
+ function isSandboxPromiseConstructor(value) {
139310
+ return isSandboxClosure(value) && promiseConstructors.has(value);
139311
+ }
139955
139312
  function createPromiseGlobals(options) {
139956
- return {
139957
- Promise: {
139313
+ promisePrototypes.delete(options.budget);
139314
+ const prototype = getPromisePrototype(options.budget);
139315
+ const construct = async ([executor], context) => {
139316
+ if (!isSandboxClosure(executor)) throw new TypeError("Promise executor must be a function.");
139317
+ let fulfill;
139318
+ let reject;
139319
+ const pending = createSandboxPromise(
139320
+ new Promise((resolve17, rejectPromise) => {
139321
+ fulfill = resolve17;
139322
+ reject = rejectPromise;
139323
+ }),
139324
+ { span: context?.span }
139325
+ );
139326
+ let settled = false;
139327
+ const settle = (state, value) => {
139328
+ if (settled) return;
139329
+ settled = true;
139330
+ try {
139331
+ if (state === "rejected") {
139332
+ reject(budgetSandboxValue(value, options.budget));
139333
+ } else if (value === pending) {
139334
+ reject(
139335
+ createSubsetErrorValue(
139336
+ "TypeError",
139337
+ "Promise cannot resolve to itself.",
139338
+ context?.stack ?? [],
139339
+ options.budget
139340
+ )
139341
+ );
139342
+ } else {
139343
+ fulfill(resolveSandboxValue(value, { budget: options.budget, self: pending }));
139344
+ }
139345
+ } catch (error3) {
139346
+ reject(error3);
139347
+ }
139348
+ };
139349
+ try {
139350
+ const result = executor.call(
139351
+ [
139352
+ createSandboxClosure({
139353
+ sandbox: true,
139354
+ name: "resolve",
139355
+ retainedValues: () => [pending],
139356
+ call: ([value]) => {
139357
+ settle("fulfilled", value);
139358
+ return void 0;
139359
+ }
139360
+ }),
139361
+ createSandboxClosure({
139362
+ sandbox: true,
139363
+ name: "reject",
139364
+ retainedValues: () => [pending],
139365
+ call: ([reason]) => {
139366
+ settle("rejected", reason);
139367
+ return void 0;
139368
+ }
139369
+ })
139370
+ ],
139371
+ { stack: context?.stack ?? [], thisValue: void 0 }
139372
+ );
139373
+ if (executor.async !== true) await result;
139374
+ else if (isSandboxPromise(result) && result.synchronousPrefix !== void 0)
139375
+ await result.synchronousPrefix;
139376
+ else if (isPromiseLike3(result)) createSandboxPromise(Promise.resolve(result));
139377
+ } catch (error3) {
139378
+ if (error3 instanceof SandboxError && (error3.code === "budgetExceeded" || error3.code === "reentry")) {
139379
+ observeSandboxPromise(pending);
139380
+ throw error3;
139381
+ }
139382
+ settle("rejected", error3);
139383
+ }
139384
+ return pending;
139385
+ };
139386
+ const promiseConstructor = createSandboxClosure({
139387
+ sandbox: true,
139388
+ name: "Promise",
139389
+ construct,
139390
+ call: () => {
139391
+ throw new TypeError("Constructor Promise requires 'new'.");
139392
+ },
139393
+ properties: {
139394
+ prototype,
139958
139395
  all: createSandboxClosure({
139959
- async: true,
139960
- call: ([values]) => createSandboxPromise(
139961
- settleIterable(values, (entries) => Promise.all(entries), options.budget)
139396
+ sandbox: true,
139397
+ call: ([values], context) => settleIterable(
139398
+ values,
139399
+ "all",
139400
+ options.budget,
139401
+ context === void 0 ? promiseConstructor : context.thisValue,
139402
+ context
139962
139403
  ),
139963
139404
  name: "all"
139964
139405
  }),
139965
139406
  race: createSandboxClosure({
139966
- async: true,
139967
- call: ([values]) => createSandboxPromise(
139968
- settleIterable(values, (entries) => Promise.race(entries), options.budget)
139407
+ sandbox: true,
139408
+ call: ([values], context) => settleIterable(
139409
+ values,
139410
+ "race",
139411
+ options.budget,
139412
+ context === void 0 ? promiseConstructor : context.thisValue,
139413
+ context
139969
139414
  ),
139970
139415
  name: "race"
139971
139416
  }),
139972
139417
  allSettled: createSandboxClosure({
139973
- async: true,
139974
- call: ([values]) => createSandboxPromise(
139975
- settleIterable(
139976
- values,
139977
- (entries) => Promise.allSettled(entries).then(
139978
- (results) => budgetSandboxValue(
139979
- results.map(
139980
- (result) => result.status === "fulfilled" ? {
139981
- status: "fulfilled",
139982
- value: result.value
139983
- } : {
139984
- reason: result.reason,
139985
- status: "rejected"
139986
- }
139987
- ),
139988
- options.budget
139989
- )
139990
- ),
139991
- options.budget
139992
- )
139418
+ sandbox: true,
139419
+ call: ([values], context) => settleIterable(
139420
+ values,
139421
+ "allSettled",
139422
+ options.budget,
139423
+ context === void 0 ? promiseConstructor : context.thisValue,
139424
+ context
139993
139425
  ),
139994
139426
  name: "allSettled"
139995
139427
  }),
139996
139428
  any: createSandboxClosure({
139997
- async: true,
139998
- call: ([values]) => createSandboxPromise(
139999
- settleIterable(
140000
- values,
140001
- (entries) => Promise.any(entries).catch((error3) => {
140002
- const aggregate = createSubsetErrorValue(
140003
- "AggregateError",
140004
- "All promises were rejected",
140005
- [],
140006
- options.budget
140007
- );
140008
- aggregate.errors = Array.isArray(error3.errors) ? error3.errors : [];
140009
- throw budgetSandboxValue(aggregate, options.budget);
140010
- }),
140011
- options.budget
140012
- )
139429
+ sandbox: true,
139430
+ call: ([values], context) => settleIterable(
139431
+ values,
139432
+ "any",
139433
+ options.budget,
139434
+ context === void 0 ? promiseConstructor : context.thisValue,
139435
+ context
140013
139436
  ),
140014
139437
  name: "any"
140015
139438
  }),
140016
139439
  resolve: createSandboxClosure({
140017
- async: true,
140018
- call: ([value]) => isSandboxPromise(value) ? value : createSandboxPromise(resolveSandboxValue(value, { budget: options.budget })),
139440
+ sandbox: true,
139441
+ call: ([value], context) => {
139442
+ const constructor = context === void 0 ? promiseConstructor : context.thisValue;
139443
+ if (typeof constructor !== "object" || constructor === null) {
139444
+ throw new TypeError("Promise.resolve requires an object receiver.");
139445
+ }
139446
+ if (isSandboxPromise(value) && getPromiseMember("constructor", options.budget) === constructor) {
139447
+ return value;
139448
+ }
139449
+ return isSandboxPromiseConstructor(constructor) ? createSandboxPromise(resolveSandboxValue(value, { budget: options.budget })) : settleConstructedPromise(constructor, value, "fulfilled", options.budget, context);
139450
+ },
140019
139451
  name: "resolve"
140020
139452
  }),
140021
139453
  reject: createSandboxClosure({
140022
- async: true,
140023
- call: ([reason], context) => createRejectedSandboxPromise(reason, options.budget, context?.span),
139454
+ sandbox: true,
139455
+ call: ([reason], context) => {
139456
+ const constructor = context === void 0 ? promiseConstructor : context.thisValue;
139457
+ return isSandboxPromiseConstructor(constructor) ? createRejectedSandboxPromise(reason, options.budget, context?.span) : settleConstructedPromise(constructor, reason, "rejected", options.budget, context);
139458
+ },
140024
139459
  name: "reject"
140025
139460
  })
140026
139461
  }
140027
- };
139462
+ });
139463
+ Object.defineProperty(prototype, "constructor", {
139464
+ value: promiseConstructor,
139465
+ writable: true,
139466
+ configurable: true
139467
+ });
139468
+ promiseConstructors.add(promiseConstructor);
139469
+ intrinsicPromiseConstructors.set(options.budget, promiseConstructor);
139470
+ return { Promise: promiseConstructor };
140028
139471
  }
140029
- function getPromiseMember(target, property, budget) {
140030
- if (property === "then") {
140031
- return createSandboxClosure({
140032
- async: true,
140033
- call: ([onFulfilled, onRejected]) => {
140034
- observeSandboxPromise(target);
140035
- const chained = createSandboxPromise(
140036
- target.promise.then(
140037
- (value) => runPromiseReaction(onFulfilled, value, "fulfilled", budget, chained),
140038
- (reason) => runPromiseReaction(onRejected, reason, "rejected", budget, chained)
140039
- )
140040
- );
140041
- return chained;
140042
- },
140043
- name: "then"
139472
+ function getPromiseMember(property, budget) {
139473
+ const prototype = getPromisePrototype(budget);
139474
+ return Object.hasOwn(prototype, property) ? prototype[property] : void 0;
139475
+ }
139476
+ async function settleConstructedPromise(constructor, value, state, budget, context) {
139477
+ const capability = await createPromiseCapability(constructor, budget, context);
139478
+ await callPromiseClosure(
139479
+ state === "fulfilled" ? capability.resolve : capability.reject,
139480
+ [value],
139481
+ void 0,
139482
+ budget,
139483
+ context
139484
+ );
139485
+ return capability.promise;
139486
+ }
139487
+ async function createPromiseCapability(constructor, budget, context) {
139488
+ if (!isSandboxClosure(constructor) || constructor.construct === void 0) {
139489
+ throw new TypeError("Promise method requires a constructor receiver.");
139490
+ }
139491
+ let resolve17;
139492
+ let reject;
139493
+ const executor = createSandboxClosure({
139494
+ sandbox: true,
139495
+ retainedValues: () => [resolve17, reject],
139496
+ call: (args) => {
139497
+ if (resolve17 !== void 0 || reject !== void 0) {
139498
+ throw new TypeError("Promise capability is already initialized.");
139499
+ }
139500
+ [resolve17, reject] = args;
139501
+ return void 0;
139502
+ }
139503
+ });
139504
+ const leaveCall = budget.enterCall();
139505
+ try {
139506
+ const promise = await constructor.construct([executor], {
139507
+ stack: context?.stack ?? [],
139508
+ thisValue: void 0,
139509
+ ...context?.span === void 0 ? {} : { span: context.span }
140044
139510
  });
139511
+ if (!isSandboxClosure(resolve17) || !isSandboxClosure(reject)) {
139512
+ throw new TypeError("Promise capability requires callable resolve and reject functions.");
139513
+ }
139514
+ return { promise, resolve: resolve17, reject };
139515
+ } finally {
139516
+ leaveCall();
140045
139517
  }
140046
- if (property === "catch") {
140047
- return createSandboxClosure({
140048
- async: true,
140049
- call: ([onRejected]) => {
139518
+ }
139519
+ async function callPromiseClosure(callback, args, thisValue, budget, context) {
139520
+ const leaveCall = budget.enterCall();
139521
+ try {
139522
+ const stack = context?.stack ?? [];
139523
+ const values = args.map(
139524
+ (value) => value instanceof Error && !(value instanceof SandboxError) ? coerceThrownValue(value, budget, stack) : value
139525
+ );
139526
+ let result = callback.call(values, { stack, thisValue });
139527
+ if (callback.async !== true) result = await result;
139528
+ else if (isPromiseLike3(result)) result = createSandboxPromise(Promise.resolve(result));
139529
+ if (isSandboxPromise(result) && result.synchronousPrefix !== void 0) {
139530
+ await result.synchronousPrefix;
139531
+ }
139532
+ return result;
139533
+ } finally {
139534
+ leaveCall();
139535
+ }
139536
+ }
139537
+ function getPromisePrototype(budget) {
139538
+ const existing = promisePrototypes.get(budget);
139539
+ if (existing !== void 0) return existing;
139540
+ const prototype = {
139541
+ then: createSandboxClosure({
139542
+ sandbox: true,
139543
+ call: ([onFulfilled, onRejected], context) => {
139544
+ const target = context?.thisValue;
139545
+ if (!isSandboxPromise(target))
139546
+ throw new TypeError("Promise.then requires a promise receiver.");
139547
+ validatePromiseConstructorProperty(target, prototype);
140050
139548
  observeSandboxPromise(target);
140051
139549
  const chained = createSandboxPromise(
140052
139550
  target.promise.then(
140053
- (value) => runPromiseReaction(void 0, value, "fulfilled", budget, chained),
140054
- (reason) => runPromiseReaction(onRejected, reason, "rejected", budget, chained)
139551
+ (value) => {
139552
+ consumeSettledHostCall(target);
139553
+ return runPromiseReaction(onFulfilled, value, "fulfilled", budget, chained);
139554
+ },
139555
+ (reason) => {
139556
+ consumeSettledHostCall(target);
139557
+ return runPromiseReaction(onRejected, reason, "rejected", budget, chained);
139558
+ }
140055
139559
  )
140056
139560
  );
140057
139561
  return chained;
140058
139562
  },
139563
+ name: "then"
139564
+ }),
139565
+ catch: createSandboxClosure({
139566
+ sandbox: true,
139567
+ call: ([onRejected], context) => {
139568
+ const target = context?.thisValue;
139569
+ const then = readPromiseReceiverProperty(target, "then", prototype);
139570
+ if (!isSandboxClosure(then)) throw new TypeError("Promise.catch requires a callable then.");
139571
+ return then.call([void 0, onRejected], {
139572
+ stack: context?.stack ?? [],
139573
+ thisValue: target
139574
+ });
139575
+ },
140059
139576
  name: "catch"
140060
- });
140061
- }
140062
- if (property === "finally") {
140063
- return createSandboxClosure({
140064
- async: true,
140065
- call: ([onFinally]) => {
140066
- observeSandboxPromise(target);
140067
- const chained = createSandboxPromise(
140068
- target.promise.then(
140069
- (value) => runPromiseFinally(onFinally, value, "fulfilled", budget, chained),
140070
- (reason) => runPromiseFinally(onFinally, reason, "rejected", budget, chained)
140071
- )
140072
- );
140073
- return chained;
139577
+ }),
139578
+ finally: createSandboxClosure({
139579
+ sandbox: true,
139580
+ call: ([onFinally], context) => {
139581
+ const target = context?.thisValue;
139582
+ if (typeof target !== "object" || target === null) {
139583
+ throw new TypeError("Promise.finally requires an object receiver.");
139584
+ }
139585
+ validatePromiseConstructorProperty(target, prototype);
139586
+ const then = readPromiseReceiverProperty(target, "then", prototype);
139587
+ if (!isSandboxClosure(then))
139588
+ throw new TypeError("Promise.finally requires a callable then.");
139589
+ const handlers = isSandboxClosure(onFinally) ? ["fulfilled", "rejected"].map(
139590
+ (state) => createSandboxClosure({
139591
+ sandbox: true,
139592
+ retainedValues: () => [onFinally],
139593
+ call: async ([value]) => {
139594
+ const result = await callPromiseClosure(
139595
+ onFinally,
139596
+ [],
139597
+ void 0,
139598
+ budget,
139599
+ context
139600
+ );
139601
+ const pending = isSandboxPromise(result) && getPromiseMember("constructor", budget) === intrinsicPromiseConstructors.get(budget) ? result : createSandboxPromise(resolveSandboxValue(result, { budget }));
139602
+ const cleanupThen = getPromiseMember("then", budget);
139603
+ if (!isSandboxClosure(cleanupThen))
139604
+ throw new TypeError("Promise cleanup requires a callable then.");
139605
+ return callPromiseClosure(
139606
+ cleanupThen,
139607
+ [
139608
+ createSandboxClosure({
139609
+ sandbox: true,
139610
+ retainedValues: () => [value],
139611
+ call: () => {
139612
+ if (state === "rejected") throw value;
139613
+ return value;
139614
+ }
139615
+ })
139616
+ ],
139617
+ pending,
139618
+ budget,
139619
+ context
139620
+ );
139621
+ }
139622
+ })
139623
+ ) : [onFinally, onFinally];
139624
+ return then.call(handlers, { stack: context?.stack ?? [], thisValue: target });
140074
139625
  },
140075
139626
  name: "finally"
140076
- });
139627
+ })
139628
+ };
139629
+ for (const name of Object.keys(prototype)) {
139630
+ Object.defineProperty(prototype, name, { enumerable: false });
140077
139631
  }
140078
- return void 0;
139632
+ promisePrototypes.set(budget, prototype);
139633
+ return prototype;
140079
139634
  }
140080
- function settleIterable(iterable, settle, budget) {
140081
- return Promise.resolve().then(
140082
- () => settle(toHostPromiseArray(iterable, budget)).then((value) => budgetSandboxValue(value, budget))
140083
- );
140084
- }
140085
- function toHostPromiseArray(iterable, budget) {
140086
- const iterator = getPromiseIterator(iterable);
140087
- if (iterator === void 0) {
140088
- throw new TypeError("Promise helpers require an iterable.");
140089
- }
140090
- const entries = [];
140091
- while (true) {
140092
- const next = readIteratorNext(iterator);
140093
- if (next.done === true) {
140094
- return entries;
140095
- }
140096
- entries.push(resolveSandboxValue(next.value, { budget }));
140097
- }
139635
+ function readPromiseReceiverProperty(receiver, property, prototype) {
139636
+ const properties = isSandboxPromise(receiver) ? prototype : isSandboxClosure(receiver) ? receiver.properties : receiver;
139637
+ return typeof properties === "object" && properties !== null && Object.hasOwn(properties, property) ? properties[property] : void 0;
140098
139638
  }
140099
- function getPromiseIterator(iterable) {
140100
- if (typeof iterable === "string") {
140101
- return iterable[Symbol.iterator]();
139639
+ function validatePromiseConstructorProperty(receiver, prototype) {
139640
+ const constructor = readPromiseReceiverProperty(receiver, "constructor", prototype);
139641
+ if (constructor !== void 0 && (typeof constructor !== "object" || constructor === null)) {
139642
+ throw new TypeError("Promise constructor property must be an object.");
140102
139643
  }
140103
- if (typeof iterable !== "object" && typeof iterable !== "function" || iterable === null) {
140104
- return void 0;
140105
- }
140106
- const iteratorMethod = iterable[Symbol.iterator];
140107
- if (typeof iteratorMethod !== "function") {
140108
- return void 0;
140109
- }
140110
- const iterator = Reflect.apply(iteratorMethod, iterable, []);
140111
- if (typeof iterator !== "object" && typeof iterator !== "function" || iterator === null) {
140112
- throw new TypeError("Promise helper iterable returned a non-object iterator.");
140113
- }
140114
- return iterator;
140115
139644
  }
140116
- function readIteratorNext(iterator) {
140117
- const nextMethod = iterator.next;
140118
- if (typeof nextMethod !== "function") {
140119
- throw new TypeError("Promise helper iterator requires a next method.");
140120
- }
140121
- const next = Reflect.apply(nextMethod, iterator, []);
140122
- if (typeof next !== "object" || next === null) {
140123
- throw new TypeError("Iterator result must be an object.");
139645
+ async function settleIterable(iterable, method, budget, constructor, context) {
139646
+ const capability = await createPromiseCapability(constructor, budget, context);
139647
+ const prototype = getPromisePrototype(budget);
139648
+ const values = [];
139649
+ let remaining = 1;
139650
+ const complete = async () => {
139651
+ if (remaining !== 0 || method === "race") return;
139652
+ if (method === "any") {
139653
+ const error3 = createSubsetErrorValue(
139654
+ "AggregateError",
139655
+ "All promises were rejected",
139656
+ [],
139657
+ budget
139658
+ );
139659
+ error3.errors = values;
139660
+ await callPromiseClosure(
139661
+ capability.reject,
139662
+ [budgetSandboxValue(error3, budget)],
139663
+ void 0,
139664
+ budget,
139665
+ context
139666
+ );
139667
+ } else {
139668
+ await callPromiseClosure(
139669
+ capability.resolve,
139670
+ [budgetSandboxValue(values, budget)],
139671
+ void 0,
139672
+ budget,
139673
+ context
139674
+ );
139675
+ }
139676
+ };
139677
+ try {
139678
+ const promiseResolve = readPromiseReceiverProperty(constructor, "resolve", prototype);
139679
+ if (!isSandboxClosure(promiseResolve))
139680
+ throw new TypeError("Promise constructor requires a callable resolve.");
139681
+ const iterator = getSandboxIterator(iterable);
139682
+ if (iterator === void 0) throw new TypeError("Promise helpers require an iterable.");
139683
+ let index = 0;
139684
+ while (true) {
139685
+ budget.visitNode();
139686
+ const next = iterator.generator ? await iterator.next() : iterator.next();
139687
+ if (typeof next !== "object" || next === null)
139688
+ throw new TypeError("Iterator result must be an object.");
139689
+ if (next.done) break;
139690
+ const value = next.value;
139691
+ try {
139692
+ budget.allocateArrayLength(index + 1);
139693
+ const entryIndex = index++;
139694
+ if (method !== "race") values.push(void 0);
139695
+ const entry = await callPromiseClosure(
139696
+ promiseResolve,
139697
+ [value],
139698
+ constructor,
139699
+ budget,
139700
+ context
139701
+ );
139702
+ let called = false;
139703
+ const handlers = ["fulfilled", "rejected"].map((state) => {
139704
+ if (method === "race" || method === "any" && state === "fulfilled")
139705
+ return state === "fulfilled" ? capability.resolve : capability.reject;
139706
+ if (method === "all" && state === "rejected") return capability.reject;
139707
+ return createSandboxClosure({
139708
+ sandbox: true,
139709
+ retainedValues: () => [
139710
+ capability.promise,
139711
+ capability.resolve,
139712
+ capability.reject,
139713
+ values
139714
+ ],
139715
+ call: async ([settlement]) => {
139716
+ if (called) return void 0;
139717
+ called = true;
139718
+ values[entryIndex] = method === "allSettled" ? state === "fulfilled" ? { status: state, value: settlement } : { status: state, reason: settlement } : settlement;
139719
+ remaining--;
139720
+ await complete();
139721
+ return void 0;
139722
+ }
139723
+ });
139724
+ });
139725
+ remaining++;
139726
+ const then = readPromiseReceiverProperty(entry, "then", prototype);
139727
+ if (!isSandboxClosure(then))
139728
+ throw new TypeError("Promise resolver result requires a callable then.");
139729
+ await callPromiseClosure(then, handlers, entry, budget, context);
139730
+ } catch (error3) {
139731
+ try {
139732
+ const closed = iterator.return?.();
139733
+ if (iterator.generator) await closed;
139734
+ } catch {
139735
+ throw error3;
139736
+ }
139737
+ throw error3;
139738
+ }
139739
+ }
139740
+ remaining--;
139741
+ await complete();
139742
+ } catch (error3) {
139743
+ if (error3 instanceof SandboxError && (error3.code === "budgetExceeded" || error3.code === "reentry")) {
139744
+ if (isSandboxPromise(capability.promise)) observeSandboxPromise(capability.promise);
139745
+ throw error3;
139746
+ }
139747
+ await callPromiseClosure(
139748
+ capability.reject,
139749
+ [error3],
139750
+ void 0,
139751
+ budget,
139752
+ context
139753
+ );
140124
139754
  }
140125
- return next;
139755
+ return capability.promise;
140126
139756
  }
140127
139757
  function schedulePromise(promise, budget) {
140128
139758
  return Promise.resolve().then(
@@ -140138,11 +139768,15 @@ function createRejectedSandboxPromise(reason, budget, span) {
140138
139768
  return createSandboxPromise(promise, { span });
140139
139769
  }
140140
139770
  function budgetSandboxValue(value, budget) {
140141
- allocateSandboxValue2(value, budget, /* @__PURE__ */ new WeakSet());
139771
+ allocateSandboxValue(value, budget, /* @__PURE__ */ new WeakSet());
140142
139772
  return value;
140143
139773
  }
140144
139774
  function resolveSandboxValue(value, options = {}) {
140145
- return Promise.resolve().then(() => resolveSandboxValueNow(value, options, /* @__PURE__ */ new WeakSet()));
139775
+ try {
139776
+ return resolveSandboxValueNow(value, options);
139777
+ } catch (error3) {
139778
+ return Promise.reject(error3);
139779
+ }
140146
139780
  }
140147
139781
  function consumeSettledHostCall(value) {
140148
139782
  if (value.hostCall?.lifecycle !== "settled") {
@@ -140150,19 +139784,22 @@ function consumeSettledHostCall(value) {
140150
139784
  }
140151
139785
  value.hostCallJournal?.consume(value.hostCall);
140152
139786
  }
140153
- function resolveSandboxValueNow(value, options, seenThenables) {
139787
+ function resolveSandboxValueNow(value, options) {
140154
139788
  if (isPromiseLike3(value)) {
140155
139789
  return Promise.resolve(value).then(
140156
- (resolved) => resolveSandboxValueNow(resolved, options, seenThenables),
139790
+ (resolved) => resolveSandboxValueNow(resolved, options),
140157
139791
  (reason) => Promise.reject(budgetIfNeeded(reason, options.budget))
140158
139792
  );
140159
139793
  }
140160
139794
  if (isSandboxPromise(value)) {
139795
+ if (options.budget !== void 0) {
139796
+ return resolvePromiseResult(value, options.budget, options.self);
139797
+ }
140161
139798
  observeSandboxPromise(value);
140162
139799
  return value.promise.then(
140163
139800
  (resolved) => {
140164
139801
  consumeSettledHostCall(value);
140165
- return resolveSandboxValueNow(resolved, options, seenThenables);
139802
+ return resolveSandboxValueNow(resolved, options);
140166
139803
  },
140167
139804
  (reason) => {
140168
139805
  consumeSettledHostCall(value);
@@ -140172,21 +139809,14 @@ function resolveSandboxValueNow(value, options, seenThenables) {
140172
139809
  }
140173
139810
  const then = getThenable(value);
140174
139811
  if (then !== void 0) {
140175
- return resolveThenable(value, then, options, seenThenables);
139812
+ return resolveThenable(value, then, options);
140176
139813
  }
140177
139814
  return Promise.resolve(budgetIfNeeded(value, options.budget));
140178
139815
  }
140179
- function resolveThenable(value, then, options, seenThenables) {
139816
+ function resolveThenable(value, then, options) {
140180
139817
  if (typeof value !== "object" || value === null) {
140181
139818
  return Promise.resolve(budgetIfNeeded(value, options.budget));
140182
139819
  }
140183
- if (seenThenables.has(value)) {
140184
- return Promise.reject({
140185
- message: "Promise cannot resolve to itself.",
140186
- name: "TypeError"
140187
- });
140188
- }
140189
- seenThenables.add(value);
140190
139820
  return new Promise((resolve17, reject) => {
140191
139821
  let settlement;
140192
139822
  let completed = false;
@@ -140196,7 +139826,9 @@ function resolveThenable(value, then, options, seenThenables) {
140196
139826
  completed = true;
140197
139827
  try {
140198
139828
  if (settlement.state === "fulfilled") {
140199
- resolve17(resolveSandboxValueNow(settlement.value, options, seenThenables));
139829
+ resolve17(
139830
+ isSandboxPromise(settlement.value) || getThenable(settlement.value) !== void 0 ? resolveSandboxValueNow(settlement.value, options) : budgetIfNeeded(settlement.value, options.budget)
139831
+ );
140200
139832
  } else {
140201
139833
  reject(budgetIfNeeded(settlement.value, options.budget));
140202
139834
  }
@@ -140215,6 +139847,7 @@ function resolveThenable(value, then, options, seenThenables) {
140215
139847
  then,
140216
139848
  [
140217
139849
  createSandboxClosure({
139850
+ sandbox: true,
140218
139851
  call: ([resolved]) => {
140219
139852
  recordSettlement("fulfilled", resolved);
140220
139853
  return void 0;
@@ -140222,6 +139855,7 @@ function resolveThenable(value, then, options, seenThenables) {
140222
139855
  name: "resolve"
140223
139856
  }),
140224
139857
  createSandboxClosure({
139858
+ sandbox: true,
140225
139859
  call: ([reason]) => {
140226
139860
  recordSettlement("rejected", reason);
140227
139861
  return void 0;
@@ -140229,57 +139863,137 @@ function resolveThenable(value, then, options, seenThenables) {
140229
139863
  name: "reject"
140230
139864
  })
140231
139865
  ],
140232
- value
140233
- ).then(
140234
- () => {
140235
- invocationPending = false;
140236
- complete();
140237
- },
140238
- (error3) => {
140239
- invocationPending = false;
140240
- recordSettlement("rejected", error3);
140241
- complete();
139866
+ value,
139867
+ {
139868
+ fulfilled: () => {
139869
+ invocationPending = false;
139870
+ complete();
139871
+ },
139872
+ rejected: (error3) => {
139873
+ invocationPending = false;
139874
+ if (error3 instanceof SandboxError && (error3.code === "budgetExceeded" || error3.code === "reentry")) {
139875
+ completed = true;
139876
+ reject(error3);
139877
+ return;
139878
+ }
139879
+ recordSettlement("rejected", error3);
139880
+ complete();
139881
+ }
140242
139882
  }
140243
- );
140244
- }).then((resolved) => budgetIfNeeded(resolved, options.budget));
139883
+ ).catch(reject);
139884
+ });
140245
139885
  }
140246
139886
  function runPromiseReaction(handler, value, state, budget, self) {
140247
- if (!isSandboxClosure(handler)) {
140248
- return state === "fulfilled" ? Promise.resolve(value) : Promise.reject(budgetSandboxValue(value, budget));
140249
- }
140250
- return callInPromiseJob(handler, [value]).then(
140251
- ({ value: result }) => resolveReactionResult(result, budget, self)
140252
- );
140253
- }
140254
- function runPromiseFinally(handler, value, state, budget, self) {
140255
- if (!isSandboxClosure(handler)) {
140256
- return runPromiseReaction(void 0, value, state, budget);
140257
- }
140258
- return callInPromiseJob(handler, []).then(
140259
- ({ value: result }) => resolveReactionResult(result, budget, self).then(
140260
- () => runPromiseReaction(void 0, value, state, budget)
140261
- )
140262
- );
139887
+ return new Promise((resolve17, reject) => {
139888
+ if (state === "rejected" && value instanceof SandboxError && (value.code === "budgetExceeded" || value.code === "reentry")) {
139889
+ reject(value);
139890
+ return;
139891
+ }
139892
+ const argument = state === "rejected" && value instanceof Error ? coerceThrownValue(value, budget, []) : value;
139893
+ const fulfilled = (result) => {
139894
+ if (isPromiseLike3(result)) {
139895
+ resolve17(resolvePromiseResult(result, budget, self));
139896
+ } else if (isSelfResolution(result, self)) {
139897
+ reject(
139898
+ createSubsetErrorValue("TypeError", "Promise cannot resolve to itself.", [], budget)
139899
+ );
139900
+ } else if (isSandboxPromise(result) || getThenable(result) !== void 0) {
139901
+ resolve17(resolvePromiseResult(result, budget, self));
139902
+ } else {
139903
+ resolve17(budgetSandboxValue(result, budget));
139904
+ }
139905
+ };
139906
+ if (isSandboxClosure(handler)) {
139907
+ callInPromiseJob(handler, [argument], void 0, { fulfilled, rejected: reject }).catch(
139908
+ reject
139909
+ );
139910
+ } else {
139911
+ runPromiseJob(() => {
139912
+ if (state === "fulfilled") fulfilled(value);
139913
+ else reject(budgetSandboxValue(value, budget));
139914
+ }).catch(reject);
139915
+ }
139916
+ });
140263
139917
  }
140264
- function callInPromiseJob(handler, args, thisValue = void 0) {
139918
+ function callInPromiseJob(handler, args, thisValue = void 0, completion) {
140265
139919
  return runPromiseJob(async () => {
140266
- let result = handler.call(args, { stack: [], thisValue });
140267
- if (handler.async !== true) result = await result;
140268
- if (isSandboxPromise(result) && result.synchronousPrefix !== void 0) {
140269
- await result.synchronousPrefix;
139920
+ try {
139921
+ let result = handler.call(args, { stack: [], thisValue });
139922
+ if (handler.async !== true) result = await result;
139923
+ if (isSandboxPromise(result) && result.synchronousPrefix !== void 0) {
139924
+ await result.synchronousPrefix;
139925
+ }
139926
+ completion?.fulfilled(result);
139927
+ return { value: result };
139928
+ } catch (error3) {
139929
+ if (completion === void 0) throw error3;
139930
+ completion.rejected(error3);
139931
+ return { value: void 0 };
140270
139932
  }
140271
- return { value: result };
140272
139933
  });
140273
139934
  }
140274
- function resolveReactionResult(result, budget, self) {
140275
- return Promise.resolve(result).then((resolved) => {
140276
- if (isSelfResolution(resolved, self)) {
140277
- return Promise.reject({
140278
- message: "Promise cannot resolve to itself.",
140279
- name: "TypeError"
140280
- });
140281
- }
140282
- return resolveSandboxValue(resolved, { budget });
139935
+ function resolvePromiseResult(result, budget, self) {
139936
+ if (isPromiseLike3(result)) {
139937
+ return Promise.resolve(result).then((resolved) => resolvePromiseResult(resolved, budget, self));
139938
+ }
139939
+ if (isSelfResolution(result, self)) {
139940
+ return Promise.reject(
139941
+ createSubsetErrorValue("TypeError", "Promise cannot resolve to itself.", [], budget)
139942
+ );
139943
+ }
139944
+ if (!isSandboxPromise(result)) return resolveSandboxValue(result, { budget, self });
139945
+ const then = getPromiseMember("then", budget);
139946
+ if (!isSandboxClosure(then)) return Promise.resolve(result);
139947
+ return new Promise((resolve17, reject) => {
139948
+ let settled = false;
139949
+ const settle = (state, value) => {
139950
+ if (settled) return;
139951
+ settled = true;
139952
+ try {
139953
+ if (state === "rejected") reject(budgetSandboxValue(value, budget));
139954
+ else if (isSandboxPromise(value) || getThenable(value) !== void 0) {
139955
+ resolve17(resolvePromiseResult(value, budget, self));
139956
+ } else {
139957
+ resolve17(budgetSandboxValue(value, budget));
139958
+ }
139959
+ } catch (error3) {
139960
+ reject(error3);
139961
+ }
139962
+ };
139963
+ runPromiseJob(async () => {
139964
+ try {
139965
+ const completion = await callPromiseClosure(
139966
+ then,
139967
+ [
139968
+ createSandboxClosure({
139969
+ sandbox: true,
139970
+ call: ([value]) => {
139971
+ settle("fulfilled", value);
139972
+ return void 0;
139973
+ }
139974
+ }),
139975
+ createSandboxClosure({
139976
+ sandbox: true,
139977
+ call: ([reason]) => {
139978
+ settle("rejected", reason);
139979
+ return void 0;
139980
+ }
139981
+ })
139982
+ ],
139983
+ result,
139984
+ budget
139985
+ );
139986
+ if (isSandboxPromise(completion)) {
139987
+ completion.promise.catch((reason) => {
139988
+ if (reason instanceof SandboxError && (reason.code === "budgetExceeded" || reason.code === "reentry")) {
139989
+ reject(reason);
139990
+ }
139991
+ });
139992
+ }
139993
+ } catch (error3) {
139994
+ settle("rejected", error3);
139995
+ }
139996
+ }).catch(reject);
140283
139997
  });
140284
139998
  }
140285
139999
  function isSelfResolution(result, self) {
@@ -140295,7 +140009,7 @@ function getThenable(value) {
140295
140009
  function budgetIfNeeded(value, budget) {
140296
140010
  return budget === void 0 ? value : budgetSandboxValue(value, budget);
140297
140011
  }
140298
- function allocateSandboxValue2(value, budget, seen) {
140012
+ function allocateSandboxValue(value, budget, seen) {
140299
140013
  if (typeof value === "string") {
140300
140014
  budget.allocateString(value);
140301
140015
  return;
@@ -140307,7 +140021,7 @@ function allocateSandboxValue2(value, budget, seen) {
140307
140021
  }
140308
140022
  seen.add(value);
140309
140023
  for (const entry of value) {
140310
- allocateSandboxValue2(entry, budget, seen);
140024
+ allocateSandboxValue(entry, budget, seen);
140311
140025
  }
140312
140026
  return;
140313
140027
  }
@@ -140319,100 +140033,137 @@ function allocateSandboxValue2(value, budget, seen) {
140319
140033
  }
140320
140034
  seen.add(value);
140321
140035
  for (const entry of Object.values(value)) {
140322
- allocateSandboxValue2(entry, budget, seen);
140036
+ allocateSandboxValue(entry, budget, seen);
140323
140037
  }
140324
140038
  }
140325
140039
  function isPromiseLike3(value) {
140326
140040
  return typeof value === "object" && value !== null && "then" in value && typeof value.then === "function" && !isSandboxClosure(value) && !isSandboxPromise(value);
140327
140041
  }
140042
+ var promiseConstructors, intrinsicPromiseConstructors, promisePrototypes;
140328
140043
  var init_promise = __esm({
140329
140044
  "packages/safejs/src/interp/promise.ts"() {
140330
140045
  "use strict";
140046
+ init_budget2();
140331
140047
  init_exceptions();
140048
+ init_iteration();
140332
140049
  init_jobs4();
140333
140050
  init_promise_tracker();
140334
140051
  init_values();
140052
+ promiseConstructors = /* @__PURE__ */ new WeakSet();
140053
+ intrinsicPromiseConstructors = /* @__PURE__ */ new WeakMap();
140054
+ promisePrototypes = /* @__PURE__ */ new WeakMap();
140335
140055
  }
140336
140056
  });
140337
140057
 
140338
140058
  // packages/safejs/src/interp/cancel.ts
140059
+ import { AsyncLocalStorage as AsyncLocalStorage6 } from "node:async_hooks";
140060
+ function withCancellationSignal(signal, task) {
140061
+ return activeCancellation.run({ signal, host: false }, task);
140062
+ }
140063
+ function invokeCancelableClosure(closure, operation, args, context, construct = false) {
140064
+ assertPromiseExecutionAllowed();
140065
+ const active = activeCancellation.getStore();
140066
+ if (active === void 0) return operation(args, context);
140067
+ if (closure.sandbox === true) {
140068
+ return activeCancellation.run(
140069
+ { signal: active.signal, host: false },
140070
+ () => operation(args, context)
140071
+ );
140072
+ }
140073
+ const signal = active.signal;
140074
+ const managed = signal !== void 0 && closure.cancellationSignal === signal;
140075
+ if (signal?.aborted && !managed) {
140076
+ if (!construct && closure.async === true)
140077
+ return createRejectedSandboxPromise2(readAbortReason(signal));
140078
+ throw readAbortReason(signal);
140079
+ }
140080
+ return activeCancellation.run({ signal, host: true }, () => {
140081
+ const result = operation(args, context);
140082
+ if (signal === void 0 || managed) return result;
140083
+ if (isPromiseLike4(result))
140084
+ return awaitWithSignal(result, signal).then((value) => {
140085
+ registerCancelablePromises(value, signal);
140086
+ return value;
140087
+ });
140088
+ registerCancelablePromises(result, signal);
140089
+ return result;
140090
+ });
140091
+ }
140339
140092
  function wrapCancelableBindings(bindings, signal) {
140340
- if (signal === void 0) {
140341
- return bindings;
140342
- }
140343
- return wrapCancelableValue(bindings, signal, /* @__PURE__ */ new WeakMap());
140093
+ if (signal !== void 0) registerCancelablePromises(bindings, signal);
140094
+ return bindings;
140344
140095
  }
140345
- function wrapCancelableValue(value, signal, seen) {
140346
- if (typeof value !== "object" || value === null) {
140347
- return value;
140348
- }
140349
- const existing = seen.get(value);
140350
- if (existing !== void 0) {
140351
- return existing;
140096
+ function registerPromiseCancellation(promise) {
140097
+ const active = activeCancellation.getStore();
140098
+ if (active?.host === false) sandboxPromises.add(promise);
140099
+ else if (active?.signal !== void 0) managePromiseCancellation(promise, active.signal);
140100
+ }
140101
+ function readPromiseCancellation(promise, original) {
140102
+ const signal = activeCancellation.getStore()?.signal;
140103
+ return signal === void 0 ? original : cancelableOutcomes.get(promise)?.get(signal) ?? original;
140104
+ }
140105
+ function managePromiseCancellation(promise, signal) {
140106
+ let outcomes = cancelableOutcomes.get(promise);
140107
+ if (outcomes?.has(signal)) return;
140108
+ if (outcomes === void 0) {
140109
+ outcomes = /* @__PURE__ */ new WeakMap();
140110
+ cancelableOutcomes.set(promise, outcomes);
140352
140111
  }
140353
- if (isSandboxClosure(value)) {
140354
- const wrapped2 = createSandboxClosure({
140355
- ...value.async === true ? { async: true } : {},
140356
- call: (args, context) => {
140357
- if (signal.aborted) {
140358
- if (value.async === true) {
140359
- return createRejectedSandboxPromise2(readAbortReason(signal));
140360
- }
140361
- throw readAbortReason(signal);
140362
- }
140363
- return wrapCancelableResult(value.call(args, context), signal, seen);
140364
- },
140365
- name: value.name
140366
- });
140367
- seen.set(value, wrapped2);
140368
- return wrapped2;
140112
+ const outcome = awaitWithSignal(promise.promise, signal);
140113
+ outcomes.set(signal, outcome);
140114
+ trackSandboxPromise(promise, outcome);
140115
+ }
140116
+ function registerCancelablePromises(value, signal) {
140117
+ const seen = /* @__PURE__ */ new WeakSet();
140118
+ const pending = [value];
140119
+ while (pending.length > 0) {
140120
+ const current = pending.pop();
140121
+ if (typeof current !== "object" || current === null || seen.has(current)) continue;
140122
+ seen.add(current);
140123
+ if (isSandboxPromise(current)) {
140124
+ if (!sandboxPromises.has(current)) managePromiseCancellation(current, signal);
140125
+ continue;
140126
+ }
140127
+ if (isSandboxClosure(current)) {
140128
+ if (current.properties !== void 0) pending.push(current.properties);
140129
+ } else if (isSandboxMap(current)) {
140130
+ for (const [key3, entry] of current.entries) pending.push(key3, entry);
140131
+ } else if (isSandboxSet(current)) {
140132
+ for (const entry of current.values) pending.push(entry);
140133
+ } else {
140134
+ for (const descriptor of Object.values(Object.getOwnPropertyDescriptors(current))) {
140135
+ if ("value" in descriptor) pending.push(descriptor.value);
140136
+ }
140137
+ }
140369
140138
  }
140139
+ }
140140
+ function awaitSandboxValue(value, signal, budget) {
140141
+ let resolved;
140370
140142
  if (isSandboxPromise(value)) {
140371
140143
  observeSandboxPromise(value);
140372
- const wrapped2 = createSandboxPromise(wrapCancelablePromise(value.promise, signal, seen), {
140373
- trackReplay: false,
140374
- ...value.synchronousPrefix === void 0 ? {} : { synchronousPrefix: value.synchronousPrefix },
140375
- ...value.hostCall === void 0 ? {} : { hostCall: value.hostCall },
140376
- ...value.hostCallJournal === void 0 ? {} : { hostCallJournal: value.hostCallJournal },
140377
- ...value.span === void 0 ? {} : { span: value.span }
140144
+ const outcome = signal === void 0 ? value.promise : cancelableOutcomes.get(value)?.get(signal) ?? value.promise;
140145
+ resolved = new Promise((resolve17, reject) => {
140146
+ const detach = onFatalPromiseRejection(reject);
140147
+ const complete = (state, result) => {
140148
+ detach?.();
140149
+ try {
140150
+ consumeSettledHostCall(value);
140151
+ if (state === "fulfilled") resolve17(result);
140152
+ else reject(result);
140153
+ } catch (error3) {
140154
+ reject(error3);
140155
+ }
140156
+ };
140157
+ outcome.then(
140158
+ (result) => complete("fulfilled", result),
140159
+ (reason) => complete("rejected", reason)
140160
+ );
140378
140161
  });
140379
- seen.set(value, wrapped2);
140380
- cancellationSignals.set(wrapped2, signal);
140381
- return wrapped2;
140382
- }
140383
- if (Array.isArray(value)) {
140384
- const wrapped2 = new Array(value.length);
140385
- seen.set(value, wrapped2);
140386
- for (let index = 0; index < value.length; index += 1) {
140387
- wrapped2[index] = wrapCancelableValue(value[index], signal, seen);
140388
- }
140389
- return wrapped2;
140390
- }
140391
- const wrapped = Object.create(Object.getPrototypeOf(value));
140392
- seen.set(value, wrapped);
140393
- for (const [key3, entry] of Object.entries(value)) {
140394
- wrapped[key3] = wrapCancelableValue(entry, signal, seen);
140395
- }
140396
- return wrapped;
140397
- }
140398
- function wrapCancelableResult(result, signal, seen) {
140399
- if (!isPromiseLike4(result)) {
140400
- return wrapCancelableValue(result, signal, seen);
140162
+ } else {
140163
+ resolved = resolveSandboxValue(value, { budget });
140401
140164
  }
140402
- return wrapCancelablePromise(result, signal, seen);
140403
- }
140404
- function wrapCancelablePromise(promise, signal, seen) {
140405
- return awaitWithSignal(promise, signal).then(
140406
- (value) => wrapCancelableValue(value, signal, seen),
140407
- (reason) => {
140408
- if (signal.aborted && reason === signal.reason) throw reason;
140409
- throw wrapCancelableUnknown(reason, signal, seen);
140410
- }
140411
- );
140412
- }
140413
- function awaitSandboxValue(value, signal) {
140414
- const resolved = resolveSandboxValue(value);
140415
- return isSandboxPromise(value) && (value.synchronousPrefix !== void 0 || cancellationSignals.get(value) === signal) ? resolved : awaitWithSignal(resolved, signal);
140165
+ const pending = isSandboxPromise(value) && (value.synchronousPrefix !== void 0 || signal !== void 0 && cancelableOutcomes.get(value)?.has(signal)) ? resolved : awaitWithSignal(resolved, signal);
140166
+ return isSandboxPromise(value) ? pending : interruptOnFatalPromiseRejection(pending);
140416
140167
  }
140417
140168
  function awaitWithSignal(promise, signal) {
140418
140169
  if (signal === void 0) return Promise.resolve(promise);
@@ -140455,15 +140206,6 @@ function awaitWithSignal(promise, signal) {
140455
140206
  );
140456
140207
  });
140457
140208
  }
140458
- function wrapCancelableUnknown(value, signal, seen) {
140459
- if (value === null || value === void 0 || typeof value === "string" || typeof value === "number" || typeof value === "boolean") {
140460
- return value;
140461
- }
140462
- if (isSandboxClosure(value) || isSandboxPromise(value) || Array.isArray(value) || typeof value === "object" && value !== null) {
140463
- return wrapCancelableValue(value, signal, seen);
140464
- }
140465
- return value;
140466
- }
140467
140209
  function readAbortReason(signal) {
140468
140210
  return signal.reason ?? createAbortError11();
140469
140211
  }
@@ -140484,9 +140226,9 @@ function createRejectedSandboxPromise2(reason) {
140484
140226
  return createSandboxPromise(promise);
140485
140227
  }
140486
140228
  function isPromiseLike4(value) {
140487
- return typeof value === "object" && value !== null && "then" in value;
140229
+ return typeof value === "object" && value !== null && "then" in value && typeof value.then === "function";
140488
140230
  }
140489
- var cancellationSignals;
140231
+ var activeCancellation, sandboxPromises, cancelableOutcomes;
140490
140232
  var init_cancel2 = __esm({
140491
140233
  "packages/safejs/src/interp/cancel.ts"() {
140492
140234
  "use strict";
@@ -140494,7 +140236,804 @@ var init_cancel2 = __esm({
140494
140236
  init_promise_tracker();
140495
140237
  init_shape();
140496
140238
  init_promise();
140497
- cancellationSignals = /* @__PURE__ */ new WeakMap();
140239
+ activeCancellation = new AsyncLocalStorage6();
140240
+ sandboxPromises = /* @__PURE__ */ new WeakSet();
140241
+ cancelableOutcomes = /* @__PURE__ */ new WeakMap();
140242
+ }
140243
+ });
140244
+
140245
+ // packages/safejs/src/interp/values.ts
140246
+ function createSandboxClosure(input) {
140247
+ const closure = {
140248
+ kind: "fn",
140249
+ call: (args, context) => invokeCancelableClosure(closure, input.call, args, context),
140250
+ name: input.name,
140251
+ ...input.construct === void 0 ? {} : {
140252
+ construct: (args, context) => invokeCancelableClosure(closure, input.construct, args, context, true)
140253
+ },
140254
+ ...input.async === true ? { async: true } : {}
140255
+ };
140256
+ Object.defineProperty(closure, sandboxClosureBrand, {
140257
+ enumerable: false,
140258
+ value: true
140259
+ });
140260
+ if (input.sandbox === true) {
140261
+ Object.defineProperty(closure, "sandbox", { value: true });
140262
+ }
140263
+ if (input.boundTarget !== void 0) {
140264
+ Object.defineProperty(closure, "boundTarget", { value: input.boundTarget });
140265
+ }
140266
+ if (input.cancellationSignal !== void 0) {
140267
+ Object.defineProperty(closure, "cancellationSignal", {
140268
+ value: input.cancellationSignal
140269
+ });
140270
+ }
140271
+ if (input.properties !== void 0) {
140272
+ Object.defineProperty(closure, "properties", {
140273
+ enumerable: false,
140274
+ value: Object.freeze(
140275
+ typeof input.properties === "function" ? input.properties(closure) : input.properties
140276
+ )
140277
+ });
140278
+ }
140279
+ if (input.retainedValues !== void 0) {
140280
+ Object.defineProperty(closure, sandboxRetainedValues, {
140281
+ value: input.retainedValues
140282
+ });
140283
+ }
140284
+ return Object.freeze(closure);
140285
+ }
140286
+ function createSandboxPromise(promise, metadata = {}) {
140287
+ const original = metadata.trackReplay === false ? promise : promiseReplayContext.getStore()?.track(promise) ?? promise;
140288
+ const sandboxPromise = {
140289
+ kind: "promise",
140290
+ get promise() {
140291
+ return readPromiseCancellation(sandboxPromise, original);
140292
+ }
140293
+ };
140294
+ Object.defineProperty(sandboxPromise, sandboxPromiseBrand, {
140295
+ enumerable: false,
140296
+ value: true
140297
+ });
140298
+ Object.defineProperty(sandboxPromise, Symbol.toStringTag, { value: "Promise" });
140299
+ if (metadata.span !== void 0) {
140300
+ Object.defineProperty(sandboxPromise, "span", {
140301
+ value: metadata.span
140302
+ });
140303
+ }
140304
+ if (metadata.synchronousPrefix !== void 0) {
140305
+ Object.defineProperty(sandboxPromise, "synchronousPrefix", {
140306
+ value: metadata.synchronousPrefix
140307
+ });
140308
+ }
140309
+ if (metadata.hostCall !== void 0) {
140310
+ Object.defineProperty(sandboxPromise, "hostCall", { value: metadata.hostCall });
140311
+ }
140312
+ if (metadata.hostCallJournal !== void 0) {
140313
+ Object.defineProperty(sandboxPromise, "hostCallJournal", {
140314
+ value: metadata.hostCallJournal
140315
+ });
140316
+ }
140317
+ trackSandboxPromise(sandboxPromise);
140318
+ registerPromiseCancellation(sandboxPromise);
140319
+ return Object.freeze(sandboxPromise);
140320
+ }
140321
+ function createSandboxGenerator(channel, metadata = void 0) {
140322
+ const generator = {
140323
+ kind: "generator",
140324
+ state: "start",
140325
+ channel,
140326
+ ...metadata
140327
+ };
140328
+ Object.defineProperty(generator, sandboxGeneratorBrand, {
140329
+ enumerable: false,
140330
+ value: true
140331
+ });
140332
+ return generator;
140333
+ }
140334
+ function createSandboxMap(entries = []) {
140335
+ const map = {};
140336
+ Object.defineProperties(map, {
140337
+ kind: {
140338
+ value: "map"
140339
+ },
140340
+ entries: {
140341
+ value: new Map(entries)
140342
+ }
140343
+ });
140344
+ Object.defineProperty(map, sandboxMapBrand, {
140345
+ enumerable: false,
140346
+ value: true
140347
+ });
140348
+ return Object.freeze(map);
140349
+ }
140350
+ function createSandboxSet(values = []) {
140351
+ const set = {};
140352
+ Object.defineProperties(set, {
140353
+ kind: {
140354
+ value: "set"
140355
+ },
140356
+ values: {
140357
+ value: new Set(values)
140358
+ }
140359
+ });
140360
+ Object.defineProperty(set, sandboxSetBrand, {
140361
+ enumerable: false,
140362
+ value: true
140363
+ });
140364
+ return Object.freeze(set);
140365
+ }
140366
+ function createSandboxRegex(source, flags = "", lastIndex = 0) {
140367
+ const regex = { kind: "regex", source, flags, lastIndex };
140368
+ Object.defineProperties(regex, {
140369
+ [sandboxRegexBrand]: { value: true },
140370
+ [sandboxRegexPattern]: { value: parseRegex(source, flags) }
140371
+ });
140372
+ return Object.seal(regex);
140373
+ }
140374
+ function getSandboxRegexPattern(regex) {
140375
+ return regex[sandboxRegexPattern];
140376
+ }
140377
+ function isSandboxClosure(value) {
140378
+ return typeof value === "object" && value !== null && sandboxClosureBrand in value;
140379
+ }
140380
+ function isSandboxMap(value) {
140381
+ return typeof value === "object" && value !== null && sandboxMapBrand in value;
140382
+ }
140383
+ function isSandboxPromise(value) {
140384
+ return typeof value === "object" && value !== null && sandboxPromiseBrand in value;
140385
+ }
140386
+ function isSandboxSet(value) {
140387
+ return typeof value === "object" && value !== null && sandboxSetBrand in value;
140388
+ }
140389
+ function isSandboxGenerator(value) {
140390
+ return typeof value === "object" && value !== null && sandboxGeneratorBrand in value;
140391
+ }
140392
+ function isSandboxRegex(value) {
140393
+ return typeof value === "object" && value !== null && sandboxRegexBrand in value;
140394
+ }
140395
+ function deepCopyToSandbox(value) {
140396
+ return copyToSandbox(value, {
140397
+ seen: /* @__PURE__ */ new WeakMap()
140398
+ });
140399
+ }
140400
+ function cloneSandboxValue(value) {
140401
+ return copyToSandbox(
140402
+ value,
140403
+ {
140404
+ seen: /* @__PURE__ */ new WeakMap()
140405
+ },
140406
+ "<root>",
140407
+ true
140408
+ );
140409
+ }
140410
+ function allocateProducedSandboxValue(value, budget) {
140411
+ allocateSandboxValue2(value, budget, /* @__PURE__ */ new WeakSet());
140412
+ return value;
140413
+ }
140414
+ function measureSandboxData(values, options = {}) {
140415
+ const seen = /* @__PURE__ */ new WeakSet();
140416
+ let usage = 0;
140417
+ const visit = (value) => {
140418
+ if (typeof value === "string") {
140419
+ usage += value.length;
140420
+ return;
140421
+ }
140422
+ if (typeof value !== "object" || value === null) return;
140423
+ if (seen.has(value)) return;
140424
+ seen.add(value);
140425
+ usage += 1;
140426
+ if (Array.isArray(value)) {
140427
+ usage += value.length;
140428
+ for (const entry of value) visit(entry);
140429
+ return;
140430
+ }
140431
+ if (isSandboxMap(value)) {
140432
+ usage += value.entries.size;
140433
+ for (const [key3, entry] of value.entries) {
140434
+ visit(key3);
140435
+ visit(entry);
140436
+ }
140437
+ return;
140438
+ }
140439
+ if (isSandboxSet(value)) {
140440
+ usage += value.values.size;
140441
+ for (const entry of value.values) visit(entry);
140442
+ return;
140443
+ }
140444
+ if (isSandboxClosure(value)) {
140445
+ if (options.ignoreClosures) return;
140446
+ if (value.properties !== void 0) visit(value.properties);
140447
+ if (!options.ignoreClosureCaptures)
140448
+ for (const retained of value[sandboxRetainedValues]?.() ?? []) visit(retained);
140449
+ return;
140450
+ }
140451
+ if (isSandboxGenerator(value)) {
140452
+ const snapshot2 = value.channel.snapshot();
140453
+ usage += snapshot2.sent.length;
140454
+ for (const completion of snapshot2.sent) visit(completion.value);
140455
+ return;
140456
+ }
140457
+ if (isSandboxPromise(value)) return;
140458
+ if (isSandboxRegex(value)) {
140459
+ usage += value.source.length + value.flags.length;
140460
+ return;
140461
+ }
140462
+ const entries = isSandboxArguments(value) ? getSandboxArgumentEntries(value) : Object.entries(value);
140463
+ usage += entries.length;
140464
+ for (const [key3, entry] of entries) {
140465
+ usage += key3.length;
140466
+ visit(entry);
140467
+ }
140468
+ };
140469
+ for (const value of values) visit(value);
140470
+ return usage;
140471
+ }
140472
+ function deepCopyFromSandbox(value, options = {}) {
140473
+ return copyFromSandbox(
140474
+ value,
140475
+ {
140476
+ seen: /* @__PURE__ */ new WeakMap()
140477
+ },
140478
+ "<root>",
140479
+ options
140480
+ );
140481
+ }
140482
+ function copyToSandbox(value, state, path189 = "<root>", cloneSandboxCollections = false, depth = 0) {
140483
+ assertSandboxDataDepth(depth);
140484
+ if (isSandboxPrimitive(value)) {
140485
+ return value;
140486
+ }
140487
+ if (isSandboxClosure(value) || isSandboxGenerator(value) || isSandboxRegex(value) || isSandboxPromise(value)) {
140488
+ return value;
140489
+ }
140490
+ if (isSandboxMap(value)) {
140491
+ if (!cloneSandboxCollections) return value;
140492
+ const existing = state.seen.get(value);
140493
+ if (existing !== void 0) return existing;
140494
+ const copy = createSandboxMap();
140495
+ state.seen.set(value, copy);
140496
+ for (const [key3, entry] of value.entries) {
140497
+ copy.entries.set(
140498
+ copyToSandbox(key3, state, `${path189}.<key>`, true, depth + 1),
140499
+ copyToSandbox(entry, state, `${path189}.<value>`, true, depth + 1)
140500
+ );
140501
+ }
140502
+ return copy;
140503
+ }
140504
+ if (isSandboxSet(value)) {
140505
+ if (!cloneSandboxCollections) return value;
140506
+ const existing = state.seen.get(value);
140507
+ if (existing !== void 0) return existing;
140508
+ const copy = createSandboxSet();
140509
+ state.seen.set(value, copy);
140510
+ for (const entry of value.values) {
140511
+ copy.values.add(copyToSandbox(entry, state, `${path189}.<value>`, true, depth + 1));
140512
+ }
140513
+ return copy;
140514
+ }
140515
+ if (isHostPromise(value)) {
140516
+ const promise = Promise.resolve(value).then(
140517
+ (resolved) => copyToSandbox(resolved, { seen: /* @__PURE__ */ new WeakMap() }),
140518
+ (reason) => Promise.reject(copyToSandbox(reason, { seen: /* @__PURE__ */ new WeakMap() }))
140519
+ );
140520
+ const sandboxPromise = createSandboxPromise(promise);
140521
+ const span = getBoundOtelSpan(value);
140522
+ if (span !== void 0) {
140523
+ bindOtelSpan(promise, span);
140524
+ bindOtelSpan(sandboxPromise, span);
140525
+ }
140526
+ return sandboxPromise;
140527
+ }
140528
+ if (value instanceof Map) {
140529
+ const existing = state.seen.get(value);
140530
+ if (existing !== void 0) {
140531
+ return existing;
140532
+ }
140533
+ const copy = createSandboxMap();
140534
+ state.seen.set(value, copy);
140535
+ for (const [key3, entry] of value) {
140536
+ copy.entries.set(
140537
+ copyToSandbox(key3, state, `${path189}.<key>`, cloneSandboxCollections, depth + 1),
140538
+ copyToSandbox(entry, state, `${path189}.<value>`, cloneSandboxCollections, depth + 1)
140539
+ );
140540
+ }
140541
+ return copy;
140542
+ }
140543
+ if (value instanceof Set) {
140544
+ const existing = state.seen.get(value);
140545
+ if (existing !== void 0) {
140546
+ return existing;
140547
+ }
140548
+ const copy = createSandboxSet();
140549
+ state.seen.set(value, copy);
140550
+ for (const entry of value) {
140551
+ copy.values.add(
140552
+ copyToSandbox(entry, state, `${path189}.<value>`, cloneSandboxCollections, depth + 1)
140553
+ );
140554
+ }
140555
+ return copy;
140556
+ }
140557
+ if (isPlainArray(value)) {
140558
+ const existing = state.seen.get(value);
140559
+ if (existing !== void 0) {
140560
+ return existing;
140561
+ }
140562
+ const copy = new Array(value.length);
140563
+ state.seen.set(value, copy);
140564
+ for (const entry of getEnumerableArrayEntries(value, path189)) {
140565
+ defineOwnDataProperty(
140566
+ copy,
140567
+ entry.key,
140568
+ copyToSandbox(
140569
+ entry.value,
140570
+ state,
140571
+ joinArrayPath(path189, entry.key),
140572
+ cloneSandboxCollections,
140573
+ depth + 1
140574
+ )
140575
+ );
140576
+ }
140577
+ return copy;
140578
+ }
140579
+ if (isSandboxArguments(value)) {
140580
+ const existing = state.seen.get(value);
140581
+ if (existing !== void 0) return existing;
140582
+ const copy = createSandboxArguments([]);
140583
+ state.seen.set(value, copy);
140584
+ copySandboxArgumentProperties(
140585
+ value,
140586
+ copy,
140587
+ (entry, key3) => copyToSandbox(entry, state, joinPath(path189, key3), cloneSandboxCollections, depth + 1)
140588
+ );
140589
+ return copy;
140590
+ }
140591
+ if (isPlainObject10(value)) {
140592
+ const existing = state.seen.get(value);
140593
+ if (existing !== void 0) {
140594
+ return existing;
140595
+ }
140596
+ const copy = createPlainObject(true);
140597
+ state.seen.set(value, copy);
140598
+ for (const entry of getEnumerableObjectEntries(value, path189)) {
140599
+ defineOwnDataProperty(
140600
+ copy,
140601
+ entry.key,
140602
+ copyToSandbox(
140603
+ entry.value,
140604
+ state,
140605
+ joinPath(path189, entry.key),
140606
+ cloneSandboxCollections,
140607
+ depth + 1
140608
+ )
140609
+ );
140610
+ }
140611
+ return copy;
140612
+ }
140613
+ throw new TypeError(`Unsupported sandbox value at ${path189}: ${describeValue(value)}`);
140614
+ }
140615
+ function copyFromSandbox(value, state, path189 = "<root>", options, depth = 0) {
140616
+ assertSandboxDataDepth(depth);
140617
+ if (isSandboxPrimitive(value)) {
140618
+ return value;
140619
+ }
140620
+ if (isSandboxClosure(value)) {
140621
+ if (options.wrapClosure === void 0) {
140622
+ throw new TypeError(
140623
+ "Sandbox closures cannot cross into host values without an explicit wrapper."
140624
+ );
140625
+ }
140626
+ const existing = state.seen.get(value);
140627
+ if (existing !== void 0) {
140628
+ return existing;
140629
+ }
140630
+ const wrapped = options.wrapClosure(value);
140631
+ state.seen.set(value, wrapped);
140632
+ return wrapped;
140633
+ }
140634
+ if (isSandboxPromise(value)) {
140635
+ observeSandboxPromise(value);
140636
+ return value.promise.then(
140637
+ (resolved) => copyFromSandbox(resolved, { seen: /* @__PURE__ */ new WeakMap() }, "<root>", options),
140638
+ (reason) => Promise.reject(
140639
+ reason instanceof SandboxError ? reason : copyFromSandbox(reason, { seen: /* @__PURE__ */ new WeakMap() }, "<root>", options)
140640
+ )
140641
+ );
140642
+ }
140643
+ if (isSandboxGenerator(value)) {
140644
+ throw new TypeError("Sandbox generators cannot cross into host values.");
140645
+ }
140646
+ if (isSandboxRegex(value)) {
140647
+ const regex = new RegExp(value.source, value.flags);
140648
+ regex.lastIndex = value.lastIndex;
140649
+ return regex;
140650
+ }
140651
+ if (isSandboxMap(value)) {
140652
+ const existing = state.seen.get(value);
140653
+ if (existing !== void 0) {
140654
+ return existing;
140655
+ }
140656
+ const copy = /* @__PURE__ */ new Map();
140657
+ state.seen.set(value, copy);
140658
+ for (const [key3, entry] of value.entries) {
140659
+ copy.set(
140660
+ copyFromSandbox(key3, state, `${path189}.<key>`, options, depth + 1),
140661
+ copyFromSandbox(entry, state, `${path189}.<value>`, options, depth + 1)
140662
+ );
140663
+ }
140664
+ return copy;
140665
+ }
140666
+ if (isSandboxSet(value)) {
140667
+ const existing = state.seen.get(value);
140668
+ if (existing !== void 0) {
140669
+ return existing;
140670
+ }
140671
+ const copy = /* @__PURE__ */ new Set();
140672
+ state.seen.set(value, copy);
140673
+ for (const entry of value.values) {
140674
+ copy.add(copyFromSandbox(entry, state, `${path189}.<value>`, options, depth + 1));
140675
+ }
140676
+ return copy;
140677
+ }
140678
+ if (isPlainArray(value)) {
140679
+ const existing = state.seen.get(value);
140680
+ if (existing !== void 0) {
140681
+ return existing;
140682
+ }
140683
+ const copy = new Array(value.length);
140684
+ state.seen.set(value, copy);
140685
+ for (const entry of getEnumerableArrayEntries(value, path189)) {
140686
+ defineOwnDataProperty(
140687
+ copy,
140688
+ entry.key,
140689
+ copyFromSandbox(entry.value, state, joinArrayPath(path189, entry.key), options, depth + 1)
140690
+ );
140691
+ }
140692
+ return copy;
140693
+ }
140694
+ if (isSandboxArguments(value)) {
140695
+ const existing = state.seen.get(value);
140696
+ if (existing !== void 0) return existing;
140697
+ const copy = createSandboxArguments([]);
140698
+ state.seen.set(value, copy);
140699
+ copySandboxArgumentProperties(
140700
+ value,
140701
+ copy,
140702
+ (entry, key3) => copyFromSandbox(entry, state, joinPath(path189, key3), options, depth + 1)
140703
+ );
140704
+ return copy;
140705
+ }
140706
+ if (isPlainObject10(value)) {
140707
+ const existing = state.seen.get(value);
140708
+ if (existing !== void 0) {
140709
+ return existing;
140710
+ }
140711
+ const copy = createPlainObject(Object.getPrototypeOf(value) === null);
140712
+ state.seen.set(value, copy);
140713
+ for (const entry of getEnumerableObjectEntries(value, path189)) {
140714
+ defineOwnDataProperty(
140715
+ copy,
140716
+ entry.key,
140717
+ copyFromSandbox(entry.value, state, joinPath(path189, entry.key), options, depth + 1)
140718
+ );
140719
+ }
140720
+ return copy;
140721
+ }
140722
+ throw new TypeError(`Unsupported sandbox value at ${path189}: ${describeValue(value)}`);
140723
+ }
140724
+ function isSandboxPrimitive(value) {
140725
+ return value === null || value === void 0 || typeof value === "string" || typeof value === "number" || typeof value === "boolean";
140726
+ }
140727
+ function isHostPromise(value) {
140728
+ return value instanceof Promise;
140729
+ }
140730
+ function allocateSandboxValue2(value, budget, seen) {
140731
+ if (typeof value === "string") {
140732
+ budget.allocateString(value);
140733
+ return;
140734
+ }
140735
+ if (Array.isArray(value)) {
140736
+ if (seen.has(value)) {
140737
+ return;
140738
+ }
140739
+ seen.add(value);
140740
+ budget.allocateArrayLength(value.length);
140741
+ for (const entry of value) {
140742
+ allocateSandboxValue2(entry, budget, seen);
140743
+ }
140744
+ return;
140745
+ }
140746
+ if (isSandboxMap(value)) {
140747
+ if (seen.has(value)) {
140748
+ return;
140749
+ }
140750
+ seen.add(value);
140751
+ budget.allocateCollectionEntries(value.entries.size);
140752
+ for (const [key3, entry] of value.entries) {
140753
+ allocateSandboxValue2(key3, budget, seen);
140754
+ allocateSandboxValue2(entry, budget, seen);
140755
+ }
140756
+ return;
140757
+ }
140758
+ if (isSandboxSet(value)) {
140759
+ if (seen.has(value)) {
140760
+ return;
140761
+ }
140762
+ seen.add(value);
140763
+ budget.allocateCollectionEntries(value.values.size);
140764
+ for (const entry of value.values) {
140765
+ allocateSandboxValue2(entry, budget, seen);
140766
+ }
140767
+ return;
140768
+ }
140769
+ if (typeof value !== "object" || value === null || isSandboxClosure(value) || isSandboxMap(value) || isSandboxSet(value) || isSandboxPromise(value)) {
140770
+ return;
140771
+ }
140772
+ if (seen.has(value)) {
140773
+ return;
140774
+ }
140775
+ seen.add(value);
140776
+ const entries = isSandboxArguments(value) ? getSandboxArgumentEntries(value).map(([, entry]) => entry) : Object.values(value);
140777
+ for (const entry of entries) {
140778
+ allocateSandboxValue2(entry, budget, seen);
140779
+ }
140780
+ }
140781
+ function isPlainObject10(value) {
140782
+ if (typeof value !== "object" || value === null || Array.isArray(value)) {
140783
+ return false;
140784
+ }
140785
+ const prototype = Object.getPrototypeOf(value);
140786
+ return prototype === Object.prototype || prototype === null;
140787
+ }
140788
+ function isPlainArray(value) {
140789
+ return Array.isArray(value) && Object.getPrototypeOf(value) === Array.prototype;
140790
+ }
140791
+ function createPlainObject(useNullPrototype) {
140792
+ return useNullPrototype ? /* @__PURE__ */ Object.create(null) : {};
140793
+ }
140794
+ function defineOwnDataProperty(target, key3, value) {
140795
+ Object.defineProperty(target, key3, {
140796
+ enumerable: true,
140797
+ configurable: true,
140798
+ writable: true,
140799
+ value
140800
+ });
140801
+ }
140802
+ function getEnumerableObjectEntries(value, path189) {
140803
+ const descriptors = Object.getOwnPropertyDescriptors(value);
140804
+ const entries = [];
140805
+ for (const [key3, descriptor] of Object.entries(descriptors)) {
140806
+ if (!descriptor.enumerable) {
140807
+ continue;
140808
+ }
140809
+ if ("get" in descriptor || "set" in descriptor) {
140810
+ throw new TypeError(`Unsupported sandbox value at ${joinPath(path189, key3)}: accessor property`);
140811
+ }
140812
+ entries.push({
140813
+ key: key3,
140814
+ value: descriptor.value
140815
+ });
140816
+ }
140817
+ return entries;
140818
+ }
140819
+ function getEnumerableArrayEntries(value, path189) {
140820
+ const descriptors = Object.getOwnPropertyDescriptors(value);
140821
+ const entries = [];
140822
+ for (const [key3, descriptor] of Object.entries(descriptors)) {
140823
+ if (key3 === "length" || !descriptor.enumerable) {
140824
+ continue;
140825
+ }
140826
+ if ("get" in descriptor || "set" in descriptor) {
140827
+ throw new TypeError(
140828
+ `Unsupported sandbox value at ${joinArrayPath(path189, key3)}: accessor property`
140829
+ );
140830
+ }
140831
+ entries.push({
140832
+ key: key3,
140833
+ value: descriptor.value
140834
+ });
140835
+ }
140836
+ return entries;
140837
+ }
140838
+ function isArrayIndexKey(value) {
140839
+ if (value === "") {
140840
+ return false;
140841
+ }
140842
+ const index = Number(value);
140843
+ return Number.isInteger(index) && index >= 0 && index < 4294967295 && String(index) === value;
140844
+ }
140845
+ function describeValue(value) {
140846
+ if (typeof value === "function") {
140847
+ return "function";
140848
+ }
140849
+ if (typeof value === "bigint" || typeof value === "symbol") {
140850
+ return typeof value;
140851
+ }
140852
+ if (typeof value === "object" && value !== null) {
140853
+ return value.constructor?.name ?? "Object";
140854
+ }
140855
+ return typeof value;
140856
+ }
140857
+ function joinPath(path189, key3) {
140858
+ return path189 === "<root>" ? `<root>.${key3}` : `${path189}.${key3}`;
140859
+ }
140860
+ function joinArrayPath(path189, key3) {
140861
+ return isArrayIndexKey(key3) ? `${path189}[${key3}]` : joinPath(path189, key3);
140862
+ }
140863
+ var sandboxClosureBrand, sandboxGeneratorBrand, sandboxMapBrand, sandboxPromiseBrand, sandboxRegexBrand, sandboxRegexPattern, sandboxSetBrand, sandboxRetainedValues;
140864
+ var init_values = __esm({
140865
+ "packages/safejs/src/interp/values.ts"() {
140866
+ "use strict";
140867
+ init_otel2();
140868
+ init_budget2();
140869
+ init_promise_tracker();
140870
+ init_promise_replay();
140871
+ init_cancel2();
140872
+ init_parse5();
140873
+ init_graph_depth();
140874
+ init_arguments();
140875
+ init_arguments();
140876
+ sandboxClosureBrand = /* @__PURE__ */ Symbol("SandboxClosure");
140877
+ sandboxGeneratorBrand = /* @__PURE__ */ Symbol("SandboxGenerator");
140878
+ sandboxMapBrand = /* @__PURE__ */ Symbol("SandboxMap");
140879
+ sandboxPromiseBrand = /* @__PURE__ */ Symbol("SandboxPromise");
140880
+ sandboxRegexBrand = /* @__PURE__ */ Symbol("SandboxRegex");
140881
+ sandboxRegexPattern = /* @__PURE__ */ Symbol("SandboxRegexPattern");
140882
+ sandboxSetBrand = /* @__PURE__ */ Symbol("SandboxSet");
140883
+ sandboxRetainedValues = /* @__PURE__ */ Symbol("SandboxRetainedValues");
140884
+ }
140885
+ });
140886
+
140887
+ // packages/safejs/src/interp/globals/math.ts
140888
+ function createMathGlobals(options = {}) {
140889
+ const random = options.random ?? Math.random;
140890
+ const mathObject = {
140891
+ E: Math.E,
140892
+ LN2: Math.LN2,
140893
+ LN10: Math.LN10,
140894
+ LOG2E: Math.LOG2E,
140895
+ LOG10E: Math.LOG10E,
140896
+ PI: Math.PI,
140897
+ SQRT1_2: Math.SQRT1_2,
140898
+ SQRT2: Math.SQRT2,
140899
+ random: createSandboxClosure({ sandbox: true, call: () => random(), name: "random" })
140900
+ };
140901
+ for (const [name, method] of Object.entries(mathMethods)) {
140902
+ mathObject[name] = createSandboxClosure({
140903
+ sandbox: true,
140904
+ call: (args) => Reflect.apply(method, Math, args),
140905
+ name
140906
+ });
140907
+ }
140908
+ return {
140909
+ Infinity: Infinity,
140910
+ Math: mathObject,
140911
+ NaN: Number.NaN
140912
+ };
140913
+ }
140914
+ function createSeededRandom(seed) {
140915
+ let state = normalizeSeed(seed);
140916
+ return {
140917
+ next: () => {
140918
+ state = Math.imul(state, 1664525) + 1013904223 >>> 0;
140919
+ return state / 4294967296;
140920
+ },
140921
+ snapshot: () => state,
140922
+ restore: (nextState) => {
140923
+ state = normalizeSeed(nextState);
140924
+ }
140925
+ };
140926
+ }
140927
+ function normalizeSeed(seed) {
140928
+ if (!Number.isFinite(seed)) {
140929
+ throw new TypeError("Seeded random requires a finite numeric seed.");
140930
+ }
140931
+ return Math.trunc(seed) >>> 0;
140932
+ }
140933
+ var mathMethods;
140934
+ var init_math = __esm({
140935
+ "packages/safejs/src/interp/globals/math.ts"() {
140936
+ "use strict";
140937
+ init_values();
140938
+ mathMethods = {
140939
+ abs: Math.abs,
140940
+ acos: Math.acos,
140941
+ acosh: Math.acosh,
140942
+ asin: Math.asin,
140943
+ asinh: Math.asinh,
140944
+ atan: Math.atan,
140945
+ atan2: Math.atan2,
140946
+ atanh: Math.atanh,
140947
+ ceil: Math.ceil,
140948
+ cbrt: Math.cbrt,
140949
+ clz32: Math.clz32,
140950
+ cos: Math.cos,
140951
+ cosh: Math.cosh,
140952
+ exp: Math.exp,
140953
+ expm1: Math.expm1,
140954
+ floor: Math.floor,
140955
+ fround: Math.fround,
140956
+ hypot: Math.hypot,
140957
+ imul: Math.imul,
140958
+ log: Math.log,
140959
+ log1p: Math.log1p,
140960
+ log10: Math.log10,
140961
+ log2: Math.log2,
140962
+ max: Math.max,
140963
+ min: Math.min,
140964
+ pow: Math.pow,
140965
+ round: Math.round,
140966
+ sign: Math.sign,
140967
+ sin: Math.sin,
140968
+ sinh: Math.sinh,
140969
+ sqrt: Math.sqrt,
140970
+ tan: Math.tan,
140971
+ tanh: Math.tanh,
140972
+ trunc: Math.trunc
140973
+ };
140974
+ }
140975
+ });
140976
+
140977
+ // packages/safejs/src/random.ts
140978
+ import { randomInt } from "node:crypto";
140979
+ function createReplayableRandom(options = {}) {
140980
+ const snapshot2 = options.snapshot;
140981
+ const saved = snapshot2?.random;
140982
+ let initialState = options.seed;
140983
+ if (saved !== void 0) {
140984
+ const hasLoopState = typeof snapshot2?.loopIterations === "object" && snapshot2.loopIterations !== null && Object.keys(snapshot2.loopIterations).length > 0;
140985
+ const replaysFromStart = snapshot2?.replay !== void 0 || Array.isArray(snapshot2?.pendingAwaits) && snapshot2.pendingAwaits.length > 0 && !hasLoopState;
140986
+ initialState = replaysFromStart ? saved.initialState ?? saved.seed : saved.resumeState ?? saved.state;
140987
+ }
140988
+ const generator = createSeededRandom(initialState ?? randomInt(4294967296));
140989
+ return { seed: saved?.seed ?? generator.snapshot(), ...generator };
140990
+ }
140991
+ var init_random = __esm({
140992
+ "packages/safejs/src/random.ts"() {
140993
+ "use strict";
140994
+ init_math();
140995
+ }
140996
+ });
140997
+
140998
+ // packages/safejs/src/restore.ts
140999
+ function restore2(snapshot2, options) {
141000
+ assertSnapshotInactive(snapshot2);
141001
+ validateDumpEnvelope(snapshot2);
141002
+ if (snapshot2.executionSemantics !== EXECUTION_SEMANTICS && (snapshot2.executionSemantics !== void 0 || snapshot2.promiseReplay !== void 0 || snapshot2.replay !== void 0 || snapshot2.initialInputs !== void 0)) {
141003
+ throw new SnapshotValidationError(
141004
+ "unsupportedVersion",
141005
+ "$.executionSemantics",
141006
+ "incompatible execution semantics; resume with the SafeJS version that created this snapshot. Migration requires explicit reconciliation, not changing its version marker."
141007
+ );
141008
+ }
141009
+ const currentSourceHash = hashSource(options.source);
141010
+ if (snapshot2.sourceHash !== currentSourceHash) {
141011
+ throw new SnapshotMismatchError(snapshot2.sourceHash, currentSourceHash);
141012
+ }
141013
+ return snapshot2;
141014
+ }
141015
+ var SnapshotMismatchError;
141016
+ var init_restore = __esm({
141017
+ "packages/safejs/src/restore.ts"() {
141018
+ "use strict";
141019
+ init_hash();
141020
+ init_shape();
141021
+ init_validation();
141022
+ init_dump_format();
141023
+ init_running_state();
141024
+ SnapshotMismatchError = class extends Error {
141025
+ actualHash;
141026
+ expectedHash;
141027
+ constructor(expectedHash, actualHash) {
141028
+ super(
141029
+ `source changed since snapshot was taken (hash ${expectedHash} expected, got ${actualHash}); pass --reset to discard`
141030
+ );
141031
+ this.name = "SnapshotMismatchError";
141032
+ this.actualHash = actualHash;
141033
+ this.expectedHash = expectedHash;
141034
+ replaceErrorStack(this);
141035
+ }
141036
+ };
140498
141037
  }
140499
141038
  });
140500
141039
 
@@ -141001,6 +141540,7 @@ function createInterpretedClosure(node, context, evaluateNode3) {
141001
141540
  return isConstructResult(result) ? result : thisValue;
141002
141541
  } : void 0;
141003
141542
  return createSandboxClosure({
141543
+ sandbox: true,
141004
141544
  ...node.async ? { async: true } : {},
141005
141545
  ...node.type === "FunctionDeclaration" || node.type === "FunctionExpression" ? node.id === void 0 ? {} : { name: node.id.name } : {},
141006
141546
  ...construct === void 0 ? {} : { construct },
@@ -141016,30 +141556,42 @@ function createInterpretedClosure(node, context, evaluateNode3) {
141016
141556
  const synchronousPrefix = new Promise((resolve17) => {
141017
141557
  completePrefix = resolve17;
141018
141558
  });
141019
- const execution = runAsyncPrefix(
141020
- () => executeClosure(
141021
- node,
141022
- args,
141023
- callContext?.thisValue,
141024
- { ...invocationContext, onSuspend: completePrefix },
141025
- evaluateNode3
141026
- )
141027
- );
141028
- execution.then(completePrefix, completePrefix);
141029
- return createSandboxPromise(
141030
- resolveSandboxValue(
141031
- execution.then(
141032
- (value) => isSandboxPromise(value) || getThenable(value) !== void 0 ? awaitSandboxValue(value, context.signal) : value
141033
- ),
141034
- { budget: context.budget }
141035
- ),
141036
- { synchronousPrefix }
141037
- );
141559
+ const promise = new Promise((resolve17, reject) => {
141560
+ runAsyncPrefix(async () => {
141561
+ try {
141562
+ const value = await executeClosure(
141563
+ node,
141564
+ args,
141565
+ callContext?.thisValue,
141566
+ { ...invocationContext, onSuspend: completePrefix },
141567
+ evaluateNode3
141568
+ );
141569
+ resolve17(
141570
+ isSandboxPromise(value) || getThenable(value) !== void 0 ? awaitSandboxValue(
141571
+ createSandboxPromise(resolveSandboxValue(value, { budget: context.budget }), {
141572
+ trackReplay: false
141573
+ }),
141574
+ context.signal,
141575
+ context.budget
141576
+ ) : allocateProducedSandboxValue(value, context.budget)
141577
+ );
141578
+ } catch (error3) {
141579
+ reject(error3);
141580
+ } finally {
141581
+ completePrefix();
141582
+ }
141583
+ }).catch((error3) => {
141584
+ reject(error3);
141585
+ completePrefix();
141586
+ });
141587
+ });
141588
+ return createSandboxPromise(promise, { synchronousPrefix });
141038
141589
  }
141039
141590
  });
141040
141591
  }
141041
141592
  function createGeneratorClosure(node, context, evaluateNode3) {
141042
141593
  return createSandboxClosure({
141594
+ sandbox: true,
141043
141595
  ...node.id === void 0 ? {} : { name: node.id.name },
141044
141596
  retainedValues: () => context.scope.retainedValues(),
141045
141597
  call: async (args, callContext) => {
@@ -141098,7 +141650,7 @@ async function evaluateAwaitExpression(node, context, evaluateNode3) {
141098
141650
  return {
141099
141651
  kind: "normal",
141100
141652
  hasValue: true,
141101
- value: await suspendJob(awaitSandboxValue(argument.value, context.signal))
141653
+ value: await suspendJob(awaitSandboxValue(argument.value, context.signal, context.budget))
141102
141654
  };
141103
141655
  } finally {
141104
141656
  leaveAwait();
@@ -141193,10 +141745,12 @@ function getParameterBindingNames(pattern) {
141193
141745
  }
141194
141746
  }
141195
141747
  function normalizeClosureResult(result, budget) {
141196
- if (isSandboxPromise(result)) {
141748
+ if (isSandboxPromise(result) && (result.synchronousPrefix !== void 0 || result.hostCall !== void 0)) {
141197
141749
  return result;
141198
141750
  }
141199
- return createSandboxPromise(resolveSandboxValue(result, { budget }));
141751
+ return createSandboxPromise(resolveSandboxValue(result, { budget }), {
141752
+ ...isSandboxPromise(result) ? { synchronousPrefix: Promise.resolve() } : {}
141753
+ });
141200
141754
  }
141201
141755
  var init_async = __esm({
141202
141756
  "packages/safejs/src/interp/async.ts"() {
@@ -141239,8 +141793,10 @@ function wrapCallerInjectedFunction(name, value, options, state) {
141239
141793
  const callable = value;
141240
141794
  return createSandboxClosure({
141241
141795
  ...isAsyncFunction(callable) ? { async: true } : {},
141796
+ cancellationSignal: options.signal,
141242
141797
  call: (args, context) => {
141243
141798
  try {
141799
+ if (options.signal?.aborted) throw readAbortReason2(options.signal);
141244
141800
  const stackFrames = context?.stack ?? [];
141245
141801
  const callbacks = {
141246
141802
  journal: options.hostCalls,
@@ -141394,16 +141950,16 @@ function executeHostCall(record2, restored, invoke2, stackFrames, options, span,
141394
141950
  }
141395
141951
  })();
141396
141952
  void promise.catch(() => void 0);
141397
- return createSandboxPromise(promise);
141953
+ return createSandboxPromise(promise, { hostCall: record2, hostCallJournal: hostCalls });
141398
141954
  }
141399
141955
  if (replayed !== void 0) {
141400
141956
  restoreReplayedHostState(record2, replayed, onReplay);
141401
- if (record2.asynchronous) return createReplayedHostCallResult(replayed);
141957
+ if (record2.asynchronous) return createReplayedHostCallResult(replayed, record2, hostCalls);
141402
141958
  if (replayed.status === "rejected") throw replayed.reason;
141403
141959
  return replayed.value;
141404
141960
  }
141405
141961
  if (restored && record2.policy === "read-side-effect" && record2.lifecycle === "consumed" && record2.outcome !== void 0) {
141406
- return createReplayedHostCallResult(record2.outcome);
141962
+ return createReplayedHostCallResult(record2.outcome, record2, hostCalls);
141407
141963
  }
141408
141964
  if (restored && record2.policy === "read-side-effect" && record2.lifecycle === "settled" && record2.outcome !== void 0) {
141409
141965
  return createHostCallPromise(record2, Promise.resolve(record2.outcome), hostCalls);
@@ -141492,10 +142048,10 @@ function restoreReplayedHostState(record2, outcome, onReplay) {
141492
142048
  throw error3;
141493
142049
  }
141494
142050
  }
141495
- function createReplayedHostCallResult(outcome) {
142051
+ function createReplayedHostCallResult(outcome, record2, hostCalls) {
141496
142052
  const promise = outcome.status === "fulfilled" ? Promise.resolve(outcome.value) : Promise.reject(outcome.reason);
141497
142053
  promise.catch(() => void 0);
141498
- return createSandboxPromise(promise);
142054
+ return createSandboxPromise(promise, { hostCall: record2, hostCallJournal: hostCalls });
141499
142055
  }
141500
142056
  function createHostCallPromise(record2, outcomePromise, hostCalls) {
141501
142057
  const promise = outcomePromise.then((outcome) => {
@@ -141984,16 +142540,19 @@ function createConsoleJsonGlobals(options) {
141984
142540
  return {
141985
142541
  JSON: {
141986
142542
  parse: createSandboxClosure({
142543
+ sandbox: true,
141987
142544
  call: async ([text5]) => parseJson4(text5, options.budget),
141988
142545
  name: "parse"
141989
142546
  }),
141990
142547
  stringify: createSandboxClosure({
142548
+ sandbox: true,
141991
142549
  call: async ([value, replacer, indent]) => stringifyJson4(value, replacer, indent, options.budget),
141992
142550
  name: "stringify"
141993
142551
  })
141994
142552
  },
141995
142553
  console: options.hostCalls === void 0 ? {
141996
142554
  error: createSandboxClosure({
142555
+ sandbox: true,
141997
142556
  call: async (args) => {
141998
142557
  sink.error(...args.map((value) => deepCopyFromSandbox(value)));
141999
142558
  return void 0;
@@ -142001,6 +142560,7 @@ function createConsoleJsonGlobals(options) {
142001
142560
  name: "error"
142002
142561
  }),
142003
142562
  log: createSandboxClosure({
142563
+ sandbox: true,
142004
142564
  call: async (args) => {
142005
142565
  sink.log(...args.map((value) => deepCopyFromSandbox(value)));
142006
142566
  return void 0;
@@ -142256,79 +142816,10 @@ var init_console_json = __esm({
142256
142816
  }
142257
142817
  });
142258
142818
 
142259
- // packages/safejs/src/interp/iteration.ts
142260
- function getSandboxIterator(value) {
142261
- if (isSandboxGenerator(value)) {
142262
- return generatorIterator(value);
142263
- }
142264
- if (typeof value === "string") {
142265
- return syncIterator(value[Symbol.iterator]());
142266
- }
142267
- if (isSandboxMap(value)) {
142268
- return syncIterator(
142269
- Array.from(value.entries, ([key3, entry]) => [key3, entry])[Symbol.iterator]()
142270
- );
142271
- }
142272
- if (isSandboxSet(value)) {
142273
- return syncIterator(value.values[Symbol.iterator]());
142274
- }
142275
- if (typeof value !== "object" && typeof value !== "function" || value === null) {
142276
- return void 0;
142277
- }
142278
- const iteratorMethod = value[Symbol.iterator];
142279
- if (typeof iteratorMethod !== "function") {
142280
- return void 0;
142281
- }
142282
- return syncIterator(Reflect.apply(iteratorMethod, value, []));
142283
- }
142284
- function generatorIterator(generator) {
142285
- const invoke2 = async (method, value) => {
142286
- const leaveRunning = enterRunningState(generator);
142287
- generator.state = "running";
142288
- try {
142289
- const result = await generator.channel[method](value);
142290
- generator.state = result.done ? "done" : "suspended";
142291
- return result;
142292
- } catch (error3) {
142293
- generator.state = "done";
142294
- throw error3;
142295
- } finally {
142296
- leaveRunning();
142297
- }
142298
- };
142299
- return {
142300
- generator: true,
142301
- next: (value) => invoke2("next", value),
142302
- return: (value) => invoke2("return", value),
142303
- throw: (error3) => invoke2("throw", error3)
142304
- };
142305
- }
142306
- function syncIterator(iterator) {
142307
- const invoke2 = async (method, value) => {
142308
- const leaveRunning = enterRunningState(iterator);
142309
- try {
142310
- return await iterator[method](value);
142311
- } finally {
142312
- leaveRunning();
142313
- }
142314
- };
142315
- return {
142316
- next: (value) => invoke2("next", value),
142317
- ...typeof iterator.return === "function" ? { return: (value) => invoke2("return", value) } : {},
142318
- ...typeof iterator.throw === "function" ? { throw: (error3) => invoke2("throw", error3) } : {}
142319
- };
142320
- }
142321
- var init_iteration = __esm({
142322
- "packages/safejs/src/interp/iteration.ts"() {
142323
- "use strict";
142324
- init_values();
142325
- init_running_state();
142326
- }
142327
- });
142328
-
142329
142819
  // packages/safejs/src/interp/globals/collections.ts
142330
142820
  function createCollectionGlobals(options) {
142331
142821
  const mapConstructor = createSandboxClosure({
142822
+ sandbox: true,
142332
142823
  call: () => {
142333
142824
  throw new TypeError("Constructor Map requires 'new'.");
142334
142825
  },
@@ -142342,6 +142833,7 @@ function createCollectionGlobals(options) {
142342
142833
  name: "Map"
142343
142834
  });
142344
142835
  const setConstructor = createSandboxClosure({
142836
+ sandbox: true,
142345
142837
  call: () => {
142346
142838
  throw new TypeError("Constructor Set requires 'new'.");
142347
142839
  },
@@ -142462,11 +142954,7 @@ function isSandboxErrorConstructor(value) {
142462
142954
  }
142463
142955
  function createErrorConstructor(name, budget) {
142464
142956
  const call = (args, context) => createSubsetError(name, args, context?.stack ?? [], budget);
142465
- const closure = createSandboxClosure({
142466
- call,
142467
- construct: call,
142468
- name
142469
- });
142957
+ const closure = createSandboxClosure({ sandbox: true, call, construct: call, name });
142470
142958
  errorConstructorNames.set(closure, name);
142471
142959
  return closure;
142472
142960
  }
@@ -142509,7 +142997,7 @@ var init_error = __esm({
142509
142997
  function createRegexGlobals() {
142510
142998
  const construct = (args) => createSandboxRegex(String(args[0] ?? ""), String(args[1] ?? ""));
142511
142999
  return {
142512
- RegExp: createSandboxClosure({ name: "RegExp", call: construct, construct })
143000
+ RegExp: createSandboxClosure({ sandbox: true, name: "RegExp", call: construct, construct })
142513
143001
  };
142514
143002
  }
142515
143003
  var init_regex = __esm({
@@ -142523,22 +143011,27 @@ var init_regex = __esm({
142523
143011
  function createMiscGlobals(options) {
142524
143012
  return {
142525
143013
  structuredClone: createSandboxClosure({
143014
+ sandbox: true,
142526
143015
  call: ([value]) => structuredCloneSandboxValue(value, options.budget),
142527
143016
  name: "structuredClone"
142528
143017
  }),
142529
143018
  parseInt: createSandboxClosure({
143019
+ sandbox: true,
142530
143020
  call: (args) => Reflect.apply(globalThis.parseInt, globalThis, [...args]),
142531
143021
  name: "parseInt"
142532
143022
  }),
142533
143023
  parseFloat: createSandboxClosure({
143024
+ sandbox: true,
142534
143025
  call: (args) => Reflect.apply(globalThis.parseFloat, globalThis, [...args]),
142535
143026
  name: "parseFloat"
142536
143027
  }),
142537
143028
  isNaN: createSandboxClosure({
143029
+ sandbox: true,
142538
143030
  call: ([value]) => globalThis.isNaN(value),
142539
143031
  name: "isNaN"
142540
143032
  }),
142541
143033
  isFinite: createSandboxClosure({
143034
+ sandbox: true,
142542
143035
  call: ([value]) => globalThis.isFinite(value),
142543
143036
  name: "isFinite"
142544
143037
  })
@@ -142588,30 +143081,37 @@ function createObjectArrayGlobals(options) {
142588
143081
  return {
142589
143082
  Object: {
142590
143083
  keys: createSandboxClosure({
143084
+ sandbox: true,
142591
143085
  call: ([value]) => budgetSandboxValue2(getOwnEnumerableKeys(value), options.budget),
142592
143086
  name: "keys"
142593
143087
  }),
142594
143088
  values: createSandboxClosure({
143089
+ sandbox: true,
142595
143090
  call: ([value]) => budgetSandboxValue2(getOwnEnumerableValues(value), options.budget),
142596
143091
  name: "values"
142597
143092
  }),
142598
143093
  entries: createSandboxClosure({
143094
+ sandbox: true,
142599
143095
  call: ([value]) => budgetSandboxValue2(getOwnEnumerableEntries(value), options.budget),
142600
143096
  name: "entries"
142601
143097
  }),
142602
143098
  hasOwn: createSandboxClosure({
143099
+ sandbox: true,
142603
143100
  call: ([value, key3]) => Reflect.apply(Object.hasOwn, Object, [value, key3]),
142604
143101
  name: "hasOwn"
142605
143102
  }),
142606
143103
  is: createSandboxClosure({
143104
+ sandbox: true,
142607
143105
  call: ([left, right]) => Reflect.apply(Object.is, Object, [left, right]),
142608
143106
  name: "is"
142609
143107
  }),
142610
143108
  fromEntries: createSandboxClosure({
143109
+ sandbox: true,
142611
143110
  call: ([value]) => budgetSandboxValue2(Reflect.apply(Object.fromEntries, Object, [value]), options.budget),
142612
143111
  name: "fromEntries"
142613
143112
  }),
142614
143113
  freeze: createSandboxClosure({
143114
+ sandbox: true,
142615
143115
  call: ([value]) => {
142616
143116
  if (typeof value === "object" && value !== null) {
142617
143117
  Object.freeze(value);
@@ -142621,76 +143121,93 @@ function createObjectArrayGlobals(options) {
142621
143121
  name: "freeze"
142622
143122
  }),
142623
143123
  isFrozen: createSandboxClosure({
143124
+ sandbox: true,
142624
143125
  call: ([value]) => Object.isFrozen(value),
142625
143126
  name: "isFrozen"
142626
143127
  }),
142627
143128
  assign: createSandboxClosure({
143129
+ sandbox: true,
142628
143130
  call: ([target, ...sources]) => assignSandboxValues(target, sources),
142629
143131
  name: "assign"
142630
143132
  })
142631
143133
  },
142632
143134
  Array: createSandboxClosure({
143135
+ sandbox: true,
142633
143136
  call: (args) => createArrayFromConstructorArgs(args, options.budget),
142634
143137
  construct: (args) => createArrayFromConstructorArgs(args, options.budget),
142635
143138
  name: "Array",
142636
143139
  properties: {
142637
143140
  isArray: createSandboxClosure({
143141
+ sandbox: true,
142638
143142
  call: ([value]) => Array.isArray(value),
142639
143143
  name: "isArray"
142640
143144
  }),
142641
143145
  from: createSandboxClosure({
143146
+ sandbox: true,
142642
143147
  call: (args) => arrayFromSandboxValues(args, options.budget),
142643
143148
  name: "from"
142644
143149
  }),
142645
143150
  of: createSandboxClosure({
143151
+ sandbox: true,
142646
143152
  call: (args) => budgetSandboxValue2(Reflect.apply(Array.of, Array, [...args]), options.budget),
142647
143153
  name: "of"
142648
143154
  })
142649
143155
  }
142650
143156
  }),
142651
143157
  String: createSandboxClosure({
143158
+ sandbox: true,
142652
143159
  call: ([value]) => options.budget.allocateString(String(value)),
142653
143160
  name: "String",
142654
143161
  properties: {
142655
143162
  raw: createSandboxClosure({
143163
+ sandbox: true,
142656
143164
  call: (args) => stringRaw(args, options.budget),
142657
143165
  name: "raw"
142658
143166
  }),
142659
143167
  fromCharCode: createSandboxClosure({
143168
+ sandbox: true,
142660
143169
  call: (args) => options.budget.allocateString(Reflect.apply(String.fromCharCode, String, [...args])),
142661
143170
  name: "fromCharCode"
142662
143171
  }),
142663
143172
  fromCodePoint: createSandboxClosure({
143173
+ sandbox: true,
142664
143174
  call: (args) => options.budget.allocateString(Reflect.apply(String.fromCodePoint, String, [...args])),
142665
143175
  name: "fromCodePoint"
142666
143176
  })
142667
143177
  }
142668
143178
  }),
142669
143179
  Number: createSandboxClosure({
143180
+ sandbox: true,
142670
143181
  call: ([value]) => Number(value),
142671
143182
  name: "Number",
142672
143183
  properties: {
142673
143184
  isFinite: createSandboxClosure({
143185
+ sandbox: true,
142674
143186
  call: ([value]) => typeof value === "number" && Number.isFinite(value),
142675
143187
  name: "isFinite"
142676
143188
  }),
142677
143189
  isNaN: createSandboxClosure({
143190
+ sandbox: true,
142678
143191
  call: ([value]) => typeof value === "number" && Number.isNaN(value),
142679
143192
  name: "isNaN"
142680
143193
  }),
142681
143194
  isInteger: createSandboxClosure({
143195
+ sandbox: true,
142682
143196
  call: ([value]) => typeof value === "number" && Number.isInteger(value),
142683
143197
  name: "isInteger"
142684
143198
  }),
142685
143199
  parseInt: createSandboxClosure({
143200
+ sandbox: true,
142686
143201
  call: (args) => Reflect.apply(Number.parseInt, Number, [...args]),
142687
143202
  name: "parseInt"
142688
143203
  }),
142689
143204
  parseFloat: createSandboxClosure({
143205
+ sandbox: true,
142690
143206
  call: (args) => Reflect.apply(Number.parseFloat, Number, [...args]),
142691
143207
  name: "parseFloat"
142692
143208
  }),
142693
143209
  isSafeInteger: createSandboxClosure({
143210
+ sandbox: true,
142694
143211
  call: ([value]) => typeof value === "number" && Number.isSafeInteger(value),
142695
143212
  name: "isSafeInteger"
142696
143213
  }),
@@ -142702,6 +143219,7 @@ function createObjectArrayGlobals(options) {
142702
143219
  }
142703
143220
  }),
142704
143221
  Boolean: createSandboxClosure({
143222
+ sandbox: true,
142705
143223
  call: ([value]) => Boolean(value),
142706
143224
  name: "Boolean"
142707
143225
  })
@@ -142831,6 +143349,7 @@ function getArrayMember(value, property, options) {
142831
143349
  }
142832
143350
  if (isArrayMethodName(property)) {
142833
143351
  return createSandboxClosure({
143352
+ sandbox: true,
142834
143353
  name: `Array#${property}`,
142835
143354
  call: (args, context) => callArrayMethod(value, property, args, options, context?.stack ?? [])
142836
143355
  });
@@ -143408,6 +143927,7 @@ function getFunctionMember(target, property, options) {
143408
143927
  return void 0;
143409
143928
  }
143410
143929
  return createSandboxClosure({
143930
+ sandbox: true,
143411
143931
  name: `Function#${property}`,
143412
143932
  call: (args, context) => callFunctionMethod(target, property, args, options, context?.stack ?? [])
143413
143933
  });
@@ -143417,6 +143937,25 @@ function isFunctionMethodName(property) {
143417
143937
  }
143418
143938
  function callFunctionMethod(target, methodName, args, options, stack) {
143419
143939
  const thisValue = args[0];
143940
+ if (methodName === "bind") {
143941
+ const boundArgs = args.slice(1);
143942
+ return createSandboxClosure({
143943
+ sandbox: true,
143944
+ name: `bound ${target.name ?? ""}`,
143945
+ boundTarget: target,
143946
+ retainedValues: () => [target, thisValue, ...boundArgs],
143947
+ call: (callArgs, context) => options.callClosure(target, [...boundArgs, ...callArgs], context?.stack ?? [], thisValue),
143948
+ ...target.construct === void 0 ? {} : {
143949
+ construct: (callArgs, context) => options.callClosure(
143950
+ target,
143951
+ [...boundArgs, ...callArgs],
143952
+ context?.stack ?? [],
143953
+ void 0,
143954
+ true
143955
+ )
143956
+ }
143957
+ });
143958
+ }
143420
143959
  if (methodName === "call") {
143421
143960
  return options.callClosure(target, args.slice(1), stack, thisValue);
143422
143961
  }
@@ -143434,7 +143973,7 @@ var init_function = __esm({
143434
143973
  "packages/safejs/src/interp/methods/function.ts"() {
143435
143974
  "use strict";
143436
143975
  init_values();
143437
- functionMethodNames = /* @__PURE__ */ new Set(["apply", "call"]);
143976
+ functionMethodNames = /* @__PURE__ */ new Set(["apply", "bind", "call"]);
143438
143977
  }
143439
143978
  });
143440
143979
 
@@ -143450,6 +143989,7 @@ function getMapMember(target, property, options) {
143450
143989
  return void 0;
143451
143990
  }
143452
143991
  return createSandboxClosure({
143992
+ sandbox: true,
143453
143993
  call: (args, context) => callMapMethod(target, property, args, options, context?.stack ?? []),
143454
143994
  name: property
143455
143995
  });
@@ -143528,6 +144068,7 @@ function getNumberMember(value, property, budget) {
143528
144068
  return void 0;
143529
144069
  }
143530
144070
  return createSandboxClosure({
144071
+ sandbox: true,
143531
144072
  name: `Number#${property}`,
143532
144073
  call: (args) => callNumberMethod(value, property, args, budget)
143533
144074
  });
@@ -143604,6 +144145,7 @@ function getGeneratorMember(target, property, budget) {
143604
144145
  return void 0;
143605
144146
  }
143606
144147
  return createSandboxClosure({
144148
+ sandbox: true,
143607
144149
  name: property,
143608
144150
  call: async ([value]) => {
143609
144151
  const iterator = getSandboxIterator(target);
@@ -143873,6 +144415,7 @@ function getRegexMember(target, property) {
143873
144415
  return void 0;
143874
144416
  }
143875
144417
  return createSandboxClosure({
144418
+ sandbox: true,
143876
144419
  name: `RegExp#${property}`,
143877
144420
  call: (args) => callRegexMethod(target, property, args)
143878
144421
  });
@@ -143926,6 +144469,7 @@ function getStringMember(value, property, budget) {
143926
144469
  return void 0;
143927
144470
  }
143928
144471
  return createSandboxClosure({
144472
+ sandbox: true,
143929
144473
  name: `String#${property}`,
143930
144474
  call: (args) => callStringMethod(value, property, args, budget)
143931
144475
  });
@@ -144222,6 +144766,7 @@ function getSetMember(target, property, options) {
144222
144766
  return void 0;
144223
144767
  }
144224
144768
  return createSandboxClosure({
144769
+ sandbox: true,
144225
144770
  call: (args, context) => callSetMethod(target, property, args, options, context?.stack ?? []),
144226
144771
  name: property
144227
144772
  });
@@ -144557,7 +145102,10 @@ async function interpret(node, options = {}) {
144557
145102
  generatorYield: options.generatorYield,
144558
145103
  resumeTarget: { nodeId: options.snapshot?.resumeNodeId }
144559
145104
  };
144560
- const evaluation = await jobs.run(() => evaluateNode2(node, context));
145105
+ const evaluation = await withCancellationSignal(
145106
+ options.signal,
145107
+ () => jobs.run(() => evaluateNode2(node, context))
145108
+ );
144561
145109
  await jobs.drain();
144562
145110
  const snapshot2 = scope.snapshot();
144563
145111
  reconcileDataBudget(
@@ -144609,6 +145157,7 @@ async function interpret(node, options = {}) {
144609
145157
  async function evaluateNode2(node, context) {
144610
145158
  const replayWait = promiseReplayContext.getStore()?.beforeNode(node.nodeId);
144611
145159
  if (replayWait !== void 0) await suspendJob(replayWait);
145160
+ assertPromiseExecutionAllowed();
144612
145161
  context.budget.visitNode();
144613
145162
  context.stats.nodeVisits += 1;
144614
145163
  if (node.nodeId !== void 0 && context.resumeTarget?.nodeId === node.nodeId) {
@@ -146059,7 +146608,7 @@ async function evaluateMemberExpression(node, context) {
146059
146608
  return {
146060
146609
  kind: "normal",
146061
146610
  hasValue: true,
146062
- value: getPromiseMember(member.object, member.property, context.budget)
146611
+ value: getPromiseMember(member.property, context.budget)
146063
146612
  };
146064
146613
  }
146065
146614
  if (isSandboxRegex(member.object)) {
@@ -146096,36 +146645,27 @@ async function evaluateNewExpression(node, context) {
146096
146645
  return callee;
146097
146646
  }
146098
146647
  const name = getConstructorName(node.callee);
146099
- if (!isSandboxClosure(callee.value) || callee.value.construct === void 0) {
146100
- throw new TypeError(`${name} is not a constructor.`);
146101
- }
146102
146648
  const args = await evaluateCallArguments(node.arguments, context);
146103
146649
  if (!args.ok) {
146104
146650
  return args.result;
146105
146651
  }
146106
- const stack = [...context.callStack, formatStackFrame(node, callee.value.name ?? name)];
146107
- const leaveCall = context.budget.enterCall();
146108
- try {
146109
- return {
146110
- kind: "normal",
146111
- hasValue: true,
146112
- value: await wrapHostResult(
146113
- callee.value.construct(args.value, {
146114
- stack,
146115
- thisValue: void 0,
146116
- span: node.span
146117
- }),
146118
- stack
146119
- )
146120
- };
146121
- } catch (error3) {
146122
- if (isFatalSandboxError(error3)) {
146123
- throw error3;
146124
- }
146125
- throw captureException(error3, stack);
146126
- } finally {
146127
- leaveCall();
146652
+ if (!isSandboxClosure(callee.value) || callee.value.construct === void 0) {
146653
+ throw new TypeError(`${name} is not a constructor.`);
146128
146654
  }
146655
+ const stack = [...context.callStack, formatStackFrame(node, callee.value.name ?? name)];
146656
+ return {
146657
+ kind: "normal",
146658
+ hasValue: true,
146659
+ value: await invokeSandboxClosure(
146660
+ callee.value,
146661
+ args.value,
146662
+ context,
146663
+ stack,
146664
+ node.span,
146665
+ void 0,
146666
+ true
146667
+ )
146668
+ };
146129
146669
  }
146130
146670
  function getConstructorName(callee) {
146131
146671
  if (callee.type === "Identifier") {
@@ -146330,7 +146870,7 @@ async function evaluateMemberCallExpression(node, context) {
146330
146870
  if (isSandboxPromise(member.object)) {
146331
146871
  return evaluateResolvedCallExpression(
146332
146872
  node,
146333
- getPromiseMember(member.object, member.property, context.budget),
146873
+ getPromiseMember(member.property, context.budget),
146334
146874
  context,
146335
146875
  member.object
146336
146876
  );
@@ -146541,6 +147081,8 @@ function applyBinaryOperator(node, left, right, context) {
146541
147081
  case ">>>":
146542
147082
  return toNumber(left) >>> toNumber(right);
146543
147083
  case "instanceof":
147084
+ while (isSandboxClosure(right) && right.boundTarget !== void 0) right = right.boundTarget;
147085
+ if (isSandboxPromiseConstructor(right)) return isSandboxPromise(left);
146544
147086
  if (isSandboxMapConstructor(right) && isSandboxMap(left)) {
146545
147087
  return true;
146546
147088
  }
@@ -146846,13 +147388,15 @@ function createSetMethodOptions(context) {
146846
147388
  }
146847
147389
  function createFunctionMethodOptions(context) {
146848
147390
  return {
146849
- callClosure: (closure, args, stack, thisValue) => invokeSandboxClosure(closure, args, context, stack, void 0, thisValue)
147391
+ callClosure: (closure, args, stack, thisValue, construct) => invokeSandboxClosure(closure, args, context, stack, void 0, thisValue, construct)
146850
147392
  };
146851
147393
  }
146852
- async function invokeSandboxClosure(callee, args, context, stack, span, thisValue = void 0) {
147394
+ async function invokeSandboxClosure(callee, args, context, stack, span, thisValue = void 0, construct = false) {
146853
147395
  const leaveCall = context.budget.enterCall();
146854
147396
  try {
146855
- const result = Reflect.apply(callee.call, void 0, [
147397
+ const invoke2 = construct ? callee.construct : callee.call;
147398
+ if (invoke2 === void 0) throw new TypeError("Value is not a constructor.");
147399
+ const result = Reflect.apply(invoke2, void 0, [
146856
147400
  args,
146857
147401
  {
146858
147402
  stack,
@@ -146863,7 +147407,7 @@ async function invokeSandboxClosure(callee, args, context, stack, span, thisValu
146863
147407
  if (isSandboxPromise(result) && result.synchronousPrefix !== void 0) {
146864
147408
  await result.synchronousPrefix;
146865
147409
  }
146866
- return callee.async === true ? normalizeClosureResult(wrapHostResult(result, stack), context.budget) : await wrapHostResult(result, stack);
147410
+ return !construct && callee.async === true ? normalizeClosureResult(wrapHostResult(result, stack), context.budget) : await wrapHostResult(result, stack);
146867
147411
  } catch (error3) {
146868
147412
  if (isFatalSandboxError(error3)) {
146869
147413
  throw error3;
@@ -147018,7 +147562,9 @@ var init_interpreter = __esm({
147018
147562
  "packages/safejs/src/interp/interpreter.ts"() {
147019
147563
  "use strict";
147020
147564
  init_promise_replay();
147565
+ init_promise_tracker();
147021
147566
  init_jobs4();
147567
+ init_cancel2();
147022
147568
  init_shape();
147023
147569
  init_async();
147024
147570
  init_host_call();
@@ -148423,7 +148969,7 @@ var init_find_exported = __esm({
148423
148969
  });
148424
148970
 
148425
148971
  // packages/safejs/src/modules/agent.ts
148426
- import { AsyncLocalStorage as AsyncLocalStorage6 } from "node:async_hooks";
148972
+ import { AsyncLocalStorage as AsyncLocalStorage7 } from "node:async_hooks";
148427
148973
  function createSpawnUsageAccumulator() {
148428
148974
  let inputTokens = 0;
148429
148975
  let outputTokens = 0;
@@ -149269,7 +149815,7 @@ var init_agent3 = __esm({
149269
149815
  init_parallel();
149270
149816
  init_types4();
149271
149817
  init_otel2();
149272
- activeUsageAccumulator = new AsyncLocalStorage6();
149818
+ activeUsageAccumulator = new AsyncLocalStorage7();
149273
149819
  oneAttemptRetryOptions = {
149274
149820
  maxAttempts: 1,
149275
149821
  backoffMs: 0,
@@ -154211,7 +154757,7 @@ var init_package2 = __esm({
154211
154757
  "package.json"() {
154212
154758
  package_default2 = {
154213
154759
  name: "poe-code",
154214
- version: "5.0.3",
154760
+ version: "6.0.0",
154215
154761
  description: "CLI tool to configure Poe API for developer workflows.",
154216
154762
  license: "MIT",
154217
154763
  type: "module",