@alaarab/ogrid-core 2.1.15 → 2.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (31) hide show
  1. package/dist/esm/index.js +3697 -16
  2. package/dist/types/formula/cellAddressUtils.d.ts +50 -0
  3. package/dist/types/formula/dependencyGraph.d.ts +72 -0
  4. package/dist/types/formula/errors.d.ts +15 -0
  5. package/dist/types/formula/evaluator.d.ts +25 -0
  6. package/dist/types/formula/formulaEngine.d.ts +104 -0
  7. package/dist/types/formula/functions/date.d.ts +2 -0
  8. package/dist/types/formula/functions/index.d.ts +2 -0
  9. package/dist/types/formula/functions/info.d.ts +2 -0
  10. package/dist/types/formula/functions/logical.d.ts +2 -0
  11. package/dist/types/formula/functions/lookup.d.ts +2 -0
  12. package/dist/types/formula/functions/math.d.ts +2 -0
  13. package/dist/types/formula/functions/stats.d.ts +2 -0
  14. package/dist/types/formula/functions/text.d.ts +2 -0
  15. package/dist/types/formula/index.d.ts +13 -0
  16. package/dist/types/formula/parser.d.ts +26 -0
  17. package/dist/types/formula/tokenizer.d.ts +7 -0
  18. package/dist/types/formula/types.d.ts +139 -0
  19. package/dist/types/index.d.ts +9 -3
  20. package/dist/types/types/columnTypes.d.ts +2 -0
  21. package/dist/types/types/dataGridTypes.d.ts +4 -0
  22. package/dist/types/utils/cellReference.d.ts +21 -0
  23. package/dist/types/utils/clipboardHelpers.d.ts +18 -2
  24. package/dist/types/utils/dataGridViewModel.d.ts +2 -1
  25. package/dist/types/utils/exportToCsv.d.ts +10 -2
  26. package/dist/types/utils/fillHelpers.d.ts +18 -1
  27. package/dist/types/utils/index.d.ts +7 -3
  28. package/dist/types/utils/virtualScroll.d.ts +34 -0
  29. package/dist/types/utils/workerSortFilter.d.ts +29 -0
  30. package/dist/types/workers/sortFilterWorker.d.ts +48 -0
  31. package/package.json +1 -1
