@univerjs-pro/engine-formula-rust 1.0.0-beta.2

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.
@@ -0,0 +1,2775 @@
1
+ // src/binding.ts
2
+ import { createRequire } from "node:module";
3
+ import process from "node:process";
4
+ var nativeBinding = null, nativeBindingSource = null, nodeRequire = createRequire(import.meta.url);
5
+ function getNativeBindingSource() {
6
+ return nativeBindingSource;
7
+ }
8
+ function formatBindingLoadError(error) {
9
+ return error instanceof Error ? error.message : String(error);
10
+ }
11
+ function createBindingLoadFailure(errors) {
12
+ return new Error(
13
+ [
14
+ "Failed to load native formula engine binding.",
15
+ `platform=${process.platform}`,
16
+ `arch=${process.arch}`,
17
+ "expected npm package=@univerjs-pro/engine-formula-rust-binding",
18
+ "attempted paths:",
19
+ ...errors.map((item) => `- ${item}`)
20
+ ].join(`
21
+ `)
22
+ );
23
+ }
24
+ async function loadNativeBinding() {
25
+ if (nativeBinding)
26
+ return nativeBinding;
27
+ if (typeof process < "u" && process.versions?.node) {
28
+ let errors = [];
29
+ try {
30
+ return nativeBinding = nodeRequire("@univerjs-pro/engine-formula-rust-binding"), nativeBindingSource = "@univerjs-pro/engine-formula-rust-binding", nativeBinding;
31
+ } catch (error) {
32
+ errors.push(`@univerjs-pro/engine-formula-rust-binding: ${formatBindingLoadError(error)}`);
33
+ }
34
+ throw createBindingLoadFailure(errors);
35
+ } else
36
+ throw new Error("WASM binding not yet implemented");
37
+ }
38
+ function executeOnRust(inputJson) {
39
+ if (!nativeBinding)
40
+ throw new Error("Native binding not loaded. Call loadNativeBinding() first.");
41
+ return nativeBinding.formulaEngineExecute(inputJson);
42
+ }
43
+ function buildLexerTreeOnRust(formula, transformSuffix = !0) {
44
+ if (!nativeBinding)
45
+ throw new Error("Native binding not loaded. Call loadNativeBinding() first.");
46
+ return nativeBinding.formulaLexerTreeBuild(formula, transformSuffix);
47
+ }
48
+ function buildSequenceNodesOnRust(formula) {
49
+ if (!nativeBinding)
50
+ throw new Error("Native binding not loaded. Call loadNativeBinding() first.");
51
+ return nativeBinding.formulaSequenceNodesBuild(formula);
52
+ }
53
+ function checkIfAddBracketOnRust(formula) {
54
+ if (!nativeBinding)
55
+ throw new Error("Native binding not loaded. Call loadNativeBinding() first.");
56
+ return nativeBinding.formulaCheckIfAddBracket(formula);
57
+ }
58
+ function formatNumberBatchOnRust(inputJson) {
59
+ if (!nativeBinding)
60
+ throw new Error("Native binding not loaded. Call loadNativeBinding() first.");
61
+ return nativeBinding.rustNumfmtFormatBatch(inputJson);
62
+ }
63
+ function parseNumberFormatInputBatchOnRust(inputJson) {
64
+ if (!nativeBinding)
65
+ throw new Error("Native binding not loaded. Call loadNativeBinding() first.");
66
+ return nativeBinding.rustNumfmtParseBatch(inputJson);
67
+ }
68
+ function parseNumberFormatMatrixBatchOnRust(inputJson) {
69
+ if (!nativeBinding)
70
+ throw new Error("Native binding not loaded. Call loadNativeBinding() first.");
71
+ return nativeBinding.rustNumfmtParseMatrixBatch(inputJson);
72
+ }
73
+ function analyzeNumberFormatBatchOnRust(inputJson) {
74
+ if (!nativeBinding)
75
+ throw new Error("Native binding not loaded. Call loadNativeBinding() first.");
76
+ return nativeBinding.rustNumfmtAnalyzeBatch(inputJson);
77
+ }
78
+ function loadSnapshotOnRust(snapshotJson) {
79
+ if (!nativeBinding)
80
+ throw new Error("Native binding not loaded. Call loadNativeBinding() first.");
81
+ return nativeBinding.rustEngineLoadSnapshot(snapshotJson);
82
+ }
83
+ function loadSnapshotBinaryOnRust(snapshotBytes) {
84
+ if (!nativeBinding)
85
+ throw new Error("Native binding not loaded. Call loadNativeBinding() first.");
86
+ return nativeBinding.rustEngineLoadSnapshotBinary(snapshotBytes);
87
+ }
88
+ function applyMutationOnRust(mutationJson) {
89
+ if (!nativeBinding)
90
+ throw new Error("Native binding not loaded. Call loadNativeBinding() first.");
91
+ return nativeBinding.rustEngineApplyMutation(mutationJson);
92
+ }
93
+ function disposeWorkbookOnRust(unitId) {
94
+ if (!nativeBinding)
95
+ throw new Error("Native binding not loaded. Call loadNativeBinding() first.");
96
+ return nativeBinding.rustEngineDisposeWorkbook(unitId);
97
+ }
98
+ function disposeAllWorkbooksOnRust() {
99
+ if (!nativeBinding)
100
+ throw new Error("Native binding not loaded. Call loadNativeBinding() first.");
101
+ return nativeBinding.rustEngineDisposeAllWorkbooks();
102
+ }
103
+ function getRustModelStats() {
104
+ if (!nativeBinding)
105
+ throw new Error("Native binding not loaded. Call loadNativeBinding() first.");
106
+ return nativeBinding.rustEngineGetModelStats();
107
+ }
108
+ function getRustCellOnRust(unitId, sheetId, row, col) {
109
+ if (!nativeBinding)
110
+ throw new Error("Native binding not loaded. Call loadNativeBinding() first.");
111
+ return nativeBinding.rustEngineGetCell(unitId, sheetId, row, col);
112
+ }
113
+ function getRustSheetStateOnRust(unitId, sheetId) {
114
+ if (!nativeBinding)
115
+ throw new Error("Native binding not loaded. Call loadNativeBinding() first.");
116
+ return nativeBinding.rustEngineGetSheetState(unitId, sheetId);
117
+ }
118
+ function getRustFormulaDataOnRust(unitId) {
119
+ if (!nativeBinding)
120
+ throw new Error("Native binding not loaded. Call loadNativeBinding() first.");
121
+ return nativeBinding.rustEngineGetFormulaData(unitId);
122
+ }
123
+ function buildRustDependencyGraphOnRust(unitId) {
124
+ if (!nativeBinding)
125
+ throw new Error("Native binding not loaded. Call loadNativeBinding() first.");
126
+ return nativeBinding.rustEngineBuildDependencyGraph(unitId);
127
+ }
128
+ function getRustDirtyDependenciesOnRust(dirtyRangesJson, unitId) {
129
+ if (!nativeBinding)
130
+ throw new Error("Native binding not loaded. Call loadNativeBinding() first.");
131
+ return nativeBinding.rustEngineGetDirtyDependencies(dirtyRangesJson, unitId);
132
+ }
133
+ function syncRustFormulaDependenciesOnRust(inputJson) {
134
+ if (!nativeBinding)
135
+ throw new Error("Native binding not loaded. Call loadNativeBinding() first.");
136
+ return nativeBinding.rustEngineSyncFormulaDependencies(inputJson);
137
+ }
138
+ function inspectRustFormulaDependencyGraphOnRust() {
139
+ if (!nativeBinding)
140
+ throw new Error("Native binding not loaded. Call loadNativeBinding() first.");
141
+ return nativeBinding.rustEngineInspectFormulaDependencyGraph();
142
+ }
143
+ function markRustFormulaDirtyOnRust(inputJson) {
144
+ if (!nativeBinding)
145
+ throw new Error("Native binding not loaded. Call loadNativeBinding() first.");
146
+ return nativeBinding.rustEngineMarkFormulaDirty(inputJson);
147
+ }
148
+ function clearRustFormulaDependenciesOnRust(inputJson) {
149
+ if (!nativeBinding)
150
+ throw new Error("Native binding not loaded. Call loadNativeBinding() first.");
151
+ return nativeBinding.rustEngineClearFormulaDependencies(inputJson);
152
+ }
153
+ function clearRustFormulaDirtyOnRust() {
154
+ if (!nativeBinding)
155
+ throw new Error("Native binding not loaded. Call loadNativeBinding() first.");
156
+ return nativeBinding.rustEngineClearFormulaDirty();
157
+ }
158
+ function executeDirtyFormulasOnRust(maxIteration, includeCalculatedNodes, includeRuntimeData, includeResultBatches) {
159
+ if (!nativeBinding)
160
+ throw new Error("Native binding not loaded. Call loadNativeBinding() first.");
161
+ return nativeBinding.rustEngineExecuteDirtyFormulas(
162
+ maxIteration,
163
+ includeCalculatedNodes,
164
+ includeRuntimeData,
165
+ includeResultBatches
166
+ );
167
+ }
168
+ function materializeWorkbookSnapshotOnRust(workbookJson, unitId, rev, dirtyInputJson) {
169
+ if (!nativeBinding)
170
+ throw new Error("Native binding not loaded. Call loadNativeBinding() first.");
171
+ return nativeBinding.rustMaterializeWorkbookSnapshot(workbookJson, unitId, rev, dirtyInputJson);
172
+ }
173
+
174
+ // src/controllers/rust-engine-sync.controller.ts
175
+ import { CommandType, Disposable, ICommandService, setDependencies } from "@univerjs/core";
176
+
177
+ // src/services/rust-formula-projection.service.ts
178
+ import {
179
+ CellValueType,
180
+ ObjectMatrix
181
+ } from "@univerjs/core";
182
+ 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([
183
+ "sheet.mutation.set-range-values",
184
+ "sheet.mutation.insert-row",
185
+ "sheet.mutation.insert-col",
186
+ "sheet.mutation.insert-sheet",
187
+ "sheet.mutation.move-range",
188
+ "sheet.mutation.move-rows",
189
+ "sheet.mutation.move-columns",
190
+ "sheet.mutation.move-cols",
191
+ "sheet.mutation.remove-col",
192
+ "sheet.mutation.remove-rows",
193
+ "sheet.mutation.remove-sheet",
194
+ "sheet.mutation.set-col-hidden",
195
+ "sheet.mutation.set-col-visible",
196
+ "sheet.mutation.set-row-hidden",
197
+ "sheet.mutation.set-row-visible",
198
+ "sheet.mutation.set-worksheet-name",
199
+ "sheet.mutation.reorder-range",
200
+ "sheet.mutation.set-worksheet-row-count",
201
+ "sheet.mutation.set-worksheet-column-count",
202
+ "formula.mutation.set-array-formula-data",
203
+ "formula.mutation.set-defined-name",
204
+ "formula.mutation.set-feature-calculation",
205
+ "formula.mutation.set-formula-data",
206
+ "formula.mutation.set-image-formula-data",
207
+ "formula.mutation.set-other-formula",
208
+ "formula.mutation.set-super-table",
209
+ RUST_SET_SUPER_TABLES_MUTATION_ID,
210
+ "formula.mutation.set-super-table-option",
211
+ "formula.mutation.remove-defined-name",
212
+ "formula.mutation.remove-feature-calculation",
213
+ "formula.mutation.remove-other-formula",
214
+ "formula.mutation.remove-super-table",
215
+ RUST_UPSERT_PROJECTION_WORKBOOK_MUTATION_ID
216
+ ]), RUST_INCREMENTAL_DEPENDENCY_MUTATIONS = /* @__PURE__ */ new Set(["sheet.mutation.set-range-values"]);
217
+ function isRustFormulaRelevantMutation(id) {
218
+ return RUST_FORMULA_RELEVANT_MUTATIONS.has(id);
219
+ }
220
+ function isRustIncrementalDependencyMutation(id) {
221
+ return RUST_INCREMENTAL_DEPENDENCY_MUTATIONS.has(id);
222
+ }
223
+ function createReferenceDataUpsertMutations(config, needs, tableService) {
224
+ let unitNameMap = config.unitNameMap, grouped = /* @__PURE__ */ new Map();
225
+ for (let need of needs) {
226
+ let key = `${need.unitId}\0${need.sheetId}`, group = grouped.get(key) ?? [];
227
+ group.push(need), grouped.set(key, group);
228
+ }
229
+ return Array.from(grouped.values()).flatMap((group) => {
230
+ let first = group[0], dataUnitId = first.dataUnitId ?? first.unitId, unitData = config.allUnitData?.[dataUnitId], sheetNameMap = config.unitSheetNameMap?.[dataUnitId] ?? {}, resolvedSheetId = unitData?.[first.sheetId] ? first.sheetId : sheetNameMap[first.sheetId] ?? first.sheetId, sheet = unitData?.[resolvedSheetId];
231
+ if (!sheet)
232
+ return [];
233
+ let sheetName = Object.entries(sheetNameMap).find(([, sheetId]) => sheetId === resolvedSheetId)?.[0] ?? first.sheetId, ranges = group.map(({ range }) => range), tables = Object.fromEntries(
234
+ group.flatMap(({ tableName }) => tableName ? [tableName] : []).filter((tableName, index, names) => names.indexOf(tableName) === index).flatMap((tableName) => {
235
+ let table = tableService?.getTable(dataUnitId, tableName), serialized = isRecord(table) ? serializeRuntimeSuperTable(table) : null;
236
+ return serialized ? [[tableName, serialized]] : [];
237
+ })
238
+ );
239
+ return [
240
+ {
241
+ id: RUST_UPSERT_REFERENCE_DATA_MUTATION_ID,
242
+ params: {
243
+ unitId: first.unitId,
244
+ name: unitNameMap?.[dataUnitId]?.name,
245
+ sheet: {
246
+ name: sheetName,
247
+ sheetId: resolvedSheetId,
248
+ rowCount: sheet.rowCount,
249
+ columnCount: sheet.columnCount,
250
+ coverage: ranges,
251
+ cellData: serializeCellDataInRanges(sheet.cellData, ranges)
252
+ },
253
+ ...Object.keys(tables).length > 0 ? { tables } : {}
254
+ },
255
+ dirtyRanges: ranges.map((range) => ({
256
+ unitId: first.unitId,
257
+ sheetId: resolvedSheetId,
258
+ range
259
+ }))
260
+ }
261
+ ];
262
+ });
263
+ }
264
+ function serializeRuntimeWorkbookSnapshots(workbooks) {
265
+ return {
266
+ workbooks: workbooks.map((workbook) => serializeRuntimeWorkbookSnapshot(workbook))
267
+ };
268
+ }
269
+ function serializeRuntimeWorkbookSnapshot(input) {
270
+ let { snapshot } = input, sheetOrder = snapshot.sheetOrder?.length > 0 ? snapshot.sheetOrder : Object.keys(snapshot.sheets ?? {}), calculation = serializeCalculation(snapshot), precisionAsDisplayed = calculation?.fullPrecision === !1, sheets = sheetOrder.map(
271
+ (sheetId) => serializeSheetSnapshot(sheetId, snapshot.sheets?.[sheetId], snapshot.styles, precisionAsDisplayed)
272
+ ).filter((sheet) => sheet != null);
273
+ return {
274
+ unitId: input.unitId || snapshot.id,
275
+ name: snapshot.name,
276
+ sheets,
277
+ ...calculation ? { calculation } : {},
278
+ resources: serializeResources(snapshot),
279
+ definedNames: serializeDefinedNames(input.definedNames, snapshot),
280
+ externalLinks: serializeExternalLinks(snapshot),
281
+ tables: serializeTables(snapshot)
282
+ };
283
+ }
284
+ function createProjectionWorkbookUpsertMutation(input) {
285
+ return {
286
+ id: RUST_UPSERT_PROJECTION_WORKBOOK_MUTATION_ID,
287
+ params: {
288
+ workbook: serializeRuntimeWorkbookSnapshot(input)
289
+ },
290
+ dirtyRanges: []
291
+ };
292
+ }
293
+ function rustExecutionOutputToFormulaCalculationPatch(output) {
294
+ let arrayFormulaOutput = output;
295
+ return {
296
+ unitData: output.resultBatches?.length ? resultBatchesToUnitData(output.resultBatches) : runtimeDataToUnitData(output.runtimeData),
297
+ unitOtherData: otherFormulaDataToUnitOtherData(output.otherFormulaData),
298
+ ...arrayFormulaOutput.arrayFormulaRange ? { arrayFormulaRange: arrayFormulaOutput.arrayFormulaRange } : {},
299
+ ...arrayFormulaOutput.arrayFormulaCellData ? { arrayFormulaCellData: arrayFormulaCellDataToUnitData(arrayFormulaOutput.arrayFormulaCellData) } : {},
300
+ errors: output.errors?.map((error) => ({
301
+ code: "RUST_FORMULA_CALCULATION_ERROR",
302
+ unitId: error.unitId,
303
+ sheetId: error.sheetId,
304
+ row: error.row,
305
+ column: error.column,
306
+ message: error.message
307
+ }))
308
+ };
309
+ }
310
+ function arrayFormulaCellDataToUnitData(input) {
311
+ let result = {};
312
+ for (let [unitId, sheetMap] of Object.entries(input)) {
313
+ let unitData = {};
314
+ result[unitId] = unitData;
315
+ for (let [sheetId, rowMap] of Object.entries(sheetMap)) {
316
+ let sheetData = {};
317
+ unitData[sheetId] = sheetData;
318
+ for (let [rowKey, colMap] of Object.entries(rowMap)) {
319
+ let rowData = {};
320
+ sheetData[Number(rowKey)] = rowData;
321
+ for (let [colKey, value] of Object.entries(colMap))
322
+ rowData[Number(colKey)] = cellDataFromRustValue(value);
323
+ }
324
+ }
325
+ }
326
+ return result;
327
+ }
328
+ function otherFormulaDataToUnitOtherData(otherFormulaData) {
329
+ let unitOtherData = {};
330
+ return Object.entries(otherFormulaData ?? {}).forEach(([unitId, sheetMap]) => {
331
+ if (!sheetMap) return;
332
+ let unitSheetData = {};
333
+ unitOtherData[unitId] = unitSheetData, Object.entries(sheetMap).forEach(([sheetId, formulaMap]) => {
334
+ if (!formulaMap) return;
335
+ let sheetData = {};
336
+ unitSheetData[sheetId] = sheetData, Object.entries(formulaMap).forEach(([formulaId, rowMap]) => {
337
+ if (!rowMap) return;
338
+ let formulaData = {};
339
+ sheetData[formulaId] = formulaData, Object.entries(rowMap).forEach(([rowKey, colMap]) => {
340
+ if (!colMap) return;
341
+ let row = Number(rowKey), rowData = {};
342
+ formulaData[row] = rowData, Object.entries(colMap).forEach(([colKey, value]) => {
343
+ rowData[Number(colKey)] = [[cellDataFromRustValue(value)]];
344
+ });
345
+ });
346
+ });
347
+ });
348
+ }), unitOtherData;
349
+ }
350
+ function createFormulaProjectionDesyncSignal(reason, error, mutationId) {
351
+ return {
352
+ reason,
353
+ mutationId,
354
+ message: error instanceof Error ? error.message : String(error)
355
+ };
356
+ }
357
+ var RustFormulaProjectionService = class {
358
+ _nativeLoaded = !1;
359
+ async load(workbooks) {
360
+ await this._ensureNativeLoaded();
361
+ try {
362
+ return {
363
+ stats: JSON.parse(loadSnapshotOnRust(JSON.stringify(serializeRuntimeWorkbookSnapshots(workbooks))))
364
+ };
365
+ } catch (error) {
366
+ return {
367
+ desync: createFormulaProjectionDesyncSignal("snapshot-load-failed", error),
368
+ errors: [errorToFormulaCalculationError("RUST_FORMULA_LOAD_ERROR", error)]
369
+ };
370
+ }
371
+ }
372
+ async applyMutation(mutation) {
373
+ await this._ensureNativeLoaded();
374
+ try {
375
+ return {
376
+ stats: JSON.parse(applyMutationOnRust(JSON.stringify(normalizeRustEngineMutation(mutation)))),
377
+ dependencyInvalidated: !isRustIncrementalDependencyMutation(mutation.id)
378
+ };
379
+ } catch (error) {
380
+ return {
381
+ dependencyInvalidated: !0,
382
+ desync: createFormulaProjectionDesyncSignal("mutation-apply-failed", error, mutation.id),
383
+ errors: [errorToFormulaCalculationError("RUST_FORMULA_MUTATION_ERROR", error)]
384
+ };
385
+ }
386
+ }
387
+ async syncFormulaDependencies(input) {
388
+ return await this._ensureNativeLoaded(), JSON.parse(syncRustFormulaDependenciesOnRust(JSON.stringify(input)));
389
+ }
390
+ async markDirty(input) {
391
+ return await this._ensureNativeLoaded(), JSON.parse(markRustFormulaDirtyOnRust(JSON.stringify(input)));
392
+ }
393
+ async calculateDirty(maxIteration = 1) {
394
+ await this._ensureNativeLoaded();
395
+ try {
396
+ let output = JSON.parse(
397
+ executeDirtyFormulasOnRust(maxIteration, !1, !1, !0)
398
+ );
399
+ return rustExecutionOutputToFormulaCalculationPatch(output);
400
+ } catch (error) {
401
+ return {
402
+ unitData: {},
403
+ unitOtherData: {},
404
+ desync: createFormulaProjectionDesyncSignal("dirty-calculation-failed", error),
405
+ errors: [errorToFormulaCalculationError("RUST_FORMULA_CALCULATION_ERROR", error)]
406
+ };
407
+ }
408
+ }
409
+ async reset() {
410
+ await this._ensureNativeLoaded();
411
+ try {
412
+ return clearRustFormulaDirtyOnRust(), clearRustFormulaDependenciesOnRust(
413
+ JSON.stringify({
414
+ unitId: "",
415
+ clearSheetFormulas: !0,
416
+ clearFeatureFormulas: !0,
417
+ clearOtherFormulas: !0
418
+ })
419
+ ), {
420
+ stats: JSON.parse(loadSnapshotOnRust(JSON.stringify({ workbooks: [] })))
421
+ };
422
+ } catch (error) {
423
+ return {
424
+ desync: createFormulaProjectionDesyncSignal("projection-reset-failed", error),
425
+ errors: [errorToFormulaCalculationError("RUST_FORMULA_RESET_ERROR", error)]
426
+ };
427
+ }
428
+ }
429
+ async disposeWorkbook(unitId) {
430
+ await this._ensureNativeLoaded();
431
+ try {
432
+ return { stats: JSON.parse(disposeWorkbookOnRust(unitId)) };
433
+ } catch (error) {
434
+ return {
435
+ desync: createFormulaProjectionDesyncSignal("workbook-dispose-failed", error),
436
+ errors: [errorToFormulaCalculationError("RUST_FORMULA_DISPOSE_ERROR", error)]
437
+ };
438
+ }
439
+ }
440
+ async _ensureNativeLoaded() {
441
+ this._nativeLoaded || (await loadNativeBinding(), this._nativeLoaded = !0);
442
+ }
443
+ };
444
+ function normalizeRustEngineMutation(mutation) {
445
+ 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 ?? {};
446
+ return {
447
+ id: mutation.id,
448
+ params,
449
+ dirtyRanges: Array.isArray(mutation.dirtyRanges) ? mutation.dirtyRanges : []
450
+ };
451
+ }
452
+ function normalizeSetSuperTablesMutationParams(params) {
453
+ return !isRecord(params) || typeof params.unitId != "string" || !Array.isArray(params.tables) ? params ?? {} : {
454
+ ...params,
455
+ tables: params.tables.map((entry) => {
456
+ let normalized = normalizeSetSuperTableMutationParams(
457
+ isRecord(entry) ? { ...entry, unitId: params.unitId } : entry
458
+ );
459
+ if (!isRecord(normalized)) return normalized;
460
+ let { unitId: _unitId, ...table } = normalized;
461
+ return table;
462
+ })
463
+ };
464
+ }
465
+ function normalizeSetSuperTableMutationParams(params) {
466
+ if (!isRecord(params) || !isRecord(params.reference))
467
+ return params ?? {};
468
+ let reference = params.reference, table = serializeRuntimeSuperTable(reference);
469
+ return table ? {
470
+ ...params,
471
+ reference: normalizeRuntimeValue(reference),
472
+ table
473
+ } : {
474
+ ...params,
475
+ reference: normalizeRuntimeValue(reference)
476
+ };
477
+ }
478
+ function serializeRuntimeSuperTable(reference) {
479
+ let sheetId = reference.sheetId, range = reference.range;
480
+ if (typeof sheetId != "string" || !isRecord(range) || typeof range.startRow != "number" || typeof range.endRow != "number" || typeof range.startColumn != "number" || typeof range.endColumn != "number")
481
+ return null;
482
+ let columns = (reference.titleMap instanceof Map ? Array.from(reference.titleMap.entries()) : isRecord(reference.titleMap) ? Object.entries(reference.titleMap) : []).filter((entry) => typeof entry[0] == "string" && typeof entry[1] == "number").toSorted((left, right) => left[1] - right[1]).map(([displayName]) => ({ displayName }));
483
+ return {
484
+ sheetId,
485
+ range: {
486
+ startRow: range.startRow,
487
+ endRow: range.endRow,
488
+ startColumn: range.startColumn,
489
+ endColumn: range.endColumn
490
+ },
491
+ columns,
492
+ showHeader: reference.showHeader !== !1,
493
+ showFooter: reference.showFooter === !0
494
+ };
495
+ }
496
+ function normalizeRuntimeValue(value) {
497
+ return value instanceof Map ? Object.fromEntries(
498
+ Array.from(value.entries(), ([key, entryValue]) => [String(key), normalizeRuntimeValue(entryValue)])
499
+ ) : Array.isArray(value) ? value.map(normalizeRuntimeValue) : isRecord(value) ? Object.fromEntries(
500
+ Object.entries(value).map(([key, entryValue]) => [key, normalizeRuntimeValue(entryValue)])
501
+ ) : value;
502
+ }
503
+ function resultBatchesToUnitData(resultBatches) {
504
+ let unitData = {};
505
+ for (let batch of resultBatches) {
506
+ let unitSheetData = unitData[batch.unitId] ?? {};
507
+ unitData[batch.unitId] = unitSheetData;
508
+ let sheetData = unitSheetData[batch.sheetId] ?? {};
509
+ unitSheetData[batch.sheetId] = sheetData;
510
+ for (let index = 0; index < batch.values.length; index++) {
511
+ let row = batch.rows[index], col = batch.cols[index], value = batch.values[index], rowData = sheetData[row] ?? {};
512
+ sheetData[row] = rowData, rowData[col] = cellDataFromRustValue(value);
513
+ }
514
+ }
515
+ return unitData;
516
+ }
517
+ function runtimeDataToUnitData(runtimeData) {
518
+ let unitData = {};
519
+ return Object.entries(runtimeData ?? {}).forEach(([unitId, sheetMap]) => {
520
+ if (!sheetMap) return;
521
+ let unitSheetData = {};
522
+ unitData[unitId] = unitSheetData, Object.entries(sheetMap).forEach(([sheetId, rowMap]) => {
523
+ if (!rowMap) return;
524
+ let sheetData = {};
525
+ unitSheetData[sheetId] = sheetData, Object.entries(rowMap).forEach(([rowKey, colMap]) => {
526
+ if (!colMap) return;
527
+ let row = Number(rowKey), rowData = {};
528
+ sheetData[row] = rowData, Object.entries(colMap).forEach(([colKey, value]) => {
529
+ rowData[Number(colKey)] = cellDataFromRustValue(value);
530
+ });
531
+ });
532
+ });
533
+ }), unitData;
534
+ }
535
+ function cellDataFromRustValue(value) {
536
+ if (value == null)
537
+ return null;
538
+ if (typeof value == "number")
539
+ return { t: CellValueType.NUMBER, v: value };
540
+ if (typeof value == "boolean")
541
+ return { t: CellValueType.BOOLEAN, v: value };
542
+ if (typeof value == "string")
543
+ return { t: CellValueType.STRING, v: value };
544
+ if (isRecord(value)) {
545
+ let cell = sanitizeCoreCellData(value);
546
+ if (Object.keys(cell).length > 0)
547
+ return cell;
548
+ }
549
+ return { v: value };
550
+ }
551
+ function sanitizeCoreCellData(value) {
552
+ let cell = {};
553
+ for (let key of ["v", "t", "p", "s", "f", "si", "ref", "xf", "custom"])
554
+ key in value && (cell[key] = value[key]);
555
+ return cell;
556
+ }
557
+ function serializeResources(snapshot) {
558
+ let resources = snapshot.resources;
559
+ if (!resources || typeof resources != "object")
560
+ return;
561
+ let serialized = {};
562
+ for (let [id, resource] of Object.entries(resources))
563
+ typeof resource?.name == "string" && (serialized[id] = {
564
+ name: resource.name,
565
+ data: resource.data
566
+ });
567
+ return Object.keys(serialized).length > 0 ? serialized : void 0;
568
+ }
569
+ function serializeCalculation(snapshot) {
570
+ for (let resource of Object.values(
571
+ snapshot.resources ?? {}
572
+ )) {
573
+ if (resource?.name !== XLSX_WORKBOOK_CALCULATION_RESOURCE)
574
+ continue;
575
+ let data = parseResourceData(resource.data);
576
+ if (!data || typeof data != "object")
577
+ return;
578
+ let fullPrecision = data.fullPrecision;
579
+ return typeof fullPrecision == "boolean" ? { fullPrecision } : void 0;
580
+ }
581
+ }
582
+ function serializeTables(snapshot) {
583
+ for (let resource of Object.values(
584
+ snapshot.resources ?? {}
585
+ )) {
586
+ if (resource?.name !== "SHEET_TABLE_PLUGIN")
587
+ continue;
588
+ let data = parseResourceData(resource.data);
589
+ if (!data || typeof data != "object")
590
+ return;
591
+ let tables = {};
592
+ for (let [sheetId, sheetTables] of Object.entries(data)) {
593
+ let tableList = sheetTables?.tables;
594
+ if (Array.isArray(tableList))
595
+ for (let table of tableList) {
596
+ let serialized = serializeTableSnapshot(sheetId, table, snapshot);
597
+ serialized && (tables[serialized.name] = serialized.table);
598
+ }
599
+ }
600
+ return Object.keys(tables).length > 0 ? tables : void 0;
601
+ }
602
+ }
603
+ function serializeTableSnapshot(sheetId, table, snapshot) {
604
+ if (!table || typeof table != "object")
605
+ return null;
606
+ let record = table, name2 = typeof record.name == "string" ? record.name : void 0, range = record.range;
607
+ if (!name2 || !range || typeof range.startRow != "number" || typeof range.endRow != "number" || typeof range.startColumn != "number" || typeof range.endColumn != "number")
608
+ return null;
609
+ let columns = Array.isArray(record.columns) ? record.columns.map((column) => {
610
+ let displayName = column?.displayName;
611
+ return typeof displayName == "string" ? { displayName } : null;
612
+ }).filter((column) => column != null) : [], showHeader = record.options?.showHeader !== !1, showFooter = typeof record.options?.showFooter == "boolean" ? record.options.showFooter : inferTableFooter(snapshot, sheetId, range.startRow, range.endRow, range.startColumn, range.endColumn);
613
+ return {
614
+ name: name2,
615
+ table: {
616
+ sheetId,
617
+ range: {
618
+ startRow: range.startRow,
619
+ endRow: range.endRow,
620
+ startColumn: range.startColumn,
621
+ endColumn: range.endColumn
622
+ },
623
+ columns,
624
+ showHeader,
625
+ showFooter
626
+ }
627
+ };
628
+ }
629
+ function parseResourceData(data) {
630
+ if (typeof data != "string")
631
+ return data;
632
+ try {
633
+ return JSON.parse(data || "{}");
634
+ } catch {
635
+ return;
636
+ }
637
+ }
638
+ function inferTableFooter(snapshot, sheetId, startRow, endRow, startColumn, endColumn) {
639
+ let row = snapshot.sheets?.[sheetId]?.cellData?.[endRow];
640
+ if (!row)
641
+ return !1;
642
+ for (let col = startColumn; col <= endColumn; col++) {
643
+ let cell = row[col];
644
+ if (cell && (typeof cell.f == "string" && /\bSUBTOTAL\s*\(/iu.test(cell.f) || col === startColumn && typeof cell.v == "string" && cell.v.trim().toLowerCase() === "total"))
645
+ return !0;
646
+ }
647
+ return !1;
648
+ }
649
+ function serializeExternalLinks(snapshot) {
650
+ let externalLinks = snapshot.externalLinks, serializedLinks = Array.isArray(externalLinks) ? externalLinks.map((link) => serializeExternalLink(link)).filter((link) => link != null) : [];
651
+ return serializedLinks.push(...serializeExternalLinksFromResource(snapshot)), serializedLinks.length > 0 ? serializedLinks : void 0;
652
+ }
653
+ function serializeExternalLinksFromResource(snapshot) {
654
+ let links = [];
655
+ for (let resource of Object.values(
656
+ snapshot.resources ?? {}
657
+ )) {
658
+ if (resource?.name !== EXTERNAL_DATA_RESOURCE)
659
+ continue;
660
+ let data = parseResourceData(resource.data);
661
+ if (isRecord(data)) {
662
+ if (data.schemaVersion === 1 && Array.isArray(data.links)) {
663
+ links.push(
664
+ ...data.links.map((link) => serializeVersionedExternalLink(link)).filter((link) => link != null)
665
+ );
666
+ continue;
667
+ }
668
+ if (!(data.signature !== EXTERNAL_DATA_SIGNATURE || !isRecord(data.units)))
669
+ for (let [unitId, unit] of Object.entries(data.units)) {
670
+ let link = serializeExternalDataUnit(unitId, unit);
671
+ link && links.push(link);
672
+ }
673
+ }
674
+ }
675
+ return links;
676
+ }
677
+ function serializeVersionedExternalLink(link) {
678
+ if (!isRecord(link) || !Number.isInteger(link.slot) || Number(link.slot) <= 0 || !isRecord(link.target))
679
+ return null;
680
+ let target = link.target, cache = isRecord(link.cache) ? link.cache : void 0, cachedSheets = Array.isArray(cache?.sheets) ? cache.sheets.map((sheet) => serializeVersionedExternalSheet(sheet)).filter((sheet) => sheet != null) : [], cachedNames = new Set(cachedSheets.map((sheet) => sheet.name.toLocaleLowerCase())), uncachedSheets = Array.isArray(link.sheetNames) ? link.sheetNames.flatMap((item) => {
681
+ if (!isRecord(item)) return [];
682
+ let { name: name2 } = item;
683
+ return typeof name2 != "string" || cachedNames.has(name2.toLocaleLowerCase()) ? [] : [
684
+ {
685
+ name: name2,
686
+ rowCount: 1048576,
687
+ columnCount: 16384,
688
+ cellData: {},
689
+ coverage: []
690
+ }
691
+ ];
692
+ }) : [], sheets = [...cachedSheets, ...uncachedSheets], definedNames = serializeVersionedExternalDefinedNames(link.definedNames), tables = serializeVersionedExternalTables(link.tables), aliases = [link.name, target.name, target.uri].filter(
693
+ (alias) => typeof alias == "string" && alias.length > 0
694
+ );
695
+ return {
696
+ ...aliases.length > 0 ? { aliases: [...new Set(aliases)] } : {},
697
+ ...definedNames ? { definedNames } : {},
698
+ sheets,
699
+ ...tables ? { tables } : {},
700
+ ...typeof target.uri == "string" ? { target: target.uri } : typeof target.name == "string" ? { target: target.name } : typeof link.name == "string" ? { target: link.name } : {},
701
+ unitId: String(link.slot)
702
+ };
703
+ }
704
+ function serializeVersionedExternalDefinedNames(value) {
705
+ if (!Array.isArray(value))
706
+ return;
707
+ let result = {};
708
+ for (let item of value)
709
+ !isRecord(item) || typeof item.name != "string" || (result[item.name] = {
710
+ name: item.name,
711
+ ...typeof item.formulaOrRefString == "string" ? { formulaOrRefString: item.formulaOrRefString } : {}
712
+ });
713
+ return Object.keys(result).length > 0 ? result : void 0;
714
+ }
715
+ function serializeVersionedExternalTables(value) {
716
+ if (!Array.isArray(value))
717
+ return;
718
+ let result = {};
719
+ for (let item of value) {
720
+ if (!isRecord(item) || typeof item.name != "string" || typeof item.sheetName != "string" || !isRange(item.range)) continue;
721
+ let columns = Array.isArray(item.columns) ? item.columns.flatMap((column) => {
722
+ if (!isRecord(column)) return [];
723
+ let { name: name2 } = column;
724
+ return typeof name2 == "string" ? [{ displayName: name2 }] : [];
725
+ }) : [];
726
+ result[item.name] = {
727
+ sheetId: item.sheetName,
728
+ range: item.range,
729
+ columns,
730
+ showHeader: item.showHeader !== !1
731
+ };
732
+ }
733
+ return Object.keys(result).length > 0 ? result : void 0;
734
+ }
735
+ function serializeVersionedExternalSheet(sheet) {
736
+ if (!isRecord(sheet) || typeof sheet.name != "string") return null;
737
+ let cellData = {};
738
+ if (Array.isArray(sheet.cells))
739
+ for (let cell of sheet.cells) {
740
+ if (!isExternalCell(cell)) continue;
741
+ let { row, column } = cell;
742
+ (cellData[row] ??= {})[column] = {
743
+ v: cell.value,
744
+ ...typeof cell.valueType == "number" ? { t: cell.valueType } : {}
745
+ };
746
+ }
747
+ return {
748
+ name: sheet.name,
749
+ ...typeof sheet.sheetId == "string" ? { sheetId: sheet.sheetId } : {},
750
+ rowCount: typeof sheet.rowCount == "number" ? sheet.rowCount : 0,
751
+ columnCount: typeof sheet.columnCount == "number" ? sheet.columnCount : 0,
752
+ cellData,
753
+ coverage: Array.isArray(sheet.coverage) ? sheet.coverage.filter(isRange) : []
754
+ };
755
+ }
756
+ function isRange(value) {
757
+ return value != null && typeof value == "object" && "startRow" in value && typeof value.startRow == "number" && "endRow" in value && typeof value.endRow == "number" && "startColumn" in value && typeof value.startColumn == "number" && "endColumn" in value && typeof value.endColumn == "number";
758
+ }
759
+ function isRustTableSnapshot(value) {
760
+ return value != null && typeof value == "object" && "sheetId" in value && typeof value.sheetId == "string" && "range" in value && isRange(value.range) && "columns" in value && Array.isArray(value.columns);
761
+ }
762
+ function isExternalCell(value) {
763
+ return isRecord(value) && Number.isInteger(value.row) && Number.isInteger(value.column);
764
+ }
765
+ function serializeExternalDataUnit(unitId, unit) {
766
+ if (!unit || typeof unit != "object")
767
+ return null;
768
+ let record = unit;
769
+ if (!record.sheets || typeof record.sheets != "object")
770
+ return null;
771
+ let sheets = Object.values(record.sheets).map((sheet) => serializeExternalSheet(sheet)).filter((sheet) => sheet != null);
772
+ if (sheets.length === 0)
773
+ return null;
774
+ let definedNames = serializeExternalDefinedNames(record.definedNames);
775
+ return {
776
+ ...definedNames === void 0 ? {} : { definedNames },
777
+ sheets,
778
+ ...typeof record.target == "string" ? { target: record.target } : {},
779
+ unitId
780
+ };
781
+ }
782
+ function serializeExternalLink(link) {
783
+ if (!isRecord(link))
784
+ return null;
785
+ let record = link;
786
+ if (!Array.isArray(record.sheets))
787
+ return null;
788
+ let sheets = record.sheets.map((sheet) => serializeExternalSheet(sheet)).filter((sheet) => sheet != null);
789
+ if (sheets.length === 0)
790
+ return null;
791
+ let definedNames = serializeExternalDefinedNames(record.definedNames), tables = serializeExternalTables(record.tables);
792
+ return {
793
+ ...definedNames === void 0 ? {} : { definedNames },
794
+ sheets,
795
+ ...tables === void 0 ? {} : { tables },
796
+ ...typeof record.target == "string" ? { target: record.target } : {},
797
+ ...typeof record.unitId == "string" ? { unitId: record.unitId } : {}
798
+ };
799
+ }
800
+ function serializeExternalTables(value) {
801
+ if (!isRecord(value)) return;
802
+ let result = {};
803
+ for (let [name2, table] of Object.entries(value))
804
+ !table || typeof table != "object" || isRustTableSnapshot(table) && (result[name2] = table);
805
+ return Object.keys(result).length > 0 ? result : void 0;
806
+ }
807
+ function serializeExternalDefinedNames(value) {
808
+ if (!isRecord(value))
809
+ return;
810
+ let definedNames = {};
811
+ for (let [key, item] of Object.entries(value)) {
812
+ if (!isRecord(item))
813
+ continue;
814
+ let record = item, name2 = typeof record.name == "string" ? record.name : key;
815
+ definedNames[key] = {
816
+ ...typeof record.id == "string" ? { id: record.id } : {},
817
+ name: name2,
818
+ ...typeof record.formulaOrRefString == "string" ? { formulaOrRefString: record.formulaOrRefString } : {},
819
+ ...typeof record.localSheetId == "string" ? { localSheetId: record.localSheetId } : {}
820
+ };
821
+ }
822
+ return Object.keys(definedNames).length > 0 ? definedNames : void 0;
823
+ }
824
+ function serializeExternalSheet(sheet) {
825
+ if (!sheet || typeof sheet != "object")
826
+ return null;
827
+ let record = sheet;
828
+ return typeof record.name != "string" ? null : {
829
+ name: record.name,
830
+ ...typeof record.sheetId == "string" ? { sheetId: record.sheetId } : {},
831
+ rowCount: typeof record.rowCount == "number" ? record.rowCount : 0,
832
+ columnCount: typeof record.columnCount == "number" ? record.columnCount : 0,
833
+ cellData: serializeCellData(record.cellData)
834
+ };
835
+ }
836
+ function serializeDefinedNames(definedNames, snapshot) {
837
+ let direct = definedNames && Object.keys(definedNames).length > 0 ? definedNames : extractDefinedNames(snapshot), sheetIds = new Set(Object.keys(snapshot.sheets ?? {})), sheetNameToId = new Map(
838
+ Object.entries(snapshot.sheets ?? {}).map(([sheetId, sheet]) => [sheet.name, sheetId])
839
+ );
840
+ return Object.fromEntries(
841
+ Object.entries(direct).map(([id, definedName]) => [
842
+ id,
843
+ {
844
+ id: definedName.id,
845
+ name: definedName.name,
846
+ formulaOrRefString: definedName.formulaOrRefString,
847
+ localSheetId: normalizeDefinedNameLocalSheetId(
848
+ definedName.localSheetId,
849
+ definedName.formulaOrRefString,
850
+ sheetIds,
851
+ sheetNameToId
852
+ )
853
+ }
854
+ ])
855
+ );
856
+ }
857
+ function normalizeDefinedNameLocalSheetId(localSheetId, formulaOrRefString, sheetIds, sheetNameToId) {
858
+ if (!localSheetId || localSheetId === "AllDefaultWorkbook")
859
+ return localSheetId;
860
+ let sheetName = extractLeadingSheetName(formulaOrRefString), sheetIdFromFormula = sheetName ? sheetNameToId.get(sheetName) : void 0;
861
+ return sheetIdFromFormula && sheetIdFromFormula !== localSheetId ? sheetIdFromFormula : sheetIds.has(localSheetId) || !sheetName ? localSheetId : sheetIdFromFormula ?? localSheetId;
862
+ }
863
+ function extractLeadingSheetName(formulaOrRefString) {
864
+ if (!formulaOrRefString)
865
+ return;
866
+ let quotedMatch = /^'((?:[^']|'')+)'!/.exec(formulaOrRefString);
867
+ return quotedMatch ? quotedMatch[1].replace(/''/g, "'") : /^([^=!]+)!/.exec(formulaOrRefString)?.[1];
868
+ }
869
+ function extractDefinedNames(snapshot) {
870
+ let direct = snapshot.definedNames;
871
+ if (direct && Object.keys(direct).length > 0)
872
+ return direct;
873
+ for (let resource of Object.values(
874
+ snapshot.resources ?? {}
875
+ )) {
876
+ if (resource?.name !== "SHEET_DEFINED_NAME_PLUGIN")
877
+ continue;
878
+ let data = parseResourceData(resource.data);
879
+ return data && typeof data == "object" ? data : {};
880
+ }
881
+ return {};
882
+ }
883
+ function serializeSheetSnapshot(sheetId, sheet, styles, precisionAsDisplayed) {
884
+ return sheet ? {
885
+ sheetId: sheet.id ?? sheetId,
886
+ name: sheet.name,
887
+ rowCount: sheet.rowCount ?? 0,
888
+ columnCount: sheet.columnCount ?? 0,
889
+ transitionEvaluation: sheet.transitionEvaluation === !0,
890
+ cellData: serializeCellData(sheet.cellData, styles, precisionAsDisplayed),
891
+ rowData: serializeVisibilityData(sheet.rowData),
892
+ columnData: serializeVisibilityData(sheet.columnData)
893
+ } : null;
894
+ }
895
+ function serializeCellData(cellData = {}, styles, precisionAsDisplayed = !1) {
896
+ let result = {}, rawCellData = cellData instanceof ObjectMatrix ? cellData.getMatrix() : cellData;
897
+ for (let [rowKey, row] of Object.entries(rawCellData ?? {})) {
898
+ if (!row)
899
+ continue;
900
+ let serializedRow = {};
901
+ for (let [colKey, cell] of Object.entries(row)) {
902
+ if (!cell || typeof cell != "object")
903
+ continue;
904
+ let cellRecord = cell, value = {};
905
+ 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") {
906
+ let hasFormula = typeof cellRecord.f == "string" && cellRecord.f.length > 0;
907
+ typeof cellRecord.si == "string" || hasFormula && isLegacyArrayFormulaCell(cellRecord) ? value.ref = cellRecord.ref : hasFormula && (value.dynamicArrayRef = cellRecord.ref);
908
+ }
909
+ if (typeof cellRecord.xf == "string" && (value.xf = cellRecord.xf), "s" in cellRecord && (value.s = cellRecord.s), precisionAsDisplayed && typeof cellRecord.f == "string") {
910
+ let displayPrecision = inferDisplayPrecision(cellRecord.s, styles);
911
+ displayPrecision !== void 0 && (value.displayPrecision = displayPrecision);
912
+ }
913
+ Object.keys(value).length > 0 && (serializedRow[Number(colKey)] = value);
914
+ }
915
+ Object.keys(serializedRow).length > 0 && (result[Number(rowKey)] = serializedRow);
916
+ }
917
+ return result;
918
+ }
919
+ function serializeCellDataInRanges(cellData, ranges) {
920
+ let serialized = serializeCellData(cellData), result = {};
921
+ for (let [rowKey, row] of Object.entries(serialized)) {
922
+ let rowIndex = Number(rowKey);
923
+ for (let [columnKey, value] of Object.entries(row)) {
924
+ let columnIndex = Number(columnKey);
925
+ ranges.some(
926
+ (range) => rowIndex >= range.startRow && rowIndex <= range.endRow && columnIndex >= range.startColumn && columnIndex <= range.endColumn
927
+ ) && ((result[rowIndex] ??= {})[columnIndex] = value);
928
+ }
929
+ }
930
+ return result;
931
+ }
932
+ function isLegacyArrayFormulaCell(cell) {
933
+ let custom = cell.custom;
934
+ if (!custom || typeof custom != "object")
935
+ return !1;
936
+ let xlsx = custom._xlsx;
937
+ return xlsx != null && typeof xlsx == "object" && xlsx.legacyArrayFormula === !0;
938
+ }
939
+ function inferDisplayPrecision(styleId, styles) {
940
+ if (typeof styleId != "string" || !styles || typeof styles != "object")
941
+ return;
942
+ let style = styles[styleId];
943
+ if (!style || typeof style != "object")
944
+ return;
945
+ let numberFormat = style.n;
946
+ if (!numberFormat || typeof numberFormat != "object")
947
+ return;
948
+ let pattern = numberFormat.pattern;
949
+ return typeof pattern == "string" ? inferFixedNumberFormatPrecision(pattern) : void 0;
950
+ }
951
+ function inferFixedNumberFormatPrecision(pattern) {
952
+ let cleaned = (pattern.split(";")[0] ?? pattern).replace(/"[^"]*"/gu, "").replace(/\\./gu, "").replace(/_.|\*./gu, "");
953
+ if (!/[0#?]/u.test(cleaned) || /[%Ee]|[ymdhsa]/iu.test(cleaned))
954
+ return;
955
+ let decimalMatch = cleaned.match(/\.([0#?]+)/u);
956
+ return decimalMatch?.[1] ? decimalMatch[1].length : 0;
957
+ }
958
+ function serializeVisibilityData(data = {}) {
959
+ let result = {};
960
+ for (let [indexKey, metadata] of Object.entries(data))
961
+ !metadata || typeof metadata != "object" || !("hd" in metadata) || (result[Number(indexKey)] = {
962
+ hd: metadata.hd
963
+ });
964
+ return result;
965
+ }
966
+ function errorToFormulaCalculationError(code, error) {
967
+ return {
968
+ code,
969
+ message: error instanceof Error ? error.message : String(error)
970
+ };
971
+ }
972
+ function isRecord(value) {
973
+ return typeof value == "object" && value !== null && !Array.isArray(value);
974
+ }
975
+
976
+ // src/controllers/rust-engine-sync.controller.ts
977
+ var rustEngineSyncState = {
978
+ snapshotEpoch: 0,
979
+ dependencyInvalidationEpoch: 0
980
+ };
981
+ function getRustEngineSyncState() {
982
+ return { ...rustEngineSyncState };
983
+ }
984
+ function markRustSnapshotLoaded() {
985
+ rustEngineSyncState.snapshotEpoch += 1, rustEngineSyncState.dependencyInvalidationEpoch += 1;
986
+ }
987
+ function markRustFormulaDependenciesInvalidated() {
988
+ rustEngineSyncState.dependencyInvalidationEpoch += 1;
989
+ }
990
+ function emitRustEngineSyncDebugEvent(event) {
991
+ let hook = globalThis.__UNIVER_RUST_FORMULA_DEBUG_HOOK__;
992
+ typeof hook == "function" && hook(event);
993
+ }
994
+ function summarizeObjectMatrixPayload(value) {
995
+ if (!value || typeof value != "object")
996
+ return {};
997
+ let cellValueCells = 0;
998
+ for (let row of Object.values(value))
999
+ !row || typeof row != "object" || (cellValueCells += Object.keys(row).length);
1000
+ return {
1001
+ cellValueRows: Object.keys(value).length,
1002
+ cellValueCells
1003
+ };
1004
+ }
1005
+ function hasObjectMatrixValues(value) {
1006
+ return !value || typeof value != "object" ? !1 : Object.values(value).some(
1007
+ (row) => row != null && typeof row == "object" && Object.keys(row).length > 0
1008
+ );
1009
+ }
1010
+ function hasRecordEntries(value) {
1011
+ return value != null && typeof value == "object" && Object.keys(value).length > 0;
1012
+ }
1013
+ function countDisplayPrecisionCells(snapshot) {
1014
+ let count = 0;
1015
+ for (let workbook of snapshot.workbooks)
1016
+ for (let sheet of workbook.sheets)
1017
+ for (let row of Object.values(sheet.cellData))
1018
+ for (let cell of Object.values(row))
1019
+ typeof cell.displayPrecision == "number" && (count += 1);
1020
+ return count;
1021
+ }
1022
+ var RustEngineSyncController = class extends Disposable {
1023
+ constructor(_commandService) {
1024
+ super();
1025
+ this._commandService = _commandService;
1026
+ this._initialize();
1027
+ }
1028
+ _commandService;
1029
+ _nativeReady = !1;
1030
+ _snapshotLoaded = !1;
1031
+ _projectionLoadPromise = null;
1032
+ _projectionDeltaBarrier = Promise.resolve();
1033
+ _pendingMutations = [];
1034
+ _projectionManagedTableUnits = /* @__PURE__ */ new Set();
1035
+ _initialize() {
1036
+ this.disposeWithMe(
1037
+ this._commandService.onCommandExecuted((command, options) => {
1038
+ this._shouldSyncMutation(command, options) && this._queueOrSyncMutation(this._serializeMutation(command, options));
1039
+ })
1040
+ );
1041
+ }
1042
+ async loadProjection(workbooks) {
1043
+ let loadPromise = this._loadProjection(workbooks);
1044
+ this._projectionLoadPromise = loadPromise;
1045
+ try {
1046
+ await loadPromise;
1047
+ } finally {
1048
+ this._projectionLoadPromise === loadPromise && (this._projectionLoadPromise = null);
1049
+ }
1050
+ }
1051
+ async waitForProjectionLoad() {
1052
+ await this._projectionLoadPromise;
1053
+ let barrier;
1054
+ do
1055
+ barrier = this._projectionDeltaBarrier, await barrier;
1056
+ while (barrier !== this._projectionDeltaBarrier);
1057
+ }
1058
+ setProjectionDeltaBarrier(barrier) {
1059
+ this._projectionDeltaBarrier = barrier;
1060
+ }
1061
+ async _loadProjection(workbooks) {
1062
+ await loadNativeBinding(), this._nativeReady = !0;
1063
+ let serializeStartedAt = performance.now(), snapshot = serializeRuntimeWorkbookSnapshots(workbooks);
1064
+ this._loadSerializedSnapshot(snapshot, performance.now() - serializeStartedAt);
1065
+ }
1066
+ applyProjectionMutation(mutation) {
1067
+ this._queueOrSyncMutation(mutation);
1068
+ }
1069
+ upsertProjectionWorkbook(workbook) {
1070
+ this._queueOrSyncMutation(createProjectionWorkbookUpsertMutation(workbook));
1071
+ }
1072
+ setProjectionManagedTableUnit(unitId) {
1073
+ this._projectionManagedTableUnits.add(unitId);
1074
+ }
1075
+ unsetProjectionManagedTableUnit(unitId) {
1076
+ this._projectionManagedTableUnits.delete(unitId);
1077
+ }
1078
+ upsertReferenceData(config, needs, tableService) {
1079
+ let mutations = createReferenceDataUpsertMutations(config, needs, tableService);
1080
+ return mutations.forEach((mutation) => this._queueOrSyncMutation(mutation)), mutations.length;
1081
+ }
1082
+ disposeProjectionWorkbook(unitId) {
1083
+ if (!(!this._nativeReady || !this._snapshotLoaded))
1084
+ try {
1085
+ disposeWorkbookOnRust(unitId), markRustFormulaDependenciesInvalidated();
1086
+ } catch {
1087
+ this._markProjectionDesynced();
1088
+ }
1089
+ }
1090
+ dispose() {
1091
+ if (super.dispose(), this._pendingMutations.length = 0, this._projectionManagedTableUnits.clear(), this._projectionLoadPromise = null, this._projectionDeltaBarrier = Promise.resolve(), !this._nativeReady) {
1092
+ this._snapshotLoaded = !1;
1093
+ return;
1094
+ }
1095
+ try {
1096
+ disposeAllWorkbooksOnRust();
1097
+ } catch {
1098
+ this._markProjectionDesynced();
1099
+ return;
1100
+ }
1101
+ this._nativeReady = !1, this._snapshotLoaded = !1;
1102
+ }
1103
+ _loadSerializedSnapshot(snapshot, serializeMs) {
1104
+ let precisionAsDisplayedWorkbookCount = snapshot.workbooks.filter(
1105
+ (workbook) => workbook.calculation?.fullPrecision === !1
1106
+ ).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;
1107
+ try {
1108
+ nativeTimings = JSON.parse(nativeOutput).timingsMs;
1109
+ } catch {
1110
+ nativeTimings = void 0;
1111
+ }
1112
+ emitRustEngineSyncDebugEvent({
1113
+ type: "loadSnapshot",
1114
+ payload: {
1115
+ workbookCount: snapshot.workbooks.length,
1116
+ serializeMs,
1117
+ stringifyMs,
1118
+ nativeMs,
1119
+ precisionAsDisplayedWorkbookCount,
1120
+ displayPrecisionCellCount,
1121
+ snapshotBytes: snapshotBuffer?.byteLength ?? snapshotJson.length,
1122
+ transport: snapshotBuffer ? "binary-json" : "string-json",
1123
+ nativeTimings
1124
+ }
1125
+ }), this._pendingMutations.splice(0, pendingCountCoveredBySnapshot), this._snapshotLoaded = !0, markRustSnapshotLoaded(), this._flushPendingMutations();
1126
+ }
1127
+ _queueOrSyncMutation(mutation) {
1128
+ if (!this._nativeReady || !this._snapshotLoaded) {
1129
+ this._pendingMutations.push(mutation);
1130
+ return;
1131
+ }
1132
+ this._syncMutation(mutation);
1133
+ }
1134
+ _flushPendingMutations() {
1135
+ for (; this._pendingMutations.length > 0; ) {
1136
+ let mutation = this._pendingMutations.shift();
1137
+ mutation && this._syncMutation(mutation);
1138
+ }
1139
+ }
1140
+ _syncMutation(mutation) {
1141
+ let totalStartedAt = performance.now(), stringifyStartedAt = performance.now(), payload = JSON.stringify(normalizeRustEngineMutation(mutation)), stringifyMs = performance.now() - stringifyStartedAt, nativeStartedAt = performance.now();
1142
+ try {
1143
+ applyMutationOnRust(payload), isRustIncrementalDependencyMutation(mutation.id) || markRustFormulaDependenciesInvalidated();
1144
+ } catch {
1145
+ this._markProjectionDesynced();
1146
+ } finally {
1147
+ emitRustEngineSyncDebugEvent({
1148
+ type: "applyMutation",
1149
+ payload: {
1150
+ id: mutation.id,
1151
+ stringifyMs,
1152
+ nativeMs: performance.now() - nativeStartedAt,
1153
+ totalMs: performance.now() - totalStartedAt,
1154
+ ...summarizeObjectMatrixPayload(
1155
+ mutation.params?.cellValue
1156
+ )
1157
+ }
1158
+ });
1159
+ }
1160
+ }
1161
+ _markProjectionDesynced() {
1162
+ this._nativeReady = !1, this._snapshotLoaded = !1;
1163
+ }
1164
+ _shouldSyncMutation(command, options) {
1165
+ if (command.type !== CommandType.MUTATION || !isRustFormulaRelevantMutation(command.id) || (command.id === "formula.mutation.set-super-table" || command.id === "formula.mutation.remove-super-table") && hasUnitId(command.params) && this._projectionManagedTableUnits.has(command.params.unitId))
1166
+ return !1;
1167
+ let syncOptions = options;
1168
+ if (syncOptions?.fromRustFormulaEngine === !0 || syncOptions?.applyFormulaCalculationResult === !0 || command.id === "sheet.mutation.set-range-values" && !hasObjectMatrixValues(command.params?.cellValue))
1169
+ return !1;
1170
+ if (command.id === "formula.mutation.set-formula-calculation-result") {
1171
+ let params = command.params;
1172
+ if (!hasRecordEntries(params?.unitData) && !hasRecordEntries(params?.unitOtherData))
1173
+ return !1;
1174
+ }
1175
+ if (command.id === "formula.mutation.set-array-formula-data") {
1176
+ let params = command.params;
1177
+ if (!hasRecordEntries(params?.arrayFormulaRange) && !hasRecordEntries(params?.arrayFormulaCellData) && !hasRecordEntries(params?.arrayFormulaEmbedded))
1178
+ return !1;
1179
+ }
1180
+ return !0;
1181
+ }
1182
+ _serializeMutation(command, options) {
1183
+ let dirtyRanges = options?.dirtyRanges;
1184
+ return {
1185
+ id: command.id,
1186
+ params: command.params ?? {},
1187
+ dirtyRanges: Array.isArray(dirtyRanges) ? dirtyRanges : []
1188
+ };
1189
+ }
1190
+ };
1191
+ function hasUnitId(value) {
1192
+ return value != null && typeof value == "object" && "unitId" in value && typeof value.unitId == "string";
1193
+ }
1194
+ setDependencies(RustEngineSyncController, [ICommandService]);
1195
+
1196
+ // src/numfmt.ts
1197
+ var nativeBindingReady = null;
1198
+ function ensureNativeBinding() {
1199
+ return nativeBindingReady ??= loadNativeBinding().catch((error) => {
1200
+ throw nativeBindingReady = null, error;
1201
+ }), nativeBindingReady;
1202
+ }
1203
+ function parseJsonOutput(output) {
1204
+ return JSON.parse(output);
1205
+ }
1206
+ async function formatNumberBatch(input) {
1207
+ return await ensureNativeBinding(), parseJsonOutput(formatNumberBatchOnRust(JSON.stringify(input)));
1208
+ }
1209
+ async function parseNumberFormatBatch(input) {
1210
+ return await ensureNativeBinding(), parseJsonOutput(parseNumberFormatInputBatchOnRust(JSON.stringify(input)));
1211
+ }
1212
+ async function parseNumberFormatMatrixBatch(input) {
1213
+ return await ensureNativeBinding(), parseJsonOutput(
1214
+ parseNumberFormatMatrixBatchOnRust(JSON.stringify(input))
1215
+ );
1216
+ }
1217
+ async function analyzeNumberFormatBatch(input) {
1218
+ return await ensureNativeBinding(), parseJsonOutput(analyzeNumberFormatBatchOnRust(JSON.stringify(input)));
1219
+ }
1220
+
1221
+ // src/plugin.ts
1222
+ import { IConfigService as IConfigService2, Injector, setDependencies as setDependencies4, touchDependencies } from "@univerjs/core";
1223
+ import { ICalculateFormulaService } from "@univerjs/engine-formula";
1224
+ import { UniverProFormulaEnginePlugin } from "@univerjs-pro/engine-formula";
1225
+
1226
+ // package.json
1227
+ var name = "@univerjs-pro/engine-formula-rust", version = "1.0.0-beta.2";
1228
+
1229
+ // src/controllers/rust-same-runtime-projection.controller.ts
1230
+ import {
1231
+ CellValueType as CellValueType2,
1232
+ CommandType as CommandType2,
1233
+ createBaseFormulaTableReferenceNormalizer,
1234
+ createBaseFormulaTableNameMap,
1235
+ Disposable as Disposable2,
1236
+ ICommandService as ICommandService2,
1237
+ IUniverInstanceService,
1238
+ LocaleType,
1239
+ ObjectMatrix as ObjectMatrix2,
1240
+ setDependencies as setDependencies2,
1241
+ toDisposable,
1242
+ UniverInstanceType
1243
+ } from "@univerjs/core";
1244
+ import {
1245
+ FormulaDataModel,
1246
+ IActiveDirtyManagerService,
1247
+ ISuperTableService,
1248
+ SetFormulaCalculationResultMutation
1249
+ } from "@univerjs/engine-formula";
1250
+ var RustSameRuntimeProjectionController = class extends Disposable2 {
1251
+ constructor(_univerInstanceService, _rustEngineSyncController, _formulaDataModel, _superTableService, _commandService, _activeDirtyManagerService) {
1252
+ super();
1253
+ this._univerInstanceService = _univerInstanceService;
1254
+ this._rustEngineSyncController = _rustEngineSyncController;
1255
+ this._formulaDataModel = _formulaDataModel;
1256
+ this._superTableService = _superTableService;
1257
+ this._commandService = _commandService;
1258
+ this._activeDirtyManagerService = _activeDirtyManagerService;
1259
+ this._initialize();
1260
+ }
1261
+ _univerInstanceService;
1262
+ _rustEngineSyncController;
1263
+ _formulaDataModel;
1264
+ _superTableService;
1265
+ _commandService;
1266
+ _activeDirtyManagerService;
1267
+ _initialProjectionLoad = Promise.resolve();
1268
+ _projectionDeltaQueue = Promise.resolve();
1269
+ _baseProjectionStructures = /* @__PURE__ */ new Map();
1270
+ _initialize() {
1271
+ for (let base of this._univerInstanceService.getAllUnitsForType(
1272
+ UniverInstanceType.UNIVER_BASE
1273
+ ))
1274
+ this._rustEngineSyncController.setProjectionManagedTableUnit(base.getUnitId()), this._rememberBaseProjectionStructure(base.getSnapshot());
1275
+ this._initialProjectionLoad = this._loadAllWorkbookProjections(), this.disposeWithMe(
1276
+ toDisposable(
1277
+ this._univerInstanceService.getTypeOfUnitAdded$(UniverInstanceType.UNIVER_SHEET).subscribe(({ unit }) => {
1278
+ this._enqueueProjectionDelta(() => {
1279
+ this._rustEngineSyncController.upsertProjectionWorkbook({
1280
+ unitId: unit.getUnitId(),
1281
+ snapshot: unit.getSnapshot()
1282
+ });
1283
+ });
1284
+ })
1285
+ )
1286
+ ), this.disposeWithMe(
1287
+ toDisposable(
1288
+ this._univerInstanceService.getTypeOfUnitAdded$(UniverInstanceType.UNIVER_BASE).subscribe(({ unit }) => {
1289
+ this._rustEngineSyncController.setProjectionManagedTableUnit(unit.getUnitId()), this._rememberBaseProjectionStructure(unit.getSnapshot()), this._enqueueProjectionDelta(() => this._upsertBaseProjection(unit.getUnitId()));
1290
+ })
1291
+ )
1292
+ ), this.disposeWithMe(
1293
+ this._commandService.onCommandExecuted((command) => {
1294
+ command.type !== CommandType2.MUTATION || !hasUnitId2(command.params) || this._univerInstanceService.getUnit(command.params.unitId, UniverInstanceType.UNIVER_BASE) && (hasTrigger(command.params) && command.params.trigger === SetFormulaCalculationResultMutation.id || isRustFormulaRelevantMutation(command.id) || this._enqueueProjectionDelta(() => this._syncBaseMutation(command)));
1295
+ })
1296
+ ), this.disposeWithMe(
1297
+ toDisposable(
1298
+ this._univerInstanceService.getTypeOfUnitDisposed$(UniverInstanceType.UNIVER_BASE).subscribe((base) => {
1299
+ this._baseProjectionStructures.delete(base.getUnitId()), this._rustEngineSyncController.unsetProjectionManagedTableUnit(base.getUnitId()), this._enqueueProjectionDelta(
1300
+ () => this._rustEngineSyncController.disposeProjectionWorkbook(base.getUnitId())
1301
+ );
1302
+ })
1303
+ )
1304
+ ), this.disposeWithMe(
1305
+ toDisposable(
1306
+ this._univerInstanceService.getTypeOfUnitDisposed$(UniverInstanceType.UNIVER_SHEET).subscribe((workbook) => {
1307
+ this._enqueueProjectionDelta(
1308
+ () => this._rustEngineSyncController.disposeProjectionWorkbook(workbook.getUnitId())
1309
+ );
1310
+ })
1311
+ )
1312
+ ), this.disposeWithMe(
1313
+ toDisposable(() => {
1314
+ this._projectionDeltaQueue = Promise.resolve();
1315
+ })
1316
+ );
1317
+ }
1318
+ _enqueueProjectionDelta(task) {
1319
+ this._projectionDeltaQueue = this._projectionDeltaQueue.then(() => this._initialProjectionLoad).then(() => {
1320
+ if (!this._disposed)
1321
+ return task();
1322
+ }).catch(() => {
1323
+ }), this._rustEngineSyncController.setProjectionDeltaBarrier(this._projectionDeltaQueue);
1324
+ }
1325
+ async _syncBaseMutation(command) {
1326
+ if (!hasUnitId2(command.params)) return;
1327
+ let unitId = command.params.unitId, dirtyData = this._activeDirtyManagerService.get(command.id)?.getDirtyData(command), dirtyRanges = (dirtyData?.dirtyRanges ?? []).filter((dirtyRange) => dirtyRange.unitId === unitId), hasStructureInvalidation = !!dirtyData?.clearDependencyTreeCache?.[unitId] || !!(dirtyData?.forceCalculation && dirtyRanges.length === 0);
1328
+ if (dirtyRanges.length > 0 && !hasStructureInvalidation) {
1329
+ this._applyBaseDirtyRanges(unitId, dirtyRanges);
1330
+ return;
1331
+ }
1332
+ hasStructureInvalidation && this._isBaseProjectionStructureUnchanged(unitId) || hasStructureInvalidation && this._applyBaseFieldInsertion(unitId, dirtyRanges) || await this._upsertBaseProjection(unitId);
1333
+ }
1334
+ _applyBaseFieldInsertion(unitId, dirtyRanges) {
1335
+ let base = this._univerInstanceService.getUnit(unitId, UniverInstanceType.UNIVER_BASE), previous = this._baseProjectionStructures.get(unitId);
1336
+ if (!base || !previous) return !1;
1337
+ let snapshot = base.getSnapshot(), insertion = findSingleBaseFieldInsertion(previous, snapshot);
1338
+ if (!insertion) return !1;
1339
+ let projectionData = this._getBaseProjectionData(unitId), sheet = projectionData?.calculationData.allUnitData[unitId]?.[insertion.tableId];
1340
+ if (!projectionData || !sheet) return !1;
1341
+ let formulaData = projectionData.formulaData[unitId]?.[insertion.tableId], cellValue = {};
1342
+ for (let row = 0; row < sheet.rowCount; row++) {
1343
+ let value = sheet.cellData.getValue(row, insertion.column), formula = formulaData?.[row]?.[insertion.column];
1344
+ cellValue[row] = {
1345
+ [insertion.column]: formula ? { ...value, ...formula } : value ?? null
1346
+ };
1347
+ }
1348
+ let insertedRange = {
1349
+ startRow: 0,
1350
+ endRow: Math.max(0, sheet.rowCount - 1),
1351
+ startColumn: insertion.column,
1352
+ endColumn: insertion.column
1353
+ };
1354
+ return this._rustEngineSyncController.applyProjectionMutation({
1355
+ id: "sheet.mutation.insert-col",
1356
+ params: {
1357
+ unitId,
1358
+ subUnitId: insertion.tableId,
1359
+ range: insertedRange
1360
+ },
1361
+ dirtyRanges: []
1362
+ }), this._rustEngineSyncController.applyProjectionMutation({
1363
+ id: "sheet.mutation.set-range-values",
1364
+ params: {
1365
+ unitId,
1366
+ subUnitId: insertion.tableId,
1367
+ cellValue
1368
+ },
1369
+ dirtyRanges: [
1370
+ {
1371
+ unitId,
1372
+ sheetId: insertion.tableId,
1373
+ range: insertedRange
1374
+ }
1375
+ ]
1376
+ }), this._rustEngineSyncController.applyProjectionMutation({
1377
+ id: RUST_SET_SUPER_TABLES_MUTATION_ID,
1378
+ params: {
1379
+ unitId,
1380
+ tables: this._getBaseTableEntries(
1381
+ insertion.tableId,
1382
+ snapshot,
1383
+ createBaseFormulaTableNameMap(snapshot)
1384
+ ).map(([tableName, reference]) => ({
1385
+ tableName,
1386
+ reference
1387
+ }))
1388
+ },
1389
+ dirtyRanges: []
1390
+ }), dirtyRanges.length > 0 && this._applyBaseDirtyRanges(unitId, dirtyRanges), this._rememberBaseProjectionStructure(snapshot), !0;
1391
+ }
1392
+ _applyBaseDirtyRanges(unitId, dirtyRanges) {
1393
+ let projectionData = this._getBaseProjectionData(unitId);
1394
+ if (!projectionData) return;
1395
+ let { calculationData, formulaData } = projectionData, rangesBySheet = /* @__PURE__ */ new Map();
1396
+ for (let dirtyRange of dirtyRanges) {
1397
+ let ranges = rangesBySheet.get(dirtyRange.sheetId) ?? [];
1398
+ ranges.push(dirtyRange), rangesBySheet.set(dirtyRange.sheetId, ranges);
1399
+ }
1400
+ for (let [sheetId, ranges] of rangesBySheet) {
1401
+ let sheet = calculationData.allUnitData[unitId]?.[sheetId];
1402
+ if (!sheet) continue;
1403
+ let cellValue = {};
1404
+ for (let { range } of ranges)
1405
+ for (let row = range.startRow; row <= range.endRow; row++)
1406
+ for (let column = range.startColumn; column <= range.endColumn; column++) {
1407
+ let value = sheet.cellData.getValue(row, column), formula = formulaData[unitId]?.[sheetId]?.[row]?.[column];
1408
+ (cellValue[row] ??= {})[column] = formula ? { ...value, ...formula } : value ?? null;
1409
+ }
1410
+ this._rustEngineSyncController.applyProjectionMutation({
1411
+ id: "sheet.mutation.set-range-values",
1412
+ params: {
1413
+ unitId,
1414
+ subUnitId: sheetId,
1415
+ cellValue
1416
+ },
1417
+ dirtyRanges: ranges
1418
+ });
1419
+ }
1420
+ }
1421
+ async _upsertBaseProjection(unitId) {
1422
+ let projectionData = this._getBaseProjectionData(unitId);
1423
+ if (!projectionData) return;
1424
+ let { calculationData, formulaData } = projectionData, workbook = this._createBaseWorkbookProjection(
1425
+ unitId,
1426
+ calculationData.allUnitData,
1427
+ calculationData.unitSheetNameMap,
1428
+ calculationData.unitNameMap,
1429
+ formulaData
1430
+ );
1431
+ workbook && this._rustEngineSyncController.upsertProjectionWorkbook(workbook);
1432
+ let base = this._univerInstanceService.getUnit(unitId, UniverInstanceType.UNIVER_BASE);
1433
+ base && this._rememberBaseProjectionStructure(base.getSnapshot());
1434
+ }
1435
+ _rememberBaseProjectionStructure(snapshot) {
1436
+ this._baseProjectionStructures.set(snapshot.id, createBaseProjectionStructure(snapshot));
1437
+ }
1438
+ _isBaseProjectionStructureUnchanged(unitId) {
1439
+ let base = this._univerInstanceService.getUnit(unitId, UniverInstanceType.UNIVER_BASE), previous = this._baseProjectionStructures.get(unitId);
1440
+ return !!(base && previous && isSameBaseProjectionStructure(previous, createBaseProjectionStructure(base.getSnapshot())));
1441
+ }
1442
+ _getBaseProjectionData(unitId) {
1443
+ let base = this._univerInstanceService.getUnit(unitId, UniverInstanceType.UNIVER_BASE);
1444
+ if (!base) return null;
1445
+ let snapshot = base.getSnapshot(), allUnitData = { [unitId]: {} }, unitSheetNameMap = { [unitId]: {} }, unitNameMap = {
1446
+ [unitId]: {
1447
+ name: snapshot.name,
1448
+ unitType: UniverInstanceType.UNIVER_BASE
1449
+ }
1450
+ }, formulaData = { [unitId]: {} }, formulaTableNames = createBaseFormulaTableNameMap(snapshot), normalizeFormulaTableReferences = createBaseFormulaTableReferenceNormalizer(snapshot, formulaTableNames);
1451
+ for (let table of Object.values(snapshot.tables)) {
1452
+ let fieldOrder = table.fieldOrder;
1453
+ allUnitData[unitId][table.id] = {
1454
+ cellData: new ObjectMatrix2(
1455
+ buildBaseRuntimeCellData(table)
1456
+ ),
1457
+ rowCount: baseRecordOrder(table).length,
1458
+ columnCount: fieldOrder.length,
1459
+ rowData: {},
1460
+ columnData: {}
1461
+ }, unitSheetNameMap[unitId][formulaTableNames.get(table.id)] = table.id;
1462
+ let tableFormulaData = {}, normalizedFormulaByFieldId = /* @__PURE__ */ new Map(), recordOrder = baseRecordOrder(table);
1463
+ for (let row = 0; row < recordOrder.length; row++)
1464
+ if (table.records[recordOrder[row]])
1465
+ for (let column = 0; column < fieldOrder.length; column++) {
1466
+ let field = table.fields[fieldOrder[column]];
1467
+ if (!field || field.type !== "formula") continue;
1468
+ let formula = String(field.config?.formula ?? "").trim();
1469
+ if (!formula) continue;
1470
+ let normalizedFormula = normalizedFormulaByFieldId.get(field.id);
1471
+ normalizedFormula == null && (normalizedFormula = normalizeBaseFormulaForEngine(
1472
+ formula,
1473
+ table,
1474
+ formulaTableNames,
1475
+ normalizeFormulaTableReferences
1476
+ ), normalizedFormulaByFieldId.set(field.id, normalizedFormula)), (tableFormulaData[row] ??= {})[column] = {
1477
+ f: normalizedFormula,
1478
+ si: field.id
1479
+ };
1480
+ }
1481
+ formulaData[unitId][table.id] = tableFormulaData;
1482
+ }
1483
+ return {
1484
+ calculationData: {
1485
+ allUnitData,
1486
+ unitSheetNameMap,
1487
+ unitNameMap
1488
+ },
1489
+ formulaData
1490
+ };
1491
+ }
1492
+ async _loadAllWorkbookProjections() {
1493
+ let workbooks = this._univerInstanceService.getAllUnitsForType(UniverInstanceType.UNIVER_SHEET).map((workbook) => ({
1494
+ unitId: workbook.getUnitId(),
1495
+ snapshot: workbook.getSnapshot()
1496
+ })), calculationData = this._formulaDataModel.getCalculateData(), formulaData = this._formulaDataModel.getFormulaData(), baseWorkbooks = this._univerInstanceService.getAllUnitsForType(UniverInstanceType.UNIVER_BASE).map(
1497
+ (base) => this._createBaseWorkbookProjection(
1498
+ base.getUnitId(),
1499
+ calculationData.allUnitData,
1500
+ calculationData.unitSheetNameMap,
1501
+ calculationData.unitNameMap ?? {},
1502
+ formulaData
1503
+ )
1504
+ ).filter((workbook) => workbook != null);
1505
+ workbooks.push(...baseWorkbooks), await this._rustEngineSyncController.loadProjection(workbooks);
1506
+ }
1507
+ _createBaseWorkbookProjection(unitId, allUnitData, unitSheetNameMap, unitNameMap, formulaData) {
1508
+ let unitData = allUnitData[unitId];
1509
+ if (!unitData) return null;
1510
+ let sheetNameMap = unitSheetNameMap[unitId] ?? {}, sheetOrder = Object.keys(unitData), resources = this._createBaseTableResource(unitId), sheets = {};
1511
+ for (let sheetId of sheetOrder) {
1512
+ let sheet = unitData[sheetId];
1513
+ if (!sheet) continue;
1514
+ let cellData = this._rawCellData(sheet.cellData);
1515
+ for (let [rowKey, row] of Object.entries(formulaData[unitId]?.[sheetId] ?? {}))
1516
+ for (let [columnKey, formula] of Object.entries(row ?? {})) {
1517
+ if (!formula) continue;
1518
+ let rowIndex = Number(rowKey), columnIndex = Number(columnKey), current = cellData[rowIndex]?.[columnIndex] ?? {};
1519
+ (cellData[rowIndex] ??= {})[columnIndex] = { ...current, ...formula };
1520
+ }
1521
+ sheets[sheetId] = {
1522
+ id: sheetId,
1523
+ name: Object.entries(sheetNameMap).find(([, currentSheetId]) => currentSheetId === sheetId)?.[0] ?? sheetId,
1524
+ rowCount: sheet.rowCount,
1525
+ columnCount: sheet.columnCount,
1526
+ cellData,
1527
+ rowData: sheet.rowData,
1528
+ columnData: sheet.columnData
1529
+ };
1530
+ }
1531
+ return {
1532
+ unitId,
1533
+ snapshot: {
1534
+ id: unitId,
1535
+ name: unitNameMap[unitId]?.name ?? unitId,
1536
+ appVersion: "",
1537
+ locale: LocaleType.EN_US,
1538
+ styles: {},
1539
+ sheetOrder,
1540
+ sheets,
1541
+ resources
1542
+ }
1543
+ };
1544
+ }
1545
+ _createBaseTableResource(unitId) {
1546
+ let base = this._univerInstanceService.getUnit(unitId, UniverInstanceType.UNIVER_BASE);
1547
+ if (base) {
1548
+ let snapshot = base.getSnapshot(), tables = Object.values(snapshot.tables), formulaTableNames = createBaseFormulaTableNameMap(snapshot), data2 = {};
1549
+ for (let table of tables)
1550
+ for (let [name2, reference] of this._getBaseTableEntries(table.id, snapshot, formulaTableNames)) {
1551
+ let columns = Array.from(reference.titleMap.entries()).toSorted((left, right) => left[1] - right[1]).map(([displayName]) => ({ displayName }));
1552
+ (data2[table.id] ??= { tables: [] }).tables.push({
1553
+ name: name2,
1554
+ range: reference.range,
1555
+ columns,
1556
+ options: { showHeader: reference.showHeader !== !1 }
1557
+ });
1558
+ }
1559
+ return [
1560
+ {
1561
+ name: "SHEET_TABLE_PLUGIN",
1562
+ data: JSON.stringify(data2)
1563
+ }
1564
+ ];
1565
+ }
1566
+ let tableMap = this._superTableService.getTableMap(unitId);
1567
+ if (!tableMap) return [];
1568
+ let data = {};
1569
+ for (let [name2, table] of tableMap) {
1570
+ let columns = Array.from(table.titleMap.entries()).toSorted((left, right) => left[1] - right[1]).map(([displayName]) => ({ displayName }));
1571
+ (data[table.sheetId] ??= { tables: [] }).tables.push({
1572
+ name: name2,
1573
+ range: table.range,
1574
+ columns,
1575
+ options: { showHeader: table.showHeader !== !1 }
1576
+ });
1577
+ }
1578
+ return [
1579
+ {
1580
+ name: "SHEET_TABLE_PLUGIN",
1581
+ data: JSON.stringify(data)
1582
+ }
1583
+ ];
1584
+ }
1585
+ _getBaseTableEntries(tableId, snapshot, formulaTableNames) {
1586
+ let table = snapshot.tables[tableId];
1587
+ if (!table) return [];
1588
+ let recordCount = baseRecordOrder(table).length, fieldOrder = table.fieldOrder, reference = {
1589
+ sheetId: table.id,
1590
+ range: {
1591
+ startRow: 0,
1592
+ endRow: Math.max(0, recordCount - 1),
1593
+ startColumn: 0,
1594
+ endColumn: Math.max(0, fieldOrder.length - 1)
1595
+ },
1596
+ titleMap: new Map(fieldOrder.map((fieldId, index) => [table.fields[fieldId]?.name ?? fieldId, index])),
1597
+ showHeader: !1
1598
+ };
1599
+ return [[formulaTableNames.get(table.id), reference]];
1600
+ }
1601
+ _rawCellData(cellData) {
1602
+ let raw = cellData.getMatrix(), result = {};
1603
+ for (let [row, values] of Object.entries(raw ?? {})) {
1604
+ let rowData = {};
1605
+ for (let [column, value] of Object.entries(values ?? {}))
1606
+ value && (rowData[Number(column)] = { ...value });
1607
+ result[Number(row)] = rowData;
1608
+ }
1609
+ return result;
1610
+ }
1611
+ };
1612
+ function createBaseProjectionStructure(snapshot) {
1613
+ let formulaTableNames = createBaseFormulaTableNameMap(snapshot);
1614
+ return {
1615
+ unitName: snapshot.name,
1616
+ tables: Object.fromEntries(
1617
+ Object.values(snapshot.tables).map((table) => [
1618
+ table.id,
1619
+ {
1620
+ formulaName: formulaTableNames.get(table.id),
1621
+ fieldOrder: [...table.fieldOrder],
1622
+ recordOrder: baseRecordOrder(table),
1623
+ fieldSignatures: Object.fromEntries(
1624
+ Object.entries(table.fields).map(([fieldId, field]) => [fieldId, JSON.stringify(field)])
1625
+ )
1626
+ }
1627
+ ])
1628
+ )
1629
+ };
1630
+ }
1631
+ function isSameBaseProjectionStructure(left, right) {
1632
+ return JSON.stringify(left) === JSON.stringify(right);
1633
+ }
1634
+ function findSingleBaseFieldInsertion(previous, snapshot) {
1635
+ let current = createBaseProjectionStructure(snapshot), previousTableIds = Object.keys(previous.tables).toSorted(), currentTableIds = Object.keys(current.tables).toSorted();
1636
+ if (JSON.stringify(previousTableIds) !== JSON.stringify(currentTableIds)) return null;
1637
+ let insertion = null;
1638
+ for (let tableId of currentTableIds) {
1639
+ let before = previous.tables[tableId], after = current.tables[tableId];
1640
+ if (!before || !after || before.formulaName !== after.formulaName || JSON.stringify(before.recordOrder) !== JSON.stringify(after.recordOrder)) return null;
1641
+ for (let fieldId of before.fieldOrder)
1642
+ if (before.fieldSignatures[fieldId] !== after.fieldSignatures[fieldId]) return null;
1643
+ if (JSON.stringify(before.fieldOrder) === JSON.stringify(after.fieldOrder)) continue;
1644
+ if (insertion || after.fieldOrder.length !== before.fieldOrder.length + 1) return null;
1645
+ let column = after.fieldOrder.findIndex((fieldId, index) => fieldId !== before.fieldOrder[index]);
1646
+ if (column < 0) return null;
1647
+ let withoutInserted = after.fieldOrder.filter((_, index) => index !== column);
1648
+ if (JSON.stringify(withoutInserted) !== JSON.stringify(before.fieldOrder)) return null;
1649
+ insertion = { tableId, column };
1650
+ }
1651
+ return insertion;
1652
+ }
1653
+ 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;
1654
+ function normalizeBaseFormulaForEngine(formula, currentTable, formulaTableNames, normalizeFormulaTableReferences) {
1655
+ let canonicalFormula = normalizeFormulaTableReferences(formula), references = [], hold = (reference) => `__BASE_FORMULA_REF_${references.push(reference) - 1}__`;
1656
+ return protectBaseTableReferences(protectBaseExternalReferences(canonicalFormula, hold), hold).replace(
1657
+ BASE_LEGACY_FIELD_REF_PATTERN,
1658
+ (_match, fieldName) => hold(createEngineThisRowRef(currentTable, fieldName, formulaTableNames))
1659
+ ).replace(BASE_SCOPED_FIELD_REF_PATTERN, (_match, prefix, scope, fieldName) => {
1660
+ let tableName = formulaTableNames.get(currentTable.id) ?? currentTable.name;
1661
+ return `${prefix}${hold(`${tableName}[[#${scope}],[${fieldName}]]`)}`;
1662
+ }).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(
1663
+ /__BASE_FORMULA_REF_(\d+)__/g,
1664
+ (_match, index) => references[Number(index)] ?? ""
1665
+ );
1666
+ }
1667
+ function protectBaseTableReferences(formula, replace) {
1668
+ return protectBaseStructuredReferences(formula, BASE_TABLE_REFERENCE_PREFIX, replace);
1669
+ }
1670
+ function protectBaseExternalReferences(formula, replace) {
1671
+ let withProtectedA1 = formula.replace(
1672
+ BASE_EXTERNAL_A1_REF_PATTERN,
1673
+ (reference, offset) => isInsideBaseFormulaString(formula, offset) ? reference : replace(reference)
1674
+ );
1675
+ return protectBaseExternalStructuredReferences(withProtectedA1, replace);
1676
+ }
1677
+ function protectBaseExternalStructuredReferences(formula, replace) {
1678
+ return protectBaseStructuredReferences(formula, BASE_EXTERNAL_STRUCTURED_REFERENCE_PREFIX, replace);
1679
+ }
1680
+ function protectBaseStructuredReferences(formula, prefixPattern, replace) {
1681
+ let spans = [];
1682
+ prefixPattern.lastIndex = 0;
1683
+ let match;
1684
+ for (; (match = prefixPattern.exec(formula)) != null; ) {
1685
+ if (isInsideBaseFormulaString(formula, match.index)) continue;
1686
+ let openBracket = prefixPattern.lastIndex - 1, depth = 0;
1687
+ for (let index = openBracket; index < formula.length; index++)
1688
+ if (formula[index] === "[" && depth++, formula[index] === "]" && (depth--, depth === 0)) {
1689
+ spans.push({ start: match.index, end: index + 1 }), prefixPattern.lastIndex = index + 1;
1690
+ break;
1691
+ }
1692
+ }
1693
+ if (spans.length === 0) return formula;
1694
+ let result = "", offset = 0;
1695
+ for (let span of spans)
1696
+ result += formula.slice(offset, span.start), result += replace(formula.slice(span.start, span.end)), offset = span.end;
1697
+ return result + formula.slice(offset);
1698
+ }
1699
+ function isInsideBaseFormulaString(formula, position) {
1700
+ let inString = !1;
1701
+ for (let index = 0; index < position; index++)
1702
+ if (formula[index] === '"') {
1703
+ if (inString && formula[index + 1] === '"') {
1704
+ index++;
1705
+ continue;
1706
+ }
1707
+ inString = !inString;
1708
+ }
1709
+ return inString;
1710
+ }
1711
+ function createEngineThisRowRef(table, fieldName, formulaTableNames) {
1712
+ return `${formulaTableNames.get(table.id) ?? table.name}[[#This Row],[${fieldName}]]`;
1713
+ }
1714
+ function baseRecordOrder(table) {
1715
+ 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);
1716
+ }
1717
+ function buildBaseRuntimeCellData(table) {
1718
+ let cellData = { ...table.cellData }, fieldOrder = table.fieldOrder, recordOrder = baseRecordOrder(table);
1719
+ for (let row = 0; row < recordOrder.length; row++) {
1720
+ let record = table.records[recordOrder[row]];
1721
+ if (record) {
1722
+ cellData[row] = { ...cellData[row] };
1723
+ for (let column = 0; column < fieldOrder.length; column++) {
1724
+ let fieldId = fieldOrder[column];
1725
+ table.fields[fieldId] && Object.prototype.hasOwnProperty.call(record.values ?? {}, fieldId) && (cellData[row][column] = toBaseRuntimeCellData(record.values[fieldId], table.fields[fieldId]));
1726
+ }
1727
+ }
1728
+ }
1729
+ return cellData;
1730
+ }
1731
+ function toBaseRuntimeCellData(value, field) {
1732
+ if (isBaseCellData(value))
1733
+ return { ...value, t: inferBaseRuntimeCellType(value.v ?? null) };
1734
+ if (field?.type === "attachment")
1735
+ return { v: "", t: CellValueType2.STRING };
1736
+ if (Array.isArray(value))
1737
+ return { v: value.join(", "), t: CellValueType2.STRING };
1738
+ if (field?.type === "link" && value && typeof value == "object") {
1739
+ let link = value;
1740
+ return { v: String(link.text ?? link.url ?? ""), t: CellValueType2.STRING };
1741
+ }
1742
+ return value === null || typeof value == "string" || typeof value == "number" || typeof value == "boolean" ? { v: value, t: inferBaseRuntimeCellType(value) } : { v: null, t: null };
1743
+ }
1744
+ function inferBaseRuntimeCellType(value) {
1745
+ return typeof value == "number" ? CellValueType2.NUMBER : typeof value == "boolean" ? CellValueType2.BOOLEAN : typeof value == "string" ? CellValueType2.STRING : null;
1746
+ }
1747
+ function isBaseCellData(value) {
1748
+ return value != null && typeof value == "object" && ["v", "t", "p", "f", "si"].some((key) => Object.prototype.hasOwnProperty.call(value, key));
1749
+ }
1750
+ function hasUnitId2(value) {
1751
+ return value != null && typeof value == "object" && "unitId" in value && typeof value.unitId == "string";
1752
+ }
1753
+ function hasTrigger(value) {
1754
+ return "trigger" in value && typeof value.trigger == "string";
1755
+ }
1756
+ setDependencies2(RustSameRuntimeProjectionController, [
1757
+ IUniverInstanceService,
1758
+ RustEngineSyncController,
1759
+ FormulaDataModel,
1760
+ ISuperTableService,
1761
+ ICommandService2,
1762
+ IActiveDirtyManagerService
1763
+ ]);
1764
+
1765
+ // src/services/calculate-formula.service.ts
1766
+ import {
1767
+ AsyncLock,
1768
+ createIdentifier,
1769
+ Disposable as Disposable3,
1770
+ ICommandService as ICommandService3,
1771
+ IConfigService,
1772
+ ObjectMatrix as ObjectMatrix3,
1773
+ setDependencies as setDependencies3
1774
+ } from "@univerjs/core";
1775
+ import {
1776
+ ENGINE_FORMULA_PLUGIN_CONFIG_KEY,
1777
+ FormulaDataModel as FormulaDataModel2,
1778
+ FormulaExecuteStageType,
1779
+ IFeatureCalculationManagerService,
1780
+ IFormulaCurrentConfigService,
1781
+ IFormulaDependencyGenerator,
1782
+ IFormulaRuntimeService,
1783
+ IOtherFormulaManagerService,
1784
+ ISuperTableService as ISuperTableService2,
1785
+ SetArrayFormulaDataMutation,
1786
+ SetFormulaCalculationResultMutation as SetFormulaCalculationResultMutation2
1787
+ } from "@univerjs/engine-formula";
1788
+ import {
1789
+ ExternalReferenceModel,
1790
+ IFormulaReferenceDataService
1791
+ } from "@univerjs-pro/engine-formula";
1792
+ import { Subject } from "rxjs";
1793
+ var IRustCalculateFormulaService = createIdentifier(
1794
+ "engine-formula-rust.calculate-formula.service"
1795
+ ), DEFAULT_INTERVAL_COUNT = 500, MAX_FEATURE_CALCULATION_PASSES = 8, MAX_EXTERNAL_REFERENCE_PASSES = 8, FORMULA_TREE_TYPE_NORMAL = 0, FORMULA_TREE_TYPE_OTHER = 1, FORMULA_TREE_TYPE_FEATURE = 2;
1796
+ function serializeRuntimeFeatureCellData(runtimeCellData) {
1797
+ let result = {};
1798
+ return Object.entries(runtimeCellData ?? {}).forEach(([unitId, sheetMap]) => {
1799
+ if (!sheetMap) return;
1800
+ let unitData = {};
1801
+ result[unitId] = unitData, Object.entries(sheetMap).forEach(([sheetId, matrix]) => {
1802
+ if (!matrix) return;
1803
+ let sheetData = {};
1804
+ unitData[sheetId] = sheetData, matrix.forValue((row, column, cell) => {
1805
+ if (cell == null) return;
1806
+ let rowData = sheetData[row] ??= {};
1807
+ rowData[column] = {
1808
+ v: cell.v,
1809
+ ...typeof cell.t == "number" ? { t: cell.t } : {},
1810
+ ...cell.p != null ? { p: cell.p } : {},
1811
+ ...typeof cell.f == "string" ? { f: cell.f } : {},
1812
+ ...typeof cell.si == "string" ? { si: cell.si } : {},
1813
+ ...typeof cell.ref == "string" ? { ref: cell.ref } : {},
1814
+ ...typeof cell.xf == "string" ? { xf: cell.xf } : {},
1815
+ ...cell.s != null ? { s: cell.s } : {}
1816
+ };
1817
+ });
1818
+ });
1819
+ }), result;
1820
+ }
1821
+ function emitRustFormulaDebugEvent(event) {
1822
+ let hook = globalThis.__UNIVER_RUST_FORMULA_DEBUG_HOOK__;
1823
+ typeof hook == "function" && hook(event);
1824
+ }
1825
+ function firstResultBatchValue(output) {
1826
+ return output.resultBatches?.find((batch) => batch.values.length > 0)?.values[0];
1827
+ }
1828
+ function resultBatchSheetCounts(output) {
1829
+ let counts = {};
1830
+ for (let batch of output.resultBatches ?? []) {
1831
+ let key = `${batch.unitId}/${batch.sheetId}`;
1832
+ counts[key] = (counts[key] ?? 0) + batch.values.length;
1833
+ }
1834
+ return counts;
1835
+ }
1836
+ var RustCalculateFormulaService = class extends Disposable3 {
1837
+ constructor(_configService, _currentConfigService, _runtimeService, _formulaDependencyGenerator, _featureCalculationManagerService, _otherFormulaManagerService, _commandService, _rustEngineSyncController, _formulaDataModel, _formulaReferenceDataService, _excelExternalReferenceModel, _superTableService) {
1838
+ super();
1839
+ this._configService = _configService;
1840
+ this._currentConfigService = _currentConfigService;
1841
+ this._runtimeService = _runtimeService;
1842
+ this._formulaDependencyGenerator = _formulaDependencyGenerator;
1843
+ this._featureCalculationManagerService = _featureCalculationManagerService;
1844
+ this._otherFormulaManagerService = _otherFormulaManagerService;
1845
+ this._commandService = _commandService;
1846
+ this._rustEngineSyncController = _rustEngineSyncController;
1847
+ this._formulaDataModel = _formulaDataModel;
1848
+ this._formulaReferenceDataService = _formulaReferenceDataService;
1849
+ this._excelExternalReferenceModel = _excelExternalReferenceModel;
1850
+ this._superTableService = _superTableService;
1851
+ this._commandService.hasCommand(SetFormulaCalculationResultMutation2.id) || this.disposeWithMe(this._commandService.registerCommand(SetFormulaCalculationResultMutation2)), this._commandService.hasCommand(SetArrayFormulaDataMutation.id) || this.disposeWithMe(this._commandService.registerCommand(SetArrayFormulaDataMutation));
1852
+ }
1853
+ _configService;
1854
+ _currentConfigService;
1855
+ _runtimeService;
1856
+ _formulaDependencyGenerator;
1857
+ _featureCalculationManagerService;
1858
+ _otherFormulaManagerService;
1859
+ _commandService;
1860
+ _rustEngineSyncController;
1861
+ _formulaDataModel;
1862
+ _formulaReferenceDataService;
1863
+ _excelExternalReferenceModel;
1864
+ _superTableService;
1865
+ _executionInProgressListener$ = new Subject();
1866
+ executionInProgressListener$ = this._executionInProgressListener$.asObservable();
1867
+ _executionCompleteListener$ = new Subject();
1868
+ executionCompleteListener$ = this._executionCompleteListener$.asObservable();
1869
+ _executeLock = new AsyncLock();
1870
+ _nativeLoaded = !1;
1871
+ _syncedSnapshotEpoch = -1;
1872
+ _syncedDependencyInvalidationEpoch = -1;
1873
+ _syncedExternalReferenceSignature = "{}";
1874
+ _externalFormulaDatasetConfig;
1875
+ _externalRequestCounter = 0;
1876
+ _externalRequestGeneration = -1;
1877
+ _externalInflight = /* @__PURE__ */ new Map();
1878
+ _externalCompleted = /* @__PURE__ */ new Map();
1879
+ dispose() {
1880
+ super.dispose(), this._executionInProgressListener$.complete(), this._executionCompleteListener$.complete();
1881
+ }
1882
+ stopFormulaExecution() {
1883
+ this._runtimeService.stopExecution();
1884
+ }
1885
+ setRuntimeFeatureCellData(featureId, featureData) {
1886
+ this._runtimeService.setRuntimeFeatureCellData(featureId, featureData);
1887
+ }
1888
+ setRuntimeFeatureRange(featureId, featureRange) {
1889
+ this._runtimeService.setRuntimeFeatureRange(featureId, featureRange);
1890
+ }
1891
+ async execute(formulaDatasetConfig) {
1892
+ 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(FormulaExecuteStageType.START), this._executionInProgressListener$.next(this._runtimeService.getRuntimeState()), this._runtimeService.reset();
1893
+ let cycleReferenceCount = Math.max(formulaDatasetConfig.maxIteration || 1, 1);
1894
+ await this._executeLock.acquire("FORMULA_EXECUTION_LOCK", async () => {
1895
+ this._runtimeService.setFormulaCycleIndex(0), await this._executeStep(cycleReferenceCount) > 0 ? this._runtimeService.markedAsSuccessfullyExecuted() : this._runtimeService.markedAsNoFunctionsExecuted(), this._runtimeService.setFormulaExecuteStage(FormulaExecuteStageType.CALCULATION_COMPLETED), this._executionInProgressListener$.next(this._runtimeService.getRuntimeState()), this._executionCompleteListener$.next(this._runtimeService.getAllRuntimeData()), this._runtimeService.reset();
1896
+ });
1897
+ }
1898
+ async _executeStep(maxIteration) {
1899
+ 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;
1900
+ output = await this._resolveExternalReferenceNeeds(output, maxIteration);
1901
+ let applyStartedAt = performance.now(), applyBreakdown = await this._applyRustDependencyOutput(output), applyMs = performance.now() - applyStartedAt;
1902
+ if (emitRustFormulaDebugEvent({
1903
+ type: "executeDirtyFormulas",
1904
+ payload: {
1905
+ calculatedNodeCount: output.calculatedNodeCount,
1906
+ hasCycle: output.hasCycle,
1907
+ cycleIterationCount: output.cycleIterationCount,
1908
+ parallelBatchCount: output.parallelBatchCount,
1909
+ parallelNodeCount: output.parallelNodeCount,
1910
+ errorCount: output.errors.length,
1911
+ resultBatchCount: output.resultBatches?.length ?? 0,
1912
+ firstResultBatchValue: firstResultBatchValue(output),
1913
+ resultBatchSheetCounts: resultBatchSheetCounts(output),
1914
+ timings: output.timings,
1915
+ functionProfile: output.functionProfile,
1916
+ bridgeTimings: {
1917
+ nativeAndSerializeMs,
1918
+ outputBytes: outputJson.length,
1919
+ parseMs,
1920
+ applyMs,
1921
+ applyConvertMs: applyBreakdown.convertMs,
1922
+ applyCommandMs: applyBreakdown.commandMs
1923
+ }
1924
+ }
1925
+ }), syncedFeatures.length > 0)
1926
+ for (let pass = 0; pass < MAX_FEATURE_CALCULATION_PASSES; pass++) {
1927
+ let refreshedFeatures = this._syncRustFormulaDependencyDefinitions(), changedFeatures = refreshedFeatures.filter(
1928
+ (feature) => previousFeatureSignatures.get(this._featureKey(feature)) !== feature.signature
1929
+ );
1930
+ if (changedFeatures.length === 0)
1931
+ break;
1932
+ this._markRustFormulaDirty(
1933
+ this._currentConfigService.getDirtyData(),
1934
+ this._dirtyFeatureMapFor(changedFeatures)
1935
+ ), 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({
1936
+ type: "executeDirtyFormulas",
1937
+ payload: {
1938
+ calculatedNodeCount: output.calculatedNodeCount,
1939
+ hasCycle: output.hasCycle,
1940
+ cycleIterationCount: output.cycleIterationCount,
1941
+ parallelBatchCount: output.parallelBatchCount,
1942
+ parallelNodeCount: output.parallelNodeCount,
1943
+ errorCount: output.errors.length,
1944
+ resultBatchCount: output.resultBatches?.length ?? 0,
1945
+ firstResultBatchValue: firstResultBatchValue(output),
1946
+ resultBatchSheetCounts: resultBatchSheetCounts(output),
1947
+ timings: output.timings,
1948
+ functionProfile: output.functionProfile,
1949
+ bridgeTimings: {
1950
+ nativeAndSerializeMs,
1951
+ outputBytes: outputJson.length,
1952
+ parseMs,
1953
+ applyMs,
1954
+ applyConvertMs: applyBreakdown.convertMs,
1955
+ applyCommandMs: applyBreakdown.commandMs
1956
+ }
1957
+ }
1958
+ }), previousFeatureSignatures = this._featureSignatureMap(refreshedFeatures);
1959
+ }
1960
+ return calculatedNodeCount;
1961
+ }
1962
+ async _resolveExternalReferenceNeeds(initialOutput, maxIteration) {
1963
+ let config = this._externalFormulaDatasetConfig;
1964
+ if (!config) return initialOutput;
1965
+ let output = initialOutput;
1966
+ for (let pass = 0; pass < MAX_EXTERNAL_REFERENCE_PASSES; pass++) {
1967
+ let rangeNeeds = output.needsData ?? [], tableNeeds = output.tableNeedsData ?? [];
1968
+ if (rangeNeeds.length === 0 && tableNeeds.length === 0) break;
1969
+ let loadedRanges = await this._loadExternalReferenceNeeds(config, output, rangeNeeds, tableNeeds);
1970
+ if (loadedRanges.length === 0 || this._rustEngineSyncController.upsertReferenceData(
1971
+ {
1972
+ ...config,
1973
+ allUnitData: this._currentConfigService.getUnitData(),
1974
+ unitSheetNameMap: this._currentConfigService.getSheetNameMap(),
1975
+ unitNameMap: this._currentConfigService.getUnitNameMap()
1976
+ },
1977
+ loadedRanges,
1978
+ this._superTableService
1979
+ ) === 0) break;
1980
+ this._syncRustFormulaDependencies(), output = JSON.parse(executeDirtyFormulasOnRust(maxIteration, !1, !1, !0));
1981
+ }
1982
+ return output;
1983
+ }
1984
+ async _loadExternalReferenceNeeds(config, output, rangeNeeds, tableNeeds) {
1985
+ let loaded = [];
1986
+ for (let need of rangeNeeds) {
1987
+ let binding = this._resolveRustExternalBinding(config, need.unitId);
1988
+ !binding || await this._loadRustExternalReference(binding, {
1989
+ sheetName: need.sheetId,
1990
+ range: need.range
1991
+ }) !== !0 || loaded.push({
1992
+ ...need,
1993
+ ...binding.dataUnitId !== need.unitId ? { dataUnitId: binding.dataUnitId } : {}
1994
+ });
1995
+ }
1996
+ for (let need of tableNeeds) {
1997
+ let binding = this._resolveRustExternalBinding(config, need.unitId);
1998
+ if (!binding) continue;
1999
+ let loadedReference = await this._loadRustExternalReference(binding, {
2000
+ tableName: need.tableName
2001
+ });
2002
+ if (loadedReference !== !0) {
2003
+ this._applyTableReferenceLoadError(output, need, loadedReference);
2004
+ continue;
2005
+ }
2006
+ let table = this._superTableService.getTable(binding.dataUnitId, need.tableName);
2007
+ table && loaded.push({
2008
+ unitId: need.unitId,
2009
+ dataUnitId: binding.dataUnitId,
2010
+ tableName: need.tableName,
2011
+ sheetId: table.sheetId,
2012
+ range: table.range
2013
+ });
2014
+ }
2015
+ return loaded;
2016
+ }
2017
+ _applyTableReferenceLoadError(output, need, error) {
2018
+ if (need.formulaId) {
2019
+ let unit = output.otherFormulaData ??= {}, sheet = unit[need.ownerUnitId] ??= {}, formulas = sheet[need.ownerSheetId] ??= {}, rows = formulas[need.formulaId] ??= {}, columns = rows[need.row] ??= {};
2020
+ columns[need.column] = error;
2021
+ return;
2022
+ }
2023
+ let batch = output.resultBatches.find(
2024
+ (candidate) => candidate.unitId === need.ownerUnitId && candidate.sheetId === need.ownerSheetId
2025
+ ) ?? {
2026
+ unitId: need.ownerUnitId,
2027
+ sheetId: need.ownerSheetId,
2028
+ rows: [],
2029
+ cols: [],
2030
+ values: []
2031
+ };
2032
+ output.resultBatches.includes(batch) || output.resultBatches.push(batch);
2033
+ let index = batch.rows.findIndex((row, index2) => row === need.row && batch.cols[index2] === need.column);
2034
+ index >= 0 ? batch.values[index] = error : (batch.rows.push(need.row), batch.cols.push(need.column), batch.values.push(error));
2035
+ }
2036
+ async _loadRustExternalReference(binding, range) {
2037
+ let generation = this._externalRequestGeneration, calculationId = `rust-formula-calculation-${generation}`, request = {
2038
+ requestId: `rust-external-request-${++this._externalRequestCounter}`,
2039
+ calculationId,
2040
+ hostUnitId: binding.hostUnitId,
2041
+ ...binding.referenceId ? { referenceId: binding.referenceId } : {},
2042
+ ...binding.bindingSlot ? { bindingSlot: binding.bindingSlot } : {},
2043
+ syntheticUnitId: binding.dataUnitId,
2044
+ target: binding.target,
2045
+ ranges: [range],
2046
+ requireFresh: !0
2047
+ }, key = [
2048
+ generation,
2049
+ binding.hostUnitId,
2050
+ binding.dataUnitId,
2051
+ range.sheetName,
2052
+ range.sheetId,
2053
+ range.tableName,
2054
+ range.range?.startRow,
2055
+ range.range?.endRow,
2056
+ range.range?.startColumn,
2057
+ range.range?.endColumn
2058
+ ].join("\0"), completed = this._externalCompleted.get(key);
2059
+ if (completed != null)
2060
+ return completed;
2061
+ let pending = this._externalInflight.get(key);
2062
+ pending || (pending = this._formulaReferenceDataService.readData(
2063
+ request
2064
+ ), this._externalInflight.set(key, pending));
2065
+ let response;
2066
+ try {
2067
+ response = await pending;
2068
+ } finally {
2069
+ this._externalInflight.get(key) === pending && this._externalInflight.delete(key);
2070
+ }
2071
+ return generation !== this._externalRequestGeneration || response.calculationId !== calculationId ? "#N/A" : response.error ? (this._externalCompleted.set(key, response.error), response.error) : response.sheets.length === 0 ? (this._externalCompleted.set(key, "#N/A"), "#N/A") : (this._materializeRustExternalReference(response, binding), this._externalCompleted.set(key, !0), !0);
2072
+ }
2073
+ _materializeRustExternalReference(response, binding) {
2074
+ let unitData = this._currentConfigService.getUnitData(), sheetNameMap = this._currentConfigService.getSheetNameMap(), unitNameMap = this._currentConfigService.getUnitNameMap(), sheets = unitData[binding.dataUnitId] ?? {}, names = sheetNameMap[binding.dataUnitId] ?? {};
2075
+ for (let responseSheet of response.sheets) {
2076
+ let current = sheets[responseSheet.sheetId], cellData = current?.cellData ?? new ObjectMatrix3();
2077
+ for (let { row, column, cell } of responseSheet.cells)
2078
+ cellData.setValue(row, column, cell);
2079
+ sheets[responseSheet.sheetId] = {
2080
+ cellData,
2081
+ rowCount: Math.max(current?.rowCount ?? 0, responseSheet.rowCount),
2082
+ columnCount: Math.max(current?.columnCount ?? 0, responseSheet.columnCount),
2083
+ rowData: current?.rowData ?? {},
2084
+ columnData: current?.columnData ?? {}
2085
+ }, names[responseSheet.name] = responseSheet.sheetId;
2086
+ }
2087
+ unitData[binding.dataUnitId] = sheets, sheetNameMap[binding.dataUnitId] = names, unitNameMap[binding.dataUnitId] = {
2088
+ name: unitNameMap[binding.dataUnitId]?.name ?? binding.qualifier,
2089
+ unitType: binding.target.unitType
2090
+ }, this._currentConfigService.registerUnitData(unitData), this._currentConfigService.registerSheetNameMap(sheetNameMap), this._currentConfigService.registerUnitNameMap(unitNameMap);
2091
+ for (let table of response.tables ?? [])
2092
+ this._superTableService.registerTable(binding.dataUnitId, table.name, {
2093
+ sheetId: table.sheetId,
2094
+ range: table.range,
2095
+ titleMap: new Map(table.columns.map((column, index) => [column, index])),
2096
+ showHeader: table.showHeader
2097
+ });
2098
+ }
2099
+ _resolveRustExternalBinding(config, unitId) {
2100
+ let externalReferences = config.externalReferences ?? {};
2101
+ for (let [hostUnitId, resource] of Object.entries(externalReferences))
2102
+ for (let [referenceId, reference] of Object.entries(resource.references))
2103
+ if (createRustProductExternalSyntheticUnitId(hostUnitId, referenceId) === unitId)
2104
+ return {
2105
+ hostUnitId,
2106
+ dataUnitId: reference.sourceUnitId,
2107
+ qualifier: reference.qualifier,
2108
+ referenceId,
2109
+ target: {
2110
+ name: reference.qualifier,
2111
+ unitType: reference.sourceUnitType,
2112
+ sourceUnitId: reference.sourceUnitId
2113
+ }
2114
+ };
2115
+ let ooxml = this._parseOoxmlExternalSyntheticUnitId(unitId);
2116
+ if (!ooxml) return;
2117
+ let binding = this._excelExternalReferenceModel.resolveBinding(ooxml.hostUnitId, String(ooxml.slot));
2118
+ if (binding.status === "resolved")
2119
+ return {
2120
+ hostUnitId: ooxml.hostUnitId,
2121
+ dataUnitId: unitId,
2122
+ qualifier: String(ooxml.slot),
2123
+ bindingSlot: ooxml.slot,
2124
+ target: binding.link.target
2125
+ };
2126
+ }
2127
+ _parseOoxmlExternalSyntheticUnitId(unitId) {
2128
+ if (!unitId.startsWith("external:") || unitId.startsWith("external:product:")) return;
2129
+ let separator = unitId.lastIndexOf(":");
2130
+ if (!(separator <= 9 || !/^\d+$/.test(unitId.slice(separator + 1))))
2131
+ try {
2132
+ return {
2133
+ hostUnitId: decodeURIComponent(unitId.slice(9, separator)),
2134
+ slot: Number(unitId.slice(separator + 1))
2135
+ };
2136
+ } catch {
2137
+ return;
2138
+ }
2139
+ }
2140
+ _buildRustInput() {
2141
+ let unitData = this._currentConfigService.getUnitData(), formulaData = this._currentConfigService.getFormulaData(), dirtyRanges = this._currentConfigService.getDirtyRanges(), config = this._configService.getConfig(ENGINE_FORMULA_PLUGIN_CONFIG_KEY);
2142
+ return {
2143
+ config: {
2144
+ maxIteration: config?.maxIteration ?? 1,
2145
+ intervalCount: config?.intervalCount ?? DEFAULT_INTERVAL_COUNT
2146
+ },
2147
+ formulaData: this._serializeFormulaData(formulaData),
2148
+ unitData: this._serializeUnitData(unitData),
2149
+ dirtyRanges: dirtyRanges || [],
2150
+ definedNames: {}
2151
+ };
2152
+ }
2153
+ _syncRustFormulaDependencies(dirtyUnitFeatureMapOverride, includeExternalReferences = !1) {
2154
+ 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;
2155
+ if (!(shouldSendExternalReferences || rebuildSheetFormulas || state.featureCalculations.length > 0 || state.otherFormulas.length > 0))
2156
+ return emitRustFormulaDebugEvent({
2157
+ type: "syncDependencies",
2158
+ payload: {
2159
+ rebuildSheetFormulas,
2160
+ skipped: !0,
2161
+ featureCalculationCount: 0,
2162
+ otherFormulaCount: 0,
2163
+ syncedFeatureCount: 0,
2164
+ timings: {
2165
+ collectMs,
2166
+ stringifyMs: 0,
2167
+ nativeMs: 0,
2168
+ parseMs: 0,
2169
+ totalMs: collectMs
2170
+ }
2171
+ }
2172
+ }), this._markRustFormulaDirty(state.dirtyData, dirtyUnitFeatureMapOverride, rebuildSheetFormulas), state.syncedFeatures;
2173
+ let stringifyStartedAt = performance.now(), inputJson = JSON.stringify({
2174
+ rebuildSheetFormulas,
2175
+ featureCalculations: state.featureCalculations,
2176
+ otherFormulas: state.otherFormulas,
2177
+ ...shouldSendExternalReferences ? { externalReferences } : {}
2178
+ }), 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;
2179
+ return emitRustFormulaDebugEvent({
2180
+ type: "syncDependencies",
2181
+ payload: {
2182
+ rebuildSheetFormulas,
2183
+ skipped: !1,
2184
+ featureCalculationCount: state.featureCalculations.length,
2185
+ otherFormulaCount: state.otherFormulas.length,
2186
+ syncedFeatureCount: state.syncedFeatures.length,
2187
+ timings: {
2188
+ collectMs,
2189
+ stringifyMs,
2190
+ nativeMs,
2191
+ parseMs,
2192
+ totalMs: collectMs + stringifyMs + nativeMs + parseMs,
2193
+ rust: output.timings
2194
+ }
2195
+ }
2196
+ }), rebuildSheetFormulas && (this._syncedSnapshotEpoch = syncState.snapshotEpoch, this._syncedDependencyInvalidationEpoch = syncState.dependencyInvalidationEpoch), includeExternalReferences && (this._syncedExternalReferenceSignature = externalReferenceSignature), this._markRustFormulaDirty(state.dirtyData, dirtyUnitFeatureMapOverride, rebuildSheetFormulas), state.syncedFeatures;
2197
+ }
2198
+ _syncRustFormulaDependencyDefinitions() {
2199
+ let state = this._collectRustFormulaDependencySyncState();
2200
+ return syncRustFormulaDependenciesOnRust(
2201
+ JSON.stringify({
2202
+ rebuildSheetFormulas: !1,
2203
+ featureCalculations: state.featureCalculations,
2204
+ otherFormulas: state.otherFormulas
2205
+ })
2206
+ ), state.syncedFeatures;
2207
+ }
2208
+ _collectRustFormulaDependencySyncState() {
2209
+ let featureCalculations = [], syncedFeatures = [], dirtyData = this._currentConfigService.getDirtyData(), runtimeData = this._runtimeService.getAllRuntimeData();
2210
+ this._featureCalculationManagerService.getReferenceExecutorMap().forEach((sheetMap) => {
2211
+ sheetMap.forEach((featureMap) => {
2212
+ featureMap.forEach((params, featureId) => {
2213
+ let { runtimeCellData, dirtyRanges: featureDirtyRanges } = params.getDirtyData(
2214
+ dirtyData,
2215
+ runtimeData
2216
+ ), serializedDirtyRanges = this._serializeFeatureDirtyRanges(featureDirtyRanges), serializedRuntimeCellData = serializeRuntimeFeatureCellData(runtimeCellData);
2217
+ this._runtimeService.setRuntimeFeatureCellData(featureId, runtimeCellData), this._runtimeService.setRuntimeFeatureRange(featureId, featureDirtyRanges), featureCalculations.push({
2218
+ unitId: params.unitId,
2219
+ sheetId: params.subUnitId,
2220
+ featureId,
2221
+ dependencyRanges: params.dependencyRanges.map((range) => ({
2222
+ unitId: range.unitId,
2223
+ sheetId: range.sheetId,
2224
+ startRow: range.range.startRow,
2225
+ endRow: range.range.endRow,
2226
+ startColumn: range.range.startColumn,
2227
+ endColumn: range.range.endColumn
2228
+ })),
2229
+ dirtyRanges: serializedDirtyRanges,
2230
+ runtimeCellData: serializedRuntimeCellData
2231
+ }), syncedFeatures.push({
2232
+ unitId: params.unitId,
2233
+ sheetId: params.subUnitId,
2234
+ featureId,
2235
+ signature: JSON.stringify({
2236
+ dirtyRanges: serializedDirtyRanges,
2237
+ runtimeCellData: serializedRuntimeCellData
2238
+ })
2239
+ });
2240
+ });
2241
+ });
2242
+ });
2243
+ let otherFormulas = [], otherFormulaData = this._otherFormulaManagerService.getOtherFormulaData();
2244
+ return Object.entries(otherFormulaData).forEach(([unitId, sheetMap]) => {
2245
+ sheetMap && Object.entries(sheetMap).forEach(([sheetId, formulaMap]) => {
2246
+ formulaMap && Object.entries(formulaMap).forEach(([formulaId, item]) => {
2247
+ item && otherFormulas.push({
2248
+ unitId,
2249
+ sheetId,
2250
+ formulaId,
2251
+ formula: item.f,
2252
+ ranges: item.ranges
2253
+ });
2254
+ });
2255
+ });
2256
+ }), { dirtyData, featureCalculations, otherFormulas, syncedFeatures };
2257
+ }
2258
+ _markRustFormulaDirty(dirtyData, dirtyUnitFeatureMapOverride, forceCalculationOverride = !1) {
2259
+ let payload = {
2260
+ forceCalculation: forceCalculationOverride || dirtyData.forceCalculation,
2261
+ includeDirtyNodes: !1,
2262
+ includeCalculationOrder: !1,
2263
+ dirtyRanges: (dirtyData.dirtyRanges ?? []).map((range) => ({
2264
+ unitId: range.unitId,
2265
+ sheetId: range.sheetId,
2266
+ startRow: range.range.startRow,
2267
+ endRow: range.range.endRow,
2268
+ startColumn: range.range.startColumn,
2269
+ endColumn: range.range.endColumn
2270
+ })),
2271
+ dirtyUnitFeatureMap: dirtyUnitFeatureMapOverride ?? dirtyData.dirtyUnitFeatureMap,
2272
+ dirtyUnitOtherFormulaMap: dirtyData.dirtyUnitOtherFormulaMap,
2273
+ dirtyNameMap: dirtyData.dirtyNameMap,
2274
+ dirtyDefinedNameMap: dirtyData.dirtyDefinedNameMap
2275
+ }, stringifyStartedAt = performance.now(), inputJson = JSON.stringify(payload), stringifyMs = performance.now() - stringifyStartedAt, nativeStartedAt = performance.now(), outputJson = markRustFormulaDirtyOnRust(inputJson), nativeMs = performance.now() - nativeStartedAt, rustTimings;
2276
+ try {
2277
+ rustTimings = JSON.parse(outputJson).timings;
2278
+ } catch {
2279
+ rustTimings = void 0;
2280
+ }
2281
+ emitRustFormulaDebugEvent({
2282
+ type: "markDirty",
2283
+ payload: {
2284
+ ...payload,
2285
+ timings: {
2286
+ stringifyMs,
2287
+ nativeMs,
2288
+ totalMs: stringifyMs + nativeMs
2289
+ },
2290
+ rustTimings
2291
+ }
2292
+ });
2293
+ }
2294
+ _dirtyFeatureMapFor(features) {
2295
+ let dirtyMap = {};
2296
+ return features.forEach(({ unitId, sheetId, featureId }) => {
2297
+ dirtyMap[unitId] = dirtyMap[unitId] ?? {}, dirtyMap[unitId][sheetId] = dirtyMap[unitId][sheetId] ?? {}, dirtyMap[unitId][sheetId][featureId] = !0;
2298
+ }), dirtyMap;
2299
+ }
2300
+ _featureKey(feature) {
2301
+ return `${feature.unitId}\0${feature.sheetId}\0${feature.featureId}`;
2302
+ }
2303
+ _featureSignatureMap(features) {
2304
+ return new Map(features.map((feature) => [this._featureKey(feature), feature.signature]));
2305
+ }
2306
+ _serializeFeatureDirtyRanges(dirtyRanges) {
2307
+ let serialized = [];
2308
+ return Object.entries(dirtyRanges).forEach(([unitId, sheetMap]) => {
2309
+ sheetMap && Object.entries(sheetMap).forEach(([sheetId, ranges]) => {
2310
+ ranges && ranges.forEach((range) => {
2311
+ serialized.push({
2312
+ unitId,
2313
+ sheetId,
2314
+ startRow: range.startRow,
2315
+ endRow: range.endRow,
2316
+ startColumn: range.startColumn,
2317
+ endColumn: range.endColumn
2318
+ });
2319
+ });
2320
+ });
2321
+ }), serialized;
2322
+ }
2323
+ _serializeFormulaData(formulaData) {
2324
+ let result = {};
2325
+ if (!formulaData || typeof formulaData != "object") return result;
2326
+ for (let [unitId, sheets] of Object.entries(formulaData))
2327
+ if (!(!sheets || typeof sheets != "object")) {
2328
+ result[unitId] = {};
2329
+ for (let [sheetId, rows] of Object.entries(sheets))
2330
+ if (!(!rows || typeof rows != "object")) {
2331
+ result[unitId][sheetId] = {};
2332
+ for (let [rowStr, cols] of Object.entries(rows)) {
2333
+ if (!cols || typeof cols != "object")
2334
+ continue;
2335
+ let row = Number(rowStr);
2336
+ result[unitId][sheetId][row] = {};
2337
+ for (let [colStr, item] of Object.entries(cols)) {
2338
+ let col = Number(colStr);
2339
+ if (typeof item == "string")
2340
+ result[unitId][sheetId][row][col] = item;
2341
+ else if (item && typeof item == "object" && typeof item.f == "string") {
2342
+ let formulaItem = item;
2343
+ result[unitId][sheetId][row][col] = {
2344
+ f: formulaItem.f,
2345
+ si: typeof formulaItem.si == "string" ? formulaItem.si : void 0,
2346
+ ref: typeof formulaItem.ref == "string" ? formulaItem.ref : void 0,
2347
+ x: typeof formulaItem.x == "number" ? formulaItem.x : void 0,
2348
+ y: typeof formulaItem.y == "number" ? formulaItem.y : void 0
2349
+ };
2350
+ }
2351
+ }
2352
+ }
2353
+ }
2354
+ }
2355
+ return result;
2356
+ }
2357
+ _serializeUnitData(unitData) {
2358
+ let result = {};
2359
+ if (!unitData) return result;
2360
+ for (let [unitId, sheets] of Object.entries(unitData)) {
2361
+ result[unitId] = {};
2362
+ for (let [sheetId, sheet] of Object.entries(sheets))
2363
+ result[unitId][sheetId] = {
2364
+ cellData: this._serializeCellData(sheet.cellData),
2365
+ rowCount: sheet.rowCount ?? 0,
2366
+ columnCount: sheet.columnCount ?? 0
2367
+ };
2368
+ }
2369
+ return result;
2370
+ }
2371
+ _serializeCellData(cellData) {
2372
+ let result = {};
2373
+ if (!cellData || typeof cellData != "object") return result;
2374
+ let data = typeof cellData.getMatrix == "function" ? cellData.getMatrix() : cellData;
2375
+ for (let [rowStr, cols] of Object.entries(data)) {
2376
+ let row = Number(rowStr);
2377
+ if (Number.isFinite(row)) {
2378
+ result[row] = {};
2379
+ for (let [colStr, cell] of Object.entries(cols)) {
2380
+ let col = Number(colStr);
2381
+ Number.isFinite(col) && (result[row][col] = {
2382
+ v: cell?.v ?? null,
2383
+ t: cell?.t ?? void 0,
2384
+ p: cell?.p ?? void 0,
2385
+ f: cell?.f ?? void 0,
2386
+ s: cell?.s ?? void 0
2387
+ });
2388
+ }
2389
+ }
2390
+ }
2391
+ return result;
2392
+ }
2393
+ _applyRustOutput(_output) {
2394
+ }
2395
+ async _applyRustDependencyOutput(output) {
2396
+ let convertStartedAt = performance.now(), patch = rustExecutionOutputToFormulaCalculationPatch(output), convertMs = performance.now() - convertStartedAt, commandStartedAt = performance.now();
2397
+ return (patch.arrayFormulaRange || patch.arrayFormulaCellData) && (this._formulaDataModel.setArrayFormulaRange(patch.arrayFormulaRange ?? {}), this._formulaDataModel.setArrayFormulaCellData(patch.arrayFormulaCellData ?? {}), await this._commandService.executeCommand(
2398
+ SetArrayFormulaDataMutation.id,
2399
+ {
2400
+ arrayFormulaRange: this._formulaDataModel.getArrayFormulaRange(),
2401
+ arrayFormulaCellData: this._formulaDataModel.getArrayFormulaCellData(),
2402
+ arrayFormulaEmbedded: {}
2403
+ },
2404
+ {
2405
+ onlyLocal: !0,
2406
+ fromRustFormulaEngine: !0
2407
+ }
2408
+ )), await this._commandService.executeCommand(
2409
+ SetFormulaCalculationResultMutation2.id,
2410
+ {
2411
+ unitData: patch.unitData,
2412
+ unitOtherData: patch.unitOtherData
2413
+ },
2414
+ {
2415
+ onlyLocal: !0,
2416
+ fromRustFormulaEngine: !0
2417
+ }
2418
+ ), {
2419
+ convertMs,
2420
+ commandMs: performance.now() - commandStartedAt
2421
+ };
2422
+ }
2423
+ async calculate(formulaString) {
2424
+ this._nativeLoaded || (await loadNativeBinding(), this._nativeLoaded = !0);
2425
+ let unitId = "__rust_formula_calculate__", sheetId = "__sheet__", input = {
2426
+ config: { maxIteration: 1, intervalCount: DEFAULT_INTERVAL_COUNT },
2427
+ formulaData: {
2428
+ [unitId]: {
2429
+ [sheetId]: {
2430
+ 0: { 0: formulaString }
2431
+ }
2432
+ }
2433
+ },
2434
+ unitData: {
2435
+ [unitId]: {
2436
+ [sheetId]: {
2437
+ rowCount: 1,
2438
+ columnCount: 1,
2439
+ cellData: {}
2440
+ }
2441
+ }
2442
+ },
2443
+ dirtyRanges: [],
2444
+ definedNames: {}
2445
+ };
2446
+ return JSON.parse(executeOnRust(JSON.stringify(input))).runtimeData?.[unitId]?.[sheetId]?.[0]?.[0] ?? null;
2447
+ }
2448
+ async executeFormulas(formulas, rowData) {
2449
+ this._nativeLoaded || (await loadNativeBinding(), this._nativeLoaded = !0), this._currentConfigService.loadDataLite(rowData);
2450
+ let unitData = this._currentConfigService.getUnitData(), formulaData = this._formulaStringMapToFormulaData(formulas), input = {
2451
+ config: { maxIteration: 1, intervalCount: DEFAULT_INTERVAL_COUNT },
2452
+ formulaData,
2453
+ unitData: this._serializeUnitData(unitData),
2454
+ dirtyRanges: [],
2455
+ definedNames: {}
2456
+ }, output = JSON.parse(executeOnRust(JSON.stringify(input)));
2457
+ return this._formulaExecutionOutputToResultMap(formulas, output);
2458
+ }
2459
+ async getAllDependencyJson(_rowData) {
2460
+ this._nativeLoaded || (await loadNativeBinding(), this._nativeLoaded = !0), this._syncRustFormulaDependencyDefinitions();
2461
+ let graph = this._getRustDependencyGraph(), inspect = this._getRustInspectGraph();
2462
+ return this._rustAllDependencyJson(graph, inspect);
2463
+ }
2464
+ async getCellDependencyJson(unitId, sheetId, row, column, _rowData) {
2465
+ this._nativeLoaded || (await loadNativeBinding(), this._nativeLoaded = !0), this._syncRustFormulaDependencyDefinitions();
2466
+ let graph = this._getRustDependencyGraph(unitId), all = this._rustGraphDependencyJson(graph), current = all.find(
2467
+ (item) => item.unitId === unitId && item.subUnitId === sheetId && item.row === row && item.column === column
2468
+ );
2469
+ if (!current)
2470
+ return;
2471
+ let byId = new Map(all.map((item) => [item.treeId, item]));
2472
+ return {
2473
+ ...current,
2474
+ children: current.children.map((id) => byId.get(id)).filter(isFormulaDependencyTreeJson),
2475
+ parents: current.parents.map((id) => byId.get(id)).filter(isFormulaDependencyTreeJson)
2476
+ };
2477
+ }
2478
+ async getRangeDependents(unitRanges) {
2479
+ this._nativeLoaded || (await loadNativeBinding(), this._nativeLoaded = !0), this._syncRustFormulaDependencyDefinitions();
2480
+ let graph = this._getRustDependencyGraph(), graphItems = this._rustGraphDependencyJson(graph), graphByCell = this._rustDependencyJsonByCell(graphItems), dirty = JSON.parse(
2481
+ getRustDirtyDependenciesOnRust(JSON.stringify(this._serializeUnitRanges(unitRanges)))
2482
+ );
2483
+ return this._uniqueDependencyJson(
2484
+ (dirty.direct ?? dirty.affected ?? []).map((cell) => graphByCell.get(this._cellKey(cell))).filter(Boolean)
2485
+ );
2486
+ }
2487
+ async getInRangeFormulas(unitRanges) {
2488
+ return this._nativeLoaded || (await loadNativeBinding(), this._nativeLoaded = !0), this._syncRustFormulaDependencyDefinitions(), this._rustGraphDependencyJson(this._getRustDependencyGraph()).filter(
2489
+ (item) => this._cellInUnitRanges(item.unitId, item.subUnitId, item.row, item.column, unitRanges)
2490
+ );
2491
+ }
2492
+ async getDependentsAndInRangeFormulas(unitRanges) {
2493
+ let [dependents, inRanges] = await Promise.all([
2494
+ this.getRangeDependents(unitRanges),
2495
+ this.getInRangeFormulas(unitRanges)
2496
+ ]);
2497
+ return { dependents, inRanges };
2498
+ }
2499
+ _formulaStringMapToFormulaData(formulas) {
2500
+ let formulaData = {};
2501
+ return Object.entries(formulas).forEach(([unitId, sheetMap]) => {
2502
+ sheetMap && (formulaData[unitId] = {}, Object.entries(sheetMap).forEach(([sheetId, rowMap]) => {
2503
+ rowMap && (formulaData[unitId][sheetId] = {}, Object.entries(rowMap).forEach(([rowKey, colMap]) => {
2504
+ if (!colMap) return;
2505
+ let row = Number(rowKey);
2506
+ formulaData[unitId][sheetId][row] = {}, Object.entries(colMap).forEach(([colKey, formulaList]) => {
2507
+ let formula = Array.isArray(formulaList) ? formulaList[0] : void 0;
2508
+ typeof formula == "string" && (formulaData[unitId][sheetId][row][Number(colKey)] = formula);
2509
+ });
2510
+ }));
2511
+ }));
2512
+ }), formulaData;
2513
+ }
2514
+ _formulaExecutionOutputToResultMap(formulas, output) {
2515
+ let result = {};
2516
+ return Object.entries(formulas).forEach(([unitId, sheetMap]) => {
2517
+ sheetMap && (result[unitId] = {}, Object.entries(sheetMap).forEach(([sheetId, rowMap]) => {
2518
+ rowMap && (result[unitId][sheetId] = {}, Object.entries(rowMap).forEach(([rowKey, colMap]) => {
2519
+ if (!colMap) return;
2520
+ let row = Number(rowKey);
2521
+ result[unitId][sheetId][row] = {}, Object.entries(colMap).forEach(([colKey, formulaList]) => {
2522
+ let col = Number(colKey), formulasForCell = Array.isArray(formulaList) ? formulaList : [], value = normalizeFormulaResultValue(
2523
+ output.runtimeData?.[unitId]?.[sheetId]?.[row]?.[col]
2524
+ );
2525
+ result[unitId][sheetId][row][col] = formulasForCell.map((formula) => ({ formula, value }));
2526
+ });
2527
+ }));
2528
+ }));
2529
+ }), result;
2530
+ }
2531
+ _getRustDependencyGraph(unitId) {
2532
+ return JSON.parse(buildRustDependencyGraphOnRust(unitId));
2533
+ }
2534
+ _getRustInspectGraph() {
2535
+ return JSON.parse(inspectRustFormulaDependencyGraphOnRust());
2536
+ }
2537
+ _rustAllDependencyJson(graph, inspect) {
2538
+ 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));
2539
+ return this._uniqueDependencyJson([...cellItems, ...nonCellItems]);
2540
+ }
2541
+ _rustGraphDependencyJson(graph) {
2542
+ return (graph.nodes ?? []).map((node) => this._rustDependencyNodeToJson(node));
2543
+ }
2544
+ _rustDependencyNodeToJson(node) {
2545
+ return {
2546
+ children: node.children ?? [],
2547
+ parents: node.parents ?? [],
2548
+ treeId: node.id,
2549
+ formula: node.formula,
2550
+ row: node.row,
2551
+ column: node.column,
2552
+ unitId: node.unitId,
2553
+ subUnitId: node.sheetId,
2554
+ refOffsetX: node.offsetX ?? 0,
2555
+ refOffsetY: node.offsetY ?? 0,
2556
+ rangeList: (node.precedentRanges ?? []).map((range) => this._rustRangeToUnitRange(range)),
2557
+ refTreeId: void 0,
2558
+ formulaId: node.formulaId ?? null,
2559
+ featureId: null,
2560
+ type: FORMULA_TREE_TYPE_NORMAL
2561
+ };
2562
+ }
2563
+ _rustFormulaNodeToDependencyJson(index, node) {
2564
+ return {
2565
+ children: [],
2566
+ parents: [],
2567
+ treeId: index,
2568
+ formula: "",
2569
+ row: node.row ?? -1,
2570
+ column: node.column ?? -1,
2571
+ unitId: node.unitId ?? "",
2572
+ subUnitId: node.sheetId ?? "",
2573
+ refOffsetX: node.refOffsetX ?? 0,
2574
+ refOffsetY: node.refOffsetY ?? 0,
2575
+ rangeList: [],
2576
+ refTreeId: void 0,
2577
+ formulaId: node.formulaId ?? null,
2578
+ featureId: node.featureId ?? null,
2579
+ type: node.nodeType === "featureCalculation" ? FORMULA_TREE_TYPE_FEATURE : FORMULA_TREE_TYPE_OTHER
2580
+ };
2581
+ }
2582
+ _rustRangeToUnitRange(range) {
2583
+ return {
2584
+ unitId: range.unitId,
2585
+ sheetId: range.sheetId,
2586
+ range: {
2587
+ startRow: range.startRow,
2588
+ endRow: range.endRow,
2589
+ startColumn: range.startColumn,
2590
+ endColumn: range.endColumn
2591
+ }
2592
+ };
2593
+ }
2594
+ _serializeUnitRanges(unitRanges) {
2595
+ return unitRanges.map((unitRange) => ({
2596
+ unitId: unitRange.unitId,
2597
+ sheetId: unitRange.sheetId,
2598
+ startRow: unitRange.range.startRow,
2599
+ endRow: unitRange.range.endRow,
2600
+ startColumn: unitRange.range.startColumn,
2601
+ endColumn: unitRange.range.endColumn
2602
+ }));
2603
+ }
2604
+ _rustDependencyJsonByCell(items) {
2605
+ return new Map(
2606
+ items.map((item) => [
2607
+ this._cellKey({
2608
+ unitId: item.unitId,
2609
+ sheetId: item.subUnitId,
2610
+ row: item.row,
2611
+ column: item.column
2612
+ }),
2613
+ item
2614
+ ])
2615
+ );
2616
+ }
2617
+ _cellKey(cell) {
2618
+ return `${cell.unitId}\0${cell.sheetId}\0${cell.row}\0${cell.column}`;
2619
+ }
2620
+ _cellInUnitRanges(unitId, sheetId, row, column, unitRanges) {
2621
+ return unitRanges.some(
2622
+ (unitRange) => unitRange.unitId === unitId && unitRange.sheetId === sheetId && row >= unitRange.range.startRow && row <= unitRange.range.endRow && column >= unitRange.range.startColumn && column <= unitRange.range.endColumn
2623
+ );
2624
+ }
2625
+ _uniqueDependencyJson(items) {
2626
+ let seen = /* @__PURE__ */ new Set(), result = [];
2627
+ return items.forEach((item) => {
2628
+ !item || seen.has(item.treeId) || (seen.add(item.treeId), result.push(item));
2629
+ }), result;
2630
+ }
2631
+ };
2632
+ setDependencies3(RustCalculateFormulaService, [
2633
+ IConfigService,
2634
+ IFormulaCurrentConfigService,
2635
+ IFormulaRuntimeService,
2636
+ IFormulaDependencyGenerator,
2637
+ IFeatureCalculationManagerService,
2638
+ IOtherFormulaManagerService,
2639
+ ICommandService3,
2640
+ RustEngineSyncController,
2641
+ FormulaDataModel2,
2642
+ IFormulaReferenceDataService,
2643
+ ExternalReferenceModel,
2644
+ ISuperTableService2
2645
+ ]);
2646
+ function createRustProductExternalSyntheticUnitId(hostUnitId, referenceId) {
2647
+ return `external:product:${encodeURIComponent(hostUnitId)}:${encodeURIComponent(referenceId)}`;
2648
+ }
2649
+ function isFormulaDependencyTreeJson(value) {
2650
+ return value !== void 0;
2651
+ }
2652
+ function normalizeFormulaResultValue(value) {
2653
+ return value == null || typeof value == "number" || typeof value == "string" || typeof value == "boolean" || Array.isArray(value) && value.every(isFormulaResultRow) ? value : null;
2654
+ }
2655
+ function isFormulaResultRow(value) {
2656
+ return Array.isArray(value) && value.every(
2657
+ (item) => item == null || typeof item == "number" || typeof item == "string" || typeof item == "boolean"
2658
+ );
2659
+ }
2660
+
2661
+ // src/plugin.ts
2662
+ var DEFAULT_RUST_FORMULA_PLUGIN_CONFIG = {}, UniverRustFormulaEnginePlugin = class extends UniverProFormulaEnginePlugin {
2663
+ constructor(_config = DEFAULT_RUST_FORMULA_PLUGIN_CONFIG, _injector, _configService) {
2664
+ super(_config, _injector, _configService);
2665
+ this._config = _config;
2666
+ this._injector = _injector;
2667
+ this._configService = _configService;
2668
+ }
2669
+ _config;
2670
+ _injector;
2671
+ _configService;
2672
+ static packageName = name;
2673
+ static version = version;
2674
+ onReady() {
2675
+ super.onReady(), !this._config?.notExecuteFormula && this._config?.useRustEngine !== !1 && touchDependencies(this._injector, [[RustEngineSyncController], [RustSameRuntimeProjectionController]]);
2676
+ }
2677
+ /**
2678
+ * UniverProFormulaEnginePlugin invokes this hook before its single DI
2679
+ * registration pass.
2680
+ */
2681
+ _extendFormulaExecutionDependencies(dependencies) {
2682
+ if (this._config?.useRustEngine !== !1 && !this._config?.notExecuteFormula) {
2683
+ let calculateServiceIndex = dependencies.findIndex(
2684
+ (dependency) => Array.isArray(dependency) && dependency[0] === ICalculateFormulaService
2685
+ ), rustDependencies = [
2686
+ [RustEngineSyncController],
2687
+ [RustSameRuntimeProjectionController],
2688
+ [IRustCalculateFormulaService, { useClass: RustCalculateFormulaService }],
2689
+ // eslint-disable-next-line react/no-unnecessary-use-prefix
2690
+ [ICalculateFormulaService, { useFactory: () => this._injector.get(IRustCalculateFormulaService) }]
2691
+ ];
2692
+ calculateServiceIndex >= 0 && dependencies.splice(calculateServiceIndex, 1), dependencies.push(...rustDependencies);
2693
+ }
2694
+ }
2695
+ };
2696
+ setDependencies4(UniverRustFormulaEnginePlugin, [Injector, IConfigService2], 1);
2697
+
2698
+ // src/services/workbook-snapshot-materializer.ts
2699
+ import { Buffer } from "node:buffer";
2700
+ async function materializeWorkbookSnapshot(workbook, unitID, rev, dirtyInput) {
2701
+ await loadNativeBinding();
2702
+ let result = await materializeWorkbookSnapshotOnRust(
2703
+ Buffer.from(JSON.stringify(workbook)),
2704
+ unitID,
2705
+ rev,
2706
+ dirtyInput == null ? void 0 : JSON.stringify(dirtyInput)
2707
+ ), draft = JSON.parse(result.snapshotDraftJson.toString("utf8")), encoder = new TextEncoder(), sheets = Object.fromEntries(
2708
+ Object.entries(draft.workbook.sheets).map(([sheetID, sheet]) => {
2709
+ let { originalMetaJson: originalMetaJson2, ...meta } = sheet;
2710
+ return [sheetID, { ...meta, originalMeta: encoder.encode(originalMetaJson2) }];
2711
+ })
2712
+ ), { originalMetaJson, ...workbookMeta } = draft.workbook;
2713
+ return {
2714
+ snapshot: {
2715
+ unitID: draft.unitID,
2716
+ type: draft.type,
2717
+ rev: draft.rev,
2718
+ workbook: {
2719
+ ...workbookMeta,
2720
+ sheets,
2721
+ originalMeta: encoder.encode(originalMetaJson)
2722
+ },
2723
+ doc: void 0,
2724
+ slide: void 0,
2725
+ board: void 0
2726
+ },
2727
+ sheetBlocks: Object.fromEntries(result.sheetBlocks.map(({ sheetId, blocks }) => [sheetId, blocks])),
2728
+ warnings: JSON.parse(result.warningsJson.toString("utf8")),
2729
+ calculationStats: JSON.parse(result.calculationStatsJson.toString("utf8"))
2730
+ };
2731
+ }
2732
+ export {
2733
+ IRustCalculateFormulaService,
2734
+ RUST_FORMULA_RELEVANT_MUTATIONS,
2735
+ RUST_INCREMENTAL_DEPENDENCY_MUTATIONS,
2736
+ RUST_UPSERT_PROJECTION_WORKBOOK_MUTATION_ID,
2737
+ RUST_UPSERT_REFERENCE_DATA_MUTATION_ID,
2738
+ RustCalculateFormulaService,
2739
+ RustEngineSyncController,
2740
+ RustFormulaProjectionService,
2741
+ UniverRustFormulaEnginePlugin,
2742
+ analyzeNumberFormatBatch,
2743
+ applyMutationOnRust,
2744
+ buildLexerTreeOnRust,
2745
+ buildRustDependencyGraphOnRust,
2746
+ buildSequenceNodesOnRust,
2747
+ checkIfAddBracketOnRust,
2748
+ clearRustFormulaDependenciesOnRust,
2749
+ clearRustFormulaDirtyOnRust,
2750
+ createFormulaProjectionDesyncSignal,
2751
+ createProjectionWorkbookUpsertMutation,
2752
+ disposeAllWorkbooksOnRust,
2753
+ disposeWorkbookOnRust,
2754
+ executeOnRust,
2755
+ formatNumberBatch,
2756
+ getNativeBindingSource,
2757
+ getRustCellOnRust,
2758
+ getRustDirtyDependenciesOnRust,
2759
+ getRustFormulaDataOnRust,
2760
+ getRustModelStats,
2761
+ getRustSheetStateOnRust,
2762
+ isRustFormulaRelevantMutation,
2763
+ isRustIncrementalDependencyMutation,
2764
+ loadNativeBinding,
2765
+ loadSnapshotOnRust,
2766
+ markRustFormulaDirtyOnRust,
2767
+ materializeWorkbookSnapshot,
2768
+ materializeWorkbookSnapshotOnRust,
2769
+ parseNumberFormatBatch,
2770
+ parseNumberFormatMatrixBatch,
2771
+ rustExecutionOutputToFormulaCalculationPatch,
2772
+ serializeRuntimeWorkbookSnapshot,
2773
+ serializeRuntimeWorkbookSnapshots,
2774
+ syncRustFormulaDependenciesOnRust
2775
+ };