@univerjs/engine-formula 1.0.0-alpha.8 → 1.0.0-beta.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (36) hide show
  1. package/lib/cjs/index.js +1175 -982
  2. package/lib/es/index.js +1177 -984
  3. package/lib/index.js +1177 -984
  4. package/lib/types/basics/common.d.ts +2 -0
  5. package/lib/types/basics/regex.d.ts +4 -4
  6. package/lib/types/controllers/formula-calculation-trigger.controller.d.ts +1 -2
  7. package/lib/types/controllers/formula.controller.d.ts +1 -1
  8. package/lib/types/engine/analysis/lexer-tree-builder.d.ts +4 -0
  9. package/lib/types/engine/analysis/lexer.d.ts +4 -2
  10. package/lib/types/engine/ast-node/base-ast-node.d.ts +1 -0
  11. package/lib/types/engine/ast-node/function-node.d.ts +1 -0
  12. package/lib/types/engine/ast-node/union-node.d.ts +8 -2
  13. package/lib/types/engine/reference-object/base-reference-object.d.ts +2 -1
  14. package/lib/types/engine/reference-object/multi-area-reference-object.d.ts +11 -3
  15. package/lib/types/engine/reference-object/table-reference-object.d.ts +1 -1
  16. package/lib/types/engine/utils/generate-ast-node.d.ts +1 -1
  17. package/lib/types/engine/value-object/array-value-object.d.ts +1 -1
  18. package/lib/types/functions/base-function.d.ts +6 -2
  19. package/lib/types/functions/compatibility/rank/index.d.ts +1 -0
  20. package/lib/types/functions/information/isblank/index.d.ts +3 -3
  21. package/lib/types/functions/logical/percentof/index.d.ts +5 -6
  22. package/lib/types/functions/lookup/choose/index.d.ts +1 -0
  23. package/lib/types/functions/lookup/function-map.d.ts +4 -1
  24. package/lib/types/functions/lookup/match/index.d.ts +1 -0
  25. package/lib/types/functions/lookup/xlookup/index.d.ts +4 -0
  26. package/lib/types/functions/math/sumproduct/index.d.ts +1 -0
  27. package/lib/types/functions/statistical/median/index.d.ts +1 -0
  28. package/lib/types/functions/statistical/percentile-exc/index.d.ts +1 -0
  29. package/lib/types/functions/statistical/percentile-inc/index.d.ts +1 -0
  30. package/lib/types/functions/statistical/rank-avg/index.d.ts +1 -0
  31. package/lib/types/functions/statistical/rank-eq/index.d.ts +1 -0
  32. package/lib/types/functions/text/textjoin/index.d.ts +1 -0
  33. package/lib/types/services/register-other-formula.service.d.ts +3 -3
  34. package/lib/types/services/runtime.service.d.ts +2 -0
  35. package/lib/umd/index.js +4 -4
  36. package/package.json +4 -4
package/lib/cjs/index.js CHANGED
@@ -1259,13 +1259,8 @@ var InvertedIndexCache = class {
1259
1259
  const rowsForEmpty = columnMap.get(DEFAULT_EMPTY_CELL_KEY);
1260
1260
  if (rowsForEmpty) rows.push(...rowsForEmpty);
1261
1261
  result.matchingRows = rows.filter((row) => rowsInCache.some(([start, end]) => row >= start && row <= end));
1262
- } else if (_value === DEFAULT_EMPTY_CELL_KEY) {
1263
- var _columnMap$get;
1264
- result.matchingRows = Array.from((_columnMap$get = columnMap.get(DEFAULT_EMPTY_CELL_KEY)) !== null && _columnMap$get !== void 0 ? _columnMap$get : []).filter((row) => rowsInCache.some(([start, end]) => row >= start && row <= end));
1265
- } else {
1266
- var _columnMap$get2;
1267
- result.matchingRows = Array.from((_columnMap$get2 = columnMap.get(_value)) !== null && _columnMap$get2 !== void 0 ? _columnMap$get2 : []).filter((row) => rowsInCache.some(([start, end]) => row >= start && row <= end));
1268
- }
1262
+ } else if (_value === DEFAULT_EMPTY_CELL_KEY) result.matchingRows = Array.from(columnMap.get(DEFAULT_EMPTY_CELL_KEY) ?? []).filter((row) => rowsInCache.some(([start, end]) => row >= start && row <= end));
1263
+ else result.matchingRows = Array.from(columnMap.get(_value) ?? []).filter((row) => rowsInCache.some(([start, end]) => row >= start && row <= end));
1269
1264
  return result;
1270
1265
  }
1271
1266
  setContinueBuildingCache(unitId, sheetId, column, startRow, endRow) {
@@ -1478,11 +1473,12 @@ const REFERENCE_REGEX_SINGLE_ROW = `^${UNIT_NAME_SHEET_NAME_REGEX}\\s*?\\${"$"}?
1478
1473
  const REFERENCE_REGEX_SINGLE_ROW_PRECOMPILING = new RegExp(REFERENCE_REGEX_SINGLE_ROW);
1479
1474
  const REFERENCE_REGEX_SINGLE_COLUMN = `^${UNIT_NAME_SHEET_NAME_REGEX}\\s*?\\${"$"}?${COLUMN_REGEX}$`;
1480
1475
  const REFERENCE_REGEX_SINGLE_COLUMN_PRECOMPILING = new RegExp(REFERENCE_REGEX_SINGLE_COLUMN);
1481
- const TABLE_NAME_REGEX = "((?![~!@#$%^&*()_+<>?:,./;’,。、‘:“《》?~!@#¥%……()【】\\[\\]\\/\\\\]).)+";
1476
+ const TABLE_NAME_REGEX = "((?![~!@#$%^&*()+<>?:,./;’,。、‘:“《》?~!@#¥%……()【】\\[\\]\\/\\\\]).)+";
1482
1477
  const TABLE_TITLE_REGEX = "\\[#.+\\]\\s*?,\\s*?";
1483
- const TABLE_CONTENT_REGEX = "\\[((?<!#)[\\s\\S])*\\]";
1478
+ const TABLE_CONTENT_REGEX = "\\[[^#]*#?\\]";
1484
1479
  const TABLE_MULTIPLE_COLUMN_REGEX = `${TABLE_CONTENT_REGEX}${RANGE_SYMBOL}${TABLE_CONTENT_REGEX}`;
1485
- const TABLE_UNIT_QUALIFIER_REGEX = `(?:(?:${UNIT_NAME_REGEX}|'(?:[^']|'')+'|[^\\s!\\[\\]]+)!)?(?:${UNIT_NAME_REGEX})?`;
1480
+ const TABLE_BRACKETED_UNIT_QUALIFIER_REGEX = "\\[(?:[^\\]]|\\]\\])+\\]";
1481
+ const TABLE_UNIT_QUALIFIER_REGEX = `(?:(?:${TABLE_BRACKETED_UNIT_QUALIFIER_REGEX}|'(?:[^']|'')+'|[^\\s!\\[\\]]+)!)?(?:${TABLE_BRACKETED_UNIT_QUALIFIER_REGEX})?`;
1486
1482
  const REFERENCE_TABLE_ALL_COLUMN_REGEX = `^${TABLE_UNIT_QUALIFIER_REGEX}${TABLE_NAME_REGEX}$`;
1487
1483
  const REFERENCE_TABLE_SINGLE_COLUMN_REGEX = `^${TABLE_UNIT_QUALIFIER_REGEX}${TABLE_NAME_REGEX}(${TABLE_CONTENT_REGEX}|\\[${TABLE_TITLE_REGEX}${TABLE_CONTENT_REGEX}\\])+$`;
1488
1484
  const REFERENCE_TABLE_MULTIPLE_COLUMN_REGEX = `^${TABLE_UNIT_QUALIFIER_REGEX}${TABLE_NAME_REGEX}(\\[${TABLE_MULTIPLE_COLUMN_REGEX}\\])?$|^${TABLE_UNIT_QUALIFIER_REGEX}${TABLE_NAME_REGEX}(\\[${TABLE_TITLE_REGEX}${TABLE_MULTIPLE_COLUMN_REGEX}\\])?$`;
@@ -1939,8 +1935,13 @@ function splitTableStructuredRef(ref) {
1939
1935
  }
1940
1936
  quoteOpen = !quoteOpen;
1941
1937
  } else if (!quoteOpen && char === "[") bracketDepth++;
