@univerjs-pro/engine-formula-rust 1.0.0-rc.0 → 1.0.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.
package/lib/cjs/index.cjs CHANGED
@@ -32,6 +32,7 @@ __export(index_exports, {
32
32
  RUST_UPSERT_REFERENCE_DATA_MUTATION_ID: () => RUST_UPSERT_REFERENCE_DATA_MUTATION_ID,
33
33
  RustCalculateFormulaService: () => RustCalculateFormulaService,
34
34
  RustEngineSyncController: () => RustEngineSyncController,
35
+ RustFormulaEngineSession: () => RustFormulaEngineSession,
35
36
  RustFormulaProjectionService: () => RustFormulaProjectionService,
36
37
  UniverRustFormulaEnginePlugin: () => UniverRustFormulaEnginePlugin,
37
38
  analyzeNumberFormatBatch: () => analyzeNumberFormatBatch,
@@ -150,11 +151,6 @@ function loadSnapshotOnRust(snapshotJson) {
150
151
  throw new Error("Native binding not loaded. Call loadNativeBinding() first.");
151
152
  return nativeBinding.rustEngineLoadSnapshot(snapshotJson);
152
153
  }
153
- function loadSnapshotBinaryOnRust(snapshotBytes) {
154
- if (!nativeBinding)
155
- throw new Error("Native binding not loaded. Call loadNativeBinding() first.");
156
- return nativeBinding.rustEngineLoadSnapshotBinary(snapshotBytes);
157
- }
158
154
  function applyMutationOnRust(mutationJson) {
159
155
  if (!nativeBinding)
160
156
  throw new Error("Native binding not loaded. Call loadNativeBinding() first.");
@@ -205,11 +201,6 @@ function syncRustFormulaDependenciesOnRust(inputJson) {
205
201
  throw new Error("Native binding not loaded. Call loadNativeBinding() first.");
206
202
  return nativeBinding.rustEngineSyncFormulaDependencies(inputJson);
207
203
  }
208
- function inspectRustFormulaDependencyGraphOnRust() {
209
- if (!nativeBinding)
210
- throw new Error("Native binding not loaded. Call loadNativeBinding() first.");
211
- return nativeBinding.rustEngineInspectFormulaDependencyGraph();
212
- }
213
204
  function markRustFormulaDirtyOnRust(inputJson) {
214
205
  if (!nativeBinding)
215
206
  throw new Error("Native binding not loaded. Call loadNativeBinding() first.");
@@ -225,21 +216,34 @@ function clearRustFormulaDirtyOnRust() {
225
216
  throw new Error("Native binding not loaded. Call loadNativeBinding() first.");
226
217
  return nativeBinding.rustEngineClearFormulaDirty();
227
218
  }
228
- function executeDirtyFormulasOnRust(maxIteration, includeCalculatedNodes, includeRuntimeData, includeResultBatches) {
229
- if (!nativeBinding)
230
- throw new Error("Native binding not loaded. Call loadNativeBinding() first.");
231
- return nativeBinding.rustEngineExecuteDirtyFormulas(
232
- maxIteration,
233
- includeCalculatedNodes,
234
- includeRuntimeData,
235
- includeResultBatches
236
- );
237
- }
238
219
  function materializeWorkbookSnapshotOnRust(workbookJson, unitId, rev, dirtyInputJson) {
239
220
  if (!nativeBinding)
240
221
  throw new Error("Native binding not loaded. Call loadNativeBinding() first.");
241
222
  return nativeBinding.rustMaterializeWorkbookSnapshot(workbookJson, unitId, rev, dirtyInputJson);
242
223
  }
224
+ var RustFormulaEngineSession = class {
225
+ _engine = null;
226
+ _disposed = !1;
227
+ async initialize() {
228
+ if (this._disposed) throw new Error("Rust formula engine session is disposed");
229
+ if (this._engine) return;
230
+ let binding = await loadNativeBinding();
231
+ if (this._disposed) throw new Error("Rust formula engine session is disposed");
232
+ if (!this._engine) {
233
+ if (typeof binding.RustFormulaEngine != "function")
234
+ throw new Error("Native formula binding lacks instance isolation; upgrade engine-formula-rust-binding");
235
+ this._engine = new binding.RustFormulaEngine();
236
+ }
237
+ }
238
+ get binding() {
239
+ if (this._disposed) throw new Error("Rust formula engine session is disposed");
240
+ if (!this._engine) throw new Error("Rust formula engine session is not initialized");
241
+ return this._engine;
242
+ }
243
+ dispose() {
244
+ this._disposed || (this._disposed = !0, this._engine?.dispose(), this._engine = null);
245
+ }
246
+ };
243
247
 
244
248
  // src/controllers/rust-engine-sync.controller.ts
245
249
  var import_core2 = require("@univerjs/core");
@@ -262,6 +266,11 @@ var XLSX_WORKBOOK_CALCULATION_RESOURCE = "UNIVER_CLI_XLSX_WORKBOOK_CALCULATION_P
262
266
  "sheet.mutation.set-col-visible",
263
267
  "sheet.mutation.set-row-hidden",
264
268
  "sheet.mutation.set-row-visible",
269
+ "sheet.mutation.set-table-filter",
270
+ "sheet.mutation.set-filter-range",
271
+ "sheet.mutation.set-filter-criteria",
272
+ "sheet.mutation.remove-filter",
273
+ "sheet.mutation.re-calc-filter",
265
274
  "sheet.mutation.set-worksheet-name",
266
275
  "sheet.mutation.reorder-range",
267
276
  "sheet.mutation.set-worksheet-row-count",
@@ -335,11 +344,18 @@ function serializeRuntimeWorkbookSnapshots(workbooks) {
335
344
  }
336
345
  function serializeRuntimeWorkbookSnapshot(input) {
337
346
  let { snapshot } = input, sheetOrder = snapshot.sheetOrder?.length > 0 ? snapshot.sheetOrder : Object.keys(snapshot.sheets ?? {}), calculation = serializeCalculation(snapshot), precisionAsDisplayed = calculation?.fullPrecision === !1, sheets = sheetOrder.map(
338
- (sheetId) => serializeSheetSnapshot(sheetId, snapshot.sheets?.[sheetId], snapshot.styles, precisionAsDisplayed)
347
+ (sheetId) => serializeSheetSnapshot(
348
+ sheetId,
349
+ snapshot.sheets?.[sheetId],
350
+ snapshot.styles,
351
+ precisionAsDisplayed,
352
+ input.styleResolver
353
+ )
339
354
  ).filter((sheet) => sheet != null);
340
355
  return {
341
356
  unitId: input.unitId || snapshot.id,
342
357
  name: snapshot.name,
358
+ dateSystem: snapshot.dateSystem,
343
359
  sheets,
344
360
  ...calculation ? { calculation } : {},
345
361
  resources: serializeResources(snapshot),
@@ -407,13 +423,16 @@ function otherFormulaDataToUnitOtherData(otherFormulaData) {
407
423
  if (!colMap) return;
408
424
  let row = Number(rowKey), rowData = {};
409
425
  formulaData[row] = rowData, Object.entries(colMap).forEach(([colKey, value]) => {
410
- rowData[Number(colKey)] = [[cellDataFromRustValue(value)]];
426
+ rowData[Number(colKey)] = otherFormulaResultFromRustValue(value);
411
427
  });
412
428
  });
413
429
  });
414
430
  });
415
431
  }), unitOtherData;
