@univerjs-pro/engine-formula-rust 1.0.0-insiders.20260809-70eefdd → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/cjs/index.cjs CHANGED
@@ -246,7 +246,7 @@ var import_core2 = require("@univerjs/core");
246
246
 
247
247
  // src/services/rust-formula-projection.service.ts
248
248
  var import_core = require("@univerjs/core");
249
- var XLSX_WORKBOOK_CALCULATION_RESOURCE = "UNIVER_CLI_XLSX_WORKBOOK_CALCULATION_PLUGIN", EXTERNAL_DATA_RESOURCE = "SHEET_EXTERNAL_DATA_PLUGIN", EXTERNAL_DATA_SIGNATURE = "external_data", RUST_UPSERT_REFERENCE_DATA_MUTATION_ID = "formula.mutation.upsert-reference-data", RUST_UPSERT_PROJECTION_WORKBOOK_MUTATION_ID = "formula.mutation.upsert-projection-workbook", RUST_FORMULA_RELEVANT_MUTATIONS = /* @__PURE__ */ new Set([
249
+ var XLSX_WORKBOOK_CALCULATION_RESOURCE = "UNIVER_CLI_XLSX_WORKBOOK_CALCULATION_PLUGIN", EXTERNAL_DATA_RESOURCE = "SHEET_EXTERNAL_DATA_PLUGIN", EXTERNAL_DATA_SIGNATURE = "external_data", RUST_UPSERT_REFERENCE_DATA_MUTATION_ID = "formula.mutation.upsert-reference-data", RUST_UPSERT_PROJECTION_WORKBOOK_MUTATION_ID = "formula.mutation.upsert-projection-workbook", RUST_SET_SUPER_TABLES_MUTATION_ID = "formula.mutation.set-super-tables", RUST_FORMULA_RELEVANT_MUTATIONS = /* @__PURE__ */ new Set([
250
250
  "sheet.mutation.set-range-values",
251
251
  "sheet.mutation.insert-row",
252
252
  "sheet.mutation.insert-col",
@@ -262,6 +262,11 @@ var XLSX_WORKBOOK_CALCULATION_RESOURCE = "UNIVER_CLI_XLSX_WORKBOOK_CALCULATION_P
262
262
  "sheet.mutation.set-col-visible",
263
263
  "sheet.mutation.set-row-hidden",
264
264
  "sheet.mutation.set-row-visible",
265
+ "sheet.mutation.set-table-filter",
266
+ "sheet.mutation.set-filter-range",
267
+ "sheet.mutation.set-filter-criteria",
268
+ "sheet.mutation.remove-filter",
269
+ "sheet.mutation.re-calc-filter",
265
270
  "sheet.mutation.set-worksheet-name",
266
271
  "sheet.mutation.reorder-range",
267
272
  "sheet.mutation.set-worksheet-row-count",
@@ -273,6 +278,7 @@ var XLSX_WORKBOOK_CALCULATION_RESOURCE = "UNIVER_CLI_XLSX_WORKBOOK_CALCULATION_P
273
278
  "formula.mutation.set-image-formula-data",
274
279
  "formula.mutation.set-other-formula",
275
280
  "formula.mutation.set-super-table",
281
+ RUST_SET_SUPER_TABLES_MUTATION_ID,
276
282
  "formula.mutation.set-super-table-option",
277
283
  "formula.mutation.remove-defined-name",
278
284
  "formula.mutation.remove-feature-calculation",
@@ -334,11 +340,18 @@ function serializeRuntimeWorkbookSnapshots(workbooks) {
334
340
  }
335
341
  function serializeRuntimeWorkbookSnapshot(input) {
336
342
  let { snapshot } = input, sheetOrder = snapshot.sheetOrder?.length > 0 ? snapshot.sheetOrder : Object.keys(snapshot.sheets ?? {}), calculation = serializeCalculation(snapshot), precisionAsDisplayed = calculation?.fullPrecision === !1, sheets = sheetOrder.map(
337
- (sheetId) => serializeSheetSnapshot(sheetId, snapshot.sheets?.[sheetId], snapshot.styles, precisionAsDisplayed)
343
+ (sheetId) => serializeSheetSnapshot(
344
+ sheetId,
345
+ snapshot.sheets?.[sheetId],
346
+ snapshot.styles,
347
+ precisionAsDisplayed,
348
+ input.styleResolver
349
+ )
338
350
  ).filter((sheet) => sheet != null);
339
351
  return {
340
352
  unitId: input.unitId || snapshot.id,
341
353
  name: snapshot.name,
354
+ dateSystem: snapshot.dateSystem,
342
355
  sheets,
343
356
  ...calculation ? { calculation } : {},
344
357
  resources: serializeResources(snapshot),
@@ -406,13 +419,16 @@ function otherFormulaDataToUnitOtherData(otherFormulaData) {
406
419
  if (!colMap) return;
407
420
  let row = Number(rowKey), rowData = {};
408
421
  formulaData[row] = rowData, Object.entries(colMap).forEach(([colKey, value]) => {
409
- rowData[Number(colKey)] = [[cellDataFromRustValue(value)]];
422
+ rowData[Number(colKey)] = otherFormulaResultFromRustValue(value);
410
423
  });
411
424
  });
412
425
  });
413
426
  });
414
427
  }), unitOtherData;
415
428
  }
