@univerjs/engine-formula 0.20.1 → 0.21.0-insiders.20260424-262d69f

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