@univerjs/engine-formula 0.20.1 → 0.21.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/es/facade.js CHANGED
@@ -1 +1,702 @@
1
- import{FBase as e,FUniver as t}from"@univerjs/core/facade";import{ICommandService as n,IConfigService as r,Inject as i,Injector as a}from"@univerjs/core";import{ENGINE_FORMULA_CYCLE_REFERENCE_COUNT as o,ENGINE_FORMULA_RETURN_DEPENDENCY_TREE as s,GlobalComputingStatusService as c,IDefinedNamesService as l,IFunctionService as u,ISuperTableService as d,LexerTreeBuilder as f,SetCellFormulaDependencyCalculationMutation as p,SetCellFormulaDependencyCalculationResultMutation as m,SetFormulaCalculationNotificationMutation as h,SetFormulaCalculationStartMutation as g,SetFormulaCalculationStopMutation as _,SetFormulaDependencyCalculationMutation as v,SetFormulaDependencyCalculationResultMutation as y,SetFormulaStringBatchCalculationMutation as b,SetFormulaStringBatchCalculationResultMutation as x,SetQueryFormulaDependencyAllMutation as S,SetQueryFormulaDependencyAllResultMutation as C,SetQueryFormulaDependencyMutation as w,SetQueryFormulaDependencyResultMutation as T,SetTriggerFormulaCalculationStartMutation as E}from"@univerjs/engine-formula";import{filter as D,firstValueFrom as O,map as k,race as A,timer as j}from"rxjs";function M(e,t){return function(n,r){t(n,r,e)}}function N(e,t,n,r){var i=arguments.length,a=i<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,n):r,o;if(typeof Reflect==`object`&&typeof Reflect.decorate==`function`)a=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--)(o=e[s])&&(a=(i<3?o(a):i>3?o(t,n,a):o(t,n))||a);return i>3&&a&&Object.defineProperty(t,n,a),a}let P=class extends e{constructor(e,t,n,r,i,a,o){super(),this._commandService=e,this._injector=t,this._lexerTreeBuilder=n,this._configService=r,this._functionService=i,this._definedNamesService=a,this._superTableService=o,this._initialize()}_initialize(){}get lexerTreeBuilder(){return this._lexerTreeBuilder}moveFormulaRefOffset(e,t,n,r){return this._lexerTreeBuilder.moveFormulaRefOffset(e,t,n,r)}sequenceNodesBuilder(e){return this._lexerTreeBuilder.sequenceNodesBuilder(e)||[]}executeCalculation(){this._commandService.executeCommand(E.id,{commands:[],forceCalculation:!0},{onlyLocal:!0})}stopCalculation(){this._commandService.executeCommand(_.id,{})}calculationStart(e){return this._commandService.onCommandExecuted(t=>{if(t.id===g.id){let n=t.params;e(n.forceCalculation)}})}calculationEnd(e){return this._commandService.onCommandExecuted(t=>{if(t.id!==h.id)return;let n=t.params;n.functionsExecutedState!==void 0&&e(n.functionsExecutedState)})}whenComputingCompleteAsync(e){let t=this._injector.get(c);return t.computingStatus?Promise.resolve(!0):O(A(t.computingStatus$.pipe(D(e=>e)),j(e==null?3e4:e).pipe(k(()=>!1))))}onCalculationEnd(){return new Promise((e,t)=>{let n=setTimeout(()=>{t(Error(`Calculation end timeout`))},3e4),r=this.calculationEnd(()=>{clearTimeout(n),r.dispose(),e()})})}calculationProcessing(e){return this._commandService.onCommandExecuted(t=>{if(t.id!==h.id)return;let n=t.params;n.stageInfo!==void 0&&e(n.stageInfo)})}setMaxIteration(e){this._configService.setConfig(o,e)}executeFormulas(e,t=3e4){return new Promise((n,r)=>{let i=this._commandService.onCommandExecuted(e=>{if(e.id!==x.id)return;let t=e.params;clearTimeout(a),i.dispose(),t.result==null?r(Error(`Formula batch calculation returned no result`)):n(t.result)}),a=setTimeout(()=>{i.dispose(),r(Error(`Formula batch calculation timeout`))},t);this._commandService.executeCommand(b.id,{formulas:e},{onlyLocal:!0})})}getAllDependencyTrees(e=3e4){return new Promise((t,n)=>{let r=this._commandService.onCommandExecuted(e=>{if(e.id!==y.id)return;let n=e.params;clearTimeout(i),r.dispose(),n.result==null?t([]):t(n.result)}),i=setTimeout(()=>{r.dispose(),n(Error(`Formula dependency calculation timeout`))},e);this._commandService.executeCommand(v.id,void 0,{onlyLocal:!0})})}getCellDependencyTree(e,t=3e4){return new Promise((n,r)=>{let i=this._commandService.onCommandExecuted(e=>{if(e.id!==m.id)return;let t=e.params;clearTimeout(a),i.dispose(),n(t.result)}),a=setTimeout(()=>{i.dispose(),r(Error(`Cell dependency calculation timeout`))},t);this._commandService.executeCommand(p.id,e,{onlyLocal:!0})})}getRangeDependents(e,t=3e4){return new Promise((n,r)=>{let i=this._commandService.onCommandExecuted(e=>{if(e.id!==T.id)return;let t=e.params;clearTimeout(a),i.dispose(),t.result==null?n([]):n(t.result)}),a=setTimeout(()=>{i.dispose(),r(Error(`Range dependents calculation timeout`))},t);this._commandService.executeCommand(w.id,{unitRanges:e},{onlyLocal:!0})})}getInRangeFormulas(e,t=3e4){return new Promise((n,r)=>{let i=this._commandService.onCommandExecuted(e=>{if(e.id!==T.id)return;let t=e.params;clearTimeout(a),i.dispose(),t.result==null?n([]):n(t.result)}),a=setTimeout(()=>{i.dispose(),r(Error(`In-range formulas calculation timeout`))},t);this._commandService.executeCommand(w.id,{unitRanges:e,isInRange:!0},{onlyLocal:!0})})}setFormulaReturnDependencyTree(e){this._configService.setConfig(s,e)}getFormulaExpressTree(e,t){return this._lexerTreeBuilder.getFormulaExprTree(e,t,this._functionService.hasExecutor.bind(this._functionService),this._definedNamesService.getValueByName.bind(this._definedNamesService),this._superTableService.getTable.bind(this._superTableService))}getRangeDependentsAndInRangeFormulas(e,t=3e4){return new Promise((n,r)=>{let i=this._commandService.onCommandExecuted(e=>{if(e.id!==C.id)return;let t=e.params;clearTimeout(a),i.dispose(),t.result==null?n({dependents:[],inRanges:[]}):n(t.result)}),a=setTimeout(()=>{i.dispose(),r(Error(`Range dependents calculation timeout`))},t);this._commandService.executeCommand(S.id,{unitRanges:e},{onlyLocal:!0})})}};P=N([M(0,i(n)),M(1,i(a)),M(2,i(f)),M(3,r),M(4,u),M(5,l),M(6,d)],P);var F=class extends t{getFormula(){return this._injector.createInstance(P)}};t.extend(F);export{P as FFormula};
1
+ import { FBase, FUniver } from "@univerjs/core/facade";
2
+ import { ICommandService, IConfigService, Inject, Injector } from "@univerjs/core";
3
+ import { ENGINE_FORMULA_CYCLE_REFERENCE_COUNT, ENGINE_FORMULA_RETURN_DEPENDENCY_TREE, GlobalComputingStatusService, IDefinedNamesService, IFunctionService, ISuperTableService, LexerTreeBuilder, SetCellFormulaDependencyCalculationMutation, SetCellFormulaDependencyCalculationResultMutation, SetFormulaCalculationNotificationMutation, SetFormulaCalculationStartMutation, SetFormulaCalculationStopMutation, SetFormulaDependencyCalculationMutation, SetFormulaDependencyCalculationResultMutation, SetFormulaStringBatchCalculationMutation, SetFormulaStringBatchCalculationResultMutation, SetQueryFormulaDependencyAllMutation, SetQueryFormulaDependencyAllResultMutation, SetQueryFormulaDependencyMutation, SetQueryFormulaDependencyResultMutation, SetTriggerFormulaCalculationStartMutation } from "@univerjs/engine-formula";
4
+ import { filter, firstValueFrom, map, race, timer } from "rxjs";
5
+
6
+ //#region \0@oxc-project+runtime@0.124.0/helpers/decorateParam.js
7
+ function __decorateParam(paramIndex, decorator) {
8
+ return function(target, key) {
9
+ decorator(target, key, paramIndex);
10
+ };
11
+ }
12
+
13
+ //#endregion
14
+ //#region \0@oxc-project+runtime@0.124.0/helpers/decorate.js
15
+ function __decorate(decorators, target, key, desc) {
16
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
17
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
18
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
19
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
20
+ }
21
+
22
+ //#endregion
23
+ //#region src/facade/f-formula.ts
24
+ let FFormula = class FFormula extends FBase {
25
+ constructor(_commandService, _injector, _lexerTreeBuilder, _configService, _functionService, _definedNamesService, _superTableService) {
26
+ super();
27
+ this._commandService = _commandService;
28
+ this._injector = _injector;
29
+ this._lexerTreeBuilder = _lexerTreeBuilder;
30
+ this._configService = _configService;
31
+ this._functionService = _functionService;
32
+ this._definedNamesService = _definedNamesService;
33
+ this._superTableService = _superTableService;
34
+ this._initialize();
35
+ }
36
+ /**
37
+ * @ignore
38
+ */
39
+ _initialize() {}
40
+ /**
41
+ * The tree builder for formula string.
42
+ * @type {LexerTreeBuilder}
43
+ */
44
+ get lexerTreeBuilder() {
45
+ return this._lexerTreeBuilder;
46
+ }
47
+ /**
48
+ * Offsets the formula
49
+ * @param {string} formulaString - The formula string to offset
50
+ * @param {number} refOffsetX - The offset column
51
+ * @param {number} refOffsetY - The offset row
52
+ * @param {boolean} [ignoreAbsolute] - Whether to ignore the absolute reference
53
+ * @returns {string} The offset formula string
54
+ *
55
+ * @example
56
+ * ```ts
57
+ * const formulaEngine = univerAPI.getFormula();
58
+ * const result = formulaEngine.moveFormulaRefOffset('=SUM(A1,B2)', 1, 1);
59
+ * console.log(result);
60
+ * ```
61
+ */
62
+ moveFormulaRefOffset(formulaString, refOffsetX, refOffsetY, ignoreAbsolute) {
63
+ return this._lexerTreeBuilder.moveFormulaRefOffset(formulaString, refOffsetX, refOffsetY, ignoreAbsolute);
64
+ }
65
+ /**
66
+ * Resolves the formula string to a 'node' node
67
+ * @param {string} formulaString - The formula string to resolve
68
+ * @returns {Array<ISequenceNode | string>} The nodes of the formula string
69
+ *
70
+ * @example
71
+ * ```ts
72
+ * const formulaEngine = univerAPI.getFormula();
73
+ * const nodes = formulaEngine.sequenceNodesBuilder('=SUM(A1,B2)');
74
+ * console.log(nodes);
75
+ * ```
76
+ */
77
+ sequenceNodesBuilder(formulaString) {
78
+ return this._lexerTreeBuilder.sequenceNodesBuilder(formulaString) || [];
79
+ }
80
+ /**
81
+ * Start the calculation of the formula.
82
+ *
83
+ * @example
84
+ * ```ts
85
+ * const formulaEngine = univerAPI.getFormula();
86
+ * formulaEngine.executeCalculation();
87
+ * ```
88
+ */
89
+ executeCalculation() {
90
+ this._commandService.executeCommand(SetTriggerFormulaCalculationStartMutation.id, {
91
+ commands: [],
92
+ forceCalculation: true
93
+ }, { onlyLocal: true });
94
+ }
95
+ /**
96
+ * Stop the calculation of the formula.
97
+ *
98
+ * @example
99
+ * ```ts
100
+ * const formulaEngine = univerAPI.getFormula();
101
+ * formulaEngine.stopCalculation();
102
+ * ```
103
+ */
104
+ stopCalculation() {
105
+ this._commandService.executeCommand(SetFormulaCalculationStopMutation.id, {});
106
+ }
107
+ /**
108
+ * Listening calculation starts.
109
+ * @param {Function} callback - The callback function to be called when the formula calculation starts.
110
+ * @returns {IDisposable} The disposable instance.
111
+ *
112
+ * @example
113
+ * ```ts
114
+ * const formulaEngine = univerAPI.getFormula();
115
+ * formulaEngine.calculationStart((forceCalculation) => {
116
+ * console.log('Calculation start', forceCalculation);
117
+ * });
118
+ * ```
119
+ */
120
+ calculationStart(callback) {
121
+ return this._commandService.onCommandExecuted((command) => {
122
+ if (command.id === SetFormulaCalculationStartMutation.id) {
123
+ const params = command.params;
124
+ callback(params.forceCalculation);
125
+ }
126
+ });
127
+ }
128
+ /**
129
+ * Listening calculation ends.
130
+ * @param {Function} callback - The callback function to be called when the formula calculation ends.
131
+ * @returns {IDisposable} The disposable instance.
132
+ *
133
+ * @example
134
+ * ```ts
135
+ * const formulaEngine = univerAPI.getFormula();
136
+ * formulaEngine.calculationEnd((functionsExecutedState) => {
137
+ * console.log('Calculation end', functionsExecutedState);
138
+ * });
139
+ * ```
140
+ */
141
+ calculationEnd(callback) {
142
+ return this._commandService.onCommandExecuted((command) => {
143
+ if (command.id !== SetFormulaCalculationNotificationMutation.id) return;
144
+ const params = command.params;
145
+ if (params.functionsExecutedState !== void 0) callback(params.functionsExecutedState);
146
+ });
147
+ }
148
+ /**
149
+ * @deprecated Use `onCalculationEnd` instead.
150
+ */
151
+ whenComputingCompleteAsync(timeout) {
152
+ const gcss = this._injector.get(GlobalComputingStatusService);
153
+ if (gcss.computingStatus) return Promise.resolve(true);
154
+ return firstValueFrom(race(gcss.computingStatus$.pipe(filter((computing) => computing)), timer(timeout !== null && timeout !== void 0 ? timeout : 3e4).pipe(map(() => false))));
155
+ }
156
+ /**
157
+ * Waits for the formula calculation to complete.
158
+ * @returns {Promise<void>} This method returns a promise that resolves when the calculation is complete.
159
+ */
160
+ onCalculationEnd() {
161
+ return new Promise((resolve, reject) => {
162
+ const timer = setTimeout(() => {
163
+ reject(/* @__PURE__ */ new Error("Calculation end timeout"));
164
+ }, 3e4);
165
+ const disposable = this.calculationEnd(() => {
166
+ clearTimeout(timer);
167
+ disposable.dispose();
168
+ resolve();
169
+ });
170
+ });
171
+ }
172
+ /**
173
+ * Listening calculation processing.
174
+ * @param {Function} callback - The callback function to be called when the formula calculation is in progress.
175
+ * @returns {IDisposable} The disposable instance.
176
+ *
177
+ * @example
178
+ * ```ts
179
+ * const formulaEngine = univerAPI.getFormula();
180
+ * formulaEngine.calculationProcessing((stageInfo) => {
181
+ * console.log('Calculation processing', stageInfo);
182
+ * });
183
+ * ```
184
+ */
185
+ calculationProcessing(callback) {
186
+ return this._commandService.onCommandExecuted((command) => {
187
+ if (command.id !== SetFormulaCalculationNotificationMutation.id) return;
188
+ const params = command.params;
189
+ if (params.stageInfo !== void 0) callback(params.stageInfo);
190
+ });
191
+ }
192
+ /**
193
+ * When a formula contains a circular reference, set the maximum number of iterations for the formula calculation.
194
+ * @param {number} maxIteration The maximum number of iterations. The default value is 1.
195
+ *
196
+ * @example
197
+ * ```ts
198
+ * // Set the maximum number of iterations for the formula calculation to 5.
199
+ * // The default value is 1.
200
+ * const formulaEngine = univerAPI.getFormula();
201
+ * formulaEngine.setMaxIteration(5);
202
+ * ```
203
+ */
204
+ setMaxIteration(maxIteration) {
205
+ this._configService.setConfig(ENGINE_FORMULA_CYCLE_REFERENCE_COUNT, maxIteration);
206
+ }
207
+ /**
208
+ * Execute a batch of formulas asynchronously and receive computed results.
209
+ *
210
+ * Each formula cell is represented as a string array:
211
+ * [fullFormula, ...subFormulas]
212
+ *
213
+ * Where:
214
+ * - fullFormula (index 0) is the complete formula expression written in the cell.
215
+ * Example: "=SUM(A1:A10) + SQRT(D7)".
216
+ *
217
+ * - subFormulas (index 1+) are **optional decomposed expressions** extracted from
218
+ * the full formula. Each of them can be independently computed by the formula engine.
219
+ *
220
+ * These sub-expressions can include:
221
+ * - Single-cell references: "A2", "B2", "C5"
222
+ * - Range references: "A1:A10"
223
+ * - Function calls: "SQRT(D7)", "ABS(A2-B2)"
224
+ * - Any sub-formula that was parsed out of the original formula and can be
225
+ * evaluated on its own.
226
+ *
227
+ * The batch execution engine may use these sub-formulas for dependency resolution,
228
+ * incremental computation, or performance optimizations.
229
+ *
230
+ * @param {IFormulaStringMap} formulas
231
+ * Nested structure (unit → sheet → row → column) describing formulas and
232
+ * their decomposed sub-expressions.
233
+ *
234
+ * @param {number} [timeout]
235
+ * Optional timeout in milliseconds. If no result is received within this
236
+ * period, the promise will be rejected.
237
+ *
238
+ * @returns {Promise<IFormulaExecuteResultMap>}
239
+ * A promise that resolves with the computed value map mirroring
240
+ * the input structure.
241
+ *
242
+ * @example
243
+ * ```ts
244
+ * const formulaEngine = univerAPI.getFormula();
245
+ * const formulas = {
246
+ * Book1: {
247
+ * Sheet1: {
248
+ * 2: {
249
+ * 3: [
250
+ * // Full formula:
251
+ * "=SUM(A1:A10) + SQRT(D7)",
252
+ *
253
+ * // Decomposed sub-formulas (each one can be evaluated independently):
254
+ * "SUM(A1:A10)", // sub-formula 1
255
+ * "SQRT(D7)", // sub-formula 2
256
+ * "A1:A10", // range reference
257
+ * "D7", // single-cell reference
258
+ * ],
259
+ * },
260
+ * 4: {
261
+ * 5: [
262
+ * "=A2 + B2 + SQRT(C5)",
263
+ * "A2",
264
+ * "B2",
265
+ * "SQRT(C5)",
266
+ * ],
267
+ * }
268
+ * },
269
+ * },
270
+ * };
271
+ *
272
+ * const result = await formulaEngine.executeFormulas(formulas);
273
+ * console.log(result);
274
+ * ```
275
+ */
276
+ executeFormulas(formulas, timeout = 3e4) {
277
+ return new Promise((resolve, reject) => {
278
+ const disposable = this._commandService.onCommandExecuted((command) => {
279
+ if (command.id !== SetFormulaStringBatchCalculationResultMutation.id) return;
280
+ const params = command.params;
281
+ clearTimeout(timer);
282
+ disposable.dispose();
283
+ if (params.result != null) resolve(params.result);
284
+ else reject(/* @__PURE__ */ new Error("Formula batch calculation returned no result"));
285
+ });
286
+ const timer = setTimeout(() => {
287
+ disposable.dispose();
288
+ reject(/* @__PURE__ */ new Error("Formula batch calculation timeout"));
289
+ }, timeout);
290
+ this._commandService.executeCommand(SetFormulaStringBatchCalculationMutation.id, { formulas }, { onlyLocal: true });
291
+ });
292
+ }
293
+ /**
294
+ * Retrieve all formula dependency trees that were produced during the latest
295
+ * dependency-analysis run. This triggers a local dependency-calculation command
296
+ * and returns the complete set of dependency trees once the calculation finishes.
297
+ *
298
+ * @param {number} [timeout]
299
+ * Optional timeout in milliseconds. If no result is received within this
300
+ * period, the promise will be rejected.
301
+ *
302
+ * @returns {Promise<IFormulaDependencyTreeJson[]>}
303
+ * A promise that resolves with the array of dependency trees.
304
+ *
305
+ * @example
306
+ * ```ts
307
+ * const formulaEngine = univerAPI.getFormula();
308
+ *
309
+ * // Fetch all dependency trees generated for the current workbook.
310
+ * const trees = await formulaEngine.getAllDependencyTrees();
311
+ * console.log('All dependency trees:', trees);
312
+ * ```
313
+ */
314
+ getAllDependencyTrees(timeout = 3e4) {
315
+ return new Promise((resolve, reject) => {
316
+ const disposable = this._commandService.onCommandExecuted((command) => {
317
+ if (command.id !== SetFormulaDependencyCalculationResultMutation.id) return;
318
+ const params = command.params;
319
+ clearTimeout(timer);
320
+ disposable.dispose();
321
+ if (params.result != null) resolve(params.result);
322
+ else resolve([]);
323
+ });
324
+ const timer = setTimeout(() => {
325
+ disposable.dispose();
326
+ reject(/* @__PURE__ */ new Error("Formula dependency calculation timeout"));
327
+ }, timeout);
328
+ this._commandService.executeCommand(SetFormulaDependencyCalculationMutation.id, void 0, { onlyLocal: true });
329
+ });
330
+ }
331
+ /**
332
+ * Retrieve the dependency tree of a specific cell. This triggers a local
333
+ * dependency-calculation command for the given unit, sheet, and cell location,
334
+ * and returns the computed dependency tree when the calculation is completed.
335
+ *
336
+ * @param param The target cell location:
337
+ * - `unitId` The workbook ID.
338
+ * - `sheetId` The sheet ID.
339
+ * - `row` The zero-based row index.
340
+ * - `column` The zero-based column index.
341
+ *
342
+ * @param {number} [timeout]
343
+ * Optional timeout in milliseconds. If no result is received within this
344
+ * period, the promise will be rejected.
345
+ *
346
+ * @returns {Promise<IFormulaDependencyTreeFullJson | undefined>}
347
+ * A promise that resolves with the dependency tree or `undefined`
348
+ * if no tree exists for that cell.
349
+ *
350
+ * @example
351
+ * ```ts
352
+ * const formulaEngine = univerAPI.getFormula();
353
+ *
354
+ * // Query the dependency tree for cell B2 in a specific sheet.
355
+ * const tree = await formulaEngine.getCellDependencyTree({
356
+ * unitId: 'workbook1',
357
+ * sheetId: 'sheet1',
358
+ * row: 1,
359
+ * column: 1,
360
+ * });
361
+ *
362
+ * console.log('Cell dependency tree:', tree);
363
+ * ```
364
+ */
365
+ getCellDependencyTree(param, timeout = 3e4) {
366
+ return new Promise((resolve, reject) => {
367
+ const disposable = this._commandService.onCommandExecuted((command) => {
368
+ if (command.id !== SetCellFormulaDependencyCalculationResultMutation.id) return;
369
+ const params = command.params;
370
+ clearTimeout(timer);
371
+ disposable.dispose();
372
+ resolve(params.result);
373
+ });
374
+ const timer = setTimeout(() => {
375
+ disposable.dispose();
376
+ reject(/* @__PURE__ */ new Error("Cell dependency calculation timeout"));
377
+ }, timeout);
378
+ this._commandService.executeCommand(SetCellFormulaDependencyCalculationMutation.id, param, { onlyLocal: true });
379
+ });
380
+ }
381
+ /**
382
+ * Retrieve the full dependency trees for all formulas that *depend on* the
383
+ * specified ranges. This triggers a local dependency-calculation command and
384
+ * resolves once the calculation completes.
385
+ *
386
+ * @param unitRanges An array of workbook/sheet ranges to query. Each range
387
+ * includes:
388
+ * - `unitId` The workbook ID.
389
+ * - `sheetId` The sheet ID.
390
+ * - `range` The row/column boundaries.
391
+ *
392
+ * @param {number} [timeout]
393
+ * Optional timeout in milliseconds. If no result is received within this
394
+ * period, the promise will be rejected.
395
+ *
396
+ * @returns {Promise<IFormulaDependencyTreeJson[]>}
397
+ * A promise that resolves with an array of `IFormulaDependencyTreeJson`
398
+ * representing formulas and their relationships within the dependency graph.
399
+ *
400
+ * @example
401
+ * ```ts
402
+ * const formulaEngine = univerAPI.getFormula();
403
+ *
404
+ * // Query all formulas that depend on A1:B10 in Sheet1.
405
+ * const dependents = await formulaEngine.getRangeDependents([
406
+ * { unitId: 'workbook1', sheetId: 'sheet1', range: { startRow: 0, endRow: 9, startColumn: 0, endColumn: 1 } }
407
+ * ]);
408
+ *
409
+ * console.log('Dependent formulas:', dependents);
410
+ * ```
411
+ */
412
+ getRangeDependents(unitRanges, timeout = 3e4) {
413
+ return new Promise((resolve, reject) => {
414
+ const disposable = this._commandService.onCommandExecuted((command) => {
415
+ if (command.id !== SetQueryFormulaDependencyResultMutation.id) return;
416
+ const params = command.params;
417
+ clearTimeout(timer);
418
+ disposable.dispose();
419
+ if (params.result != null) resolve(params.result);
420
+ else resolve([]);
421
+ });
422
+ const timer = setTimeout(() => {
423
+ disposable.dispose();
424
+ reject(/* @__PURE__ */ new Error("Range dependents calculation timeout"));
425
+ }, timeout);
426
+ this._commandService.executeCommand(SetQueryFormulaDependencyMutation.id, { unitRanges }, { onlyLocal: true });
427
+ });
428
+ }
429
+ /**
430
+ * Retrieve the dependency trees of all formulas *inside* the specified ranges.
431
+ * Unlike `getRangeDependents`, this API only returns formulas whose definitions
432
+ * physically reside within the queried ranges.
433
+ *
434
+ * Internally this triggers the same dependency-calculation command but with
435
+ * `isInRange = true`, and the promise resolves when the results are ready.
436
+ *
437
+ * @param unitRanges An array of workbook/sheet ranges defining the lookup
438
+ * boundaries:
439
+ * - `unitId` The workbook ID.
440
+ * - `sheetId` The sheet ID.
441
+ * - `range` The zero-based grid range.
442
+ *
443
+ * @param {number} [timeout]
444
+ * Optional timeout in milliseconds. If no result is received within this
445
+ * period, the promise will be rejected.
446
+ *
447
+ * @returns {Promise<IFormulaDependencyTreeJson[]>}
448
+ * A promise that resolves with an array of `IFormulaDependencyTreeJson`
449
+ * describing every formula found in the provided ranges along with
450
+ * their parent/child relationships.
451
+ *
452
+ * @example
453
+ * ```ts
454
+ * const formulaEngine = univerAPI.getFormula();
455
+ *
456
+ * // Query all formulas that lie within A1:D20 in Sheet1.
457
+ * const formulasInRange = await formulaEngine.getInRangeFormulas([
458
+ * { unitId: 'workbook1', sheetId: 'sheet1', range: { startRow: 0, endRow: 19, startColumn: 0, endColumn: 3 } }
459
+ * ]);
460
+ *
461
+ * console.log('Formulas inside range:', formulasInRange);
462
+ * ```
463
+ */
464
+ getInRangeFormulas(unitRanges, timeout = 3e4) {
465
+ return new Promise((resolve, reject) => {
466
+ const disposable = this._commandService.onCommandExecuted((command) => {
467
+ if (command.id !== SetQueryFormulaDependencyResultMutation.id) return;
468
+ const params = command.params;
469
+ clearTimeout(timer);
470
+ disposable.dispose();
471
+ if (params.result != null) resolve(params.result);
472
+ else resolve([]);
473
+ });
474
+ const timer = setTimeout(() => {
475
+ disposable.dispose();
476
+ reject(/* @__PURE__ */ new Error("In-range formulas calculation timeout"));
477
+ }, timeout);
478
+ this._commandService.executeCommand(SetQueryFormulaDependencyMutation.id, {
479
+ unitRanges,
480
+ isInRange: true
481
+ }, { onlyLocal: true });
482
+ });
483
+ }
484
+ /**
485
+ * Enable or disable emitting formula dependency trees after each formula calculation.
486
+ *
487
+ * When enabled, the formula engine will emit the dependency trees produced by
488
+ * each completed formula calculation through the internal command system.
489
+ * Consumers can obtain the result by listening for the corresponding
490
+ * calculation-result command.
491
+ *
492
+ * When disabled, dependency trees will not be emitted.
493
+ *
494
+ * This option only controls whether dependency trees are exposed.
495
+ * It does not affect formula calculation behavior.
496
+ *
497
+ * @param {boolean} value
498
+ * Whether to emit formula dependency trees after calculation.
499
+ * - `true`: Emit dependency trees after each calculation.
500
+ * - `false`: Do not emit dependency trees (default behavior).
501
+ *
502
+ * @example
503
+ * ```ts
504
+ * const formulaEngine = univerAPI.getFormula();
505
+ *
506
+ * // Enable dependency tree emission
507
+ * formulaEngine.setFormulaReturnDependencyTree(true);
508
+ *
509
+ * // Listen for dependency trees produced by formula calculation
510
+ * const trees = await new Promise<IFormulaDependencyTreeJson[]>((resolve, reject) => {
511
+ * const timer = setTimeout(() => {
512
+ * disposable.dispose();
513
+ * reject(new Error('Timeout waiting for formula dependency trees'));
514
+ * }, 30_000);
515
+ *
516
+ * const disposable = commandService.onCommandExecuted((command) => {
517
+ * if (command.id !== SetFormulaDependencyCalculationResultMutation.id) {
518
+ * return;
519
+ * }
520
+ *
521
+ * clearTimeout(timer);
522
+ * disposable.dispose();
523
+ *
524
+ * const params = command.params as ISetFormulaDependencyCalculationResultMutation;
525
+ * resolve(params.result ?? []);
526
+ * });
527
+ * });
528
+ *
529
+ * console.log('Dependency trees:', trees);
530
+ * ```
531
+ */
532
+ setFormulaReturnDependencyTree(value) {
533
+ this._configService.setConfig(ENGINE_FORMULA_RETURN_DEPENDENCY_TREE, value);
534
+ }
535
+ /**
536
+ * Parse a formula string and return its **formula expression tree**.
537
+ *
538
+ * This API analyzes the syntactic structure of a formula and builds an
539
+ * expression tree that reflects how the formula is composed (functions,
540
+ * operators, ranges, and nested expressions), without performing calculation
541
+ * or dependency evaluation.
542
+ *
543
+ * The returned tree is suitable for:
544
+ * - Formula structure visualization
545
+ * - Explaining complex formulas (e.g. LET / LAMBDA)
546
+ * - Debugging or inspecting formula composition
547
+ * - Building advanced formula tooling
548
+ *
549
+ * ---
550
+ *
551
+ * @example
552
+ * ```ts
553
+ * const formulaEngine = univerAPI.getFormula();
554
+ *
555
+ * const formula = '=LET(x,SUM(A1,B1,A1:B10),y,OFFSET(A1:B10,0,1),SUM(x,y)+x)+1';
556
+ *
557
+ * const exprTree = formulaEngine.getFormulaExpressTree(formula);
558
+ *
559
+ * console.log(exprTree);
560
+ * ```
561
+ *
562
+ * Example output (simplified):
563
+ *
564
+ * ```json
565
+ * {
566
+ * "value": "let(x,sum(A1,B1,A1:B10),y,offset(A1:B10,0,1),sum(x,y)+x)+1",
567
+ * "children": [
568
+ * {
569
+ * "value": "let(x,sum(A1,B1,A1:B10),y,offset(A1:B10,0,1),sum(x,y)+x)",
570
+ * "children": [
571
+ * {
572
+ * "value": "sum(A1,B1,A1:B10)",
573
+ * "children": [
574
+ * {
575
+ * "value": "A1:B10",
576
+ * "children": []
577
+ * }
578
+ * ]
579
+ * },
580
+ * {
581
+ * "value": "offset(A1:B10,0,1)",
582
+ * "children": [
583
+ * {
584
+ * "value": "A1:B10",
585
+ * "children": []
586
+ * }
587
+ * ]
588
+ * }
589
+ * ]
590
+ * }
591
+ * ]
592
+ * }
593
+ * ```
594
+ *
595
+ * @param formulaString The formula string to parse (with or without leading `=`)
596
+ * @returns A formula expression tree describing the hierarchical structure of the formula
597
+ */
598
+ getFormulaExpressTree(formulaString, unitId) {
599
+ return this._lexerTreeBuilder.getFormulaExprTree(formulaString, unitId, this._functionService.hasExecutor.bind(this._functionService), this._definedNamesService.getValueByName.bind(this._definedNamesService), this._superTableService.getTable.bind(this._superTableService));
600
+ }
601
+ /**
602
+ * Retrieve **both**:
603
+ * 1) the full dependency trees of all formulas that **depend on** the specified ranges, and
604
+ * 2) the dependency trees of all formulas that **physically reside inside** the specified ranges.
605
+ *
606
+ * This is a convenience API that combines the behaviors of
607
+ * `getRangeDependents` and `getInRangeFormulas` into a single call.
608
+ *
609
+ * Internally, it triggers a local dependency-calculation command once and
610
+ * resolves when both result sets are available, avoiding duplicate
611
+ * calculations and event listeners.
612
+ *
613
+ * @param unitRanges An array of workbook/sheet ranges to query. Each range
614
+ * includes:
615
+ * - `unitId` The workbook ID.
616
+ * - `sheetId` The sheet ID.
617
+ * - `range` The zero-based row/column boundaries.
618
+ *
619
+ * @param {number} [timeout]
620
+ * Optional timeout in milliseconds. If the dependency calculation does
621
+ * not complete within this period, the promise will be rejected.
622
+ *
623
+ * @returns {Promise<IFormulaDependentsAndInRangeResults>}
624
+ * A promise that resolves with an object containing:
625
+ * - `dependents`: Dependency trees of all formulas that depend on the
626
+ * specified ranges (upstream consumers).
627
+ * - `inRanges`: Dependency trees of all formulas whose definitions
628
+ * are located inside the specified ranges.
629
+ *
630
+ * @example
631
+ * ```ts
632
+ * const formulaEngine = univerAPI.getFormula();
633
+ *
634
+ * const result = await formulaEngine.getRangeDependentsAndInRangeFormulas([
635
+ * {
636
+ * unitId: 'workbook1',
637
+ * sheetId: 'sheet1',
638
+ * range: { startRow: 0, endRow: 9, startColumn: 0, endColumn: 1 },
639
+ * },
640
+ * ]);
641
+ *
642
+ * console.log('Dependent formulas:', result.dependents);
643
+ * console.log('Formulas inside range:', result.inRanges);
644
+ * ```
645
+ */
646
+ getRangeDependentsAndInRangeFormulas(unitRanges, timeout = 3e4) {
647
+ return new Promise((resolve, reject) => {
648
+ const disposable = this._commandService.onCommandExecuted((command) => {
649
+ if (command.id !== SetQueryFormulaDependencyAllResultMutation.id) return;
650
+ const params = command.params;
651
+ clearTimeout(timer);
652
+ disposable.dispose();
653
+ if (params.result != null) resolve(params.result);
654
+ else resolve({
655
+ dependents: [],
656
+ inRanges: []
657
+ });
658
+ });
659
+ const timer = setTimeout(() => {
660
+ disposable.dispose();
661
+ reject(/* @__PURE__ */ new Error("Range dependents calculation timeout"));
662
+ }, timeout);
663
+ this._commandService.executeCommand(SetQueryFormulaDependencyAllMutation.id, { unitRanges }, { onlyLocal: true });
664
+ });
665
+ }
666
+ };
667
+ FFormula = __decorate([
668
+ __decorateParam(0, Inject(ICommandService)),
669
+ __decorateParam(1, Inject(Injector)),
670
+ __decorateParam(2, Inject(LexerTreeBuilder)),
671
+ __decorateParam(3, IConfigService),
672
+ __decorateParam(4, IFunctionService),
673
+ __decorateParam(5, IDefinedNamesService),
674
+ __decorateParam(6, ISuperTableService)
675
+ ], FFormula);
676
+
677
+ //#endregion
678
+ //#region src/facade/f-univer.ts
679
+ /**
680
+ * Copyright 2023-present DreamNum Co., Ltd.
681
+ *
682
+ * Licensed under the Apache License, Version 2.0 (the "License");
683
+ * you may not use this file except in compliance with the License.
684
+ * You may obtain a copy of the License at
685
+ *
686
+ * http://www.apache.org/licenses/LICENSE-2.0
687
+ *
688
+ * Unless required by applicable law or agreed to in writing, software
689
+ * distributed under the License is distributed on an "AS IS" BASIS,
690
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
691
+ * See the License for the specific language governing permissions and
692
+ * limitations under the License.
693
+ */
694
+ var FUniverEngineFormulaMixin = class extends FUniver {
695
+ getFormula() {
696
+ return this._injector.createInstance(FFormula);
697
+ }
698
+ };
699
+ FUniver.extend(FUniverEngineFormulaMixin);
700
+
701
+ //#endregion
702
+ export { FFormula };