package/dist/esm/index.js CHANGED
@@ -38,14 +38,23 @@ function escapeCsvValue(value) {
38
38
  function buildCsvHeader(columns) {
39
39
  return columns.map((c) => escapeCsvValue(c.name)).join(",");
40
40
  }
41
- function buildCsvRows(items, columns, getValue) {
41
+ function buildCsvRows(items, columns, getValue, formulaOptions) {
42
42
  return items.map(
43
- (item) => columns.map((c) => escapeCsvValue(getValue(item, c.columnId))).join(",")
43
+ (item, rowIdx) => columns.map((col) => {
44
+ if (formulaOptions?.exportMode === "formulas" && formulaOptions.hasFormula && formulaOptions.getFormula && formulaOptions.columnIdToIndex) {
45
+ const colIdx = formulaOptions.columnIdToIndex.get(col.columnId);
46
+ if (colIdx !== void 0 && formulaOptions.hasFormula(colIdx, rowIdx)) {
47
+ const formula = formulaOptions.getFormula(colIdx, rowIdx);
48
+ if (formula) return escapeCsvValue(formula);
49
+ }
50
+ }
51
+ return escapeCsvValue(getValue(item, col.columnId));
52
+ }).join(",")
44
53
  );
45
54
  }
46
- function exportToCsv(items, columns, getValue, filename) {
55
+ function exportToCsv(items, columns, getValue, filename, formulaOptions) {
47
56
  const header = buildCsvHeader(columns);
48
- const rows = buildCsvRows(items, columns, getValue);
57
+ const rows = buildCsvRows(items, columns, getValue, formulaOptions);
49
58
  const csv = [header, ...rows].join("\n");
50
59
  triggerCsvDownload(csv, filename ?? `export_${(/* @__PURE__ */ new Date()).toISOString().slice(0, 10)}.csv`);
51
60
  }
@@ -738,6 +747,66 @@ function calculateDropTarget(params) {
738
747
  }
739
748
 
740
749
  // src/utils/virtualScroll.ts
750
+ function computeVisibleColumnRange(scrollLeft, columnWidths, containerWidth, overscan = 2) {
751
+ if (columnWidths.length === 0 || containerWidth <= 0) {
752
+ return { startIndex: 0, endIndex: -1, leftOffset: 0, rightOffset: 0 };
753
+ }
754
+ let cumWidth = 0;
755
+ let rawStart = columnWidths.length;
756
+ let rawEnd = -1;
757
+ for (let i = 0; i < columnWidths.length; i++) {
758
+ const colStart = cumWidth;
759
+ cumWidth += columnWidths[i];
760
+ if (cumWidth > scrollLeft && rawStart === columnWidths.length) {
761
+ rawStart = i;
762
+ }
763
+ if (colStart < scrollLeft + containerWidth) {
764
+ rawEnd = i;
765
+ }
766
+ }
767
+ if (rawStart > rawEnd) {
768
+ return { startIndex: 0, endIndex: -1, leftOffset: 0, rightOffset: 0 };
769
+ }
770
+ const startIndex = Math.max(0, rawStart - overscan);
771
+ const endIndex = Math.min(columnWidths.length - 1, rawEnd + overscan);
772
+ let leftOffset = 0;
773
+ for (let i = 0; i < startIndex; i++) {
774
+ leftOffset += columnWidths[i];
775
+ }
776
+ let rightOffset = 0;
777
+ for (let i = endIndex + 1; i < columnWidths.length; i++) {
778
+ rightOffset += columnWidths[i];
779
+ }
780
+ return { startIndex, endIndex, leftOffset, rightOffset };
781
+ }
782
+ function partitionColumnsForVirtualization(visibleCols, columnRange, pinnedColumns) {
783
+ const pinnedLeft = [];
784
+ const pinnedRight = [];
785
+ const unpinned = [];
786
+ for (const col of visibleCols) {
787
+ const pin = pinnedColumns?.[col.columnId];
788
+ if (pin === "left") pinnedLeft.push(col);
789
+ else if (pin === "right") pinnedRight.push(col);
790
+ else unpinned.push(col);
791
+ }
792
+ if (!columnRange || columnRange.endIndex < 0) {
793
+ return {
794
+ pinnedLeft,
795
+ virtualizedUnpinned: unpinned,
796
+ pinnedRight,
797
+ leftSpacerWidth: 0,
798
+ rightSpacerWidth: 0
799
+ };
800
+ }
801
+ const virtualizedUnpinned = unpinned.slice(columnRange.startIndex, columnRange.endIndex + 1);
802
+ return {
803
+ pinnedLeft,
804
+ virtualizedUnpinned,
805
+ pinnedRight,
806
+ leftSpacerWidth: columnRange.leftOffset,
807
+ rightSpacerWidth: columnRange.rightOffset
808
+ };
809
+ }
741
810
  function computeVisibleRange(scrollTop, rowHeight, containerHeight, totalRows, overscan = 5) {
742
811
  if (totalRows <= 0 || rowHeight <= 0 || containerHeight <= 0) {
743
812
  return { startIndex: 0, endIndex: 0, offsetTop: 0, offsetBottom: 0 };
@@ -766,6 +835,250 @@ function getScrollTopForRow(rowIndex, rowHeight, containerHeight, align = "start
766
835
  }
767
836
  }
768
837
 
838
+ // src/workers/sortFilterWorker.ts
839
+ function workerBody() {
840
+ const ctx = self;
841
+ ctx.onmessage = (e) => {
842
+ const msg = e.data;
843
+ if (msg.type !== "sort-filter") return;
844
+ const { requestId, values, filters, sort } = msg;
845
+ const rowCount = values.length;
846
+ let indices = [];
847
+ const filterEntries = Object.entries(filters);
848
+ if (filterEntries.length === 0) {
849
+ indices = new Array(rowCount);
850
+ for (let i = 0; i < rowCount; i++) indices[i] = i;
851
+ } else {
852
+ for (let r = 0; r < rowCount; r++) {
853
+ let pass = true;
854
+ for (let f = 0; f < filterEntries.length; f++) {
855
+ const colIdx = Number(filterEntries[f][0]);
856
+ const filter = filterEntries[f][1];
857
+ const cellVal = values[r][colIdx];
858
+ switch (filter.type) {
859
+ case "text": {
860
+ const trimmed = filter.value.trim().toLowerCase();
861
+ if (trimmed && !String(cellVal ?? "").toLowerCase().includes(trimmed)) {
862
+ pass = false;
863
+ }
864
+ break;
865
+ }
866
+ case "multiSelect": {
867
+ if (filter.value.length > 0) {
868
+ const set = new Set(filter.value);
869
+ if (!set.has(String(cellVal ?? ""))) {
870
+ pass = false;
871
+ }
872
+ }
873
+ break;
874
+ }
875
+ case "date": {
876
+ if (cellVal == null) {
877
+ pass = false;
878
+ break;
879
+ }
880
+ const ts = new Date(String(cellVal)).getTime();
881
+ if (isNaN(ts)) {
882
+ pass = false;
883
+ break;
884
+ }
885
+ if (filter.value.from) {
886
+ const fromTs = (/* @__PURE__ */ new Date(filter.value.from + "T00:00:00")).getTime();
887
+ if (ts < fromTs) {
888
+ pass = false;
889
+ break;
890
+ }
891
+ }
892
+ if (filter.value.to) {
893
+ const toTs = (/* @__PURE__ */ new Date(filter.value.to + "T23:59:59.999")).getTime();
894
+ if (ts > toTs) {
895
+ pass = false;
896
+ break;
897
+ }
898
+ }
899
+ break;
900
+ }
901
+ }
902
+ if (!pass) break;
903
+ }
904
+ if (pass) indices.push(r);
905
+ }
906
+ }
907
+ if (sort) {
908
+ const { columnIndex, direction } = sort;
909
+ const dir = direction === "asc" ? 1 : -1;
910
+ indices.sort((a, b) => {
911
+ const av = values[a][columnIndex];
912
+ const bv = values[b][columnIndex];
913
+ if (av == null && bv == null) return 0;
914
+ if (av == null) return -1 * dir;
915
+ if (bv == null) return 1 * dir;
916
+ if (typeof av === "number" && typeof bv === "number") {
917
+ return av === bv ? 0 : av > bv ? dir : -dir;
918
+ }
919
+ const sa = String(av).toLowerCase();
920
+ const sb = String(bv).toLowerCase();
921
+ return sa === sb ? 0 : sa > sb ? dir : -dir;
922
+ });
923
+ }
924
+ const response = {
925
+ type: "sort-filter-result",
926
+ requestId,
927
+ indices
928
+ };
929
+ ctx.postMessage(response);
930
+ };
931
+ }
932
+
933
+ // src/utils/workerSortFilter.ts
934
+ var workerInstance = null;
935
+ var requestCounter = 0;
936
+ var pendingRequests = /* @__PURE__ */ new Map();
937
+ function createSortFilterWorker() {
938
+ if (workerInstance) return workerInstance;
939
+ if (typeof Worker === "undefined" || typeof Blob === "undefined" || typeof URL === "undefined") {
940
+ return null;
941
+ }
942
+ try {
943
+ const fnStr = workerBody.toString();
944
+ const blob = new Blob(
945
+ [`(${fnStr})()`],
946
+ { type: "application/javascript" }
947
+ );
948
+ const url = URL.createObjectURL(blob);
949
+ workerInstance = new Worker(url);
950
+ URL.revokeObjectURL(url);
951
+ workerInstance.onmessage = (e) => {
952
+ const { requestId, indices } = e.data;
953
+ const pending = pendingRequests.get(requestId);
954
+ if (pending) {
955
+ pendingRequests.delete(requestId);
956
+ pending.resolve(indices);
957
+ }
958
+ };
959
+ workerInstance.onerror = (err) => {
960
+ for (const [id, pending] of pendingRequests) {
961
+ pending.reject(new Error(err.message || "Worker error"));
962
+ pendingRequests.delete(id);
963
+ }
964
+ };
965
+ return workerInstance;
966
+ } catch {
967
+ return null;
968
+ }
969
+ }
970
+ function terminateSortFilterWorker() {
971
+ if (workerInstance) {
972
+ workerInstance.terminate();
973
+ workerInstance = null;
974
+ }
975
+ for (const [id, pending] of pendingRequests) {
976
+ pending.reject(new Error("Worker terminated"));
977
+ pendingRequests.delete(id);
978
+ }
979
+ }
980
+ function extractValueMatrix(data, columns) {
981
+ const matrix = new Array(data.length);
982
+ for (let r = 0; r < data.length; r++) {
983
+ const row = new Array(columns.length);
984
+ for (let c = 0; c < columns.length; c++) {
985
+ const val = getCellValue(data[r], columns[c]);
986
+ if (val == null) {
987
+ row[c] = null;
988
+ } else if (typeof val === "string" || typeof val === "number" || typeof val === "boolean") {
989
+ row[c] = val;
990
+ } else {
991
+ row[c] = String(val);
992
+ }
993
+ }
994
+ matrix[r] = row;
995
+ }
996
+ return matrix;
997
+ }
998
+ function processClientSideDataAsync(data, columns, filters, sortBy, sortDirection) {
999
+ if (sortBy) {
1000
+ const sortCol = columns.find((c) => c.columnId === sortBy);
1001
+ if (sortCol?.compare) {
1002
+ return Promise.resolve(processClientSideData(data, columns, filters, sortBy, sortDirection));
1003
+ }
1004
+ }
1005
+ const worker = createSortFilterWorker();
1006
+ if (!worker) {
1007
+ return Promise.resolve(processClientSideData(data, columns, filters, sortBy, sortDirection));
1008
+ }
1009
+ const columnIndexMap = /* @__PURE__ */ new Map();
1010
+ for (let i = 0; i < columns.length; i++) {
1011
+ columnIndexMap.set(columns[i].columnId, i);
1012
+ }
1013
+ const values = extractValueMatrix(data, columns);
1014
+ const columnMeta = columns.map((col, idx) => ({
1015
+ type: col.type ?? "text",
1016
+ index: idx
1017
+ }));
1018
+ const workerFilters = {};
1019
+ for (const col of columns) {
1020
+ const filterKey = getFilterField(col);
1021
+ const val = filters[filterKey];
1022
+ if (!val) continue;
1023
+ const colIdx = columnIndexMap.get(col.columnId);
1024
+ if (colIdx === void 0) continue;
1025
+ switch (val.type) {
1026
+ case "text":
1027
+ workerFilters[colIdx] = { type: "text", value: val.value };
1028
+ break;
1029
+ case "multiSelect":
1030
+ workerFilters[colIdx] = { type: "multiSelect", value: val.value };
1031
+ break;
1032
+ case "date":
1033
+ workerFilters[colIdx] = { type: "date", value: { from: val.value.from, to: val.value.to } };
1034
+ break;
1035
+ // 'people' filter has a UserLike object — fall back to sync
1036
+ case "people":
1037
+ return Promise.resolve(processClientSideData(data, columns, filters, sortBy, sortDirection));
1038
+ }
1039
+ }
1040
+ let sort;
1041
+ if (sortBy) {
1042
+ const sortColIdx = columnIndexMap.get(sortBy);
1043
+ if (sortColIdx !== void 0) {
1044
+ sort = { columnIndex: sortColIdx, direction: sortDirection ?? "asc" };
1045
+ }
1046
+ }
1047
+ const requestId = ++requestCounter;
1048
+ return new Promise((resolve, reject) => {
1049
+ pendingRequests.set(requestId, {
1050
+ resolve: (indices) => {
1051
+ const result = new Array(indices.length);
1052
+ for (let i = 0; i < indices.length; i++) {
1053
+ result[i] = data[indices[i]];
1054
+ }
1055
+ resolve(result);
1056
+ },
1057
+ reject
1058
+ });
1059
+ const request = {
1060
+ type: "sort-filter",
1061
+ requestId,
1062
+ values,
1063
+ columnMeta,
1064
+ filters: workerFilters,
1065
+ sort
1066
+ };
1067
+ worker.postMessage(request);
1068
+ });
1069
+ }
1070
+
1071
+ // src/formula/types.ts
1072
+ var FormulaError = class {
1073
+ constructor(type, message) {
1074
+ this.type = type;
1075
+ this.message = message;
1076
+ }
1077
+ toString() {
1078
+ return this.type;
1079
+ }
1080
+ };
1081
+
769
1082
  // src/utils/dataGridViewModel.ts
770
1083
  function getHeaderFilterConfig(col, input) {
771
1084
  const filterable = isFilterConfig(col.filterable) ? col.filterable : null;
@@ -899,7 +1212,8 @@ function computeCellDescriptor(item, col, rowIndex, colIdx, input) {
899
1212
  const canEditAny = canEditInline || canEditPopup;
900
1213
  const isEditing = input.editingCell?.rowId === rowId && input.editingCell?.columnId === col.columnId;
901
1214
  const isActive = !input.isDragging && input.activeCell?.rowIndex === rowIndex && input.activeCell?.columnIndex === globalColIndex;
902
- const isInRange = input.selectionRange != null && isInSelectionRange(input.selectionRange, rowIndex, colIdx);
1215
+ const isSingleCellRange = input.selectionRange != null && input.selectionRange.startRow === input.selectionRange.endRow && input.selectionRange.startCol === input.selectionRange.endCol;
1216
+ const isInRange = input.selectionRange != null && !isSingleCellRange && isInSelectionRange(input.selectionRange, rowIndex, colIdx);
903
1217
  const isInCutRange = input.cutRange != null && isInSelectionRange(input.cutRange, rowIndex, colIdx);
904
1218
  const isInCopyRange = input.copyRange != null && isInSelectionRange(input.copyRange, rowIndex, colIdx);
905
1219
  const isSelectionEndCell = !input.isDragging && input.copyRange == null && input.cutRange == null && input.selectionRange != null && rowIndex === input.selectionRange.endRow && colIdx === input.selectionRange.endCol;
@@ -941,6 +1255,9 @@ function computeCellDescriptor(item, col, rowIndex, colIdx, input) {
941
1255
  };
942
1256
  }
943
1257
  function resolveCellDisplayContent(col, item, displayValue) {
1258
+ if (displayValue instanceof FormulaError) {
1259
+ return displayValue.toString();
1260
+ }
944
1261
  const c = col;
945
1262
  if (c.renderCell && typeof c.renderCell === "function") {
946
1263
  return c.renderCell(item);
@@ -956,10 +1273,14 @@ function resolveCellDisplayContent(col, item, displayValue) {
956
1273
  }
957
1274
  return String(displayValue);
958
1275
  }
959
- function resolveCellStyle(col, item) {
1276
+ function resolveCellStyle(col, item, displayValue) {
960
1277
  const c = col;
961
- if (!c.cellStyle) return void 0;
962
- return typeof c.cellStyle === "function" ? c.cellStyle(item) : c.cellStyle;
1278
+ const isError = displayValue instanceof FormulaError;
1279
+ const base = c.cellStyle ? typeof c.cellStyle === "function" ? c.cellStyle(item) : c.cellStyle : void 0;
1280
+ if (isError) {
1281
+ return { ...base, color: "var(--ogrid-formula-error-color, #d32f2f)" };
1282
+ }
1283
+ return base;
963
1284
  }
964
1285
  function buildInlineEditorProps(item, col, descriptor, callbacks) {
965
1286
  return {
@@ -1079,6 +1400,7 @@ var AUTOSIZE_MAX_PX = 520;
1079
1400
  function measureHeaderWidth(th) {
1080
1401
  const cs = getComputedStyle(th);
1081
1402
  const thPadding = (parseFloat(cs.paddingLeft) || 0) + (parseFloat(cs.paddingRight) || 0);
1403
+ const thBorders = (parseFloat(cs.borderLeftWidth) || 0) + (parseFloat(cs.borderRightWidth) || 0);
1082
1404
  let resizeHandleWidth = 0;
1083
1405
  for (let i = 0; i < th.children.length; i++) {
1084
1406
  const child = th.children[i];
@@ -1101,12 +1423,14 @@ function measureHeaderWidth(th) {
1101
1423
  overflow: child.style.overflow,
1102
1424
  flexShrink: child.style.flexShrink,
1103
1425
  width: child.style.width,
1104
- minWidth: child.style.minWidth
1426
+ minWidth: child.style.minWidth,
1427
+ maxWidth: child.style.maxWidth
1105
1428
  });
1106
1429
  child.style.overflow = "visible";
1107
1430
  child.style.flexShrink = "0";
1108
1431
  child.style.width = "max-content";
1109
1432
  child.style.minWidth = "max-content";
1433
+ child.style.maxWidth = "none";
1110
1434
  }
1111
1435
  expandDescendants(child);
1112
1436
  }
@@ -1124,8 +1448,9 @@ function measureHeaderWidth(th) {
1124
1448
  m.el.style.flexShrink = m.flexShrink;
1125
1449
  m.el.style.width = m.width;
1126
1450
  m.el.style.minWidth = m.minWidth;
1451
+ m.el.style.maxWidth = m.maxWidth;
1127
1452
  }
1128
- return expandedWidth + resizeHandleWidth + thPadding;
1453
+ return expandedWidth + resizeHandleWidth + thPadding + thBorders;
1129
1454
  }
1130
1455
  function measureColumnContentWidth(columnId, minWidth, container) {
1131
1456
  const minW = minWidth ?? DEFAULT_MIN_COLUMN_WIDTH;
@@ -1342,7 +1667,7 @@ function formatCellValueForTsv(raw, formatted) {
1342
1667
  return "[Object]";
1343
1668
  }
1344
1669
  }
1345
- function formatSelectionAsTsv(items, visibleCols, range) {
1670
+ function formatSelectionAsTsv(items, visibleCols, range, formulaOptions) {
1346
1671
  const norm = normalizeSelectionRange(range);
1347
1672
  const rows = [];
1348
1673
  for (let r = norm.startRow; r <= norm.endRow; r++) {
@@ -1351,6 +1676,16 @@ function formatSelectionAsTsv(items, visibleCols, range) {
1351
1676
  if (r >= items.length || c >= visibleCols.length) break;
1352
1677
  const item = items[r];
1353
1678
  const col = visibleCols[c];
1679
+ if (formulaOptions?.hasFormula && formulaOptions?.getFormula) {
1680
+ const flatColIndex = formulaOptions.flatColumns.findIndex((fc) => fc.columnId === col.columnId);
1681
+ if (flatColIndex >= 0 && formulaOptions.hasFormula(flatColIndex, r)) {
1682
+ const formulaStr = formulaOptions.getFormula(flatColIndex, r);
1683
+ if (formulaStr) {
1684
+ cells.push(formulaStr);
1685
+ continue;
1686
+ }
1687
+ }
1688
+ }
1354
1689
  const raw = getCellValue(item, col);
1355
1690
  const clipboard = col.clipboardFormatter ? col.clipboardFormatter(raw, item) : null;
1356
1691
  const formatted = clipboard ?? (col.valueFormatter ? col.valueFormatter(raw, item) : raw);
@@ -1365,7 +1700,7 @@ function parseTsvClipboard(text) {
1365
1700
  const lines = text.split(/\r?\n/).filter((l) => l.length > 0);
1366
1701
  return lines.map((line) => line.split(" "));
1367
1702
  }
1368
- function applyPastedValues(parsedRows, anchorRow, anchorCol, items, visibleCols) {
1703
+ function applyPastedValues(parsedRows, anchorRow, anchorCol, items, visibleCols, formulaOptions) {
1369
1704
  const events = [];
1370
1705
  for (let r = 0; r < parsedRows.length; r++) {
1371
1706
  const cells = parsedRows[r];
@@ -1376,9 +1711,16 @@ function applyPastedValues(parsedRows, anchorRow, anchorCol, items, visibleCols)
1376
1711
  const item = items[targetRow];
1377
1712
  const col = visibleCols[targetCol];
1378
1713
  if (!isColumnEditable(col, item)) continue;
1379
- const rawValue = cells[c] ?? "";
1714
+ const cellText = cells[c] ?? "";
1715
+ if (cellText.startsWith("=") && formulaOptions?.setFormula) {
1716
+ const flatColIndex = formulaOptions.flatColumns.findIndex((fc) => fc.columnId === col.columnId);
1717
+ if (flatColIndex >= 0) {
1718
+ formulaOptions.setFormula(flatColIndex, targetRow, cellText);
1719
+ continue;
1720
+ }
1721
+ }
1380
1722
  const oldValue = getCellValue(item, col);
1381
- const result = parseValue(rawValue, oldValue, item, col);
1723
+ const result = parseValue(cellText, oldValue, item, col);
1382
1724
  if (!result.valid) continue;
1383
1725
  events.push({
1384
1726
  item,
@@ -1414,13 +1756,116 @@ function applyCutClear(cutRange, items, visibleCols) {
1414
1756
  return events;
1415
1757
  }
1416
1758
 
1759
+ // src/utils/cellReference.ts
1760
+ function indexToColumnLetter(index) {
1761
+ let result = "";
1762
+ let n = index;
1763
+ while (n >= 0) {
1764
+ result = String.fromCharCode(n % 26 + 65) + result;
1765
+ n = Math.floor(n / 26) - 1;
1766
+ }
1767
+ return result;
1768
+ }
1769
+ function formatCellReference(colIndex, rowNumber) {
1770
+ return `${indexToColumnLetter(colIndex)}${rowNumber}`;
1771
+ }
1772
+
1773
+ // src/formula/cellAddressUtils.ts
1774
+ function columnLetterToIndex(letters) {
1775
+ let result = 0;
1776
+ const upper = letters.toUpperCase();
1777
+ for (let i = 0; i < upper.length; i++) {
1778
+ result = result * 26 + (upper.charCodeAt(i) - 64);
1779
+ }
1780
+ return result - 1;
1781
+ }
1782
+ var CELL_REF_RE = /^(\$?)([A-Za-z]+)(\$?)(\d+)$/;
1783
+ var ADJUST_REF_RE = /(?:'[^']*'!|[A-Za-z_]\w*!)?(\$?)([A-Z]+)(\$?)(\d+)/g;
1784
+ function parseCellRef(ref) {
1785
+ const m = ref.match(CELL_REF_RE);
1786
+ if (!m) return null;
1787
+ const absCol = m[1] === "$";
1788
+ const colLetters = m[2];
1789
+ const absRow = m[3] === "$";
1790
+ const rowNum = parseInt(m[4], 10);
1791
+ if (rowNum < 1) return null;
1792
+ return {
1793
+ col: columnLetterToIndex(colLetters),
1794
+ row: rowNum - 1,
1795
+ // 0-based internally
1796
+ absCol,
1797
+ absRow
1798
+ };
1799
+ }
1800
+ function parseRange(rangeStr) {
1801
+ const parts = rangeStr.split(":");
1802
+ if (parts.length !== 2) return null;
1803
+ const start = parseCellRef(parts[0]);
1804
+ const end = parseCellRef(parts[1]);
1805
+ if (!start || !end) return null;
1806
+ return { start, end };
1807
+ }
1808
+ function formatAddress(addr) {
1809
+ const colStr = (addr.absCol ? "$" : "") + indexToColumnLetter(addr.col);
1810
+ const rowStr = (addr.absRow ? "$" : "") + (addr.row + 1);
1811
+ const cellStr = colStr + rowStr;
1812
+ if (addr.sheet) {
1813
+ const sheetStr = addr.sheet.includes(" ") ? `'${addr.sheet}'` : addr.sheet;
1814
+ return `${sheetStr}!${cellStr}`;
1815
+ }
1816
+ return cellStr;
1817
+ }
1818
+ function adjustFormulaReferences(formula, colDelta, rowDelta) {
1819
+ ADJUST_REF_RE.lastIndex = 0;
1820
+ return formula.replace(ADJUST_REF_RE, (match, colAbs, colLetters, rowAbs, rowDigits) => {
1821
+ const cellRefStart = match.indexOf(colAbs + colLetters);
1822
+ const sheetPrefix = cellRefStart > 0 ? match.substring(0, cellRefStart) : "";
1823
+ let newCol = colLetters;
1824
+ let newRow = rowDigits;
1825
+ if (colAbs !== "$") {
1826
+ const colIdx = columnLetterToIndex(colLetters) + colDelta;
1827
+ if (colIdx < 0) return "#REF!";
1828
+ newCol = indexToColumnLetter(colIdx);
1829
+ }
1830
+ if (rowAbs !== "$") {
1831
+ const rowNum = parseInt(rowDigits, 10) + rowDelta;
1832
+ if (rowNum < 1) return "#REF!";
1833
+ newRow = String(rowNum);
1834
+ }
1835
+ return `${sheetPrefix}${colAbs}${newCol}${rowAbs}${newRow}`;
1836
+ });
1837
+ }
1838
+ function toCellKey(col, row, sheet) {
1839
+ if (sheet) return `${sheet}:${col},${row}`;
1840
+ return `${col},${row}`;
1841
+ }
1842
+ function fromCellKey(key) {
1843
+ const colonIdx = key.indexOf(":");
1844
+ if (colonIdx >= 0 && isNaN(parseInt(key.substring(0, colonIdx), 10))) {
1845
+ const sheet = key.substring(0, colonIdx);
1846
+ const rest = key.substring(colonIdx + 1);
1847
+ const commaIdx = rest.indexOf(",");
1848
+ return {
1849
+ col: parseInt(rest.substring(0, commaIdx), 10),
1850
+ row: parseInt(rest.substring(commaIdx + 1), 10),
1851
+ sheet
1852
+ };
1853
+ }
1854
+ const i = key.indexOf(",");
1855
+ return {
1856
+ col: parseInt(key.substring(0, i), 10),
1857
+ row: parseInt(key.substring(i + 1), 10)
1858
+ };
1859
+ }
1860
+
1417
1861
  // src/utils/fillHelpers.ts
1418
- function applyFillValues(range, sourceRow, sourceCol, items, visibleCols) {
1862
+ function applyFillValues(range, sourceRow, sourceCol, items, visibleCols, formulaOptions) {
1419
1863
  const events = [];
1420
1864
  const startItem = items[range.startRow];
1421
1865
  const startColDef = visibleCols[range.startCol];
1422
1866
  if (!startItem || !startColDef) return events;
1423
1867
  const startValue = getCellValue(startItem, startColDef);
1868
+ const srcFlatColIndex = formulaOptions ? formulaOptions.flatColumns.findIndex((c) => c.columnId === startColDef.columnId) : -1;
1424
1869
  for (let row = range.startRow; row <= range.endRow; row++) {
1425
1870
  for (let col = range.startCol; col <= range.endCol; col++) {
1426
1871
  if (row === sourceRow && col === sourceCol) continue;
@@ -1428,6 +1873,19 @@ function applyFillValues(range, sourceRow, sourceCol, items, visibleCols) {
1428
1873
  const item = items[row];
1429
1874
  const colDef = visibleCols[col];
1430
1875
  if (!isColumnEditable(colDef, item)) continue;
1876
+ if (formulaOptions && formulaOptions.hasFormula && formulaOptions.getFormula && formulaOptions.setFormula && srcFlatColIndex >= 0 && formulaOptions.hasFormula(srcFlatColIndex, sourceRow)) {
1877
+ const srcFormula = formulaOptions.getFormula(srcFlatColIndex, sourceRow);
1878
+ if (srcFormula) {
1879
+ const rowDelta = row - sourceRow;
1880
+ const colDelta = col - sourceCol;
1881
+ const adjusted = adjustFormulaReferences(srcFormula, colDelta, rowDelta);
1882
+ const targetFlatColIdx = formulaOptions.flatColumns.findIndex((c) => c.columnId === colDef.columnId);
1883
+ if (targetFlatColIdx >= 0) {
1884
+ formulaOptions.setFormula(targetFlatColIdx, row, adjusted);
1885
+ continue;
1886
+ }
1887
+ }
1888
+ }
1431
1889
  const oldValue = getCellValue(item, colDef);
1432
1890
  const result = parseValue(startValue, oldValue, item, colDef);
1433
1891
  if (!result.valid) continue;
@@ -1652,4 +2110,3227 @@ var Z_INDEX = {
1652
2110
  CONTEXT_MENU: 1e4
1653
2111
  };
1654
2112
 
1655
- export { AUTOSIZE_EXTRA_PX, AUTOSIZE_MAX_PX, CELL_PADDING, CHECKBOX_COLUMN_WIDTH, COLUMN_HEADER_MENU_ITEMS, CellDescriptorCache, DEFAULT_DEBOUNCE_MS, DEFAULT_MIN_COLUMN_WIDTH, GRID_BORDER_RADIUS, GRID_CONTEXT_MENU_ITEMS, MAX_PAGE_BUTTONS, PAGE_SIZE_OPTIONS, PEOPLE_SEARCH_DEBOUNCE_MS, ROW_NUMBER_COLUMN_WIDTH, SIDEBAR_TRANSITION_MS, UndoRedoStack, Z_INDEX, applyCellDeletion, applyCutClear, applyFillValues, applyPastedValues, applyRangeRowSelection, areGridRowPropsEqual, booleanParser, buildCellIndex, buildCsvHeader, buildCsvRows, buildHeaderRows, buildInlineEditorProps, buildPopoverEditorProps, calculateDropTarget, clampSelectionToBounds, computeAggregations, computeArrowNavigation, computeAutoScrollSpeed, computeNextSortState, computeRowSelectionState, computeTabNavigation, computeTotalHeight, computeVisibleRange, currencyParser, dateParser, debounce, deriveFilterOptionsFromData, emailParser, escapeCsvValue, exportToCsv, findCtrlArrowTarget, flattenColumns, formatCellValueForTsv, formatSelectionAsTsv, formatShortcut, getCellRenderDescriptor, getCellValue, getColumnHeaderMenuItems, getContextMenuHandlers, getDataGridStatusBarConfig, getFilterField, getHeaderFilterConfig, getMultiSelectFilterFields, getPaginationViewModel, getPinStateForColumn, getScrollTopForRow, getStatusBarParts, injectGlobalStyles, isColumnEditable, isFilterConfig, isInSelectionRange, isRowInRange, measureColumnContentWidth, measureRange, mergeFilter, normalizeSelectionRange, numberParser, parseTsvClipboard, parseValue, processClientSideData, rangesEqual, reorderColumnArray, resolveCellDisplayContent, resolveCellStyle, toUserLike, triggerCsvDownload, validateColumns, validateRowIds, validateVirtualScrollConfig };
2113
+ // src/formula/errors.ts
2114
+ var REF_ERROR = new FormulaError("#REF!", "Invalid cell reference");
2115
+ var DIV_ZERO_ERROR = new FormulaError("#DIV/0!", "Division by zero");
2116
+ var VALUE_ERROR = new FormulaError("#VALUE!", "Wrong value type");
2117
+ var NAME_ERROR = new FormulaError("#NAME?", "Unknown function or name");
2118
+ var CIRC_ERROR = new FormulaError("#CIRC!", "Circular reference");
2119
+ var GENERAL_ERROR = new FormulaError("#ERROR!", "Formula error");
2120
+ var NA_ERROR = new FormulaError("#N/A", "No match found");
2121
+ function isFormulaError(value) {
2122
+ return value instanceof FormulaError;
2123
+ }
2124
+
2125
+ // src/formula/tokenizer.ts
2126
+ var CELL_REF_PATTERN = /^\$?[A-Za-z]+\$?\d+$/;
2127
+ var SINGLE_CHAR_OPERATORS = {
2128
+ "+": "PLUS",
2129
+ "-": "MINUS",
2130
+ "*": "MULTIPLY",
2131
+ "/": "DIVIDE",
2132
+ "^": "POWER",
2133
+ "%": "PERCENT",
2134
+ "&": "AMPERSAND",
2135
+ "=": "EQ"
2136
+ };
2137
+ var DELIMITERS = {
2138
+ "(": "LPAREN",
2139
+ ")": "RPAREN",
2140
+ ",": "COMMA",
2141
+ ":": "COLON"
2142
+ };
2143
+ function tokenize(input) {
2144
+ const tokens = [];
2145
+ let pos = 0;
2146
+ while (pos < input.length) {
2147
+ const ch = input[pos];
2148
+ if (ch === " " || ch === " " || ch === "\r" || ch === "\n") {
2149
+ pos++;
2150
+ continue;
2151
+ }
2152
+ if (ch >= "0" && ch <= "9" || ch === "." && pos + 1 < input.length && input[pos + 1] >= "0" && input[pos + 1] <= "9") {
2153
+ const start = pos;
2154
+ while (pos < input.length && input[pos] >= "0" && input[pos] <= "9") {
2155
+ pos++;
2156
+ }
2157
+ if (pos < input.length && input[pos] === ".") {
2158
+ pos++;
2159
+ while (pos < input.length && input[pos] >= "0" && input[pos] <= "9") {
2160
+ pos++;
2161
+ }
2162
+ }
2163
+ tokens.push({ type: "NUMBER", value: input.slice(start, pos), position: start });
2164
+ continue;
2165
+ }
2166
+ if (ch === "'") {
2167
+ const start = pos;
2168
+ pos++;
2169
+ const nameStart = pos;
2170
+ while (pos < input.length && input[pos] !== "'") {
2171
+ pos++;
2172
+ }
2173
+ const sheetName = input.slice(nameStart, pos);
2174
+ if (pos < input.length && input[pos] === "'") {
2175
+ pos++;
2176
+ if (pos < input.length && input[pos] === "!") {
2177
+ pos++;
2178
+ tokens.push({ type: "SHEET_REF", value: sheetName, position: start });
2179
+ continue;
2180
+ }
2181
+ }
2182
+ throw new FormulaError("#ERROR!", `Invalid sheet reference at position ${start}`);
2183
+ }
2184
+ if (ch === '"') {
2185
+ const start = pos;
2186
+ pos++;
2187
+ const scanStart = pos;
2188
+ let hasEscapes = false;
2189
+ while (pos < input.length) {
2190
+ if (input[pos] === '"') {
2191
+ if (pos + 1 < input.length && input[pos + 1] === '"') {
2192
+ hasEscapes = true;
2193
+ pos += 2;
2194
+ } else {
2195
+ break;
2196
+ }
2197
+ } else {
2198
+ pos++;
2199
+ }
2200
+ }
2201
+ let value;
2202
+ if (!hasEscapes) {
2203
+ value = input.slice(scanStart, pos);
2204
+ } else {
2205
+ value = input.slice(scanStart, pos).replace(/""/g, '"');
2206
+ }
2207
+ if (pos < input.length) pos++;
2208
+ tokens.push({ type: "STRING", value, position: start });
2209
+ continue;
2210
+ }
2211
+ if (ch === ">" && pos + 1 < input.length && input[pos + 1] === "=") {
2212
+ tokens.push({ type: "GTE", value: ">=", position: pos });
2213
+ pos += 2;
2214
+ continue;
2215
+ }
2216
+ if (ch === "<" && pos + 1 < input.length && input[pos + 1] === "=") {
2217
+ tokens.push({ type: "LTE", value: "<=", position: pos });
2218
+ pos += 2;
2219
+ continue;
2220
+ }
2221
+ if (ch === "<" && pos + 1 < input.length && input[pos + 1] === ">") {
2222
+ tokens.push({ type: "NEQ", value: "<>", position: pos });
2223
+ pos += 2;
2224
+ continue;
2225
+ }
2226
+ if (ch === ">" || ch === "<") {
2227
+ const type = ch === ">" ? "GT" : "LT";
2228
+ tokens.push({ type, value: ch, position: pos });
2229
+ pos++;
2230
+ continue;
2231
+ }
2232
+ if (SINGLE_CHAR_OPERATORS[ch]) {
2233
+ tokens.push({ type: SINGLE_CHAR_OPERATORS[ch], value: ch, position: pos });
2234
+ pos++;
2235
+ continue;
2236
+ }
2237
+ if (DELIMITERS[ch]) {
2238
+ tokens.push({ type: DELIMITERS[ch], value: ch, position: pos });
2239
+ pos++;
2240
+ continue;
2241
+ }
2242
+ if (ch === "$" || ch >= "A" && ch <= "Z" || ch >= "a" && ch <= "z") {
2243
+ const start = pos;
2244
+ while (pos < input.length && (input[pos] >= "A" && input[pos] <= "Z" || input[pos] >= "a" && input[pos] <= "z" || input[pos] >= "0" && input[pos] <= "9" || input[pos] === "$" || input[pos] === "_")) {
2245
+ pos++;
2246
+ }
2247
+ const word = input.slice(start, pos);
2248
+ if (pos < input.length && input[pos] === "!") {
2249
+ pos++;
2250
+ tokens.push({ type: "SHEET_REF", value: word, position: start });
2251
+ continue;
2252
+ }
2253
+ if (pos < input.length && input[pos] === "(") {
2254
+ tokens.push({ type: "FUNCTION", value: word, position: start });
2255
+ continue;
2256
+ }
2257
+ const upper = word.toUpperCase();
2258
+ if (upper === "TRUE" || upper === "FALSE") {
2259
+ tokens.push({ type: "BOOLEAN", value: upper, position: start });
2260
+ continue;
2261
+ }
2262
+ if (CELL_REF_PATTERN.test(word)) {
2263
+ tokens.push({ type: "CELL_REF", value: word, position: start });
2264
+ continue;
2265
+ }
2266
+ tokens.push({ type: "IDENTIFIER", value: word, position: start });
2267
+ continue;
2268
+ }
2269
+ throw new FormulaError("#ERROR!", `Unexpected character: ${ch}`);
2270
+ }
2271
+ tokens.push({ type: "EOF", value: "", position: pos });
2272
+ return tokens;
2273
+ }
2274
+
2275
+ // src/formula/parser.ts
2276
+ function parse(tokens, namedRanges) {
2277
+ let pos = 0;
2278
+ function peek() {
2279
+ return tokens[pos];
2280
+ }
2281
+ function advance() {
2282
+ const token = tokens[pos];
2283
+ pos++;
2284
+ return token;
2285
+ }
2286
+ function expect(type) {
2287
+ const token = peek();
2288
+ if (token && token.type === type) {
2289
+ return advance();
2290
+ }
2291
+ return null;
2292
+ }
2293
+ function errorNode(message) {
2294
+ return { kind: "error", error: new FormulaError("#ERROR!", message) };
2295
+ }
2296
+ function expression() {
2297
+ return comparison();
2298
+ }
2299
+ function comparison() {
2300
+ let left = concat();
2301
+ while (peek()) {
2302
+ const t = peek();
2303
+ let op = null;
2304
+ if (t.type === "GT") op = ">";
2305
+ else if (t.type === "LT") op = "<";
2306
+ else if (t.type === "GTE") op = ">=";
2307
+ else if (t.type === "LTE") op = "<=";
2308
+ else if (t.type === "EQ") op = "=";
2309
+ else if (t.type === "NEQ") op = "<>";
2310
+ else break;
2311
+ advance();
2312
+ const right = concat();
2313
+ left = { kind: "binaryOp", op, left, right };
2314
+ }
2315
+ return left;
2316
+ }
2317
+ function concat() {
2318
+ let left = addition();
2319
+ while (peek() && peek().type === "AMPERSAND") {
2320
+ advance();
2321
+ const right = addition();
2322
+ left = { kind: "binaryOp", op: "&", left, right };
2323
+ }
2324
+ return left;
2325
+ }
2326
+ function addition() {
2327
+ let left = multiplication();
2328
+ while (peek()) {
2329
+ const t = peek();
2330
+ let op = null;
2331
+ if (t.type === "PLUS") op = "+";
2332
+ else if (t.type === "MINUS") op = "-";
2333
+ else break;
2334
+ advance();
2335
+ const right = multiplication();
2336
+ left = { kind: "binaryOp", op, left, right };
2337
+ }
2338
+ return left;
2339
+ }
2340
+ function multiplication() {
2341
+ let left = power();
2342
+ while (peek()) {
2343
+ const t = peek();
2344
+ let op = null;
2345
+ if (t.type === "MULTIPLY") op = "*";
2346
+ else if (t.type === "DIVIDE") op = "/";
2347
+ else break;
2348
+ advance();
2349
+ const right = power();
2350
+ left = { kind: "binaryOp", op, left, right };
2351
+ }
2352
+ return left;
2353
+ }
2354
+ function power() {
2355
+ let left = unary();
2356
+ while (peek() && peek().type === "POWER") {
2357
+ advance();
2358
+ const right = unary();
2359
+ left = { kind: "binaryOp", op: "^", left, right };
2360
+ }
2361
+ return left;
2362
+ }
2363
+ function unary() {
2364
+ const t = peek();
2365
+ if (t && (t.type === "MINUS" || t.type === "PLUS")) {
2366
+ const op = t.type === "MINUS" ? "-" : "+";
2367
+ advance();
2368
+ const operand = unary();
2369
+ return { kind: "unaryOp", op, operand };
2370
+ }
2371
+ return postfix();
2372
+ }
2373
+ function postfix() {
2374
+ let node = primary();
2375
+ if (peek() && peek().type === "PERCENT") {
2376
+ advance();
2377
+ node = { kind: "binaryOp", op: "%", left: node, right: { kind: "number", value: 100 } };
2378
+ }
2379
+ return node;
2380
+ }
2381
+ function primary() {
2382
+ const t = peek();
2383
+ if (!t || t.type === "EOF") {
2384
+ return errorNode("Unexpected end of expression");
2385
+ }
2386
+ if (t.type === "NUMBER") {
2387
+ advance();
2388
+ return { kind: "number", value: parseFloat(t.value) };
2389
+ }
2390
+ if (t.type === "STRING") {
2391
+ advance();
2392
+ return { kind: "string", value: t.value };
2393
+ }
2394
+ if (t.type === "BOOLEAN") {
2395
+ advance();
2396
+ return { kind: "boolean", value: t.value.toUpperCase() === "TRUE" };
2397
+ }
2398
+ if (t.type === "CELL_REF") {
2399
+ return cellRefOrRange();
2400
+ }
2401
+ if (t.type === "FUNCTION") {
2402
+ return functionCall();
2403
+ }
2404
+ if (t.type === "IDENTIFIER") {
2405
+ return namedRangeRef();
2406
+ }
2407
+ if (t.type === "SHEET_REF") {
2408
+ return sheetRef();
2409
+ }
2410
+ if (t.type === "LPAREN") {
2411
+ advance();
2412
+ const node = expression();
2413
+ if (!expect("RPAREN")) {
2414
+ return errorNode("Expected closing parenthesis");
2415
+ }
2416
+ return node;
2417
+ }
2418
+ advance();
2419
+ return errorNode(`Unexpected token: ${t.value}`);
2420
+ }
2421
+ function cellRefOrRange() {
2422
+ const refToken = advance();
2423
+ const address = parseCellRef(refToken.value);
2424
+ if (!address) {
2425
+ return errorNode(`Invalid cell reference: ${refToken.value}`);
2426
+ }
2427
+ if (peek() && peek().type === "COLON") {
2428
+ advance();
2429
+ const endToken = expect("CELL_REF");
2430
+ if (!endToken) {
2431
+ return errorNode('Expected cell reference after ":"');
2432
+ }
2433
+ const endAddress = parseCellRef(endToken.value);
2434
+ if (!endAddress) {
2435
+ return errorNode(`Invalid cell reference: ${endToken.value}`);
2436
+ }
2437
+ return {
2438
+ kind: "range",
2439
+ start: address,
2440
+ end: endAddress,
2441
+ raw: `${refToken.value}:${endToken.value}`
2442
+ };
2443
+ }
2444
+ return {
2445
+ kind: "cellRef",
2446
+ address,
2447
+ raw: refToken.value
2448
+ };
2449
+ }
2450
+ function functionCall() {
2451
+ const nameToken = advance();
2452
+ const name = nameToken.value.toUpperCase();
2453
+ if (!expect("LPAREN")) {
2454
+ return errorNode(`Expected "(" after function name "${name}"`);
2455
+ }
2456
+ const args = [];
2457
+ if (peek() && peek().type !== "RPAREN" && peek().type !== "EOF") {
2458
+ args.push(expression());
2459
+ while (peek() && peek().type === "COMMA") {
2460
+ advance();
2461
+ args.push(expression());
2462
+ }
2463
+ }
2464
+ if (!expect("RPAREN")) {
2465
+ return errorNode(`Expected ")" after function arguments for "${name}"`);
2466
+ }
2467
+ return { kind: "functionCall", name, args };
2468
+ }
2469
+ function namedRangeRef() {
2470
+ const nameToken = advance();
2471
+ const name = nameToken.value.toUpperCase();
2472
+ const ref = namedRanges?.get(name);
2473
+ if (!ref) {
2474
+ return { kind: "error", error: new FormulaError("#NAME?", `Unknown name: ${nameToken.value}`) };
2475
+ }
2476
+ if (ref.includes(":")) {
2477
+ const rangeRef = parseRange(ref);
2478
+ if (rangeRef) {
2479
+ return { kind: "range", start: rangeRef.start, end: rangeRef.end, raw: ref };
2480
+ }
2481
+ }
2482
+ const cellRef = parseCellRef(ref);
2483
+ if (cellRef) {
2484
+ return { kind: "cellRef", address: cellRef, raw: ref };
2485
+ }
2486
+ return { kind: "error", error: new FormulaError("#REF!", `Invalid named range reference: ${ref}`) };
2487
+ }
2488
+ function sheetRef() {
2489
+ const sheetToken = advance();
2490
+ const sheetName = sheetToken.value;
2491
+ const cellToken = expect("CELL_REF");
2492
+ if (!cellToken) {
2493
+ return errorNode(`Expected cell reference after sheet "${sheetName}!"`);
2494
+ }
2495
+ const address = parseCellRef(cellToken.value);
2496
+ if (!address) {
2497
+ return errorNode(`Invalid cell reference: ${cellToken.value}`);
2498
+ }
2499
+ address.sheet = sheetName;
2500
+ if (peek() && peek().type === "COLON") {
2501
+ advance();
2502
+ const endToken = expect("CELL_REF");
2503
+ if (!endToken) {
2504
+ return errorNode('Expected cell reference after ":"');
2505
+ }
2506
+ const endAddress = parseCellRef(endToken.value);
2507
+ if (!endAddress) {
2508
+ return errorNode(`Invalid cell reference: ${endToken.value}`);
2509
+ }
2510
+ endAddress.sheet = sheetName;
2511
+ return {
2512
+ kind: "range",
2513
+ start: address,
2514
+ end: endAddress,
2515
+ raw: `${sheetName}!${cellToken.value}:${endToken.value}`
2516
+ };
2517
+ }
2518
+ return {
2519
+ kind: "cellRef",
2520
+ address,
2521
+ raw: `${sheetName}!${cellToken.value}`
2522
+ };
2523
+ }
2524
+ const result = expression();
2525
+ if (peek() && peek().type !== "EOF") {
2526
+ return errorNode(`Unexpected token after expression: ${peek().value}`);
2527
+ }
2528
+ return result;
2529
+ }
2530
+
2531
+ // src/formula/evaluator.ts
2532
+ function toNumber(val) {
2533
+ if (val instanceof FormulaError) return val;
2534
+ if (val === null || val === void 0 || val === "") return 0;
2535
+ if (typeof val === "boolean") return val ? 1 : 0;
2536
+ if (typeof val === "number") return val;
2537
+ if (val instanceof Date) return val.getTime();
2538
+ const n = Number(val);
2539
+ if (isNaN(n)) return new FormulaError("#VALUE!", `Cannot convert "${val}" to number`);
2540
+ return n;
2541
+ }
2542
+ function toString(val) {
2543
+ if (val === null || val === void 0) return "";
2544
+ if (val instanceof FormulaError) return val.toString();
2545
+ if (val instanceof Date) return val.toLocaleDateString();
2546
+ return String(val);
2547
+ }
2548
+ function toBoolean(val) {
2549
+ if (typeof val === "boolean") return val;
2550
+ if (typeof val === "number") return val !== 0;
2551
+ if (typeof val === "string") {
2552
+ if (val.toUpperCase() === "TRUE") return true;
2553
+ if (val.toUpperCase() === "FALSE") return false;
2554
+ return val.length > 0;
2555
+ }
2556
+ return val !== null && val !== void 0;
2557
+ }
2558
+ function flattenArgs(args, context, evaluator) {
2559
+ const result = [];
2560
+ for (const arg of args) {
2561
+ if (arg.kind === "range") {
2562
+ const values = context.getRangeValues({ start: arg.start, end: arg.end });
2563
+ for (const row of values) {
2564
+ for (const val of row) {
2565
+ result.push(val);
2566
+ }
2567
+ }
2568
+ } else {
2569
+ result.push(evaluator.evaluate(arg, context));
2570
+ }
2571
+ }
2572
+ return result;
2573
+ }
2574
+ var FormulaEvaluator = class {
2575
+ constructor(builtInFunctions) {
2576
+ this.functions = new Map(builtInFunctions);
2577
+ }
2578
+ registerFunction(name, fn) {
2579
+ this.functions.set(name.toUpperCase(), fn);
2580
+ }
2581
+ evaluate(node, context) {
2582
+ switch (node.kind) {
2583
+ case "number":
2584
+ return node.value;
2585
+ case "string":
2586
+ return node.value;
2587
+ case "boolean":
2588
+ return node.value;
2589
+ case "error":
2590
+ return node.error;
2591
+ case "cellRef": {
2592
+ const val = context.getCellValue(node.address);
2593
+ return val;
2594
+ }
2595
+ case "range":
2596
+ return context.getCellValue(node.start);
2597
+ case "functionCall":
2598
+ return this.evaluateFunction(node.name, node.args, context);
2599
+ case "binaryOp":
2600
+ return this.evaluateBinaryOp(node.op, node.left, node.right, context);
2601
+ case "unaryOp":
2602
+ return this.evaluateUnaryOp(node.op, node.operand, context);
2603
+ }
2604
+ }
2605
+ evaluateFunction(name, args, context) {
2606
+ const fn = this.functions.get(name);
2607
+ if (!fn) {
2608
+ return new FormulaError("#NAME?", `Unknown function: ${name}`);
2609
+ }
2610
+ if (args.length < fn.minArgs) {
2611
+ return new FormulaError("#ERROR!", `${name} requires at least ${fn.minArgs} argument(s)`);
2612
+ }
2613
+ if (fn.maxArgs >= 0 && args.length > fn.maxArgs) {
2614
+ return new FormulaError("#ERROR!", `${name} accepts at most ${fn.maxArgs} argument(s)`);
2615
+ }
2616
+ return fn.evaluate(args, context, this);
2617
+ }
2618
+ evaluateBinaryOp(op, left, right, context) {
2619
+ if (op === "&") {
2620
+ const l = this.evaluate(left, context);
2621
+ if (l instanceof FormulaError) return l;
2622
+ const r = this.evaluate(right, context);
2623
+ if (r instanceof FormulaError) return r;
2624
+ return toString(l) + toString(r);
2625
+ }
2626
+ if (op === ">" || op === "<" || op === ">=" || op === "<=" || op === "=" || op === "<>") {
2627
+ const l = this.evaluate(left, context);
2628
+ if (l instanceof FormulaError) return l;
2629
+ const r = this.evaluate(right, context);
2630
+ if (r instanceof FormulaError) return r;
2631
+ return this.compare(op, l, r);
2632
+ }
2633
+ const lVal = this.evaluate(left, context);
2634
+ if (lVal instanceof FormulaError) return lVal;
2635
+ const rVal = this.evaluate(right, context);
2636
+ if (rVal instanceof FormulaError) return rVal;
2637
+ const lNum = toNumber(lVal);
2638
+ if (lNum instanceof FormulaError) return lNum;
2639
+ const rNum = toNumber(rVal);
2640
+ if (rNum instanceof FormulaError) return rNum;
2641
+ switch (op) {
2642
+ case "+":
2643
+ return lNum + rNum;
2644
+ case "-":
2645
+ return lNum - rNum;
2646
+ case "*":
2647
+ return lNum * rNum;
2648
+ case "/":
2649
+ if (rNum === 0) return new FormulaError("#DIV/0!");
2650
+ return lNum / rNum;
2651
+ case "^":
2652
+ return Math.pow(lNum, rNum);
2653
+ case "%":
2654
+ return lNum * rNum / 100;
2655
+ default:
2656
+ return new FormulaError("#ERROR!", `Unknown operator: ${op}`);
2657
+ }
2658
+ }
2659
+ evaluateUnaryOp(op, operand, context) {
2660
+ const val = this.evaluate(operand, context);
2661
+ if (val instanceof FormulaError) return val;
2662
+ const num = toNumber(val);
2663
+ if (num instanceof FormulaError) return num;
2664
+ return op === "-" ? -num : num;
2665
+ }
2666
+ compare(op, left, right) {
2667
+ if (typeof left === "number" && typeof right === "number") {
2668
+ return this.numCompare(op, left, right);
2669
+ }
2670
+ if (typeof left === "string" && typeof right === "string") {
2671
+ return this.strCompare(op, left, right);
2672
+ }
2673
+ if (typeof left === "boolean" && typeof right === "boolean") {
2674
+ return this.numCompare(op, left ? 1 : 0, right ? 1 : 0);
2675
+ }
2676
+ const lNum = toNumber(left);
2677
+ const rNum = toNumber(right);
2678
+ if (typeof lNum === "number" && typeof rNum === "number") {
2679
+ return this.numCompare(op, lNum, rNum);
2680
+ }
2681
+ return this.strCompare(op, toString(left), toString(right));
2682
+ }
2683
+ numCompare(op, a, b) {
2684
+ switch (op) {
2685
+ case ">":
2686
+ return a > b;
2687
+ case "<":
2688
+ return a < b;
2689
+ case ">=":
2690
+ return a >= b;
2691
+ case "<=":
2692
+ return a <= b;
2693
+ case "=":
2694
+ return a === b;
2695
+ case "<>":
2696
+ return a !== b;
2697
+ default:
2698
+ return false;
2699
+ }
2700
+ }
2701
+ strCompare(op, a, b) {
2702
+ const al = a.toLowerCase();
2703
+ const bl = b.toLowerCase();
2704
+ switch (op) {
2705
+ case ">":
2706
+ return al > bl;
2707
+ case "<":
2708
+ return al < bl;
2709
+ case ">=":
2710
+ return al >= bl;
2711
+ case "<=":
2712
+ return al <= bl;
2713
+ case "=":
2714
+ return al === bl;
2715
+ case "<>":
2716
+ return al !== bl;
2717
+ default:
2718
+ return false;
2719
+ }
2720
+ }
2721
+ };
2722
+
2723
+ // src/formula/dependencyGraph.ts
2724
+ var EMPTY_SET = Object.freeze(/* @__PURE__ */ new Set());
2725
+ var DependencyGraph = class {
2726
+ constructor() {
2727
+ /** cell -> set of cells it depends on (references in its formula) */
2728
+ this.dependencies = /* @__PURE__ */ new Map();
2729
+ /** cell -> set of cells that depend on it (reverse index) */
2730
+ this.dependents = /* @__PURE__ */ new Map();
2731
+ }
2732
+ /**
2733
+ * Set the dependencies for a cell, replacing any previous ones.
2734
+ * Updates both the forward (dependencies) and reverse (dependents) maps.
2735
+ */
2736
+ setDependencies(cell, deps) {
2737
+ this.removeDependenciesInternal(cell);
2738
+ this.dependencies.set(cell, deps);
2739
+ for (const dep of deps) {
2740
+ let depSet = this.dependents.get(dep);
2741
+ if (!depSet) {
2742
+ depSet = /* @__PURE__ */ new Set();
2743
+ this.dependents.set(dep, depSet);
2744
+ }
2745
+ depSet.add(cell);
2746
+ }
2747
+ }
2748
+ /**
2749
+ * Remove all dependency information for a cell from both maps.
2750
+ */
2751
+ removeDependencies(cell) {
2752
+ this.removeDependenciesInternal(cell);
2753
+ this.dependencies.delete(cell);
2754
+ }
2755
+ /**
2756
+ * Get all cells that directly or transitively depend on `changedCell`,
2757
+ * returned in topological order (a cell appears AFTER all cells it depends on).
2758
+ *
2759
+ * Uses Kahn's algorithm. If a cycle is detected, cycle participants are
2760
+ * appended at the end (the engine will assign #CIRC! to them).
2761
+ */
2762
+ getRecalcOrder(changedCell) {
2763
+ return this.topologicalSort(/* @__PURE__ */ new Set([changedCell]));
2764
+ }
2765
+ /**
2766
+ * Same as getRecalcOrder but for multiple changed cells.
2767
+ * Union of all transitive dependents, topologically sorted.
2768
+ */
2769
+ getRecalcOrderBatch(changedCells) {
2770
+ return this.topologicalSort(new Set(changedCells));
2771
+ }
2772
+ /**
2773
+ * Check if adding dependencies from `cell` to `deps` would create a cycle.
2774
+ * DFS from each dep: if we can reach `cell`, it would create a cycle.
2775
+ */
2776
+ wouldCreateCycle(cell, deps) {
2777
+ if (deps.has(cell)) {
2778
+ return true;
2779
+ }
2780
+ const visited = /* @__PURE__ */ new Set();
2781
+ for (const dep of deps) {
2782
+ if (this.canReach(dep, cell, visited)) {
2783
+ return true;
2784
+ }
2785
+ }
2786
+ return false;
2787
+ }
2788
+ /**
2789
+ * Return direct dependents of a cell (cells whose formulas reference this cell).
2790
+ * Returns an empty set if none.
2791
+ */
2792
+ getDependents(cell) {
2793
+ return this.dependents.get(cell) ?? EMPTY_SET;
2794
+ }
2795
+ /**
2796
+ * Return direct dependencies of a cell (cells referenced in this cell's formula).
2797
+ * Returns an empty set if none.
2798
+ */
2799
+ getDependencies(cell) {
2800
+ return this.dependencies.get(cell) ?? EMPTY_SET;
2801
+ }
2802
+ /**
2803
+ * Clear both maps entirely.
2804
+ */
2805
+ clear() {
2806
+ this.dependencies.clear();
2807
+ this.dependents.clear();
2808
+ }
2809
+ // ---------------------------------------------------------------------------
2810
+ // Private helpers
2811
+ // ---------------------------------------------------------------------------
2812
+ /**
2813
+ * Remove `cell` from the forward dependencies map and clean up reverse
2814
+ * references in the dependents map.
2815
+ */
2816
+ removeDependenciesInternal(cell) {
2817
+ const oldDeps = this.dependencies.get(cell);
2818
+ if (!oldDeps) {
2819
+ return;
2820
+ }
2821
+ for (const oldDep of oldDeps) {
2822
+ const depSet = this.dependents.get(oldDep);
2823
+ if (depSet) {
2824
+ depSet.delete(cell);
2825
+ if (depSet.size === 0) {
2826
+ this.dependents.delete(oldDep);
2827
+ }
2828
+ }
2829
+ }
2830
+ this.dependencies.delete(cell);
2831
+ }
2832
+ /**
2833
+ * Iterative DFS: check if `target` is reachable from `start` by following
2834
+ * the dependency chain. Iterative to avoid stack overflow for deep chains.
2835
+ */
2836
+ canReach(start, target, visited) {
2837
+ if (start === target) return true;
2838
+ if (visited.has(start)) return false;
2839
+ const stack = [start];
2840
+ visited.add(start);
2841
+ while (stack.length > 0) {
2842
+ const current = stack.pop();
2843
+ const deps = this.dependencies.get(current);
2844
+ if (!deps) continue;
2845
+ for (const dep of deps) {
2846
+ if (dep === target) return true;
2847
+ if (!visited.has(dep)) {
2848
+ visited.add(dep);
2849
+ stack.push(dep);
2850
+ }
2851
+ }
2852
+ }
2853
+ return false;
2854
+ }
2855
+ /**
2856
+ * Topological sort using Kahn's algorithm.
2857
+ *
2858
+ * 1. Collect all cells transitively dependent on the changed cell(s).
2859
+ * 2. Build in-degree map for these cells (count how many of their
2860
+ * dependencies are in the affected set).
2861
+ * 3. Start with cells whose in-degree is 0 (only depend on unaffected
2862
+ * cells or the changed cells themselves).
2863
+ * 4. Process queue: for each cell, reduce in-degree of its dependents,
2864
+ * add to queue when in-degree reaches 0.
2865
+ * 5. If any cells remain unprocessed, they're in a cycle — append them
2866
+ * at the end (engine marks as #CIRC!).
2867
+ */
2868
+ topologicalSort(changedCells) {
2869
+ const affected = /* @__PURE__ */ new Set();
2870
+ const bfsQueue = [];
2871
+ for (const changed of changedCells) {
2872
+ const directDependents = this.dependents.get(changed);
2873
+ if (directDependents) {
2874
+ for (const dep of directDependents) {
2875
+ if (!affected.has(dep)) {
2876
+ affected.add(dep);
2877
+ bfsQueue.push(dep);
2878
+ }
2879
+ }
2880
+ }
2881
+ }
2882
+ let head = 0;
2883
+ while (head < bfsQueue.length) {
2884
+ const current = bfsQueue[head++];
2885
+ const currentDependents = this.dependents.get(current);
2886
+ if (currentDependents) {
2887
+ for (const dep of currentDependents) {
2888
+ if (!affected.has(dep)) {
2889
+ affected.add(dep);
2890
+ bfsQueue.push(dep);
2891
+ }
2892
+ }
2893
+ }
2894
+ }
2895
+ if (affected.size === 0) {
2896
+ return [];
2897
+ }
2898
+ const inDegree = /* @__PURE__ */ new Map();
2899
+ for (const cell of affected) {
2900
+ let degree = 0;
2901
+ const deps = this.dependencies.get(cell);
2902
+ if (deps) {
2903
+ for (const dep of deps) {
2904
+ if (affected.has(dep)) {
2905
+ degree++;
2906
+ }
2907
+ }
2908
+ }
2909
+ inDegree.set(cell, degree);
2910
+ }
2911
+ const queue = [];
2912
+ for (const [cell, degree] of inDegree) {
2913
+ if (degree === 0) {
2914
+ queue.push(cell);
2915
+ }
2916
+ }
2917
+ const result = [];
2918
+ let queueHead = 0;
2919
+ while (queueHead < queue.length) {
2920
+ const cell = queue[queueHead++];
2921
+ result.push(cell);
2922
+ const cellDependents = this.dependents.get(cell);
2923
+ if (cellDependents) {
2924
+ for (const dependent of cellDependents) {
2925
+ if (affected.has(dependent)) {
2926
+ const newDegree = inDegree.get(dependent) - 1;
2927
+ inDegree.set(dependent, newDegree);
2928
+ if (newDegree === 0) {
2929
+ queue.push(dependent);
2930
+ }
2931
+ }
2932
+ }
2933
+ }
2934
+ }
2935
+ if (result.length < affected.size) {
2936
+ const resultSet = new Set(result);
2937
+ for (const cell of affected) {
2938
+ if (!resultSet.has(cell)) {
2939
+ result.push(cell);
2940
+ }
2941
+ }
2942
+ }
2943
+ return result;
2944
+ }
2945
+ };
2946
+
2947
+ // src/formula/functions/math.ts
2948
+ function registerMathFunctions(registry) {
2949
+ registry.set("SUM", {
2950
+ minArgs: 1,
2951
+ maxArgs: -1,
2952
+ evaluate(args, context, evaluator) {
2953
+ const values = flattenArgs(args, context, evaluator);
2954
+ let sum = 0;
2955
+ for (const val of values) {
2956
+ if (val instanceof FormulaError) return val;
2957
+ if (typeof val === "number") {
2958
+ sum += val;
2959
+ } else if (typeof val === "boolean") {
2960
+ sum += val ? 1 : 0;
2961
+ }
2962
+ }
2963
+ return sum;
2964
+ }
2965
+ });
2966
+ registry.set("AVERAGE", {
2967
+ minArgs: 1,
2968
+ maxArgs: -1,
2969
+ evaluate(args, context, evaluator) {
2970
+ const values = flattenArgs(args, context, evaluator);
2971
+ let sum = 0;
2972
+ let count = 0;
2973
+ for (const val of values) {
2974
+ if (val instanceof FormulaError) return val;
2975
+ if (typeof val === "number") {
2976
+ sum += val;
2977
+ count++;
2978
+ } else if (typeof val === "boolean") {
2979
+ sum += val ? 1 : 0;
2980
+ count++;
2981
+ }
2982
+ }
2983
+ if (count === 0) return new FormulaError("#DIV/0!", "No numeric values for AVERAGE");
2984
+ return sum / count;
2985
+ }
2986
+ });
2987
+ registry.set("MIN", {
2988
+ minArgs: 1,
2989
+ maxArgs: -1,
2990
+ evaluate(args, context, evaluator) {
2991
+ const values = flattenArgs(args, context, evaluator);
2992
+ let min = Infinity;
2993
+ for (const val of values) {
2994
+ if (val instanceof FormulaError) return val;
2995
+ if (typeof val === "number") {
2996
+ if (val < min) min = val;
2997
+ } else if (typeof val === "boolean") {
2998
+ const n = val ? 1 : 0;
2999
+ if (n < min) min = n;
3000
+ }
3001
+ }
3002
+ return min === Infinity ? 0 : min;
3003
+ }
3004
+ });
3005
+ registry.set("MAX", {
3006
+ minArgs: 1,
3007
+ maxArgs: -1,
3008
+ evaluate(args, context, evaluator) {
3009
+ const values = flattenArgs(args, context, evaluator);
3010
+ let max = -Infinity;
3011
+ for (const val of values) {
3012
+ if (val instanceof FormulaError) return val;
3013
+ if (typeof val === "number") {
3014
+ if (val > max) max = val;
3015
+ } else if (typeof val === "boolean") {
3016
+ const n = val ? 1 : 0;
3017
+ if (n > max) max = n;
3018
+ }
3019
+ }
3020
+ return max === -Infinity ? 0 : max;
3021
+ }
3022
+ });
3023
+ registry.set("COUNT", {
3024
+ minArgs: 1,
3025
+ maxArgs: -1,
3026
+ evaluate(args, context, evaluator) {
3027
+ const values = flattenArgs(args, context, evaluator);
3028
+ let count = 0;
3029
+ for (const val of values) {
3030
+ if (val instanceof FormulaError) return val;
3031
+ if (typeof val === "number") {
3032
+ count++;
3033
+ }
3034
+ }
3035
+ return count;
3036
+ }
3037
+ });
3038
+ registry.set("COUNTA", {
3039
+ minArgs: 1,
3040
+ maxArgs: -1,
3041
+ evaluate(args, context, evaluator) {
3042
+ const values = flattenArgs(args, context, evaluator);
3043
+ let count = 0;
3044
+ for (const val of values) {
3045
+ if (val instanceof FormulaError) return val;
3046
+ if (val !== null && val !== void 0 && val !== "") {
3047
+ count++;
3048
+ }
3049
+ }
3050
+ return count;
3051
+ }
3052
+ });
3053
+ registry.set("ROUND", {
3054
+ minArgs: 2,
3055
+ maxArgs: 2,
3056
+ evaluate(args, context, evaluator) {
3057
+ const rawNum = evaluator.evaluate(args[0], context);
3058
+ if (rawNum instanceof FormulaError) return rawNum;
3059
+ const num = toNumber(rawNum);
3060
+ if (num instanceof FormulaError) return num;
3061
+ const rawDigits = evaluator.evaluate(args[1], context);
3062
+ if (rawDigits instanceof FormulaError) return rawDigits;
3063
+ const digits = toNumber(rawDigits);
3064
+ if (digits instanceof FormulaError) return digits;
3065
+ const factor = Math.pow(10, Math.trunc(digits));
3066
+ return Math.round(num * factor) / factor;
3067
+ }
3068
+ });
3069
+ registry.set("ABS", {
3070
+ minArgs: 1,
3071
+ maxArgs: 1,
3072
+ evaluate(args, context, evaluator) {
3073
+ const rawVal = evaluator.evaluate(args[0], context);
3074
+ if (rawVal instanceof FormulaError) return rawVal;
3075
+ const num = toNumber(rawVal);
3076
+ if (num instanceof FormulaError) return num;
3077
+ return Math.abs(num);
3078
+ }
3079
+ });
3080
+ registry.set("CEILING", {
3081
+ minArgs: 2,
3082
+ maxArgs: 2,
3083
+ evaluate(args, context, evaluator) {
3084
+ const rawNum = evaluator.evaluate(args[0], context);
3085
+ if (rawNum instanceof FormulaError) return rawNum;
3086
+ const num = toNumber(rawNum);
3087
+ if (num instanceof FormulaError) return num;
3088
+ const rawSig = evaluator.evaluate(args[1], context);
3089
+ if (rawSig instanceof FormulaError) return rawSig;
3090
+ const significance = toNumber(rawSig);
3091
+ if (significance instanceof FormulaError) return significance;
3092
+ if (significance === 0) return 0;
3093
+ return Math.ceil(num / significance) * significance;
3094
+ }
3095
+ });
3096
+ registry.set("FLOOR", {
3097
+ minArgs: 2,
3098
+ maxArgs: 2,
3099
+ evaluate(args, context, evaluator) {
3100
+ const rawNum = evaluator.evaluate(args[0], context);
3101
+ if (rawNum instanceof FormulaError) return rawNum;
3102
+ const num = toNumber(rawNum);
3103
+ if (num instanceof FormulaError) return num;
3104
+ const rawSig = evaluator.evaluate(args[1], context);
3105
+ if (rawSig instanceof FormulaError) return rawSig;
3106
+ const significance = toNumber(rawSig);
3107
+ if (significance instanceof FormulaError) return significance;
3108
+ if (significance === 0) return 0;
3109
+ return Math.floor(num / significance) * significance;
3110
+ }
3111
+ });
3112
+ registry.set("MOD", {
3113
+ minArgs: 2,
3114
+ maxArgs: 2,
3115
+ evaluate(args, context, evaluator) {
3116
+ const rawNum = evaluator.evaluate(args[0], context);
3117
+ if (rawNum instanceof FormulaError) return rawNum;
3118
+ const num = toNumber(rawNum);
3119
+ if (num instanceof FormulaError) return num;
3120
+ const rawDiv = evaluator.evaluate(args[1], context);
3121
+ if (rawDiv instanceof FormulaError) return rawDiv;
3122
+ const divisor = toNumber(rawDiv);
3123
+ if (divisor instanceof FormulaError) return divisor;
3124
+ if (divisor === 0) return new FormulaError("#DIV/0!", "Division by zero in MOD");
3125
+ return num % divisor;
3126
+ }
3127
+ });
3128
+ registry.set("POWER", {
3129
+ minArgs: 2,
3130
+ maxArgs: 2,
3131
+ evaluate(args, context, evaluator) {
3132
+ const rawBase = evaluator.evaluate(args[0], context);
3133
+ if (rawBase instanceof FormulaError) return rawBase;
3134
+ const base = toNumber(rawBase);
3135
+ if (base instanceof FormulaError) return base;
3136
+ const rawExp = evaluator.evaluate(args[1], context);
3137
+ if (rawExp instanceof FormulaError) return rawExp;
3138
+ const exponent = toNumber(rawExp);
3139
+ if (exponent instanceof FormulaError) return exponent;
3140
+ return Math.pow(base, exponent);
3141
+ }
3142
+ });
3143
+ registry.set("SQRT", {
3144
+ minArgs: 1,
3145
+ maxArgs: 1,
3146
+ evaluate(args, context, evaluator) {
3147
+ const rawVal = evaluator.evaluate(args[0], context);
3148
+ if (rawVal instanceof FormulaError) return rawVal;
3149
+ const num = toNumber(rawVal);
3150
+ if (num instanceof FormulaError) return num;
3151
+ if (num < 0) return new FormulaError("#VALUE!", "Cannot take square root of negative number");
3152
+ return Math.sqrt(num);
3153
+ }
3154
+ });
3155
+ registry.set("ROUNDUP", {
3156
+ minArgs: 2,
3157
+ maxArgs: 2,
3158
+ evaluate(args, context, evaluator) {
3159
+ const rawNum = evaluator.evaluate(args[0], context);
3160
+ if (rawNum instanceof FormulaError) return rawNum;
3161
+ const num = toNumber(rawNum);
3162
+ if (num instanceof FormulaError) return num;
3163
+ const rawDigits = evaluator.evaluate(args[1], context);
3164
+ if (rawDigits instanceof FormulaError) return rawDigits;
3165
+ const digits = toNumber(rawDigits);
3166
+ if (digits instanceof FormulaError) return digits;
3167
+ const factor = Math.pow(10, Math.trunc(digits));
3168
+ return num >= 0 ? Math.ceil(num * factor) / factor : Math.floor(num * factor) / factor;
3169
+ }
3170
+ });
3171
+ registry.set("ROUNDDOWN", {
3172
+ minArgs: 2,
3173
+ maxArgs: 2,
3174
+ evaluate(args, context, evaluator) {
3175
+ const rawNum = evaluator.evaluate(args[0], context);
3176
+ if (rawNum instanceof FormulaError) return rawNum;
3177
+ const num = toNumber(rawNum);
3178
+ if (num instanceof FormulaError) return num;
3179
+ const rawDigits = evaluator.evaluate(args[1], context);
3180
+ if (rawDigits instanceof FormulaError) return rawDigits;
3181
+ const digits = toNumber(rawDigits);
3182
+ if (digits instanceof FormulaError) return digits;
3183
+ const factor = Math.pow(10, Math.trunc(digits));
3184
+ return Math.trunc(num * factor) / factor;
3185
+ }
3186
+ });
3187
+ registry.set("INT", {
3188
+ minArgs: 1,
3189
+ maxArgs: 1,
3190
+ evaluate(args, context, evaluator) {
3191
+ const rawVal = evaluator.evaluate(args[0], context);
3192
+ if (rawVal instanceof FormulaError) return rawVal;
3193
+ const num = toNumber(rawVal);
3194
+ if (num instanceof FormulaError) return num;
3195
+ return Math.floor(num);
3196
+ }
3197
+ });
3198
+ registry.set("TRUNC", {
3199
+ minArgs: 1,
3200
+ maxArgs: 2,
3201
+ evaluate(args, context, evaluator) {
3202
+ const rawVal = evaluator.evaluate(args[0], context);
3203
+ if (rawVal instanceof FormulaError) return rawVal;
3204
+ const num = toNumber(rawVal);
3205
+ if (num instanceof FormulaError) return num;
3206
+ let digits = 0;
3207
+ if (args.length >= 2) {
3208
+ const rawD = evaluator.evaluate(args[1], context);
3209
+ if (rawD instanceof FormulaError) return rawD;
3210
+ const d = toNumber(rawD);
3211
+ if (d instanceof FormulaError) return d;
3212
+ digits = Math.trunc(d);
3213
+ }
3214
+ const factor = Math.pow(10, digits);
3215
+ return Math.trunc(num * factor) / factor;
3216
+ }
3217
+ });
3218
+ registry.set("PRODUCT", {
3219
+ minArgs: 1,
3220
+ maxArgs: -1,
3221
+ evaluate(args, context, evaluator) {
3222
+ const values = flattenArgs(args, context, evaluator);
3223
+ let product = 1;
3224
+ let hasNumber = false;
3225
+ for (const val of values) {
3226
+ if (val instanceof FormulaError) return val;
3227
+ if (typeof val === "number") {
3228
+ product *= val;
3229
+ hasNumber = true;
3230
+ }
3231
+ }
3232
+ return hasNumber ? product : 0;
3233
+ }
3234
+ });
3235
+ registry.set("SUMPRODUCT", {
3236
+ minArgs: 1,
3237
+ maxArgs: -1,
3238
+ evaluate(args, context, evaluator) {
3239
+ const arrays = [];
3240
+ for (const arg of args) {
3241
+ if (arg.kind !== "range") {
3242
+ return new FormulaError("#VALUE!", "SUMPRODUCT arguments must be ranges");
3243
+ }
3244
+ arrays.push(context.getRangeValues({ start: arg.start, end: arg.end }));
3245
+ }
3246
+ if (arrays.length === 0) return 0;
3247
+ const rows = arrays[0].length;
3248
+ const cols = rows > 0 ? arrays[0][0].length : 0;
3249
+ for (let a = 1; a < arrays.length; a++) {
3250
+ if (arrays[a].length !== rows || rows > 0 && arrays[a][0].length !== cols) {
3251
+ return new FormulaError("#VALUE!", "SUMPRODUCT arrays must have same dimensions");
3252
+ }
3253
+ }
3254
+ let sum = 0;
3255
+ for (let r = 0; r < rows; r++) {
3256
+ for (let c = 0; c < cols; c++) {
3257
+ let product = 1;
3258
+ for (let a = 0; a < arrays.length; a++) {
3259
+ const v = toNumber(arrays[a][r][c]);
3260
+ if (v instanceof FormulaError) {
3261
+ product = 0;
3262
+ break;
3263
+ }
3264
+ product *= v;
3265
+ }
3266
+ sum += product;
3267
+ }
3268
+ }
3269
+ return sum;
3270
+ }
3271
+ });
3272
+ registry.set("MEDIAN", {
3273
+ minArgs: 1,
3274
+ maxArgs: -1,
3275
+ evaluate(args, context, evaluator) {
3276
+ const values = flattenArgs(args, context, evaluator);
3277
+ const nums = [];
3278
+ for (const val of values) {
3279
+ if (val instanceof FormulaError) return val;
3280
+ if (typeof val === "number") nums.push(val);
3281
+ }
3282
+ if (nums.length === 0) return new FormulaError("#NUM!", "No numeric values for MEDIAN");
3283
+ nums.sort((a, b) => a - b);
3284
+ const mid = Math.floor(nums.length / 2);
3285
+ return nums.length % 2 !== 0 ? nums[mid] : (nums[mid - 1] + nums[mid]) / 2;
3286
+ }
3287
+ });
3288
+ registry.set("LARGE", {
3289
+ minArgs: 2,
3290
+ maxArgs: 2,
3291
+ evaluate(args, context, evaluator) {
3292
+ if (args[0].kind !== "range") {
3293
+ return new FormulaError("#VALUE!", "LARGE first argument must be a range");
3294
+ }
3295
+ const rangeData = context.getRangeValues({ start: args[0].start, end: args[0].end });
3296
+ const rawK = evaluator.evaluate(args[1], context);
3297
+ if (rawK instanceof FormulaError) return rawK;
3298
+ const k = toNumber(rawK);
3299
+ if (k instanceof FormulaError) return k;
3300
+ const nums = [];
3301
+ for (const row of rangeData) {
3302
+ for (const cell of row) {
3303
+ if (typeof cell === "number") nums.push(cell);
3304
+ }
3305
+ }
3306
+ const ki = Math.trunc(k);
3307
+ if (ki < 1 || ki > nums.length) return new FormulaError("#NUM!", "LARGE k out of range");
3308
+ nums.sort((a, b) => b - a);
3309
+ return nums[ki - 1];
3310
+ }
3311
+ });
3312
+ registry.set("SMALL", {
3313
+ minArgs: 2,
3314
+ maxArgs: 2,
3315
+ evaluate(args, context, evaluator) {
3316
+ if (args[0].kind !== "range") {
3317
+ return new FormulaError("#VALUE!", "SMALL first argument must be a range");
3318
+ }
3319
+ const rangeData = context.getRangeValues({ start: args[0].start, end: args[0].end });
3320
+ const rawK = evaluator.evaluate(args[1], context);
3321
+ if (rawK instanceof FormulaError) return rawK;
3322
+ const k = toNumber(rawK);
3323
+ if (k instanceof FormulaError) return k;
3324
+ const nums = [];
3325
+ for (const row of rangeData) {
3326
+ for (const cell of row) {
3327
+ if (typeof cell === "number") nums.push(cell);
3328
+ }
3329
+ }
3330
+ const ki = Math.trunc(k);
3331
+ if (ki < 1 || ki > nums.length) return new FormulaError("#NUM!", "SMALL k out of range");
3332
+ nums.sort((a, b) => a - b);
3333
+ return nums[ki - 1];
3334
+ }
3335
+ });
3336
+ registry.set("RANK", {
3337
+ minArgs: 2,
3338
+ maxArgs: 3,
3339
+ evaluate(args, context, evaluator) {
3340
+ const rawNum = evaluator.evaluate(args[0], context);
3341
+ if (rawNum instanceof FormulaError) return rawNum;
3342
+ const num = toNumber(rawNum);
3343
+ if (num instanceof FormulaError) return num;
3344
+ if (args[1].kind !== "range") {
3345
+ return new FormulaError("#VALUE!", "RANK second argument must be a range");
3346
+ }
3347
+ const rangeData = context.getRangeValues({ start: args[1].start, end: args[1].end });
3348
+ let order = 0;
3349
+ if (args.length >= 3) {
3350
+ const rawO = evaluator.evaluate(args[2], context);
3351
+ if (rawO instanceof FormulaError) return rawO;
3352
+ const o = toNumber(rawO);
3353
+ if (o instanceof FormulaError) return o;
3354
+ order = o;
3355
+ }
3356
+ const nums = [];
3357
+ for (const row of rangeData) {
3358
+ for (const cell of row) {
3359
+ if (typeof cell === "number") nums.push(cell);
3360
+ }
3361
+ }
3362
+ if (!nums.includes(num)) return new FormulaError("#N/A", "RANK value not found in range");
3363
+ let rank = 1;
3364
+ for (const n of nums) {
3365
+ if (order === 0 ? n > num : n < num) rank++;
3366
+ }
3367
+ return rank;
3368
+ }
3369
+ });
3370
+ registry.set("SIGN", {
3371
+ minArgs: 1,
3372
+ maxArgs: 1,
3373
+ evaluate(args, context, evaluator) {
3374
+ const rawVal = evaluator.evaluate(args[0], context);
3375
+ if (rawVal instanceof FormulaError) return rawVal;
3376
+ const num = toNumber(rawVal);
3377
+ if (num instanceof FormulaError) return num;
3378
+ return num > 0 ? 1 : num < 0 ? -1 : 0;
3379
+ }
3380
+ });
3381
+ registry.set("LOG", {
3382
+ minArgs: 1,
3383
+ maxArgs: 2,
3384
+ evaluate(args, context, evaluator) {
3385
+ const rawVal = evaluator.evaluate(args[0], context);
3386
+ if (rawVal instanceof FormulaError) return rawVal;
3387
+ const num = toNumber(rawVal);
3388
+ if (num instanceof FormulaError) return num;
3389
+ if (num <= 0) return new FormulaError("#NUM!", "LOG requires a positive number");
3390
+ let base = 10;
3391
+ if (args.length >= 2) {
3392
+ const rawB = evaluator.evaluate(args[1], context);
3393
+ if (rawB instanceof FormulaError) return rawB;
3394
+ const b = toNumber(rawB);
3395
+ if (b instanceof FormulaError) return b;
3396
+ if (b <= 0 || b === 1) return new FormulaError("#NUM!", "LOG base must be positive and not 1");
3397
+ base = b;
3398
+ }
3399
+ return Math.log(num) / Math.log(base);
3400
+ }
3401
+ });
3402
+ registry.set("LN", {
3403
+ minArgs: 1,
3404
+ maxArgs: 1,
3405
+ evaluate(args, context, evaluator) {
3406
+ const rawVal = evaluator.evaluate(args[0], context);
3407
+ if (rawVal instanceof FormulaError) return rawVal;
3408
+ const num = toNumber(rawVal);
3409
+ if (num instanceof FormulaError) return num;
3410
+ if (num <= 0) return new FormulaError("#NUM!", "LN requires a positive number");
3411
+ return Math.log(num);
3412
+ }
3413
+ });
3414
+ registry.set("EXP", {
3415
+ minArgs: 1,
3416
+ maxArgs: 1,
3417
+ evaluate(args, context, evaluator) {
3418
+ const rawVal = evaluator.evaluate(args[0], context);
3419
+ if (rawVal instanceof FormulaError) return rawVal;
3420
+ const num = toNumber(rawVal);
3421
+ if (num instanceof FormulaError) return num;
3422
+ return Math.exp(num);
3423
+ }
3424
+ });
3425
+ registry.set("PI", {
3426
+ minArgs: 0,
3427
+ maxArgs: 0,
3428
+ evaluate() {
3429
+ return Math.PI;
3430
+ }
3431
+ });
3432
+ registry.set("RAND", {
3433
+ minArgs: 0,
3434
+ maxArgs: 0,
3435
+ evaluate() {
3436
+ return Math.random();
3437
+ }
3438
+ });
3439
+ registry.set("RANDBETWEEN", {
3440
+ minArgs: 2,
3441
+ maxArgs: 2,
3442
+ evaluate(args, context, evaluator) {
3443
+ const rawLow = evaluator.evaluate(args[0], context);
3444
+ if (rawLow instanceof FormulaError) return rawLow;
3445
+ const low = toNumber(rawLow);
3446
+ if (low instanceof FormulaError) return low;
3447
+ const rawHigh = evaluator.evaluate(args[1], context);
3448
+ if (rawHigh instanceof FormulaError) return rawHigh;
3449
+ const high = toNumber(rawHigh);
3450
+ if (high instanceof FormulaError) return high;
3451
+ const lo = Math.ceil(low);
3452
+ const hi = Math.floor(high);
3453
+ if (lo > hi) return new FormulaError("#NUM!", "RANDBETWEEN bottom must be <= top");
3454
+ return Math.floor(Math.random() * (hi - lo + 1)) + lo;
3455
+ }
3456
+ });
3457
+ }
3458
+
3459
+ // src/formula/functions/logical.ts
3460
+ function flattenArgs2(args, context, evaluator) {
3461
+ const result = [];
3462
+ for (const arg of args) {
3463
+ if (arg.kind === "range") {
3464
+ const values = context.getRangeValues({ start: arg.start, end: arg.end });
3465
+ for (const row of values) {
3466
+ for (const cell of row) {
3467
+ result.push(cell);
3468
+ }
3469
+ }
3470
+ } else {
3471
+ result.push(evaluator.evaluate(arg, context));
3472
+ }
3473
+ }
3474
+ return result;
3475
+ }
3476
+ function registerLogicalFunctions(registry) {
3477
+ registry.set("IF", {
3478
+ minArgs: 2,
3479
+ maxArgs: 3,
3480
+ evaluate(args, context, evaluator) {
3481
+ const condition = evaluator.evaluate(args[0], context);
3482
+ if (condition instanceof FormulaError) return condition;
3483
+ if (condition) {
3484
+ return evaluator.evaluate(args[1], context);
3485
+ } else {
3486
+ if (args.length >= 3) {
3487
+ return evaluator.evaluate(args[2], context);
3488
+ }
3489
+ return false;
3490
+ }
3491
+ }
3492
+ });
3493
+ registry.set("AND", {
3494
+ minArgs: 1,
3495
+ maxArgs: -1,
3496
+ evaluate(args, context, evaluator) {
3497
+ const values = flattenArgs2(args, context, evaluator);
3498
+ for (const val of values) {
3499
+ if (val instanceof FormulaError) return val;
3500
+ if (!val) return false;
3501
+ }
3502
+ return true;
3503
+ }
3504
+ });
3505
+ registry.set("OR", {
3506
+ minArgs: 1,
3507
+ maxArgs: -1,
3508
+ evaluate(args, context, evaluator) {
3509
+ const values = flattenArgs2(args, context, evaluator);
3510
+ for (const val of values) {
3511
+ if (val instanceof FormulaError) return val;
3512
+ if (val) return true;
3513
+ }
3514
+ return false;
3515
+ }
3516
+ });
3517
+ registry.set("NOT", {
3518
+ minArgs: 1,
3519
+ maxArgs: 1,
3520
+ evaluate(args, context, evaluator) {
3521
+ const val = evaluator.evaluate(args[0], context);
3522
+ if (val instanceof FormulaError) return val;
3523
+ return !val;
3524
+ }
3525
+ });
3526
+ registry.set("IFERROR", {
3527
+ minArgs: 2,
3528
+ maxArgs: 2,
3529
+ evaluate(args, context, evaluator) {
3530
+ const val = evaluator.evaluate(args[0], context);
3531
+ if (val instanceof FormulaError) {
3532
+ return evaluator.evaluate(args[1], context);
3533
+ }
3534
+ return val;
3535
+ }
3536
+ });
3537
+ registry.set("IFNA", {
3538
+ minArgs: 2,
3539
+ maxArgs: 2,
3540
+ evaluate(args, context, evaluator) {
3541
+ const val = evaluator.evaluate(args[0], context);
3542
+ if (val instanceof FormulaError && val.type === "#N/A") {
3543
+ return evaluator.evaluate(args[1], context);
3544
+ }
3545
+ return val;
3546
+ }
3547
+ });
3548
+ registry.set("IFS", {
3549
+ minArgs: 2,
3550
+ maxArgs: -1,
3551
+ evaluate(args, context, evaluator) {
3552
+ if (args.length % 2 !== 0) {
3553
+ return new FormulaError("#VALUE!", "IFS requires pairs of condition, value");
3554
+ }
3555
+ for (let i = 0; i < args.length; i += 2) {
3556
+ const condition = evaluator.evaluate(args[i], context);
3557
+ if (condition instanceof FormulaError) return condition;
3558
+ if (condition) {
3559
+ return evaluator.evaluate(args[i + 1], context);
3560
+ }
3561
+ }
3562
+ return new FormulaError("#N/A", "IFS no condition was TRUE");
3563
+ }
3564
+ });
3565
+ registry.set("SWITCH", {
3566
+ minArgs: 3,
3567
+ maxArgs: -1,
3568
+ evaluate(args, context, evaluator) {
3569
+ const expr = evaluator.evaluate(args[0], context);
3570
+ if (expr instanceof FormulaError) return expr;
3571
+ const hasDefault = (args.length - 1) % 2 !== 0;
3572
+ const pairCount = hasDefault ? (args.length - 2) / 2 : (args.length - 1) / 2;
3573
+ for (let i = 0; i < pairCount; i++) {
3574
+ const caseVal = evaluator.evaluate(args[1 + i * 2], context);
3575
+ if (caseVal instanceof FormulaError) return caseVal;
3576
+ if (expr === caseVal) {
3577
+ return evaluator.evaluate(args[2 + i * 2], context);
3578
+ }
3579
+ }
3580
+ if (hasDefault) {
3581
+ return evaluator.evaluate(args[args.length - 1], context);
3582
+ }
3583
+ return new FormulaError("#N/A", "SWITCH no match found");
3584
+ }
3585
+ });
3586
+ registry.set("CHOOSE", {
3587
+ minArgs: 2,
3588
+ maxArgs: -1,
3589
+ evaluate(args, context, evaluator) {
3590
+ const rawIdx = evaluator.evaluate(args[0], context);
3591
+ if (rawIdx instanceof FormulaError) return rawIdx;
3592
+ if (typeof rawIdx !== "number") return new FormulaError("#VALUE!", "CHOOSE index must be a number");
3593
+ const idx = Math.trunc(rawIdx);
3594
+ if (idx < 1 || idx >= args.length) {
3595
+ return new FormulaError("#VALUE!", "CHOOSE index out of range");
3596
+ }
3597
+ return evaluator.evaluate(args[idx], context);
3598
+ }
3599
+ });
3600
+ registry.set("XOR", {
3601
+ minArgs: 1,
3602
+ maxArgs: -1,
3603
+ evaluate(args, context, evaluator) {
3604
+ const values = flattenArgs2(args, context, evaluator);
3605
+ let trueCount = 0;
3606
+ for (const val of values) {
3607
+ if (val instanceof FormulaError) return val;
3608
+ if (val) trueCount++;
3609
+ }
3610
+ return trueCount % 2 === 1;
3611
+ }
3612
+ });
3613
+ }
3614
+
3615
+ // src/formula/functions/lookup.ts
3616
+ function registerLookupFunctions(registry) {
3617
+ registry.set("VLOOKUP", {
3618
+ minArgs: 3,
3619
+ maxArgs: 4,
3620
+ evaluate(args, context, evaluator) {
3621
+ const lookupValue = evaluator.evaluate(args[0], context);
3622
+ if (lookupValue instanceof FormulaError) return lookupValue;
3623
+ if (args[1].kind !== "range") {
3624
+ return new FormulaError("#VALUE!", "VLOOKUP table_array must be a range");
3625
+ }
3626
+ const tableData = context.getRangeValues({ start: args[1].start, end: args[1].end });
3627
+ const rawColIndex = evaluator.evaluate(args[2], context);
3628
+ if (rawColIndex instanceof FormulaError) return rawColIndex;
3629
+ const colIndex = toNumber(rawColIndex);
3630
+ if (colIndex instanceof FormulaError) return colIndex;
3631
+ if (colIndex < 1) return new FormulaError("#VALUE!", "VLOOKUP col_index must be >= 1");
3632
+ if (tableData.length > 0 && colIndex > tableData[0].length) {
3633
+ return new FormulaError("#REF!", "VLOOKUP col_index exceeds table columns");
3634
+ }
3635
+ let rangeLookup = true;
3636
+ if (args.length >= 4) {
3637
+ const rawRL = evaluator.evaluate(args[3], context);
3638
+ if (rawRL instanceof FormulaError) return rawRL;
3639
+ rangeLookup = !!rawRL;
3640
+ }
3641
+ const col = Math.trunc(colIndex) - 1;
3642
+ const lookupLower = typeof lookupValue === "string" ? lookupValue.toLowerCase() : null;
3643
+ if (rangeLookup) {
3644
+ let bestRow = -1;
3645
+ for (let r = 0; r < tableData.length; r++) {
3646
+ const cellVal = tableData[r][0];
3647
+ if (cellVal === null || cellVal === void 0) continue;
3648
+ if (typeof lookupValue === "number" && typeof cellVal === "number") {
3649
+ if (cellVal <= lookupValue) bestRow = r;
3650
+ else break;
3651
+ } else if (lookupLower !== null && typeof cellVal === "string") {
3652
+ if (cellVal.toLowerCase() <= lookupLower) bestRow = r;
3653
+ else break;
3654
+ }
3655
+ }
3656
+ if (bestRow === -1) return new FormulaError("#N/A", "VLOOKUP no match found");
3657
+ return tableData[bestRow][col] ?? null;
3658
+ } else {
3659
+ for (let r = 0; r < tableData.length; r++) {
3660
+ const cellVal = tableData[r][0];
3661
+ if (lookupLower !== null && typeof cellVal === "string") {
3662
+ if (cellVal.toLowerCase() === lookupLower) {
3663
+ return tableData[r][col] ?? null;
3664
+ }
3665
+ } else if (cellVal === lookupValue) {
3666
+ return tableData[r][col] ?? null;
3667
+ }
3668
+ }
3669
+ return new FormulaError("#N/A", "VLOOKUP no exact match found");
3670
+ }
3671
+ }
3672
+ });
3673
+ registry.set("INDEX", {
3674
+ minArgs: 2,
3675
+ maxArgs: 3,
3676
+ evaluate(args, context, evaluator) {
3677
+ if (args[0].kind !== "range") {
3678
+ return new FormulaError("#VALUE!", "INDEX first argument must be a range");
3679
+ }
3680
+ const rangeData = context.getRangeValues({ start: args[0].start, end: args[0].end });
3681
+ const rawRow = evaluator.evaluate(args[1], context);
3682
+ if (rawRow instanceof FormulaError) return rawRow;
3683
+ const rowNum = toNumber(rawRow);
3684
+ if (rowNum instanceof FormulaError) return rowNum;
3685
+ let colNum = 1;
3686
+ if (args.length >= 3) {
3687
+ const rawCol = evaluator.evaluate(args[2], context);
3688
+ if (rawCol instanceof FormulaError) return rawCol;
3689
+ const c2 = toNumber(rawCol);
3690
+ if (c2 instanceof FormulaError) return c2;
3691
+ colNum = c2;
3692
+ }
3693
+ const r = Math.trunc(rowNum) - 1;
3694
+ const c = Math.trunc(colNum) - 1;
3695
+ if (r < 0 || r >= rangeData.length) {
3696
+ return new FormulaError("#REF!", "INDEX row out of bounds");
3697
+ }
3698
+ if (c < 0 || rangeData.length > 0 && c >= rangeData[0].length) {
3699
+ return new FormulaError("#REF!", "INDEX column out of bounds");
3700
+ }
3701
+ return rangeData[r][c] ?? null;
3702
+ }
3703
+ });
3704
+ registry.set("HLOOKUP", {
3705
+ minArgs: 3,
3706
+ maxArgs: 4,
3707
+ evaluate(args, context, evaluator) {
3708
+ const lookupValue = evaluator.evaluate(args[0], context);
3709
+ if (lookupValue instanceof FormulaError) return lookupValue;
3710
+ if (args[1].kind !== "range") {
3711
+ return new FormulaError("#VALUE!", "HLOOKUP table_array must be a range");
3712
+ }
3713
+ const tableData = context.getRangeValues({ start: args[1].start, end: args[1].end });
3714
+ const rawRowIndex = evaluator.evaluate(args[2], context);
3715
+ if (rawRowIndex instanceof FormulaError) return rawRowIndex;
3716
+ const rowIndex = toNumber(rawRowIndex);
3717
+ if (rowIndex instanceof FormulaError) return rowIndex;
3718
+ if (rowIndex < 1) return new FormulaError("#VALUE!", "HLOOKUP row_index must be >= 1");
3719
+ if (rowIndex > tableData.length) {
3720
+ return new FormulaError("#REF!", "HLOOKUP row_index exceeds table rows");
3721
+ }
3722
+ let rangeLookup = true;
3723
+ if (args.length >= 4) {
3724
+ const rawRL = evaluator.evaluate(args[3], context);
3725
+ if (rawRL instanceof FormulaError) return rawRL;
3726
+ rangeLookup = !!rawRL;
3727
+ }
3728
+ const row = Math.trunc(rowIndex) - 1;
3729
+ const firstRow = tableData[0] || [];
3730
+ const lookupLower = typeof lookupValue === "string" ? lookupValue.toLowerCase() : null;
3731
+ if (rangeLookup) {
3732
+ let bestCol = -1;
3733
+ for (let c = 0; c < firstRow.length; c++) {
3734
+ const cellVal = firstRow[c];
3735
+ if (cellVal === null || cellVal === void 0) continue;
3736
+ if (typeof lookupValue === "number" && typeof cellVal === "number") {
3737
+ if (cellVal <= lookupValue) bestCol = c;
3738
+ else break;
3739
+ } else if (lookupLower !== null && typeof cellVal === "string") {
3740
+ if (cellVal.toLowerCase() <= lookupLower) bestCol = c;
3741
+ else break;
3742
+ }
3743
+ }
3744
+ if (bestCol === -1) return new FormulaError("#N/A", "HLOOKUP no match found");
3745
+ return tableData[row][bestCol] ?? null;
3746
+ } else {
3747
+ for (let c = 0; c < firstRow.length; c++) {
3748
+ const cellVal = firstRow[c];
3749
+ if (lookupLower !== null && typeof cellVal === "string") {
3750
+ if (cellVal.toLowerCase() === lookupLower) return tableData[row][c] ?? null;
3751
+ } else if (cellVal === lookupValue) {
3752
+ return tableData[row][c] ?? null;
3753
+ }
3754
+ }
3755
+ return new FormulaError("#N/A", "HLOOKUP no exact match found");
3756
+ }
3757
+ }
3758
+ });
3759
+ registry.set("XLOOKUP", {
3760
+ minArgs: 3,
3761
+ maxArgs: 6,
3762
+ evaluate(args, context, evaluator) {
3763
+ const lookupValue = evaluator.evaluate(args[0], context);
3764
+ if (lookupValue instanceof FormulaError) return lookupValue;
3765
+ if (args[1].kind !== "range") {
3766
+ return new FormulaError("#VALUE!", "XLOOKUP lookup_array must be a range");
3767
+ }
3768
+ const lookupArray = context.getRangeValues({ start: args[1].start, end: args[1].end });
3769
+ if (args[2].kind !== "range") {
3770
+ return new FormulaError("#VALUE!", "XLOOKUP return_array must be a range");
3771
+ }
3772
+ const returnArray = context.getRangeValues({ start: args[2].start, end: args[2].end });
3773
+ let ifNotFound = new FormulaError("#N/A", "XLOOKUP no match found");
3774
+ if (args.length >= 4) {
3775
+ ifNotFound = evaluator.evaluate(args[3], context);
3776
+ }
3777
+ let matchMode = 0;
3778
+ if (args.length >= 5) {
3779
+ const rawMM = evaluator.evaluate(args[4], context);
3780
+ if (rawMM instanceof FormulaError) return rawMM;
3781
+ const mm = toNumber(rawMM);
3782
+ if (mm instanceof FormulaError) return mm;
3783
+ matchMode = Math.trunc(mm);
3784
+ }
3785
+ let searchMode = 1;
3786
+ if (args.length >= 6) {
3787
+ const rawSM = evaluator.evaluate(args[5], context);
3788
+ if (rawSM instanceof FormulaError) return rawSM;
3789
+ const sm = toNumber(rawSM);
3790
+ if (sm instanceof FormulaError) return sm;
3791
+ searchMode = Math.trunc(sm);
3792
+ }
3793
+ const isRow = lookupArray.length === 1;
3794
+ const len = isRow ? lookupArray[0].length : lookupArray.length;
3795
+ const getVal = isRow ? (i) => lookupArray[0][i] : (i) => lookupArray[i][0];
3796
+ const lookupLower = typeof lookupValue === "string" ? lookupValue.toLowerCase() : null;
3797
+ const eq = (a, b) => {
3798
+ if (lookupLower !== null && typeof a === "string") return a.toLowerCase() === lookupLower;
3799
+ return a === b;
3800
+ };
3801
+ let foundIdx = -1;
3802
+ if (matchMode === 0) {
3803
+ const start = searchMode >= 0 ? 0 : len - 1;
3804
+ const end = searchMode >= 0 ? len : -1;
3805
+ const step = searchMode >= 0 ? 1 : -1;
3806
+ for (let i = start; i !== end; i += step) {
3807
+ if (eq(getVal(i), lookupValue)) {
3808
+ foundIdx = i;
3809
+ break;
3810
+ }
3811
+ }
3812
+ } else if (matchMode === -1) {
3813
+ let best = -1;
3814
+ for (let i = 0; i < len; i++) {
3815
+ const v = getVal(i);
3816
+ if (eq(v, lookupValue)) {
3817
+ foundIdx = i;
3818
+ break;
3819
+ }
3820
+ if (typeof lookupValue === "number" && typeof v === "number" && v < lookupValue) {
3821
+ if (best === -1 || v > getVal(best)) best = i;
3822
+ }
3823
+ }
3824
+ if (foundIdx === -1) foundIdx = best;
3825
+ } else if (matchMode === 1) {
3826
+ let best = -1;
3827
+ for (let i = 0; i < len; i++) {
3828
+ const v = getVal(i);
3829
+ if (eq(v, lookupValue)) {
3830
+ foundIdx = i;
3831
+ break;
3832
+ }
3833
+ if (typeof lookupValue === "number" && typeof v === "number" && v > lookupValue) {
3834
+ if (best === -1 || v < getVal(best)) best = i;
3835
+ }
3836
+ }
3837
+ if (foundIdx === -1) foundIdx = best;
3838
+ }
3839
+ if (foundIdx === -1) return ifNotFound;
3840
+ const isReturnRow = returnArray.length === 1;
3841
+ if (isReturnRow) return returnArray[0][foundIdx] ?? null;
3842
+ return returnArray[foundIdx]?.[0] ?? null;
3843
+ }
3844
+ });
3845
+ registry.set("MATCH", {
3846
+ minArgs: 2,
3847
+ maxArgs: 3,
3848
+ evaluate(args, context, evaluator) {
3849
+ const lookupValue = evaluator.evaluate(args[0], context);
3850
+ if (lookupValue instanceof FormulaError) return lookupValue;
3851
+ if (args[1].kind !== "range") {
3852
+ return new FormulaError("#VALUE!", "MATCH lookup_array must be a range");
3853
+ }
3854
+ const rangeData = context.getRangeValues({ start: args[1].start, end: args[1].end });
3855
+ const isSingleRow = rangeData.length === 1;
3856
+ const values = isSingleRow ? rangeData[0] : rangeData;
3857
+ const getValue = isSingleRow ? (i) => values[i] : (i) => values[i][0];
3858
+ const valuesLength = isSingleRow ? values.length : values.length;
3859
+ let matchType = 1;
3860
+ if (args.length >= 3) {
3861
+ const rawMT = evaluator.evaluate(args[2], context);
3862
+ if (rawMT instanceof FormulaError) return rawMT;
3863
+ const mt = toNumber(rawMT);
3864
+ if (mt instanceof FormulaError) return mt;
3865
+ matchType = mt;
3866
+ }
3867
+ const lookupLower = typeof lookupValue === "string" ? lookupValue.toLowerCase() : null;
3868
+ if (matchType === 0) {
3869
+ for (let i = 0; i < valuesLength; i++) {
3870
+ const cellVal = getValue(i);
3871
+ if (lookupLower !== null && typeof cellVal === "string") {
3872
+ if (cellVal.toLowerCase() === lookupLower) return i + 1;
3873
+ } else if (cellVal === lookupValue) {
3874
+ return i + 1;
3875
+ }
3876
+ }
3877
+ return new FormulaError("#N/A", "MATCH no exact match found");
3878
+ } else if (matchType === 1) {
3879
+ let bestIndex = -1;
3880
+ for (let i = 0; i < valuesLength; i++) {
3881
+ const cellVal = getValue(i);
3882
+ if (cellVal === null || cellVal === void 0) continue;
3883
+ if (typeof lookupValue === "number" && typeof cellVal === "number") {
3884
+ if (cellVal <= lookupValue) bestIndex = i;
3885
+ else break;
3886
+ } else if (lookupLower !== null && typeof cellVal === "string") {
3887
+ if (cellVal.toLowerCase() <= lookupLower) bestIndex = i;
3888
+ else break;
3889
+ }
3890
+ }
3891
+ if (bestIndex === -1) return new FormulaError("#N/A", "MATCH no match found");
3892
+ return bestIndex + 1;
3893
+ } else {
3894
+ let bestIndex = -1;
3895
+ for (let i = 0; i < valuesLength; i++) {
3896
+ const cellVal = getValue(i);
3897
+ if (cellVal === null || cellVal === void 0) continue;
3898
+ if (typeof lookupValue === "number" && typeof cellVal === "number") {
3899
+ if (cellVal >= lookupValue) bestIndex = i;
3900
+ else break;
3901
+ } else if (lookupLower !== null && typeof cellVal === "string") {
3902
+ if (cellVal.toLowerCase() >= lookupLower) bestIndex = i;
3903
+ else break;
3904
+ }
3905
+ }
3906
+ if (bestIndex === -1) return new FormulaError("#N/A", "MATCH no match found");
3907
+ return bestIndex + 1;
3908
+ }
3909
+ }
3910
+ });
3911
+ }
3912
+
3913
+ // src/formula/functions/text.ts
3914
+ function registerTextFunctions(registry) {
3915
+ registry.set("CONCATENATE", {
3916
+ minArgs: 1,
3917
+ maxArgs: -1,
3918
+ evaluate(args, context, evaluator) {
3919
+ const values = flattenArgs(args, context, evaluator);
3920
+ const parts = [];
3921
+ for (const val of values) {
3922
+ if (val instanceof FormulaError) return val;
3923
+ parts.push(toString(val));
3924
+ }
3925
+ return parts.join("");
3926
+ }
3927
+ });
3928
+ registry.set("CONCAT", {
3929
+ minArgs: 1,
3930
+ maxArgs: -1,
3931
+ evaluate(args, context, evaluator) {
3932
+ const values = flattenArgs(args, context, evaluator);
3933
+ const parts = [];
3934
+ for (const val of values) {
3935
+ if (val instanceof FormulaError) return val;
3936
+ parts.push(toString(val));
3937
+ }
3938
+ return parts.join("");
3939
+ }
3940
+ });
3941
+ registry.set("UPPER", {
3942
+ minArgs: 1,
3943
+ maxArgs: 1,
3944
+ evaluate(args, context, evaluator) {
3945
+ const val = evaluator.evaluate(args[0], context);
3946
+ if (val instanceof FormulaError) return val;
3947
+ return toString(val).toUpperCase();
3948
+ }
3949
+ });
3950
+ registry.set("LOWER", {
3951
+ minArgs: 1,
3952
+ maxArgs: 1,
3953
+ evaluate(args, context, evaluator) {
3954
+ const val = evaluator.evaluate(args[0], context);
3955
+ if (val instanceof FormulaError) return val;
3956
+ return toString(val).toLowerCase();
3957
+ }
3958
+ });
3959
+ registry.set("TRIM", {
3960
+ minArgs: 1,
3961
+ maxArgs: 1,
3962
+ evaluate(args, context, evaluator) {
3963
+ const val = evaluator.evaluate(args[0], context);
3964
+ if (val instanceof FormulaError) return val;
3965
+ return toString(val).trim();
3966
+ }
3967
+ });
3968
+ registry.set("LEFT", {
3969
+ minArgs: 1,
3970
+ maxArgs: 2,
3971
+ evaluate(args, context, evaluator) {
3972
+ const val = evaluator.evaluate(args[0], context);
3973
+ if (val instanceof FormulaError) return val;
3974
+ const text = toString(val);
3975
+ let numChars = 1;
3976
+ if (args.length >= 2) {
3977
+ const rawNum = evaluator.evaluate(args[1], context);
3978
+ if (rawNum instanceof FormulaError) return rawNum;
3979
+ const n = toNumber(rawNum);
3980
+ if (n instanceof FormulaError) return n;
3981
+ numChars = Math.trunc(n);
3982
+ }
3983
+ if (numChars < 0) return new FormulaError("#VALUE!", "LEFT num_chars must be >= 0");
3984
+ return text.substring(0, numChars);
3985
+ }
3986
+ });
3987
+ registry.set("RIGHT", {
3988
+ minArgs: 1,
3989
+ maxArgs: 2,
3990
+ evaluate(args, context, evaluator) {
3991
+ const val = evaluator.evaluate(args[0], context);
3992
+ if (val instanceof FormulaError) return val;
3993
+ const text = toString(val);
3994
+ let numChars = 1;
3995
+ if (args.length >= 2) {
3996
+ const rawNum = evaluator.evaluate(args[1], context);
3997
+ if (rawNum instanceof FormulaError) return rawNum;
3998
+ const n = toNumber(rawNum);
3999
+ if (n instanceof FormulaError) return n;
4000
+ numChars = Math.trunc(n);
4001
+ }
4002
+ if (numChars < 0) return new FormulaError("#VALUE!", "RIGHT num_chars must be >= 0");
4003
+ return text.substring(Math.max(0, text.length - numChars));
4004
+ }
4005
+ });
4006
+ registry.set("MID", {
4007
+ minArgs: 3,
4008
+ maxArgs: 3,
4009
+ evaluate(args, context, evaluator) {
4010
+ const val = evaluator.evaluate(args[0], context);
4011
+ if (val instanceof FormulaError) return val;
4012
+ const text = toString(val);
4013
+ const rawStart = evaluator.evaluate(args[1], context);
4014
+ if (rawStart instanceof FormulaError) return rawStart;
4015
+ const startPos = toNumber(rawStart);
4016
+ if (startPos instanceof FormulaError) return startPos;
4017
+ const rawNum = evaluator.evaluate(args[2], context);
4018
+ if (rawNum instanceof FormulaError) return rawNum;
4019
+ const numChars = toNumber(rawNum);
4020
+ if (numChars instanceof FormulaError) return numChars;
4021
+ const start = Math.trunc(startPos);
4022
+ const count = Math.trunc(numChars);
4023
+ if (start < 1) return new FormulaError("#VALUE!", "MID start_num must be >= 1");
4024
+ if (count < 0) return new FormulaError("#VALUE!", "MID num_chars must be >= 0");
4025
+ return text.substring(start - 1, start - 1 + count);
4026
+ }
4027
+ });
4028
+ registry.set("LEN", {
4029
+ minArgs: 1,
4030
+ maxArgs: 1,
4031
+ evaluate(args, context, evaluator) {
4032
+ const val = evaluator.evaluate(args[0], context);
4033
+ if (val instanceof FormulaError) return val;
4034
+ return toString(val).length;
4035
+ }
4036
+ });
4037
+ registry.set("SUBSTITUTE", {
4038
+ minArgs: 3,
4039
+ maxArgs: 4,
4040
+ evaluate(args, context, evaluator) {
4041
+ const val = evaluator.evaluate(args[0], context);
4042
+ if (val instanceof FormulaError) return val;
4043
+ const text = toString(val);
4044
+ const rawOld = evaluator.evaluate(args[1], context);
4045
+ if (rawOld instanceof FormulaError) return rawOld;
4046
+ const oldText = toString(rawOld);
4047
+ const rawNew = evaluator.evaluate(args[2], context);
4048
+ if (rawNew instanceof FormulaError) return rawNew;
4049
+ const newText = toString(rawNew);
4050
+ if (args.length >= 4) {
4051
+ const rawInstance = evaluator.evaluate(args[3], context);
4052
+ if (rawInstance instanceof FormulaError) return rawInstance;
4053
+ const instanceNum = toNumber(rawInstance);
4054
+ if (instanceNum instanceof FormulaError) return instanceNum;
4055
+ const n = Math.trunc(instanceNum);
4056
+ if (n < 1) return new FormulaError("#VALUE!", "SUBSTITUTE instance_num must be >= 1");
4057
+ let count = 0;
4058
+ let result = "";
4059
+ let searchFrom = 0;
4060
+ while (searchFrom <= text.length) {
4061
+ const idx = text.indexOf(oldText, searchFrom);
4062
+ if (idx === -1) {
4063
+ result += text.substring(searchFrom);
4064
+ break;
4065
+ }
4066
+ count++;
4067
+ if (count === n) {
4068
+ result += text.substring(searchFrom, idx) + newText;
4069
+ result += text.substring(idx + oldText.length);
4070
+ break;
4071
+ } else {
4072
+ result += text.substring(searchFrom, idx + oldText.length);
4073
+ searchFrom = idx + oldText.length;
4074
+ }
4075
+ }
4076
+ return result;
4077
+ } else {
4078
+ if (oldText === "") return text;
4079
+ return text.split(oldText).join(newText);
4080
+ }
4081
+ }
4082
+ });
4083
+ registry.set("FIND", {
4084
+ minArgs: 2,
4085
+ maxArgs: 3,
4086
+ evaluate(args, context, evaluator) {
4087
+ const rawFind = evaluator.evaluate(args[0], context);
4088
+ if (rawFind instanceof FormulaError) return rawFind;
4089
+ const findText = toString(rawFind);
4090
+ const rawWithin = evaluator.evaluate(args[1], context);
4091
+ if (rawWithin instanceof FormulaError) return rawWithin;
4092
+ const withinText = toString(rawWithin);
4093
+ let startNum = 1;
4094
+ if (args.length >= 3) {
4095
+ const rawStart = evaluator.evaluate(args[2], context);
4096
+ if (rawStart instanceof FormulaError) return rawStart;
4097
+ const s = toNumber(rawStart);
4098
+ if (s instanceof FormulaError) return s;
4099
+ startNum = Math.trunc(s);
4100
+ }
4101
+ if (startNum < 1) return new FormulaError("#VALUE!", "FIND start_num must be >= 1");
4102
+ const idx = withinText.indexOf(findText, startNum - 1);
4103
+ if (idx === -1) return new FormulaError("#VALUE!", "FIND text not found");
4104
+ return idx + 1;
4105
+ }
4106
+ });
4107
+ registry.set("SEARCH", {
4108
+ minArgs: 2,
4109
+ maxArgs: 3,
4110
+ evaluate(args, context, evaluator) {
4111
+ const rawFind = evaluator.evaluate(args[0], context);
4112
+ if (rawFind instanceof FormulaError) return rawFind;
4113
+ const findText = toString(rawFind).toLowerCase();
4114
+ const rawWithin = evaluator.evaluate(args[1], context);
4115
+ if (rawWithin instanceof FormulaError) return rawWithin;
4116
+ const withinText = toString(rawWithin).toLowerCase();
4117
+ let startNum = 1;
4118
+ if (args.length >= 3) {
4119
+ const rawStart = evaluator.evaluate(args[2], context);
4120
+ if (rawStart instanceof FormulaError) return rawStart;
4121
+ const s = toNumber(rawStart);
4122
+ if (s instanceof FormulaError) return s;
4123
+ startNum = Math.trunc(s);
4124
+ }
4125
+ if (startNum < 1) return new FormulaError("#VALUE!", "SEARCH start_num must be >= 1");
4126
+ const idx = withinText.indexOf(findText, startNum - 1);
4127
+ if (idx === -1) return new FormulaError("#VALUE!", "SEARCH text not found");
4128
+ return idx + 1;
4129
+ }
4130
+ });
4131
+ registry.set("REPLACE", {
4132
+ minArgs: 4,
4133
+ maxArgs: 4,
4134
+ evaluate(args, context, evaluator) {
4135
+ const rawText = evaluator.evaluate(args[0], context);
4136
+ if (rawText instanceof FormulaError) return rawText;
4137
+ const text = toString(rawText);
4138
+ const rawStart = evaluator.evaluate(args[1], context);
4139
+ if (rawStart instanceof FormulaError) return rawStart;
4140
+ const startPos = toNumber(rawStart);
4141
+ if (startPos instanceof FormulaError) return startPos;
4142
+ const rawNum = evaluator.evaluate(args[2], context);
4143
+ if (rawNum instanceof FormulaError) return rawNum;
4144
+ const numChars = toNumber(rawNum);
4145
+ if (numChars instanceof FormulaError) return numChars;
4146
+ const rawNew = evaluator.evaluate(args[3], context);
4147
+ if (rawNew instanceof FormulaError) return rawNew;
4148
+ const newText = toString(rawNew);
4149
+ const start = Math.trunc(startPos) - 1;
4150
+ const count = Math.trunc(numChars);
4151
+ return text.substring(0, start) + newText + text.substring(start + count);
4152
+ }
4153
+ });
4154
+ registry.set("REPT", {
4155
+ minArgs: 2,
4156
+ maxArgs: 2,
4157
+ evaluate(args, context, evaluator) {
4158
+ const rawText = evaluator.evaluate(args[0], context);
4159
+ if (rawText instanceof FormulaError) return rawText;
4160
+ const text = toString(rawText);
4161
+ const rawTimes = evaluator.evaluate(args[1], context);
4162
+ if (rawTimes instanceof FormulaError) return rawTimes;
4163
+ const times = toNumber(rawTimes);
4164
+ if (times instanceof FormulaError) return times;
4165
+ const n = Math.trunc(times);
4166
+ if (n < 0) return new FormulaError("#VALUE!", "REPT number must be >= 0");
4167
+ return text.repeat(n);
4168
+ }
4169
+ });
4170
+ registry.set("EXACT", {
4171
+ minArgs: 2,
4172
+ maxArgs: 2,
4173
+ evaluate(args, context, evaluator) {
4174
+ const rawA = evaluator.evaluate(args[0], context);
4175
+ if (rawA instanceof FormulaError) return rawA;
4176
+ const rawB = evaluator.evaluate(args[1], context);
4177
+ if (rawB instanceof FormulaError) return rawB;
4178
+ return toString(rawA) === toString(rawB);
4179
+ }
4180
+ });
4181
+ registry.set("PROPER", {
4182
+ minArgs: 1,
4183
+ maxArgs: 1,
4184
+ evaluate(args, context, evaluator) {
4185
+ const val = evaluator.evaluate(args[0], context);
4186
+ if (val instanceof FormulaError) return val;
4187
+ return toString(val).toLowerCase().replace(/\b\w/g, (c) => c.toUpperCase());
4188
+ }
4189
+ });
4190
+ registry.set("CLEAN", {
4191
+ minArgs: 1,
4192
+ maxArgs: 1,
4193
+ evaluate(args, context, evaluator) {
4194
+ const val = evaluator.evaluate(args[0], context);
4195
+ if (val instanceof FormulaError) return val;
4196
+ return toString(val).replace(/[\x00-\x1F]/g, "");
4197
+ }
4198
+ });
4199
+ registry.set("CHAR", {
4200
+ minArgs: 1,
4201
+ maxArgs: 1,
4202
+ evaluate(args, context, evaluator) {
4203
+ const rawVal = evaluator.evaluate(args[0], context);
4204
+ if (rawVal instanceof FormulaError) return rawVal;
4205
+ const num = toNumber(rawVal);
4206
+ if (num instanceof FormulaError) return num;
4207
+ const n = Math.trunc(num);
4208
+ if (n < 1 || n > 65535) return new FormulaError("#VALUE!", "CHAR number must be 1-65535");
4209
+ return String.fromCharCode(n);
4210
+ }
4211
+ });
4212
+ registry.set("CODE", {
4213
+ minArgs: 1,
4214
+ maxArgs: 1,
4215
+ evaluate(args, context, evaluator) {
4216
+ const val = evaluator.evaluate(args[0], context);
4217
+ if (val instanceof FormulaError) return val;
4218
+ const text = toString(val);
4219
+ if (text.length === 0) return new FormulaError("#VALUE!", "CODE requires non-empty text");
4220
+ return text.charCodeAt(0);
4221
+ }
4222
+ });
4223
+ registry.set("TEXT", {
4224
+ minArgs: 2,
4225
+ maxArgs: 2,
4226
+ evaluate(args, context, evaluator) {
4227
+ const rawVal = evaluator.evaluate(args[0], context);
4228
+ if (rawVal instanceof FormulaError) return rawVal;
4229
+ const rawFmt = evaluator.evaluate(args[1], context);
4230
+ if (rawFmt instanceof FormulaError) return rawFmt;
4231
+ const fmt = toString(rawFmt);
4232
+ const num = toNumber(rawVal);
4233
+ if (num instanceof FormulaError) return toString(rawVal);
4234
+ if (fmt.includes("%")) {
4235
+ const decimals2 = (fmt.match(/0/g) || []).length - 1;
4236
+ return (num * 100).toFixed(Math.max(0, decimals2)) + "%";
4237
+ }
4238
+ const decimalMatch = fmt.match(/\.(0+)/);
4239
+ const decimals = decimalMatch ? decimalMatch[1].length : 0;
4240
+ const useCommas = fmt.includes(",");
4241
+ const result = num.toFixed(decimals);
4242
+ if (useCommas) {
4243
+ const [intPart, decPart] = result.split(".");
4244
+ const withCommas = intPart.replace(/\B(?=(\d{3})+(?!\d))/g, ",");
4245
+ return decPart ? withCommas + "." + decPart : withCommas;
4246
+ }
4247
+ return result;
4248
+ }
4249
+ });
4250
+ registry.set("VALUE", {
4251
+ minArgs: 1,
4252
+ maxArgs: 1,
4253
+ evaluate(args, context, evaluator) {
4254
+ const val = evaluator.evaluate(args[0], context);
4255
+ if (val instanceof FormulaError) return val;
4256
+ if (typeof val === "number") return val;
4257
+ const raw = toString(val).trim();
4258
+ const isPercent = raw.endsWith("%");
4259
+ const text = raw.replace(/[,$%\s]/g, "");
4260
+ const n = Number(text);
4261
+ if (isNaN(n)) return new FormulaError("#VALUE!", "VALUE cannot convert text to number");
4262
+ return isPercent ? n / 100 : n;
4263
+ }
4264
+ });
4265
+ registry.set("TEXTJOIN", {
4266
+ minArgs: 3,
4267
+ maxArgs: -1,
4268
+ evaluate(args, context, evaluator) {
4269
+ const rawDelim = evaluator.evaluate(args[0], context);
4270
+ if (rawDelim instanceof FormulaError) return rawDelim;
4271
+ const delimiter = toString(rawDelim);
4272
+ const rawIgnore = evaluator.evaluate(args[1], context);
4273
+ if (rawIgnore instanceof FormulaError) return rawIgnore;
4274
+ const ignoreEmpty = !!rawIgnore;
4275
+ const parts = [];
4276
+ for (let i = 2; i < args.length; i++) {
4277
+ const arg = args[i];
4278
+ if (arg.kind === "range") {
4279
+ const rangeData = context.getRangeValues({ start: arg.start, end: arg.end });
4280
+ for (const row of rangeData) {
4281
+ for (const cell of row) {
4282
+ if (cell instanceof FormulaError) return cell;
4283
+ const s = toString(cell);
4284
+ if (!ignoreEmpty || s !== "") parts.push(s);
4285
+ }
4286
+ }
4287
+ } else {
4288
+ const val = evaluator.evaluate(args[i], context);
4289
+ if (val instanceof FormulaError) return val;
4290
+ const s = toString(val);
4291
+ if (!ignoreEmpty || s !== "") parts.push(s);
4292
+ }
4293
+ }
4294
+ return parts.join(delimiter);
4295
+ }
4296
+ });
4297
+ }
4298
+
4299
+ // src/formula/functions/date.ts
4300
+ function toDate(val) {
4301
+ if (val instanceof FormulaError) return val;
4302
+ if (val instanceof Date) {
4303
+ if (isNaN(val.getTime())) return new FormulaError("#VALUE!", "Invalid date");
4304
+ return val;
4305
+ }
4306
+ if (typeof val === "string") {
4307
+ const d = new Date(val);
4308
+ if (isNaN(d.getTime())) return new FormulaError("#VALUE!", `Cannot parse "${val}" as date`);
4309
+ return d;
4310
+ }
4311
+ if (typeof val === "number") {
4312
+ const d = new Date(val);
4313
+ if (isNaN(d.getTime())) return new FormulaError("#VALUE!", "Invalid numeric date");
4314
+ return d;
4315
+ }
4316
+ return new FormulaError("#VALUE!", "Cannot convert value to date");
4317
+ }
4318
+ function registerDateFunctions(registry) {
4319
+ registry.set("TODAY", {
4320
+ minArgs: 0,
4321
+ maxArgs: 0,
4322
+ evaluate(_args, context) {
4323
+ const now = context.now();
4324
+ return new Date(now.getFullYear(), now.getMonth(), now.getDate());
4325
+ }
4326
+ });
4327
+ registry.set("NOW", {
4328
+ minArgs: 0,
4329
+ maxArgs: 0,
4330
+ evaluate(_args, context) {
4331
+ return context.now();
4332
+ }
4333
+ });
4334
+ registry.set("YEAR", {
4335
+ minArgs: 1,
4336
+ maxArgs: 1,
4337
+ evaluate(args, context, evaluator) {
4338
+ const val = evaluator.evaluate(args[0], context);
4339
+ if (val instanceof FormulaError) return val;
4340
+ const date = toDate(val);
4341
+ if (date instanceof FormulaError) return date;
4342
+ return date.getFullYear();
4343
+ }
4344
+ });
4345
+ registry.set("MONTH", {
4346
+ minArgs: 1,
4347
+ maxArgs: 1,
4348
+ evaluate(args, context, evaluator) {
4349
+ const val = evaluator.evaluate(args[0], context);
4350
+ if (val instanceof FormulaError) return val;
4351
+ const date = toDate(val);
4352
+ if (date instanceof FormulaError) return date;
4353
+ return date.getMonth() + 1;
4354
+ }
4355
+ });
4356
+ registry.set("DAY", {
4357
+ minArgs: 1,
4358
+ maxArgs: 1,
4359
+ evaluate(args, context, evaluator) {
4360
+ const val = evaluator.evaluate(args[0], context);
4361
+ if (val instanceof FormulaError) return val;
4362
+ const date = toDate(val);
4363
+ if (date instanceof FormulaError) return date;
4364
+ return date.getDate();
4365
+ }
4366
+ });
4367
+ registry.set("DATE", {
4368
+ minArgs: 3,
4369
+ maxArgs: 3,
4370
+ evaluate(args, context, evaluator) {
4371
+ const rawY = evaluator.evaluate(args[0], context);
4372
+ if (rawY instanceof FormulaError) return rawY;
4373
+ const y = toNumber(rawY);
4374
+ if (y instanceof FormulaError) return y;
4375
+ const rawM = evaluator.evaluate(args[1], context);
4376
+ if (rawM instanceof FormulaError) return rawM;
4377
+ const m = toNumber(rawM);
4378
+ if (m instanceof FormulaError) return m;
4379
+ const rawD = evaluator.evaluate(args[2], context);
4380
+ if (rawD instanceof FormulaError) return rawD;
4381
+ const d = toNumber(rawD);
4382
+ if (d instanceof FormulaError) return d;
4383
+ return new Date(Math.trunc(y), Math.trunc(m) - 1, Math.trunc(d));
4384
+ }
4385
+ });
4386
+ registry.set("DATEDIF", {
4387
+ minArgs: 3,
4388
+ maxArgs: 3,
4389
+ evaluate(args, context, evaluator) {
4390
+ const rawStart = evaluator.evaluate(args[0], context);
4391
+ if (rawStart instanceof FormulaError) return rawStart;
4392
+ const startDate = toDate(rawStart);
4393
+ if (startDate instanceof FormulaError) return startDate;
4394
+ const rawEnd = evaluator.evaluate(args[1], context);
4395
+ if (rawEnd instanceof FormulaError) return rawEnd;
4396
+ const endDate = toDate(rawEnd);
4397
+ if (endDate instanceof FormulaError) return endDate;
4398
+ const rawUnit = evaluator.evaluate(args[2], context);
4399
+ if (rawUnit instanceof FormulaError) return rawUnit;
4400
+ const unit = String(rawUnit).toUpperCase();
4401
+ if (startDate > endDate) return new FormulaError("#NUM!", "DATEDIF start date must be <= end date");
4402
+ switch (unit) {
4403
+ case "Y": {
4404
+ let years = endDate.getFullYear() - startDate.getFullYear();
4405
+ if (endDate.getMonth() < startDate.getMonth() || endDate.getMonth() === startDate.getMonth() && endDate.getDate() < startDate.getDate()) {
4406
+ years--;
4407
+ }
4408
+ return years;
4409
+ }
4410
+ case "M": {
4411
+ let months = (endDate.getFullYear() - startDate.getFullYear()) * 12 + endDate.getMonth() - startDate.getMonth();
4412
+ if (endDate.getDate() < startDate.getDate()) months--;
4413
+ return months;
4414
+ }
4415
+ case "D":
4416
+ return Math.floor((endDate.getTime() - startDate.getTime()) / 864e5);
4417
+ default:
4418
+ return new FormulaError("#VALUE!", "DATEDIF unit must be Y, M, or D");
4419
+ }
4420
+ }
4421
+ });
4422
+ registry.set("EDATE", {
4423
+ minArgs: 2,
4424
+ maxArgs: 2,
4425
+ evaluate(args, context, evaluator) {
4426
+ const rawDate = evaluator.evaluate(args[0], context);
4427
+ if (rawDate instanceof FormulaError) return rawDate;
4428
+ const date = toDate(rawDate);
4429
+ if (date instanceof FormulaError) return date;
4430
+ const rawMonths = evaluator.evaluate(args[1], context);
4431
+ if (rawMonths instanceof FormulaError) return rawMonths;
4432
+ const months = toNumber(rawMonths);
4433
+ if (months instanceof FormulaError) return months;
4434
+ const result = new Date(date);
4435
+ result.setMonth(result.getMonth() + Math.trunc(months));
4436
+ return result;
4437
+ }
4438
+ });
4439
+ registry.set("EOMONTH", {
4440
+ minArgs: 2,
4441
+ maxArgs: 2,
4442
+ evaluate(args, context, evaluator) {
4443
+ const rawDate = evaluator.evaluate(args[0], context);
4444
+ if (rawDate instanceof FormulaError) return rawDate;
4445
+ const date = toDate(rawDate);
4446
+ if (date instanceof FormulaError) return date;
4447
+ const rawMonths = evaluator.evaluate(args[1], context);
4448
+ if (rawMonths instanceof FormulaError) return rawMonths;
4449
+ const months = toNumber(rawMonths);
4450
+ if (months instanceof FormulaError) return months;
4451
+ const result = new Date(date.getFullYear(), date.getMonth() + Math.trunc(months) + 1, 0);
4452
+ return result;
4453
+ }
4454
+ });
4455
+ registry.set("WEEKDAY", {
4456
+ minArgs: 1,
4457
+ maxArgs: 2,
4458
+ evaluate(args, context, evaluator) {
4459
+ const rawDate = evaluator.evaluate(args[0], context);
4460
+ if (rawDate instanceof FormulaError) return rawDate;
4461
+ const date = toDate(rawDate);
4462
+ if (date instanceof FormulaError) return date;
4463
+ let returnType = 1;
4464
+ if (args.length >= 2) {
4465
+ const rawRT = evaluator.evaluate(args[1], context);
4466
+ if (rawRT instanceof FormulaError) return rawRT;
4467
+ const rt = toNumber(rawRT);
4468
+ if (rt instanceof FormulaError) return rt;
4469
+ returnType = Math.trunc(rt);
4470
+ }
4471
+ const day = date.getDay();
4472
+ switch (returnType) {
4473
+ case 1:
4474
+ return day + 1;
4475
+ // 1=Sun, 7=Sat
4476
+ case 2:
4477
+ return day === 0 ? 7 : day;
4478
+ // 1=Mon, 7=Sun
4479
+ case 3:
4480
+ return day === 0 ? 6 : day - 1;
4481
+ // 0=Mon, 6=Sun
4482
+ default:
4483
+ return new FormulaError("#VALUE!", "WEEKDAY return_type must be 1, 2, or 3");
4484
+ }
4485
+ }
4486
+ });
4487
+ registry.set("HOUR", {
4488
+ minArgs: 1,
4489
+ maxArgs: 1,
4490
+ evaluate(args, context, evaluator) {
4491
+ const val = evaluator.evaluate(args[0], context);
4492
+ if (val instanceof FormulaError) return val;
4493
+ const date = toDate(val);
4494
+ if (date instanceof FormulaError) return date;
4495
+ return date.getHours();
4496
+ }
4497
+ });
4498
+ registry.set("MINUTE", {
4499
+ minArgs: 1,
4500
+ maxArgs: 1,
4501
+ evaluate(args, context, evaluator) {
4502
+ const val = evaluator.evaluate(args[0], context);
4503
+ if (val instanceof FormulaError) return val;
4504
+ const date = toDate(val);
4505
+ if (date instanceof FormulaError) return date;
4506
+ return date.getMinutes();
4507
+ }
4508
+ });
4509
+ registry.set("SECOND", {
4510
+ minArgs: 1,
4511
+ maxArgs: 1,
4512
+ evaluate(args, context, evaluator) {
4513
+ const val = evaluator.evaluate(args[0], context);
4514
+ if (val instanceof FormulaError) return val;
4515
+ const date = toDate(val);
4516
+ if (date instanceof FormulaError) return date;
4517
+ return date.getSeconds();
4518
+ }
4519
+ });
4520
+ registry.set("NETWORKDAYS", {
4521
+ minArgs: 2,
4522
+ maxArgs: 2,
4523
+ evaluate(args, context, evaluator) {
4524
+ const rawStart = evaluator.evaluate(args[0], context);
4525
+ if (rawStart instanceof FormulaError) return rawStart;
4526
+ const startDate = toDate(rawStart);
4527
+ if (startDate instanceof FormulaError) return startDate;
4528
+ const rawEnd = evaluator.evaluate(args[1], context);
4529
+ if (rawEnd instanceof FormulaError) return rawEnd;
4530
+ const endDate = toDate(rawEnd);
4531
+ if (endDate instanceof FormulaError) return endDate;
4532
+ const start = new Date(startDate.getFullYear(), startDate.getMonth(), startDate.getDate());
4533
+ const end = new Date(endDate.getFullYear(), endDate.getMonth(), endDate.getDate());
4534
+ const sign = end >= start ? 1 : -1;
4535
+ const [from, to] = sign === 1 ? [start, end] : [end, start];
4536
+ let count = 0;
4537
+ const current = new Date(from);
4538
+ while (current <= to) {
4539
+ const day = current.getDay();
4540
+ if (day !== 0 && day !== 6) count++;
4541
+ current.setDate(current.getDate() + 1);
4542
+ }
4543
+ return count * sign;
4544
+ }
4545
+ });
4546
+ }
4547
+
4548
+ // src/formula/functions/stats.ts
4549
+ function makeCriteria(op, value) {
4550
+ return { op, value, valueLower: typeof value === "string" ? value.toLowerCase() : null };
4551
+ }
4552
+ function parseCriteria(criteria) {
4553
+ if (typeof criteria === "number") {
4554
+ return makeCriteria("=", criteria);
4555
+ }
4556
+ if (typeof criteria !== "string") {
4557
+ return makeCriteria("=", criteria);
4558
+ }
4559
+ const str = criteria.trim();
4560
+ if (str.startsWith(">=")) {
4561
+ return makeCriteria(">=", parseNumericOrString(str.substring(2).trim()));
4562
+ }
4563
+ if (str.startsWith("<=")) {
4564
+ return makeCriteria("<=", parseNumericOrString(str.substring(2).trim()));
4565
+ }
4566
+ if (str.startsWith("<>")) {
4567
+ return makeCriteria("<>", parseNumericOrString(str.substring(2).trim()));
4568
+ }
4569
+ if (str.startsWith(">")) {
4570
+ return makeCriteria(">", parseNumericOrString(str.substring(1).trim()));
4571
+ }
4572
+ if (str.startsWith("<")) {
4573
+ return makeCriteria("<", parseNumericOrString(str.substring(1).trim()));
4574
+ }
4575
+ if (str.startsWith("=")) {
4576
+ return makeCriteria("=", parseNumericOrString(str.substring(1).trim()));
4577
+ }
4578
+ return makeCriteria("=", parseNumericOrString(str));
4579
+ }
4580
+ function parseNumericOrString(s) {
4581
+ const n = Number(s);
4582
+ if (!isNaN(n) && s !== "") return n;
4583
+ return s;
4584
+ }
4585
+ function matchesCriteria(cellValue, criteria) {
4586
+ const { op, value } = criteria;
4587
+ let comparableCell = cellValue;
4588
+ if (typeof value === "number" && typeof cellValue !== "number") {
4589
+ const n = toNumber(cellValue);
4590
+ if (n instanceof FormulaError) return false;
4591
+ comparableCell = n;
4592
+ }
4593
+ if (typeof comparableCell === "string" && criteria.valueLower !== null) {
4594
+ const a = comparableCell.toLowerCase();
4595
+ const b = criteria.valueLower;
4596
+ switch (op) {
4597
+ case "=":
4598
+ return a === b;
4599
+ case "<>":
4600
+ return a !== b;
4601
+ case ">":
4602
+ return a > b;
4603
+ case "<":
4604
+ return a < b;
4605
+ case ">=":
4606
+ return a >= b;
4607
+ case "<=":
4608
+ return a <= b;
4609
+ }
4610
+ }
4611
+ if (typeof comparableCell === "number" && typeof value === "number") {
4612
+ switch (op) {
4613
+ case "=":
4614
+ return comparableCell === value;
4615
+ case "<>":
4616
+ return comparableCell !== value;
4617
+ case ">":
4618
+ return comparableCell > value;
4619
+ case "<":
4620
+ return comparableCell < value;
4621
+ case ">=":
4622
+ return comparableCell >= value;
4623
+ case "<=":
4624
+ return comparableCell <= value;
4625
+ }
4626
+ }
4627
+ if (op === "=") return comparableCell === value;
4628
+ if (op === "<>") return comparableCell !== value;
4629
+ return false;
4630
+ }
4631
+ function registerStatsFunctions(registry) {
4632
+ registry.set("SUMIF", {
4633
+ minArgs: 2,
4634
+ maxArgs: 3,
4635
+ evaluate(args, context, evaluator) {
4636
+ if (args[0].kind !== "range") {
4637
+ return new FormulaError("#VALUE!", "SUMIF range must be a cell range");
4638
+ }
4639
+ const criteriaRange = context.getRangeValues({ start: args[0].start, end: args[0].end });
4640
+ const rawCriteria = evaluator.evaluate(args[1], context);
4641
+ if (rawCriteria instanceof FormulaError) return rawCriteria;
4642
+ const criteria = parseCriteria(rawCriteria);
4643
+ let sumRange;
4644
+ if (args.length >= 3) {
4645
+ if (args[2].kind !== "range") {
4646
+ return new FormulaError("#VALUE!", "SUMIF sum_range must be a cell range");
4647
+ }
4648
+ sumRange = context.getRangeValues({ start: args[2].start, end: args[2].end });
4649
+ } else {
4650
+ sumRange = criteriaRange;
4651
+ }
4652
+ let sum = 0;
4653
+ for (let r = 0; r < criteriaRange.length; r++) {
4654
+ for (let c = 0; c < criteriaRange[r].length; c++) {
4655
+ if (matchesCriteria(criteriaRange[r][c], criteria)) {
4656
+ const sumVal = sumRange[r] && sumRange[r][c] !== void 0 ? sumRange[r][c] : null;
4657
+ const n = toNumber(sumVal);
4658
+ if (typeof n === "number") {
4659
+ sum += n;
4660
+ }
4661
+ }
4662
+ }
4663
+ }
4664
+ return sum;
4665
+ }
4666
+ });
4667
+ registry.set("COUNTIF", {
4668
+ minArgs: 2,
4669
+ maxArgs: 2,
4670
+ evaluate(args, context, evaluator) {
4671
+ if (args[0].kind !== "range") {
4672
+ return new FormulaError("#VALUE!", "COUNTIF range must be a cell range");
4673
+ }
4674
+ const rangeData = context.getRangeValues({ start: args[0].start, end: args[0].end });
4675
+ const rawCriteria = evaluator.evaluate(args[1], context);
4676
+ if (rawCriteria instanceof FormulaError) return rawCriteria;
4677
+ const criteria = parseCriteria(rawCriteria);
4678
+ let count = 0;
4679
+ for (let r = 0; r < rangeData.length; r++) {
4680
+ for (let c = 0; c < rangeData[r].length; c++) {
4681
+ if (matchesCriteria(rangeData[r][c], criteria)) {
4682
+ count++;
4683
+ }
4684
+ }
4685
+ }
4686
+ return count;
4687
+ }
4688
+ });
4689
+ registry.set("AVERAGEIF", {
4690
+ minArgs: 2,
4691
+ maxArgs: 3,
4692
+ evaluate(args, context, evaluator) {
4693
+ if (args[0].kind !== "range") {
4694
+ return new FormulaError("#VALUE!", "AVERAGEIF range must be a cell range");
4695
+ }
4696
+ const criteriaRange = context.getRangeValues({ start: args[0].start, end: args[0].end });
4697
+ const rawCriteria = evaluator.evaluate(args[1], context);
4698
+ if (rawCriteria instanceof FormulaError) return rawCriteria;
4699
+ const criteria = parseCriteria(rawCriteria);
4700
+ let avgRange;
4701
+ if (args.length >= 3) {
4702
+ if (args[2].kind !== "range") {
4703
+ return new FormulaError("#VALUE!", "AVERAGEIF avg_range must be a cell range");
4704
+ }
4705
+ avgRange = context.getRangeValues({ start: args[2].start, end: args[2].end });
4706
+ } else {
4707
+ avgRange = criteriaRange;
4708
+ }
4709
+ let sum = 0;
4710
+ let count = 0;
4711
+ for (let r = 0; r < criteriaRange.length; r++) {
4712
+ for (let c = 0; c < criteriaRange[r].length; c++) {
4713
+ if (matchesCriteria(criteriaRange[r][c], criteria)) {
4714
+ const avgVal = avgRange[r] && avgRange[r][c] !== void 0 ? avgRange[r][c] : null;
4715
+ const n = toNumber(avgVal);
4716
+ if (typeof n === "number") {
4717
+ sum += n;
4718
+ count++;
4719
+ }
4720
+ }
4721
+ }
4722
+ }
4723
+ if (count === 0) return new FormulaError("#DIV/0!", "No matching values for AVERAGEIF");
4724
+ return sum / count;
4725
+ }
4726
+ });
4727
+ registry.set("SUMIFS", {
4728
+ minArgs: 3,
4729
+ maxArgs: -1,
4730
+ evaluate(args, context, evaluator) {
4731
+ if ((args.length - 1) % 2 !== 0) {
4732
+ return new FormulaError("#VALUE!", "SUMIFS requires sum_range + pairs of criteria_range, criteria");
4733
+ }
4734
+ if (args[0].kind !== "range") {
4735
+ return new FormulaError("#VALUE!", "SUMIFS sum_range must be a cell range");
4736
+ }
4737
+ const sumRange = context.getRangeValues({ start: args[0].start, end: args[0].end });
4738
+ const pairs = [];
4739
+ for (let i = 1; i < args.length; i += 2) {
4740
+ const rangeArg = args[i];
4741
+ if (rangeArg.kind !== "range") {
4742
+ return new FormulaError("#VALUE!", "SUMIFS criteria_range must be a cell range");
4743
+ }
4744
+ const range = context.getRangeValues({ start: rangeArg.start, end: rangeArg.end });
4745
+ const rawCriteria = evaluator.evaluate(args[i + 1], context);
4746
+ if (rawCriteria instanceof FormulaError) return rawCriteria;
4747
+ pairs.push({ range, criteria: parseCriteria(rawCriteria) });
4748
+ }
4749
+ let sum = 0;
4750
+ for (let r = 0; r < sumRange.length; r++) {
4751
+ for (let c = 0; c < sumRange[r].length; c++) {
4752
+ let allMatch = true;
4753
+ for (const pair of pairs) {
4754
+ const cellVal = pair.range[r]?.[c];
4755
+ if (!matchesCriteria(cellVal, pair.criteria)) {
4756
+ allMatch = false;
4757
+ break;
4758
+ }
4759
+ }
4760
+ if (allMatch) {
4761
+ const n = toNumber(sumRange[r][c]);
4762
+ if (typeof n === "number") sum += n;
4763
+ }
4764
+ }
4765
+ }
4766
+ return sum;
4767
+ }
4768
+ });
4769
+ registry.set("COUNTIFS", {
4770
+ minArgs: 2,
4771
+ maxArgs: -1,
4772
+ evaluate(args, context, evaluator) {
4773
+ if (args.length % 2 !== 0) {
4774
+ return new FormulaError("#VALUE!", "COUNTIFS requires pairs of criteria_range, criteria");
4775
+ }
4776
+ const pairs = [];
4777
+ for (let i = 0; i < args.length; i += 2) {
4778
+ const rangeArg = args[i];
4779
+ if (rangeArg.kind !== "range") {
4780
+ return new FormulaError("#VALUE!", "COUNTIFS criteria_range must be a cell range");
4781
+ }
4782
+ const range = context.getRangeValues({ start: rangeArg.start, end: rangeArg.end });
4783
+ const rawCriteria = evaluator.evaluate(args[i + 1], context);
4784
+ if (rawCriteria instanceof FormulaError) return rawCriteria;
4785
+ pairs.push({ range, criteria: parseCriteria(rawCriteria) });
4786
+ }
4787
+ const firstRange = pairs[0].range;
4788
+ let count = 0;
4789
+ for (let r = 0; r < firstRange.length; r++) {
4790
+ for (let c = 0; c < firstRange[r].length; c++) {
4791
+ let allMatch = true;
4792
+ for (const pair of pairs) {
4793
+ const cellVal = pair.range[r]?.[c];
4794
+ if (!matchesCriteria(cellVal, pair.criteria)) {
4795
+ allMatch = false;
4796
+ break;
4797
+ }
4798
+ }
4799
+ if (allMatch) count++;
4800
+ }
4801
+ }
4802
+ return count;
4803
+ }
4804
+ });
4805
+ registry.set("AVERAGEIFS", {
4806
+ minArgs: 3,
4807
+ maxArgs: -1,
4808
+ evaluate(args, context, evaluator) {
4809
+ if ((args.length - 1) % 2 !== 0) {
4810
+ return new FormulaError("#VALUE!", "AVERAGEIFS requires avg_range + pairs of criteria_range, criteria");
4811
+ }
4812
+ if (args[0].kind !== "range") {
4813
+ return new FormulaError("#VALUE!", "AVERAGEIFS avg_range must be a cell range");
4814
+ }
4815
+ const avgRange = context.getRangeValues({ start: args[0].start, end: args[0].end });
4816
+ const pairs = [];
4817
+ for (let i = 1; i < args.length; i += 2) {
4818
+ const rangeArg = args[i];
4819
+ if (rangeArg.kind !== "range") {
4820
+ return new FormulaError("#VALUE!", "AVERAGEIFS criteria_range must be a cell range");
4821
+ }
4822
+ const range = context.getRangeValues({ start: rangeArg.start, end: rangeArg.end });
4823
+ const rawCriteria = evaluator.evaluate(args[i + 1], context);
4824
+ if (rawCriteria instanceof FormulaError) return rawCriteria;
4825
+ pairs.push({ range, criteria: parseCriteria(rawCriteria) });
4826
+ }
4827
+ let sum = 0;
4828
+ let count = 0;
4829
+ for (let r = 0; r < avgRange.length; r++) {
4830
+ for (let c = 0; c < avgRange[r].length; c++) {
4831
+ let allMatch = true;
4832
+ for (const pair of pairs) {
4833
+ const cellVal = pair.range[r]?.[c];
4834
+ if (!matchesCriteria(cellVal, pair.criteria)) {
4835
+ allMatch = false;
4836
+ break;
4837
+ }
4838
+ }
4839
+ if (allMatch) {
4840
+ const n = toNumber(avgRange[r][c]);
4841
+ if (typeof n === "number") {
4842
+ sum += n;
4843
+ count++;
4844
+ }
4845
+ }
4846
+ }
4847
+ }
4848
+ if (count === 0) return new FormulaError("#DIV/0!", "No matching values for AVERAGEIFS");
4849
+ return sum / count;
4850
+ }
4851
+ });
4852
+ }
4853
+
4854
+ // src/formula/functions/info.ts
4855
+ function registerInfoFunctions(registry) {
4856
+ registry.set("ISBLANK", {
4857
+ minArgs: 1,
4858
+ maxArgs: 1,
4859
+ evaluate(args, context, evaluator) {
4860
+ const val = evaluator.evaluate(args[0], context);
4861
+ return val === null || val === void 0 || val === "";
4862
+ }
4863
+ });
4864
+ registry.set("ISNUMBER", {
4865
+ minArgs: 1,
4866
+ maxArgs: 1,
4867
+ evaluate(args, context, evaluator) {
4868
+ const val = evaluator.evaluate(args[0], context);
4869
+ return typeof val === "number" && !isNaN(val);
4870
+ }
4871
+ });
4872
+ registry.set("ISTEXT", {
4873
+ minArgs: 1,
4874
+ maxArgs: 1,
4875
+ evaluate(args, context, evaluator) {
4876
+ const val = evaluator.evaluate(args[0], context);
4877
+ return typeof val === "string";
4878
+ }
4879
+ });
4880
+ registry.set("ISERROR", {
4881
+ minArgs: 1,
4882
+ maxArgs: 1,
4883
+ evaluate(args, context, evaluator) {
4884
+ const val = evaluator.evaluate(args[0], context);
4885
+ return val instanceof FormulaError;
4886
+ }
4887
+ });
4888
+ registry.set("ISNA", {
4889
+ minArgs: 1,
4890
+ maxArgs: 1,
4891
+ evaluate(args, context, evaluator) {
4892
+ const val = evaluator.evaluate(args[0], context);
4893
+ return val instanceof FormulaError && val.type === "#N/A";
4894
+ }
4895
+ });
4896
+ registry.set("TYPE", {
4897
+ minArgs: 1,
4898
+ maxArgs: 1,
4899
+ evaluate(args, context, evaluator) {
4900
+ const val = evaluator.evaluate(args[0], context);
4901
+ if (val instanceof FormulaError) return 16;
4902
+ if (typeof val === "number") return 1;
4903
+ if (typeof val === "string") return 2;
4904
+ if (typeof val === "boolean") return 4;
4905
+ if (val === null || val === void 0) return 1;
4906
+ return 1;
4907
+ }
4908
+ });
4909
+ }
4910
+
4911
+ // src/formula/functions/index.ts
4912
+ function createBuiltInFunctions() {
4913
+ const registry = /* @__PURE__ */ new Map();
4914
+ registerMathFunctions(registry);
4915
+ registerLogicalFunctions(registry);
4916
+ registerLookupFunctions(registry);
4917
+ registerTextFunctions(registry);
4918
+ registerDateFunctions(registry);
4919
+ registerStatsFunctions(registry);
4920
+ registerInfoFunctions(registry);
4921
+ return registry;
4922
+ }
4923
+
4924
+ // src/formula/formulaEngine.ts
4925
+ function extractDependencies(node) {
4926
+ const deps = /* @__PURE__ */ new Set();
4927
+ function walk(n) {
4928
+ switch (n.kind) {
4929
+ case "cellRef":
4930
+ deps.add(toCellKey(n.address.col, n.address.row, n.address.sheet));
4931
+ break;
4932
+ case "range": {
4933
+ const sheet = n.start.sheet;
4934
+ const minRow = Math.min(n.start.row, n.end.row);
4935
+ const maxRow = Math.max(n.start.row, n.end.row);
4936
+ const minCol = Math.min(n.start.col, n.end.col);
4937
+ const maxCol = Math.max(n.start.col, n.end.col);
4938
+ for (let r = minRow; r <= maxRow; r++) {
4939
+ for (let c = minCol; c <= maxCol; c++) {
4940
+ deps.add(toCellKey(c, r, sheet));
4941
+ }
4942
+ }
4943
+ break;
4944
+ }
4945
+ case "functionCall":
4946
+ for (const arg of n.args) walk(arg);
4947
+ break;
4948
+ case "binaryOp":
4949
+ walk(n.left);
4950
+ walk(n.right);
4951
+ break;
4952
+ case "unaryOp":
4953
+ walk(n.operand);
4954
+ break;
4955
+ }
4956
+ }
4957
+ walk(node);
4958
+ return deps;
4959
+ }
4960
+ var FormulaEngine = class {
4961
+ constructor(config) {
4962
+ this.formulas = /* @__PURE__ */ new Map();
4963
+ this.parsedFormulas = /* @__PURE__ */ new Map();
4964
+ this.values = /* @__PURE__ */ new Map();
4965
+ this.depGraph = new DependencyGraph();
4966
+ this.namedRanges = /* @__PURE__ */ new Map();
4967
+ this.sheetAccessors = /* @__PURE__ */ new Map();
4968
+ const builtIns = createBuiltInFunctions();
4969
+ if (config?.customFunctions) {
4970
+ for (const [name, fn] of Object.entries(config.customFunctions)) {
4971
+ builtIns.set(name.toUpperCase(), fn);
4972
+ }
4973
+ }
4974
+ if (config?.namedRanges) {
4975
+ for (const [name, ref] of Object.entries(config.namedRanges)) {
4976
+ this.namedRanges.set(name.toUpperCase(), ref);
4977
+ }
4978
+ }
4979
+ this.evaluator = new FormulaEvaluator(builtIns);
4980
+ this.maxChainLength = config?.maxChainLength ?? 1e3;
4981
+ }
4982
+ /**
4983
+ * Set or clear a formula for a cell.
4984
+ */
4985
+ setFormula(col, row, formula, accessor) {
4986
+ const key = toCellKey(col, row);
4987
+ if (formula === null || formula === "") {
4988
+ const oldValue2 = this.values.get(key);
4989
+ this.formulas.delete(key);
4990
+ this.parsedFormulas.delete(key);
4991
+ this.values.delete(key);
4992
+ this.depGraph.removeDependencies(key);
4993
+ return {
4994
+ updatedCells: oldValue2 !== void 0 ? [{ cellKey: key, col, row, oldValue: oldValue2, newValue: void 0 }] : []
4995
+ };
4996
+ }
4997
+ const expression = formula.startsWith("=") ? formula.slice(1) : formula;
4998
+ let ast;
4999
+ try {
5000
+ const tokens = tokenize(expression);
5001
+ ast = parse(tokens, this.namedRanges);
5002
+ } catch (err) {
5003
+ const error = err instanceof FormulaError ? err : new FormulaError("#ERROR!", String(err));
5004
+ ast = { kind: "error", error };
5005
+ }
5006
+ const deps = extractDependencies(ast);
5007
+ if (deps.has(key) || this.depGraph.wouldCreateCycle(key, deps)) {
5008
+ const oldValue2 = this.values.get(key);
5009
+ const circError = new FormulaError("#CIRC!", "Circular reference detected");
5010
+ this.formulas.set(key, formula);
5011
+ this.parsedFormulas.set(key, ast);
5012
+ this.values.set(key, circError);
5013
+ this.depGraph.setDependencies(key, deps);
5014
+ return {
5015
+ updatedCells: [{ cellKey: key, col, row, oldValue: oldValue2, newValue: circError }]
5016
+ };
5017
+ }
5018
+ this.depGraph.setDependencies(key, deps);
5019
+ this.formulas.set(key, formula);
5020
+ this.parsedFormulas.set(key, ast);
5021
+ const oldValue = this.values.get(key);
5022
+ const context = this.createContext(accessor);
5023
+ const newValue = this.evaluator.evaluate(ast, context);
5024
+ this.values.set(key, newValue);
5025
+ const updatedCells = [
5026
+ { cellKey: key, col, row, oldValue, newValue }
5027
+ ];
5028
+ const recalcOrder = this.depGraph.getRecalcOrder(key);
5029
+ this.recalcCells(recalcOrder, accessor, updatedCells);
5030
+ return { updatedCells };
5031
+ }
5032
+ /**
5033
+ * Notify the engine that a non-formula cell's value changed.
5034
+ */
5035
+ onCellChanged(col, row, accessor) {
5036
+ const key = toCellKey(col, row);
5037
+ const recalcOrder = this.depGraph.getRecalcOrder(key);
5038
+ if (recalcOrder.length === 0) return { updatedCells: [] };
5039
+ const updatedCells = [];
5040
+ this.recalcCells(recalcOrder, accessor, updatedCells);
5041
+ return { updatedCells };
5042
+ }
5043
+ /**
5044
+ * Batch notify: multiple cells changed.
5045
+ */
5046
+ onCellsChanged(cells, accessor) {
5047
+ const keys = cells.map((c) => toCellKey(c.col, c.row));
5048
+ const recalcOrder = this.depGraph.getRecalcOrderBatch(keys);
5049
+ if (recalcOrder.length === 0) return { updatedCells: [] };
5050
+ const updatedCells = [];
5051
+ this.recalcCells(recalcOrder, accessor, updatedCells);
5052
+ return { updatedCells };
5053
+ }
5054
+ /**
5055
+ * Get the current computed value for a cell.
5056
+ */
5057
+ getValue(col, row) {
5058
+ return this.values.get(toCellKey(col, row));
5059
+ }
5060
+ /**
5061
+ * Get the formula string for a cell.
5062
+ */
5063
+ getFormula(col, row) {
5064
+ return this.formulas.get(toCellKey(col, row));
5065
+ }
5066
+ /**
5067
+ * Check if a cell has a formula.
5068
+ */
5069
+ hasFormula(col, row) {
5070
+ return this.formulas.has(toCellKey(col, row));
5071
+ }
5072
+ /**
5073
+ * Register a custom function at runtime.
5074
+ */
5075
+ registerFunction(name, fn) {
5076
+ this.evaluator.registerFunction(name, fn);
5077
+ }
5078
+ /**
5079
+ * Full recalculation of all formulas.
5080
+ */
5081
+ recalcAll(accessor) {
5082
+ const updatedCells = [];
5083
+ const context = this.createContext(accessor);
5084
+ if (this.formulas.size === 0) return { updatedCells };
5085
+ const allFormulaKeys = [];
5086
+ for (const key of this.formulas.keys()) allFormulaKeys.push(key);
5087
+ const recalcOrder = this.depGraph.getRecalcOrderBatch(allFormulaKeys);
5088
+ const ordered = new Set(recalcOrder);
5089
+ for (const key of allFormulaKeys) {
5090
+ if (!ordered.has(key)) {
5091
+ const { col, row } = fromCellKey(key);
5092
+ const ast = this.parsedFormulas.get(key);
5093
+ if (!ast) continue;
5094
+ const oldValue = this.values.get(key);
5095
+ const newValue = this.evaluator.evaluate(ast, context);
5096
+ this.values.set(key, newValue);
5097
+ updatedCells.push({ cellKey: key, col, row, oldValue, newValue });
5098
+ }
5099
+ }
5100
+ this.recalcCells(recalcOrder, accessor, updatedCells);
5101
+ return { updatedCells };
5102
+ }
5103
+ /**
5104
+ * Clear all formulas and cached values.
5105
+ */
5106
+ clear() {
5107
+ this.formulas.clear();
5108
+ this.parsedFormulas.clear();
5109
+ this.values.clear();
5110
+ this.depGraph.clear();
5111
+ }
5112
+ /**
5113
+ * Get all formula entries for serialization.
5114
+ */
5115
+ getAllFormulas() {
5116
+ const result = [];
5117
+ for (const [key, formula] of this.formulas) {
5118
+ const { col, row } = fromCellKey(key);
5119
+ result.push({ col, row, formula });
5120
+ }
5121
+ return result;
5122
+ }
5123
+ /**
5124
+ * Bulk-load formulas. Recalculates everything.
5125
+ */
5126
+ loadFormulas(formulas, accessor) {
5127
+ this.clear();
5128
+ for (const { col, row, formula } of formulas) {
5129
+ const key = toCellKey(col, row);
5130
+ const expression = formula.startsWith("=") ? formula.slice(1) : formula;
5131
+ let ast;
5132
+ try {
5133
+ const tokens = tokenize(expression);
5134
+ ast = parse(tokens, this.namedRanges);
5135
+ } catch (err) {
5136
+ const error = err instanceof FormulaError ? err : new FormulaError("#ERROR!", String(err));
5137
+ ast = { kind: "error", error };
5138
+ }
5139
+ this.formulas.set(key, formula);
5140
+ this.parsedFormulas.set(key, ast);
5141
+ const deps = extractDependencies(ast);
5142
+ this.depGraph.setDependencies(key, deps);
5143
+ }
5144
+ return this.recalcAll(accessor);
5145
+ }
5146
+ // --- Named Ranges ---
5147
+ /**
5148
+ * Define a named range (e.g. "Revenue" → "A1:A10").
5149
+ */
5150
+ defineNamedRange(name, ref) {
5151
+ this.namedRanges.set(name.toUpperCase(), ref);
5152
+ }
5153
+ /**
5154
+ * Remove a named range by name.
5155
+ */
5156
+ removeNamedRange(name) {
5157
+ this.namedRanges.delete(name.toUpperCase());
5158
+ }
5159
+ /**
5160
+ * Get all named ranges as a Map (name → ref).
5161
+ */
5162
+ getNamedRanges() {
5163
+ return this.namedRanges;
5164
+ }
5165
+ // --- Sheet Accessors ---
5166
+ /**
5167
+ * Register a data accessor for a named sheet (for cross-sheet references).
5168
+ */
5169
+ registerSheet(name, accessor) {
5170
+ this.sheetAccessors.set(name, accessor);
5171
+ }
5172
+ /**
5173
+ * Unregister a sheet accessor.
5174
+ */
5175
+ unregisterSheet(name) {
5176
+ this.sheetAccessors.delete(name);
5177
+ }
5178
+ // --- Formula Auditing ---
5179
+ /**
5180
+ * Get all cells that a cell depends on (deep, transitive precedents).
5181
+ */
5182
+ getPrecedents(col, row) {
5183
+ const key = toCellKey(col, row);
5184
+ const result = [];
5185
+ const visited = /* @__PURE__ */ new Set();
5186
+ const queue = [];
5187
+ const directDeps = this.depGraph.getDependencies(key);
5188
+ for (const dep of directDeps) {
5189
+ if (!visited.has(dep)) {
5190
+ visited.add(dep);
5191
+ queue.push(dep);
5192
+ }
5193
+ }
5194
+ let head = 0;
5195
+ while (head < queue.length) {
5196
+ const current = queue[head++];
5197
+ const parsed = fromCellKey(current);
5198
+ result.push({
5199
+ cellKey: current,
5200
+ col: parsed.col,
5201
+ row: parsed.row,
5202
+ formula: this.formulas.get(current),
5203
+ value: this.values.has(current) ? this.values.get(current) : void 0
5204
+ });
5205
+ const deps = this.depGraph.getDependencies(current);
5206
+ for (const dep of deps) {
5207
+ if (!visited.has(dep)) {
5208
+ visited.add(dep);
5209
+ queue.push(dep);
5210
+ }
5211
+ }
5212
+ }
5213
+ return result;
5214
+ }
5215
+ /**
5216
+ * Get all cells that depend on this cell (deep, transitive dependents).
5217
+ */
5218
+ getDependents(col, row) {
5219
+ const key = toCellKey(col, row);
5220
+ const result = [];
5221
+ const visited = /* @__PURE__ */ new Set();
5222
+ const queue = [];
5223
+ const directDeps = this.depGraph.getDependents(key);
5224
+ for (const dep of directDeps) {
5225
+ if (!visited.has(dep)) {
5226
+ visited.add(dep);
5227
+ queue.push(dep);
5228
+ }
5229
+ }
5230
+ let head = 0;
5231
+ while (head < queue.length) {
5232
+ const current = queue[head++];
5233
+ const parsed = fromCellKey(current);
5234
+ result.push({
5235
+ cellKey: current,
5236
+ col: parsed.col,
5237
+ row: parsed.row,
5238
+ formula: this.formulas.get(current),
5239
+ value: this.values.has(current) ? this.values.get(current) : void 0
5240
+ });
5241
+ const deps = this.depGraph.getDependents(current);
5242
+ for (const dep of deps) {
5243
+ if (!visited.has(dep)) {
5244
+ visited.add(dep);
5245
+ queue.push(dep);
5246
+ }
5247
+ }
5248
+ }
5249
+ return result;
5250
+ }
5251
+ /**
5252
+ * Get a full audit trail for a cell: target + precedents + dependents.
5253
+ */
5254
+ getAuditTrail(col, row) {
5255
+ const key = toCellKey(col, row);
5256
+ const target = {
5257
+ cellKey: key,
5258
+ col,
5259
+ row,
5260
+ formula: this.formulas.get(key),
5261
+ value: this.values.has(key) ? this.values.get(key) : void 0
5262
+ };
5263
+ return {
5264
+ target,
5265
+ precedents: this.getPrecedents(col, row),
5266
+ dependents: this.getDependents(col, row)
5267
+ };
5268
+ }
5269
+ // --- Private methods ---
5270
+ createContext(accessor) {
5271
+ const contextNow = /* @__PURE__ */ new Date();
5272
+ return {
5273
+ getCellValue: (addr) => {
5274
+ const key = toCellKey(addr.col, addr.row, addr.sheet);
5275
+ const cached = this.values.get(key);
5276
+ if (cached !== void 0) return cached;
5277
+ if (addr.sheet) {
5278
+ const sheetAccessor = this.sheetAccessors.get(addr.sheet);
5279
+ if (!sheetAccessor) return new FormulaError("#REF!", `Unknown sheet: ${addr.sheet}`);
5280
+ return sheetAccessor.getCellValue(addr.col, addr.row);
5281
+ }
5282
+ return accessor.getCellValue(addr.col, addr.row);
5283
+ },
5284
+ getRangeValues: (range) => {
5285
+ const result = [];
5286
+ const sheet = range.start.sheet;
5287
+ const rangeAccessor = sheet ? this.sheetAccessors.get(sheet) : accessor;
5288
+ if (sheet && !rangeAccessor) {
5289
+ return [[new FormulaError("#REF!", `Unknown sheet: ${sheet}`)]];
5290
+ }
5291
+ const minRow = Math.min(range.start.row, range.end.row);
5292
+ const maxRow = Math.max(range.start.row, range.end.row);
5293
+ const minCol = Math.min(range.start.col, range.end.col);
5294
+ const maxCol = Math.max(range.start.col, range.end.col);
5295
+ for (let r = minRow; r <= maxRow; r++) {
5296
+ const row = [];
5297
+ for (let c = minCol; c <= maxCol; c++) {
5298
+ const key = toCellKey(c, r, sheet);
5299
+ const cached = this.values.get(key);
5300
+ if (cached !== void 0) {
5301
+ row.push(cached);
5302
+ } else {
5303
+ row.push(rangeAccessor.getCellValue(c, r));
5304
+ }
5305
+ }
5306
+ result.push(row);
5307
+ }
5308
+ return result;
5309
+ },
5310
+ now: () => contextNow
5311
+ };
5312
+ }
5313
+ recalcCells(order, accessor, updatedCells) {
5314
+ const context = this.createContext(accessor);
5315
+ let count = 0;
5316
+ for (const key of order) {
5317
+ if (count++ > this.maxChainLength) {
5318
+ const { col: col2, row: row2 } = fromCellKey(key);
5319
+ const oldValue2 = this.values.get(key);
5320
+ const circError = new FormulaError("#CIRC!", "Dependency chain too long");
5321
+ this.values.set(key, circError);
5322
+ updatedCells.push({ cellKey: key, col: col2, row: row2, oldValue: oldValue2, newValue: circError });
5323
+ continue;
5324
+ }
5325
+ const ast = this.parsedFormulas.get(key);
5326
+ if (!ast) continue;
5327
+ const { col, row } = fromCellKey(key);
5328
+ const oldValue = this.values.get(key);
5329
+ const newValue = this.evaluator.evaluate(ast, context);
5330
+ this.values.set(key, newValue);
5331
+ updatedCells.push({ cellKey: key, col, row, oldValue, newValue });
5332
+ }
5333
+ }
5334
+ };
5335
+
5336
+ export { AUTOSIZE_EXTRA_PX, AUTOSIZE_MAX_PX, CELL_PADDING, CHECKBOX_COLUMN_WIDTH, CIRC_ERROR, COLUMN_HEADER_MENU_ITEMS, CellDescriptorCache, DEFAULT_DEBOUNCE_MS, DEFAULT_MIN_COLUMN_WIDTH, DIV_ZERO_ERROR, DependencyGraph, FormulaEngine, FormulaError, FormulaEvaluator, GENERAL_ERROR, GRID_BORDER_RADIUS, GRID_CONTEXT_MENU_ITEMS, MAX_PAGE_BUTTONS, NAME_ERROR, NA_ERROR, PAGE_SIZE_OPTIONS, PEOPLE_SEARCH_DEBOUNCE_MS, REF_ERROR, ROW_NUMBER_COLUMN_WIDTH, SIDEBAR_TRANSITION_MS, UndoRedoStack, VALUE_ERROR, Z_INDEX, adjustFormulaReferences, applyCellDeletion, applyCutClear, applyFillValues, applyPastedValues, applyRangeRowSelection, areGridRowPropsEqual, booleanParser, buildCellIndex, buildCsvHeader, buildCsvRows, buildHeaderRows, buildInlineEditorProps, buildPopoverEditorProps, calculateDropTarget, clampSelectionToBounds, columnLetterToIndex, computeAggregations, computeArrowNavigation, computeAutoScrollSpeed, computeNextSortState, computeRowSelectionState, computeTabNavigation, computeTotalHeight, computeVisibleColumnRange, computeVisibleRange, createBuiltInFunctions, createSortFilterWorker, currencyParser, dateParser, debounce, deriveFilterOptionsFromData, emailParser, escapeCsvValue, exportToCsv, extractValueMatrix, findCtrlArrowTarget, flattenArgs, flattenColumns, formatAddress, formatCellReference, formatCellValueForTsv, formatSelectionAsTsv, formatShortcut, toString as formulaToString, fromCellKey, getCellRenderDescriptor, getCellValue, getColumnHeaderMenuItems, getContextMenuHandlers, getDataGridStatusBarConfig, getFilterField, getHeaderFilterConfig, getMultiSelectFilterFields, getPaginationViewModel, getPinStateForColumn, getScrollTopForRow, getStatusBarParts, indexToColumnLetter, injectGlobalStyles, isColumnEditable, isFilterConfig, isFormulaError, isInSelectionRange, isRowInRange, measureColumnContentWidth, measureRange, mergeFilter, normalizeSelectionRange, numberParser, parse, parseCellRef, parseRange, parseTsvClipboard, parseValue, partitionColumnsForVirtualization, processClientSideData, processClientSideDataAsync, rangesEqual, reorderColumnArray, resolveCellDisplayContent, resolveCellStyle, terminateSortFilterWorker, toBoolean, toCellKey, toNumber, toUserLike, tokenize, triggerCsvDownload, validateColumns, validateRowIds, validateVirtualScrollConfig };