416
432
  }
433
+ function otherFormulaResultFromRustValue(value) {
434
+ return Array.isArray(value) ? value.map((row) => (Array.isArray(row) ? row : [row]).map((cell) => cellDataFromRustValue(cell))) : [[cellDataFromRustValue(value)]];
435
+ }
417
436
  function createFormulaProjectionDesyncSignal(reason, error, mutationId) {
418
437
  return {
419
438
  reason,
@@ -422,12 +441,20 @@ function createFormulaProjectionDesyncSignal(reason, error, mutationId) {
422
441
  };
423
442
  }
424
443
  var RustFormulaProjectionService = class {
444
+ engine = new RustFormulaEngineSession();
445
+ dispose() {
446
+ this.engine.dispose();
447
+ }
425
448
  _nativeLoaded = !1;
426
449
  async load(workbooks) {
427
450
  await this._ensureNativeLoaded();
428
451
  try {
429
452
  return {
430
- stats: JSON.parse(loadSnapshotOnRust(JSON.stringify(serializeRuntimeWorkbookSnapshots(workbooks))))
453
+ stats: JSON.parse(
454
+ this.engine.binding.rustEngineLoadSnapshot(
455
+ JSON.stringify(serializeRuntimeWorkbookSnapshots(workbooks))
456
+ )
457
+ )
431
458
  };
432
459
  } catch (error) {
433
460
  return {
@@ -440,7 +467,9 @@ var RustFormulaProjectionService = class {
440
467
  await this._ensureNativeLoaded();
441
468
  try {
442
469
  return {
443
- stats: JSON.parse(applyMutationOnRust(JSON.stringify(normalizeRustEngineMutation(mutation)))),
470
+ stats: JSON.parse(
471
+ this.engine.binding.rustEngineApplyMutation(JSON.stringify(normalizeRustEngineMutation(mutation)))
472
+ ),
444
473
  dependencyInvalidated: !isRustIncrementalDependencyMutation(mutation.id)
445
474
  };
446
475
  } catch (error) {
@@ -452,16 +481,16 @@ var RustFormulaProjectionService = class {
452
481
  }
453
482
  }
454
483
  async syncFormulaDependencies(input) {
455
- return await this._ensureNativeLoaded(), JSON.parse(syncRustFormulaDependenciesOnRust(JSON.stringify(input)));
484
+ return await this._ensureNativeLoaded(), JSON.parse(this.engine.binding.rustEngineSyncFormulaDependencies(JSON.stringify(input)));
456
485
  }
457
486
  async markDirty(input) {
458
- return await this._ensureNativeLoaded(), JSON.parse(markRustFormulaDirtyOnRust(JSON.stringify(input)));
487
+ return await this._ensureNativeLoaded(), JSON.parse(this.engine.binding.rustEngineMarkFormulaDirty(JSON.stringify(input)));
459
488
  }
460
489
  async calculateDirty(maxIteration = 1) {
461
490
  await this._ensureNativeLoaded();
462
491
  try {
463
492
  let output = JSON.parse(
464
- executeDirtyFormulasOnRust(maxIteration, !1, !1, !0)
493
+ this.engine.binding.rustEngineExecuteDirtyFormulas(maxIteration, !1, !1, !0)
465
494
  );
466
495
  return rustExecutionOutputToFormulaCalculationPatch(output);
467
496
  } catch (error) {
@@ -476,7 +505,7 @@ var RustFormulaProjectionService = class {
476
505
  async reset() {
477
506
  await this._ensureNativeLoaded();
478
507
  try {
479
- return clearRustFormulaDirtyOnRust(), clearRustFormulaDependenciesOnRust(
508
+ return this.engine.binding.rustEngineClearFormulaDirty(), this.engine.binding.rustEngineClearFormulaDependencies(
480
509
  JSON.stringify({
481
510
  unitId: "",
482
511
  clearSheetFormulas: !0,
@@ -484,7 +513,11 @@ var RustFormulaProjectionService = class {
484
513
  clearOtherFormulas: !0
485
514
  })
486
515
  ), {
487
- stats: JSON.parse(loadSnapshotOnRust(JSON.stringify({ workbooks: [] })))
516
+ stats: JSON.parse(
517
+ this.engine.binding.rustEngineLoadSnapshot(
518
+ JSON.stringify({ workbooks: [] })
519
+ )
520
+ )
488
521
  };
489
522
  } catch (error) {
490
523
  return {
@@ -496,7 +529,7 @@ var RustFormulaProjectionService = class {
496
529
  async disposeWorkbook(unitId) {
497
530
  await this._ensureNativeLoaded();
498
531
  try {
499
- return { stats: JSON.parse(disposeWorkbookOnRust(unitId)) };
532
+ return { stats: JSON.parse(this.engine.binding.rustEngineDisposeWorkbook(unitId)) };
500
533
  } catch (error) {
501
534
  return {
502
535
  desync: createFormulaProjectionDesyncSignal("workbook-dispose-failed", error),
@@ -505,7 +538,7 @@ var RustFormulaProjectionService = class {
505
538
  }
506
539
  }
507
540
  async _ensureNativeLoaded() {
508
- this._nativeLoaded || (await loadNativeBinding(), this._nativeLoaded = !0);
541
+ this._nativeLoaded || (await this.engine.initialize(), this._nativeLoaded = !0);
509
542
  }
510
543
  };
511
544
  function normalizeRustEngineMutation(mutation) {
@@ -947,19 +980,19 @@ function extractDefinedNames(snapshot) {
947
980
  }
948
981
  return {};
949
982
  }
950
- function serializeSheetSnapshot(sheetId, sheet, styles, precisionAsDisplayed) {
983
+ function serializeSheetSnapshot(sheetId, sheet, styles, precisionAsDisplayed, styleResolver) {
951
984
  return sheet ? {
952
985
  sheetId: sheet.id ?? sheetId,
953
986
  name: sheet.name,
954
987
  rowCount: sheet.rowCount ?? 0,
955
988
  columnCount: sheet.columnCount ?? 0,
956
989
  transitionEvaluation: sheet.transitionEvaluation === !0,
957
- cellData: serializeCellData(sheet.cellData, styles, precisionAsDisplayed),
990
+ cellData: serializeCellData(sheet.cellData, styles, precisionAsDisplayed, styleResolver),
958
991
  rowData: serializeVisibilityData(sheet.rowData),
959
992
  columnData: serializeVisibilityData(sheet.columnData)
960
993
  } : null;
961
994
  }
962
- function serializeCellData(cellData = {}, styles, precisionAsDisplayed = !1) {
995
+ function serializeCellData(cellData = {}, styles, precisionAsDisplayed = !1, styleResolver) {
963
996
  let result = {}, rawCellData = cellData instanceof import_core.ObjectMatrix ? cellData.getMatrix() : cellData;
964
997
  for (let [rowKey, row] of Object.entries(rawCellData ?? {})) {
965
998
  if (!row)
@@ -968,13 +1001,15 @@ function serializeCellData(cellData = {}, styles, precisionAsDisplayed = !1) {
968
1001
  for (let [colKey, cell] of Object.entries(row)) {
969
1002
  if (!cell || typeof cell != "object")
970
1003
  continue;
971
- let cellRecord = cell, value = {};
972
- 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") {
1004
+ let cellRecord = cell, resolvedStyle = styleResolver?.getStyleByCell(cell), value = {};
1005
+ 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") {
973
1006
  let hasFormula = typeof cellRecord.f == "string" && cellRecord.f.length > 0;
974
1007
  typeof cellRecord.si == "string" || hasFormula && isLegacyArrayFormulaCell(cellRecord) ? value.ref = cellRecord.ref : hasFormula && (value.dynamicArrayRef = cellRecord.ref);
975
1008
  }
976
- if (typeof cellRecord.xf == "string" && (value.xf = cellRecord.xf), "s" in cellRecord && (value.s = cellRecord.s), precisionAsDisplayed && typeof cellRecord.f == "string") {
977
- let displayPrecision = inferDisplayPrecision(cellRecord.s, styles);
1009
+ typeof cellRecord.xf == "string" && (value.xf = cellRecord.xf), "s" in cellRecord && (value.s = cellRecord.s);
1010
+ let numberFormat = resolveNumberFormatPattern(cellRecord.s, styles, resolvedStyle);
1011
+ if (numberFormat !== void 0 && (value.numberFormat = numberFormat), precisionAsDisplayed && typeof cellRecord.f == "string") {
1012
+ let displayPrecision = inferDisplayPrecision(cellRecord.s, styles, resolvedStyle);
978
1013
  displayPrecision !== void 0 && (value.displayPrecision = displayPrecision);
979
1014
  }
980
1015
  Object.keys(value).length > 0 && (serializedRow[Number(colKey)] = value);
@@ -997,23 +1032,19 @@ function serializeCellDataInRanges(cellData, ranges) {
997
1032
  return result;
998
1033
  }
999
1034
  function isLegacyArrayFormulaCell(cell) {
1000
- let custom = cell.custom;
1001
- if (!custom || typeof custom != "object")
1002
- return !1;
1003
- let xlsx = custom._xlsx;
1004
- return xlsx != null && typeof xlsx == "object" && xlsx.legacyArrayFormula === !0;
1035
+ return cell.ft === import_core.FormulaType.ARRAY && cell.fd !== import_core.BooleanNumber.TRUE;
1005
1036
  }
1006
- function inferDisplayPrecision(styleId, styles) {
1007
- if (typeof styleId != "string" || !styles || typeof styles != "object")
1008
- return;
1009
- let style = styles[styleId];
1010
- if (!style || typeof style != "object")
1011
- return;
1037
+ function inferDisplayPrecision(styleId, styles, resolvedStyle) {
1038
+ let pattern = resolveNumberFormatPattern(styleId, styles, resolvedStyle);
1039
+ return pattern === void 0 ? void 0 : inferFixedNumberFormatPrecision(pattern);
1040
+ }
1041
+ function resolveNumberFormatPattern(styleRef, styles, resolvedStyle) {
1042
+ let style = resolvedStyle ?? (typeof styleRef == "string" && styles && typeof styles == "object" ? styles[styleRef] : styleRef);
1043
+ if (!style || typeof style != "object") return;
1012
1044
  let numberFormat = style.n;
1013
- if (!numberFormat || typeof numberFormat != "object")
1014
- return;
1045
+ if (!numberFormat || typeof numberFormat != "object") return;
1015
1046
  let pattern = numberFormat.pattern;
1016
- return typeof pattern == "string" ? inferFixedNumberFormatPrecision(pattern) : void 0;
1047
+ return typeof pattern == "string" ? pattern : void 0;
1017
1048
  }
1018
1049
  function inferFixedNumberFormatPrecision(pattern) {
1019
1050
  let cleaned = (pattern.split(";")[0] ?? pattern).replace(/"[^"]*"/gu, "").replace(/\\./gu, "").replace(/_.|\*./gu, "");
@@ -1041,19 +1072,6 @@ function isRecord(value) {
1041
1072
  }
1042
1073
 
1043
1074
  // src/controllers/rust-engine-sync.controller.ts
1044
- var rustEngineSyncState = {
1045
- snapshotEpoch: 0,
1046
- dependencyInvalidationEpoch: 0
1047
- };
1048
- function getRustEngineSyncState() {
1049
- return { ...rustEngineSyncState };
1050
- }
1051
- function markRustSnapshotLoaded() {
1052
- rustEngineSyncState.snapshotEpoch += 1, rustEngineSyncState.dependencyInvalidationEpoch += 1;
1053
- }
1054
- function markRustFormulaDependenciesInvalidated() {
1055
- rustEngineSyncState.dependencyInvalidationEpoch += 1;
1056
- }
1057
1075
  function emitRustEngineSyncDebugEvent(event) {
1058
1076
  let hook = globalThis.__UNIVER_RUST_FORMULA_DEBUG_HOOK__;
1059
1077
  typeof hook == "function" && hook(event);
@@ -1093,6 +1111,17 @@ var RustEngineSyncController = class extends import_core2.Disposable {
1093
1111
  this._initialize();
1094
1112
  }
1095
1113
  _commandService;
1114
+ engine = new RustFormulaEngineSession();
1115
+ _syncState = { snapshotEpoch: 0, dependencyInvalidationEpoch: 0 };
1116
+ getSyncState() {
1117
+ return { ...this._syncState };
1118
+ }
1119
+ _markSnapshotLoaded() {
1120
+ this._syncState.snapshotEpoch += 1, this._syncState.dependencyInvalidationEpoch += 1;
1121
+ }
1122
+ _markDependenciesInvalidated() {
1123
+ this._syncState.dependencyInvalidationEpoch += 1;
1124
+ }
1096
1125
  _nativeReady = !1;
1097
1126
  _snapshotLoaded = !1;
1098
1127
  _projectionLoadPromise = null;
@@ -1126,7 +1155,7 @@ var RustEngineSyncController = class extends import_core2.Disposable {
1126
1155
  this._projectionDeltaBarrier = barrier;
1127
1156
  }
1128
1157
  async _loadProjection(workbooks) {
1129
- await loadNativeBinding(), this._nativeReady = !0;
1158
+ await this.engine.initialize(), this._nativeReady = !0;
1130
1159
  let serializeStartedAt = performance.now(), snapshot = serializeRuntimeWorkbookSnapshots(workbooks);
1131
1160
  this._loadSerializedSnapshot(snapshot, performance.now() - serializeStartedAt);
1132
1161
  }
@@ -1149,20 +1178,17 @@ var RustEngineSyncController = class extends import_core2.Disposable {
1149
1178
  disposeProjectionWorkbook(unitId) {
1150
1179
  if (!(!this._nativeReady || !this._snapshotLoaded))
1151
1180
  try {
1152
- disposeWorkbookOnRust(unitId), markRustFormulaDependenciesInvalidated();
1181
+ this.engine.binding.rustEngineDisposeWorkbook(unitId), this._markDependenciesInvalidated();
1153
1182
  } catch {
1154
- this._markProjectionDesynced();
1183
+ this.markProjectionDesynced();
1155
1184
  }
1156
1185
  }
1157
1186
  dispose() {
1158
- if (super.dispose(), this._pendingMutations.length = 0, this._projectionManagedTableUnits.clear(), this._projectionLoadPromise = null, this._projectionDeltaBarrier = Promise.resolve(), !this._nativeReady) {
1159
- this._snapshotLoaded = !1;
1160
- return;
1161
- }
1187
+ super.dispose(), this._pendingMutations.length = 0, this._projectionManagedTableUnits.clear(), this._projectionLoadPromise = null, this._projectionDeltaBarrier = Promise.resolve();
1162
1188
  try {
1163
- disposeAllWorkbooksOnRust();
1189
+ this.engine.dispose();
1164
1190
  } catch {
1165
- this._markProjectionDesynced();
1191
+ this.markProjectionDesynced();
1166
1192
  return;
1167
1193
  }
1168
1194
  this._nativeReady = !1, this._snapshotLoaded = !1;
@@ -1170,7 +1196,7 @@ var RustEngineSyncController = class extends import_core2.Disposable {
1170
1196
  _loadSerializedSnapshot(snapshot, serializeMs) {
1171
1197
  let precisionAsDisplayedWorkbookCount = snapshot.workbooks.filter(
1172
1198
  (workbook) => workbook.calculation?.fullPrecision === !1
1173
- ).length, displayPrecisionCellCount = countDisplayPrecisionCells(snapshot), pendingCountCoveredBySnapshot = this._pendingMutations.length, stringifyStartedAt = performance.now(), snapshotJson = JSON.stringify(snapshot), stringifyMs = performance.now() - stringifyStartedAt, snapshotBuffer = globalThis.Buffer?.from(snapshotJson), nativeStartedAt = performance.now(), nativeOutput = snapshotBuffer ? loadSnapshotBinaryOnRust(snapshotBuffer) : loadSnapshotOnRust(snapshotJson), nativeMs = performance.now() - nativeStartedAt, nativeTimings;
1199
+ ).length, displayPrecisionCellCount = countDisplayPrecisionCells(snapshot), pendingCountCoveredBySnapshot = this._pendingMutations.length, stringifyStartedAt = performance.now(), snapshotJson = JSON.stringify(snapshot), stringifyMs = performance.now() - stringifyStartedAt, snapshotBuffer = globalThis.Buffer?.from(snapshotJson), nativeStartedAt = performance.now(), nativeOutput = snapshotBuffer ? this.engine.binding.rustEngineLoadSnapshotBinary(snapshotBuffer) : this.engine.binding.rustEngineLoadSnapshot(snapshotJson), nativeMs = performance.now() - nativeStartedAt, nativeTimings;
1174
1200
  try {
1175
1201
  nativeTimings = JSON.parse(nativeOutput).timingsMs;
1176
1202
  } catch {
@@ -1189,7 +1215,7 @@ var RustEngineSyncController = class extends import_core2.Disposable {
1189
1215
  transport: snapshotBuffer ? "binary-json" : "string-json",
1190
1216
  nativeTimings
1191
1217
  }
1192
- }), this._pendingMutations.splice(0, pendingCountCoveredBySnapshot), this._snapshotLoaded = !0, markRustSnapshotLoaded(), this._flushPendingMutations();
1218
+ }), this._pendingMutations.splice(0, pendingCountCoveredBySnapshot), this._snapshotLoaded = !0, this._markSnapshotLoaded(), this._flushPendingMutations();
1193
1219
  }
1194
1220
  _queueOrSyncMutation(mutation) {
1195
1221
  if (!this._nativeReady || !this._snapshotLoaded) {
@@ -1207,9 +1233,9 @@ var RustEngineSyncController = class extends import_core2.Disposable {
1207
1233
  _syncMutation(mutation) {
1208
1234
  let totalStartedAt = performance.now(), stringifyStartedAt = performance.now(), payload = JSON.stringify(normalizeRustEngineMutation(mutation)), stringifyMs = performance.now() - stringifyStartedAt, nativeStartedAt = performance.now();
1209
1235
  try {
1210
- applyMutationOnRust(payload), isRustIncrementalDependencyMutation(mutation.id) || markRustFormulaDependenciesInvalidated();
1236
+ this.engine.binding.rustEngineApplyMutation(payload), isRustIncrementalDependencyMutation(mutation.id) || this._markDependenciesInvalidated();
1211
1237
  } catch {
1212
- this._markProjectionDesynced();
1238
+ this.markProjectionDesynced();
1213
1239
  } finally {
1214
1240
  emitRustEngineSyncDebugEvent({
1215
1241
  type: "applyMutation",
@@ -1225,7 +1251,11 @@ var RustEngineSyncController = class extends import_core2.Disposable {
1225
1251
  });
1226
1252
  }
1227
1253
  }
1228
- _markProjectionDesynced() {
1254
+ /**
1255
+ * Marks the native projection as out of sync so the next mutation reloads it.
1256
+ * Also used by the projection controller when a background projection load fails.
1257
+ */
1258
+ markProjectionDesynced() {
1229
1259
  this._nativeReady = !1, this._snapshotLoaded = !1;
1230
1260
  }
1231
1261
  _shouldSyncMutation(command, options) {
@@ -1289,7 +1319,7 @@ async function analyzeNumberFormatBatch(input) {
1289
1319
  var import_core5 = require("@univerjs/core"), import_engine_formula4 = require("@univerjs/engine-formula"), import_engine_formula5 = require("@univerjs-pro/engine-formula");
1290
1320
 
1291
1321
  // package.json
1292
- var name = "@univerjs-pro/engine-formula-rust", version = "1.0.0-rc.0";
1322
+ var name = "@univerjs-pro/engine-formula-rust", version = "1.0.1";
1293
1323
 
1294
1324
  // src/controllers/rust-same-runtime-projection.controller.ts
1295
1325
  var import_core3 = require("@univerjs/core"), import_engine_formula = require("@univerjs/engine-formula");
@@ -1318,13 +1348,16 @@ var RustSameRuntimeProjectionController = class extends import_core3.Disposable
1318
1348
  import_core3.UniverInstanceType.UNIVER_BASE
1319
1349
  ))
1320
1350
  this._rustEngineSyncController.setProjectionManagedTableUnit(base.getUnitId()), this._rememberBaseProjectionStructure(base.getSnapshot());
1321
- this._initialProjectionLoad = this._loadAllWorkbookProjections(), this.disposeWithMe(
1351
+ this._initialProjectionLoad = this._loadAllWorkbookProjections().catch(() => {
1352
+ this._rustEngineSyncController.markProjectionDesynced();
1353
+ }), this.disposeWithMe(
1322
1354
  (0, import_core3.toDisposable)(
1323
1355
  this._univerInstanceService.getTypeOfUnitAdded$(import_core3.UniverInstanceType.UNIVER_SHEET).subscribe(({ unit }) => {
1324
1356
  this._enqueueProjectionDelta(() => {
1325
1357
  this._rustEngineSyncController.upsertProjectionWorkbook({
1326
1358
  unitId: unit.getUnitId(),
1327
- snapshot: unit.getSnapshot()
1359
+ snapshot: unit.getSnapshot(),
1360
+ styleResolver: unit.getStyles()
1328
1361
  });
1329
1362
  });
1330
1363
  })
@@ -1538,7 +1571,8 @@ var RustSameRuntimeProjectionController = class extends import_core3.Disposable
1538
1571
  async _loadAllWorkbookProjections() {
1539
1572
  let workbooks = this._univerInstanceService.getAllUnitsForType(import_core3.UniverInstanceType.UNIVER_SHEET).map((workbook) => ({
1540
1573
  unitId: workbook.getUnitId(),
1541
- snapshot: workbook.getSnapshot()
1574
+ snapshot: workbook.getSnapshot(),
1575
+ styleResolver: workbook.getStyles()
1542
1576
  })), calculationData = this._formulaDataModel.getCalculateData(), formulaData = this._formulaDataModel.getFormulaData(), baseWorkbooks = this._univerInstanceService.getAllUnitsForType(import_core3.UniverInstanceType.UNIVER_BASE).map(
1543
1577
  (base) => this._createBaseWorkbookProjection(
1544
1578
  base.getUnitId(),
@@ -1854,7 +1888,7 @@ function resultBatchSheetCounts(output) {
1854
1888
  return counts;
1855
1889
  }
1856
1890
  var RustCalculateFormulaService = class extends import_core4.Disposable {
1857
- constructor(_configService, _currentConfigService, _runtimeService, _formulaDependencyGenerator, _featureCalculationManagerService, _otherFormulaManagerService, _commandService, _rustEngineSyncController, _formulaDataModel, _formulaReferenceDataService, _excelExternalReferenceModel, _superTableService) {
1891
+ constructor(_configService, _currentConfigService, _runtimeService, _formulaDependencyGenerator, _featureCalculationManagerService, _otherFormulaManagerService, _commandService, _rustEngineSyncController, _formulaDataModel, _formulaReferenceDataService, _excelExternalReferenceModel, _superTableService, _definedNamesService) {
1858
1892
  super();
1859
1893
  this._configService = _configService;
1860
1894
  this._currentConfigService = _currentConfigService;
@@ -1868,6 +1902,7 @@ var RustCalculateFormulaService = class extends import_core4.Disposable {
1868
1902
  this._formulaReferenceDataService = _formulaReferenceDataService;
1869
1903
  this._excelExternalReferenceModel = _excelExternalReferenceModel;
1870
1904
  this._superTableService = _superTableService;
1905
+ this._definedNamesService = _definedNamesService;
1871
1906
  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));
1872
1907
  }
1873
1908
  _configService;
@@ -1882,6 +1917,7 @@ var RustCalculateFormulaService = class extends import_core4.Disposable {
1882
1917
  _formulaReferenceDataService;
1883
1918
  _excelExternalReferenceModel;
1884
1919
  _superTableService;
1920
+ _definedNamesService;
1885
1921
  _executionInProgressListener$ = new import_rxjs.Subject();
1886
1922
  executionInProgressListener$ = this._executionInProgressListener$.asObservable();
1887
1923
  _executionCompleteListener$ = new import_rxjs.Subject();
@@ -1909,14 +1945,19 @@ var RustCalculateFormulaService = class extends import_core4.Disposable {
1909
1945
  this._runtimeService.setRuntimeFeatureRange(featureId, featureRange);
1910
1946
  }
1911
1947
  async execute(formulaDatasetConfig) {
1912
- this._nativeLoaded || (await loadNativeBinding(), this._nativeLoaded = !0), await this._rustEngineSyncController.waitForProjectionLoad(), this._externalFormulaDatasetConfig = formulaDatasetConfig, this._currentConfigService.load(formulaDatasetConfig), this._externalRequestGeneration++, this._externalInflight.clear(), this._externalCompleted.clear(), this._runtimeService.setFormulaExecuteStage(import_engine_formula2.FormulaExecuteStageType.START), this._executionInProgressListener$.next(this._runtimeService.getRuntimeState()), this._runtimeService.reset();
1948
+ this._nativeLoaded || (await this._rustEngineSyncController.engine.initialize(), this._nativeLoaded = !0), await this._rustEngineSyncController.waitForProjectionLoad(), this._externalFormulaDatasetConfig = formulaDatasetConfig, this._currentConfigService.load(formulaDatasetConfig), this._externalRequestGeneration++, this._externalInflight.clear(), this._externalCompleted.clear(), this._runtimeService.setFormulaExecuteStage(import_engine_formula2.FormulaExecuteStageType.START), this._executionInProgressListener$.next(this._runtimeService.getRuntimeState()), this._runtimeService.reset();
1913
1949
  let cycleReferenceCount = Math.max(formulaDatasetConfig.maxIteration || 1, 1);
1914
1950
  await this._executeLock.acquire("FORMULA_EXECUTION_LOCK", async () => {
1915
1951
  this._runtimeService.setFormulaCycleIndex(0), await this._executeStep(cycleReferenceCount) > 0 ? this._runtimeService.markedAsSuccessfullyExecuted() : this._runtimeService.markedAsNoFunctionsExecuted(), this._runtimeService.setFormulaExecuteStage(import_engine_formula2.FormulaExecuteStageType.CALCULATION_COMPLETED), this._executionInProgressListener$.next(this._runtimeService.getRuntimeState()), this._executionCompleteListener$.next(this._runtimeService.getAllRuntimeData()), this._runtimeService.reset();
1916
1952
  });
1917
1953
  }
1918
1954
  async _executeStep(maxIteration) {
1919
- let syncedFeatures = this._syncRustFormulaDependencies(void 0, !0), previousFeatureSignatures = this._featureSignatureMap(syncedFeatures), executeStartedAt = performance.now(), outputJson = executeDirtyFormulasOnRust(maxIteration, !1, !1, !0), nativeAndSerializeMs = performance.now() - executeStartedAt, parseStartedAt = performance.now(), output = JSON.parse(outputJson), calculatedNodeCount = output.calculatedNodeCount, parseMs = performance.now() - parseStartedAt;
1955
+ let syncedFeatures = this._syncRustFormulaDependencies(void 0, !0), previousFeatureSignatures = this._featureSignatureMap(syncedFeatures), executeStartedAt = performance.now(), outputJson = this._rustEngineSyncController.engine.binding.rustEngineExecuteDirtyFormulas(
1956
+ maxIteration,
1957
+ !1,
1958
+ !1,
1959
+ !0
1960
+ ), nativeAndSerializeMs = performance.now() - executeStartedAt, parseStartedAt = performance.now(), output = JSON.parse(outputJson), calculatedNodeCount = output.calculatedNodeCount, parseMs = performance.now() - parseStartedAt;
1920
1961
  output = await this._resolveExternalReferenceNeeds(output, maxIteration);
1921
1962
  let applyStartedAt = performance.now(), applyBreakdown = await this._applyRustDependencyOutput(output), applyMs = performance.now() - applyStartedAt;
1922
1963
  if (emitRustFormulaDebugEvent({
@@ -1952,7 +1993,12 @@ var RustCalculateFormulaService = class extends import_core4.Disposable {
1952
1993
  this._markRustFormulaDirty(
1953
1994
  this._currentConfigService.getDirtyData(),
1954
1995
  this._dirtyFeatureMapFor(changedFeatures)
1955
- ), executeStartedAt = performance.now(), outputJson = executeDirtyFormulasOnRust(maxIteration, !1, !1, !0), nativeAndSerializeMs = performance.now() - executeStartedAt, parseStartedAt = performance.now(), output = JSON.parse(outputJson), calculatedNodeCount += output.calculatedNodeCount, parseMs = performance.now() - parseStartedAt, output = await this._resolveExternalReferenceNeeds(output, maxIteration), applyStartedAt = performance.now(), applyBreakdown = await this._applyRustDependencyOutput(output), applyMs = performance.now() - applyStartedAt, emitRustFormulaDebugEvent({
1996
+ ), executeStartedAt = performance.now(), outputJson = this._rustEngineSyncController.engine.binding.rustEngineExecuteDirtyFormulas(
1997
+ maxIteration,
1998
+ !1,
1999
+ !1,
2000
+ !0
2001
+ ), nativeAndSerializeMs = performance.now() - executeStartedAt, parseStartedAt = performance.now(), output = JSON.parse(outputJson), calculatedNodeCount += output.calculatedNodeCount, parseMs = performance.now() - parseStartedAt, output = await this._resolveExternalReferenceNeeds(output, maxIteration), applyStartedAt = performance.now(), applyBreakdown = await this._applyRustDependencyOutput(output), applyMs = performance.now() - applyStartedAt, emitRustFormulaDebugEvent({
1956
2002
  type: "executeDirtyFormulas",
1957
2003
  payload: {
1958
2004
  calculatedNodeCount: output.calculatedNodeCount,
@@ -1997,7 +2043,14 @@ var RustCalculateFormulaService = class extends import_core4.Disposable {
1997
2043
  loadedRanges,
1998
2044
  this._superTableService
1999
2045
  ) === 0) break;
2000
- this._syncRustFormulaDependencies(), output = JSON.parse(executeDirtyFormulasOnRust(maxIteration, !1, !1, !0));
2046
+ this._syncRustFormulaDependencies(), output = JSON.parse(
2047
+ this._rustEngineSyncController.engine.binding.rustEngineExecuteDirtyFormulas(
2048
+ maxIteration,
2049
+ !1,
2050
+ !1,
2051
+ !0
2052
+ )
2053
+ );
2001
2054
  }
2002
2055
  return output;
2003
2056
  }
@@ -2171,7 +2224,7 @@ var RustCalculateFormulaService = class extends import_core4.Disposable {
2171
2224
  };
2172
2225
  }
2173
2226
  _syncRustFormulaDependencies(dirtyUnitFeatureMapOverride, includeExternalReferences = !1) {
2174
- let syncState = getRustEngineSyncState(), externalReferences = includeExternalReferences ? this._externalFormulaDatasetConfig?.externalReferences ?? {} : void 0, externalReferenceSignature = externalReferences ? JSON.stringify(externalReferences) : this._syncedExternalReferenceSignature, shouldSendExternalReferences = includeExternalReferences && (externalReferenceSignature !== "{}" || this._syncedExternalReferenceSignature !== "{}"), rebuildSheetFormulas = this._syncedSnapshotEpoch !== syncState.snapshotEpoch || this._syncedDependencyInvalidationEpoch !== syncState.dependencyInvalidationEpoch || shouldSendExternalReferences, collectStartedAt = performance.now(), state = this._collectRustFormulaDependencySyncState(), collectMs = performance.now() - collectStartedAt;
2227
+ let syncState = this._rustEngineSyncController.getSyncState(), externalReferences = includeExternalReferences ? this._externalFormulaDatasetConfig?.externalReferences ?? {} : void 0, externalReferenceSignature = externalReferences ? JSON.stringify(externalReferences) : this._syncedExternalReferenceSignature, shouldSendExternalReferences = includeExternalReferences && (externalReferenceSignature !== "{}" || this._syncedExternalReferenceSignature !== "{}"), rebuildSheetFormulas = this._syncedSnapshotEpoch !== syncState.snapshotEpoch || this._syncedDependencyInvalidationEpoch !== syncState.dependencyInvalidationEpoch || shouldSendExternalReferences, collectStartedAt = performance.now(), state = this._collectRustFormulaDependencySyncState(), collectMs = performance.now() - collectStartedAt;
2175
2228
  if (!(shouldSendExternalReferences || rebuildSheetFormulas || state.featureCalculations.length > 0 || state.otherFormulas.length > 0))
2176
2229
  return emitRustFormulaDebugEvent({
2177
2230
  type: "syncDependencies",
@@ -2195,7 +2248,7 @@ var RustCalculateFormulaService = class extends import_core4.Disposable {
2195
2248
  featureCalculations: state.featureCalculations,
2196
2249
  otherFormulas: state.otherFormulas,
2197
2250
  ...shouldSendExternalReferences ? { externalReferences } : {}
2198
- }), stringifyMs = performance.now() - stringifyStartedAt, nativeStartedAt = performance.now(), outputJson = syncRustFormulaDependenciesOnRust(inputJson), nativeMs = performance.now() - nativeStartedAt, parseStartedAt = performance.now(), output = JSON.parse(outputJson), parseMs = performance.now() - parseStartedAt;
2251
+ }), stringifyMs = performance.now() - stringifyStartedAt, nativeStartedAt = performance.now(), outputJson = this._rustEngineSyncController.engine.binding.rustEngineSyncFormulaDependencies(inputJson), nativeMs = performance.now() - nativeStartedAt, parseStartedAt = performance.now(), output = JSON.parse(outputJson), parseMs = performance.now() - parseStartedAt;
2199
2252
  return emitRustFormulaDebugEvent({
2200
2253
  type: "syncDependencies",
2201
2254
  payload: {
@@ -2217,7 +2270,7 @@ var RustCalculateFormulaService = class extends import_core4.Disposable {
2217
2270
  }
2218
2271
  _syncRustFormulaDependencyDefinitions() {
2219
2272
  let state = this._collectRustFormulaDependencySyncState();
2220
- return syncRustFormulaDependenciesOnRust(
2273
+ return this._rustEngineSyncController.engine.binding.rustEngineSyncFormulaDependencies(
2221
2274
  JSON.stringify({
2222
2275
  rebuildSheetFormulas: !1,
2223
2276
  featureCalculations: state.featureCalculations,
@@ -2292,7 +2345,7 @@ var RustCalculateFormulaService = class extends import_core4.Disposable {
2292
2345
  dirtyUnitOtherFormulaMap: dirtyData.dirtyUnitOtherFormulaMap,
2293
2346
  dirtyNameMap: dirtyData.dirtyNameMap,
2294
2347
  dirtyDefinedNameMap: dirtyData.dirtyDefinedNameMap
2295
- }, stringifyStartedAt = performance.now(), inputJson = JSON.stringify(payload), stringifyMs = performance.now() - stringifyStartedAt, nativeStartedAt = performance.now(), outputJson = markRustFormulaDirtyOnRust(inputJson), nativeMs = performance.now() - nativeStartedAt, rustTimings;
2348
+ }, stringifyStartedAt = performance.now(), inputJson = JSON.stringify(payload), stringifyMs = performance.now() - stringifyStartedAt, nativeStartedAt = performance.now(), outputJson = this._rustEngineSyncController.engine.binding.rustEngineMarkFormulaDirty(inputJson), nativeMs = performance.now() - nativeStartedAt, rustTimings;
2296
2349
  try {
2297
2350
  rustTimings = JSON.parse(outputJson).timings;
2298
2351
  } catch {
@@ -2379,16 +2432,23 @@ var RustCalculateFormulaService = class extends import_core4.Disposable {
2379
2432
  if (!unitData) return result;
2380
2433
  for (let [unitId, sheets] of Object.entries(unitData)) {
2381
2434
  result[unitId] = {};
2435
+ let styles = this._currentConfigService.getUnitStylesData()[unitId], sheetNames = Object.fromEntries(
2436
+ Object.entries(this._currentConfigService.getSheetNameMap()[unitId] ?? {}).map(([name2, id]) => [
2437
+ id,
2438
+ name2
2439
+ ])
2440
+ );
2382
2441
  for (let [sheetId, sheet] of Object.entries(sheets))
2383
2442
  result[unitId][sheetId] = {
2384
- cellData: this._serializeCellData(sheet.cellData),
2443
+ name: sheetNames[sheetId],
2444
+ cellData: this._serializeCellData(sheet.cellData, styles),
2385
2445
  rowCount: sheet.rowCount ?? 0,
2386
2446
  columnCount: sheet.columnCount ?? 0
2387
2447
  };
2388
2448
  }
2389
2449
  return result;
2390
2450
  }
2391
- _serializeCellData(cellData) {
2451
+ _serializeCellData(cellData, styles) {
2392
2452
  let result = {};
2393
2453
  if (!cellData || typeof cellData != "object") return result;
2394
2454
  let data = typeof cellData.getMatrix == "function" ? cellData.getMatrix() : cellData;
@@ -2398,13 +2458,23 @@ var RustCalculateFormulaService = class extends import_core4.Disposable {
2398
2458
  result[row] = {};
2399
2459
  for (let [colStr, cell] of Object.entries(cols)) {
2400
2460
  let col = Number(colStr);
2401
- Number.isFinite(col) && (result[row][col] = {
2461
+ if (!Number.isFinite(col))
2462
+ continue;
2463
+ result[row][col] = {
2402
2464
  v: cell?.v ?? null,
2403
2465
  t: cell?.t ?? void 0,
2404
2466
  p: cell?.p ?? void 0,
2405
2467
  f: cell?.f ?? void 0,
2406
2468
  s: cell?.s ?? void 0
2407
- });
2469
+ };
2470
+ let style = styles?.getStyleByCell(cell);
2471
+ if (style && typeof style == "object") {
2472
+ let numberFormat = style.n;
2473
+ if (numberFormat && typeof numberFormat == "object") {
2474
+ let pattern = numberFormat.pattern;
2475
+ typeof pattern == "string" && (result[row][col].numberFormat = pattern);
2476
+ }
2477
+ }
2408
2478
  }
2409
2479
  }
2410
2480
  }
@@ -2413,7 +2483,9 @@ var RustCalculateFormulaService = class extends import_core4.Disposable {
2413
2483
  _applyRustOutput(_output) {
2414
2484
  }
2415
2485
  async _applyRustDependencyOutput(output) {
2416
- let convertStartedAt = performance.now(), patch = rustExecutionOutputToFormulaCalculationPatch(output), convertMs = performance.now() - convertStartedAt, commandStartedAt = performance.now();
2486
+ let convertStartedAt = performance.now(), patch = rustExecutionOutputToFormulaCalculationPatch(output);
2487
+ this._mergeRuntimeUnitData(patch.unitData);
2488
+ let convertMs = performance.now() - convertStartedAt, commandStartedAt = performance.now();
2417
2489
  return (patch.arrayFormulaRange || patch.arrayFormulaCellData) && (this._formulaDataModel.setArrayFormulaRange(patch.arrayFormulaRange ?? {}), this._formulaDataModel.setArrayFormulaCellData(patch.arrayFormulaCellData ?? {}), await this._commandService.executeCommand(
2418
2490
  import_engine_formula2.SetArrayFormulaDataMutation.id,
2419
2491
  {
@@ -2440,8 +2512,22 @@ var RustCalculateFormulaService = class extends import_core4.Disposable {
2440
2512
  commandMs: performance.now() - commandStartedAt
2441
2513
  };
2442
2514
  }
2515
+ _mergeRuntimeUnitData(unitData) {
2516
+ let runtimeUnitData = this._runtimeService.getUnitData();
2517
+ Object.entries(unitData).forEach(([unitId, sheetMap]) => {
2518
+ if (!sheetMap) return;
2519
+ let runtimeSheetMap = runtimeUnitData[unitId] ??= {};
2520
+ Object.entries(sheetMap).forEach(([sheetId, cellData]) => {
2521
+ if (!cellData) return;
2522
+ let runtimeMatrix = runtimeSheetMap[sheetId] ??= new import_core4.ObjectMatrix();
2523
+ new import_core4.ObjectMatrix(cellData).forValue((row, column, cell) => {
2524
+ runtimeMatrix.setValue(row, column, cell);
2525
+ });
2526
+ });
2527
+ });
2528
+ }
2443
2529
  async calculate(formulaString) {
2444
- this._nativeLoaded || (await loadNativeBinding(), this._nativeLoaded = !0);
2530
+ this._nativeLoaded || (await this._rustEngineSyncController.engine.initialize(), this._nativeLoaded = !0);
2445
2531
  let unitId = "__rust_formula_calculate__", sheetId = "__sheet__", input = {
2446
2532
  config: { maxIteration: 1, intervalCount: DEFAULT_INTERVAL_COUNT },
2447
2533
  formulaData: {
@@ -2466,23 +2552,35 @@ var RustCalculateFormulaService = class extends import_core4.Disposable {
2466
2552
  return JSON.parse(executeOnRust(JSON.stringify(input))).runtimeData?.[unitId]?.[sheetId]?.[0]?.[0] ?? null;
2467
2553
  }
2468
2554
  async executeFormulas(formulas, rowData) {
2469
- this._nativeLoaded || (await loadNativeBinding(), this._nativeLoaded = !0), this._currentConfigService.loadDataLite(rowData);
2470
- let unitData = this._currentConfigService.getUnitData(), formulaData = this._formulaStringMapToFormulaData(formulas), input = {
2555
+ this._nativeLoaded || (await this._rustEngineSyncController.engine.initialize(), this._nativeLoaded = !0), this._currentConfigService.loadDataLite(rowData);
2556
+ let unitData = this._currentConfigService.getUnitData(), definedNames = {};
2557
+ for (let [unitId, names] of Object.entries(this._definedNamesService.getAllDefinedNames()))
2558
+ for (let [id, name2] of Object.entries(names))
2559
+ definedNames[JSON.stringify([unitId, id])] = {
2560
+ unitId,
2561
+ localSheetId: name2.localSheetId === "AllDefaultWorkbook" ? void 0 : name2.localSheetId,
2562
+ name: name2.name,
2563
+ formula: name2.formulaOrRefString
2564
+ };
2565
+ let input = {
2471
2566
  config: { maxIteration: 1, intervalCount: DEFAULT_INTERVAL_COUNT },
2472
- formulaData,
2567
+ formulaData: {},
2568
+ queryFormulas: this._formulaStringMapToQueryData(formulas),
2473
2569
  unitData: this._serializeUnitData(unitData),
2474
2570
  dirtyRanges: [],
2475
- definedNames: {}
2571
+ definedNames
2476
2572
  }, output = JSON.parse(executeOnRust(JSON.stringify(input)));
2573
+ if (!output.queryResults)
2574
+ throw new Error("Native formula binding does not support independent formula queries");
2477
2575
  return this._formulaExecutionOutputToResultMap(formulas, output);
2478
2576
  }
2479
2577
  async getAllDependencyJson(_rowData) {
2480
- this._nativeLoaded || (await loadNativeBinding(), this._nativeLoaded = !0), this._syncRustFormulaDependencyDefinitions();
2578
+ this._nativeLoaded || (await this._rustEngineSyncController.engine.initialize(), this._nativeLoaded = !0), this._syncRustFormulaDependencyDefinitions();
2481
2579
  let graph = this._getRustDependencyGraph(), inspect = this._getRustInspectGraph();
2482
2580
  return this._rustAllDependencyJson(graph, inspect);
2483
2581
  }
2484
2582
  async getCellDependencyJson(unitId, sheetId, row, column, _rowData) {
2485
- this._nativeLoaded || (await loadNativeBinding(), this._nativeLoaded = !0), this._syncRustFormulaDependencyDefinitions();
2583
+ this._nativeLoaded || (await this._rustEngineSyncController.engine.initialize(), this._nativeLoaded = !0), this._syncRustFormulaDependencyDefinitions();
2486
2584
  let graph = this._getRustDependencyGraph(unitId), all = this._rustGraphDependencyJson(graph), current = all.find(
2487
2585
  (item) => item.unitId === unitId && item.subUnitId === sheetId && item.row === row && item.column === column
2488
2586
  );
@@ -2496,16 +2594,18 @@ var RustCalculateFormulaService = class extends import_core4.Disposable {
2496
2594
  };
2497
2595
  }
2498
2596
  async getRangeDependents(unitRanges) {
2499
- this._nativeLoaded || (await loadNativeBinding(), this._nativeLoaded = !0), this._syncRustFormulaDependencyDefinitions();
2597
+ this._nativeLoaded || (await this._rustEngineSyncController.engine.initialize(), this._nativeLoaded = !0), this._syncRustFormulaDependencyDefinitions();
2500
2598
  let graph = this._getRustDependencyGraph(), graphItems = this._rustGraphDependencyJson(graph), graphByCell = this._rustDependencyJsonByCell(graphItems), dirty = JSON.parse(
2501
- getRustDirtyDependenciesOnRust(JSON.stringify(this._serializeUnitRanges(unitRanges)))
2599
+ this._rustEngineSyncController.engine.binding.rustEngineGetDirtyDependencies(
2600
+ JSON.stringify(this._serializeUnitRanges(unitRanges))
2601
+ )
2502
2602
  );
2503
2603
  return this._uniqueDependencyJson(
2504
2604
  (dirty.direct ?? dirty.affected ?? []).map((cell) => graphByCell.get(this._cellKey(cell))).filter(Boolean)
2505
2605
  );
2506
2606
  }
2507
2607
  async getInRangeFormulas(unitRanges) {
2508
- return this._nativeLoaded || (await loadNativeBinding(), this._nativeLoaded = !0), this._syncRustFormulaDependencyDefinitions(), this._rustGraphDependencyJson(this._getRustDependencyGraph()).filter(
2608
+ return this._nativeLoaded || (await this._rustEngineSyncController.engine.initialize(), this._nativeLoaded = !0), this._syncRustFormulaDependencyDefinitions(), this._rustGraphDependencyJson(this._getRustDependencyGraph()).filter(
2509
2609
  (item) => this._cellInUnitRanges(item.unitId, item.subUnitId, item.row, item.column, unitRanges)
2510
2610
  );
2511
2611
  }
@@ -2516,7 +2616,7 @@ var RustCalculateFormulaService = class extends import_core4.Disposable {
2516
2616
  ]);
2517
2617
  return { dependents, inRanges };
2518
2618
  }
2519
- _formulaStringMapToFormulaData(formulas) {
2619
+ _formulaStringMapToQueryData(formulas) {
2520
2620
  let formulaData = {};
2521
2621
  return Object.entries(formulas).forEach(([unitId, sheetMap]) => {
2522
2622
  sheetMap && (formulaData[unitId] = {}, Object.entries(sheetMap).forEach(([sheetId, rowMap]) => {
@@ -2524,8 +2624,7 @@ var RustCalculateFormulaService = class extends import_core4.Disposable {
2524
2624
  if (!colMap) return;
2525
2625
  let row = Number(rowKey);
2526
2626
  formulaData[unitId][sheetId][row] = {}, Object.entries(colMap).forEach(([colKey, formulaList]) => {
2527
- let formula = Array.isArray(formulaList) ? formulaList[0] : void 0;
2528
- typeof formula == "string" && (formulaData[unitId][sheetId][row][Number(colKey)] = formula);
2627
+ Array.isArray(formulaList) && (formulaData[unitId][sheetId][row][Number(colKey)] = formulaList);
2529
2628
  });
2530
2629
  }));
2531
2630
  }));
@@ -2539,20 +2638,27 @@ var RustCalculateFormulaService = class extends import_core4.Disposable {
2539
2638
  if (!colMap) return;
2540
2639
  let row = Number(rowKey);
2541
2640
  result[unitId][sheetId][row] = {}, Object.entries(colMap).forEach(([colKey, formulaList]) => {
2542
- let col = Number(colKey), formulasForCell = Array.isArray(formulaList) ? formulaList : [], value = normalizeFormulaResultValue(
2543
- output.runtimeData?.[unitId]?.[sheetId]?.[row]?.[col]
2544
- );
2545
- result[unitId][sheetId][row][col] = formulasForCell.map((formula) => ({ formula, value }));
2641
+ let col = Number(colKey), formulasForCell = Array.isArray(formulaList) ? formulaList : [];
2642
+ result[unitId][sheetId][row][col] = formulasForCell.map((formula, index) => ({
2643
+ formula,
2644
+ value: normalizeFormulaResultValue(
2645
+ output.queryResults?.[unitId]?.[sheetId]?.[row]?.[col]?.[index]?.value
2646
+ )
2647
+ }));
2546
2648
  });
2547
2649
  }));
2548
2650
  }));
2549
2651
  }), result;
2550
2652
  }
2551
2653
  _getRustDependencyGraph(unitId) {
2552
- return JSON.parse(buildRustDependencyGraphOnRust(unitId));
2654
+ return JSON.parse(
2655
+ this._rustEngineSyncController.engine.binding.rustEngineBuildDependencyGraph(unitId)
2656
+ );
2553
2657
  }
2554
2658
  _getRustInspectGraph() {
2555
- return JSON.parse(inspectRustFormulaDependencyGraphOnRust());
2659
+ return JSON.parse(
2660
+ this._rustEngineSyncController.engine.binding.rustEngineInspectFormulaDependencyGraph()
2661
+ );
2556
2662
  }
2557
2663
  _rustAllDependencyJson(graph, inspect) {
2558
2664
  let cellItems = this._rustGraphDependencyJson(graph), seen = new Set(cellItems.map((item) => item.treeId)), nonCellItems = (inspect.nodes ?? []).filter((item) => item.node.nodeType !== "cellFormula" && !seen.has(item.index)).map((item) => this._rustFormulaNodeToDependencyJson(item.index, item.node));
@@ -2661,7 +2767,8 @@ var RustCalculateFormulaService = class extends import_core4.Disposable {
2661
2767
  import_engine_formula2.FormulaDataModel,
2662
2768
  import_engine_formula3.IFormulaReferenceDataService,
2663
2769
  import_engine_formula3.ExternalReferenceModel,
2664
- import_engine_formula2.ISuperTableService
2770
+ import_engine_formula2.ISuperTableService,
2771
+ import_engine_formula2.IDefinedNamesService
2665
2772
  ]);
2666
2773
  function createRustProductExternalSyntheticUnitId(hostUnitId, referenceId) {
2667
2774
  return `external:product:${encodeURIComponent(hostUnitId)}:${encodeURIComponent(referenceId)}`;
@@ -2758,6 +2865,7 @@ async function materializeWorkbookSnapshot(workbook, unitID, rev, dirtyInput) {
2758
2865
  RUST_UPSERT_REFERENCE_DATA_MUTATION_ID,
2759
2866
  RustCalculateFormulaService,
2760
2867
  RustEngineSyncController,
2868
+ RustFormulaEngineSession,
2761
2869
  RustFormulaProjectionService,
2762
2870
  UniverRustFormulaEnginePlugin,
2763
2871
  analyzeNumberFormatBatch,