ooxml-core 1.2.0 → 1.2.1

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 (82) hide show
  1. package/dist/{PptxHandler-SJTINPU4.mjs → PptxHandler-VQQS4VS6.mjs} +2 -2
  2. package/dist/automation/index.cjs +1059 -328
  3. package/dist/automation/index.mjs +1059 -328
  4. package/dist/chart/bar-cluster-geometry.d.ts +6 -0
  5. package/dist/chart/bar-cluster-geometry.d.ts.map +1 -1
  6. package/dist/chart/index.cjs +5 -2
  7. package/dist/chart/index.mjs +5 -3
  8. package/dist/chart/render/chart-spacing.d.ts.map +1 -1
  9. package/dist/{chunk-TEOAOAIF.mjs → chunk-5U27IVB7.mjs} +3 -3
  10. package/dist/{chunk-VYTA2OUN.mjs → chunk-5VLNF4OX.mjs} +1 -1
  11. package/dist/{chunk-CQQAPUAG.mjs → chunk-V2BIGIH4.mjs} +11 -9
  12. package/dist/{chunk-FI4RSJ24.mjs → chunk-XBNSBDNT.mjs} +1 -1
  13. package/dist/{chunk-XCZ7U3GZ.mjs → chunk-XSFHGZFH.mjs} +11 -9
  14. package/dist/docx/index.cjs +4 -2
  15. package/dist/docx/index.mjs +4 -2
  16. package/dist/docx/layout/index.cjs +4 -2
  17. package/dist/docx/layout/index.mjs +4 -2
  18. package/dist/docx/ui/index.cjs +4 -2
  19. package/dist/docx/ui/index.mjs +4 -2
  20. package/dist/index.cjs +5 -2
  21. package/dist/index.mjs +5 -2
  22. package/dist/pptx/automation/index.cjs +27 -17
  23. package/dist/pptx/automation/index.mjs +5 -5
  24. package/dist/pptx/chunks/index-EZJZ7USt.d.ts.map +1 -1
  25. package/dist/pptx/cli/index.cjs +27 -17
  26. package/dist/pptx/cli/index.mjs +4 -4
  27. package/dist/pptx/converter/index.mjs +2 -2
  28. package/dist/pptx/index.cjs +27 -17
  29. package/dist/pptx/index.mjs +5 -5
  30. package/dist/teams/index.cjs +157 -82
  31. package/dist/teams/index.mjs +157 -82
  32. package/dist/xlsx/edit/context.d.ts +3 -1
  33. package/dist/xlsx/edit/context.d.ts.map +1 -1
  34. package/dist/xlsx/edit/history.d.ts +18 -0
  35. package/dist/xlsx/edit/history.d.ts.map +1 -1
  36. package/dist/xlsx/edit/session-calc.d.ts +30 -8
  37. package/dist/xlsx/edit/session-calc.d.ts.map +1 -1
  38. package/dist/xlsx/edit/session.d.ts.map +1 -1
  39. package/dist/xlsx/edit/sheets.d.ts.map +1 -1
  40. package/dist/xlsx/edit/types.d.ts +23 -3
  41. package/dist/xlsx/edit/types.d.ts.map +1 -1
  42. package/dist/xlsx/formula/engine-core.d.ts.map +1 -1
  43. package/dist/xlsx/formula/engine-host.d.ts +6 -2
  44. package/dist/xlsx/formula/engine-host.d.ts.map +1 -1
  45. package/dist/xlsx/formula/engine-prepare.d.ts +33 -0
  46. package/dist/xlsx/formula/engine-prepare.d.ts.map +1 -0
  47. package/dist/xlsx/formula/engine-structure.d.ts +40 -0
  48. package/dist/xlsx/formula/engine-structure.d.ts.map +1 -0
  49. package/dist/xlsx/formula/engine-types.d.ts +26 -0
  50. package/dist/xlsx/formula/engine-types.d.ts.map +1 -1
  51. package/dist/xlsx/formula/engine.d.ts.map +1 -1
  52. package/dist/xlsx/formula/formula-shape.d.ts +28 -0
  53. package/dist/xlsx/formula/formula-shape.d.ts.map +1 -0
  54. package/dist/xlsx/formula/graph-index.d.ts +3 -1
  55. package/dist/xlsx/formula/graph-index.d.ts.map +1 -1
  56. package/dist/xlsx/formula/graph.d.ts +5 -0
  57. package/dist/xlsx/formula/graph.d.ts.map +1 -1
  58. package/dist/xlsx/formula/lexemes.d.ts.map +1 -1
  59. package/dist/xlsx/formula/parse-cache.d.ts +9 -0
  60. package/dist/xlsx/formula/parse-cache.d.ts.map +1 -0
  61. package/dist/xlsx/formula/parser.d.ts +3 -0
  62. package/dist/xlsx/formula/parser.d.ts.map +1 -1
  63. package/dist/xlsx/formula/ref-text.d.ts +14 -0
  64. package/dist/xlsx/formula/ref-text.d.ts.map +1 -0
  65. package/dist/xlsx/formula/references.d.ts.map +1 -1
  66. package/dist/xlsx/formula/shift-formula.d.ts +19 -0
  67. package/dist/xlsx/formula/shift-formula.d.ts.map +1 -0
  68. package/dist/xlsx/formula/shift-graph.d.ts +42 -0
  69. package/dist/xlsx/formula/shift-graph.d.ts.map +1 -0
  70. package/dist/xlsx/formula/transform.d.ts +2 -23
  71. package/dist/xlsx/formula/transform.d.ts.map +1 -1
  72. package/dist/xlsx/index.cjs +1069 -329
  73. package/dist/xlsx/index.mjs +1069 -330
  74. package/dist/xlsx/layout/index.d.ts +1 -1
  75. package/dist/xlsx/layout/index.d.ts.map +1 -1
  76. package/dist/xlsx/layout/sheet-queries.d.ts +7 -0
  77. package/dist/xlsx/layout/sheet-queries.d.ts.map +1 -1
  78. package/dist/xlsx/load/index.cjs +152 -90
  79. package/dist/xlsx/load/index.mjs +152 -90
  80. package/dist/xlsx/ui/index.cjs +1071 -340
  81. package/dist/xlsx/ui/index.mjs +1071 -340
  82. package/package.json +1 -1
@@ -2102,7 +2102,7 @@ var NAME_RE = /^[A-Za-z_\\\u00A1-\uFFFF][A-Za-z0-9_.?\\\u00A1-\uFFFF]*/;
2102
2102
  var CELL_RE = /^(\$?)([A-Za-z]{1,3})(\$?)(\d{1,7})/;
2103
2103
  var COLS_RE = /^(\$?)([A-Za-z]{1,3}):(\$?)([A-Za-z]{1,3})/;
2104
2104
  var ROWS_RE = /^(\$?)(\d{1,7}):(\$?)(\d{1,7})/;