1942
- else if (!quoteOpen && char === "]") bracketDepth--;
1943
- else if (!quoteOpen && bracketDepth === 0 && char === "!") {
1938
+ else if (!quoteOpen && char === "]") {
1939
+ if (bracketDepth > 0 && tableRef[i + 1] === "]") {
1940
+ i++;
1941
+ continue;
1942
+ }
1943
+ bracketDepth--;
1944
+ } else if (!quoteOpen && bracketDepth === 0 && char === "!") {
1944
1945
  qualifierEnd = i;
1945
1946
  break;
1946
1947
  }
@@ -1948,8 +1949,10 @@ function splitTableStructuredRef(ref) {
1948
1949
  if (qualifierEnd >= 0) {
1949
1950
  unitQualifier = tableRef.slice(0, qualifierEnd).trim();
1950
1951
  tableRef = tableRef.slice(qualifierEnd + 1);
1951
- if (unitQualifier.startsWith("'") && unitQualifier.endsWith("'")) unitQualifier = unitQualifier.slice(1, -1);
1952
- if (unitQualifier.startsWith("[") && unitQualifier.endsWith("]")) unitQualifier = unitQualifier.slice(1, -1);
1952
+ const isQuotedQualifier = unitQualifier.startsWith("'") && unitQualifier.endsWith("'");
1953
+ const isBracketedQualifier = !isQuotedQualifier && unitQualifier.startsWith("[") && unitQualifier.endsWith("]");
1954
+ if (isQuotedQualifier) unitQualifier = unitQualifier.slice(1, -1);
1955
+ else if (isBracketedQualifier) unitQualifier = unitQualifier.slice(1, -1).replaceAll("]]", "]");
1953
1956
  unitQualifier = unquoteSheetName(unitQualifier);
1954
1957
  } else if (tableRef.startsWith("[")) {
1955
1958
  const legacyQualifierEnd = tableRef.indexOf("]");
@@ -2099,7 +2102,6 @@ let DefinedNamesService = class DefinedNamesService extends _univerjs_core.Dispo
2099
2102
  const nameMap = this._definedNameMap[unitId];
2100
2103
  if (nameMap === void 0) return null;
2101
2104
  if (sheetId) {
2102
- var _workbookScope;
2103
2105
  const normalizedName = name.toLowerCase();
2104
2106
  let workbookScope = null;
2105
2107
  let firstMatch = null;
@@ -2111,7 +2113,7 @@ let DefinedNamesService = class DefinedNamesService extends _univerjs_core.Dispo
2111
2113
  if (workbookScope == null) workbookScope = item;
2112
2114
  }
2113
2115
  }
2114
- return (_workbookScope = workbookScope) !== null && _workbookScope !== void 0 ? _workbookScope : firstMatch;
2116
+ return workbookScope ?? firstMatch;
2115
2117
  }
2116
2118
  const cachedMap = this._nameCacheMap[unitId];
2117
2119
  if (cachedMap) return cachedMap[name.toLowerCase()] || null;
@@ -2413,7 +2415,7 @@ var SuperTableService = class extends _univerjs_core.Disposable {
2413
2415
  }
2414
2416
  hasTable(unitId, tableName) {
2415
2417
  const unitIdMap = this._tableMap.get(unitId);
2416
- if (unitIdMap) return unitIdMap.keys().some((name) => name.toLowerCase() === tableName.toLowerCase());
2418
+ if (unitIdMap) return Array.from(unitIdMap.keys()).some((name) => name.toLowerCase() === tableName.toLowerCase());
2417
2419
  return false;
2418
2420
  }
2419
2421
  _update() {
@@ -3823,9 +3825,11 @@ var LexerTreeBuilder = class extends _univerjs_core.Disposable {
3823
3825
  return this._nodeMaker(formulaString);
3824
3826
  }
3825
3827
  treeBuilder(formulaString, transformSuffix = true, injectDefinedNameParam) {
3826
- if (transformSuffix === true) {
3828
+ const isCacheable = !/\b(?:LET|LAMBDA)\s*\(/iu.test(formulaString);
3829
+ const cacheKey = injectDefinedNameParam == null ? formulaString : `${injectDefinedNameParam.unitId ?? ""}\0${injectDefinedNameParam.sheetId ?? ""}\0${injectDefinedNameParam.refOffsetX}\0${injectDefinedNameParam.refOffsetY}\0${formulaString}`;
3830
+ if (transformSuffix === true && isCacheable) {
3827
3831
  var _this$_simpleCheckDef;
3828
- const lexerNode = FormulaLexerNodeCache.get(formulaString);
3832
+ const lexerNode = FormulaLexerNodeCache.get(cacheKey);
3829
3833
  const simpleCheckDefinedNameResult = injectDefinedNameParam && ((_this$_simpleCheckDef = this._simpleCheckDefinedName) === null || _this$_simpleCheckDef === void 0 ? void 0 : _this$_simpleCheckDef.call(this, formulaString, injectDefinedNameParam));
3830
3834
  if (lexerNode && !simpleCheckDefinedNameResult) return lexerNode;
3831
3835
  }
@@ -3857,13 +3861,13 @@ var LexerTreeBuilder = class extends _univerjs_core.Disposable {
3857
3861
  if (node) this._currentLexerNode = node;
3858
3862
  if (transformSuffix) {
3859
3863
  if (!this._suffixExpressionHandler(this._currentLexerNode)) return "#VALUE!";
3860
- FormulaLexerNodeCache.set(formulaString, this._currentLexerNode);
3864
+ if (isCacheable) FormulaLexerNodeCache.set(cacheKey, this._currentLexerNode);
3861
3865
  }
3862
3866
  if (currentHasDefinedName) this._currentLexerNode.setDefinedNames(currentDefinedNames);
3863
3867
  return this._currentLexerNode;
3864
3868
  }
3865
3869
  _handleDefinedName(sequenceArray, param) {
3866
- const { unitId, sheetId, getValueByName, getSheetName } = param;
3870
+ const { unitId, sheetId, hasFunction, getValueByName } = param;
3867
3871
  if (unitId == null) return {
3868
3872
  sequenceString: "",
3869
3873
  hasDefinedName: false,
@@ -3882,11 +3886,19 @@ var LexerTreeBuilder = class extends _univerjs_core.Disposable {
3882
3886
  const { nodeType, token: tokenRaw } = node;
3883
3887
  let token = tokenRaw;
3884
3888
  if (nodeType === 4 || nodeType === 3) {
3885
- if (nodeType === 3) token = this._getHasSheetNameDefinedName(tokenRaw, unitId, param);
3889
+ if (nodeType === 3) {
3890
+ const nextNode = sequenceNodes[i + 1];
3891
+ if (typeof nextNode === "string" && nextNode.trim() === "(" && hasFunction(tokenRaw.trim().toUpperCase())) {
3892
+ sequenceString += tokenRaw;
3893
+ continue;
3894
+ }
3895
+ token = this._getHasSheetNameDefinedName(tokenRaw, unitId, param);
3896
+ }
3886
3897
  const definedNameToken = token.trim();
3887
3898
  const definedContent = getValueByName(unitId, definedNameToken, sheetId);
3888
3899
  if (definedContent) {
3889
- const refString = definedContent.formulaOrRefString;
3900
+ const refOffsetX = definedContent.localSheetId === "AllDefaultWorkbook" ? param.refOffsetX - 1 : param.refOffsetX;
3901
+ const refString = definedContent.formulaOrRefString.startsWith("=") ? definedContent.formulaOrRefString : this._moveDefinedNameRefOffset(definedContent.formulaOrRefString, refOffsetX, param.refOffsetY);
3890
3902
  const nestedDefinedNameParam = this._handleNestedDefinedName(refString, param);
3891
3903
  if (nestedDefinedNameParam == null || typeof nestedDefinedNameParam !== "object") {
3892
3904
  sequenceString += nestedDefinedNameParam || "#NAME?";
@@ -3913,6 +3925,28 @@ var LexerTreeBuilder = class extends _univerjs_core.Disposable {
3913
3925
  definedNames
3914
3926
  };
3915
3927
  }
3928
+ _moveDefinedNameRefOffset(formulaString, refOffsetX, refOffsetY) {
3929
+ const sequenceNodes = this.sequenceNodesBuilder(formulaString);
3930
+ if (sequenceNodes == null) return formulaString;
3931
+ return generateStringWithSequence(sequenceNodes.map((node) => {
3932
+ if (typeof node === "string" || node.nodeType !== 4) return node;
3933
+ const sequenceGrid = deserializeRangeWithSheetWithCache(node.token);
3934
+ const range = (0, _univerjs_core.moveRangeByOffset)(sequenceGrid.range, refOffsetX, refOffsetY);
3935
+ const wrap = (value, limit) => (value % limit + limit) % limit;
3936
+ range.startRow = wrap(range.startRow, _univerjs_core.MAX_ROW_COUNT);
3937
+ range.endRow = wrap(range.endRow, _univerjs_core.MAX_ROW_COUNT);
3938
+ range.startColumn = wrap(range.startColumn, _univerjs_core.MAX_COLUMN_COUNT);
3939
+ range.endColumn = wrap(range.endColumn, _univerjs_core.MAX_COLUMN_COUNT);
3940
+ return {
3941
+ ...node,
3942
+ token: serializeRangeToRefString({
3943
+ range,
3944
+ unitId: sequenceGrid.unitId,
3945
+ sheetName: sequenceGrid.sheetName
3946
+ })
3947
+ };
3948
+ }));
3949
+ }
3916
3950
  _getHasSheetNameDefinedName(tokenRaw, unitId, param) {
3917
3951
  if (!tokenRaw.includes("!")) return tokenRaw;
3918
3952
  const parts = tokenRaw.split("!");
@@ -4339,7 +4373,7 @@ var LexerTreeBuilder = class extends _univerjs_core.Disposable {
4339
4373
  }
4340
4374
  this._resetSegment();
4341
4375
  continue;
4342
- } else if (currentString === "(" && this.isSingleQuotationClose() && this.isDoubleQuotationClose()) if (this._segmentCount() > 0 || this.isLambdaOpen()) {
4376
+ } else if (currentString === "(" && this.isSingleQuotationClose() && this.isDoubleQuotationClose() && this.isSquareBracketClose()) if (this._segmentCount() > 0 || this.isLambdaOpen()) {
4343
4377
  if (this.isLambdaClose()) {
4344
4378
  this._newAndPushCurrentLexerNode(this._segment, cur);
4345
4379
  this._resetSegment();
@@ -4367,7 +4401,7 @@ var LexerTreeBuilder = class extends _univerjs_core.Disposable {
4367
4401
  this._openBracketNormalIndex();
4368
4402
  this._resetSegment();
4369
4403
  }
4370
- else if (currentString === ")" && this.isSingleQuotationClose() && this.isDoubleQuotationClose()) {
4404
+ else if (currentString === ")" && this.isSingleQuotationClose() && this.isDoubleQuotationClose() && this.isSquareBracketClose()) {
4371
4405
  if (this._formulaErrorLastTokenCheck(formulaChars, cur - 1)) this._formalErrorOccurred();
4372
4406
  this._pushNodeToChildren(this._segment);
4373
4407
  this._resetSegment();
@@ -5083,9 +5117,11 @@ let FormulaDataModel = class FormulaDataModel extends _univerjs_core.Disposable
5083
5117
  const unitId = base.getUnitId();
5084
5118
  formulaData[unitId] = {};
5085
5119
  const tables = Object.values(snapshot.tables);
5120
+ const formulaTableNames = (0, _univerjs_core.createBaseFormulaTableNameMap)(snapshot);
5086
5121
  for (let j = 0; j < tables.length; j++) {
5087
5122
  const table = tables[j];
5088
5123
  const tableFormulaData = {};
5124
+ const normalizedFormulaByFieldId = /* @__PURE__ */ new Map();
5089
5125
  const recordOrder = table.recordOrder;
5090
5126
  if (!recordOrder) {
5091
5127
  formulaData[unitId][table.id] = tableFormulaData;
@@ -5095,15 +5131,20 @@ let FormulaDataModel = class FormulaDataModel extends _univerjs_core.Disposable
5095
5131
  const recordId = recordOrder[row];
5096
5132
  if (!table.records[recordId]) continue;
5097
5133
  for (let col = 0; col < table.fieldOrder.length; col++) {
5098
- var _field$config$formula, _field$config, _row, _tableFormulaData$_ro;
5134
+ var _field$config;
5099
5135
  const fieldId = table.fieldOrder[col];
5100
5136
  const field = table.fields[fieldId];
5101
5137
  if (!field || field.type !== "formula") continue;
5102
- const formula = String((_field$config$formula = (_field$config = field.config) === null || _field$config === void 0 ? void 0 : _field$config.formula) !== null && _field$config$formula !== void 0 ? _field$config$formula : "").trim();
5138
+ const formula = String(((_field$config = field.config) === null || _field$config === void 0 ? void 0 : _field$config.formula) ?? "").trim();
5103
5139
  if (!formula) continue;
5104
- (_tableFormulaData$_ro = tableFormulaData[_row = row]) !== null && _tableFormulaData$_ro !== void 0 || (tableFormulaData[_row] = {});
5140
+ let normalizedFormula = normalizedFormulaByFieldId.get(field.id);
5141
+ if (normalizedFormula == null) {
5142
+ normalizedFormula = normalizeBaseFormulaForEngine(formula, table, snapshot, formulaTableNames);
5143
+ normalizedFormulaByFieldId.set(field.id, normalizedFormula);
5144
+ }
5145
+ tableFormulaData[row] ??= {};
5105
5146
  tableFormulaData[row][col] = {
5106
- f: normalizeBaseFormulaForEngine(formula, table, snapshot),
5147
+ f: normalizedFormula,
5107
5148
  si: field.id
5108
5149
  };
5109
5150
  }
@@ -5231,16 +5272,17 @@ let FormulaDataModel = class FormulaDataModel extends _univerjs_core.Disposable
5231
5272
  };
5232
5273
  const baseData = {};
5233
5274
  const tableNameMap = {};
5275
+ const formulaTableNames = (0, _univerjs_core.createBaseFormulaTableNameMap)(snapshot);
5234
5276
  for (const table of Object.values(snapshot.tables)) {
5235
- var _table$recordOrder$le, _table$recordOrder;
5277
+ var _table$recordOrder;
5236
5278
  baseData[table.id] = {
5237
5279
  cellData: new _univerjs_core.ObjectMatrix(buildBaseRuntimeCellData(table)),
5238
- rowCount: (_table$recordOrder$le = (_table$recordOrder = table.recordOrder) === null || _table$recordOrder === void 0 ? void 0 : _table$recordOrder.length) !== null && _table$recordOrder$le !== void 0 ? _table$recordOrder$le : 0,
5280
+ rowCount: ((_table$recordOrder = table.recordOrder) === null || _table$recordOrder === void 0 ? void 0 : _table$recordOrder.length) ?? 0,
5239
5281
  columnCount: table.fieldOrder.length,
5240
5282
  rowData: {},
5241
5283
  columnData: {}
5242
5284
  };
5243
- tableNameMap[table.name] = table.id;
5285
+ addEngineBaseTableNameMappings(tableNameMap, table, formulaTableNames);
5244
5286
  }
5245
5287
  allUnitData[unitId] = baseData;
5246
5288
  unitStylesData[unitId] = new _univerjs_core.Styles();
@@ -5278,7 +5320,7 @@ let FormulaDataModel = class FormulaDataModel extends _univerjs_core.Disposable
5278
5320
  return rowData;
5279
5321
  }
5280
5322
  updateFormulaData(unitId, sheetId, cellValue) {
5281
- var _this$_univerInstance, _formulaData$unitId$s, _formulaData$unitId;
5323
+ var _this$_univerInstance, _formulaData$unitId;
5282
5324
  const cellMatrix = new _univerjs_core.ObjectMatrix(cellValue);
5283
5325
  const newSheetFormulaDataMatrix = new _univerjs_core.ObjectMatrix();
5284
5326
  const worksheetCellMatrix = (_this$_univerInstance = this._univerInstanceService.getUnit(unitId)) === null || _this$_univerInstance === void 0 || (_this$_univerInstance = _this$_univerInstance.getSheetBySheetId(sheetId)) === null || _this$_univerInstance === void 0 ? void 0 : _this$_univerInstance.getCellMatrix();
@@ -5313,7 +5355,7 @@ let FormulaDataModel = class FormulaDataModel extends _univerjs_core.Disposable
5313
5355
  const formulaData = {};
5314
5356
  initSheetFormulaData(formulaData, unitId, sheetId, sharedFormulaCellMatrix);
5315
5357
  const deleteFormulaIdMap = /* @__PURE__ */ new Map();
5316
- const sheetFormulaDataMatrix = new _univerjs_core.ObjectMatrix((_formulaData$unitId$s = (_formulaData$unitId = formulaData[unitId]) === null || _formulaData$unitId === void 0 ? void 0 : _formulaData$unitId[sheetId]) !== null && _formulaData$unitId$s !== void 0 ? _formulaData$unitId$s : {});
5358
+ const sheetFormulaDataMatrix = new _univerjs_core.ObjectMatrix(((_formulaData$unitId = formulaData[unitId]) === null || _formulaData$unitId === void 0 ? void 0 : _formulaData$unitId[sheetId]) ?? {});
5317
5359
  cellMatrix.forValue((r, c, cell) => {
5318
5360
  var _worksheetCellMatrix$;
5319
5361
  if (!(0, _univerjs_core.isFormulaId)(worksheetCellMatrix === null || worksheetCellMatrix === void 0 || (_worksheetCellMatrix$ = worksheetCellMatrix.getValue(r, c)) === null || _worksheetCellMatrix$ === void 0 ? void 0 : _worksheetCellMatrix$.si) && !(0, _univerjs_core.isFormulaId)(cell === null || cell === void 0 ? void 0 : cell.si)) return;
@@ -5510,7 +5552,7 @@ let FormulaDataModel = class FormulaDataModel extends _univerjs_core.Disposable
5510
5552
  if ((0, _univerjs_core.isFormulaString)(cell === null || cell === void 0 ? void 0 : cell.f) && (0, _univerjs_core.isFormulaId)(formulaId)) formulaIds.add(String(formulaId));
5511
5553
  });
5512
5554
  cellMatrix.forValue((row, column, cell) => {
5513
- var _arrayFormulaRangeMat, _this$_arrayFormulaRa7, _arrayFormulaCellData, _this$_arrayFormulaCe5;
5555
+ var _this$_arrayFormulaRa7, _this$_arrayFormulaCe5;
5514
5556
  const ref = cell === null || cell === void 0 ? void 0 : cell.ref;
5515
5557
  const formula = cell === null || cell === void 0 ? void 0 : cell.f;
5516
5558
  const formulaId = cell === null || cell === void 0 ? void 0 : cell.si;
@@ -5522,8 +5564,8 @@ let FormulaDataModel = class FormulaDataModel extends _univerjs_core.Disposable
5522
5564
  if (range.startRow === row && range.endRow === row && range.startColumn === column && range.endColumn === column && !isArrayConstantFormula(formula)) return true;
5523
5565
  if (!this._arrayFormulaRange[unitId]) this._arrayFormulaRange[unitId] = {};
5524
5566
  if (!this._arrayFormulaCellData[unitId]) this._arrayFormulaCellData[unitId] = {};
5525
- (_arrayFormulaRangeMat = arrayFormulaRangeMatrix) !== null && _arrayFormulaRangeMat !== void 0 || (arrayFormulaRangeMatrix = new _univerjs_core.ObjectMatrix((_this$_arrayFormulaRa7 = this._arrayFormulaRange[unitId]) === null || _this$_arrayFormulaRa7 === void 0 ? void 0 : _this$_arrayFormulaRa7[sheetId]));
5526
- (_arrayFormulaCellData = arrayFormulaCellDataMatrix) !== null && _arrayFormulaCellData !== void 0 || (arrayFormulaCellDataMatrix = new _univerjs_core.ObjectMatrix((_this$_arrayFormulaCe5 = this._arrayFormulaCellData[unitId]) === null || _this$_arrayFormulaCe5 === void 0 ? void 0 : _this$_arrayFormulaCe5[sheetId]));
5567
+ arrayFormulaRangeMatrix ??= new _univerjs_core.ObjectMatrix((_this$_arrayFormulaRa7 = this._arrayFormulaRange[unitId]) === null || _this$_arrayFormulaRa7 === void 0 ? void 0 : _this$_arrayFormulaRa7[sheetId]);
5568
+ arrayFormulaCellDataMatrix ??= new _univerjs_core.ObjectMatrix((_this$_arrayFormulaCe5 = this._arrayFormulaCellData[unitId]) === null || _this$_arrayFormulaCe5 === void 0 ? void 0 : _this$_arrayFormulaCe5[sheetId]);
5527
5569
  if (arrayFormulaRangeMatrix.getValue(row, column) == null) arrayFormulaRangeMatrix.setValue(row, column, range);
5528
5570
  for (let r = range.startRow; r <= range.endRow; r++) for (let c = range.startColumn; c <= range.endColumn; c++) {
5529
5571
  if (arrayFormulaCellDataMatrix.getValue(r, c) != null) continue;
@@ -5584,31 +5626,47 @@ function initSheetFormulaData(formulaData, unitId, sheetId, cellMatrix) {
5584
5626
  return { [unitId]: { [sheetId]: newSheetFormulaData } };
5585
5627
  }
5586
5628
  const BASE_LEGACY_FIELD_REF_PATTERN = /\{([^}]+)\}/g;
5587
- const BASE_TABLE_FIELD_REF_PATTERN = /\b([A-Z_]\w*)\[([^\]]+)\]/gi;
5588
- const BASE_BRACKET_FIELD_REF_PATTERN = /(^|[^A-Za-z0-9_\]\[])\[([^\]]+)\]/g;
5629
+ const BASE_TABLE_SCOPED_FIELD_REF_PATTERN = /\b([A-Z_][\w.]*)\[\[\s*#(This Row|Data)\s*\],\s*\[([^\]]+)\]\]/gi;
5630
+ const BASE_TABLE_CURRENT_ROW_FIELD_REF_PATTERN = /\b([A-Z_][\w.]*)\[@\[([^\]]+)\]\]/gi;
5631
+ const BASE_TABLE_FIELD_REF_PATTERN = /\b([A-Z_][\w.]*)\[([^\[\]#]+)\]/gi;
5632
+ const BASE_SCOPED_FIELD_REF_PATTERN = /(^|[^\w\[])\[\[\s*#(This Row|Data)\s*\],\s*\[([^\]]+)\]\]/gi;
5633
+ const BASE_CURRENT_ROW_FIELD_REF_PATTERN = /(^|[^\w\[])\[@\[([^\]]+)\]\](?!\])/g;
5634
+ const BASE_BRACKET_FIELD_REF_PATTERN = /(^|[^\w\[])\[@?([^\[\]#]+)\](?!\])/g;
5589
5635
  const BASE_EXTERNAL_A1_REF_PATTERN = /(?:'\[[^\]]+\](?:[^']|'')+'|\[[^\]]+\][^\s'!]+)!\$?[A-Z]{1,3}\$?\d+(?::\$?[A-Z]{1,3}\$?\d+)?/gi;
5590
5636
  const BASE_EXTERNAL_STRUCTURED_REFERENCE_PREFIX = /(?:'((?:[^']|'')+)'|\[[^\]]+\]|[A-Za-z0-9_.-]+)![^\s!\[\]]+\[/g;
5591
- function normalizeBaseFormulaForEngine(formula, currentTable, snapshot) {
5637
+ function normalizeBaseFormulaForEngine(formula, currentTable, snapshot, formulaTableNames) {
5592
5638
  const refs = [];
5593
5639
  const hold = (ref) => {
5594
5640
  return `__BASE_FORMULA_REF_${refs.push(ref) - 1}__`;
5595
5641
  };
5596
- return protectBaseExternalReferences(formula, hold).replace(BASE_LEGACY_FIELD_REF_PATTERN, (_match, fieldName) => hold(createEngineThisRowRef(currentTable, fieldName, snapshot))).replace(BASE_TABLE_FIELD_REF_PATTERN, (_match, sourceTableName, fieldName) => {
5597
- const targetTable = resolveBaseFormulaTable(sourceTableName, currentTable, snapshot);
5598
- return targetTable ? hold(createEngineThisRowRef(targetTable, fieldName, snapshot)) : `${sourceTableName}[${fieldName}]`;
5599
- }).replace(BASE_BRACKET_FIELD_REF_PATTERN, (_match, prefix, fieldName) => `${prefix}${hold(createEngineThisRowRef(currentTable, fieldName, snapshot))}`).replace(/__BASE_FORMULA_REF_(\d+)__/g, (_match, index) => {
5600
- var _refs$Number;
5601
- return (_refs$Number = refs[Number(index)]) !== null && _refs$Number !== void 0 ? _refs$Number : "";
5602
- });
5642
+ return protectBaseFormulaParts(formula, hold).replace(BASE_LEGACY_FIELD_REF_PATTERN, (_match, fieldName) => hold(createEngineThisRowRef(currentTable, fieldName, formulaTableNames))).replace(BASE_TABLE_SCOPED_FIELD_REF_PATTERN, (_match, sourceTableName, scope, fieldName) => {
5643
+ const targetTable = resolveBaseFormulaTable(sourceTableName, currentTable, snapshot, formulaTableNames);
5644
+ if (!targetTable) return `${sourceTableName}[[#${scope}],[${fieldName}]]`;
5645
+ return hold(scope.toLowerCase() === "data" ? createEngineColumnRef(targetTable, fieldName, formulaTableNames) : createEngineThisRowRef(targetTable, fieldName, formulaTableNames));
5646
+ }).replace(BASE_TABLE_CURRENT_ROW_FIELD_REF_PATTERN, (_match, sourceTableName, fieldName) => {
5647
+ const targetTable = resolveBaseFormulaTable(sourceTableName, currentTable, snapshot, formulaTableNames);
5648
+ return targetTable ? hold(createEngineThisRowRef(targetTable, fieldName, formulaTableNames)) : `${sourceTableName}[@[${fieldName}]]`;
5649
+ }).replace(BASE_SCOPED_FIELD_REF_PATTERN, (_match, prefix, scope, fieldName) => `${prefix}${hold(scope.toLowerCase() === "data" ? createEngineColumnRef(currentTable, fieldName, formulaTableNames) : createEngineThisRowRef(currentTable, fieldName, formulaTableNames))}`).replace(BASE_CURRENT_ROW_FIELD_REF_PATTERN, (_match, prefix, fieldName) => `${prefix}${hold(createEngineThisRowRef(currentTable, fieldName, formulaTableNames))}`).replace(BASE_TABLE_FIELD_REF_PATTERN, (_match, sourceTableName, fieldName) => {
5650
+ const targetTable = resolveBaseFormulaTable(sourceTableName, currentTable, snapshot, formulaTableNames);
5651
+ if (targetTable) return hold(createEngineColumnRef(targetTable, fieldName, formulaTableNames));
5652
+ return `${sourceTableName}[${fieldName}]`;
5653
+ }).replace(BASE_BRACKET_FIELD_REF_PATTERN, (_match, prefix, fieldName) => `${prefix}${hold(createEngineThisRowRef(currentTable, fieldName, formulaTableNames))}`).replace(/__BASE_FORMULA_REF_(\d+)__/g, (_match, index) => refs[Number(index)] ?? "");
5603
5654
  }
5604
5655
  function protectBaseExternalReferences(formula, replace) {
5605
5656
  return protectBaseExternalStructuredReferences(formula.replace(BASE_EXTERNAL_A1_REF_PATTERN, (reference, offset) => isInsideBaseFormulaString(formula, offset) ? reference : replace(reference)), replace);
5606
5657
  }
5658
+ function protectBaseFormulaParts(formula, replace) {
5659
+ return protectBaseFormulaStrings(protectBaseExternalReferences(formula, replace), replace);
5660
+ }
5661
+ function protectBaseFormulaStrings(formula, replace) {
5662
+ return formula.replace(/"(?:""|[^"])*"/g, replace);
5663
+ }
5607
5664
  function protectBaseExternalStructuredReferences(formula, replace) {
5608
5665
  const spans = [];
5609
5666
  BASE_EXTERNAL_STRUCTURED_REFERENCE_PREFIX.lastIndex = 0;
5610
- let match;
5611
- while ((match = BASE_EXTERNAL_STRUCTURED_REFERENCE_PREFIX.exec(formula)) != null) {
5667
+ while (true) {
5668
+ const match = BASE_EXTERNAL_STRUCTURED_REFERENCE_PREFIX.exec(formula);
5669
+ if (match == null) break;
5612
5670
  if (isInsideBaseFormulaString(formula, match.index)) continue;
5613
5671
  const openBracket = BASE_EXTERNAL_STRUCTURED_REFERENCE_PREFIX.lastIndex - 1;
5614
5672
  let depth = 0;
@@ -5648,17 +5706,20 @@ function isInsideBaseFormulaString(formula, position) {
5648
5706
  }
5649
5707
  return inString;
5650
5708
  }
5651
- function createEngineThisRowRef(table, fieldName, snapshot) {
5652
- return `${getEngineBaseTableName(table, snapshot)}[[#This Row],[${fieldName}]]`;
5709
+ function createEngineThisRowRef(table, fieldName, formulaTableNames) {
5710
+ return `${formulaTableNames.get(table.id) ?? (0, _univerjs_core.getBaseFormulaTableName)(table, { tables: { [table.id]: table } })}[[#This Row],[${fieldName}]]`;
5653
5711
  }
5654
- function getEngineBaseTableName(table, snapshot) {
5655
- const tables = Object.values(snapshot.tables);
5656
- let sameNameCount = 0;
5657
- for (let i = 0; i < tables.length; i++) if (tables[i].name === table.name) {
5658
- sameNameCount++;
5659
- if (sameNameCount > 1) break;
5660
- }
5661
- return sameNameCount === 1 ? table.name : table.id;
5712
+ function createEngineColumnRef(table, fieldName, formulaTableNames) {
5713
+ return `${formulaTableNames.get(table.id) ?? (0, _univerjs_core.getBaseFormulaTableName)(table, { tables: { [table.id]: table } })}[[#Data],[${fieldName}]]`;
5714
+ }
5715
+ function addEngineBaseTableNameMappings(tableNameMap, table, formulaTableNames) {
5716
+ tableNameMap[formulaTableNames.get(table.id) ?? table.name] = table.id;
5717
+ }
5718
+ function createStableExcelTableName(tableId) {
5719
+ return `_T_${Array.from(tableId, (character) => {
5720
+ var _character$codePointA;
5721
+ return /[A-Za-z0-9]/.test(character) ? character : `_x${((_character$codePointA = character.codePointAt(0)) === null || _character$codePointA === void 0 ? void 0 : _character$codePointA.toString(16)) ?? "0"}_`;
5722
+ }).join("")}`;
5662
5723
  }
5663
5724
  function buildBaseRuntimeCellData(table) {
5664
5725
  const cellData = { ...table.cellData };
@@ -5675,8 +5736,7 @@ function buildBaseRuntimeCellData(table) {
5675
5736
  if (table.records[recordId]) recordOrder.push(recordId);
5676
5737
  }
5677
5738
  } else {
5678
- var _table$records;
5679
- const allRecords = Object.values((_table$records = table.records) !== null && _table$records !== void 0 ? _table$records : {});
5739
+ const allRecords = Object.values(table.records ?? {});
5680
5740
  const records = [];
5681
5741
  for (let i = 0; i < allRecords.length; i++) {
5682
5742
  const record = allRecords[i];
@@ -5695,9 +5755,8 @@ function buildBaseRuntimeCellData(table) {
5695
5755
  if (!record) continue;
5696
5756
  cellData[row] = { ...cellData[row] };
5697
5757
  for (let col = 0; col < fieldOrder.length; col++) {
5698
- var _record$values;
5699
5758
  const fieldId = fieldOrder[col];
5700
- if (!Object.prototype.hasOwnProperty.call((_record$values = record.values) !== null && _record$values !== void 0 ? _record$values : {}, fieldId)) continue;
5759
+ if (!Object.prototype.hasOwnProperty.call(record.values ?? {}, fieldId)) continue;
5701
5760
  cellData[row][col] = toBaseRuntimeCellData(record.values[fieldId], table.fields[fieldId]);
5702
5761
  }
5703
5762
  }
@@ -5714,10 +5773,9 @@ function toBaseRuntimeCellData(value, field) {
5714
5773
  t: _univerjs_core.CellValueType.STRING
5715
5774
  };
5716
5775
  if ((field === null || field === void 0 ? void 0 : field.type) === "link" && value && typeof value === "object") {
5717
- var _ref, _link$text;
5718
5776
  const link = value;
5719
5777
  return {
5720
- v: String((_ref = (_link$text = link.text) !== null && _link$text !== void 0 ? _link$text : link.url) !== null && _ref !== void 0 ? _ref : ""),
5778
+ v: String(link.text ?? link.url ?? ""),
5721
5779
  t: _univerjs_core.CellValueType.STRING
5722
5780
  };
5723
5781
  }
@@ -5731,8 +5789,7 @@ function toBaseRuntimeCellData(value, field) {
5731
5789
  };
5732
5790
  }
5733
5791
  function normalizeBaseCellData(cell) {
5734
- var _cell$v;
5735
- const type = inferBaseRuntimeCellType((_cell$v = cell.v) !== null && _cell$v !== void 0 ? _cell$v : null);
5792
+ const type = inferBaseRuntimeCellType(cell.v ?? null);
5736
5793
  return {
5737
5794
  ...cell,
5738
5795
  t: type
@@ -5750,11 +5807,13 @@ function isArrayConstantFormula(formula) {
5750
5807
  function isBaseCellData(value) {
5751
5808
  return !!value && typeof value === "object" && (Object.prototype.hasOwnProperty.call(value, "v") || Object.prototype.hasOwnProperty.call(value, "t") || Object.prototype.hasOwnProperty.call(value, "p") || Object.prototype.hasOwnProperty.call(value, "f") || Object.prototype.hasOwnProperty.call(value, "si"));
5752
5809
  }
5753
- function resolveBaseFormulaTable(tableName, currentTable, snapshot) {
5754
- if (!tableName || tableName === "table" || tableName === currentTable.id || tableName === currentTable.name) return currentTable;
5755
- const byId = snapshot.tables[tableName];
5756
- if (byId) return byId;
5757
- const matches = Object.values(snapshot.tables).filter((table) => table.name === tableName);
5810
+ function resolveBaseFormulaTable(tableName, currentTable, snapshot, formulaTableNames) {
5811
+ if (!tableName) return currentTable;
5812
+ const normalizedName = tableName.toLowerCase();
5813
+ const matches = Object.values(snapshot.tables).filter((table) => {
5814
+ var _formulaTableNames$ge;
5815
+ return table.id.toLowerCase() === normalizedName || table.name.toLowerCase() === normalizedName || ((_formulaTableNames$ge = formulaTableNames.get(table.id)) === null || _formulaTableNames$ge === void 0 ? void 0 : _formulaTableNames$ge.toLowerCase()) === normalizedName || createStableExcelTableName(table.id).toLowerCase() === normalizedName;
5816
+ });
5758
5817
  return matches.length === 1 ? matches[0] : void 0;
5759
5818
  }
5760
5819
 
@@ -5784,9 +5843,8 @@ var SheetRowFilteredService = class extends _univerjs_core.Disposable {
5784
5843
  this._getRowFilteredCallback = callback;
5785
5844
  }
5786
5845
  getRowFiltered(unitId, subUnitId, row) {
5787
- var _this$_getRowFiltered;
5788
5846
  if (!this._getRowFilteredCallback) return false;
5789
- return (_this$_getRowFiltered = this._getRowFilteredCallback(unitId, subUnitId, row)) !== null && _this$_getRowFiltered !== void 0 ? _this$_getRowFiltered : false;
5847
+ return this._getRowFilteredCallback(unitId, subUnitId, row) ?? false;
5790
5848
  }
5791
5849
  };
5792
5850
  const ISheetRowFilteredService = (0, _univerjs_core.createIdentifier)("univer.formula.sheet-row-filtered.service");
@@ -5919,7 +5977,6 @@ let FormulaCurrentConfigService = class FormulaCurrentConfigService extends _uni
5919
5977
  return this._localeService.getCurrentLocale();
5920
5978
  }
5921
5979
  getSheetsInfo() {
5922
- var _this$_sheetIdToNameM;
5923
5980
  const workbook = this._univerInstanceService.getCurrentUnitOfType(_univerjs_core.UniverInstanceType.UNIVER_SHEET);
5924
5981
  if (!workbook) return {
5925
5982
  sheetOrder: [],
@@ -5928,7 +5985,7 @@ let FormulaCurrentConfigService = class FormulaCurrentConfigService extends _uni
5928
5985
  const { id, sheetOrder } = workbook.getSnapshot();
5929
5986
  return {
5930
5987
  sheetOrder,
5931
- sheetNameMap: (_this$_sheetIdToNameM = this._sheetIdToNameMap[id]) !== null && _this$_sheetIdToNameM !== void 0 ? _this$_sheetIdToNameM : {}
5988
+ sheetNameMap: this._sheetIdToNameMap[id] ?? {}
5932
5989
  };
5933
5990
  }
5934
5991
  getSheetRowColumnCount(unitId, sheetId) {
@@ -5955,7 +6012,6 @@ let FormulaCurrentConfigService = class FormulaCurrentConfigService extends _uni
5955
6012
  return filteredOutRows;
5956
6013
  }
5957
6014
  load(config) {
5958
- var _config$externalRefer;
5959
6015
  this._calculationGeneration++;
5960
6016
  if (config.allUnitData && config.unitSheetNameMap && config.unitStylesData) {
5961
6017
  this._unitData = config.allUnitData;
@@ -5981,7 +6037,7 @@ let FormulaCurrentConfigService = class FormulaCurrentConfigService extends _uni
5981
6037
  this._dirtySuperTableMap = config.dirtySuperTableMap || {};
5982
6038
  this._dirtyUnitFeatureMap = config.dirtyUnitFeatureMap;
5983
6039
  this._dirtyUnitOtherFormulaMap = config.dirtyUnitOtherFormulaMap;
5984
- this._externalReferences = (_config$externalRefer = config.externalReferences) !== null && _config$externalRefer !== void 0 ? _config$externalRefer : {};
6040
+ this._externalReferences = config.externalReferences ?? {};
5985
6041
  this._excludedCell = config.excludedCell;
5986
6042
  this._mergeNameMap(this._sheetNameMap, this._dirtyNameMap);
5987
6043
  }
@@ -6045,13 +6101,12 @@ let FormulaCurrentConfigService = class FormulaCurrentConfigService extends _uni
6045
6101
  });
6046
6102
  }
6047
6103
  _loadSheetData() {
6048
- var _workbook$getUnitId, _worksheet$getSheetId;
6049
6104
  const workbook = this._univerInstanceService.getCurrentUnitOfType(_univerjs_core.UniverInstanceType.UNIVER_SHEET);
6050
6105
  const worksheet = workbook === null || workbook === void 0 ? void 0 : workbook.getActiveSheet();
6051
6106
  const base = workbook ? null : this._univerInstanceService.getCurrentUnitOfType(_univerjs_core.UniverInstanceType.UNIVER_BASE);
6052
6107
  const table = base ? getFirstBaseTable(base.getSnapshot().tables, base.getSnapshot().tableOrder) : null;
6053
- this._executeUnitId = (_workbook$getUnitId = workbook === null || workbook === void 0 ? void 0 : workbook.getUnitId()) !== null && _workbook$getUnitId !== void 0 ? _workbook$getUnitId : base === null || base === void 0 ? void 0 : base.getUnitId();
6054
- this._executeSubUnitId = (_worksheet$getSheetId = worksheet === null || worksheet === void 0 ? void 0 : worksheet.getSheetId()) !== null && _worksheet$getSheetId !== void 0 ? _worksheet$getSheetId : table === null || table === void 0 ? void 0 : table.id;
6108
+ this._executeUnitId = (workbook === null || workbook === void 0 ? void 0 : workbook.getUnitId()) ?? (base === null || base === void 0 ? void 0 : base.getUnitId());
6109
+ this._executeSubUnitId = (worksheet === null || worksheet === void 0 ? void 0 : worksheet.getSheetId()) ?? (table === null || table === void 0 ? void 0 : table.id);
6055
6110
  return this._formulaDataModel.getCalculateData();
6056
6111
  }
6057
6112
  /**
@@ -6083,29 +6138,334 @@ FormulaCurrentConfigService = __decorate([
6083
6138
  __decorateParam(3, (0, _univerjs_core.Inject)(ISheetRowFilteredService))
6084
6139
  ], FormulaCurrentConfigService);
6085
6140
  function getFirstBaseTable(tables, tableOrder) {
6086
- var _Object$values$;
6087
6141
  for (const tableId of tableOrder) {
6088
6142
  const table = tables[tableId];
6089
6143
  if (table) return table;
6090
6144
  }
6091
- return (_Object$values$ = Object.values(tables)[0]) !== null && _Object$values$ !== void 0 ? _Object$values$ : null;
6145
+ return Object.values(tables)[0] ?? null;
6092
6146
  }
6093
6147
  const IFormulaCurrentConfigService = (0, _univerjs_core.createIdentifier)("univer.formula.current-data.service");
6094
6148
 
6149
+ //#endregion
6150
+ //#region src/engine/ast-node/node-type.ts
6151
+ const NODE_ORDER_MAP = /* @__PURE__ */ new Map([
6152
+ [1, 7],
6153
+ [2, 9],
6154
+ [3, 8],
6155
+ [4, 6],
6156
+ [5, 1],
6157
+ [6, 2],
6158
+ [9, 10],
6159
+ [10, 3],
6160
+ [11, 4],
6161
+ [12, 5]
6162
+ ]);
6163
+
6164
+ //#endregion
6165
+ //#region src/engine/ast-node/base-ast-node.ts
6166
+ var BaseAstNode = class {
6167
+ constructor(_token) {
6168
+ this._token = _token;
6169
+ _defineProperty(this, "_children", []);
6170
+ _defineProperty(this, "_definedNames", void 0);
6171
+ _defineProperty(this, "_parent", void 0);
6172
+ _defineProperty(this, "_valueObject", void 0);
6173
+ _defineProperty(this, "_calculateState", false);
6174
+ _defineProperty(this, "_async", false);
6175
+ _defineProperty(this, "_address", false);
6176
+ _defineProperty(this, "_isForcedCalculateFunction", false);
6177
+ }
6178
+ dispose() {
6179
+ var _this$_valueObject;
6180
+ this._children.forEach((node) => {
6181
+ node.dispose();
6182
+ });
6183
+ (_this$_valueObject = this._valueObject) === null || _this$_valueObject === void 0 || _this$_valueObject.dispose();
6184
+ this._valueObject = null;
6185
+ this._children = [];
6186
+ this._definedNames = null;
6187
+ this._parent = null;
6188
+ }
6189
+ get nodeType() {
6190
+ return 8;
6191
+ }
6192
+ resetCalculationState() {
6193
+ this._children.forEach((node) => {
6194
+ node.resetCalculationState();
6195
+ });
6196
+ this._valueObject = null;
6197
+ this._calculateState = false;
6198
+ }
6199
+ isAsync() {
6200
+ return this._async;
6201
+ }
6202
+ isAddress() {
6203
+ return this._address;
6204
+ }
6205
+ isForcedCalculateFunction() {
6206
+ return this._isForcedCalculateFunction;
6207
+ }
6208
+ setAsync() {
6209
+ this._async = true;
6210
+ }
6211
+ setAddress() {
6212
+ this._address = true;
6213
+ }
6214
+ getParent() {
6215
+ return this._parent;
6216
+ }
6217
+ setParent(node) {
6218
+ this._parent = node;
6219
+ node.addChildren(this);
6220
+ }
6221
+ setForcedCalculateFunction() {
6222
+ this._isForcedCalculateFunction = true;
6223
+ }
6224
+ getChildren() {
6225
+ return this._children;
6226
+ }
6227
+ addChildren(...astNode) {
6228
+ this._children.push(...astNode);
6229
+ }
6230
+ getToken() {
6231
+ return this._token;
6232
+ }
6233
+ setValue(value) {
6234
+ this._valueObject = value;
6235
+ }
6236
+ getValue() {
6237
+ return this._valueObject;
6238
+ }
6239
+ preservesLazyIfReferenceArray(_child) {
6240
+ return false;
6241
+ }
6242
+ isCalculated() {
6243
+ return this._calculateState;
6244
+ }
6245
+ setCalculated() {
6246
+ this._calculateState = true;
6247
+ }
6248
+ execute() {}
6249
+ setNotEmpty(state = true) {}
6250
+ async executeAsync() {
6251
+ return Promise.resolve(0);
6252
+ }
6253
+ serialize() {
6254
+ const token = this.getToken();
6255
+ const children = this.getChildren();
6256
+ const childrenSerialization = [];
6257
+ const childrenCount = children.length;
6258
+ for (let i = 0; i < childrenCount; i++) {
6259
+ const item = children[i];
6260
+ childrenSerialization.push(item.serialize());
6261
+ }
6262
+ const result = {
6263
+ token,
6264
+ nodeType: this.nodeType
6265
+ };
6266
+ if (childrenCount > 0) result.children = childrenSerialization;
6267
+ return result;
6268
+ }
6269
+ hasDefinedName(definedName) {
6270
+ var _this$_definedNames;
6271
+ return ((_this$_definedNames = this._definedNames) === null || _this$_definedNames === void 0 ? void 0 : _this$_definedNames.includes(definedName)) || false;
6272
+ }
6273
+ setDefinedNames(definedNames) {
6274
+ this._definedNames = definedNames;
6275
+ }
6276
+ getDefinedNames() {
6277
+ return this._definedNames;
6278
+ }
6279
+ };
6280
+ var ErrorNode = class ErrorNode extends BaseAstNode {
6281
+ constructor(errorType) {
6282
+ super(errorType);
6283
+ _defineProperty(this, "_errorValueObject", void 0);
6284
+ this._errorValueObject = ErrorValueObject.create(errorType);
6285
+ }
6286
+ get nodeType() {
6287
+ return 7;
6288
+ }
6289
+ static create(errorType) {
6290
+ return new ErrorNode(errorType);
6291
+ }
6292
+ getValue() {
6293
+ return this._errorValueObject;
6294
+ }
6295
+ };
6296
+
6297
+ //#endregion
6298
+ //#region src/engine/utils/generate-ast-node.ts
6299
+ const FORMULA_CACHE_LRU_COUNT$1 = 5e3;
6300
+ const FORMULA_AST_CACHE = new FormulaAstLRU(FORMULA_CACHE_LRU_COUNT$1);
6301
+ const DIRTY_DEFINED_NAME_SET_CACHE = /* @__PURE__ */ new WeakMap();
6302
+ const DIRTY_SUPER_TABLE_PATTERN_CACHE = /* @__PURE__ */ new WeakMap();
6303
+ function generateAstNode(unitId, formulaString, lexer, astTreeBuilder, currentConfigService, subUnitId, definedNameRefOffsetX = 0, definedNameRefOffsetY = 0) {
6304
+ if (subUnitId) {
6305
+ currentConfigService.setExecuteUnitId(unitId);
6306
+ currentConfigService.setExecuteSubUnitId(subUnitId);
6307
+ }
6308
+ const cacheKey = `${unitId}:${subUnitId ?? currentConfigService.getExecuteSubUnitId() ?? ""}:${definedNameRefOffsetX}:${definedNameRefOffsetY}:${formulaString}`;
6309
+ let astNode = FORMULA_AST_CACHE.get(cacheKey);
6310
+ if (!(checkIsChangedByDefinedName(unitId, formulaString, currentConfigService) || checkIsChangedBySuperTable(unitId, formulaString, currentConfigService)) && astNode && !isDirtyDefinedForNode(astNode, currentConfigService, unitId)) return astNode;
6311
+ const lexerNode = lexer.treeBuilder(formulaString, true, unitId, definedNameRefOffsetX, definedNameRefOffsetY);
6312
+ if (ERROR_TYPE_SET.has(lexerNode)) return ErrorNode.create(lexerNode);
6313
+ astNode = astTreeBuilder.parse(lexerNode);
6314
+ if (astNode == null) {
6315
+ console.error("generateAstNode astNode is null");
6316
+ return ErrorNode.create(lexerNode);
6317
+ }
6318
+ FORMULA_AST_CACHE.set(cacheKey, astNode);
6319
+ return astNode;
6320
+ }
6321
+ function checkIsChangedByDefinedName(unitId, formula, currentConfigService) {
6322
+ const unitDefinedNameMap = currentConfigService.getDirtyDefinedNameMap()[unitId];
6323
+ if (unitDefinedNameMap == null) return false;
6324
+ return getNormalizedDirtyDefinedNameSet(unitDefinedNameMap).has(normalizeFormulaText(formula));
6325
+ }
6326
+ function normalizeFormulaText(formula) {
6327
+ return formula.startsWith("=") ? formula.slice(1) : formula;
6328
+ }
6329
+ function checkIsChangedBySuperTable(unitId, formula, currentConfigService) {
6330
+ var _currentConfigService;
6331
+ const getDirtySuperTableMap = (_currentConfigService = currentConfigService.getDirtySuperTableMap) === null || _currentConfigService === void 0 ? void 0 : _currentConfigService.bind(currentConfigService);
6332
+ const changedSuperTableMap = getDirtySuperTableMap === null || getDirtySuperTableMap === void 0 ? void 0 : getDirtySuperTableMap();
6333
+ const unitSuperTableMap = changedSuperTableMap === null || changedSuperTableMap === void 0 ? void 0 : changedSuperTableMap[unitId];
6334
+ if (unitSuperTableMap == null) return false;
6335
+ const tableReferencePattern = getDirtySuperTableReferencePattern(unitSuperTableMap);
6336
+ return (tableReferencePattern === null || tableReferencePattern === void 0 ? void 0 : tableReferencePattern.test(normalizeFormulaText(formula))) ?? false;
6337
+ }
6338
+ function getNormalizedDirtyDefinedNameSet(unitDefinedNameMap) {
6339
+ let normalizedNameSet = DIRTY_DEFINED_NAME_SET_CACHE.get(unitDefinedNameMap);
6340
+ if (normalizedNameSet == null) {
6341
+ normalizedNameSet = new Set(Object.keys(unitDefinedNameMap).map(normalizeFormulaText));
6342
+ DIRTY_DEFINED_NAME_SET_CACHE.set(unitDefinedNameMap, normalizedNameSet);
6343
+ }
6344
+ return normalizedNameSet;
6345
+ }
6346
+ function getDirtySuperTableReferencePattern(unitSuperTableMap) {
6347
+ let tableReferencePattern = DIRTY_SUPER_TABLE_PATTERN_CACHE.get(unitSuperTableMap);
6348
+ if (tableReferencePattern === void 0) {
6349
+ const tableNames = Object.keys(unitSuperTableMap).filter((tableName) => tableName.length > 0);
6350
+ tableReferencePattern = tableNames.length > 0 ? _univerjs_core.regexp.createRegExpFromSafeFragment(`(^|[^A-Za-z0-9_])${_univerjs_core.regexp.or(...tableNames)}(\\s*\\[|$|[^A-Za-z0-9_])`, "i") : null;
6351
+ DIRTY_SUPER_TABLE_PATTERN_CACHE.set(unitSuperTableMap, tableReferencePattern);
6352
+ }
6353
+ return tableReferencePattern;
6354
+ }
6355
+ function isDirtyDefinedForNode(node, currentConfigService, unitId) {
6356
+ const definedNameMap = currentConfigService.getDirtyDefinedNameMap();
6357
+ const executeUnitId = unitId;
6358
+ if (executeUnitId != null && definedNameMap[executeUnitId] != null) {
6359
+ const names = Object.keys(definedNameMap[executeUnitId]);
6360
+ for (let i = 0, len = names.length; i < len; i++) {
6361
+ const name = names[i];
6362
+ if (node.hasDefinedName(name)) return true;
6363
+ }
6364
+ }
6365
+ return false;
6366
+ }
6367
+ function includeDefinedName(tree, node, currentConfigService) {
6368
+ /**
6369
+ * Detect whether the dirty map contains a defined name.
6370
+ */
6371
+ if (node != null) {
6372
+ if (isDirtyDefinedForNode(node, currentConfigService, tree.unitId)) return true;
6373
+ }
6374
+ return false;
6375
+ }
6376
+
6377
+ //#endregion
6378
+ //#region src/services/function.service.ts
6379
+ const IFunctionService = (0, _univerjs_core.createIdentifier)("univer.formula-function.service");
6380
+ var FunctionService = class extends _univerjs_core.Disposable {
6381
+ constructor(..._args) {
6382
+ super(..._args);
6383
+ _defineProperty(this, "_functionExecutors", /* @__PURE__ */ new Map());
6384
+ _defineProperty(this, "_functionDescriptions", /* @__PURE__ */ new Map());
6385
+ }
6386
+ dispose() {
6387
+ super.dispose();
6388
+ this._functionExecutors.clear();
6389
+ this._functionDescriptions.clear();
6390
+ }
6391
+ registerExecutors(...functions) {
6392
+ for (let i = 0; i < functions.length; i++) {
6393
+ const func = functions[i];
6394
+ this._functionExecutors.set(func.name, func);
6395
+ }
6396
+ }
6397
+ getExecutors() {
6398
+ return this._functionExecutors;
6399
+ }
6400
+ getExecutor(functionToken) {
6401
+ return this._functionExecutors.get(functionToken);
6402
+ }
6403
+ hasExecutor(functionToken) {
6404
+ return this._functionExecutors.has(functionToken);
6405
+ }
6406
+ unregisterExecutors(...functionTokens) {
6407
+ for (let i = 0; i < functionTokens.length; i++) {
6408
+ const functionToken = functionTokens[i];
6409
+ this._functionExecutors.delete(functionToken);
6410
+ }
6411
+ }
6412
+ registerDescriptions(...descriptions) {
6413
+ for (let i = 0; i < descriptions.length; i++) {
6414
+ const description = descriptions[i];
6415
+ this._functionDescriptions.set(description.functionName, description);
6416
+ }
6417
+ return (0, _univerjs_core.toDisposable)(() => {
6418
+ for (let i = 0; i < descriptions.length; i++) {
6419
+ const description = descriptions[i];
6420
+ this._functionDescriptions.delete(description.functionName);
6421
+ }
6422
+ });
6423
+ }
6424
+ getDescriptions() {
6425
+ return this._functionDescriptions;
6426
+ }
6427
+ getDescription(functionToken) {
6428
+ return this._functionDescriptions.get(functionToken);
6429
+ }
6430
+ hasDescription(functionToken) {
6431
+ return this._functionDescriptions.has(functionToken);
6432
+ }
6433
+ unregisterDescriptions(...functionTokens) {
6434
+ for (let i = 0; i < functionTokens.length; i++) {
6435
+ const functionToken = functionTokens[i];
6436
+ this._functionDescriptions.delete(functionToken);
6437
+ }
6438
+ }
6439
+ clearDescriptions() {
6440
+ this._functionDescriptions.clear();
6441
+ }
6442
+ deleteFormulaAstCacheKey(...functionToken) {
6443
+ FORMULA_AST_CACHE.forEach((_, key) => {
6444
+ functionToken.forEach((token) => {
6445
+ if (key.includes(token)) FORMULA_AST_CACHE.delete(key);
6446
+ });
6447
+ });
6448
+ }
6449
+ };
6450
+
6095
6451
  //#endregion
6096
6452
  //#region src/engine/analysis/lexer.ts
6097
6453
  let Lexer = class Lexer extends _univerjs_core.Disposable {
6098
- constructor(_definedNamesService, _lexerTreeBuilder, _formulaCurrentConfigService) {
6454
+ constructor(_definedNamesService, _lexerTreeBuilder, _formulaCurrentConfigService, _functionService) {
6099
6455
  super();
6100
6456
  this._definedNamesService = _definedNamesService;
6101
6457
  this._lexerTreeBuilder = _lexerTreeBuilder;
6102
6458
  this._formulaCurrentConfigService = _formulaCurrentConfigService;
6459
+ this._functionService = _functionService;
6103
6460
  }
6104
- treeBuilder(formulaString, transformSuffix = true, unitId) {
6461
+ treeBuilder(formulaString, transformSuffix = true, unitId, refOffsetX = 0, refOffsetY = 0) {
6105
6462
  if (this._definedNamesService.getAllDefinedNamesIsEmpty()) return this._lexerTreeBuilder.treeBuilder(formulaString, transformSuffix);
6106
6463
  return this._lexerTreeBuilder.treeBuilder(formulaString, transformSuffix, {
6107
- unitId: unitId !== null && unitId !== void 0 ? unitId : this._formulaCurrentConfigService.getExecuteUnitId(),
6464
+ unitId: unitId ?? this._formulaCurrentConfigService.getExecuteUnitId(),
6108
6465
  sheetId: this._formulaCurrentConfigService.getExecuteSubUnitId(),
6466
+ refOffsetX,
6467
+ refOffsetY,
6468
+ hasFunction: this._functionService.hasExecutor.bind(this._functionService),
6109
6469
  getValueByName: this._definedNamesService.getValueByName.bind(this._definedNamesService),
6110
6470
  getDirtyDefinedNameMap: this._formulaCurrentConfigService.getDirtyDefinedNameMap.bind(this._formulaCurrentConfigService),
6111
6471
  getSheetName: this._formulaCurrentConfigService.getSheetName.bind(this._formulaCurrentConfigService)
@@ -6115,13 +6475,13 @@ let Lexer = class Lexer extends _univerjs_core.Disposable {
6115
6475
  Lexer = __decorate([
6116
6476
  __decorateParam(0, IDefinedNamesService),
6117
6477
  __decorateParam(1, (0, _univerjs_core.Inject)(LexerTreeBuilder)),
6118
- __decorateParam(2, IFormulaCurrentConfigService)
6478
+ __decorateParam(2, IFormulaCurrentConfigService),
6479
+ __decorateParam(3, IFunctionService)
6119
6480
  ], Lexer);
6120
6481
 
6121
6482
  //#endregion
6122
6483
  //#region src/engine/utils/cell.ts
6123
6484
  function getCellValue(cell) {
6124
- var _cell$v;
6125
6485
  if (cell === null) return 0;
6126
6486
  if (cell === null || cell === void 0 ? void 0 : cell.p) {
6127
6487
  const body = cell === null || cell === void 0 ? void 0 : cell.p.body;
@@ -6129,7 +6489,7 @@ function getCellValue(cell) {
6129
6489
  const data = body.dataStream;
6130
6490
  return normalizeRichTextFormulaValue(_univerjs_core.BuildTextUtils.transform.getPlainText(data));
6131
6491
  }
6132
- return (_cell$v = cell === null || cell === void 0 ? void 0 : cell.v) !== null && _cell$v !== void 0 ? _cell$v : 0;
6492
+ return (cell === null || cell === void 0 ? void 0 : cell.v) ?? 0;
6133
6493
  }
6134
6494
  function normalizeRichTextFormulaValue(value) {
6135
6495
  return value.replace(/\r\n|\r|\n/g, "\r\n");
@@ -7295,9 +7655,8 @@ var StringValueObject = class StringValueObject extends BaseValueObject {
7295
7655
  if (cached && options && this.checkCacheByOptions(cached, options)) return cached;
7296
7656
  const instance = new StringValueObject(value);
7297
7657
  if (options === null || options === void 0 ? void 0 : options.isHyperlink) {
7298
- var _options$hyperlinkUrl;
7299
7658
  instance._isHyperlink = options.isHyperlink;
7300
- instance._hyperlinkUrl = (_options$hyperlinkUrl = options.hyperlinkUrl) !== null && _options$hyperlinkUrl !== void 0 ? _options$hyperlinkUrl : "";
7659
+ instance._hyperlinkUrl = options.hyperlinkUrl ?? "";
7301
7660
  }
7302
7661
  if (options === null || options === void 0 ? void 0 : options.isImage) {
7303
7662
  instance._isImage = options.isImage;
@@ -7838,11 +8197,16 @@ var ArrayValueObject = class ArrayValueObject extends BaseValueObject {
7838
8197
  * the sequential matching approach is only used for special matches in XLOOKUP and XMATCH.
7839
8198
  * For example, when match_mode is set to 1 and -1 for an exact match. If not found, it returns the next smaller item.
7840
8199
  */
7841
- orderSearch(valueObject, searchType = 1, isDesc = false, isFuzzyMatching = false) {
8200
+ orderSearch(valueObject, searchType = 1, isDesc = false, isFuzzyMatching = false, keepFirstNearest = false) {
7842
8201
  let result;
7843
8202
  let maxOrMin;
7844
8203
  let resultPosition;
7845
8204
  let maxOrMinPosition;
8205
+ const _isNearer = (itemValue, currentValue) => {
8206
+ const distance = itemValue.minus(valueObject).abs();
8207
+ const currentDistance = currentValue.minus(valueObject).abs();
8208
+ return keepFirstNearest ? distance.isLessThan(currentDistance).getValue() === true : distance.isLessThanOrEqual(currentDistance).getValue() === true;
8209
+ };
7846
8210
  const _handleMatch = (itemValue, row, column) => {
7847
8211
  if (itemValue == null || itemValue.isNull()) return true;
7848
8212
  let matchObject;
@@ -7859,7 +8223,7 @@ var ArrayValueObject = class ArrayValueObject extends BaseValueObject {
7859
8223
  }
7860
8224
  if (searchType === 2) {
7861
8225
  if (itemValue.isGreaterThan(valueObject).getValue() === true) {
7862
- if (maxOrMin == null || itemValue.minus(valueObject).abs().isLessThanOrEqual(maxOrMin.minus(valueObject).abs()).getValue() === true) {
8226
+ if (maxOrMin == null || _isNearer(itemValue, maxOrMin)) {
7863
8227
  maxOrMin = itemValue;
7864
8228
  maxOrMinPosition = {
7865
8229
  row,
@@ -7869,7 +8233,7 @@ var ArrayValueObject = class ArrayValueObject extends BaseValueObject {
7869
8233
  }
7870
8234
  } else if (searchType === 1) {
7871
8235
  if (itemValue.isLessThan(valueObject).getValue() === true) {
7872
- if (maxOrMin == null || itemValue.minus(valueObject).abs().isLessThanOrEqual(maxOrMin.minus(valueObject).abs()).getValue() === true) {
8236
+ if (maxOrMin == null || _isNearer(itemValue, maxOrMin)) {
7873
8237
  maxOrMin = itemValue;
7874
8238
  maxOrMinPosition = {
7875
8239
  row,
@@ -8372,11 +8736,12 @@ var ArrayValueObject = class ArrayValueObject extends BaseValueObject {
8372
8736
  const sheetId = this.getSheetId();
8373
8737
  const startRow = this.getCurrentRow();
8374
8738
  const startColumn = this.getCurrentColumn();
8739
+ const isWildcardComparison = batchOperatorType === 5 && valueObject.isString() && isWildcard(String(valueObject.getValue()));
8375
8740
  /**
8376
8741
  * If comparison operations are conducted for a single numerical value,
8377
8742
  * then retrieve the judgment from the inverted index. This enhances performance.
8378
8743
  */
8379
- if (batchOperatorType === 5 && this._useInvertedIndexCache) {
8744
+ if (batchOperatorType === 5 && this._useInvertedIndexCache && !isWildcardComparison) {
8380
8745
  const { rowsInCache, rowsNotInCache } = CELL_INVERTED_INDEX_CACHE.canUseCache(unitId, sheetId, column + startColumn, startRow, startRow + rowCount - 1);
8381
8746
  if (rowsInCache.length > 0) {
8382
8747
  if (operator === "=" && !(valueObject.isString() && isWildcard(valueObject.getValue()))) {
@@ -8605,6 +8970,7 @@ var ValueObjectFactory = class {
8605
8970
  const rawValueUpper = rawValue.toLocaleUpperCase().trim();
8606
8971
  if (ERROR_TYPE_SET.has(rawValueUpper)) return ErrorValueObject.create(rawValueUpper);
8607
8972
  if (rawValueUpper === "TRUE" || rawValueUpper === "FALSE") return createBooleanValueObjectByRawValue(rawValue);
8973
+ if (isStringWrappedByDoubleQuotes(rawValue)) return createStringValueObjectByRawValue(rawValue);
8608
8974
  if ((0, _univerjs_core.isRealNum)(rawValue) && Number(rawValue).toString() === rawValue.trim()) return NumberValueObject.create(Number(rawValue));
8609
8975
  if (!isIgnoreNumberPattern) {
8610
8976
  const { isNumberPattern, value, pattern } = stringIsNumberPattern(rawValue);
@@ -8625,8 +8991,8 @@ function isStringWrappedByDoubleQuotes(input) {
8625
8991
 
8626
8992
  //#endregion
8627
8993
  //#region src/engine/reference-object/base-reference-object.ts
8628
- const FORMULA_CACHE_LRU_COUNT$1 = 1e4;
8629
- const FORMULA_REF_TO_ARRAY_CACHE = new FormulaAstLRU(FORMULA_CACHE_LRU_COUNT$1);
8994
+ const FORMULA_CACHE_LRU_COUNT = 1e4;
8995
+ const FORMULA_REF_TO_ARRAY_CACHE = new FormulaAstLRU(FORMULA_CACHE_LRU_COUNT);
8630
8996
  var BaseReferenceObject = class extends ObjectClassType {
8631
8997
  constructor(_token) {
8632
8998
  super();
@@ -8763,6 +9129,7 @@ var BaseReferenceObject = class extends ObjectClassType {
8763
9129
  }
8764
9130
  setForcedSheetId(sheetNameMap) {
8765
9131
  var _sheetNameMap$this$ge;
9132
+ if (!this._forcedSheetName) return;
8766
9133
  this._forcedSheetId = (_sheetNameMap$this$ge = sheetNameMap[this.getUnitId()]) === null || _sheetNameMap$this$ge === void 0 ? void 0 : _sheetNameMap$this$ge[this._forcedSheetName];
8767
9134
  }
8768
9135
  setForcedSheetIdDirect(sheetId) {
@@ -8984,11 +9351,9 @@ var BaseReferenceObject = class extends ObjectClassType {
8984
9351
  return getRuntimeFeatureCell(row, column, this.getSheetId(), this.getUnitId(), this._runtimeFeatureCellData);
8985
9352
  }
8986
9353
  getCellByPosition(rowRaw, columnRaw) {
8987
- let row = rowRaw;
8988
- let column = columnRaw;
8989
- const rangeData = this.getRangeData();
8990
- if (!row) row = rangeData.startRow;
8991
- if (!column) column = rangeData.startColumn;
9354
+ const range = this.getRangePosition();
9355
+ const row = rowRaw ?? range.startRow;
9356
+ const column = columnRaw ?? range.startColumn;
8992
9357
  const cell = this.getCellData(row, column);
8993
9358
  if (!cell) return NullValueObject.create();
8994
9359
  return this.getCellValueObject(cell);
@@ -9058,6 +9423,9 @@ var BaseReferenceObject = class extends ObjectClassType {
9058
9423
  unitId: this.getUnitId()
9059
9424
  };
9060
9425
  }
9426
+ toUnitRanges() {
9427
+ return [this.toUnitRange()];
9428
+ }
9061
9429
  _checkIfWorksheetMiss() {
9062
9430
  if ((this._forcedSheetId == null || this._forcedSheetId.length === 0) && this._forcedSheetName.length > 0) return true;
9063
9431
  return false;
@@ -9162,7 +9530,7 @@ var CellReferenceObject = class extends BaseReferenceObject {
9162
9530
  unionBy(referenceObject) {
9163
9531
  if (!referenceObject.isCell()) return ErrorValueObject.create("#REF!");
9164
9532
  const cellReferenceObject = referenceObject;
9165
- const newRangeData = this.unionRange(this.getRangeData(), cellReferenceObject.getRangeData());
9533
+ const newRangeData = this.unionRange(this.getRangePosition(), cellReferenceObject.getRangePosition());
9166
9534
  return this._createRange(newRangeData);
9167
9535
  }
9168
9536
  unionRange(rangeData1, rangeData2) {
@@ -9204,8 +9572,6 @@ var CellReferenceObject = class extends BaseReferenceObject {
9204
9572
  rangeReferenceObject.setArrayFormulaCellData(this.getArrayFormulaCellData());
9205
9573
  rangeReferenceObject.setRuntimeArrayFormulaCellData(this.getRuntimeArrayFormulaCellData());
9206
9574
  rangeReferenceObject.setRuntimeFeatureCellData(this.getRuntimeFeatureCellData());
9207
- const { x, y } = this.getRefOffset();
9208
- rangeReferenceObject.setRefOffset(x, y);
9209
9575
  const forceSheetId = this.getForcedSheetId();
9210
9576
  rangeReferenceObject.setForcedSheetName(this.getForcedSheetName());
9211
9577
  if (forceSheetId != null) rangeReferenceObject.setForcedSheetIdDirect(forceSheetId);
@@ -9326,7 +9692,7 @@ function expandArrayValueObject(rowCount, columnCount, valueObject, defaultValue
9326
9692
  continue;
9327
9693
  }
9328
9694
  if (r >= valueRowCount || c >= valueColumnCount) {
9329
- row.push(defaultValue !== null && defaultValue !== void 0 ? defaultValue : NullValueObject.create());
9695
+ row.push(defaultValue ?? NullValueObject.create());
9330
9696
  continue;
9331
9697
  }
9332
9698
  const value = valueObject.get(r, c);
@@ -9664,8 +10030,11 @@ function filterSameValueObjectResult(array, range, criteria) {
9664
10030
  return array.mapValue((valueObject, r, c) => {
9665
10031
  const rangeValueObject = range.get(r, c);
9666
10032
  const isBlankStringCriteria = criteriaObject.isString() && criteriaObject.getValue() === "";
10033
+ if (isBlankStringCriteria && (operator === ">" || operator === ">=" || operator === "<" || operator === "<=")) return BooleanValueObject.create(false);
9667
10034
  if (operator === "<>" && isBlankStringCriteria && (rangeValueObject === null || rangeValueObject === void 0 ? void 0 : rangeValueObject.isString()) && rangeValueObject.getValue() === "") return BooleanValueObject.create(true);
9668
- if (criteriaObject.isString() && criteriaObject.getValue() !== "" && (operator === "<" || operator === "<=") && (rangeValueObject == null || rangeValueObject.isNull() || rangeValueObject.isString() && rangeValueObject.getValue() === "")) return BooleanValueObject.create(false);
10035
+ if (criteriaObject.isString() && isWildcard(`${criteriaObject.getValue()}`) && (rangeValueObject === null || rangeValueObject === void 0 ? void 0 : rangeValueObject.isString()) && rangeValueObject.getValue() === "") return valueObject;
10036
+ if (criteriaObject.isString() && criteriaObject.getValue() !== "" && (operator === "<" || operator === "<=") && (rangeValueObject === null || rangeValueObject === void 0 ? void 0 : rangeValueObject.isString()) && rangeValueObject.getValue() === "") return BooleanValueObject.create(true);
10037
+ if (criteriaObject.isString() && criteriaObject.getValue() !== "" && (operator === "<" || operator === "<=") && (rangeValueObject == null || rangeValueObject.isNull())) return BooleanValueObject.create(false);
9669
10038
  if (criteriaObject.isString() && (rangeValueObject === null || rangeValueObject === void 0 ? void 0 : rangeValueObject.isString()) && (operator === "<" || operator === "<=") && isSameLowerBoundBucket(rangeValueObject.getValue(), criteriaObject.getValue())) return BooleanValueObject.create(false);
9670
10039
  if ((rangeValueObject === null || rangeValueObject === void 0 ? void 0 : rangeValueObject.isNumber()) && criteriaObject.isString()) {
9671
10040
  const criteriaNumber = criteriaObject.convertToNumberObjectValue();
@@ -9834,12 +10203,12 @@ let FormulaRuntimeService = class FormulaRuntimeService extends _univerjs_core.D
9834
10203
  return this._currentColumn;
9835
10204
  }
9836
10205
  get currentRowCount() {
9837
- var _this$_functionRefInf, _this$_functionRefInf2;
9838
- return (_this$_functionRefInf = (_this$_functionRefInf2 = this._functionRefInfoOverrideStack[this._functionRefInfoOverrideStack.length - 1]) === null || _this$_functionRefInf2 === void 0 ? void 0 : _this$_functionRefInf2.rowCount) !== null && _this$_functionRefInf !== void 0 ? _this$_functionRefInf : this._currentRowCount;
10206
+ var _this$_functionRefInf;
10207
+ return ((_this$_functionRefInf = this._functionRefInfoOverrideStack[this._functionRefInfoOverrideStack.length - 1]) === null || _this$_functionRefInf === void 0 ? void 0 : _this$_functionRefInf.rowCount) ?? this._currentRowCount;
9839
10208
  }
9840
10209
  get currentColumnCount() {
9841
- var _this$_functionRefInf3, _this$_functionRefInf4;
9842
- return (_this$_functionRefInf3 = (_this$_functionRefInf4 = this._functionRefInfoOverrideStack[this._functionRefInfoOverrideStack.length - 1]) === null || _this$_functionRefInf4 === void 0 ? void 0 : _this$_functionRefInf4.columnCount) !== null && _this$_functionRefInf3 !== void 0 ? _this$_functionRefInf3 : this._currentColumnCount;
10210
+ var _this$_functionRefInf2;
10211
+ return ((_this$_functionRefInf2 = this._functionRefInfoOverrideStack[this._functionRefInfoOverrideStack.length - 1]) === null || _this$_functionRefInf2 === void 0 ? void 0 : _this$_functionRefInf2.columnCount) ?? this._currentColumnCount;
9843
10212
  }
9844
10213
  get currentSubUnitId() {
9845
10214
  return this._currentSubUnitId;
@@ -9958,6 +10327,9 @@ let FormulaRuntimeService = class FormulaRuntimeService extends _univerjs_core.D
9958
10327
  this._functionRefInfoOverrideStack.pop();
9959
10328
  };
9960
10329
  }
10330
+ hasFunctionRefInfoOverride() {
10331
+ return this._functionRefInfoOverrideStack.length > 0;
10332
+ }
9961
10333
  clearFunctionDefinitionPrivacyVar() {
9962
10334
  this._functionDefinitionPrivacyVar.clear();
9963
10335
  }
@@ -10275,151 +10647,6 @@ let FormulaRuntimeService = class FormulaRuntimeService extends _univerjs_core.D
10275
10647
  FormulaRuntimeService = __decorate([__decorateParam(0, IFormulaCurrentConfigService), __decorateParam(1, IHyperlinkEngineFormulaService)], FormulaRuntimeService);
10276
10648
  const IFormulaRuntimeService = (0, _univerjs_core.createIdentifier)("univer.formula.runtime.service");
10277
10649
 
10278
- //#endregion
10279
- //#region src/engine/ast-node/node-type.ts
10280
- const NODE_ORDER_MAP = /* @__PURE__ */ new Map([
10281
- [1, 7],
10282
- [2, 9],
10283
- [3, 8],
10284
- [4, 6],
10285
- [5, 1],
10286
- [6, 2],
10287
- [9, 10],
10288
- [10, 3],
10289
- [11, 4],
10290
- [12, 5]
10291
- ]);
10292
-
10293
- //#endregion
10294
- //#region src/engine/ast-node/base-ast-node.ts
10295
- var BaseAstNode = class {
10296
- constructor(_token) {
10297
- this._token = _token;
10298
- _defineProperty(this, "_children", []);
10299
- _defineProperty(this, "_definedNames", void 0);
10300
- _defineProperty(this, "_parent", void 0);
10301
- _defineProperty(this, "_valueObject", void 0);
10302
- _defineProperty(this, "_calculateState", false);
10303
- _defineProperty(this, "_async", false);
10304
- _defineProperty(this, "_address", false);
10305
- _defineProperty(this, "_isForcedCalculateFunction", false);
10306
- }
10307
- dispose() {
10308
- var _this$_valueObject;
10309
- this._children.forEach((node) => {
10310
- node.dispose();
10311
- });
10312
- (_this$_valueObject = this._valueObject) === null || _this$_valueObject === void 0 || _this$_valueObject.dispose();
10313
- this._valueObject = null;
10314
- this._children = [];
10315
- this._definedNames = null;
10316
- this._parent = null;
10317
- }
10318
- get nodeType() {
10319
- return 8;
10320
- }
10321
- resetCalculationState() {
10322
- this._children.forEach((node) => {
10323
- node.resetCalculationState();
10324
- });
10325
- this._valueObject = null;
10326
- this._calculateState = false;
10327
- }
10328
- isAsync() {
10329
- return this._async;
10330
- }
10331
- isAddress() {
10332
- return this._address;
10333
- }
10334
- isForcedCalculateFunction() {
10335
- return this._isForcedCalculateFunction;
10336
- }
10337
- setAsync() {
10338
- this._async = true;
10339
- }
10340
- setAddress() {
10341
- this._address = true;
10342
- }
10343
- getParent() {
10344
- return this._parent;
10345
- }
10346
- setParent(node) {
10347
- this._parent = node;
10348
- node.addChildren(this);
10349
- }
10350
- setForcedCalculateFunction() {
10351
- this._isForcedCalculateFunction = true;
10352
- }
10353
- getChildren() {
10354
- return this._children;
10355
- }
10356
- addChildren(...astNode) {
10357
- this._children.push(...astNode);
10358
- }
10359
- getToken() {
10360
- return this._token;
10361
- }
10362
- setValue(value) {
10363
- this._valueObject = value;
10364
- }
10365
- getValue() {
10366
- return this._valueObject;
10367
- }
10368
- isCalculated() {
10369
- return this._calculateState;
10370
- }
10371
- setCalculated() {
10372
- this._calculateState = true;
10373
- }
10374
- execute() {}
10375
- setNotEmpty(state = true) {}
10376
- async executeAsync() {
10377
- return Promise.resolve(0);
10378
- }
10379
- serialize() {
10380
- const token = this.getToken();
10381
- const children = this.getChildren();
10382
- const childrenSerialization = [];
10383
- const childrenCount = children.length;
10384
- for (let i = 0; i < childrenCount; i++) {
10385
- const item = children[i];
10386
- childrenSerialization.push(item.serialize());
10387
- }
10388
- const result = {
10389
- token,
10390
- nodeType: this.nodeType
10391
- };
10392
- if (childrenCount > 0) result.children = childrenSerialization;
10393
- return result;
10394
- }
10395
- hasDefinedName(definedName) {
10396
- var _this$_definedNames;
10397
- return ((_this$_definedNames = this._definedNames) === null || _this$_definedNames === void 0 ? void 0 : _this$_definedNames.includes(definedName)) || false;
10398
- }
10399
- setDefinedNames(definedNames) {
10400
- this._definedNames = definedNames;
10401
- }
10402
- getDefinedNames() {
10403
- return this._definedNames;
10404
- }
10405
- };
10406
- var ErrorNode = class ErrorNode extends BaseAstNode {
10407
- constructor(errorType) {
10408
- super(errorType);
10409
- _defineProperty(this, "_errorValueObject", void 0);
10410
- this._errorValueObject = ErrorValueObject.create(errorType);
10411
- }
10412
- get nodeType() {
10413
- return 7;
10414
- }
10415
- static create(errorType) {
10416
- return new ErrorNode(errorType);
10417
- }
10418
- getValue() {
10419
- return this._errorValueObject;
10420
- }
10421
- };
10422
-
10423
10650
  //#endregion
10424
10651
  //#region src/engine/ast-node/base-ast-node-factory.ts
10425
10652
  var BaseAstNodeFactory = class {
@@ -10485,161 +10712,6 @@ const COLUMN_LIKE_FUNCTION_NAMES = new Set(ALL_GROUPS.flatMap((g) => Object.valu
10485
10712
  return idx > 0 && idx <= _univerjs_core.MAX_COLUMN_COUNT;
10486
10713
  }));
10487
10714
 
10488
- //#endregion
10489
- //#region src/engine/utils/generate-ast-node.ts
10490
- const FORMULA_CACHE_LRU_COUNT = 5e3;
10491
- const FORMULA_AST_CACHE = new FormulaAstLRU(FORMULA_CACHE_LRU_COUNT);
10492
- const DIRTY_DEFINED_NAME_SET_CACHE = /* @__PURE__ */ new WeakMap();
10493
- const DIRTY_SUPER_TABLE_PATTERN_CACHE = /* @__PURE__ */ new WeakMap();
10494
- function generateAstNode(unitId, formulaString, lexer, astTreeBuilder, currentConfigService, subUnitId) {
10495
- var _ref;
10496
- if (subUnitId) {
10497
- currentConfigService.setExecuteUnitId(unitId);
10498
- currentConfigService.setExecuteSubUnitId(subUnitId);
10499
- }
10500
- const cacheKey = `${unitId}:${(_ref = subUnitId !== null && subUnitId !== void 0 ? subUnitId : currentConfigService.getExecuteSubUnitId()) !== null && _ref !== void 0 ? _ref : ""}:${formulaString}`;
10501
- let astNode = FORMULA_AST_CACHE.get(cacheKey);
10502
- if (!(checkIsChangedByDefinedName(unitId, formulaString, currentConfigService) || checkIsChangedBySuperTable(unitId, formulaString, currentConfigService)) && astNode && !isDirtyDefinedForNode(astNode, currentConfigService, unitId)) return astNode;
10503
- const lexerNode = lexer.treeBuilder(formulaString, true, unitId);
10504
- if (ERROR_TYPE_SET.has(lexerNode)) return ErrorNode.create(lexerNode);
10505
- astNode = astTreeBuilder.parse(lexerNode);
10506
- if (astNode == null) {
10507
- console.error("generateAstNode astNode is null");
10508
- return ErrorNode.create(lexerNode);
10509
- }
10510
- FORMULA_AST_CACHE.set(cacheKey, astNode);
10511
- return astNode;
10512
- }
10513
- function checkIsChangedByDefinedName(unitId, formula, currentConfigService) {
10514
- const unitDefinedNameMap = currentConfigService.getDirtyDefinedNameMap()[unitId];
10515
- if (unitDefinedNameMap == null) return false;
10516
- return getNormalizedDirtyDefinedNameSet(unitDefinedNameMap).has(normalizeFormulaText(formula));
10517
- }
10518
- function normalizeFormulaText(formula) {
10519
- return formula.startsWith("=") ? formula.slice(1) : formula;
10520
- }
10521
- function checkIsChangedBySuperTable(unitId, formula, currentConfigService) {
10522
- var _currentConfigService, _tableReferencePatter;
10523
- const getDirtySuperTableMap = (_currentConfigService = currentConfigService.getDirtySuperTableMap) === null || _currentConfigService === void 0 ? void 0 : _currentConfigService.bind(currentConfigService);
10524
- const changedSuperTableMap = getDirtySuperTableMap === null || getDirtySuperTableMap === void 0 ? void 0 : getDirtySuperTableMap();
10525
- const unitSuperTableMap = changedSuperTableMap === null || changedSuperTableMap === void 0 ? void 0 : changedSuperTableMap[unitId];
10526
- if (unitSuperTableMap == null) return false;
10527
- const tableReferencePattern = getDirtySuperTableReferencePattern(unitSuperTableMap);
10528
- return (_tableReferencePatter = tableReferencePattern === null || tableReferencePattern === void 0 ? void 0 : tableReferencePattern.test(normalizeFormulaText(formula))) !== null && _tableReferencePatter !== void 0 ? _tableReferencePatter : false;
10529
- }
10530
- function getNormalizedDirtyDefinedNameSet(unitDefinedNameMap) {
10531
- let normalizedNameSet = DIRTY_DEFINED_NAME_SET_CACHE.get(unitDefinedNameMap);
10532
- if (normalizedNameSet == null) {
10533
- normalizedNameSet = new Set(Object.keys(unitDefinedNameMap).map(normalizeFormulaText));
10534
- DIRTY_DEFINED_NAME_SET_CACHE.set(unitDefinedNameMap, normalizedNameSet);
10535
- }
10536
- return normalizedNameSet;
10537
- }
10538
- function getDirtySuperTableReferencePattern(unitSuperTableMap) {
10539
- let tableReferencePattern = DIRTY_SUPER_TABLE_PATTERN_CACHE.get(unitSuperTableMap);
10540
- if (tableReferencePattern === void 0) {
10541
- const tableNames = Object.keys(unitSuperTableMap).filter((tableName) => tableName.length > 0);
10542
- tableReferencePattern = tableNames.length > 0 ? _univerjs_core.regexp.createRegExpFromSafeFragment(`(^|[^A-Za-z0-9_])${_univerjs_core.regexp.or(...tableNames)}(\\s*\\[|$|[^A-Za-z0-9_])`, "i") : null;
10543
- DIRTY_SUPER_TABLE_PATTERN_CACHE.set(unitSuperTableMap, tableReferencePattern);
10544
- }
10545
- return tableReferencePattern;
10546
- }
10547
- function isDirtyDefinedForNode(node, currentConfigService, unitId) {
10548
- const definedNameMap = currentConfigService.getDirtyDefinedNameMap();
10549
- const executeUnitId = unitId;
10550
- if (executeUnitId != null && definedNameMap[executeUnitId] != null) {
10551
- const names = Object.keys(definedNameMap[executeUnitId]);
10552
- for (let i = 0, len = names.length; i < len; i++) {
10553
- const name = names[i];
10554
- if (node.hasDefinedName(name)) return true;
10555
- }
10556
- }
10557
- return false;
10558
- }
10559
- function includeDefinedName(tree, node, currentConfigService) {
10560
- /**
10561
- * Detect whether the dirty map contains a defined name.
10562
- */
10563
- if (node != null) {
10564
- if (isDirtyDefinedForNode(node, currentConfigService, tree.unitId)) return true;
10565
- }
10566
- return false;
10567
- }
10568
-
10569
- //#endregion
10570
- //#region src/services/function.service.ts
10571
- const IFunctionService = (0, _univerjs_core.createIdentifier)("univer.formula-function.service");
10572
- var FunctionService = class extends _univerjs_core.Disposable {
10573
- constructor(..._args) {
10574
- super(..._args);
10575
- _defineProperty(this, "_functionExecutors", /* @__PURE__ */ new Map());
10576
- _defineProperty(this, "_functionDescriptions", /* @__PURE__ */ new Map());
10577
- }
10578
- dispose() {
10579
- super.dispose();
10580
- this._functionExecutors.clear();
10581
- this._functionDescriptions.clear();
10582
- }
10583
- registerExecutors(...functions) {
10584
- for (let i = 0; i < functions.length; i++) {
10585
- const func = functions[i];
10586
- this._functionExecutors.set(func.name, func);
10587
- }
10588
- }
10589
- getExecutors() {
10590
- return this._functionExecutors;
10591
- }
10592
- getExecutor(functionToken) {
10593
- return this._functionExecutors.get(functionToken);
10594
- }
10595
- hasExecutor(functionToken) {
10596
- return this._functionExecutors.has(functionToken);
10597
- }
10598
- unregisterExecutors(...functionTokens) {
10599
- for (let i = 0; i < functionTokens.length; i++) {
10600
- const functionToken = functionTokens[i];
10601
- this._functionExecutors.delete(functionToken);
10602
- }
10603
- }
10604
- registerDescriptions(...descriptions) {
10605
- for (let i = 0; i < descriptions.length; i++) {
10606
- const description = descriptions[i];
10607
- this._functionDescriptions.set(description.functionName, description);
10608
- }
10609
- return (0, _univerjs_core.toDisposable)(() => {
10610
- for (let i = 0; i < descriptions.length; i++) {
10611
- const description = descriptions[i];
10612
- this._functionDescriptions.delete(description.functionName);
10613
- }
10614
- });
10615
- }
10616
- getDescriptions() {
10617
- return this._functionDescriptions;
10618
- }
10619
- getDescription(functionToken) {
10620
- return this._functionDescriptions.get(functionToken);
10621
- }
10622
- hasDescription(functionToken) {
10623
- return this._functionDescriptions.has(functionToken);
10624
- }
10625
- unregisterDescriptions(...functionTokens) {
10626
- for (let i = 0; i < functionTokens.length; i++) {
10627
- const functionToken = functionTokens[i];
10628
- this._functionDescriptions.delete(functionToken);
10629
- }
10630
- }
10631
- clearDescriptions() {
10632
- this._functionDescriptions.clear();
10633
- }
10634
- deleteFormulaAstCacheKey(...functionToken) {
10635
- FORMULA_AST_CACHE.forEach((_, key) => {
10636
- functionToken.forEach((token) => {
10637
- if (key.includes(token)) FORMULA_AST_CACHE.delete(key);
10638
- });
10639
- });
10640
- }
10641
- };
10642
-
10643
10715
  //#endregion
10644
10716
  //#region src/services/unit-reference-resolver.service.ts
10645
10717
  const IFormulaUnitReferenceResolver = (0, _univerjs_core.createIdentifier)("univer.formula.unit-reference-resolver");
@@ -10711,9 +10783,10 @@ var PrefixNode = class extends BaseAstNode {
10711
10783
  this.setValue(result);
10712
10784
  }
10713
10785
  _handlerAT(value) {
10714
- if (!value.isReferenceObject()) return ErrorValueObject.create("#VALUE!");
10786
+ if (value instanceof ArrayValueObject) return value.get(0, 0) ?? ErrorValueObject.create("#VALUE!");
10787
+ if (!value.isReferenceObject()) return value;
10715
10788
  const currentValue = value;
10716
- if (currentValue.isCell()) return ErrorValueObject.create("#VALUE!");
10789
+ if (currentValue.isCell()) return currentValue.getCellByPosition();
10717
10790
  if (this._preserveAtRangeForFormula2LookupArray()) return currentValue;
10718
10791
  const runtimeService = this._runtimeService;
10719
10792
  const currentRow = runtimeService.currentRow || 0;
@@ -10731,7 +10804,7 @@ var PrefixNode = class extends BaseAstNode {
10731
10804
  let parent = node.getParent();
10732
10805
  let sawCompareOperator = false;
10733
10806
  while (parent != null) {
10734
- if (parent.nodeType === 3) sawCompareOperator || (sawCompareOperator = OPERATOR_TOKEN_COMPARE_SET.has(parent.getToken()));
10807
+ if (parent.nodeType === 3) sawCompareOperator ||= OPERATOR_TOKEN_COMPARE_SET.has(parent.getToken());
10735
10808
  if (parent.nodeType === 4) {
10736
10809
  const functionName = parent.getToken().toUpperCase();
10737
10810
  if (sawCompareOperator && functionName === "XMATCH") return parent.getChildren().indexOf(node) === 1;
@@ -10817,6 +10890,9 @@ var FunctionNode = class extends BaseAstNode {
10817
10890
  get nodeType() {
10818
10891
  return 4;
10819
10892
  }
10893
+ preservesLazyIfReferenceArray(child) {
10894
+ return this._functionExecutor.lazyIfReferenceArrayArgumentIndexes.includes(this.getChildren().indexOf(child));
10895
+ }
10820
10896
  async executeAsync() {
10821
10897
  const children = this.getChildren();
10822
10898
  this._compatibility();
@@ -10875,6 +10951,7 @@ var FunctionNode = class extends BaseAstNode {
10875
10951
  if (!this._functionExecutor.returnsLegacyArrayAsScalar || !isTopLevel || !result.isArray()) return result;
10876
10952
  const array = result;
10877
10953
  if (array.getRowCount() <= 1 && array.getColumnCount() <= 1) return result;
10954
+ if (this._runtimeService.hasFunctionRefInfoOverride() && (this._runtimeService.currentRowCount > 1 || this._runtimeService.currentColumnCount > 1)) return result;
10878
10955
  return array.getFirstCell();
10879
10956
  }
10880
10957
  /**
@@ -10966,10 +11043,7 @@ var FunctionNode = class extends BaseAstNode {
10966
11043
  if (minParams !== -1 && maxParams !== -1 && (children.length < minParams || children.length > maxParams)) return ErrorValueObject.create("#N/A");
10967
11044
  this._setRefInfo();
10968
11045
  this._handleAddressFunction();
10969
- return this._functionExecutor.calculateAst(children, (node) => {
10970
- var _this$_getChildVarian;
10971
- return (_this$_getChildVarian = this._getChildVariant(node)) !== null && _this$_getChildVarian !== void 0 ? _this$_getChildVarian : null;
10972
- });
11046
+ return this._functionExecutor.calculateAst(children, (node) => this._getChildVariant(node) ?? null);
10973
11047
  }
10974
11048
  async _calculateAsync(variants) {
10975
11049
  const { minParams, maxParams } = this._functionExecutor;
@@ -11241,7 +11315,6 @@ let Interpreter = class Interpreter extends _univerjs_core.Disposable {
11241
11315
  return true;
11242
11316
  }
11243
11317
  async _executeLazyIfErrorAsync(node, refOffsetX, refOffsetY) {
11244
- var _children$1$getValue;
11245
11318
  const children = node.getChildren();
11246
11319
  if (children.length !== 2) return false;
11247
11320
  await this._executeAsync(children[0], refOffsetX, refOffsetY);
@@ -11253,11 +11326,10 @@ let Interpreter = class Interpreter extends _univerjs_core.Disposable {
11253
11326
  return true;
11254
11327
  }
11255
11328
  await this._executeAsync(children[1], refOffsetX, refOffsetY);
11256
- node.setValue((_children$1$getValue = children[1].getValue()) !== null && _children$1$getValue !== void 0 ? _children$1$getValue : ErrorValueObject.create("#VALUE!"));
11329
+ node.setValue(children[1].getValue() ?? ErrorValueObject.create("#VALUE!"));
11257
11330
  return true;
11258
11331
  }
11259
11332
  _executeLazyIfError(node, refOffsetX, refOffsetY) {
11260
- var _children$1$getValue2;
11261
11333
  const children = node.getChildren();
11262
11334
  if (children.length !== 2) return false;
11263
11335
  this._execute(children[0], refOffsetX, refOffsetY);
@@ -11269,7 +11341,7 @@ let Interpreter = class Interpreter extends _univerjs_core.Disposable {
11269
11341
  return true;
11270
11342
  }
11271
11343
  this._execute(children[1], refOffsetX, refOffsetY);
11272
- node.setValue((_children$1$getValue2 = children[1].getValue()) !== null && _children$1$getValue2 !== void 0 ? _children$1$getValue2 : ErrorValueObject.create("#VALUE!"));
11344
+ node.setValue(children[1].getValue() ?? ErrorValueObject.create("#VALUE!"));
11273
11345
  return true;
11274
11346
  }
11275
11347
  _toLazyIfErrorValue(value) {
@@ -11285,12 +11357,13 @@ let Interpreter = class Interpreter extends _univerjs_core.Disposable {
11285
11357
  }
11286
11358
  _toLazyIfSelectedValue(value, node) {
11287
11359
  if (value == null) return ErrorValueObject.create("#VALUE!");
11360
+ const preserveArray = this._preserveLazyIfSelectedReferenceArray(node);
11288
11361
  if (value.isReferenceObject()) {
11289
11362
  const reference = value;
11290
- if (this._preserveLazyIfSelectedReferenceArray(node)) return reference.toArrayValueObject();
11363
+ if (preserveArray) return reference.toArrayValueObject();
11291
11364
  value = this._implicitLazyIfReferenceValue(reference);
11292
11365
  }
11293
- if (value.isArray()) value = this._implicitLazyIfArrayValue(value);
11366
+ if (value.isArray() && !preserveArray) value = this._implicitLazyIfArrayValue(value);
11294
11367
  if (!value.isArray()) {
11295
11368
  const baseValue = value;
11296
11369
  return baseValue.isNull() ? NumberValueObject.create(0) : baseValue;
@@ -11311,7 +11384,7 @@ let Interpreter = class Interpreter extends _univerjs_core.Disposable {
11311
11384
  let child = node;
11312
11385
  let parent = child.getParent();
11313
11386
  while (parent != null) {
11314
- if (parent.nodeType === 4) return parent.getToken().toUpperCase() === "MATCH" && parent.getChildren().indexOf(child) === 1;
11387
+ if (parent.nodeType === 4) return parent.preservesLazyIfReferenceArray(child);
11315
11388
  child = parent;
11316
11389
  parent = parent.getParent();
11317
11390
  }
@@ -11800,6 +11873,7 @@ var TableReferenceObject = class extends BaseReferenceObject {
11800
11873
  const tableStartRow = range.startRow;
11801
11874
  const tableEndRow = range.endRow;
11802
11875
  const dataStartRow = tableStartRow + (this._tableData.showHeader === false ? 0 : 1);
11876
+ const dataEndRow = tableEndRow - (this._tableData.showFooter === true ? 1 : 0);
11803
11877
  let startRow = -1;
11804
11878
  let endRow = -1;
11805
11879
  switch (type) {
@@ -11809,7 +11883,7 @@ var TableReferenceObject = class extends BaseReferenceObject {
11809
11883
  break;
11810
11884
  case "#Data":
11811
11885
  startRow = dataStartRow;
11812
- endRow = tableEndRow;
11886
+ endRow = dataEndRow;
11813
11887
  break;
11814
11888
  case "#Headers":
11815
11889
  if (this._tableData.showHeader === false) {
@@ -11825,14 +11899,14 @@ var TableReferenceObject = class extends BaseReferenceObject {
11825
11899
  endRow = tableEndRow;
11826
11900
  break;
11827
11901
  case "#This Row": {
11828
- const r = this._resolveThisRow(tableStartRow, tableEndRow);
11902
+ const r = this._resolveThisRow(dataStartRow, dataEndRow);
11829
11903
  startRow = r;
11830
11904
  endRow = r;
11831
11905
  break;
11832
11906
  }
11833
11907
  default:
11834
11908
  startRow = dataStartRow;
11835
- endRow = tableEndRow;
11909
+ endRow = dataEndRow;
11836
11910
  break;
11837
11911
  }
11838
11912
  this.setRangeData({
@@ -11859,7 +11933,8 @@ var TableReferenceObject = class extends BaseReferenceObject {
11859
11933
  getCellData(row, column) {
11860
11934
  if (this._isCurrentRowForRange) {
11861
11935
  const { startRow, endRow } = this._tableData.range;
11862
- if (row < startRow || row > endRow) return { v: "#N/A" };
11936
+ const lastCurrentRow = endRow - (this._tableData.showFooter === true ? 1 : 0);
11937
+ if (row < startRow || row > lastCurrentRow) return { v: "#N/A" };
11863
11938
  }
11864
11939
  return super.getCellData(row, column);
11865
11940
  }
@@ -11884,10 +11959,9 @@ var TableReferenceObject = class extends BaseReferenceObject {
11884
11959
  * - Has comma: Left is Section, right is column/column range
11885
11960
  */
11886
11961
  _parseStructuredRef(raw, titleMap) {
11887
- var _range$startColumn, _range$endColumn;
11888
11962
  const { range } = this._tableData;
11889
- const fullStartCol = (_range$startColumn = range.startColumn) !== null && _range$startColumn !== void 0 ? _range$startColumn : 0;
11890
- const fullEndCol = (_range$endColumn = range.endColumn) !== null && _range$endColumn !== void 0 ? _range$endColumn : 0;
11963
+ const fullStartCol = range.startColumn ?? 0;
11964
+ const fullEndCol = range.endColumn ?? 0;
11891
11965
  if (!raw || raw.trim().length === 0) return {
11892
11966
  startColumn: fullStartCol,
11893
11967
  endColumn: fullEndCol,
@@ -11939,6 +12013,14 @@ var TableReferenceObject = class extends BaseReferenceObject {
11939
12013
  const sectionRaw = body.slice(0, commaAt).trim();
11940
12014
  const columnsRaw = body.slice(commaAt + 1).trim();
11941
12015
  const section = this._parseSectionMaybeBracketed(sectionRaw);
12016
+ if (section === void 0) {
12017
+ const { startColumn, endColumn } = this._parseColumnOrRange(body, titleMap, fullStartCol);
12018
+ return {
12019
+ startColumn,
12020
+ endColumn,
12021
+ type: "#Data"
12022
+ };
12023
+ }
11942
12024
  const { startColumn, endColumn } = this._parseColumnOrRange(columnsRaw, titleMap, fullStartCol);
11943
12025
  return {
11944
12026
  startColumn,
@@ -11967,13 +12049,12 @@ var TableReferenceObject = class extends BaseReferenceObject {
11967
12049
  }
11968
12050
  /**
11969
12051
  * Parse Section, compatible with both "[#Data]" and "#Data" inputs
11970
- * Returns TableOptionType if matched; returns DATA if not (could throw error instead)
12052
+ * Returns TableOptionType if matched; returns undefined when the comma belongs to a column title.
11971
12053
  */
11972
12054
  _parseSectionMaybeBracketed(raw) {
11973
12055
  const x = raw.trim();
11974
12056
  const inner = x.startsWith("[") && x.endsWith("]") ? this._stripOuterBracketOnce(x) : x;
11975
- const typeMaybe = this._mapSection(inner);
11976
- return typeMaybe !== null && typeMaybe !== void 0 ? typeMaybe : "#Data";
12057
+ return this._mapSection(inner);
11977
12058
  }
11978
12059
  /**
11979
12060
  * Section mapping: Only accepts keywords starting with #.
@@ -11998,6 +12079,14 @@ var TableReferenceObject = class extends BaseReferenceObject {
11998
12079
  */
11999
12080
  _parseColumnOrRange(raw, titleMap, fullStartCol) {
12000
12081
  const s = raw.trim();
12082
+ const singleColumnIndex = this._titleToIndex(this._stripOuterBracketIfAny(s), titleMap);
12083
+ if (singleColumnIndex !== -1) {
12084
+ const column = fullStartCol + singleColumnIndex;
12085
+ return {
12086
+ startColumn: column,
12087
+ endColumn: column
12088
+ };
12089
+ }
12001
12090
  const colonAt = this._findColonAtTopLevel(s);
12002
12091
  if (colonAt === -1) {
12003
12092
  const name = this._stripOuterBracketIfAny(s);
@@ -12050,9 +12139,9 @@ var TableReferenceObject = class extends BaseReferenceObject {
12050
12139
  return -1;
12051
12140
  }
12052
12141
  /** Resolve #This Row's row number; takes first data row (tableStartRow+1) when no context available */
12053
- _resolveThisRow(tableStartRow, tableEndRow) {
12142
+ _resolveThisRow(dataStartRow, dataEndRow) {
12054
12143
  this._isCurrentRowForRange = true;
12055
- return Math.min(tableStartRow + 1, tableEndRow);
12144
+ return Math.min(dataStartRow, dataEndRow);
12056
12145
  }
12057
12146
  };
12058
12147
 
@@ -12239,12 +12328,11 @@ let ReferenceNodeFactory = class ReferenceNodeFactory extends BaseAstNodeFactory
12239
12328
  return this._superTableService.getTableMap(unitId);
12240
12329
  }
12241
12330
  _getNode(tokenTrim, isLexerNode, isPrepareMerge, param) {
12242
- var _tableMap$has;
12243
12331
  const currentConfigService = this._currentConfigService;
12244
12332
  const runtimeService = this._formulaRuntimeService;
12245
12333
  const makeRef = (type) => new ReferenceNode(currentConfigService, runtimeService, tokenTrim, type, this._unitReferenceResolver, this._superTableService, this._externalReferenceDataLoader, isPrepareMerge);
12246
12334
  const tableMap = this._getTableMap();
12247
- if ((_tableMap$has = tableMap === null || tableMap === void 0 ? void 0 : tableMap.has(tokenTrim)) !== null && _tableMap$has !== void 0 ? _tableMap$has : false) return this._getTableReferenceNode(tokenTrim, isPrepareMerge, true);
12335
+ if ((tableMap === null || tableMap === void 0 ? void 0 : tableMap.has(tokenTrim)) ?? false) return this._getTableReferenceNode(tokenTrim, isPrepareMerge, true);
12248
12336
  if (regexTestSingeRange(tokenTrim)) return makeRef(0);
12249
12337
  const parentIsUnion = isLexerNode && this._checkParentIsUnionOperator(param);
12250
12338
  if (parentIsUnion && regexTestSingleRow(tokenTrim)) return makeRef(2);
@@ -12359,11 +12447,253 @@ SuffixNodeFactory = __decorate([
12359
12447
  __decorateParam(2, IFormulaCurrentConfigService)
12360
12448
  ], SuffixNodeFactory);
12361
12449
 
12450
+ //#endregion
12451
+ //#region src/engine/reference-object/multi-area-reference-object.ts
12452
+ var MultiAreaReferenceObject = class extends BaseReferenceObject {
12453
+ constructor(token, areas = [], _arrayMode = "first-cell-grid") {
12454
+ super(token);
12455
+ this._arrayMode = _arrayMode;
12456
+ _defineProperty(this, "_areas", []);
12457
+ this._areas = areas;
12458
+ }
12459
+ dispose() {
12460
+ this._areas.forEach((row) => {
12461
+ row.forEach((a) => a.dispose());
12462
+ });
12463
+ this._areas = [];
12464
+ super.dispose();
12465
+ }
12466
+ getAreas() {
12467
+ return this._areas;
12468
+ }
12469
+ setAreas(areas) {
12470
+ this._areas = areas;
12471
+ }
12472
+ /**
12473
+ * Append an area:
12474
+ * - If a single AreaValue is passed, it will be wrapped as one row.
12475
+ * - If an AreaValue[] is passed, it will be inserted as an entire row.
12476
+ */
12477
+ addArea(area) {
12478
+ if (Array.isArray(area)) this._areas.push(area);
12479
+ else this._areas.push([area]);
12480
+ }
12481
+ /** Flatten the 2D areas to reuse 1D logic */
12482
+ _flatAreas() {
12483
+ return this._areas.flat();
12484
+ }
12485
+ isMultiArea() {
12486
+ return true;
12487
+ }
12488
+ isRange() {
12489
+ return false;
12490
+ }
12491
+ isCell() {
12492
+ return false;
12493
+ }
12494
+ isRow() {
12495
+ return false;
12496
+ }
12497
+ isColumn() {
12498
+ return false;
12499
+ }
12500
+ getRowCount() {
12501
+ if (this._arrayMode === "first-cell-grid") return this._areas.length;
12502
+ let total = 0;
12503
+ for (const a of this._flatAreas()) if (a instanceof BaseReferenceObject) total += a.getRowCount();
12504
+ return total;
12505
+ }
12506
+ getColumnCount() {
12507
+ if (this._arrayMode === "first-cell-grid") return this._areas.reduce((max, row) => Math.max(max, row.length), 0);
12508
+ return this._flatAreas().reduce((max, area) => area instanceof BaseReferenceObject ? Math.max(max, area.getColumnCount()) : max, 0);
12509
+ }
12510
+ isExceedRange() {
12511
+ return this._flatAreas().some((a) => {
12512
+ return a instanceof BaseReferenceObject && a.isExceedRange();
12513
+ });
12514
+ }
12515
+ setRefOffset(x = 0, y = 0) {
12516
+ super.setRefOffset(x, y);
12517
+ this._flatAreas().forEach((a) => {
12518
+ if (a instanceof BaseReferenceObject) a.setRefOffset(x, y);
12519
+ });
12520
+ }
12521
+ _getReferenceArea() {
12522
+ return this._flatAreas().find((area) => area instanceof BaseReferenceObject);
12523
+ }
12524
+ /**
12525
+ * Multi-area reference may span multiple sheets, but Excel requires
12526
+ * them to be in the same sheet for most functions. We follow Excel semantics
12527
+ * by returning the first area’s identifiers.
12528
+ */
12529
+ getUnitId() {
12530
+ var _this$_getReferenceAr;
12531
+ return ((_this$_getReferenceAr = this._getReferenceArea()) === null || _this$_getReferenceAr === void 0 ? void 0 : _this$_getReferenceAr.getUnitId()) ?? super.getUnitId();
12532
+ }
12533
+ getSheetId() {
12534
+ var _this$_getReferenceAr2;
12535
+ return ((_this$_getReferenceAr2 = this._getReferenceArea()) === null || _this$_getReferenceAr2 === void 0 ? void 0 : _this$_getReferenceAr2.getSheetId()) ?? super.getSheetId();
12536
+ }
12537
+ getActiveSheetRowCount() {
12538
+ var _this$_getReferenceAr3;
12539
+ return ((_this$_getReferenceAr3 = this._getReferenceArea()) === null || _this$_getReferenceAr3 === void 0 ? void 0 : _this$_getReferenceAr3.getActiveSheetRowCount()) ?? 0;
12540
+ }
12541
+ getActiveSheetColumnCount() {
12542
+ var _this$_getReferenceAr4;
12543
+ return ((_this$_getReferenceAr4 = this._getReferenceArea()) === null || _this$_getReferenceAr4 === void 0 ? void 0 : _this$_getReferenceAr4.getActiveSheetColumnCount()) ?? 0;
12544
+ }
12545
+ /**
12546
+ * Iterate through all areas in order, flattening the multi-area into
12547
+ * a sequence of cells.
12548
+ *
12549
+ * Note: The order here is "row-major":
12550
+ * iterate by the row order of _areas, then within each row by the area order.
12551
+ */
12552
+ iterator(callback) {
12553
+ for (const row of this._areas) {
12554
+ let stopRow = false;
12555
+ for (const area of row) {
12556
+ if (!(area instanceof BaseReferenceObject)) continue;
12557
+ let stopArea = false;
12558
+ area.iterator((v, r, c) => {
12559
+ const res = callback(v, r, c);
12560
+ if (res === false) {
12561
+ stopArea = true;
12562
+ stopRow = true;
12563
+ return false;
12564
+ }
12565
+ return res;
12566
+ });
12567
+ if (stopArea) break;
12568
+ }
12569
+ if (stopRow) return;
12570
+ }
12571
+ }
12572
+ /**
12573
+ * Excel defines the "first cell" of a multi-area reference
12574
+ * as the first cell of the first area.
12575
+ */
12576
+ getFirstCell() {
12577
+ const first = this._getReferenceArea();
12578
+ if (!first) return super.getFirstCell();
12579
+ return first.getFirstCell();
12580
+ }
12581
+ /**
12582
+ * For multi-area, we only take the *first cell* of each area and
12583
+ * arrange them into a 2D ArrayValueObject:
12584
+ *
12585
+ * - outer `_areas` dimension => rows
12586
+ * - inner `_areas[row]` dimension => columns
12587
+ */
12588
+ toArrayValueObject() {
12589
+ if (this._arrayMode === "stack-areas") return this._stackAreas();
12590
+ const rows = this._areas.length;
12591
+ if (rows === 0) return createNewArray([], 0, 0);
12592
+ const cols = this.getColumnCount();
12593
+ const result = [];
12594
+ for (let r = 0; r < rows; r++) {
12595
+ const rowAreas = this._areas[r] ?? [];
12596
+ result[r] = [];
12597
+ for (let c = 0; c < cols; c++) {
12598
+ const area = rowAreas[c];
12599
+ if (!area) {
12600
+ result[r][c] = NullValueObject.create();
12601
+ continue;
12602
+ }
12603
+ if (area instanceof ErrorValueObject) {
12604
+ result[r][c] = area;
12605
+ continue;
12606
+ }
12607
+ result[r][c] = area.toArrayValueObject(false).getRealValue(0, 0) ?? NullValueObject.create();
12608
+ }
12609
+ }
12610
+ return createNewArray(result, rows, cols);
12611
+ }
12612
+ _stackAreas() {
12613
+ const result = [];
12614
+ const cols = this.getColumnCount();
12615
+ for (const area of this._flatAreas()) {
12616
+ if (area instanceof ErrorValueObject) {
12617
+ const row = new Array(cols).fill(NullValueObject.create());
12618
+ row[0] = area;
12619
+ result.push(row);
12620
+ continue;
12621
+ }
12622
+ const array = area.toArrayValueObject(false);
12623
+ for (let r = 0; r < array.getRowCount(); r++) {
12624
+ const row = [];
12625
+ for (let c = 0; c < cols; c++) row[c] = array.getRealValue(r, c) ?? NullValueObject.create();
12626
+ result.push(row);
12627
+ }
12628
+ }
12629
+ return createNewArray(result, result.length, cols);
12630
+ }
12631
+ getRangePosition() {
12632
+ const flat = this._flatAreas();
12633
+ if (!flat.length) return super.getRangePosition();
12634
+ let minStartRow = Number.POSITIVE_INFINITY;
12635
+ let minStartColumn = Number.POSITIVE_INFINITY;
12636
+ let maxEndRow = Number.NEGATIVE_INFINITY;
12637
+ let maxEndColumn = Number.NEGATIVE_INFINITY;
12638
+ for (const area of flat) {
12639
+ if (!(area instanceof BaseReferenceObject)) continue;
12640
+ const { startRow, startColumn, endRow, endColumn } = area.getRangePosition();
12641
+ if (!Number.isFinite(startRow) || !Number.isFinite(startColumn) || !Number.isFinite(endRow) || !Number.isFinite(endColumn)) continue;
12642
+ if (startRow < minStartRow) minStartRow = startRow;
12643
+ if (startColumn < minStartColumn) minStartColumn = startColumn;
12644
+ if (endRow > maxEndRow) maxEndRow = endRow;
12645
+ if (endColumn > maxEndColumn) maxEndColumn = maxEndColumn < endColumn ? endColumn : maxEndColumn;
12646
+ }
12647
+ if (!Number.isFinite(minStartRow) || !Number.isFinite(minStartColumn) || !Number.isFinite(maxEndRow) || !Number.isFinite(maxEndColumn)) return super.getRangePosition();
12648
+ return {
12649
+ startRow: minStartRow,
12650
+ startColumn: minStartColumn,
12651
+ endRow: maxEndRow,
12652
+ endColumn: maxEndColumn
12653
+ };
12654
+ }
12655
+ toUnitRange() {
12656
+ return {
12657
+ range: this.getRangePosition(),
12658
+ sheetId: this.getSheetId(),
12659
+ unitId: this.getUnitId()
12660
+ };
12661
+ }
12662
+ toUnitRanges() {
12663
+ return this._flatAreas().filter((area) => area instanceof BaseReferenceObject).flatMap((area) => area.toUnitRanges());
12664
+ }
12665
+ getRangeData() {
12666
+ const flat = this._flatAreas();
12667
+ if (!flat.length) return super.getRangeData();
12668
+ let minStartRow = Number.POSITIVE_INFINITY;
12669
+ let minStartColumn = Number.POSITIVE_INFINITY;
12670
+ let maxEndRow = Number.NEGATIVE_INFINITY;
12671
+ let maxEndColumn = Number.NEGATIVE_INFINITY;
12672
+ for (const area of flat) {
12673
+ if (!(area instanceof BaseReferenceObject)) continue;
12674
+ const { startRow, startColumn, endRow, endColumn } = area.getRangeData();
12675
+ if (!Number.isFinite(startRow) || !Number.isFinite(startColumn) || !Number.isFinite(endRow) || !Number.isFinite(endColumn)) continue;
12676
+ if (startRow < minStartRow) minStartRow = startRow;
12677
+ if (startColumn < minStartColumn) minStartColumn = startColumn;
12678
+ if (endRow > maxEndRow) maxEndRow = endRow;
12679
+ if (endColumn > maxEndColumn) maxEndColumn = endColumn;
12680
+ }
12681
+ if (!Number.isFinite(minStartRow) || !Number.isFinite(minStartColumn) || !Number.isFinite(maxEndRow) || !Number.isFinite(maxEndColumn)) return super.getRangeData();
12682
+ return {
12683
+ startRow: minStartRow,
12684
+ startColumn: minStartColumn,
12685
+ endRow: maxEndRow,
12686
+ endColumn: maxEndColumn
12687
+ };
12688
+ }
12689
+ };
12690
+
12362
12691
  //#endregion
12363
12692
  //#region src/engine/ast-node/union-node.ts
12364
12693
  var UnionNode = class extends BaseAstNode {
12365
- constructor(operatorString) {
12694
+ constructor(operatorString, _currentConfigService) {
12366
12695
  super(operatorString);
12696
+ this._currentConfigService = _currentConfigService;
12367
12697
  }
12368
12698
  get nodeType() {
12369
12699
  return 10;
@@ -12380,28 +12710,74 @@ var UnionNode = class extends BaseAstNode {
12380
12710
  return;
12381
12711
  }
12382
12712
  let result;
12383
- if (this.getToken() === ":") result = this._unionFunction(leftNode, rightNode);
12713
+ if (this.getToken() === ":") result = this._createThreeDimensionalReference(leftChild.getToken(), rightNode) ?? this._unionFunction(leftNode, rightNode);
12384
12714
  else result = ErrorValueObject.create("#NAME?");
12385
12715
  this.setValue(result);
12386
12716
  }
12717
+ _createThreeDimensionalReference(firstSheetToken, rightNode) {
12718
+ if (!(rightNode instanceof BaseReferenceObject)) return;
12719
+ const source = rightNode;
12720
+ const firstSheetName = this._normalizeSheetName(firstSheetToken);
12721
+ const lastSheetName = this._normalizeSheetName(source.getForcedSheetName());
12722
+ if (!firstSheetName || !lastSheetName) return;
12723
+ const { sheetOrder, sheetNameMap } = this._currentConfigService.getSheetsInfo();
12724
+ const sheetIdsByName = new Map(Object.entries(sheetNameMap).map(([sheetId, sheetName]) => [sheetName.toLocaleLowerCase(), sheetId]));
12725
+ const firstSheetId = sheetIdsByName.get(firstSheetName.toLocaleLowerCase());
12726
+ const lastSheetId = sheetIdsByName.get(lastSheetName.toLocaleLowerCase());
12727
+ const firstIndex = firstSheetId == null ? -1 : sheetOrder.indexOf(firstSheetId);
12728
+ const lastIndex = lastSheetId == null ? -1 : sheetOrder.indexOf(lastSheetId);
12729
+ if (firstIndex < 0 || lastIndex < 0) return;
12730
+ const startIndex = Math.min(firstIndex, lastIndex);
12731
+ const endIndex = Math.max(firstIndex, lastIndex);
12732
+ const areas = sheetOrder.slice(startIndex, endIndex + 1).map((sheetId) => {
12733
+ const reference = new RangeReferenceObject(source.getRangeData(), sheetId, source.getUnitId());
12734
+ this._copyReferenceContext(source, reference);
12735
+ reference.setForcedSheetIdDirect(sheetId);
12736
+ reference.setForcedSheetName(sheetNameMap[sheetId] ?? "");
12737
+ return [reference];
12738
+ });
12739
+ return new MultiAreaReferenceObject(`${firstSheetToken}:${source.getToken()}`, areas, "stack-areas");
12740
+ }
12741
+ _normalizeSheetName(token) {
12742
+ const trimmed = token.trim();
12743
+ if (trimmed.startsWith("'") && trimmed.endsWith("'")) return trimmed.slice(1, -1).replace(/''/g, "'");
12744
+ return trimmed;
12745
+ }
12746
+ _copyReferenceContext(source, target) {
12747
+ target.setDefaultUnitId(source.getDefaultUnitId());
12748
+ target.setDefaultSheetId(source.getDefaultSheetId());
12749
+ target.setUnitData(source.getUnitData());
12750
+ target.setUnitStylesData(source.getUnitStylesData());
12751
+ target.setFilteredOutRows(source.getFilteredOutRows());
12752
+ target.setRuntimeData(source.getRuntimeData());
12753
+ target.setArrayFormulaCellData(source.getArrayFormulaCellData());
12754
+ target.setArrayFormulaRange(source.getArrayFormulaRange());
12755
+ target.setRuntimeArrayFormulaCellData(source.getRuntimeArrayFormulaCellData());
12756
+ target.setRuntimeArrayFormulaRange(source.getRuntimeArrayFormulaRange());
12757
+ target.setRuntimeFeatureCellData(source.getRuntimeFeatureCellData());
12758
+ const currentRow = source.getCurrentRow();
12759
+ const currentColumn = source.getCurrentColumn();
12760
+ if (currentRow != null && currentColumn != null) target.setCurrentRowAndColumn(currentRow, currentColumn);
12761
+ const { x, y } = source.getRefOffset();
12762
+ target.setRefOffset(x, y);
12763
+ }
12387
12764
  _unionFunction(variant1, variant2) {
12388
12765
  if (variant1.isError() || variant2.isError()) return ErrorValueObject.create("#REF!");
12389
- if (!variant1.isReferenceObject() || !variant2.isReferenceObject()) return ErrorValueObject.create("#REF!");
12390
- variant1 = variant1;
12391
- variant2 = variant2;
12766
+ if (!(variant1 instanceof BaseReferenceObject) || !(variant2 instanceof BaseReferenceObject)) return ErrorValueObject.create("#REF!");
12392
12767
  return getRangeReferenceObjectFromCache(variant1, variant2);
12393
12768
  }
12394
12769
  };
12395
12770
  let UnionNodeFactory = class UnionNodeFactory extends BaseAstNodeFactory {
12396
- constructor(_functionService) {
12771
+ constructor(_functionService, _currentConfigService) {
12397
12772
  super();
12398
12773
  this._functionService = _functionService;
12774
+ this._currentConfigService = _currentConfigService;
12399
12775
  }
12400
12776
  get zIndex() {
12401
12777
  return NODE_ORDER_MAP.get(10) || 100;
12402
12778
  }
12403
12779
  create(param) {
12404
- return new UnionNode(param);
12780
+ return new UnionNode(param, this._currentConfigService);
12405
12781
  }
12406
12782
  checkAndCreateNodeType(param) {
12407
12783
  if (!(param instanceof LexerNode)) return;
@@ -12411,7 +12787,7 @@ let UnionNodeFactory = class UnionNodeFactory extends BaseAstNodeFactory {
12411
12787
  return this.create(tokenTrim);
12412
12788
  }
12413
12789
  };
12414
- UnionNodeFactory = __decorate([__decorateParam(0, IFunctionService)], UnionNodeFactory);
12790
+ UnionNodeFactory = __decorate([__decorateParam(0, IFunctionService), __decorateParam(1, IFormulaCurrentConfigService)], UnionNodeFactory);
12415
12791
 
12416
12792
  //#endregion
12417
12793
  //#region src/engine/ast-node/value-node.ts
@@ -12432,8 +12808,8 @@ var ValueNode = class extends BaseAstNode {
12432
12808
  const parent = this.getParent();
12433
12809
  let isIgnoreNumberPattern = true;
12434
12810
  if ((parent === null || parent === void 0 ? void 0 : parent.nodeType) === 4) {
12435
- var _isFunctionExecutorAr, _isFunctionExecutorAr2;
12436
- isIgnoreNumberPattern = (_isFunctionExecutorAr = (_isFunctionExecutorAr2 = parent.isFunctionExecutorArgumentsIgnoreNumberPattern) === null || _isFunctionExecutorAr2 === void 0 ? void 0 : _isFunctionExecutorAr2.call(parent)) !== null && _isFunctionExecutorAr !== void 0 ? _isFunctionExecutorAr : true;
12811
+ var _isFunctionExecutorAr;
12812
+ isIgnoreNumberPattern = ((_isFunctionExecutorAr = parent.isFunctionExecutorArgumentsIgnoreNumberPattern) === null || _isFunctionExecutorAr === void 0 ? void 0 : _isFunctionExecutorAr.call(parent)) ?? true;
12437
12813
  }
12438
12814
  this.setValue(ValueObjectFactory.create(token, isIgnoreNumberPattern));
12439
12815
  }
@@ -12658,7 +13034,7 @@ let AstTreeBuilder = class AstTreeBuilder extends _univerjs_core.Disposable {
12658
13034
  if (astNode == null) {
12659
13035
  const aggregatorNode = this._createGroupByAggregatorTokenNode(item);
12660
13036
  if (aggregatorNode != null) return aggregatorNode;
12661
- return new ErrorFunctionNode();
13037
+ return new ErrorFunctionNode(typeof item === "string" ? item : item.getToken());
12662
13038
  }
12663
13039
  return astNode;
12664
13040
  }
@@ -13317,8 +13693,8 @@ var FormulaDependencyTreeVirtual = class extends FormulaDependencyTreeCalculator
13317
13693
  return this.refTree.subUnitId;
13318
13694
  }
13319
13695
  get formula() {
13320
- var _this$refTree$formula, _this$refTree;
13321
- return (_this$refTree$formula = (_this$refTree = this.refTree) === null || _this$refTree === void 0 ? void 0 : _this$refTree.formula) !== null && _this$refTree$formula !== void 0 ? _this$refTree$formula : "";
13696
+ var _this$refTree;
13697
+ return ((_this$refTree = this.refTree) === null || _this$refTree === void 0 ? void 0 : _this$refTree.formula) ?? "";
13322
13698
  }
13323
13699
  get nodeData() {
13324
13700
  return {
@@ -13552,13 +13928,12 @@ var FormulaDependencyTreeModel = class {
13552
13928
  this.refOffsetY = tree.refOffsetY;
13553
13929
  this.rangeList = tree.rangeList;
13554
13930
  if (tree.isVirtual) {
13555
- var _refTree$treeId, _refTree;
13556
- this.refTreeId = (_refTree$treeId = (_refTree = tree.refTree) === null || _refTree === void 0 ? void 0 : _refTree.treeId) !== null && _refTree$treeId !== void 0 ? _refTree$treeId : -1;
13931
+ var _refTree;
13932
+ this.refTreeId = ((_refTree = tree.refTree) === null || _refTree === void 0 ? void 0 : _refTree.treeId) ?? -1;
13557
13933
  } else {
13558
- var _formulaId, _featureId;
13559
13934
  this.formula = tree.formula;
13560
- this.formulaId = (_formulaId = tree.formulaId) !== null && _formulaId !== void 0 ? _formulaId : void 0;
13561
- this.featureId = (_featureId = tree.featureId) !== null && _featureId !== void 0 ? _featureId : void 0;
13935
+ this.formulaId = tree.formulaId ?? void 0;
13936
+ this.featureId = tree.featureId ?? void 0;
13562
13937
  this.type = tree.type;
13563
13938
  }
13564
13939
  }
@@ -13746,14 +14121,13 @@ let FormulaDependencyGenerator = class FormulaDependencyGenerator extends _unive
13746
14121
  const columnCount = sheetSize.columnCount > 0 ? sheetSize.columnCount : 1;
13747
14122
  const subFormulaDataKeys = Object.keys(subFormulaData);
13748
14123
  for (const subFormulaDataId of subFormulaDataKeys) {
13749
- var _treeMatrix$getValue;
13750
14124
  const hasOtherFormula = this._dependencyManagerService.hasOtherFormulaDataMainData(subFormulaDataId);
13751
14125
  const { f: formulaString, ranges } = subFormulaData[subFormulaDataId];
13752
14126
  let isCache = false;
13753
14127
  if (hasOtherFormula) isCache = true;
13754
14128
  const { firstRow, firstColumn } = this._getFirstCellOfRange(ranges);
13755
14129
  const treeMatrix = this._dependencyManagerService.getOtherFormulaDependency(unitId, subUnitId, subFormulaDataId);
13756
- const firstFDtree = new FormulaDependencyTree((_treeMatrix$getValue = treeMatrix === null || treeMatrix === void 0 ? void 0 : treeMatrix.getValue(0, 0)) !== null && _treeMatrix$getValue !== void 0 ? _treeMatrix$getValue : generateRandomDependencyTreeId(this._dependencyManagerService));
14130
+ const firstFDtree = new FormulaDependencyTree((treeMatrix === null || treeMatrix === void 0 ? void 0 : treeMatrix.getValue(0, 0)) ?? generateRandomDependencyTreeId(this._dependencyManagerService));
13757
14131
  for (let i = 0; i < ranges.length; i++) {
13758
14132
  const range = ranges[i];
13759
14133
  const { startRow, startColumn } = range;
@@ -13887,7 +14261,7 @@ let FormulaDependencyGenerator = class FormulaDependencyGenerator extends _unive
13887
14261
  return this._dependencyTreeCache.get(treeId);
13888
14262
  }
13889
14263
  _getTreeNode(tree) {
13890
- return generateAstNode(tree.unitId, tree.formula, this._lexer, this._astTreeBuilder, this._currentConfigService, tree.subUnitId);
14264
+ return generateAstNode(tree.unitId, tree.formula, this._lexer, this._astTreeBuilder, this._currentConfigService, tree.subUnitId, tree.column, tree.row);
13891
14265
  }
13892
14266
  *_traverse(treeList, skippedTreeIds) {
13893
14267
  const stack = treeList;
@@ -14123,15 +14497,13 @@ let FormulaDependencyGenerator = class FormulaDependencyGenerator extends _unive
14123
14497
  }
14124
14498
  }
14125
14499
  async _executeNode(node, refOffsetX = 0, refOffsetY = 0) {
14126
- let value;
14127
14500
  const nodeData = {
14128
14501
  node,
14129
14502
  refOffsetX,
14130
14503
  refOffsetY
14131
14504
  };
14132
- if (this._interpreter.checkAsyncNode(node)) value = await this._interpreter.executeAsync(nodeData);
14133
- else value = this._interpreter.execute(nodeData);
14134
- return value;
14505
+ const value = this._interpreter.checkAsyncNode(node) ? await this._interpreter.executeAsync(nodeData) : this._interpreter.execute(nodeData);
14506
+ return value instanceof BaseReferenceObject ? value : null;
14135
14507
  }
14136
14508
  /**
14137
14509
  * Calculate the range required for collection in advance,
@@ -14148,8 +14520,8 @@ let FormulaDependencyGenerator = class FormulaDependencyGenerator extends _unive
14148
14520
  const rangeList = [];
14149
14521
  for (let i = 0, len = preCalculateNodeList.length; i < len; i++) {
14150
14522
  const node = preCalculateNodeList[i];
14151
- const gridRange = (await this._executeNode(node, refOffsetX, refOffsetY)).toUnitRange();
14152
- rangeList.push(gridRange);
14523
+ const value = await this._executeNode(node, refOffsetX, refOffsetY);
14524
+ if (value != null) rangeList.push(...value.toUnitRanges());
14153
14525
  node.setValue(null);
14154
14526
  }
14155
14527
  return rangeList;
@@ -14284,8 +14656,8 @@ let FormulaDependencyGenerator = class FormulaDependencyGenerator extends _unive
14284
14656
  const rangeList = [];
14285
14657
  for (let i = 0, len = referenceFunctionList.length; i < len; i++) {
14286
14658
  const node = referenceFunctionList[i];
14287
- const gridRange = (await this._executeNode(node, refOffsetX, refOffsetY)).toUnitRange();
14288
- rangeList.push(gridRange);
14659
+ const value = await this._executeNode(node, refOffsetX, refOffsetY);
14660
+ if (value != null) rangeList.push(...value.toUnitRanges());
14289
14661
  node.setValue(null);
14290
14662
  }
14291
14663
  return rangeList;
@@ -14658,7 +15030,7 @@ let CalculateFormulaService = class CalculateFormulaService extends _univerjs_co
14658
15030
  while (treeList.length > 0) {
14659
15031
  const tree = treeList.pop();
14660
15032
  this._runtimeService.setCurrent(tree.row, tree.column, tree.rowCount, tree.columnCount, tree.subUnitId, tree.unitId);
14661
- const node = generateAstNode(tree.unitId, tree.formula, this._lexer, this._astTreeBuilder, this._currentConfigService, tree.subUnitId);
15033
+ const node = generateAstNode(tree.unitId, tree.formula, this._lexer, this._astTreeBuilder, this._currentConfigService, tree.subUnitId, tree.column, tree.row);
14662
15034
  const nodeData = {
14663
15035
  node,
14664
15036
  refOffsetX: tree.refOffsetX,
@@ -14940,7 +15312,7 @@ let CalculateController = class CalculateController extends _univerjs_core.Dispo
14940
15312
  if (dependencyTreeModelData.length > 0) this._commandService.executeCommand(SetFormulaDependencyCalculationResultMutation.id, { result: dependencyTreeModelData }, { onlyLocal: true });
14941
15313
  }
14942
15314
  async _applyResult(data) {
14943
- const { unitData, unitOtherData, arrayFormulaRange, arrayFormulaCellData, clearArrayFormulaCellData, arrayFormulaEmbedded, imageFormulaData, dependencyTreeModelData } = data;
15315
+ const { unitData, unitOtherData, arrayFormulaRange, arrayFormulaCellData, clearArrayFormulaCellData, arrayFormulaEmbedded, imageFormulaData } = data;
14944
15316
  if (!unitData) {
14945
15317
  this._applyTreeResult(data);
14946
15318
  console.error("No sheetData from Formula Engine!");
@@ -15076,8 +15448,7 @@ var FormulaCalculationSessionService = class extends _univerjs_core.Disposable {
15076
15448
  }
15077
15449
  markResultApplied(type = "sheet", result) {
15078
15450
  if (result && this._currentResult !== result) {
15079
- var _this$_preAppliedResu;
15080
- const types = (_this$_preAppliedResu = this._preAppliedResultTypes.get(result)) !== null && _this$_preAppliedResu !== void 0 ? _this$_preAppliedResu : /* @__PURE__ */ new Set();
15451
+ const types = this._preAppliedResultTypes.get(result) ?? /* @__PURE__ */ new Set();
15081
15452
  types.add(type);
15082
15453
  this._preAppliedResultTypes.set(result, types);
15083
15454
  return;
@@ -15253,13 +15624,13 @@ let RegisterOtherFormulaService = class RegisterOtherFormulaService extends _uni
15253
15624
  this._activeDirtyManagerService = _activeDirtyManagerService;
15254
15625
  this._lifecycleService = _lifecycleService;
15255
15626
  _defineProperty(this, "_formulaCacheMap", /* @__PURE__ */ new Map());
15627
+ _defineProperty(this, "_mutationSyncHandler", void 0);
15256
15628
  _defineProperty(this, "_formulaChangeWithRange$", new rxjs.Subject());
15257
15629
  _defineProperty(this, "formulaChangeWithRange$", this._formulaChangeWithRange$.asObservable());
15258
15630
  _defineProperty(this, "_formulaResult$", new rxjs.Subject());
15259
15631
  _defineProperty(this, "formulaResult$", this._formulaResult$.asObservable());
15260
15632
  _defineProperty(this, "_otherFormulaResultApplied$", new rxjs.Subject());
15261
15633
  _defineProperty(this, "otherFormulaResultApplied$", this._otherFormulaResultApplied$.asObservable());
15262
- _defineProperty(this, "calculateStarted$", new rxjs.BehaviorSubject(false));
15263
15634
  this._initFormulaRegister();
15264
15635
  this._initFormulaCalculationResultChange();
15265
15636
  }
@@ -15268,7 +15639,6 @@ let RegisterOtherFormulaService = class RegisterOtherFormulaService extends _uni
15268
15639
  this._formulaChangeWithRange$.complete();
15269
15640
  this._formulaResult$.complete();
15270
15641
  this._otherFormulaResultApplied$.complete();
15271
- this.calculateStarted$.complete();
15272
15642
  }
15273
15643
  _ensureCacheMap(unitId, subUnitId) {
15274
15644
  let unitMap = this._formulaCacheMap.get(unitId);
@@ -15294,6 +15664,7 @@ let RegisterOtherFormulaService = class RegisterOtherFormulaService extends _uni
15294
15664
  }
15295
15665
  });
15296
15666
  const handleRegister = (option) => {
15667
+ var _this$_mutationSyncHa;
15297
15668
  const { unitId, subUnitId, formulaText, formulaId, ranges } = option;
15298
15669
  if (!this._ensureCacheMap(unitId, subUnitId).has(formulaId)) return;
15299
15670
  const params = {
@@ -15304,13 +15675,29 @@ let RegisterOtherFormulaService = class RegisterOtherFormulaService extends _uni
15304
15675
  ranges
15305
15676
  } }
15306
15677
  };
15307
- this._commandService.executeCommand(SetOtherFormulaMutation.id, params, { onlyLocal: true }).then(() => {
15678
+ const waitForMutationSync = (_this$_mutationSyncHa = this._mutationSyncHandler) === null || _this$_mutationSyncHa === void 0 ? void 0 : _this$_mutationSyncHa.call(this, unitId);
15679
+ this._commandService.executeCommand(SetOtherFormulaMutation.id, params, { onlyLocal: true }).then(async () => {
15680
+ if (this._disposed) return;
15681
+ await (waitForMutationSync === null || waitForMutationSync === void 0 ? void 0 : waitForMutationSync());
15308
15682
  if (this._disposed) return;
15309
15683
  this._commandService.executeCommand(OtherFormulaMarkDirty.id, { [unitId]: { [subUnitId]: { [formulaId]: true } } }, { onlyLocal: true });
15310
15684
  });
15311
15685
  };
15312
- this.disposeWithMe(this._formulaChangeWithRange$.pipe((0, rxjs.bufferWhen)(() => this.calculateStarted$.pipe((0, rxjs.skip)(1), (0, rxjs.filter)((calculateStarted) => calculateStarted)))).subscribe((options) => options.forEach(handleRegister)));
15313
- this.disposeWithMe(this._formulaChangeWithRange$.pipe((0, rxjs.filter)(() => this.calculateStarted$.getValue())).subscribe(handleRegister));
15686
+ this.disposeWithMe(this._formulaChangeWithRange$.subscribe((option) => {
15687
+ if (this._commandService.hasCommand(SetOtherFormulaMutation.id) && this._commandService.hasCommand(OtherFormulaMarkDirty.id)) {
15688
+ handleRegister(option);
15689
+ return;
15690
+ }
15691
+ this._lifecycleService.onStage(_univerjs_core.LifecycleStages.Ready).then(() => {
15692
+ if (!this._disposed) handleRegister(option);
15693
+ });
15694
+ }));
15695
+ }
15696
+ setMutationSyncHandler(handler) {
15697
+ this._mutationSyncHandler = handler;
15698
+ return (0, _univerjs_core.toDisposable)(() => {
15699
+ if (this._mutationSyncHandler === handler) this._mutationSyncHandler = void 0;
15700
+ });
15314
15701
  }
15315
15702
  _initFormulaCalculationResultChange() {
15316
15703
  this.disposeWithMe(this._commandService.onCommandExecuted((commandInfo) => {
@@ -15382,11 +15769,13 @@ let RegisterOtherFormulaService = class RegisterOtherFormulaService extends _uni
15382
15769
  return Object.fromEntries(Array.from(unitMap.entries(), ([subUnitId, formulas]) => [subUnitId, Object.fromEntries(Array.from(formulas.keys(), (formulaId) => [formulaId, true]))]));
15383
15770
  }
15384
15771
  deleteFormula(unitId, subUnitId, formulaIdList) {
15772
+ var _this$_mutationSyncHa2;
15385
15773
  const params = {
15386
15774
  unitId,
15387
15775
  subUnitId,
15388
15776
  formulaIdList
15389
15777
  };
15778
+ (_this$_mutationSyncHa2 = this._mutationSyncHandler) === null || _this$_mutationSyncHa2 === void 0 || _this$_mutationSyncHa2.call(this, unitId);
15390
15779
  this._commandService.executeCommand(RemoveOtherFormulaMutation.id, params, { onlyLocal: true });
15391
15780
  const cacheMap = this._ensureCacheMap(unitId, subUnitId);
15392
15781
  formulaIdList.forEach((id) => cacheMap.delete(id));
@@ -15639,8 +16028,7 @@ function refactorReferenceSegment(segment, oldName, newName) {
15639
16028
  const escapedName = newName.replace(/'/g, "''");
15640
16029
  return quote ? `'[${escapedName}]${sheetName}'!` : `[${newName}]${sheetName}!`;
15641
16030
  }).replace(TABLE_UNIT_QUALIFIER, (token, boundary, quoted, bracketed, plain) => {
15642
- var _ref, _ref2;
15643
- if (!equalsQualifier((_ref = (_ref2 = quoted !== null && quoted !== void 0 ? quoted : bracketed) !== null && _ref2 !== void 0 ? _ref2 : plain) !== null && _ref !== void 0 ? _ref : "", oldName)) return token;
16031
+ if (!equalsQualifier(quoted ?? bracketed ?? plain ?? "", oldName)) return token;
15644
16032
  if (quoted != null) return `${boundary}'${newName.replace(/'/g, "''")}'!`;
15645
16033
  if (bracketed != null) return `${boundary}[${newName}]!`;
15646
16034
  return `${boundary}${quoteQualifier(newName)}!`;
@@ -15698,11 +16086,10 @@ function shouldAppendOpenBracket(functionType) {
15698
16086
  return functionType !== 16 && functionType !== 17;
15699
16087
  }
15700
16088
  function getFormulaReplaceResult(nodes, index, formulaName, functionType) {
15701
- var _cloneNodes$pop;
15702
16089
  if (index === -1) return;
15703
16090
  const cloneNodes = [...nodes];
15704
16091
  const lastNodes = cloneNodes.splice(index + 1);
15705
- const oldNode = (_cloneNodes$pop = cloneNodes.pop()) !== null && _cloneNodes$pop !== void 0 ? _cloneNodes$pop : "";
16092
+ const oldNode = cloneNodes.pop() ?? "";
15706
16093
  let offset = (typeof oldNode === "string" ? oldNode.length : oldNode.token.length) - formulaName.length;
15707
16094
  cloneNodes.push(formulaName);
15708
16095
  if (lastNodes[0] !== "(" && shouldAppendOpenBracket(functionType)) {
@@ -15764,12 +16151,11 @@ function isFormulaReferenceAddingTextContext(formulaText, offset) {
15764
16151
  return Boolean(character && matchRefDrawToken(character) && (!nextCharacter || isFormulaLexerToken(nextCharacter) && nextCharacter !== "("));
15765
16152
  }
15766
16153
  function resolveFormulaReferenceEditingContext(options) {
15767
- var _options$selectionSta, _options$selectionEnd;
15768
16154
  const { formulaText, sequenceNodes } = options;
15769
16155
  const offset = Math.max(0, Math.min(options.offset, formulaText.length));
15770
16156
  let nodeIndex = getFormulaSequenceNodeIndex(sequenceNodes, offset);
15771
- const selectionStart = (_options$selectionSta = options.selectionStart) !== null && _options$selectionSta !== void 0 ? _options$selectionSta : offset;
15772
- const selectionEnd = (_options$selectionEnd = options.selectionEnd) !== null && _options$selectionEnd !== void 0 ? _options$selectionEnd : selectionStart;
16157
+ const selectionStart = options.selectionStart ?? offset;
16158
+ const selectionEnd = options.selectionEnd ?? selectionStart;
15773
16159
  if (selectionEnd > selectionStart) nodeIndex = sequenceNodes.findIndex((node) => typeof node !== "string" && isFormulaReferenceNode(node) && node.startIndex < selectionEnd && node.endIndex + 1 > selectionStart);
15774
16160
  const referenceIndex = getFormulaReferenceIndex(sequenceNodes, nodeIndex);
15775
16161
  if (referenceIndex !== -1) return {
@@ -15786,7 +16172,7 @@ function resolveFormulaReferenceEditingContext(options) {
15786
16172
  };
15787
16173
  }
15788
16174
  function getFormulaHighlightDataStream(leadingCharacter, sequenceNodes, sourceText) {
15789
- return `${leadingCharacter}${sourceText !== null && sourceText !== void 0 ? sourceText : sequenceNodes.map((node) => typeof node === "string" ? node : node.token).join("")}\r\n`;
16175
+ return `${leadingCharacter}${sourceText ?? sequenceNodes.map((node) => typeof node === "string" ? node : node.token).join("")}\r\n`;
15790
16176
  }
15791
16177
  function buildFormulaTextRuns(descriptionService, colors, sequenceNodes, options) {
15792
16178
  const textRuns = [];
@@ -15796,16 +16182,15 @@ function buildFormulaTextRuns(descriptionService, colors, sequenceNodes, options
15796
16182
  for (let index = 0; index < sequenceNodes.length; index++) {
15797
16183
  const node = sequenceNodes[index];
15798
16184
  if (typeof node === "string") {
15799
- var _textRuns$at$ed, _textRuns$at;
15800
- const start = (_textRuns$at$ed = (_textRuns$at = textRuns.at(-1)) === null || _textRuns$at === void 0 ? void 0 : _textRuns$at.ed) !== null && _textRuns$at$ed !== void 0 ? _textRuns$at$ed : 0;
16185
+ var _textRuns;
16186
+ const start = ((_textRuns = textRuns[textRuns.length - 1]) === null || _textRuns === void 0 ? void 0 : _textRuns.ed) ?? 0;
15801
16187
  textRuns.push(createTextRun(start, start + node.length, colors.plainTextColor));
15802
16188
  continue;
15803
16189
  }
15804
16190
  let color = colors.plainTextColor;
15805
16191
  if (!descriptionService.hasDefinedNameDescription(node.token.trim())) {
15806
16192
  if (isFormulaReferenceNode(node)) {
15807
- var _referenceColors$get;
15808
- color = (_referenceColors$get = referenceColors.get(node.token)) !== null && _referenceColors$get !== void 0 ? _referenceColors$get : colors.formulaRefColors[refColorIndex % colors.formulaRefColors.length];
16193
+ color = referenceColors.get(node.token) ?? colors.formulaRefColors[refColorIndex % colors.formulaRefColors.length];
15809
16194
  if (!referenceColors.has(node.token)) {
15810
16195
  referenceColors.set(node.token, color);
15811
16196
  refColorIndex += 1;
@@ -15857,13 +16242,13 @@ function applyTextRunColor(textRuns, start, end, color) {
15857
16242
  continue;
15858
16243
  }
15859
16244
  if (run.st < start) {
15860
- var _run$ts$cl$rgb, _run$ts;
15861
- nextRuns.push(createTextRun(run.st, start, (_run$ts$cl$rgb = (_run$ts = run.ts) === null || _run$ts === void 0 || (_run$ts = _run$ts.cl) === null || _run$ts === void 0 ? void 0 : _run$ts.rgb) !== null && _run$ts$cl$rgb !== void 0 ? _run$ts$cl$rgb : color));
16245
+ var _run$ts;
16246
+ nextRuns.push(createTextRun(run.st, start, ((_run$ts = run.ts) === null || _run$ts === void 0 || (_run$ts = _run$ts.cl) === null || _run$ts === void 0 ? void 0 : _run$ts.rgb) ?? color));
15862
16247
  }
15863
16248
  nextRuns.push(createTextRun(Math.max(run.st, start), Math.min(run.ed, end), color));
15864
16249
  if (run.ed > end) {
15865
- var _run$ts$cl$rgb2, _run$ts2;
15866
- nextRuns.push(createTextRun(end, run.ed, (_run$ts$cl$rgb2 = (_run$ts2 = run.ts) === null || _run$ts2 === void 0 || (_run$ts2 = _run$ts2.cl) === null || _run$ts2 === void 0 ? void 0 : _run$ts2.rgb) !== null && _run$ts$cl$rgb2 !== void 0 ? _run$ts$cl$rgb2 : color));
16250
+ var _run$ts2;
16251
+ nextRuns.push(createTextRun(end, run.ed, ((_run$ts2 = run.ts) === null || _run$ts2 === void 0 || (_run$ts2 = _run$ts2.cl) === null || _run$ts2 === void 0 ? void 0 : _run$ts2.rgb) ?? color));
15867
16252
  }
15868
16253
  }
15869
16254
  textRuns.splice(0, textRuns.length, ...nextRuns);
@@ -16059,6 +16444,14 @@ var BaseFunction = class {
16059
16444
  "needsAstChildren",
16060
16445
  false
16061
16446
  );
16447
+ _defineProperty(
16448
+ this,
16449
+ /**
16450
+ * Arguments that preserve a selected lazy IF branch as a reference array.
16451
+ */
16452
+ "lazyIfReferenceArrayArgumentIndexes",
16453
+ []
16454
+ );
16062
16455
  _defineProperty(
16063
16456
  this,
16064
16457
  /**
@@ -16271,8 +16664,8 @@ var BaseFunction = class {
16271
16664
  if (isFirst) return this._getOneFirstByRaw(resultArrayValue);
16272
16665
  return this._getOneLastByRaw(resultArrayValue);
16273
16666
  }
16274
- orderSearch(value, searchArray, resultArray, searchType = 1, isDesc = false) {
16275
- const position = searchArray.orderSearch(value, searchType, isDesc);
16667
+ orderSearch(value, searchArray, resultArray, searchType = 1, isDesc = false, keepFirstNearest = false) {
16668
+ const position = searchArray.orderSearch(value, searchType, isDesc, false, keepFirstNearest);
16276
16669
  if (position == null) return ErrorValueObject.create("#N/A");
16277
16670
  const resultValue = resultArray.get(position.row, position.column) || NullValueObject.create();
16278
16671
  if (resultValue.isNull()) return ErrorValueObject.create("#N/A");
@@ -16302,8 +16695,8 @@ var BaseFunction = class {
16302
16695
  if (axis === 0) return resultArray.slice([position.row, position.row + 1]);
16303
16696
  return resultArray.slice(void 0, [position.column, position.column + 1]);
16304
16697
  }
16305
- orderSearchExpand(value, searchArray, resultArray, searchType = 1, isDesc = false, axis = 0) {
16306
- const position = searchArray.orderSearch(value, searchType, isDesc);
16698
+ orderSearchExpand(value, searchArray, resultArray, searchType = 1, isDesc = false, axis = 0, keepFirstNearest = false) {
16699
+ const position = searchArray.orderSearch(value, searchType, isDesc, false, keepFirstNearest);
16307
16700
  if (position == null) return ErrorValueObject.create("#N/A");
16308
16701
  if (axis === 0) return resultArray.slice([position.row, position.row + 1]);
16309
16702
  return resultArray.slice(void 0, [position.column, position.column + 1]);
@@ -18242,7 +18635,7 @@ function getAggregateResult(options, refs) {
18242
18635
  return result;
18243
18636
  }
18244
18637
  function getArrayValuesByAggregateIgnoreOptions(array, options, formulaDataModel) {
18245
- const { ignoreRowHidden = false, ignoreErrorValues = false, ignoreNested = false } = options !== null && options !== void 0 ? options : {};
18638
+ const { ignoreRowHidden = false, ignoreErrorValues = false, ignoreNested = false } = options ?? {};
18246
18639
  const values = [];
18247
18640
  if (array.isReferenceObject()) {
18248
18641
  var _unitData$unitId2;
@@ -18368,8 +18761,8 @@ var BetaInv = class extends BaseFunction {
18368
18761
  _defineProperty(this, "maxParams", 5);
18369
18762
  }
18370
18763
  calculate(probability, alpha, beta, A, B) {
18371
- let _A = A !== null && A !== void 0 ? A : NumberValueObject.create(0);
18372
- let _B = B !== null && B !== void 0 ? B : NumberValueObject.create(1);
18764
+ let _A = A ?? NumberValueObject.create(0);
18765
+ let _B = B ?? NumberValueObject.create(1);
18373
18766
  if (_A.isNull()) _A = NumberValueObject.create(0);
18374
18767
  if (_B.isNull()) _B = NumberValueObject.create(1);
18375
18768
  const maxRowLength = Math.max(probability.isArray() ? probability.getRowCount() : 1, alpha.isArray() ? alpha.getRowCount() : 1, beta.isArray() ? beta.getRowCount() : 1, _A.isArray() ? _A.getRowCount() : 1, _B.isArray() ? _B.getRowCount() : 1);
@@ -19172,6 +19565,7 @@ var PercentileInc = class extends BaseFunction {
19172
19565
  super(..._args);
19173
19566
  _defineProperty(this, "minParams", 2);
19174
19567
  _defineProperty(this, "maxParams", 2);
19568
+ _defineProperty(this, "lazyIfReferenceArrayArgumentIndexes", [0]);
19175
19569
  }
19176
19570
  calculate(array, k) {
19177
19571
  const arrayValues = getArrayValuesByAggregateIgnoreOptions(array);
@@ -19201,7 +19595,7 @@ var PercentrankInc = class extends BaseFunction {
19201
19595
  }
19202
19596
  calculate(array, x, significance) {
19203
19597
  const arrayValues = this._getValues(array);
19204
- let _significance = significance !== null && significance !== void 0 ? significance : NumberValueObject.create(3);
19598
+ let _significance = significance ?? NumberValueObject.create(3);
19205
19599
  if (_significance.isNull()) _significance = NumberValueObject.create(3);
19206
19600
  const maxRowLength = Math.max(x.isArray() ? x.getRowCount() : 1, _significance.isArray() ? _significance.getRowCount() : 1);
19207
19601
  const maxColumnLength = Math.max(x.isArray() ? x.getColumnCount() : 1, _significance.isArray() ? _significance.getColumnCount() : 1);
@@ -19763,8 +20157,8 @@ var Betadist = class extends BaseFunction {
19763
20157
  _defineProperty(this, "maxParams", 5);
19764
20158
  }
19765
20159
  calculate(x, alpha, beta, A, B) {
19766
- let _A = A !== null && A !== void 0 ? A : NumberValueObject.create(0);
19767
- let _B = B !== null && B !== void 0 ? B : NumberValueObject.create(1);
20160
+ let _A = A ?? NumberValueObject.create(0);
20161
+ let _B = B ?? NumberValueObject.create(1);
19768
20162
  if (_A.isNull()) _A = NumberValueObject.create(0);
19769
20163
  if (_B.isNull()) _B = NumberValueObject.create(1);
19770
20164
  const maxRowLength = Math.max(x.isArray() ? x.getRowCount() : 1, alpha.isArray() ? alpha.getRowCount() : 1, beta.isArray() ? beta.getRowCount() : 1, _A.isArray() ? _A.getRowCount() : 1, _B.isArray() ? _B.getRowCount() : 1);
@@ -20020,12 +20414,13 @@ var Rank = class extends BaseFunction {
20020
20414
  _defineProperty(this, "minParams", 2);
20021
20415
  _defineProperty(this, "maxParams", 3);
20022
20416
  _defineProperty(this, "needsReferenceObject", true);
20417
+ _defineProperty(this, "lazyIfReferenceArrayArgumentIndexes", [1]);
20023
20418
  }
20024
20419
  calculate(number, ref, order) {
20025
20420
  let _number = number;
20026
20421
  if (_number.isReferenceObject()) _number = _number.toArrayValueObject();
20027
20422
  const { refHasError, refErrorObject, refNumbers } = this._checkRefReferenceObject(ref);
20028
- let _order = order !== null && order !== void 0 ? order : NumberValueObject.create(0);
20423
+ let _order = order ?? NumberValueObject.create(0);
20029
20424
  if (_order.isReferenceObject()) _order = _order.toArrayValueObject();
20030
20425
  const maxRowLength = Math.max(_number.isArray() ? _number.getRowCount() : 1, _order.isArray() ? _order.getRowCount() : 1);
20031
20426
  const maxColumnLength = Math.max(_number.isArray() ? _number.getColumnCount() : 1, _order.isArray() ? _order.getColumnCount() : 1);
@@ -21062,7 +21457,7 @@ var Days360 = class extends BaseFunction {
21062
21457
  _defineProperty(this, "maxParams", 3);
21063
21458
  }
21064
21459
  calculate(startDate, endDate, method) {
21065
- const _method = method !== null && method !== void 0 ? method : BooleanValueObject.create(false);
21460
+ const _method = method ?? BooleanValueObject.create(false);
21066
21461
  if (startDate.isError()) return startDate;
21067
21462
  if (endDate.isError()) return endDate;
21068
21463
  if (_method.isError()) return _method;
@@ -21176,7 +21571,7 @@ var Epochtodate = class extends BaseFunction {
21176
21571
  _defineProperty(this, "needsReferenceObject", true);
21177
21572
  }
21178
21573
  calculate(timestamp, unit) {
21179
- const _unit = unit !== null && unit !== void 0 ? unit : NumberValueObject.create(1);
21574
+ const _unit = unit ?? NumberValueObject.create(1);
21180
21575
  const { isError, errorObject, timestampIsReferenceObject, timestampObject, unitObject } = this._checkVariants(timestamp, _unit);
21181
21576
  if (isError) return errorObject;
21182
21577
  if (timestampObject.isNull() || timestampObject.isBoolean() || timestampObject.isString()) return ErrorValueObject.create("#VALUE!");
@@ -21683,7 +22078,7 @@ var Today = class extends BaseFunction {
21683
22078
  }
21684
22079
  calculate() {
21685
22080
  const now = /* @__PURE__ */ new Date();
21686
- const currentSerial = excelDateSerial(new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate())));
22081
+ const currentSerial = excelDateSerial(new Date(Date.UTC(now.getFullYear(), now.getMonth(), now.getDate())));
21687
22082
  return NumberValueObject.create(currentSerial, DEFAULT_DATE_FORMAT);
21688
22083
  }
21689
22084
  };
@@ -21789,7 +22184,7 @@ var Weekday = class extends BaseFunction {
21789
22184
  });
21790
22185
  }
21791
22186
  calculate(serialNumber, returnType) {
21792
- const _returnType = returnType !== null && returnType !== void 0 ? returnType : NumberValueObject.create(1);
22187
+ const _returnType = returnType ?? NumberValueObject.create(1);
21793
22188
  if (serialNumber.isError()) return serialNumber;
21794
22189
  if (_returnType.isError()) return _returnType;
21795
22190
  const maxRowLength = Math.max(serialNumber.isArray() ? serialNumber.getRowCount() : 1, _returnType.isArray() ? _returnType.getRowCount() : 1);
@@ -21843,7 +22238,7 @@ var Weeknum = class extends BaseFunction {
21843
22238
  }
21844
22239
  calculate(serialNumber, returnType) {
21845
22240
  let _serialNumber = serialNumber;
21846
- let _returnType = returnType !== null && returnType !== void 0 ? returnType : NumberValueObject.create(1);
22241
+ let _returnType = returnType ?? NumberValueObject.create(1);
21847
22242
  if (_serialNumber.isArray()) {
21848
22243
  const rowCount = _serialNumber.getRowCount();
21849
22244
  const columnCount = _serialNumber.getColumnCount();
@@ -21977,7 +22372,7 @@ var WorkdayIntl = class extends BaseFunction {
21977
22372
  return this._handleSingleObject(startDate, days, weekend, holidays);
21978
22373
  }
21979
22374
  _handleSingleObject(startDate, days, weekend, holidays) {
21980
- const _weekend = weekend !== null && weekend !== void 0 ? weekend : NumberValueObject.create(1);
22375
+ const _weekend = weekend ?? NumberValueObject.create(1);
21981
22376
  const _startDate = this._checkArrayError(startDate);
21982
22377
  if (_startDate.isError()) return _startDate;
21983
22378
  const _days = this._checkArrayError(days);
@@ -22074,7 +22469,7 @@ var Yearfrac = class extends BaseFunction {
22074
22469
  _defineProperty(this, "maxParams", 3);
22075
22470
  }
22076
22471
  calculate(startDate, endDate, basis) {
22077
- let _basis = basis !== null && basis !== void 0 ? basis : NumberValueObject.create(0);
22472
+ let _basis = basis ?? NumberValueObject.create(0);
22078
22473
  const _startDate = checkVariantErrorIsArray(startDate);
22079
22474
  if (_startDate.isError()) return _startDate;
22080
22475
  const _endDate = checkVariantErrorIsArray(endDate);
@@ -22919,7 +23314,7 @@ var Complex = class extends BaseFunction {
22919
23314
  _defineProperty(this, "maxParams", 3);
22920
23315
  }
22921
23316
  calculate(realNum, iNum, suffix) {
22922
- const { isError, errorObject, variants } = checkVariantsErrorIsArrayOrBoolean(realNum, iNum, suffix !== null && suffix !== void 0 ? suffix : StringValueObject.create("i"));
23317
+ const { isError, errorObject, variants } = checkVariantsErrorIsArrayOrBoolean(realNum, iNum, suffix ?? StringValueObject.create("i"));
22923
23318
  if (isError) return errorObject;
22924
23319
  const [realNumObject, iNumObject, suffixObject] = variants;
22925
23320
  const realNumValue = +realNumObject.getValue();
@@ -24719,7 +25114,7 @@ var Delta = class extends BaseFunction {
24719
25114
  _defineProperty(this, "maxParams", 2);
24720
25115
  }
24721
25116
  calculate(number1, number2) {
24722
- const { isError, errorObject, variants } = checkVariantsErrorIsArrayOrBoolean(number1, number2 !== null && number2 !== void 0 ? number2 : NumberValueObject.create(0));
25117
+ const { isError, errorObject, variants } = checkVariantsErrorIsArrayOrBoolean(number1, number2 ?? NumberValueObject.create(0));
24723
25118
  if (isError) return errorObject;
24724
25119
  const [number1Object, number2Object] = variants;
24725
25120
  const number1Value = +number1Object.getValue();
@@ -24827,7 +25222,7 @@ var Gestep = class extends BaseFunction {
24827
25222
  }
24828
25223
  calculate(number, step) {
24829
25224
  if (number.isNull()) return ErrorValueObject.create("#N/A");
24830
- const { isError, errorObject, variants } = checkVariantsErrorIsArrayOrBoolean(number, step !== null && step !== void 0 ? step : NumberValueObject.create(0));
25225
+ const { isError, errorObject, variants } = checkVariantsErrorIsArrayOrBoolean(number, step ?? NumberValueObject.create(0));
24831
25226
  if (isError) return errorObject;
24832
25227
  const [numberObject, stepObject] = variants;
24833
25228
  const numberValue = +numberObject.getValue();
@@ -25223,7 +25618,7 @@ var Imlog = class extends BaseFunction {
25223
25618
  const { isError, errorObject, variants } = checkVariantsErrorIsArrayOrBoolean(inumber);
25224
25619
  if (isError) return errorObject;
25225
25620
  const [inumberObject] = variants;
25226
- let _base = base !== null && base !== void 0 ? base : NumberValueObject.create(10);
25621
+ let _base = base ?? NumberValueObject.create(10);
25227
25622
  if (_base.isArray()) {
25228
25623
  const rowCount = _base.getRowCount();
25229
25624
  const columnCount = _base.getColumnCount();
@@ -26086,8 +26481,8 @@ var Accrint = class extends BaseFunction {
26086
26481
  _defineProperty(this, "maxParams", 8);
26087
26482
  }
26088
26483
  calculate(issue, firstInterest, settlement, rate, par, frequency, basis, calcMethod) {
26089
- const _basis = basis !== null && basis !== void 0 ? basis : NumberValueObject.create(0);
26090
- const _calcMethod = calcMethod !== null && calcMethod !== void 0 ? calcMethod : BooleanValueObject.create(true);
26484
+ const _basis = basis ?? NumberValueObject.create(0);
26485
+ const _calcMethod = calcMethod ?? BooleanValueObject.create(true);
26091
26486
  const { isError, errorObject, variants } = checkVariantsErrorIsArrayOrBoolean(issue, firstInterest, settlement, rate, par, frequency, _basis);
26092
26487
  if (isError) return errorObject;
26093
26488
  const [issueObject, firstInterestObject, settlementObject, rateObject, parObject, frequencyObject, basisObject] = variants;
@@ -26166,7 +26561,7 @@ var Accrintm = class extends BaseFunction {
26166
26561
  _defineProperty(this, "maxParams", 5);
26167
26562
  }
26168
26563
  calculate(issue, settlement, rate, par, basis) {
26169
- const { isError, errorObject, variants } = checkVariantsErrorIsArrayOrBoolean(issue, settlement, rate, par, basis !== null && basis !== void 0 ? basis : NumberValueObject.create(0));
26564
+ const { isError, errorObject, variants } = checkVariantsErrorIsArrayOrBoolean(issue, settlement, rate, par, basis ?? NumberValueObject.create(0));
26170
26565
  if (isError) return errorObject;
26171
26566
  const [issueObject, settlementObject, rateObject, parObject, basisObject] = variants;
26172
26567
  const issueSerialNumber = getDateSerialNumberByObject(issueObject);
@@ -26194,7 +26589,7 @@ var Amorlinc = class extends BaseFunction {
26194
26589
  _defineProperty(this, "maxParams", 7);
26195
26590
  }
26196
26591
  calculate(cost, datePurchased, firstPeriod, salvage, period, rate, basis) {
26197
- const { isError, errorObject, variants } = checkVariantsErrorIsArrayOrBoolean(cost, datePurchased, firstPeriod, salvage, period, rate, basis !== null && basis !== void 0 ? basis : NumberValueObject.create(0));
26592
+ const { isError, errorObject, variants } = checkVariantsErrorIsArrayOrBoolean(cost, datePurchased, firstPeriod, salvage, period, rate, basis ?? NumberValueObject.create(0));
26198
26593
  if (isError) return errorObject;
26199
26594
  const [costObject, datePurchasedObject, firstPeriodObject, salvageObject, periodObject, rateObject, basisObject] = variants;
26200
26595
  const datePurchasedSerialNumber = getDateSerialNumberByObject(datePurchasedObject);
@@ -26241,7 +26636,7 @@ var Coupdaybs = class extends BaseFunction {
26241
26636
  _defineProperty(this, "maxParams", 4);
26242
26637
  }
26243
26638
  calculate(settlement, maturity, frequency, basis) {
26244
- const { isError, errorObject, variants } = checkVariantsErrorIsArrayOrBoolean(settlement, maturity, frequency, basis !== null && basis !== void 0 ? basis : NumberValueObject.create(0));
26639
+ const { isError, errorObject, variants } = checkVariantsErrorIsArrayOrBoolean(settlement, maturity, frequency, basis ?? NumberValueObject.create(0));
26245
26640
  if (isError) return errorObject;
26246
26641
  const [settlementObject, maturityObject, frequencyObject, basisObject] = variants;
26247
26642
  const settlementSerialNumber = getDateSerialNumberByObject(settlementObject);
@@ -26270,7 +26665,7 @@ var Coupdays = class extends BaseFunction {
26270
26665
  _defineProperty(this, "maxParams", 4);
26271
26666
  }
26272
26667
  calculate(settlement, maturity, frequency, basis) {
26273
- const { isError, errorObject, variants } = checkVariantsErrorIsArrayOrBoolean(settlement, maturity, frequency, basis !== null && basis !== void 0 ? basis : NumberValueObject.create(0));
26668
+ const { isError, errorObject, variants } = checkVariantsErrorIsArrayOrBoolean(settlement, maturity, frequency, basis ?? NumberValueObject.create(0));
26274
26669
  if (isError) return errorObject;
26275
26670
  const [settlementObject, maturityObject, frequencyObject, basisObject] = variants;
26276
26671
  const settlementSerialNumber = getDateSerialNumberByObject(settlementObject);
@@ -26299,7 +26694,7 @@ var Coupdaysnc = class extends BaseFunction {
26299
26694
  _defineProperty(this, "maxParams", 4);
26300
26695
  }
26301
26696
  calculate(settlement, maturity, frequency, basis) {
26302
- const { isError, errorObject, variants } = checkVariantsErrorIsArrayOrBoolean(settlement, maturity, frequency, basis !== null && basis !== void 0 ? basis : NumberValueObject.create(0));
26697
+ const { isError, errorObject, variants } = checkVariantsErrorIsArrayOrBoolean(settlement, maturity, frequency, basis ?? NumberValueObject.create(0));
26303
26698
  if (isError) return errorObject;
26304
26699
  const [settlementObject, maturityObject, frequencyObject, basisObject] = variants;
26305
26700
  const settlementSerialNumber = getDateSerialNumberByObject(settlementObject);
@@ -26334,7 +26729,7 @@ var Coupncd = class extends BaseFunction {
26334
26729
  _defineProperty(this, "maxParams", 4);
26335
26730
  }
26336
26731
  calculate(settlement, maturity, frequency, basis) {
26337
- const { isError, errorObject, variants } = checkVariantsErrorIsArrayOrBoolean(settlement, maturity, frequency, basis !== null && basis !== void 0 ? basis : NumberValueObject.create(0));
26732
+ const { isError, errorObject, variants } = checkVariantsErrorIsArrayOrBoolean(settlement, maturity, frequency, basis ?? NumberValueObject.create(0));
26338
26733
  if (isError) return errorObject;
26339
26734
  const [settlementObject, maturityObject, frequencyObject, basisObject] = variants;
26340
26735
  const settlementSerialNumber = getDateSerialNumberByObject(settlementObject);
@@ -26363,7 +26758,7 @@ var Coupnum = class extends BaseFunction {
26363
26758
  _defineProperty(this, "maxParams", 4);
26364
26759
  }
26365
26760
  calculate(settlement, maturity, frequency, basis) {
26366
- const { isError, errorObject, variants } = checkVariantsErrorIsArrayOrBoolean(settlement, maturity, frequency, basis !== null && basis !== void 0 ? basis : NumberValueObject.create(0));
26761
+ const { isError, errorObject, variants } = checkVariantsErrorIsArrayOrBoolean(settlement, maturity, frequency, basis ?? NumberValueObject.create(0));
26367
26762
  if (isError) return errorObject;
26368
26763
  const [settlementObject, maturityObject, frequencyObject, basisObject] = variants;
26369
26764
  const settlementSerialNumber = getDateSerialNumberByObject(settlementObject);
@@ -26393,7 +26788,7 @@ var Couppcd = class extends BaseFunction {
26393
26788
  _defineProperty(this, "maxParams", 4);
26394
26789
  }
26395
26790
  calculate(settlement, maturity, frequency, basis) {
26396
- const { isError, errorObject, variants } = checkVariantsErrorIsArrayOrBoolean(settlement, maturity, frequency, basis !== null && basis !== void 0 ? basis : NumberValueObject.create(0));
26791
+ const { isError, errorObject, variants } = checkVariantsErrorIsArrayOrBoolean(settlement, maturity, frequency, basis ?? NumberValueObject.create(0));
26397
26792
  if (isError) return errorObject;
26398
26793
  const [settlementObject, maturityObject, frequencyObject, basisObject] = variants;
26399
26794
  const settlementSerialNumber = getDateSerialNumberByObject(settlementObject);
@@ -26506,7 +26901,7 @@ var Db = class extends BaseFunction {
26506
26901
  _defineProperty(this, "needsLocale", true);
26507
26902
  }
26508
26903
  calculate(cost, salvage, life, period, month) {
26509
- let _month = month !== null && month !== void 0 ? month : NumberValueObject.create(12);
26904
+ let _month = month ?? NumberValueObject.create(12);
26510
26905
  if (_month.isNull()) _month = NumberValueObject.create(12);
26511
26906
  const maxRowLength = Math.max(cost.isArray() ? cost.getRowCount() : 1, salvage.isArray() ? salvage.getRowCount() : 1, life.isArray() ? life.getRowCount() : 1, period.isArray() ? period.getRowCount() : 1, _month.isArray() ? _month.getRowCount() : 1);
26512
26907
  const maxColumnLength = Math.max(cost.isArray() ? cost.getColumnCount() : 1, salvage.isArray() ? salvage.getColumnCount() : 1, life.isArray() ? life.getColumnCount() : 1, period.isArray() ? period.getColumnCount() : 1, _month.isArray() ? _month.getColumnCount() : 1);
@@ -26562,7 +26957,7 @@ var Ddb = class extends BaseFunction {
26562
26957
  _defineProperty(this, "needsLocale", true);
26563
26958
  }
26564
26959
  calculate(cost, salvage, life, period, factor) {
26565
- let _factor = factor !== null && factor !== void 0 ? factor : NumberValueObject.create(2);
26960
+ let _factor = factor ?? NumberValueObject.create(2);
26566
26961
  if (_factor.isNull()) _factor = NumberValueObject.create(2);
26567
26962
  const maxRowLength = Math.max(cost.isArray() ? cost.getRowCount() : 1, salvage.isArray() ? salvage.getRowCount() : 1, life.isArray() ? life.getRowCount() : 1, period.isArray() ? period.getRowCount() : 1, _factor.isArray() ? _factor.getRowCount() : 1);
26568
26963
  const maxColumnLength = Math.max(cost.isArray() ? cost.getColumnCount() : 1, salvage.isArray() ? salvage.getColumnCount() : 1, life.isArray() ? life.getColumnCount() : 1, period.isArray() ? period.getColumnCount() : 1, _factor.isArray() ? _factor.getColumnCount() : 1);
@@ -26600,7 +26995,7 @@ var Disc = class extends BaseFunction {
26600
26995
  _defineProperty(this, "maxParams", 5);
26601
26996
  }
26602
26997
  calculate(settlement, maturity, pr, redemption, basis) {
26603
- const { isError, errorObject, variants } = checkVariantsErrorIsArrayOrBoolean(settlement, maturity, pr, redemption, basis !== null && basis !== void 0 ? basis : NumberValueObject.create(0));
26998
+ const { isError, errorObject, variants } = checkVariantsErrorIsArrayOrBoolean(settlement, maturity, pr, redemption, basis ?? NumberValueObject.create(0));
26604
26999
  if (isError) return errorObject;
26605
27000
  const [settlementObject, maturityObject, prObject, redemptionObject, basisObject] = variants;
26606
27001
  const settlementSerialNumber = getDateSerialNumberByObject(settlementObject);
@@ -26677,7 +27072,7 @@ var Duration = class extends BaseFunction {
26677
27072
  _defineProperty(this, "maxParams", 6);
26678
27073
  }
26679
27074
  calculate(settlement, maturity, coupon, yld, frequency, basis) {
26680
- let _basis = basis !== null && basis !== void 0 ? basis : NumberValueObject.create(0);
27075
+ let _basis = basis ?? NumberValueObject.create(0);
26681
27076
  if (_basis.isNull()) _basis = NumberValueObject.create(0);
26682
27077
  const { isError, errorObject, variants } = checkVariantsErrorIsNullorArrayOrBoolean(settlement, maturity, coupon, yld, frequency, _basis);
26683
27078
  if (isError) return errorObject;
@@ -26734,8 +27129,8 @@ var Fv = class extends BaseFunction {
26734
27129
  _defineProperty(this, "needsLocale", true);
26735
27130
  }
26736
27131
  calculate(rate, nper, pmt, pv, type) {
26737
- const _pv = pv !== null && pv !== void 0 ? pv : NumberValueObject.create(0);
26738
- const _type = type !== null && type !== void 0 ? type : NumberValueObject.create(0);
27132
+ const _pv = pv ?? NumberValueObject.create(0);
27133
+ const _type = type ?? NumberValueObject.create(0);
26739
27134
  const maxRowLength = Math.max(rate.isArray() ? rate.getRowCount() : 1, nper.isArray() ? nper.getRowCount() : 1, pmt.isArray() ? pmt.getRowCount() : 1, _pv.isArray() ? _pv.getRowCount() : 1, _type.isArray() ? _type.getRowCount() : 1);
26740
27135
  const maxColumnLength = Math.max(rate.isArray() ? rate.getColumnCount() : 1, nper.isArray() ? nper.getColumnCount() : 1, pmt.isArray() ? pmt.getColumnCount() : 1, _pv.isArray() ? _pv.getColumnCount() : 1, _type.isArray() ? _type.getColumnCount() : 1);
26741
27136
  const rateArray = expandArrayValueObject(maxRowLength, maxColumnLength, rate, ErrorValueObject.create("#N/A"));
@@ -26800,7 +27195,7 @@ var Intrate = class extends BaseFunction {
26800
27195
  _defineProperty(this, "maxParams", 5);
26801
27196
  }
26802
27197
  calculate(settlement, maturity, investment, redemption, basis) {
26803
- const { isError, errorObject, variants } = checkVariantsErrorIsArrayOrBoolean(settlement, maturity, investment, redemption, basis !== null && basis !== void 0 ? basis : NumberValueObject.create(0));
27198
+ const { isError, errorObject, variants } = checkVariantsErrorIsArrayOrBoolean(settlement, maturity, investment, redemption, basis ?? NumberValueObject.create(0));
26804
27199
  if (isError) return errorObject;
26805
27200
  const [settlementObject, maturityObject, investmentObject, redemptionObject, basisObject] = variants;
26806
27201
  const settlementSerialNumber = getDateSerialNumberByObject(settlementObject);
@@ -26828,8 +27223,8 @@ var Ipmt = class extends BaseFunction {
26828
27223
  _defineProperty(this, "needsLocale", true);
26829
27224
  }
26830
27225
  calculate(rate, per, nper, pv, fv, type) {
26831
- const _fv = fv !== null && fv !== void 0 ? fv : NumberValueObject.create(0);
26832
- const _type = type !== null && type !== void 0 ? type : NumberValueObject.create(0);
27226
+ const _fv = fv ?? NumberValueObject.create(0);
27227
+ const _type = type ?? NumberValueObject.create(0);
26833
27228
  const maxRowLength = Math.max(rate.isArray() ? rate.getRowCount() : 1, per.isArray() ? per.getRowCount() : 1, nper.isArray() ? nper.getRowCount() : 1, pv.isArray() ? pv.getRowCount() : 1, _fv.isArray() ? _fv.getRowCount() : 1, _type.isArray() ? _type.getRowCount() : 1);
26834
27229
  const maxColumnLength = Math.max(rate.isArray() ? rate.getColumnCount() : 1, per.isArray() ? per.getColumnCount() : 1, nper.isArray() ? nper.getColumnCount() : 1, pv.isArray() ? pv.getColumnCount() : 1, _fv.isArray() ? _fv.getColumnCount() : 1, _type.isArray() ? _type.getColumnCount() : 1);
26835
27230
  const rateArray = expandArrayValueObject(maxRowLength, maxColumnLength, rate, ErrorValueObject.create("#N/A"));
@@ -26868,7 +27263,7 @@ var Irr = class extends BaseFunction {
26868
27263
  _defineProperty(this, "maxParams", 2);
26869
27264
  }
26870
27265
  calculate(values, guess) {
26871
- let _guess = guess !== null && guess !== void 0 ? guess : NumberValueObject.create(.1);
27266
+ let _guess = guess ?? NumberValueObject.create(.1);
26872
27267
  if (_guess.isNull()) _guess = NumberValueObject.create(.1);
26873
27268
  if (_guess.isArray()) return _guess.map((guessObject, rowIndex, columnIndex) => this._handleSingleObject(values, guessObject, rowIndex, columnIndex));
26874
27269
  return this._handleSingleObject(values, _guess);
@@ -26967,7 +27362,7 @@ var Mduration = class extends BaseFunction {
26967
27362
  _defineProperty(this, "maxParams", 6);
26968
27363
  }
26969
27364
  calculate(settlement, maturity, coupon, yld, frequency, basis) {
26970
- let _basis = basis !== null && basis !== void 0 ? basis : NumberValueObject.create(0);
27365
+ let _basis = basis ?? NumberValueObject.create(0);
26971
27366
  if (_basis.isNull()) _basis = NumberValueObject.create(0);
26972
27367
  const { isError, errorObject, variants } = checkVariantsErrorIsNullorArrayOrBoolean(settlement, maturity, coupon, yld, frequency, _basis);
26973
27368
  if (isError) return errorObject;
@@ -27123,8 +27518,8 @@ var Nper = class extends BaseFunction {
27123
27518
  _defineProperty(this, "maxParams", 5);
27124
27519
  }
27125
27520
  calculate(rate, pmt, pv, fv, type) {
27126
- const _fv = fv !== null && fv !== void 0 ? fv : NumberValueObject.create(0);
27127
- const _type = type !== null && type !== void 0 ? type : NumberValueObject.create(0);
27521
+ const _fv = fv ?? NumberValueObject.create(0);
27522
+ const _type = type ?? NumberValueObject.create(0);
27128
27523
  const maxRowLength = Math.max(rate.isArray() ? rate.getRowCount() : 1, pmt.isArray() ? pmt.getRowCount() : 1, pv.isArray() ? pv.getRowCount() : 1, _fv.isArray() ? _fv.getRowCount() : 1, _type.isArray() ? _type.getRowCount() : 1);
27129
27524
  const maxColumnLength = Math.max(rate.isArray() ? rate.getColumnCount() : 1, pmt.isArray() ? pmt.getColumnCount() : 1, pv.isArray() ? pv.getColumnCount() : 1, _fv.isArray() ? _fv.getColumnCount() : 1, _type.isArray() ? _type.getColumnCount() : 1);
27130
27525
  const rateArray = expandArrayValueObject(maxRowLength, maxColumnLength, rate, ErrorValueObject.create("#N/A"));
@@ -27235,7 +27630,7 @@ var Oddfprice = class extends BaseFunction {
27235
27630
  _defineProperty(this, "maxParams", 9);
27236
27631
  }
27237
27632
  calculate(settlement, maturity, issue, firstCoupon, rate, yld, redemption, frequency, basis) {
27238
- let _basis = basis !== null && basis !== void 0 ? basis : NumberValueObject.create(0);
27633
+ let _basis = basis ?? NumberValueObject.create(0);
27239
27634
  if (_basis.isNull()) _basis = NumberValueObject.create(0);
27240
27635
  const { isError, errorObject, variants } = checkVariantsErrorIsNullorArrayOrBoolean(settlement, maturity, issue, firstCoupon, rate, yld, redemption, frequency, _basis);
27241
27636
  if (isError) return errorObject;
@@ -27279,7 +27674,7 @@ var Oddfyield = class extends BaseFunction {
27279
27674
  _defineProperty(this, "maxParams", 9);
27280
27675
  }
27281
27676
  calculate(settlement, maturity, issue, firstCoupon, rate, pr, redemption, frequency, basis) {
27282
- let _basis = basis !== null && basis !== void 0 ? basis : NumberValueObject.create(0);
27677
+ let _basis = basis ?? NumberValueObject.create(0);
27283
27678
  if (_basis.isNull()) _basis = NumberValueObject.create(0);
27284
27679
  const { isError, errorObject, variants } = checkVariantsErrorIsNullorArrayOrBoolean(settlement, maturity, issue, firstCoupon, rate, pr, redemption, frequency, _basis);
27285
27680
  if (isError) return errorObject;
@@ -27332,7 +27727,7 @@ var Oddlprice = class extends BaseFunction {
27332
27727
  _defineProperty(this, "maxParams", 8);
27333
27728
  }
27334
27729
  calculate(settlement, maturity, lastInterest, rate, yld, redemption, frequency, basis) {
27335
- let _basis = basis !== null && basis !== void 0 ? basis : NumberValueObject.create(0);
27730
+ let _basis = basis ?? NumberValueObject.create(0);
27336
27731
  if (_basis.isNull()) _basis = NumberValueObject.create(0);
27337
27732
  const { isError, errorObject, variants } = checkVariantsErrorIsNullorArrayOrBoolean(settlement, maturity, lastInterest, rate, yld, redemption, frequency, _basis);
27338
27733
  if (isError) return errorObject;
@@ -27417,7 +27812,7 @@ var Oddlyield = class extends BaseFunction {
27417
27812
  _defineProperty(this, "maxParams", 9);
27418
27813
  }
27419
27814
  calculate(settlement, maturity, lastInterest, rate, pr, redemption, frequency, basis) {
27420
- let _basis = basis !== null && basis !== void 0 ? basis : NumberValueObject.create(0);
27815
+ let _basis = basis ?? NumberValueObject.create(0);
27421
27816
  if (_basis.isNull()) _basis = NumberValueObject.create(0);
27422
27817
  const { isError, errorObject, variants } = checkVariantsErrorIsNullorArrayOrBoolean(settlement, maturity, lastInterest, rate, pr, redemption, frequency, _basis);
27423
27818
  if (isError) return errorObject;
@@ -27534,8 +27929,8 @@ var Pmt = class extends BaseFunction {
27534
27929
  _defineProperty(this, "needsLocale", true);
27535
27930
  }
27536
27931
  calculate(rate, nper, pv, fv, type) {
27537
- const _fv = fv !== null && fv !== void 0 ? fv : NumberValueObject.create(0);
27538
- const _type = type !== null && type !== void 0 ? type : NumberValueObject.create(0);
27932
+ const _fv = fv ?? NumberValueObject.create(0);
27933
+ const _type = type ?? NumberValueObject.create(0);
27539
27934
  const maxRowLength = Math.max(rate.isArray() ? rate.getRowCount() : 1, nper.isArray() ? nper.getRowCount() : 1, pv.isArray() ? pv.getRowCount() : 1, _fv.isArray() ? _fv.getRowCount() : 1, _type.isArray() ? _type.getRowCount() : 1);
27540
27935
  const maxColumnLength = Math.max(rate.isArray() ? rate.getColumnCount() : 1, nper.isArray() ? nper.getColumnCount() : 1, pv.isArray() ? pv.getColumnCount() : 1, _fv.isArray() ? _fv.getColumnCount() : 1, _type.isArray() ? _type.getColumnCount() : 1);
27541
27936
  const rateArray = expandArrayValueObject(maxRowLength, maxColumnLength, rate, ErrorValueObject.create("#N/A"));
@@ -27573,8 +27968,8 @@ var Ppmt = class extends BaseFunction {
27573
27968
  _defineProperty(this, "needsLocale", true);
27574
27969
  }
27575
27970
  calculate(rate, per, nper, pv, fv, type) {
27576
- const _fv = fv !== null && fv !== void 0 ? fv : NumberValueObject.create(0);
27577
- const _type = type !== null && type !== void 0 ? type : NumberValueObject.create(0);
27971
+ const _fv = fv ?? NumberValueObject.create(0);
27972
+ const _type = type ?? NumberValueObject.create(0);
27578
27973
  const maxRowLength = Math.max(rate.isArray() ? rate.getRowCount() : 1, per.isArray() ? per.getRowCount() : 1, nper.isArray() ? nper.getRowCount() : 1, pv.isArray() ? pv.getRowCount() : 1, _fv.isArray() ? _fv.getRowCount() : 1, _type.isArray() ? _type.getRowCount() : 1);
27579
27974
  const maxColumnLength = Math.max(rate.isArray() ? rate.getColumnCount() : 1, per.isArray() ? per.getColumnCount() : 1, nper.isArray() ? nper.getColumnCount() : 1, pv.isArray() ? pv.getColumnCount() : 1, _fv.isArray() ? _fv.getColumnCount() : 1, _type.isArray() ? _type.getColumnCount() : 1);
27580
27975
  const rateArray = expandArrayValueObject(maxRowLength, maxColumnLength, rate, ErrorValueObject.create("#N/A"));
@@ -27613,7 +28008,7 @@ var Price = class extends BaseFunction {
27613
28008
  _defineProperty(this, "maxParams", 7);
27614
28009
  }
27615
28010
  calculate(settlement, maturity, rate, yld, redemption, frequency, basis) {
27616
- let _basis = basis !== null && basis !== void 0 ? basis : NumberValueObject.create(0);
28011
+ let _basis = basis ?? NumberValueObject.create(0);
27617
28012
  if (_basis.isNull()) _basis = NumberValueObject.create(0);
27618
28013
  const { isError, errorObject, variants } = checkVariantsErrorIsNullorArrayOrBoolean(settlement, maturity, rate, yld, redemption, frequency, _basis);
27619
28014
  if (isError) return errorObject;
@@ -27647,7 +28042,7 @@ var Pricedisc = class extends BaseFunction {
27647
28042
  _defineProperty(this, "maxParams", 5);
27648
28043
  }
27649
28044
  calculate(settlement, maturity, discount, redemption, basis) {
27650
- let _basis = basis !== null && basis !== void 0 ? basis : NumberValueObject.create(0);
28045
+ let _basis = basis ?? NumberValueObject.create(0);
27651
28046
  if (_basis.isNull()) _basis = NumberValueObject.create(0);
27652
28047
  const { isError, errorObject, variants } = checkVariantsErrorIsNullorArrayOrBoolean(settlement, maturity, discount, redemption, _basis);
27653
28048
  if (isError) return errorObject;
@@ -27676,7 +28071,7 @@ var Pricemat = class extends BaseFunction {
27676
28071
  _defineProperty(this, "maxParams", 6);
27677
28072
  }
27678
28073
  calculate(settlement, maturity, issue, rate, yld, basis) {
27679
- let _basis = basis !== null && basis !== void 0 ? basis : NumberValueObject.create(0);
28074
+ let _basis = basis ?? NumberValueObject.create(0);
27680
28075
  if (_basis.isNull()) _basis = NumberValueObject.create(0);
27681
28076
  const { isError, errorObject, variants } = checkVariantsErrorIsNullorArrayOrBoolean(settlement, maturity, issue, rate, yld, _basis);
27682
28077
  if (isError) return errorObject;
@@ -27715,8 +28110,8 @@ var Pv = class extends BaseFunction {
27715
28110
  _defineProperty(this, "needsLocale", true);
27716
28111
  }
27717
28112
  calculate(rate, nper, pmt, fv, type) {
27718
- const _fv = fv !== null && fv !== void 0 ? fv : NumberValueObject.create(0);
27719
- const _type = type !== null && type !== void 0 ? type : NumberValueObject.create(0);
28113
+ const _fv = fv ?? NumberValueObject.create(0);
28114
+ const _type = type ?? NumberValueObject.create(0);
27720
28115
  const maxRowLength = Math.max(rate.isArray() ? rate.getRowCount() : 1, nper.isArray() ? nper.getRowCount() : 1, pmt.isArray() ? pmt.getRowCount() : 1, _fv.isArray() ? _fv.getRowCount() : 1, _type.isArray() ? _type.getRowCount() : 1);
27721
28116
  const maxColumnLength = Math.max(rate.isArray() ? rate.getColumnCount() : 1, nper.isArray() ? nper.getColumnCount() : 1, pmt.isArray() ? pmt.getColumnCount() : 1, _fv.isArray() ? _fv.getColumnCount() : 1, _type.isArray() ? _type.getColumnCount() : 1);
27722
28117
  const rateArray = expandArrayValueObject(maxRowLength, maxColumnLength, rate, ErrorValueObject.create("#N/A"));
@@ -27753,9 +28148,9 @@ var Rate = class extends BaseFunction {
27753
28148
  _defineProperty(this, "maxParams", 6);
27754
28149
  }
27755
28150
  calculate(nper, pmt, pv, fv, type, guess) {
27756
- const _fv = fv !== null && fv !== void 0 ? fv : NumberValueObject.create(0);
27757
- const _type = type !== null && type !== void 0 ? type : NumberValueObject.create(0);
27758
- const _guess = guess !== null && guess !== void 0 ? guess : NumberValueObject.create(.1);
28151
+ const _fv = fv ?? NumberValueObject.create(0);
28152
+ const _type = type ?? NumberValueObject.create(0);
28153
+ const _guess = guess ?? NumberValueObject.create(.1);
27759
28154
  const maxRowLength = Math.max(nper.isArray() ? nper.getRowCount() : 1, pmt.isArray() ? pmt.getRowCount() : 1, pv.isArray() ? pv.getRowCount() : 1, _fv.isArray() ? _fv.getRowCount() : 1, _type.isArray() ? _type.getRowCount() : 1, _guess.isArray() ? _guess.getRowCount() : 1);
27760
28155
  const maxColumnLength = Math.max(nper.isArray() ? nper.getColumnCount() : 1, pmt.isArray() ? pmt.getColumnCount() : 1, pv.isArray() ? pv.getColumnCount() : 1, _fv.isArray() ? _fv.getColumnCount() : 1, _type.isArray() ? _type.getColumnCount() : 1, _guess.isArray() ? _guess.getColumnCount() : 1);
27761
28156
  const nperArray = expandArrayValueObject(maxRowLength, maxColumnLength, nper, ErrorValueObject.create("#N/A"));
@@ -27840,7 +28235,7 @@ var Received = class extends BaseFunction {
27840
28235
  _defineProperty(this, "maxParams", 5);
27841
28236
  }
27842
28237
  calculate(settlement, maturity, investment, discount, basis) {
27843
- let _basis = basis !== null && basis !== void 0 ? basis : NumberValueObject.create(0);
28238
+ let _basis = basis ?? NumberValueObject.create(0);
27844
28239
  if (_basis.isNull()) _basis = NumberValueObject.create(0);
27845
28240
  const { isError, errorObject, variants } = checkVariantsErrorIsNullorArrayOrBoolean(settlement, maturity, investment, discount, _basis);
27846
28241
  if (isError) return errorObject;
@@ -28062,9 +28457,9 @@ var Vdb = class extends BaseFunction {
28062
28457
  _defineProperty(this, "needsLocale", true);
28063
28458
  }
28064
28459
  calculate(cost, salvage, life, startPeriod, endPeriod, factor, noSwitch) {
28065
- let _factor = factor !== null && factor !== void 0 ? factor : NumberValueObject.create(2);
28460
+ let _factor = factor ?? NumberValueObject.create(2);
28066
28461
  if (_factor.isNull()) _factor = NumberValueObject.create(2);
28067
- let _noSwitch = noSwitch !== null && noSwitch !== void 0 ? noSwitch : BooleanValueObject.create(false);
28462
+ let _noSwitch = noSwitch ?? BooleanValueObject.create(false);
28068
28463
  if (_noSwitch.isNull()) _noSwitch = BooleanValueObject.create(false);
28069
28464
  const maxRowLength = Math.max(cost.isArray() ? cost.getRowCount() : 1, salvage.isArray() ? salvage.getRowCount() : 1, life.isArray() ? life.getRowCount() : 1, startPeriod.isArray() ? startPeriod.getRowCount() : 1, endPeriod.isArray() ? endPeriod.getRowCount() : 1, _factor.isArray() ? _factor.getRowCount() : 1, _noSwitch.isArray() ? _noSwitch.getRowCount() : 1);
28070
28465
  const maxColumnLength = Math.max(cost.isArray() ? cost.getColumnCount() : 1, salvage.isArray() ? salvage.getColumnCount() : 1, life.isArray() ? life.getColumnCount() : 1, startPeriod.isArray() ? startPeriod.getColumnCount() : 1, endPeriod.isArray() ? endPeriod.getColumnCount() : 1, _factor.isArray() ? _factor.getColumnCount() : 1, _noSwitch.isArray() ? _noSwitch.getColumnCount() : 1);
@@ -28158,7 +28553,7 @@ var Xirr = class extends BaseFunction {
28158
28553
  if (values.isNull() || dates.isNull()) return ErrorValueObject.create("#N/A");
28159
28554
  const { isError, errorObejct, _values, _dates } = this._checkErrors(values, dates);
28160
28555
  if (isError) return errorObejct;
28161
- let _guess = guess !== null && guess !== void 0 ? guess : NumberValueObject.create(.1);
28556
+ let _guess = guess ?? NumberValueObject.create(.1);
28162
28557
  if (_guess.isNull()) _guess = NumberValueObject.create(.1);
28163
28558
  const { isError: _isError_guess, errorObject: _errorObject_guess, variants } = checkVariantsErrorIsArrayOrBoolean(_guess);
28164
28559
  if (_isError_guess) return _errorObject_guess;
@@ -28501,7 +28896,7 @@ var Yield = class extends BaseFunction {
28501
28896
  _defineProperty(this, "maxParams", 7);
28502
28897
  }
28503
28898
  calculate(settlement, maturity, rate, pr, redemption, frequency, basis) {
28504
- let _basis = basis !== null && basis !== void 0 ? basis : NumberValueObject.create(0);
28899
+ let _basis = basis ?? NumberValueObject.create(0);
28505
28900
  if (_basis.isNull()) _basis = NumberValueObject.create(0);
28506
28901
  const { isError, errorObject, variants } = checkVariantsErrorIsNullorArrayOrBoolean(settlement, maturity, rate, pr, redemption, frequency, _basis);
28507
28902
  if (isError) return errorObject;
@@ -28554,7 +28949,7 @@ var Yielddisc = class extends BaseFunction {
28554
28949
  _defineProperty(this, "maxParams", 5);
28555
28950
  }
28556
28951
  calculate(settlement, maturity, pr, redemption, basis) {
28557
- let _basis = basis !== null && basis !== void 0 ? basis : NumberValueObject.create(0);
28952
+ let _basis = basis ?? NumberValueObject.create(0);
28558
28953
  if (_basis.isNull()) _basis = NumberValueObject.create(0);
28559
28954
  const { isError, errorObject, variants } = checkVariantsErrorIsNullorArrayOrBoolean(settlement, maturity, pr, redemption, _basis);
28560
28955
  if (isError) return errorObject;
@@ -28583,7 +28978,7 @@ var Yieldmat = class extends BaseFunction {
28583
28978
  _defineProperty(this, "maxParams", 6);
28584
28979
  }
28585
28980
  calculate(settlement, maturity, issue, rate, pr, basis) {
28586
- let _basis = basis !== null && basis !== void 0 ? basis : NumberValueObject.create(0);
28981
+ let _basis = basis ?? NumberValueObject.create(0);
28587
28982
  if (_basis.isNull()) _basis = NumberValueObject.create(0);
28588
28983
  const { isError, errorObject, variants } = checkVariantsErrorIsNullorArrayOrBoolean(settlement, maturity, issue, rate, pr, _basis);
28589
28984
  if (isError) return errorObject;
@@ -28718,6 +29113,7 @@ var Cell = class extends BaseFunction {
28718
29113
  if (_reference.isError()) return _reference;
28719
29114
  if (!_reference.isReferenceObject()) return ErrorValueObject.create("#N/A");
28720
29115
  const { columnData, defaultColumnWidth } = _reference.getCurrentActiveSheetData();
29116
+ const forcedSheetName = _reference.getForcedSheetName();
28721
29117
  _reference = _reference.toArrayValueObject();
28722
29118
  const _currentRow = _reference.getCurrentRow();
28723
29119
  const _currentColumn = _reference.getCurrentColumn();
@@ -28725,7 +29121,7 @@ var Cell = class extends BaseFunction {
28725
29121
  const infoTypeValue = `${infoType.getValue()}`;
28726
29122
  let result;
28727
29123
  switch (infoTypeValue.toLocaleLowerCase()) {
28728
- case "address": return StringValueObject.create(`$${_univerjs_core.Tools.chatAtABC(_currentColumn)}$${_currentRow + 1}`);
29124
+ case "address": return StringValueObject.create(`${forcedSheetName ? `${addQuotesBothSides(forcedSheetName)}!` : ""}$${_univerjs_core.Tools.chatAtABC(_currentColumn)}$${_currentRow + 1}`);
28729
29125
  case "col": return NumberValueObject.create(_currentColumn + 1);
28730
29126
  case "color": return NumberValueObject.create(0);
28731
29127
  case "contents": return _reference;
@@ -28794,7 +29190,7 @@ var Isbetween = class extends BaseFunction {
28794
29190
  _defineProperty(this, "maxParams", 5);
28795
29191
  }
28796
29192
  calculate(valueToCompare, lowerValue, upperValue, lowerValueIsInclusive, upperValueIsInclusive) {
28797
- const { isError, errorObject, variants } = checkVariantsErrorIsArray(valueToCompare, lowerValue, upperValue, lowerValueIsInclusive !== null && lowerValueIsInclusive !== void 0 ? lowerValueIsInclusive : BooleanValueObject.create(true), upperValueIsInclusive !== null && upperValueIsInclusive !== void 0 ? upperValueIsInclusive : BooleanValueObject.create(true));
29193
+ const { isError, errorObject, variants } = checkVariantsErrorIsArray(valueToCompare, lowerValue, upperValue, lowerValueIsInclusive ?? BooleanValueObject.create(true), upperValueIsInclusive ?? BooleanValueObject.create(true));
28798
29194
  if (isError) return errorObject;
28799
29195
  const [valueToCompareObject, lowerValueObject, upperValueObject, lowerValueIsInclusiveObject, upperValueIsInclusiveObject] = variants;
28800
29196
  if (lowerValueIsInclusiveObject.isString() || upperValueIsInclusiveObject.isString()) return ErrorValueObject.create("#VALUE!");
@@ -28816,8 +29212,13 @@ var Isblank = class extends BaseFunction {
28816
29212
  super(..._args);
28817
29213
  _defineProperty(this, "minParams", 1);
28818
29214
  _defineProperty(this, "maxParams", 1);
29215
+ _defineProperty(this, "needsReferenceObject", true);
28819
29216
  }
28820
29217
  calculate(value) {
29218
+ if (value instanceof BaseReferenceObject) {
29219
+ const array = value.toArrayValueObject(false).mapValue((valueObject) => BooleanValueObject.create(valueObject.isNull()));
29220
+ return array.getRowCount() === 1 && array.getColumnCount() === 1 ? array.getFirstCell() : array;
29221
+ }
28821
29222
  if (value.isNull()) return BooleanValueObject.create(true);
28822
29223
  else if (value.isArray()) return value.mapValue((valueObject) => {
28823
29224
  if (valueObject.isNull()) return BooleanValueObject.create(true);
@@ -29580,10 +29981,7 @@ var Groupby = class extends BaseFunction {
29580
29981
  return {
29581
29982
  rowCount: array.getRowCount(),
29582
29983
  columnCount: array.getColumnCount(),
29583
- valueAt: (row, column) => {
29584
- var _array$get;
29585
- return (_array$get = array.get(row, column)) !== null && _array$get !== void 0 ? _array$get : NullValueObject.create();
29586
- }
29984
+ valueAt: (row, column) => array.get(row, column) ?? NullValueObject.create()
29587
29985
  };
29588
29986
  }
29589
29987
  return {
@@ -29653,10 +30051,7 @@ var Groupby = class extends BaseFunction {
29653
30051
  }
29654
30052
  }
29655
30053
  _sum(values) {
29656
- return values.reduce((sum, value) => {
29657
- var _this$_numericValue;
29658
- return sum + ((_this$_numericValue = this._numericValue(value)) !== null && _this$_numericValue !== void 0 ? _this$_numericValue : 0);
29659
- }, 0);
30054
+ return values.reduce((sum, value) => sum + (this._numericValue(value) ?? 0), 0);
29660
30055
  }
29661
30056
  _numericValue(value) {
29662
30057
  return value.isNumber() ? Number(value.getValue()) : void 0;
@@ -29664,10 +30059,7 @@ var Groupby = class extends BaseFunction {
29664
30059
  _numberValue(variant) {
29665
30060
  if (variant == null || variant.isError()) return 0;
29666
30061
  if (variant.isReferenceObject()) variant = variant.getFirstCell();
29667
- if (variant.isArray()) {
29668
- var _get;
29669
- variant = (_get = variant.get(0, 0)) !== null && _get !== void 0 ? _get : NullValueObject.create();
29670
- }
30062
+ if (variant.isArray()) variant = variant.get(0, 0) ?? NullValueObject.create();
29671
30063
  const value = variant.getValue();
29672
30064
  return typeof value === "number" ? Math.trunc(value) : Math.trunc(Number(value) || 0);
29673
30065
  }
@@ -30104,20 +30496,72 @@ var Or = class extends BaseFunction {
30104
30496
  }
30105
30497
  };
30106
30498
 
30499
+ //#endregion
30500
+ //#region src/functions/math/sum/index.ts
30501
+ var Sum = class extends BaseFunction {
30502
+ constructor(..._args) {
30503
+ super(..._args);
30504
+ _defineProperty(this, "minParams", 1);
30505
+ _defineProperty(this, "maxParams", 255);
30506
+ }
30507
+ calculate(...variants) {
30508
+ let accumulatorAll = NumberValueObject.create(0);
30509
+ for (let i = 0; i < variants.length; i++) {
30510
+ let variant = variants[i];
30511
+ variant = this._legacyImplicitDerivedArray(variant);
30512
+ if (variant.isString()) variant = variant.convertToNumberObjectValue();
30513
+ if (variant.isError()) return variant;
30514
+ if (variant.isArray()) variant = variant.sum();
30515
+ if (variant.isError()) return variant;
30516
+ accumulatorAll = accumulatorAll.plus(variant);
30517
+ if (accumulatorAll.isError()) return accumulatorAll;
30518
+ }
30519
+ return accumulatorAll;
30520
+ }
30521
+ _legacyImplicitDerivedArray(variant) {
30522
+ if (!variant.isArray()) return variant;
30523
+ const array = variant;
30524
+ if (array.usesInvertedIndexCache() || !array.usesLegacyImplicitForAggregate()) return variant;
30525
+ const startRow = array.getCurrentRow();
30526
+ const startColumn = array.getCurrentColumn();
30527
+ if (startRow < 0 || startColumn < 0) return variant;
30528
+ const rowCount = array.getRowCount();
30529
+ const columnCount = array.getColumnCount();
30530
+ let rowIndex = -1;
30531
+ let columnIndex = -1;
30532
+ if (rowCount === 1) {
30533
+ rowIndex = 0;
30534
+ columnIndex = this.column - startColumn;
30535
+ } else if (columnCount === 1) {
30536
+ rowIndex = this.row - startRow;
30537
+ columnIndex = 0;
30538
+ } else {
30539
+ rowIndex = this.row - startRow;
30540
+ columnIndex = this.column - startColumn;
30541
+ }
30542
+ if (rowIndex < 0 || rowIndex >= rowCount || columnIndex < 0 || columnIndex >= columnCount) return variant;
30543
+ return array.get(rowIndex, columnIndex) || variant;
30544
+ }
30545
+ };
30546
+
30107
30547
  //#endregion
30108
30548
  //#region src/functions/logical/percentof/index.ts
30109
30549
  /**
30110
- * PERCENTOF is an Excel GROUPBY aggregator token. It is evaluated by GROUPBY's
30111
- * AST path, not as a standalone scalar function.
30550
+ * PERCENTOF is logically equivalent to SUM(dataSubset) / SUM(dataAll).
30551
+ * GROUPBY also consumes the function name as an aggregator token through its AST path.
30112
30552
  */
30113
- var Percentof = class extends BaseFunction {
30553
+ var Percentof = class extends Sum {
30114
30554
  constructor(..._args) {
30115
30555
  super(..._args);
30116
- _defineProperty(this, "minParams", 0);
30117
- _defineProperty(this, "maxParams", 0);
30556
+ _defineProperty(this, "minParams", 2);
30557
+ _defineProperty(this, "maxParams", 2);
30118
30558
  }
30119
- calculate(..._variants) {
30120
- return ErrorValueObject.create("#VALUE!");
30559
+ calculate(dataSubset, dataAll) {
30560
+ const subsetTotal = super.calculate(dataSubset);
30561
+ if (subsetTotal.isError()) return subsetTotal;
30562
+ const allTotal = super.calculate(dataAll);
30563
+ if (allTotal.isError()) return allTotal;
30564
+ return subsetTotal.divided(allTotal);
30121
30565
  }
30122
30566
  };
30123
30567
 
@@ -30526,6 +30970,7 @@ var Choose = class extends BaseFunction {
30526
30970
  super(..._args);
30527
30971
  _defineProperty(this, "minParams", 2);
30528
30972
  _defineProperty(this, "maxParams", 255);
30973
+ _defineProperty(this, "lazyIfReferenceArrayArgumentIndexes", Array.from({ length: this.maxParams - 1 }, (_, index) => index + 1));
30529
30974
  _defineProperty(this, "needsReferenceObject", true);
30530
30975
  }
30531
30976
  calculate(indexNum, ...variants) {
@@ -30710,7 +31155,7 @@ var Drop = class extends BaseFunction {
30710
31155
  _defineProperty(this, "maxParams", 3);
30711
31156
  }
30712
31157
  calculate(array, rows, columns) {
30713
- const _columns = columns !== null && columns !== void 0 ? columns : NumberValueObject.create(0);
31158
+ const _columns = columns ?? NumberValueObject.create(0);
30714
31159
  const arrayRowCount = array.isArray() ? array.getRowCount() : 1;
30715
31160
  const arrayColumnCount = array.isArray() ? array.getColumnCount() : 1;
30716
31161
  const maxRowLength = Math.max(rows.isArray() ? rows.getRowCount() : 1, _columns.isArray() ? _columns.getRowCount() : 1);
@@ -30785,8 +31230,8 @@ var Expand = class extends BaseFunction {
30785
31230
  const arrayRowCount = array.isArray() ? array.getRowCount() : 1;
30786
31231
  const arrayColumnCount = array.isArray() ? array.getColumnCount() : 1;
30787
31232
  let _rows = rows;
30788
- let _columns = columns !== null && columns !== void 0 ? columns : NumberValueObject.create(arrayColumnCount);
30789
- const _padWith = padWith !== null && padWith !== void 0 ? padWith : ErrorValueObject.create("#N/A");
31233
+ let _columns = columns ?? NumberValueObject.create(arrayColumnCount);
31234
+ const _padWith = padWith ?? ErrorValueObject.create("#N/A");
30790
31235
  if (rows.isNull()) _rows = NumberValueObject.create(arrayRowCount);
30791
31236
  if (_columns.isNull()) _columns = NumberValueObject.create(arrayColumnCount);
30792
31237
  const maxRowLength = Math.max(_rows.isArray() ? _rows.getRowCount() : 1, _columns.isArray() ? _columns.getRowCount() : 1);
@@ -30878,7 +31323,7 @@ var Filter = class extends BaseFunction {
30878
31323
  _defineProperty(this, "maxParams", 3);
30879
31324
  }
30880
31325
  calculate(array, include, ifEmpty) {
30881
- const _ifEmpty = ifEmpty !== null && ifEmpty !== void 0 ? ifEmpty : ErrorValueObject.create("#CALC!");
31326
+ const _ifEmpty = ifEmpty ?? ErrorValueObject.create("#CALC!");
30882
31327
  if (array.isError()) return array;
30883
31328
  if (include.isError()) return include;
30884
31329
  const arrayRowCount = array.isArray() ? array.getRowCount() : 1;
@@ -31130,7 +31575,7 @@ var ImageFunction = class extends BaseFunction {
31130
31575
  if (altText.isBoolean()) altTextValue = altText.getValue() ? "TRUE" : "FALSE";
31131
31576
  else if (!altText.isNull()) altTextValue = `${altText.getValue()}`;
31132
31577
  }
31133
- let _sizing = sizing !== null && sizing !== void 0 ? sizing : NumberValueObject.create(0);
31578
+ let _sizing = sizing ?? NumberValueObject.create(0);
31134
31579
  if (_sizing.isString()) _sizing = _sizing.convertToNumberObjectValue();
31135
31580
  if (_sizing.isError()) return _sizing;
31136
31581
  const sizingValue = Math.abs(Math.trunc(+_sizing.getValue()));
@@ -31140,11 +31585,11 @@ var ImageFunction = class extends BaseFunction {
31140
31585
  1,
31141
31586
  2
31142
31587
  ].includes(sizingValue) && (height || width)) return ErrorValueObject.create("#VALUE!");
31143
- let _height = height !== null && height !== void 0 ? height : NumberValueObject.create(0);
31588
+ let _height = height ?? NumberValueObject.create(0);
31144
31589
  if (_height.isString()) _height = _height.convertToNumberObjectValue();
31145
31590
  if (_height.isError()) return _height;
31146
31591
  const heightValue = Math.ceil(+_height.getValue());
31147
- let _width = width !== null && width !== void 0 ? width : NumberValueObject.create(0);
31592
+ let _width = width ?? NumberValueObject.create(0);
31148
31593
  if (_width.isString()) _width = _width.convertToNumberObjectValue();
31149
31594
  if (_width.isError()) return _width;
31150
31595
  const widthValue = Math.ceil(+_width.getValue());
@@ -31186,7 +31631,7 @@ var Index = class extends BaseFunction {
31186
31631
  if (rowNum.isReferenceObject()) _rowNum = rowNum.toArrayValueObject();
31187
31632
  let _columnNum = columnNum;
31188
31633
  if (_columnNum === null || _columnNum === void 0 ? void 0 : _columnNum.isReferenceObject()) _columnNum = columnNum.toArrayValueObject();
31189
- let _areaNum = areaNum !== null && areaNum !== void 0 ? areaNum : NumberValueObject.create(1);
31634
+ let _areaNum = areaNum ?? NumberValueObject.create(1);
31190
31635
  if (_areaNum.isReferenceObject()) _areaNum = areaNum.toArrayValueObject();
31191
31636
  const maxRowLength = Math.max(_rowNum.isArray() ? _rowNum.getRowCount() : 1, (_columnNum === null || _columnNum === void 0 ? void 0 : _columnNum.isArray()) ? _columnNum.getRowCount() : 1, _areaNum.isArray() ? _areaNum.getRowCount() : 1);
31192
31637
  const maxColumnLength = Math.max(_rowNum.isArray() ? _rowNum.getColumnCount() : 1, (_columnNum === null || _columnNum === void 0 ? void 0 : _columnNum.isArray()) ? _columnNum.getColumnCount() : 1, _areaNum.isArray() ? _areaNum.getColumnCount() : 1);
@@ -31446,6 +31891,7 @@ var Match = class extends BaseFunction {
31446
31891
  super(..._args);
31447
31892
  _defineProperty(this, "minParams", 2);
31448
31893
  _defineProperty(this, "maxParams", 3);
31894
+ _defineProperty(this, "lazyIfReferenceArrayArgumentIndexes", [1]);
31449
31895
  }
31450
31896
  calculate(lookupValue, lookupArray, matchType) {
31451
31897
  if (lookupValue.isError()) return lookupValue;
@@ -31478,236 +31924,6 @@ var Match = class extends BaseFunction {
31478
31924
  }
31479
31925
  };
31480
31926
 
31481
- //#endregion
31482
- //#region src/engine/reference-object/multi-area-reference-object.ts
31483
- var MultiAreaReferenceObject = class extends BaseReferenceObject {
31484
- constructor(token, areas = []) {
31485
- super(token);
31486
- _defineProperty(this, "_areas", []);
31487
- this._areas = areas;
31488
- }
31489
- dispose() {
31490
- this._areas.forEach((row) => {
31491
- row.forEach((a) => a.dispose());
31492
- });
31493
- this._areas = [];
31494
- super.dispose();
31495
- }
31496
- getAreas() {
31497
- return this._areas;
31498
- }
31499
- setAreas(areas) {
31500
- this._areas = areas;
31501
- }
31502
- /**
31503
- * Append an area:
31504
- * - If a single AreaValue is passed, it will be wrapped as one row.
31505
- * - If an AreaValue[] is passed, it will be inserted as an entire row.
31506
- */
31507
- addArea(area) {
31508
- if (Array.isArray(area)) this._areas.push(area);
31509
- else this._areas.push([area]);
31510
- }
31511
- /** Flatten the 2D areas to reuse 1D logic */
31512
- _flatAreas() {
31513
- return this._areas.flat();
31514
- }
31515
- isMultiArea() {
31516
- return true;
31517
- }
31518
- isRange() {
31519
- return false;
31520
- }
31521
- isCell() {
31522
- return false;
31523
- }
31524
- isRow() {
31525
- return false;
31526
- }
31527
- isColumn() {
31528
- return false;
31529
- }
31530
- getRowCount() {
31531
- let total = 0;
31532
- for (const a of this._flatAreas()) {
31533
- if (a.isError()) continue;
31534
- total += a.getRowCount();
31535
- }
31536
- return total;
31537
- }
31538
- getColumnCount() {
31539
- let total = 0;
31540
- for (const a of this._flatAreas()) {
31541
- if (a.isError()) continue;
31542
- total += a.getColumnCount();
31543
- }
31544
- return total;
31545
- }
31546
- isExceedRange() {
31547
- return this._flatAreas().some((a) => {
31548
- if (a.isError()) return false;
31549
- return a.isExceedRange();
31550
- });
31551
- }
31552
- setRefOffset(x = 0, y = 0) {
31553
- super.setRefOffset(x, y);
31554
- this._flatAreas().forEach((a) => {
31555
- if (a.isError()) return;
31556
- a.setRefOffset(x, y);
31557
- });
31558
- }
31559
- _getReferenceArea() {
31560
- return this._flatAreas().find((a) => !a.isError());
31561
- }
31562
- /**
31563
- * Multi-area reference may span multiple sheets, but Excel requires
31564
- * them to be in the same sheet for most functions. We follow Excel semantics
31565
- * by returning the first area’s identifiers.
31566
- */
31567
- getUnitId() {
31568
- var _this$_getReferenceAr, _this$_getReferenceAr2;
31569
- return (_this$_getReferenceAr = (_this$_getReferenceAr2 = this._getReferenceArea()) === null || _this$_getReferenceAr2 === void 0 ? void 0 : _this$_getReferenceAr2.getUnitId()) !== null && _this$_getReferenceAr !== void 0 ? _this$_getReferenceAr : super.getUnitId();
31570
- }
31571
- getSheetId() {
31572
- var _this$_getReferenceAr3, _this$_getReferenceAr4;
31573
- return (_this$_getReferenceAr3 = (_this$_getReferenceAr4 = this._getReferenceArea()) === null || _this$_getReferenceAr4 === void 0 ? void 0 : _this$_getReferenceAr4.getSheetId()) !== null && _this$_getReferenceAr3 !== void 0 ? _this$_getReferenceAr3 : super.getSheetId();
31574
- }
31575
- getActiveSheetRowCount() {
31576
- var _this$_getReferenceAr5, _this$_getReferenceAr6;
31577
- return (_this$_getReferenceAr5 = (_this$_getReferenceAr6 = this._getReferenceArea()) === null || _this$_getReferenceAr6 === void 0 ? void 0 : _this$_getReferenceAr6.getActiveSheetRowCount()) !== null && _this$_getReferenceAr5 !== void 0 ? _this$_getReferenceAr5 : 0;
31578
- }
31579
- getActiveSheetColumnCount() {
31580
- var _this$_getReferenceAr7, _this$_getReferenceAr8;
31581
- return (_this$_getReferenceAr7 = (_this$_getReferenceAr8 = this._getReferenceArea()) === null || _this$_getReferenceAr8 === void 0 ? void 0 : _this$_getReferenceAr8.getActiveSheetColumnCount()) !== null && _this$_getReferenceAr7 !== void 0 ? _this$_getReferenceAr7 : 0;
31582
- }
31583
- /**
31584
- * Iterate through all areas in order, flattening the multi-area into
31585
- * a sequence of cells.
31586
- *
31587
- * Note: The order here is "row-major":
31588
- * iterate by the row order of _areas, then within each row by the area order.
31589
- */
31590
- iterator(callback) {
31591
- for (const row of this._areas) {
31592
- let stopRow = false;
31593
- for (const area of row) {
31594
- if (area.isError()) continue;
31595
- let stopArea = false;
31596
- area.iterator((v, r, c) => {
31597
- const res = callback(v, r, c);
31598
- if (res === false) {
31599
- stopArea = true;
31600
- stopRow = true;
31601
- return false;
31602
- }
31603
- return res;
31604
- });
31605
- if (stopArea) break;
31606
- }
31607
- if (stopRow) return;
31608
- }
31609
- }
31610
- /**
31611
- * Excel defines the "first cell" of a multi-area reference
31612
- * as the first cell of the first area.
31613
- */
31614
- getFirstCell() {
31615
- const first = this._getReferenceArea();
31616
- if (!first) return super.getFirstCell();
31617
- return first.getFirstCell();
31618
- }
31619
- /**
31620
- * For multi-area, we only take the *first cell* of each area and
31621
- * arrange them into a 2D ArrayValueObject:
31622
- *
31623
- * - outer `_areas` dimension => rows
31624
- * - inner `_areas[row]` dimension => columns
31625
- */
31626
- toArrayValueObject() {
31627
- var _this$_areas$0$length, _this$_areas$;
31628
- const rows = this._areas.length;
31629
- if (rows === 0) return createNewArray([], 0, 0);
31630
- const cols = (_this$_areas$0$length = (_this$_areas$ = this._areas[0]) === null || _this$_areas$ === void 0 ? void 0 : _this$_areas$.length) !== null && _this$_areas$0$length !== void 0 ? _this$_areas$0$length : 0;
31631
- const result = [];
31632
- for (let r = 0; r < rows; r++) {
31633
- const rowAreas = this._areas[r];
31634
- if (!rowAreas) continue;
31635
- result[r] = result[r] || [];
31636
- for (let c = 0; c < cols; c++) {
31637
- const area = rowAreas[c];
31638
- if (!area) continue;
31639
- if (area.isError()) {
31640
- result[r][c] = area;
31641
- continue;
31642
- }
31643
- let firstValue = null;
31644
- area.iterator((v) => {
31645
- firstValue = v !== null && v !== void 0 ? v : null;
31646
- return false;
31647
- });
31648
- if (firstValue != null) result[r][c] = firstValue;
31649
- result[r][c] = NullValueObject.create();
31650
- }
31651
- }
31652
- return createNewArray(result, rows, cols);
31653
- }
31654
- getRangePosition() {
31655
- const flat = this._flatAreas();
31656
- if (!flat.length) return super.getRangePosition();
31657
- let minStartRow = Number.POSITIVE_INFINITY;
31658
- let minStartColumn = Number.POSITIVE_INFINITY;
31659
- let maxEndRow = Number.NEGATIVE_INFINITY;
31660
- let maxEndColumn = Number.NEGATIVE_INFINITY;
31661
- for (const area of flat) {
31662
- if (area.isError()) continue;
31663
- const { startRow, startColumn, endRow, endColumn } = area.getRangePosition();
31664
- if (!Number.isFinite(startRow) || !Number.isFinite(startColumn) || !Number.isFinite(endRow) || !Number.isFinite(endColumn)) continue;
31665
- if (startRow < minStartRow) minStartRow = startRow;
31666
- if (startColumn < minStartColumn) minStartColumn = startColumn;
31667
- if (endRow > maxEndRow) maxEndRow = endRow;
31668
- if (endColumn > maxEndColumn) maxEndColumn = maxEndColumn < endColumn ? endColumn : maxEndColumn;
31669
- }
31670
- if (!Number.isFinite(minStartRow) || !Number.isFinite(minStartColumn) || !Number.isFinite(maxEndRow) || !Number.isFinite(maxEndColumn)) return super.getRangePosition();
31671
- return {
31672
- startRow: minStartRow,
31673
- startColumn: minStartColumn,
31674
- endRow: maxEndRow,
31675
- endColumn: maxEndColumn
31676
- };
31677
- }
31678
- toUnitRange() {
31679
- return {
31680
- range: this.getRangePosition(),
31681
- sheetId: this.getSheetId(),
31682
- unitId: this.getUnitId()
31683
- };
31684
- }
31685
- getRangeData() {
31686
- const flat = this._flatAreas();
31687
- if (!flat.length) return super.getRangeData();
31688
- let minStartRow = Number.POSITIVE_INFINITY;
31689
- let minStartColumn = Number.POSITIVE_INFINITY;
31690
- let maxEndRow = Number.NEGATIVE_INFINITY;
31691
- let maxEndColumn = Number.NEGATIVE_INFINITY;
31692
- for (const area of flat) {
31693
- if (area.isError()) continue;
31694
- const { startRow, startColumn, endRow, endColumn } = area.getRangeData();
31695
- if (!Number.isFinite(startRow) || !Number.isFinite(startColumn) || !Number.isFinite(endRow) || !Number.isFinite(endColumn)) continue;
31696
- if (startRow < minStartRow) minStartRow = startRow;
31697
- if (startColumn < minStartColumn) minStartColumn = startColumn;
31698
- if (endRow > maxEndRow) maxEndRow = endRow;
31699
- if (endColumn > maxEndColumn) maxEndColumn = endColumn;
31700
- }
31701
- if (!Number.isFinite(minStartRow) || !Number.isFinite(minStartColumn) || !Number.isFinite(maxEndRow) || !Number.isFinite(maxEndColumn)) return super.getRangeData();
31702
- return {
31703
- startRow: minStartRow,
31704
- startColumn: minStartColumn,
31705
- endRow: maxEndRow,
31706
- endColumn: maxEndColumn
31707
- };
31708
- }
31709
- };
31710
-
31711
31927
  //#endregion
31712
31928
  //#region src/functions/lookup/offset/index.ts
31713
31929
  var Offset = class extends BaseFunction {
@@ -31733,10 +31949,10 @@ var Offset = class extends BaseFunction {
31733
31949
  if (_rows.isReferenceObject()) _rows = _rows.toArrayValueObject();
31734
31950
  let _columns = columns;
31735
31951
  if (_columns.isReferenceObject()) _columns = _columns.toArrayValueObject();
31736
- let _height = height !== null && height !== void 0 ? height : NumberValueObject.create(rowCount);
31952
+ let _height = height ?? NumberValueObject.create(rowCount);
31737
31953
  if (_height.isReferenceObject()) _height = _height.toArrayValueObject();
31738
31954
  if (_height.isNull()) _height = NumberValueObject.create(rowCount);
31739
- let _width = width !== null && width !== void 0 ? width : NumberValueObject.create(columnCount);
31955
+ let _width = width ?? NumberValueObject.create(columnCount);
31740
31956
  if (_width.isReferenceObject()) _width = _width.toArrayValueObject();
31741
31957
  if (_width.isNull()) _width = NumberValueObject.create(columnCount);
31742
31958
  const maxRowLength = Math.max(_rows.isArray() ? _rows.getRowCount() : 1, _columns.isArray() ? _columns.getRowCount() : 1, _height.isArray() ? _height.getRowCount() : 1, _width.isArray() ? _width.getRowCount() : 1);
@@ -31873,9 +32089,9 @@ var Sort = class extends BaseFunction {
31873
32089
  _defineProperty(this, "maxParams", 4);
31874
32090
  }
31875
32091
  calculate(array, sortIndex, sortOrder, byCol) {
31876
- let _sortIndex = sortIndex !== null && sortIndex !== void 0 ? sortIndex : NumberValueObject.create(1);
31877
- let _sortOrder = sortOrder !== null && sortOrder !== void 0 ? sortOrder : NumberValueObject.create(1);
31878
- const _byCol = byCol !== null && byCol !== void 0 ? byCol : BooleanValueObject.create(false);
32092
+ let _sortIndex = sortIndex ?? NumberValueObject.create(1);
32093
+ let _sortOrder = sortOrder ?? NumberValueObject.create(1);
32094
+ const _byCol = byCol ?? BooleanValueObject.create(false);
31879
32095
  if (_sortIndex.isNull()) _sortIndex = NumberValueObject.create(1);
31880
32096
  if (_sortOrder.isNull()) _sortOrder = NumberValueObject.create(1);
31881
32097
  if (_byCol.isArray()) {
@@ -32212,7 +32428,7 @@ var Take = class extends BaseFunction {
32212
32428
  const arrayRowCount = array.isArray() ? array.getRowCount() : 1;
32213
32429
  const arrayColumnCount = array.isArray() ? array.getColumnCount() : 1;
32214
32430
  let _rows = rows;
32215
- let _columns = columns !== null && columns !== void 0 ? columns : NumberValueObject.create(arrayColumnCount);
32431
+ let _columns = columns ?? NumberValueObject.create(arrayColumnCount);
32216
32432
  if (rows.isNull()) _rows = NumberValueObject.create(arrayRowCount);
32217
32433
  if (_columns.isNull()) _columns = NumberValueObject.create(arrayColumnCount);
32218
32434
  const maxRowLength = Math.max(_rows.isArray() ? _rows.getRowCount() : 1, _columns.isArray() ? _columns.getRowCount() : 1);
@@ -32287,8 +32503,8 @@ var Tocol = class extends BaseFunction {
32287
32503
  _defineProperty(this, "maxParams", 3);
32288
32504
  }
32289
32505
  calculate(array, ignore, scanByColumn) {
32290
- const _ignore = ignore !== null && ignore !== void 0 ? ignore : NumberValueObject.create(0);
32291
- const _scanByColumn = scanByColumn !== null && scanByColumn !== void 0 ? scanByColumn : BooleanValueObject.create(false);
32506
+ const _ignore = ignore ?? NumberValueObject.create(0);
32507
+ const _scanByColumn = scanByColumn ?? BooleanValueObject.create(false);
32292
32508
  const maxRowLength = Math.max(_ignore.isArray() ? _ignore.getRowCount() : 1, _scanByColumn.isArray() ? _scanByColumn.getRowCount() : 1);
32293
32509
  const maxColumnLength = Math.max(_ignore.isArray() ? _ignore.getColumnCount() : 1, _scanByColumn.isArray() ? _scanByColumn.getColumnCount() : 1);
32294
32510
  const ignoreArray = expandArrayValueObject(maxRowLength, maxColumnLength, _ignore, ErrorValueObject.create("#N/A"));
@@ -32363,8 +32579,8 @@ var Torow = class extends BaseFunction {
32363
32579
  _defineProperty(this, "maxParams", 3);
32364
32580
  }
32365
32581
  calculate(array, ignore, scanByColumn) {
32366
- const _ignore = ignore !== null && ignore !== void 0 ? ignore : NumberValueObject.create(0);
32367
- const _scanByColumn = scanByColumn !== null && scanByColumn !== void 0 ? scanByColumn : BooleanValueObject.create(false);
32582
+ const _ignore = ignore ?? NumberValueObject.create(0);
32583
+ const _scanByColumn = scanByColumn ?? BooleanValueObject.create(false);
32368
32584
  const maxRowLength = Math.max(_ignore.isArray() ? _ignore.getRowCount() : 1, _scanByColumn.isArray() ? _scanByColumn.getRowCount() : 1);
32369
32585
  const maxColumnLength = Math.max(_ignore.isArray() ? _ignore.getColumnCount() : 1, _scanByColumn.isArray() ? _scanByColumn.getColumnCount() : 1);
32370
32586
  const ignoreArray = expandArrayValueObject(maxRowLength, maxColumnLength, _ignore, ErrorValueObject.create("#N/A"));
@@ -32459,8 +32675,8 @@ var Unique = class extends BaseFunction {
32459
32675
  _defineProperty(this, "maxParams", 3);
32460
32676
  }
32461
32677
  calculate(array, byCol, exactlyOnce) {
32462
- const _byCol = byCol !== null && byCol !== void 0 ? byCol : BooleanValueObject.create(false);
32463
- const _exactlyOnce = exactlyOnce !== null && exactlyOnce !== void 0 ? exactlyOnce : BooleanValueObject.create(false);
32678
+ const _byCol = byCol ?? BooleanValueObject.create(false);
32679
+ const _exactlyOnce = exactlyOnce ?? BooleanValueObject.create(false);
32464
32680
  const arrayRowCount = array.isArray() ? array.getRowCount() : 1;
32465
32681
  const arrayColumnCount = array.isArray() ? array.getColumnCount() : 1;
32466
32682
  const maxRowLength = Math.max(_byCol.isArray() ? _byCol.getRowCount() : 1, _exactlyOnce.isArray() ? _exactlyOnce.getRowCount() : 1);
@@ -32589,7 +32805,7 @@ var Vlookup = class extends BaseFunction {
32589
32805
  if (!tableArray.isArray()) return ErrorValueObject.create("#VALUE!");
32590
32806
  if (colIndexNum.isError()) return colIndexNum;
32591
32807
  if (rangeLookup === null || rangeLookup === void 0 ? void 0 : rangeLookup.isError()) return rangeLookup;
32592
- const _rangeLookup = rangeLookup !== null && rangeLookup !== void 0 ? rangeLookup : BooleanValueObject.create(true);
32808
+ const _rangeLookup = rangeLookup ?? BooleanValueObject.create(true);
32593
32809
  if (isSingleValueObject(lookupValue) && isSingleValueObject(_rangeLookup) && colIndexNum.isArray()) return this._handleArrayColIndexNum(lookupValue, tableArray, colIndexNum, _rangeLookup);
32594
32810
  return this._handleNonArrayColIndexNum(lookupValue, tableArray, colIndexNum, _rangeLookup);
32595
32811
  }
@@ -32712,7 +32928,7 @@ var Wrapcols = class extends BaseFunction {
32712
32928
  _defineProperty(this, "maxParams", 3);
32713
32929
  }
32714
32930
  calculate(vector, wrapCount, padWith) {
32715
- let _padWith = padWith !== null && padWith !== void 0 ? padWith : ErrorValueObject.create("#N/A");
32931
+ let _padWith = padWith ?? ErrorValueObject.create("#N/A");
32716
32932
  if (_padWith.isNull()) _padWith = ErrorValueObject.create("#N/A");
32717
32933
  const vectorRowCount = vector.isArray() ? vector.getRowCount() : 1;
32718
32934
  const vectorColumnCount = vector.isArray() ? vector.getColumnCount() : 1;
@@ -32767,7 +32983,7 @@ var Wraprows = class extends BaseFunction {
32767
32983
  _defineProperty(this, "maxParams", 3);
32768
32984
  }
32769
32985
  calculate(vector, wrapCount, padWith) {
32770
- let _padWith = padWith !== null && padWith !== void 0 ? padWith : ErrorValueObject.create("#N/A");
32986
+ let _padWith = padWith ?? ErrorValueObject.create("#N/A");
32771
32987
  if (_padWith.isNull()) _padWith = ErrorValueObject.create("#N/A");
32772
32988
  const vectorRowCount = vector.isArray() ? vector.getRowCount() : 1;
32773
32989
  const vectorColumnCount = vector.isArray() ? vector.getColumnCount() : 1;
@@ -32825,13 +33041,13 @@ var Xlookup = class extends BaseFunction {
32825
33041
  _defineProperty(this, "maxParams", 6);
32826
33042
  }
32827
33043
  calculate(lookupValue, lookupArray, returnArray, ifNotFound, matchMode, searchMode) {
32828
- let _ifNotFound = ifNotFound !== null && ifNotFound !== void 0 ? ifNotFound : ErrorValueObject.create("#N/A");
33044
+ let _ifNotFound = ifNotFound ?? ErrorValueObject.create("#N/A");
32829
33045
  if (ifNotFound === null || ifNotFound === void 0 ? void 0 : ifNotFound.isNull()) _ifNotFound = ErrorValueObject.create("#N/A");
32830
- let _matchMode = matchMode !== null && matchMode !== void 0 ? matchMode : NumberValueObject.create(0);
33046
+ let _matchMode = matchMode ?? NumberValueObject.create(0);
32831
33047
  if (matchMode === null || matchMode === void 0 ? void 0 : matchMode.isNull()) _matchMode = NumberValueObject.create(0);
32832
- let _searchMode = searchMode !== null && searchMode !== void 0 ? searchMode : NumberValueObject.create(1);
33048
+ let _searchMode = searchMode ?? NumberValueObject.create(1);
32833
33049
  if (searchMode === null || searchMode === void 0 ? void 0 : searchMode.isNull()) _searchMode = NumberValueObject.create(1);
32834
- const _lookupValue = this._legacyImplicitLookupValue(lookupValue);
33050
+ const _lookupValue = this.currentFormulaRowCount > 1 || this.currentFormulaColumnCount > 1 ? lookupValue : this._legacyImplicitLookupValue(lookupValue);
32835
33051
  if (_lookupValue.isError()) return _lookupValue;
32836
33052
  const rowCountLookup = lookupArray.isArray() ? lookupArray.getRowCount() : 1;
32837
33053
  const columnCountLookup = lookupArray.isArray() ? lookupArray.getColumnCount() : 1;
@@ -32913,8 +33129,8 @@ var Xlookup = class extends BaseFunction {
32913
33129
  return this.binarySearchExpand(value, searchArray, resultArray, axis, searchType, matchType);
32914
33130
  }
32915
33131
  if (matchModeValue === 2) return this.fuzzySearchExpand(value, searchArray, resultArray, searchModeValue !== -1, axis);
32916
- if (matchModeValue === -1 || matchModeValue === 1) return this.orderSearchExpand(value, searchArray, resultArray, matchModeValue === 1 ? 2 : 1, searchModeValue === -1, axis);
32917
- return this.equalSearchExpand(value, searchArray, resultArray, searchModeValue !== -1, axis);
33132
+ if (matchModeValue === -1 || matchModeValue === 1) return this.orderSearchExpand(value, searchArray, resultArray, matchModeValue === 1 ? 2 : 1, searchModeValue === -1, axis, true);
33133
+ return this._exactSearchExpand(value, searchArray, resultArray, searchModeValue !== -1, axis);
32918
33134
  }
32919
33135
  _handleSingleObject(value, searchArray, resultArray, matchModeValue, searchModeValue) {
32920
33136
  if ((searchModeValue === 2 || searchModeValue === -2) && matchModeValue !== 2) {
@@ -32923,8 +33139,38 @@ var Xlookup = class extends BaseFunction {
32923
33139
  return this.binarySearch(value, searchArray, resultArray, searchType, matchType);
32924
33140
  }
32925
33141
  if (matchModeValue === 2) return this.fuzzySearch(value, searchArray, resultArray, searchModeValue !== -1);
32926
- if (matchModeValue === -1 || matchModeValue === 1) return this.orderSearch(value, searchArray, resultArray, matchModeValue === 1 ? 2 : 1, searchModeValue === -1);
32927
- return this.equalSearch(value, searchArray, resultArray, searchModeValue !== -1);
33142
+ if (matchModeValue === -1 || matchModeValue === 1) return this.orderSearch(value, searchArray, resultArray, matchModeValue === 1 ? 2 : 1, searchModeValue === -1, true);
33143
+ return this._exactSearch(value, searchArray, resultArray, searchModeValue !== -1);
33144
+ }
33145
+ _exactSearch(value, searchArray, resultArray, isFirst) {
33146
+ const position = this._findExactPosition(value, searchArray, isFirst);
33147
+ if (position == null) return ErrorValueObject.create("#N/A");
33148
+ return resultArray.get(position.row, position.column) ?? ErrorValueObject.create("#N/A");
33149
+ }
33150
+ _exactSearchExpand(value, searchArray, resultArray, isFirst, axis) {
33151
+ const position = this._findExactPosition(value, searchArray, isFirst);
33152
+ if (position == null) return ErrorValueObject.create("#N/A");
33153
+ return axis === 0 ? resultArray.slice([position.row, position.row + 1]) ?? ErrorValueObject.create("#N/A") : resultArray.slice(void 0, [position.column, position.column + 1]) ?? ErrorValueObject.create("#N/A");
33154
+ }
33155
+ _findExactPosition(value, searchArray, isFirst) {
33156
+ let position;
33157
+ const find = (candidate, row, column) => {
33158
+ if (candidate != null && this._isExactMatch(candidate, value)) {
33159
+ position = {
33160
+ row,
33161
+ column
33162
+ };
33163
+ return false;
33164
+ }
33165
+ };
33166
+ if (isFirst) searchArray.iterator(find);
33167
+ else searchArray.iteratorReverse(find);
33168
+ return position;
33169
+ }
33170
+ _isExactMatch(candidate, value) {
33171
+ if (candidate.isError() || value.isError()) return candidate.isError() && value.isError() && candidate.getValue() === value.getValue();
33172
+ if (candidate.isNull() !== value.isNull() || candidate.isNumber() !== value.isNumber() || candidate.isString() !== value.isString() || candidate.isBoolean() !== value.isBoolean()) return false;
33173
+ return candidate.isEqual(value).getValue() === true;
32928
33174
  }
32929
33175
  _blankResultAsZero(value) {
32930
33176
  if (value.isNull()) return NumberValueObject.create(0);
@@ -33467,7 +33713,7 @@ var Base = class extends BaseFunction {
33467
33713
  _defineProperty(this, "maxParams", 3);
33468
33714
  }
33469
33715
  calculate(number, radix, minLength) {
33470
- const _minLength = minLength !== null && minLength !== void 0 ? minLength : NumberValueObject.create(0);
33716
+ const _minLength = minLength ?? NumberValueObject.create(0);
33471
33717
  if (number.isError()) return number;
33472
33718
  if (radix.isError()) return radix;
33473
33719
  if (_minLength.isError()) return _minLength;
@@ -33549,8 +33795,8 @@ var CeilingMath = class extends BaseFunction {
33549
33795
  _defineProperty(this, "maxParams", 3);
33550
33796
  }
33551
33797
  calculate(number, significance, mode) {
33552
- const _significance = significance !== null && significance !== void 0 ? significance : NumberValueObject.create(1);
33553
- const _mode = mode !== null && mode !== void 0 ? mode : NumberValueObject.create(0);
33798
+ const _significance = significance ?? NumberValueObject.create(1);
33799
+ const _mode = mode ?? NumberValueObject.create(0);
33554
33800
  if (number.isError()) return number;
33555
33801
  if (_significance.isError()) return _significance;
33556
33802
  if (_mode.isError()) return _mode;
@@ -33595,7 +33841,7 @@ var CeilingPrecise = class extends BaseFunction {
33595
33841
  _defineProperty(this, "maxParams", 2);
33596
33842
  }
33597
33843
  calculate(number, significance) {
33598
- const _significance = significance !== null && significance !== void 0 ? significance : NumberValueObject.create(1);
33844
+ const _significance = significance ?? NumberValueObject.create(1);
33599
33845
  if (number.isError()) return number;
33600
33846
  if (_significance.isError()) return _significance;
33601
33847
  const maxRowLength = Math.max(number.isArray() ? number.getRowCount() : 1, _significance.isArray() ? _significance.getRowCount() : 1);
@@ -34009,8 +34255,8 @@ var FloorMath = class extends BaseFunction {
34009
34255
  _defineProperty(this, "maxParams", 3);
34010
34256
  }
34011
34257
  calculate(number, significance, mode) {
34012
- const _significance = significance !== null && significance !== void 0 ? significance : NumberValueObject.create(1);
34013
- const _mode = mode !== null && mode !== void 0 ? mode : NumberValueObject.create(0);
34258
+ const _significance = significance ?? NumberValueObject.create(1);
34259
+ const _mode = mode ?? NumberValueObject.create(0);
34014
34260
  const maxRowLength = Math.max(number.isArray() ? number.getRowCount() : 1, _significance.isArray() ? _significance.getRowCount() : 1, _mode.isArray() ? _mode.getRowCount() : 1);
34015
34261
  const maxColumnLength = Math.max(number.isArray() ? number.getColumnCount() : 1, _significance.isArray() ? _significance.getColumnCount() : 1, _mode.isArray() ? _mode.getColumnCount() : 1);
34016
34262
  const numberArray = expandArrayValueObject(maxRowLength, maxColumnLength, number, ErrorValueObject.create("#N/A"));
@@ -34049,7 +34295,7 @@ var FloorPrecise = class extends BaseFunction {
34049
34295
  _defineProperty(this, "maxParams", 2);
34050
34296
  }
34051
34297
  calculate(number, significance) {
34052
- const _significance = significance !== null && significance !== void 0 ? significance : NumberValueObject.create(1);
34298
+ const _significance = significance ?? NumberValueObject.create(1);
34053
34299
  if (number.isError()) return number;
34054
34300
  if (_significance.isError()) return _significance;
34055
34301
  const maxRowLength = Math.max(number.isArray() ? number.getRowCount() : 1, _significance.isArray() ? _significance.getRowCount() : 1);
@@ -34249,7 +34495,7 @@ var Log = class extends BaseFunction {
34249
34495
  _defineProperty(this, "maxParams", 2);
34250
34496
  }
34251
34497
  calculate(number, base) {
34252
- const _base = base !== null && base !== void 0 ? base : NumberValueObject.create(10);
34498
+ const _base = base ?? NumberValueObject.create(10);
34253
34499
  if (number.isError()) return number;
34254
34500
  if (_base.isError()) return _base;
34255
34501
  const maxRowLength = Math.max(number.isArray() ? number.getRowCount() : 1, _base.isArray() ? _base.getRowCount() : 1);
@@ -34762,11 +35008,11 @@ var Randarray = class extends BaseFunction {
34762
35008
  if (min === null || min === void 0 ? void 0 : min.isError()) return min;
34763
35009
  if (max === null || max === void 0 ? void 0 : max.isError()) return max;
34764
35010
  if (wholeNumber === null || wholeNumber === void 0 ? void 0 : wholeNumber.isError()) return wholeNumber;
34765
- const _rows = rows !== null && rows !== void 0 ? rows : NumberValueObject.create(1);
34766
- const _columns = columns !== null && columns !== void 0 ? columns : NumberValueObject.create(1);
34767
- const _min = min !== null && min !== void 0 ? min : NumberValueObject.create(0);
34768
- const _max = max !== null && max !== void 0 ? max : NumberValueObject.create(1);
34769
- const _wholeNumber = wholeNumber !== null && wholeNumber !== void 0 ? wholeNumber : NumberValueObject.create(0);
35011
+ const _rows = rows ?? NumberValueObject.create(1);
35012
+ const _columns = columns ?? NumberValueObject.create(1);
35013
+ const _min = min ?? NumberValueObject.create(0);
35014
+ const _max = max ?? NumberValueObject.create(1);
35015
+ const _wholeNumber = wholeNumber ?? NumberValueObject.create(0);
34770
35016
  return this._calculateResult(_rows, _columns, _min, _max, _wholeNumber);
34771
35017
  }
34772
35018
  _calculateResult(rows, columns, min, max, wholeNumber) {
@@ -34913,7 +35159,7 @@ var Roman = class extends BaseFunction {
34913
35159
  _defineProperty(this, "maxParams", 2);
34914
35160
  }
34915
35161
  calculate(number, form) {
34916
- const _form = form !== null && form !== void 0 ? form : NumberValueObject.create(0);
35162
+ const _form = form ?? NumberValueObject.create(0);
34917
35163
  const maxRowLength = Math.max(number.isArray() ? number.getRowCount() : 1, _form.isArray() ? _form.getRowCount() : 1);
34918
35164
  const maxColumnLength = Math.max(number.isArray() ? number.getColumnCount() : 1, _form.isArray() ? _form.getColumnCount() : 1);
34919
35165
  const numberArray = expandArrayValueObject(maxRowLength, maxColumnLength, number, ErrorValueObject.create("#N/A"));
@@ -35120,9 +35366,9 @@ var Sequence = class extends BaseFunction {
35120
35366
  }
35121
35367
  calculate(rows, columns, start, step) {
35122
35368
  let _rows = rows;
35123
- let _columns = columns !== null && columns !== void 0 ? columns : NumberValueObject.create(1);
35124
- let _start = start !== null && start !== void 0 ? start : NumberValueObject.create(1);
35125
- let _step = step !== null && step !== void 0 ? step : NumberValueObject.create(1);
35369
+ let _columns = columns ?? NumberValueObject.create(1);
35370
+ let _start = start ?? NumberValueObject.create(1);
35371
+ let _step = step ?? NumberValueObject.create(1);
35126
35372
  if (_rows.isNull()) _rows = NumberValueObject.create(1);
35127
35373
  if (_columns.isNull()) _columns = NumberValueObject.create(1);
35128
35374
  if (_start.isNull()) _start = NumberValueObject.create(1);
@@ -35476,8 +35722,7 @@ var Subtotal = class extends BaseFunction {
35476
35722
  multiAreaRefs.forEach((ref) => {
35477
35723
  const rowAreas = ref.getAreas().map((row) => {
35478
35724
  if (!row || row.length === 0) return ref;
35479
- const firstNonError = row.find((a) => !a.isError());
35480
- return firstNonError !== null && firstNonError !== void 0 ? firstNonError : row[0];
35725
+ return row.find((a) => !a.isError()) ?? row[0];
35481
35726
  });
35482
35727
  multiAreaInfoMap.set(ref, {
35483
35728
  ref,
@@ -35492,54 +35737,6 @@ var Subtotal = class extends BaseFunction {
35492
35737
  }
35493
35738
  };
35494
35739
 
35495
- //#endregion
35496
- //#region src/functions/math/sum/index.ts
35497
- var Sum = class extends BaseFunction {
35498
- constructor(..._args) {
35499
- super(..._args);
35500
- _defineProperty(this, "minParams", 1);
35501
- _defineProperty(this, "maxParams", 255);
35502
- }
35503
- calculate(...variants) {
35504
- let accumulatorAll = NumberValueObject.create(0);
35505
- for (let i = 0; i < variants.length; i++) {
35506
- let variant = variants[i];
35507
- variant = this._legacyImplicitDerivedArray(variant);
35508
- if (variant.isString()) variant = variant.convertToNumberObjectValue();
35509
- if (variant.isError()) return variant;
35510
- if (variant.isArray()) variant = variant.sum();
35511
- if (variant.isError()) return variant;
35512
- accumulatorAll = accumulatorAll.plus(variant);
35513
- if (accumulatorAll.isError()) return accumulatorAll;
35514
- }
35515
- return accumulatorAll;
35516
- }
35517
- _legacyImplicitDerivedArray(variant) {
35518
- if (!variant.isArray()) return variant;
35519
- const array = variant;
35520
- if (array.usesInvertedIndexCache() || !array.usesLegacyImplicitForAggregate()) return variant;
35521
- const startRow = array.getCurrentRow();
35522
- const startColumn = array.getCurrentColumn();
35523
- if (startRow < 0 || startColumn < 0) return variant;
35524
- const rowCount = array.getRowCount();
35525
- const columnCount = array.getColumnCount();
35526
- let rowIndex = -1;
35527
- let columnIndex = -1;
35528
- if (rowCount === 1) {
35529
- rowIndex = 0;
35530
- columnIndex = this.column - startColumn;
35531
- } else if (columnCount === 1) {
35532
- rowIndex = this.row - startRow;
35533
- columnIndex = 0;
35534
- } else {
35535
- rowIndex = this.row - startRow;
35536
- columnIndex = this.column - startColumn;
35537
- }
35538
- if (rowIndex < 0 || rowIndex >= rowCount || columnIndex < 0 || columnIndex >= columnCount) return variant;
35539
- return array.get(rowIndex, columnIndex) || variant;
35540
- }
35541
- };
35542
-
35543
35740
  //#endregion
35544
35741
  //#region src/functions/math/sumif/index.ts
35545
35742
  var Sumif = class extends BaseFunction {
@@ -35626,6 +35823,7 @@ var Sumproduct = class extends BaseFunction {
35626
35823
  super(..._args);
35627
35824
  _defineProperty(this, "minParams", 1);
35628
35825
  _defineProperty(this, "maxParams", 255);
35826
+ _defineProperty(this, "lazyIfReferenceArrayArgumentIndexes", Array.from({ length: this.maxParams }, (_, index) => index));
35629
35827
  }
35630
35828
  calculate(array1, ...variants) {
35631
35829
  if (array1.isError()) return array1;
@@ -35688,8 +35886,7 @@ var Sumproduct = class extends BaseFunction {
35688
35886
  */
35689
35887
  _getVariantCell(variant, row, col) {
35690
35888
  if (!variant.isArray()) return variant;
35691
- const cell = variant.get(row, col);
35692
- return cell !== null && cell !== void 0 ? cell : null;
35889
+ return variant.get(row, col) ?? null;
35693
35890
  }
35694
35891
  _initArray1(array1) {
35695
35892
  let _array1 = array1;
@@ -35971,7 +36168,7 @@ var Trunc = class extends BaseFunction {
35971
36168
  _defineProperty(this, "maxParams", 2);
35972
36169
  }
35973
36170
  calculate(number, numDigits) {
35974
- const _numDigits = numDigits !== null && numDigits !== void 0 ? numDigits : NumberValueObject.create(0);
36171
+ const _numDigits = numDigits ?? NumberValueObject.create(0);
35975
36172
  const maxRowLength = Math.max(number.isArray() ? number.getRowCount() : 1, _numDigits.isArray() ? _numDigits.getRowCount() : 1);
35976
36173
  const maxColumnLength = Math.max(number.isArray() ? number.getColumnCount() : 1, _numDigits.isArray() ? _numDigits.getColumnCount() : 1);
35977
36174
  const numberArray = expandArrayValueObject(maxRowLength, maxColumnLength, number, ErrorValueObject.create("#N/A"));
@@ -36616,8 +36813,8 @@ var BetaDist = class extends BaseFunction {
36616
36813
  _defineProperty(this, "maxParams", 6);
36617
36814
  }
36618
36815
  calculate(x, alpha, beta, cumulative, A, B) {
36619
- let _A = A !== null && A !== void 0 ? A : NumberValueObject.create(0);
36620
- let _B = B !== null && B !== void 0 ? B : NumberValueObject.create(1);
36816
+ let _A = A ?? NumberValueObject.create(0);
36817
+ let _B = B ?? NumberValueObject.create(1);
36621
36818
  if (_A.isNull()) _A = NumberValueObject.create(0);
36622
36819
  if (_B.isNull()) _B = NumberValueObject.create(1);
36623
36820
  const maxRowLength = Math.max(x.isArray() ? x.getRowCount() : 1, alpha.isArray() ? alpha.getRowCount() : 1, beta.isArray() ? beta.getRowCount() : 1, cumulative.isArray() ? cumulative.getRowCount() : 1, _A.isArray() ? _A.getRowCount() : 1, _B.isArray() ? _B.getRowCount() : 1);
@@ -36672,7 +36869,7 @@ var BinomDistRange = class extends BaseFunction {
36672
36869
  _defineProperty(this, "maxParams", 4);
36673
36870
  }
36674
36871
  calculate(trials, probabilityS, numberS, numberS2) {
36675
- let _numberS2 = numberS2 !== null && numberS2 !== void 0 ? numberS2 : numberS;
36872
+ let _numberS2 = numberS2 ?? numberS;
36676
36873
  if (_numberS2.isNull()) _numberS2 = numberS;
36677
36874
  const maxRowLength = Math.max(trials.isArray() ? trials.getRowCount() : 1, probabilityS.isArray() ? probabilityS.getRowCount() : 1, numberS.isArray() ? numberS.getRowCount() : 1, _numberS2.isArray() ? _numberS2.getRowCount() : 1);
36678
36875
  const maxColumnLength = Math.max(trials.isArray() ? trials.getColumnCount() : 1, probabilityS.isArray() ? probabilityS.getColumnCount() : 1, numberS.isArray() ? numberS.getColumnCount() : 1, _numberS2.isArray() ? _numberS2.getColumnCount() : 1);
@@ -37545,7 +37742,7 @@ var Growth = class extends BaseFunction {
37545
37742
  if (knownXsValues instanceof ErrorValueObject) return knownXsValues;
37546
37743
  const newXsValues = this._getNewXsValues(knownXsValues, newXs);
37547
37744
  if (newXsValues instanceof ErrorValueObject) return newXsValues;
37548
- let _constb = constb !== null && constb !== void 0 ? constb : BooleanValueObject.create(true);
37745
+ let _constb = constb ?? BooleanValueObject.create(true);
37549
37746
  if (_constb.isArray()) _constb = _constb.get(0, 0);
37550
37747
  if (_constb.isString()) _constb = _constb.convertToNumberObjectValue();
37551
37748
  if (_constb.isError()) return _constb;
@@ -37825,9 +38022,9 @@ var Linest = class extends BaseFunction {
37825
38022
  if (knownYsValues instanceof ErrorValueObject) return knownYsValues;
37826
38023
  const knownXsValues = this._getKnownXsValues(knownYsValues, knownXs);
37827
38024
  if (knownXsValues instanceof ErrorValueObject) return knownXsValues;
37828
- let _constb = constb !== null && constb !== void 0 ? constb : BooleanValueObject.create(true);
38025
+ let _constb = constb ?? BooleanValueObject.create(true);
37829
38026
  if (_constb.isArray()) _constb = _constb.get(0, 0);
37830
- let _stats = stats !== null && stats !== void 0 ? stats : BooleanValueObject.create(false);
38027
+ let _stats = stats ?? BooleanValueObject.create(false);
37831
38028
  if (_stats.isArray()) _stats = _stats.get(0, 0);
37832
38029
  const { isError: _isError, errorObject: _errorObject, variants } = checkVariantsErrorIsStringToNumber(_constb, _stats);
37833
38030
  if (_isError) return _errorObject;
@@ -37982,9 +38179,9 @@ var Logest = class extends BaseFunction {
37982
38179
  if (knownYsValues instanceof ErrorValueObject) return knownYsValues;
37983
38180
  const knownXsValues = this._getKnownXsValues(knownYsValues, knownXs);
37984
38181
  if (knownXsValues instanceof ErrorValueObject) return knownXsValues;
37985
- let _constb = constb !== null && constb !== void 0 ? constb : BooleanValueObject.create(true);
38182
+ let _constb = constb ?? BooleanValueObject.create(true);
37986
38183
  if (_constb.isArray()) _constb = _constb.get(0, 0);
37987
- let _stats = stats !== null && stats !== void 0 ? stats : BooleanValueObject.create(false);
38184
+ let _stats = stats ?? BooleanValueObject.create(false);
37988
38185
  if (_stats.isArray()) _stats = _stats.get(0, 0);
37989
38186
  const { isError: _isError, errorObject: _errorObject, variants } = checkVariantsErrorIsStringToNumber(_constb, _stats);
37990
38187
  if (_isError) return _errorObject;
@@ -38324,6 +38521,7 @@ var Median = class extends BaseFunction {
38324
38521
  super(..._args);
38325
38522
  _defineProperty(this, "minParams", 1);
38326
38523
  _defineProperty(this, "maxParams", 255);
38524
+ _defineProperty(this, "lazyIfReferenceArrayArgumentIndexes", Array.from({ length: this.maxParams }, (_, index) => index));
38327
38525
  }
38328
38526
  calculate(...variants) {
38329
38527
  const values = [];
@@ -38654,6 +38852,7 @@ var PercentileExc = class extends BaseFunction {
38654
38852
  super(..._args);
38655
38853
  _defineProperty(this, "minParams", 2);
38656
38854
  _defineProperty(this, "maxParams", 2);
38855
+ _defineProperty(this, "lazyIfReferenceArrayArgumentIndexes", [0]);
38657
38856
  }
38658
38857
  calculate(array, k) {
38659
38858
  const arrayValues = getArrayValuesByAggregateIgnoreOptions(array);
@@ -38683,7 +38882,7 @@ var PercentrankExc = class extends BaseFunction {
38683
38882
  }
38684
38883
  calculate(array, x, significance) {
38685
38884
  const arrayValues = this._getValues(array);
38686
- let _significance = significance !== null && significance !== void 0 ? significance : NumberValueObject.create(3);
38885
+ let _significance = significance ?? NumberValueObject.create(3);
38687
38886
  if (_significance.isNull()) _significance = NumberValueObject.create(3);
38688
38887
  const maxRowLength = Math.max(x.isArray() ? x.getRowCount() : 1, _significance.isArray() ? _significance.getRowCount() : 1);
38689
38888
  const maxColumnLength = Math.max(x.isArray() ? x.getColumnCount() : 1, _significance.isArray() ? _significance.getColumnCount() : 1);
@@ -38846,7 +39045,7 @@ var Prob = class extends BaseFunction {
38846
39045
  }
38847
39046
  calculate(xRange, probRange, lowerLimit, upperLimit) {
38848
39047
  const { isError, errorObject, xRangeValues, probRangeValues } = this._handleXRangeAndProbRange(xRange, probRange);
38849
- let _upperLimit = upperLimit !== null && upperLimit !== void 0 ? upperLimit : lowerLimit;
39048
+ let _upperLimit = upperLimit ?? lowerLimit;
38850
39049
  if (upperLimit === null || upperLimit === void 0 ? void 0 : upperLimit.isNull()) _upperLimit = lowerLimit;
38851
39050
  const maxRowLength = Math.max(lowerLimit.isArray() ? lowerLimit.getRowCount() : 1, _upperLimit.isArray() ? _upperLimit.getRowCount() : 1);
38852
39051
  const maxColumnLength = Math.max(lowerLimit.isArray() ? lowerLimit.getColumnCount() : 1, _upperLimit.isArray() ? _upperLimit.getColumnCount() : 1);
@@ -38971,12 +39170,13 @@ var RankAvg = class extends BaseFunction {
38971
39170
  _defineProperty(this, "minParams", 2);
38972
39171
  _defineProperty(this, "maxParams", 3);
38973
39172
  _defineProperty(this, "needsReferenceObject", true);
39173
+ _defineProperty(this, "lazyIfReferenceArrayArgumentIndexes", [1]);
38974
39174
  }
38975
39175
  calculate(number, ref, order) {
38976
39176
  let _number = number;
38977
39177
  if (_number.isReferenceObject()) _number = _number.toArrayValueObject();
38978
39178
  const { refHasError, refErrorObject, refNumbers } = this._checkRefReferenceObject(ref);
38979
- let _order = order !== null && order !== void 0 ? order : NumberValueObject.create(0);
39179
+ let _order = order ?? NumberValueObject.create(0);
38980
39180
  if (_order.isReferenceObject()) _order = _order.toArrayValueObject();
38981
39181
  const maxRowLength = Math.max(_number.isArray() ? _number.getRowCount() : 1, _order.isArray() ? _order.getRowCount() : 1);
38982
39182
  const maxColumnLength = Math.max(_number.isArray() ? _number.getColumnCount() : 1, _order.isArray() ? _order.getColumnCount() : 1);
@@ -39045,12 +39245,13 @@ var RankEq = class extends BaseFunction {
39045
39245
  _defineProperty(this, "minParams", 2);
39046
39246
  _defineProperty(this, "maxParams", 3);
39047
39247
  _defineProperty(this, "needsReferenceObject", true);
39248
+ _defineProperty(this, "lazyIfReferenceArrayArgumentIndexes", [1]);
39048
39249
  }
39049
39250
  calculate(number, ref, order) {
39050
39251
  let _number = number;
39051
39252
  if (_number.isReferenceObject()) _number = _number.toArrayValueObject();
39052
39253
  const { refHasError, refErrorObject, refNumbers } = this._checkRefReferenceObject(ref);
39053
- let _order = order !== null && order !== void 0 ? order : NumberValueObject.create(0);
39254
+ let _order = order ?? NumberValueObject.create(0);
39054
39255
  if (_order.isReferenceObject()) _order = _order.toArrayValueObject();
39055
39256
  const maxRowLength = Math.max(_number.isArray() ? _number.getRowCount() : 1, _order.isArray() ? _order.getRowCount() : 1);
39056
39257
  const maxColumnLength = Math.max(_number.isArray() ? _number.getColumnCount() : 1, _order.isArray() ? _order.getColumnCount() : 1);
@@ -39609,7 +39810,7 @@ var Trend = class extends BaseFunction {
39609
39810
  if (knownXsValues instanceof ErrorValueObject) return knownXsValues;
39610
39811
  const newXsValues = this._getNewXsValues(knownXsValues, newXs);
39611
39812
  if (newXsValues instanceof ErrorValueObject) return newXsValues;
39612
- let _constb = constb !== null && constb !== void 0 ? constb : BooleanValueObject.create(true);
39813
+ let _constb = constb ?? BooleanValueObject.create(true);
39613
39814
  if (_constb.isArray()) _constb = _constb.get(0, 0);
39614
39815
  if (_constb.isString()) _constb = _constb.convertToNumberObjectValue();
39615
39816
  if (_constb.isError()) return _constb;
@@ -39878,7 +40079,7 @@ var Arraytotext = class extends BaseFunction {
39878
40079
  _defineProperty(this, "maxParams", 2);
39879
40080
  }
39880
40081
  calculate(array, format) {
39881
- let _format = format !== null && format !== void 0 ? format : NumberValueObject.create(0);
40082
+ let _format = format ?? NumberValueObject.create(0);
39882
40083
  if (format === null || format === void 0 ? void 0 : format.isNull()) _format = NumberValueObject.create(0);
39883
40084
  if (_format.isArray()) {
39884
40085
  const resultArray = _format.mapValue((formatObject) => this._handleSingleObject(array, formatObject));
@@ -40188,12 +40389,11 @@ var Concatenate = class extends BaseFunction {
40188
40389
  return arrayValue.getUnitId() !== "" && arrayValue.getSheetId() !== "" && arrayValue.getCurrentRow() >= 0 && arrayValue.getCurrentColumn() >= 0;
40189
40390
  });
40190
40391
  for (const textValue of textValues) result = expandArrayValueObject(maxRowLength, maxColumnLength, textValue, ErrorValueObject.create("#N/A")).mapValue((textValueObject, rowIndex, columnIndex) => {
40191
- var _resultValueObject$ge, _textValueObject$getV;
40192
40392
  const resultValueObject = result && result.get(rowIndex, columnIndex);
40193
40393
  if (resultValueObject === null || resultValueObject === void 0 ? void 0 : resultValueObject.isError()) return resultValueObject;
40194
40394
  if (textValueObject.isError()) return textValueObject;
40195
- const resultValueObjectString = (resultValueObject === null || resultValueObject === void 0 ? void 0 : resultValueObject.isNull()) ? "" : formatValueForFormulaText((_resultValueObject$ge = resultValueObject === null || resultValueObject === void 0 ? void 0 : resultValueObject.getValue()) !== null && _resultValueObject$ge !== void 0 ? _resultValueObject$ge : null);
40196
- const textValueObjectString = (textValueObject === null || textValueObject === void 0 ? void 0 : textValueObject.isNull()) ? "" : formatValueForFormulaText((_textValueObject$getV = textValueObject === null || textValueObject === void 0 ? void 0 : textValueObject.getValue()) !== null && _textValueObject$getV !== void 0 ? _textValueObject$getV : null);
40395
+ const resultValueObjectString = (resultValueObject === null || resultValueObject === void 0 ? void 0 : resultValueObject.isNull()) ? "" : formatValueForFormulaText((resultValueObject === null || resultValueObject === void 0 ? void 0 : resultValueObject.getValue()) ?? null);
40396
+ const textValueObjectString = (textValueObject === null || textValueObject === void 0 ? void 0 : textValueObject.isNull()) ? "" : formatValueForFormulaText((textValueObject === null || textValueObject === void 0 ? void 0 : textValueObject.getValue()) ?? null);
40197
40397
  return StringValueObject.create(`${resultValueObjectString}${textValueObjectString}`);
40198
40398
  });
40199
40399
  if (!result) return ErrorValueObject.create("#VALUE!");
@@ -40249,7 +40449,7 @@ var Dollar = class extends BaseFunction {
40249
40449
  _defineProperty(this, "needsLocale", true);
40250
40450
  }
40251
40451
  calculate(number, decimals) {
40252
- let _decimals = decimals !== null && decimals !== void 0 ? decimals : NumberValueObject.create(2);
40452
+ let _decimals = decimals ?? NumberValueObject.create(2);
40253
40453
  if (_decimals.isNull()) _decimals = NumberValueObject.create(2);
40254
40454
  const maxRowLength = Math.max(number.isArray() ? number.getRowCount() : 1, _decimals.isArray() ? _decimals.getRowCount() : 1);
40255
40455
  const maxColumnLength = Math.max(number.isArray() ? number.getColumnCount() : 1, _decimals.isArray() ? _decimals.getColumnCount() : 1);
@@ -40348,7 +40548,7 @@ var Find = class extends BaseFunction {
40348
40548
  _defineProperty(this, "maxParams", 3);
40349
40549
  }
40350
40550
  calculate(findText, withinText, startNum) {
40351
- const _startNum = startNum !== null && startNum !== void 0 ? startNum : NumberValueObject.create(1);
40551
+ const _startNum = startNum ?? NumberValueObject.create(1);
40352
40552
  const maxRowLength = Math.max(findText.isArray() ? findText.getRowCount() : 1, withinText.isArray() ? withinText.getRowCount() : 1, _startNum.isArray() ? _startNum.getRowCount() : 1);
40353
40553
  const maxColumnLength = Math.max(findText.isArray() ? findText.getColumnCount() : 1, withinText.isArray() ? withinText.getColumnCount() : 1, _startNum.isArray() ? _startNum.getColumnCount() : 1);
40354
40554
  const findTextArray = expandArrayValueObject(maxRowLength, maxColumnLength, findText, ErrorValueObject.create("#N/A"));
@@ -40442,7 +40642,7 @@ var Findb = class extends BaseFunction {
40442
40642
  _defineProperty(this, "maxParams", 3);
40443
40643
  }
40444
40644
  calculate(findText, withinText, startNum) {
40445
- const _startNum = startNum !== null && startNum !== void 0 ? startNum : NumberValueObject.create(1);
40645
+ const _startNum = startNum ?? NumberValueObject.create(1);
40446
40646
  const maxRowLength = Math.max(findText.isArray() ? findText.getRowCount() : 1, withinText.isArray() ? withinText.getRowCount() : 1, _startNum.isArray() ? _startNum.getRowCount() : 1);
40447
40647
  const maxColumnLength = Math.max(findText.isArray() ? findText.getColumnCount() : 1, withinText.isArray() ? withinText.getColumnCount() : 1, _startNum.isArray() ? _startNum.getColumnCount() : 1);
40448
40648
  const findTextArray = expandArrayValueObject(maxRowLength, maxColumnLength, findText, ErrorValueObject.create("#N/A"));
@@ -40484,9 +40684,9 @@ var Fixed = class extends BaseFunction {
40484
40684
  _defineProperty(this, "maxParams", 3);
40485
40685
  }
40486
40686
  calculate(number, decimals, noCommas) {
40487
- let _decimals = decimals !== null && decimals !== void 0 ? decimals : NumberValueObject.create(2);
40687
+ let _decimals = decimals ?? NumberValueObject.create(2);
40488
40688
  if (_decimals.isNull()) _decimals = NumberValueObject.create(2);
40489
- let _noCommas = noCommas !== null && noCommas !== void 0 ? noCommas : BooleanValueObject.create(false);
40689
+ let _noCommas = noCommas ?? BooleanValueObject.create(false);
40490
40690
  if (_noCommas.isNull()) _noCommas = BooleanValueObject.create(false);
40491
40691
  const maxRowLength = Math.max(number.isArray() ? number.getRowCount() : 1, _decimals.isArray() ? _decimals.getRowCount() : 1, _noCommas.isArray() ? _noCommas.getRowCount() : 1);
40492
40692
  const maxColumnLength = Math.max(number.isArray() ? number.getColumnCount() : 1, _decimals.isArray() ? _decimals.getColumnCount() : 1, _noCommas.isArray() ? _noCommas.getColumnCount() : 1);
@@ -40533,7 +40733,7 @@ var Left = class extends BaseFunction {
40533
40733
  _defineProperty(this, "maxParams", 2);
40534
40734
  }
40535
40735
  calculate(text, numChars) {
40536
- const _numChars = numChars !== null && numChars !== void 0 ? numChars : NumberValueObject.create(1);
40736
+ const _numChars = numChars ?? NumberValueObject.create(1);
40537
40737
  const maxRowLength = Math.max(text.isArray() ? text.getRowCount() : 1, _numChars.isArray() ? _numChars.getRowCount() : 1);
40538
40738
  const maxColumnLength = Math.max(text.isArray() ? text.getColumnCount() : 1, _numChars.isArray() ? _numChars.getColumnCount() : 1);
40539
40739
  const textArray = expandArrayValueObject(maxRowLength, maxColumnLength, text, ErrorValueObject.create("#N/A"));
@@ -40570,7 +40770,7 @@ var Leftb = class extends BaseFunction {
40570
40770
  _defineProperty(this, "maxParams", 2);
40571
40771
  }
40572
40772
  calculate(text, numBytes) {
40573
- const _numBytes = numBytes !== null && numBytes !== void 0 ? numBytes : NumberValueObject.create(1);
40773
+ const _numBytes = numBytes ?? NumberValueObject.create(1);
40574
40774
  const maxRowLength = Math.max(text.isArray() ? text.getRowCount() : 1, _numBytes.isArray() ? _numBytes.getRowCount() : 1);
40575
40775
  const maxColumnLength = Math.max(text.isArray() ? text.getColumnCount() : 1, _numBytes.isArray() ? _numBytes.getColumnCount() : 1);
40576
40776
  const textArray = expandArrayValueObject(maxRowLength, maxColumnLength, text, NullValueObject.create());
@@ -40885,7 +41085,7 @@ var Numbervalue = class extends BaseFunction {
40885
41085
  return true;
40886
41086
  }
40887
41087
  calculate(text, decimalSeparator, groupSeparator) {
40888
- const _decimalSeparator = decimalSeparator !== null && decimalSeparator !== void 0 ? decimalSeparator : StringValueObject.create(".");
41088
+ const _decimalSeparator = decimalSeparator ?? StringValueObject.create(".");
40889
41089
  const maxRowLength = Math.max(text.isArray() ? text.getRowCount() : 1, _decimalSeparator.isArray() ? _decimalSeparator.getRowCount() : 1, (groupSeparator === null || groupSeparator === void 0 ? void 0 : groupSeparator.isArray()) ? groupSeparator.getRowCount() : 1);
40890
41090
  const maxColumnLength = Math.max(text.isArray() ? text.getColumnCount() : 1, _decimalSeparator.isArray() ? _decimalSeparator.getColumnCount() : 1, (groupSeparator === null || groupSeparator === void 0 ? void 0 : groupSeparator.isArray()) ? groupSeparator.getColumnCount() : 1);
40891
41091
  const textArray = expandArrayValueObject(maxRowLength, maxColumnLength, text, ErrorValueObject.create("#N/A"));
@@ -41416,8 +41616,7 @@ function isValidRegExp(regExpString) {
41416
41616
  return !(/\(\?<=.*?\)/g.test(regExpString) && !/\[.*?(\?<=.*?)\]/g.test(regExpString) || /\(\?<!.*?\)/g.test(regExpString) && !/\[.*?(\?<!.*?)\]/g.test(regExpString));
41417
41617
  }
41418
41618
  function isSafeRegExp(regExp, options) {
41419
- var _options$limit;
41420
- const limit = (_options$limit = options === null || options === void 0 ? void 0 : options.limit) !== null && _options$limit !== void 0 ? _options$limit : 25;
41619
+ const limit = (options === null || options === void 0 ? void 0 : options.limit) ?? 25;
41421
41620
  let str;
41422
41621
  if (Object.prototype.toString.call(regExp) === "[object RegExp]") str = regExp.source;
41423
41622
  else if (regExp && typeof regExp !== "string") str = `${regExp}`;
@@ -41697,7 +41896,7 @@ var Right = class extends BaseFunction {
41697
41896
  _defineProperty(this, "maxParams", 2);
41698
41897
  }
41699
41898
  calculate(text, numChars) {
41700
- const _numChars = numChars !== null && numChars !== void 0 ? numChars : NumberValueObject.create(1);
41899
+ const _numChars = numChars ?? NumberValueObject.create(1);
41701
41900
  const maxRowLength = Math.max(text.isArray() ? text.getRowCount() : 1, _numChars.isArray() ? _numChars.getRowCount() : 1);
41702
41901
  const maxColumnLength = Math.max(text.isArray() ? text.getColumnCount() : 1, _numChars.isArray() ? _numChars.getColumnCount() : 1);
41703
41902
  const textArray = expandArrayValueObject(maxRowLength, maxColumnLength, text, ErrorValueObject.create("#N/A"));
@@ -41734,7 +41933,7 @@ var Rightb = class extends BaseFunction {
41734
41933
  _defineProperty(this, "maxParams", 2);
41735
41934
  }
41736
41935
  calculate(text, numBytes) {
41737
- const _numBytes = numBytes !== null && numBytes !== void 0 ? numBytes : NumberValueObject.create(1);
41936
+ const _numBytes = numBytes ?? NumberValueObject.create(1);
41738
41937
  const maxRowLength = Math.max(text.isArray() ? text.getRowCount() : 1, _numBytes.isArray() ? _numBytes.getRowCount() : 1);
41739
41938
  const maxColumnLength = Math.max(text.isArray() ? text.getColumnCount() : 1, _numBytes.isArray() ? _numBytes.getColumnCount() : 1);
41740
41939
  const textArray = expandArrayValueObject(maxRowLength, maxColumnLength, text, ErrorValueObject.create("#N/A"));
@@ -41777,7 +41976,7 @@ var Search = class extends BaseFunction {
41777
41976
  _defineProperty(this, "maxParams", 3);
41778
41977
  }
41779
41978
  calculate(findText, withinText, startNum) {
41780
- const _startNum = startNum !== null && startNum !== void 0 ? startNum : NumberValueObject.create(1);
41979
+ const _startNum = startNum ?? NumberValueObject.create(1);
41781
41980
  const maxRowLength = Math.max(findText.isArray() ? findText.getRowCount() : 1, withinText.isArray() ? withinText.getRowCount() : 1, _startNum.isArray() ? _startNum.getRowCount() : 1);
41782
41981
  const maxColumnLength = Math.max(findText.isArray() ? findText.getColumnCount() : 1, withinText.isArray() ? withinText.getColumnCount() : 1, _startNum.isArray() ? _startNum.getColumnCount() : 1);
41783
41982
  const findTextArray = expandArrayValueObject(maxRowLength, maxColumnLength, findText, ErrorValueObject.create("#N/A"));
@@ -41818,7 +42017,7 @@ var Searchb = class extends BaseFunction {
41818
42017
  _defineProperty(this, "maxParams", 3);
41819
42018
  }
41820
42019
  calculate(findText, withinText, startNum) {
41821
- const _startNum = startNum !== null && startNum !== void 0 ? startNum : NumberValueObject.create(1);
42020
+ const _startNum = startNum ?? NumberValueObject.create(1);
41822
42021
  const maxRowLength = Math.max(findText.isArray() ? findText.getRowCount() : 1, withinText.isArray() ? withinText.getRowCount() : 1, _startNum.isArray() ? _startNum.getRowCount() : 1);
41823
42022
  const maxColumnLength = Math.max(findText.isArray() ? findText.getColumnCount() : 1, withinText.isArray() ? withinText.getColumnCount() : 1, _startNum.isArray() ? _startNum.getColumnCount() : 1);
41824
42023
  const findTextArray = expandArrayValueObject(maxRowLength, maxColumnLength, findText, ErrorValueObject.create("#N/A"));
@@ -41991,15 +42190,15 @@ var Textafter = class extends BaseFunction {
41991
42190
  }
41992
42191
  calculate(text, delimiter, instanceNum, matchMode, matchEnd, ifNotFound) {
41993
42192
  let instanceNumIsNull = false;
41994
- let _instanceNum = instanceNum !== null && instanceNum !== void 0 ? instanceNum : NumberValueObject.create(1);
42193
+ let _instanceNum = instanceNum ?? NumberValueObject.create(1);
41995
42194
  if (_instanceNum.isNull()) {
41996
42195
  instanceNumIsNull = true;
41997
42196
  _instanceNum = NumberValueObject.create(1);
41998
42197
  }
41999
42198
  const onlyThreeVariant = !matchMode;
42000
- const _matchMode = matchMode !== null && matchMode !== void 0 ? matchMode : NumberValueObject.create(0);
42001
- const _matchEnd = matchEnd !== null && matchEnd !== void 0 ? matchEnd : NumberValueObject.create(0);
42002
- const _ifNotFound = ifNotFound !== null && ifNotFound !== void 0 ? ifNotFound : ErrorValueObject.create("#N/A");
42199
+ const _matchMode = matchMode ?? NumberValueObject.create(0);
42200
+ const _matchEnd = matchEnd ?? NumberValueObject.create(0);
42201
+ const _ifNotFound = ifNotFound ?? ErrorValueObject.create("#N/A");
42003
42202
  const maxRowLength = Math.max(text.isArray() ? text.getRowCount() : 1, _instanceNum.isArray() ? _instanceNum.getRowCount() : 1, _matchMode.isArray() ? _matchMode.getRowCount() : 1, _matchEnd.isArray() ? _matchEnd.getRowCount() : 1, _ifNotFound.isArray() ? _ifNotFound.getRowCount() : 1);
42004
42203
  const maxColumnLength = Math.max(text.isArray() ? text.getColumnCount() : 1, _instanceNum.isArray() ? _instanceNum.getColumnCount() : 1, _matchMode.isArray() ? _matchMode.getColumnCount() : 1, _matchEnd.isArray() ? _matchEnd.getColumnCount() : 1, _ifNotFound.isArray() ? _ifNotFound.getColumnCount() : 1);
42005
42204
  const textArray = expandArrayValueObject(maxRowLength, maxColumnLength, text, ErrorValueObject.create("#N/A"));
@@ -42134,15 +42333,15 @@ var Textbefore = class extends BaseFunction {
42134
42333
  }
42135
42334
  calculate(text, delimiter, instanceNum, matchMode, matchEnd, ifNotFound) {
42136
42335
  let instanceNumIsNull = false;
42137
- let _instanceNum = instanceNum !== null && instanceNum !== void 0 ? instanceNum : NumberValueObject.create(1);
42336
+ let _instanceNum = instanceNum ?? NumberValueObject.create(1);
42138
42337
  if (_instanceNum.isNull()) {
42139
42338
  instanceNumIsNull = true;
42140
42339
  _instanceNum = NumberValueObject.create(1);
42141
42340
  }
42142
42341
  const onlyThreeVariant = !matchMode;
42143
- const _matchMode = matchMode !== null && matchMode !== void 0 ? matchMode : NumberValueObject.create(0);
42144
- const _matchEnd = matchEnd !== null && matchEnd !== void 0 ? matchEnd : NumberValueObject.create(0);
42145
- const _ifNotFound = ifNotFound !== null && ifNotFound !== void 0 ? ifNotFound : ErrorValueObject.create("#N/A");
42342
+ const _matchMode = matchMode ?? NumberValueObject.create(0);
42343
+ const _matchEnd = matchEnd ?? NumberValueObject.create(0);
42344
+ const _ifNotFound = ifNotFound ?? ErrorValueObject.create("#N/A");
42146
42345
  const maxRowLength = Math.max(text.isArray() ? text.getRowCount() : 1, _instanceNum.isArray() ? _instanceNum.getRowCount() : 1, _matchMode.isArray() ? _matchMode.getRowCount() : 1, _matchEnd.isArray() ? _matchEnd.getRowCount() : 1, _ifNotFound.isArray() ? _ifNotFound.getRowCount() : 1);
42147
42346
  const maxColumnLength = Math.max(text.isArray() ? text.getColumnCount() : 1, _instanceNum.isArray() ? _instanceNum.getColumnCount() : 1, _matchMode.isArray() ? _matchMode.getColumnCount() : 1, _matchEnd.isArray() ? _matchEnd.getColumnCount() : 1, _ifNotFound.isArray() ? _ifNotFound.getColumnCount() : 1);
42148
42347
  const textArray = expandArrayValueObject(maxRowLength, maxColumnLength, text, ErrorValueObject.create("#N/A"));
@@ -42273,6 +42472,7 @@ var Textjoin = class extends BaseFunction {
42273
42472
  super(..._args);
42274
42473
  _defineProperty(this, "minParams", 3);
42275
42474
  _defineProperty(this, "maxParams", 255);
42475
+ _defineProperty(this, "lazyIfReferenceArrayArgumentIndexes", Array.from({ length: this.maxParams - 2 }, (_, index) => index + 2));
42276
42476
  }
42277
42477
  calculate(delimiter, ignoreEmpty, ...variants) {
42278
42478
  const delimiterValues = this._getDelimiterValues(delimiter);
@@ -42350,10 +42550,10 @@ var Textsplit = class extends BaseFunction {
42350
42550
  _defineProperty(this, "maxParams", 6);
42351
42551
  }
42352
42552
  calculate(text, colDelimiter, rowDelimiter, ignoreEmpty, matchMode, padWith) {
42353
- let _rowDelimiter = rowDelimiter !== null && rowDelimiter !== void 0 ? rowDelimiter : StringValueObject.create("\\s");
42354
- const _ignoreEmpty = ignoreEmpty !== null && ignoreEmpty !== void 0 ? ignoreEmpty : NumberValueObject.create(0);
42355
- const _matchMode = matchMode !== null && matchMode !== void 0 ? matchMode : NumberValueObject.create(0);
42356
- const _padWith = padWith !== null && padWith !== void 0 ? padWith : StringValueObject.create("#N/A");
42553
+ let _rowDelimiter = rowDelimiter ?? StringValueObject.create("\\s");
42554
+ const _ignoreEmpty = ignoreEmpty ?? NumberValueObject.create(0);
42555
+ const _matchMode = matchMode ?? NumberValueObject.create(0);
42556
+ const _padWith = padWith ?? StringValueObject.create("#N/A");
42357
42557
  const { _variant, values: rowDelimiterValue } = this._getStringValues(_rowDelimiter, false);
42358
42558
  _rowDelimiter = _variant;
42359
42559
  const allowBlankColDelimiter = rowDelimiter != null && !rowDelimiter.isNull() && !_rowDelimiter.isError() && rowDelimiterValue.length > 0;
@@ -42629,7 +42829,7 @@ var Valuetotext = class extends BaseFunction {
42629
42829
  _defineProperty(this, "maxParams", 2);
42630
42830
  }
42631
42831
  calculate(value, format) {
42632
- const _format = format !== null && format !== void 0 ? format : NumberValueObject.create(0);
42832
+ const _format = format ?? NumberValueObject.create(0);
42633
42833
  const maxRowLength = Math.max(value.isArray() ? value.getRowCount() : 1, _format.isArray() ? _format.getRowCount() : 1);
42634
42834
  const maxColumnLength = Math.max(value.isArray() ? value.getColumnCount() : 1, _format.isArray() ? _format.getColumnCount() : 1);
42635
42835
  const valueArray = expandArrayValueObject(maxRowLength, maxColumnLength, value, ErrorValueObject.create("#N/A"));
@@ -42907,7 +43107,7 @@ function getObjectValue(result, isUseStrip = false) {
42907
43107
  //#endregion
42908
43108
  //#region package.json
42909
43109
  var name = "@univerjs/engine-formula";
42910
- var version = "1.0.0-alpha.8";
43110
+ var version = "1.0.0-beta.1";
42911
43111
 
42912
43112
  //#endregion
42913
43113
  //#region src/services/global-computing-status.service.ts
@@ -43099,14 +43299,13 @@ function createEmptyDirtyData() {
43099
43299
  };
43100
43300
  }
43101
43301
  function mergeDirtyData(left, right) {
43102
- var _right$dirtyRanges, _left$dirtySuperTable;
43103
43302
  const dirtyRanges = [...left.dirtyRanges];
43104
- mergeDirtyRanges(dirtyRanges, (_right$dirtyRanges = right.dirtyRanges) !== null && _right$dirtyRanges !== void 0 ? _right$dirtyRanges : []);
43303
+ mergeDirtyRanges(dirtyRanges, right.dirtyRanges ?? []);
43105
43304
  return {
43106
43305
  dirtyRanges,
43107
43306
  dirtyNameMap: mergeDirtyUnitStringMap(left.dirtyNameMap, right.dirtyNameMap),
43108
43307
  dirtyDefinedNameMap: mergeDirtyUnitStringMap(left.dirtyDefinedNameMap, right.dirtyDefinedNameMap),
43109
- dirtySuperTableMap: mergeDirtyUnitStringMap((_left$dirtySuperTable = left.dirtySuperTableMap) !== null && _left$dirtySuperTable !== void 0 ? _left$dirtySuperTable : {}, right.dirtySuperTableMap),
43308
+ dirtySuperTableMap: mergeDirtyUnitStringMap(left.dirtySuperTableMap ?? {}, right.dirtySuperTableMap),
43110
43309
  dirtyUnitFeatureMap: mergeDirtyUnitNestedMap(left.dirtyUnitFeatureMap, right.dirtyUnitFeatureMap),
43111
43310
  dirtyUnitOtherFormulaMap: mergeDirtyUnitNestedMap(left.dirtyUnitOtherFormulaMap, right.dirtyUnitOtherFormulaMap),
43112
43311
  clearDependencyTreeCache: mergeDirtyUnitStringMap(left.clearDependencyTreeCache, right.clearDependencyTreeCache),
@@ -43136,7 +43335,7 @@ function getDirtyRangeKey({ unitId, sheetId, range }) {
43136
43335
  }
43137
43336
  function mergeDirtyUnitStringMap(left, right) {
43138
43337
  const result = { ...left };
43139
- Object.entries(right !== null && right !== void 0 ? right : {}).forEach(([unitId, values]) => {
43338
+ Object.entries(right ?? {}).forEach(([unitId, values]) => {
43140
43339
  result[unitId] = {
43141
43340
  ...result[unitId],
43142
43341
  ...values
@@ -43146,9 +43345,9 @@ function mergeDirtyUnitStringMap(left, right) {
43146
43345
  }
43147
43346
  function mergeDirtyUnitNestedMap(left, right) {
43148
43347
  const result = { ...left };
43149
- Object.entries(right !== null && right !== void 0 ? right : {}).forEach(([unitId, sheets]) => {
43348
+ Object.entries(right ?? {}).forEach(([unitId, sheets]) => {
43150
43349
  const unitResult = { ...result[unitId] };
43151
- Object.entries(sheets !== null && sheets !== void 0 ? sheets : {}).forEach(([sheetId, values]) => {
43350
+ Object.entries(sheets ?? {}).forEach(([sheetId, values]) => {
43152
43351
  unitResult[sheetId] = {
43153
43352
  ...unitResult[sheetId],
43154
43353
  ...values
@@ -43179,7 +43378,7 @@ function dirtyDataIntersects(left, right) {
43179
43378
  ].some(([leftMap, rightMap]) => hasSameNestedKey(leftMap, rightMap));
43180
43379
  }
43181
43380
  function clearedSheetIntersects(cleared, dirty) {
43182
- return Object.entries(cleared.clearDependencyTreeCache).some(([unitId, sheets]) => Object.keys(sheets !== null && sheets !== void 0 ? sheets : {}).some((sheetId) => {
43381
+ return Object.entries(cleared.clearDependencyTreeCache).some(([unitId, sheets]) => Object.keys(sheets ?? {}).some((sheetId) => {
43183
43382
  var _dirty$dirtyNameMap$u, _dirty$dirtyUnitFeatu, _dirty$dirtyUnitOther;
43184
43383
  return dirty.dirtyRanges.some((range) => range.unitId === unitId && range.sheetId === sheetId) || ((_dirty$dirtyNameMap$u = dirty.dirtyNameMap[unitId]) === null || _dirty$dirtyNameMap$u === void 0 ? void 0 : _dirty$dirtyNameMap$u[sheetId]) != null || ((_dirty$dirtyUnitFeatu = dirty.dirtyUnitFeatureMap[unitId]) === null || _dirty$dirtyUnitFeatu === void 0 ? void 0 : _dirty$dirtyUnitFeatu[sheetId]) != null || ((_dirty$dirtyUnitOther = dirty.dirtyUnitOtherFormulaMap[unitId]) === null || _dirty$dirtyUnitOther === void 0 ? void 0 : _dirty$dirtyUnitOther[sheetId]) != null;
43185
43384
  }));
@@ -43208,12 +43407,9 @@ function hasSameNestedKey(left, right) {
43208
43407
  * limitations under the License.
43209
43408
  */
43210
43409
  let FormulaCalculationTriggerController = class FormulaCalculationTriggerController extends _univerjs_core.Disposable {
43211
- constructor(formulaCalculationTriggerService, registerOtherFormulaService, lifecycleService) {
43410
+ constructor(formulaCalculationTriggerService, lifecycleService) {
43212
43411
  super();
43213
- const start = () => {
43214
- formulaCalculationTriggerService.start();
43215
- registerOtherFormulaService.calculateStarted$.next(true);
43216
- };
43412
+ const start = () => formulaCalculationTriggerService.start();
43217
43413
  if ((0, _univerjs_core.isNodeEnv)()) {
43218
43414
  start();
43219
43415
  return;
@@ -43221,11 +43417,7 @@ let FormulaCalculationTriggerController = class FormulaCalculationTriggerControl
43221
43417
  this.disposeWithMe(lifecycleService.lifecycle$.pipe((0, rxjs.filter)((stage) => stage >= _univerjs_core.LifecycleStages.Rendered), (0, rxjs.take)(1)).subscribe(start));
43222
43418
  }
43223
43419
  };
43224
- FormulaCalculationTriggerController = __decorate([
43225
- __decorateParam(0, (0, _univerjs_core.Inject)(FormulaCalculationTriggerService)),
43226
- __decorateParam(1, (0, _univerjs_core.Inject)(RegisterOtherFormulaService)),
43227
- __decorateParam(2, (0, _univerjs_core.Inject)(_univerjs_core.LifecycleService))
43228
- ], FormulaCalculationTriggerController);
43420
+ FormulaCalculationTriggerController = __decorate([__decorateParam(0, (0, _univerjs_core.Inject)(FormulaCalculationTriggerService)), __decorateParam(1, (0, _univerjs_core.Inject)(_univerjs_core.LifecycleService))], FormulaCalculationTriggerController);
43229
43421
 
43230
43422
  //#endregion
43231
43423
  //#region src/controllers/formula.controller.ts
@@ -43248,10 +43440,12 @@ let FormulaController = class FormulaController extends _univerjs_core.Disposabl
43248
43440
  _syncOtherFormulaUnits() {
43249
43441
  const dataSyncPrimaryController = this._dataSyncPrimaryController;
43250
43442
  if (!dataSyncPrimaryController) return;
43251
- this.disposeWithMe(this._registerOtherFormulaService.formulaChangeWithRange$.subscribe(({ unitId }) => {
43252
- if (this._syncedOtherFormulaUnits.has(unitId)) return;
43253
- this._syncedOtherFormulaUnits.add(unitId);
43254
- this.disposeWithMe(dataSyncPrimaryController.syncUnitMutations(unitId));
43443
+ this.disposeWithMe(this._registerOtherFormulaService.setMutationSyncHandler((unitId) => {
43444
+ if (!this._syncedOtherFormulaUnits.has(unitId)) {
43445
+ this._syncedOtherFormulaUnits.add(unitId);
43446
+ this.disposeWithMe(dataSyncPrimaryController.syncUnitMutations(unitId));
43447
+ }
43448
+ return () => dataSyncPrimaryController.waitForPendingMutations();
43255
43449
  }));
43256
43450
  }
43257
43451
  _registerCommands() {
@@ -43292,9 +43486,8 @@ let FormulaController = class FormulaController extends _univerjs_core.Disposabl
43292
43486
  });
43293
43487
  }
43294
43488
  _registerFunctions() {
43295
- var _config$function;
43296
43489
  const config = this._configService.getConfig(ENGINE_FORMULA_PLUGIN_CONFIG_KEY);
43297
- const functions = ALL_IMPLEMENTED_FUNCTIONS.concat((_config$function = config === null || config === void 0 ? void 0 : config.function) !== null && _config$function !== void 0 ? _config$function : []).map((registerObject) => {
43490
+ const functions = ALL_IMPLEMENTED_FUNCTIONS.concat((config === null || config === void 0 ? void 0 : config.function) ?? []).map((registerObject) => {
43298
43491
  const Func = registerObject[0];
43299
43492
  const name = registerObject[1];
43300
43493
  return new Func(name);
@@ -56493,7 +56686,7 @@ let RegisterFunctionService = class RegisterFunctionService extends _univerjs_co
56493
56686
  const { locales, description, calculate } = params;
56494
56687
  if (locales) this._localeService.load(locales);
56495
56688
  const disposables = new _univerjs_core.DisposableCollection();
56496
- const descriptions = description !== null && description !== void 0 ? description : calculate.map(([_func, functionName, functionIntroduction]) => {
56689
+ const descriptions = description ?? calculate.map(([_func, functionName, functionIntroduction]) => {
56497
56690
  return {
56498
56691
  functionName,
56499
56692
  functionType: 15,