429
+ function otherFormulaResultFromRustValue(value) {
430
+ return Array.isArray(value) ? value.map((row) => (Array.isArray(row) ? row : [row]).map((cell) => cellDataFromRustValue(cell))) : [[cellDataFromRustValue(value)]];
431
+ }
416
432
  function createFormulaProjectionDesyncSignal(reason, error, mutationId) {
417
433
  return {
418
434
  reason,
@@ -508,13 +524,26 @@ var RustFormulaProjectionService = class {
508
524
  }
509
525
  };
510
526
  function normalizeRustEngineMutation(mutation) {
511
- let params = mutation.id === "formula.mutation.set-super-table" ? normalizeSetSuperTableMutationParams(mutation.params) : mutation.params ?? {};
527
+ let params = mutation.id === "formula.mutation.set-super-table" ? normalizeSetSuperTableMutationParams(mutation.params) : mutation.id === RUST_SET_SUPER_TABLES_MUTATION_ID ? normalizeSetSuperTablesMutationParams(mutation.params) : mutation.params ?? {};
512
528
  return {
513
529
  id: mutation.id,
514
530
  params,
515
531
  dirtyRanges: Array.isArray(mutation.dirtyRanges) ? mutation.dirtyRanges : []
516
532
  };
517
533
  }
534
+ function normalizeSetSuperTablesMutationParams(params) {
535
+ return !isRecord(params) || typeof params.unitId != "string" || !Array.isArray(params.tables) ? params ?? {} : {
536
+ ...params,
537
+ tables: params.tables.map((entry) => {
538
+ let normalized = normalizeSetSuperTableMutationParams(
539
+ isRecord(entry) ? { ...entry, unitId: params.unitId } : entry
540
+ );
541
+ if (!isRecord(normalized)) return normalized;
542
+ let { unitId: _unitId, ...table } = normalized;
543
+ return table;
544
+ })
545
+ };
546
+ }
518
547
  function normalizeSetSuperTableMutationParams(params) {
519
548
  if (!isRecord(params) || !isRecord(params.reference))
520
549
  return params ?? {};
@@ -933,19 +962,19 @@ function extractDefinedNames(snapshot) {
933
962
  }
934
963
  return {};
935
964
  }
936
- function serializeSheetSnapshot(sheetId, sheet, styles, precisionAsDisplayed) {
965
+ function serializeSheetSnapshot(sheetId, sheet, styles, precisionAsDisplayed, styleResolver) {
937
966
  return sheet ? {
938
967
  sheetId: sheet.id ?? sheetId,
939
968
  name: sheet.name,
940
969
  rowCount: sheet.rowCount ?? 0,
941
970
  columnCount: sheet.columnCount ?? 0,
942
971
  transitionEvaluation: sheet.transitionEvaluation === !0,
943
- cellData: serializeCellData(sheet.cellData, styles, precisionAsDisplayed),
972
+ cellData: serializeCellData(sheet.cellData, styles, precisionAsDisplayed, styleResolver),
944
973
  rowData: serializeVisibilityData(sheet.rowData),
945
974
  columnData: serializeVisibilityData(sheet.columnData)
946
975
  } : null;
947
976
  }
948
- function serializeCellData(cellData = {}, styles, precisionAsDisplayed = !1) {
977
+ function serializeCellData(cellData = {}, styles, precisionAsDisplayed = !1, styleResolver) {
949
978
  let result = {}, rawCellData = cellData instanceof import_core.ObjectMatrix ? cellData.getMatrix() : cellData;
950
979
  for (let [rowKey, row] of Object.entries(rawCellData ?? {})) {
951
980
  if (!row)
@@ -954,13 +983,15 @@ function serializeCellData(cellData = {}, styles, precisionAsDisplayed = !1) {
954
983
  for (let [colKey, cell] of Object.entries(row)) {
955
984
  if (!cell || typeof cell != "object")
956
985
  continue;
957
- let cellRecord = cell, value = {};
958
- if ("v" in cellRecord && (value.v = cellRecord.v), typeof cellRecord.t == "number" && (value.t = cellRecord.t), "p" in cellRecord && (value.p = cellRecord.p), typeof cellRecord.f == "string" && (value.f = cellRecord.f), typeof cellRecord.si == "string" && (value.si = cellRecord.si), typeof cellRecord.ref == "string") {
986
+ let cellRecord = cell, resolvedStyle = styleResolver?.getStyleByCell(cell), value = {};
987
+ if ("v" in cellRecord && (value.v = cellRecord.v), typeof cellRecord.t == "number" && (value.t = cellRecord.t), "p" in cellRecord && (value.p = cellRecord.p), typeof cellRecord.f == "string" && (value.f = cellRecord.f), typeof cellRecord.ft == "number" && (value.ft = cellRecord.ft), (cellRecord.fd === import_core.BooleanNumber.FALSE || cellRecord.fd === import_core.BooleanNumber.TRUE) && (value.fd = cellRecord.fd), typeof cellRecord.si == "string" && (value.si = cellRecord.si), typeof cellRecord.ref == "string") {
959
988
  let hasFormula = typeof cellRecord.f == "string" && cellRecord.f.length > 0;
960
989
  typeof cellRecord.si == "string" || hasFormula && isLegacyArrayFormulaCell(cellRecord) ? value.ref = cellRecord.ref : hasFormula && (value.dynamicArrayRef = cellRecord.ref);
961
990
  }
962
- if (typeof cellRecord.xf == "string" && (value.xf = cellRecord.xf), "s" in cellRecord && (value.s = cellRecord.s), precisionAsDisplayed && typeof cellRecord.f == "string") {
963
- let displayPrecision = inferDisplayPrecision(cellRecord.s, styles);
991
+ typeof cellRecord.xf == "string" && (value.xf = cellRecord.xf), "s" in cellRecord && (value.s = cellRecord.s);
992
+ let numberFormat = resolveNumberFormatPattern(cellRecord.s, styles, resolvedStyle);
993
+ if (numberFormat !== void 0 && (value.numberFormat = numberFormat), precisionAsDisplayed && typeof cellRecord.f == "string") {
994
+ let displayPrecision = inferDisplayPrecision(cellRecord.s, styles, resolvedStyle);
964
995
  displayPrecision !== void 0 && (value.displayPrecision = displayPrecision);
965
996
  }
966
997
  Object.keys(value).length > 0 && (serializedRow[Number(colKey)] = value);
@@ -983,23 +1014,19 @@ function serializeCellDataInRanges(cellData, ranges) {
983
1014
  return result;
984
1015
  }
985
1016
  function isLegacyArrayFormulaCell(cell) {
986
- let custom = cell.custom;
987
- if (!custom || typeof custom != "object")
988
- return !1;
989
- let xlsx = custom._xlsx;
990
- return xlsx != null && typeof xlsx == "object" && xlsx.legacyArrayFormula === !0;
1017
+ return cell.ft === import_core.FormulaType.ARRAY && cell.fd !== import_core.BooleanNumber.TRUE;
991
1018
  }
992
- function inferDisplayPrecision(styleId, styles) {
993
- if (typeof styleId != "string" || !styles || typeof styles != "object")
994
- return;
995
- let style = styles[styleId];
996
- if (!style || typeof style != "object")
997
- return;
1019
+ function inferDisplayPrecision(styleId, styles, resolvedStyle) {
1020
+ let pattern = resolveNumberFormatPattern(styleId, styles, resolvedStyle);
1021
+ return pattern === void 0 ? void 0 : inferFixedNumberFormatPrecision(pattern);
1022
+ }
1023
+ function resolveNumberFormatPattern(styleRef, styles, resolvedStyle) {
1024
+ let style = resolvedStyle ?? (typeof styleRef == "string" && styles && typeof styles == "object" ? styles[styleRef] : styleRef);
1025
+ if (!style || typeof style != "object") return;
998
1026
  let numberFormat = style.n;
999
- if (!numberFormat || typeof numberFormat != "object")
1000
- return;
1027
+ if (!numberFormat || typeof numberFormat != "object") return;
1001
1028
  let pattern = numberFormat.pattern;
1002
- return typeof pattern == "string" ? inferFixedNumberFormatPrecision(pattern) : void 0;
1029
+ return typeof pattern == "string" ? pattern : void 0;
1003
1030
  }
1004
1031
  function inferFixedNumberFormatPrecision(pattern) {
1005
1032
  let cleaned = (pattern.split(";")[0] ?? pattern).replace(/"[^"]*"/gu, "").replace(/\\./gu, "").replace(/_.|\*./gu, "");
@@ -1082,6 +1109,7 @@ var RustEngineSyncController = class extends import_core2.Disposable {
1082
1109
  _nativeReady = !1;
1083
1110
  _snapshotLoaded = !1;
1084
1111
  _projectionLoadPromise = null;
1112
+ _projectionDeltaBarrier = Promise.resolve();
1085
1113
  _pendingMutations = [];
1086
1114
  _projectionManagedTableUnits = /* @__PURE__ */ new Set();
1087
1115
  _initialize() {
@@ -1102,6 +1130,13 @@ var RustEngineSyncController = class extends import_core2.Disposable {
1102
1130
  }
1103
1131
  async waitForProjectionLoad() {
1104
1132
  await this._projectionLoadPromise;
1133
+ let barrier;
1134
+ do
1135
+ barrier = this._projectionDeltaBarrier, await barrier;
1136
+ while (barrier !== this._projectionDeltaBarrier);
1137
+ }
1138
+ setProjectionDeltaBarrier(barrier) {
1139
+ this._projectionDeltaBarrier = barrier;
1105
1140
  }
1106
1141
  async _loadProjection(workbooks) {
1107
1142
  await loadNativeBinding(), this._nativeReady = !0;
@@ -1133,7 +1168,7 @@ var RustEngineSyncController = class extends import_core2.Disposable {
1133
1168
  }
1134
1169
  }
1135
1170
  dispose() {
1136
- if (super.dispose(), this._pendingMutations.length = 0, this._projectionManagedTableUnits.clear(), this._projectionLoadPromise = null, !this._nativeReady) {
1171
+ if (super.dispose(), this._pendingMutations.length = 0, this._projectionManagedTableUnits.clear(), this._projectionLoadPromise = null, this._projectionDeltaBarrier = Promise.resolve(), !this._nativeReady) {
1137
1172
  this._snapshotLoaded = !1;
1138
1173
  return;
1139
1174
  }
@@ -1267,7 +1302,7 @@ async function analyzeNumberFormatBatch(input) {
1267
1302
  var import_core5 = require("@univerjs/core"), import_engine_formula4 = require("@univerjs/engine-formula"), import_engine_formula5 = require("@univerjs-pro/engine-formula");
1268
1303
 
1269
1304
  // package.json
1270
- var name = "@univerjs-pro/engine-formula-rust", version = "1.0.0-insiders.20260809-70eefdd";
1305
+ var name = "@univerjs-pro/engine-formula-rust", version = "1.0.0";
1271
1306
 
1272
1307
  // src/controllers/rust-same-runtime-projection.controller.ts
1273
1308
  var import_core3 = require("@univerjs/core"), import_engine_formula = require("@univerjs/engine-formula");
@@ -1290,18 +1325,20 @@ var RustSameRuntimeProjectionController = class extends import_core3.Disposable
1290
1325
  _activeDirtyManagerService;
1291
1326
  _initialProjectionLoad = Promise.resolve();
1292
1327
  _projectionDeltaQueue = Promise.resolve();
1328
+ _baseProjectionStructures = /* @__PURE__ */ new Map();
1293
1329
  _initialize() {
1294
1330
  for (let base of this._univerInstanceService.getAllUnitsForType(
1295
1331
  import_core3.UniverInstanceType.UNIVER_BASE
1296
1332
  ))
1297
- this._rustEngineSyncController.setProjectionManagedTableUnit(base.getUnitId());
1333
+ this._rustEngineSyncController.setProjectionManagedTableUnit(base.getUnitId()), this._rememberBaseProjectionStructure(base.getSnapshot());
1298
1334
  this._initialProjectionLoad = this._loadAllWorkbookProjections(), this.disposeWithMe(
1299
1335
  (0, import_core3.toDisposable)(
1300
1336
  this._univerInstanceService.getTypeOfUnitAdded$(import_core3.UniverInstanceType.UNIVER_SHEET).subscribe(({ unit }) => {
1301
1337
  this._enqueueProjectionDelta(() => {
1302
1338
  this._rustEngineSyncController.upsertProjectionWorkbook({
1303
1339
  unitId: unit.getUnitId(),
1304
- snapshot: unit.getSnapshot()
1340
+ snapshot: unit.getSnapshot(),
1341
+ styleResolver: unit.getStyles()
1305
1342
  });
1306
1343
  });
1307
1344
  })
@@ -1309,7 +1346,7 @@ var RustSameRuntimeProjectionController = class extends import_core3.Disposable
1309
1346
  ), this.disposeWithMe(
1310
1347
  (0, import_core3.toDisposable)(
1311
1348
  this._univerInstanceService.getTypeOfUnitAdded$(import_core3.UniverInstanceType.UNIVER_BASE).subscribe(({ unit }) => {
1312
- this._rustEngineSyncController.setProjectionManagedTableUnit(unit.getUnitId()), this._enqueueProjectionDelta(() => this._upsertBaseProjection(unit.getUnitId()));
1349
+ this._rustEngineSyncController.setProjectionManagedTableUnit(unit.getUnitId()), this._rememberBaseProjectionStructure(unit.getSnapshot()), this._enqueueProjectionDelta(() => this._upsertBaseProjection(unit.getUnitId()));
1313
1350
  })
1314
1351
  )
1315
1352
  ), this.disposeWithMe(
@@ -1319,7 +1356,7 @@ var RustSameRuntimeProjectionController = class extends import_core3.Disposable
1319
1356
  ), this.disposeWithMe(
1320
1357
  (0, import_core3.toDisposable)(
1321
1358
  this._univerInstanceService.getTypeOfUnitDisposed$(import_core3.UniverInstanceType.UNIVER_BASE).subscribe((base) => {
1322
- this._rustEngineSyncController.unsetProjectionManagedTableUnit(base.getUnitId()), this._enqueueProjectionDelta(
1359
+ this._baseProjectionStructures.delete(base.getUnitId()), this._rustEngineSyncController.unsetProjectionManagedTableUnit(base.getUnitId()), this._enqueueProjectionDelta(
1323
1360
  () => this._rustEngineSyncController.disposeProjectionWorkbook(base.getUnitId())
1324
1361
  );
1325
1362
  })
@@ -1343,7 +1380,7 @@ var RustSameRuntimeProjectionController = class extends import_core3.Disposable
1343
1380
  if (!this._disposed)
1344
1381
  return task();
1345
1382
  }).catch(() => {
1346
- });
1383
+ }), this._rustEngineSyncController.setProjectionDeltaBarrier(this._projectionDeltaQueue);
1347
1384
  }
1348
1385
  async _syncBaseMutation(command) {
1349
1386
  if (!hasUnitId2(command.params)) return;
@@ -1352,7 +1389,65 @@ var RustSameRuntimeProjectionController = class extends import_core3.Disposable
1352
1389
  this._applyBaseDirtyRanges(unitId, dirtyRanges);
1353
1390
  return;
1354
1391
  }
1355
- await this._upsertBaseProjection(unitId);
1392
+ hasStructureInvalidation && this._isBaseProjectionStructureUnchanged(unitId) || hasStructureInvalidation && this._applyBaseFieldInsertion(unitId, dirtyRanges) || await this._upsertBaseProjection(unitId);
1393
+ }
1394
+ _applyBaseFieldInsertion(unitId, dirtyRanges) {
1395
+ let base = this._univerInstanceService.getUnit(unitId, import_core3.UniverInstanceType.UNIVER_BASE), previous = this._baseProjectionStructures.get(unitId);
1396
+ if (!base || !previous) return !1;
1397
+ let snapshot = base.getSnapshot(), insertion = findSingleBaseFieldInsertion(previous, snapshot);
1398
+ if (!insertion) return !1;
1399
+ let projectionData = this._getBaseProjectionData(unitId), sheet = projectionData?.calculationData.allUnitData[unitId]?.[insertion.tableId];
1400
+ if (!projectionData || !sheet) return !1;
1401
+ let formulaData = projectionData.formulaData[unitId]?.[insertion.tableId], cellValue = {};
1402
+ for (let row = 0; row < sheet.rowCount; row++) {
1403
+ let value = sheet.cellData.getValue(row, insertion.column), formula = formulaData?.[row]?.[insertion.column];
1404
+ cellValue[row] = {
1405
+ [insertion.column]: formula ? { ...value, ...formula } : value ?? null
1406
+ };
1407
+ }
1408
+ let insertedRange = {
1409
+ startRow: 0,
1410
+ endRow: Math.max(0, sheet.rowCount - 1),
1411
+ startColumn: insertion.column,
1412
+ endColumn: insertion.column
1413
+ };
1414
+ return this._rustEngineSyncController.applyProjectionMutation({
1415
+ id: "sheet.mutation.insert-col",
1416
+ params: {
1417
+ unitId,
1418
+ subUnitId: insertion.tableId,
1419
+ range: insertedRange
1420
+ },
1421
+ dirtyRanges: []
1422
+ }), this._rustEngineSyncController.applyProjectionMutation({
1423
+ id: "sheet.mutation.set-range-values",
1424
+ params: {
1425
+ unitId,
1426
+ subUnitId: insertion.tableId,
1427
+ cellValue
1428
+ },
1429
+ dirtyRanges: [
1430
+ {
1431
+ unitId,
1432
+ sheetId: insertion.tableId,
1433
+ range: insertedRange
1434
+ }
1435
+ ]
1436
+ }), this._rustEngineSyncController.applyProjectionMutation({
1437
+ id: RUST_SET_SUPER_TABLES_MUTATION_ID,
1438
+ params: {
1439
+ unitId,
1440
+ tables: this._getBaseTableEntries(
1441
+ insertion.tableId,
1442
+ snapshot,
1443
+ (0, import_core3.createBaseFormulaTableNameMap)(snapshot)
1444
+ ).map(([tableName, reference]) => ({
1445
+ tableName,
1446
+ reference
1447
+ }))
1448
+ },
1449
+ dirtyRanges: []
1450
+ }), dirtyRanges.length > 0 && this._applyBaseDirtyRanges(unitId, dirtyRanges), this._rememberBaseProjectionStructure(snapshot), !0;
1356
1451
  }
1357
1452
  _applyBaseDirtyRanges(unitId, dirtyRanges) {
1358
1453
  let projectionData = this._getBaseProjectionData(unitId);
@@ -1394,6 +1489,15 @@ var RustSameRuntimeProjectionController = class extends import_core3.Disposable
1394
1489
  formulaData
1395
1490
  );
1396
1491
  workbook && this._rustEngineSyncController.upsertProjectionWorkbook(workbook);
1492
+ let base = this._univerInstanceService.getUnit(unitId, import_core3.UniverInstanceType.UNIVER_BASE);
1493
+ base && this._rememberBaseProjectionStructure(base.getSnapshot());
1494
+ }
1495
+ _rememberBaseProjectionStructure(snapshot) {
1496
+ this._baseProjectionStructures.set(snapshot.id, createBaseProjectionStructure(snapshot));
1497
+ }
1498
+ _isBaseProjectionStructureUnchanged(unitId) {
1499
+ let base = this._univerInstanceService.getUnit(unitId, import_core3.UniverInstanceType.UNIVER_BASE), previous = this._baseProjectionStructures.get(unitId);
1500
+ return !!(base && previous && isSameBaseProjectionStructure(previous, createBaseProjectionStructure(base.getSnapshot())));
1397
1501
  }
1398
1502
  _getBaseProjectionData(unitId) {
1399
1503
  let base = this._univerInstanceService.getUnit(unitId, import_core3.UniverInstanceType.UNIVER_BASE);
@@ -1403,9 +1507,9 @@ var RustSameRuntimeProjectionController = class extends import_core3.Disposable
1403
1507
  name: snapshot.name,
1404
1508
  unitType: import_core3.UniverInstanceType.UNIVER_BASE
1405
1509
  }
1406
- }, formulaData = { [unitId]: {} };
1510
+ }, formulaData = { [unitId]: {} }, formulaTableNames = (0, import_core3.createBaseFormulaTableNameMap)(snapshot), normalizeFormulaTableReferences = (0, import_core3.createBaseFormulaTableReferenceNormalizer)(snapshot, formulaTableNames);
1407
1511
  for (let table of Object.values(snapshot.tables)) {
1408
- let fieldOrder = table.fieldOrder.filter((fieldId) => table.fields[fieldId] != null);
1512
+ let fieldOrder = table.fieldOrder;
1409
1513
  allUnitData[unitId][table.id] = {
1410
1514
  cellData: new import_core3.ObjectMatrix(
1411
1515
  buildBaseRuntimeCellData(table)
@@ -1414,18 +1518,25 @@ var RustSameRuntimeProjectionController = class extends import_core3.Disposable
1414
1518
  columnCount: fieldOrder.length,
1415
1519
  rowData: {},
1416
1520
  columnData: {}
1417
- }, unitSheetNameMap[unitId][table.name] = table.id;
1418
- let tableFormulaData = {}, recordOrder = baseRecordOrder(table);
1521
+ }, unitSheetNameMap[unitId][formulaTableNames.get(table.id)] = table.id;
1522
+ let tableFormulaData = {}, normalizedFormulaByFieldId = /* @__PURE__ */ new Map(), recordOrder = baseRecordOrder(table);
1419
1523
  for (let row = 0; row < recordOrder.length; row++)
1420
1524
  if (table.records[recordOrder[row]])
1421
1525
  for (let column = 0; column < fieldOrder.length; column++) {
1422
1526
  let field = table.fields[fieldOrder[column]];
1423
1527
  if (!field || field.type !== "formula") continue;
1424
1528
  let formula = String(field.config?.formula ?? "").trim();
1425
- formula && ((tableFormulaData[row] ??= {})[column] = {
1426
- f: normalizeBaseFormulaForEngine(formula, table, snapshot),
1529
+ if (!formula) continue;
1530
+ let normalizedFormula = normalizedFormulaByFieldId.get(field.id);
1531
+ normalizedFormula == null && (normalizedFormula = normalizeBaseFormulaForEngine(
1532
+ formula,
1533
+ table,
1534
+ formulaTableNames,
1535
+ normalizeFormulaTableReferences
1536
+ ), normalizedFormulaByFieldId.set(field.id, normalizedFormula)), (tableFormulaData[row] ??= {})[column] = {
1537
+ f: normalizedFormula,
1427
1538
  si: field.id
1428
- });
1539
+ };
1429
1540
  }
1430
1541
  formulaData[unitId][table.id] = tableFormulaData;
1431
1542
  }
@@ -1441,7 +1552,8 @@ var RustSameRuntimeProjectionController = class extends import_core3.Disposable
1441
1552
  async _loadAllWorkbookProjections() {
1442
1553
  let workbooks = this._univerInstanceService.getAllUnitsForType(import_core3.UniverInstanceType.UNIVER_SHEET).map((workbook) => ({
1443
1554
  unitId: workbook.getUnitId(),
1444
- snapshot: workbook.getSnapshot()
1555
+ snapshot: workbook.getSnapshot(),
1556
+ styleResolver: workbook.getStyles()
1445
1557
  })), calculationData = this._formulaDataModel.getCalculateData(), formulaData = this._formulaDataModel.getFormulaData(), baseWorkbooks = this._univerInstanceService.getAllUnitsForType(import_core3.UniverInstanceType.UNIVER_BASE).map(
1446
1558
  (base) => this._createBaseWorkbookProjection(
1447
1559
  base.getUnitId(),
@@ -1494,25 +1606,17 @@ var RustSameRuntimeProjectionController = class extends import_core3.Disposable
1494
1606
  _createBaseTableResource(unitId) {
1495
1607
  let base = this._univerInstanceService.getUnit(unitId, import_core3.UniverInstanceType.UNIVER_BASE);
1496
1608
  if (base) {
1497
- let snapshot = base.getSnapshot(), tables = Object.values(snapshot.tables), data2 = {};
1498
- for (let table of tables) {
1499
- let recordCount = baseRecordOrder(table).length, fieldOrder = table.fieldOrder.filter((fieldId) => table.fields[fieldId] != null), tableNames = /* @__PURE__ */ new Set([table.id, getEngineBaseTableName(table, snapshot)]);
1500
- isUniqueBaseTableName(table, snapshot) && tableNames.add(table.name);
1501
- for (let name2 of tableNames)
1609
+ let snapshot = base.getSnapshot(), tables = Object.values(snapshot.tables), formulaTableNames = (0, import_core3.createBaseFormulaTableNameMap)(snapshot), data2 = {};
1610
+ for (let table of tables)
1611
+ for (let [name2, reference] of this._getBaseTableEntries(table.id, snapshot, formulaTableNames)) {
1612
+ let columns = Array.from(reference.titleMap.entries()).toSorted((left, right) => left[1] - right[1]).map(([displayName]) => ({ displayName }));
1502
1613
  (data2[table.id] ??= { tables: [] }).tables.push({
1503
1614
  name: name2,
1504
- range: {
1505
- startRow: 0,
1506
- endRow: Math.max(0, recordCount - 1),
1507
- startColumn: 0,
1508
- endColumn: Math.max(0, fieldOrder.length - 1)
1509
- },
1510
- columns: fieldOrder.map((fieldId) => ({
1511
- displayName: table.fields[fieldId]?.name ?? fieldId
1512
- })),
1513
- options: { showHeader: !1 }
1615
+ range: reference.range,
1616
+ columns,
1617
+ options: { showHeader: reference.showHeader !== !1 }
1514
1618
  });
1515
- }
1619
+ }
1516
1620
  return [
1517
1621
  {
1518
1622
  name: "SHEET_TABLE_PLUGIN",
@@ -1539,6 +1643,22 @@ var RustSameRuntimeProjectionController = class extends import_core3.Disposable
1539
1643
  }
1540
1644
  ];
1541
1645
  }
1646
+ _getBaseTableEntries(tableId, snapshot, formulaTableNames) {
1647
+ let table = snapshot.tables[tableId];
1648
+ if (!table) return [];
1649
+ let recordCount = baseRecordOrder(table).length, fieldOrder = table.fieldOrder, reference = {
1650
+ sheetId: table.id,
1651
+ range: {
1652
+ startRow: 0,
1653
+ endRow: Math.max(0, recordCount - 1),
1654
+ startColumn: 0,
1655
+ endColumn: Math.max(0, fieldOrder.length - 1)
1656
+ },
1657
+ titleMap: new Map(fieldOrder.map((fieldId, index) => [table.fields[fieldId]?.name ?? fieldId, index])),
1658
+ showHeader: !1
1659
+ };
1660
+ return [[formulaTableNames.get(table.id), reference]];
1661
+ }
1542
1662
  _rawCellData(cellData) {
1543
1663
  let raw = cellData.getMatrix(), result = {};
1544
1664
  for (let [row, values] of Object.entries(raw ?? {})) {
@@ -1549,16 +1669,58 @@ var RustSameRuntimeProjectionController = class extends import_core3.Disposable
1549
1669
  }
1550
1670
  return result;
1551
1671
  }
1552
- }, BASE_LEGACY_FIELD_REF_PATTERN = /\{([^}]+)\}/g, BASE_TABLE_REFERENCE_PREFIX = /\b[A-Z_][\w.]*\[/gi, BASE_SCOPED_FIELD_REF_PATTERN = /(^|[^\w[])\[\[\s*#(This Row|Data)\s*\],\s*\[([^\]]+)\]\]/gi, BASE_CURRENT_ROW_FIELD_REF_PATTERN = /(^|[^\w[])\[@\[([^\]]+)\]\](?!\])/g, BASE_BRACKET_FIELD_REF_PATTERN = /(^|[^A-Za-z0-9_[\]])\[([^\]]+)\]/g, BASE_EXTERNAL_A1_REF_PATTERN = /(?:'\[[^\]]+\](?:[^']|'')+'|\[[^\]]+\][^\s'!]+)!\$?[A-Z]{1,3}\$?\d+(?::\$?[A-Z]{1,3}\$?\d+)?/gi, BASE_EXTERNAL_STRUCTURED_REFERENCE_PREFIX = /(?:'((?:[^']|'')+)'|\[[^\]]+\]|[A-Za-z0-9_.-]+)![^\s![\]]+\[/g;
1553
- function normalizeBaseFormulaForEngine(formula, currentTable, snapshot) {
1554
- let references = [], hold = (reference) => `__BASE_FORMULA_REF_${references.push(reference) - 1}__`;
1555
- return protectBaseTableReferences(protectBaseExternalReferences(formula, hold), hold).replace(
1672
+ };
1673
+ function createBaseProjectionStructure(snapshot) {
1674
+ let formulaTableNames = (0, import_core3.createBaseFormulaTableNameMap)(snapshot);
1675
+ return {
1676
+ unitName: snapshot.name,
1677
+ tables: Object.fromEntries(
1678
+ Object.values(snapshot.tables).map((table) => [
1679
+ table.id,
1680
+ {
1681
+ formulaName: formulaTableNames.get(table.id),
1682
+ fieldOrder: [...table.fieldOrder],
1683
+ recordOrder: baseRecordOrder(table),
1684
+ fieldSignatures: Object.fromEntries(
1685
+ Object.entries(table.fields).map(([fieldId, field]) => [fieldId, JSON.stringify(field)])
1686
+ )
1687
+ }
1688
+ ])
1689
+ )
1690
+ };
1691
+ }
1692
+ function isSameBaseProjectionStructure(left, right) {
1693
+ return JSON.stringify(left) === JSON.stringify(right);
1694
+ }
1695
+ function findSingleBaseFieldInsertion(previous, snapshot) {
1696
+ let current = createBaseProjectionStructure(snapshot), previousTableIds = Object.keys(previous.tables).toSorted(), currentTableIds = Object.keys(current.tables).toSorted();
1697
+ if (JSON.stringify(previousTableIds) !== JSON.stringify(currentTableIds)) return null;
1698
+ let insertion = null;
1699
+ for (let tableId of currentTableIds) {
1700
+ let before = previous.tables[tableId], after = current.tables[tableId];
1701
+ if (!before || !after || before.formulaName !== after.formulaName || JSON.stringify(before.recordOrder) !== JSON.stringify(after.recordOrder)) return null;
1702
+ for (let fieldId of before.fieldOrder)
1703
+ if (before.fieldSignatures[fieldId] !== after.fieldSignatures[fieldId]) return null;
1704
+ if (JSON.stringify(before.fieldOrder) === JSON.stringify(after.fieldOrder)) continue;
1705
+ if (insertion || after.fieldOrder.length !== before.fieldOrder.length + 1) return null;
1706
+ let column = after.fieldOrder.findIndex((fieldId, index) => fieldId !== before.fieldOrder[index]);
1707
+ if (column < 0) return null;
1708
+ let withoutInserted = after.fieldOrder.filter((_, index) => index !== column);
1709
+ if (JSON.stringify(withoutInserted) !== JSON.stringify(before.fieldOrder)) return null;
1710
+ insertion = { tableId, column };
1711
+ }
1712
+ return insertion;
1713
+ }
1714
+ var BASE_LEGACY_FIELD_REF_PATTERN = /\{([^}]+)\}/g, BASE_TABLE_REFERENCE_PREFIX = /\b[A-Z_][\w.]*\[/gi, BASE_SCOPED_FIELD_REF_PATTERN = /(^|[^\w[])\[\[\s*#(This Row|Data)\s*\],\s*\[([^\]]+)\]\]/gi, BASE_CURRENT_ROW_FIELD_REF_PATTERN = /(^|[^\w[])\[@\[([^\]]+)\]\](?!\])/g, BASE_BRACKET_FIELD_REF_PATTERN = /(^|[^A-Za-z0-9_[\]])\[([^\]]+)\]/g, BASE_EXTERNAL_A1_REF_PATTERN = /(?:'\[[^\]]+\](?:[^']|'')+'|\[[^\]]+\][^\s'!]+)!\$?[A-Z]{1,3}\$?\d+(?::\$?[A-Z]{1,3}\$?\d+)?/gi, BASE_EXTERNAL_STRUCTURED_REFERENCE_PREFIX = /(?:'((?:[^']|'')+)'|\[[^\]]+\]|[A-Za-z0-9_.-]+)![^\s![\]]+\[/g;
1715
+ function normalizeBaseFormulaForEngine(formula, currentTable, formulaTableNames, normalizeFormulaTableReferences) {
1716
+ let canonicalFormula = normalizeFormulaTableReferences(formula), references = [], hold = (reference) => `__BASE_FORMULA_REF_${references.push(reference) - 1}__`;
1717
+ return protectBaseTableReferences(protectBaseExternalReferences(canonicalFormula, hold), hold).replace(
1556
1718
  BASE_LEGACY_FIELD_REF_PATTERN,
1557
- (_match, fieldName) => hold(createEngineThisRowRef(currentTable, fieldName, snapshot))
1719
+ (_match, fieldName) => hold(createEngineThisRowRef(currentTable, fieldName, formulaTableNames))
1558
1720
  ).replace(BASE_SCOPED_FIELD_REF_PATTERN, (_match, prefix, scope, fieldName) => {
1559
- let tableName = getEngineBaseTableName(currentTable, snapshot);
1721
+ let tableName = formulaTableNames.get(currentTable.id) ?? currentTable.name;
1560
1722
  return `${prefix}${hold(`${tableName}[[#${scope}],[${fieldName}]]`)}`;
1561
- }).replace(BASE_CURRENT_ROW_FIELD_REF_PATTERN, (_match, prefix, fieldName) => `${prefix}${hold(createEngineThisRowRef(currentTable, fieldName, snapshot))}`).replace(BASE_BRACKET_FIELD_REF_PATTERN, (_match, prefix, fieldName) => `${prefix}${hold(createEngineThisRowRef(currentTable, fieldName, snapshot))}`).replace(
1723
+ }).replace(BASE_CURRENT_ROW_FIELD_REF_PATTERN, (_match, prefix, fieldName) => `${prefix}${hold(createEngineThisRowRef(currentTable, fieldName, formulaTableNames))}`).replace(BASE_BRACKET_FIELD_REF_PATTERN, (_match, prefix, fieldName) => `${prefix}${hold(createEngineThisRowRef(currentTable, fieldName, formulaTableNames))}`).replace(
1562
1724
  /__BASE_FORMULA_REF_(\d+)__/g,
1563
1725
  (_match, index) => references[Number(index)] ?? ""
1564
1726
  );
@@ -1607,37 +1769,21 @@ function isInsideBaseFormulaString(formula, position) {
1607
1769
  }
1608
1770
  return inString;
1609
1771
  }
1610
- function createEngineThisRowRef(table, fieldName, snapshot) {
1611
- return `${getEngineBaseTableName(table, snapshot)}[[#This Row],[${fieldName}]]`;
1612
- }
1613
- function getEngineBaseTableName(table, snapshot) {
1614
- return isUniqueBaseTableName(table, snapshot) && isExcelTableName(table.name) ? table.name : createStableExcelTableName(table.id);
1615
- }
1616
- function isUniqueBaseTableName(table, snapshot) {
1617
- let normalizedName = table.name.trim().toLowerCase();
1618
- return Object.values(snapshot.tables).filter((candidate) => candidate.name.trim().toLowerCase() === normalizedName).length === 1;
1619
- }
1620
- function isExcelTableName(name2) {
1621
- return name2.length === 0 || name2.length > 255 || !/^[A-Za-z_][A-Za-z0-9_.]*$/.test(name2) ? !1 : !/^[RC]$/i.test(name2) && !/^[A-Za-z]{1,3}[1-9]\d*$/.test(name2) && !/^R(?:\d+)?C(?:\d+)?$/i.test(name2);
1622
- }
1623
- function createStableExcelTableName(tableId) {
1624
- return `_T_${Array.from(
1625
- tableId,
1626
- (character) => /[A-Za-z0-9]/.test(character) ? character : `_x${character.codePointAt(0)?.toString(16) ?? "0"}_`
1627
- ).join("")}`;
1772
+ function createEngineThisRowRef(table, fieldName, formulaTableNames) {
1773
+ return `${formulaTableNames.get(table.id) ?? table.name}[[#This Row],[${fieldName}]]`;
1628
1774
  }
1629
1775
  function baseRecordOrder(table) {
1630
1776
  return table.recordOrder ? table.recordOrder.filter((recordId) => table.records[recordId] != null) : Object.values(table.records ?? {}).toSorted((left, right) => left.orderKey.localeCompare(right.orderKey)).map((record) => record.id);
1631
1777
  }
1632
1778
  function buildBaseRuntimeCellData(table) {
1633
- let cellData = { ...table.cellData }, fieldOrder = table.fieldOrder.filter((fieldId) => table.fields[fieldId] != null), recordOrder = baseRecordOrder(table);
1779
+ let cellData = { ...table.cellData }, fieldOrder = table.fieldOrder, recordOrder = baseRecordOrder(table);
1634
1780
  for (let row = 0; row < recordOrder.length; row++) {
1635
1781
  let record = table.records[recordOrder[row]];
1636
1782
  if (record) {
1637
1783
  cellData[row] = { ...cellData[row] };
1638
1784
  for (let column = 0; column < fieldOrder.length; column++) {
1639
1785
  let fieldId = fieldOrder[column];
1640
- Object.prototype.hasOwnProperty.call(record.values ?? {}, fieldId) && (cellData[row][column] = toBaseRuntimeCellData(record.values[fieldId], table.fields[fieldId]));
1786
+ table.fields[fieldId] && Object.prototype.hasOwnProperty.call(record.values ?? {}, fieldId) && (cellData[row][column] = toBaseRuntimeCellData(record.values[fieldId], table.fields[fieldId]));
1641
1787
  }
1642
1788
  }
1643
1789
  }
@@ -1723,7 +1869,7 @@ function resultBatchSheetCounts(output) {
1723
1869
  return counts;
1724
1870
  }
1725
1871
  var RustCalculateFormulaService = class extends import_core4.Disposable {
1726
- constructor(_configService, _currentConfigService, _runtimeService, _formulaDependencyGenerator, _featureCalculationManagerService, _otherFormulaManagerService, _commandService, _rustEngineSyncController, _formulaDataModel, _formulaReferenceDataService, _excelExternalReferenceModel, _superTableService) {
1872
+ constructor(_configService, _currentConfigService, _runtimeService, _formulaDependencyGenerator, _featureCalculationManagerService, _otherFormulaManagerService, _commandService, _rustEngineSyncController, _formulaDataModel, _formulaReferenceDataService, _excelExternalReferenceModel, _superTableService, _definedNamesService) {
1727
1873
  super();
1728
1874
  this._configService = _configService;
1729
1875
  this._currentConfigService = _currentConfigService;
@@ -1737,6 +1883,7 @@ var RustCalculateFormulaService = class extends import_core4.Disposable {
1737
1883
  this._formulaReferenceDataService = _formulaReferenceDataService;
1738
1884
  this._excelExternalReferenceModel = _excelExternalReferenceModel;
1739
1885
  this._superTableService = _superTableService;
1886
+ this._definedNamesService = _definedNamesService;
1740
1887
  this._commandService.hasCommand(import_engine_formula2.SetFormulaCalculationResultMutation.id) || this.disposeWithMe(this._commandService.registerCommand(import_engine_formula2.SetFormulaCalculationResultMutation)), this._commandService.hasCommand(import_engine_formula2.SetArrayFormulaDataMutation.id) || this.disposeWithMe(this._commandService.registerCommand(import_engine_formula2.SetArrayFormulaDataMutation));
1741
1888
  }
1742
1889
  _configService;
@@ -1751,6 +1898,7 @@ var RustCalculateFormulaService = class extends import_core4.Disposable {
1751
1898
  _formulaReferenceDataService;
1752
1899
  _excelExternalReferenceModel;
1753
1900
  _superTableService;
1901
+ _definedNamesService;
1754
1902
  _executionInProgressListener$ = new import_rxjs.Subject();
1755
1903
  executionInProgressListener$ = this._executionInProgressListener$.asObservable();
1756
1904
  _executionCompleteListener$ = new import_rxjs.Subject();
@@ -2248,16 +2396,23 @@ var RustCalculateFormulaService = class extends import_core4.Disposable {
2248
2396
  if (!unitData) return result;
2249
2397
  for (let [unitId, sheets] of Object.entries(unitData)) {
2250
2398
  result[unitId] = {};
2399
+ let styles = this._currentConfigService.getUnitStylesData()[unitId], sheetNames = Object.fromEntries(
2400
+ Object.entries(this._currentConfigService.getSheetNameMap()[unitId] ?? {}).map(([name2, id]) => [
2401
+ id,
2402
+ name2
2403
+ ])
2404
+ );
2251
2405
  for (let [sheetId, sheet] of Object.entries(sheets))
2252
2406
  result[unitId][sheetId] = {
2253
- cellData: this._serializeCellData(sheet.cellData),
2407
+ name: sheetNames[sheetId],
2408
+ cellData: this._serializeCellData(sheet.cellData, styles),
2254
2409
  rowCount: sheet.rowCount ?? 0,
2255
2410
  columnCount: sheet.columnCount ?? 0
2256
2411
  };
2257
2412
  }
2258
2413
  return result;
2259
2414
  }
2260
- _serializeCellData(cellData) {
2415
+ _serializeCellData(cellData, styles) {
2261
2416
  let result = {};
2262
2417
  if (!cellData || typeof cellData != "object") return result;
2263
2418
  let data = typeof cellData.getMatrix == "function" ? cellData.getMatrix() : cellData;
@@ -2267,13 +2422,23 @@ var RustCalculateFormulaService = class extends import_core4.Disposable {
2267
2422
  result[row] = {};
2268
2423
  for (let [colStr, cell] of Object.entries(cols)) {
2269
2424
  let col = Number(colStr);
2270
- Number.isFinite(col) && (result[row][col] = {
2425
+ if (!Number.isFinite(col))
2426
+ continue;
2427
+ result[row][col] = {
2271
2428
  v: cell?.v ?? null,
2272
2429
  t: cell?.t ?? void 0,
2273
2430
  p: cell?.p ?? void 0,
2274
2431
  f: cell?.f ?? void 0,
2275
2432
  s: cell?.s ?? void 0
2276
- });
2433
+ };
2434
+ let style = styles?.getStyleByCell(cell);
2435
+ if (style && typeof style == "object") {
2436
+ let numberFormat = style.n;
2437
+ if (numberFormat && typeof numberFormat == "object") {
2438
+ let pattern = numberFormat.pattern;
2439
+ typeof pattern == "string" && (result[row][col].numberFormat = pattern);
2440
+ }
2441
+ }
2277
2442
  }
2278
2443
  }
2279
2444
  }
@@ -2282,7 +2447,9 @@ var RustCalculateFormulaService = class extends import_core4.Disposable {
2282
2447
  _applyRustOutput(_output) {
2283
2448
  }
2284
2449
  async _applyRustDependencyOutput(output) {
2285
- let convertStartedAt = performance.now(), patch = rustExecutionOutputToFormulaCalculationPatch(output), convertMs = performance.now() - convertStartedAt, commandStartedAt = performance.now();
2450
+ let convertStartedAt = performance.now(), patch = rustExecutionOutputToFormulaCalculationPatch(output);
2451
+ this._mergeRuntimeUnitData(patch.unitData);
2452
+ let convertMs = performance.now() - convertStartedAt, commandStartedAt = performance.now();
2286
2453
  return (patch.arrayFormulaRange || patch.arrayFormulaCellData) && (this._formulaDataModel.setArrayFormulaRange(patch.arrayFormulaRange ?? {}), this._formulaDataModel.setArrayFormulaCellData(patch.arrayFormulaCellData ?? {}), await this._commandService.executeCommand(
2287
2454
  import_engine_formula2.SetArrayFormulaDataMutation.id,
2288
2455
  {
@@ -2309,6 +2476,20 @@ var RustCalculateFormulaService = class extends import_core4.Disposable {
2309
2476
  commandMs: performance.now() - commandStartedAt
2310
2477
  };
2311
2478
  }
2479
+ _mergeRuntimeUnitData(unitData) {
2480
+ let runtimeUnitData = this._runtimeService.getUnitData();
2481
+ Object.entries(unitData).forEach(([unitId, sheetMap]) => {
2482
+ if (!sheetMap) return;
2483
+ let runtimeSheetMap = runtimeUnitData[unitId] ??= {};
2484
+ Object.entries(sheetMap).forEach(([sheetId, cellData]) => {
2485
+ if (!cellData) return;
2486
+ let runtimeMatrix = runtimeSheetMap[sheetId] ??= new import_core4.ObjectMatrix();
2487
+ new import_core4.ObjectMatrix(cellData).forValue((row, column, cell) => {
2488
+ runtimeMatrix.setValue(row, column, cell);
2489
+ });
2490
+ });
2491
+ });
2492
+ }
2312
2493
  async calculate(formulaString) {
2313
2494
  this._nativeLoaded || (await loadNativeBinding(), this._nativeLoaded = !0);
2314
2495
  let unitId = "__rust_formula_calculate__", sheetId = "__sheet__", input = {
@@ -2336,13 +2517,25 @@ var RustCalculateFormulaService = class extends import_core4.Disposable {
2336
2517
  }
2337
2518
  async executeFormulas(formulas, rowData) {
2338
2519
  this._nativeLoaded || (await loadNativeBinding(), this._nativeLoaded = !0), this._currentConfigService.loadDataLite(rowData);
2339
- let unitData = this._currentConfigService.getUnitData(), formulaData = this._formulaStringMapToFormulaData(formulas), input = {
2520
+ let unitData = this._currentConfigService.getUnitData(), definedNames = {};
2521
+ for (let [unitId, names] of Object.entries(this._definedNamesService.getAllDefinedNames()))
2522
+ for (let [id, name2] of Object.entries(names))
2523
+ definedNames[JSON.stringify([unitId, id])] = {
2524
+ unitId,
2525
+ localSheetId: name2.localSheetId === "AllDefaultWorkbook" ? void 0 : name2.localSheetId,
2526
+ name: name2.name,
2527
+ formula: name2.formulaOrRefString
2528
+ };
2529
+ let input = {
2340
2530
  config: { maxIteration: 1, intervalCount: DEFAULT_INTERVAL_COUNT },
2341
- formulaData,
2531
+ formulaData: {},
2532
+ queryFormulas: this._formulaStringMapToQueryData(formulas),
2342
2533
  unitData: this._serializeUnitData(unitData),
2343
2534
  dirtyRanges: [],
2344
- definedNames: {}
2535
+ definedNames
2345
2536
  }, output = JSON.parse(executeOnRust(JSON.stringify(input)));
2537
+ if (!output.queryResults)
2538
+ throw new Error("Native formula binding does not support independent formula queries");
2346
2539
  return this._formulaExecutionOutputToResultMap(formulas, output);
2347
2540
  }
2348
2541
  async getAllDependencyJson(_rowData) {
@@ -2385,7 +2578,7 @@ var RustCalculateFormulaService = class extends import_core4.Disposable {
2385
2578
  ]);
2386
2579
  return { dependents, inRanges };
2387
2580
  }
2388
- _formulaStringMapToFormulaData(formulas) {
2581
+ _formulaStringMapToQueryData(formulas) {
2389
2582
  let formulaData = {};
2390
2583
  return Object.entries(formulas).forEach(([unitId, sheetMap]) => {
2391
2584
  sheetMap && (formulaData[unitId] = {}, Object.entries(sheetMap).forEach(([sheetId, rowMap]) => {
@@ -2393,8 +2586,7 @@ var RustCalculateFormulaService = class extends import_core4.Disposable {
2393
2586
  if (!colMap) return;
2394
2587
  let row = Number(rowKey);
2395
2588
  formulaData[unitId][sheetId][row] = {}, Object.entries(colMap).forEach(([colKey, formulaList]) => {
2396
- let formula = Array.isArray(formulaList) ? formulaList[0] : void 0;
2397
- typeof formula == "string" && (formulaData[unitId][sheetId][row][Number(colKey)] = formula);
2589
+ Array.isArray(formulaList) && (formulaData[unitId][sheetId][row][Number(colKey)] = formulaList);
2398
2590
  });
2399
2591
  }));
2400
2592
  }));
@@ -2408,10 +2600,13 @@ var RustCalculateFormulaService = class extends import_core4.Disposable {
2408
2600
  if (!colMap) return;
2409
2601
  let row = Number(rowKey);
2410
2602
  result[unitId][sheetId][row] = {}, Object.entries(colMap).forEach(([colKey, formulaList]) => {
2411
- let col = Number(colKey), formulasForCell = Array.isArray(formulaList) ? formulaList : [], value = normalizeFormulaResultValue(
2412
- output.runtimeData?.[unitId]?.[sheetId]?.[row]?.[col]
2413
- );
2414
- result[unitId][sheetId][row][col] = formulasForCell.map((formula) => ({ formula, value }));
2603
+ let col = Number(colKey), formulasForCell = Array.isArray(formulaList) ? formulaList : [];
2604
+ result[unitId][sheetId][row][col] = formulasForCell.map((formula, index) => ({
2605
+ formula,
2606
+ value: normalizeFormulaResultValue(
2607
+ output.queryResults?.[unitId]?.[sheetId]?.[row]?.[col]?.[index]?.value
2608
+ )
2609
+ }));
2415
2610
  });
2416
2611
  }));
2417
2612
  }));
@@ -2530,7 +2725,8 @@ var RustCalculateFormulaService = class extends import_core4.Disposable {
2530
2725
  import_engine_formula2.FormulaDataModel,
2531
2726
  import_engine_formula3.IFormulaReferenceDataService,
2532
2727
  import_engine_formula3.ExternalReferenceModel,
2533
- import_engine_formula2.ISuperTableService
2728
+ import_engine_formula2.ISuperTableService,
2729
+ import_engine_formula2.IDefinedNamesService
2534
2730
  ]);
2535
2731
  function createRustProductExternalSyntheticUnitId(hostUnitId, referenceId) {
2536
2732
  return `external:product:${encodeURIComponent(hostUnitId)}:${encodeURIComponent(referenceId)}`;