2105
- var NUMBER_RE2 = /^(?:\d+\.?\d*|\.\d+)(?:[eE][+-]?\d+)?/;
2105
+ var NUMBER_RE2 = /^(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?/;
2106
2106
  var sticky = (re) => new RegExp(re.source.replace(/^\^/, ""), "y");
2107
2107
  var CELL_AT = sticky(CELL_RE);
2108
2108
  var COLS_AT = sticky(COLS_RE);
@@ -2474,7 +2474,9 @@ var PREC_INTERSECT = 9;
2474
2474
  var PREC_RANGE = 10;
2475
2475
  var OPERAND_START = /* @__PURE__ */ new Set(["ref", "name", "func", "open", "structured"]);
2476
2476
  function parseFormula(formula) {
2477
- const all2 = tokenize(formula);
2477
+ return parseTokens(tokenize(formula));
2478
+ }
2479
+ function parseTokens(all2) {
2478
2480
  const tokens2 = [];
2479
2481
  const wsBefore = [];
2480
2482
  let sawWs = false;
@@ -2759,6 +2761,222 @@ function localDateToSerial(date, date1904 = date1904Mode) {
2759
2761
  return base + (utc - dayStart) / DAY_MS;
2760
2762
  }
2761
2763
 
2764
+ // xlsx/formula/area-index.ts
2765
+ var BUCKET_WIDTH = 64;
2766
+ var CHUNK_SHIFT = 6;
2767
+ var CHUNKS = 64;
2768
+ function push(map, key, value) {
2769
+ const list = map.get(key);
2770
+ if (list) list.push(value);
2771
+ else map.set(key, [value]);
2772
+ }
2773
+ function inner(map, sheet) {
2774
+ let found = map.get(sheet);
2775
+ if (!found) map.set(sheet, found = /* @__PURE__ */ new Map());
2776
+ return found;
2777
+ }
2778
+ var AreaIndex = class {
2779
+ cells = /* @__PURE__ */ new Map();
2780
+ chunked = /* @__PURE__ */ new Map();
2781
+ tall = /* @__PURE__ */ new Map();
2782
+ wide = /* @__PURE__ */ new Map();
2783
+ add(area, node) {
2784
+ const { start, end } = area.range;
2785
+ if (start.row === end.row && end.col - start.col + 1 <= BUCKET_WIDTH) {
2786
+ const cells = inner(this.cells, area.sheet);
2787
+ for (let col = start.col; col <= end.col; col++) push(cells, cellKey(start.row, col), node);
2788
+ return;
2789
+ }
2790
+ const entry3 = { range: area.range, node };
2791
+ if (end.col - start.col + 1 > BUCKET_WIDTH) {
2792
+ const list = this.wide.get(area.sheet);
2793
+ if (list) list.push(entry3);
2794
+ else this.wide.set(area.sheet, [entry3]);
2795
+ return;
2796
+ }
2797
+ const first2 = start.row >> CHUNK_SHIFT;
2798
+ const last = end.row >> CHUNK_SHIFT;
2799
+ if (last - first2 + 1 > CHUNKS) {
2800
+ const cols2 = inner(this.tall, area.sheet);
2801
+ for (let c2 = start.col; c2 <= end.col; c2++) push(cols2, c2, entry3);
2802
+ return;
2803
+ }
2804
+ const cols = inner(this.chunked, area.sheet);
2805
+ for (let c2 = start.col; c2 <= end.col; c2++) {
2806
+ let chunks = cols.get(c2);
2807
+ if (!chunks) cols.set(c2, chunks = /* @__PURE__ */ new Map());
2808
+ for (let k = first2; k <= last; k++) push(chunks, k, entry3);
2809
+ }
2810
+ }
2811
+ /** Items whose areas intersect `range` on `sheet` (each once). */
2812
+ dependents(sheet, range, out) {
2813
+ const found = out instanceof Set ? out : /* @__PURE__ */ new Set();
2814
+ this.collect(sheet, range, found);
2815
+ if (Array.isArray(out)) for (const node of found) out.push(node);
2816
+ }
2817
+ collect(sheet, range, out) {
2818
+ const { start, end } = range;
2819
+ const check3 = (list) => {
2820
+ if (list) {
2821
+ for (const entry3 of list) if (rangesIntersect(entry3.range, range)) out.add(entry3.node);
2822
+ }
2823
+ };
2824
+ const cells = this.cells.get(sheet);
2825
+ if (cells) {
2826
+ const size = (end.row - start.row + 1) * (end.col - start.col + 1);
2827
+ if (size <= 4096) {
2828
+ for (let r = start.row; r <= end.row; r++) {
2829
+ for (let c2 = start.col; c2 <= end.col; c2++) {
2830
+ const list = cells.get(cellKey(r, c2));
2831
+ if (list) for (const node of list) out.add(node);
2832
+ }
2833
+ }
2834
+ } else {
2835
+ for (const [key, list] of cells) {
2836
+ const { row: row2, col } = keyToAddress(key);
2837
+ if (row2 >= start.row && row2 <= end.row && col >= start.col && col <= end.col)
2838
+ for (const node of list) out.add(node);
2839
+ }
2840
+ }
2841
+ }
2842
+ const columns = (map, visit2) => {
2843
+ if (!map) return;
2844
+ if (end.col - start.col + 1 <= map.size) {
2845
+ for (let c2 = start.col; c2 <= end.col; c2++) if (map.has(c2)) visit2(c2);
2846
+ } else for (const c2 of map.keys()) if (c2 >= start.col && c2 <= end.col) visit2(c2);
2847
+ };
2848
+ const chunked = this.chunked.get(sheet);
2849
+ const first2 = start.row >> CHUNK_SHIFT;
2850
+ const last = end.row >> CHUNK_SHIFT;
2851
+ columns(chunked, (c2) => {
2852
+ const chunks = chunked?.get(c2);
2853
+ if (last - first2 + 1 <= chunks.size) {
2854
+ for (let k = first2; k <= last; k++) check3(chunks.get(k));
2855
+ } else for (const [k, list] of chunks) if (k >= first2 && k <= last) check3(list);
2856
+ });
2857
+ const tall = this.tall.get(sheet);
2858
+ columns(tall, (c2) => check3(tall?.get(c2)));
2859
+ check3(this.wide.get(sheet));
2860
+ }
2861
+ };
2862
+
2863
+ // xlsx/formula/graph-index.ts
2864
+ var ColumnIndex = class {
2865
+ sheets = /* @__PURE__ */ new Map();
2866
+ constructor(nodes) {
2867
+ for (const node of nodes) {
2868
+ let cols = this.sheets.get(node.sheet);
2869
+ if (!cols) this.sheets.set(node.sheet, cols = /* @__PURE__ */ new Map());
2870
+ let list = cols.get(node.col);
2871
+ if (!list) cols.set(node.col, list = []);
2872
+ list.push(node);
2873
+ }
2874
+ for (const cols of this.sheets.values())
2875
+ for (const list of cols.values()) list.sort((a2, b) => a2.row - b.row);
2876
+ }
2877
+ nodesIn(area, out) {
2878
+ const cols = this.sheets.get(area.sheet);
2879
+ if (!cols) return;
2880
+ const { start, end } = area.range;
2881
+ const width = end.col - start.col + 1;
2882
+ const scan4 = (list) => {
2883
+ let lo = 0;
2884
+ let hi = list.length;
2885
+ while (lo < hi) {
2886
+ const mid = lo + hi >> 1;
2887
+ if (list[mid].row < start.row) lo = mid + 1;
2888
+ else hi = mid;
2889
+ }
2890
+ for (let i2 = lo; i2 < list.length; i2++) {
2891
+ const node = list[i2];
2892
+ if (node.row > end.row) break;
2893
+ out.push(node);
2894
+ }
2895
+ };
2896
+ if (width <= cols.size) {
2897
+ for (let c2 = start.col; c2 <= end.col; c2++) {
2898
+ const list = cols.get(c2);
2899
+ if (list) scan4(list);
2900
+ }
2901
+ } else {
2902
+ for (const [c2, list] of cols) if (c2 >= start.col && c2 <= end.col) scan4(list);
2903
+ }
2904
+ }
2905
+ };
2906
+ var ReverseIndex = class extends AreaIndex {
2907
+ constructor(nodes = []) {
2908
+ super();
2909
+ for (const node of nodes) this.addNode(node);
2910
+ }
2911
+ /** Indexes one more formula's precedents. */
2912
+ addNode(node) {
2913
+ for (const dep of node.deps) this.add(dep, node);
2914
+ for (const dep of node.dynamicDeps) this.add(dep, node);
2915
+ }
2916
+ };
2917
+
2918
+ // xlsx/formula/engine-prepare.ts
2919
+ var CHECK_EVERY = 32;
2920
+ var GraphPreparation = class {
2921
+ constructor(workbook, create) {
2922
+ this.workbook = workbook;
2923
+ this.create = create;
2924
+ }
2925
+ workbook;
2926
+ create;
2927
+ reverse = new ReverseIndex();
2928
+ formulas = { dynamic: [], unvalued: [] };
2929
+ sheet = 0;
2930
+ rows;
2931
+ row = 0;
2932
+ cells;
2933
+ finished = false;
2934
+ /**
2935
+ * Adds formulas to the graph until `timeRemaining` (milliseconds, as an idle deadline reports
2936
+ * them) reaches zero, or until every formula is in. Returns true when the graph is complete.
2937
+ */
2938
+ run(timeRemaining) {
2939
+ let visited = 0;
2940
+ while (!this.finished) {
2941
+ const cells = this.cells ?? this.nextRow();
2942
+ if (!cells) continue;
2943
+ const next = cells.next();
2944
+ if (next.done) {
2945
+ this.cells = void 0;
2946
+ continue;
2947
+ }
2948
+ const [col, cell] = next.value;
2949
+ if (cell.formula) this.add(this.create(this.sheet, this.row, col, cell), cell);
2950
+ if (timeRemaining && ++visited % CHECK_EVERY === 0 && timeRemaining() <= 0) break;
2951
+ }
2952
+ return this.finished;
2953
+ }
2954
+ add(node, cell) {
2955
+ this.reverse.addNode(node);
2956
+ if (!node.legacy && !node.arrayRange) this.formulas.dynamic.push(node);
2957
+ if (cell.value === null && !node.keepCached) this.formulas.unvalued.push(node);
2958
+ }
2959
+ /** Moves to the next stored row (and sheet), or marks the walk finished. */
2960
+ nextRow() {
2961
+ for (; ; ) {
2962
+ const sheet = this.workbook.sheets[this.sheet];
2963
+ if (!sheet) {
2964
+ this.finished = true;
2965
+ return void 0;
2966
+ }
2967
+ this.rows ??= sheet.rows.entries();
2968
+ const next = this.rows.next();
2969
+ if (!next.done) {
2970
+ this.row = next.value[0];
2971
+ this.cells = next.value[1].entries();
2972
+ return this.cells;
2973
+ }
2974
+ this.rows = void 0;
2975
+ this.sheet++;
2976
+ }
2977
+ }
2978
+ };
2979
+
2762
2980
  // xlsx/formula/text-number.ts
2763
2981
  var MONTHS2 = [
2764
2982
  "jan",
@@ -5893,8 +6111,10 @@ var FINANCIAL_FUNCTIONS = [
5893
6111
 
5894
6112
  // xlsx/formula/references.ts
5895
6113
  function sheetIndex(host, name) {
6114
+ const sheets = host.workbook.sheets;
6115
+ for (let i2 = 0; i2 < sheets.length; i2++) if (sheets[i2]?.name === name) return i2;
5896
6116
  const lower2 = name.toLowerCase();
5897
- return host.workbook.sheets.findIndex((sheet) => sheet.name.toLowerCase() === lower2);
6117
+ return sheets.findIndex((sheet) => sheet.name.toLowerCase() === lower2);
5898
6118
  }
5899
6119
  function prefixSheets(host, prefix, current) {
5900
6120
  if (!prefix) return [current];
@@ -7464,9 +7684,9 @@ function readBlock(ctx, area, rows, cols) {
7464
7684
  if (host.readBlock) return host.readBlock(area.sheet, range);
7465
7685
  return Matrix.build(rows, cols, (r, c2) => ctx.readCell(area.sheet, row2 + r, col + c2));
7466
7686
  }
7467
- function shapedMatrices(ctx, values2, sameShape) {
7687
+ function shapedMatrices(ctx, values2, sameShape2) {
7468
7688
  let { rows, cols } = shapeOf(values2[0] ?? null);
7469
- if (sameShape) {
7689
+ if (sameShape2) {
7470
7690
  for (const value of values2) {
7471
7691
  const shape2 = shapeOf(value);
7472
7692
  if (shape2.rows !== rows || shape2.cols !== cols) fail(ERR.VALUE);
@@ -7492,12 +7712,12 @@ function shapedMatrices(ctx, values2, sameShape) {
7492
7712
  });
7493
7713
  return { matrices, total: total2, block: rows * cols };
7494
7714
  }
7495
- function matchingCells(ctx, pairs, target, sameShape) {
7715
+ function matchingCells(ctx, pairs, target, sameShape2) {
7496
7716
  const ranges = pairs.map((p) => p.range);
7497
7717
  const { matrices, total: total2, block } = shapedMatrices(
7498
7718
  ctx,
7499
7719
  target === void 0 ? ranges : [...ranges, target],
7500
- sameShape
7720
+ sameShape2
7501
7721
  );
7502
7722
  const tests = pairs.map((p) => makeCriteria(scalar(p.criteria)));
7503
7723
  const values2 = matrices[matrices.length - 1];
@@ -7536,7 +7756,7 @@ function indexedCandidates(pairs, matrices) {
7536
7756
  }
7537
7757
  return void 0;
7538
7758
  }
7539
- var matchingValues = (ctx, pairs, target, sameShape) => matchingCells(ctx, pairs, target, sameShape).values;
7759
+ var matchingValues = (ctx, pairs, target, sameShape2) => matchingCells(ctx, pairs, target, sameShape2).values;
7540
7760
  function criteriaPairs(args, from) {
7541
7761
  if ((args.length - from) % 2 !== 0) fail(ERR.VALUE);
7542
7762
  const pairs = [];
@@ -11430,7 +11650,7 @@ var REFERENCE_ARGUMENT = /* @__PURE__ */ new Set([
11430
11650
  "AREAS",
11431
11651
  "ISREF"
11432
11652
  ]);
11433
- var push = (c2, area) => {
11653
+ var push2 = (c2, area) => {
11434
11654
  (c2.dynamic > 0 ? c2.dynamicDeps : c2.deps).push(area);
11435
11655
  };
11436
11656
  function spans(areas) {
@@ -11456,7 +11676,7 @@ function visit(node, c2) {
11456
11676
  if (!sheets) return;
11457
11677
  const range = specRange(node.ref);
11458
11678
  const target = node.spill ? { start: range.start, end: { ...range.start } } : range;
11459
- for (const sheet of sheets) push(c2, { sheet, range: target });
11679
+ for (const sheet of sheets) push2(c2, { sheet, range: target });
11460
11680
  return;
11461
11681
  }
11462
11682
  case "name": {
@@ -11530,7 +11750,7 @@ function visitBinary(node, c2) {
11530
11750
  const list = c2.dynamic > 0 ? c2.dynamicDeps : c2.deps;
11531
11751
  const l = list[list.length - 2];
11532
11752
  const r = list[list.length - 1];
11533
- if (l && r && l.sheet === r.sheet) push(c2, spans([l, r])[0]);
11753
+ if (l && r && l.sheet === r.sheet) push2(c2, spans([l, r])[0]);
11534
11754
  continue;
11535
11755
  }
11536
11756
  const mentioned = [...c2.deps.slice(staticStart), ...c2.dynamicDeps.slice(dynamicStart)];
@@ -11546,7 +11766,7 @@ function addStructured(ref, c2) {
11546
11766
  sheet: c2.sheet,
11547
11767
  row: c2.row,
11548
11768
  col: c2.col});
11549
- if (value instanceof RefValue) for (const area of value.areas) push(c2, area);
11769
+ if (value instanceof RefValue) for (const area of value.areas) push2(c2, area);
11550
11770
  }
11551
11771
  function analyze(ast, host, sheet, row2, col) {
11552
11772
  const c2 = {
@@ -11570,155 +11790,191 @@ function analyze(ast, host, sheet, row2, col) {
11570
11790
  };
11571
11791
  }
11572
11792
 
11573
- // xlsx/formula/area-index.ts
11574
- var BUCKET_WIDTH = 64;
11575
- var CHUNK_SHIFT = 6;
11576
- var CHUNKS = 64;
11577
- function push2(map, key, value) {
11578
- const list = map.get(key);
11579
- if (list) list.push(value);
11580
- else map.set(key, [value]);
11793
+ // xlsx/formula/formula-shape.ts
11794
+ var isDigit4 = (code) => code >= 48 && code <= 57;
11795
+ function formulaShape(formula) {
11796
+ const starts = [];
11797
+ const ends = [];
11798
+ let hash = 2166136261;
11799
+ for (let i2 = 0; i2 < formula.length; i2++) {
11800
+ let code = formula.charCodeAt(i2);
11801
+ if (isDigit4(code)) {
11802
+ let j = i2 + 1;
11803
+ while (j < formula.length && isDigit4(formula.charCodeAt(j))) j++;
11804
+ starts.push(i2);
11805
+ ends.push(j);
11806
+ i2 = j - 1;
11807
+ code = 0;
11808
+ }
11809
+ hash = Math.imul(hash ^ code, 16777619);
11810
+ }
11811
+ return { hash: hash >>> 0, starts, ends };
11581
11812
  }
11582
- function inner(map, sheet) {
11583
- let found = map.get(sheet);
11584
- if (!found) map.set(sheet, found = /* @__PURE__ */ new Map());
11585
- return found;
11813
+ function sameText(a2, from, b, at, length) {
11814
+ for (let k = 0; k < length; k++)
11815
+ if (a2.charCodeAt(from + k) !== b.charCodeAt(at + k)) return false;
11816
+ return true;
11586
11817
  }
11587
- var AreaIndex = class {
11588
- cells = /* @__PURE__ */ new Map();
11589
- chunked = /* @__PURE__ */ new Map();
11590
- tall = /* @__PURE__ */ new Map();
11591
- wide = /* @__PURE__ */ new Map();
11592
- add(area, node) {
11593
- const { start, end } = area.range;
11594
- if (start.row === end.row && end.col - start.col + 1 <= BUCKET_WIDTH) {
11595
- const cells = inner(this.cells, area.sheet);
11596
- for (let col = start.col; col <= end.col; col++) push2(cells, cellKey(start.row, col), node);
11597
- return;
11818
+ function sameShape(a2, as, b, bs) {
11819
+ const runs = as.starts.length;
11820
+ if (runs !== bs.starts.length) return false;
11821
+ let fromA = 0;
11822
+ let fromB = 0;
11823
+ for (let i2 = 0; i2 <= runs; i2++) {
11824
+ const toA = i2 < runs ? as.starts[i2] : a2.length;
11825
+ const toB = i2 < runs ? bs.starts[i2] : b.length;
11826
+ if (toA - fromA !== toB - fromB || !sameText(a2, fromA, b, fromB, toA - fromA)) return false;
11827
+ fromA = as.ends[i2] ?? 0;
11828
+ fromB = bs.ends[i2] ?? 0;
11829
+ }
11830
+ return true;
11831
+ }
11832
+ function makeTemplate(formula, shape2) {
11833
+ let tokens2;
11834
+ let ast;
11835
+ try {
11836
+ tokens2 = tokenize(formula);
11837
+ ast = parseTokens(tokens2);
11838
+ } catch (e) {
11839
+ if (e instanceof RangeError) return new FormulaError(e.message, -1, "#VALUE!");
11840
+ if (e instanceof FormulaError) return e;
11841
+ throw e;
11842
+ }
11843
+ const { starts } = shape2;
11844
+ const slotted = starts.map(() => false);
11845
+ const refs = /* @__PURE__ */ new Map();
11846
+ let run2 = 0;
11847
+ for (const token of tokens2) {
11848
+ const end = token.start + token.text.length;
11849
+ const first2 = run2;
11850
+ while (run2 < starts.length && starts[run2] < end) run2++;
11851
+ const ref = token.kind === "ref" ? token.ref : void 0;
11852
+ if (!ref || ref.kind === "cols") continue;
11853
+ const count2 = ref.kind === "cell" ? 1 : 2;
11854
+ if (run2 - first2 < count2) continue;
11855
+ const at = run2 - count2;
11856
+ const indexes2 = count2 === 1 ? [at] : [at, at + 1];
11857
+ if (indexes2.some((i2) => formula.charCodeAt(starts[i2]) === 48)) continue;
11858
+ for (const i2 of indexes2) slotted[i2] = true;
11859
+ refs.set(ref, count2 === 1 ? { start: at } : { start: at, end: at + 1 });
11860
+ }
11861
+ return { formula, shape: shape2, ast, slotted, refs };
11862
+ }
11863
+ function rowsFor(t, formula, shape2) {
11864
+ if (!sameShape(t.formula, t.shape, formula, shape2)) return void 0;
11865
+ const rows = [];
11866
+ for (let i2 = 0; i2 < shape2.starts.length; i2++) {
11867
+ const start = shape2.starts[i2];
11868
+ const length = shape2.ends[i2] - start;
11869
+ if (!t.slotted[i2]) {
11870
+ const own = t.shape.starts[i2];
11871
+ if (t.shape.ends[i2] - own !== length) return void 0;
11872
+ if (!sameText(t.formula, own, formula, start, length)) return void 0;
11873
+ rows.push(-1);
11874
+ continue;
11598
11875
  }
11599
- const entry3 = { range: area.range, node };
11600
- if (end.col - start.col + 1 > BUCKET_WIDTH) {
11601
- const list = this.wide.get(area.sheet);
11602
- if (list) list.push(entry3);
11603
- else this.wide.set(area.sheet, [entry3]);
11604
- return;
11876
+ if (length > 7 || formula.charCodeAt(start) === 48) return void 0;
11877
+ let row2 = 0;
11878
+ for (let k = start; k < start + length; k++) row2 = row2 * 10 + formula.charCodeAt(k) - 48;
11879
+ if (row2 < 1 || row2 > MAX_ROW + 1) return void 0;
11880
+ rows.push(row2 - 1);
11881
+ }
11882
+ return rows;
11883
+ }
11884
+ function shiftSpec(spec2, slots, rows) {
11885
+ const startRow = rows[slots.start];
11886
+ const endRow = slots.end === void 0 ? startRow : rows[slots.end];
11887
+ if (startRow === spec2.start.row && endRow === spec2.end.row) return spec2;
11888
+ const { start: from, end: to } = spec2;
11889
+ const start = { row: startRow, col: from.col, rowAbs: from.rowAbs, colAbs: from.colAbs };
11890
+ if (slots.end === void 0) return { kind: spec2.kind, start, end: start };
11891
+ const end = { row: endRow, col: to.col, rowAbs: to.rowAbs, colAbs: to.colAbs };
11892
+ return { kind: spec2.kind, start, end };
11893
+ }
11894
+ function copyTree(node, t, rows) {
11895
+ switch (node.type) {
11896
+ case "ref": {
11897
+ const slots = node.ref ? t.refs.get(node.ref) : void 0;
11898
+ if (!slots || !node.ref) return node;
11899
+ const ref = shiftSpec(node.ref, slots, rows);
11900
+ if (ref === node.ref) return node;
11901
+ const copy = { type: "ref" };
11902
+ if (node.prefix) copy.prefix = node.prefix;
11903
+ copy.ref = ref;
11904
+ if (node.spill) copy.spill = true;
11905
+ return copy;
11605
11906
  }
11606
- const first2 = start.row >> CHUNK_SHIFT;
11607
- const last = end.row >> CHUNK_SHIFT;
11608
- if (last - first2 + 1 > CHUNKS) {
11609
- const cols2 = inner(this.tall, area.sheet);
11610
- for (let c2 = start.col; c2 <= end.col; c2++) push2(cols2, c2, entry3);
11611
- return;
11907
+ case "unary":
11908
+ case "percent": {
11909
+ const operand4 = copyTree(node.operand, t, rows);
11910
+ if (operand4 === node.operand) return node;
11911
+ return node.type === "unary" ? { type: "unary", op: node.op, operand: operand4 } : { type: "percent", operand: operand4 };
11612
11912
  }
11613
- const cols = inner(this.chunked, area.sheet);
11614
- for (let c2 = start.col; c2 <= end.col; c2++) {
11615
- let chunks = cols.get(c2);
11616
- if (!chunks) cols.set(c2, chunks = /* @__PURE__ */ new Map());
11617
- for (let k = first2; k <= last; k++) push2(chunks, k, entry3);
11913
+ case "binary": {
11914
+ const left2 = copyTree(node.left, t, rows);
11915
+ const right2 = copyTree(node.right, t, rows);
11916
+ if (left2 === node.left && right2 === node.right) return node;
11917
+ return { type: "binary", op: node.op, left: left2, right: right2 };
11618
11918
  }
11619
- }
11620
- /** Items whose areas intersect `range` on `sheet` (each once). */
11621
- dependents(sheet, range, out) {
11622
- const found = out instanceof Set ? out : /* @__PURE__ */ new Set();
11623
- this.collect(sheet, range, found);
11624
- if (Array.isArray(out)) for (const node of found) out.push(node);
11625
- }
11626
- collect(sheet, range, out) {
11627
- const { start, end } = range;
11628
- const check3 = (list) => {
11629
- if (list) {
11630
- for (const entry3 of list) if (rangesIntersect(entry3.range, range)) out.add(entry3.node);
11631
- }
11632
- };
11633
- const cells = this.cells.get(sheet);
11634
- if (cells) {
11635
- const size = (end.row - start.row + 1) * (end.col - start.col + 1);
11636
- if (size <= 4096) {
11637
- for (let r = start.row; r <= end.row; r++) {
11638
- for (let c2 = start.col; c2 <= end.col; c2++) {
11639
- const list = cells.get(cellKey(r, c2));
11640
- if (list) for (const node of list) out.add(node);
11641
- }
11642
- }
11643
- } else {
11644
- for (const [key, list] of cells) {
11645
- const { row: row2, col } = keyToAddress(key);
11646
- if (row2 >= start.row && row2 <= end.row && col >= start.col && col <= end.col)
11647
- for (const node of list) out.add(node);
11648
- }
11649
- }
11919
+ case "call": {
11920
+ const args = copyAll(node.args, t, rows);
11921
+ if (args === node.args) return node;
11922
+ return { type: "call", name: node.name, rawName: node.rawName, args };
11650
11923
  }
11651
- const columns = (map, visit2) => {
11652
- if (!map) return;
11653
- if (end.col - start.col + 1 <= map.size) {
11654
- for (let c2 = start.col; c2 <= end.col; c2++) if (map.has(c2)) visit2(c2);
11655
- } else for (const c2 of map.keys()) if (c2 >= start.col && c2 <= end.col) visit2(c2);
11656
- };
11657
- const chunked = this.chunked.get(sheet);
11658
- const first2 = start.row >> CHUNK_SHIFT;
11659
- const last = end.row >> CHUNK_SHIFT;
11660
- columns(chunked, (c2) => {
11661
- const chunks = chunked?.get(c2);
11662
- if (last - first2 + 1 <= chunks.size) {
11663
- for (let k = first2; k <= last; k++) check3(chunks.get(k));
11664
- } else for (const [k, list] of chunks) if (k >= first2 && k <= last) check3(list);
11665
- });
11666
- const tall = this.tall.get(sheet);
11667
- columns(tall, (c2) => check3(tall?.get(c2)));
11668
- check3(this.wide.get(sheet));
11669
- }
11670
- };
11671
-
11672
- // xlsx/formula/graph-index.ts
11673
- var ColumnIndex = class {
11674
- sheets = /* @__PURE__ */ new Map();
11675
- constructor(nodes) {
11676
- for (const node of nodes) {
11677
- let cols = this.sheets.get(node.sheet);
11678
- if (!cols) this.sheets.set(node.sheet, cols = /* @__PURE__ */ new Map());
11679
- let list = cols.get(node.col);
11680
- if (!list) cols.set(node.col, list = []);
11681
- list.push(node);
11924
+ case "invoke": {
11925
+ const callee = copyTree(node.callee, t, rows);
11926
+ const args = copyAll(node.args, t, rows);
11927
+ if (callee === node.callee && args === node.args) return node;
11928
+ return { type: "invoke", callee, args };
11682
11929
  }
11683
- for (const cols of this.sheets.values())
11684
- for (const list of cols.values()) list.sort((a2, b) => a2.row - b.row);
11930
+ default:
11931
+ return node;
11685
11932
  }
11686
- nodesIn(area, out) {
11687
- const cols = this.sheets.get(area.sheet);
11688
- if (!cols) return;
11689
- const { start, end } = area.range;
11690
- const width = end.col - start.col + 1;
11691
- const scan4 = (list) => {
11692
- let lo = 0;
11693
- let hi = list.length;
11694
- while (lo < hi) {
11695
- const mid = lo + hi >> 1;
11696
- if (list[mid].row < start.row) lo = mid + 1;
11697
- else hi = mid;
11698
- }
11699
- for (let i2 = lo; i2 < list.length; i2++) {
11700
- const node = list[i2];
11701
- if (node.row > end.row) break;
11702
- out.push(node);
11703
- }
11704
- };
11705
- if (width <= cols.size) {
11706
- for (let c2 = start.col; c2 <= end.col; c2++) {
11707
- const list = cols.get(c2);
11708
- if (list) scan4(list);
11709
- }
11710
- } else {
11711
- for (const [c2, list] of cols) if (c2 >= start.col && c2 <= end.col) scan4(list);
11712
- }
11933
+ }
11934
+ function copyAll(nodes, t, rows) {
11935
+ let out;
11936
+ for (let i2 = 0; i2 < nodes.length; i2++) {
11937
+ const node = nodes[i2];
11938
+ const copy = copyTree(node, t, rows);
11939
+ if (copy !== node && !out) out = nodes.slice(0, i2);
11940
+ out?.push(copy);
11941
+ }
11942
+ return out ?? nodes;
11943
+ }
11944
+ function fromTemplate(t, formula, shape2) {
11945
+ const rows = rowsFor(t, formula, shape2);
11946
+ return rows ? copyTree(t.ast, t, rows) : void 0;
11947
+ }
11948
+
11949
+ // xlsx/formula/parse-cache.ts
11950
+ var MAX_TEMPLATE_LENGTH = 2048;
11951
+ var MAX_ENTRIES = 1e5;
11952
+ var MAX_TEMPLATES = 1e4;
11953
+ var NO_RUNS = { hash: 0, starts: [], ends: [] };
11954
+ var treeOf = (made) => "ast" in made ? made.ast : made;
11955
+ var ParseCache = class {
11956
+ byText = /* @__PURE__ */ new Map();
11957
+ templates = /* @__PURE__ */ new Map();
11958
+ parse(formula) {
11959
+ let ast = this.byText.get(formula);
11960
+ if (ast) return ast;
11961
+ ast = this.parseNew(formula);
11962
+ if (this.byText.size > MAX_ENTRIES) this.byText.clear();
11963
+ this.byText.set(formula, ast);
11964
+ return ast;
11713
11965
  }
11714
- };
11715
- var ReverseIndex = class extends AreaIndex {
11716
- constructor(nodes) {
11717
- super();
11718
- for (const node of nodes) {
11719
- for (const dep of node.deps) this.add(dep, node);
11720
- for (const dep of node.dynamicDeps) this.add(dep, node);
11966
+ parseNew(formula) {
11967
+ if (formula.length > MAX_TEMPLATE_LENGTH) return treeOf(makeTemplate(formula, NO_RUNS));
11968
+ const shape2 = formulaShape(formula);
11969
+ const template = this.templates.get(shape2.hash);
11970
+ const reused = template && fromTemplate(template, formula, shape2);
11971
+ if (reused) return reused;
11972
+ const made = makeTemplate(formula, shape2);
11973
+ if (!template && "ast" in made) {
11974
+ if (this.templates.size > MAX_TEMPLATES) this.templates.clear();
11975
+ this.templates.set(shape2.hash, made);
11721
11976
  }
11977
+ return treeOf(made);
11722
11978
  }
11723
11979
  };
11724
11980
 
@@ -11859,7 +12115,7 @@ var EngineHost = class {
11859
12115
  options;
11860
12116
  nodes = /* @__PURE__ */ new Map();
11861
12117
  footprints = /* @__PURE__ */ new Set();
11862
- astCache = /* @__PURE__ */ new Map();
12118
+ parsed = new ParseCache();
11863
12119
  boundsCache = /* @__PURE__ */ new Map();
11864
12120
  inProgress = /* @__PURE__ */ new Set();
11865
12121
  cycles = /* @__PURE__ */ new Set();
@@ -11883,6 +12139,8 @@ var EngineHost = class {
11883
12139
  evaluations = 0;
11884
12140
  built = false;
11885
12141
  needsFull = false;
12142
+ /** No recalculation has run since the workbook was opened: stored values may stand. */
12143
+ fresh = true;
11886
12144
  // ---- EvalHost ----
11887
12145
  readCell(sheet, row2, col) {
11888
12146
  const cell = this.workbook.sheets[sheet]?.rows.get(row2)?.get(col);
@@ -11971,41 +12229,15 @@ var EngineHost = class {
11971
12229
  return this.workbook.sheets[sheet]?.rows.get(row2)?.get(col)?.formula;
11972
12230
  }
11973
12231
  parse(formula) {
11974
- let ast = this.astCache.get(formula);
11975
- if (!ast) {
11976
- try {
11977
- ast = parseFormula(formula);
11978
- } catch (e) {
11979
- if (e instanceof RangeError) ast = new FormulaError(e.message, -1, "#VALUE!");
11980
- else if (!(e instanceof FormulaError)) throw e;
11981
- else ast = e;
11982
- }
11983
- if (this.astCache.size > 1e5) this.astCache.clear();
11984
- this.astCache.set(formula, ast);
11985
- }
11986
- return ast;
12232
+ return this.parsed.parse(formula);
11987
12233
  }
11988
12234
  now() {
11989
12235
  return this.options.now ? this.options.now() : /* @__PURE__ */ new Date();
11990
12236
  }
11991
- random() {
11992
- return this.options.random ? this.options.random() : Math.random();
11993
- }
11994
- // ---- graph ----
11995
- build() {
11996
- this.nodes.clear();
11997
- this.footprints.clear();
11998
- this.footprintIndex = void 0;
11999
- this.workbook.sheets.forEach((sheet, s) => {
12000
- for (const [row2, cells] of sheet.rows) {
12001
- for (const [col, cell] of cells) {
12002
- if (cell.formula) this.createNode(s, row2, col, cell, true);
12003
- }
12004
- }
12005
- });
12006
- this.built = true;
12007
- this.graphChanged();
12008
- }
12237
+ random() {
12238
+ return this.options.random ? this.options.random() : Math.random();
12239
+ }
12240
+ // ---- graph ----
12009
12241
  createNode(sheet, row2, col, cell, initial) {
12010
12242
  const formula = cell.formula ?? "";
12011
12243
  const parsed = this.parse(formula);
@@ -12034,6 +12266,14 @@ var EngineHost = class {
12034
12266
  map.set(cellKey(row2, col), node);
12035
12267
  return node;
12036
12268
  }
12269
+ /** Parses a node's text again after a structural edit rewrote it (see `FormulaNode.stale`). */
12270
+ refreshAst(node) {
12271
+ const parsed = this.parse(node.formula);
12272
+ delete node.stale;
12273
+ delete node.parseError;
12274
+ node.ast = parsed instanceof FormulaError ? void 0 : parsed;
12275
+ if (parsed instanceof FormulaError && parsed.code) node.parseError = err(parsed.code);
12276
+ }
12037
12277
  removeNode(node, changed) {
12038
12278
  const sheet = this.workbook.sheets[node.sheet];
12039
12279
  if (node.spill && sheet) {
@@ -12464,6 +12704,7 @@ var EngineCore = class extends EngineHost {
12464
12704
  return { host: this, sheet, row: row2, col, scope: void 0, depth: 0, root, legacy };
12465
12705
  }
12466
12706
  evaluateFormula(node) {
12707
+ if (node.stale) this.refreshAst(node);
12467
12708
  if (!node.ast) return node.parseError ?? ERR.NAME;
12468
12709
  const ast = node.ast;
12469
12710
  const frame = this.frameFor(node.sheet, node.row, node.col, ast, node.legacy);
@@ -12481,20 +12722,363 @@ var EngineCore = class extends EngineHost {
12481
12722
  }
12482
12723
  };
12483
12724
 
12725
+ // xlsx/formula/shift-graph.ts
12726
+ var POSITIONAL = /* @__PURE__ */ new Set(["ROW", "COLUMN"]);
12727
+ var DESCRIPTIVE = /* @__PURE__ */ new Set(["FORMULATEXT", "CELL", "SHEET"]);
12728
+ var traitsCache = /* @__PURE__ */ new WeakMap();
12729
+ function astTraits(ast) {
12730
+ const cached = traitsCache.get(ast);
12731
+ if (cached) return cached;
12732
+ const sheets = /* @__PURE__ */ new Set();
12733
+ const traits = { complex: false, opaque: false, positional: false, descriptive: false, sheets };
12734
+ const stack2 = [ast];
12735
+ while (stack2.length) {
12736
+ const node = stack2.pop();
12737
+ switch (node.type) {
12738
+ case "ref":
12739
+ if (node.prefix) {
12740
+ sheets.add(node.prefix.sheet.toLowerCase());
12741
+ if (node.prefix.sheet2 !== void 0) {
12742
+ sheets.add(node.prefix.sheet2.toLowerCase());
12743
+ traits.complex = true;
12744
+ }
12745
+ }
12746
+ break;
12747
+ case "name":
12748
+ if (node.prefix) sheets.add(node.prefix.sheet.toLowerCase());
12749
+ traits.complex = true;
12750
+ break;
12751
+ case "structured":
12752
+ traits.complex = true;
12753
+ break;
12754
+ case "unary":
12755
+ case "percent":
12756
+ stack2.push(node.operand);
12757
+ break;
12758
+ case "binary":
12759
+ stack2.push(node.left, node.right);
12760
+ break;
12761
+ case "call":
12762
+ if (POSITIONAL.has(node.name)) traits.positional = true;
12763
+ if (DESCRIPTIVE.has(node.name)) traits.descriptive = true;
12764
+ if (!getFunction(node.name)) traits.complex = traits.opaque = true;
12765
+ stack2.push(...node.args);
12766
+ break;
12767
+ case "invoke":
12768
+ stack2.push(node.callee, ...node.args);
12769
+ break;
12770
+ }
12771
+ }
12772
+ traitsCache.set(ast, traits);
12773
+ return traits;
12774
+ }
12775
+ function intervalDelta(a2, b, shift2) {
12776
+ const { at, count: count2 } = shift2;
12777
+ if (count2 > 0) {
12778
+ if (b < at) return 0;
12779
+ if (a2 < at) return void 0;
12780
+ return b + count2 > (shift2.axis === "row" ? MAX_ROW : MAX_COL) ? void 0 : count2;
12781
+ }
12782
+ const last = at - count2 - 1;
12783
+ if (b < at) return 0;
12784
+ if (a2 > last) return count2;
12785
+ return void 0;
12786
+ }
12787
+ function areaDelta(area, sheet, shift2) {
12788
+ if (area.sheet !== sheet) return 0;
12789
+ const { start, end } = area.range;
12790
+ return shift2.axis === "row" ? intervalDelta(start.row, end.row, shift2) : intervalDelta(start.col, end.col, shift2);
12791
+ }
12792
+ function movedRange(range, axis, delta) {
12793
+ if (delta === 0) return range;
12794
+ return axis === "row" ? {
12795
+ start: { row: range.start.row + delta, col: range.start.col },
12796
+ end: { row: range.end.row + delta, col: range.end.col }
12797
+ } : {
12798
+ start: { row: range.start.row, col: range.start.col + delta },
12799
+ end: { row: range.end.row, col: range.end.col + delta }
12800
+ };
12801
+ }
12802
+ function reachesEdit(areas, sheet, shift2) {
12803
+ for (const area of areas) {
12804
+ if (area.sheet !== sheet) continue;
12805
+ if ((shift2.axis === "row" ? area.range.end.row : area.range.end.col) >= shift2.at) return true;
12806
+ }
12807
+ return false;
12808
+ }
12809
+ function intersectionMoves(area, delta, pos, nodeDelta, axis) {
12810
+ if (delta === nodeDelta) return false;
12811
+ const { start, end } = area.range;
12812
+ const a2 = axis === "row" ? start.row : start.col;
12813
+ const b = axis === "row" ? end.row : end.col;
12814
+ if (a2 === b) return false;
12815
+ return pos >= a2 && pos <= b || pos + nodeDelta >= a2 + delta && pos + nodeDelta <= b + delta;
12816
+ }
12817
+
12818
+ // xlsx/formula/engine-structure.ts
12819
+ var sameAreas = (a2, b) => a2.length === b.length && a2.every((x, i2) => {
12820
+ const y = b[i2];
12821
+ return x.sheet === y.sheet && sameRange(x.range, y.range);
12822
+ });
12823
+ var EngineStructure = class extends EngineCore {
12824
+ /** Formulas a structural edit left to recalculate (with their dependents) on the next pass. */
12825
+ structuralSeeds = /* @__PURE__ */ new Set();
12826
+ /** Whether the graph describes the workbook as it was before the edit just reported. */
12827
+ graphReady() {
12828
+ return this.built && !this.needsFull;
12829
+ }
12830
+ /** Parses a node's current text again and recomputes its precedents. */
12831
+ reanalyze(node) {
12832
+ const parsed = this.parse(node.formula);
12833
+ delete node.stale;
12834
+ delete node.parseError;
12835
+ if (parsed instanceof FormulaError) {
12836
+ node.ast = void 0;
12837
+ if (parsed.code) node.parseError = err(parsed.code);
12838
+ node.deps = [];
12839
+ node.dynamicDeps = [];
12840
+ return;
12841
+ }
12842
+ node.ast = parsed;
12843
+ const found = analyze(parsed, this, node.sheet, node.row, node.col);
12844
+ node.deps = found.deps;
12845
+ node.dynamicDeps = found.dynamicDeps;
12846
+ node.volatile = found.volatile;
12847
+ node.unsupported = found.unsupported;
12848
+ }
12849
+ /**
12850
+ * Moves the graph for rows or columns inserted or deleted on `sheet`, after the workbook was
12851
+ * changed (cells moved, formulas rewritten). Spills on the sheet, array formulas the edit cuts
12852
+ * and anything unexpected fall back to a rebuild on the next recalculation.
12853
+ */
12854
+ shiftCells(sheet, shift2) {
12855
+ if (!this.graphReady() || !this.shiftable(sheet, shift2)) {
12856
+ this.invalidate();
12857
+ return;
12858
+ }
12859
+ const ws = this.workbook.sheets[sheet];
12860
+ const own = this.nodes.get(sheet);
12861
+ if (!ws) return;
12862
+ const moved = /* @__PURE__ */ new Map();
12863
+ if (own) {
12864
+ const next = /* @__PURE__ */ new Map();
12865
+ for (const node of own.values()) {
12866
+ const pos = shift2.axis === "row" ? node.row : node.col;
12867
+ const delta = intervalDelta(pos, pos, shift2);
12868
+ if (delta === void 0) {
12869
+ this.dropNode(node);
12870
+ continue;
12871
+ }
12872
+ if (delta !== 0) {
12873
+ moved.set(node, delta);
12874
+ if (shift2.axis === "row") node.row += delta;
12875
+ else node.col += delta;
12876
+ }
12877
+ next.set(cellKey(node.row, node.col), node);
12878
+ }
12879
+ this.nodes.set(sheet, next);
12880
+ }
12881
+ for (const map of this.nodes.values())
12882
+ for (const node of map.values()) {
12883
+ if (!this.shiftNode(node, sheet, shift2, moved.get(node) ?? 0)) {
12884
+ this.invalidate();
12885
+ return;
12886
+ }
12887
+ }
12888
+ this.boundsCache.clear();
12889
+ this.graphChanged();
12890
+ }
12891
+ /** No spill or stale spilled value on the sheet, and no array formula the edit cuts. */
12892
+ shiftable(sheet, shift2) {
12893
+ for (const node of this.footprints) {
12894
+ if (node.sheet !== sheet) continue;
12895
+ if (node.spill || node.blockedSpill) return false;
12896
+ if (node.arrayRange && areaDelta({ sheet, range: node.arrayRange }, sheet, shift2) === void 0)
12897
+ return false;
12898
+ }
12899
+ const ws = this.workbook.sheets[sheet];
12900
+ let spilled = false;
12901
+ ws?.rows.forEach((cells) => {
12902
+ if (!spilled) cells.forEach((cell) => spilled ||= isSpilledCell(cell));
12903
+ });
12904
+ return !spilled;
12905
+ }
12906
+ dropNode(node) {
12907
+ this.structuralSeeds.delete(node);
12908
+ this.cycles.delete(node);
12909
+ this.footprints.delete(node);
12910
+ }
12911
+ /** Updates one formula for the edit; false when the graph cannot follow it. */
12912
+ shiftNode(node, sheet, shift2, nodeDelta) {
12913
+ const cell = this.workbook.sheets[node.sheet]?.rows.get(node.row)?.get(node.col);
12914
+ if (cell?.formula === void 0) return false;
12915
+ if (node.arrayRange) {
12916
+ const delta = areaDelta({ sheet: node.sheet, range: node.arrayRange }, sheet, shift2);
12917
+ if (delta === void 0) return false;
12918
+ node.arrayRange = movedRange(node.arrayRange, shift2.axis, delta);
12919
+ if (!cell.arrayRange || !sameRange(node.arrayRange, normalizeRange(cell.arrayRange)))
12920
+ return false;
12921
+ }
12922
+ const changed = cell.formula !== node.formula;
12923
+ const traits = node.ast && astTraits(node.ast);
12924
+ const reached = reachesEdit(node.deps, sheet, shift2) || reachesEdit(node.dynamicDeps, sheet, shift2);
12925
+ if (!changed && !reached && nodeDelta === 0 && !traits?.descriptive && !traits?.opaque)
12926
+ return true;
12927
+ if (traits?.complex) {
12928
+ node.formula = cell.formula;
12929
+ this.reanalyze(node);
12930
+ this.structuralSeeds.add(node);
12931
+ return true;
12932
+ }
12933
+ const pos = shift2.axis === "row" ? node.row - nodeDelta : node.col - nodeDelta;
12934
+ const moves = { seed: !!traits?.descriptive, moved: false, cut: false };
12935
+ const deps = this.moveAreas(node.deps, sheet, shift2, pos, nodeDelta, moves);
12936
+ const dynamicDeps = this.moveAreas(node.dynamicDeps, sheet, shift2, pos, nodeDelta, moves);
12937
+ const { cut, moved: anyMoved } = moves;
12938
+ let seed = moves.seed;
12939
+ if (cut || changed !== anyMoved) {
12940
+ node.formula = cell.formula;
12941
+ this.reanalyze(node);
12942
+ this.structuralSeeds.add(node);
12943
+ return true;
12944
+ }
12945
+ if (traits?.positional && (anyMoved || nodeDelta !== 0)) seed = true;
12946
+ node.deps = deps;
12947
+ node.dynamicDeps = dynamicDeps;
12948
+ if (changed) {
12949
+ node.formula = cell.formula;
12950
+ node.stale = true;
12951
+ }
12952
+ if (seed) this.structuralSeeds.add(node);
12953
+ return true;
12954
+ }
12955
+ /**
12956
+ * Areas moved for the edit (the same list when none moves). Records in `moves` whether one
12957
+ * moved, one was cut (deleted, widened, pushed off the grid) and whether implicit intersection
12958
+ * with one can now pick another cell.
12959
+ */
12960
+ moveAreas(list, sheet, shift2, pos, nodeDelta, moves) {
12961
+ let out;
12962
+ for (let i2 = 0; i2 < list.length; i2++) {
12963
+ const area = list[i2];
12964
+ const delta = areaDelta(area, sheet, shift2);
12965
+ if (delta === void 0) {
12966
+ moves.cut = true;
12967
+ continue;
12968
+ }
12969
+ if (intersectionMoves(area, delta, pos, nodeDelta, shift2.axis)) moves.seed = true;
12970
+ if (delta === 0) continue;
12971
+ moves.moved = true;
12972
+ out ??= list.slice();
12973
+ out[i2] = { sheet: area.sheet, range: movedRange(area.range, shift2.axis, delta) };
12974
+ }
12975
+ return out ?? list;
12976
+ }
12977
+ /**
12978
+ * Follows a sheet rename (`from` to `to`, formulas already rewritten): precedents are kept by
12979
+ * sheet index, so only rewritten formulas need their text parsed again, and only formulas that
12980
+ * name the new sheet without having been rewritten (previously unresolved), describe sheets
12981
+ * (CELL, SHEET, FORMULATEXT) or read defined names whose areas changed are recalculated.
12982
+ */
12983
+ renameSheet(from, to) {
12984
+ if (!this.graphReady()) {
12985
+ this.invalidate();
12986
+ return;
12987
+ }
12988
+ const target = to.toLowerCase();
12989
+ let depsChanged = false;
12990
+ for (const map of this.nodes.values())
12991
+ for (const node of map.values()) {
12992
+ const cell = this.workbook.sheets[node.sheet]?.rows.get(node.row)?.get(node.col);
12993
+ if (cell?.formula === void 0) {
12994
+ this.invalidate();
12995
+ return;
12996
+ }
12997
+ const changed = cell.formula !== node.formula;
12998
+ const traits = node.ast && astTraits(node.ast);
12999
+ node.formula = cell.formula;
13000
+ if (traits?.complex || !changed && traits?.sheets.has(target)) {
13001
+ const deps = node.deps;
13002
+ const dynamicDeps = node.dynamicDeps;
13003
+ this.reanalyze(node);
13004
+ const same4 = sameAreas(deps, node.deps) && sameAreas(dynamicDeps, node.dynamicDeps);
13005
+ if (!same4) depsChanged = true;
13006
+ if (!same4 || !traits?.complex) this.structuralSeeds.add(node);
13007
+ } else if (changed) node.stale = true;
13008
+ if (traits?.descriptive || traits?.opaque) this.structuralSeeds.add(node);
13009
+ }
13010
+ if (depsChanged) this.graphChanged();
13011
+ }
13012
+ /** Takes the formulas queued by structural edits. */
13013
+ takeStructuralSeeds(into) {
13014
+ for (const node of this.structuralSeeds)
13015
+ if (this.nodes.get(node.sheet)?.get(cellKey(node.row, node.col)) === node) into.add(node);
13016
+ this.structuralSeeds.clear();
13017
+ }
13018
+ };
13019
+
12484
13020
  // xlsx/formula/engine.ts
12485
- var Engine = class extends EngineCore {
13021
+ var Engine = class extends EngineStructure {
13022
+ preparation;
13023
+ /** The prepared formulas the first recalculation checks (see `trustsStoredValues`). */
13024
+ prepared;
13025
+ // ---- the graph ----
13026
+ prepare(timeRemaining) {
13027
+ if (this.built || this.needsFull) return true;
13028
+ this.preparation ??= this.startPreparation();
13029
+ if (!this.preparation.run(timeRemaining)) return false;
13030
+ this.finishPreparation(this.preparation);
13031
+ return true;
13032
+ }
13033
+ discardPreparation() {
13034
+ if (!this.fresh || this.needsFull) return;
13035
+ this.preparation = void 0;
13036
+ this.prepared = void 0;
13037
+ this.structuralSeeds.clear();
13038
+ this.nodes.clear();
13039
+ this.footprints.clear();
13040
+ this.graphChanged();
13041
+ this.built = false;
13042
+ }
13043
+ /** Completes the graph, continuing a preparation that is under way. */
13044
+ build() {
13045
+ const preparation = this.preparation ?? this.startPreparation();
13046
+ preparation.run();
13047
+ this.finishPreparation(preparation);
13048
+ }
13049
+ startPreparation() {
13050
+ this.nodes.clear();
13051
+ this.footprints.clear();
13052
+ this.footprintIndex = void 0;
13053
+ this.prepared = void 0;
13054
+ return new GraphPreparation(
13055
+ this.workbook,
13056
+ (s, row2, col, cell) => this.createNode(s, row2, col, cell, true)
13057
+ );
13058
+ }
13059
+ finishPreparation(preparation) {
13060
+ this.preparation = void 0;
13061
+ this.built = true;
13062
+ this.graphChanged();
13063
+ this.reverseIndex = preparation.reverse;
13064
+ this.prepared = preparation.formulas;
13065
+ }
12486
13066
  // ---- recalculation ----
12487
13067
  recalculateAll() {
13068
+ this.fresh = false;
13069
+ this.prepared = void 0;
12488
13070
  if (this.needsFull) this.releaseAllSpills();
12489
13071
  if (!this.built || this.needsFull) this.build();
12490
13072
  this.needsFull = false;
13073
+ this.structuralSeeds.clear();
12491
13074
  this.cycles = /* @__PURE__ */ new Set();
12492
13075
  this.run(new Set(this.allNodes()), true);
12493
13076
  }
12494
13077
  recalculateFrom(changes) {
12495
13078
  const seeds = /* @__PURE__ */ new Set();
12496
- if (!this.built && !this.needsFull) {
12497
- this.build();
13079
+ if (this.fresh && !this.needsFull) {
13080
+ this.fresh = false;
13081
+ if (!this.built) this.build();
12498
13082
  if (!this.trustsStoredValues(changes, seeds)) {
12499
13083
  this.recalculateAll();
12500
13084
  return;
@@ -12538,6 +13122,7 @@ var Engine = class extends EngineCore {
12538
13122
  }
12539
13123
  }
12540
13124
  if (structural) this.graphChanged();
13125
+ this.takeStructuralSeeds(seeds);
12541
13126
  const reverse2 = this.reverse();
12542
13127
  for (const area of changed) reverse2.dependents(area.sheet, area.range, seeds);
12543
13128
  for (const node of this.allNodes()) if (node.volatile) seeds.add(node);
@@ -12549,13 +13134,18 @@ var Engine = class extends EngineCore {
12549
13134
  * without a value into `missing`.
12550
13135
  */
12551
13136
  trustsStoredValues(changes, missing) {
13137
+ const prepared = this.prepared;
13138
+ this.prepared = void 0;
13139
+ if (!prepared) return false;
12552
13140
  const changed = new Set(changes.map((c2) => `${c2.sheet}:${cellKey(c2.row, c2.col)}`));
12553
- for (const node of this.allNodes()) {
12554
- const legacyOrArray = node.legacy || node.arrayRange;
12555
- if (!legacyOrArray && !changed.has(`${node.sheet}:${cellKey(node.row, node.col)}`))
13141
+ const current = (node) => this.nodes.get(node.sheet)?.get(cellKey(node.row, node.col)) === node;
13142
+ for (const node of prepared.dynamic) {
13143
+ if (current(node) && !changed.has(`${node.sheet}:${cellKey(node.row, node.col)}`))
12556
13144
  return false;
13145
+ }
13146
+ for (const node of prepared.unvalued) {
12557
13147
  const cell = this.workbook.sheets[node.sheet]?.rows.get(node.row)?.get(node.col);
12558
- if (cell && cell.value === null && !node.keepCached) missing.add(node);
13148
+ if (current(node) && cell && cell.value === null) missing.add(node);
12559
13149
  }
12560
13150
  return true;
12561
13151
  }
@@ -12569,7 +13159,10 @@ var Engine = class extends EngineCore {
12569
13159
  return !!anchor?.spill && rangeHas(anchor.spill, row2, col);
12570
13160
  }
12571
13161
  invalidate() {
13162
+ this.structuralSeeds.clear();
12572
13163
  this.releaseAllSpills();
13164
+ this.preparation = void 0;
13165
+ this.prepared = void 0;
12573
13166
  this.nodes.clear();
12574
13167
  this.footprints.clear();
12575
13168
  this.graphChanged();
@@ -12614,7 +13207,7 @@ function createCalcEngine(workbook, options = {}) {
12614
13207
  return new Engine(workbook, options);
12615
13208
  }
12616
13209
 
12617
- // xlsx/formula/transform.ts
13210
+ // xlsx/formula/ref-text.ts
12618
13211
  function safeTokens(formula) {
12619
13212
  try {
12620
13213
  return tokenize(formula);
@@ -12633,50 +13226,26 @@ function formatRefSpec(spec2) {
12633
13226
  if (spec2.kind === "cell") return a2;
12634
13227
  return `${a2}:${cornerText(spec2.end, spec2.kind)}`;
12635
13228
  }
12636
- function rewrite(token, ref) {
13229
+ function rewriteRef(token, ref) {
12637
13230
  const prefix = token.prefix?.text ?? "";
12638
13231
  if (!ref) return `${prefix}#REF!`;
12639
13232
  return `${prefix}${formatRefSpec(ref)}${token.spill ? "#" : ""}`;
12640
13233
  }
12641
13234
  var sameSpec = (a2, b) => a2.kind === b.kind && a2.start.row === b.start.row && a2.start.col === b.start.col && a2.end.row === b.end.row && a2.end.col === b.end.col;
12642
- function translateFormula(formula, dRow, dCol) {
12643
- const tokens2 = safeTokens(formula);
12644
- if (!tokens2) return formula;
12645
- for (const token of tokens2) {
12646
- if (token.kind !== "ref" || !token.ref) continue;
12647
- const spec2 = token.ref;
12648
- const move = (c2) => {
12649
- const row2 = spec2.kind === "cols" || c2.rowAbs ? c2.row : c2.row + dRow;
12650
- const col = spec2.kind === "rows" || c2.colAbs ? c2.col : c2.col + dCol;
12651
- if (row2 < 0 || row2 > MAX_ROW || col < 0 || col > MAX_COL) return void 0;
12652
- return { ...c2, row: row2, col };
12653
- };
12654
- const start = move(spec2.start);
12655
- const end = move(spec2.end);
12656
- const next = start && end ? { kind: spec2.kind, start, end } : void 0;
12657
- if (next && sameSpec(next, spec2)) continue;
12658
- token.text = rewrite(token, next);
12659
- }
12660
- return joinTokens(tokens2);
13235
+ var needsQuote = (name) => !/^[A-Za-z_¡-￿][A-Za-z0-9_.¡-￿]*$/.test(name) || /^[A-Za-z]{1,3}\d+$/.test(name) || /^(?:R\d*C?\d*|C\d*)$/i.test(name) || /^(?:TRUE|FALSE)$/i.test(name);
13236
+ function prefixText(prefix) {
13237
+ const sheets = prefix.sheet2 !== void 0 ? `${prefix.sheet}:${prefix.sheet2}` : prefix.sheet;
13238
+ const book = prefix.book !== void 0 ? `[${prefix.book}]` : "";
13239
+ const quote2 = needsQuote(prefix.sheet) || prefix.sheet2 !== void 0 && needsQuote(prefix.sheet2);
13240
+ return quote2 ? `'${(book + sheets).replace(/'/g, "''")}'!` : `${book}${sheets}!`;
12661
13241
  }
12662
- var sheetMatches = (prefix, formulaSheet, sheet) => {
12663
- if (prefix?.book !== void 0) return false;
12664
- const name = prefix ? prefix.sheet : formulaSheet;
12665
- return name.toLowerCase() === sheet.toLowerCase();
12666
- };
12667
- function shiftInterval(a2, b, at, count2, max) {
12668
- if (count2 > 0) {
12669
- const na2 = a2 >= at ? a2 + count2 : a2;
12670
- const nb2 = b >= at ? b + count2 : b;
12671
- if (nb2 > max) return na2 > max ? void 0 : [na2, max];
12672
- return [na2, nb2];
12673
- }
12674
- const n2 = -count2;
12675
- const last = at + n2 - 1;
12676
- if (a2 >= at && b <= last) return void 0;
12677
- const na = a2 < at ? a2 : a2 <= last ? at : a2 - n2;
12678
- const nb = b < at ? b : b <= last ? at - 1 : b - n2;
12679
- return [na, nb];
13242
+
13243
+ // xlsx/formula/shift-formula.ts
13244
+ var templates = /* @__PURE__ */ new Map();
13245
+ var MAX_TEMPLATES2 = 2e5;
13246
+ function remember(text3, template) {
13247
+ if (templates.size >= MAX_TEMPLATES2) templates.clear();
13248
+ templates.set(text3, template);
12680
13249
  }
12681
13250
  function mergeSpacedAreas(tokens2) {
12682
13251
  const out = [];
@@ -12703,63 +13272,145 @@ function mergeSpacedAreas(tokens2) {
12703
13272
  }
12704
13273
  return out;
12705
13274
  }
12706
- function shiftFormula(formula, formulaSheet, spec2) {
12707
- if (spec2.count === 0) return formula;
13275
+ function templateOf(formula) {
13276
+ const cached = templates.get(formula);
13277
+ if (cached !== void 0) return cached;
12708
13278
  const raw2 = safeTokens(formula);
12709
- if (!raw2) return formula;
12710
- const tokens2 = mergeSpacedAreas(raw2);
12711
- const isRow = spec2.axis === "row";
12712
- for (const token of tokens2) {
12713
- if (token.kind !== "ref" || !token.ref || !sheetMatches(token.prefix, formulaSheet, spec2.sheet))
12714
- continue;
12715
- const ref = token.ref;
12716
- if (isRow && ref.kind === "cols" || !isRow && ref.kind === "rows") continue;
12717
- const startFirst = isRow ? ref.start.row <= ref.end.row : ref.start.col <= ref.end.col;
12718
- const lo = startFirst ? ref.start : ref.end;
12719
- const hi = startFirst ? ref.end : ref.start;
12720
- const shifted2 = shiftInterval(
12721
- isRow ? lo.row : lo.col,
12722
- isRow ? hi.row : hi.col,
12723
- spec2.at,
12724
- spec2.count,
12725
- isRow ? MAX_ROW : MAX_COL
12726
- );
12727
- let next;
12728
- if (shifted2) {
12729
- const [a2, b] = shifted2;
12730
- const nlo = isRow ? { ...lo, row: a2 } : { ...lo, col: a2 };
12731
- const nhi = isRow ? { ...hi, row: b } : { ...hi, col: b };
12732
- next = { kind: ref.kind, start: startFirst ? nlo : nhi, end: startFirst ? nhi : nlo };
12733
- if (ref.kind === "cell") next.end = next.start;
13279
+ let template = null;
13280
+ if (raw2) {
13281
+ template = [];
13282
+ let literal2 = "";
13283
+ for (const token of mergeSpacedAreas(raw2)) {
13284
+ if (token.kind !== "ref" && !(token.kind === "name" && token.prefix)) {
13285
+ literal2 += token.text;
13286
+ continue;
13287
+ }
13288
+ if (literal2) template.push(literal2);
13289
+ literal2 = "";
13290
+ const part = { kind: token.kind, text: token.text };
13291
+ if (token.prefix) {
13292
+ part.prefix = token.prefix;
13293
+ if (token.prefix.book === void 0) part.sheet = token.prefix.sheet.toLowerCase();
13294
+ }
13295
+ if (token.ref) part.ref = token.ref;
13296
+ if (token.spill) part.spill = true;
13297
+ template.push(part);
12734
13298
  }
12735
- if (next && sameSpec(next, ref)) continue;
12736
- token.text = rewrite(token, next);
13299
+ if (literal2) template.push(literal2);
12737
13300
  }
12738
- return joinTokens(tokens2);
13301
+ remember(formula, template);
13302
+ return template;
12739
13303
  }
12740
- var needsQuote = (name) => !/^[A-Za-z_\u00A1-\uFFFF][A-Za-z0-9_.\u00A1-\uFFFF]*$/.test(name) || /^[A-Za-z]{1,3}\d+$/.test(name) || /^(?:R\d*C?\d*|C\d*)$/i.test(name) || /^(?:TRUE|FALSE)$/i.test(name);
12741
- function prefixText(prefix) {
12742
- const sheets = prefix.sheet2 !== void 0 ? `${prefix.sheet}:${prefix.sheet2}` : prefix.sheet;
12743
- const book = prefix.book !== void 0 ? `[${prefix.book}]` : "";
12744
- const quote2 = needsQuote(prefix.sheet) || prefix.sheet2 !== void 0 && needsQuote(prefix.sheet2);
12745
- return quote2 ? `'${(book + sheets).replace(/'/g, "''")}'!` : `${book}${sheets}!`;
13304
+ function rewriteTemplate(formula, rewrite2) {
13305
+ const template = templateOf(formula);
13306
+ if (!template) return formula;
13307
+ let next;
13308
+ for (let i2 = 0; i2 < template.length; i2++) {
13309
+ const part = template[i2];
13310
+ if (typeof part === "string") continue;
13311
+ const changed = rewrite2(part);
13312
+ if (!changed) continue;
13313
+ next ??= template.slice();
13314
+ next[i2] = changed;
13315
+ }
13316
+ if (!next) return formula;
13317
+ const text3 = next.map((part) => typeof part === "string" ? part : part.text).join("");
13318
+ remember(text3, next);
13319
+ return text3;
13320
+ }
13321
+ function shiftInterval(a2, b, at, count2, max) {
13322
+ if (count2 > 0) {
13323
+ const na2 = a2 >= at ? a2 + count2 : a2;
13324
+ const nb2 = b >= at ? b + count2 : b;
13325
+ if (nb2 > max) return na2 > max ? void 0 : [na2, max];
13326
+ return [na2, nb2];
13327
+ }
13328
+ const n2 = -count2;
13329
+ const last = at + n2 - 1;
13330
+ if (a2 >= at && b <= last) return void 0;
13331
+ const na = a2 < at ? a2 : a2 <= last ? at : a2 - n2;
13332
+ const nb = b < at ? b : b <= last ? at - 1 : b - n2;
13333
+ return [na, nb];
13334
+ }
13335
+ function shiftRef(ref, spec2) {
13336
+ const isRow = spec2.axis === "row";
13337
+ if (isRow && ref.kind === "cols" || !isRow && ref.kind === "rows") return ref;
13338
+ const startFirst = isRow ? ref.start.row <= ref.end.row : ref.start.col <= ref.end.col;
13339
+ const lo = startFirst ? ref.start : ref.end;
13340
+ const hi = startFirst ? ref.end : ref.start;
13341
+ const shifted2 = shiftInterval(
13342
+ isRow ? lo.row : lo.col,
13343
+ isRow ? hi.row : hi.col,
13344
+ spec2.at,
13345
+ spec2.count,
13346
+ isRow ? MAX_ROW : MAX_COL
13347
+ );
13348
+ if (!shifted2) return void 0;
13349
+ const [a2, b] = shifted2;
13350
+ const nlo = isRow ? { ...lo, row: a2 } : { ...lo, col: a2 };
13351
+ const nhi = isRow ? { ...hi, row: b } : { ...hi, col: b };
13352
+ const next = {
13353
+ kind: ref.kind,
13354
+ start: startFirst ? nlo : nhi,
13355
+ end: startFirst ? nhi : nlo
13356
+ };
13357
+ if (ref.kind === "cell") next.end = next.start;
13358
+ return sameSpec(next, ref) ? ref : next;
13359
+ }
13360
+ function shiftFormula(formula, formulaSheet, spec2) {
13361
+ if (spec2.count === 0) return formula;
13362
+ const sheet = spec2.sheet.toLowerCase();
13363
+ const own = formulaSheet.toLowerCase() === sheet;
13364
+ return rewriteTemplate(formula, (part) => {
13365
+ if (part.kind !== "ref" || !part.ref || (part.prefix ? part.sheet !== sheet : !own))
13366
+ return void 0;
13367
+ const next = shiftRef(part.ref, spec2);
13368
+ if (next === part.ref) return void 0;
13369
+ const out = { kind: "ref", text: rewriteRef(part, next) };
13370
+ if (part.prefix) out.prefix = part.prefix;
13371
+ if (part.sheet !== void 0) out.sheet = part.sheet;
13372
+ if (next) out.ref = next;
13373
+ if (part.spill) out.spill = true;
13374
+ return out;
13375
+ });
12746
13376
  }
12747
13377
  function renameSheetInFormula(formula, oldName, newName) {
12748
- const tokens2 = safeTokens(formula);
12749
- if (!tokens2) return formula;
12750
13378
  const lower2 = oldName.toLowerCase();
12751
- for (const token of tokens2) {
12752
- const prefix = token.prefix;
12753
- if (!prefix || prefix.book !== void 0) continue;
12754
- const first2 = prefix.sheet.toLowerCase() === lower2;
13379
+ return rewriteTemplate(formula, (part) => {
13380
+ const prefix = part.prefix;
13381
+ if (!prefix || part.sheet === void 0) return void 0;
13382
+ const first2 = part.sheet === lower2;
12755
13383
  const second = prefix.sheet2?.toLowerCase() === lower2;
12756
- if (!first2 && !second) continue;
13384
+ if (!first2 && !second) return void 0;
12757
13385
  const renamed = { ...prefix, sheet: first2 ? newName : prefix.sheet };
12758
13386
  if (prefix.sheet2 !== void 0) renamed.sheet2 = second ? newName : prefix.sheet2;
12759
13387
  const text3 = prefixText(renamed);
12760
- token.text = text3 + token.text.slice(prefix.text.length);
12761
13388
  renamed.text = text3;
12762
- token.prefix = renamed;
13389
+ const out = { ...part, text: text3 + part.text.slice(prefix.text.length) };
13390
+ out.prefix = renamed;
13391
+ out.sheet = renamed.sheet.toLowerCase();
13392
+ return out;
13393
+ });
13394
+ }
13395
+
13396
+ // xlsx/formula/transform.ts
13397
+ function translateFormula(formula, dRow, dCol) {
13398
+ const tokens2 = safeTokens(formula);
13399
+ if (!tokens2) return formula;
13400
+ for (const token of tokens2) {
13401
+ if (token.kind !== "ref" || !token.ref) continue;
13402
+ const spec2 = token.ref;
13403
+ const move = (c2) => {
13404
+ const row2 = spec2.kind === "cols" || c2.rowAbs ? c2.row : c2.row + dRow;
13405
+ const col = spec2.kind === "rows" || c2.colAbs ? c2.col : c2.col + dCol;
13406
+ if (row2 < 0 || row2 > MAX_ROW || col < 0 || col > MAX_COL) return void 0;
13407
+ return { ...c2, row: row2, col };
13408
+ };
13409
+ const start = move(spec2.start);
13410
+ const end = move(spec2.end);
13411
+ const next = start && end ? { kind: spec2.kind, start, end } : void 0;
13412
+ if (next && sameSpec(next, spec2)) continue;
13413
+ token.text = rewriteRef(token, next);
12763
13414
  }
12764
13415
  return joinTokens(tokens2);
12765
13416
  }
@@ -15586,7 +16237,7 @@ var FUTURE_FUNCTIONS = new Set(
15586
16237
  "AGGREGATE BETA.DIST BETA.INV BINOM.DIST BINOM.INV CEILING.PRECISE CHISQ.DIST CHISQ.DIST.RT CHISQ.INV CHISQ.INV.RT CHISQ.TEST CONFIDENCE.NORM CONFIDENCE.T COVARIANCE.P COVARIANCE.S ERF.PRECISE ERFC.PRECISE EXPON.DIST F.DIST F.DIST.RT F.INV F.INV.RT F.TEST FLOOR.PRECISE GAMMA.DIST GAMMA.INV GAMMALN.PRECISE HYPGEOM.DIST LOGNORM.DIST LOGNORM.INV MODE.MULT MODE.SNGL NEGBINOM.DIST NETWORKDAYS.INTL NORM.DIST NORM.INV NORM.S.DIST NORM.S.INV PERCENTILE.EXC PERCENTILE.INC PERCENTRANK.EXC PERCENTRANK.INC POISSON.DIST QUARTILE.EXC QUARTILE.INC RANK.AVG RANK.EQ STDEV.P STDEV.S T.DIST T.DIST.2T T.DIST.RT T.INV T.INV.2T T.TEST VAR.P VAR.S WEIBULL.DIST WORKDAY.INTL ACOT ACOTH ARABIC BASE BINOM.DIST.RANGE BITAND BITLSHIFT BITOR BITRSHIFT BITXOR CEILING.MATH COMBINA COT COTH CSC CSCH DAYS DECIMAL ENCODEURL FILTERXML FLOOR.MATH FORMULATEXT GAMMA GAUSS IFNA IMCOSH IMCOT IMCSC IMCSCH IMSEC IMSECH IMSINH IMTAN ISFORMULA ISOWEEKNUM MUNIT NUMBERVALUE PDURATION PERMUTATIONA PHI RRI SEC SECH SHEET SHEETS SKEW.P UNICHAR UNICODE WEBSERVICE XOR CONCAT FORECAST.ETS FORECAST.ETS.CONFINT FORECAST.ETS.SEASONALITY FORECAST.ETS.STAT FORECAST.LINEAR IFS MAXIFS MINIFS SWITCH TEXTJOIN XLOOKUP XMATCH FILTER SORT SORTBY UNIQUE SEQUENCE RANDARRAY LET LAMBDA TEXTBEFORE TEXTAFTER TEXTSPLIT VSTACK HSTACK TAKE DROP CHOOSEROWS CHOOSECOLS TOCOL TOROW WRAPROWS WRAPCOLS EXPAND ARRAYTOTEXT VALUETOTEXT ISOMITTED BYROW BYCOL MAP REDUCE SCAN MAKEARRAY IMAGE GROUPBY PIVOTBY PERCENTOF REGEXTEST REGEXEXTRACT REGEXREPLACE TRIMRANGE ANCHORARRAY SINGLE STOCKHISTORY FIELDVALUE".split(" ")
15587
16238
  );
15588
16239
  var WORKSHEET_PREFIXED = /* @__PURE__ */ new Set(["FILTER", "SORT"]);
15589
- function rewrite2(formula, visit2) {
16240
+ function rewrite(formula, visit2) {
15590
16241
  const out = [];
15591
16242
  let i2 = 0;
15592
16243
  while (i2 < formula.length) {
@@ -15629,7 +16280,7 @@ function rewrite2(formula, visit2) {
15629
16280
  }
15630
16281
  function stripFuturePrefixes(formula) {
15631
16282
  if (!formula.includes("_xl")) return formula;
15632
- const plain2 = rewrite2(formula, (token, next, out) => {
16283
+ const plain2 = rewrite(formula, (token, next, out) => {
15633
16284
  if (!next.startsWith("(")) return false;
15634
16285
  const stripped = token.replace(/^(_xlfn\.)?(_xlws\.)?/i, "");
15635
16286
  if (stripped === token) return false;
@@ -15639,7 +16290,7 @@ function stripFuturePrefixes(formula) {
15639
16290
  return fromStoredSyntax(plain2);
15640
16291
  }
15641
16292
  function addFuturePrefixes(formula) {
15642
- return rewrite2(toStoredSyntax(formula), (token, next, out) => {
16293
+ return rewrite(toStoredSyntax(formula), (token, next, out) => {
15643
16294
  if (!next.startsWith("(")) return false;
15644
16295
  const upper2 = token.toUpperCase();
15645
16296
  if (!FUTURE_FUNCTIONS.has(upper2)) return false;
@@ -17721,13 +18372,13 @@ function dataBarLengths(rule, node) {
17721
18372
  maxLength: rule.maxLength ?? numAttr(bar, "maxLength") ?? 90
17722
18373
  };
17723
18374
  }
17724
- function rewriteConditionalExtension(rule, rewrite3) {
18375
+ function rewriteConditionalExtension(rule, rewrite2) {
17725
18376
  if (!rule.extensionXml) return;
17726
18377
  const doc = parseXml(rule.extensionXml);
17727
18378
  let changed = false;
17728
18379
  for (const formula of descendants(doc.documentElement, "f", XM)) {
17729
18380
  const before = formula.textContent ?? "";
17730
- const next = rewrite3(before);
18381
+ const next = rewrite2(before);
17731
18382
  if (before !== next) {
17732
18383
  formula.textContent = next;
17733
18384
  changed = true;
@@ -19870,6 +20521,7 @@ Reply:
19870
20521
  }
19871
20522
 
19872
20523
  // chart/bar-cluster-geometry.ts
20524
+ var DEFAULT_BAR_GAP_WIDTH = 150;
19873
20525
  function assertBarClusterOptions(options) {
19874
20526
  for (const [field, min, max] of [
19875
20527
  ["barGapWidth", 0, 500],
@@ -19883,7 +20535,8 @@ function assertBarClusterOptions(options) {
19883
20535
  function clusteredBarGeometry(barGroupWidth, seriesCount, chartData) {
19884
20536
  const overlap = chartData.barOverlap ?? 0;
19885
20537
  const overlapSpan = 1 + (seriesCount - 1) * (1 - overlap / 100);
19886
- const singleBarWidth = chartData.barGapWidth !== void 0 ? barGroupWidth / (overlapSpan + Math.max(chartData.barGapWidth, 0) / 100) : barGroupWidth * 0.7 / seriesCount;
20538
+ const gapWidth = chartData.barGapWidth ?? DEFAULT_BAR_GAP_WIDTH;
20539
+ const singleBarWidth = barGroupWidth / (overlapSpan + Math.max(gapWidth, 0) / 100);
19887
20540
  const step2 = singleBarWidth * (1 - overlap / 100);
19888
20541
  return { singleBarWidth, step: step2, clusterWidth: singleBarWidth + step2 * (seriesCount - 1) };
19889
20542
  }
@@ -24375,13 +25028,13 @@ function linearTrend(values2) {
24375
25028
  const slope = den ? num3 / den : 0;
24376
25029
  return (k) => Number((meanY + slope * (k - meanX)).toPrecision(15));
24377
25030
  }
24378
- var isDigit4 = (ch) => ch !== void 0 && ch >= "0" && ch <= "9";
25031
+ var isDigit5 = (ch) => ch !== void 0 && ch >= "0" && ch <= "9";
24379
25032
  function matchTextNumber(text3) {
24380
25033
  let end = text3.length;
24381
- while (end > 0 && !isDigit4(text3[end - 1])) end--;
25034
+ while (end > 0 && !isDigit5(text3[end - 1])) end--;
24382
25035
  if (end === 0) return null;
24383
25036
  let start = end;
24384
- while (start > 0 && isDigit4(text3[start - 1])) start--;
25037
+ while (start > 0 && isDigit5(text3[start - 1])) start--;
24385
25038
  return [text3, text3.slice(0, start), text3.slice(start, end), text3.slice(end)];
24386
25039
  }
24387
25040
  var QUARTER = /^(q|qtr|quarter)(\s?)([1-4])$/i;
@@ -24564,10 +25217,10 @@ function removeValidationArea(rules, area) {
24564
25217
  }
24565
25218
 
24566
25219
  // xlsx/edit/conditional-formulas.ts
24567
- function rewriteConditionalRule(rule, rewrite3) {
25220
+ function rewriteConditionalRule(rule, rewrite2) {
24568
25221
  const safe2 = (formula) => {
24569
25222
  try {
24570
- return rewrite3(formula);
25223
+ return rewrite2(formula);
24571
25224
  } catch {
24572
25225
  return formula;
24573
25226
  }
@@ -25086,7 +25739,7 @@ function shiftPreservedXml(sheet, shift2, moveRange, banded) {
25086
25739
  (xml) => xml.includes("sqref")
25087
25740
  );
25088
25741
  }
25089
- function rewritePreservedFormulas(sheet, rewrite3) {
25742
+ function rewritePreservedFormulas(sheet, rewrite2) {
25090
25743
  editEntries(
25091
25744
  sheet,
25092
25745
  "extLst",
@@ -25096,7 +25749,7 @@ function rewritePreservedFormulas(sheet, rewrite3) {
25096
25749
  const text3 = f6.textContent ?? "";
25097
25750
  let next = text3;
25098
25751
  try {
25099
- next = rewrite3(text3, sheet.name);
25752
+ next = rewrite2(text3, sheet.name);
25100
25753
  } catch {
25101
25754
  next = text3;
25102
25755
  }
@@ -25111,46 +25764,46 @@ function rewritePreservedFormulas(sheet, rewrite3) {
25111
25764
  }
25112
25765
 
25113
25766
  // xlsx/edit/shift-formulas.ts
25114
- function safe(rewrite3, formula, formulaSheet) {
25767
+ function safe(rewrite2, formula, formulaSheet) {
25115
25768
  try {
25116
- return rewrite3(formula, formulaSheet);
25769
+ return rewrite2(formula, formulaSheet);
25117
25770
  } catch {
25118
25771
  return formula;
25119
25772
  }
25120
25773
  }
25121
- function rewriteFormulas(workbook, rewrite3) {
25122
- for (const sheet of workbook.sheets) rewriteSheetFormulas(sheet, rewrite3);
25774
+ function rewriteFormulas(workbook, rewrite2) {
25775
+ for (const sheet of workbook.sheets) rewriteSheetFormulas(sheet, rewrite2);
25123
25776
  for (const definedName of workbook.definedNames) {
25124
25777
  const local = definedName.localSheet === void 0 ? void 0 : workbook.sheets[definedName.localSheet];
25125
- definedName.formula = safe(rewrite3, definedName.formula, local?.name ?? "");
25778
+ definedName.formula = safe(rewrite2, definedName.formula, local?.name ?? "");
25126
25779
  }
25127
25780
  }
25128
- function rewriteSheetFormulas(sheet, rewrite3) {
25129
- rewritePreservedFormulas(sheet, rewrite3);
25781
+ function rewriteSheetFormulas(sheet, rewrite2) {
25782
+ rewritePreservedFormulas(sheet, rewrite2);
25130
25783
  {
25131
25784
  const name = sheet.name;
25132
25785
  for (const table2 of sheet.tables)
25133
25786
  for (const column of table2.columns)
25134
25787
  if (column.calculatedColumnFormula !== void 0)
25135
- column.calculatedColumnFormula = safe(rewrite3, column.calculatedColumnFormula, name);
25788
+ column.calculatedColumnFormula = safe(rewrite2, column.calculatedColumnFormula, name);
25136
25789
  for (const cells of sheet.rows.values())
25137
25790
  for (const cell of cells.values())
25138
- if (cell.formula !== void 0) cell.formula = safe(rewrite3, cell.formula, name);
25791
+ if (cell.formula !== void 0) cell.formula = safe(rewrite2, cell.formula, name);
25139
25792
  for (const cf of sheet.conditionalFormats)
25140
- for (const rule of cf.rules) rewriteConditionalRule(rule, (f6) => rewrite3(f6, name));
25793
+ for (const rule of cf.rules) rewriteConditionalRule(rule, (f6) => rewrite2(f6, name));
25141
25794
  for (const dv of sheet.dataValidations) {
25142
- if (dv.formula1 !== void 0) dv.formula1 = safe(rewrite3, dv.formula1, name);
25143
- if (dv.formula2 !== void 0) dv.formula2 = safe(rewrite3, dv.formula2, name);
25795
+ if (dv.formula1 !== void 0) dv.formula1 = safe(rewrite2, dv.formula1, name);
25796
+ if (dv.formula2 !== void 0) dv.formula2 = safe(rewrite2, dv.formula2, name);
25144
25797
  }
25145
25798
  for (const link of sheet.hyperlinks)
25146
25799
  if (link.location && /![A-Za-z$]/.test(link.location))
25147
- link.location = safe(rewrite3, link.location, name);
25800
+ link.location = safe(rewrite2, link.location, name);
25148
25801
  for (const drawing of sheet.drawings) {
25149
25802
  if (drawing.kind !== "chart") continue;
25150
25803
  for (const series of drawing.series) {
25151
- if (series.nameRef) series.nameRef = safe(rewrite3, series.nameRef, name);
25152
- if (series.categoriesRef) series.categoriesRef = safe(rewrite3, series.categoriesRef, name);
25153
- if (series.valuesRef) series.valuesRef = safe(rewrite3, series.valuesRef, name);
25804
+ if (series.nameRef) series.nameRef = safe(rewrite2, series.nameRef, name);
25805
+ if (series.categoriesRef) series.categoriesRef = safe(rewrite2, series.categoriesRef, name);
25806
+ if (series.valuesRef) series.valuesRef = safe(rewrite2, series.valuesRef, name);
25154
25807
  }
25155
25808
  }
25156
25809
  }
@@ -25337,7 +25990,7 @@ function shiftAxis(ctx, s, axis, at, count2, insert) {
25337
25990
  applyAxisShift(ctx, sheet, shift2);
25338
25991
  if (insert) inheritFormats(sheet, axis, at, count2);
25339
25992
  },
25340
- { sheet: s, structural: true }
25993
+ { sheet: s, structural: true, calc: { kind: "shift", sheet: s, shift: shift2 } }
25341
25994
  );
25342
25995
  }
25343
25996
  var insertRows = (ctx, s, at, count2) => shiftAxis(ctx, s, "row", at, count2, true);
@@ -27155,6 +27808,14 @@ function setCalcMode(ctx, mode) {
27155
27808
 
27156
27809
  // xlsx/edit/session-calc.ts
27157
27810
  var isStructural = (step2) => step2.structural || step2.entries.some((entry3) => entry3.before.kind !== "cells");
27811
+ function hintFor(step2, mode) {
27812
+ const hint = step2.calc;
27813
+ if (!hint) return void 0;
27814
+ if (hint.kind === "rename")
27815
+ return mode === "undo" ? { kind: "rename", from: hint.to, to: hint.from } : hint;
27816
+ return mode === "undo" ? void 0 : hint;
27817
+ }
27818
+ var settingsOf = (workbook) => `${workbook.iterate ? `${workbook.iterate.count}:${workbook.iterate.delta}` : ""}|${workbook.date1904}`;
27158
27819
  var SessionCalculator = class {
27159
27820
  constructor(workbook, calc, enabled) {
27160
27821
  this.workbook = workbook;
@@ -27164,43 +27825,113 @@ var SessionCalculator = class {
27164
27825
  workbook;
27165
27826
  calc;
27166
27827
  enabled;
27167
- /** Structural edits made in manual mode leave the dependency graph stale until a full pass. */
27828
+ /** Structural edits the engine could not follow leave the dependency graph stale (manual mode). */
27168
27829
  staleGraph = false;
27830
+ /** Cells changed in manual mode since the last calculation. */
27831
+ dirty = [];
27832
+ /** The settings at the last calculation; undefined before the first. */
27833
+ calculated;
27169
27834
  /** Recalculates after an applied, undone or redone step (failures become warnings). */
27170
- afterStep(step2) {
27171
- if (!this.enabled) return;
27835
+ afterStep(step2, mode = "apply") {
27836
+ if (!this.enabled) {
27837
+ this.calc.discardPreparation();
27838
+ return;
27839
+ }
27840
+ const structural = isStructural(step2);
27841
+ const hint = structural ? hintFor(step2, mode) : void 0;
27172
27842
  if (calcModeOf(this.workbook) === "manual") {
27173
- if (isStructural(step2)) this.staleGraph = true;
27843
+ if (hint && !this.staleGraph && !this.dirty.length) {
27844
+ this.guard(() => this.follow(hint));
27845
+ return;
27846
+ }
27847
+ this.calc.discardPreparation();
27848
+ if (structural) this.staleGraph = true;
27849
+ else this.dirty.push(...touchedCells(step2));
27850
+ return;
27851
+ }
27852
+ if (hint && !this.staleGraph) {
27853
+ this.guard(() => {
27854
+ this.follow(hint);
27855
+ this.calc.recalculateFrom(touchedCells(step2));
27856
+ this.calculated = settingsOf(this.workbook);
27857
+ });
27174
27858
  return;
27175
27859
  }
27176
- this.recalc(isStructural(step2), () => touchedCells(step2));
27860
+ this.recalc(structural, () => touchedCells(step2));
27177
27861
  }
27178
27862
  /** Recalculates after a change applied outside the history (a collaborator's edit). */
27179
27863
  afterExternal(structural, cells) {
27180
- if (!this.enabled) return;
27181
- if (calcModeOf(this.workbook) === "manual") {
27864
+ if (!this.enabled || calcModeOf(this.workbook) === "manual") {
27865
+ this.calc.discardPreparation();
27866
+ if (!this.enabled) return;
27182
27867
  if (structural) this.staleGraph = true;
27868
+ else this.dirty.push(...cells);
27183
27869
  return;
27184
27870
  }
27185
27871
  this.recalc(structural, () => cells);
27186
27872
  }
27187
- recalc(structural, cells) {
27873
+ follow(hint) {
27874
+ if (hint.kind === "shift") this.calc.shiftCells(hint.sheet, hint.shift);
27875
+ else this.calc.renameSheet(hint.from, hint.to);
27876
+ }
27877
+ guard(run2) {
27878
+ try {
27879
+ run2();
27880
+ } catch (error) {
27881
+ const message = `Recalculation failed: ${error instanceof Error ? error.message : String(error)}`;
27882
+ if (!this.workbook.warnings.includes(message)) this.workbook.warnings.push(message);
27883
+ }
27884
+ }
27885
+ /** Builds the dependency graph ahead of the first edit (see `EditSession.prepareCalculation`). */
27886
+ prepare(timeRemaining) {
27887
+ if (!this.enabled || calcModeOf(this.workbook) === "manual" || this.staleGraph) return true;
27188
27888
  try {
27889
+ return this.calc.prepare(timeRemaining);
27890
+ } catch {
27891
+ this.calc.discardPreparation();
27892
+ return true;
27893
+ }
27894
+ }
27895
+ /**
27896
+ * Before a structural edit the graph can follow in place: finishes a graph being prepared (or
27897
+ * builds it) while it still matches the workbook, so the edit moves it instead of rebuilding.
27898
+ */
27899
+ beforeStructural() {
27900
+ if (!this.enabled || calcModeOf(this.workbook) === "manual" || this.staleGraph) return;
27901
+ this.prepare();
27902
+ }
27903
+ recalc(structural, cells) {
27904
+ this.guard(() => {
27189
27905
  if (this.staleGraph || structural) this.full();
27190
27906
  else {
27191
27907
  const changed = cells();
27192
27908
  if (changed.length) this.calc.recalculateFrom(changed);
27909
+ this.calculated = settingsOf(this.workbook);
27193
27910
  }
27194
- } catch (error) {
27195
- const message = `Recalculation failed: ${error instanceof Error ? error.message : String(error)}`;
27196
- if (!this.workbook.warnings.includes(message)) this.workbook.warnings.push(message);
27197
- }
27911
+ });
27198
27912
  }
27199
- /** Rebuilds the dependency graph and recalculates every formula (F9). */
27913
+ /** Rebuilds the dependency graph and recalculates every formula (Ctrl+Alt+F9). */
27200
27914
  full() {
27201
27915
  this.staleGraph = false;
27916
+ this.dirty = [];
27202
27917
  this.calc.invalidate();
27203
27918
  this.calc.recalculateAll();
27919
+ this.calculated = settingsOf(this.workbook);
27920
+ }
27921
+ /**
27922
+ * Calculate Now (F9): the cells changed since the last calculation, the formulas structural
27923
+ * edits queued, their dependents and the volatile functions. Everything when `full`, before
27924
+ * the session's first calculation, after the iteration settings changed or while the graph
27925
+ * is stale.
27926
+ */
27927
+ now(full) {
27928
+ if (full || this.staleGraph || this.calculated !== settingsOf(this.workbook)) {
27929
+ this.full();
27930
+ return;
27931
+ }
27932
+ const changed = this.dirty;
27933
+ this.dirty = [];
27934
+ this.calc.recalculateFrom(changed);
27204
27935
  }
27205
27936
  /**
27206
27937
  * Recalculates one sheet's formulas and their dependents (Shift+F9); after structural edits
@@ -30971,12 +31702,12 @@ function renameSheet(ctx, index2, name) {
30971
31702
  ctx.run(
30972
31703
  "Rename sheet",
30973
31704
  "sheets",
30974
- [{ kind: "workbook" }],
31705
+ [{ kind: "refs" }],
30975
31706
  () => {
30976
31707
  rewriteFormulas(workbook, (formula) => renameSheetInFormula(formula, old, name));
30977
31708
  sheet.name = name;
30978
31709
  },
30979
- { sheet: index2, structural: true }
31710
+ { sheet: index2, structural: true, calc: { kind: "rename", from: old, to: name } }
30980
31711
  );
30981
31712
  }
30982
31713
  function moveSheet(ctx, from, to) {
@@ -31366,13 +32097,12 @@ function createEditSession(workbook, options = {}) {
31366
32097
  for (const listener of [...listeners]) listener(change);
31367
32098
  };
31368
32099
  const calculator = new SessionCalculator(workbook, calc, autoRecalc);
31369
- const recalc = (step2) => calculator.afterStep(step2);
31370
- const begin = (label2, kind, info) => ({
31371
- step: { label: label2, entries: [], structural: info.structural ?? false },
31372
- kind,
31373
- sheet: info.sheet,
31374
- ranges: [...info.ranges ?? []]
31375
- });
32100
+ const recalc = (step2, mode = "apply") => calculator.afterStep(step2, mode);
32101
+ const begin = (label2, kind, info) => {
32102
+ const step2 = { label: label2, entries: [], structural: info.structural ?? false };
32103
+ if (info.calc) step2.calc = info.calc;
32104
+ return { step: step2, kind, sheet: info.sheet, ranges: [...info.ranges ?? []] };
32105
+ };
31376
32106
  const finish = (current) => {
31377
32107
  if (!current.step.entries.length) return;
31378
32108
  history.push(current.step);
@@ -31397,10 +32127,12 @@ function createEditSession(workbook, options = {}) {
31397
32127
  const outer = !open;
31398
32128
  const current = open ?? begin(label2, kind, info);
31399
32129
  if (!outer) {
32130
+ delete current.step.calc;
31400
32131
  if (info.structural) current.step.structural = true;
31401
32132
  if (current.sheet === void 0 && info.sheet !== void 0) current.sheet = info.sheet;
31402
32133
  current.ranges.push(...info.ranges ?? []);
31403
32134
  }
32135
+ if (outer && info.calc) calculator.beforeStructural();
31404
32136
  open = current;
31405
32137
  const mark = current.step.entries.length;
31406
32138
  const befores = scopes.map((scope) => captureScope(workbook, scope));
@@ -31448,7 +32180,7 @@ function createEditSession(workbook, options = {}) {
31448
32180
  if (open) throw new Error(`Cannot ${kind} inside a batch`);
31449
32181
  const step2 = kind === "undo" ? history.undo(workbook) : history.redo(workbook);
31450
32182
  if (!step2) return false;
31451
- recalc(step2);
32183
+ recalc(step2, kind);
31452
32184
  emit({ kind, label: step2.label, structural: step2.structural });
31453
32185
  return true;
31454
32186
  };
@@ -31527,10 +32259,11 @@ function createEditSession(workbook, options = {}) {
31527
32259
  setDocumentProperties: (patch2) => setDocumentProperties(ctx, patch2),
31528
32260
  setAutoRecalc: (enabled) => setCalcMode(ctx, enabled ? "auto" : "manual"),
31529
32261
  autoRecalc: () => autoRecalc && calcModeOf(workbook) === "auto",
31530
- calculateNow() {
31531
- calculator.full();
32262
+ calculateNow(options2) {
32263
+ calculator.now(options2?.full ?? false);
31532
32264
  emit({ kind: "cells", label: "Calculate now", structural: false });
31533
32265
  },
32266
+ prepareCalculation: (opts) => calculator.prepare(opts?.timeRemaining),
31534
32267
  calculateSheet(s) {
31535
32268
  calculator.sheet(s);
31536
32269
  emit({ kind: "cells", label: "Calculate sheet", sheet: s, structural: false });
@@ -32185,6 +32918,7 @@ function selectionStats(workbook, sheet, ranges) {
32185
32918
  const seen = /* @__PURE__ */ new Set();
32186
32919
  let min = Infinity;
32187
32920
  let max = -Infinity;
32921
+ let numFmt;
32188
32922
  for (const range of ranges)
32189
32923
  forEachCellInRange(ws, range, (cell, row2, col) => {
32190
32924
  if (ranges.length > 1) {
@@ -32197,6 +32931,7 @@ function selectionStats(workbook, sheet, ranges) {
32197
32931
  out.count++;
32198
32932
  if (typeof value === "number" && Number.isFinite(value)) {
32199
32933
  out.numericCount++;
32934
+ numFmt ??= styleAt(workbook, effectiveStyleId(ws, row2, col)).numFmt || "General";
32200
32935
  out.sum += value;
32201
32936
  min = Math.min(min, value);
32202
32937
  max = Math.max(max, value);
@@ -32206,9 +32941,13 @@ function selectionStats(workbook, sheet, ranges) {
32206
32941
  out.average = out.sum / out.numericCount;
32207
32942
  out.min = min;
32208
32943
  out.max = max;
32944
+ out.numFmt = numFmt ?? "General";
32209
32945
  }
32210
32946
  return out;
32211
32947
  }
32948
+ function formatSelectionStat(workbook, stats, value) {
32949
+ return formatValue(value, stats.numFmt ?? "General", { date1904: workbook.date1904 }).text;
32950
+ }
32212
32951
  function isOverflowTarget(sheet, row2, col) {
32213
32952
  const cell = getCell(sheet, row2, col);
32214
32953
  if (cell && (cell.value !== null && cell.value !== "" || cell.formula)) return false;
@@ -33093,7 +33832,7 @@ function chartAreaRect(model, part, area) {
33093
33832
  function chartBarSpacing(chart) {
33094
33833
  const stacked = chart.grouping === "stacked" || chart.grouping === "percentStacked";
33095
33834
  return {
33096
- barGapWidth: chart.barGapWidth ?? 150,
33835
+ barGapWidth: chart.barGapWidth ?? DEFAULT_BAR_GAP_WIDTH,
33097
33836
  barOverlap: chart.barOverlap ?? (stacked ? 100 : 0)
33098
33837
  };
33099
33838
  }
@@ -33930,4 +34669,4 @@ function createRefEvaluator(workbook, calc, options = {}) {
33930
34669
  };
33931
34670
  }
33932
34671
 
33933
- export { AxisMetrics, BORDER_STYLES, BUILTIN_CELL_STYLES, BUILTIN_NUMBER_FORMATS, CHART_FILL_PARTS, CIRCULAR_REFERENCE_WARNING, COLUMN_PADDING_PX, DEFAULT_ANCHOR_EXTENT_EMU, DEFAULT_BASE_COL_WIDTH, DEFAULT_COL_WIDTH, DEFAULT_MAX_DIGIT_WIDTH, DEFAULT_ROW_HEIGHT, DEFAULT_THEME, DEFAULT_VALIDATION_MESSAGE, ERROR_CODES, FORMAT_PRESETS, FUNCTION_CATALOG, FormulaError, IMAGE_EXTENSIONS, INDENT_PX_PER_LEVEL, INDEXED_COLORS, MAX_COL, MAX_DATE_SERIAL, MAX_OUTLINE_LEVEL, MAX_ROW, MIN_TWO_CELL_PIXELS, OVERFLOW_TEXT, PERCENT_SCALE, REFERENCE_COLORS, THEME_SLOTS, TIME_PERIODS, acceptsReference, activeParam, addFuturePrefixes, anchorKind, anchorToPixelBox, applyBuiltinStyle, applyStylePatch, applyTint, approximateMeasure, autoFitColumnWidth, autoFitRowHeight, autoGrowRows, autoSeriesColor, bordersView, builtinCellStyle, builtinFormatId, calcModeOf, callAtCaret, categoryTotals, cellError, cellInputText, cellKey, cellView, cellsFromText, charactersToColumnWidth, charactersToPixels, chartBarSpacing, chartColorPalettePatch, chartColorScheme, chartDrawingColor, chartElementFill, chartElementFillPatch, chartElementGradientPatch, chartElementSolidFillPatch, chartElementTransparency, chartElementTransparencyPatch, chartGradientStopTransparency, chartSeriesFillPatch, chartSeriesGradientPatch, chartSeriesSolidColor, chartSeriesSolidFillPatch, chartSeriesTransparency, chartSeriesTransparencyPatch, chartView, chartWithElementFills, closeParens, coloredReferences, columnIndex, columnLabel, columnWidthToPixels, compareCellValues, compareValues, createCalcEngine, createConditionalFormatEvaluator, createEditSession, createGridMetrics, createRefEvaluator, createWorkbook, createWorksheet, currentRegion, dateToSerial, defaultCellStyle, defaultColumnPixels, deleteCell, deleteSheetInFormula, detectSeries, edgeView, effectiveStyleId, fillView, fontView, forEachCell, forEachCellInRange, formatAddress, formatAxisValue, formatGeneral, formatRange, formatRefSpec, formatValue, formulaBarText, functionMatches, generalAlignment, getCell, getCellAt, getValue, hasSparklineAt, hls240ToRgb, inTimePeriod, insideString, internStyle, isCellError, isDateFormat, isEmptyCell, isErrorCode, isFormulaText, isOverflowTarget, isSpilledCell, keyToAddress, layoutRemoteSelections, legacyPasswordHash, lineHeightPoints, listValidationOptions, loadXlsx, mergeAt, mergeFont, mergeView, mergeWouldDiscard, mixColors, modernPasswordHash, modulateLuminance, moveReferencesInFormula, nameAtCaret, navigate, needsArrayEvaluation, newMediaPart, nextSheetId, nextSheetName, niceScale, normalizeRange, numberInputText, numberToText, overflowExtent, parseAddress, parseCellInput, parseFormula, parseHex, parseHtmlTable, parseNumberText, parseR1C1Range, parseRange, parseTsv, patchStyle, percentile, pictureAnchorAt, pixelBoxToAnchor, pixelSizeToExtent, pixelsToCharacters, pixelsToColumnWidth, pixelsToPoints, pointsToPixels, presetEdges, putCell, queryPattern, quoteSheetName, rangeContains, rangeSize, rangesIntersect, readSparklineGroup, readSparklineGroups, readSparklineValues, referenceSpans, referenceTarget, referencedRanges, renameSheetInFormula, renameTableInFormula, renderChartSvg, replaceText, resolveColor, resolvePasteOptions, resolveSparklineRange, rgbToHls240, rotationDegrees, rowsToRefit, sameChartColor, saveXlsx, scaleColor, selectionStats, serialToDate, sheetByName, sheetSparklineGroups, shiftFormula, shiftRange, shiftSpan, sparklineScale, sparklineValues, sparklineView, sparklineViewAt, spillAnchorOf, splice, stepDecimals, stripFuturePrefixes, structuredToA1, styleAt, styleKey, subtractRange, syntaxParams, themeColor, timePeriodFormula, toHexColor, toHtml, toTsv, toggleAbsolute, tokenize, translateFormula, translateReferences, uniqueHeaders, usedRange, validateCellInput, validateDefinedName, validateSheetName, validateTableName, validationAt, verifySheetPassword, verifySheetPasswordAsync, verifyWorkbookPassword, visibleCells, wrappedLineCount, zoomPercent };
34672
+ export { AxisMetrics, BORDER_STYLES, BUILTIN_CELL_STYLES, BUILTIN_NUMBER_FORMATS, CHART_FILL_PARTS, CIRCULAR_REFERENCE_WARNING, COLUMN_PADDING_PX, DEFAULT_ANCHOR_EXTENT_EMU, DEFAULT_BASE_COL_WIDTH, DEFAULT_COL_WIDTH, DEFAULT_MAX_DIGIT_WIDTH, DEFAULT_ROW_HEIGHT, DEFAULT_THEME, DEFAULT_VALIDATION_MESSAGE, ERROR_CODES, FORMAT_PRESETS, FUNCTION_CATALOG, FormulaError, IMAGE_EXTENSIONS, INDENT_PX_PER_LEVEL, INDEXED_COLORS, MAX_COL, MAX_DATE_SERIAL, MAX_OUTLINE_LEVEL, MAX_ROW, MIN_TWO_CELL_PIXELS, OVERFLOW_TEXT, PERCENT_SCALE, REFERENCE_COLORS, THEME_SLOTS, TIME_PERIODS, acceptsReference, activeParam, addFuturePrefixes, anchorKind, anchorToPixelBox, applyBuiltinStyle, applyStylePatch, applyTint, approximateMeasure, autoFitColumnWidth, autoFitRowHeight, autoGrowRows, autoSeriesColor, bordersView, builtinCellStyle, builtinFormatId, calcModeOf, callAtCaret, categoryTotals, cellError, cellInputText, cellKey, cellView, cellsFromText, charactersToColumnWidth, charactersToPixels, chartBarSpacing, chartColorPalettePatch, chartColorScheme, chartDrawingColor, chartElementFill, chartElementFillPatch, chartElementGradientPatch, chartElementSolidFillPatch, chartElementTransparency, chartElementTransparencyPatch, chartGradientStopTransparency, chartSeriesFillPatch, chartSeriesGradientPatch, chartSeriesSolidColor, chartSeriesSolidFillPatch, chartSeriesTransparency, chartSeriesTransparencyPatch, chartView, chartWithElementFills, closeParens, coloredReferences, columnIndex, columnLabel, columnWidthToPixels, compareCellValues, compareValues, createCalcEngine, createConditionalFormatEvaluator, createEditSession, createGridMetrics, createRefEvaluator, createWorkbook, createWorksheet, currentRegion, dateToSerial, defaultCellStyle, defaultColumnPixels, deleteCell, deleteSheetInFormula, detectSeries, edgeView, effectiveStyleId, fillView, fontView, forEachCell, forEachCellInRange, formatAddress, formatAxisValue, formatGeneral, formatRange, formatRefSpec, formatSelectionStat, formatValue, formulaBarText, functionMatches, generalAlignment, getCell, getCellAt, getValue, hasSparklineAt, hls240ToRgb, inTimePeriod, insideString, internStyle, isCellError, isDateFormat, isEmptyCell, isErrorCode, isFormulaText, isOverflowTarget, isSpilledCell, keyToAddress, layoutRemoteSelections, legacyPasswordHash, lineHeightPoints, listValidationOptions, loadXlsx, mergeAt, mergeFont, mergeView, mergeWouldDiscard, mixColors, modernPasswordHash, modulateLuminance, moveReferencesInFormula, nameAtCaret, navigate, needsArrayEvaluation, newMediaPart, nextSheetId, nextSheetName, niceScale, normalizeRange, numberInputText, numberToText, overflowExtent, parseAddress, parseCellInput, parseFormula, parseHex, parseHtmlTable, parseNumberText, parseR1C1Range, parseRange, parseTsv, patchStyle, percentile, pictureAnchorAt, pixelBoxToAnchor, pixelSizeToExtent, pixelsToCharacters, pixelsToColumnWidth, pixelsToPoints, pointsToPixels, presetEdges, putCell, queryPattern, quoteSheetName, rangeContains, rangeSize, rangesIntersect, readSparklineGroup, readSparklineGroups, readSparklineValues, referenceSpans, referenceTarget, referencedRanges, renameSheetInFormula, renameTableInFormula, renderChartSvg, replaceText, resolveColor, resolvePasteOptions, resolveSparklineRange, rgbToHls240, rotationDegrees, rowsToRefit, sameChartColor, saveXlsx, scaleColor, selectionStats, serialToDate, sheetByName, sheetSparklineGroups, shiftFormula, shiftRange, shiftSpan, sparklineScale, sparklineValues, sparklineView, sparklineViewAt, spillAnchorOf, splice, stepDecimals, stripFuturePrefixes, structuredToA1, styleAt, styleKey, subtractRange, syntaxParams, themeColor, timePeriodFormula, toHexColor, toHtml, toTsv, toggleAbsolute, tokenize, translateFormula, translateReferences, uniqueHeaders, usedRange, validateCellInput, validateDefinedName, validateSheetName, validateTableName, validationAt, verifySheetPassword, verifySheetPasswordAsync, verifyWorkbookPassword, visibleCells, wrappedLineCount, zoomPercent };